aboutsummaryrefslogtreecommitdiffstats
path: root/docs
diff options
context:
space:
mode:
authorDanilo M. <danix@danix.xyz>2026-11-16 17:13:54 +0100
committerDanilo M. <danix@danix.xyz>2026-11-16 17:13:54 +0100
commit2c129fe088e75254840682fb966928a9ea482ed5 (patch)
treed8ee5b4943333d919e318de6b3ff63532ddf7ef6 /docs
parent835abc36ffd7bb79a1a7ed58ac365253b2d8be93 (diff)
downloaddeck-it-2c129fe088e75254840682fb966928a9ea482ed5.tar.gz
deck-it-2c129fe088e75254840682fb966928a9ea482ed5.zip
docs(plan): Xbox tab
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'docs')
-rw-r--r--docs/superpowers/plans/2026-11-16-xbox.md1569
1 files changed, 1569 insertions, 0 deletions
diff --git a/docs/superpowers/plans/2026-11-16-xbox.md b/docs/superpowers/plans/2026-11-16-xbox.md
new file mode 100644
index 0000000..90f87a4
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-16-xbox.md
@@ -0,0 +1,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): ...`.