Compare commits

...

3 Commits

Author SHA1 Message Date
a3d7641193 Add change explanation: manual-pick-grace-and-multi-pick
Some checks are pending
pre-commit / pre-commit (push) Waiting to run
Tests / test (3.10) (push) Waiting to run
Tests / test (3.11) (push) Waiting to run
Tests / test (3.12) (push) Waiting to run
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-19 17:42:00 +02:00
05e070ca27 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>
2026-07-19 17:28:23 +02:00
eb1472a433 feat(enforcer): add 4-day grace period to undo a manual pick
A manual pick had no escape hatch: once locked in, every command except
done/check/status/enforce/setup/serve exited 1 for 14 days or until 100%
achievements. A wrong pick meant two weeks stuck with it.

Adds a short mistake-correction window:

- MANUAL_GRACE_DAYS = 4 — within 4 days, 'abandon-pick <app_id>' backs out
  of the pick. Outside it the command refuses and exits 1.
- The app_id must be passed explicitly and must match the active pick, so
  an abandon cannot be triggered by muscle memory.
- 'abandon-pick' joins _MANUAL_LOCK_EXEMPT_COMMANDS — the pre-dispatch
  lock check would otherwise block the only way out. It is dropped from
  the advertised command list once the window closes.
- Abandoning clears the lock and the assignment, uninstalls the game, and
  reuses the existing skipped_until cooldown for ABANDON_COOLDOWN_DAYS=30
  so 'scan' does not hand it straight back.
- _actions.abandon_manual_pick is state-only (no uninstall cascade),
  matching apply_manual_pick, so the gated MCP abandon_pick tool reuses it.

Also fixes a crash surfaced while picking a replacement game: the
SteamUnavailableError family (including SteamUpdateInProgressError, raised
when a game update defers a Steam restart) was only caught in the enforce
loop. cmd_hide, cmd_pick, cmd_pick_manual and both cmd_done reconciliation
points called hide_other_games bare, so an undrivable Steam aborted the
command with a traceback — after the pick had already been saved. All six
sites now go through the new stdout-free try_hide_other_games wrapper and
report "Library hiding: skipped (<reason>)" instead.

Verified live: lock message advertises the window, expired/wrong-id/no-arg
paths exit 1, and abandoning released the AoE2 lock, uninstalled it and
recorded the 30-day cooldown. 1030 tests pass at 100% coverage.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-19 17:04:08 +02:00
23 changed files with 2415 additions and 219 deletions

View File

