# Assistant on the tablet: 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 Assistant tab on the tablet: chat with formatted streamed replies, voice through the tablet's mic, model choice, and the canvas's Ask presets and Do ops applied to a file picked on the PC with qarma. **Architecture:** `deckit/modules/assistant.py` is one client of desktop-assistant's JSON-lines socket; a reader thread folds events into an in-memory state the tab polls every 0.5s. Presets, ops and paths come from a new quickshell IPC call, `assistant catalog`. The server gains two generic pieces: raw-body upload actions (for the voice WAV) and `/fonts/nerd.ttf`. **Tech stack:** Python 3.11 stdlib; plain JS modules; `marked` 18.2.0 (MIT, vendored); QML (quickshell); qarma. **Spec:** `docs/superpowers/specs/2026-11-10-assistant-design.md`. **Three repos** (all under `~/Programming/GIT/`, all on master, commits GPG-signed by the global config, end every message with `Co-Authored-By: Claude Opus 5.5 `): `desktop-assistant` (Task 1), `quickshell` (Task 2), `deck-it` (the rest). **Deviations from the spec**, made while planning (Task 13 writes them back into the spec): 1. The model's audio inputs come from the daemon's `models` event (Task 1, one line: the daemon already reads `architecture.input_modalities` from `/v1/models` for its own check), not from deck-it calling the router. The catalog has no `routerRoot`. 2. Voice uses `MediaRecorder` plus `OfflineAudioContext` to resample to 16 kHz mono, then a JS WAV encoder; no AudioWorklet file. 3. qarma gets `--multiple` unless the op has `max: 1`; an op's `min` is checked after the pick. 4. A code block's copy icon is added to finished turns only, which covers "once its fence closes". 5. The catalog flattens the canvas's Compress submenu into four ops (`.zip`, `.tar.gz`, `.tar.xz`, `.tar.bz2`) of kind `any`. ## File map | File | Change | Responsibility | | --- | --- | --- | | `desktop-assistant/assistant.py` | modify `send_models` | `inputs` on local models | | `quickshell/desktop/shell.qml` | modify | `assistant catalog` IPC function | | `quickshell/desktop/assistant/Files.js` | modify | `exts()`: kind → extensions | | `quickshell/desktop/assistant/Ops.js` | modify | `catalog()`: ops with Compress flattened | | `quickshell/desktop/assistant/Presets.js` | modify | sentence moved into defaults; `prompt()` unchanged text | | `quickshell/desktop/assistant/test_presets.js` | modify | follows `prompt()` | | `deck-it/deckit/module.py` | modify | `Module.uploads` | | `deck-it/deckit/server.py` | modify | upload actions; `/fonts/nerd.ttf` | | `deck-it/deckit/modules/assistant.py` | create | daemon client, fold, actions, pick | | `deck-it/static/wav.js` | create | WAV encoder, blob → 16 kHz WAV | | `deck-it/static/md.js` | create | safe Markdown render | | `deck-it/static/vendor/marked/marked.esm.js` | create (download) | Markdown parser | | `deck-it/static/modules/assistant.js` | create | the tab | | `deck-it/static/deck.css` | modify | font face, `.assistant` styles | | `deck-it/config.toml` | modify | `[assistant] shell`, module on | | `deck-it/tests/test_server.py` | modify | upload and font tests | | `deck-it/tests/test_assistant.py` | create | fold, hears, client, pick | | `deck-it/tests/test_wav.mjs`, `tests/test_md.mjs` | create | JS checks | | `deck-it/tests/test_js.py` | create | runs the `.mjs` checks under unittest | | `deck-it/AGENTS.md`, `README.md` | modify | docs | --- ### Task 1: desktop-assistant reports each local model's inputs **Files:** - Modify: `~/Programming/GIT/desktop-assistant/assistant.py` (`send_models`, around line 868) - [ ] **Step 1: Change the local model list** In `send_models`, replace ```python local = [{"id": m["id"], "status": m["status"]["value"], "cloud": False} for m in json.load(r)["data"]] ``` with ```python # inputs as model_inputs() reads them, so a client can grey out # a mic for a model that cannot hear; None when not reported. local = [{"id": m["id"], "status": m["status"]["value"], "cloud": False, "inputs": (m.get("architecture") or {}).get("input_modalities")} for m in json.load(r)["data"]] ``` - [ ] **Step 2: Update the protocol doc** In `docs/superpowers/specs/2026-10-23-cloud-models-design.md` (the spec that defines the `models` event; confirm with `grep -rn '"models"' docs/superpowers/specs/`), add `inputs` to the local item's fields: `{id, status, cloud: false, inputs}`, `inputs` being the router's `architecture.input_modalities` or null. - [ ] **Step 3: Run the self-check** Run: `cd ~/Programming/GIT/desktop-assistant && python3 assistant.py --test` Expected: passes as before (no test asserts the exact local item shape; if one does, add `"inputs": None` to its expected dict). - [ ] **Step 4: Restart the daemon and look** Run: `./assistant.sh restart` then `python3 -c "import socket,json,os;s=socket.socket(socket.AF_UNIX);s.connect(os.environ['XDG_RUNTIME_DIR']+'/desktop-assistant.sock');s.sendall(b'{\"type\":\"models\"}\n');f=s.makefile();[print(l.strip()[:300]) for l in f if '\"models\"' in l][:1]" ` (Ctrl+C after the models line). Expected: local items carry `"inputs"`. - [ ] **Step 5: Commit** ```bash git add assistant.py docs/superpowers/specs/ git commit -m "feat: models event reports each local model's inputs Co-Authored-By: Claude Opus 5.5 " ``` --- ### Task 2: quickshell `assistant catalog` and preset prompts as written **Files:** - Modify: `~/Programming/GIT/quickshell/desktop/assistant/Files.js` - Modify: `~/Programming/GIT/quickshell/desktop/assistant/Ops.js` - Modify: `~/Programming/GIT/quickshell/desktop/assistant/Presets.js` - Modify: `~/Programming/GIT/quickshell/desktop/assistant/test_presets.js` - Modify: `~/Programming/GIT/quickshell/desktop/shell.qml` (the `assistant` IpcHandler, end of file) - Modify: `~/Programming/GIT/quickshell/desktop/assistant/README.md` - [ ] **Step 1: `Files.exts()`** Top-level `const` in a QML JS library is not visible to importers (the files export through `var` and functions), so add after `function chats`: ```js // kind -> suffixes, for a file dialog's filter (deck-it's picker). function exts() { return { text: TEXT, code: CODE, image: IMAGE, video: VIDEO, archive: ARCHIVE, pdf: [".pdf"] }; } ``` - [ ] **Step 2: `Ops.catalog()`** Add after the `COMPRESS` list: ```js // Every operation as one flat list, for deck-it's tablet tab: the Compress // submenu's formats become ops of their own, for any kind. function catalog() { return OPS.filter(o => o.op !== "compress") .concat(COMPRESS.map(c => Object.assign({ kinds: ["any"] }, c))); } ``` - [ ] **Step 3: Presets send their prompt as written** In `Presets.js`, append " Answer in the language of the document." to the `prompt` of each of the nine `DEFAULTS` entries (inside the string), and replace ```js // The model answers in the language it is asked in; a preset is asked in // English, so it says which language to use. function prompt(p) { return p.prompt + " Answer in the language of the document."; } ``` with ```js // Sent as written: a preset says which language to answer in, so a // Translate preset can name its target. The defaults ask for the // document's own language. function prompt(p) { return p.prompt; } ``` - [ ] **Step 4: Fix the preset test** Run: `cd ~/Programming/GIT/quickshell && node desktop/assistant/test_presets.js` Expected: FAIL where it asserts the appended sentence. Change that assertion so `prompt(p)` equals `p.prompt`, and add one that every default prompt ends with "Answer in the language of the document.". Re-run: PASS. - [ ] **Step 5: The IPC function** In `shell.qml`, add imports next to the existing ones at the top: ```qml import "assistant/Presets.js" as Presets import "assistant/Ops.js" as Ops import "assistant/Files.js" as Files ``` (skip any already imported; check with `grep -n '^import' desktop/shell.qml`), and extend the `assistant` handler: ```qml // qs -p ipc call assistant toggle -> SUPER+Home // qs -p ipc call assistant catalog -> JSON for deck-it's tablet tab IpcHandler { target: "assistant" function toggle() { assistant.toggle(); } function catalog(): string { return JSON.stringify({ presets: Presets.list(Prefs.presets), ops: Ops.catalog(), kinds: Files.exts(), fileops: assistant.fileops, outDir: assistant.outDir, mdPrompt: assistant.mdPrompt, preferred: Prefs.assistantModel }); } } ``` - [ ] **Step 6: Check it live** quickshell reloads on save. Run: `qs -p ~/Programming/GIT/quickshell/desktop ipc call assistant catalog | python3 -m json.tool | head -40` Expected: JSON with `presets` (9 or your saved list), `ops` (17 entries, no `compress`), `kinds`, `fileops` an absolute path, `outDir`, `mdPrompt`, `preferred`. Also open the canvas (SUPER+Home), stage a PDF, press Summarize: the reply is in the document's language, as before. - [ ] **Step 7: README line** In `desktop/assistant/README.md`, under the `ipc call assistant toggle` example, add: ``` qs -p ./desktop ipc call assistant catalog `catalog` answers one JSON line for deck-it's tablet tab: the Ask presets in use, the Do ops (Compress's formats as ops of their own), kind → suffixes, the fileops path, the output folder, the To .md prompt and the preferred model. Presets are sent as written, so each says which language to answer in. ``` - [ ] **Step 8: Commit** ```bash cd ~/Programming/GIT/quickshell git add desktop/shell.qml desktop/assistant/Files.js desktop/assistant/Ops.js \ desktop/assistant/Presets.js desktop/assistant/test_presets.js desktop/assistant/README.md git commit -m "feat(assistant): catalog IPC for deck-it, presets sent as written Co-Authored-By: Claude Opus 5.5 " ``` --- ### Task 3: server upload actions **Files:** - Modify: `deckit/module.py` (`Module` dataclass) - Modify: `deckit/server.py` (`do_POST`) - Test: `tests/test_server.py` - [ ] **Step 1: Write the failing tests** In `tests/test_server.py`, `setUpClass`, give the demo module an upload action. Replace the `mod.Module("demo", ...)` construction with: ```python mod.Module("demo", "Demo", lambda: {"ok": True}, {"ping": lambda body: {"got": body.get("n")}, "boom": lambda body: int(body.get("x")), "put": lambda data: {"len": len(data)}}, uploads={"put": ("audio/wav", 10)}), ``` and add to the `Server` class: ```python def test_upload_takes_raw_bytes(self): h = {**HOST, **ORIGIN, "Content-Type": "audio/wav"} status, body = self.req("POST", "/api/demo/put", h, b"RIFF1234") self.assertEqual((status, json.loads(body)), (200, {"len": 8})) def test_upload_limits(self): h = {**HOST, **ORIGIN, "Content-Type": "audio/wav"} self.assertEqual(self.req("POST", "/api/demo/put", h, b"x" * 11)[0], 400) self.assertEqual(self.req("POST", "/api/demo/put", {**h, "Content-Type": "application/json"}, b"{}")[0], 400) self.assertEqual(self.req("POST", "/api/demo/put", {"Host": "127.0.0.1:8765", **ORIGIN, "Content-Type": "audio/wav"}, b"RIFF")[0], 401) ``` - [ ] **Step 2: Run to see them fail** Run: `python3 -m unittest tests.test_server -v` Expected: ERROR, `Module.__init__() got an unexpected keyword argument 'uploads'`. - [ ] **Step 3: `Module.uploads`** In `deckit/module.py`, add the field after `actions`: ```python # action -> (content type, max bytes): actions that take a raw body, # such as a voice clip, instead of a small JSON object. uploads: dict[str, tuple[str, int]] = field(default_factory=dict) ``` - [ ] **Step 4: Route uploads in `do_POST`** In `deckit/server.py`, replace from `try:\n fn = REGISTRY.get(name).actions.get(action)` through the end of `do_POST` with: ```python try: mod_ = REGISTRY.get(name) except module.ModuleError as e: return self._send(404, str(e).encode()) fn = mod_.actions.get(action) if fn is None: return self._send(404, b"unknown action") try: length = int(self.headers.get("Content-Length", 0) or 0) except ValueError: return self._send(400, b"Invalid Content-Length") ctype, limit = mod_.uploads.get(action, ("application/json", 4096)) if self.headers.get("Content-Type") != ctype or not 0 < length <= limit: return self._send(400, b"Unexpected body") data = self.rfile.read(length) try: result = fn(data if action in mod_.uploads else json.loads(data)) except module.ModuleError as e: return self._send(400, str(e).encode()) except (ValueError, AttributeError, TypeError, KeyError): return self._send(400, b"Invalid request") if result is None: return self._send(204) return self._json(result) ``` - [ ] **Step 5: Run the tests** Run: `python3 -m unittest discover -s tests` Expected: all pass (the old oversized-body test still answers 400). - [ ] **Step 6: Commit** ```bash git add deckit/module.py deckit/server.py tests/test_server.py git commit -m "feat(server): upload actions take a raw body up to their own limit Co-Authored-By: Claude Opus 5.5 " ``` --- ### Task 4: server serves the Nerd Font **Files:** - Modify: `deckit/server.py` - Test: `tests/test_server.py` - [ ] **Step 1: Write the failing test** ```python def test_nerd_font(self): from unittest import mock import tempfile from pathlib import Path f = Path(tempfile.mkdtemp()) / "InconsolataNerdFont-Regular.ttf" f.write_bytes(b"\x00\x01\x00\x00font") srv._font.clear() with mock.patch.object(srv, "_run", return_value=str(f)): self.assertEqual(self.req("GET", "/fonts/nerd.ttf", HOST), (200, b"\x00\x01\x00\x00font")) srv._font.clear() with mock.patch.object(srv, "_run", return_value="/usr/share/fonts/DejaVuSans.ttf"): self.assertEqual(self.req("GET", "/fonts/nerd.ttf", HOST)[0], 404) srv._font.clear() ``` - [ ] **Step 2: Run to see it fail** Run: `python3 -m unittest tests.test_server.Server.test_nerd_font -v` Expected: ERROR, `module 'deckit.server' has no attribute '_font'`. - [ ] **Step 3: Implement** In `deckit/server.py`, after `art()`: ```python _font = {} def nerd_font(): """The Nerd Font the canvas draws its icons with, for the tablet.""" if "p" not in _font: out = _run(["fc-match", "-f", "%{file}", "Inconsolata Nerd Font:style=Regular"]) # fc-match falls back to any font; only a Nerd Font has the glyphs. _font["p"] = Path(out) if "NerdFont" in out.replace(" ", "") and Path(out).is_file() else None return _font["p"] ``` and in `do_GET`, after the `/icons/` branch: ```python if path == "/fonts/nerd.ttf": f = nerd_font() return self._send(200, f.read_bytes(), "font/ttf", cache=True) if f else self._send(404) ``` - [ ] **Step 4: Run the tests** Run: `python3 -m unittest discover -s tests` Expected: all pass. - [ ] **Step 5: Commit** ```bash git add deckit/server.py tests/test_server.py git commit -m "feat(server): serve the Nerd Font at /fonts/nerd.ttf Co-Authored-By: Claude Opus 5.5 " ``` --- ### Task 5: assistant state folding and the audio rule **Files:** - Create: `deckit/modules/assistant.py` - Test: `tests/test_assistant.py` - [ ] **Step 1: Write the failing tests** `tests/test_assistant.py` (license header as in `tests/test_tablet.py`, with "tests for assistant"): ```python import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) import unittest from deckit.modules import assistant as a def folded(*events): st = a.blank() for e in events: a.fold(st, e) return st class Fold(unittest.TestCase): def test_hello_with_a_reply_in_flight(self): st = folded({"type": "hello", "state": "thinking", "model": "m1", "chat_model": "c1", "turns": [{"user": "hi", "reply": "yo", "tools": ["now"], "files": []}], "pending": {"user": "and?", "reply": "par", "think": "", "tools": [], "files": []}}) self.assertEqual((st["state"], st["model"], st["chatModel"]), ("thinking", "m1", "c1")) self.assertEqual(st["turns"][0]["tools"], ["now"]) self.assertEqual(st["pending"]["reply"], "par") def test_a_turn_streams_and_settles(self): st = folded({"type": "user", "text": "q"}, {"type": "think", "delta": "h"}, {"type": "tool", "name": "web", "done": False}, {"type": "tool", "name": "web", "done": True}, {"type": "token", "delta": "a"}, {"type": "token", "delta": "b"}, {"type": "done", "id": 3}) self.assertIsNone(st["pending"]) self.assertEqual(st["turns"], [{"user": "q", "reply": "ab", "think": "h", "tools": ["web"], "stopped": False}]) def test_stop_keeps_the_partial_reply_marked(self): st = folded({"type": "user", "text": "q"}, {"type": "token", "delta": "a"}, {"type": "error", "message": "stopped", "turn": True}, {"type": "done", "id": None, "stopped": True}) self.assertEqual(st["turns"][-1]["error"], "stopped") self.assertIsNone(st["pending"]) def test_command_error_is_a_notice(self): self.assertEqual(folded({"type": "error", "message": "bad id"})["notice"], "bad id") def test_conversation_replaces_the_transcript(self): st = folded({"type": "user", "text": "q"}, {"type": "conversation", "id": None, "turns": [], "model": None}) self.assertEqual((st["turns"], st["pending"], st["epoch"]), ([], None, 1)) def test_written_ends_the_op(self): st = a.blank() st["op"] = {"label": "To .md", "running": True, "ok": False, "out": [], "error": ""} a.fold(st, {"type": "written", "path": "/x/doc.md"}) self.assertEqual((st["op"]["running"], st["op"]["ok"], st["op"]["out"]), (False, True, ["/x/doc.md"])) def test_refused_write_ends_the_op(self): st = a.blank() st["op"] = {"label": "To .md", "running": True, "ok": False, "out": [], "error": ""} a.fold(st, {"type": "error", "message": "bad write", "turn": True}) self.assertEqual((st["op"]["running"], st["op"]["error"]), (False, "bad write")) class Hears(unittest.TestCase): MODELS = [{"id": "deaf", "status": "loaded", "cloud": False, "inputs": ["text"]}, {"id": "ears", "status": "unloaded", "cloud": False, "inputs": ["text", "audio"]}, {"id": "p:big", "provider": "p", "cloud": True}] def test_local_pick_decides(self): self.assertTrue(a.hears(self.MODELS, "ears")) self.assertFalse(a.hears(self.MODELS, "deaf")) def test_cloud_or_no_pick_uses_the_loaded_model(self): self.assertFalse(a.hears(self.MODELS, "p:big")) self.assertFalse(a.hears(self.MODELS, None)) def test_unknown_is_yes(self): self.assertTrue(a.hears([], None)) self.assertTrue(a.hears([{"id": "x", "status": "loaded", "cloud": False, "inputs": None}], None)) if __name__ == "__main__": unittest.main() ``` - [ ] **Step 2: Run to see them fail** Run: `python3 -m unittest tests.test_assistant -v` Expected: ERROR, `cannot import name 'assistant'`. - [ ] **Step 3: Implement the pure part** `deckit/modules/assistant.py`: ```python # deck-it - assistant module # Copyright (C) 2026 Danilo M. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """desktop-assistant on the tablet: chat, voice, model choice, and the canvas's Ask presets and Do ops applied to a file picked on the PC. One client of the daemon's socket (JSON lines both ways; every client sees every event), folded into one state the tab polls. The protocol is desktop-assistant's docs/superpowers/specs/2026-10-16-text-daemon-design.md. """ import json import os import socket import subprocess import threading from pathlib import Path from ..module import Module, ModuleError RUN = Path(os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}")) SOCK = RUN / "desktop-assistant.sock" VOICE = RUN / "deck-it" / "voice.wav" MAX_VOICE = 2_000_000 # 60 s of 16 kHz mono 16-bit is 1.92 MB def blank(): return {"connected": False, "error": None, "state": "idle", "tool": None, "model": None, "chatModel": None, "turns": [], "pending": None, "notice": "", "models": [], "picking": None, "op": None, "catalog": None, "catalogError": "", "epoch": 0} def _turn(t): return {"user": t.get("user", ""), "reply": t.get("reply", ""), "think": t.get("think", ""), "tools": list(t.get("tools") or [])} def fold(st, e): """Apply one daemon event to the state the tab polls.""" kind = e.get("type") if kind == "hello": st.update(state=e.get("state", "idle"), tool=e.get("tool"), model=e.get("model"), chatModel=e.get("chat_model"), turns=[_turn(t) for t in e.get("turns") or []], pending=_turn(e["pending"]) if e.get("pending") else None, epoch=st["epoch"] + 1) elif kind == "state": st.update(state=e.get("state", "idle"), tool=e.get("tool")) elif kind == "user": st.update(pending=_turn({"user": e.get("text", "")}), notice="") elif kind in ("think", "token"): p = st["pending"] or _turn({}) p["think" if kind == "think" else "reply"] += e.get("delta", "") st["pending"] = p elif kind == "tool": if st["pending"] and not e.get("done"): st["pending"]["tools"].append(e.get("name", "")) elif kind == "done": if st["pending"]: st["turns"].append({**st["pending"], "stopped": bool(e.get("stopped"))}) st["pending"] = None elif kind == "error": msg = e.get("message", "") if e.get("turn") and (st["op"] or {}).get("running"): st["op"].update(running=False, error=msg) # a refused or failed write elif e.get("turn") and st["pending"]: st["turns"].append({**st["pending"], "error": msg}) st["pending"] = None else: st["notice"] = msg elif kind == "ctx": if e.get("model"): st["model"] = e["model"] elif kind == "models": st["models"] = e.get("items") or [] elif kind == "conversation": st.update(turns=[_turn(t) for t in e.get("turns") or []], pending=None, chatModel=e.get("model"), epoch=st["epoch"] + 1) elif kind == "written": if st["op"]: st["op"].update(running=False, ok=True, out=[e.get("path", "")]) def hears(models, wanted): """Whether the model that will hear a voice question takes audio: the chat's pick if it is local, else the loaded local model (a cloud chat's voice is transcribed locally). Unknown counts as yes.""" local = [m for m in models if not m.get("cloud")] m = (next((m for m in local if m.get("id") == wanted), None) or next((m for m in local if m.get("status") != "unloaded"), None)) inputs = m.get("inputs") if m else None return inputs is None or "audio" in inputs ``` - [ ] **Step 4: Run the tests** Run: `python3 -m unittest tests.test_assistant -v` Expected: PASS. (The module has no `make` yet; `unittest discover` would not load it as a deck-it module because `[modules] assistant = false` until Task 9, so the full suite still passes.) Run: `python3 -m unittest discover -s tests` Expected: all pass. - [ ] **Step 5: Commit** ```bash git add deckit/modules/assistant.py tests/test_assistant.py git commit -m "feat(assistant): fold daemon events into the tab's state Co-Authored-By: Claude Opus 5.5 " ``` --- ### Task 6: the daemon client and chat, model and voice actions **Files:** - Modify: `deckit/modules/assistant.py` - Test: `tests/test_assistant.py` - [ ] **Step 1: Write the failing tests** Append to `tests/test_assistant.py` (above `if __name__`), adding `import json, os, socket, tempfile, threading, time` to the imports: ```python class FakeDaemon: """A desktop-assistant stand-in: says hello, records commands, can push events.""" def __init__(self, path): self.got, self.conns = [], [] self.srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) self.srv.bind(path) self.srv.listen() threading.Thread(target=self.serve, daemon=True).start() def serve(self): while True: try: c, _ = self.srv.accept() except OSError: return self.conns.append(c) c.sendall(b'{"type":"hello","state":"idle","model":"m1","turns":[],"pending":null}\n') threading.Thread(target=self.read, args=(c,), daemon=True).start() def read(self, c): for line in c.makefile("r"): self.got.append(json.loads(line)) def push(self, e): for c in self.conns: c.sendall((json.dumps(e) + "\n").encode()) def close(self): for c in self.conns: c.close() self.srv.close() def until(fn, secs=2): end = time.monotonic() + secs while time.monotonic() < end: if fn(): return True time.sleep(0.02) return False class Client(unittest.TestCase): def setUp(self): self.dir = tempfile.mkdtemp(dir="/tmp") a.SOCK = Path(self.dir) / "d.sock" a.VOICE = Path(self.dir) / "deck-it" / "voice.wav" self.d = FakeDaemon(str(a.SOCK)) self.m = a.make({"assistant": {"shell": "/nonexistent"}}) self.m.start() self.assertTrue(until(lambda: self.m.state()["connected"])) def tearDown(self): self.m.stop() self.d.close() def test_connects_and_asks_for_models(self): self.assertTrue(until(lambda: {"type": "models"} in self.d.got)) self.assertEqual(self.m.state()["model"], "m1") def test_ask_carries_the_picked_model(self): self.d.push({"type": "models", "items": [{"id": "ears", "status": "loaded", "cloud": False, "inputs": ["audio"]}]}) self.assertTrue(until(lambda: self.m.state()["models"])) self.m.actions["model"]({"id": "ears"}) self.m.actions["ask"]({"text": "hi"}) self.assertTrue(until(lambda: {"type": "ask", "text": "hi", "model": "ears"} in self.d.got)) self.assertTrue(self.m.state()["hears"]) def test_bad_input_is_refused(self): for bad in ({}, {"text": ""}, {"text": 3}): with self.assertRaises(a.ModuleError): self.m.actions["ask"](bad) with self.assertRaises(a.ModuleError): self.m.actions["model"]({"id": "nope"}) def test_cloud_pick_with_turns_warns_once(self): self.d.push({"type": "models", "items": [{"id": "p:big", "provider": "p", "cloud": True}]}) self.d.push({"type": "user", "text": "q"}) self.d.push({"type": "done", "id": 1}) self.assertTrue(until(lambda: self.m.state()["models"] and self.m.state()["turns"])) self.m.actions["model"]({"id": "p:big"}) self.assertIn("goes to p", self.m.state()["notice"]) def test_voice_writes_the_clip_and_asks(self): wav = b"RIFF\x24\x00\x00\x00WAVE" + b"\x00" * 32 self.m.actions["voice"](wav) self.assertEqual(a.VOICE.read_bytes(), wav) self.assertTrue(until(lambda: {"type": "ask", "text": "", "audio": str(a.VOICE)} in self.d.got)) with self.assertRaises(a.ModuleError): self.m.actions["voice"](b"not a wav") def test_streamed_state_is_a_copy(self): self.d.push({"type": "user", "text": "q"}) self.d.push({"type": "token", "delta": "a"}) self.assertTrue(until(lambda: (self.m.state()["pending"] or {}).get("reply") == "a")) s = self.m.state() s["pending"]["reply"] = "changed" self.assertEqual(self.m.state()["pending"]["reply"], "a") ``` - [ ] **Step 2: Run to see them fail** Run: `python3 -m unittest tests.test_assistant -v` Expected: the `Client` tests ERROR with `module ... has no attribute 'make'`. - [ ] **Step 3: Implement `make` with the client and these actions** Append to `deckit/modules/assistant.py`: ```python def make(cfg: dict) -> Module: shell = os.path.expanduser(cfg.get("assistant", {}).get("shell", "")) lock = threading.Lock() # guards st send_lock = threading.Lock() # one writer on the socket at a time stop = threading.Event() st = blank() conn = {"sock": None, "qarma": None} def send(cmd): s = conn["sock"] if s is None: raise ModuleError("assistant not running") try: with send_lock: s.sendall((json.dumps(cmd) + "\n").encode()) except OSError as e: raise ModuleError(f"assistant: {e}") from None def wanted(): # Caller holds lock. As the canvas: the chat's pick, else the # preferred model, else none (the daemon uses what is loaded). return st["chatModel"] or (st["catalog"] or {}).get("preferred") or None def with_model(cmd): with lock: m = wanted() return {**cmd, "model": m} if m else cmd def loop(): while not stop.is_set(): s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) try: s.connect(str(SOCK)) except OSError as e: s.close() with lock: st.update(connected=False, error=str(e) or type(e).__name__) stop.wait(5) continue conn["sock"] = s with lock: st.update(connected=True, error=None) try: send({"type": "models"}) for line in s.makefile("r", encoding="utf-8"): try: e = json.loads(line) except ValueError: continue with lock: fold(st, e) except (OSError, ModuleError): pass conn["sock"] = None s.close() with lock: st.update(connected=False, error="disconnected") stop.wait(5) def state(): with lock: out = json.loads(json.dumps(st)) # a copy: the reader keeps writing out["wanted"] = wanted() out["hears"] = hears(st["models"], out["wanted"]) return out def ask(body): text = body.get("text") if not isinstance(text, str) or not text.strip(): raise ModuleError("text required") send(with_model({"type": "ask", "text": text})) def model(body): mid = body.get("id") with lock: m = next((x for x in st["models"] if x.get("id") == mid), None) if m is None: raise ModuleError("unknown model") was_cloud = any(x.get("cloud") and x.get("id") == wanted() for x in st["models"]) # Moving a chat with turns to the cloud sends its history there. if m.get("cloud") and not was_cloud and st["turns"]: st["notice"] = f"History in this chat goes to {m.get('provider')}." st["chatModel"] = mid def voice(data): if data[:4] != b"RIFF" or data[8:12] != b"WAVE": raise ModuleError("not a WAV") VOICE.parent.mkdir(mode=0o700, parents=True, exist_ok=True) tmp = VOICE.with_suffix(".tmp") tmp.write_bytes(data) os.replace(tmp, VOICE) send(with_model({"type": "ask", "text": "", "audio": str(VOICE)})) def close(): stop.set() s = conn["sock"] if s is not None: try: s.shutdown(socket.SHUT_RDWR) except OSError: pass return Module( name="assistant", title="Assistant", state=state, actions={"ask": ask, "stop": lambda b: send({"type": "stop"}), "new": lambda b: send({"type": "new"}), "models": lambda b: send({"type": "models"}), "model": model, "voice": voice}, uploads={"voice": ("audio/wav", MAX_VOICE)}, start=lambda: threading.Thread(target=loop, daemon=True).start(), stop=close, ) ``` - [ ] **Step 4: Run the tests** Run: `python3 -m unittest tests.test_assistant -v` Expected: PASS. Run: `python3 -m unittest discover -s tests` Expected: all pass. - [ ] **Step 5: Commit** ```bash git add deckit/modules/assistant.py tests/test_assistant.py git commit -m "feat(assistant): daemon client with chat, model and voice actions Co-Authored-By: Claude Opus 5.5 " ``` --- ### Task 7: catalog, pick, and the Do ops **Files:** - Modify: `deckit/modules/assistant.py` - Test: `tests/test_assistant.py` - [ ] **Step 1: Write the failing tests** Append (adding `import stat` to the imports): ```python CATALOG = {"presets": [{"label": "Translate", "icon": "", "kinds": ["pdf", "text"], "prompt": "Translate this into English."}], "ops": [{"label": "To .md", "icon": "", "op": "md", "kinds": ["pdf"], "max": 1}, {"label": "Merge", "icon": "", "op": "pdf-merge", "kinds": ["pdf"], "min": 2}, {"label": ".zip", "icon": "", "op": "zip", "kinds": ["any"]}], "kinds": {"pdf": [".pdf"], "text": [".md", ".txt"]}, "fileops": "", "outDir": "/tmp/out", "mdPrompt": "As Markdown.", "preferred": ""} class QarmaArgs(unittest.TestCase): def test_filter_and_multiple(self): args = a.qarma_args(CATALOG["presets"][0], CATALOG["kinds"]) self.assertIn("--multiple", args) self.assertIn("--file-filter=Translate | *.md *.pdf *.txt", args) def test_single_file_op_and_any_kind(self): self.assertNotIn("--multiple", a.qarma_args(CATALOG["ops"][0], CATALOG["kinds"])) self.assertFalse([x for x in a.qarma_args(CATALOG["ops"][2], CATALOG["kinds"]) if x.startswith("--file-filter")]) def stub(dirpath, name, body): p = Path(dirpath) / name p.write_text("#!/bin/sh\n" + body + "\n") p.chmod(p.stat().st_mode | stat.S_IXUSR) return p class Pick(Client): def setUp(self): self.bin = tempfile.mkdtemp(dir="/tmp") cat = dict(CATALOG, fileops=str(Path(self.bin) / "fileops")) stub(self.bin, "qs", "cat <<'EOF'\n" + json.dumps(cat) + "\nEOF") self.path = os.environ["PATH"] os.environ["PATH"] = self.bin + ":" + self.path super().setUp() def tearDown(self): os.environ["PATH"] = self.path super().tearDown() def test_preset_asks_with_the_picked_files(self): stub(self.bin, "qarma", "printf '/docs/a.pdf'") self.m.actions["pick"]({"preset": "Translate"}) self.assertTrue(until(lambda: {"type": "ask", "text": "Translate this into English.", "files": ["/docs/a.pdf"]} in self.d.got)) self.assertIsNone(self.m.state()["picking"]) def test_cancelled_dialog_does_nothing(self): stub(self.bin, "qarma", "exit 1") self.m.actions["pick"]({"preset": "Translate"}) self.assertTrue(until(lambda: self.m.state()["picking"] is None)) self.assertFalse([c for c in self.d.got if c["type"] == "ask"]) def test_op_runs_fileops(self): stub(self.bin, "qarma", "printf '/v/a.pdf\\n/v/b.pdf'") stub(self.bin, "fileops", 'echo \'{"ok": true, "out": ["/tmp/out/a+b.pdf"]}\'') self.m.actions["pick"]({"op": "Merge"}) self.assertTrue(until(lambda: (self.m.state()["op"] or {}).get("ok"))) self.assertEqual(self.m.state()["op"]["out"], ["/tmp/out/a+b.pdf"]) def test_op_min_is_checked(self): stub(self.bin, "qarma", "printf '/v/a.pdf'") self.m.actions["pick"]({"op": "Merge"}) self.assertTrue(until(lambda: (self.m.state()["op"] or {}).get("error"))) self.assertIn("at least 2", self.m.state()["op"]["error"]) def test_md_goes_to_the_daemon(self): stub(self.bin, "qarma", "printf '/docs/scan.pdf'") self.m.actions["pick"]({"op": "To .md"}) self.assertTrue(until(lambda: {"type": "write", "files": ["/docs/scan.pdf"], "prompt": "As Markdown.", "dir": "/tmp/out", "name": "scan.md"} in self.d.got)) def test_unknown_label_and_busy(self): stub(self.bin, "qarma", "sleep 2") with self.assertRaises(a.ModuleError): self.m.actions["pick"]({"preset": "Nope"}) self.m.actions["pick"]({"preset": "Translate"}) with self.assertRaises(a.ModuleError): self.m.actions["pick"]({"preset": "Translate"}) self.m.actions["cancel"]({}) self.assertTrue(until(lambda: self.m.state()["picking"] is None, 3)) ``` (`Pick` subclasses `Client`, so it re-runs `Client`'s tests too, which is harmless; they still pass with stubs on PATH.) - [ ] **Step 2: Run to see them fail** Run: `python3 -m unittest tests.test_assistant -v` Expected: ERROR, `module ... has no attribute 'qarma_args'`, and the `Pick` tests fail with `KeyError: 'pick'`. - [ ] **Step 3: `qarma_args`** Add after `hears` in `deckit/modules/assistant.py`: ```python def qarma_args(item, kinds): """The file dialog for a preset or op: filtered to its kinds' suffixes, several files unless the op takes one.""" args = ["qarma", "--file-selection", f"--title={item['label']}", "--separator=\n"] if item.get("max") != 1: args.append("--multiple") exts = sorted({e for k in item.get("kinds", []) for e in kinds.get(k, [])}) if exts: args.append(f"--file-filter={item['label']} | " + " ".join("*" + e for e in exts)) return args ``` - [ ] **Step 4: Catalog, pick, cancel** Inside `make`, after `voice`, add: ```python def load_catalog(): try: out = subprocess.run(["qs", "-p", shell, "ipc", "call", "assistant", "catalog"], capture_output=True, text=True, timeout=5, check=True).stdout cat, err = json.loads(out), "" except (OSError, subprocess.SubprocessError, ValueError) as e: cat, err = None, f"no presets from keystone: {e}" with lock: st.update(catalog=cat, catalogError=err) return cat def choose(cat, item): """Paths picked in qarma on the PC; [] when the dialog is cancelled.""" p = subprocess.Popen(qarma_args(item, cat.get("kinds", {})), stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True) conn["qarma"] = p out, _ = p.communicate() conn["qarma"] = None return [x for x in out.split("\n") if x.startswith("/")] if p.returncode == 0 else [] def set_op(**kw): with lock: st["op"].update(**kw) def run_pick(cat, item, kind): try: paths = choose(cat, item) except (OSError, subprocess.SubprocessError) as e: with lock: st.update(picking=None, notice=f"qarma: {e}") return with lock: st["picking"] = None if not paths: return try: if kind == "preset": send(with_model({"type": "ask", "text": item["prompt"], "files": paths})) return with lock: st["op"] = {"label": item["label"], "running": True, "ok": False, "out": [], "error": ""} if len(paths) < item.get("min", 1): set_op(running=False, error=f"{item['label']} needs at least {item['min']} files") elif item["op"] == "md": # As the canvas: the daemon writes it; `written` ends the op. send({"type": "write", "files": paths[:1], "prompt": cat["mdPrompt"], "dir": cat["outDir"], "name": Path(paths[0]).stem + ".md"}) else: try: out = subprocess.run([cat["fileops"], item["op"], cat["outDir"], *paths], capture_output=True, text=True).stdout r = json.loads(out.strip().splitlines()[-1]) except (OSError, ValueError, IndexError): r = {"ok": False, "error": "fileops gave no answer"} set_op(running=False, ok=bool(r.get("ok")), out=r.get("out") or [], error=r.get("error", "")) except ModuleError as e: with lock: if st["op"] and st["op"]["running"]: st["op"].update(running=False, error=str(e)) else: st["notice"] = str(e) def pick(body): cat = load_catalog() if not cat: raise ModuleError(st["catalogError"]) if isinstance(body.get("preset"), str): kind, items, label = "preset", cat.get("presets", []), body["preset"] elif isinstance(body.get("op"), str): kind, items, label = "op", cat.get("ops", []), body["op"] else: raise ModuleError("preset or op required") item = next((i for i in items if i.get("label") == label), None) if item is None: raise ModuleError(f"unknown {kind}: {label}") with lock: if st["picking"] or (st["op"] or {}).get("running"): raise ModuleError("busy") st.update(picking=label, op=None) threading.Thread(target=run_pick, args=(cat, item, kind), daemon=True).start() def cancel(body): p = conn["qarma"] if p is not None: p.terminate() ``` Register them: in the `actions` dict add `"pick": pick, "cancel": cancel`, and change `start` so the tab has presets before the first pick: ```python start=lambda: [threading.Thread(target=f, daemon=True).start() for f in (loop, load_catalog)], ``` - [ ] **Step 5: Run the tests** Run: `python3 -m unittest tests.test_assistant -v` Expected: PASS. Run: `python3 -m unittest discover -s tests` Expected: all pass. - [ ] **Step 6: Commit** ```bash git add deckit/modules/assistant.py tests/test_assistant.py git commit -m "feat(assistant): presets and ops on a file picked on the PC Co-Authored-By: Claude Opus 5.5 " ``` --- ### Task 8: WAV encoder and safe Markdown **Files:** - Create: `static/wav.js`, `static/md.js` - Create: `static/vendor/marked/marked.esm.js` (download), `static/vendor/marked/LICENSE.md` - Create: `tests/test_wav.mjs`, `tests/test_md.mjs`, `tests/test_js.py` - [ ] **Step 1: Vendor marked 18.2.0** ```bash mkdir -p static/vendor/marked curl -fsSL -o static/vendor/marked/marked.esm.js https://cdn.jsdelivr.net/npm/marked@18.2.0/lib/marked.esm.js curl -fsSL -o static/vendor/marked/LICENSE.md https://cdn.jsdelivr.net/npm/marked@18.2.0/LICENSE.md grep -c "export" static/vendor/marked/marked.esm.js ``` Expected: a non-zero count (an ES module). - [ ] **Step 2: Write the failing JS tests** `tests/test_wav.mjs`: ```js // deck-it - check for static/wav.js: `node tests/test_wav.mjs` import assert from "node:assert/strict"; import { encodeWav } from "../static/wav.js"; const buf = encodeWav(new Float32Array([0, 1, -1]), 16000); const v = new DataView(buf); const tag = (o) => String.fromCharCode(...new Uint8Array(buf, o, 4)); assert.equal(buf.byteLength, 44 + 6); assert.equal(tag(0), "RIFF"); assert.equal(tag(8), "WAVE"); assert.equal(v.getUint16(20, true), 1); // PCM assert.equal(v.getUint16(22, true), 1); // mono assert.equal(v.getUint32(24, true), 16000); assert.equal(v.getUint16(34, true), 16); assert.equal(v.getUint32(40, true), 6); assert.deepEqual([v.getInt16(44, true), v.getInt16(46, true), v.getInt16(48, true)], [0, 32767, -32768]); console.log("wav ok"); ``` `tests/test_md.mjs`: ```js // deck-it - check for static/md.js: `node tests/test_md.mjs` import assert from "node:assert/strict"; import { render } from "../static/md.js"; assert.match(render("**hi**"), /hi<\/strong>/); assert.match(render("```\ncode\n```"), /
code/);
assert.match(render("| a |\n| - |\n| 1 |"), //);
assert.ok(!render("a x").includes(""), "inline HTML escaped");
assert.ok(!render("").includes("x<\/a>/);
console.log("md ok");
```

`tests/test_js.py` (license header as the other tests):

```python
"""Runs the plain-node checks for the frontend's pure modules."""

import shutil
import subprocess
import unittest
from pathlib import Path

HERE = Path(__file__).resolve().parent


@unittest.skipUnless(shutil.which("node"), "node not installed")
class Node(unittest.TestCase):
    def test_checks(self):
        for f in sorted(HERE.glob("test_*.mjs")):
            with self.subTest(f.name):
                r = subprocess.run(["node", str(f)], capture_output=True, text=True)
                self.assertEqual(r.returncode, 0, r.stderr)
```

- [ ] **Step 3: Run to see them fail**

Run: `node tests/test_wav.mjs`
Expected: `ERR_MODULE_NOT_FOUND` for `static/wav.js`.

- [ ] **Step 4: `static/wav.js`**

```js
// deck-it - WAV for the assistant's voice questions
// (GPLv2 header as in static/modules/obs.js)

// The daemon takes a WAV (desktop-assistant checks its header and length),
// and MediaRecorder gives webm/opus, so the clip is decoded, resampled to
// 16 kHz mono and written as 16-bit PCM here.

export function encodeWav(samples, rate) {
  const buf = new ArrayBuffer(44 + samples.length * 2);
  const v = new DataView(buf);
  const tag = (o, s) => { for (let i = 0; i < 4; i++) v.setUint8(o + i, s.charCodeAt(i)); };
  tag(0, "RIFF"); v.setUint32(4, 36 + samples.length * 2, true); tag(8, "WAVE");
  tag(12, "fmt "); v.setUint32(16, 16, true); v.setUint16(20, 1, true); v.setUint16(22, 1, true);
  v.setUint32(24, rate, true); v.setUint32(28, rate * 2, true); v.setUint16(32, 2, true);
  v.setUint16(34, 16, true);
  tag(36, "data"); v.setUint32(40, samples.length * 2, true);
  for (let i = 0; i < samples.length; i++) {
    const s = Math.max(-1, Math.min(1, samples[i]));
    v.setInt16(44 + i * 2, s < 0 ? s * 0x8000 : s * 0x7fff, true);
  }
  return buf;
}

export async function toWav(blob, rate = 16000) {
  const ctx = new AudioContext();
  try {
    const decoded = await ctx.decodeAudioData(await blob.arrayBuffer());
    const off = new OfflineAudioContext(1, Math.ceil(decoded.duration * rate), rate);
    const src = off.createBufferSource();
    src.buffer = decoded;
    src.connect(off.destination);
    src.start();
    return encodeWav((await off.startRendering()).getChannelData(0), rate);
  } finally {
    ctx.close();
  }
}
```

(Write the full GPLv2 header block, copied from `static/modules/obs.js`
with the first line changed, in place of the parenthesised note; same for
`md.js` and `assistant.js` below.)

- [ ] **Step 5: `static/md.js`**

```js
// deck-it - Markdown for the assistant's replies
// (GPLv2 header as in static/modules/obs.js)

// As the canvas: raw HTML from the model is shown as text, links only for
// http(s) and mailto, and an image is a link, never fetched (a quoted
// search result would otherwise make the tablet load a remote URL).

import { Marked } from "./vendor/marked/marked.esm.js";

const esc = (s) => String(s).replace(/[&<>"']/g, (c) =>
  ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
const SAFE = /^(https?:|mailto:)/i;
const out = (href, inner) => `${inner}`;

const md = new Marked({
  gfm: true,
  renderer: {
    html({ text }) { return esc(text); },
    link({ href, tokens }) {
      const inner = this.parser.parseInline(tokens);
      return SAFE.test(href ?? "") ? out(href, inner) : inner;
    },
    image({ href, text }) {
      return SAFE.test(href ?? "") ? out(href, esc(text || href)) : esc(text);
    },
  },
});

export function render(text) { return md.parse(text ?? ""); }
```

- [ ] **Step 6: Run the JS checks**

Run: `node tests/test_wav.mjs && node tests/test_md.mjs`
Expected: `wav ok`, `md ok`. If a renderer assertion fails, read
`static/vendor/marked/marked.esm.js`'s `_Renderer` class for the 18.x
method signatures (`html`, `link`, `image`) and adjust `md.js` to them.

Run: `python3 -m unittest discover -s tests && node --check static/wav.js && node --check static/md.js`
Expected: all pass.

- [ ] **Step 7: Commit**

```bash
git add static/wav.js static/md.js static/vendor/marked tests/test_wav.mjs tests/test_md.mjs tests/test_js.py
git commit -m "feat(assistant): WAV encoder and safe Markdown for the tab

Vendors marked 18.2.0 (MIT).

Co-Authored-By: Claude Opus 5.5 "
```

---

### Task 9: config and enabling the module

**Files:**
- Modify: `config.toml`

- [ ] **Step 1: Turn it on and add the table**

In `[modules]`, change `assistant = false` to `assistant = true`, and add
after the `[k1c]` table:

```toml
[assistant]
# keystone's desktop shell, the quickshell config whose `assistant catalog`
# IPC call lists the canvas's Ask presets and Do ops for the tab.
shell = "~/Programming/GIT/quickshell/desktop"
```

- [ ] **Step 2: Check `deck-it defaults` still prints valid JSON**

Run: `./deck-it defaults | python3 -m json.tool | grep -A2 '"assistant"'`
Expected: the `assistant` table with `shell`, and `"assistant": true` under modules.

- [ ] **Step 3: Run the suite**

Run: `python3 -m unittest discover -s tests`
Expected: all pass. `test_panel_for_every_module` FAILS now: no
`static/modules/assistant.js` yet. That is Task 10's first file; do not
commit this task alone, commit it with Task 10.

---

### Task 10: the tab

**Files:**
- Create: `static/modules/assistant.js`
- Modify: `static/deck.css`

- [ ] **Step 1: `static/modules/assistant.js`**

```js
// deck-it - assistant panel
// (GPLv2 header as in static/modules/obs.js)

// desktop-assistant on the tablet: chat with formatted streamed replies,
// voice through the tablet's mic, model choice, and the canvas's Ask
// presets and Do ops on a file picked on the PC. Every control is an icon
// (the Nerd Font the server serves), sized for a finger.

import { offline } from "../offline.js";
import { render } from "../md.js";
import { toWav } from "../wav.js";

// Font Awesome codepoints, present in Inconsolata Nerd Font.
const G = { send: "", stop: "", mic: "", micOff: "", plus: "",
            cloud: "", close: "", copy: "", fallback: "" };
const MAX_REC = 59;
const STATUS = { thinking: "thinking…", transcribing: "transcribing…" };

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

function iconBtn(glyph, label, cls = "") {
  const b = document.createElement("button");
  b.className = `ib nf ${cls}`;
  b.textContent = glyph;
  b.setAttribute("aria-label", label);
  b.title = label;
  return b;
}

function note(el, text) {
  el._note = text;
  clearTimeout(el._noteT);
  el._noteT = setTimeout(() => { el._note = ""; }, 6000);
}

function act(el, action, body) {
  post(action, body).catch((e) => note(el, e.message));
}

function addCopy(box) {
  for (const pre of box.querySelectorAll("pre")) {
    const b = iconBtn(G.copy, "Copy", "copy");
    // The tablet's clipboard; the button's own glyph is outside .
    b.onclick = () => navigator.clipboard?.writeText(pre.querySelector("code")?.innerText ?? "");
    pre.append(b);
  }
}

function turnNode(t, live) {
  const d = document.createElement("div");
  d.className = "as-turn";
  if (t.user) {
    const q = document.createElement("div");
    q.className = "as-q";
    q.textContent = t.user;
    d.append(q);
  }
  if (t.tools?.length) {
    const tools = document.createElement("div");
    tools.className = "as-tools";
    tools.textContent = t.tools.join(" · ");
    d.append(tools);
  }
  const a = document.createElement("div");
  a.className = "as-a md";
  a.innerHTML = render(t.reply);
  if (!live) addCopy(a);
  d.append(a);
  if (t.error && t.error !== "stopped") {
    const e = document.createElement("div");
    e.className = "as-err bad";
    e.textContent = t.error;
    d.append(e);
  }
  return d;
}

function renderLog(log, st, el) {
  const bottom = log.scrollHeight - log.scrollTop - log.clientHeight < 40;
  if (el._epoch !== st.epoch || el._done > st.turns.length) {
    log.textContent = "";
    el._epoch = st.epoch;
    el._done = 0;
  }
  log.querySelector(".as-live")?.remove();
  for (; el._done < st.turns.length; el._done++) log.append(turnNode(st.turns[el._done], false));
  if (st.pending) {
    const live = turnNode(st.pending, true);
    live.classList.add("as-live");
    log.append(live);
  }
  if (bottom) log.scrollTop = log.scrollHeight;
}

function renderStrip(strip, st, el) {
  if (st.picking) {
    const key = `picking:${st.picking}`;
    if (strip._key === key) return;
    strip._key = key;
    strip.innerHTML = `
`; strip.querySelector("span").textContent = `${st.picking}: choose the file on the PC`; const cancel = iconBtn(G.close, "Cancel"); cancel.onclick = () => act(el, "cancel"); strip.firstElementChild.append(cancel); return; } const cat = st.catalog; const key = JSON.stringify([cat?.presets, cat?.ops, st.catalogError]); if (strip._key === key) return; strip._key = key; strip.textContent = ""; if (!cat) { strip.innerHTML = `
`; strip.firstElementChild.textContent = st.catalogError || "Loading presets…"; return; } for (const [kind, items] of [["preset", cat.presets ?? []], ["op", cat.ops ?? []]]) { const row = document.createElement("div"); row.className = `as-row ${kind}`; for (const item of items) { const b = document.createElement("button"); b.className = "as-tile"; b.title = item.prompt ?? item.label; b.setAttribute("aria-label", item.label); b.innerHTML = ``; b.querySelector("i").textContent = item.icon || G.fallback; b.querySelector("span").textContent = item.label; b.onclick = () => act(el, "pick", { [kind]: item.label }); row.append(b); } strip.append(row); } } function renderOp(box, op) { box.hidden = !op; if (!op) return; const name = (p) => p.slice(p.lastIndexOf("/") + 1); box.className = `as-op ${op.running ? "" : op.ok ? "good" : "bad"}`; box.textContent = op.running ? `${op.label}…` : op.ok ? `Saved: ${op.out.map(name).join(", ")}` : `${op.label}: ${op.error}`; } function renderModels(panel, st, el) { const key = JSON.stringify([st.models, st.wanted]); if (panel._key === key) return; panel._key = key; panel.textContent = ""; for (const m of st.models) { const b = document.createElement("button"); b.className = `as-mrow${m.id === st.wanted ? " on" : ""}`; b.innerHTML = ``; b.querySelector("i").textContent = m.cloud ? G.cloud : ""; b.querySelector("span").textContent = m.id; b.querySelector("small").textContent = m.cloud ? m.provider : m.status; b.onclick = () => { panel.hidden = true; act(el, "model", { id: m.id }); }; panel.append(b); } } async function toggleMic(el) { if (el._rec) { el._rec.stop(); return; } let stream; try { stream = await navigator.mediaDevices.getUserMedia({ audio: true }); } catch (e) { el._micDenied = true; note(el, `microphone: ${e.message}`); return; } const rec = new MediaRecorder(stream); const chunks = []; rec.ondataavailable = (e) => chunks.push(e.data); rec.onstop = async () => { stream.getTracks().forEach((t) => t.stop()); clearTimeout(el._recCap); const secs = (Date.now() - el._recAt) / 1000; el._rec = null; if (secs < 0.5) return; try { const wav = await toWav(new Blob(chunks, { type: rec.mimeType })); const r = await fetch("/api/assistant/voice", { method: "POST", headers: { "Content-Type": "audio/wav" }, body: wav, }); if (!r.ok) throw new Error((await r.text()) || r.statusText); } catch (e) { note(el, `voice: ${e.message}`); } }; el._rec = rec; el._recAt = Date.now(); rec.start(); el._recCap = setTimeout(() => rec.state === "recording" && rec.stop(), MAX_REC * 1000); } export default { title: "Assistant", tab: "Assistant", interval: 0.5, mount(el) { el.innerHTML = `
`; const head = el.querySelector(".as-head"); const fresh = iconBtn(G.plus, "New chat"); fresh.onclick = () => act(el, "new"); head.append(fresh); const panel = el.querySelector(".as-models"); el.querySelector(".as-model").onclick = () => { panel.hidden = !panel.hidden; if (!panel.hidden) act(el, "models"); }; el.querySelector(".as-log").onclick = () => { panel.hidden = true; }; const bar = el.querySelector(".as-bar"); const input = bar.querySelector("textarea"); const mic = iconBtn(G.mic, "Ask by voice", "mic"); mic.onclick = () => toggleMic(el); const send = iconBtn(G.send, "Send", "send"); send.onclick = () => { if (el._busy) return act(el, "stop"); const text = input.value.trim(); if (!text) return; input.value = ""; act(el, "ask", { text }); }; input.addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); send.onclick(); } }); bar.append(mic, send); }, update(st, el) { const main = el.querySelector(".as-main"); const off = el.querySelector(".as-off"); main.hidden = !st.connected; if (!st.connected) { offline(off, { icon: "/icons/assistant.svg", // hidden by offline.js when the theme has none title: "Assistant not running", detail: "Start desktop-assistant and the chat appears here.", reason: st.error, }); return; } off.textContent = ""; off._offline = null; el._busy = !!st.pending || st.state !== "idle"; const model = el.querySelector(".as-model"); const cloud = st.models.some((m) => m.cloud && m.id === st.wanted); model.querySelector("i").textContent = cloud ? G.cloud : ""; model.querySelector("span").textContent = st.wanted || st.model || "model"; el.querySelector(".as-status").textContent = st.state === "tool" ? `running ${st.tool}…` : STATUS[st.state] ?? ""; const panel = el.querySelector(".as-models"); if (!panel.hidden) renderModels(panel, st, el); renderStrip(el.querySelector(".as-strip"), st, el); renderOp(el.querySelector(".as-op"), st.op); renderLog(el.querySelector(".as-log"), st, el); el.querySelector(".as-notice").textContent = el._note || st.notice || ""; const send = el.querySelector(".send"); send.textContent = el._busy ? G.stop : G.send; send.setAttribute("aria-label", el._busy ? "Stop" : "Send"); send.title = send.getAttribute("aria-label"); const mic = el.querySelector(".mic"); const deaf = !st.hears || el._micDenied; mic.disabled = deaf && !el._rec; mic.textContent = deaf ? G.micOff : G.mic; mic.classList.toggle("on", !!el._rec); mic.title = el._micDenied ? "Microphone not allowed" : !st.hears ? `${st.wanted || st.model} takes no audio` : el._rec ? `Recording ${Math.floor((Date.now() - el._recAt) / 1000)}s, tap to send` : "Ask by voice"; mic.dataset.secs = el._rec ? `${Math.floor((Date.now() - el._recAt) / 1000)}` : ""; }, }; ``` - [ ] **Step 2: Styles** Append to `static/deck.css`: ```css /* Assistant tab. Icons are the Nerd Font glyphs the canvas uses, served by deck-it from the PC; every control is at least 48px for a finger. */ @font-face { font-family: "deckit-nerd"; src: url("/fonts/nerd.ttf") format("truetype"); font-display: block; } .nf { font-family: "deckit-nerd"; font-style: normal; } .assistant { display: flex; flex-direction: column; height: calc(100dvh - 120px); } .assistant .as-main { display: flex; flex-direction: column; gap: 10px; flex: 1; min-height: 0; position: relative; } .assistant .ib { min-width: 48px; min-height: 48px; border-radius: 12px; font-size: 1.4rem; background: var(--udt-surface0); border: 1px solid var(--udt-surface1); color: var(--udt-text); cursor: pointer; } .assistant .ib:active { background: var(--udt-surface1); } .assistant .ib:disabled { opacity: .4; } .assistant .as-head { display: flex; align-items: center; gap: 10px; } .assistant .as-model { min-height: 48px; padding: 0 14px; border-radius: 12px; font: inherit; display: flex; gap: 8px; align-items: center; background: var(--udt-surface0); border: 1px solid var(--udt-surface1); color: var(--udt-text); max-width: 50%; } .assistant .as-model span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .assistant .as-status { flex: 1; color: var(--udt-subtext0); font-size: 0.857rem; } .assistant .as-models { position: absolute; top: 58px; left: 0; z-index: 2; max-height: 60%; overflow-y: auto; min-width: 50%; background: var(--udt-mantle); border: 1px solid var(--udt-surface1); border-radius: 12px; padding: 6px; } .assistant .as-mrow { display: flex; align-items: center; gap: 10px; width: 100%; min-height: 48px; padding: 0 10px; font: inherit; background: none; border: 1px solid transparent; border-radius: 8px; color: var(--udt-text); text-align: left; } .assistant .as-mrow.on { border-color: var(--udt-accent); } .assistant .as-mrow span { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .assistant .as-mrow small { color: var(--udt-overlay0); } .assistant .as-row { display: flex; gap: 8px; overflow-x: auto; padding-bottom: 4px; } .assistant .as-tile { flex: none; width: 84px; min-height: 72px; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 4px; border-radius: 12px; font: inherit; cursor: pointer; background: var(--udt-surface0); border: 1px solid var(--udt-surface1); color: var(--udt-text); } .assistant .as-row.op .as-tile { background: var(--udt-surface1); } .assistant .as-tile i { font-size: 1.6rem; } .assistant .as-tile span { font-size: 0.714rem; color: var(--udt-subtext0); max-width: 76px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .assistant .as-picking { display: flex; align-items: center; gap: 12px; min-height: 72px; color: var(--udt-yellow); } .assistant .as-picking span { flex: 1; } .assistant .as-op, .assistant .as-notice, .assistant .as-note { font-size: 0.857rem; color: var(--udt-subtext0); } .assistant .as-notice:empty { display: none; } .assistant .as-log { flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 14px; padding-right: 4px; } .assistant .as-q { align-self: flex-end; background: var(--udt-surface1); border-radius: 12px; padding: 8px 12px; white-space: pre-wrap; margin-left: 20%; } .assistant .as-tools { font-size: 0.786rem; color: var(--udt-overlay0); } .assistant .md { line-height: 1.45; overflow-wrap: anywhere; } .assistant .md pre { position: relative; background: var(--udt-crust); border-radius: 8px; padding: 10px; overflow-x: auto; } .assistant .md pre .copy { position: absolute; top: 4px; right: 4px; } .assistant .md code { font-family: "Inconsolata Nerd Font Mono", ui-monospace, monospace; } .assistant .md table { border-collapse: collapse; } .assistant .md th, .assistant .md td { border: 1px solid var(--udt-surface1); padding: 4px 8px; } .assistant .md a { color: var(--udt-accent); } .assistant .as-bar { display: flex; gap: 8px; align-items: flex-end; } .assistant .as-bar textarea { flex: 1; min-height: 48px; max-height: 30vh; resize: none; font: inherit; padding: 12px; border-radius: 12px; background: var(--udt-surface0); border: 1px solid var(--udt-surface1); color: var(--udt-text); field-sizing: content; } .assistant .mic.on { background: var(--udt-red); border-color: var(--udt-red); color: var(--udt-crust); } .assistant .mic.on::after { content: attr(data-secs); font-family: inherit; font-size: 0.714rem; margin-left: 4px; } ``` Check the variable names used (`--udt-mantle`, `--udt-crust`, `--udt-yellow`, `--udt-red`, `--udt-accent`, `--udt-overlay0`) exist: `grep -o -- '--udt-[a-z0-9]*' static/deck.css | sort -u` and `curl`-free: `python3 -c "from deckit import theme; print(theme.load())" | grep -o -- '--udt-[a-z0-9]*' | sort -u`. Replace any missing one with the nearest that exists. - [ ] **Step 3: Checks** Run: `node --check static/modules/assistant.js && python3 -m unittest discover -s tests` Expected: all pass, including `test_panel_for_every_module`. - [ ] **Step 4: Commit (with Task 9)** ```bash git add config.toml static/modules/assistant.js static/deck.css git commit -m "feat(assistant): the Assistant tab Chat with formatted streamed replies, voice through the tablet's mic, model choice, and the canvas's Ask presets and Do ops on a file picked on the PC with qarma. Icon controls from the Nerd Font, 48px minimum. Co-Authored-By: Claude Opus 5.5 " ``` --- ### Task 11: docs **Files:** - Modify: `AGENTS.md`, `README.md` - [ ] **Step 1: AGENTS.md** After the `tablet` bullet in "How it fits together", add: ```markdown - `assistant` is a client of desktop-assistant's socket (`$XDG_RUNTIME_DIR/desktop-assistant.sock`, JSON lines; every client sees every event); a reader thread folds events into the state the tab polls every 0.5s. Presets, ops and paths come from quickshell's `qs -p <[assistant] shell> ipc call assistant catalog`. Files are picked on the PC with qarma, never named by the tablet. Voice is a WAV upload (`Module.uploads`, a raw body with its own size limit) written to the run dir and asked with `audio`. The tab's icons are the Nerd Font the server serves at `/fonts/nerd.ttf`; Markdown goes through `static/md.js` (vendored `marked`, HTML escaped, images never fetched). ``` and under Testing add: `node tests/test_*.mjs` runs inside the unittest suite through `tests/test_js.py`. - [ ] **Step 2: README.md** In Requirements, PC list, add `- optional: desktop-assistant and qarma for the Assistant tab`. In Usage, add **Assistant** to the tab list, and a bullet: ```markdown - The Assistant tab talks to desktop-assistant: type or tap the mic to ask, pick the model, and use the canvas's Ask presets and Do ops on a file you choose in a dialog on the PC (add a Translate preset on keystone's Ask presets page to get one here). ``` - [ ] **Step 3: Commit** ```bash git add AGENTS.md README.md git commit -m "docs: the Assistant tab Co-Authored-By: Claude Opus 5.5 " ``` --- ### Task 12: manual check on the tablet - [ ] Restart: `deck-it stop && deck-it wifi` (or the USB start). - [ ] Assistant tab appears; header shows the loaded model; icons render (not boxes). If boxes: `curl --unix-socket $XDG_RUNTIME_DIR/deck-it/http.sock -H 'Host: 127.0.0.1:8765' -o /dev/null -w '%{http_code}' http://x/fonts/nerd.ttf` must be 200. - [ ] Typed question: reply streams, Markdown formatted, code block gets a copy icon when done; Stop mid-reply works. - [ ] Open the canvas on the PC: the same conversation shows there; New on the tablet clears both. - [ ] Model panel: lists local and cloud; picking a cloud model in a chat with turns shows the history notice. - [ ] Mic: first tap asks permission; record ~3s, tap again; "transcribing…" then the transcribed question and its reply. With a model without audio, the mic is greyed out. - [ ] Add a "Translate" preset on keystone's Ask presets page (prompt "Translate this into English.", kinds pdf and text); tap it on the tablet; qarma opens on the PC filtered to PDFs and text; pick a file; the translation streams on the tablet. - [ ] Do op "To PNG" on an image: "Saved: .png"; the file is in the output folder. Merge with one PDF: "needs at least 2 files". ### Task 13: write the deviations back into the spec - [ ] In `docs/superpowers/specs/2026-11-10-assistant-design.md`: - catalog: drop `routerRoot`; models: "inputs come from the daemon's `models` event (desktop-assistant reports `architecture.input_modalities` per local model)"; - Voice: "`MediaRecorder`, then `decodeAudioData` and an `OfflineAudioContext` at 16 kHz mono, then a JS WAV encoder"; - Pick: "`--multiple` unless the op has `max: 1`; an op's `min` is checked after the pick"; - UI: "a code block gets a copy icon once its turn is finished"; - catalog `ops`: "Compress's formats as ops of their own, kind `any`". - [ ] Commit: ```bash git add docs/superpowers/specs/2026-11-10-assistant-design.md git commit -m "docs: assistant spec follows the plan's decisions Co-Authored-By: Claude Opus 5.5 " ```