feat(enforcer): allow two concurrent manual picks

The enforcer allowed exactly one game: `current_app_id` was the single
"allowed" id threaded through the uninstall guard, the process killer, the
library hider and the auto-installer. Picking a second game manually meant
the first was uninstalled and hidden.

Manual picks are now a set, capped by `Config.max_manual_picks` (default 2).
Every active pick stays installed, visible and un-killed; the lock releases
only when all of them are finished or past their own 14-day deadline.

- `State.manual_picks` holds `{app_id, game_name, started_at}` entries. The
  legacy single-slot `manual_pick_*` fields are still read on load, migrated
  into the list and cleared, so a live lock survives the upgrade.
- `_actions.allowed_app_ids` / `allowed_games` are the single source of truth
  for "may exist". `uninstall_other_games`, `hide_other_games` (incl. its
  injected JS), `enforce_allowed_game` and `_guard_installed_games` now take
  that set instead of one app id; every call site passes it.
- `pick-manual` joins `_MANUAL_LOCK_EXEMPT_COMMANDS` so a second game can be
  added while the first holds the lock — the cap is what limits it, not the
  lock check. Its post-pick cascade operates on the whole allowed set, so
  adding a pick never tears down an earlier one.
- `abandon-pick <app_id>` drops only that pick; a survivor inherits the
  assignment and keeps the lock. Grace and deadline are per pick.
- `cmd_done` is unchanged: it finishes `current_app_id` and auto-picks a
  replacement, so two games stay queued. A finished pick leaves the active
  set automatically via `finished_app_ids`.

Deployment note, learned the hard way during development: the daemon holds
the allowed set in code, so it MUST be restarted after upgrading. A
pre-upgrade daemon knows only `current_app_id` and uninstalled the other pick
as "unauthorized" within seconds of the second pick being made.

Verified live: legacy KCD2 lock migrated on load; a second pick (Vampire
Survivors) was accepted while the first was locked, with both kept by the
uninstall pass; a third was refused at the cap; abandoning one pick left the
other locked and handed it the assignment; the restarted daemon reports
"KEEPING allowed game" for both. 1060 tests pass at 100% coverage.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Krzysztof Rudnicki 2026-07-19 17:28:23 +02:00
parent eb1472a433
commit 05e070ca27
19 changed files with 1003 additions and 325 deletions

View File

