# Now Playing Games Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. **Goal:** The Dashboard's music card shows the running game (Steam, PCSX2, DuckStation on the PC, or the Xbox) instead of the track. **Architecture:** New module `deckit/modules/games.py` finds a PC game among Hyprland's windows and reads name, cover and playtime from the launcher's own files. The dashboard polls `games`, `xbox` and `music`; `music.js` picks a game with `pickGame()` and shows it in place of the music view. **Tech Stack:** Python 3.11 stdlib, plain JS modules, `node` for the `.mjs` checks. Spec: `docs/superpowers/specs/2026-11-18-now-playing-games-design.md`. Run all tests: `python3 -m unittest discover -s tests` (runs the `.mjs` checks too). --- ### Task 1: Parsers (VDF and emulator game list cache) **Files:** - Create: `deckit/modules/games.py` - Test: `tests/test_games.py` - [ ] **Step 1: Write the failing test** `tests/test_games.py`: ```python # deck-it - tests for games # Copyright (C) 2026 Danilo M. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) import unittest import deckit.modules.games as games def lp(s: str) -> bytes: """A gamelist.cache string: little-endian u32 length, then the bytes.""" b = s.encode() return len(b).to_bytes(4, "little") + b def cache(*entries) -> bytes: """A gamelist.cache with (path, serial, title) entries and junk between.""" return b'GLCE"\0\0\0' + b"".join(lp(p) + lp(s) + lp(t) + b"\x01\x02\0\0\x9f" for p, s, t in entries) class Parsers(unittest.TestCase): def test_vdf_nested(self): d = games.vdf('"A"\n{\n\t"name"\t\t"Game \\"X\\""\n\t"apps"\n\t{\n\t\t"10"\t"1"\n\t}\n}\n') self.assertEqual(d, {"A": {"name": 'Game \\"X\\"', "apps": {"10": "1"}}}) def test_get_ignores_case(self): self.assertEqual(games._get({"Software": {"valve": {"x": "1"}}}, "software", "Valve", "x"), "1") self.assertIsNone(games._get({"a": "1"}, "a", "b")) def test_cache_serials(self): data = cache(("/g/A (Europe).cue", "SCES-01615", "A (Europe)"), ("/g/B.iso", "SLES-53559", "B - Most Wanted")) self.assertEqual(games.cache_serials(data), {"A (Europe)": "SCES-01615", "B - Most Wanted": "SLES-53559"}) def test_cache_serials_garbage(self): self.assertEqual(games.cache_serials(b"\xff" * 64), {}) if __name__ == "__main__": unittest.main() ``` - [ ] **Step 2: Run test to verify it fails** Run: `python3 -m unittest tests.test_games -v` Expected: FAIL, `ModuleNotFoundError: No module named 'deckit.modules.games'` - [ ] **Step 3: Write minimal implementation** `deckit/modules/games.py`: ```python # deck-it - games module # Copyright (C) 2026 Danilo M. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """Now playing for PC games: Steam, PCSX2 and DuckStation. The game is the first Hyprland window that is one. Its name, cover and total playtime come from the launcher's own files, so no account is needed. """ import re def vdf(text: str) -> dict: """Valve's KeyValues text: "key" "value" pairs and "key" { ... } blocks.""" root, stack, key = {}, [], None cur = root for m in re.finditer(r'"((?:[^"\\]|\\.)*)"|([{}])', text): s, brace = m.groups() if brace == "{": new = {} cur[key] = new stack.append(cur) cur, key = new, None elif brace == "}": cur, key = (stack.pop() if stack else cur), None elif key is None: key = s else: cur[key], key = s, None return root def _get(d, *keys): """d[k1][k2]..., keys matched without case (KeyValues ignores it).""" for k in keys: if not isinstance(d, dict): return None d = next((v for kk, v in d.items() if kk.lower() == k.lower()), None) return d def _lstr(data: bytes, i: int): """The length-prefixed string at i and the offset after it, or (None, i).""" if i + 4 > len(data): return None, i n = int.from_bytes(data[i:i + 4], "little") if not 0 < n <= 4096 or i + 4 + n > len(data): return None, i try: return data[i + 4:i + 4 + n].decode(), i + 4 + n except UnicodeDecodeError: return None, i def cache_serials(data: bytes) -> dict: """title -> serial from an emulator's cache/gamelist.cache, whose entries (PCSX2 and DuckStation alike) start with path, serial and title strings.""" out = {} for i in range(len(data) - 5): if data[i + 4] != 0x2F: # an entry's path starts with "/" continue path, j = _lstr(data, i) if not path: continue serial, j = _lstr(data, j) title, _ = _lstr(data, j) if serial and title: out.setdefault(title, serial) return out ``` - [ ] **Step 4: Run test to verify it passes** Run: `python3 -m unittest tests.test_games -v` Expected: 4 tests OK - [ ] **Step 5: Commit** ```bash git add deckit/modules/games.py tests/test_games.py git commit -m "feat(games): parse Steam VDF and emulator game list caches" ``` --- ### Task 2: Game lookup, detection and the module **Files:** - Modify: `deckit/modules/games.py` - Test: `tests/test_games.py` - [ ] **Step 1: Write the failing tests** Add to `tests/test_games.py`, after the `Parsers` class (add `import json`, `import tempfile` to the imports): ```python class Lookup(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() self.root = Path(self.tmp.name) def tearDown(self): self.tmp.cleanup() def put(self, rel, data): p = self.root / rel p.parent.mkdir(parents=True, exist_ok=True) (p.write_bytes if isinstance(data, bytes) else p.write_text)(data) return p def steam(self): steam = self.root / "Steam" other = self.root / "lib2" self.put("Steam/steamapps/libraryfolders.vdf", f'"libraryfolders"\n{{\n"0"\n{{\n"path" "{steam}"\n}}\n"1"\n{{\n"path" "{other}"\n}}\n}}\n') self.put("lib2/steamapps/appmanifest_217200.acf", '"AppState"\n{\n"appid" "217200"\n"name" "Worms"\n}\n') self.put("Steam/userdata/1/config/localconfig.vdf", '"UserLocalConfigStore"\n{\n"Software"\n{\n"Valve"\n{\n"Steam"\n{\n"apps"\n{\n' '"217200"\n{\n"Playtime" "125"\n}\n}\n}\n}\n}\n}\n') self.put("Steam/appcache/librarycache/217200/library_600x900.jpg", b"JPG") return steam def test_steam_game(self): g = games.steam_game(self.steam(), "217200") self.assertEqual((g["platform"], g["name"], g["minutes"]), ("steam", "Worms", 125)) self.assertEqual(g["cover"].name, "library_600x900.jpg") def test_steam_game_missing_files(self): g = games.steam_game(self.root / "nope", "1") self.assertEqual((g["name"], g["minutes"], g["cover"]), (None, None, None)) def emu(self): emu = self.root / "duck" self.put("duck/cache/gamelist.cache", cache(("/g/a.cue", "SCES-01615", "Cool Boarders 3 (Europe)"))) self.put("duck/playtime.dat", "SCES-01615 1006 1789987473\n") self.put("duck/covers/SCES-01615.jpg", b"JPG") return emu def test_emu_game(self): g = games.emu_game("ps1", self.emu(), "playtime.dat", "Cool Boarders 3 (Europe)") self.assertEqual((g["platform"], g["name"], g["minutes"]), ("ps1", "Cool Boarders 3 (Europe)", 16)) self.assertEqual(g["cover"].name, "SCES-01615.jpg") def test_emu_game_title_contains_cache_title(self): g = games.emu_game("ps1", self.emu(), "playtime.dat", "Cool Boarders 3 (Europe) [SCES-01615]") self.assertEqual(g["minutes"], 16) def test_emu_game_unknown(self): g = games.emu_game("ps1", self.emu(), "playtime.dat", "Other") self.assertEqual((g["name"], g["minutes"], g["cover"]), ("Other", None, None)) def test_detect(self): emu = {"duckstation": ("ps1", self.root, "p")} d = lambda *cs: games.detect([{"class": c, "title": t} for c, t in cs], emu) self.assertEqual(d(("kitty", "x"), ("steam_app_42", "Game")), ("steam", "42", "Game")) self.assertEqual(d(("duckstation-qt", "Cool Boarders")), ("duckstation", "Cool Boarders", "Cool Boarders")) self.assertIsNone(d(("duckstation-qt", "DuckStation 0.1-1234"))) self.assertIsNone(d(("steam", "Steam"))) def make(self, clients): emu = {"duckstation": ("ps1", self.emu(), "playtime.dat")} run = lambda cmd, timeout=2: json.dumps(clients[0]) return games.make({"run": run, "steam_root": self.steam(), "emulators": emu}) def test_state_and_cover(self): clients = [[{"class": "steam_app_217200", "title": "Worms W.M.D"}]] m = self.make(clients) st = m.state()["playing"] self.assertEqual((st["platform"], st["name"], st["minutes"]), ("steam", "Worms", 125)) self.assertIsInstance(st["session"], int) key = st["cover"].rsplit("/", 1)[1] self.assertEqual(m.image(key), (b"JPG", "image/jpeg")) self.assertIsNone(m.image("other")) self.assertEqual(m.state()["playing"]["session"], st["session"]) # same game, same session clients[0] = [] self.assertEqual(m.state(), {"playing": None}) self.assertIsNone(m.image(key)) def test_state_hyprctl_fails(self): m = self.make([""]) self.assertEqual(m.state(), {"playing": None}) ``` - [ ] **Step 2: Run tests to verify they fail** Run: `python3 -m unittest tests.test_games -v` Expected: FAIL, `AttributeError: module 'deckit.modules.games' has no attribute 'steam_game'` (and `emu_game`, `detect`, `make`) - [ ] **Step 3: Write the implementation** In `deckit/modules/games.py`, replace `import re` with: ```python import hashlib import json import re import subprocess import time from pathlib import Path from ..module import Module HOME = Path.home() STEAM = HOME / ".local/share/Steam" # window class substring -> (platform, data dir, playtime.dat in it) EMULATORS = { "pcsx2": ("ps2", HOME / ".config/PCSX2", "inis/playtime.dat"), "duckstation": ("ps1", HOME / ".local/share/duckstation", "playtime.dat"), } def _run(cmd, timeout=2): try: return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout).stdout.strip() except (OSError, subprocess.TimeoutExpired): return "" def _read(p: Path) -> str: try: return p.read_text(errors="replace") except OSError: return "" def _int(v): try: return int(v) except (TypeError, ValueError): return None ``` Append after `cache_serials`: ```python def _first_file(paths): return next((p for p in paths if p.is_file()), None) def steam_game(root: Path, appid: str) -> dict: libs = _get(vdf(_read(root / "steamapps/libraryfolders.vdf")), "libraryfolders") or {} dirs = [root] + [Path(v["path"]) for v in libs.values() if isinstance(v, dict) and v.get("path")] name = next((_get(vdf(acf), "AppState", "name") for acf in (_read(d / f"steamapps/appmanifest_{appid}.acf") for d in dirs) if acf), None) minutes = next((m for m in (_int(_get(vdf(_read(f)), "UserLocalConfigStore", "Software", "Valve", "Steam", "apps", appid, "Playtime")) for f in sorted(root.glob("userdata/*/config/localconfig.vdf"))) if m is not None), None) art = root / "appcache/librarycache" / appid return {"platform": "steam", "name": name, "minutes": minutes, "cover": _first_file([art / "library_600x900.jpg", art / "header.jpg"])} def emu_game(platform: str, root: Path, playtime: str, title: str) -> dict: try: serials = cache_serials((root / "cache/gamelist.cache").read_bytes()) except OSError: serials = {} # ponytail: the window title names the game; a title that only contains a # cache title (an emulator adding the serial or a version) takes the longest. serial = serials.get(title) or next( (serials[t] for t in sorted(serials, key=len, reverse=True) if t in title), None) minutes = None if serial: for line in _read(root / playtime).splitlines(): f = line.split() if len(f) >= 2 and f[0] == serial and f[1].isdigit(): minutes = int(f[1]) // 60 covers = [root / "covers" / f"{stem}{ext}" for stem in filter(None, (serial, title)) for ext in (".jpg", ".png")] return {"platform": platform, "name": title, "minutes": minutes, "cover": _first_file(covers)} def detect(clients: list, emulators: dict): """(kind, arg, title) for the first window that is a game: kind "steam" with the app id, or an emulator key with the window title.""" for c in clients: cls, title = c.get("class") or "", c.get("title") or "" m = re.fullmatch(r"steam_app_(\d+)", cls) if m: return "steam", m[1], title for k in emulators: # the idle game list's title is the emulator's own name if k in cls.lower() and title and not title.lower().startswith(k): return k, title, title return None def make(cfg: dict) -> Module: run = cfg.get("run", _run) steam = Path(cfg.get("steam_root", STEAM)) emulators = cfg.get("emulators", EMULATORS) cur = {"id": None, "game": None, "session": None, "key": None} def state(): try: clients = json.loads(run(["hyprctl", "clients", "-j"]) or "[]") except ValueError: clients = [] found = detect(clients if isinstance(clients, list) else [], emulators) if found != cur["id"]: # ponytail: the session starts when deck-it first sees the game, as on the Xbox. game, key = None, None if found: kind, arg, title = found game = steam_game(steam, arg) if kind == "steam" else emu_game(*emulators[kind], title) game["name"] = game["name"] or title if game["cover"]: key = hashlib.sha1(str(game["cover"]).encode()).hexdigest()[:16] cur.update(id=found, game=game, key=key, session=int(time.time()) if found else None) g = cur["game"] if not g: return {"playing": None} return {"playing": {"platform": g["platform"], "name": g["name"], "minutes": g["minutes"], "cover": f"/api/games/image/{cur['key']}" if cur["key"] else None, "session": cur["session"]}} def image(key): g = cur["game"] if not g or not cur["key"] or key != cur["key"]: return None try: data = g["cover"].read_bytes() except OSError: return None return data, "image/png" if g["cover"].suffix == ".png" else "image/jpeg" return Module(name="games", title="Games", state=state, image=image) ``` - [ ] **Step 4: Run tests to verify they pass** Run: `python3 -m unittest tests.test_games -v` Expected: 12 tests OK - [ ] **Step 5: Commit** ```bash git add deckit/modules/games.py tests/test_games.py git commit -m "feat(games): find the PC game and its name, cover and playtime" ``` --- ### Task 3: The card shows the game **Files:** - Modify: `static/modules/music.js` - Modify: `static/dashboard.js:265-269` - Modify: `static/deck.css` (after line 716, the `.dash-music` rules) - Test: `tests/test_music.mjs` - [ ] **Step 1: Write the failing test** `tests/test_music.mjs`: ```js // deck-it - node checks for the music card's game pick // Copyright (C) 2026 Danilo M. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import assert from "node:assert/strict"; import { pickGame, hours } from "../static/modules/music.js"; const pc = { playing: { platform: "steam", name: "Worms", cover: null, minutes: 5, session: 100 } }; const xbox = { playing: { id: "7", name: "Forza" }, session: 200, titles: [{ id: "7", cover: "https://x/c.png", minutes: 90 }] }; assert.equal(pickGame(null, null), null); assert.equal(pickGame({ playing: null }, { playing: null }), null); assert.deepEqual(pickGame(pc, xbox), pc.playing); assert.deepEqual(pickGame({ playing: null }, xbox), { platform: "xbox", name: "Forza", cover: "https://x/c.png", minutes: 90, session: 200 }); assert.deepEqual(pickGame(undefined, { playing: { id: "8", name: "New" }, session: 1 }), { platform: "xbox", name: "New", cover: null, minutes: null, session: 1 }); assert.equal(hours(0), "0m"); assert.equal(hours(59), "59m"); assert.equal(hours(125), "2h 05m"); console.log("music ok"); ``` - [ ] **Step 2: Run test to verify it fails** Run: `node tests/test_music.mjs` Expected: FAIL, `SyntaxError: The requested module '../static/modules/music.js' does not provide an export named ...` - [ ] **Step 3: Implement** In `static/modules/music.js`, after the `clock` function add: ```js // Minutes as "2h 05m", or "59m" under an hour. export function hours(min) { min = Math.max(0, Math.floor(min || 0)); return min < 60 ? `${min}m` : `${Math.floor(min / 60)}h ${String(min % 60).padStart(2, "0")}m`; } // The game the card shows instead of the music, from /api/games and // /api/xbox: a PC game first, then the Xbox's. export function pickGame(pc, xbox) { if (pc?.playing) return pc.playing; const g = xbox?.playing; if (!g) return null; const t = (xbox.titles ?? []).find((x) => x.id === g.id); return { platform: "xbox", name: g.name, cover: t?.cover ?? null, minutes: t?.minutes ?? null, session: xbox.session }; } const PLATFORM = { steam: "Steam", ps1: "PlayStation", ps2: "PlayStation 2", xbox: "Xbox" }; ``` In `mount(el)`, change the template's first line from `
` so the markup becomes (the music part unchanged, the game part added after it): ```js el.innerHTML = `
♪
Nothing playing
0:00
`; ``` Then the existing `el.querySelector(".controls")`, `.vol`, `.seek` lookups still hit the music part, since it comes first. Change `update(st, el)` to `update(st, el, game = null)` and put this at its top: ```js const [musicEl, gameEl] = el.querySelectorAll(":scope > .music"); musicEl.hidden = Boolean(game); gameEl.hidden = !game; if (game) { const img = gameEl.querySelector("img.art"); img.hidden = !game.cover; gameEl.querySelector(".art.empty").hidden = Boolean(game.cover); if (game.cover && img.getAttribute("src") !== game.cover) img.src = game.cover; gameEl.querySelector(".plat").textContent = PLATFORM[game.platform] ?? ""; gameEl.querySelector(".title").textContent = game.name ?? ""; const session = game.session ? (Date.now() / 1000 - game.session) / 60 : 0; gameEl.querySelector(".times").textContent = game.minutes != null ? `${hours(session)} now · ${hours(game.minutes + session)} total` : `${hours(session)} now`; return; } ``` The rest of `update` stays, but its lookups of `.art`, `img.art`, `.title`, `.artist`, `.album` must be scoped to `musicEl` (the game part has the same classes). Replace `el.querySelector(` with `musicEl.querySelector(` everywhere inside `update` below the block above. In `static/dashboard.js`, replace lines 265-269: ```js if (on.has("music")) import("./modules/music.js").then(({ default: music, pickGame }) => { const el = $(".dash-music"); music.mount(el); // The card shows a running game (PC or Xbox) instead of the music. const last = { music: {}, games: null, xbox: null }; const draw = () => music.update(last.music, el, pickGame(last.games, last.xbox)); poll("music", music.interval ?? 2, (st) => { last.music = st; draw(); }); if (on.has("games")) poll("games", 5, (st) => { last.games = st; draw(); }); if (on.has("xbox")) poll("xbox", 30, (st) => { last.xbox = st; draw(); }); }); ``` In `static/deck.css`, after the `.dash-music .music .vol` rule: ```css .music[hidden], .music [hidden] { display: none; } /* .art.empty sets display: flex */ .music.game .times { display: block; color: var(--udt-subtext0); } .dash-music .music.game .art { width: 72px; height: 96px; } ``` (`.dash-music .music .album { display: none; }` hides the album line in the card; the `.times` rule above shows it again for the game, and the `.music .top` / `.music .art` rules already style the rest.) - [ ] **Step 4: Run checks** Run: `node tests/test_music.mjs && node --check static/modules/music.js && node --check static/dashboard.js && python3 -m unittest discover -s tests` Expected: `music ok`, no syntax errors, all tests OK - [ ] **Step 5: Commit** ```bash git add static/modules/music.js static/dashboard.js static/deck.css tests/test_music.mjs git commit -m "feat(dashboard): the music card shows the game being played" ``` --- ### Task 4: Config flag and docs **Files:** - Modify: `config.toml` (`[modules]`) - Modify: `AGENTS.md` (after the `music` bullet) - [ ] **Step 1: Add the flag** In `config.toml` `[modules]`, after `music = true`: ```toml games = true ``` - [ ] **Step 2: Document** In `AGENTS.md`, after the bullet starting "`music` drives any MPRIS player", add: ```markdown - `games` finds a PC game among `hyprctl clients`: class `steam_app_`, or `pcsx2`/`duckstation` with a window title other than the emulator's name. Steam's name, cover and minutes come from its appmanifest, librarycache and localconfig.vdf; an emulator's from the title, matched in its `cache/gamelist.cache` for the serial, then `covers/` and `playtime.dat`. The cover is served at `/api/games/image/`, current game only. The Dashboard's music card (`music.js` `pickGame`) shows a PC game, else the Xbox's `playing`, instead of the track. ``` - [ ] **Step 3: Run the suite** Run: `python3 -m unittest discover -s tests` Expected: all OK - [ ] **Step 4: Commit** ```bash git add config.toml AGENTS.md git commit -m "docs: the games module and the now playing card" ``` - [ ] **Step 5: Manual check (user)** Restart deck-it, start a Steam game, then a PS1 game in DuckStation and a PS2 game in PCSX2: the card shows cover, name, platform, session and total. Close the game: music returns. Start an Xbox game: the card shows it within 30s.