@ -0,0 +1,685 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Manual picks: a way out, and a second slot</title>
<style>
:root {
--bg: #fbfbfa; --fg: #1c1c1a; --muted: #5f6360; --rule: #e2e2dd;
--card: #ffffff; --accent: #1f6f5c; --accent-soft: #e6f2ee;
--warn: #8a4b1f; --warn-soft: #fbeee2; --code-bg: #f4f4f1;
--good: #1f6f5c; --bad: #a2352b;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #16181a; --fg: #e6e6e2; --muted: #9aa0a0; --rule: #2c2f31;
--card: #1d2022; --accent: #6fd0b3; --accent-soft: #16302a;
--warn: #e0a878; --warn-soft: #2e2419; --code-bg: #202325;
--good: #6fd0b3; --bad: #e08a80;
}
}
* { box-sizing: border-box; }
body {
margin: 0 auto; padding: 2.5rem 1rem 5rem; max-width: min(48rem, 92vw);
background: var(--bg); color: var(--fg); line-height: 1.65;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
font-size: 17px;
}
h1 { font-size: 1.9rem; line-height: 1.25; margin: 0 0 .4rem; letter-spacing: -.015em; }
h2 { font-size: 1.35rem; margin: 3rem 0 .8rem; letter-spacing: -.01em;
padding-bottom: .35rem; border-bottom: 1px solid var(--rule); }
h3 { font-size: 1.05rem; margin: 2rem 0 .5rem; }
p, li { color: var(--fg); }
.sub { color: var(--muted); margin: 0 0 2rem; font-size: 1.02rem; }
a { color: var(--accent); }
code { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
background: var(--code-bg); padding: .1em .35em; border-radius: 4px; font-size: .88em; }
pre { background: var(--code-bg); border: 1px solid var(--rule); border-radius: 8px;
padding: .9rem 1rem; overflow-x: auto; }
pre code { background: none; padding: 0; white-space: pre-wrap; word-break: break-word; font-size: .82rem; line-height: 1.5; }
nav.toc { background: var(--card); border: 1px solid var(--rule); border-radius: 10px;
padding: .9rem 1.2rem; margin-bottom: 2rem; }
nav.toc ol { margin: .3rem 0 0; padding-left: 1.2rem; }
nav.toc li { margin: .18rem 0; }
.note { background: var(--accent-soft); border-left: 3px solid var(--accent);
padding: .8rem 1rem; border-radius: 0 8px 8px 0; margin: 1.2rem 0; }
.warn { background: var(--warn-soft); border-left: 3px solid var(--warn);
padding: .8rem 1rem; border-radius: 0 8px 8px 0; margin: 1.2rem 0; }
.diagram { background: var(--card); border: 1px solid var(--rule); border-radius: 10px;
padding: 1.1rem; margin: 1.4rem 0; }
.diagram h4 { margin: 0 0 .9rem; font-size: .82rem; text-transform: uppercase;
letter-spacing: .08em; color: var(--muted); font-weight: 600; }
.row { display: flex; gap: .6rem; flex-wrap: wrap; align-items: stretch; }
.chip { border: 1px solid var(--rule); border-radius: 8px; padding: .5rem .7rem;
background: var(--bg); font-size: .84rem; flex: 1 1 8rem; min-width: 7.5rem; }
.chip .t { font-weight: 600; display: block; }
.chip .m { color: var(--muted); font-size: .78rem; }
.chip.keep { border-color: var(--good); background: var(--accent-soft); }
.chip.kill { border-color: var(--bad); opacity: .72; text-decoration-color: var(--bad); }
.chip.kill .t { text-decoration: line-through; }
.arrow { text-align: center; color: var(--muted); font-size: 1.3rem; margin: .5rem 0; }
.split { display: grid; grid-template-columns: 1fr; gap: 1rem; }
@media (min-width: 40rem) { .split { grid-template-columns: 1fr 1fr; } }
.panel { border: 1px solid var(--rule); border-radius: 9px; padding: .9rem; background: var(--bg); }
.panel h5 { margin: 0 0 .6rem; font-size: .8rem; text-transform: uppercase;
letter-spacing: .07em; color: var(--muted); }
.tl { display: flex; align-items: center; gap: 0; margin: .5rem 0 1rem; }
.tl .seg { flex: 1; height: 26px; display: flex; align-items: center; justify-content: center;
font-size: .72rem; border: 1px solid var(--rule); }
.tl .seg:first-child { border-radius: 6px 0 0 6px; }
.tl .seg:last-child { border-radius: 0 6px 6px 0; }
.seg.grace { background: var(--accent-soft); border-color: var(--accent); color: var(--fg); }
.seg.locked { background: var(--code-bg); }
/* micro-world */
.mw { background: var(--card); border: 1px solid var(--rule); border-radius: 10px; padding: 1.1rem; margin: 1.5rem 0; }
.mw h4 { margin: 0 0 .2rem; font-size: 1rem; }
.mw .hint { color: var(--muted); font-size: .85rem; margin: 0 0 .9rem; }
.mw button { font: inherit; font-size: .82rem; padding: .35rem .7rem; border-radius: 6px;
border: 1px solid var(--rule); background: var(--bg); color: var(--fg); cursor: pointer; }
.mw button:hover:not(:disabled) { border-color: var(--accent); }
.mw button:disabled { opacity: .4; cursor: not-allowed; }
.mw .controls { display: flex; gap: .4rem; flex-wrap: wrap; margin: .7rem 0; }
.mw .out { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: .8rem; background: var(--code-bg); border-radius: 8px; padding: .8rem;
overflow-x: auto; white-space: pre-wrap; word-break: break-word; }
.mw .lockbar { padding: .5rem .8rem; border-radius: 7px; font-size: .85rem; font-weight: 600; margin: .6rem 0; }
.lockbar.on { background: var(--warn-soft); color: var(--warn); }
.lockbar.off { background: var(--accent-soft); color: var(--accent); }
.gamerow { display: flex; align-items: center; gap: .5rem; flex-wrap: wrap;
padding: .5rem 0; border-top: 1px solid var(--rule); font-size: .85rem; }
.gamerow:first-of-type { border-top: none; }
.gamerow .nm { flex: 1 1 9rem; min-width: 8rem; }
.badge { font-size: .7rem; padding: .12rem .45rem; border-radius: 999px; border: 1px solid var(--rule); color: var(--muted); }
.badge.act { border-color: var(--accent); color: var(--accent); }
/* quiz */
.q { border: 1px solid var(--rule); border-radius: 10px; padding: 1rem 1.1rem; margin: 1.1rem 0; background: var(--card); }
.q p.qt { font-weight: 600; margin: 0 0 .8rem; }
.opt { display: block; width: 100%; text-align: left; font: inherit; font-size: .9rem;
margin: .4rem 0; padding: .55rem .8rem; border: 1px solid var(--rule);
border-radius: 7px; background: var(--bg); color: var(--fg); cursor: pointer; }
.opt:hover:not(.done) { border-color: var(--accent); }
.opt.correct { border-color: var(--good); background: var(--accent-soft); }
.opt.wrong { border-color: var(--bad); opacity: .75; }
.opt.done { cursor: default; }
.why { font-size: .85rem; color: var(--muted); margin: .6rem 0 0; display: none; }
.why.show { display: block; }
.score { position: sticky; bottom: 1rem; background: var(--card); border: 1px solid var(--rule);
border-radius: 999px; padding: .5rem 1.1rem; font-size: .88rem; display: inline-block; margin-top: 1rem; }
footer { margin-top: 4rem; padding-top: 1rem; border-top: 1px solid var(--rule);
color: var(--muted); font-size: .85rem; }
</style>
</head>
<body>
<h1>Manual picks: a way out, and a second slot</h1>
<p class="sub">Two changes to the Steam Backlog Enforcer — a 4-day window to undo a manual pick, and support for two locked-in games at once. Commits <code>eb1472a</code> and <code>05e070c</code>, 19 July 2026.</p>
<nav class="toc">
<strong>Contents</strong>
<ol>
<li><a href="#background">Background — what the enforcer does</a></li>
<li><a href="#intuition">Intuition — one slot becomes a set</a></li>
<li><a href="#code">The code, by concern</a></li>
<li><a href="#quiz">Quiz</a></li>
</ol>
</nav>
<h2 id="background">Background — what the enforcer does</h2>
<p>The Steam Backlog Enforcer is a self-discipline tool. It picks one game from your Steam
backlog, then makes it genuinely hard to play anything else: it uninstalls every other game,
hides them from the Steam library, blocks the store, and runs a daemon that kills unauthorized
game processes on sight. You finish the assigned game to 100% achievements, run <code>done</code>,
and it hands you the next one.</p>
<p>Most of that machinery answers a single question — <em>which game is allowed to exist right
now?</em> Before this change, the answer lived in one field of the persisted state:</p>
<pre><code>@dataclass
class State:
current_app_id: int | None = None
current_game_name: str = ""
finished_app_ids: list[int] = field(default_factory=list)
...</code></pre>
<p>and every enforcement primitive took that one id as a parameter — <code>uninstall_other_games(allowed_app_id)</code>,
<code>hide_other_games(owned, allowed_app_id)</code>, <code>enforce_allowed_game(allowed_app_id)</code>,
<code>_guard_installed_games(allowed_app_id)</code>. Each one compared with <code>==</code> and removed
everything else.</p>
<h3>The manual pick, and its trap</h3>
<p>Normally the enforcer chooses for you. <code>pick-manual &lt;app_id&gt;</code> lets you override that
and name the game yourself — but because self-chosen commitments are the easy ones to wriggle
out of, it was deliberately built as the strictest mode in the tool. Picking a game recorded
three fields and slammed a door:</p>
<pre><code>manual_pick_app_id: int | None
manual_pick_game_name: str
manual_pick_started_at: str # ISO-8601 UTC</code></pre>
<p>From then on, <code>main()</code> ran a check before dispatching <em>any</em> command:</p>
<pre><code>def _enforce_manual_pick_lock(command: str, state: State) -> None:
if not _is_manual_pick_locked(state):
return
if command in _MANUAL_LOCK_EXEMPT_COMMANDS:
return
_show_manual_pick_lock_message(state)
sys.exit(1)</code></pre>
<p>Only six commands survived that gate: <code>done</code>, <code>check</code>, <code>status</code>,
<code>enforce</code>, <code>setup</code>, <code>serve</code>. The lock released on exactly two
conditions — the picked game appearing in <code>finished_app_ids</code>, or 14 days elapsing.</p>
<p>Which is fine right up until you pick the wrong game. That is what prompted this change: a
manual pick of Age of Empires II that turned out to be a mistake, with no in-app path out of it
for two weeks. <code>scan</code>, <code>pick</code>, <code>list</code>, <code>reset</code> — all
of them exited 1.</p>
<h2 id="intuition">Intuition — one slot becomes a set</h2>
<p>Two independent problems, and the second one is what makes the first one safe.</p>
<h3>Problem 1: a commitment with no undo</h3>
<p>A lock is only useful if it survives the moment you want to break it — that is the whole point.
But there's a difference between <em>"I don't feel like this game today"</em> (the lock should
absolutely win) and <em>"I typed the wrong app id"</em> or <em>"this isn't the game I thought it
was"</em>. The fix is a short window where the second reading is still plausible:</p>
<div class="diagram">
<h4>Lifetime of one manual pick</h4>
<div class="tl">
<div class="seg grace">day 0</div>
<div class="seg grace">1</div>
<div class="seg grace">2</div>
<div class="seg grace">3</div>
<div class="seg locked">4</div>
<div class="seg locked">5</div>
<div class="seg locked">…</div>
<div class="seg locked">13</div>
<div class="seg locked">14 →</div>
</div>
<div class="row">
<div class="chip keep"><span class="t">Days 0–4: grace</span><span class="m"><code>abandon-pick &lt;id&gt;</code> works. Advertised in the lock message.</span></div>
<div class="chip"><span class="t">Days 4–14: locked</span><span class="m">Command refuses and exits 1; it is dropped from the advertised command list.</span></div>
</div>
</div>
<p>Four days, and the window is deliberately awkward to use: you must pass the app id explicitly
and it must match an active pick, so no one abandons a commitment by muscle memory. Abandoning
also costs something — the game goes onto the existing 30-day <code>skipped_until</code> cooldown,
so <code>scan</code> will not hand it back tomorrow.</p>
<div class="note">
<strong>Why reuse <code>skipped_until</code>?</strong> The state already had a
<code>skip_for_days(app_id, days)</code> helper, used when you decline a freshly-picked game in
<code>cmd_done</code>. An abandoned pick is the same idea with a longer fuse, so it reuses the
mechanism rather than inventing a parallel one.
</div>
<h3>Problem 2: undo alone is an escape hatch</h3>
<p>Here's the loop that a naive grace period opens: pick a game → abandon it → pick another →
abandon that one. Each new pick stamps a fresh <code>started_at</code>, so the grace clock resets
forever and the enforcer enforces nothing.</p>
<p>The chosen answer was not to forbid re-picking, but to make a second concurrent pick a
first-class, <em>capped</em> feature. If you may legitimately have two games locked in, correcting
a pick no longer requires a pick→abandon→pick cycle, and the cap is what bounds the whole thing.
<code>Config.max_manual_picks</code> defaults to 2.</p>
<p>That turns the enforcer's central question from "which game?" into "which <em>set</em> of
games?" — and that is the real substance of the diff:</p>
<div class="diagram">
<h4>An enforcement pass, before and after</h4>
<div class="split">
<div class="panel">
<h5>Before — one allowed id</h5>
<p style="margin:.2rem 0 .6rem;font-size:.85rem;color:var(--muted)"><code>current_app_id = 1794680</code></p>
<div class="row">
<div class="chip kill"><span class="t">KCD II</span><span class="m">1771300 · removed</span></div>
<div class="chip keep"><span class="t">Vampire Survivors</span><span class="m">1794680 · kept</span></div>
</div>
<div class="arrow">↓</div>
<div class="chip kill" style="flex:none"><span class="t">Anything else</span><span class="m">uninstalled, hidden, killed</span></div>
</div>
<div class="panel">
<h5>After — an allowed set</h5>
<p style="margin:.2rem 0 .6rem;font-size:.85rem;color:var(--muted)"><code>allowed_app_ids = {1771300, 1794680}</code></p>
<div class="row">
<div class="chip keep"><span class="t">KCD II</span><span class="m">1771300 · kept</span></div>
<div class="chip keep"><span class="t">Vampire Survivors</span><span class="m">1794680 · kept</span></div>
</div>
<div class="arrow">↓</div>
<div class="chip kill" style="flex:none"><span class="t">Anything else</span><span class="m">uninstalled, hidden, killed</span></div>
</div>
</div>
</div>
<p>One function now answers that question for the whole system:</p>
<pre><code>def allowed_app_ids(state: State) -> set[int]:
"""Return every app id the enforcer must leave installed and visible."""
return {app_id for app_id, _ in allowed_games(state)}</code></pre>
<p>It is the union of the active manual picks and the current assignment. Every primitive that
used to take one id now takes this set, and every call site passes <code>allowed_app_ids(state)</code>.
"Active" does real work here — a pick drops out of the set the moment its game is finished or its
own 14-day deadline passes, so nothing has to be explicitly cleaned up.</p>
<h3>Play with the rule</h3>
<p>The widget below runs the actual new logic — <code>_pick_is_active</code>, the grace test, the
cap, and the allowed set — reimplemented faithfully in JS. Advance the clock and watch picks fall
out of the set on their own.</p>
<div class="mw" id="mw">
<h4>Enforcement sandbox</h4>
<p class="hint">Library below is what's installed. Advance days, finish a game, or abandon a pick, and watch the allowed set and lock recompute.</p>
<div id="mw-clock" style="font-size:.85rem;color:var(--muted)"></div>
<div class="controls">
<button data-act="day1">+1 day</button>
<button data-act="day3">+3 days</button>
<button data-act="pick3">pick-manual 620 (Portal 2)</button>
<button data-act="reset">reset</button>
</div>
<div id="mw-games"></div>
<div class="lockbar" id="mw-lock"></div>
<div class="out" id="mw-out"></div>
</div>
<h2 id="code">The code, by concern</h2>
<h3>1. State: one slot becomes a list, without losing a live lock</h3>
<p>The three <code>manual_pick_*</code> fields became a list of entries. The subtlety is that a
lock was <em>active on the author's own machine</em> while this was being written — dropping the
old fields would have silently released it. So they are still read, migrated once, and cleared:</p>
<pre><code>def _migrate_legacy_manual_pick(self) -> None:
"""Fold a pre-multi-pick single manual pick into ``manual_picks``."""
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
...</code></pre>
<p>Called from <code>State.load()</code>, so it happens in memory on read and persists on the next
save. Entries are plain dicts rather than a dataclass because <code>save()</code> serialises
<code>self.__dict__</code> straight to JSON.</p>
<h3>2. Predicates: "is it locked" becomes "is anything still active"</h3>
<p><code>_pick_is_active</code> holds the per-pick rule. Note the defensive branch — a corrupt
timestamp keeps the pick <em>active</em>, because for an enforcement tool the safe answer to "I
can't tell when this expires" is "it hasn't":</p>
<pre><code>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</code></pre>
<p>Everything else is a thin layer on top: <code>active_manual_picks</code> filters the list,
<code>is_manual_pick_locked</code> is <code>bool(active_manual_picks(state))</code>, and the grace
helpers take an <code>app_id</code> so each pick has its own window.</p>
<h3>3. Plumbing the set through the enforcement primitives</h3>
<p>Four functions changed shape from <code>allowed_app_id: int | None</code> to
<code>allowed_app_ids: set[int]</code>, swapping equality for membership. The interesting one is
the library hider, because its comparison lives inside JavaScript injected into Steam over the
DevTools Protocol:</p>
<pre><code>- 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)
- const allowed = {allowed_js};
+ const allowed = new Set({allowed_json});
...
- .filter(id => id !== allowed)
+ .filter(id => !allowed.has(id))
...
- if (allowed !== null) await collectionStore.SetAppsAsHidden([allowed], false);
+ if (allowed.size > 0) await collectionStore.SetAppsAsHidden([...allowed], false);</code></pre>
<h3>4. The CLI: the lock now permits the commands that manage it</h3>
<p>Two commands had to become reachable <em>while locked</em>, which sounds like weakening the lock
but isn't:</p>
<pre><code>_MANUAL_LOCK_EXEMPT_COMMANDS = frozenset({
"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",
})</code></pre>
<p><code>abandon-pick</code> is obvious — it is the only way out, so the pre-dispatch gate would
otherwise make it dead on arrival. <code>pick-manual</code> is the subtle one: the gate no longer
limits it, so the limit moved into the command itself, where <code>_report_pick_slots</code>
exits 1 once <code>manual_pick_slots_left</code> hits zero. The lock check answers "may I run this
command", the cap answers "may I add another game" — two different questions that used to share
one mechanism.</p>
<p>The post-pick cascade moved from a single id to the whole set, which is what stops a second
pick from tearing down the first:</p>
<pre><code>allowed = allowed_app_ids(state)
if config.uninstall_other_games:
count = uninstall_other_games(allowed)
for app_id, name in allowed_games(state):
if not is_game_installed(app_id):
install_game(app_id, name, config.steam_id, use_steam_protocol=True)
hidden, skipped = try_hide_other_games(owned_ids, allowed)</code></pre>
<h3>5. A crash found along the way</h3>
<p>Picking a replacement game surfaced an unrelated bug: <code>SteamUpdateInProgressError</code>
(raised when a game update defers a Steam restart) was only caught in the enforce loop. The five
interactive call sites called <code>hide_other_games</code> bare, so an undrivable Steam aborted
the command with a traceback — <em>after</em> the pick had already been saved. A small wrapper
turns that class of failure into a return value:</p>
<pre><code>def try_hide_other_games(owned_app_ids, allowed_app_ids) -> tuple[int, str | None]:
try:
return hide_other_games(owned_app_ids, allowed_app_ids), None
except SteamUnavailableError as exc:
return 0, str(exc)</code></pre>
<p>All six sites now report <code>Library hiding: skipped (&lt;reason&gt;)</code> and carry on.</p>
<div class="warn">
<strong>The deployment trap.</strong> The enforce daemon runs from the working tree
(<code>WorkingDirectory=/home/kuhy/steam-backlog-enforcer</code>) but only reloads on restart.
During development, the still-running <em>pre-upgrade</em> daemon knew only <code>current_app_id</code> —
which the second pick had just moved — so within one 3-second loop it uninstalled the other pick as
"unauthorized" and deleted an in-progress download. The code was right; the running process was
stale. <code>sudo systemctl restart steam-backlog-enforcer</code> is now part of deploying any
change to this logic.
</div>
<h2 id="quiz">Quiz</h2>
<p class="sub" style="margin-bottom:1rem">Five questions on the reasoning behind the change. Click an option to check it.</p>
<div id="quiz"></div>
<div class="score" id="score">Score: 0 / 0</div>
<footer>
Generated for <code>steam-backlog-enforcer</code> · commits <code>eb1472a</code>, <code>05e070c</code> ·
sources: <code>_actions.py</code>, <code>config.py</code>, <code>main.py</code>,
<code>library_hider.py</code>, <code>_enforce_loop.py</code>.
</footer>
<script>
/* ---------- micro-world: the real rule, reimplemented ---------- */
(function () {
var MANUAL_LOCK_DAYS = 14, MANUAL_GRACE_DAYS = 4, MAX_PICKS = 2;
var DAY = 86400000;
var state, now;
function initial() {
now = 0;
state = {
currentAppId: 1794680,
currentName: "Vampire Survivors",
finished: [],
picks: [
{ app_id: 1771300, game_name: "Kingdom Come: Deliverance II", started_at: -1 * DAY },
{ app_id: 1794680, game_name: "Vampire Survivors", started_at: 0 }
],
library: [
{ app_id: 1771300, name: "Kingdom Come: Deliverance II" },
{ app_id: 1794680, name: "Vampire Survivors" },
{ app_id: 620, name: "Portal 2" },
{ app_id: 228980, name: "Steamworks Common", protected: true }
]
};
}
// mirrors _pick_is_active
function pickIsActive(p) {
if (p.app_id == null || state.finished.indexOf(p.app_id) !== -1) return false;
if (p.started_at != null) {
if (now >= p.started_at + MANUAL_LOCK_DAYS * DAY) return false;
}
return true;
}
function activePicks() { return state.picks.filter(pickIsActive); }
function isLocked() { return activePicks().length > 0; }
// mirrors allowed_games / allowed_app_ids
function allowedGames() {
var out = [];
if (state.currentAppId != null) out.push([state.currentAppId, state.currentName]);
activePicks().forEach(function (p) {
if (!out.some(function (g) { return g[0] === p.app_id; })) out.push([p.app_id, p.game_name]);
});
return out;
}
function allowedIds() { return allowedGames().map(function (g) { return g[0]; }); }
// mirrors manual_pick_grace_remaining
function graceLeft(appId) {
var p = activePicks().filter(function (x) { return x.app_id === appId; })[0];
if (!p || p.started_at == null) return null;
return (p.started_at + MANUAL_GRACE_DAYS * DAY - now) / DAY;
}
function abandon(appId) {
var g = graceLeft(appId);
if (g === null || g <= 0) return false;
state.picks = activePicks().filter(function (p) { return p.app_id !== appId; });
if (state.currentAppId === appId) {
var survivor = state.picks.length ? state.picks[state.picks.length - 1] : null;
state.currentAppId = survivor ? survivor.app_id : null;
state.currentName = survivor ? survivor.game_name : "";
}
return true;
}
function addPick(appId, name) {
var act = activePicks();
if (act.length >= MAX_PICKS) return "cap of " + MAX_PICKS + " reached";
if (act.some(function (p) { return p.app_id === appId; })) return "already picked";
state.picks = act.concat([{ app_id: appId, game_name: name, started_at: now }]);
state.currentAppId = appId; state.currentName = name;
return null;
}
var elGames = document.getElementById("mw-games"),
elLock = document.getElementById("mw-lock"),
elOut = document.getElementById("mw-out"),
elClock = document.getElementById("mw-clock");
function render() {
var allowed = allowedIds();
elClock.textContent = "Clock: day " + (now / DAY).toFixed(0) +
" · cap " + activePicks().length + "/" + MAX_PICKS;
elGames.innerHTML = "";
state.library.forEach(function (g) {
var isAllowed = allowed.indexOf(g.app_id) !== -1;
var pick = activePicks().filter(function (p) { return p.app_id === g.app_id; })[0];
var row = document.createElement("div");
row.className = "gamerow";
var nm = document.createElement("span");
nm.className = "nm";
nm.textContent = g.name + " (" + g.app_id + ")";
row.appendChild(nm);
var b = document.createElement("span");
b.className = "badge" + (isAllowed ? " act" : "");
b.textContent = g.protected ? "protected" : (isAllowed ? "allowed" : "would be removed");
row.appendChild(b);
if (pick) {
var gl = graceLeft(g.app_id);
var ab = document.createElement("button");
ab.textContent = gl !== null && gl > 0
? "abandon-pick (" + gl.toFixed(1) + "d grace)" : "abandon-pick (expired)";
ab.disabled = !(gl !== null && gl > 0);
ab.onclick = function () { abandon(g.app_id); render(); };
row.appendChild(ab);
var fin = document.createElement("button");
fin.textContent = "finish 100%";
fin.onclick = function () { state.finished.push(g.app_id); render(); };
row.appendChild(fin);
}
elGames.appendChild(row);
});
var locked = isLocked();
elLock.className = "lockbar " + (locked ? "on" : "off");
elLock.textContent = locked
? "MANUAL PICK LOCK ACTIVE — " + activePicks().length + " pick(s) still holding it"
: "Lock released — every pick is finished or past its 14-day deadline";
var lines = [];
lines.push("allowed_app_ids(state) = {" + allowed.join(", ") + "}");
lines.push("current_app_id = " + (state.currentAppId === null ? "None" : state.currentAppId));
lines.push("");
var removed = state.library.filter(function (g) {
return !g.protected && allowed.indexOf(g.app_id) === -1;
});
lines.push("_guard_installed_games would remove: " +
(removed.length ? removed.map(function (g) { return g.name; }).join(", ") : "nothing"));
elOut.textContent = lines.join("\n");
}
document.getElementById("mw").addEventListener("click", function (ev) {
var act = ev.target.getAttribute && ev.target.getAttribute("data-act");
if (!act) return;
if (act === "day1") now += DAY;
else if (act === "day3") now += 3 * DAY;
else if (act === "pick3") {
var err = addPick(620, "Portal 2");
if (err) { elOut.textContent = "pick-manual 620 refused: " + err; return; }
} else if (act === "reset") initial();
render();
});
initial();
render();
})();
/* ---------- quiz ---------- */
(function () {
var QUESTIONS = [
{
q: "During development the running daemon deleted an in-progress download the instant a second pick was added. Why?",
opts: [
"The new pick's cascade uninstalled it before the state file was saved",
"That game had passed its own 14-day deadline and left the active set",
"The live daemon still ran old code that allowed only current_app_id",
"Steam itself dropped the manifest because the update was interrupted"
],
correct: 2,
why: "The daemon runs from the working tree but only reloads on restart, so it enforced the pre-upgrade single-slot rule."
},
{
q: "A stored pick has a started_at value that cannot be parsed. What does _pick_is_active do with it?",
opts: [
"Treats the pick as active, since no deadline can be evaluated",
"Drops the pick, on the grounds that corrupt data is not a lock",
"Rewrites started_at to now, restarting the 14-day countdown",
"Raises the ValueError so the caller can repair the state file"
],
correct: 0,
why: "For an enforcement tool, 'I can't tell when this expires' has to mean 'it hasn't' — otherwise corrupt data becomes a way out."
},
{
q: "Why does the enforcer need allowed_app_ids() rather than reading current_app_id directly?",
opts: [
"It caches the id so the guard avoids re-reading state each loop",
"It resolves game names, which the notifications and installs need",
"It excludes protected Steam runtimes from the uninstall sweep",
"It unions the assignment with active picks, so both games survive"
],
correct: 3,
why: "The guard, killer, hider and installer all consult that one set; a second pick is only safe because they share it."
},
{
q: "pick-manual was added to the commands allowed to run while the lock is active. What keeps that from defeating the lock?",
opts: [
"The 4-day grace window, which expires and re-blocks the command",
"The cap in cmd_pick_manual, which exits 1 once no slot is left",
"The pre-dispatch check, which still rejects a third pick attempt",
"The 30-day cooldown, which bars re-picking an abandoned game"
],
correct: 1,
why: "The lock check answers 'may I run this command'; the cap answers 'may I add another game'. Two questions, two mechanisms."
},
{
q: "Two picks are active and you abandon the one that is also the current assignment. What happens to current_app_id?",
opts: [
"It is cleared to None, so scan can assign a fresh game next run",
"It stays pointed at the abandoned game until the next enforce pass",
"The surviving pick inherits it, so that game remains guarded",
"It moves to whichever allowed game is currently still installed"
],
correct: 2,
why: "abandon_manual_pick hands the assignment to a survivor, and only clears it when no pick remains."
}
];
var answered = 0, right = 0;
var host = document.getElementById("quiz"), score = document.getElementById("score");
QUESTIONS.forEach(function (item, qi) {
var box = document.createElement("div");
box.className = "q";
var t = document.createElement("p");
t.className = "qt";
t.textContent = (qi + 1) + ". " + item.q;
box.appendChild(t);
var why = document.createElement("p");
why.className = "why";
why.textContent = item.why;
item.opts.forEach(function (text, oi) {
var b = document.createElement("button");
b.className = "opt";
b.textContent = text;
b.onclick = function () {
if (box.dataset.done) return;
box.dataset.done = "1";
answered++;
if (oi === item.correct) right++;
Array.prototype.forEach.call(box.querySelectorAll(".opt"), function (o, i) {
o.classList.add("done");
if (i === item.correct) o.classList.add("correct");
else if (i === oi) o.classList.add("wrong");
});
why.classList.add("show");
score.textContent = "Score: " + right + " / " + answered;
};
box.appendChild(b);
});
box.appendChild(why);
host.appendChild(box);
});
})();
</script>
</body>
</html>