@ -33,11 +33,71 @@ MANUAL_GRACE_DAYS = 4
ABANDON_COOLDOWN_DAYS = 30
def is_manual_pick_locked(state: State) -> bool:
"""Return ``True`` if the manual-pick lock is currently in force.
def _pick_is_active(state: State, pick: dict[str, Any]) -> bool:
"""Return ``True`` if *pick* still holds the lock.
The lock releases once the picked game reaches ``finished_app_ids`` or once
``MANUAL_LOCK_DAYS`` have elapsed since the pick timestamp.
A pick stops being active once its game is finished (100% achievements) or
once ``MANUAL_LOCK_DAYS`` have elapsed. A missing or malformed timestamp
keeps it active: with no deadline to evaluate, the safe answer for an
enforcement tool is "still locked".
Args:
state: The loaded enforcer state (for ``finished_app_ids``).
pick: One ``state.manual_picks`` entry.
Returns:
Whether this pick still counts toward the lock.
"""
app_id = pick.get("app_id")
if app_id is None or app_id in state.finished_app_ids:
return False
started_at = pick.get("started_at") or ""
if started_at:
try:
started = datetime.fromisoformat(started_at)
except ValueError:
return True
if datetime.now(timezone.utc) >= started + timedelta(days=MANUAL_LOCK_DAYS):
return False
return True
def active_manual_picks(state: State) -> list[dict[str, Any]]:
"""Return the manual picks that still hold the lock, oldest first.
Args:
state: The loaded enforcer state.
Returns:
The subset of ``state.manual_picks`` that is neither finished nor past
its own deadline.
"""
return [p for p in state.manual_picks if _pick_is_active(state, p)]
def find_manual_pick(state: State, app_id: int) -> dict[str, Any] | None:
"""Return the active manual pick for *app_id*, or ``None``.
Args:
state: The loaded enforcer state.
app_id: The Steam app id to look for.
Returns:
The matching active pick entry, or ``None`` if *app_id* is not one.
"""
return next(
(p for p in active_manual_picks(state) if p.get("app_id") == app_id),
None,
)
def is_manual_pick_locked(state: State) -> bool:
"""Return ``True`` if any manual pick is currently holding the lock.
With several picks allowed at once the lock releases only when every one
of them is finished or expired.
Args:
state: The loaded enforcer state.
@ -45,28 +105,70 @@ def is_manual_pick_locked(state: State) -> bool:
Returns:
Whether the manual-pick lock is active right now.
"""
if state.manual_pick_app_id is None:
return False
# Lock released once the game appears in finished_app_ids.
if state.manual_pick_app_id in state.finished_app_ids:
return False
# Lock released after MANUAL_LOCK_DAYS days from the pick timestamp.
if state.manual_pick_started_at:
try:
started = datetime.fromisoformat(state.manual_pick_started_at)
deadline = started + timedelta(days=MANUAL_LOCK_DAYS)
if datetime.now(timezone.utc) >= deadline:
return False
except ValueError:
pass
return True
return bool(active_manual_picks(state))
def apply_manual_pick(state: State, app_id: int, game_name: str) -> None:
"""Assign *app_id* as the manually-picked game and persist ``state``.
def allowed_app_ids(state: State) -> set[int]:
"""Return every app id the enforcer must leave installed and visible.
This is the single source of truth for "may exist" across the uninstall
guard, the process killer, the library hider and the auto-installer. It is
the union of the active manual picks and the current assignment, so two
manually-picked games survive an enforcement pass while everything else is
still removed.
Args:
state: The loaded enforcer state.
Returns:
The set of allowed app ids (empty when nothing is assigned).
"""
return {app_id for app_id, _ in allowed_games(state)}
def allowed_games(state: State) -> list[tuple[int, str]]:
"""Return ``(app_id, name)`` for every game the enforcer must keep.
Same membership as :func:`allowed_app_ids`, but carrying names so callers
can install and report on each one. The current assignment comes first.
Args:
state: The loaded enforcer state.
Returns:
Allowed games as ``(app_id, name)`` pairs, without duplicates.
"""
games: list[tuple[int, str]] = []
if state.current_app_id is not None:
games.append((state.current_app_id, state.current_game_name))
for pick in active_manual_picks(state):
app_id = pick.get("app_id")
if app_id is not None and all(app_id != aid for aid, _ in games):
games.append((app_id, pick.get("game_name", "")))
return games
def manual_pick_slots_left(state: State, max_picks: int) -> int:
"""Return how many further manual picks fit under *max_picks*.
Args:
state: The loaded enforcer state.
max_picks: Configured cap (``Config.max_manual_picks``).
Returns:
Remaining slots, never negative.
"""
return max(0, max_picks - len(active_manual_picks(state)))
def apply_manual_pick(
state: State,
app_id: int,
game_name: str,
*,
max_picks: int = 1,
) -> str | None:
"""Add *app_id* to the manual picks and persist ``state``.
This is the non-interactive, side-effect-scoped core of the CLI's
``pick-manual`` command. It mutates and saves ``State`` only; it deliberately
@ -75,88 +177,119 @@ def apply_manual_pick(state: State, app_id: int, game_name: str) -> None:
its interactive ``YES`` confirmation. Keeping this state-only means an
automated caller (the MCP server) can never wipe installed games.
Finished and expired entries are dropped on the way through so the stored
list does not grow without bound.
Args:
state: The enforcer state to mutate and save.
app_id: The Steam app id to lock in.
game_name: Human-readable name for the picked game.
max_picks: How many picks may be active at once.
Returns:
``None`` on success, or a message explaining why the pick was refused
(already picked, or no slots left), in which case nothing was saved.
"""
active = active_manual_picks(state)
if any(p.get("app_id") == app_id for p in active):
return f"{game_name} (AppID={app_id}) is already one of your manual picks."
if len(active) >= max_picks:
names = ", ".join(f"{p['game_name']} (AppID={p['app_id']})" for p in active)
return (
f"You already have {len(active)} manual pick(s) locked in "
f"(cap is {max_picks}): {names}."
)
now = datetime.now(timezone.utc).isoformat()
state.manual_pick_app_id = app_id
state.manual_pick_game_name = game_name
state.manual_pick_started_at = now
# Rewriting from `active` also prunes finished/expired entries.
state.manual_picks = [
*active,
{"app_id": app_id, "game_name": game_name, "started_at": now},
]
state.current_app_id = app_id
state.current_game_name = game_name
if not state.enforcement_started_at:
state.enforcement_started_at = now
state.save()
return None
def manual_pick_grace_remaining(state: State) -> float | None:
"""Return days left in the manual-pick grace window, or ``None``.
def manual_pick_grace_remaining(state: State, app_id: int) -> float | None:
"""Return days left in *app_id*'s grace window, or ``None``.
``None`` means "no grace window applies": there is no manual pick, or its
timestamp is missing/malformed. A value <= 0 means the window has closed.
``None`` means "no grace window applies": *app_id* is not an active manual
pick, or its timestamp is missing/malformed. A value <= 0 means the window
has closed.
Args:
state: The loaded enforcer state.
app_id: The manually-picked app id to measure.
Returns:
Fractional days remaining before the pick can no longer be abandoned,
or ``None`` when the question does not apply.
"""
if state.manual_pick_app_id is None or not state.manual_pick_started_at:
pick = find_manual_pick(state, app_id)
if pick is None or not pick.get("started_at"):
return None
try:
started = datetime.fromisoformat(state.manual_pick_started_at)
started = datetime.fromisoformat(pick["started_at"])
except ValueError:
return None
deadline = started + timedelta(days=MANUAL_GRACE_DAYS)
return (deadline - datetime.now(timezone.utc)).total_seconds() / 86400
def can_abandon_manual_pick(state: State) -> bool:
"""Return ``True`` if the current manual pick is still inside its grace window.
def can_abandon_manual_pick(state: State, app_id: int) -> bool:
"""Return ``True`` if *app_id* is still inside its grace window.
Args:
state: The loaded enforcer state.
app_id: The manually-picked app id to check.
Returns:
Whether ``abandon_manual_pick`` would be accepted right now.
"""
remaining = manual_pick_grace_remaining(state)
remaining = manual_pick_grace_remaining(state, app_id)
return remaining is not None and remaining > 0
def abandon_manual_pick(state: State) -> bool:
"""Drop the manual pick and persist ``state``, if still inside the grace window.
def abandon_manual_pick(state: State, app_id: int) -> bool:
"""Drop one manual pick and persist ``state``, if still inside its grace window.
Clears both the manual-pick lock and the game assignment, and puts the
abandoned app id on the existing skip cooldown so ``scan`` will not hand
the same game straight back. State-only: like ``apply_manual_pick`` this
deliberately performs no uninstall/hide cascade, so the MCP server can call
it without touching the filesystem.
Only the named pick is dropped: any other active pick keeps its own lock
and deadline. The abandoned app id goes onto the existing skip cooldown so
``scan`` will not hand the same game straight back. State-only: like
``apply_manual_pick`` this performs no uninstall/hide cascade, so the MCP
server can call it without touching the filesystem.
Args:
state: The enforcer state to mutate and save.
app_id: The manually-picked app id to back out of.
Returns:
``True`` if the pick was abandoned, ``False`` if the grace window has
closed (or there was no pick), in which case ``state`` is untouched.
``True`` if the pick was abandoned, ``False`` if its grace window has
closed (or it is not an active pick), in which case ``state`` is
untouched.
"""
if not can_abandon_manual_pick(state):
if not can_abandon_manual_pick(state, app_id):
return False
app_id = state.manual_pick_app_id
if app_id is not None:
state.skip_for_days(app_id, ABANDON_COOLDOWN_DAYS)
state.skip_for_days(app_id, ABANDON_COOLDOWN_DAYS)
state.manual_picks = [
p for p in active_manual_picks(state) if p.get("app_id") != app_id
]
state.manual_pick_app_id = None
state.manual_pick_game_name = ""
state.manual_pick_started_at = ""
# The pick was also the assignment; clearing it lets 'scan' reassign.
# The abandoned pick may also have been the current assignment; hand the
# assignment to a surviving pick so the enforcer keeps guarding it, or
# clear it so 'scan' can reassign.
if state.current_app_id == app_id:
state.current_app_id = None
state.current_game_name = ""
survivor = state.manual_picks[-1] if state.manual_picks else None
state.current_app_id = survivor["app_id"] if survivor else None
state.current_game_name = survivor["game_name"] if survivor else ""
state.save()
return True
@ -195,5 +328,11 @@ def status_payload(state: State) -> dict[str, Any]:
"until": total_block.until.isoformat() if total_block.until else None,
},
"manual_pick_locked": is_manual_pick_locked(state),
"manual_pick_grace_days_left": manual_pick_grace_remaining(state),
"manual_picks": [
{
**pick,
"grace_days_left": manual_pick_grace_remaining(state, pick["app_id"]),
}
for pick in active_manual_picks(state)
],
}

View File

@ -5,6 +5,7 @@ from __future__ import annotations
import logging
import sys
from steam_backlog_enforcer._actions import allowed_app_ids
from steam_backlog_enforcer._enforce_loop import get_all_owned_app_ids
from steam_backlog_enforcer.config import Config, State, load_snapshot
from steam_backlog_enforcer.enforcer import (
@ -212,7 +213,7 @@ def _finalize_completion(
owned_ids = get_all_owned_app_ids(config)
if owned_ids:
hidden, skipped = try_hide_other_games(owned_ids, state.current_app_id)
hidden, skipped = try_hide_other_games(owned_ids, allowed_app_ids(state))
if skipped is not None:
_echo(f"\n Library hiding: skipped ({skipped})")
elif hidden > 0:
@ -253,14 +254,14 @@ def _enforce_on_done(config: Config, state: State) -> None:
if config.kill_unauthorized_games:
violations = enforce_allowed_game(
state.current_app_id,
allowed_app_ids(state),
kill_unauthorized=True,
)
for pid, app_id in violations:
_echo(f" Killed unauthorized game: AppID={app_id} (PID={pid})")
if config.uninstall_other_games:
count = uninstall_other_games(state.current_app_id)
count = uninstall_other_games(allowed_app_ids(state))
if count:
_echo(f" Uninstalled {count} unauthorized game(s)")
@ -278,7 +279,7 @@ def _enforce_on_done(config: Config, state: State) -> None:
# assigned game hidden and stale games visible.
owned_ids = get_all_owned_app_ids(config)
if owned_ids:
hidden, skipped = try_hide_other_games(owned_ids, state.current_app_id)
hidden, skipped = try_hide_other_games(owned_ids, allowed_app_ids(state))
if skipped is not None:
_echo(f" Library hiding: skipped ({skipped})")
elif hidden > 0:

View File

@ -7,6 +7,7 @@ import logging
import time
from typing import Any
from steam_backlog_enforcer._actions import allowed_app_ids, allowed_games
from steam_backlog_enforcer._total_block import (
end_total_block_cleanup,
enforce_total_block_tick,
@ -144,17 +145,34 @@ def get_all_owned_app_ids(config: Config) -> list[int]:
ENFORCE_INTERVAL = 3
def _guard_installed_games(allowed_app_id: int | None) -> int:
def _allowed_names(state: State) -> str:
"""Return a human-readable list of the games the user may play.
Args:
state: Current enforcer state.
Returns:
Comma-separated game names, or "your assigned game" when none is set.
"""
names = [name for _, name in allowed_games(state) if name]
return ", ".join(names) if names else "your assigned game"
def _guard_installed_games(allowed_app_ids: set[int]) -> int:
"""Remove any unauthorized game manifests + files. Runs every loop.
Args:
allowed_app_ids: Every app id that may stay installed — the assignment
plus any concurrent manual picks.
Returns number of games removed this pass.
"""
if allowed_app_id is None:
if not allowed_app_ids:
return 0
installed = get_installed_games()
count = 0
for app_id, name in installed:
if app_id == allowed_app_id:
if app_id in allowed_app_ids:
continue
if is_protected_app(app_id):
continue
@ -167,11 +185,25 @@ def _guard_installed_games(allowed_app_id: int | None) -> int:
send_notification(
"Game Removed!",
f"Uninstalled {name} (AppID={app_id}). "
f"Only the assigned game is allowed.",
f"Only your assigned game(s) are allowed.",
)
return count
def _reinstall_missing_allowed(config: Config, state: State) -> None:
"""Re-install any allowed game that vanished between loop iterations.
Args:
config: Enforcer configuration.
state: Current enforcer state.
"""
for app_id, name in allowed_games(state):
if is_game_installed(app_id):
continue
logger.info("Allowed game disappeared — re-installing %s", name)
install_game(app_id, name, config.steam_id)
def _enforce_setup(config: Config, state: State) -> None:
"""Perform initial setup for enforcement mode.
@ -189,7 +221,7 @@ def _enforce_setup(config: Config, state: State) -> None:
# Initial cleanup.
if config.uninstall_other_games:
_echo(" Uninstalling non-assigned games...")
count = uninstall_other_games(state.current_app_id)
count = uninstall_other_games(allowed_app_ids(state))
_echo(f" Uninstalled {count} games")
# Auto-install the assigned game.
@ -200,31 +232,26 @@ def _enforce_setup(config: Config, state: State) -> None:
def _enforce_auto_install(config: Config, state: State) -> None:
"""Auto-install the assigned game if not already installed.
"""Auto-install every allowed game that is not installed yet.
Args:
config: Enforcer configuration.
state: Current enforcer state.
"""
app_id = state.current_app_id
if app_id is None:
return
if not is_game_installed(app_id):
_echo(f" Auto-installing {state.current_game_name}...")
for app_id, name in allowed_games(state):
if is_game_installed(app_id):
_echo(f" Allowed game already installed: {name}")
continue
_echo(f" Auto-installing {name}...")
if install_game(
app_id,
state.current_game_name,
name,
config.steam_id,
use_steam_protocol=True,
):
send_notification(
"Game Installing",
f"{state.current_game_name} is being downloaded.",
)
send_notification("Game Installing", f"{name} is being downloaded.")
else:
_echo(" Could not auto-install. Install manually from Steam.")
else:
_echo(f" Assigned game already installed: {state.current_game_name}")
def _enforce_hide_games(config: Config, state: State) -> None:
@ -245,7 +272,7 @@ def _enforce_hide_games(config: Config, state: State) -> None:
# which spun the service through ~1000 restarts against a Steam that had
# been uninstalled - each attempt leaving a dead process named "steam"
# behind that /proc scanners misread as a live Steam.
hidden, skipped = try_hide_other_games(owned_ids, state.current_app_id)
hidden, skipped = try_hide_other_games(owned_ids, allowed_app_ids(state))
if skipped is not None:
_echo(f" Library hiding: skipped ({skipped})")
return
@ -281,41 +308,29 @@ def _enforce_loop_iteration(config: Config, state: State) -> None:
if not steam_is_installed():
return
if state.current_app_id is None:
allowed = allowed_app_ids(state)
if not allowed:
return
# A) Kill unauthorized game processes.
if config.kill_unauthorized_games:
violations = enforce_allowed_game(
state.current_app_id,
kill_unauthorized=True,
)
violations = enforce_allowed_game(allowed, kill_unauthorized=True)
for pid, app_id in violations:
_echo(f" Killed unauthorized game: AppID={app_id} (PID={pid})")
send_notification(
"Game Blocked!",
f"Killed unauthorized game (AppID={app_id}). "
f"Focus on {state.current_game_name}!",
f"Focus on {_allowed_names(state)}!",
)
# B) Remove any newly-installed unauthorized games.
if config.uninstall_other_games:
removed = _guard_installed_games(state.current_app_id)
removed = _guard_installed_games(allowed)
if removed > 0:
_echo(f" Guard removed {removed} unauthorized game(s)")
# C) Re-install assigned game if it was somehow removed.
app_id = state.current_app_id
if app_id is not None and not is_game_installed(app_id):
logger.info(
"Assigned game disappeared — re-installing %s",
state.current_game_name,
)
install_game(
app_id,
state.current_game_name,
config.steam_id,
)
# C) Re-install any allowed game that was somehow removed.
_reinstall_missing_allowed(config, state)
# D) Re-apply immutable flag so config cannot be edited without root.
lock_enforcement_files(CONFIG_FILE)

View File

@ -36,14 +36,16 @@ from steam_backlog_enforcer._actions import (
MANUAL_GRACE_DAYS,
MANUAL_LOCK_DAYS,
abandon_manual_pick,
active_manual_picks,
apply_manual_pick,
can_abandon_manual_pick,
find_manual_pick,
manual_pick_grace_remaining,
status_payload,
)
from steam_backlog_enforcer._total_block import start_total_block
from steam_backlog_enforcer._web_dataset import build_web_dataset, dataset_to_payload
from steam_backlog_enforcer.config import State, load_snapshot
from steam_backlog_enforcer.config import Config, State, load_snapshot
from steam_backlog_enforcer.steam_api import GameInfo
# Log to STDERR only — STDOUT carries the MCP JSON-RPC protocol frames, so a
@ -203,7 +205,15 @@ def pick_manual(app_id: int, *, confirm: bool = False) -> dict[str, Any]:
),
"confirm_required": True,
}
apply_manual_pick(State.load(), app_id, game_name)
state = State.load()
refused = apply_manual_pick(
state,
app_id,
game_name,
max_picks=Config.load().max_manual_picks,
)
if refused is not None:
return {"ok": False, "reason": refused}
logger.info("pick_manual applied: %s (AppID=%s)", game_name, app_id)
return {
"ok": True,
@ -228,19 +238,22 @@ def abandon_pick(app_id: int, *, confirm: bool = False) -> dict[str, Any]:
confirm: Set ``True`` to actually abandon the pick; otherwise preview.
"""
state = State.load()
if state.manual_pick_app_id is None:
picks = active_manual_picks(state)
if not picks:
return {"ok": False, "reason": "No manual pick is active."}
if app_id != state.manual_pick_app_id:
pick = find_manual_pick(state, app_id)
if pick is None:
listed = ", ".join(f"AppID={p['app_id']}" for p in picks)
return {
"ok": False,
"reason": (
f"AppID={app_id} is not the active manual pick "
f"(AppID={state.manual_pick_app_id})."
f"AppID={app_id} is not one of the active manual picks ({listed})."
),
}
remaining = manual_pick_grace_remaining(state)
if not can_abandon_manual_pick(state):
remaining = manual_pick_grace_remaining(state, app_id)
if not can_abandon_manual_pick(state, app_id):
return {
"ok": False,
"reason": (
@ -249,7 +262,7 @@ def abandon_pick(app_id: int, *, confirm: bool = False) -> dict[str, Any]:
),
}
game_name = state.manual_pick_game_name
game_name = str(pick["game_name"])
if not confirm:
return {
"ok": True,
@ -266,7 +279,7 @@ def abandon_pick(app_id: int, *, confirm: bool = False) -> dict[str, Any]:
"confirm_required": True,
}
abandon_manual_pick(state)
abandon_manual_pick(state, app_id)
logger.info("abandon_pick applied: %s (AppID=%s)", game_name, app_id)
return {
"ok": True,

View File

@ -18,6 +18,7 @@ from dataclasses import asdict, dataclass, field
from datetime import datetime, timezone
from typing import Any
from steam_backlog_enforcer._actions import allowed_app_ids
from steam_backlog_enforcer._hltb_types import _read_raw_cache
from steam_backlog_enforcer._scanning_confidence import (
_MIN_COMP_100_POLLS,
@ -407,8 +408,7 @@ def build_web_dataset(state: State) -> WebDataset:
)
exclude = set(state.finished_app_ids)
if state.current_app_id is not None:
exclude.add(state.current_app_id)
exclude.update(allowed_app_ids(state))
rows = _build_games(raw_games, exclude)

View File

@ -60,6 +60,12 @@ class Config:
kill_unauthorized_games: bool = True
uninstall_other_games: bool = True
desktop_notifications: bool = True
max_manual_picks: int = 2
"""How many games may be manually locked in at once.
All active picks stay installed and visible; the enforcer treats them as
one allowed set. Raising this weakens enforcement proportionally.
"""
def save(self) -> None:
"""Persist config to disk."""
@ -98,7 +104,18 @@ class State:
manual_pick_app_id: int | None = None
manual_pick_game_name: str = ""
manual_pick_started_at: str = ""
"""ISO-8601 UTC timestamp when the user manually locked in a game."""
"""Legacy single-slot manual pick, migrated into ``manual_picks`` on load.
Kept as fields so an older ``state.json`` still deserialises; they are
blanked once migrated and are never written again.
"""
manual_picks: list[dict[str, Any]] = field(default_factory=list)
"""Active manual picks, newest last.
Each entry is ``{"app_id": int, "game_name": str, "started_at": iso}``.
Plain dicts rather than a dataclass because ``save`` serialises
``self.__dict__`` straight to JSON.
"""
def skip_for_days(self, app_id: int, days: int) -> None:
"""Mark ``app_id`` as skipped for ``days`` days from now (UTC)."""
@ -144,11 +161,33 @@ class State:
except (json.JSONDecodeError, OSError, ValueError):
logger.warning("Corrupt state file, using defaults.")
return cls()
return cls(
state = cls(
**{k: v for k, v in data.items() if k in cls.__dataclass_fields__}
)
state._migrate_legacy_manual_pick()
return state
return cls()
def _migrate_legacy_manual_pick(self) -> None:
"""Fold a pre-multi-pick single manual pick into ``manual_picks``.
A live lock written by the old single-slot code must survive the
upgrade, so the legacy fields are read once, converted, and cleared.
Migration happens in memory; the next ``save`` persists it.
"""
if self.manual_pick_app_id is None or self.manual_picks:
return
self.manual_picks = [
{
"app_id": self.manual_pick_app_id,
"game_name": self.manual_pick_game_name,
"started_at": self.manual_pick_started_at,
}
]
self.manual_pick_app_id = None
self.manual_pick_game_name = ""
self.manual_pick_started_at = ""
def save_snapshot(data: list[dict[str, Any]]) -> None:
"""Save an achievement snapshot to disk."""

View File

@ -38,3 +38,31 @@ full 2 weeks. There is now a short mistake-correction window:
The lock-active message advertises `abandon-pick` only while the window is
still open, and the `pick-manual` warning mentions it up front.
## Two concurrent manual picks (added 2026-07-19)
`Config.max_manual_picks` (default 2) is how many games may be locked in at
once. Both stay installed, visible and un-killed; the lock releases only when
every pick is finished or past its own 14-day deadline.
- `State.manual_picks` is the list of `{app_id, game_name, started_at}`
entries. The old single-slot `manual_pick_*` fields are still read on load,
migrated into the list, then cleared — a live lock survives the upgrade.
- `_actions.allowed_app_ids(state)` (assignment ∪ active picks) is the single
source of truth for "may exist". `uninstall_other_games`,
`hide_other_games`, `enforce_allowed_game` and `_guard_installed_games` all
take that set instead of one app id.
- `pick-manual` is in `_MANUAL_LOCK_EXEMPT_COMMANDS` so a second game can be
added while the first holds the lock; the cap is what limits it. Its
post-pick cascade operates on the whole allowed set, so adding a pick never
tears down an earlier one.
- `abandon-pick <app_id>` drops only that pick; a survivor inherits the
assignment and keeps the lock.
- `cmd_done` still finishes `current_app_id` and auto-picks a replacement, so
two games stay queued. A finished pick leaves the active set automatically
via `finished_app_ids` — no pruning needed.
**Deployment note:** the enforce daemon holds the allowed set in code, so
`sudo systemctl restart steam-backlog-enforcer` is required after upgrading.
A pre-upgrade daemon only knows `current_app_id` and will uninstall the other
pick as "unauthorized" within seconds — this happened once during development.

View File

@ -102,21 +102,27 @@ def _kill_pid_by_name(pid: int, name: str) -> bool:
def enforce_allowed_game(
allowed_app_id: int | None,
allowed_app_ids: set[int],
*,
kill_unauthorized: bool = True,
) -> list[tuple[int, int]]:
"""Check running games; optionally kill unauthorized ones.
Args:
allowed_app_ids: Every app id the user may play right now — the
assignment plus any concurrent manual picks. Empty disables the
check entirely (nothing is assigned, so nothing is unauthorized).
kill_unauthorized: Whether to kill violating processes.
Returns list of (pid, app_id) that were killed or detected.
"""
if allowed_app_id is None:
if not allowed_app_ids:
return []
running = get_running_steam_game_pids()
violations: list[tuple[int, int]] = []
for pid, app_id in running.items():
if allowed_app_id is not None and app_id == allowed_app_id:
if app_id in allowed_app_ids:
continue
# Skip Steam client itself (app_id 0 or very low IDs).
if app_id == 0:

View File

@ -411,8 +411,12 @@ def uninstall_game(app_id: int, game_name: str = "") -> bool:
return success
def uninstall_other_games(allowed_app_id: int | None) -> int:
"""Uninstall all installed games except the assigned one and protected IDs.
def uninstall_other_games(allowed_app_ids: set[int]) -> int:
"""Uninstall all installed games except the allowed ones and protected IDs.
Args:
allowed_app_ids: Every app id that must survive — the assignment plus
any concurrent manual picks. Empty means "keep nothing".
Returns: number of games uninstalled.
"""
@ -420,8 +424,8 @@ def uninstall_other_games(allowed_app_id: int | None) -> int:
count = 0
for app_id, name in installed:
if app_id == allowed_app_id:
logger.info("KEEPING assigned game: %s (AppID=%d)", name, app_id)
if app_id in allowed_app_ids:
logger.info("KEEPING allowed game: %s (AppID=%d)", name, app_id)
continue
if is_protected_app(app_id):
logger.debug("Skipping protected: %s (AppID=%d)", name, app_id)

View File

@ -311,9 +311,9 @@ _SETTLE_DELAY_MS = 200
def hide_other_games(
owned_app_ids: list[int],
allowed_app_id: int | None,
allowed_app_ids: set[int],
) -> int:
"""Hide every game except *allowed_app_id* in the Steam library.
"""Hide every game except *allowed_app_ids* in the Steam library.
Uses the Chrome DevTools Protocol to call
``collectionStore.SetAppsAsHidden()`` in Steam's JS context.
@ -331,12 +331,12 @@ def hide_other_games(
"""
ensure_steam_debug_port()
allowed_js = str(allowed_app_id) if allowed_app_id is not None else "null"
extra_ids = sorted(aid for aid in owned_app_ids if aid != allowed_app_id)
allowed_json = json.dumps(sorted(allowed_app_ids))
extra_ids = sorted(aid for aid in owned_app_ids if aid not in allowed_app_ids)
extra_json = json.dumps(extra_ids)
js = f"""
(async () => {{
const allowed = {allowed_js};
const allowed = new Set({allowed_json});
const coll = collectionStore.allGamesCollection;
const extraIds = {extra_json};
let totalHidden = 0;
@ -358,7 +358,7 @@ def hide_other_games(
for (let pass = 0; pass < maxPasses; pass++) {{
let visible = coll && coll.visibleApps
? coll.visibleApps.map(a => a.appid).filter(id => id !== allowed)
? coll.visibleApps.map(a => a.appid).filter(id => !allowed.has(id))
: [];
if (pass === 0) {{
@ -378,8 +378,8 @@ def hide_other_games(
await new Promise(r => setTimeout(r, {_SETTLE_DELAY_MS}));
}}
if (allowed !== null) {{
await collectionStore.SetAppsAsHidden([allowed], false);
if (allowed.size > 0) {{
await collectionStore.SetAppsAsHidden([...allowed], false);
}}
return JSON.stringify({{ totalHidden }});
@ -396,7 +396,7 @@ def hide_other_games(
def try_hide_other_games(
owned_app_ids: list[int],
allowed_app_id: int | None,
allowed_app_ids: set[int],
) -> tuple[int, str | None]:
"""Hide other games, degrading gracefully when Steam cannot be driven.
@ -410,7 +410,7 @@ def try_hide_other_games(
Args:
owned_app_ids: All owned app ids, used to seed the first hide pass.
allowed_app_id: The one game that must stay visible, if any.
allowed_app_ids: Every game that must stay visible.
Returns:
``(hidden_count, skip_reason)``. ``skip_reason`` is ``None`` when the
@ -418,7 +418,7 @@ def try_hide_other_games(
is 0.
"""
try:
return hide_other_games(owned_app_ids, allowed_app_id), None
return hide_other_games(owned_app_ids, allowed_app_ids), None
except SteamUnavailableError as exc:
return 0, str(exc)

View File

@ -18,9 +18,14 @@ from steam_backlog_enforcer._actions import (
)
from steam_backlog_enforcer._actions import (
abandon_manual_pick,
active_manual_picks,
allowed_app_ids,
allowed_games,
apply_manual_pick,
can_abandon_manual_pick,
find_manual_pick,
manual_pick_grace_remaining,
manual_pick_slots_left,
)
from steam_backlog_enforcer._actions import (
is_manual_pick_locked as _is_manual_pick_locked,
@ -92,7 +97,18 @@ _MIN_CLI_ARGS = 2
# Principle: only what is needed to release the lock (done/check) or
# that cannot change the game assignment (status, enforce, setup, serve).
_MANUAL_LOCK_EXEMPT_COMMANDS = frozenset(
{"done", "check", "status", "enforce", "setup", "serve", "abandon-pick"}
{
"done",
"check",
"status",
"enforce",
"setup",
"serve",
"abandon-pick",
# Allowed so a second game can be locked in alongside the first; the
# cap inside cmd_pick_manual is what stops this being a way out.
"pick-manual",
}
)
# Commands that remain usable while a total gaming block is active. Far
@ -141,49 +157,65 @@ def _enforce_total_block_lock(command: str) -> None:
# ──────────────────────────────────────────────────────────────
def _show_manual_pick_lock_message(state: State) -> None:
"""Print the aggressive lock-active message to stdout."""
_echo("\n" + "=" * 60)
_echo(" *** MANUAL PICK LOCK ACTIVE ***")
_echo("=" * 60)
_echo(
f"\nYou manually picked: {state.manual_pick_game_name}"
f" (AppID={state.manual_pick_app_id})"
)
def _describe_pick(state: State, pick: dict[str, object]) -> bool:
"""Print one manual pick's deadline and grace status; return if abandonable.
if state.manual_pick_started_at:
Args:
state: Current enforcer state.
pick: One active entry from ``state.manual_picks``.
Returns:
Whether this pick is still inside its grace window.
"""
app_id = pick["app_id"]
_echo(f"\n {pick['game_name']} (AppID={app_id})")
started_at = str(pick.get("started_at") or "")
if started_at:
try:
started = datetime.fromisoformat(state.manual_pick_started_at)
started = datetime.fromisoformat(started_at)
deadline = started + timedelta(days=_MANUAL_LOCK_DAYS)
days_left = (deadline - datetime.now(timezone.utc)).days
_echo(f"Locked since: {started.strftime('%Y-%m-%d')}")
_echo(f" Locked since: {started.strftime('%Y-%m-%d')}")
_echo(
f"Deadline: {deadline.strftime('%Y-%m-%d')}"
f" Deadline: {deadline.strftime('%Y-%m-%d')}"
f" ({max(0, days_left)} day(s) remaining)"
)
except ValueError:
pass
grace_left = manual_pick_grace_remaining(state, int(str(app_id)))
if grace_left is not None and grace_left > 0:
_echo(
f" Undo: abandon-pick {app_id}"
f" ({grace_left:.1f} of {_MANUAL_GRACE_DAYS} grace day(s) left)"
)
return True
return False
def _show_manual_pick_lock_message(state: State) -> None:
"""Print the aggressive lock-active message to stdout."""
picks = active_manual_picks(state)
_echo("\n" + "=" * 60)
_echo(" *** MANUAL PICK LOCK ACTIVE ***")
_echo("=" * 60)
_echo(f"\nYou manually picked {len(picks)} game(s):")
any_in_grace = False
for pick in picks:
any_in_grace |= _describe_pick(state, pick)
_echo(
"\nYou CANNOT use any other feature until you finish this game"
"\n(100% achievements) or the 2-week deadline passes."
"\n\nTo release the lock: finish the game, then run 'done' or 'check'."
"\nYou CANNOT use any other feature until you finish these games"
"\n(100% achievements) or their 2-week deadlines pass."
"\n\nTo release the lock: finish them, then run 'done' or 'check'."
)
# Mistake-correction window: only advertised while it is still open, and
# once closed 'abandon-pick' is dropped from the allowed list rather than
# offered as a command that would only refuse.
grace_left = manual_pick_grace_remaining(state)
in_grace = grace_left is not None and grace_left > 0
if in_grace:
_echo(
f"\nPicked this by mistake? You have {grace_left:.1f} day(s) of the"
f"\n{_MANUAL_GRACE_DAYS}-day grace period left:"
f"\n abandon-pick {state.manual_pick_app_id}"
)
# 'abandon-pick' is dropped from the allowed list once no pick is still
# inside its window, rather than offered as a command that would refuse.
usable = set(_MANUAL_LOCK_EXEMPT_COMMANDS)
if not in_grace:
if not any_in_grace:
usable.discard("abandon-pick")
_echo(f"\nAllowed commands: {', '.join(sorted(usable))}")
_echo("=" * 60 + "\n")
@ -234,7 +266,17 @@ def cmd_status(_config: Config, state: State) -> None:
is_assigned_installed = any(aid == state.current_app_id for aid, _ in installed)
_echo(f"Assigned game installed: {is_assigned_installed}")
if _is_manual_pick_locked(state):
picks = active_manual_picks(state)
if picks:
_echo(f"\nManual picks ({len(picks)}):")
for pick in picks:
grace = manual_pick_grace_remaining(state, pick["app_id"])
undo = (
f" — undoable for {grace:.1f} more day(s)"
if grace is not None and grace > 0
else ""
)
_echo(f" {pick['game_name']} (AppID={pick['app_id']}){undo}")
_echo("\n[MANUAL PICK LOCK is active — most commands are blocked]")
@ -326,6 +368,7 @@ def cmd_reset(config: Config, state: State) -> None:
state.manual_pick_app_id = None
state.manual_pick_game_name = ""
state.manual_pick_started_at = ""
state.manual_picks = []
state.save()
_echo("State reset. Store unblocked.")
@ -346,19 +389,21 @@ def cmd_uninstall(_config: Config, state: State) -> None:
_echo("No game assigned. Run 'scan' first.")
return
allowed = allowed_app_ids(state)
installed = get_installed_games()
to_remove = [
(aid, n)
for aid, n in installed
if aid != state.current_app_id and not is_protected_app(aid)
if aid not in allowed and not is_protected_app(aid)
]
if not to_remove:
_echo("No games to uninstall (only assigned game and runtimes installed).")
_echo("No games to uninstall (only allowed games and runtimes installed).")
return
_echo(f"\nWill uninstall {len(to_remove)} games, keeping:")
_echo(f" - {state.current_game_name} (AppID={state.current_app_id})")
for aid, name in allowed_games(state):
_echo(f" - {name} (AppID={aid})")
_echo(" - Steam runtimes and Proton versions\n")
_echo("Games to remove:")
for aid, name in to_remove:
@ -370,7 +415,7 @@ def cmd_uninstall(_config: Config, state: State) -> None:
_echo("Aborted.")
return
count = uninstall_other_games(state.current_app_id)
count = uninstall_other_games(allowed_app_ids(state))
_echo(f"\nUninstalled {count} games.")
@ -468,7 +513,7 @@ def cmd_hide(config: Config, state: State) -> None:
return
_echo(f"Hiding all games except {state.current_game_name}...")
hidden, skipped = try_hide_other_games(owned_ids, state.current_app_id)
hidden, skipped = try_hide_other_games(owned_ids, allowed_app_ids(state))
if skipped is not None:
_echo(f"Library hiding: skipped ({skipped})")
return
@ -511,7 +556,7 @@ def cmd_pick(config: Config, state: State) -> None:
if state.current_app_id is not None:
owned_ids = get_all_owned_app_ids(config)
if owned_ids:
hidden, skipped = try_hide_other_games(owned_ids, state.current_app_id)
hidden, skipped = try_hide_other_games(owned_ids, allowed_app_ids(state))
if skipped is not None:
_echo(f"\n Library hiding: skipped ({skipped})")
elif hidden > 0:
@ -548,6 +593,69 @@ def _resolve_game_name(config: Config, app_id: int) -> str | None:
return None
def _report_pick_slots(config: Config, state: State) -> list[dict[str, object]]:
"""Show which manual picks are already locked in; exit if the cap is full.
Args:
config: Enforcer configuration (for ``max_manual_picks``).
state: Current enforcer state.
Returns:
The currently-active manual picks.
"""
existing = active_manual_picks(state)
if existing:
_echo(f"\nAlready locked in ({len(existing)}/{config.max_manual_picks}):")
for pick in existing:
_echo(f" - {pick['game_name']} (AppID={pick['app_id']})")
if manual_pick_slots_left(state, config.max_manual_picks) == 0:
_echo(
f"\nError: you already have {config.max_manual_picks} manual pick(s)."
f"\nFinish one, or undo one with 'abandon-pick <app_id>' while it is"
f"\nstill inside its {_MANUAL_GRACE_DAYS}-day grace window."
)
sys.exit(1)
return existing
def _apply_allowed_set(config: Config, state: State) -> None:
"""Make the filesystem and library match the allowed set.
Uninstalls everything outside it, installs every allowed game that is
missing, and hides the rest of the library. Operating on the whole set
(rather than one app id) is what lets a second manual pick coexist with
the first instead of tearing it down.
Args:
config: Enforcer configuration.
state: Current enforcer state.
"""
allowed = allowed_app_ids(state)
if config.uninstall_other_games:
_echo(" Uninstalling non-allowed games...")
count = uninstall_other_games(allowed)
if count:
_echo(f" Uninstalled {count} non-allowed game(s)")
for app_id, name in allowed_games(state):
if is_game_installed(app_id):
_echo(f" {name} is already installed.")
continue
_echo(f" Installing {name}...")
install_game(app_id, name, config.steam_id, use_steam_protocol=True)
owned_ids = get_all_owned_app_ids(config)
if owned_ids:
hidden, skipped = try_hide_other_games(owned_ids, allowed)
if skipped is not None:
_echo(f" Library hiding: skipped ({skipped})")
elif hidden > 0:
_echo(f" Library: hid {hidden} games")
def cmd_pick_manual(config: Config, state: State, args: list[str]) -> None:
"""Manually pick a game by Steam app_id, locking the enforcer for 2 weeks.
@ -574,11 +682,15 @@ def cmd_pick_manual(config: Config, state: State, args: list[str]) -> None:
return
_echo(f"\nGame found: {game_name} (AppID={app_id})")
existing = _report_pick_slots(config, state)
_echo(
f"\nWARNING: Picking this game will:"
f"\n - Override your current assignment"
f"\n - Add it to your allowed games ({len(existing) + 1} of"
f" {config.max_manual_picks} slot(s) used)"
f"\n - Lock ALL other commands for {_MANUAL_LOCK_DAYS} DAYS or until"
f"\n you reach 100% achievements"
f"\n you reach 100% achievements on every pick"
f"\n - Leave only these commands usable:"
f"\n {', '.join(sorted(_MANUAL_LOCK_EXEMPT_COMMANDS))}"
f"\n - Stay undoable via 'abandon-pick {app_id}' for the first"
@ -594,32 +706,23 @@ def cmd_pick_manual(config: Config, state: State, args: list[str]) -> None:
# State mutation is the shared, stdout-free core (also used by the MCP
# server); the destructive post-assignment cascade below stays CLI-only.
apply_manual_pick(state, app_id, game_name)
refused = apply_manual_pick(
state,
app_id,
game_name,
max_picks=config.max_manual_picks,
)
if refused is not None:
_echo(f"\nError: {refused}")
sys.exit(1)
_echo(f"\nManual pick confirmed: {game_name} (AppID={app_id})")
_echo(f"Lock active from now until 100% achievements or {_MANUAL_LOCK_DAYS} days.")
_echo("Run 'done' or 'check' once you have 100% to release the lock.\n")
# Post-assignment: mirror what _assign_chosen_game + cmd_pick do.
if config.uninstall_other_games:
_echo(" Uninstalling non-assigned games...")
count = uninstall_other_games(app_id)
if count:
_echo(f" Uninstalled {count} non-assigned game(s)")
if not is_game_installed(app_id):
_echo(f" Installing {game_name}...")
install_game(app_id, game_name, config.steam_id, use_steam_protocol=True)
else:
_echo(f" {game_name} is already installed.")
owned_ids = get_all_owned_app_ids(config)
if owned_ids:
hidden, skipped = try_hide_other_games(owned_ids, app_id)
if skipped is not None:
_echo(f" Library hiding: skipped ({skipped})")
elif hidden > 0:
_echo(f" Library: hid {hidden} games")
# Post-assignment: mirror what _assign_chosen_game + cmd_pick do, but for
# the whole allowed set so an earlier pick is not torn down by a later one.
_apply_allowed_set(config, state)
_ABANDON_PICK_USAGE = (
@ -653,15 +756,15 @@ def _abandon_pick_target(state: State, args: list[str]) -> int | None:
_echo(f"Error: app_id must be a number, got '{args[0]}'.")
return None
if state.manual_pick_app_id is None:
picks = active_manual_picks(state)
if not picks:
_echo("No manual pick is active — nothing to abandon.")
return None
if app_id != state.manual_pick_app_id:
if find_manual_pick(state, app_id) is None:
listed = ", ".join(f"{p['game_name']} (AppID={p['app_id']})" for p in picks)
_echo(
f"Error: AppID={app_id} is not your manual pick.\n"
f"Current pick: {state.manual_pick_game_name}"
f" (AppID={state.manual_pick_app_id})."
f"Error: AppID={app_id} is not one of your manual picks.\nActive: {listed}."
)
return None
@ -680,12 +783,13 @@ def cmd_abandon_pick(_config: Config, state: State, args: list[str]) -> None:
if app_id is None:
sys.exit(1)
game_name = state.manual_pick_game_name
pick = find_manual_pick(state, app_id)
game_name = str(pick["game_name"]) if pick else ""
if not can_abandon_manual_pick(state):
if not can_abandon_manual_pick(state, app_id):
# ``remaining`` is negative once the window has closed, so its
# magnitude is how long ago that happened.
remaining = manual_pick_grace_remaining(state)
remaining = manual_pick_grace_remaining(state, app_id)
elapsed = (
f"{abs(remaining):.1f} day(s) ago"
if remaining is not None
@ -698,22 +802,27 @@ def cmd_abandon_pick(_config: Config, state: State, args: list[str]) -> None:
)
sys.exit(1)
others = [p for p in active_manual_picks(state) if p["app_id"] != app_id]
_echo(f"\nAbandoning manual pick: {game_name} (AppID={app_id})")
_echo(
f"\nThis will:"
f"\n - Release the manual pick lock"
f"\n - Drop this pick from your allowed games"
f"\n - Uninstall {game_name}"
f"\n - Keep it out of auto-assignment for"
f" {_ABANDON_COOLDOWN_DAYS} days"
f"\n - Leave you with no assigned game (run 'scan' to get one)"
)
if others:
kept = ", ".join(f"{p['game_name']} (AppID={p['app_id']})" for p in others)
_echo(f"\n Your other pick(s) stay locked in: {kept}")
else:
_echo("\n - Leaves you with no assigned game (run 'scan' to get one)")
_echo()
confirm = input(f"Type YES to abandon {game_name}: ").strip()
if confirm != "YES":
_echo("Aborted.")
return
if not abandon_manual_pick(state):
if not abandon_manual_pick(state, app_id):
# Should be unreachable: the grace check above already passed.
_echo("Error: the grace period closed before the pick could be abandoned.")
sys.exit(1)
@ -727,8 +836,11 @@ def cmd_abandon_pick(_config: Config, state: State, args: list[str]) -> None:
else:
_echo(" Warning: could not uninstall — remove it from Steam manually.")
_echo("\nNo game is assigned now. Run 'scan' to get a new assignment,")
_echo("or 'pick-manual <app_id>' to choose one yourself.\n")
if state.current_app_id is None:
_echo("\nNo game is assigned now. Run 'scan' to get a new assignment,")
_echo("or 'pick-manual <app_id>' to choose one yourself.\n")
else:
_echo(f"\nStill assigned: {state.current_game_name}\n")
_BLOCK_GAMING_USAGE = (

View File

@ -10,10 +10,15 @@ import pytest
from steam_backlog_enforcer import _actions
from steam_backlog_enforcer._actions import (
abandon_manual_pick,
active_manual_picks,
allowed_app_ids,
allowed_games,
apply_manual_pick,
can_abandon_manual_pick,
find_manual_pick,
is_manual_pick_locked,
manual_pick_grace_remaining,
manual_pick_slots_left,
status_payload,
)
from steam_backlog_enforcer._total_block import TotalBlockStatus
@ -29,39 +34,87 @@ class TestIsManualPickLocked:
assert is_manual_pick_locked(State()) is False
def test_finished_game_releases_lock(self) -> None:
state = State(manual_pick_app_id=5, finished_app_ids=[5])
state = State(
manual_picks=[{"app_id": 5, "game_name": "G", "started_at": ""}],
finished_app_ids=[5],
)
assert is_manual_pick_locked(state) is False
def test_empty_timestamp_stays_locked(self) -> None:
# manual pick set but no started_at → locked (no expiry to evaluate).
state = State(manual_pick_app_id=5, manual_pick_started_at="")
# Pick set but no started_at → locked (no expiry to evaluate).
state = State(manual_picks=[{"app_id": 5, "game_name": "G", "started_at": ""}])
assert is_manual_pick_locked(state) is True
def test_recent_pick_is_locked(self) -> None:
state = State(manual_pick_app_id=5, manual_pick_started_at=_iso_days_ago(1))
state = State(
manual_picks=[
{"app_id": 5, "game_name": "G", "started_at": _iso_days_ago(1)}
]
)
assert is_manual_pick_locked(state) is True
def test_expired_pick_releases_lock(self) -> None:
state = State(
manual_pick_app_id=5,
manual_pick_started_at=_iso_days_ago(_actions.MANUAL_LOCK_DAYS + 1),
manual_picks=[
{
"app_id": 5,
"game_name": "G",
"started_at": _iso_days_ago(_actions.MANUAL_LOCK_DAYS + 1),
}
]
)
assert is_manual_pick_locked(state) is False
def test_malformed_timestamp_stays_locked(self) -> None:
state = State(manual_pick_app_id=5, manual_pick_started_at="not-a-date")
def test_one_active_pick_holds_the_lock_for_all(self) -> None:
# Multi-pick: the lock only lifts when every pick is done/expired.
state = State(
manual_picks=[
{"app_id": 5, "game_name": "Done", "started_at": _iso_days_ago(1)},
{"app_id": 6, "game_name": "Live", "started_at": _iso_days_ago(1)},
],
finished_app_ids=[5],
)
assert is_manual_pick_locked(state) is True
class TestLegacyManualPickMigration:
"""A lock written by the old single-slot code must survive the upgrade."""
def test_legacy_pick_is_migrated_on_load(self) -> None:
started = _iso_days_ago(1)
State(
manual_pick_app_id=5,
manual_pick_game_name="Legacy",
manual_pick_started_at=started,
).save()
loaded = State.load()
assert loaded.manual_picks == [
{"app_id": 5, "game_name": "Legacy", "started_at": started}
]
assert loaded.manual_pick_app_id is None
assert loaded.manual_pick_game_name == ""
assert loaded.manual_pick_started_at == ""
assert is_manual_pick_locked(loaded) is True
def test_new_format_is_left_alone(self) -> None:
State(manual_picks=[{"app_id": 9, "game_name": "New", "started_at": ""}]).save()
assert [p["app_id"] for p in State.load().manual_picks] == [9]
def test_no_pick_needs_no_migration(self) -> None:
State().save()
assert State.load().manual_picks == []
class TestApplyManualPick:
def test_sets_all_fields_and_enforcement_start(self) -> None:
state = State()
apply_manual_pick(state, 440, "Team Fortress 2")
assert state.manual_pick_app_id == 440
assert state.manual_pick_game_name == "Team Fortress 2"
assert apply_manual_pick(state, 440, "Team Fortress 2") is None
assert [p["app_id"] for p in state.manual_picks] == [440]
assert state.manual_picks[0]["game_name"] == "Team Fortress 2"
assert state.current_app_id == 440
assert state.current_game_name == "Team Fortress 2"
assert state.manual_pick_started_at != ""
assert state.manual_picks[0]["started_at"] != ""
# enforcement_started_at was empty, so it is set now.
assert state.enforcement_started_at != ""
@ -75,77 +128,87 @@ class TestApplyManualPick:
apply_manual_pick(state, 70, "Half-Life")
assert State.load().current_app_id == 70
def test_default_cap_is_one(self) -> None:
# Callers that do not opt in keep the historical single-slot behaviour.
state = State()
apply_manual_pick(state, 440, "TF2")
assert apply_manual_pick(state, 620, "Portal 2") is not None
def _pick(app_id: int = 440, name: str = "TF2", days_ago: float = 1.0) -> dict:
return {
"app_id": app_id,
"game_name": name,
"started_at": _iso_days_ago(days_ago),
}
class TestManualPickGraceRemaining:
def test_no_pick_returns_none(self) -> None:
assert manual_pick_grace_remaining(State()) is None
assert manual_pick_grace_remaining(State(), 440) is None
def test_unknown_app_id_returns_none(self) -> None:
state = State(manual_picks=[_pick(440)])
assert manual_pick_grace_remaining(state, 999) is None
def test_missing_timestamp_returns_none(self) -> None:
state = State(manual_pick_app_id=5, manual_pick_started_at="")
assert manual_pick_grace_remaining(state) is None
state = State(manual_picks=[{"app_id": 440, "game_name": "TF2"}])
assert manual_pick_grace_remaining(state, 440) is None
def test_malformed_timestamp_returns_none(self) -> None:
state = State(manual_pick_app_id=5, manual_pick_started_at="not-a-date")
assert manual_pick_grace_remaining(state) is None
state = State(
manual_picks=[
{"app_id": 440, "game_name": "TF2", "started_at": "not-a-date"}
]
)
assert manual_pick_grace_remaining(state, 440) is None
def test_fresh_pick_has_almost_the_full_window(self) -> None:
state = State(manual_pick_app_id=5, manual_pick_started_at=_iso_days_ago(0))
remaining = manual_pick_grace_remaining(state)
state = State(manual_picks=[_pick(days_ago=0)])
remaining = manual_pick_grace_remaining(state, 440)
assert remaining is not None
assert remaining == pytest.approx(_actions.MANUAL_GRACE_DAYS, abs=0.01)
def test_expired_window_is_negative(self) -> None:
state = State(
manual_pick_app_id=5,
manual_pick_started_at=_iso_days_ago(_actions.MANUAL_GRACE_DAYS + 1),
)
remaining = manual_pick_grace_remaining(state)
state = State(manual_picks=[_pick(days_ago=_actions.MANUAL_GRACE_DAYS + 1)])
remaining = manual_pick_grace_remaining(state, 440)
assert remaining is not None
assert remaining == pytest.approx(-1.0, abs=0.01)
class TestCanAbandonManualPick:
def test_inside_window(self) -> None:
state = State(
manual_pick_app_id=5,
manual_pick_started_at=_iso_days_ago(_actions.MANUAL_GRACE_DAYS - 1),
)
assert can_abandon_manual_pick(state) is True
state = State(manual_picks=[_pick(days_ago=_actions.MANUAL_GRACE_DAYS - 1)])
assert can_abandon_manual_pick(state, 440) is True
def test_outside_window(self) -> None:
state = State(
manual_pick_app_id=5,
manual_pick_started_at=_iso_days_ago(_actions.MANUAL_GRACE_DAYS + 1),
)
assert can_abandon_manual_pick(state) is False
state = State(manual_picks=[_pick(days_ago=_actions.MANUAL_GRACE_DAYS + 1)])
assert can_abandon_manual_pick(state, 440) is False
def test_no_pick(self) -> None:
assert can_abandon_manual_pick(State()) is False
assert can_abandon_manual_pick(State(), 440) is False
class TestAbandonManualPick:
def _fresh_pick(self) -> State:
def _state(self, *, picks: list[dict] | None = None) -> State:
picks = picks if picks is not None else [_pick()]
return State(
manual_pick_app_id=440,
manual_pick_game_name="Team Fortress 2",
manual_pick_started_at=_iso_days_ago(1),
current_app_id=440,
current_game_name="Team Fortress 2",
manual_picks=picks,
current_app_id=picks[-1]["app_id"],
current_game_name=picks[-1]["game_name"],
)
def test_clears_lock_and_assignment(self) -> None:
state = self._fresh_pick()
assert abandon_manual_pick(state) is True
assert state.manual_pick_app_id is None
assert state.manual_pick_game_name == ""
assert state.manual_pick_started_at == ""
state = self._state()
assert abandon_manual_pick(state, 440) is True
assert state.manual_picks == []
assert state.current_app_id is None
assert state.current_game_name == ""
assert is_manual_pick_locked(state) is False
def test_records_cooldown(self) -> None:
state = self._fresh_pick()
abandon_manual_pick(state)
state = self._state()
abandon_manual_pick(state, 440)
expiry = datetime.fromisoformat(state.skipped_until["440"])
expected = datetime.now(timezone.utc) + timedelta(
days=_actions.ABANDON_COOLDOWN_DAYS
@ -153,38 +216,128 @@ class TestAbandonManualPick:
assert abs((expiry - expected).total_seconds()) < 60
def test_persists_to_disk(self) -> None:
state = self._fresh_pick()
abandon_manual_pick(state)
assert State.load().manual_pick_app_id is None
abandon_manual_pick(self._state(), 440)
assert State.load().manual_picks == []
def test_refuses_after_grace_and_leaves_state_untouched(self) -> None:
state = self._fresh_pick()
state.manual_pick_started_at = _iso_days_ago(_actions.MANUAL_GRACE_DAYS + 1)
assert abandon_manual_pick(state) is False
assert state.manual_pick_app_id == 440
state = self._state(
picks=[_pick(days_ago=_actions.MANUAL_GRACE_DAYS + 1)],
)
assert abandon_manual_pick(state, 440) is False
assert [p["app_id"] for p in state.manual_picks] == [440]
assert state.current_app_id == 440
assert state.skipped_until == {}
def test_no_cooldown_when_pick_id_is_missing(self) -> None:
# Defensive branch: the grace check normally guarantees an app id, so
# force the inconsistent state to prove no cooldown key is invented.
state = State(current_app_id=None)
with patch.object(_actions, "can_abandon_manual_pick", return_value=True):
assert abandon_manual_pick(state) is True
assert state.skipped_until == {}
assert state.manual_pick_app_id is None
def test_other_pick_survives_and_takes_the_assignment(self) -> None:
# The whole point of multi-pick: abandoning one keeps the other locked.
state = self._state(picks=[_pick(440, "TF2"), _pick(620, "Portal 2")])
assert abandon_manual_pick(state, 620) is True
assert [p["app_id"] for p in state.manual_picks] == [440]
assert state.current_app_id == 440
assert state.current_game_name == "TF2"
assert is_manual_pick_locked(state) is True
def test_keeps_unrelated_assignment(self) -> None:
# A pick whose lock outlived a later reassignment must not clear the
# newer assignment when abandoned.
state = self._fresh_pick()
# A pick that is not the current assignment must not clear it.
state = self._state(picks=[_pick(440, "TF2")])
state.current_app_id = 70
state.current_game_name = "Half-Life"
abandon_manual_pick(state)
abandon_manual_pick(state, 440)
assert state.current_app_id == 70
assert state.current_game_name == "Half-Life"
class TestActiveManualPicksAndAllowedSet:
def test_finished_pick_drops_out(self) -> None:
state = State(manual_picks=[_pick(440)], finished_app_ids=[440])
assert active_manual_picks(state) == []
assert is_manual_pick_locked(state) is False
def test_expired_pick_drops_out(self) -> None:
state = State(
manual_picks=[_pick(days_ago=_actions.MANUAL_LOCK_DAYS + 1)],
)
assert active_manual_picks(state) == []
def test_missing_timestamp_stays_active(self) -> None:
# No deadline to evaluate → stay locked (safe answer for an enforcer).
state = State(manual_picks=[{"app_id": 440, "game_name": "TF2"}])
assert len(active_manual_picks(state)) == 1
def test_malformed_timestamp_stays_active(self) -> None:
state = State(
manual_picks=[
{"app_id": 440, "game_name": "TF2", "started_at": "not-a-date"}
]
)
assert len(active_manual_picks(state)) == 1
def test_entry_without_app_id_is_ignored(self) -> None:
state = State(manual_picks=[{"game_name": "Corrupt"}])
assert active_manual_picks(state) == []
def test_allowed_set_unions_picks_and_assignment(self) -> None:
state = State(
manual_picks=[_pick(440, "TF2"), _pick(620, "Portal 2")],
current_app_id=70,
current_game_name="Half-Life",
)
assert allowed_app_ids(state) == {70, 440, 620}
assert allowed_games(state)[0] == (70, "Half-Life")
def test_allowed_set_deduplicates_assignment(self) -> None:
state = State(
manual_picks=[_pick(440, "TF2")],
current_app_id=440,
current_game_name="TF2",
)
assert allowed_app_ids(state) == {440}
assert allowed_games(state) == [(440, "TF2")]
def test_empty_state_allows_nothing(self) -> None:
assert allowed_app_ids(State()) == set()
assert allowed_games(State()) == []
def test_find_manual_pick(self) -> None:
state = State(manual_picks=[_pick(440, "TF2")])
found = find_manual_pick(state, 440)
assert found is not None
assert found["game_name"] == "TF2"
assert find_manual_pick(state, 999) is None
class TestApplyManualPickCap:
def test_appends_second_pick(self) -> None:
state = State(manual_picks=[_pick(440, "TF2")])
assert apply_manual_pick(state, 620, "Portal 2", max_picks=2) is None
assert [p["app_id"] for p in state.manual_picks] == [440, 620]
# Newest pick becomes the assignment.
assert state.current_app_id == 620
def test_refuses_beyond_cap(self) -> None:
state = State(manual_picks=[_pick(440, "TF2"), _pick(620, "Portal 2")])
refused = apply_manual_pick(state, 70, "Half-Life", max_picks=2)
assert refused is not None
assert "cap is 2" in refused
assert len(state.manual_picks) == 2
def test_refuses_duplicate_pick(self) -> None:
state = State(manual_picks=[_pick(440, "TF2")])
refused = apply_manual_pick(state, 440, "TF2", max_picks=2)
assert refused is not None
assert "already one of your manual picks" in refused
def test_prunes_finished_entries(self) -> None:
state = State(manual_picks=[_pick(440, "TF2")], finished_app_ids=[440])
assert apply_manual_pick(state, 620, "Portal 2", max_picks=2) is None
assert [p["app_id"] for p in state.manual_picks] == [620]
def test_slots_left(self) -> None:
state = State(manual_picks=[_pick(440, "TF2")])
assert manual_pick_slots_left(state, 2) == 1
assert manual_pick_slots_left(state, 1) == 0
class TestStatusPayload:
def _patch_leaves(
self,

View File

@ -223,14 +223,14 @@ class TestGuardInstalledGames:
patch(f"{PKG}.uninstall_game", return_value=True),
patch(f"{PKG}.send_notification"),
):
assert _guard_installed_games(440) == 1
assert _guard_installed_games({440}) == 1
def test_skips_allowed(self) -> None:
with patch(
f"{PKG}.get_installed_games",
return_value=[(440, "TF2")],
):
assert _guard_installed_games(440) == 0
assert _guard_installed_games({440}) == 0
def test_skips_protected(self) -> None:
with (
@ -240,7 +240,7 @@ class TestGuardInstalledGames:
),
patch(f"{PKG}.is_protected_app", side_effect=lambda aid: aid == 228980),
):
assert _guard_installed_games(440) == 0
assert _guard_installed_games({440}) == 0
def test_uninstall_fails(self) -> None:
with (
@ -250,10 +250,10 @@ class TestGuardInstalledGames:
),
patch(f"{PKG}.uninstall_game", return_value=False),
):
assert _guard_installed_games(440) == 0
assert _guard_installed_games({440}) == 0
def test_allowed_none_skips(self) -> None:
assert _guard_installed_games(None) == 0
assert _guard_installed_games(set()) == 0
class TestEnforceSetup:

View File

@ -96,7 +96,7 @@ class TestEnforceAllowedGame:
"steam_backlog_enforcer.enforcer.get_running_steam_game_pids",
return_value={100: 440},
):
result = enforce_allowed_game(440)
result = enforce_allowed_game({440})
assert result == []
def test_kills_unauthorized(self) -> None:
@ -107,7 +107,7 @@ class TestEnforceAllowedGame:
),
patch("steam_backlog_enforcer.enforcer.kill_process") as mock_kill,
):
result = enforce_allowed_game(440, kill_unauthorized=True)
result = enforce_allowed_game({440}, kill_unauthorized=True)
assert result == [(100, 570)]
mock_kill.assert_called_once_with(100, 570)
@ -116,7 +116,7 @@ class TestEnforceAllowedGame:
"steam_backlog_enforcer.enforcer.get_running_steam_game_pids",
return_value={100: 0},
):
result = enforce_allowed_game(440)
result = enforce_allowed_game({440})
assert result == []
def test_detects_without_killing(self) -> None:
@ -124,11 +124,11 @@ class TestEnforceAllowedGame:
"steam_backlog_enforcer.enforcer.get_running_steam_game_pids",
return_value={100: 570},
):
result = enforce_allowed_game(440, kill_unauthorized=False)
result = enforce_allowed_game({440}, kill_unauthorized=False)
assert result == [(100, 570)]
def test_allowed_none(self) -> None:
result = enforce_allowed_game(None, kill_unauthorized=True)
result = enforce_allowed_game(set(), kill_unauthorized=True)
assert result == []
def test_skips_protected_app_id(self) -> None:
@ -144,7 +144,7 @@ class TestEnforceAllowedGame:
),
patch("steam_backlog_enforcer.enforcer.kill_process") as mock_kill,
):
result = enforce_allowed_game(440, kill_unauthorized=True)
result = enforce_allowed_game({440}, kill_unauthorized=True)
assert result == []
mock_kill.assert_not_called()

