From 27da58c6fe6d9aa377b6cdc153915f095d6f5449 Mon Sep 17 00:00:00 2001 From: zurdi Date: Wed, 16 Sep 2026 12:47:53 +0200 Subject: [PATCH 1/3] fix(tasks): refuse a manual task run when no worker is listening A task run with no RQ worker sat queued forever while the UI reported it queued and later refreshed as if it had run. The endpoint now answers 503 with the reason, the Settings sections show that reason instead of the axios wrapper, and the developer setup documents how to start the workers. The delete-ROM dialog's filesystem warning gets its bottom padding above the footer, and the cleanup-queued message loses its em dash in every locale. Co-Authored-By: Claude Fable 5.1 --- DEVELOPER_SETUP.md | 10 +++++ backend/endpoints/tasks.py | 10 ++++- backend/tests/endpoints/test_tasks.py | 37 +++++++++++++++++-- frontend/src/locales/bg_BG/settings.json | 2 +- frontend/src/locales/cs_CZ/settings.json | 2 +- frontend/src/locales/de_DE/settings.json | 2 +- frontend/src/locales/en_GB/settings.json | 2 +- frontend/src/locales/en_US/settings.json | 2 +- frontend/src/locales/es_ES/settings.json | 2 +- frontend/src/locales/fr_FR/settings.json | 2 +- frontend/src/locales/hu_HU/settings.json | 2 +- frontend/src/locales/it_IT/settings.json | 2 +- frontend/src/locales/ja_JP/settings.json | 2 +- frontend/src/locales/ko_KR/settings.json | 2 +- frontend/src/locales/pl_PL/settings.json | 2 +- frontend/src/locales/pt_BR/settings.json | 2 +- frontend/src/locales/ro_RO/settings.json | 2 +- frontend/src/locales/ru_RU/settings.json | 2 +- frontend/src/locales/tr_TR/settings.json | 2 +- frontend/src/locales/zh_CN/settings.json | 2 +- frontend/src/locales/zh_TW/settings.json | 2 +- .../v2/components/Dialogs/DeleteRomDialog.vue | 2 +- .../Settings/MissingFirmwareSection.vue | 9 ++++- .../Settings/MissingGamesSection.vue | 5 ++- 24 files changed, 82 insertions(+), 27 deletions(-) diff --git a/DEVELOPER_SETUP.md b/DEVELOPER_SETUP.md index fcc3d916f..e3967c38c 100644 --- a/DEVELOPER_SETUP.md +++ b/DEVELOPER_SETUP.md @@ -126,6 +126,16 @@ cd backend uv run python3 main.py ``` +#### - Run the task workers + +Manual tasks (the missing ROMs and firmware cleanups, folder sync) and the scheduled jobs run on an RQ worker, and scans on a worker of their own. Without them a task stays queued. + +```sh +cd backend +uv run rq worker --url redis://127.0.0.1:6379/0 --worker-class handler.rq_worker.RomMWorker --with-scheduler high default low +uv run rq worker --url redis://127.0.0.1:6379/0 --worker-class handler.rq_worker.RomMWorker scans +``` + ### Setting up the frontend #### - Install node.js dependencies diff --git a/backend/endpoints/tasks.py b/backend/endpoints/tasks.py index 781be1b6e..04f8d0694 100644 --- a/backend/endpoints/tasks.py +++ b/backend/endpoints/tasks.py @@ -1,7 +1,7 @@ from datetime import datetime, timezone from typing import Any, Final, Mapping, cast -from fastapi import Body, HTTPException, Request +from fastapi import Body, HTTPException, Request, status from rq import Worker from rq.exceptions import NoSuchJobError from rq.job import Job, JobStatus @@ -27,6 +27,7 @@ from handler.redis_handler import ( ALL_QUEUES, get_job_func_name, get_worker_current_job, + low_prio_queue, redis_client, ) from tasks.registry import MANUAL_TASKS, SCHEDULED_TASKS, enqueue_task @@ -301,6 +302,13 @@ async def run_single_task( detail=f"Task '{task_name}' cannot be run", ) + # Without a worker the job would sit queued while the UI reports it done. + if not Worker.all(queue=low_prio_queue, connection=redis_client): + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail="No task worker is running, so the task cannot be queued", + ) + # The caller's arguments are nested rather than spread, so a body cannot # name a different task than the one this route just authorized. job = enqueue_task(task_name, task_kwargs=task_kwargs or {}) diff --git a/backend/tests/endpoints/test_tasks.py b/backend/tests/endpoints/test_tasks.py index bc5045bc1..43d594aaa 100644 --- a/backend/tests/endpoints/test_tasks.py +++ b/backend/tests/endpoints/test_tasks.py @@ -254,10 +254,11 @@ class TestRunSingleTask: ) def test_run_single_task_success(self, mock_enqueue, client, access_token): """Test successful running of a single task""" - response = client.post( - "/api/tasks/run/test_task", - headers={"Authorization": f"Bearer {access_token}"}, - ) + with patch("endpoints.tasks.Worker.all", return_value=[Mock()]): + response = client.post( + "/api/tasks/run/test_task", + headers={"Authorization": f"Bearer {access_token}"}, + ) assert response.status_code == status.HTTP_200_OK data = response.json() @@ -271,6 +272,34 @@ class TestRunSingleTask: mock_enqueue.assert_called_once() + @patch("endpoints.tasks.enqueue_task") + @patch( + "endpoints.tasks.RUNNABLE_TASKS", + { + "test_task": Mock( + spec=Task, + task_type=TaskType.CLEANUP, + title="Test Task", + enabled=True, + manual_run=True, + can_run_manually=True, + run=Mock(), + ), + }, + ) + def test_run_single_task_without_a_worker_is_refused( + self, mock_enqueue, client, access_token + ): + with patch("endpoints.tasks.Worker.all", return_value=[]): + response = client.post( + "/api/tasks/run/test_task", + headers={"Authorization": f"Bearer {access_token}"}, + ) + + assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE + assert "worker" in response.json()["detail"] + mock_enqueue.assert_not_called() + @patch("endpoints.tasks.RUNNABLE_TASKS", {}) def test_run_single_task_not_found(self, client, access_token): """Test running a non-existent task""" diff --git a/frontend/src/locales/bg_BG/settings.json b/frontend/src/locales/bg_BG/settings.json index e44881f55..6e054e4ac 100644 --- a/frontend/src/locales/bg_BG/settings.json +++ b/frontend/src/locales/bg_BG/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "Това ще изтрие окончателно всички липсващи ROM-ове{platform} от базата данни и техните директории. Това действие е необратимо.", "cleanup-firmware-confirm": "Това ще изтрие окончателно всеки запис за фърмуер{platform}, чийто файл липсва от файловата система. Нищо няма да бъде премахнато от диска.", "cleanup-firmware-queued": "Задачата за почистване е на опашка, липсващият фърмуер ще бъде изтрит скоро", - "cleanup-queued": "Задачата за почистване е на опашка — липсващите ROM-ове ще бъдат изтрити скоро", + "cleanup-queued": "Задачата за почистване е на опашка, липсващите ROM-ове ще бъдат изтрити скоро", "client-api-tokens": "API токени", "client-token-confirm-delete": "Сигурен ли си, че искаш да отмениш този токен? Всички устройства които го използват ще загубят достъп.", "client-token-confirm-regenerate": "Това ще анулира текущия токен. Всички устройства използващи стария токен ще трябва да се сдвоят отново.", diff --git a/frontend/src/locales/cs_CZ/settings.json b/frontend/src/locales/cs_CZ/settings.json index 8d6eff176..551e45a3e 100644 --- a/frontend/src/locales/cs_CZ/settings.json +++ b/frontend/src/locales/cs_CZ/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Tímto se z databáze trvale odstraní každý záznam firmwaru{platform}, jehož soubor v souborovém systému chybí. Na disku se nic nesmaže.", "cleanup-firmware-queued": "Úloha vyčištění zařazena do fronty, chybějící firmware bude brzy smazán", - "cleanup-queued": "Úloha vyčištění zařazena do fronty — chybějící ROMy budou brzy smazány", + "cleanup-queued": "Úloha vyčištění zařazena do fronty, chybějící ROMy budou brzy smazány", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/de_DE/settings.json b/frontend/src/locales/de_DE/settings.json index f8652f65b..82aac3b55 100644 --- a/frontend/src/locales/de_DE/settings.json +++ b/frontend/src/locales/de_DE/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Dadurch wird jeder Firmware-Eintrag{platform}, dessen Datei im Dateisystem fehlt, dauerhaft aus der Datenbank gelöscht. Auf der Festplatte wird nichts entfernt.", "cleanup-firmware-queued": "Bereinigungsaufgabe in Warteschlange, fehlende Firmware wird in Kürze gelöscht", - "cleanup-queued": "Bereinigungsaufgabe in Warteschlange — fehlende ROMs werden in Kürze gelöscht", + "cleanup-queued": "Bereinigungsaufgabe in Warteschlange, fehlende ROMs werden in Kürze gelöscht", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/en_GB/settings.json b/frontend/src/locales/en_GB/settings.json index 33cee5a75..15991bb83 100644 --- a/frontend/src/locales/en_GB/settings.json +++ b/frontend/src/locales/en_GB/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "This will permanently delete every firmware entry{platform} whose file is missing from the filesystem. Nothing is removed from disk.", "cleanup-firmware-queued": "Cleanup task queued, missing firmware will be deleted shortly", - "cleanup-queued": "Cleanup task queued — missing ROMs will be deleted shortly", + "cleanup-queued": "Cleanup task queued, missing ROMs will be deleted shortly", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/en_US/settings.json b/frontend/src/locales/en_US/settings.json index d937dfb81..a65550cbc 100644 --- a/frontend/src/locales/en_US/settings.json +++ b/frontend/src/locales/en_US/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "This will permanently delete every firmware entry{platform} whose file is missing from the filesystem. Nothing is removed from disk.", "cleanup-firmware-queued": "Cleanup task queued, missing firmware will be deleted shortly", - "cleanup-queued": "Cleanup task queued — missing ROMs will be deleted shortly", + "cleanup-queued": "Cleanup task queued, missing ROMs will be deleted shortly", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/es_ES/settings.json b/frontend/src/locales/es_ES/settings.json index 436d9086f..8288d1918 100644 --- a/frontend/src/locales/es_ES/settings.json +++ b/frontend/src/locales/es_ES/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Esto eliminará permanentemente de la base de datos cada entrada de firmware{platform} cuyo archivo falte en el sistema de archivos. No se elimina nada del disco.", "cleanup-firmware-queued": "Tarea de limpieza en cola, el firmware ausente se eliminará en breve", - "cleanup-queued": "Tarea de limpieza en cola — las ROMs ausentes se eliminarán en breve", + "cleanup-queued": "Tarea de limpieza en cola, las ROMs ausentes se eliminarán en breve", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/fr_FR/settings.json b/frontend/src/locales/fr_FR/settings.json index fa935cda0..e51b89588 100644 --- a/frontend/src/locales/fr_FR/settings.json +++ b/frontend/src/locales/fr_FR/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Cette action supprimera définitivement de la base de données chaque entrée de firmware{platform} dont le fichier est absent du système de fichiers. Rien n'est supprimé du disque.", "cleanup-firmware-queued": "Tâche de nettoyage mise en file d'attente, les firmwares manquants seront supprimés sous peu", - "cleanup-queued": "Tâche de nettoyage mise en file d'attente — les ROMs manquantes seront supprimées sous peu", + "cleanup-queued": "Tâche de nettoyage mise en file d'attente, les ROMs manquantes seront supprimées sous peu", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/hu_HU/settings.json b/frontend/src/locales/hu_HU/settings.json index 852efb92c..bec569027 100644 --- a/frontend/src/locales/hu_HU/settings.json +++ b/frontend/src/locales/hu_HU/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Ez véglegesen törli az adatbázisból minden olyan firmware-bejegyzést{platform}, amelynek a fájlja hiányzik a fájlrendszerből. A lemezről semmi sem törlődik.", "cleanup-firmware-queued": "Takarítási feladat sorba állítva, a hiányzó firmware hamarosan törlődik", - "cleanup-queued": "Takarítási feladat sorba állítva — a hiányzó ROM-ok hamarosan törlődnek", + "cleanup-queued": "Takarítási feladat sorba állítva, a hiányzó ROM-ok hamarosan törlődnek", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/it_IT/settings.json b/frontend/src/locales/it_IT/settings.json index 0a765ff44..a7b82eddf 100644 --- a/frontend/src/locales/it_IT/settings.json +++ b/frontend/src/locales/it_IT/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Questa azione eliminerà definitivamente dal database ogni voce di firmware{platform} il cui file manca dal filesystem. Nulla viene rimosso dal disco.", "cleanup-firmware-queued": "Attività di pulizia accodata, il firmware mancante verrà eliminato a breve", - "cleanup-queued": "Attività di pulizia accodata — le ROM mancanti verranno eliminate a breve", + "cleanup-queued": "Attività di pulizia accodata, le ROM mancanti verranno eliminate a breve", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/ja_JP/settings.json b/frontend/src/locales/ja_JP/settings.json index b9b1eac35..453fc2a3d 100644 --- a/frontend/src/locales/ja_JP/settings.json +++ b/frontend/src/locales/ja_JP/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "ファイルシステムにファイルが存在しないファームウェアの登録{platform}をデータベースから完全に削除します。ディスク上のファイルは削除されません。", "cleanup-firmware-queued": "クリーンアップタスクをキューに追加しました。不足しているファームウェアはまもなく削除されます", - "cleanup-queued": "クリーンアップタスクをキューに追加しました — 不足しているROMはまもなく削除されます", + "cleanup-queued": "クリーンアップタスクをキューに追加しました, 不足しているROMはまもなく削除されます", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/ko_KR/settings.json b/frontend/src/locales/ko_KR/settings.json index 675e110d8..f0fcbab95 100644 --- a/frontend/src/locales/ko_KR/settings.json +++ b/frontend/src/locales/ko_KR/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "파일 시스템에서 파일이 사라진 모든 펌웨어 항목{platform}을 데이터베이스에서 영구적으로 삭제합니다. 디스크에서는 아무것도 삭제되지 않습니다.", "cleanup-firmware-queued": "정리 작업이 대기열에 추가되었습니다. 누락된 펌웨어는 곧 삭제됩니다", - "cleanup-queued": "정리 작업이 대기열에 추가되었습니다 — 누락된 ROM은 곧 삭제됩니다", + "cleanup-queued": "정리 작업이 대기열에 추가되었습니다, 누락된 ROM은 곧 삭제됩니다", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/pl_PL/settings.json b/frontend/src/locales/pl_PL/settings.json index 37e4589ce..862779eac 100644 --- a/frontend/src/locales/pl_PL/settings.json +++ b/frontend/src/locales/pl_PL/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Spowoduje to trwałe usunięcie z bazy danych każdego wpisu oprogramowania{platform}, którego plik nie istnieje w systemie plików. Nic nie zostanie usunięte z dysku.", "cleanup-firmware-queued": "Zadanie czyszczenia w kolejce, brakujące oprogramowanie zostanie wkrótce usunięte", - "cleanup-queued": "Zadanie czyszczenia w kolejce — brakujące ROM-y zostaną wkrótce usunięte", + "cleanup-queued": "Zadanie czyszczenia w kolejce, brakujące ROM-y zostaną wkrótce usunięte", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/pt_BR/settings.json b/frontend/src/locales/pt_BR/settings.json index b6e6d637c..69b38e47e 100644 --- a/frontend/src/locales/pt_BR/settings.json +++ b/frontend/src/locales/pt_BR/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "Isso excluirá permanentemente do banco de dados todas as ROMs ausentes{platform} e seus diretórios de recursos. Esta ação não pode ser desfeita.", "cleanup-firmware-confirm": "Isso excluirá permanentemente do banco de dados cada entrada de firmware{platform} cujo arquivo esteja ausente no sistema de arquivos. Nada é removido do disco.", "cleanup-firmware-queued": "Tarefa de limpeza na fila, o firmware ausente será excluído em breve", - "cleanup-queued": "Tarefa de limpeza na fila — as ROMs ausentes serão excluídas em breve", + "cleanup-queued": "Tarefa de limpeza na fila, as ROMs ausentes serão excluídas em breve", "client-api-tokens": "Tokens de API de cliente", "client-token-confirm-delete": "Tem certeza de que deseja revogar este token? Qualquer dispositivo que o utilize perderá o acesso.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/ro_RO/settings.json b/frontend/src/locales/ro_RO/settings.json index 0015b9032..fdd01ec01 100644 --- a/frontend/src/locales/ro_RO/settings.json +++ b/frontend/src/locales/ro_RO/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Aceasta va șterge definitiv din baza de date fiecare intrare de firmware{platform} al cărei fișier lipsește din sistemul de fișiere. Nu se șterge nimic de pe disc.", "cleanup-firmware-queued": "Sarcina de curățare a fost pusă în coadă, firmware-ul lipsă va fi șters în scurt timp", - "cleanup-queued": "Sarcina de curățare a fost pusă în coadă — ROM-urile lipsă vor fi șterse în scurt timp", + "cleanup-queued": "Sarcina de curățare a fost pusă în coadă, ROM-urile lipsă vor fi șterse în scurt timp", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/ru_RU/settings.json b/frontend/src/locales/ru_RU/settings.json index fc092e0ed..8e9fd6ce5 100644 --- a/frontend/src/locales/ru_RU/settings.json +++ b/frontend/src/locales/ru_RU/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Это навсегда удалит из базы данных каждую запись прошивки{platform}, файл которой отсутствует в файловой системе. С диска ничего не удаляется.", "cleanup-firmware-queued": "Задача очистки поставлена в очередь, отсутствующие прошивки скоро будут удалены", - "cleanup-queued": "Задача очистки поставлена в очередь — отсутствующие ROM-ы скоро будут удалены", + "cleanup-queued": "Задача очистки поставлена в очередь, отсутствующие ROM-ы скоро будут удалены", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/tr_TR/settings.json b/frontend/src/locales/tr_TR/settings.json index 9980d17f7..4af68ae01 100644 --- a/frontend/src/locales/tr_TR/settings.json +++ b/frontend/src/locales/tr_TR/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "Bu işlem, veritabanından tüm eksik ROM'ları{platform} ve kaynak dizinlerini kalıcı olarak siler. Bu işlem geri alınamaz.", "cleanup-firmware-confirm": "Bu işlem, dosyası dosya sisteminde bulunmayan her firmware kaydını{platform} veritabanından kalıcı olarak siler. Diskten hiçbir şey silinmez.", "cleanup-firmware-queued": "Temizlik görevi sıraya alındı, eksik firmware kısa süre içinde silinecek", - "cleanup-queued": "Temizlik görevi sıraya alındı — eksik ROM'lar kısa süre içinde silinecek", + "cleanup-queued": "Temizlik görevi sıraya alındı, eksik ROM'lar kısa süre içinde silinecek", "client-api-tokens": "İstemci API Tokenları", "client-token-confirm-delete": "Bu tokenı iptal etmek istediğinizden emin misiniz? Kullanan tüm cihazlar erişimini kaybedecek.", "client-token-confirm-regenerate": "Bu işlem mevcut kimlik bilgisini geçersiz kılacak. Eski tokenı kullanan cihazların yeniden eşleştirilmesi gerekecek.", diff --git a/frontend/src/locales/zh_CN/settings.json b/frontend/src/locales/zh_CN/settings.json index e88aea1f4..73878b961 100644 --- a/frontend/src/locales/zh_CN/settings.json +++ b/frontend/src/locales/zh_CN/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "这会从数据库中永久删除所有缺失的 ROM{platform} 及其资源目录。此操作无法撤销。", "cleanup-firmware-confirm": "这将从数据库中永久删除文件已从文件系统中缺失的所有固件条目{platform}。磁盘上的文件不会被删除。", "cleanup-firmware-queued": "清理任务已排队,缺失的固件将很快被删除", - "cleanup-queued": "清理任务已排队 — 缺失的 ROM 将很快被删除", + "cleanup-queued": "清理任务已排队, 缺失的 ROM 将很快被删除", "client-api-tokens": "客户端 API 令牌", "client-token-confirm-delete": "确定要吊销此令牌吗?任何使用它的设备都将失去访问权限。", "client-token-confirm-regenerate": "这会使当前凭据失效。任何使用旧令牌的设备都需要重新配对。", diff --git a/frontend/src/locales/zh_TW/settings.json b/frontend/src/locales/zh_TW/settings.json index b49966b49..5f4036918 100644 --- a/frontend/src/locales/zh_TW/settings.json +++ b/frontend/src/locales/zh_TW/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "這將從資料庫中永久刪除檔案已從檔案系統中缺失的所有韌體項目{platform}。磁碟上的檔案不會被刪除。", "cleanup-firmware-queued": "清理任務已排程,缺失的韌體將在稍後被刪除", - "cleanup-queued": "清理任務已排程 — 缺失的 ROM 將在稍後被刪除", + "cleanup-queued": "清理任務已排程, 缺失的 ROM 將在稍後被刪除", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/v2/components/Dialogs/DeleteRomDialog.vue b/frontend/src/v2/components/Dialogs/DeleteRomDialog.vue index 5fde135cb..c17f84c37 100644 --- a/frontend/src/v2/components/Dialogs/DeleteRomDialog.vue +++ b/frontend/src/v2/components/Dialogs/DeleteRomDialog.vue @@ -423,7 +423,7 @@ function closeDialog() { } .r-v2-del-rom__append { - padding: 10px 14px 0; + padding: 10px 14px 12px; display: flex; flex-direction: column; gap: 8px; diff --git a/frontend/src/v2/components/Settings/MissingFirmwareSection.vue b/frontend/src/v2/components/Settings/MissingFirmwareSection.vue index bf6a2eb5d..3190f452c 100644 --- a/frontend/src/v2/components/Settings/MissingFirmwareSection.vue +++ b/frontend/src/v2/components/Settings/MissingFirmwareSection.vue @@ -15,6 +15,7 @@ import PlatformSelect from "@/v2/components/shared/PlatformSelect.vue"; import { useConfirm } from "@/v2/composables/useConfirm"; import { useSnackbar } from "@/v2/composables/useSnackbar"; import { useTaskCompletion } from "@/v2/composables/useTaskCompletion"; +import { errorMessage } from "@/v2/utils/errorMessage"; defineOptions({ inheritAttrs: false }); @@ -74,7 +75,9 @@ async function fetchMissingFirmware() { ); } catch (err) { snackbar.error( - t("settings.couldnt-fetch-missing-firmware", { error: String(err) }), + t("settings.couldnt-fetch-missing-firmware", { + error: errorMessage(err), + }), ); } finally { loading.value = false; @@ -103,7 +106,9 @@ async function cleanupAll() { snackbar.success(t("settings.cleanup-firmware-queued")); if (await awaitTask(data.task_id)) await fetchMissingFirmware(); } catch (err) { - snackbar.error(t("settings.couldnt-queue-cleanup", { error: String(err) })); + snackbar.error( + t("settings.couldnt-queue-cleanup", { error: errorMessage(err) }), + ); } finally { cleaningUp.value = false; } diff --git a/frontend/src/v2/components/Settings/MissingGamesSection.vue b/frontend/src/v2/components/Settings/MissingGamesSection.vue index c8ab5ff12..46b7494c2 100644 --- a/frontend/src/v2/components/Settings/MissingGamesSection.vue +++ b/frontend/src/v2/components/Settings/MissingGamesSection.vue @@ -45,6 +45,7 @@ import { useTaskCompletion } from "@/v2/composables/useTaskCompletion"; import { useWebpSupport } from "@/v2/composables/useWebpSupport"; import storeGalleryRoms, { NO_SIDECARS } from "@/v2/stores/galleryRoms"; import storeGallerySelection from "@/v2/stores/gallerySelection"; +import { errorMessage } from "@/v2/utils/errorMessage"; interface PlatformItem { id: number; @@ -238,7 +239,9 @@ async function cleanupAll() { await galleryRoms.fetchInitialMetadata(NO_SIDECARS); } } catch (err) { - snackbar.error(t("settings.couldnt-queue-cleanup", { error: String(err) })); + snackbar.error( + t("settings.couldnt-queue-cleanup", { error: errorMessage(err) }), + ); } finally { cleaningUp.value = false; } From 3972feabb55b60c768e7054fd56cf83281e18050 Mon Sep 17 00:00:00 2001 From: zurdi Date: Wed, 16 Sep 2026 13:30:15 +0200 Subject: [PATCH 2/3] fix(tasks): describe the cleanup stats a finished job actually carries `GET /tasks/status` failed response validation once a missing-ROMs cleanup had run: the task reports `platform_ids` while the schema still declared `platform_id`, and the missing-firmware cleanup had no schema at all. Both shapes are declared now, the generated types follow, and the task-by-id test checks a finished job of each kind. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01F9ta8rXUTP9aMdatPYKX4K --- backend/endpoints/responses/__init__.py | 15 +++++++- backend/tests/endpoints/test_tasks.py | 37 +++++++++++++++++++ frontend/src/__generated__/index.ts | 1 + .../__generated__/models/CleanupTaskMeta.ts | 3 +- .../models/MissingFirmwareCleanupStats.ts | 11 ++++++ .../models/MissingRomsCleanupStats.ts | 2 +- 6 files changed, 65 insertions(+), 4 deletions(-) create mode 100644 frontend/src/__generated__/models/MissingFirmwareCleanupStats.ts diff --git a/backend/endpoints/responses/__init__.py b/backend/endpoints/responses/__init__.py index b225d6f89..6f1fa89c2 100644 --- a/backend/endpoints/responses/__init__.py +++ b/backend/endpoints/responses/__init__.py @@ -53,13 +53,24 @@ class OrphanedResourcesCleanupStats(TypedDict): class MissingRomsCleanupStats(TypedDict): - platform_id: int | None + platform_ids: list[int] | None roms_found: int roms_deleted: int errors: int -CleanupStats = Union[OrphanedResourcesCleanupStats, MissingRomsCleanupStats] +class MissingFirmwareCleanupStats(TypedDict): + platform_ids: list[int] | None + firmware_found: int + firmware_deleted: int + errors: int + + +CleanupStats = Union[ + OrphanedResourcesCleanupStats, + MissingRomsCleanupStats, + MissingFirmwareCleanupStats, +] class CleanupTaskMeta(TypedDict): diff --git a/backend/tests/endpoints/test_tasks.py b/backend/tests/endpoints/test_tasks.py index 43d594aaa..73db588b2 100644 --- a/backend/tests/endpoints/test_tasks.py +++ b/backend/tests/endpoints/test_tasks.py @@ -6,6 +6,8 @@ from fastapi import status from rq.exceptions import NoSuchJobError from handler.redis_handler import redis_client +from tasks.manual.cleanup_missing_firmware import CleanupMissingFirmwareStats +from tasks.manual.cleanup_missing_roms import CleanupMissingRomsStats from tasks.tasks import Task, TaskType @@ -411,6 +413,41 @@ class TestGetTasksStatus: class TestGetTaskById: """Test suite for the get_task_by_id endpoint""" + @pytest.mark.parametrize( + "stats", + [ + CleanupMissingRomsStats(platform_ids=[3], roms_found=2, roms_deleted=2), + CleanupMissingFirmwareStats(firmware_found=1, firmware_deleted=1), + ], + ) + @patch("endpoints.tasks.Job.fetch") + def test_a_finished_cleanup_reports_its_stats( + self, mock_job_fetch, client, access_token, stats + ): + mock_job = Mock() + for field in ("enqueued_at", "created_at", "started_at", "ended_at"): + setattr(mock_job, field, Mock()) + getattr(mock_job, field).isoformat.return_value = "2023-01-01T00:00:00" + mock_job.get_meta.return_value = { + "task_key": "cleanup_missing_roms", + "task_type": TaskType.CLEANUP, + "cleanup_stats": stats.to_dict(), + } + mock_job.func_name = "tasks.tasks.run_task_by_name" + mock_job.kwargs = {"name": "cleanup_missing_roms"} + mock_job.get_status.return_value = "finished" + mock_job.id = "cleanup-job" + mock_job.result = stats.to_dict() + mock_job_fetch.return_value = mock_job + + response = client.get( + "/api/tasks/cleanup-job", + headers={"Authorization": f"Bearer {access_token}"}, + ) + + assert response.status_code == status.HTTP_200_OK + assert response.json()["meta"]["cleanup_stats"] == stats.to_dict() + @patch("endpoints.tasks.Job.fetch") def test_get_task_by_id_success(self, mock_job_fetch, client, access_token): """Test successful retrieval of a task by job ID""" diff --git a/frontend/src/__generated__/index.ts b/frontend/src/__generated__/index.ts index 95ca60ceb..7ef424937 100644 --- a/frontend/src/__generated__/index.ts +++ b/frontend/src/__generated__/index.ts @@ -130,6 +130,7 @@ export type { MemoryCardVersionSchema } from './models/MemoryCardVersionSchema'; export type { MetadataCoverageItem } from './models/MetadataCoverageItem'; export type { MetadataMediaType } from './models/MetadataMediaType'; export type { MetadataSourcesDict } from './models/MetadataSourcesDict'; +export type { MissingFirmwareCleanupStats } from './models/MissingFirmwareCleanupStats'; export type { MissingRomsCleanupStats } from './models/MissingRomsCleanupStats'; export type { MobyMetadataPlatform } from './models/MobyMetadataPlatform'; export type { MusicGameFacetSchema } from './models/MusicGameFacetSchema'; diff --git a/frontend/src/__generated__/models/CleanupTaskMeta.ts b/frontend/src/__generated__/models/CleanupTaskMeta.ts index ad55db405..1e0897265 100644 --- a/frontend/src/__generated__/models/CleanupTaskMeta.ts +++ b/frontend/src/__generated__/models/CleanupTaskMeta.ts @@ -2,9 +2,10 @@ /* istanbul ignore file */ /* tslint:disable */ /* eslint-disable */ +import type { MissingFirmwareCleanupStats } from './MissingFirmwareCleanupStats'; import type { MissingRomsCleanupStats } from './MissingRomsCleanupStats'; import type { OrphanedResourcesCleanupStats } from './OrphanedResourcesCleanupStats'; export type CleanupTaskMeta = { - cleanup_stats: (OrphanedResourcesCleanupStats | MissingRomsCleanupStats | null); + cleanup_stats: (OrphanedResourcesCleanupStats | MissingRomsCleanupStats | MissingFirmwareCleanupStats | null); }; diff --git a/frontend/src/__generated__/models/MissingFirmwareCleanupStats.ts b/frontend/src/__generated__/models/MissingFirmwareCleanupStats.ts new file mode 100644 index 000000000..ed5c09be1 --- /dev/null +++ b/frontend/src/__generated__/models/MissingFirmwareCleanupStats.ts @@ -0,0 +1,11 @@ +/* generated using openapi-typescript-codegen -- do not edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ +export type MissingFirmwareCleanupStats = { + platform_ids: (Array | null); + firmware_found: number; + firmware_deleted: number; + errors: number; +}; + diff --git a/frontend/src/__generated__/models/MissingRomsCleanupStats.ts b/frontend/src/__generated__/models/MissingRomsCleanupStats.ts index ced1b85cb..59d8bffc4 100644 --- a/frontend/src/__generated__/models/MissingRomsCleanupStats.ts +++ b/frontend/src/__generated__/models/MissingRomsCleanupStats.ts @@ -3,7 +3,7 @@ /* tslint:disable */ /* eslint-disable */ export type MissingRomsCleanupStats = { - platform_id: (number | null); + platform_ids: (Array | null); roms_found: number; roms_deleted: number; errors: number; From bd90488e73f036834c84cdcbe339646591330e7e Mon Sep 17 00:00:00 2001 From: zurdi Date: Wed, 16 Sep 2026 13:58:45 +0200 Subject: [PATCH 3/3] fix(tasks): count only live workers, and cover the review's gaps The worker guard now ignores workers that announced their death or are suspended, and the tests run with a live worker on the task queue by default, so the other successful-run tests pass again; a scan-only, dead or suspended worker is checked to be refused. The developer setup runs each worker in its own terminal, adds the RQ cron process that registers the schedule, and ties the Redis URL to the `.env` defaults. The Japanese, Korean and Chinese cleanup messages use their own punctuation, and both Settings sections have a test that the server's reason reaches the error snackbar. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01F9ta8rXUTP9aMdatPYKX4K --- DEVELOPER_SETUP.md | 13 +++- backend/endpoints/tasks.py | 20 +++++- backend/tests/endpoints/test_tasks.py | 72 +++++++++++++++++-- frontend/src/locales/ja_JP/settings.json | 2 +- frontend/src/locales/ko_KR/settings.json | 2 +- frontend/src/locales/zh_CN/settings.json | 2 +- frontend/src/locales/zh_TW/settings.json | 2 +- .../Settings/MissingFirmwareSection.test.ts | 65 ++++++++++++++--- .../Settings/MissingGamesSection.test.ts | 71 +++++++++++++++--- 9 files changed, 218 insertions(+), 31 deletions(-) diff --git a/DEVELOPER_SETUP.md b/DEVELOPER_SETUP.md index e3967c38c..6b0518c13 100644 --- a/DEVELOPER_SETUP.md +++ b/DEVELOPER_SETUP.md @@ -128,14 +128,25 @@ uv run python3 main.py #### - Run the task workers -Manual tasks (the missing ROMs and firmware cleanups, folder sync) and the scheduled jobs run on an RQ worker, and scans on a worker of their own. Without them a task stays queued. +Manual tasks (the missing ROMs and firmware cleanups, folder sync) and every scheduled job run on RQ workers, and scans on a worker of their own. Without them a task stays queued. Each command is a foreground process, so run them in separate terminals. The Redis URL below matches the `REDIS_*` defaults in `.env`; adjust it if you changed them. ```sh cd backend uv run rq worker --url redis://127.0.0.1:6379/0 --worker-class handler.rq_worker.RomMWorker --with-scheduler high default low +``` + +```sh +cd backend uv run rq worker --url redis://127.0.0.1:6379/0 --worker-class handler.rq_worker.RomMWorker scans ``` +`--with-scheduler` only releases delayed jobs. The recurring schedule itself is registered by the RQ cron process, which the workers then execute: + +```sh +cd backend +RQ_REDIS_URL=redis://127.0.0.1:6379/0 uv run rq cron tasks.cron_config +``` + ### Setting up the frontend #### - Install node.js dependencies diff --git a/backend/endpoints/tasks.py b/backend/endpoints/tasks.py index 04f8d0694..119957b14 100644 --- a/backend/endpoints/tasks.py +++ b/backend/endpoints/tasks.py @@ -2,10 +2,11 @@ from datetime import datetime, timezone from typing import Any, Final, Mapping, cast from fastapi import Body, HTTPException, Request, status -from rq import Worker +from rq import Queue, Worker from rq.exceptions import NoSuchJobError from rq.job import Job, JobStatus from rq.registry import FailedJobRegistry, FinishedJobRegistry +from rq.worker import WorkerStatus from config import ENABLE_RESCAN_ON_FILESYSTEM_CHANGE, RESCAN_ON_FILESYSTEM_CHANGE_DELAY from decorators.auth import protected_route @@ -274,6 +275,19 @@ async def get_task_by_id(request: Request, task_id: str) -> TaskStatusResponse: TASK_KWARGS = Body(default=None) +def _listening_workers(queue: Queue) -> list[Worker]: + """Registered workers of ``queue`` that are alive and not suspended. + + A crashed worker stays registered until its TTL expires, which RQ's own + maintenance sweep bounds; this filters the ones that told us they left. + """ + return [ + worker + for worker in Worker.all(queue=queue, connection=redis_client) + if worker.death_date is None and worker.get_state() != WorkerStatus.SUSPENDED + ] + + @protected_route(router.post, "/run/{task_name}", [Scope.TASKS_RUN]) async def run_single_task( request: Request, @@ -302,8 +316,8 @@ async def run_single_task( detail=f"Task '{task_name}' cannot be run", ) - # Without a worker the job would sit queued while the UI reports it done. - if not Worker.all(queue=low_prio_queue, connection=redis_client): + # Without a worker the job would sit queued while the UI waits on it. + if not _listening_workers(low_prio_queue): raise HTTPException( status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="No task worker is running, so the task cannot be queued", diff --git a/backend/tests/endpoints/test_tasks.py b/backend/tests/endpoints/test_tasks.py index 73db588b2..dd73d6f0f 100644 --- a/backend/tests/endpoints/test_tasks.py +++ b/backend/tests/endpoints/test_tasks.py @@ -5,12 +5,31 @@ import pytest from fastapi import status from rq.exceptions import NoSuchJobError -from handler.redis_handler import redis_client +from handler.redis_handler import low_prio_queue, redis_client, scan_queue from tasks.manual.cleanup_missing_firmware import CleanupMissingFirmwareStats from tasks.manual.cleanup_missing_roms import CleanupMissingRomsStats from tasks.tasks import Task, TaskType +def _live_worker() -> Mock: + worker = Mock(death_date=None) + worker.get_state.return_value = "idle" + return worker + + +@pytest.fixture(autouse=True) +def task_queue_worker(): + """A live worker on the task queue, so a run is accepted unless a test + takes it away.""" + worker = _live_worker() + + def workers_for(connection=None, queue=None, **_kwargs): + return [worker] if queue is low_prio_queue else [] + + with patch("endpoints.tasks.Worker.all", side_effect=workers_for) as mocked: + yield mocked + + def _job_with_meta(meta: dict[str, Any]) -> Mock: """A finished job carrying `meta`, for asserting on what the response reports.""" job = Mock() @@ -256,11 +275,10 @@ class TestRunSingleTask: ) def test_run_single_task_success(self, mock_enqueue, client, access_token): """Test successful running of a single task""" - with patch("endpoints.tasks.Worker.all", return_value=[Mock()]): - response = client.post( - "/api/tasks/run/test_task", - headers={"Authorization": f"Bearer {access_token}"}, - ) + response = client.post( + "/api/tasks/run/test_task", + headers={"Authorization": f"Bearer {access_token}"}, + ) assert response.status_code == status.HTTP_200_OK data = response.json() @@ -302,6 +320,48 @@ class TestRunSingleTask: assert "worker" in response.json()["detail"] mock_enqueue.assert_not_called() + @pytest.mark.parametrize( + "workers_for", + [ + # A scan worker does not serve the task queue. + lambda connection=None, queue=None, **_: ( + [_live_worker()] if queue is scan_queue else [] + ), + # One that announced its death or was suspended does not count. + lambda connection=None, queue=None, **_: [Mock(death_date="gone")], + lambda connection=None, queue=None, **_: [ + Mock(death_date=None, **{"get_state.return_value": "suspended"}) + ], + ], + ids=["scan-worker-only", "dead-worker", "suspended-worker"], + ) + @patch("endpoints.tasks.enqueue_task") + @patch( + "endpoints.tasks.RUNNABLE_TASKS", + { + "test_task": Mock( + spec=Task, + task_type=TaskType.CLEANUP, + title="Test Task", + enabled=True, + manual_run=True, + can_run_manually=True, + run=Mock(), + ), + }, + ) + def test_only_a_live_worker_on_the_task_queue_counts( + self, mock_enqueue, client, access_token, workers_for + ): + with patch("endpoints.tasks.Worker.all", side_effect=workers_for): + response = client.post( + "/api/tasks/run/test_task", + headers={"Authorization": f"Bearer {access_token}"}, + ) + + assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE + mock_enqueue.assert_not_called() + @patch("endpoints.tasks.RUNNABLE_TASKS", {}) def test_run_single_task_not_found(self, client, access_token): """Test running a non-existent task""" diff --git a/frontend/src/locales/ja_JP/settings.json b/frontend/src/locales/ja_JP/settings.json index 453fc2a3d..4b5fcf10d 100644 --- a/frontend/src/locales/ja_JP/settings.json +++ b/frontend/src/locales/ja_JP/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "ファイルシステムにファイルが存在しないファームウェアの登録{platform}をデータベースから完全に削除します。ディスク上のファイルは削除されません。", "cleanup-firmware-queued": "クリーンアップタスクをキューに追加しました。不足しているファームウェアはまもなく削除されます", - "cleanup-queued": "クリーンアップタスクをキューに追加しました, 不足しているROMはまもなく削除されます", + "cleanup-queued": "クリーンアップタスクをキューに追加しました。不足しているROMはまもなく削除されます", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/ko_KR/settings.json b/frontend/src/locales/ko_KR/settings.json index f0fcbab95..a86085b76 100644 --- a/frontend/src/locales/ko_KR/settings.json +++ b/frontend/src/locales/ko_KR/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "파일 시스템에서 파일이 사라진 모든 펌웨어 항목{platform}을 데이터베이스에서 영구적으로 삭제합니다. 디스크에서는 아무것도 삭제되지 않습니다.", "cleanup-firmware-queued": "정리 작업이 대기열에 추가되었습니다. 누락된 펌웨어는 곧 삭제됩니다", - "cleanup-queued": "정리 작업이 대기열에 추가되었습니다, 누락된 ROM은 곧 삭제됩니다", + "cleanup-queued": "정리 작업이 대기열에 추가되었습니다. 누락된 ROM은 곧 삭제됩니다", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/zh_CN/settings.json b/frontend/src/locales/zh_CN/settings.json index 73878b961..a3a9bacbd 100644 --- a/frontend/src/locales/zh_CN/settings.json +++ b/frontend/src/locales/zh_CN/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "这会从数据库中永久删除所有缺失的 ROM{platform} 及其资源目录。此操作无法撤销。", "cleanup-firmware-confirm": "这将从数据库中永久删除文件已从文件系统中缺失的所有固件条目{platform}。磁盘上的文件不会被删除。", "cleanup-firmware-queued": "清理任务已排队,缺失的固件将很快被删除", - "cleanup-queued": "清理任务已排队, 缺失的 ROM 将很快被删除", + "cleanup-queued": "清理任务已排队,缺失的 ROM 将很快被删除", "client-api-tokens": "客户端 API 令牌", "client-token-confirm-delete": "确定要吊销此令牌吗?任何使用它的设备都将失去访问权限。", "client-token-confirm-regenerate": "这会使当前凭据失效。任何使用旧令牌的设备都需要重新配对。", diff --git a/frontend/src/locales/zh_TW/settings.json b/frontend/src/locales/zh_TW/settings.json index 5f4036918..39b9111ff 100644 --- a/frontend/src/locales/zh_TW/settings.json +++ b/frontend/src/locales/zh_TW/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "這將從資料庫中永久刪除檔案已從檔案系統中缺失的所有韌體項目{platform}。磁碟上的檔案不會被刪除。", "cleanup-firmware-queued": "清理任務已排程,缺失的韌體將在稍後被刪除", - "cleanup-queued": "清理任務已排程, 缺失的 ROM 將在稍後被刪除", + "cleanup-queued": "清理任務已排程,缺失的 ROM 將在稍後被刪除", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/v2/components/Settings/MissingFirmwareSection.test.ts b/frontend/src/v2/components/Settings/MissingFirmwareSection.test.ts index fc380aee4..c20a8a93a 100644 --- a/frontend/src/v2/components/Settings/MissingFirmwareSection.test.ts +++ b/frontend/src/v2/components/Settings/MissingFirmwareSection.test.ts @@ -1,30 +1,55 @@ import { flushPromises, mount } from "@vue/test-utils"; +import { AxiosError } from "axios"; import { createPinia, setActivePinia } from "pinia"; import { beforeEach, describe, expect, it, vi } from "vitest"; import storePlatforms from "@/stores/platforms"; import MissingFirmwareSection from "./MissingFirmwareSection.vue"; -const { getFirmware, runTask, getTaskById, confirm } = vi.hoisted(() => ({ - getFirmware: vi.fn(), - runTask: vi.fn(), - getTaskById: vi.fn(), - confirm: vi.fn(), -})); +const { getFirmware, runTask, getTaskById, confirm, snackbarError } = + vi.hoisted(() => ({ + getFirmware: vi.fn(), + runTask: vi.fn(), + getTaskById: vi.fn(), + confirm: vi.fn(), + snackbarError: vi.fn(), + })); vi.mock("@/services/api/firmware", () => ({ default: { getFirmware } })); vi.mock("@/services/api/task", () => ({ default: { runTask, getTaskById } })); +// Error messages keep their `error` parameter so the tests can see what +// reached the snackbar. vi.mock("vue-i18n", () => ({ - useI18n: () => ({ t: (key: string) => key }), + useI18n: () => ({ + t: (key: string, params?: { error?: string }) => + params?.error ? `${key}: ${params.error}` : key, + }), })); vi.mock("@/v2/composables/useConfirm", () => ({ useConfirm: () => confirm, })); vi.mock("@/v2/composables/useSnackbar", () => ({ - useSnackbar: () => ({ success: vi.fn(), error: vi.fn() }), + useSnackbar: () => ({ success: vi.fn(), error: snackbarError }), })); +// The server's reason for a refused request, as axios delivers it. +function serverError(detail: string) { + return new AxiosError( + "Request failed with status code 503", + "ERR_BAD_RESPONSE", + undefined, + undefined, + { + status: 503, + statusText: "Service Unavailable", + data: { detail }, + headers: {}, + config: {} as never, + }, + ); +} + const PS1 = { id: 1, slug: "ps", @@ -96,6 +121,7 @@ describe("MissingFirmwareSection", () => { getTaskById.mockResolvedValue({ data: { status: "finished" } }); confirm.mockReset(); confirm.mockResolvedValue(true); + snackbarError.mockReset(); getFirmware.mockReset(); getFirmware.mockResolvedValue({ data: [firmware(10, PS1.id, "scph5501.bin")], @@ -238,4 +264,27 @@ describe("MissingFirmwareSection", () => { 0, ); }); + + it("tells why the server refused the cleanup", async () => { + runTask.mockRejectedValue(serverError("No task worker is running")); + const wrapper = mountSection(); + await flushPromises(); + + wrapper.findComponent({ name: "RMenuItem" }).vm.$emit("click"); + await flushPromises(); + + expect(snackbarError).toHaveBeenCalledWith( + "settings.couldnt-queue-cleanup: No task worker is running", + ); + }); + + it("tells why the list could not be fetched", async () => { + getFirmware.mockRejectedValue(serverError("Database unavailable")); + mountSection(); + await flushPromises(); + + expect(snackbarError).toHaveBeenCalledWith( + "settings.couldnt-fetch-missing-firmware: Database unavailable", + ); + }); }); diff --git a/frontend/src/v2/components/Settings/MissingGamesSection.test.ts b/frontend/src/v2/components/Settings/MissingGamesSection.test.ts index 1f35876f8..8b4c7b163 100644 --- a/frontend/src/v2/components/Settings/MissingGamesSection.test.ts +++ b/frontend/src/v2/components/Settings/MissingGamesSection.test.ts @@ -1,28 +1,46 @@ import { flushPromises, mount } from "@vue/test-utils"; +import { AxiosError } from "axios"; import { createPinia, setActivePinia } from "pinia"; import { beforeEach, describe, expect, it, vi } from "vitest"; import MissingGamesSection from "./MissingGamesSection.vue"; -const { getRoms } = vi.hoisted(() => ({ getRoms: vi.fn() })); +const { getRoms, runTask, getTaskById, confirm, snackbarError } = vi.hoisted( + () => ({ + getRoms: vi.fn(), + runTask: vi.fn(), + getTaskById: vi.fn(), + confirm: vi.fn(), + snackbarError: vi.fn(), + }), +); vi.mock("@/services/api/rom", () => ({ default: { getRoms } })); vi.mock("@/services/api/task", () => ({ - default: { - runTask: vi.fn().mockResolvedValue({ data: { task_id: "job-1" } }), - getTaskById: vi.fn().mockResolvedValue({ data: { status: "finished" } }), - }, + default: { runTask, getTaskById }, })); +// Error messages keep their `error` parameter so the tests can see what +// reached the snackbar. vi.mock("vue-i18n", () => ({ - useI18n: () => ({ t: (key: string) => key }), + useI18n: () => ({ + t: (key: string, params?: { error?: string }) => + params?.error ? `${key}: ${params.error}` : key, + }), })); vi.mock("@/v2/composables/useConfirm", () => ({ - useConfirm: () => vi.fn().mockResolvedValue(false), + useConfirm: () => confirm, })); vi.mock("@/v2/composables/useSnackbar", () => ({ - useSnackbar: () => ({ success: vi.fn(), error: vi.fn() }), + useSnackbar: () => ({ success: vi.fn(), error: snackbarError }), })); + +// The kebab's items live in RMenu's default slot; the auto-stub drops slot +// content, so render it to reach the cleanup action. +const RMenuStub = { + name: "RMenu", + template: '
', +}; vi.mock("@/v2/composables/useWebpSupport", () => ({ useWebpSupport: () => ({ supportsWebp: { value: true } }), })); @@ -37,7 +55,7 @@ function mountSection() { GameListSkeletonRow: true, RBtn: true, RIcon: true, - RMenu: true, + RMenu: RMenuStub, RMenuItem: true, RSelect: true, RTag: true, @@ -54,6 +72,13 @@ describe("MissingGamesSection", () => { getRoms.mockResolvedValue({ data: { total: 0, items: [], char_index: {}, rom_id_index: [] }, }); + runTask.mockReset(); + runTask.mockResolvedValue({ data: { task_id: "job-1" } }); + getTaskById.mockReset(); + getTaskById.mockResolvedValue({ data: { status: "finished" } }); + confirm.mockReset(); + confirm.mockResolvedValue(false); + snackbarError.mockReset(); }); // The tab renders no filter drawer, no A-Z strip and drives its scroller @@ -87,4 +112,32 @@ describe("MissingGamesSection", () => { expect(params.withFilterValues).toBe(false); expect(params.withRomIdIndex).toBe(false); }); + + it("tells why the server refused the cleanup", async () => { + confirm.mockResolvedValue(true); + runTask.mockRejectedValue( + new AxiosError( + "Request failed with status code 503", + "ERR_BAD_RESPONSE", + undefined, + undefined, + { + status: 503, + statusText: "Service Unavailable", + data: { detail: "No task worker is running" }, + headers: {}, + config: {} as never, + }, + ), + ); + const wrapper = mountSection(); + await flushPromises(); + + wrapper.findComponent({ name: "RMenuItem" }).vm.$emit("click"); + await flushPromises(); + + expect(snackbarError).toHaveBeenCalledWith( + "settings.couldnt-queue-cleanup: No task worker is running", + ); + }); });