View File

@ -30,8 +30,12 @@
<div class="wrap">
<div class="kicker">steam-backlog-enforcer</div>
<h1>Change explanations</h1>
<p class="lead">2 explanations · interactive walkthroughs of notable changes, newest first.</p>
<p class="lead">3 explanations · interactive walkthroughs of notable changes, newest first.</p>
<div class="grid">
<a class="card" href="2026-07-19-explanation-manual-pick-grace-and-multi-pick.html">
<span class="date">2026-07-19</span>
<span class="title">Manual picks: a way out, and a second slot</span>
</a>
<a class="card" href="2026-07-18-explanation-steam-cdp-restart-fix.html">
<span class="date">2026-07-18</span>
<span class="title">Fix: Steam CDP restart never worked</span>

View File

@ -23,12 +23,81 @@ if TYPE_CHECKING:
# truth: both ``main.py`` and the MCP server import it from here.
MANUAL_LOCK_DAYS = 14
# Mistake-correction window: for this many days after a manual pick the user
# may still back out via ``abandon-pick``. Deliberately short — it exists to
# undo a wrong pick, not to serve as an escape hatch from the lock.
MANUAL_GRACE_DAYS = 4
# How long an abandoned pick stays out of the auto-assignment pool, so that
# ``scan`` does not immediately hand back the game the user just rejected.
ABANDON_COOLDOWN_DAYS = 30
def _pick_is_active(state: State, pick: dict[str, Any]) -> bool:
"""Return ``True`` if *pick* still holds the lock.
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 the manual-pick lock is currently in force.
"""Return ``True`` if any manual pick is currently holding the lock.
The lock releases once the picked game reaches ``finished_app_ids`` or once
``MANUAL_LOCK_DAYS`` have elapsed since the pick timestamp.
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.
@ -36,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
@ -66,20 +177,121 @@ 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, app_id: int) -> float | None:
"""Return days left in *app_id*'s grace window, or ``None``.
``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.
"""
pick = find_manual_pick(state, app_id)
if pick is None or not pick.get("started_at"):
return None
try:
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, 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, app_id)
return remaining is not None and remaining > 0
def abandon_manual_pick(state: State, app_id: int) -> bool:
"""Drop one manual pick and persist ``state``, if still inside its grace window.
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 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, app_id):
return False
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
]
# 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:
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
def status_payload(state: State) -> dict[str, Any]:
@ -116,4 +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_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 (
@ -24,7 +25,7 @@ from steam_backlog_enforcer.hltb import (
load_hltb_polls_cache,
save_hltb_cache,
)
from steam_backlog_enforcer.library_hider import hide_other_games
from steam_backlog_enforcer.library_hider import try_hide_other_games
from steam_backlog_enforcer.scanning import pick_next_game
from steam_backlog_enforcer.steam_api import GameInfo, SteamAPIClient
@ -212,8 +213,10 @@ def _finalize_completion(
owned_ids = get_all_owned_app_ids(config)
if owned_ids:
hidden = hide_other_games(owned_ids, state.current_app_id)
if hidden > 0:
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:
_echo(f"\n Library: hid {hidden} games")
if not is_game_installed(state.current_app_id):
@ -251,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)")
@ -276,8 +279,10 @@ 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 = hide_other_games(owned_ids, state.current_app_id)
if hidden > 0:
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:
_echo(f" Library: hid {hidden} games")

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,
@ -38,9 +39,8 @@ from steam_backlog_enforcer.game_install import (
uninstall_other_games,
)
from steam_backlog_enforcer.library_hider import (
SteamUnavailableError,
hide_other_games,
steam_is_installed,
try_hide_other_games,
)
from steam_backlog_enforcer.steam_api import SteamAPIClient
from steam_backlog_enforcer.store_blocker import block_store
@ -145,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
@ -168,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.
@ -190,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.
@ -201,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:
@ -246,10 +272,9 @@ 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.
try:
hidden = hide_other_games(owned_ids, state.current_app_id)
except SteamUnavailableError as exc:
_echo(f" Library hiding: skipped ({exc})")
hidden, skipped = try_hide_other_games(owned_ids, allowed_app_ids(state))
if skipped is not None:
_echo(f" Library hiding: skipped ({skipped})")
return
if hidden > 0:
@ -283,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

@ -32,13 +32,20 @@ from typing import Any
from mcp.server.fastmcp import FastMCP
from steam_backlog_enforcer._actions import (
ABANDON_COOLDOWN_DAYS,
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
@ -198,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,
@ -209,6 +224,72 @@ def pick_manual(app_id: int, *, confirm: bool = False) -> dict[str, Any]:
}
@mcp.tool()
def abandon_pick(app_id: int, *, confirm: bool = False) -> dict[str, Any]:
"""Undo a manual pick inside its grace window (gated write).
With ``confirm=False`` (the default) this performs **no** mutation and
returns a preview. Only works within ``MANUAL_GRACE_DAYS`` days of the
pick. Like ``pick_manual``, this mutates **state only** — the CLI's
``abandon-pick`` additionally uninstalls the abandoned game.
Args:
app_id: The manually-picked app id to back out of.
confirm: Set ``True`` to actually abandon the pick; otherwise preview.
"""
state = State.load()
picks = active_manual_picks(state)
if not picks:
return {"ok": False, "reason": "No manual pick is active."}
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 one of the active manual picks ({listed})."
),
}
remaining = manual_pick_grace_remaining(state, app_id)
if not can_abandon_manual_pick(state, app_id):
return {
"ok": False,
"reason": (
f"The {MANUAL_GRACE_DAYS}-day grace period has expired; "
"the pick can no longer be abandoned."
),
}
game_name = str(pick["game_name"])
if not confirm:
return {
"ok": True,
"preview": True,
"action": "abandon_pick",
"app_id": app_id,
"game_name": game_name,
"grace_days_left": remaining,
"effect": (
"Releases the manual pick lock, clears the assignment, and "
f"keeps the game out of auto-assignment for "
f"{ABANDON_COOLDOWN_DAYS} days."
),
"confirm_required": True,
}
abandon_manual_pick(state, app_id)
logger.info("abandon_pick applied: %s (AppID=%s)", game_name, app_id)
return {
"ok": True,
"applied": True,
"action": "abandon_pick",
"app_id": app_id,
"game_name": game_name,
}
@mcp.tool()
def block_gaming(days: int, *, confirm: bool = False) -> dict[str, Any]:
"""Start a total gaming block for ``days`` days (gated, privileged write).

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