View File

@ -123,7 +123,7 @@ class TestUninstallOtherGames:
),
patch(f"{PKG}.uninstall_game", return_value=True) as mock_uninstall,
):
count = uninstall_other_games(440)
count = uninstall_other_games({440})
assert count == 1
mock_uninstall.assert_called_once_with(730, "CS")
@ -135,7 +135,7 @@ class TestUninstallOtherGames:
),
patch(f"{PKG}.uninstall_game") as mock_uninstall,
):
count = uninstall_other_games(None)
count = uninstall_other_games(set())
assert count == 0
mock_uninstall.assert_not_called()
@ -147,7 +147,7 @@ class TestUninstallOtherGames:
),
patch(f"{PKG}.uninstall_game", return_value=False),
):
count = uninstall_other_games(None)
count = uninstall_other_games(set())
assert count == 0
def test_all_allowed_or_protected(self) -> None:
@ -158,6 +158,6 @@ class TestUninstallOtherGames:
),
patch(f"{PKG}.uninstall_game") as mock_uninstall,
):
count = uninstall_other_games(440)
count = uninstall_other_games({440})
assert count == 0
mock_uninstall.assert_not_called()

View File

@ -254,7 +254,7 @@ class TestHideOtherGames:
return_value='{"totalHidden": 5}',
),
):
count = hide_other_games([1, 2, 3], 1)
count = hide_other_games([1, 2, 3], {1})
assert count == 5
def test_empty_list(self) -> None:
@ -271,7 +271,7 @@ class TestHideOtherGames:
return_value='{"totalHidden": 0}',
),
):
count = hide_other_games([1], 1)
count = hide_other_games([1], {1})
assert count == 0
def test_no_allowed(self) -> None:
@ -288,7 +288,7 @@ class TestHideOtherGames:
return_value='{"totalHidden": 2}',
),
):
count = hide_other_games([1, 2], None)
count = hide_other_games([1, 2], set())
assert count == 2
@ -302,14 +302,14 @@ class TestTryHideOtherGames:
def test_success_returns_count_and_no_reason(self) -> None:
with patch(f"{PKG}.hide_other_games", return_value=7):
assert try_hide_other_games([1, 2], 1) == (7, None)
assert try_hide_other_games([1, 2], {1}) == (7, None)
def test_steam_unavailable_is_reported_not_raised(self) -> None:
with patch(
f"{PKG}.hide_other_games",
side_effect=SteamUnavailableError("Steam is not installed"),
):
hidden, reason = try_hide_other_games([1, 2], 1)
hidden, reason = try_hide_other_games([1, 2], {1})
assert hidden == 0
assert reason == "Steam is not installed"
@ -318,7 +318,7 @@ class TestTryHideOtherGames:
f"{PKG}.hide_other_games",
side_effect=SteamUpdateInProgressError("update in progress"),
):
hidden, reason = try_hide_other_games([1, 2], 1)
hidden, reason = try_hide_other_games([1, 2], {1})
assert hidden == 0
assert reason == "update in progress"

