From c9ae0bf0b1de03100e1ea87f39f458f87f3bc55b Mon Sep 17 00:00:00 2001 From: Krzysztof kuhy Rudnicki Date: Sun, 22 Nov 2026 20:46:31 +0100 Subject: [PATCH] Install by target, dry run and Valve Proton The install job takes optional target (AppID, URL or name), dry_run and valve_proton params. The target is resolved inside the games allowed today (allowed_games plus approved exceptions) and refused otherwise; the installer only gets the checked --appid. Dry run runs the installer's --dry-run alone, so it is safe while a game runs. The no-target picker now offers not-installed approved exceptions too. Todo: 6ee260a4 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WzxdWZCxnNWLtpVwFLVk9w --- DOCS-web-control-api.md | 3 + DOCS-web-install.md | 29 +++ steam_backlog_enforcer/_command_params.py | 26 ++ steam_backlog_enforcer/_fast_install.py | 8 +- steam_backlog_enforcer/_fast_install_cmd.py | 15 +- steam_backlog_enforcer/game_install.py | 21 +- steam_backlog_enforcer/jobs/_registry.py | 18 +- .../main/_install_target.py | 112 +++++++++ steam_backlog_enforcer/main/install.py | 74 ++++-- .../tests/test_fast_install_helpers.py | 9 + .../tests/test_game_install_queue.py | 4 +- .../tests/test_install_target.py | 228 ++++++++++++++++++ 12 files changed, 516 insertions(+), 31 deletions(-) create mode 100644 DOCS-web-install.md create mode 100644 steam_backlog_enforcer/main/_install_target.py create mode 100644 steam_backlog_enforcer/tests/test_install_target.py diff --git a/DOCS-web-control-api.md b/DOCS-web-control-api.md index d564d03..32f0322 100644 --- a/DOCS-web-control-api.md +++ b/DOCS-web-control-api.md @@ -186,6 +186,9 @@ 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). + ## Friction (server/daemon-enforced) | Command | Phrase (exact) | Extra | diff --git a/DOCS-web-install.md b/DOCS-web-install.md new file mode 100644 index 0000000..ddd2a93 --- /dev/null +++ b/DOCS-web-install.md @@ -0,0 +1,29 @@ +# `install` job params and result + +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`. + +All three params are optional (`_command_params.PARAMS["install"]`): + +- `target` (string): an AppID, a Steam URL (`…/app//…`) or a name, as + the installer's own `TARGET` argument. The job resolves it, never the + installer: inside the games allowed today, which are `allowed_games(state)` + plus the approved exceptions (named from the owned records). AppIDs and URLs + are parsed locally; names match exact title first, then substring (case + ignored), with no Steam search. Several matches → a `choice` prompt; no + match, or an id outside that set → the job fails (`locked`) and no + installer runs. The installer only ever gets the checked `--appid`. + Without `target`, the job offers every allowed game not yet fully + installed, approved exceptions included (`choice` when more than one). +- `dry_run` (bool): runs only `steam_installer.cli --appid --dry-run` + and relays its report as `log` lines. No manifest is queued, Steam is not + closed, there is no `steam://` fallback, so it is allowed while a game runs. + An installer failure fails the job (`op_failed`). +- `valve_proton` (bool): passes `--valve-proton` to the installer. + +The result `data` is `InstallResultData` `{app_id, dry_run, +fast_install_skipped}` once a game was chosen (else the assignment). The +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). diff --git a/steam_backlog_enforcer/_command_params.py b/steam_backlog_enforcer/_command_params.py index de47628..a9b68a1 100644 --- a/steam_backlog_enforcer/_command_params.py +++ b/steam_backlog_enforcer/_command_params.py @@ -65,6 +65,32 @@ PARAMS: Final[dict[str, tuple[ParamSpec, ...]]] = { help="Leave unchecked to keep playing them alongside the new pick.", ), ), + # No target: the picker over every allowed game not yet installed. + "install": ( + ParamSpec( + "target", + "AppID, Steam URL or name", + "string", + required=False, + help="Only games allowed today; an ambiguous name asks.", + ), + ParamSpec( + "dry_run", + "Dry run", + "bool", + required=False, + default=0, + help="Shows what the installer would do and changes nothing.", + ), + ParamSpec( + "valve_proton", + "Valve Proton", + "bool", + required=False, + default=0, + help="Keep the game on Valve's default Proton.", + ), + ), "pick-manual": (_APP_ID,), "abandon-pick": (_APP_ID,), "add-exception": ( diff --git a/steam_backlog_enforcer/_fast_install.py b/steam_backlog_enforcer/_fast_install.py index d0b9734..68889cd 100644 --- a/steam_backlog_enforcer/_fast_install.py +++ b/steam_backlog_enforcer/_fast_install.py @@ -189,7 +189,11 @@ def _wait_detached(app_id: int, label: str) -> bool: def fast_install( - app_id: int, label: str, prepare: Callable[[], object] = lambda: None + app_id: int, + label: str, + prepare: Callable[[], object] = lambda: None, + *, + valve_proton: bool = False, ) -> bool: """Install *app_id* with steam-game-installer. @@ -213,7 +217,7 @@ def fast_install( _echo(f" Fast install of {label} skipped: {reason}.") return False - cmd = build_cmd(installer, app_id, user) + cmd = build_cmd(installer, app_id, user, valve_proton=valve_proton) prepare() if not sys.stdin.isatty(): _spawn_detached(cmd, app_id, label) diff --git a/steam_backlog_enforcer/_fast_install_cmd.py b/steam_backlog_enforcer/_fast_install_cmd.py index 031de4f..437849d 100644 --- a/steam_backlog_enforcer/_fast_install_cmd.py +++ b/steam_backlog_enforcer/_fast_install_cmd.py @@ -51,11 +51,20 @@ def steam_account_name() -> str | None: return match.group(1) if match else None -def build_cmd(installer: Path, app_id: int, user: str | None) -> list[str]: +def build_cmd( + installer: Path, + app_id: int, + user: str | None, + *, + valve_proton: bool = False, + dry_run: bool = False, +) -> list[str]: """The installer invocation, dropped to the desktop user when root. Launched as ``python3 -m steam_installer.cli`` with the checkout on ``PYTHONPATH``: ``sudo`` resets the environment, so it is named in the argv. + *valve_proton* keeps the game on Valve's default Proton; *dry_run* only + reports what the installer would do. """ cmd = [ "env", @@ -69,6 +78,10 @@ def build_cmd(installer: Path, app_id: int, user: str | None) -> list[str]: "--language", _LANGUAGE, ] + if valve_proton: + cmd.append("--valve-proton") + if dry_run: + cmd.append("--dry-run") account = steam_account_name() if account: cmd += ["--username", account] diff --git a/steam_backlog_enforcer/game_install.py b/steam_backlog_enforcer/game_install.py index 3fbb3eb..eb7dd1e 100644 --- a/steam_backlog_enforcer/game_install.py +++ b/steam_backlog_enforcer/game_install.py @@ -138,6 +138,7 @@ def install_game( steam_id: str, *, use_steam_protocol: bool = False, + valve_proton: bool = False, ) -> bool: """Install a game, through steam-game-installer when it can be used. @@ -145,22 +146,19 @@ def install_game( below it is the fallback for when it is refused or fails. When *use_steam_protocol* is True the ``steam://install`` URI handler - is used, which lets Steam determine the correct install directory from - its own metadata. This avoids mismatches between the display name and - the canonical ``installdir`` that can cause "Missing game executable" - errors. Falls back to writing a fabricated appmanifest if the URI - handler is unavailable. + is used, so Steam picks the canonical ``installdir`` from its own + metadata (a display-name mismatch causes "Missing game executable"). + Falls back to a fabricated appmanifest if the handler is unavailable. - When *use_steam_protocol* is False (the default) a minimal - appmanifest with StateFlags=1026 is written directly. This is - suitable for non-interactive / daemon contexts where opening a Steam - dialog is undesirable. + When False (the default) a minimal appmanifest with StateFlags=1026 is + written directly: no Steam dialog, for non-interactive / daemon use. Args: app_id: Steam application ID. game_name: Human-readable game name. steam_id: Steam64 ID of the account that owns the game. use_steam_protocol: Prefer the ``steam://install`` URI handler. + valve_proton: Keep the game on Valve's default Proton (fast path). Returns True if the install was triggered successfully. """ @@ -170,9 +168,8 @@ def install_game( return ready # The installer only finishes a manifest it finds: queue a fresh install first. - if fast_install( - app_id, label, partial(_queue_download, app_id, game_name, steam_id) - ): + prepare = partial(_queue_download, app_id, game_name, steam_id) + if fast_install(app_id, label, prepare, valve_proton=valve_proton): return True # Steam already has a download of its own going: let it carry on, rather # than overwrite its manifest with the fabricated one below. diff --git a/steam_backlog_enforcer/jobs/_registry.py b/steam_backlog_enforcer/jobs/_registry.py index e667423..51c9851 100644 --- a/steam_backlog_enforcer/jobs/_registry.py +++ b/steam_backlog_enforcer/jobs/_registry.py @@ -104,6 +104,22 @@ def _pick( return _assignment(state) +def _install( + params: Mapping[str, ParamValue], _progress: Progress, _prompter: Prompter +) -> JobResult: + """``install``: optional target, dry run and Valve-Proton switch.""" + state = State.load() + target = params.get("target") + data = cmd_install( + Config.load(), + state, + target=str(target) if target else None, + dry_run=bool(params.get("dry_run")), + valve_proton=bool(params.get("valve_proton")), + ) + return data if data is not None else _assignment(state) + + def _enforce_demo( params: Mapping[str, ParamValue], _progress: Progress, _prompter: Prompter ) -> JobResult: @@ -157,7 +173,7 @@ HANDLERS: dict[str, JobHandler] = { "pick": _pick, "pick-manual": _with_args(cmd_pick_manual, "app_id"), "abandon-pick": _with_args(cmd_abandon_pick, "app_id"), - "install": _cli(cmd_install), + "install": _install, "uninstall": _cli(cmd_uninstall), "hide": _cli(cmd_hide), "unhide": _cli(cmd_unhide), diff --git a/steam_backlog_enforcer/main/_install_target.py b/steam_backlog_enforcer/main/_install_target.py new file mode 100644 index 0000000..793bb31 --- /dev/null +++ b/steam_backlog_enforcer/main/_install_target.py @@ -0,0 +1,112 @@ +"""Which game ``install`` may touch, and the installer's dry run. + +The web ``install`` takes a target the way the installer does (AppID, Steam +URL or name), but the enforcer resolves it, inside the set of games allowed +today, before the installer runs. The installer then only ever gets the +checked ``--appid``: handing it the raw text would let its own Steam search +pick an app this check never saw. Names are matched locally, so a refused +game costs no network call and an ambiguous one is a choice, never a guess. +""" + +from __future__ import annotations + +import subprocess +from typing import TYPE_CHECKING + +from steam_backlog_enforcer._actions import allowed_games +from steam_backlog_enforcer._desktop_env import resolve_desktop_user +from steam_backlog_enforcer._echo import _echo +from steam_backlog_enforcer._fast_install_cmd import build_cmd, installer_path +from steam_backlog_enforcer._owned_apps_cache import load_owned_records +from steam_backlog_enforcer._prompter import PromptOption, current_prompter +from steam_backlog_enforcer._whitelist_locking import get_approved_exception_ids +from steam_backlog_enforcer.jobs._errors import JobError +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. +_DRY_RUN_TIMEOUT_SECONDS = 50 + + +def install_candidates(config: Config, state: State) -> list[tuple[int, str]]: + """Every game ``install`` may install today, as ``(app_id, name)``. + + The enforcer's allowed games (assignment first, then manual picks) plus + the approved exceptions, named from the owned-games records. + """ + games = allowed_games(state) + known = {aid for aid, _ in games} + records = load_owned_records(config.steam_id) or [] + names = {int(r["app_id"]): str(r.get("name") or "") for r in records} + for app_id in sorted(get_approved_exception_ids() - known): + games.append((app_id, names.get(app_id, ""))) + return games + + +def _refuse(text: str) -> JobError: + """The refusal for a game that is not allowed today.""" + return JobError(f"{text!r} is not a game allowed today.", code="locked") + + +def resolve_target(text: str, candidates: list[tuple[int, str]]) -> tuple[int, str]: + """Resolve *text* to one of *candidates*. + + Raises: + JobError: ``locked`` when the target is not an allowed game. + """ + literal = parse_literal(text) + if literal is not None: + game = next((g for g in candidates if g[0] == literal[0]), None) + if game is None: + raise _refuse(text) + return game + wanted = text.strip().casefold() + exact = [g for g in candidates if g[1].casefold() == wanted] + matches = exact or [g for g in candidates if wanted in g[1].casefold()] + if not matches: + raise _refuse(text) + if len(matches) == 1: + return matches[0] + options = [PromptOption(str(aid), name) for aid, name in matches] + picked = int(current_prompter().choice("Install which game", options)) + return next(g for g in matches if g[0] == picked) + + +def dry_run_install(app_id: int, name: str, *, valve_proton: bool) -> None: + """Run the installer's ``--dry-run`` for *app_id* and relay its report. + + Never goes through ``install_game``: no manifest is queued, Steam is not + closed and there is no ``steam://`` fallback, so it is safe while a game + is running. + + Raises: + JobError: ``op_failed`` when the installer is missing or fails. + """ + installer = installer_path() + if installer is None: + msg = "steam-game-installer is missing from this checkout." + raise JobError(msg, code="op_failed") + cmd = build_cmd( + installer, + app_id, + resolve_desktop_user(), + valve_proton=valve_proton, + dry_run=True, + ) + _echo(f"Dry run for {name or f'AppID={app_id}'}:") + proc = subprocess.run( + cmd, + check=False, + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + timeout=_DRY_RUN_TIMEOUT_SECONDS, + ) + 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") diff --git a/steam_backlog_enforcer/main/install.py b/steam_backlog_enforcer/main/install.py index 07e9c7e..95b9401 100644 --- a/steam_backlog_enforcer/main/install.py +++ b/steam_backlog_enforcer/main/install.py @@ -14,6 +14,7 @@ from steam_backlog_enforcer._prompter import ( current_prompter, ) from steam_backlog_enforcer._steam_errors import SteamUnavailableError +from steam_backlog_enforcer._steam_restart_guard import game_is_running from steam_backlog_enforcer._steam_state import is_game_fully_installed from steam_backlog_enforcer.game_install import ( _echo, @@ -26,6 +27,11 @@ from steam_backlog_enforcer.library_hider import ( try_hide_other_games, unhide_all_games, ) +from steam_backlog_enforcer.main._install_target import ( + dry_run_install, + install_candidates, + resolve_target, +) if TYPE_CHECKING: from steam_backlog_enforcer.config import Config, State @@ -78,16 +84,16 @@ def cmd_uninstall(_config: Config, state: State) -> None: _echo(f"\nUninstalled {count} games.") -def _pick_install_target(state: State) -> tuple[int, str] | None: +def _pick_install_target( + candidates: list[tuple[int, str]], +) -> tuple[int, str] | None: """The allowed game to install: the only unfinished one, or the user's pick. Every allowed game counts, not just the assignment: a manual pick whose fast install was skipped (a game was running at pick time) needs a way to - start it later too. + start it later too, and so does an approved exception. """ - pending = [ - (aid, n) for aid, n in allowed_games(state) if not is_game_fully_installed(aid) - ] + pending = [(aid, n) for aid, n in candidates if not is_game_fully_installed(aid)] if not pending: _echo("All allowed games are already installed.") return None @@ -98,31 +104,71 @@ def _pick_install_target(state: State) -> tuple[int, str] | None: return next(game for game in pending if game[0] == picked) -def cmd_install(config: Config, state: State) -> None: +def cmd_install( + config: Config, + state: State, + *, + target: str | None = None, + dry_run: bool = False, + valve_proton: bool = False, +) -> dict[str, object] | None: """Install an allowed game, through the fast installer when it can be used. A download Steam already started is taken over, so this is also how a - fast install that was skipped earlier gets started. + fast install that was skipped earlier gets started. *target* (AppID, URL + or name) must be a game allowed today; *dry_run* only reports what the + installer would do. + + Returns: + ``{app_id, dry_run, fast_install_skipped}`` once a game was chosen, + else ``None``. + + Raises: + JobError: ``locked`` for a target that is not allowed today. """ - if not allowed_games(state): + candidates = install_candidates(config, state) + if not candidates: _echo("No game currently assigned. Run 'scan' first.") - return - target = _pick_install_target(state) - if target is None: - return - app_id, name = target + return None + if target: + chosen: tuple[int, str] | None = resolve_target(target, candidates) + else: + chosen = _pick_install_target(candidates) + if chosen is None: + return None + app_id, name = chosen + result: dict[str, object] = { + "app_id": app_id, + "dry_run": dry_run, + "fast_install_skipped": None, + } + if dry_run: + current_progress().phase(f"Dry run of {name or app_id}") + dry_run_install(app_id, name, valve_proton=valve_proton) + return result + # The installer closes Steam: with a game running the fast path is + # refused (Steam's own download starts instead), and the UI says why. + if game_is_running(): + result["fast_install_skipped"] = "game_running" _echo(f"Installing {name} (AppID={app_id})...") # install_game only *starts* the download (fast installer or steam://); # there is no download-progress loop to report on yet. current_progress().phase(f"Starting install of {name}") - if not install_game(app_id, name, config.steam_id, use_steam_protocol=True): + if not install_game( + app_id, + name, + config.steam_id, + use_steam_protocol=True, + valve_proton=valve_proton, + ): _echo("Failed to start the install.") elif fast_install_failure(app_id) is None: _echo("Done!") else: # The fast install already printed its "Failed: ..." line. _echo("Steam's own download was started instead.") + return result def cmd_hide(config: Config, state: State) -> None: diff --git a/steam_backlog_enforcer/tests/test_fast_install_helpers.py b/steam_backlog_enforcer/tests/test_fast_install_helpers.py index ccc011f..6767624 100644 --- a/steam_backlog_enforcer/tests/test_fast_install_helpers.py +++ b/steam_backlog_enforcer/tests/test_fast_install_helpers.py @@ -110,3 +110,12 @@ class TestIsFastInstalling: _RUNS.append(_DetachedRun(5, MagicMock(), Path("/nonexistent"))) assert _fast_install.is_fast_installing(5) is True assert _fast_install.is_fast_installing(6) is False + + +def test_build_cmd_valve_proton_and_dry_run() -> None: + """The two install switches become the installer's own flags.""" + with patch.object(_fast_install_cmd, "steam_account_name", return_value=None): + cmd = _fast_install_cmd.build_cmd( + Path("/x/steam_installer/cli.py"), 7, None, valve_proton=True, dry_run=True + ) + assert cmd[-2:] == ["--valve-proton", "--dry-run"] diff --git a/steam_backlog_enforcer/tests/test_game_install_queue.py b/steam_backlog_enforcer/tests/test_game_install_queue.py index b74d4db..ba8805f 100644 --- a/steam_backlog_enforcer/tests/test_game_install_queue.py +++ b/steam_backlog_enforcer/tests/test_game_install_queue.py @@ -27,7 +27,9 @@ class TestQueueBeforeFastInstall: install is queued with Steam before the installer runs, not after.""" seen: list[bool] = [] - def fast(_app_id: int, _label: str, prepare: Callable[[], object]) -> bool: + def fast( + _app_id: int, _label: str, prepare: Callable[[], object], **_kw: object + ) -> bool: prepare() seen.append((tmp_path / "appmanifest_440.acf").exists()) return True diff --git a/steam_backlog_enforcer/tests/test_install_target.py b/steam_backlog_enforcer/tests/test_install_target.py new file mode 100644 index 0000000..5b860d9 --- /dev/null +++ b/steam_backlog_enforcer/tests/test_install_target.py @@ -0,0 +1,228 @@ +"""Tests for ``install`` with a target, a dry run and the Valve-Proton switch. + +The locker stays intact: the target is resolved and checked by the enforcer +against the games allowed today (the assignment, manual picks and approved +exceptions), and the installer only ever gets the checked ``--appid``. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING +from unittest.mock import MagicMock, patch + +import pytest + +from steam_backlog_enforcer._command_params import validate_params +from steam_backlog_enforcer._prompter import use_prompter +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.main import cmd_install +from steam_backlog_enforcer.main._install_target import ( + install_candidates, + resolve_target, +) +from steam_backlog_enforcer.tests._fake_prompter import FakePrompter + +if TYPE_CHECKING: + from collections.abc import Iterator + +PKG = "steam_backlog_enforcer.main.install" +TGT = "steam_backlog_enforcer.main._install_target" +CANDIDATES = [(1, "Portal"), (2, "Portal 2"), (3, "Hades")] + + +def _state() -> State: + return State( + current_app_id=1, + current_game_name="Portal", + manual_picks=[{"app_id": 2, "game_name": "Portal 2"}], + ) + + +@pytest.fixture(name="env") +def _env() -> Iterator[dict[str, MagicMock]]: + """Exceptions = {3: Hades}; nothing installed; no game running.""" + with ( + patch(f"{TGT}.get_approved_exception_ids", return_value=frozenset({3})), + patch( + f"{TGT}.load_owned_records", + return_value=[{"app_id": 3, "name": "Hades"}], + ), + patch(f"{PKG}.is_game_fully_installed", return_value=False), + patch(f"{PKG}.install_game", return_value=True) as install, + patch(f"{PKG}.fast_install_failure", return_value=None), + patch(f"{PKG}.game_is_running", return_value=False) as running, + patch(f"{TGT}.subprocess.run") as run, + patch(f"{TGT}.installer_path", return_value=MagicMock()), + patch(f"{TGT}.build_cmd", return_value=["installer"]) as build, + patch(f"{PKG}._echo"), + patch(f"{TGT}._echo"), + ): + run.return_value = MagicMock(returncode=0, stdout="would install\n") + yield {"install": install, "run": run, "build": build, "running": running} + + +class TestCandidates: + """Allowed today = allowed_games plus approved exceptions.""" + + def test_exception_is_a_candidate_with_its_owned_name(self) -> None: + """An approved exception is offered under its owned-records name.""" + with ( + patch(f"{TGT}.get_approved_exception_ids", return_value=frozenset({3})), + patch( + f"{TGT}.load_owned_records", + return_value=[{"app_id": 3, "name": "Hades"}, {"app_id": 9}], + ), + ): + assert install_candidates(Config(steam_id="i"), _state()) == CANDIDATES + + def test_exception_without_records_gets_an_empty_name(self) -> None: + """No owned records: the exception still counts, nameless.""" + with ( + patch(f"{TGT}.get_approved_exception_ids", return_value=frozenset({1, 5})), + patch(f"{TGT}.load_owned_records", return_value=None), + ): + got = install_candidates(Config(steam_id="i"), _state()) + assert got == [(1, "Portal"), (2, "Portal 2"), (5, "")] + + +class TestResolveTarget: + """AppID, URL and name all resolve inside the allowed set only.""" + + def test_appid(self) -> None: + """A bare allowed AppID resolves to itself.""" + assert resolve_target("2", CANDIDATES) == (2, "Portal 2") + + def test_url(self) -> None: + """A store URL resolves through its ``app/``.""" + url = "https://store.steampowered.com/app/3/Hades/" + assert resolve_target(url, CANDIDATES) == (3, "Hades") + + @pytest.mark.parametrize( + "text", ["999", "https://steamcommunity.com/app/999/guides/", "Doom"] + ) + def test_not_allowed_is_refused(self, text: str) -> None: + """Any game outside the allowed set is refused as ``locked``.""" + with pytest.raises(JobError) as exc: + resolve_target(text, CANDIDATES) + assert exc.value.code == "locked" + + def test_exact_name_wins(self) -> None: + """A fully typed title does not install the sequel.""" + assert resolve_target("portal", CANDIDATES) == (1, "Portal") + + def test_unique_partial_name(self) -> None: + """A unique partial name resolves without asking.""" + assert resolve_target("had", CANDIDATES) == (3, "Hades") + + def test_ambiguous_name_asks(self) -> None: + """Several matches are offered as a choice, never guessed.""" + prompter = FakePrompter(choices=["2"]) + with use_prompter(prompter): + assert resolve_target("Port", CANDIDATES) == (2, "Portal 2") + assert prompter.asked[0][1] == ["1", "2"] + + +class TestInstallJob: + """cmd_install with the web job's params.""" + + def test_picker_offers_not_installed_exception( + self, env: dict[str, MagicMock] + ) -> None: + """Todo 6ee260a4: the no-target picker includes approved exceptions.""" + prompter = FakePrompter(choices=["3"]) + with use_prompter(prompter): + cmd_install(Config(steam_id="i"), _state()) + assert prompter.asked[0][1] == ["1", "2", "3"] + assert env["install"].call_args.args[:2] == (3, "Hades") + + def test_disallowed_target_starts_nothing(self, env: dict[str, MagicMock]) -> None: + """A refused target never reaches the installer.""" + with pytest.raises(JobError): + cmd_install(Config(steam_id="i"), _state(), target="999") + env["install"].assert_not_called() + env["run"].assert_not_called() + + def test_allowed_target_installs(self, env: dict[str, MagicMock]) -> None: + """An allowed target installs, Valve Proton passed through.""" + result = cmd_install( + Config(steam_id="i"), _state(), target="Hades", valve_proton=True + ) + assert env["install"].call_args.args[:2] == (3, "Hades") + assert env["install"].call_args.kwargs["valve_proton"] is True + assert result == {"app_id": 3, "dry_run": False, "fast_install_skipped": None} + + def test_game_running_is_reported(self, env: dict[str, MagicMock]) -> None: + """The fast-install guard's refusal is in the result data for the UI.""" + env["running"].return_value = True + result = cmd_install(Config(steam_id="i"), _state(), target="3") + assert result is not None + assert result["fast_install_skipped"] == "game_running" + + def test_dry_run_changes_nothing(self, env: dict[str, MagicMock]) -> None: + """Dry run: only the installer's --dry-run, even with a game running.""" + env["running"].return_value = True + result = cmd_install( + Config(steam_id="i"), _state(), target="3", dry_run=True, valve_proton=True + ) + env["install"].assert_not_called() + assert env["build"].call_args.kwargs == {"valve_proton": True, "dry_run": True} + assert env["build"].call_args.args[1] == 3 + assert result == {"app_id": 3, "dry_run": True, "fast_install_skipped": None} + + def test_failed_dry_run_fails_the_job(self, env: dict[str, MagicMock]) -> None: + """A dry run the installer rejects is a failed job, not a success.""" + env["run"].return_value = MagicMock(returncode=1, stdout="ERROR x\n") + with pytest.raises(JobError) as exc: + cmd_install(Config(steam_id="i"), _state(), target="3", dry_run=True) + assert exc.value.code == "op_failed" + + def test_dry_run_without_installer(self, env: dict[str, MagicMock]) -> None: + """No installer in the checkout: the dry run fails loudly.""" + with ( + patch(f"{TGT}.installer_path", return_value=None), + pytest.raises(JobError), + ): + cmd_install(Config(steam_id="i"), _state(), target="3", dry_run=True) + env["run"].assert_not_called() + + +class TestInstallParamsAndHandler: + """The web form's params reach cmd_install unchanged.""" + + def test_install_params_are_optional(self) -> None: + """target / dry_run / valve_proton are all optional.""" + assert validate_params("install", {}) == {"dry_run": 0, "valve_proton": 0} + got = validate_params("install", {"target": " Hades ", "dry_run": 1}) + assert got == {"target": "Hades", "dry_run": 1, "valve_proton": 0} + + def test_handler_maps_params(self) -> None: + """The job handler turns the flat params into cmd_install kwargs.""" + with ( + patch.object(_registry, "cmd_install", return_value={"app_id": 3}) as cmd, + patch.object(_registry.State, "load", return_value=_state()), + patch.object(_registry.Config, "load", return_value=Config()), + ): + out = _registry.HANDLERS["install"]( + {"target": "3", "dry_run": 1, "valve_proton": 0}, + MagicMock(), + MagicMock(), + ) + assert out == {"app_id": 3} + assert cmd.call_args.kwargs == { + "target": "3", + "dry_run": True, + "valve_proton": False, + } + + def test_handler_without_target(self) -> None: + """No target: the picker path, and None data becomes the assignment.""" + with ( + patch.object(_registry, "cmd_install", return_value=None) as cmd, + patch.object(_registry.State, "load", return_value=_state()), + patch.object(_registry.Config, "load", return_value=Config()), + ): + out = _registry.HANDLERS["install"]({}, MagicMock(), MagicMock()) + assert cmd.call_args.kwargs["target"] is None + assert out == {"current_app_id": 1, "current_game_name": "Portal"}