aboutsummaryrefslogtreecommitdiffstats
path: root/docs/superpowers/plans/2026-11-18-now-playing-games.md
blob: 3904968d59959e55c3a82dda9a6f5da87c7881be (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
# 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. <danix@danix.xyz>
#
# 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. <danix@danix.xyz>
#
# 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. <danix@danix.xyz>
//
// 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 `      <div class="music">` so the markup becomes (the music part unchanged, the game part added after it):

```js
    el.innerHTML = `
      <div class="music">
        <div class="top">
          <div class="art empty">♪</div>
          <div class="meta">
            <div class="title">Nothing playing</div>
            <div class="artist muted"></div>
            <div class="album muted"></div>
          </div>
        </div>
        <div class="seek">
          <input type="range" min="0" max="1" step="1" value="0" aria-label="Seek">
          <span class="time num">0:00</span>
        </div>
        <div class="controls">
          <div class="vol">
            <input type="range" min="0" max="100" step="1" value="0" aria-label="Volume">
            <span class="level num"></span>
          </div>
        </div>
      </div>
      <div class="music game" hidden>
        <div class="top">
          <img class="art" alt="" hidden><div class="art empty nf"></div>
          <div class="meta">
            <div class="artist plat muted"></div>
            <div class="title"></div>
            <div class="album times num"></div>
          </div>
        </div>
      </div>`;
```

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_<id>`,
  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/<serial>` and
  `playtime.dat`. The cover is served at `/api/games/image/<key>`, 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.