@ -17,3 +17,52 @@ Logic should be as follows:
test the functionality with 489830 (The Elder Scrolls V: Skyrim Special Edition)
as always first write full functionality confirm that it works alone and with the user and only AFTER that write tests and coverage and fix issues
## Grace period (added 2026-07-19)
A manual pick can be a mistake, and with no way out the user is stuck for the
full 2 weeks. There is now a short mistake-correction window:
- `MANUAL_GRACE_DAYS = 4` — for 4 days after the pick, `abandon-pick <app_id>`
backs out of it. Outside that window the command refuses and exits 1.
- The app_id must be passed explicitly and must match the active pick, so an
abandon cannot be triggered by muscle memory.
- `abandon-pick` is in `_MANUAL_LOCK_EXEMPT_COMMANDS` — otherwise the
pre-dispatch lock check in `main()` would block the only way out.
- Abandoning clears the lock **and** the assignment, uninstalls the game, and
puts it on the existing `skipped_until` cooldown for
`ABANDON_COOLDOWN_DAYS = 30` so `scan` does not hand it straight back.
- `_actions.abandon_manual_pick` is state-only (no uninstall), matching the
`apply_manual_pick` rule, so the MCP `abandon_pick` tool can reuse it. Both
MCP tools stay gated behind `confirm=True`.
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 }});
@ -394,6 +394,35 @@ def hide_other_games(
return count
def try_hide_other_games(
owned_app_ids: list[int],
allowed_app_ids: set[int],
) -> tuple[int, str | None]:
"""Hide other games, degrading gracefully when Steam cannot be driven.
An unreachable Steam (not running, no debug port) or a deferred restart
(a game update is in flight) is never fatal: there is simply no library to
reconcile this pass. Every interactive command should skip and carry on
rather than abort with a traceback, so this wrapper turns the
:class:`SteamUnavailableError` family into a return value.
Stdout-free on purpose — callers phrase the skip message themselves.
Args:
owned_app_ids: All owned app ids, used to seed the first hide pass.
allowed_app_ids: Every game that must stay visible.
Returns:
``(hidden_count, skip_reason)``. ``skip_reason`` is ``None`` when the
pass ran; otherwise it explains why hiding was skipped and the count
is 0.
"""
try:
return hide_other_games(owned_app_ids, allowed_app_ids), None
except SteamUnavailableError as exc:
return 0, str(exc)
def unhide_all_games(owned_app_ids: list[int]) -> int:
"""Remove all games from the hidden collection.

View File

@ -7,11 +7,25 @@ import logging
import sys
from typing import TYPE_CHECKING
from steam_backlog_enforcer._actions import (
ABANDON_COOLDOWN_DAYS as _ABANDON_COOLDOWN_DAYS,
)
from steam_backlog_enforcer._actions import (
MANUAL_GRACE_DAYS as _MANUAL_GRACE_DAYS,
)
from steam_backlog_enforcer._actions import (
MANUAL_LOCK_DAYS as _MANUAL_LOCK_DAYS,
)
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,
@ -46,11 +60,12 @@ from steam_backlog_enforcer.game_install import (
install_game,
is_game_installed,
is_protected_app,
uninstall_game,
uninstall_other_games,
)
from steam_backlog_enforcer.library_hider import (
hide_other_games,
restart_steam,
try_hide_other_games,
unhide_all_games,
)
from steam_backlog_enforcer.scanning import (
@ -82,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"}
{
"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
@ -131,35 +157,67 @@ 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'."
f"\n\nAllowed commands: {', '.join(sorted(_MANUAL_LOCK_EXEMPT_COMMANDS))}"
"\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'."
)
# '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 any_in_grace:
usable.discard("abandon-pick")
_echo(f"\nAllowed commands: {', '.join(sorted(usable))}")
_echo("=" * 60 + "\n")
@ -208,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]")
@ -300,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.")
@ -320,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:
@ -344,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.")
@ -442,7 +513,10 @@ def cmd_hide(config: Config, state: State) -> None:
return
_echo(f"Hiding all games except {state.current_game_name}...")
hidden = 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
_echo(f"Hidden {hidden} games.")
if hidden > 0:
@ -482,8 +556,10 @@ 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 = hide_other_games(owned_ids, state.current_app_id)
if hidden > 0:
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:
_echo(f"\n Library: hid {hidden} games")
@ -517,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.
@ -543,13 +682,19 @@ 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 - Only 'done', 'check', 'status', 'enforce', 'setup', 'serve'"
f"\n will remain usable during this period"
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"
f"\n {_MANUAL_GRACE_DAYS} days"
)
_echo()
confirm = input(
@ -561,30 +706,141 @@ 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)")
# 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)
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)
_ABANDON_PICK_USAGE = (
"Usage: abandon-pick <app_id>\n"
" app_id : the manually-picked game you want to back out of.\n\n"
f"Only works within {_MANUAL_GRACE_DAYS} days of the pick."
)
def _abandon_pick_target(state: State, args: list[str]) -> int | None:
"""Validate the abandon-pick argument against the active manual pick.
Requiring the explicit app_id (rather than defaulting to the current pick)
makes an accidental abandon impossible to trigger by muscle memory.
Args:
state: Current enforcer state.
args: Remaining CLI args (first element should be the app_id).
Returns:
The validated app id, or ``None`` if the input was unusable (a message
has already been printed in that case).
"""
if not args:
_echo(_ABANDON_PICK_USAGE)
return None
try:
app_id = int(args[0])
except ValueError:
_echo(f"Error: app_id must be a number, got '{args[0]}'.")
return None
picks = active_manual_picks(state)
if not picks:
_echo("No manual pick is active — nothing to abandon.")
return None
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 one of your manual picks.\nActive: {listed}."
)
return None
return app_id
def cmd_abandon_pick(_config: Config, state: State, args: list[str]) -> None:
"""Back out of a manual pick while still inside the grace period.
Args:
_config: Enforcer configuration (unused, kept for dispatch symmetry).
state: Current enforcer state.
args: Remaining CLI args (first element should be the app_id).
"""
app_id = _abandon_pick_target(state, args)
if app_id is None:
sys.exit(1)
pick = find_manual_pick(state, app_id)
game_name = str(pick["game_name"]) if pick else ""
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, app_id)
elapsed = (
f"{abs(remaining):.1f} day(s) ago"
if remaining is not None
else "at an unknown time"
)
_echo(
f"\nGrace period EXPIRED for {game_name} (AppID={app_id}).\n"
f"The {_MANUAL_GRACE_DAYS}-day window closed {elapsed}.\n"
"Finish the game (100% achievements) or wait out the lock."
)
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 - 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"
)
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(f" {game_name} is already installed.")
_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
owned_ids = get_all_owned_app_ids(config)
if owned_ids:
hidden = hide_other_games(owned_ids, app_id)
if hidden > 0:
_echo(f" Library: hid {hidden} games")
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)
_echo(f"\nManual pick abandoned: {game_name}")
if is_game_installed(app_id):
_echo(f" Uninstalling {game_name}...")
if uninstall_game(app_id, game_name):
_echo(" Uninstalled.")
else:
_echo(" Warning: could not uninstall — remove it from Steam manually.")
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 = (
@ -668,6 +924,9 @@ COMMANDS: dict[str, tuple[str, Callable[[Config, State], object]]] = {
_EXTRA_COMMAND_DESCRIPTIONS: dict[str, str] = {
"add-exception": "Request 24h-locked whitelist exception (use --reason)",
"pick-manual": f"Pick a game by app_id, lock enforcer for {_MANUAL_LOCK_DAYS} days",
"abandon-pick": (
f"Undo a manual pick within {_MANUAL_GRACE_DAYS} days (needs app_id)"
),
"block-gaming": "Block ALL gaming for <days> days, no in-app undo",
}
@ -717,6 +976,10 @@ def main() -> None:
cmd_pick_manual(config, state, sys.argv[2:])
return
if command == "abandon-pick":
cmd_abandon_pick(config, state, sys.argv[2:])
return
_, func = COMMANDS[command]
func(config, state)

View File

@ -5,10 +5,20 @@ from __future__ import annotations
from datetime import datetime, timedelta, timezone
from unittest.mock import patch
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
@ -24,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 != ""
@ -70,6 +128,215 @@ 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(), 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_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_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_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_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_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_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(), 440) is False
class TestAbandonManualPick:
def _state(self, *, picks: list[dict] | None = None) -> State:
picks = picks if picks is not None else [_pick()]
return State(
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._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._state()
abandon_manual_pick(state, 440)
expiry = datetime.fromisoformat(state.skipped_until["440"])
expected = datetime.now(timezone.utc) + timedelta(
days=_actions.ABANDON_COOLDOWN_DAYS
)
assert abs((expiry - expected).total_seconds()) < 60
def test_persists_to_disk(self) -> 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._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_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 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, 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(

View File

@ -16,7 +16,6 @@ from steam_backlog_enforcer._enforce_loop import (
get_all_owned_app_ids,
)
from steam_backlog_enforcer.config import Config, State
from steam_backlog_enforcer.library_hider import SteamUnavailableError
if TYPE_CHECKING:
from pathlib import Path
@ -224,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 (
@ -241,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 (
@ -251,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:
@ -349,7 +348,7 @@ class TestEnforceHideGames:
state = State(current_app_id=1)
with (
patch(f"{PKG}.get_all_owned_app_ids", return_value=[1, 2, 3]),
patch(f"{PKG}.hide_other_games", return_value=2),
patch(f"{PKG}.try_hide_other_games", return_value=(2, None)),
patch(f"{PKG}._echo"),
):
_enforce_hide_games(Config(), state)
@ -358,7 +357,7 @@ class TestEnforceHideGames:
state = State(current_app_id=1)
with (
patch(f"{PKG}.get_all_owned_app_ids", return_value=[1, 2]),
patch(f"{PKG}.hide_other_games", return_value=0),
patch(f"{PKG}.try_hide_other_games", return_value=(0, None)),
patch(f"{PKG}._echo") as mock_echo,
):
_enforce_hide_games(Config(), state)
@ -384,8 +383,8 @@ class TestEnforceHideGames:
with (
patch(f"{PKG}.get_all_owned_app_ids", return_value=[1, 2, 3]),
patch(
f"{PKG}.hide_other_games",
side_effect=SteamUnavailableError("Steam is not installed"),
f"{PKG}.try_hide_other_games",
return_value=(0, "Steam is not installed"),
),
patch(f"{PKG}._echo") as mock_echo,
):

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

@ -8,12 +8,15 @@ from unittest.mock import MagicMock, patch
from steam_backlog_enforcer.library_hider import (
_SPAWNED,
SteamUnavailableError,
SteamUpdateInProgressError,
_reap_spawned,
_resolve_desktop_user,
_run_as_user,
hide_other_games,
restart_steam,
steam_is_installed,
try_hide_other_games,
unhide_all_games,
)
@ -251,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:
@ -268,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:
@ -285,10 +288,41 @@ class TestHideOtherGames:
return_value='{"totalHidden": 2}',
),
):
count = hide_other_games([1, 2], None)
count = hide_other_games([1, 2], set())
assert count == 2
class TestTryHideOtherGames:
"""Tests for the graceful wrapper around hide_other_games.
Regression guard: an unreachable Steam (or a deferred restart while a game
update is in flight) used to escape as a traceback out of every
interactive command that reconciles the library.
"""
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)
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})
assert hidden == 0
assert reason == "Steam is not installed"
def test_update_in_progress_is_reported_not_raised(self) -> None:
with patch(
f"{PKG}.hide_other_games",
side_effect=SteamUpdateInProgressError("update in progress"),
):
hidden, reason = try_hide_other_games([1, 2], {1})
assert hidden == 0
assert reason == "update in progress"
class TestUnhideAllGames:
"""Tests for unhide_all_games."""

View File

@ -342,7 +342,7 @@ class TestCmdHide:
state = State(current_app_id=1, current_game_name="G")
with (
patch(f"{PKG}.get_all_owned_app_ids", return_value=[1, 2]),
patch(f"{PKG}.hide_other_games", return_value=1),
patch(f"{PKG}.try_hide_other_games", return_value=(1, None)),
patch(f"{PKG}._echo"),
):
cmd_hide(Config(), state)
@ -351,11 +351,28 @@ class TestCmdHide:
state = State(current_app_id=1, current_game_name="G")
with (
patch(f"{PKG}.get_all_owned_app_ids", return_value=[1]),
patch(f"{PKG}.hide_other_games", return_value=0),
patch(f"{PKG}.try_hide_other_games", return_value=(0, None)),
patch(f"{PKG}._echo"),
):
cmd_hide(Config(), state)
def test_unreachable_steam_reports_skip(self) -> None:
# Regression guard: a deferred Steam restart used to escape as a
# traceback instead of degrading to a skip message.
state = State(current_app_id=1, current_game_name="G")
with (
patch(f"{PKG}.get_all_owned_app_ids", return_value=[1, 2]),
patch(
f"{PKG}.try_hide_other_games",
return_value=(0, "update in progress"),
),
patch(f"{PKG}._echo") as mock_echo,
):
cmd_hide(Config(), state)
output = " ".join(str(c) for c in mock_echo.call_args_list)
assert "skipped (update in progress)" in output
assert "Hidden" not in output
class TestCmdUnhide:
"""Tests for cmd_unhide."""

View File

@ -46,7 +46,7 @@ class TestFinalizeCompletion:
patch(f"{CMD_DONE_PKG}.load_snapshot", return_value=snap),
patch(f"{CMD_DONE_PKG}.pick_next_game") as mock_pick,
patch(f"{CMD_DONE_PKG}.get_all_owned_app_ids", return_value=[1, 2, 3]),
patch(f"{CMD_DONE_PKG}.hide_other_games", return_value=2),
patch(f"{CMD_DONE_PKG}.try_hide_other_games", return_value=(2, None)),
patch(f"{CMD_DONE_PKG}.send_notification"),
patch.object(State, "save"),
):
@ -64,6 +64,41 @@ class TestFinalizeCompletion:
_finalize_completion(config, state, "G", 1)
assert 1 in state.finished_app_ids
def test_hide_skipped_when_steam_unreachable(self) -> None:
# Reconciliation is best-effort: an undrivable Steam must not abort
# the completion flow.
config = Config(steam_api_key="k", steam_id="i")
state = State(current_app_id=1, current_game_name="G")
snap = [_snap(2, "NewGame", 10, 0, 5.0)]
with (
patch(f"{CMD_DONE_PKG}._echo") as mock_echo,
patch(f"{CMD_DONE_PKG}.load_snapshot", return_value=snap),
patch(f"{CMD_DONE_PKG}.pick_next_game") as mock_pick,
patch(f"{CMD_DONE_PKG}.get_all_owned_app_ids", return_value=[1, 2, 3]),
patch(
f"{CMD_DONE_PKG}.try_hide_other_games",
return_value=(0, "update in progress"),
),
patch(f"{CMD_DONE_PKG}.is_game_installed", return_value=True),
patch(f"{CMD_DONE_PKG}.send_notification"),
patch.object(State, "save"),
):
def set_next(
_games: object,
s: State,
_c: object,
**_kwargs: object,
) -> None:
s.current_app_id = 2
s.current_game_name = "NewGame"
mock_pick.side_effect = set_next
_finalize_completion(config, state, "G", 1)
assert "skipped (update in progress)" in " ".join(
str(c) for c in mock_echo.call_args_list
)
def test_no_snapshot(self) -> None:
config = Config()
state = State(current_app_id=1, current_game_name="G")
@ -131,7 +166,7 @@ class TestFinalizeCompletion:
patch(f"{CMD_DONE_PKG}.load_snapshot", return_value=snap),
patch(f"{CMD_DONE_PKG}.pick_next_game") as mock_pick,
patch(f"{CMD_DONE_PKG}.get_all_owned_app_ids", return_value=[1, 2]),
patch(f"{CMD_DONE_PKG}.hide_other_games", return_value=0),
patch(f"{CMD_DONE_PKG}.try_hide_other_games", return_value=(0, None)),
patch(f"{CMD_DONE_PKG}.send_notification"),
patch.object(State, "save"),
):
@ -206,7 +241,7 @@ class TestFinalizeCompletion:
patch(f"{CMD_DONE_PKG}.load_snapshot", return_value=snap),
patch(f"{CMD_DONE_PKG}.pick_next_game", side_effect=set_next),
patch(f"{CMD_DONE_PKG}.get_all_owned_app_ids", return_value=[1, 2]),
patch(f"{CMD_DONE_PKG}.hide_other_games", return_value=1),
patch(f"{CMD_DONE_PKG}.try_hide_other_games", return_value=(1, None)),
patch(f"{CMD_DONE_PKG}.is_game_installed", return_value=False),
patch(f"{CMD_DONE_PKG}.install_game") as mock_install,
patch(f"{CMD_DONE_PKG}.send_notification"),
@ -236,7 +271,7 @@ class TestFinalizeCompletion:
patch(f"{CMD_DONE_PKG}.load_snapshot", return_value=snap),
patch(f"{CMD_DONE_PKG}.pick_next_game", side_effect=set_next),
patch(f"{CMD_DONE_PKG}.get_all_owned_app_ids", return_value=[1, 2]),
patch(f"{CMD_DONE_PKG}.hide_other_games", return_value=1),
patch(f"{CMD_DONE_PKG}.try_hide_other_games", return_value=(1, None)),
patch(f"{CMD_DONE_PKG}.is_game_installed", return_value=True),
patch(f"{CMD_DONE_PKG}.install_game") as mock_install,
patch(f"{CMD_DONE_PKG}.send_notification"),
@ -268,7 +303,7 @@ class TestEnforceOnDone:
patch(f"{CMD_DONE_PKG}.uninstall_other_games", return_value=2),
patch(f"{CMD_DONE_PKG}.is_game_installed", return_value=True),
patch(f"{CMD_DONE_PKG}.get_all_owned_app_ids", return_value=[1, 2]),
patch(f"{CMD_DONE_PKG}.hide_other_games", return_value=1),
patch(f"{CMD_DONE_PKG}.try_hide_other_games", return_value=(1, None)),
):
_enforce_on_done(config, state)
@ -284,10 +319,27 @@ class TestEnforceOnDone:
patch(f"{CMD_DONE_PKG}.uninstall_other_games", return_value=0),
patch(f"{CMD_DONE_PKG}.is_game_installed", return_value=True),
patch(f"{CMD_DONE_PKG}.get_all_owned_app_ids", return_value=[]),
patch(f"{CMD_DONE_PKG}.hide_other_games", return_value=0),
patch(f"{CMD_DONE_PKG}.try_hide_other_games", return_value=(0, None)),
):
_enforce_on_done(config, state)
def test_hide_skipped_when_steam_unreachable(self) -> None:
config = Config(kill_unauthorized_games=False, uninstall_other_games=False)
state = State(current_app_id=1, current_game_name="G")
with (
patch(f"{CMD_DONE_PKG}._echo") as mock_echo,
patch(f"{CMD_DONE_PKG}.is_game_installed", return_value=True),
patch(f"{CMD_DONE_PKG}.get_all_owned_app_ids", return_value=[1, 2]),
patch(
f"{CMD_DONE_PKG}.try_hide_other_games",
return_value=(0, "Steam is not installed"),
),
):
_enforce_on_done(config, state)
assert "skipped (Steam is not installed)" in " ".join(
str(c) for c in mock_echo.call_args_list
)
def test_reinstall_when_not_installed(self) -> None:
config = Config(
kill_unauthorized_games=False,
@ -300,7 +352,7 @@ class TestEnforceOnDone:
patch(f"{CMD_DONE_PKG}.is_game_installed", return_value=False),
patch(f"{CMD_DONE_PKG}.install_game") as mock_install,
patch(f"{CMD_DONE_PKG}.get_all_owned_app_ids", return_value=[1, 2]),
patch(f"{CMD_DONE_PKG}.hide_other_games", return_value=0),
patch(f"{CMD_DONE_PKG}.try_hide_other_games", return_value=(0, None)),
):
_enforce_on_done(config, state)
mock_install.assert_called_once_with(1, "G", "s1", use_steam_protocol=True)

View File

@ -240,11 +240,11 @@ class TestCmdPick:
patch(f"{PKG}.load_hltb_cache", return_value={2: 5.0}),
patch(f"{PKG}.pick_next_game"),
patch(f"{PKG}.get_all_owned_app_ids", return_value=[1, 2, 3]),
patch(f"{PKG}.hide_other_games", return_value=2) as mock_hide,
patch(f"{PKG}.try_hide_other_games", return_value=(2, None)) as mock_hide,
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)]
@ -254,12 +254,30 @@ class TestCmdPick:
patch(f"{PKG}.load_hltb_cache", return_value={}),
patch(f"{PKG}.pick_next_game"),
patch(f"{PKG}.get_all_owned_app_ids", return_value=[1, 2, 3]),
patch(f"{PKG}.hide_other_games", return_value=0),
patch(f"{PKG}.try_hide_other_games", return_value=(0, None)),
patch(f"{PKG}._echo") as mock_echo,
):
cmd_pick(Config(steam_api_key="k", steam_id="i"), state)
mock_echo.assert_not_called()
def test_unreachable_steam_reports_skip(self) -> None:
snap = [_snap(2, "NewGame", 10, 0, 5.0)]
state = State(current_app_id=2, current_game_name="NewGame")
with (
patch(f"{PKG}.load_snapshot", return_value=snap),
patch(f"{PKG}.load_hltb_cache", return_value={}),
patch(f"{PKG}.pick_next_game"),
patch(f"{PKG}.get_all_owned_app_ids", return_value=[1, 2, 3]),
patch(
f"{PKG}.try_hide_other_games",
return_value=(0, "Steam is not installed"),
),
patch(f"{PKG}._echo") as mock_echo,
):
cmd_pick(Config(steam_api_key="k", steam_id="i"), state)
output = " ".join(str(c) for c in mock_echo.call_args_list)
assert "skipped (Steam is not installed)" in output
def test_no_hide_when_no_current_app(self) -> None:
snap = [_snap(2, "NewGame", 10, 0, 5.0)]
with (
@ -279,7 +297,7 @@ class TestCmdPick:
patch(f"{PKG}.load_hltb_cache", return_value={}),
patch(f"{PKG}.pick_next_game"),
patch(f"{PKG}.get_all_owned_app_ids", return_value=[]),
patch(f"{PKG}.hide_other_games") as mock_hide,
patch(f"{PKG}.try_hide_other_games") as mock_hide,
):
cmd_pick(Config(steam_api_key="k", steam_id="i"), state)
mock_hide.assert_not_called()

View File

@ -10,11 +10,13 @@ import pytest
from steam_backlog_enforcer.config import Config, State
from steam_backlog_enforcer.main import (
_MANUAL_GRACE_DAYS,
_MANUAL_LOCK_DAYS,
_enforce_manual_pick_lock,
_is_manual_pick_locked,
_resolve_game_name,
_show_manual_pick_lock_message,
cmd_abandon_pick,
cmd_pick_manual,
cmd_status,
main,
@ -37,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}],
)
@ -138,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())
# ──────────────────────────────────────────────────────────────
@ -221,7 +218,7 @@ class TestCmdPickManual:
f"{PKG}.is_game_installed": False,
f"{PKG}.install_game": None,
f"{PKG}.get_all_owned_app_ids": [1, 2, 489830],
f"{PKG}.hide_other_games": 2,
f"{PKG}.try_hide_other_games": (2, None),
}
def test_invalid_app_id(self) -> None:
@ -275,16 +272,16 @@ class TestCmdPickManual:
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=[1, 489830]),
patch(f"{PKG}.hide_other_games", return_value=1) as mock_hide,
patch(f"{PKG}.try_hide_other_games", return_value=(1, None)) as mock_hide,
):
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()
@ -328,7 +325,7 @@ class TestCmdPickManual:
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=[]),
patch(f"{PKG}.hide_other_games") as mock_hide,
patch(f"{PKG}.try_hide_other_games") as mock_hide,
):
cmd_pick_manual(Config(), state, ["489830"])
mock_hide.assert_not_called()
@ -388,12 +385,35 @@ class TestCmdPickManual:
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=[1, 2]),
patch(f"{PKG}.hide_other_games", return_value=0),
patch(f"{PKG}.try_hide_other_games", return_value=(0, None)),
):
cmd_pick_manual(Config(), state, ["489830"])
output = " ".join(str(c) for c in mock_echo.call_args_list)
assert "Library: hid" not in output
def test_unreachable_steam_reports_skip(self) -> None:
# The pick itself must survive a Steam that cannot be driven: this
# used to abort cmd_pick_manual with a traceback after the pick had
# already been saved.
state = State()
with (
patch(f"{PKG}._resolve_game_name", return_value="Skyrim SE"),
patch(f"{PKG}._echo") as mock_echo,
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=[1, 2]),
patch(
f"{PKG}.try_hide_other_games",
return_value=(0, "update in progress"),
),
):
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 [p["app_id"] for p in state.manual_picks] == [489830]
# ──────────────────────────────────────────────────────────────
# main() dispatch to pick-manual
@ -412,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()
# ──────────────────────────────────────────────────────────────
@ -452,3 +471,320 @@ class TestCmdStatusLockHint:
cmd_status(Config(), State())
output = " ".join(str(c) for c in mock_echo.call_args_list)
assert "MANUAL PICK LOCK" not in output
# ──────────────────────────────────────────────────────────────
# cmd_abandon_pick (grace period escape hatch)
# ──────────────────────────────────────────────────────────────
# Inside the 4-day grace window / already past it.
_IN_GRACE = (datetime.now(timezone.utc) - timedelta(days=1)).isoformat()
_PAST_GRACE = (
datetime.now(timezone.utc) - timedelta(days=_MANUAL_GRACE_DAYS + 1)
).isoformat()
def _abandonable_state(app_id: int = 100, started_at: str = _IN_GRACE) -> State:
state = _locked_state(app_id=app_id, started_at=started_at)
state.current_app_id = app_id
state.current_game_name = state.manual_pick_game_name
return state
class TestCmdAbandonPick:
def test_no_args_exits(self) -> None:
with patch(f"{PKG}._echo") as mock_echo, pytest.raises(SystemExit) as exc:
cmd_abandon_pick(Config(), _abandonable_state(), [])
assert exc.value.code == 1
assert "Usage" in " ".join(str(c) for c in mock_echo.call_args_list)
def test_non_numeric_app_id_exits(self) -> None:
with patch(f"{PKG}._echo") as mock_echo, pytest.raises(SystemExit):
cmd_abandon_pick(Config(), _abandonable_state(), ["abc"])
assert "must be a number" in " ".join(str(c) for c in mock_echo.call_args_list)
def test_no_active_pick_exits(self) -> None:
with patch(f"{PKG}._echo") as mock_echo, pytest.raises(SystemExit):
cmd_abandon_pick(Config(), State(), ["100"])
assert "No manual pick" in " ".join(str(c) for c in mock_echo.call_args_list)
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 one of your manual picks" in " ".join(
str(c) for c in mock_echo.call_args_list
)
def test_expired_grace_exits_without_mutating(self) -> None:
state = _abandonable_state(started_at=_PAST_GRACE)
with (
patch(f"{PKG}._echo") as mock_echo,
patch.object(State, "save") as mock_save,
pytest.raises(SystemExit) as exc,
):
cmd_abandon_pick(Config(), state, ["100"])
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 [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")
with patch(f"{PKG}._echo"), pytest.raises(SystemExit):
cmd_abandon_pick(Config(), state, ["100"])
def test_aborted_when_not_yes(self) -> None:
state = _abandonable_state()
with (
patch(f"{PKG}._echo"),
patch("builtins.input", return_value="no"),
patch.object(State, "save") as mock_save,
patch(f"{PKG}.uninstall_game") as mock_uninstall,
):
cmd_abandon_pick(Config(), state, ["100"])
mock_save.assert_not_called()
mock_uninstall.assert_not_called()
assert [p["app_id"] for p in state.manual_picks] == [100]
def test_success_clears_lock_and_uninstalls(self) -> None:
state = _abandonable_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=True),
patch(f"{PKG}.uninstall_game", return_value=True) as mock_uninstall,
):
cmd_abandon_pick(Config(), state, ["100"])
assert state.manual_picks == []
assert state.current_app_id is None
assert state.skipped_until["100"] != ""
mock_uninstall.assert_called_once_with(100, "TestGame")
assert "abandoned" in " ".join(str(c) for c in mock_echo.call_args_list)
def test_skips_uninstall_when_not_installed(self) -> None:
state = _abandonable_state()
with (
patch(f"{PKG}._echo"),
patch("builtins.input", return_value="YES"),
patch.object(State, "save"),
patch(f"{PKG}.is_game_installed", return_value=False),
patch(f"{PKG}.uninstall_game") as mock_uninstall,
):
cmd_abandon_pick(Config(), state, ["100"])
mock_uninstall.assert_not_called()
def test_warns_when_uninstall_fails(self) -> None:
state = _abandonable_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=True),
patch(f"{PKG}.uninstall_game", return_value=False),
):
cmd_abandon_pick(Config(), state, ["100"])
assert "Warning" in " ".join(str(c) for c in mock_echo.call_args_list)
def test_race_between_check_and_apply_exits(self) -> None:
# The grace check passes, then the state-only core refuses: defensive
# branch that must exit rather than report a false success.
state = _abandonable_state()
with (
patch(f"{PKG}._echo") as mock_echo,
patch("builtins.input", return_value="YES"),
patch(f"{PKG}.abandon_manual_pick", return_value=False),
pytest.raises(SystemExit) as exc,
):
cmd_abandon_pick(Config(), state, ["100"])
assert exc.value.code == 1
assert "grace period closed" in " ".join(
str(c) for c in mock_echo.call_args_list
)
class TestAbandonPickLockInteraction:
def test_abandon_pick_is_exempt_from_the_lock(self) -> None:
# The escape hatch must survive the pre-dispatch lock check.
_enforce_manual_pick_lock("abandon-pick", _locked_state())
def test_main_dispatches_abandon_pick_while_locked(self) -> None:
argv = ["prog", "abandon-pick", "100"]
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=_abandonable_state()),
patch(f"{PKG}.cmd_abandon_pick") as mock_cmd,
):
main()
mock_cmd.assert_called_once()
def test_lock_message_advertises_abandon_within_grace(self) -> None:
state = _abandonable_state(started_at=_IN_GRACE)
with patch(f"{PKG}._echo") as mock_echo:
_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 day(s) left" in output
def test_lock_message_hides_abandon_after_grace(self) -> None:
state = _abandonable_state(started_at=_PAST_GRACE)
with patch(f"{PKG}._echo") as mock_echo:
_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

@ -7,9 +7,11 @@ already-tested leaf functions.
from __future__ import annotations
from datetime import datetime, timedelta, timezone
from unittest.mock import patch
from steam_backlog_enforcer import _mcp
from steam_backlog_enforcer.config import State
from steam_backlog_enforcer.steam_api import GameInfo
@ -168,12 +170,86 @@ 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:
"""The MCP escape hatch mirrors the CLI grace rules, state-only."""
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_picks=[
{"app_id": app_id, "game_name": "TF2", "started_at": started}
],
current_app_id=app_id,
current_game_name="TF2",
)
def test_no_active_pick(self) -> None:
with patch.object(_mcp.State, "load", return_value=State()):
out = _mcp.abandon_pick(440)
assert out["ok"] is False
assert "No manual pick" in out["reason"]
def test_wrong_app_id(self) -> None:
with patch.object(_mcp.State, "load", return_value=self._state()):
out = _mcp.abandon_pick(999)
assert out["ok"] is False
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)
with patch.object(_mcp.State, "load", return_value=state):
out = _mcp.abandon_pick(440)
assert out["ok"] is False
assert "grace period has expired" in out["reason"]
def test_preview_does_not_mutate(self) -> None:
with (
patch.object(_mcp.State, "load", return_value=self._state()),
patch.object(_mcp, "abandon_manual_pick") as amp,
):
out = _mcp.abandon_pick(440)
assert out["preview"] is True
assert out["game_name"] == "TF2"
assert out["grace_days_left"] > 0
amp.assert_not_called()
def test_confirm_applies(self) -> None:
state = self._state()
with (
patch.object(_mcp.State, "load", return_value=state),
patch.object(_mcp, "abandon_manual_pick") as amp,
):
out = _mcp.abandon_pick(440, confirm=True)
assert out["applied"] is True
assert out["app_id"] == 440
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: