diff --git a/DOCS-web-control-api.md b/DOCS-web-control-api.md index 32f0322..a9ee4ce 100644 --- a/DOCS-web-control-api.md +++ b/DOCS-web-control-api.md @@ -186,8 +186,8 @@ with explicit params, a `Progress` reporter and a `Prompter`. its text search for the same step. - `result` โ€” `{ok, summary, data?}` exactly once at the end. -`install`'s target, dry run, Valve-Proton switch and result data: see -[DOCS-web-install.md](DOCS-web-install.md). +`install`'s target, dry run, Valve Proton and result; `repair-ghosts` and its +`game_running` refusal: see [DOCS-web-install.md](DOCS-web-install.md). ## Friction (server/daemon-enforced) diff --git a/DOCS-web-install.md b/DOCS-web-install.md index ddd2a93..2aa1adc 100644 --- a/DOCS-web-install.md +++ b/DOCS-web-install.md @@ -1,4 +1,4 @@ -# `install` job params and result +# `install` and `repair-ghosts` jobs Part of the web control API ([DOCS-web-control-api.md](DOCS-web-control-api.md)); the TS mirror of the result is `InstallResultData` in `web/src/api/contract.ts`. @@ -27,3 +27,25 @@ installer closes Steam, so a real install while a game runs skips the fast path (`_fast_install._refusal`) and Steam's own download starts: `fast_install_skipped` is then `"game_running"`, and the UI paints the `result.game-running` mark on the result (`result.dry-run` for a dry run). + +## `repair-ghosts` + +`./run.sh repair-ghosts` and the `repair-ghosts` job (Library page, icon +`cmd.repair-ghosts`) run the installer's `--repair-ghosts` +(`main/repair_ghosts.py`): every cold ghost manifest is renamed to +`*.ghost-` and its empty folder removed; a ghost with staged bytes is +only reported (`DOCS-steam-installer.md`, "Ghost installs"). No params, result +`data` = the assignment, an installer failure is `op_failed`. + +The installer does not close Steam here, but it rewrites the library under a +client that may be reading it, so it gets `install`'s guard +(`_steam_restart_guard.game_is_running`). + +| Command | Phrase (exact) | Checked | +|---|---|---| +| `repair-ghosts` | `delete ghost manifests` | at `POST /api/jobs` (`_web_jobs._PRECHECKED`), then again in the job | + +At `POST /api/jobs` the phrase is checked first (`400 wrong_phrase`), then the +guard (`409 game_running`). Either refusal creates no job. The job re-checks +both, because a game can start in between. The UI paints the +`result.game-running` mark on a `game_running` refusal. diff --git a/steam_backlog_enforcer/_command_catalog.py b/steam_backlog_enforcer/_command_catalog.py index 99b14a6..19389f4 100644 --- a/steam_backlog_enforcer/_command_catalog.py +++ b/steam_backlog_enforcer/_command_catalog.py @@ -72,6 +72,7 @@ CATALOG: Final[dict[str, _Entry]] = { "hide": _job("library"), "unhide": _job("library"), "add-exception": _job("library"), + "repair-ghosts": _job("library"), "gaming-status": _view("gaming", "/api/budget"), "gaming-reset": _job("gaming"), "gaming-unblock": _job("gaming"), diff --git a/steam_backlog_enforcer/_command_help.py b/steam_backlog_enforcer/_command_help.py index e8db8e6..c206bc6 100644 --- a/steam_backlog_enforcer/_command_help.py +++ b/steam_backlog_enforcer/_command_help.py @@ -31,6 +31,7 @@ COMMAND_DESCRIPTIONS: Final[dict[str, str]] = { "stats": "Show backlog completion-time estimates", "gaming-status": "Show today's gaming time and block state", "gaming-reset": "Reset today's gaming counter (root + phrase)", + "repair-ghosts": "Delete the fake 'installed' manifests anonymous steamcmd left", } # Commands with non-standard arg handling (shown in help but not in COMMANDS). diff --git a/steam_backlog_enforcer/_fast_install_cmd.py b/steam_backlog_enforcer/_fast_install_cmd.py index 437849d..0e2e1f3 100644 --- a/steam_backlog_enforcer/_fast_install_cmd.py +++ b/steam_backlog_enforcer/_fast_install_cmd.py @@ -86,3 +86,20 @@ def build_cmd( if account: cmd += ["--username", account] return desktop_user_cmd(cmd, user) + + +def build_repair_ghosts_cmd(installer: Path, user: str | None) -> list[str]: + """The installer's ``--repair-ghosts`` run, dropped to the desktop user. + + No AppID: it scans every library for the fake manifests anonymous + steamcmd left and clears only the cold ones (``DOCS-steam-installer.md``). + """ + cmd = [ + "env", + f"PYTHONPATH={installer.parents[1]}", + _PYTHON, + "-m", + "steam_installer.cli", + "--repair-ghosts", + ] + return desktop_user_cmd(cmd, user) diff --git a/steam_backlog_enforcer/_friction.py b/steam_backlog_enforcer/_friction.py index 193e3ca..a9e0b73 100644 --- a/steam_backlog_enforcer/_friction.py +++ b/steam_backlog_enforcer/_friction.py @@ -52,6 +52,8 @@ FRICTION: Final[dict[str, Friction]] = { "uninstall": Friction("uninstall {count} games"), "reset": Friction("wipe all enforcer state"), "restore-backup": Friction("restore backup {backup_id}"), + # Checked at POST /api/jobs too (_web_jobs._PRECHECKED), then again by the job. + "repair-ghosts": Friction("delete ghost manifests"), } diff --git a/steam_backlog_enforcer/_steam_restart_guard.py b/steam_backlog_enforcer/_steam_restart_guard.py index 5543f69..728375e 100644 --- a/steam_backlog_enforcer/_steam_restart_guard.py +++ b/steam_backlog_enforcer/_steam_restart_guard.py @@ -25,6 +25,9 @@ from steam_backlog_enforcer._steam_state import steam_update_in_progress logger = logging.getLogger(__name__) +# The refusal of a web job that waits for the game to exit (``game_running``). +GAME_RUNNING_JOB_MSG = "A game is running: this waits until it exits." + def game_is_running() -> bool: """Whether a Steam game is currently running. diff --git a/steam_backlog_enforcer/_web_errors.py b/steam_backlog_enforcer/_web_errors.py index e98f16e..4519c59 100644 --- a/steam_backlog_enforcer/_web_errors.py +++ b/steam_backlog_enforcer/_web_errors.py @@ -30,6 +30,7 @@ STATUS_BY_CODE: Final[dict[str, HTTPStatus]] = { "busy": HTTPStatus.CONFLICT, "countdown_running": HTTPStatus.CONFLICT, "not_cancellable": HTTPStatus.CONFLICT, + "game_running": HTTPStatus.CONFLICT, "pending_lapsed": HTTPStatus.GONE, "rate_limited": HTTPStatus.TOO_MANY_REQUESTS, "daemon_unreachable": HTTPStatus.SERVICE_UNAVAILABLE, diff --git a/steam_backlog_enforcer/_web_jobs.py b/steam_backlog_enforcer/_web_jobs.py index 8f5d4a3..2221374 100644 --- a/steam_backlog_enforcer/_web_jobs.py +++ b/steam_backlog_enforcer/_web_jobs.py @@ -11,11 +11,15 @@ refused as ``busy`` because a scan is running. from __future__ import annotations from http import HTTPStatus -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, Final from steam_backlog_enforcer._backups import list_backups from steam_backlog_enforcer._command_params import InvalidParamsError, validate_params from steam_backlog_enforcer._friction import expected_phrase, phrase_matches +from steam_backlog_enforcer._steam_restart_guard import ( + GAME_RUNNING_JOB_MSG, + game_is_running, +) from steam_backlog_enforcer._web_daemon import confirm_phrase_of from steam_backlog_enforcer._web_errors import ApiError, from_job_error, not_found from steam_backlog_enforcer._web_io import Reply, no_content, ok @@ -33,6 +37,10 @@ if TYPE_CHECKING: # (demo 0) is the daemon's. _ENFORCE_MODES = {"demo": 1, "restart": 0} +# Jobs whose phrase and game-running guard are checked here, before a job +# exists, so a refusal never leaves a job behind; the job re-checks both. +_PRECHECKED: Final = frozenset({"repair-ghosts"}) + def _invalid(message: str) -> ApiError: """An ``invalid_params`` 400.""" @@ -73,6 +81,25 @@ def _job_request(request: Request) -> tuple[str, dict[str, Any], str | None]: return command, params, phrase +def _precheck(command: str, phrase: str | None) -> None: + """Refuse a :data:`_PRECHECKED` job before it is created. + + The phrase goes first: it is what the user can fix, and it stays + provable while a game runs. + + Raises: + ApiError: ``wrong_phrase``, or ``game_running`` while a game runs. + """ + if command not in _PRECHECKED: + return + expected = expected_phrase(command) or "" + if not phrase_matches(expected, phrase or ""): + msg = f'Type "{expected}" to run {command}.' + raise ApiError(msg, code="wrong_phrase") + if game_is_running(): + raise ApiError(GAME_RUNNING_JOB_MSG, code="game_running") + + def jobs_view(_request: Request) -> Reply: """``GET /api/jobs`` โ€” newest first, at most 50.""" return ok(list_jobs()) @@ -98,6 +125,7 @@ def create_job_view(request: Request) -> Reply: raise _invalid(str(exc)) from None if is_privileged(command, clean): return run_privileged(command, clean, phrase) + _precheck(command, phrase) try: job_id = create_job(command, clean, confirm_phrase=phrase) except JobError as exc: diff --git a/steam_backlog_enforcer/jobs/_errors.py b/steam_backlog_enforcer/jobs/_errors.py index e3b80d6..52c8a1c 100644 --- a/steam_backlog_enforcer/jobs/_errors.py +++ b/steam_backlog_enforcer/jobs/_errors.py @@ -13,6 +13,7 @@ JobErrorCode = Literal[ "busy", "not_cancellable", "op_failed", + "game_running", ] diff --git a/steam_backlog_enforcer/jobs/_registry.py b/steam_backlog_enforcer/jobs/_registry.py index 51c9851..aaa6467 100644 --- a/steam_backlog_enforcer/jobs/_registry.py +++ b/steam_backlog_enforcer/jobs/_registry.py @@ -33,6 +33,7 @@ from steam_backlog_enforcer.main import ( cmd_list, cmd_pick, cmd_pick_manual, + cmd_repair_ghosts, cmd_reset, cmd_stats, cmd_unhide, @@ -180,6 +181,7 @@ HANDLERS: dict[str, JobHandler] = { "add-exception": _add_exception, "reset": _cli(cmd_reset), "restore-backup": _restore_backup, + "repair-ghosts": _cli(cmd_repair_ghosts), "stats": _cli(cmd_stats), "list": _cli(cmd_list), "enforce": _enforce_demo, diff --git a/steam_backlog_enforcer/jobs/_specs.py b/steam_backlog_enforcer/jobs/_specs.py index ea339c3..d0f3c2d 100644 --- a/steam_backlog_enforcer/jobs/_specs.py +++ b/steam_backlog_enforcer/jobs/_specs.py @@ -56,6 +56,7 @@ JOB_FLAGS: Final[dict[str, JobFlags]] = { "add-exception": JobFlags(), "reset": JobFlags(), "restore-backup": JobFlags(), + "repair-ghosts": JobFlags(), "stats": JobFlags(mutating=False, cancellable=True), "list": JobFlags(mutating=False, cancellable=True), # Only the demo runs as a job (see is_privileged). diff --git a/steam_backlog_enforcer/main/__init__.py b/steam_backlog_enforcer/main/__init__.py index 7542b32..2b18da5 100644 --- a/steam_backlog_enforcer/main/__init__.py +++ b/steam_backlog_enforcer/main/__init__.py @@ -73,6 +73,7 @@ from steam_backlog_enforcer.main.picks import ( cmd_pick, cmd_pick_manual, ) +from steam_backlog_enforcer.main.repair_ghosts import cmd_repair_ghosts from steam_backlog_enforcer.main.status import cmd_list, cmd_status from steam_backlog_enforcer.scanning import do_check, do_scan @@ -113,6 +114,7 @@ __all__ = [ "cmd_list", "cmd_pick", "cmd_pick_manual", + "cmd_repair_ghosts", "cmd_reset", "cmd_serve", "cmd_setup", @@ -142,6 +144,7 @@ _HANDLERS: dict[str, Callable[[Config, State], object]] = { "stats": cmd_stats, "gaming-status": cmd_gaming_status, "gaming-reset": cmd_gaming_reset, + "repair-ghosts": cmd_repair_ghosts, } # Descriptions live in _command_help (the web catalog reads them too); the diff --git a/steam_backlog_enforcer/main/_install_target.py b/steam_backlog_enforcer/main/_install_target.py index 793bb31..d503a65 100644 --- a/steam_backlog_enforcer/main/_install_target.py +++ b/steam_backlog_enforcer/main/_install_target.py @@ -26,7 +26,8 @@ from steam_installer.target import parse_literal if TYPE_CHECKING: from steam_backlog_enforcer.config import Config, State -# The dry run only reads Steam's app cache and library folders. +# The dry run only reads Steam's app cache and library folders; repair-ghosts +# only scans them and renames a few manifests. _DRY_RUN_TIMEOUT_SECONDS = 50 @@ -96,6 +97,18 @@ def dry_run_install(app_id: int, name: str, *, valve_proton: bool) -> None: dry_run=True, ) _echo(f"Dry run for {name or f'AppID={app_id}'}:") + code = relay_installer(cmd) + if code: + msg = f"Dry run failed (installer exit {code})." + raise JobError(msg, code="op_failed") + + +def relay_installer(cmd: list[str]) -> int: + """Run a short, prompt-free installer *cmd*, echo its output, return its exit. + + Used for the read-only ``--dry-run`` and for ``--repair-ghosts``; neither + downloads, so both fit the same timeout. + """ proc = subprocess.run( cmd, check=False, @@ -107,6 +120,4 @@ def dry_run_install(app_id: int, name: str, *, valve_proton: bool) -> None: ) for line in proc.stdout.splitlines(): _echo(f" {line}") - if proc.returncode: - msg = f"Dry run failed (installer exit {proc.returncode})." - raise JobError(msg, code="op_failed") + return proc.returncode diff --git a/steam_backlog_enforcer/main/repair_ghosts.py b/steam_backlog_enforcer/main/repair_ghosts.py new file mode 100644 index 0000000..ac416c3 --- /dev/null +++ b/steam_backlog_enforcer/main/repair_ghosts.py @@ -0,0 +1,52 @@ +"""``repair-ghosts``: the installer's ``--repair-ghosts``, behind friction. + +The installer renames each cold ghost manifest (one that claims "installed" +with nothing on disk) and removes its empty folder; a ghost with staged bytes +is reported and kept. It does not close Steam itself, but it rewrites the +library under a client that may be reading it, so it waits like ``install`` +does until no game is running. The web server checks the phrase and the guard +before a job exists (``_web_jobs``); this re-checks both inside the job. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from steam_backlog_enforcer._desktop_env import resolve_desktop_user +from steam_backlog_enforcer._fast_install_cmd import ( + build_repair_ghosts_cmd, + installer_path, +) +from steam_backlog_enforcer._prompter import PromptAbortedError, confirm_phrase +from steam_backlog_enforcer._steam_restart_guard import ( + GAME_RUNNING_JOB_MSG, + game_is_running, +) +from steam_backlog_enforcer.jobs._errors import JobError +from steam_backlog_enforcer.main._install_target import relay_installer + +if TYPE_CHECKING: + from steam_backlog_enforcer.config import Config, State + + +def cmd_repair_ghosts(_config: Config, _state: State) -> None: + """Delete the ghost manifests, after the guard and the typed phrase. + + Raises: + JobError: ``game_running`` while a game runs; ``op_failed`` when the + installer is missing or exits non-zero. + PromptAbortedError: The phrase was not typed exactly. + """ + if game_is_running(): + raise JobError(GAME_RUNNING_JOB_MSG, code="game_running") + if not confirm_phrase("repair-ghosts", "Delete the ghost install manifests?"): + msg = "Aborted." + raise PromptAbortedError(msg) + installer = installer_path() + if installer is None: + msg = "steam-game-installer is missing from this checkout." + raise JobError(msg, code="op_failed") + code = relay_installer(build_repair_ghosts_cmd(installer, resolve_desktop_user())) + if code: + msg = f"repair-ghosts failed (installer exit {code})." + raise JobError(msg, code="op_failed") diff --git a/steam_backlog_enforcer/tests/test_repair_ghosts.py b/steam_backlog_enforcer/tests/test_repair_ghosts.py new file mode 100644 index 0000000..1bc43c2 --- /dev/null +++ b/steam_backlog_enforcer/tests/test_repair_ghosts.py @@ -0,0 +1,200 @@ +"""Tests for ``repair-ghosts``: CLI command, job, catalog and POST-time friction.""" + +from __future__ import annotations + +from http import HTTPStatus +from typing import TYPE_CHECKING +from unittest.mock import MagicMock, patch + +import pytest + +from steam_backlog_enforcer import _command_catalog, _web_jobs +from steam_backlog_enforcer._fast_install_cmd import build_repair_ghosts_cmd +from steam_backlog_enforcer._friction import expected_phrase +from steam_backlog_enforcer._prompter import PromptAbortedError, use_prompter +from steam_backlog_enforcer._web_errors import STATUS_BY_CODE, ApiError +from steam_backlog_enforcer.config import Config, State +from steam_backlog_enforcer.jobs import _registry +from steam_backlog_enforcer.jobs._errors import JobError +from steam_backlog_enforcer.jobs._specs import JOB_FLAGS +from steam_backlog_enforcer.main import COMMANDS +from steam_backlog_enforcer.main.repair_ghosts import cmd_repair_ghosts +from steam_backlog_enforcer.tests._fake_prompter import FakePrompter +from steam_backlog_enforcer.tests._web_request import make_request + +if TYPE_CHECKING: + from collections.abc import Iterator + from pathlib import Path + +PKG = "steam_backlog_enforcer.main.repair_ghosts" +TGT = "steam_backlog_enforcer.main._install_target" +PHRASE = "delete ghost manifests" + + +@pytest.fixture(name="env") +def _env() -> Iterator[dict[str, MagicMock]]: + """No game running, an installer present, the subprocess mocked.""" + with ( + patch(f"{PKG}.game_is_running", return_value=False) as running, + patch(f"{PKG}.installer_path", return_value=MagicMock()), + patch(f"{PKG}.build_repair_ghosts_cmd", return_value=["inst"]) as build, + patch(f"{TGT}.subprocess.run") as run, + patch(f"{TGT}._echo") as echo, + ): + run.return_value = MagicMock(returncode=0, stdout="No ghost installs found.\n") + yield {"running": running, "run": run, "build": build, "echo": echo} + + +def _run(phrases: tuple[bool, ...] = (True,)) -> FakePrompter: + prompter = FakePrompter(phrases=phrases) + with use_prompter(prompter): + cmd_repair_ghosts(Config(), State()) + return prompter + + +class TestCommand: + """``cmd_repair_ghosts``: guard, phrase, then the installer.""" + + def test_runs_the_installer_and_relays_its_report( + self, env: dict[str, MagicMock] + ) -> None: + """The right phrase runs ``--repair-ghosts`` and echoes every line.""" + prompter = _run() + assert prompter.asked[0][1] == PHRASE + env["run"].assert_called_once() + assert env["run"].call_args.args[0] == ["inst"] + env["echo"].assert_any_call(" No ghost installs found.") + + def test_game_running_refuses_before_the_phrase( + self, env: dict[str, MagicMock] + ) -> None: + """A running game refuses with ``game_running``; nothing runs.""" + env["running"].return_value = True + with pytest.raises(JobError) as exc: + _run(phrases=()) + assert exc.value.code == "game_running" + env["run"].assert_not_called() + + def test_wrong_phrase_aborts(self, env: dict[str, MagicMock]) -> None: + """A wrong phrase aborts the job and never runs the installer.""" + with pytest.raises(PromptAbortedError): + _run(phrases=(False,)) + env["run"].assert_not_called() + + def test_installer_failure_fails_the_job(self, env: dict[str, MagicMock]) -> None: + """A non-zero installer exit is ``op_failed``.""" + env["run"].return_value = MagicMock(returncode=1, stdout="ERROR x\n") + with pytest.raises(JobError) as exc: + _run() + assert exc.value.code == "op_failed" + + def test_missing_installer(self, env: dict[str, MagicMock]) -> None: + """No installer in the checkout fails loudly before any subprocess.""" + with ( + patch(f"{PKG}.installer_path", return_value=None), + pytest.raises(JobError), + ): + _run() + env["run"].assert_not_called() + + +class TestWiring: + """CLI, job, catalog, friction and error-code tables.""" + + def test_argv(self, tmp_path: Path) -> None: + """The installer gets ``--repair-ghosts`` and no AppID.""" + installer = tmp_path / "steam_installer" / "cli.py" + with patch( + "steam_backlog_enforcer._fast_install_cmd.desktop_user_cmd", + side_effect=lambda cmd, _user: cmd, + ): + cmd = build_repair_ghosts_cmd(installer, None) + assert cmd[-3:] == ["-m", "steam_installer.cli", "--repair-ghosts"] + assert f"PYTHONPATH={tmp_path}" in cmd + assert "--appid" not in cmd + + def test_tables(self) -> None: + """One phrase, one 409 code, a CLI command, a job and a library card.""" + assert expected_phrase("repair-ghosts") == PHRASE + assert STATUS_BY_CODE["game_running"] == HTTPStatus.CONFLICT + assert COMMANDS["repair-ghosts"][1] is cmd_repair_ghosts + assert JOB_FLAGS["repair-ghosts"].mutating + assert "repair-ghosts" in _registry.HANDLERS + assert _command_catalog.CATALOG["repair-ghosts"].category == "library" + + def test_job_handler_returns_the_assignment( + self, env: dict[str, MagicMock] + ) -> None: + """The job runs the CLI command and reports the assignment.""" + with ( + use_prompter(FakePrompter(phrases=(True,))), + patch.object(_registry.State, "load", return_value=State()), + patch.object(_registry.Config, "load", return_value=Config()), + ): + data = _registry.HANDLERS["repair-ghosts"]({}, MagicMock(), MagicMock()) + env["run"].assert_called_once() + assert data == {"current_app_id": None, "current_game_name": None} + + +_WEB = "steam_backlog_enforcer._web_jobs" + + +def _post(phrase: str | None, *, running: bool = False) -> tuple[object, MagicMock]: + body: dict[str, object] = {"command": "repair-ghosts", "params": {}} + if phrase is not None: + body["confirm_phrase"] = phrase + with ( + patch(f"{_WEB}.create_job", return_value="j1") as create, + patch(f"{_WEB}.read_job", return_value={"id": "j1"}), + patch(f"{_WEB}.game_is_running", return_value=running), + ): + try: + reply: object = _web_jobs.create_job_view(make_request(body=body)) + except ApiError as exc: + reply = exc + return reply, create + + +class TestPostTimeFriction: + """``POST /api/jobs`` refuses before a job exists.""" + + @pytest.mark.parametrize("phrase", [None, "", "Delete ghost manifests"]) + def test_wrong_phrase_creates_no_job(self, phrase: str | None) -> None: + """A missing or wrong phrase is ``wrong_phrase`` and no job.""" + reply, create = _post(phrase) + assert isinstance(reply, ApiError) + assert reply.code == "wrong_phrase" + create.assert_not_called() + + def test_wrong_phrase_wins_over_a_running_game(self) -> None: + """The phrase is checked first, so friction is provable mid-game.""" + reply, _ = _post("nope", running=True) + assert isinstance(reply, ApiError) + assert reply.code == "wrong_phrase" + + def test_game_running_creates_no_job(self) -> None: + """The right phrase while a game runs is ``game_running`` (409).""" + reply, create = _post(PHRASE, running=True) + assert isinstance(reply, ApiError) + assert (reply.code, reply.status) == ("game_running", HTTPStatus.CONFLICT) + create.assert_not_called() + + def test_right_phrase_creates_the_job(self) -> None: + """The right phrase with no game creates the job, phrase passed on.""" + reply, create = _post(f" {PHRASE} ") + assert not isinstance(reply, ApiError) + create.assert_called_once_with( + "repair-ghosts", {}, confirm_phrase=f" {PHRASE} " + ) + + def test_other_commands_are_not_prechecked(self) -> None: + """Commands outside the set keep their job-side check only.""" + with ( + patch(f"{_WEB}.create_job", return_value="j1") as create, + patch(f"{_WEB}.read_job", return_value={"id": "j1"}), + patch(f"{_WEB}.game_is_running", return_value=True), + ): + _web_jobs.create_job_view( + make_request(body={"command": "uninstall", "params": {}}) + ) + create.assert_called_once() diff --git a/web/src/api/contract.ts b/web/src/api/contract.ts index 102515a..e737370 100644 --- a/web/src/api/contract.ts +++ b/web/src/api/contract.ts @@ -30,6 +30,7 @@ export type CommandName = | 'gaming-reset' | 'gaming-unblock' | 'serve' + | 'repair-ghosts' /** Job spawned by `POST /api/backups/{id}/restore`, not a CLI command. */ | 'restore-backup' /** Failed end-of-window store re-block the web server records; never started by hand. */ diff --git a/web/src/api/errors.ts b/web/src/api/errors.ts index 16cbee5..9064a0b 100644 --- a/web/src/api/errors.ts +++ b/web/src/api/errors.ts @@ -21,6 +21,7 @@ const EXPLAIN: Record = { op_failed: { title: 'Action failed', hint: 'The daemon or the job process hit an error. See the job log or the daemon journal on System.' }, server_stale: { title: 'Server is restarting', hint: 'It was running outdated code and restarts on the current code. Retry in a few seconds.' }, unsupported: { title: 'Not supported here', hint: 'Nothing supervises this process (it is not running under systemd), so a restart would be a stop.' }, + game_running: { title: 'Game running', hint: 'This waits until the game exits. Run it again after you stop playing.' }, network: { title: 'Server not reachable', hint: 'Is it running? Start it with ./run.sh serve.' }, http: { title: 'Unexpected server error', hint: 'Check the server log.' }, } diff --git a/web/src/api/jobContract.ts b/web/src/api/jobContract.ts index 1058187..82c709b 100644 --- a/web/src/api/jobContract.ts +++ b/web/src/api/jobContract.ts @@ -118,6 +118,8 @@ export type ApiErrorCode = | 'server_stale' /** Daemon cannot do this here, e.g. restart while unsupervised. */ | 'unsupported' + /** A game is running and this job waits until it exits (409). */ + | 'game_running' export interface ApiError { error: ApiErrorCode diff --git a/web/src/commands/catalog.ts b/web/src/commands/catalog.ts index 749b84d..6ee889e 100644 --- a/web/src/commands/catalog.ts +++ b/web/src/commands/catalog.ts @@ -44,6 +44,7 @@ export const COMMAND_HOME = { serve: '/system', 'restore-backup': '/system', 're-block': '/store', + 'repair-ghosts': '/library', } as const satisfies Record /** A command's registered icon id (`cmd.`); the compiler proves every command has one. */ diff --git a/web/src/commands/runnerDialog.failures.test.ts b/web/src/commands/runnerDialog.failures.test.ts index fe38212..8cddfe0 100644 --- a/web/src/commands/runnerDialog.failures.test.ts +++ b/web/src/commands/runnerDialog.failures.test.ts @@ -48,6 +48,21 @@ describe(' start failures', () => { expect(text()).toContain('sudo ./run.sh gaming-unblock') }) + it('paints the game-running mark when a running game refuses the job', async () => { + const spec = makeSpec('repair-ghosts', { friction: { phrase_template: 'delete ghost manifests' } }) + openRunner([spec], 'repair-ghosts', { extra: { 'POST /api/jobs': apiError(409, 'game_running', 'a game is running') } }) + await vi.waitFor(() => { expect(document.querySelector('.phrase input')).not.toBeNull() }) + const input = must(document.querySelector('.phrase input')) + input.value = 'delete ghost manifests' + input.dispatchEvent(new Event('input', { bubbles: true })) + submit(await found('Run repair-ghosts')) + await vi.waitFor(() => { expect(document.querySelector('[data-code="game_running"]')).not.toBeNull() }) + const refusal = must(document.querySelector('[data-code="game_running"]')) + expect(refusal).toHaveTextContent('๐ŸŽฎโธ๏ธ') + expect(refusal).toHaveTextContent('a game is running') + expect(refusal.getAttribute('aria-label')).toMatch(/^Game running\./) + }) + it('has no fallback for a command without one', async () => { openRunner([makeSpec('scan')], 'scan', { extra: { 'POST /api/jobs': apiError(502, 'daemon_unreachable') } }) submit(await found('Run scan')) diff --git a/web/src/commands/runnerForm.ts b/web/src/commands/runnerForm.ts index 15d9255..6520a42 100644 --- a/web/src/commands/runnerForm.ts +++ b/web/src/commands/runnerForm.ts @@ -166,6 +166,7 @@ export class Runner { failure?.code === 'daemon_unreachable' && fallback ? terminalFallback(fallback) : null, + failure?.code === 'game_running' ? iconInline('result.game-running') : null, ), ] : []), diff --git a/web/src/icons/coverage.test.ts b/web/src/icons/coverage.test.ts index 68da6f4..0a86bb8 100644 --- a/web/src/icons/coverage.test.ts +++ b/web/src/icons/coverage.test.ts @@ -48,9 +48,9 @@ describe('icon words cover the whole UI', () => { expect(hits, `${hits.length} unregistered icon sites`).toEqual([]) }) - it('the first 46 registry entries are the pass-1 icons (all answered but cmd.re-block), then the rest', () => { + it('the first 47 registry entries are the pass-1 icons (all answered but cmd.re-block and cmd.repair-ghosts), then the rest', () => { const ids = ICONS.map((e) => e.id) - expect(ids.slice(0, 46).filter((id) => /^(nav|palette|cmd|job\.state|notice)\./.test(id))).toHaveLength(46) - expect(ids[45]).toBe('notice.danger') + expect(ids.slice(0, 47).filter((id) => /^(nav|palette|cmd|job\.state|notice)\./.test(id))).toHaveLength(47) + expect(ids[46]).toBe('notice.danger') }) }) diff --git a/web/src/icons/registry.json b/web/src/icons/registry.json index 4723bd7..434324d 100644 --- a/web/src/icons/registry.json +++ b/web/src/icons/registry.json @@ -23,6 +23,7 @@ "cmd.abandon-pick": { "glyph": "โŒ", "spoken": "Abandon pick", "desc": "Runs abandon pick: undoes a manual pick, so the enforcer assigns a game again.", "words": ["abandon", "undo", "drop"], "alts": ["โœ–๏ธ", "โ†ฉ๏ธ", "๐Ÿšฎ"] }, "cmd.install": { "glyph": "โฌ‡๏ธ", "spoken": "Install", "desc": "Runs install: downloads an allowed game, trying the fast installer first.", "words": ["install", "download", "get"], "alts": ["๐Ÿ“ฅ", "๐Ÿ”ฝ", "โฌ"] }, "cmd.uninstall": { "glyph": "๐Ÿ—‘๏ธ", "spoken": "Uninstall", "desc": "Runs uninstall: removes every installed game that is neither assigned nor protected.", "words": ["uninstall", "remove", "clean"], "alts": ["๐Ÿงน", "โ๏ธ", "๐Ÿชฃ"] }, + "cmd.repair-ghosts": { "glyph": "๐Ÿ‘ป", "spoken": "Repair ghosts", "desc": "Runs repair ghosts: deletes the fake installed manifests anonymous steamcmd left, keeping any with staged bytes.", "words": ["ghosts", "phantom", "fake"], "alts": ["๐ŸงŸ", "๐Ÿชฆ", "๐Ÿซฅ"] }, "cmd.hide": { "glyph": "๐Ÿ™ˆ", "spoken": "Hide", "desc": "Runs hide: hides every game except the assigned one in the Steam library.", "words": ["hide", "conceal", "mask"], "alts": ["๐Ÿซฃ", "๐Ÿ•ถ๏ธ", "๐ŸŒซ๏ธ"] }, "cmd.unhide": { "glyph": "๐Ÿ‘๏ธ", "spoken": "Unhide", "desc": "Runs unhide: shows every game in the Steam library again.", "words": ["unhide", "show", "reveal"], "alts": ["๐Ÿ‘€", "๐Ÿ”ฆ", "๐ŸชŸ"] }, "cmd.buy-dlc": { "glyph": "๐Ÿ’ณ", "spoken": "Buy DLC", "desc": "Runs buy DLC: unblocks the Steam store for 15 minutes so you can buy a game or DLC.", "words": ["DLC", "buy", "purchase"], "alts": ["๐Ÿ’ต", "๐Ÿช™", "๐Ÿท๏ธ"] }, diff --git a/web/src/icons/registry.test.ts b/web/src/icons/registry.test.ts index 51d6486..46c22b2 100644 --- a/web/src/icons/registry.test.ts +++ b/web/src/icons/registry.test.ts @@ -9,13 +9,13 @@ const JOB_STATES: JobState[] = ['queued', 'running', 'waiting_input', 'succeeded const TONES: Tone[] = ['info', 'success', 'warning', 'danger'] describe('icon registry', () => { - it('registers pass 1 first (8 nav, the palette, 27 commands, 6 job states, 4 tones), then the rest of the UI', () => { + it('registers pass 1 first (8 nav, the palette, 28 commands, 6 job states, 4 tones), then the rest of the UI', () => { const ids = ICONS.map((e) => e.id) expect(new Set(ids).size).toBe(ids.length) const pass1 = /^(nav|palette|cmd|job\.state|notice)\./ - expect(ids.slice(0, 8 + 1 + 27 + 6 + 4).every((id) => pass1.test(id))).toBe(true) - expect(ids.slice(8 + 1 + 27 + 6 + 4).some((id) => pass1.test(id))).toBe(false) - expect(ids.length).toBeGreaterThan(46) + expect(ids.slice(0, 8 + 1 + 28 + 6 + 4).every((id) => pass1.test(id))).toBe(true) + expect(ids.slice(8 + 1 + 28 + 6 + 4).some((id) => pass1.test(id))).toBe(false) + expect(ids.length).toBeGreaterThan(47) for (const n of NAV) expect(isIconId(n.icon)).toBe(true) expect(isIconId('palette.open')).toBe(true) for (const name of Object.keys(COMMAND_HOME) as (keyof typeof COMMAND_HOME)[]) { diff --git a/web/src/pages/library/index.astro b/web/src/pages/library/index.astro index 2de6c1f..a19e199 100644 --- a/web/src/pages/library/index.astro +++ b/web/src/pages/library/index.astro @@ -12,6 +12,7 @@ import '../../styles/library-page.css' +