aboutsummaryrefslogtreecommitdiffstats
path: root/docs/superpowers/plans/2026-11-16-xbox.md
blob: 90f87a465e0438a39d9dfc3226a98e94e95bc695 (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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
# Xbox Tab 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:** An Xbox tab on the tablet with the user's Xbox Live profile, presence, consoles, recent games, achievements and friends, console power and media control, keystone presentation mode while a game runs, and a one-time switch to the tab per gaming session.

**Architecture:** `deckit/modules/xbox.py` holds an `Xbox` object: a device code sign-in, a refresh token file, the MS → Xbox user token → XSTS chain, a background thread reading Xbox Live every 30s (presence, consoles) and 10 min (the rest), and `xccs` commands. Pure `summarize_*` functions shape each response. `static/modules/xbox.js` draws the tab; `app.js`'s `peekTab` learns an `Infinity` duration. Keystone's `Status.qml` ORs `status.xbox` into presentation.

**Tech Stack:** Python 3.11 stdlib (`urllib`, `threading`, `json`), plain JS, QML (quickshell repo).

Spec: `docs/superpowers/specs/2026-11-16-xbox-tab-design.md`. API shapes are taken from xbox-webapi-python (`xbox/webapi/api/provider/*`, `authentication/manager.py`).

---

## File map

- Create `deckit/modules/xbox.py`: the module (HTTP helper, summarizers, `Xbox`, `make`).
- Create `tests/test_xbox.py`: summarizers, auth, login, tick, status file, actions.
- Create `static/modules/xbox.js`: the tab, and `sessionPeek`.
- Create `tests/test_xbox.mjs`: `sessionPeek`.
- Modify `static/app.js` (`peekTab`): a non-finite duration shows the tab and stays.
- Modify `static/deck.css`: `.xbox` styles.
- Modify `config.toml`: `[modules] xbox`, `[xbox] client_id`.
- Modify `AGENTS.md`, `README.md`: the module.
- Quickshell repo: `shared/Status.qml`, `desktop/modules/deckit/Modules.js`, `desktop/modules/deckit/DeckItServicesPage.qml`, `desktop/modules/status/README.md`.

Run all Python tests with `python3 -m unittest discover -s tests`; one file with `python3 -m unittest tests.test_xbox -v`.

---

### Task 1: Summarizers

**Files:**
- Create: `deckit/modules/xbox.py`
- Create: `tests/test_xbox.py`

- [ ] **Step 1: Write the failing tests**

`tests/test_xbox.py`:

```python
# deck-it - tests for the Xbox 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.

import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

import unittest

import deckit.modules.xbox as xb

PRESENCE = {"xuid": "1", "state": "Online", "devices": [{"type": "Scarlett", "titles": [
    {"id": "750323071", "name": "Home", "placement": "Background", "state": "Active"},
    {"id": "1234", "name": "Some Game", "placement": "Full", "state": "Active",
     "activity": {"richPresence": "Ranked match"}}]}]}
CONSOLES = {"status": {"errorCode": "OK"}, "result": [
    {"id": "CON1", "name": "Living room", "consoleType": "XboxSeriesX", "powerState": "On",
     "storageDevices": [{"storageDeviceName": "Internal", "freeSpaceBytes": 4e11, "totalSpaceBytes": 1e12}]}]}
PROFILE = {"profileUsers": [{"id": "1", "settings": [
    {"id": "Gamertag", "value": "Player"}, {"id": "GameDisplayPicRaw", "value": "https://img.example.org/p.png"},
    {"id": "Gamerscore", "value": "12345"}]}]}
HISTORY = {"titles": [
    {"titleId": "1234", "name": "Some Game", "type": "Game", "displayImage": "https://img.example.org/c.png",
     "titleHistory": {"lastTimePlayed": "2026-11-16T10:00:00Z"},
     "achievement": {"currentAchievements": 5, "totalAchievements": 50, "currentGamerscore": 100,
                     "totalGamerscore": 1000, "progressPercentage": 10.0}},
    {"titleId": "99", "name": "Video App", "type": "App", "displayImage": None}]}
STATS = {"statlistscollection": [{"arrangebyfieldid": "1", "stats": [
    {"titleid": "1234", "name": "MinutesPlayed", "value": "185"}]}]}
ACHIEVEMENTS = {"achievements": [{"name": "First", "description": "Do a thing",
    "mediaAssets": [{"url": "https://img.example.org/a.png"}], "titleAssociations": [{"name": "Some Game"}],
    "rewards": [{"type": "Gamerscore", "value": "15"}], "progression": {"timeUnlocked": "2026-11-15T20:00:00Z"}}]}
FRIENDS = {"people": [
    {"gamertag": "zed", "displayPicRaw": "z.png", "presenceState": "Offline", "presenceText": "Offline", "isFavorite": True},
    {"gamertag": "bob", "displayPicRaw": "b.png", "presenceState": "Online", "presenceText": "Some Game", "isFavorite": False},
    {"gamertag": "amy", "displayPicRaw": "a.png", "presenceState": "Online", "presenceText": "Home", "isFavorite": True}]}


class Summaries(unittest.TestCase):
    def test_foreground_is_the_full_placement_title(self):
        self.assertEqual(xb.foreground(PRESENCE),
                         {"id": "1234", "name": "Some Game", "rich": "Ranked match", "device": "Scarlett"})
        self.assertIsNone(xb.foreground({"state": "Offline"}))

    def test_foreground_takes_a_list_activity_too(self):
        p = {"devices": [{"titles": [{"id": 7, "name": "X", "placement": "Full", "activity": [{"richPresence": "Lobby"}]}]}]}
        self.assertEqual(xb.foreground(p)["rich"], "Lobby")
        self.assertEqual(xb.foreground(p)["id"], "7")

    def test_presence_has_last_seen(self):
        p = xb.summarize_presence({"state": "Offline", "lastSeen": {"titleName": "Home", "timestamp": "2026-11-15T22:00:00Z"}})
        self.assertEqual(p, {"state": "Offline", "title": None,
                             "last_seen": {"title": "Home", "when": "2026-11-15T22:00:00Z"}})

    def test_profile(self):
        self.assertEqual(xb.summarize_profile(PROFILE),
                         {"gamertag": "Player", "pic": "https://img.example.org/p.png", "gamerscore": 12345})

    def test_consoles(self):
        c = xb.summarize_consoles(CONSOLES)[0]
        self.assertEqual((c["id"], c["name"], c["power"]), ("CON1", "Living room", "On"))
        self.assertEqual(c["storage"], [{"name": "Internal", "free": 4e11, "total": 1e12}])

    def test_minutes_and_titles(self):
        minutes = xb.minutes_played(STATS)
        self.assertEqual(minutes, {"1234": 185})
        t = xb.summarize_titles(HISTORY, minutes)
        self.assertEqual(t[0]["minutes"], 185)
        self.assertEqual(t[0]["achievements"], {"done": 5, "total": 50, "score": 100, "max": 1000, "pct": 10.0})
        self.assertEqual((t[1]["type"], t[1]["minutes"]), ("App", None))

    def test_achievements(self):
        a = xb.summarize_achievements(ACHIEVEMENTS)[0]
        self.assertEqual(a, {"name": "First", "description": "Do a thing", "icon": "https://img.example.org/a.png",
                             "score": 15, "title": "Some Game", "unlocked": "2026-11-15T20:00:00Z"})

    def test_friends_online_then_favourite_then_name(self):
        self.assertEqual([f["gamertag"] for f in xb.summarize_friends(FRIENDS)], ["amy", "bob", "zed"])


if __name__ == "__main__":
    unittest.main()
```

- [ ] **Step 2: Run to verify it fails**

Run: `python3 -m unittest tests.test_xbox -v`
Expected: FAIL, `ModuleNotFoundError: No module named 'deckit.modules.xbox'`.

- [ ] **Step 3: Write the module's head and summarizers**

`deckit/modules/xbox.py`:

```python
# deck-it - Xbox Live: profile, presence, games, friends and console control
# 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.

"""Xbox Live: the user's profile, presence, consoles, recent games,
achievements and friends, and the console's power and media control.

A retail console has no local API, so everything goes through Xbox Live with
the user's own Azure app (a public client for personal accounts). Sign-in is
the device code flow, started from the tab; the refresh token lives in
~/.config/deck-it/xbox-token.json and the short-lived tokens only in memory.
While the console runs a game, $XDG_RUNTIME_DIR/status.xbox holds 1, which
keystone's Status.qml ORs into presentation mode.

The endpoints, headers and command bodies follow xbox-webapi-python; Microsoft
documents none of them for third parties.
"""

import json
import os
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
from pathlib import Path

from ..module import Module, ModuleError


def foreground(presence: dict) -> dict | None:
    """The title filling a console's screen, if any."""
    for dev in presence.get("devices") or []:
        for t in dev.get("titles") or []:
            if t.get("placement") == "Full" and t.get("state", "Active") == "Active":
                act = t.get("activity") or {}
                if isinstance(act, list):
                    act = act[0] if act else {}
                return {"id": str(t.get("id")), "name": t.get("name"), "rich": act.get("richPresence"),
                        "device": dev.get("type")}
    return None


def summarize_presence(p: dict) -> dict:
    seen = p.get("lastSeen")
    return {"state": p.get("state"), "title": foreground(p),
            "last_seen": {"title": seen.get("titleName"), "when": seen.get("timestamp")} if seen else None}


def summarize_profile(r: dict) -> dict:
    s = {x["id"]: x.get("value") for x in r["profileUsers"][0]["settings"]}
    return {"gamertag": s.get("Gamertag"), "pic": s.get("GameDisplayPicRaw"),
            "gamerscore": int(s.get("Gamerscore") or 0)}


def summarize_consoles(r: dict) -> list:
    return [{"id": c["id"], "name": c.get("name"), "type": c.get("consoleType"), "power": c.get("powerState"),
             "storage": [{"name": d.get("storageDeviceName"), "free": d.get("freeSpaceBytes"),
                          "total": d.get("totalSpaceBytes")} for d in c.get("storageDevices") or []]}
            for c in r.get("result") or []]


def minutes_played(r: dict) -> dict:
    """title id -> minutes, from a userstats batch of MinutesPlayed."""
    out = {}
    for coll in r.get("statlistscollection") or []:
        for s in coll.get("stats") or []:
            if s.get("name") == "MinutesPlayed" and s.get("value") is not None:
                out[str(s.get("titleid") or s.get("titleId"))] = int(float(s["value"]))
    return out


def summarize_titles(r: dict, minutes: dict) -> list:
    out = []
    for t in r.get("titles") or []:
        a = t.get("achievement") or {}
        tid = str(t["titleId"])
        out.append({"id": tid, "name": t.get("name"), "type": t.get("type"), "cover": t.get("displayImage"),
                    "last": (t.get("titleHistory") or {}).get("lastTimePlayed"),
                    "achievements": {"done": a.get("currentAchievements", 0), "total": a.get("totalAchievements", 0),
                                     "score": a.get("currentGamerscore", 0), "max": a.get("totalGamerscore", 0),
                                     "pct": a.get("progressPercentage", 0)},
                    "minutes": minutes.get(tid)})
    return out


def summarize_achievements(r: dict) -> list:
    out = []
    for a in r.get("achievements") or []:
        score = next((int(x.get("value") or 0) for x in a.get("rewards") or [] if x.get("type") == "Gamerscore"), 0)
        out.append({"name": a.get("name"), "description": a.get("description"),
                    "icon": next((m.get("url") for m in a.get("mediaAssets") or []), None),
                    "score": score,
                    "title": next((t.get("name") for t in a.get("titleAssociations") or []), None),
                    "unlocked": (a.get("progression") or {}).get("timeUnlocked")})
    return out


def summarize_friends(r: dict) -> list:
    people = [{"gamertag": p.get("gamertag"), "pic": p.get("displayPicRaw"), "state": p.get("presenceState"),
               "text": p.get("presenceText"), "favorite": bool(p.get("isFavorite"))}
              for p in r.get("people") or []]
    people.sort(key=lambda p: (p["state"] != "Online", not p["favorite"], (p["gamertag"] or "").lower()))
    return people


# Replaced in Task 4; here so module discovery (deckit.modules.build) keeps working.
def make(cfg: dict) -> Module:
    return Module(name="xbox", title="Xbox", state=lambda: {"offline": True, "unconfigured": True})
```

- [ ] **Step 4: Run to verify it passes**

Run: `python3 -m unittest tests.test_xbox -v && python3 -m unittest discover -s tests`
Expected: 8 tests OK, then the whole suite OK.

- [ ] **Step 5: Commit**

```bash
git add deckit/modules/xbox.py tests/test_xbox.py
git commit -m "feat(xbox): shape Xbox Live responses for the tab"
```

---

### Task 2: HTTP helper, token file and the auth chain

**Files:**
- Modify: `deckit/modules/xbox.py`
- Modify: `tests/test_xbox.py`

- [ ] **Step 1: Write the failing tests**

Add to `tests/test_xbox.py`, after the fixtures (add `import json`, `import os`, `import tempfile` to the imports):

```python
XSTS = {"Token": "XT", "DisplayClaims": {"xui": [{"uhs": "UHS", "xid": "1"}]}}


class Fake:
    """Answers by URL; `fail` maps a URL fragment to an HttpError to raise once."""

    def __init__(self, **over):
        self.calls, self.fail = [], {}
        self.answers = {
            "/oauth2/v2.0/token": {"access_token": "AT", "refresh_token": "RT2"},
            "/oauth2/v2.0/devicecode": {"user_code": "ABCD-1234", "verification_uri": "https://microsoft.com/devicelogin",
                                        "expires_in": 900, "interval": 0, "device_code": "DEV"},
            "user.auth.xboxlive.com": {"Token": "UT"},
            "xsts.auth.xboxlive.com": XSTS,
            "userpresence": PRESENCE,
            "/lists/devices": CONSOLES,
            "profile.xboxlive.com": PROFILE,
            "titlehistory": HISTORY,
            "titleid(": {"titles": [{"type": "Game"}]},
            "userstats": STATS,
            "achievements.xboxlive.com": ACHIEVEMENTS,
            "peoplehub": FRIENDS,
            "/commands": {"status": {"errorCode": "OK"}, "opId": "op"},
        }
        self.answers.update(over)

    def __call__(self, url, data=None, headers=None, timeout=10):
        self.calls.append((url, data, headers or {}))
        for frag, err in list(self.fail.items()):
            if frag in url:
                del self.fail[frag]
                raise err
        for frag, answer in self.answers.items():
            if frag in url:
                return answer
        raise AssertionError(f"unexpected url {url}")

    def urls(self, frag):
        return [c for c in self.calls if frag in c[0]]


class Base(unittest.TestCase):
    def setUp(self):
        self.dir = tempfile.TemporaryDirectory()
        self.addCleanup(self.dir.cleanup)
        self.token = Path(self.dir.name) / "cfg" / "xbox-token.json"
        self.status = Path(self.dir.name) / "status.xbox"
        self.fake = Fake()

    def xbox(self, signed_in=True, client_id="CID"):
        if signed_in:
            self.token.parent.mkdir(parents=True, exist_ok=True)
            self.token.write_text(json.dumps({"refresh_token": "RT"}))
        return xb.Xbox({"xbox": {"client_id": client_id}}, self.fake, self.token, self.status)


class Auth(Base):
    def test_chain_builds_the_xbl3_header(self):
        x = self.xbox()
        x.api("https://userpresence.xboxlive.com/users/me?level=all", 3)
        url, data, headers = self.fake.urls("userpresence")[0]
        self.assertEqual(headers["Authorization"], "XBL3.0 x=UHS;XT")
        self.assertEqual(headers["x-xbl-contract-version"], "3")
        user = self.fake.urls("user.auth")[0][1]
        self.assertEqual(user["Properties"]["RpsTicket"], "d=AT")
        self.assertEqual(x.auth["xuid"], "1")

    def test_a_rotated_refresh_token_is_saved_private(self):
        x = self.xbox()
        x.api("https://userpresence.xboxlive.com/users/me?level=all", 3)
        self.assertEqual(json.loads(self.token.read_text()), {"refresh_token": "RT2"})
        self.assertEqual(os.stat(self.token).st_mode & 0o777, 0o600)

    def test_a_401_renews_once(self):
        x = self.xbox()
        x.api("https://userpresence.xboxlive.com/users/me?level=all", 3)
        self.fake.fail["userpresence"] = xb.HttpError(401, {})
        x.api("https://userpresence.xboxlive.com/users/me?level=all", 3)
        self.assertEqual(len(self.fake.urls("xsts.auth")), 2)

    def test_a_refused_refresh_token_signs_out(self):
        x = self.xbox()
        self.fake.fail["/oauth2/v2.0/token"] = xb.HttpError(400, {"error": "invalid_grant"})
        with self.assertRaises(xb.SignedOut):
            x.api("https://userpresence.xboxlive.com/users/me?level=all", 3)
        self.assertFalse(self.token.exists())
        self.assertIsNone(x.refresh)
```

- [ ] **Step 2: Run to verify it fails**

Run: `python3 -m unittest tests.test_xbox -v`
Expected: the `Auth` tests ERROR with `AttributeError: module 'deckit.modules.xbox' has no attribute 'Xbox'`.

- [ ] **Step 3: Implement**

In `deckit/modules/xbox.py`, after the imports and before `foreground`, add the constants, `HttpError`, `SignedOut` and `_http`:

```python
MS = "https://login.microsoftonline.com/consumers/oauth2/v2.0"
SCOPE = "XboxLive.signin offline_access"
USER_AUTH = "https://user.auth.xboxlive.com/user/authenticate"
XSTS_AUTH = "https://xsts.auth.xboxlive.com/xsts/authorize"
PRESENCE = "https://userpresence.xboxlive.com/users/me?level=all"
XCCS = "https://xccs.xboxlive.com"
DEVICES = XCCS + "/lists/devices?queryCurrentDevice=false&includeStorageDevices=true"
TITLEHUB = "https://titlehub.xboxlive.com/users/xuid({})/titles/"
PROFILE = "https://profile.xboxlive.com/users/me/profile/settings?settings=Gamertag,GameDisplayPicRaw,Gamerscore"
ACHIEVEMENTS = ("https://achievements.xboxlive.com/users/xuid({})/achievements"
                "?orderBy=UnlockTime&unlockedOnly=true&maxItems=10")
FRIENDS = "https://peoplehub.xboxlive.com/users/me/people/friends/decoration/presenceDetail"
USERSTATS = "https://userstats.xboxlive.com/batch"
# titlehub answers only clients that name themselves; these are the Xbox app's.
HUB = {"x-xbl-client-name": "XboxApp", "x-xbl-client-type": "UWA", "x-xbl-client-version": "39.39.22001.0"}
SG = {"skillplatform": "RemoteManagement"}

FAST = 30            # seconds between presence and console reads
SLOW = 600           # seconds between profile, games, achievements and friends reads
# ponytail: renewed by age, not by the XSTS NotAfter (about 16h); a 401 renews early too.
XSTS_FOR = 8 * 3600
TITLES = 12          # recent games shown

TOKEN = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "deck-it" / "xbox-token.json"
STATUS = Path(os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}") / "status.xbox"


class HttpError(OSError):
    """An HTTP error answer, with its JSON body when it had one."""

    def __init__(self, status: int, body: dict | None):
        super().__init__(f"HTTP {status}")
        self.status, self.body = status, body or {}


class SignedOut(Exception):
    """No refresh token, or Microsoft no longer accepts it."""


def _http(url, data=None, headers=None, timeout=10):
    """A JSON answer. data: a dict or list goes as JSON, a str as a form."""
    h = {"Accept": "application/json", **(headers or {})}
    body = None
    if isinstance(data, dict | list):
        body, h["Content-Type"] = json.dumps(data).encode(), "application/json"
    elif isinstance(data, str):
        body, h["Content-Type"] = data.encode(), "application/x-www-form-urlencoded"
    try:
        with urllib.request.urlopen(urllib.request.Request(url, data=body, headers=h), timeout=timeout) as r:
            raw = r.read()
    except urllib.error.HTTPError as e:
        try:
            payload = json.loads(e.read() or b"{}")
        except ValueError:
            payload = {}
        raise HttpError(e.code, payload if isinstance(payload, dict) else {}) from None
    return json.loads(raw) if raw else {}
```

At the end of the file, add the class with the token and auth parts:

```python
class Xbox:
    def __init__(self, cfg: dict, http=_http, token=TOKEN, status=STATUS):
        self.client_id = str(cfg.get("xbox", {}).get("client_id", "")).strip()
        self.http, self.token_path, self.status_path = http, Path(token), Path(status)
        self.refresh = self._load()
        self.auth = None                 # {"header", "xuid", "at"} from the last XSTS
        self.auth_lock = threading.Lock()
        self.sg_session = str(uuid.uuid4())

    # --- the refresh token file ----------------------------------------
    def _load(self):
        try:
            return json.loads(self.token_path.read_text())["refresh_token"]
        except (OSError, ValueError, KeyError, TypeError):
            return None

    def _save(self, refresh: str):
        self.token_path.parent.mkdir(parents=True, exist_ok=True)
        tmp = self.token_path.with_suffix(".tmp")
        tmp.unlink(missing_ok=True)
        with os.fdopen(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w") as f:
            json.dump({"refresh_token": refresh}, f)
        os.replace(tmp, self.token_path)
        self.refresh = refresh

    # --- tokens ---------------------------------------------------------
    def _form(self, **fields):
        return self.http(MS + "/token", urllib.parse.urlencode({"client_id": self.client_id, **fields}))

    def _authorize(self):
        """Refresh token -> MS access token -> Xbox user token -> XSTS."""
        if not self.refresh:
            raise SignedOut
        try:
            tok = self._form(grant_type="refresh_token", refresh_token=self.refresh, scope=SCOPE)
        except HttpError as e:
            if e.body.get("error") in ("invalid_grant", "interaction_required"):
                self.token_path.unlink(missing_ok=True)
                self.refresh, self.auth = None, None
                raise SignedOut from None
            raise
        if tok.get("refresh_token") and tok["refresh_token"] != self.refresh:
            self._save(tok["refresh_token"])
        v1 = {"x-xbl-contract-version": "1"}
        user = self.http(USER_AUTH, {"RelyingParty": "http://auth.xboxlive.com", "TokenType": "JWT",
                                     "Properties": {"AuthMethod": "RPS", "SiteName": "user.auth.xboxlive.com",
                                                    "RpsTicket": "d=" + tok["access_token"]}}, v1)
        xsts = self.http(XSTS_AUTH, {"RelyingParty": "http://xboxlive.com", "TokenType": "JWT",
                                     "Properties": {"UserTokens": [user["Token"]], "SandboxId": "RETAIL"}}, v1)
        xui = xsts["DisplayClaims"]["xui"][0]
        self.auth = {"header": f"XBL3.0 x={xui['uhs']};{xsts['Token']}", "xuid": xui["xid"],
                     "at": time.monotonic()}

    def api(self, url, contract, data=None, extra=None):
        """An Xbox Live call with the XSTS header; a 401 renews it once."""
        with self.auth_lock:
            if not self.auth or time.monotonic() - self.auth["at"] > XSTS_FOR:
                self._authorize()
        for retry in (True, False):
            headers = {"Authorization": self.auth["header"], "x-xbl-contract-version": str(contract),
                       "Accept-Language": "en-US", **(extra or {})}
            try:
                return self.http(url, data, headers)
            except HttpError as e:
                if e.status != 401 or not retry:
                    raise
                with self.auth_lock:
                    self._authorize()
```

- [ ] **Step 4: Run to verify it passes**

Run: `python3 -m unittest tests.test_xbox -v`
Expected: all OK (12 tests).

- [ ] **Step 5: Commit**

```bash
git add deckit/modules/xbox.py tests/test_xbox.py
git commit -m "feat(xbox): Xbox Live auth chain and token file"
```

---

### Task 3: Device code sign-in

**Files:**
- Modify: `deckit/modules/xbox.py`
- Modify: `tests/test_xbox.py`

- [ ] **Step 1: Write the failing tests**

Add to `tests/test_xbox.py`:

```python
class Login(Base):
    def test_no_client_id_refuses(self):
        with self.assertRaises(xb.ModuleError):
            self.xbox(signed_in=False, client_id="").start_login({})

    def test_start_returns_the_code_and_state_shows_it(self):
        x = self.xbox(signed_in=False)
        x._wait_login = lambda: None          # the test drives login_step itself
        view = x.start_login({})
        self.assertEqual((view["code"], view["url"]), ("ABCD-1234", "https://microsoft.com/devicelogin"))
        self.assertEqual(x.state()["login"]["code"], "ABCD-1234")
        self.assertFalse(x.state()["signed_in"])

    def test_pending_then_done_saves_the_token(self):
        x = self.xbox(signed_in=False)
        x._wait_login = lambda: None
        x.start_login({})
        self.fake.fail["/oauth2/v2.0/token"] = xb.HttpError(400, {"error": "authorization_pending"})
        self.assertEqual(x.login_step(), "pending")
        self.assertEqual(x.login_step(), "done")
        self.assertEqual(json.loads(self.token.read_text()), {"refresh_token": "RT2"})
        self.assertIsNone(x.login)
        form = self.fake.urls("/oauth2/v2.0/token")[-1][1]
        self.assertIn("device_code=DEV", form)

    def test_declined_or_expired_ends_it(self):
        x = self.xbox(signed_in=False)
        x._wait_login = lambda: None
        x.start_login({})
        self.fake.fail["/oauth2/v2.0/token"] = xb.HttpError(400, {"error": "expired_token"})
        self.assertEqual(x.login_step(), "failed")
        self.assertIsNone(x.state()["login"])
```

- [ ] **Step 2: Run to verify it fails**

Run: `python3 -m unittest tests.test_xbox -v`
Expected: `Login` tests ERROR, `'Xbox' object has no attribute 'start_login'` (and `state`).

- [ ] **Step 3: Implement**

In `Xbox.__init__`, after `self.sg_session = ...`, add:

```python
        self.login = None                # the device code flow while it runs
        self.data = {}                   # presence, consoles, profile, titles, achievements, friends
        self.offline, self.reason = False, None
        self.types = {}                  # title id -> titlehub type ("Game", "App")
        self.playing, self.session = None, None
        self.status_on = None            # what status.xbox last got
        self.slow_at, self.slow_title = None, None
        self.wake, self.stopping = threading.Event(), False
```

Add the methods to `Xbox`:

```python
    # --- device code sign-in -------------------------------------------
    def start_login(self, body=None):
        if not self.client_id:
            raise ModuleError("no Xbox client id configured")
        if self.login and time.time() < self.login["expires"]:
            return self._login_view()
        try:
            r = self.http(MS + "/devicecode", urllib.parse.urlencode({"client_id": self.client_id, "scope": SCOPE}))
        except OSError as e:
            raise ModuleError(f"sign-in failed: {e}") from e
        self.login = {"code": r["user_code"], "url": r["verification_uri"], "expires": time.time() + r["expires_in"],
                      "device": r["device_code"], "interval": r.get("interval", 5)}
        threading.Thread(target=self._wait_login, daemon=True).start()
        return self._login_view()

    def _login_view(self):
        login = self.login
        return {k: login[k] for k in ("code", "url", "expires")} if login else None

    def login_step(self) -> str:
        """One poll of the token endpoint: "done", "pending" or "failed"."""
        login = self.login
        if not login or time.time() > login["expires"]:
            self.login = None
            return "failed"
        try:
            tok = self._form(grant_type="urn:ietf:params:oauth:grant-type:device_code", device_code=login["device"])
        except HttpError as e:
            err = e.body.get("error")
            if err == "slow_down":
                login["interval"] += 5
            if err in ("authorization_pending", "slow_down"):
                return "pending"
            self.login = None
            return "failed"
        except OSError:
            return "pending"
        self._save(tok["refresh_token"])
        self.login, self.auth = None, None
        self.wake.set()
        return "done"

    def _wait_login(self):
        while not self.stopping:
            login = self.login
            if not login:
                return
            time.sleep(login["interval"])
            if self.login_step() != "pending":
                return

    # --- what the tab polls --------------------------------------------
    def state(self):
        if not self.client_id:
            return {"offline": True, "unconfigured": True}
        if not self.refresh:
            return {"signed_in": False, "login": self._login_view()}
        if not self.data.get("profile"):
            return {"signed_in": True, "offline": self.offline, "reason": self.reason, "loading": not self.offline}
        return {"signed_in": True, "stale": self.offline, "reason": self.reason, **self.data,
                "playing": self.playing, "session": self.session}
```

- [ ] **Step 4: Run to verify it passes**

Run: `python3 -m unittest tests.test_xbox -v`
Expected: all OK (16 tests).

- [ ] **Step 5: Commit**

```bash
git add deckit/modules/xbox.py tests/test_xbox.py
git commit -m "feat(xbox): device code sign-in from the tab"
```

---

### Task 4: Reads, playing, status file, commands, `make`

**Files:**
- Modify: `deckit/modules/xbox.py`
- Modify: `tests/test_xbox.py`
- Modify: `config.toml`

- [ ] **Step 1: Write the failing tests**

Add to `tests/test_xbox.py`:

```python
class Tick(Base):
    def test_a_tick_reads_everything_and_marks_the_game(self):
        x = self.xbox()
        x.tick()
        st = x.state()
        self.assertEqual(st["profile"]["gamertag"], "Player")
        self.assertEqual(st["consoles"][0]["id"], "CON1")
        self.assertEqual(st["titles"][0]["minutes"], 185)
        self.assertEqual(st["achievements"][0]["score"], 15)
        self.assertEqual(st["friends"][0]["gamertag"], "amy")
        self.assertEqual(st["playing"]["name"], "Some Game")
        self.assertIsInstance(st["session"], int)
        self.assertEqual(self.status.read_text(), "1")

    def test_slow_reads_wait_unless_the_title_changes(self):
        x = self.xbox()
        x.tick(), x.tick()
        self.assertEqual(len(self.fake.urls("profile.xboxlive.com")), 1)
        self.fake.answers["userpresence"] = {"state": "Online", "devices": [{"titles": [
            {"id": "99", "name": "Video App", "placement": "Full"}]}]}
        x.tick()
        self.assertEqual(len(self.fake.urls("profile.xboxlive.com")), 2)

    def test_an_app_is_not_playing_and_ends_the_session(self):
        x = self.xbox()
        x.tick()
        self.fake.answers["userpresence"] = {"state": "Online", "devices": [{"titles": [
            {"id": "99", "name": "Video App", "placement": "Full"}]}]}
        x.tick()
        self.assertIsNone(x.state()["playing"])
        self.assertIsNone(x.state()["session"])
        self.assertEqual(self.status.read_text(), "0")

    def test_an_unknown_title_type_is_looked_up_once(self):
        self.fake.answers["userpresence"] = {"state": "Online", "devices": [{"titles": [
            {"id": "555", "name": "New Game", "placement": "Full"}]}]}
        x = self.xbox()
        x.tick(), x.tick()
        self.assertEqual(len(self.fake.urls("titleid(555)")), 1)
        self.assertEqual(x.state()["playing"]["id"], "555")

    def test_network_down_keeps_the_data_as_stale(self):
        x = self.xbox()
        x.tick()
        self.fake.fail["userpresence"] = OSError("no route")
        x.tick()
        st = x.state()
        self.assertTrue(st["stale"])
        self.assertEqual(st["profile"]["gamertag"], "Player")

    def test_one_failing_part_keeps_the_rest(self):
        x = self.xbox()
        self.fake.fail["peoplehub"] = xb.HttpError(403, {})
        x.tick()
        st = x.state()
        self.assertFalse(st["stale"])
        self.assertEqual(st["friends"], [])
        self.assertEqual(st["profile"]["gamertag"], "Player")

    def test_signed_out_clears_playing(self):
        x = self.xbox()
        x.tick()
        self.fake.fail["/oauth2/v2.0/token"] = xb.HttpError(400, {"error": "invalid_grant"})
        x.auth = None
        x.tick()
        self.assertFalse(x.state()["signed_in"])
        self.assertEqual(self.status.read_text(), "0")

    def test_stop_writes_zero(self):
        x = self.xbox()
        x.tick()
        x.stop()
        self.assertEqual(self.status.read_text(), "0")


class Commands(Base):
    def test_a_command_goes_to_xccs(self):
        x = self.xbox()
        x.tick()
        x.command("vol_up", {"console": "CON1"})
        url, data, headers = self.fake.urls("/commands")[0]
        self.assertEqual((data["type"], data["command"], data["linkedXboxId"]), ("Audio", "Volume", "CON1"))
        self.assertEqual(data["parameters"], [{"direction": "Up", "amount": "1"}])
        self.assertEqual(headers["skillplatform"], "RemoteManagement")

    def test_unknown_console_is_refused(self):
        x = self.xbox()
        x.tick()
        with self.assertRaises(xb.ModuleError):
            x.command("wake", {"console": "OTHER"})

    def test_an_xccs_error_becomes_the_message(self):
        self.fake.answers["/commands"] = {"status": {"errorCode": "DeviceUnavailable", "errorMessage": "Console is off"}}
        x = self.xbox()
        x.tick()
        with self.assertRaisesRegex(xb.ModuleError, "Console is off"):
            x.command("off", {"console": "CON1"})

    def test_make_lists_the_actions(self):
        m = xb.make({"xbox": {"client_id": ""}})
        self.assertEqual(set(m.actions), {"login", *xb.COMMANDS})
        self.assertEqual(m.state(), {"offline": True, "unconfigured": True})
```

- [ ] **Step 2: Run to verify it fails**

Run: `python3 -m unittest tests.test_xbox -v`
Expected: `Tick` and `Commands` tests ERROR, `'Xbox' object has no attribute 'tick'`.

- [ ] **Step 3: Implement**

After the `SG = ...` constant add:

```python
COMMANDS = {
    "wake": ("Power", "WakeUp", None),
    "off": ("Power", "TurnOff", None),
    "play": ("Media", "Play", None),
    "pause": ("Media", "Pause", None),
    "vol_up": ("Audio", "Volume", [{"direction": "Up", "amount": "1"}]),
    "vol_down": ("Audio", "Volume", [{"direction": "Down", "amount": "1"}]),
    "mute": ("Audio", "Mute", None),
    "unmute": ("Audio", "Unmute", None),
}
```

Add the methods to `Xbox`:

```python
    # --- reads ----------------------------------------------------------
    def read_fast(self):
        presence = summarize_presence(self.api(PRESENCE, 3))
        consoles = summarize_consoles(self.api(DEVICES, 4, extra=SG))
        self.data = {**self.data, "presence": presence, "consoles": consoles}

    def read_slow(self):
        """Each part on its own: an endpoint that refuses keeps its last data,
        a network failure (a plain OSError) ends the read."""
        xuid = self.auth["xuid"]

        def titles():
            history = self.api(TITLEHUB.format(xuid) + f"titlehistory/decoration/achievement,image?maxItems={TITLES}",
                               2, extra=HUB)
            ids = [str(t["titleId"]) for t in history.get("titles") or []]
            try:
                minutes = minutes_played(self.api(USERSTATS, 2, {
                    "arrangebyfield": "xuid", "xuids": [xuid],
                    "stats": [{"name": "MinutesPlayed", "titleId": i} for i in ids]})) if ids else {}
            except HttpError:
                minutes = {}
            out = summarize_titles(history, minutes)
            self.types.update({t["id"]: t["type"] for t in out})
            return out

        parts = {
            "profile": lambda: summarize_profile(self.api(PROFILE, 3)),
            "titles": titles,
            "achievements": lambda: summarize_achievements(self.api(ACHIEVEMENTS.format(xuid), 2)),
            "friends": lambda: summarize_friends(self.api(FRIENDS, 7)),
        }
        for key, read in parts.items():
            try:
                self.data = {**self.data, key: read()}
            except HttpError as e:
                if e.status == 401:
                    raise
                self.data = {**self.data, key: self.data.get(key) or ([] if key != "profile" else None)}
                self.reason = f"{key}: {e}"

    def type_of(self, tid: str):
        if tid not in self.types:
            try:
                r = self.api(TITLEHUB.format(self.auth["xuid"]) + f"titleid({tid})/decoration/detail", 2, extra=HUB)
                self.types[tid] = ((r.get("titles") or [{}])[0]).get("type")
            except HttpError:
                self.types[tid] = None        # the home screen and system apps have no entry
        return self.types[tid]

    def tick(self):
        if not self.refresh:
            return self._set_playing(None)
        try:
            self.reason = None
            self.read_fast()
            fg = self.data["presence"]["title"]
            fg_id = fg and fg["id"]
            if self.slow_at is None or time.monotonic() - self.slow_at >= SLOW or fg_id != self.slow_title:
                self.read_slow()
                self.slow_at, self.slow_title = time.monotonic(), fg_id
            self._set_playing(fg if fg and self.type_of(fg["id"]) == "Game" else None)
            self.offline = False
        except SignedOut:
            self.data = {}
            self._set_playing(None)
        except (OSError, ValueError, KeyError, TypeError, IndexError) as e:
            self.offline, self.reason = True, str(e)

    # --- playing --------------------------------------------------------
    def _set_playing(self, game):
        # ponytail: the session starts when deck-it first sees the game, so a
        # restart mid-game counts as a new session (and switches the tab again).
        if game and not self.playing:
            self.session = int(time.time())
        elif not game:
            self.session = None
        self.playing = game
        on = game is not None
        if on != self.status_on:
            tmp = self.status_path.with_name("." + self.status_path.name + ".tmp")
            tmp.write_text("1" if on else "0")
            os.replace(tmp, self.status_path)
            self.status_on = on

    # --- console commands -----------------------------------------------
    def command(self, name: str, body: dict):
        cid = (body or {}).get("console")
        if cid not in {c["id"] for c in self.data.get("consoles") or []}:
            raise ModuleError("unknown console")
        typ, cmd, params = COMMANDS[name]
        try:
            r = self.api(XCCS + "/commands", 4, {
                "destination": "Xbox", "type": typ, "command": cmd, "sessionId": self.sg_session,
                "sourceId": "com.microsoft.smartglass", "parameters": params or [{}], "linkedXboxId": cid}, SG)
        except SignedOut:
            raise ModuleError("not signed in to Xbox") from None
        except OSError as e:
            raise ModuleError(f"{name} failed: {e}") from e
        status = r.get("status") or {}
        if status.get("errorCode", "OK") != "OK":
            raise ModuleError(status.get("errorMessage") or status["errorCode"])
        self.wake.set()

    # --- the reader thread ----------------------------------------------
    def run(self):
        while not self.stopping:
            self.tick()
            self.wake.wait(FAST)
            self.wake.clear()

    def start(self):
        if self.client_id:
            threading.Thread(target=self.run, daemon=True).start()

    def stop(self):
        self.stopping = True
        self.wake.set()
        self._set_playing(None)
```

Replace the placeholder `make` from Task 1 with:

```python
def make(cfg: dict) -> Module:
    x = Xbox(cfg, cfg.get("http", _http))
    actions = {name: (lambda body, n=name: x.command(n, body)) for name in COMMANDS}
    actions["login"] = x.start_login
    return Module(name="xbox", title="Xbox", state=x.state, actions=actions, start=x.start, stop=x.stop)
```

`config.toml`: in `[modules]` after `actions = true` add `xbox = true`. After the `[k1c]` table add:

```toml
[xbox]
# The client id of your own Azure app registration: a public client for
# personal Microsoft accounts, with public client flows allowed. Empty: the
# Xbox tab says it is not configured. Sign-in happens on the tab.
client_id = ""
```

- [ ] **Step 4: Run the tests**

Run: `python3 -m unittest tests.test_xbox -v`
Expected: all OK (28 tests).
Run: `python3 -m unittest discover -s tests`
Expected: all OK (the stats test that builds every module now builds `xbox` too).

- [ ] **Step 5: Commit**

```bash
git add deckit/modules/xbox.py tests/test_xbox.py config.toml
git commit -m "feat(xbox): Xbox Live reads, presentation flag and console commands"
```

---

### Task 5: `peekTab` stays for `Infinity`, and `sessionPeek`

**Files:**
- Modify: `static/app.js:90-99`
- Create: `static/modules/xbox.js` (only `sessionPeek` and a stub default export in this task)
- Create: `tests/test_xbox.mjs`

- [ ] **Step 1: Write the failing node test**

`tests/test_xbox.mjs`:

```js
// deck-it - checks for the Xbox tab's session switch
// 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";

const { sessionPeek } = await import("../static/modules/xbox.js");

const store = new Map();
const fake = { getItem: (k) => store.get(k) ?? null, setItem: (k, v) => store.set(k, String(v)) };

assert.equal(sessionPeek({ session: null }, fake), 0);
assert.equal(sessionPeek({ session: 100 }, fake), Infinity);   // a new session switches once
assert.equal(sessionPeek({ session: 100 }, fake), 0);          // then never again
assert.equal(sessionPeek({ session: null }, fake), 0);
assert.equal(sessionPeek({ session: 200 }, fake), Infinity);   // the next session does
console.log("xbox ok");
```

- [ ] **Step 2: Run to verify it fails**

Run: `node tests/test_xbox.mjs`
Expected: FAIL, `Cannot find module .../static/modules/xbox.js`.

- [ ] **Step 3: Implement**

`static/modules/xbox.js` (Task 6 replaces the default export with the full panel):

```js
// deck-it - the Xbox tab: Xbox Live profile, games, friends and the console
// 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.

const SESSION_KEY = "deckit-xbox-session";

// A game session on the Xbox brings this tab forward once and leaves it
// there (app.js reads Infinity as "stay"). The session is remembered, so a
// reload, or leaving the tab, does not bring it back until the next one.
export function sessionPeek(st, store = globalThis.localStorage) {
  if (!st.session || store.getItem(SESSION_KEY) === String(st.session)) return 0;
  store.setItem(SESSION_KEY, st.session);
  return Infinity;
}

export default { title: "Xbox", tab: "Xbox", interval: 5, peek: (st) => sessionPeek(st) };
```

`static/app.js`, replace the `peekTab` comment and function (lines 90-99) with:

```js
// A panel's peek(state) gives seconds when something new turned up: its tab
// comes forward that long, then the page goes back, unless touched first.
// Infinity brings it forward to stay, as a page change by hand would.
let peek = null;   // {back, timer} while a tab is shown on its own
function peekTab(name, seconds) {
  const now = Object.keys(tabs).find((n) => !tabs[n].section.hidden);
  if (now === name && !peek) return;   // already there by choice
  if (!Number.isFinite(seconds)) return showTab(name);
  const back = peek?.back ?? now;
  showTab(name);
  peek = { back, timer: setTimeout(() => showTab(back), seconds * 1000) };
}
```

- [ ] **Step 4: Run the checks**

Run: `node tests/test_xbox.mjs && node --check static/app.js && node --check static/modules/xbox.js`
Expected: `xbox ok`, no syntax errors.
Run: `python3 -m unittest tests.test_js -v`
Expected: OK.

- [ ] **Step 5: Commit**

```bash
git add static/app.js static/modules/xbox.js tests/test_xbox.mjs
git commit -m "feat(xbox): switch to the Xbox tab once per game session"
```

---

### Task 6: The Xbox panel and its CSS

**Files:**
- Modify: `static/modules/xbox.js`
- Modify: `static/deck.css` (append)

- [ ] **Step 1: Write the panel**

In `static/modules/xbox.js`, add after the license header:

```js
import { offline } from "../offline.js";
import { hold } from "../hold.js";
```

and replace the stub `export default ...` line with:

```js
// Nerd Font (Material Design) glyphs.
const G = {
  xbox: "\u{F05B9}", power: "\u{F0425}", play: "\u{F040A}", pause: "\u{F03E4}",
  vol_down: "\u{F075E}", vol_up: "\u{F075D}", mute: "\u{F0581}", unmute: "\u{F057E}",
};
const MEDIA = ["play", "pause", "vol_down", "vol_up", "mute", "unmute"];
const LABEL = { play: "Play", pause: "Pause", vol_down: "Volume down", vol_up: "Volume up",
  mute: "Mute", unmute: "Unmute" };
const POWER = { On: ["On", "good"], ConnectedStandby: ["Standby", ""], Off: ["Off", ""],
  SystemUpdate: ["Updating", "warn"] };

function h(tag, cls, text) {
  const e = document.createElement(tag);
  if (cls) e.className = cls;
  if (text != null) e.textContent = text;
  return e;
}

// Images come straight from Microsoft's CDN; a broken one hides.
function img(src, cls) {
  const i = h("img", cls);
  i.alt = "";
  i.loading = "lazy";
  i.referrerPolicy = "no-referrer";
  i.onerror = () => { i.hidden = true; };
  if (src) i.src = src;
  else i.hidden = true;
  return i;
}

const hours = (m) => (m == null ? "" : m < 60 ? `${m} min` : `${Math.round(m / 60)} h`);
const gb = (b) => `${Math.round(b / 1e9)} GB`;
function ago(iso) {
  if (!iso) return "";
  const s = (Date.now() - Date.parse(iso)) / 1000;
  if (s < 3600) return `${Math.max(1, Math.round(s / 60))} min ago`;
  if (s < 86400) return `${Math.round(s / 3600)} h ago`;
  return `${Math.round(s / 86400)} d ago`;
}
function clock(since) {
  const s = Math.max(0, Math.floor(Date.now() / 1000 - since));
  const m = Math.floor(s / 60);
  return `${Math.floor(m / 60)}:${String(m % 60).padStart(2, "0")}`;
}

async function post(action, body) {
  const r = await fetch(`/api/xbox/${action}`, {
    method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body),
  });
  if (!r.ok) throw new Error((await r.text()) || `${action} failed`);
}

async function send(action, id, card) {
  const err = card.querySelector(".xb-err");
  err.textContent = "";
  try {
    await post(action, { console: id });
  } catch (e) {
    err.textContent = e.message;
  }
}

function presenceLine(st) {
  const p = st.presence ?? {};
  if (p.title) return [p.title.name, p.title.rich].filter(Boolean).join(" · ");
  if (p.state === "Online") return "Online";
  return p.last_seen ? `Last seen ${ago(p.last_seen.when)} · ${p.last_seen.title ?? ""}` : (p.state ?? "");
}

function consoleCard(c) {
  const on = c.power === "On";
  const card = h("div", "xb-card xb-console");
  const head = h("div", "xb-chead");
  const [label, cls] = POWER[c.power] ?? [c.power ?? "?", ""];
  head.append(h("i", "nf xb-glyph", G.xbox), h("span", "xb-cname", c.name), h("span", `xb-pill ${cls}`, label));
  // Tap wakes, hold turns off: a stray touch must not switch a game off.
  const power = h("button", `ib hold xb-power${on ? " on" : ""}`, G.power);
  power.classList.add("nf");
  power.setAttribute("aria-label", "Power: tap to wake, hold to turn off");
  hold(power, () => send("off", c.id, card), { tap: () => send("wake", c.id, card) });
  head.append(power);
  card.append(head);
  for (const d of c.storage ?? []) {
    const row = h("div", "xb-disk");
    const used = d.total ? (d.total - d.free) / d.total : 0;
    row.append(h("span", "", `${d.name} · ${gb(d.free)} free of ${gb(d.total)}`));
    const bar = h("div", "gbar");
    bar.append(h("i"));
    bar.firstChild.style.width = `${Math.round(used * 100)}%`;
    row.append(bar);
    card.append(row);
  }
  if (on) {
    const media = h("div", "xb-media");
    for (const a of MEDIA) {
      const b = h("button", "ib nf", G[a]);
      b.setAttribute("aria-label", LABEL[a]);
      b.onclick = () => send(a, c.id, card);
      media.append(b);
    }
    card.append(media);
  }
  card.append(h("div", "xb-err"));
  return card;
}

function nowPlaying(st) {
  const g = st.playing;
  const t = (st.titles ?? []).find((x) => x.id === g.id);
  const card = h("div", "xb-card xb-now");
  card.append(img(t?.cover, "xb-cover"));
  const info = h("div", "xb-ninfo");
  info.append(h("div", "xb-nlabel", "Now playing"), h("div", "xb-ntitle", g.name ?? ""),
              h("div", "xb-nrich", g.rich ?? ""), h("div", "xb-clock num", clock(st.session)));
  if (t) {
    const a = t.achievements;
    info.append(h("div", "xb-nach", `${a.score} / ${a.max} G · ${Math.round(a.pct)}%`));
    const bar = h("div", "gbar");
    bar.append(h("i"));
    bar.firstChild.style.width = `${a.pct}%`;
    info.append(bar);
  }
  card.append(info);
  return card;
}

function gameTile(t) {
  const tile = h("div", "xb-game");
  tile.append(img(t.cover, "xb-gcover"), h("div", "xb-gname", t.name ?? ""));
  if (t.type === "Game") {
    const a = t.achievements;
    const bar = h("div", "gbar");
    bar.append(h("i"));
    bar.firstChild.style.width = `${a.pct}%`;
    tile.append(bar, h("div", "xb-gmeta", [`${a.score}/${a.max} G`, hours(t.minutes)].filter(Boolean).join(" · ")));
  } else {
    tile.append(h("div", "xb-gmeta", ago(t.last)));
  }
  return tile;
}

function row(pic, title, sub, side, cls = "") {
  const r = h("div", `xb-row ${cls}`);
  const text = h("div", "xb-rtext");
  text.append(h("div", "xb-rtitle", title ?? ""), h("div", "xb-rsub", sub ?? ""));
  r.append(img(pic, "xb-rpic"), text, h("span", "xb-rside", side ?? ""));
  return r;
}

function signIn(box, st) {
  box.textContent = "";
  const wrap = h("div", "xb-login");
  wrap.append(h("i", "nf xb-logo", G.xbox), h("div", "xb-ltitle", "Sign in to Xbox"));
  if (st.login) {
    wrap.append(h("div", "xb-lhint", `On any device, open ${st.login.url} and enter`),
                h("div", "xb-code num", st.login.code));
  } else {
    const b = h("button", "ib xb-lbtn", "Sign in");
    const err = h("div", "xb-err");
    b.onclick = async () => {
      b.disabled = true;
      try {
        await post("login", {});
      } catch (e) {
        err.textContent = e.message;
        b.disabled = false;
      }
    };
    wrap.append(h("div", "xb-lhint", "Your profile, games, friends and console appear here."), b, err);
  }
  box.append(wrap);
}

function render(box, st) {
  box.textContent = "";
  const p = st.profile ?? {};
  const head = h("div", "xb-head");
  const who = h("div", "xb-who");
  who.append(h("div", "xb-tag", p.gamertag ?? ""), h("div", "xb-pres", presenceLine(st)));
  head.append(img(p.pic, "xb-pic"), who, h("div", "xb-score num", `${p.gamerscore ?? 0} G`));
  box.append(head);
  if (st.stale) box.append(h("div", "xb-stale", "Xbox Live is not answering; this is the last data."));
  const top = h("div", "xb-top");
  if (st.playing) top.append(nowPlaying(st));
  for (const c of st.consoles ?? []) top.append(consoleCard(c));
  box.append(top);

  box.append(h("div", "xb-section", "Recent games"));
  const games = h("div", "xb-games");
  for (const t of st.titles ?? []) games.append(gameTile(t));
  box.append(games);

  const lists = h("div", "xb-lists");
  const ach = h("div", "xb-card xb-list");
  ach.append(h("div", "xb-section", "Achievements"));
  for (const a of st.achievements ?? []) ach.append(row(a.icon, a.name, `${a.title ?? ""} · ${ago(a.unlocked)}`, `${a.score} G`));
  const fr = h("div", "xb-card xb-list");
  const online = (st.friends ?? []).filter((f) => f.state === "Online").length;
  fr.append(h("div", "xb-section", `Friends · ${online} online`));
  for (const f of st.friends ?? []) {
    fr.append(row(f.pic, f.gamertag, f.text, f.favorite ? "★" : "", f.state === "Online" ? "on" : ""));
  }
  lists.append(ach, fr);
  box.append(lists);
}

export default {
  title: "Xbox",
  tab: "Xbox",
  interval: 5,
  peek: (st) => sessionPeek(st),

  mount(el) {
    el.innerHTML = '<div class="xbox"><div class="xb-off"></div><div class="xb-on"></div></div>';
  },

  update(st, el) {
    const off = el.querySelector(".xb-off");
    const on = el.querySelector(".xb-on");
    const down = st.unconfigured || (st.offline && st.signed_in !== false);
    off.hidden = !down;
    on.hidden = down;
    if (down) {
      offline(off, st.unconfigured
        ? { icon: "/icons/xbox.svg", title: "Xbox is not configured",
            detail: "Set your Azure app's client id as [xbox] client_id on keystone's deck-it page." }
        : { icon: "/icons/xbox.svg", title: "Xbox Live is not answering",
            detail: "The tab fills in by itself once Xbox Live answers.", reason: st.reason });
      on._key = null;
      return;
    }
    // Drawn again only when the data changed: a redraw restarts the images
    // and would cut a held power button short.
    // ponytail: a hold across a 30s data change still restarts; key per card if it bites.
    const key = JSON.stringify(st);
    if (on._key !== key) {
      on._key = key;
      if (st.signed_in === false) signIn(on, st);
      else if (st.loading) on.replaceChildren(h("div", "xb-loading", "Loading Xbox Live…"));
      else render(on, st);
    }
    const c = on.querySelector(".xb-clock");
    if (c) c.textContent = clock(st.session);
  },
};
```

- [ ] **Step 2: Append the CSS**

At the end of `static/deck.css`:

```css
/* Xbox tab */
.xbox { display: flex; flex-direction: column; gap: 14px; padding: 4px 2px; }
.xbox .xb-on, .xbox .xb-on > * { min-width: 0; }
.xbox .xb-on { display: flex; flex-direction: column; gap: 14px; }
.xbox .xb-on[hidden], .xbox .xb-off[hidden] { display: none; }
.xbox .xb-card { background: var(--udt-mantle); border: 1px solid var(--udt-surface0); border-radius: 18px; padding: 14px; }
.xbox .xb-head { display: flex; align-items: center; gap: 14px; }
.xbox .xb-pic { width: 64px; height: 64px; border-radius: 50%; background: var(--udt-surface0); }
.xbox .xb-who { flex: 1; min-width: 0; }
.xbox .xb-tag { font-size: 1.4rem; font-weight: 700; }
.xbox .xb-pres { color: var(--udt-subtext0); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.xbox .xb-score { font-size: 1.3rem; font-weight: 600; color: var(--udt-accent); }
.xbox .xb-stale, .xbox .xb-err { color: var(--udt-red); font-size: 0.857rem; }
.xbox .xb-top { display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap: 14px; }
.xbox .xb-now { display: flex; gap: 16px; align-items: center; border-color: var(--udt-accent); }
.xbox .xb-cover { width: 140px; aspect-ratio: 1; object-fit: cover; border-radius: 12px; }
.xbox .xb-ninfo { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 6px; }
.xbox .xb-nlabel, .xbox .xb-section { color: var(--udt-subtext0); font-size: 0.857rem; text-transform: uppercase; letter-spacing: 0.06em; }
.xbox .xb-ntitle { font-size: 1.4rem; font-weight: 700; }
.xbox .xb-nrich { color: var(--udt-subtext1); }
.xbox .xb-clock { font-size: 1.6rem; font-weight: 600; }
.xbox .xb-console { display: flex; flex-direction: column; gap: 10px; }
.xbox .xb-chead { display: flex; align-items: center; gap: 10px; }
.xbox .xb-glyph { font-size: 1.8rem; color: var(--udt-green); }
.xbox .xb-cname { flex: 1; font-size: 1.15rem; font-weight: 600; }
.xbox .xb-pill { padding: 4px 12px; border-radius: 999px; background: var(--udt-surface1); font-weight: 600; }
.xbox .xb-pill.good { background: var(--udt-green); color: var(--udt-crust); }
.xbox .xb-pill.warn { background: var(--udt-yellow); color: var(--udt-crust); }
.xbox .ib { min-width: 56px; min-height: 56px; border-radius: 14px; font-size: 1.5rem;
  background: var(--udt-surface0); border: 1px solid var(--udt-surface1); color: var(--udt-text); cursor: pointer; }
.xbox .xb-power { width: 64px; height: 64px; border-radius: 50%; font-size: 1.8rem; padding: 0; }
.xbox .xb-power.on { border-color: var(--udt-green); color: var(--udt-green); }
.xbox .hold { position: relative; overflow: hidden; isolation: isolate; touch-action: none; }
.xbox .hold::before { content: ""; position: absolute; inset: 0; z-index: -1; background: var(--udt-red);
  transform: scaleX(0); transform-origin: left; }
.xbox .hold.holding::before { transform: scaleX(1); transition: transform var(--hold, 800ms) linear; }
.xbox .xb-disk { display: flex; flex-direction: column; gap: 4px; color: var(--udt-subtext1); font-size: 0.857rem; }
.xbox .xb-media { display: flex; flex-wrap: wrap; gap: 10px; }
.xbox .xb-games { display: grid; grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); gap: 12px; }
.xbox .xb-game { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
.xbox .xb-gcover { width: 100%; aspect-ratio: 1; object-fit: cover; border-radius: 12px; background: var(--udt-surface0); }
.xbox .xb-gname { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.xbox .xb-gmeta { color: var(--udt-subtext0); font-size: 0.857rem; }
.xbox .xb-lists { display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap: 14px; }
.xbox .xb-list { display: flex; flex-direction: column; gap: 8px; }
.xbox .xb-row { display: flex; align-items: center; gap: 10px; }
.xbox .xb-rpic { width: 44px; height: 44px; border-radius: 10px; background: var(--udt-surface0); flex: none; }
.xbox .xb-row.on .xb-rpic { outline: 2px solid var(--udt-green); }
.xbox .xb-rtext { flex: 1; min-width: 0; }
.xbox .xb-rtitle { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.xbox .xb-rsub { color: var(--udt-subtext0); font-size: 0.857rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.xbox .xb-rside { color: var(--udt-accent); font-weight: 600; }
.xbox .xb-login { display: flex; flex-direction: column; align-items: center; gap: 14px; padding: 48px 12px; text-align: center; }
.xbox .xb-logo { font-size: 4rem; color: var(--udt-green); }
.xbox .xb-ltitle { font-size: 1.4rem; font-weight: 700; }
.xbox .xb-lhint, .xbox .xb-loading { color: var(--udt-subtext0); }
.xbox .xb-code { font-size: 3rem; font-weight: 700; letter-spacing: 0.15em; color: var(--udt-accent); }
.xbox .xb-lbtn { padding: 0 32px; font-size: 1.2rem; }
```

- [ ] **Step 3: Check**

Run: `node --check static/modules/xbox.js && node tests/test_xbox.mjs && python3 -m unittest discover -s tests`
Expected: `xbox ok`, all tests OK.

- [ ] **Step 4: Commit**

```bash
git add static/modules/xbox.js static/deck.css
git commit -m "feat(xbox): the Xbox tab"
```

---

### Task 7: Docs

**Files:**
- Modify: `AGENTS.md`
- Modify: `README.md`

- [ ] **Step 1: AGENTS.md**

In "How it fits together", after the `tablet` bullet, add:

```markdown
- `xbox` reads Xbox Live with the user's own Azure app (`[xbox] client_id`, a
  public client for personal accounts): device code sign-in started from the
  tab, the refresh token in `~/.config/deck-it/xbox-token.json` (0600), the
  MS → user token → XSTS chain in memory. A thread reads presence and the
  consoles (`xccs`) every 30s, profile, recent titles (titlehub, minutes from
  userstats), the last achievements and friends every 10 min and on a title
  change; an endpoint that refuses keeps its last data. A foreground title
  that titlehub calls a Game is `playing`: `$XDG_RUNTIME_DIR/status.xbox`
  gets 1 (keystone ORs it into presentation) and `xbox.js`'s `peek` returns
  `Infinity` once per `session`, which `app.js` reads as "show and stay".
  Console actions are `xccs` commands (power: tap wakes, hold turns off;
  media and volume), for a console id the last state listed. Endpoints and
  bodies follow xbox-webapi-python; Microsoft documents none of them.
```

- [ ] **Step 2: README.md**

Read `README.md`, find the section that lists the tabs/modules, and add an Xbox entry in its style stating: what it shows; that it needs an Azure app registration (Entra admin center, App registrations, New registration: "Personal Microsoft accounts only", redirect URI "Public client/native" `http://localhost`, then Authentication: allow public client flows); that the client id goes in `[xbox] client_id`; that sign-in is on the tab; that console control needs Remote features on and the Sleep power mode. Keep "Development Approach" the last section.

- [ ] **Step 3: Commit**

```bash
git add AGENTS.md README.md
git commit -m "docs: the Xbox tab"
```

---

### Task 8: Keystone (quickshell repo)

**Files (in `~/Programming/GIT/quickshell`):**
- Modify: `shared/Status.qml:34-38`, `:235-236`
- Modify: `desktop/modules/deckit/Modules.js:17-20`
- Modify: `desktop/modules/deckit/DeckItServicesPage.qml:33-34`
- Modify: `desktop/modules/status/README.md`

- [ ] **Step 1: Status.qml**

Replace lines 34-38:

```qml
    // Set by the game detector below, on its own file so it never fights the
    // manual toggle: presentation is the OR, and a game ending clears only its
    // half. A manual "on" therefore survives a game session.
    readonly property bool gaming: gamingFile.value
    readonly property bool presentation: presFile.value || gamingFile.value
```

with:

```qml
    // Set by the game detector below, on its own file so it never fights the
    // manual toggle: presentation is the OR, and a game ending clears only its
    // half. A manual "on" therefore survives a game session. status.xbox is
    // the same for a game on the Xbox, written by deck-it's xbox module.
    readonly property bool gaming: gamingFile.value || xboxFile.value
    readonly property bool presentation: presFile.value || gaming
```

After `ModeFile { id: gamingFile; path: root.dir + "/status.gaming" }` add:

```qml
    // Written only by deck-it while the Xbox runs a game.
    ModeFile { id: xboxFile; path: root.dir + "/status.xbox" }
```

Check `setGaming` (line ~111) compares `on !== root.gaming`; with `gaming` now including the Xbox, a PC detector "off" while the Xbox plays would skip the write. Change it to compare against the file:

```qml
    function setGaming(on) {
        if (on !== gamingFile.value) gamingFile.write(on);
    }
```

- [ ] **Step 2: Modules.js**

`var TABS = ["windows", "obs", "k1c", "assistant", "vm", "xbox"];` and add `xbox: "Xbox"` to `NAMES`.

- [ ] **Step 3: DeckItServicesPage.qml**

After the K1C `Setting`, add:

```qml
    Setting { store: col.st; section: "xbox"; key: "client_id"; label: "Xbox client id"
              placeholder: "Azure app client id"; hint: "Your Azure app registration, for the Xbox tab. Sign in on the tab." }
```

- [ ] **Step 4: status README**

In the list of files under "The files are the interface" add `$XDG_RUNTIME_DIR/status.xbox`, and change the sentence about `status.gaming` to: "`status.gaming` is written only by the shell's game detector and `status.xbox` only by deck-it while the Xbox runs a game; neither is a mode `statusctl` exposes, and either one turns presentation on."

- [ ] **Step 5: Check and commit**

Run the repo's status test: `bash desktop/modules/status/test-statusctl.sh`
Expected: passes as before.
Restart the shell (`qs -p ~/Programming/GIT/quickshell/desktop` per its AGENTS.md) and run `echo 1 > $XDG_RUNTIME_DIR/status.xbox`: presentation turns on; `echo 0 > ...` turns it off.

```bash
cd ~/Programming/GIT/quickshell
git add shared/Status.qml desktop/modules/deckit/Modules.js desktop/modules/deckit/DeckItServicesPage.qml desktop/modules/status/README.md
git commit -m "feat(status): a game on the Xbox turns presentation on"
```

---

### Task 9: Live check (with the user)

- [ ] Put the client id in `~/.config/deck-it/config.toml` (`[xbox] client_id = "..."`), restart deck-it.
- [ ] Open the Xbox tab, tap Sign in, enter the code at the URL, approve. The tab fills within 30s; `~/.config/deck-it/xbox-token.json` is mode 600.
- [ ] Check every section against the Xbox app: gamerscore, presence, console name and storage, recent games and minutes, achievements, friends.
- [ ] With Remote features on: wake from standby, media and volume while on, hold to turn off. A command error shows on the card.
- [ ] Start a game: within 30s `status.xbox` is 1, presentation is on, the tablet switches to the Xbox tab once; switch away, it stays away. Quit to home: `status.xbox` 0, presentation off.
- [ ] Any endpoint or body that Xbox Live refuses: fix it in `xbox.py` and its test fixture, commit `fix(xbox): ...`.