View File

@ -244,7 +244,7 @@ class TestCmdPick:
patch(f"{PKG}._echo"),
):
cmd_pick(Config(steam_api_key="k", steam_id="i"), state)
mock_hide.assert_called_once_with([1, 2, 3], 2)
mock_hide.assert_called_once_with([1, 2, 3], {2})
def test_no_hide_message_when_none_hidden(self) -> None:
snap = [_snap(2, "NewGame", 10, 0, 5.0)]

View File

@ -39,9 +39,7 @@ def _locked_state(
started_at: str = _STARTED_AT,
) -> State:
return State(
manual_pick_app_id=app_id,
manual_pick_game_name=name,
manual_pick_started_at=started_at,
manual_picks=[{"app_id": app_id, "game_name": name, "started_at": started_at}],
)
@ -140,13 +138,10 @@ class TestEnforceManualPickLock:
):
_enforce_manual_pick_lock("add-exception", state)
def test_pick_manual_blocked_when_already_locked(self) -> None:
state = _locked_state()
with (
patch(f"{PKG}._show_manual_pick_lock_message"),
pytest.raises(SystemExit),
):
_enforce_manual_pick_lock("pick-manual", state)
def test_pick_manual_allowed_when_already_locked(self) -> None:
# A second pick must be reachable while the first holds the lock; the
# cap inside cmd_pick_manual is what limits it, not the lock check.
_enforce_manual_pick_lock("pick-manual", _locked_state())
# ──────────────────────────────────────────────────────────────
@ -281,12 +276,12 @@ class TestCmdPickManual:
):
cmd_pick_manual(config, state, ["489830"])
assert state.manual_pick_app_id == 489830
assert state.manual_pick_game_name == "Skyrim SE"
assert state.manual_pick_started_at != ""
assert [p["app_id"] for p in state.manual_picks] == [489830]
assert state.manual_picks[0]["game_name"] == "Skyrim SE"
assert state.manual_picks[0]["started_at"] != ""
assert state.current_app_id == 489830
mock_save.assert_called_once()
mock_uninstall.assert_called_once_with(489830)
mock_uninstall.assert_called_once_with({489830})
mock_install.assert_called_once()
mock_hide.assert_called_once()
@ -417,7 +412,7 @@ class TestCmdPickManual:
cmd_pick_manual(Config(), state, ["489830"])
output = " ".join(str(c) for c in mock_echo.call_args_list)
assert "skipped (update in progress)" in output
assert state.manual_pick_app_id == 489830
assert [p["app_id"] for p in state.manual_picks] == [489830]
# ──────────────────────────────────────────────────────────────
@ -437,18 +432,17 @@ class TestMainDispatchPickManual:
main()
mock_cmd.assert_called_once()
def test_pick_manual_blocked_when_locked(self) -> None:
state = _locked_state()
def test_pick_manual_dispatches_while_locked(self) -> None:
# Reaching cmd_pick_manual is required for a second concurrent pick.
argv = ["prog", "pick-manual", "730"]
with (
patch.object(sys, "argv", argv),
patch(f"{PKG}.Config.load", return_value=Config(steam_api_key="k")),
patch(f"{PKG}.State.load", return_value=state),
patch(f"{PKG}._show_manual_pick_lock_message"),
pytest.raises(SystemExit) as exc_info,
patch(f"{PKG}.State.load", return_value=_locked_state()),
patch(f"{PKG}.cmd_pick_manual") as mock_cmd,
):
main()
assert exc_info.value.code == 1
mock_cmd.assert_called_once()
# ──────────────────────────────────────────────────────────────
@ -517,7 +511,7 @@ class TestCmdAbandonPick:
def test_wrong_app_id_exits(self) -> None:
with patch(f"{PKG}._echo") as mock_echo, pytest.raises(SystemExit):
cmd_abandon_pick(Config(), _abandonable_state(app_id=100), ["999"])
assert "not your manual pick" in " ".join(
assert "not one of your manual picks" in " ".join(
str(c) for c in mock_echo.call_args_list
)
@ -532,7 +526,7 @@ class TestCmdAbandonPick:
assert exc.value.code == 1
assert "EXPIRED" in " ".join(str(c) for c in mock_echo.call_args_list)
mock_save.assert_not_called()
assert state.manual_pick_app_id == 100
assert [p["app_id"] for p in state.manual_picks] == [100]
def test_expired_grace_with_bad_timestamp_still_exits(self) -> None:
state = _abandonable_state(started_at="not-a-date")
@ -550,7 +544,7 @@ class TestCmdAbandonPick:
cmd_abandon_pick(Config(), state, ["100"])
mock_save.assert_not_called()
mock_uninstall.assert_not_called()
assert state.manual_pick_app_id == 100
assert [p["app_id"] for p in state.manual_picks] == [100]
def test_success_clears_lock_and_uninstalls(self) -> None:
state = _abandonable_state()
@ -562,7 +556,7 @@ class TestCmdAbandonPick:
patch(f"{PKG}.uninstall_game", return_value=True) as mock_uninstall,
):
cmd_abandon_pick(Config(), state, ["100"])
assert state.manual_pick_app_id is None
assert state.manual_picks == []
assert state.current_app_id is None
assert state.skipped_until["100"] != ""
mock_uninstall.assert_called_once_with(100, "TestGame")
@ -631,7 +625,7 @@ class TestAbandonPickLockInteraction:
_show_manual_pick_lock_message(state)
output = " ".join(str(c) for c in mock_echo.call_args_list)
assert "abandon-pick 100" in output
assert "grace period" in output
assert "grace day(s) left" in output
def test_lock_message_hides_abandon_after_grace(self) -> None:
state = _abandonable_state(started_at=_PAST_GRACE)
@ -639,3 +633,158 @@ class TestAbandonPickLockInteraction:
_show_manual_pick_lock_message(state)
output = " ".join(str(c) for c in mock_echo.call_args_list)
assert "abandon-pick" not in output
# ──────────────────────────────────────────────────────────────
# Two concurrent manual picks (cap, coexistence, per-pick abandon)
# ──────────────────────────────────────────────────────────────
def _two_pick_state() -> State:
state = State(
manual_picks=[
{"app_id": 100, "game_name": "TestGame", "started_at": _IN_GRACE},
{"app_id": 200, "game_name": "SecondGame", "started_at": _IN_GRACE},
],
)
state.current_app_id = 200
state.current_game_name = "SecondGame"
return state
class TestPickManualCap:
def test_second_pick_is_added_not_replacing(self) -> None:
state = _locked_state(app_id=100)
with (
patch(f"{PKG}._echo"),
patch(f"{PKG}._resolve_game_name", return_value="Skyrim SE"),
patch("builtins.input", return_value="YES"),
patch.object(State, "save"),
patch(f"{PKG}.uninstall_other_games", return_value=0),
patch(f"{PKG}.is_game_installed", return_value=True),
patch(f"{PKG}.get_all_owned_app_ids", return_value=[]),
):
cmd_pick_manual(Config(max_manual_picks=2), state, ["489830"])
assert [p["app_id"] for p in state.manual_picks] == [100, 489830]
def test_third_pick_refused_at_cap(self) -> None:
state = _two_pick_state()
with (
patch(f"{PKG}._echo") as mock_echo,
patch(f"{PKG}._resolve_game_name", return_value="Skyrim SE"),
pytest.raises(SystemExit) as exc,
):
cmd_pick_manual(Config(max_manual_picks=2), state, ["489830"])
assert exc.value.code == 1
output = " ".join(str(c) for c in mock_echo.call_args_list)
assert "already have 2 manual pick(s)" in output
assert "Already locked in (2/2)" in output
assert len(state.manual_picks) == 2
def test_duplicate_pick_refused_by_core(self) -> None:
# The cap has room, so this exercises the core's own refusal path.
state = _locked_state(app_id=489830)
with (
patch(f"{PKG}._echo") as mock_echo,
patch(f"{PKG}._resolve_game_name", return_value="Skyrim SE"),
patch("builtins.input", return_value="YES"),
patch.object(State, "save"),
patch(f"{PKG}.uninstall_other_games", return_value=0),
patch(f"{PKG}.is_game_installed", return_value=True),
patch(f"{PKG}.get_all_owned_app_ids", return_value=[]),
pytest.raises(SystemExit),
):
cmd_pick_manual(Config(max_manual_picks=2), state, ["489830"])
assert "already one of your manual picks" in " ".join(
str(c) for c in mock_echo.call_args_list
)
def test_cascade_keeps_every_allowed_game(self) -> None:
# The regression this whole feature turns on: adding a second pick must
# not uninstall or hide the first.
state = _locked_state(app_id=100)
with (
patch(f"{PKG}._echo"),
patch(f"{PKG}._resolve_game_name", return_value="Skyrim SE"),
patch("builtins.input", return_value="YES"),
patch.object(State, "save"),
patch(f"{PKG}.uninstall_other_games", return_value=0) as mock_uninstall,
patch(f"{PKG}.is_game_installed", return_value=True),
patch(f"{PKG}.get_all_owned_app_ids", return_value=[1, 100, 489830]),
patch(f"{PKG}.try_hide_other_games", return_value=(1, None)) as mock_hide,
):
cmd_pick_manual(Config(max_manual_picks=2), state, ["489830"])
mock_uninstall.assert_called_once_with({100, 489830})
mock_hide.assert_called_once_with([1, 100, 489830], {100, 489830})
def test_installs_every_missing_allowed_game(self) -> None:
state = _locked_state(app_id=100)
with (
patch(f"{PKG}._echo"),
patch(f"{PKG}._resolve_game_name", return_value="Skyrim SE"),
patch("builtins.input", return_value="YES"),
patch.object(State, "save"),
patch(f"{PKG}.uninstall_other_games", return_value=0),
patch(f"{PKG}.is_game_installed", return_value=False),
patch(f"{PKG}.install_game") as mock_install,
patch(f"{PKG}.get_all_owned_app_ids", return_value=[]),
):
cmd_pick_manual(Config(max_manual_picks=2), state, ["489830"])
installed = {call.args[0] for call in mock_install.call_args_list}
assert installed == {100, 489830}
class TestAbandonOneOfTwoPicks:
def test_other_pick_survives(self) -> None:
state = _two_pick_state()
with (
patch(f"{PKG}._echo") as mock_echo,
patch("builtins.input", return_value="YES"),
patch.object(State, "save"),
patch(f"{PKG}.is_game_installed", return_value=False),
):
cmd_abandon_pick(Config(), state, ["200"])
output = " ".join(str(c) for c in mock_echo.call_args_list)
assert "stay locked in: TestGame (AppID=100)" in output
assert "Still assigned: TestGame" in output
assert [p["app_id"] for p in state.manual_picks] == [100]
assert state.current_app_id == 100
def test_wrong_id_lists_all_active_picks(self) -> None:
state = _two_pick_state()
with patch(f"{PKG}._echo") as mock_echo, pytest.raises(SystemExit):
cmd_abandon_pick(Config(), state, ["999"])
output = " ".join(str(c) for c in mock_echo.call_args_list)
assert "TestGame (AppID=100)" in output
assert "SecondGame (AppID=200)" in output
def test_lock_message_lists_both_picks(self) -> None:
with patch(f"{PKG}._echo") as mock_echo:
_show_manual_pick_lock_message(_two_pick_state())
output = " ".join(str(c) for c in mock_echo.call_args_list)
assert "picked 2 game(s)" in output
assert "abandon-pick 100" in output
assert "abandon-pick 200" in output
def test_status_lists_both_picks(self) -> None:
with (
patch(f"{PKG}.is_store_blocked", return_value=False),
patch(f"{PKG}.get_installed_games", return_value=[]),
patch(f"{PKG}._echo") as mock_echo,
):
cmd_status(Config(), _two_pick_state())
output = " ".join(str(c) for c in mock_echo.call_args_list)
assert "Manual picks (2)" in output
assert "undoable for" in output
def test_status_omits_undo_after_grace(self) -> None:
state = _two_pick_state()
state.manual_picks[0]["started_at"] = _PAST_GRACE
state.manual_picks[1]["started_at"] = _PAST_GRACE
with (
patch(f"{PKG}.is_store_blocked", return_value=False),
patch(f"{PKG}.get_installed_games", return_value=[]),
patch(f"{PKG}._echo") as mock_echo,
):
cmd_status(Config(), state)
assert "undoable for" not in " ".join(str(c) for c in mock_echo.call_args_list)

