aboutsummaryrefslogtreecommitdiffstats
path: root/docs/superpowers/plans/2026-11-10-assistant.md
blob: 4cee512407be4072d22b83b55ca960b6cfc0f5bd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
# 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 <noreply@anthropic.com>`):
`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 <noreply@anthropic.com>"
```

---

### 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 <this dir> ipc call assistant toggle    -> SUPER+Home
    //   qs -p <this dir> 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 <noreply@anthropic.com>"
```

---

### 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 <noreply@anthropic.com>"
```

---

### 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 <noreply@anthropic.com>"
```

---

### 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. <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.

"""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 <noreply@anthropic.com>"
```

---

### 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 <noreply@anthropic.com>"
```

---

### 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 <noreply@anthropic.com>"
```

---

### 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**"), /<strong>hi<\/strong>/);
assert.match(render("```\ncode\n```"), /<pre><code>code/);
assert.match(render("| a |\n| - |\n| 1 |"), /<table>/);
assert.ok(!render("a <b>x</b>").includes("<b>"), "inline HTML escaped");
assert.ok(!render("<img src=x onerror=alert(1)>").includes("<img"), "block HTML escaped");
assert.ok(!render("![p](https://example.org/p.png)").includes("<img"), "images never load");
assert.match(render("![p](https://example.org/p.png)"), /href="https:\/\/example.org\/p.png"/);
assert.ok(!render("[x](javascript:alert(1))").includes("href"), "unsafe link dropped");
assert.match(render("[x](https://example.org)"), /<a href="https:\/\/example.org" target="_blank" rel="noopener noreferrer">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) =>
  ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
const SAFE = /^(https?:|mailto:)/i;
const out = (href, inner) => `<a href="${esc(href)}" target="_blank" rel="noopener noreferrer">${inner}</a>`;

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 <noreply@anthropic.com>"
```

---

### 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 <code>.
    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 = `<div class="as-picking"><span></span></div>`;
    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 = `<div class="as-note"></div>`;
    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 = `<i class="nf"></i><span></span>`;
      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 = `<i class="nf"></i><span></span><small></small>`;
    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 = `
      <div class="assistant">
        <div class="as-off"></div>
        <div class="as-main">
          <div class="as-head">
            <button class="as-model"><i class="nf"></i><span></span></button>
            <span class="as-status"></span>
          </div>
          <div class="as-models" hidden></div>
          <div class="as-strip"></div>
          <div class="as-op" hidden></div>
          <div class="as-log"></div>
          <div class="as-notice"></div>
          <div class="as-bar"><textarea rows="1" aria-label="Question"></textarea></div>
        </div>
      </div>`;
    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 <noreply@anthropic.com>"
```

---

### 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 <noreply@anthropic.com>"
```

---

### 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: <name>.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 <noreply@anthropic.com>"
```