View File

@ -170,12 +170,18 @@ class TestPickManualGate:
_mcp, "load_snapshot", return_value=[{"app_id": 440, "name": "TF2"}]
),
patch.object(_mcp, "State") as state,
patch.object(_mcp, "apply_manual_pick") as amp,
patch.object(_mcp, "Config") as config,
patch.object(_mcp, "apply_manual_pick", return_value=None) as amp,
):
out = _mcp.pick_manual(440, confirm=True)
assert out["applied"] is True
assert out["app_id"] == 440
amp.assert_called_once_with(state.load.return_value, 440, "TF2")
amp.assert_called_once_with(
state.load.return_value,
440,
"TF2",
max_picks=config.load.return_value.max_manual_picks,
)
class TestAbandonPickGate:
@ -184,9 +190,9 @@ class TestAbandonPickGate:
def _state(self, *, days_ago: float = 1.0, app_id: int = 440) -> State:
started = (datetime.now(timezone.utc) - timedelta(days=days_ago)).isoformat()
return State(
manual_pick_app_id=app_id,
manual_pick_game_name="TF2",
manual_pick_started_at=started,
manual_picks=[
{"app_id": app_id, "game_name": "TF2", "started_at": started}
],
current_app_id=app_id,
current_game_name="TF2",
)
@ -201,7 +207,7 @@ class TestAbandonPickGate:
with patch.object(_mcp.State, "load", return_value=self._state()):
out = _mcp.abandon_pick(999)
assert out["ok"] is False
assert "not the active manual pick" in out["reason"]
assert "not one of the active manual picks" in out["reason"]
def test_expired_grace(self) -> None:
state = self._state(days_ago=_mcp.MANUAL_GRACE_DAYS + 1)
@ -230,7 +236,20 @@ class TestAbandonPickGate:
out = _mcp.abandon_pick(440, confirm=True)
assert out["applied"] is True
assert out["app_id"] == 440
amp.assert_called_once_with(state)
amp.assert_called_once_with(state, 440)
def test_refused_at_cap(self) -> None:
with (
patch.object(
_mcp, "load_snapshot", return_value=[{"app_id": 440, "name": "TF2"}]
),
patch.object(_mcp, "State"),
patch.object(_mcp, "Config"),
patch.object(_mcp, "apply_manual_pick", return_value="cap reached"),
):
out = _mcp.pick_manual(440, confirm=True)
assert out["ok"] is False
assert out["reason"] == "cap reached"
class TestBlockGamingGate: