snyvi 1.3.0

A fast, beautiful viewer for the documents your agents produce
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
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
//! The local HTTP server: UI shell, JSON API, SSE, and the receive endpoint.

use crate::browse::Browser;
use crate::config::{self, Paths};
use crate::platform;
use crate::receive::{self, Payload};
use crate::render::{self, Renderer};
use crate::store::{Doc, Store};
use axum::{
    body::Body,
    extract::{
        ws::{Message, WebSocket, WebSocketUpgrade},
        Path, Query, State,
    },
    http::{header, HeaderMap, HeaderValue, StatusCode},
    response::{
        sse::{Event, KeepAlive, Sse},
        Html, IntoResponse, Response,
    },
    routing::{get, post},
    Json, Router,
};
use serde::Deserialize;
use serde_json::json;
use std::borrow::Cow;
use std::convert::Infallible;
use std::path::PathBuf;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Instant;
use tokio::sync::broadcast;
use tokio_stream::{wrappers::BroadcastStream, StreamExt};

pub const VERSION: &str = env!("CARGO_PKG_VERSION");
/// The commit and target from build.rs, "" outside a checkout.
pub const BUILD_SHA: &str = env!("SNYVI_GIT_SHA");
pub const BUILD_TARGET: &str = env!("SNYVI_TARGET");

const INDEX_HTML: &str = include_str!("../ui/index.html");
const APP_CSS: &str = include_str!(concat!(env!("OUT_DIR"), "/app.css"));
const APP_JS: &str = include_str!(concat!(env!("OUT_DIR"), "/app.js"));
const BOOT_JS: &str = include_str!(concat!(env!("OUT_DIR"), "/boot.js"));
/// The diagram driver, imported by app.js with the first diagram and never on a
/// page without one. A module, so it is fetched rather than linked.
const MMD_JS: &str = include_str!(concat!(env!("OUT_DIR"), "/mmd.js"));
/// The desk view: the pane grid, the painter, the keys. Loaded when a desk is
/// opened and not before, like the diagram driver -- a reader who never opens a
/// desk pays nothing for it.
const DESK_JS: &str = include_str!(concat!(env!("OUT_DIR"), "/desk.js"));
/// The window's frame -- the bar's three buttons and what drags -- fetched
/// only inside the native window, since a tab has no window to frame.
const FRAME_JS: &str = include_str!(concat!(env!("OUT_DIR"), "/frame.js"));
/// The game behind the rocket at the foot of the sidebar, fetched when the
/// rocket is pressed and never before: a reader who never presses it pays
/// nothing for it.
const GAME_JS: &str = include_str!(concat!(env!("OUT_DIR"), "/game.js"));
/// The about panel and the reset dialog, fetched when one of them is opened:
/// neither is on the way to reading a document, and both ask the daemon
/// something the moment they open, so the module rides with that request.
const ABOUT_JS: &str = include_str!(concat!(env!("OUT_DIR"), "/about.js"));
/// Find in the document -- the bar `/` opens and the marks it lays down --
/// fetched the first time it is asked for. A reader who never searches inside
/// a document never fetches it, and the page's calls into it are no-ops until
/// it is there, because until then nothing is marked.
const FIND_JS: &str = include_str!(concat!(env!("OUT_DIR"), "/find.js"));
/// What a folder and a desk can be asked to do -- the right-click menu, making
/// a desk, closing one, opening a folder -- fetched on the first such click. A
/// reader who only reads never fetches it; the sidebar draws its desks without
/// it, because drawing them is in `app.js` and only doing something is here.
const MENU_JS: &str = include_str!(concat!(env!("OUT_DIR"), "/menu.js"));
/// Mermaid, gzip-compressed at build time; served with Content-Encoding: gzip.
const MERMAID_JS_GZ: &[u8] = include_bytes!("../ui/mermaid.min.js.gz");
/// Content-Security-Policy for the UI. Everything comes from the daemon itself; Mermaid
/// needs inline styles for the SVG it produces, and images may be data URIs.
const CSP: &str = "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'";
const FONTS: &[(&str, &[u8])] = &[
    ("inter.woff2", include_bytes!("../ui/fonts/inter.woff2")),
    (
        "inter-italic.woff2",
        include_bytes!("../ui/fonts/inter-italic.woff2"),
    ),
    (
        "jetbrains-mono.woff2",
        include_bytes!("../ui/fonts/jetbrains-mono.woff2"),
    ),
    (
        "source-serif.woff2",
        include_bytes!("../ui/fonts/source-serif.woff2"),
    ),
    (
        "source-serif-italic.woff2",
        include_bytes!("../ui/fonts/source-serif-italic.woff2"),
    ),
    // Literata and Atkinson Hyperlegible Next (both OFL), latin cuts: two
    // more reading faces for the Aa button. Fetched only when chosen.
    (
        "literata.woff2",
        include_bytes!("../ui/fonts/literata.woff2"),
    ),
    (
        "literata-italic.woff2",
        include_bytes!("../ui/fonts/literata-italic.woff2"),
    ),
    (
        "atkinson.woff2",
        include_bytes!("../ui/fonts/atkinson.woff2"),
    ),
    (
        "atkinson-italic.woff2",
        include_bytes!("../ui/fonts/atkinson-italic.woff2"),
    ),
    // Nerd Fonts' symbols (MIT, `symbols-nerd.LICENSE`), cut to the private
    // use area: the icons a prompt draws in a pane. Fetched only when a pane
    // shows one -- the face's `unicode-range` in ui/desk.js.
    (
        "symbols-nerd.woff2",
        include_bytes!("../ui/fonts/symbols-nerd.woff2"),
    ),
];

/// Where the UI is read from.
///
/// The shipped daemon serves the five text assets `include_str!` compiled into
/// it, which is why a stylesheet change costs a rebuild: the bytes are in the
/// binary. They are the files in `ui/` with their comments and indentation
/// taken out -- `build.rs` runs each through `crate::strip` on the way in, so
/// the wire carries what a browser reads and the source keeps its prose.
/// `SNYVI_UI_DIR` points at a working tree's `ui/` instead, and every request
/// reads the file off disk, as written, comments and all: the dev loop is
/// where a person reads them. That is the whole dev loop -- a saved stylesheet
/// becomes a reload, and with the watcher below, not even that.
///
/// Dev only, and it says so: the variable has to be set deliberately, an unset
/// or unreadable one falls back to the compiled-in copy rather than failing,
/// and nothing about the response changes except its cache header. The names
/// are these four constants, never anything a request carries, so there is no
/// path for a URL to reach a file that is not one of them.
pub struct Ui {
    dir: Option<PathBuf>,
}

impl Ui {
    fn from_env() -> Ui {
        let dir = std::env::var_os("SNYVI_UI_DIR")
            .map(PathBuf::from)
            .filter(|d| d.join("app.css").is_file());
        Ui { dir }
    }

    /// True while assets come off disk.
    pub fn live(&self) -> bool {
        self.dir.is_some()
    }

    /// The named asset: off disk when live, the compiled-in copy otherwise.
    /// A file that has gone missing mid-edit -- an editor writing by rename --
    /// falls back rather than serving an empty page.
    fn text(&self, name: &str, built_in: &'static str) -> Cow<'static, str> {
        self.dir
            .as_ref()
            .and_then(|d| std::fs::read_to_string(d.join(name)).ok())
            .map_or(Cow::Borrowed(built_in), Cow::Owned)
    }

    /// What the UI assets hash to right now. The page carries this as
    /// `?v=`, `/api/health` reports it, and a page whose copy no longer
    /// matches the daemon's reloads -- so recomputing it per request is what
    /// makes an edit on disk a new bundle, with no restart in it.
    fn version(&self, built_in: &str) -> String {
        let Some(_) = self.dir.as_ref() else {
            return built_in.to_string();
        };
        let mut h = blake3::Hasher::new();
        for (name, fallback) in [
            ("index.html", INDEX_HTML),
            ("app.css", APP_CSS),
            ("app.js", APP_JS),
            ("boot.js", BOOT_JS),
            ("mmd.js", MMD_JS),
            ("desk.js", DESK_JS),
            ("frame.js", FRAME_JS),
            ("game.js", GAME_JS),
            ("about.js", ABOUT_JS),
            ("find.js", FIND_JS),
            ("menu.js", MENU_JS),
        ] {
            h.update(self.text(name, fallback).as_bytes());
        }
        h.finalize().to_hex()[..8].to_string()
    }
}

pub struct App {
    pub store: Store,
    pub renderer: Renderer,
    pub browse: Browser,
    /// Where the store and the token live; a reset needs to know.
    pub paths: Paths,
    /// Behind a lock because a reset replaces it: the old token is dead from
    /// that moment, which is the point of replacing it.
    pub token: std::sync::RwLock<String>,
    pub events: broadcast::Sender<String>,
    /// Fires when `snyvi stop` asks the daemon to exit.
    pub shutdown: broadcast::Sender<()>,
    pub started: Instant,
    /// Build hash for immutable asset URLs, for the compiled-in bundle.
    /// Read through `asset_v()`, which a live UI recomputes per request.
    built_v: String,
    /// Normally the compiled-in UI; `SNYVI_UI_DIR` makes it the one on disk.
    pub ui: Ui,
    /// Last time any open tab reported having focus; drives desktop notifications.
    pub last_focus: std::sync::Mutex<Instant>,
    /// How many native windows are reading. `snyvi app` opens the page with a
    /// mark on it, the page carries the mark into its event stream, and the
    /// count falls when that stream ends -- so this is exactly as live as the
    /// window is, with nothing to time out and nothing to leave stale when a
    /// window is quit.
    ///
    /// **A count and nothing more.** The mark it is kept by rides the query
    /// string, so anything that can reach the daemon can inflate it; what that
    /// buys is a link handed to a window that is not there, and never a
    /// privilege. Authority is `capabilities` below, which is minted per launch
    /// and never appears in a URL the server sees. The two signals coexist
    /// because they answer different questions -- how many are reading, and
    /// whether this page is one of them -- and only the second is trusted.
    pub windows: AtomicUsize,
    /// How many event streams are open, window or not. One per page, and a
    /// page holds a browser connection for as long as it holds one: a browser
    /// allows six to a host, so a page that does not give its stream back on
    /// the way out costs the next page a socket. Reported so a probe can say
    /// that it does.
    pub streams: AtomicUsize,
    /// Which agents are here now, and how many of each: the MCP server holds
    /// an event stream under its client's name from `initialize` until its
    /// process ends, so this is exactly as live as the agent is, the way the
    /// window count is. Before it, the daemon heard of an agent only when one
    /// sent, and the page could say "last sent 12 minutes ago" of a session
    /// that had been closed for eleven.
    pub online: std::sync::Mutex<std::collections::BTreeMap<String, usize>>,
    /// The capabilities minted for windows, kept beside the token so a window
    /// open across a restart keeps its panes. See `crate::capability`.
    pub capabilities: crate::capability::Capabilities,
    /// The panes that have been woken since this daemon started: their
    /// screens, and their processes while they run. See `crate::pane`.
    pub panes: Arc<crate::pane::Panes>,
    /// The last few lines agents left beside the work. See `crate::note`.
    pub notes: crate::note::Notes,
}

impl App {
    /// The live agents, for health, the boot payload and the `agents` event.
    pub fn online(&self) -> serde_json::Value {
        let m = self.online.lock().unwrap_or_else(|e| e.into_inner());
        json!(*m)
    }
    /// Is a native window up? What decides whether a link is handed to it or
    /// opened in a browser beside it.
    pub fn has_window(&self) -> bool {
        self.windows.load(Ordering::Relaxed) > 0
    }
    /// The bundle this daemon is serving. Constant for a shipped build, and
    /// the hash of what is on disk while the UI is live.
    pub fn asset_v(&self) -> String {
        self.ui.version(&self.built_v)
    }
}

type S = State<Arc<App>>;

/// The most the queue is ever sent as. Past this a reader is not going to
/// read down the line; the count beside the rows says how many there are.
const QUEUE_MAX: usize = 500;
/// How much of it a page opens with. The sidebar shows six and the bar shows
/// the oldest; the inbox, which lists them all, asks for the rest itself. A
/// library with hundreds waiting used to double the shell page.
const QUEUE_BOOT: usize = 24;

/// The queue's length, for the events and the boot payload: every tab keeps
/// its count from here rather than by arithmetic on what it happened to see.
fn waiting(app: &App) -> i64 {
    app.store.waiting().unwrap_or(0)
}

pub async fn run(paths: Paths) -> anyhow::Result<()> {
    let token = config::load_or_create_token(&paths)?;
    let store = Store::open(&paths)?;
    let renderer = Renderer::new();
    let (tx, _) = broadcast::channel(64);
    let (stop_tx, mut stop_rx) = broadcast::channel::<()>(1);
    // The Mermaid bundle is in the hash as well. It is served immutable for a
    // year like every other asset, and its URL had no version in it -- so a
    // browser that had cached one snyvi's bundle would have kept it across
    // every upgrade, which is exactly what a trimmed bundle would need to
    // replace. Hashing a megabyte once at startup costs under a millisecond.
    let asset_v = {
        let mut h = blake3::Hasher::new();
        h.update(INDEX_HTML.as_bytes());
        h.update(APP_CSS.as_bytes());
        h.update(APP_JS.as_bytes());
        h.update(DESK_JS.as_bytes());
        h.update(FRAME_JS.as_bytes());
        h.update(GAME_JS.as_bytes());
        h.update(ABOUT_JS.as_bytes());
        h.update(FIND_JS.as_bytes());
        h.update(MENU_JS.as_bytes());
        h.update(VERSION.as_bytes());
        h.update(MERMAID_JS_GZ);
        h.finalize().to_hex()[..8].to_string()
    };
    let panes = crate::pane::Panes::new(&paths.data_dir, tx.clone());
    let app = Arc::new(App {
        store,
        renderer,
        browse: Browser::load(paths.config_dir.join("folders.json")),
        paths: paths.clone(),
        token: std::sync::RwLock::new(token),
        events: tx,
        shutdown: stop_tx,
        started: Instant::now(),
        built_v: asset_v,
        ui: Ui::from_env(),
        last_focus: std::sync::Mutex::new(Instant::now() - std::time::Duration::from_secs(60)),
        windows: AtomicUsize::new(0),
        streams: AtomicUsize::new(0),
        online: std::sync::Mutex::new(Default::default()),
        capabilities: crate::capability::Capabilities::load(paths.config_dir.join("capabilities")),
        panes,
        notes: Default::default(),
    });
    // Kept past the router, which takes its own: what the daemon does on the
    // way out needs the panes.
    let leaving = app.clone();
    let told = app.shutdown.clone();
    crate::watch::spawn_browse_watcher(app.clone());
    crate::watch::spawn_ui_watcher(app.clone());

    let router = Router::new()
        .route("/", get(shell_home))
        .route("/connect", get(shell_connect))
        .route("/d/{id}", get(shell_doc))
        .route("/b/{id}", get(shell_browse))
        .route("/b/{id}/{*path}", get(shell_browse_file))
        .route("/assets/app.css", get(asset_css))
        .route("/assets/app.js", get(asset_js))
        .route("/assets/boot.js", get(asset_boot))
        .route("/assets/mmd.js", get(asset_mmd))
        .route("/assets/mermaid.js", get(asset_mermaid))
        .route("/files/{id}/{*path}", get(doc_file))
        .route("/assets/fonts/{name}", get(asset_font))
        .route("/api/health", get(health))
        .route("/api/about", get(about))
        .route("/api/agents", get(agents))
        .route("/api/tree", get(tree))
        .route("/api/projects/{id}/tree", get(project_tree))
        .route("/api/workflows/{id}/tree", get(workflow_tree))
        .route("/api/inbox", get(inbox))
        .route("/api/search", get(search))
        .route("/api/docs", post(receive_doc))
        .route("/api/docs/{id}", get(doc_json))
        .route("/api/docs/{id}/pin", post(pin))
        .route("/api/docs/{id}/read", post(mark_read))
        .route("/api/queue", get(queue))
        .route("/api/queue/clear", post(clear_queue))
        .route("/api/docs/{id}/delete", post(delete_doc))
        .route("/api/docs/{id}/undelete", post(undelete_doc))
        .route("/api/docs/{id}/history", get(history))
        .route("/api/projects/{id}/rename", post(rename_project))
        .route("/api/workflows/{id}/rename", post(rename_workflow))
        .route("/api/docs/{id}/split", get(doc_split))
        .route("/api/docs/{id}/outline", get(doc_outline))
        .route("/api/notes", get(notes).post(receive_note))
        .route("/api/notes/seen", post(see_notes))
        .route("/api/focus", post(focus))
        .route("/api/shutdown", post(shutdown))
        .route("/api/reset", get(reset_census).post(reset))
        .route("/api/terminal", post(terminal))
        .route("/api/browse", get(browse_list).post(browse_open))
        .route("/api/browse/pick", post(browse_pick))
        .route("/api/browse/{id}/close", post(browse_close))
        .route("/api/browse/{id}/tree", get(browse_tree))
        .route("/api/browse/{id}/file", get(browse_file))
        .route("/api/browse/{id}/raw", get(browse_raw))
        .route("/api/browse/{id}/raw/{*path}", get(browse_raw_path))
        .route("/api/browse/{id}/find", get(browse_find))
        .route("/api/browse/{id}/outline", get(browse_outline))
        .route("/api/docs/{id}/raw", get(doc_raw))
        .route("/api/docs/{id}/blob", get(doc_blob))
        .route("/api/compare/{a}/{b}", get(compare))
        .route("/api/events", get(events))
        .route("/api/capability", post(mint_capability))
        .route("/api/desk", get(desk_socket))
        .route("/api/desks", get(desks).post(create_desk))
        .route("/api/desks/{id}/rename", post(rename_desk))
        .route("/api/desks/{id}/layout", post(desk_layout))
        .route("/api/desks/{id}/delete", post(delete_desk))
        .route("/api/desks/{id}/panes", post(open_pane))
        .route("/api/desks/{id}/docs", get(desk_docs))
        .route("/api/desks/{id}/notes", get(desk_notes).post(add_desk_note))
        .route("/api/desks/{id}/notes/{note}", post(set_desk_note))
        .route(
            "/api/desks/{id}/notes/{note}/remove",
            post(remove_desk_note),
        )
        .route(
            "/api/desks/{id}/notes/{note}/restore",
            post(restore_desk_note),
        )
        .route("/api/panes/{id}/delete", post(close_pane))
        .route("/api/panes/{id}/start", post(start_pane))
        .route("/api/panes/{id}/stop", post(stop_pane))
        .route(
            "/api/panes/{id}/paste",
            post(paste_image).layer(axum::extract::DefaultBodyLimit::max(receive::MAX_BYTES)),
        )
        .route("/desks", get(shell_desk_list))
        .route("/desk/{id}", get(shell_desk))
        .route("/assets/desk.js", get(asset_desk))
        .route("/assets/frame.js", get(asset_frame))
        .route("/assets/game.js", get(asset_game))
        .route("/assets/about.js", get(asset_about))
        .route("/assets/find.js", get(asset_find))
        .route("/assets/menu.js", get(asset_menu))
        .with_state(app);

    let addr = format!("127.0.0.1:{}", config::port());
    let listener = tokio::net::TcpListener::bind(&addr).await?;
    eprintln!("snyvi {VERSION} listening on http://{addr}");
    axum::serve(listener, router)
        .with_graceful_shutdown(async move {
            let term = async {
                #[cfg(unix)]
                {
                    let mut sig =
                        tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
                            .expect("SIGTERM handler");
                    sig.recv().await;
                }
                #[cfg(not(unix))]
                std::future::pending::<()>().await;
            };
            tokio::select! {
                _ = tokio::signal::ctrl_c() => {},
                _ = term => {},
                _ = stop_rx.recv() => {},
            }
            // However it was asked, every open stream is told: a graceful
            // shutdown waits for each one, and an event stream or a desk
            // socket never ends of its own accord. `snyvi stop` already sends
            // this; a signal, which is how systemd and a logout ask, did not.
            let _ = told.send(());
        })
        .await?;
    // Every pane's text is written down and every process is hung up on: a
    // daemon that is going takes its shells with it, and they do not come
    // back with the next one. What comes back is the text, greyed.
    leaving.panes.shutdown();
    Ok(())
}

// ---------- shell ----------

/// How much of a project the sidebar is given when it is expanded: enough to
/// read, never a year of sessions. Everything past this is one click away and
/// arrives whole, so nothing is hidden -- only unasked for.
const TREE_WORKFLOWS: usize = 10;
const TREE_DOCS: usize = 10;

/// One project's rows: its sessions, newest first, each holding its newest
/// documents.
///
/// `whole` is the workflow the reader is reading in, which comes back complete
/// rather than capped: `[` and `]` step through the versions of a document, and
/// a cap there would stop them somewhere arbitrary. The page a reader opens and
/// the fetch their tab makes later both come through here, so an arrival cannot
/// quietly hand back a shorter list than the page did.
fn project_rows(
    app: &App,
    project_id: i64,
    workflows: usize,
    docs: usize,
    whole: Option<i64>,
) -> Vec<crate::store::TreeWorkflow> {
    let mut wfs = app
        .store
        .project_tree(project_id, workflows, docs)
        .unwrap_or_default();
    if let Some(id) = whole {
        if let Ok(Some(full)) = app.store.workflow_tree(id) {
            match wfs.iter().position(|w| w.id == full.id) {
                Some(at) => wfs[at] = full,
                // The document being read is in a session too old to be among
                // the most recent few. It goes in anyway: the reader is in it.
                None => wfs.insert(0, full),
            }
        }
    }
    wfs
}

/// The same rows, keyed by project id, which is the shape the boot payload
/// carries them in.
fn subtree(app: &App, project_id: i64, whole: Option<i64>) -> serde_json::Value {
    let wfs = project_rows(app, project_id, TREE_WORKFLOWS, TREE_DOCS, whole);
    let mut m = serde_json::Map::new();
    m.insert(
        project_id.to_string(),
        serde_json::to_value(wfs).unwrap_or_default(),
    );
    serde_json::Value::Object(m)
}

fn escape_json_for_script(s: &str) -> String {
    s.replace("</", "<\\/")
}

fn shell(app: &App, mut boot: serde_json::Value, initial_html: &str, title: &str) -> Response {
    // The build hash, for the one asset the client asks for itself rather than
    // through the markup: the Mermaid bundle.
    if let Some(o) = boot.as_object_mut() {
        o.insert("v".into(), serde_json::Value::String(app.asset_v()));
        // What is waiting to be read, on every page: the bar above the
        // document and the section at the top of the sidebar draw from it
        // before the first paint, so a reload never loses count.
        o.insert(
            "queue".into(),
            serde_json::to_value(app.store.queue(QUEUE_BOOT).unwrap_or_default())
                .unwrap_or_default(),
        );
        o.insert("waiting".into(), json!(waiting(app)));
        // Who is here, for the count beside the brand mark on the first paint.
        o.insert("online".into(), app.online());
        // The note showing at the foot of the sidebar, and the trail under it.
        o.insert("notes".into(), json!(app.notes.list()));
    }
    let page = app
        .ui
        .text("index.html", INDEX_HTML)
        .replace("{{V}}", &app.asset_v())
        .replace("{{TITLE}}", &html_escape::encode_text(title))
        .replace("{{INITIAL_HTML}}", initial_html)
        .replace("{{BOOT_JSON}}", &escape_json_for_script(&boot.to_string()));
    (
        [
            (
                header::CONTENT_SECURITY_POLICY,
                HeaderValue::from_static(CSP),
            ),
            (
                header::X_CONTENT_TYPE_OPTIONS,
                HeaderValue::from_static("nosniff"),
            ),
            (
                header::REFERRER_POLICY,
                HeaderValue::from_static("no-referrer"),
            ),
        ],
        Html(page),
    )
        .into_response()
}

pub fn fmt_time(ts: i64) -> String {
    use time::{format_description::FormatItem, macros::format_description, OffsetDateTime};
    const F: &[FormatItem] =
        format_description!("[month repr:short] [day padding:none], [hour]:[minute]");
    let local = OffsetDateTime::from_unix_timestamp(ts)
        .map(|t| {
            t.to_offset(time::UtcOffset::current_local_offset().unwrap_or(time::UtcOffset::UTC))
        })
        .unwrap_or(OffsetDateTime::UNIX_EPOCH);
    local.format(F).unwrap_or_default()
}

/// Server-side document markup, mirrored by `renderDoc` in app.js.
fn doc_html(doc: &Doc, body: &str) -> String {
    let e = html_escape::encode_text;
    let mut sub = format!("{} · {}", e(&doc.project), e(&doc.workflow_title));
    if let Some(b) = &doc.branch {
        sub.push_str(&format!(" · <span class=\"branch\">{}</span>", e(b)));
    }
    sub.push_str(&format!(" · {}", fmt_time(doc.received_at)));
    format!(
        "<header class=\"doc-head\"><h1 class=\"doc-title\">{}</h1><p class=\"doc-sub\">{}</p></header><article class=\"prose kind-{}\">{}</article>",
        e(&doc.title),
        sub,
        doc.kind.as_str(),
        render::chunk_code(body)
    )
}

async fn shell_home(State(app): S) -> Response {
    let tree = app.store.projects().unwrap_or_default();
    let inbox = app.store.inbox(50).unwrap_or_default();
    // A single project is shown expanded, so its rows are wanted on this page
    // and are worth the bytes rather than a second round trip. Any more than
    // one and the reader's own choice of what is open decides, which is in
    // their browser and not here.
    let sub = match tree.as_slice() {
        [only] => subtree(&app, only.id, None),
        _ => serde_json::Value::Object(Default::default()),
    };
    let mut boot = json!({ "view": "inbox", "tree": tree, "sub": sub, "inbox": inbox, "browse": app.browse.list(), "version": VERSION });
    // An empty library opens on the connect page, and the page is on screen
    // with the sidebar rather than a round trip after it.
    if inbox.is_empty() {
        boot["agents"] = agents_json(&app);
    }
    shell(&app, boot, "", "snyvi")
}

/// The connect page, asked for: from `?`, or by its address.
async fn shell_connect(State(app): S) -> Response {
    let tree = app.store.projects().unwrap_or_default();
    let boot = json!({ "view": "connect", "tree": tree, "sub": {}, "browse": app.browse.list(), "version": VERSION, "agents": agents_json(&app) });
    shell(&app, boot, "", "Connect an agent · snyvi")
}

async fn shell_doc(State(app): S, Path(id): Path<String>) -> Response {
    let Ok(Some(doc)) = app.store.get(&id) else {
        return (StatusCode::NOT_FOUND, Html("<h1>Not found</h1>")).into_response();
    };
    let body = app.store.html(&id).unwrap_or_default();
    let tree = app.store.projects().unwrap_or_default();
    let previous = app.store.previous(&doc).ok().flatten().map(|p| p.id);
    let title = doc.title.clone();
    let folder = doc_folder(&app, &doc);
    // The project this document is in is the one the sidebar opens on, so it
    // arrives with the page rather than a moment after it.
    let sub = subtree(&app, doc.project_id, Some(doc.workflow_id));
    let boot = json!({ "view": "doc", "tree": tree, "sub": sub, "doc": doc, "previous": previous, "folder": folder, "browse": app.browse.list(), "version": VERSION });
    shell(&app, boot, &doc_html(&doc, &body), &title)
}

/// A desk, by its address. The page is the same page in a window and a tab --
/// what differs is that a tab holds no capability, and the desk view says so
/// in one sentence rather than drawing a grid that could never run anything.
/// So nothing about a desk is in this answer: the page asks for it with the
/// capability, or cannot.
async fn shell_desk(State(app): S, Path(id): Path<i64>) -> Response {
    let tree = app.store.projects().unwrap_or_default();
    let boot = json!({ "view": "desk", "desk": id, "tree": tree, "sub": {}, "browse": app.browse.list(), "version": VERSION });
    shell(&app, boot, "", "Desk · snyvi")
}

/// Every desk, which is where the sidebar's `Desks` row goes.
async fn shell_desk_list(State(app): S) -> Response {
    let tree = app.store.projects().unwrap_or_default();
    let boot = json!({ "view": "desk", "desk": null, "tree": tree, "sub": {}, "browse": app.browse.list(), "version": VERSION });
    shell(&app, boot, "", "Desks · snyvi")
}

// ---------- assets ----------

fn immutable(content_type: &'static str, body: impl Into<Body>) -> Response {
    (
        [
            (header::CONTENT_TYPE, HeaderValue::from_static(content_type)),
            (
                header::CACHE_CONTROL,
                HeaderValue::from_static("public, max-age=31536000, immutable"),
            ),
        ],
        body.into(),
    )
        .into_response()
}

/// An asset that is immutable for a shipped build -- its URL carries the
/// build hash, so a year is the right answer -- and uncached while the UI is
/// live, where the whole point is that the next request sees the edit.
fn asset(app: &App, content_type: &'static str, name: &str, built_in: &'static str) -> Response {
    let body = app.ui.text(name, built_in).into_owned();
    if !app.ui.live() {
        return immutable(content_type, body);
    }
    (
        [
            (header::CONTENT_TYPE, HeaderValue::from_static(content_type)),
            (header::CACHE_CONTROL, HeaderValue::from_static("no-store")),
        ],
        body,
    )
        .into_response()
}

async fn asset_css(State(app): S) -> Response {
    asset(&app, "text/css; charset=utf-8", "app.css", APP_CSS)
}
async fn asset_js(State(app): S) -> Response {
    asset(
        &app,
        "application/javascript; charset=utf-8",
        "app.js",
        APP_JS,
    )
}
async fn asset_boot(State(app): S) -> Response {
    asset(
        &app,
        "application/javascript; charset=utf-8",
        "boot.js",
        BOOT_JS,
    )
}
/// The diagram driver. Immutable like the rest for a shipped build, and served
/// on the same terms as app.js -- it is the same UI, split at the one seam where
/// most page loads do not need what is on the other side.
async fn asset_mmd(State(app): S) -> Response {
    asset(
        &app,
        "application/javascript; charset=utf-8",
        "mmd.js",
        MMD_JS,
    )
}
/// The desk view, on the same terms as the diagram driver.
async fn asset_desk(State(app): S) -> Response {
    asset(
        &app,
        "application/javascript; charset=utf-8",
        "desk.js",
        DESK_JS,
    )
}
/// The window's frame, on the same terms: a tab never asks for it.
async fn asset_frame(State(app): S) -> Response {
    asset(
        &app,
        "application/javascript; charset=utf-8",
        "frame.js",
        FRAME_JS,
    )
}
/// The game, on the same terms: nothing asks for it but the rocket.
async fn asset_game(State(app): S) -> Response {
    asset(
        &app,
        "application/javascript; charset=utf-8",
        "game.js",
        GAME_JS,
    )
}
/// The about panel and the reset dialog, on the same terms: nothing asks for
/// them but the two buttons that open them.
async fn asset_about(State(app): S) -> Response {
    asset(
        &app,
        "application/javascript; charset=utf-8",
        "about.js",
        ABOUT_JS,
    )
}
/// Find, on the same terms: the bar is not up until someone puts it up.
async fn asset_find(State(app): S) -> Response {
    asset(
        &app,
        "application/javascript; charset=utf-8",
        "find.js",
        FIND_JS,
    )
}
/// The folder menu and the desk actions, on the same terms: nothing here has
/// happened until someone has clicked something.
async fn asset_menu(State(app): S) -> Response {
    asset(
        &app,
        "application/javascript; charset=utf-8",
        "menu.js",
        MENU_JS,
    )
}
async fn asset_mermaid() -> Response {
    (
        [
            (
                header::CONTENT_TYPE,
                HeaderValue::from_static("application/javascript; charset=utf-8"),
            ),
            (header::CONTENT_ENCODING, HeaderValue::from_static("gzip")),
            (
                header::CACHE_CONTROL,
                HeaderValue::from_static("public, max-age=31536000, immutable"),
            ),
        ],
        MERMAID_JS_GZ,
    )
        .into_response()
}

/// Images referenced relatively from a document, resolved against the source file's
/// directory and confined to the project root. Image types only.
async fn doc_file(State(app): S, Path((id, rel)): Path<(String, String)>) -> Response {
    let Ok(Some(doc)) = app.store.get(&id) else {
        return StatusCode::NOT_FOUND.into_response();
    };
    let Some(src) = doc.source_path.as_deref() else {
        return StatusCode::NOT_FOUND.into_response();
    };
    let Some(dir) = std::path::Path::new(src).parent() else {
        return StatusCode::NOT_FOUND.into_response();
    };
    let target = dir.join(&rel);
    let ext = target
        .extension()
        .map(|e| e.to_string_lossy().to_ascii_lowercase())
        .unwrap_or_default();
    if !render::is_image_ext(&ext) {
        return StatusCode::FORBIDDEN.into_response();
    }
    let (Ok(canon), Ok(root)) = (
        target.canonicalize(),
        crate::project::resolve(dir).root.canonicalize(),
    ) else {
        return StatusCode::NOT_FOUND.into_response();
    };
    if !canon.starts_with(&root) {
        return StatusCode::FORBIDDEN.into_response();
    }
    match tokio::fs::read(&canon).await {
        Ok(bytes) => {
            let mime = mime_guess::from_path(&canon)
                .first_or_octet_stream()
                .to_string();
            (
                [
                    (header::CONTENT_TYPE, mime),
                    (header::CACHE_CONTROL, "private, max-age=300".to_string()),
                ],
                bytes,
            )
                .into_response()
        }
        Err(_) => StatusCode::NOT_FOUND.into_response(),
    }
}
async fn asset_font(Path(name): Path<String>) -> Response {
    match FONTS.iter().find(|(n, _)| *n == name) {
        Some((_, bytes)) => immutable("font/woff2", *bytes),
        None => StatusCode::NOT_FOUND.into_response(),
    }
}

// ---------- api ----------

async fn health(State(app): S) -> Json<serde_json::Value> {
    Json(json!({
        "ok": true,
        "version": VERSION,
        "commit": BUILD_SHA,
        // So `snyvi stop` can end this exact process if it ignores the
        // shutdown endpoint, without having to guess which snyvi it is.
        "pid": std::process::id(),
        "docs": app.store.count().unwrap_or(0),
        // Whether a link should be handed to a window or opened in a browser.
        // `snyvi open`, `snyvi browse` and the MCP server all ask here.
        "window": app.has_window(),
        "streams": app.streams.load(Ordering::Relaxed),
        // How many pane processes are running, so `snyvi bench` and a person
        // with curl can see what a desk is costing without a window open.
        "panes": app.panes.running(),
        // Which agents hold a stream right now, by the name each gave.
        "agents": app.online(),
        // The bundle this daemon serves, so a page that reconnects after an
        // upgrade can tell it is running another one's and reload.
        "v": app.asset_v(),
        "languages": app.renderer.languages().len(),
        "uptime_s": app.started.elapsed().as_secs(),
    }))
}

/// The about panel: what this is, which build is answering, where its
/// files are, and what Claude Code has of it. The version comes from here
/// and not from the page's bundle, so the panel cannot name a number
/// `snyvi --version` would not.
async fn about(State(app): S) -> Json<serde_json::Value> {
    let exe = std::env::current_exe().ok();
    Json(json!({
        "name": "snyvi",
        "description": env!("CARGO_PKG_DESCRIPTION"),
        "version": VERSION,
        "commit": BUILD_SHA,
        "target": BUILD_TARGET,
        "binary": exe.as_deref().map(|p| p.display().to_string()),
        "data_dir": app.paths.data_dir.display().to_string(),
        "config_dir": app.paths.config_dir.display().to_string(),
        "agents": std::iter::once(crate::setup::claude_code_status())
            .chain(crate::agents::status_lines())
            .collect::<Vec<_>>()
            .join("\n"),
        "license": env!("CARGO_PKG_LICENSE"),
        "repository": env!("CARGO_PKG_REPOSITORY"),
        "docs": app.store.count().unwrap_or(0),
        "uptime_s": app.started.elapsed().as_secs(),
    }))
}

/// The connect page's rows: every agent and what its own file says it has
/// of snyvi, read now, whether it is here now, and when each last sent
/// something. `program` is how this binary is spelled to them, for the page
/// to show in its commands.
async fn agents(State(app): S) -> Response {
    Json(agents_json(&app)).into_response()
}

fn agents_json(app: &App) -> serde_json::Value {
    let senders = app.store.senders().unwrap_or_default();
    let online = app.online.lock().unwrap_or_else(|e| e.into_inner()).clone();
    json!({
        "program": crate::setup::program().0,
        "rows": crate::agents::rows(&senders, &online),
        "online": online,
        "now": crate::store::now(),
    })
}

async fn tree(State(app): S) -> Response {
    match app.store.projects() {
        Ok(t) => Json(t).into_response(),
        Err(e) => err(e),
    }
}

#[derive(Deserialize)]
struct TreeQ {
    workflows: Option<usize>,
    docs: Option<usize>,
    /// A workflow to send whole whatever the caps are: the one the reader is in.
    whole: Option<i64>,
}

/// What one project holds, fetched when a reader expands it. Zero for either
/// cap means all of them: that is a reader who clicked past the cap, and the
/// answer to "show me the rest" is the rest.
async fn project_tree(State(app): S, Path(id): Path<i64>, Query(q): Query<TreeQ>) -> Response {
    let workflows = q.workflows.unwrap_or(TREE_WORKFLOWS);
    let docs = q.docs.unwrap_or(TREE_DOCS);
    Json(project_rows(&app, id, workflows, docs, q.whole)).into_response()
}

/// One workflow, whole. Asked for by the tree when a reader wants everything in
/// a session, and by nothing else.
async fn workflow_tree(State(app): S, Path(id): Path<i64>) -> Response {
    match app.store.workflow_tree(id) {
        Ok(Some(w)) => Json(w).into_response(),
        Ok(None) => StatusCode::NOT_FOUND.into_response(),
        Err(e) => err(e),
    }
}

#[derive(Deserialize)]
struct Limit {
    limit: Option<usize>,
}

async fn inbox(State(app): S, Query(q): Query<Limit>) -> Response {
    match app.store.inbox(q.limit.unwrap_or(50).min(500)) {
        Ok(t) => Json(t).into_response(),
        Err(e) => err(e),
    }
}

#[derive(Deserialize)]
struct SearchQ {
    q: String,
    limit: Option<usize>,
}

async fn search(State(app): S, Query(q): Query<SearchQ>) -> Response {
    match app.store.search(&q.q, q.limit.unwrap_or(30).min(200)) {
        Ok(t) => Json(t).into_response(),
        Err(e) => err(e),
    }
}

async fn doc_json(State(app): S, Path(id): Path<String>) -> Response {
    match app.store.get(&id) {
        Ok(Some(doc)) => {
            let body = app.store.html(&id).unwrap_or_default();
            let previous = app.store.previous(&doc).ok().flatten().map(|p| p.id);
            // A stored page or PDF is framed from its own bytes. Only the one file was
            // snapshotted, so unlike browse mode there are no sibling assets to load.
            let preview = doc
                .source_path
                .as_deref()
                .map(render::ext_of)
                .and_then(|e| render::preview_kind(&e));
            Json(json!({
                "doc": doc,
                "html": doc_html(&doc, &body),
                "previous": previous,
                "preview": preview,
                "preview_url": preview.map(|_| format!("/api/docs/{id}/blob")),
                // So the page knows whether there is a terminal button to draw.
                // A control that is disabled and cannot say why is worse than
                // no control, and the directory is not something the page can
                // work out for itself -- it is a parent path on a machine whose
                // separator the page does not know.
                "folder": doc_folder(&app, &doc),
            }))
            .into_response()
        }
        Ok(None) => StatusCode::NOT_FOUND.into_response(),
        Err(e) => err(e),
    }
}

async fn doc_raw(State(app): S, Path(id): Path<String>) -> Response {
    match app.store.source(&id) {
        Ok(src) => ([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], src).into_response(),
        Err(_) => StatusCode::NOT_FOUND.into_response(),
    }
}

/// A stored document's bytes, as they arrived. This is how an image document's
/// `<img>` gets its picture; the content type comes from the source file's name so
/// the browser knows what it is.
async fn doc_blob(State(app): S, Path(id): Path<String>) -> Response {
    let Ok(Some(doc)) = app.store.get(&id) else {
        return StatusCode::NOT_FOUND.into_response();
    };
    let Ok(bytes) = app.store.source_bytes(&id) else {
        return StatusCode::NOT_FOUND.into_response();
    };
    let mime = doc
        .source_path
        .as_deref()
        .map(|p| mime_guess::from_path(p).first_or_octet_stream().to_string())
        .unwrap_or_else(|| "application/octet-stream".to_string());
    let mut headers = HeaderMap::new();
    if let Ok(v) = HeaderValue::from_str(&mime) {
        headers.insert(header::CONTENT_TYPE, v);
    }
    // Documents are immutable, so the bytes behind an id never change.
    headers.insert(
        header::CACHE_CONTROL,
        HeaderValue::from_static("private, max-age=31536000"),
    );
    protect(
        &mut headers,
        &doc.source_path
            .as_deref()
            .map(render::ext_of)
            .unwrap_or_default(),
    );
    (headers, bytes).into_response()
}

#[derive(Deserialize)]
struct ViewQ {
    view: Option<String>,
}

async fn doc_split(State(app): S, Path(id): Path<String>) -> Response {
    match (app.store.get(&id), app.store.source(&id)) {
        (Ok(Some(doc)), Ok(src)) if doc.kind == crate::render::Kind::Diff => {
            Json(json!({ "html": render::diff_split(&src) })).into_response()
        }
        (Ok(Some(_)), _) => StatusCode::BAD_REQUEST.into_response(),
        _ => StatusCode::NOT_FOUND.into_response(),
    }
}

/// Declarations in a stored code document, for the rail.
async fn doc_outline(State(app): S, Path(id): Path<String>) -> Response {
    let Ok(Some(doc)) = app.store.get(&id) else {
        return StatusCode::NOT_FOUND.into_response();
    };
    if doc.kind != crate::render::Kind::Code {
        return Json(Vec::<crate::render::Outline>::new()).into_response();
    }
    if let Some(json) = app.store.outline(&id) {
        return ([(header::CONTENT_TYPE, "application/json")], json).into_response();
    }
    let app2 = app.clone();
    match tokio::task::spawn_blocking(move || outline_of(&app2, &id, doc.lang.as_deref())).await {
        Ok(Some(json)) => ([(header::CONTENT_TYPE, "application/json")], json).into_response(),
        Ok(None) => StatusCode::NOT_FOUND.into_response(),
        Err(e) => err(anyhow::anyhow!(e)),
    }
}

/// A stored code document's outline, worked out and kept beside its HTML. A
/// document does not change, so this runs once: on arrival, in the background,
/// or on the first open of one that came before outlines were kept.
fn outline_of(app: &App, id: &str, lang: Option<&str>) -> Option<String> {
    let src = app.store.source(id).ok()?;
    let json = serde_json::to_string(&app.renderer.outline(lang, &src)).ok()?;
    let _ = app.store.set_outline(id, &json);
    Some(json)
}

async fn history(State(app): S, Path(id): Path<String>) -> Response {
    let Ok(Some(doc)) = app.store.get(&id) else {
        return StatusCode::NOT_FOUND.into_response();
    };
    let Some(path) = doc.source_path.as_deref() else {
        return Json(Vec::<Doc>::new()).into_response();
    };
    match app.store.history(doc.project_id, path) {
        Ok(h) => Json(h).into_response(),
        Err(e) => err(e),
    }
}

/// Delete at once, and say nothing first. The page offers Undo for a few
/// seconds; the document is on disk until `prune` runs either way.
async fn delete_doc(State(app): S, Path(id): Path<String>) -> Response {
    match app.store.delete(&id) {
        Ok(true) => {
            emit(
                &app,
                "deleted",
                json!({ "id": id, "waiting": waiting(&app) }),
            );
            Json(json!({ "ok": true })).into_response()
        }
        Ok(false) => StatusCode::NOT_FOUND.into_response(),
        Err(e) => err(e),
    }
}

/// The other half of Undo. Gone means pruned, which is the one delete that
/// cannot be taken back.
async fn undelete_doc(State(app): S, Path(id): Path<String>) -> Response {
    match app.store.undelete(&id) {
        Ok(true) => {
            let doc = app.store.get(&id).ok().flatten();
            emit(
                &app,
                "restored",
                json!({ "id": id, "doc": doc, "waiting": waiting(&app) }),
            );
            Json(json!({ "ok": true, "doc": doc })).into_response()
        }
        Ok(false) => (
            StatusCode::GONE,
            Json(json!({ "error": "that document has been pruned" })),
        )
            .into_response(),
        Err(e) => err(e),
    }
}

/// Ask the daemon to exit, so a new binary can take over the port.
async fn shutdown(State(app): S, headers: HeaderMap) -> Response {
    if !authorized(&app, &headers) {
        return (
            StatusCode::UNAUTHORIZED,
            Json(json!({ "error": "missing or invalid token" })),
        )
            .into_response();
    }
    let _ = app.shutdown.send(());
    Json(json!({ "ok": true, "version": VERSION })).into_response()
}

/// What a reset would take, for the sentence that asks.
async fn reset_census(State(app): S) -> Response {
    match app.store.census() {
        Ok(c) => Json(c).into_response(),
        Err(e) => err(e),
    }
}

#[derive(Deserialize)]
struct ResetBody {
    /// The number of documents the caller was shown and typed back. It has to
    /// be the number there is now: a document that arrived between the
    /// sentence and the answer makes the answer stale, and the caller is told
    /// to look again rather than reset a library other than the one described.
    documents: i64,
    /// Said explicitly, or the pinned documents keep the reset from happening.
    #[serde(default)]
    pinned: bool,
    /// The number of desks the caller was shown, checked the way the documents
    /// are. Missing reads as none: a caller that never said there were desks
    /// never showed the reader any, and is refused if there are.
    #[serde(default)]
    desks: i64,
}

/// Back to a fresh install: every document and version, the index, the token,
/// and -- by the event this ends with -- the preferences every open page keeps.
/// The daemon stays up and the agents stay registered, so the next send lands
/// in an empty library. The one action here that cannot be undone, and the one
/// that asks for a number rather than a click.
///
/// A same-origin POST is accepted beside the token, as `terminal` explains:
/// the page has no token, and the dialog is the page's.
async fn reset(State(app): S, headers: HeaderMap, Json(b): Json<ResetBody>) -> Response {
    if !from_this_page(&headers) && !authorized(&app, &headers) {
        return (
            StatusCode::FORBIDDEN,
            Json(json!({ "error": "not from this page, and no token" })),
        )
            .into_response();
    }
    let census = match app.store.census() {
        Ok(c) => c,
        Err(e) => return err(e),
    };
    if b.documents != census.documents {
        return (
            StatusCode::CONFLICT,
            Json(json!({
                "error": format!("the library has changed: {} document(s) now, not {}; look again", census.documents, b.documents),
                "census": census,
            })),
        )
            .into_response();
    }
    if b.desks != census.desks {
        return (
            StatusCode::CONFLICT,
            Json(json!({
                "error": format!("the desks have changed: {} now, not {}; look again", census.desks, b.desks),
                "census": census,
            })),
        )
            .into_response();
    }
    if census.pinned > 0 && !b.pinned {
        return (
            StatusCode::CONFLICT,
            Json(json!({
                "error": format!("{} pinned document(s) would go with it; say so", census.pinned),
                "census": census,
            })),
        )
            .into_response();
    }
    // The wipe and the VACUUM are disk work, and on a disk under pressure
    // they take as long as they take: off the runtime, so the other pages'
    // requests -- and the reload they are about to make -- are still answered.
    let app2 = app.clone();
    match tokio::task::spawn_blocking(move || app2.store.reset()).await {
        Ok(Ok(())) => {}
        Ok(Err(e)) => return err(e),
        Err(e) => return err(anyhow::anyhow!("reset task: {e}")),
    }
    // The store has let go of every pane; the processes and their text go too.
    app.panes.clear();
    for root in app.browse.list() {
        app.browse.close(&root.id);
    }
    let _ = std::fs::remove_file(app.paths.config_dir.join("sessions.json"));
    let _ = std::fs::remove_file(app.paths.config_dir.join("folders.json"));
    match config::rotate_token(&app.paths) {
        Ok(t) => *app.token.write().unwrap() = t,
        Err(e) => return err(e),
    }
    emit(&app, "reset", json!({}));
    Json(json!({ "ok": true, "removed": census })).into_response()
}

/// Open tabs report focus so arrivals only raise a desktop notification when nobody is looking.
async fn focus(State(app): S) -> StatusCode {
    *app.last_focus.lock().unwrap() = Instant::now();
    StatusCode::NO_CONTENT
}

fn notify_desktop(app: &App, doc: &Doc) {
    if std::env::var("SNYVI_NOTIFY")
        .map(|v| v == "0")
        .unwrap_or(false)
    {
        return;
    }
    let focused_recently =
        app.last_focus.lock().unwrap().elapsed() < std::time::Duration::from_secs(4);
    if focused_recently {
        return;
    }
    // Clicking it opens the document where the reader reads: the window it
    // belongs to, raised, or a browser when there is no window. The daemon is
    // the one process that knows which, so it decides here rather than handing
    // a URL to the desktop and hoping.
    let url = format!("{}/d/{}", config::base_url(), doc.id);
    let has_window = app.has_window();
    crate::platform::notify_open(
        &doc.title,
        &format!("{} · {}", doc.project, doc.workflow_title),
        move || {
            if has_window && crate::desktop::hand_to_window(&url) {
                return;
            }
            platform::open_url(&url);
        },
    );
}

async fn compare(
    State(app): S,
    Path((a, b)): Path<(String, String)>,
    Query(v): Query<ViewQ>,
) -> Response {
    let (Ok(Some(da)), Ok(Some(db))) = (app.store.get(&a), app.store.get(&b)) else {
        return StatusCode::NOT_FOUND.into_response();
    };
    let (Ok(sa), Ok(sb)) = (app.store.source(&a), app.store.source(&b)) else {
        return StatusCode::NOT_FOUND.into_response();
    };
    let a_name = format!("{} ({})", da.title, fmt_time(da.received_at));
    let b_name = format!("{} ({})", db.title, fmt_time(db.received_at));
    let unified = render::unified(&a_name, &sa, &b_name, &sb);
    let html = if unified.trim().is_empty() {
        "<p class=\"empty\">No changes between these two versions.</p>".to_string()
    } else if v.view.as_deref() == Some("split") {
        render::diff_split(&unified)
    } else {
        render::diff(&unified)
    };
    Json(json!({ "a": da, "b": db, "html": html })).into_response()
}

#[derive(Deserialize)]
struct EventsQ {
    /// Set by a page that is inside the native window, so the daemon knows
    /// there is one to hand a link to. A string rather than a bool because a
    /// query string is not JSON: `?window=1` is what a page would naturally
    /// send, and it is not a bool to serde.
    ///
    /// Forgeable, and deliberately kept anyway: it is a count hint, not a
    /// credential. `EventSource` cannot set a header, so the capability cannot
    /// ride this stream and the count has nowhere else to live; what makes that
    /// safe is that nothing reachable from here grants anything. See
    /// `App::windows`.
    #[serde(default)]
    window: Option<String>,
    /// Set by the MCP server, with the name its client gave in `initialize`,
    /// so the daemon knows that agent is here for as long as the stream is.
    #[serde(default)]
    agent: Option<String>,
}

impl EventsQ {
    fn is_window(&self) -> bool {
        self.window
            .as_deref()
            .is_some_and(|v| !matches!(v, "" | "0" | "false" | "False"))
    }

    /// The agent's name, trimmed and cut to a length the header can hold.
    /// None when it is empty, which is a page and not an agent.
    fn agent(&self) -> Option<String> {
        let name = self.agent.as_deref()?.trim();
        if name.is_empty() {
            return None;
        }
        Some(name.chars().take(64).collect())
    }
}

/// Held by an event stream for as long as that stream lasts. A page that is
/// closed, reloaded or navigated away from takes its connection with it, and
/// an agent's process that ends takes its own; every count follows. Nothing
/// here times out, so a window that is quit is not a window a moment later,
/// a page that is gone is not a socket, and an agent whose session was
/// closed is not here.
struct StreamMark {
    app: Arc<App>,
    window: bool,
    agent: Option<String>,
}

impl StreamMark {
    fn new(app: Arc<App>, window: bool, agent: Option<String>) -> StreamMark {
        app.streams.fetch_add(1, Ordering::Relaxed);
        if window {
            app.windows.fetch_add(1, Ordering::Relaxed);
        }
        if let Some(name) = &agent {
            let changed = {
                let mut m = app.online.lock().unwrap_or_else(|e| e.into_inner());
                *m.entry(name.clone()).or_insert(0) += 1;
                json!(*m)
            };
            emit(&app, "agents", json!({ "online": changed }));
        }
        StreamMark { app, window, agent }
    }
}

impl Drop for StreamMark {
    fn drop(&mut self) {
        self.app.streams.fetch_sub(1, Ordering::Relaxed);
        if self.window {
            self.app.windows.fetch_sub(1, Ordering::Relaxed);
        }
        if let Some(name) = &self.agent {
            let changed = {
                let mut m = self.app.online.lock().unwrap_or_else(|e| e.into_inner());
                if let Some(n) = m.get_mut(name) {
                    *n -= 1;
                    if *n == 0 {
                        m.remove(name);
                    }
                }
                json!(*m)
            };
            emit(&self.app, "agents", json!({ "online": changed }));
        }
    }
}

/// Broadcast payloads are "<event name>\n<json>".
///
/// The stream ends when the daemon is asked to stop. A graceful shutdown
/// closes the listener and then waits for every response in flight to
/// finish, and a stream that never ends is a response that never finishes:
/// the old daemon stayed up for as long as the window did, listening on
/// nothing, and the window stayed on it -- it heard no more arrivals, and the
/// daemon that took the port counted no window and handed every agent a link
/// to open in a browser instead. Seen on this machine: ten hours, one tab per
/// document. Ended here, the page reconnects to whatever is on the port now.
async fn events(
    State(app): S,
    Query(q): Query<EventsQ>,
) -> Sse<impl tokio_stream::Stream<Item = Result<Event, Infallible>>> {
    let rx = app.events.subscribe();
    let stop = BroadcastStream::new(app.shutdown.subscribe()).map(|_| None);
    let mark = StreamMark::new(app.clone(), q.is_window(), q.agent());
    let stream = BroadcastStream::new(rx)
        .filter_map(move |m| {
            // Captured so that the mark lives exactly as long as the stream does.
            let _keep = &mark;
            m.ok().map(|msg| {
                let (name, data) = msg.split_once('\n').unwrap_or(("doc", msg.as_str()));
                Some(Ok(Event::default().event(name).data(data)))
            })
        })
        .merge(stop)
        .take_while(Option::is_some)
        .map(Option::unwrap);
    Sse::new(stream).keep_alive(KeepAlive::default())
}

pub(crate) fn emit(app: &App, name: &str, data: serde_json::Value) {
    let _ = app.events.send(format!("{name}\n{data}"));
}

#[derive(Deserialize)]
struct PinBody {
    pinned: bool,
}

#[derive(Deserialize)]
struct RenameBody {
    name: String,
}

/// One line for a desk's list. Bounded and trimmed by `desk::add_note`, not
/// here: the cap belongs beside the list it is a cap on.
#[derive(Deserialize)]
struct NoteTextBody {
    text: String,
}

/// What changed about a line. Either half may be absent, so ticking a row off
/// does not have to send its text back with it.
#[derive(Debug, Default, Deserialize)]
struct NoteEditBody {
    #[serde(default)]
    text: Option<String>,
    #[serde(default)]
    done: Option<bool>,
}

/// A label the sidebar has to draw on one line, so it is trimmed of the whitespace
/// an accidental paste brings and cut to a length that cannot push the tree around.
fn clean_name(raw: &str) -> Option<String> {
    let name: String = raw
        .chars()
        .map(|c| if c.is_control() { ' ' } else { c })
        .collect();
    let name = name.split_whitespace().collect::<Vec<_>>().join(" ");
    if name.is_empty() {
        return None;
    }
    Some(name.chars().take(120).collect())
}

/// Renaming is a label, like pinning: it moves nothing on disk and reveals nothing,
/// so it needs no token. The identity underneath (a project's root, a workflow's key)
/// is untouched, so what arrives next still lands where it did.
async fn rename_project(State(app): S, Path(id): Path<i64>, Json(b): Json<RenameBody>) -> Response {
    let Some(name) = clean_name(&b.name) else {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "a name cannot be empty" })),
        )
            .into_response();
    };
    match app.store.rename_project(id, &name) {
        Ok(true) => {
            emit(&app, "renamed", json!({ "project": id, "name": name }));
            Json(json!({ "ok": true, "name": name })).into_response()
        }
        Ok(false) => StatusCode::NOT_FOUND.into_response(),
        Err(e) => err(e),
    }
}

async fn rename_workflow(
    State(app): S,
    Path(id): Path<i64>,
    Json(b): Json<RenameBody>,
) -> Response {
    let Some(name) = clean_name(&b.name) else {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "a name cannot be empty" })),
        )
            .into_response();
    };
    match app.store.rename_workflow(id, &name) {
        Ok(true) => {
            emit(&app, "renamed", json!({ "workflow": id, "name": name }));
            Json(json!({ "ok": true, "name": name })).into_response()
        }
        Ok(false) => StatusCode::NOT_FOUND.into_response(),
        Err(e) => err(e),
    }
}

/// The queue: what arrived and has not been opened, oldest first.
async fn queue(State(app): S, Query(q): Query<Limit>) -> Response {
    match app.store.queue(q.limit.unwrap_or(QUEUE_MAX).min(QUEUE_MAX)) {
        Ok(q) => Json(q).into_response(),
        Err(e) => err(e),
    }
}

/// A tab opened a document. Every other tab hears, so the same row leaves
/// the queue everywhere at once; a document already read answers the same
/// and tells nobody, since nothing changed.
async fn mark_read(State(app): S, Path(id): Path<String>) -> Response {
    match app.store.mark_read(&id) {
        Ok(true) => {
            emit(
                &app,
                "read",
                json!({ "ids": [id], "waiting": waiting(&app) }),
            );
            Json(json!({ "ok": true })).into_response()
        }
        Ok(false) => Json(json!({ "ok": true })).into_response(),
        Err(e) => err(e),
    }
}

/// Everything waiting, read without being opened.
async fn clear_queue(State(app): S) -> Response {
    match app.store.mark_all_read() {
        Ok(ids) => {
            if !ids.is_empty() {
                emit(&app, "read", json!({ "ids": ids, "waiting": 0 }));
            }
            Json(json!({ "ok": true, "n": ids.len() })).into_response()
        }
        Err(e) => err(e),
    }
}

/// Pinning is UI state, so it needs no token; it only affects what `prune` keeps.
async fn pin(State(app): S, Path(id): Path<String>, Json(b): Json<PinBody>) -> Response {
    match app.store.set_pinned(&id, b.pinned) {
        Ok(true) => {
            emit(&app, "pinned", json!({ "id": id, "pinned": b.pinned }));
            Json(json!({ "ok": true })).into_response()
        }
        Ok(false) => StatusCode::NOT_FOUND.into_response(),
        Err(e) => err(e),
    }
}

async fn receive_doc(State(app): S, headers: HeaderMap, Json(payload): Json<Payload>) -> Response {
    if !authorized(&app, &headers) {
        return (
            StatusCode::UNAUTHORIZED,
            Json(json!({ "error": "missing or invalid token" })),
        )
            .into_response();
    }
    // Rendering is CPU work; keep it off the async executor.
    let app2 = app.clone();
    let result =
        tokio::task::spawn_blocking(move || receive::receive(&app2.store, &app2.renderer, payload))
            .await;
    match result {
        Ok(Ok(received)) => {
            let doc = received.doc;
            let url = format!("{}/d/{}", config::base_url(), doc.id);
            emit(
                &app,
                "doc",
                json!({ "doc": doc, "url": url, "existing": received.existing, "supersedes": received.supersedes, "waiting": waiting(&app) }),
            );
            if !received.existing {
                notify_desktop(&app, &doc);
            }
            if received.needs_full_highlight {
                spawn_full_highlight(app.clone(), doc.id.clone(), doc.lang.clone());
            }
            // The rail's outline, ready before the reader opens it.
            if doc.kind == crate::render::Kind::Code {
                let (app2, id, lang) = (app.clone(), doc.id.clone(), doc.lang.clone());
                tokio::task::spawn_blocking(move || outline_of(&app2, &id, lang.as_deref()));
            }
            let status = if received.existing {
                StatusCode::OK
            } else {
                StatusCode::CREATED
            };
            (
                status,
                Json(json!({
                    "id": doc.id,
                    "url": url,
                    // The same document as a `snyvi://` link, which opens in
                    // the window rather than a browser -- given only where
                    // there is a window executable for the desktop to hand
                    // it to, since anywhere else the link opens nothing.
                    "app_url": crate::desktop::window_installed().then(|| crate::desktop::app_url(&doc.id)),
                    "doc": doc,
                    "existing": received.existing,
                    // So the sender can say where the document went without a
                    // second round trip: a window, or a link to click.
                    "window": app.has_window(),
                })),
            )
                .into_response()
        }
        Ok(Err(e)) => (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": e.to_string() })),
        )
            .into_response(),
        Err(e) => err(anyhow::anyhow!(e)),
    }
}

/// A note from an agent: kept, and shown to every page at once. Never a
/// desktop notification -- a note that could be missed costs nothing.
async fn receive_note(
    State(app): S,
    headers: HeaderMap,
    Json(n): Json<crate::note::NewNote>,
) -> Response {
    if !authorized(&app, &headers) {
        return (
            StatusCode::UNAUTHORIZED,
            Json(json!({ "error": "missing or invalid token" })),
        )
            .into_response();
    }
    match app.notes.add(n, crate::store::now()) {
        Ok(note) => {
            emit(&app, "notes", json!({ "notes": app.notes.list() }));
            (
                StatusCode::CREATED,
                Json(json!({ "note": note, "window": app.has_window() })),
            )
                .into_response()
        }
        Err(e) => (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": e.to_string() })),
        )
            .into_response(),
    }
}

async fn notes(State(app): S) -> Json<serde_json::Value> {
    Json(json!({ "notes": app.notes.list() }))
}

/// A reader looked: the glow goes out in every page.
async fn see_notes(State(app): S) -> Json<serde_json::Value> {
    if app.notes.see() {
        emit(&app, "notes", json!({ "notes": app.notes.list() }));
    }
    Json(json!({ "ok": true }))
}

/// Large code files are stored partly plain for an instant first view; finish the
/// highlight off the request path and tell open tabs to refetch.
fn spawn_full_highlight(app: Arc<App>, id: String, lang: Option<String>) {
    tokio::task::spawn_blocking(move || {
        let Ok(src) = app.store.source(&id) else {
            return;
        };
        let html = app.renderer.render_code_uncapped(lang.as_deref(), &src);
        if app.store.replace_html(&id, &html).is_ok() {
            emit(&app, "rendered", json!({ "id": id }));
        }
    });
}

// ---------- browse ----------

#[derive(Deserialize)]
struct OpenBody {
    path: String,
}

#[derive(Deserialize)]
struct PathQ {
    path: Option<String>,
}

#[derive(Deserialize)]
struct FindQ {
    q: Option<String>,
    limit: Option<usize>,
}

/// Opening a folder exposes its files, so this one needs the token. Reading inside a
/// root the user already opened does not.
#[derive(Deserialize)]
struct TerminalBody {
    doc: Option<String>,
    root: Option<String>,
    path: Option<String>,
}

/// The directory a terminal would open in for a document, if one exists.
///
/// In order: the folder the file was sent from, then the project's root. The
/// second is the case that matters. `source_path` is an `Option` and a document
/// sent as content rather than as a path has none, so without the fallback the
/// button would be missing from exactly the sends that come straight out of an
/// agent.
fn doc_folder(app: &App, doc: &Doc) -> Option<std::path::PathBuf> {
    doc.source_path
        .as_deref()
        .and_then(|p| std::path::Path::new(p).parent().map(|d| d.to_path_buf()))
        .into_iter()
        .chain(app.store.project_root(doc.project_id).map(Into::into))
        .find(|d: &std::path::PathBuf| d.is_dir())
}

/// Mint a capability for a window that is opening.
///
/// The token is required, and this is the only endpoint whose answer is itself
/// a secret. The caller is `snyvi app`, in the moment between deciding to open a
/// window and launching one: see `crate::capability` for why the answer is not
/// the token itself and never reaches disk.
async fn mint_capability(State(app): S, headers: HeaderMap) -> Response {
    if !authorized(&app, &headers) {
        return (StatusCode::FORBIDDEN, Json(json!({ "error": "no token" }))).into_response();
    }
    match app.capabilities.mint() {
        Ok(capability) => Json(json!({ "capability": capability })).into_response(),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({ "error": e.to_string() })),
        )
            .into_response(),
    }
}

/// How long a socket has to prove itself. A page that holds the capability
/// sends it in its first frame, which on a loopback connection is one round
/// trip; anything still silent after this is not a page of ours, and the
/// deadline is what keeps a connection that will never speak from being held
/// open by whatever opened it.
const CAPABILITY_DEADLINE: std::time::Duration = std::time::Duration::from_secs(2);

/// The first frame on a desk socket, and the only one read before the
/// capability is known to be good.
#[derive(Deserialize)]
struct Hello {
    capability: String,
}

/// What a page says on its desk socket once it is allowed. `docs/DESK.md` has
/// the protocol; the frames going the other way are `crate::screen`'s.
#[derive(Deserialize)]
#[serde(tag = "t")]
enum Said {
    /// The panes this page is showing, which replaces whatever it showed
    /// before. Each is sent a status, its old text if it has any, and a
    /// snapshot, and then its frames.
    #[serde(rename = "watch")]
    Watch { panes: Vec<String> },
    /// Keys or a paste, for one pane this page is watching.
    #[serde(rename = "in")]
    In { p: String, d: String },
    /// The size a pane is drawn at on this page.
    #[serde(rename = "size")]
    Size { p: String, c: u16, r: u16 },
}

/// One pane's frames, from its broadcast to this socket. A page that falls so
/// far behind that the broadcast drops frames for it is not sent the rest:
/// it is sent a fresh snapshot, which is always right, instead of a diff
/// against a screen it no longer holds.
async fn forward(
    live: Arc<crate::pane::Live>,
    first: Vec<String>,
    mut rx: broadcast::Receiver<Arc<str>>,
    out: tokio::sync::mpsc::Sender<Arc<str>>,
) {
    for f in first {
        if out.send(f.into()).await.is_err() {
            return;
        }
    }
    loop {
        match rx.recv().await {
            Ok(m) => {
                if out.send(m).await.is_err() {
                    return;
                }
            }
            Err(broadcast::error::RecvError::Lagged(_)) => {
                let (first, fresh) = live.attach();
                rx = fresh;
                for f in first {
                    if out.send(f.into()).await.is_err() {
                        return;
                    }
                }
            }
            Err(broadcast::error::RecvError::Closed) => return,
        }
    }
}

/// The socket desks will speak over, and today the capability's proof and
/// nothing else.
///
/// Three refusals before a single byte of desk traffic could ever flow: the
/// capability is not accepted from the query string, the handshake must come
/// from snyvi's own page, and the socket is inert until a valid capability
/// arrives. A browser tab gets past none of them, which is the premise the
/// whole feature rests on.
async fn desk_socket(
    State(app): S,
    headers: HeaderMap,
    Query(q): Query<std::collections::HashMap<String, String>>,
    ws: WebSocketUpgrade,
) -> Response {
    // Refused rather than quietly upgraded, so that an attempt to put the
    // capability where it would be logged fails at the place it is made. A
    // query string lands in the request path; the fragment it rides on instead
    // is never sent to a server at all.
    if q.contains_key(crate::desktop::CAPABILITY_KEY) || q.contains_key("capability") {
        return (
            StatusCode::FORBIDDEN,
            Json(json!({ "error": "the capability is not a query parameter" })),
        )
            .into_response();
    }
    // The same check the terminal button is behind, for the same reason: a page
    // on another origin is refused, and a local process with no browser sends
    // neither header and is refused too.
    if !from_this_page(&headers) {
        return (
            StatusCode::FORBIDDEN,
            Json(json!({ "error": "not from this page" })),
        )
            .into_response();
    }
    ws.on_upgrade(move |socket| desk_session(app, socket))
}

/// What a first frame means: allowed, or not.
///
/// Split out from the socket so the rule can be read and tested on its own,
/// which is worth doing for the one function in this server that decides
/// whether a thing may run a shell. Anything that is not a well-formed frame
/// carrying a live capability under the one key that means it is a refusal.
fn hello_allows(caps: &crate::capability::Capabilities, frame: Option<&str>) -> bool {
    frame
        .and_then(|f| serde_json::from_str::<Hello>(f).ok())
        .is_some_and(|h| caps.verify(&h.capability))
}

/// A desk socket from the upgrade to the close.
///
/// It proves itself and then does nothing, which is the whole of this phase:
/// the panes that will speak here are two phases out. What is being built now
/// is the one thing they cannot be built without -- a socket that a window can
/// open and a tab cannot.
async fn desk_session(app: Arc<App>, mut socket: WebSocket) {
    let first = tokio::time::timeout(CAPABILITY_DEADLINE, socket.recv()).await;
    let frame = match &first {
        Ok(Some(Ok(Message::Text(t)))) => Some(t.as_str()),
        // Silence past the deadline, a close, a socket error, or a binary
        // frame: none of them is a capability, and all of them end the same
        // way. Only the text frame is read.
        _ => None,
    };
    if !hello_allows(&app.capabilities, frame) {
        let _ = socket
            .send(Message::Text(
                json!({ "error": "no capability" }).to_string().into(),
            ))
            .await;
        let _ = socket.send(Message::Close(None)).await;
        return;
    }
    let _ = socket
        .send(Message::Text(json!({ "ok": true }).to_string().into()))
        .await;
    // Bounded, so a page that cannot keep up makes its forwarders wait, and a
    // forwarder that waits long enough is resynced rather than buffered.
    let (out, mut frames) = tokio::sync::mpsc::channel::<Arc<str>>(64);
    let mut going = app.shutdown.subscribe();
    let mut watching: std::collections::HashMap<
        String,
        (Arc<crate::pane::Live>, tokio::task::JoinHandle<()>),
    > = Default::default();
    loop {
        tokio::select! {
            // The daemon is going, and the page's reconnect is what tells the
            // reader: the capability it holds dies with this process.
            _ = going.recv() => break,
            f = frames.recv() => {
                let Some(f) = f else { break };
                if socket.send(Message::Text(f.to_string().into())).await.is_err() {
                    break;
                }
            }
            msg = socket.recv() => {
                let text = match msg {
                    Some(Ok(Message::Text(t))) => t,
                    Some(Ok(Message::Close(_))) | None | Some(Err(_)) => break,
                    Some(Ok(_)) => continue,
                };
                let Ok(said) = serde_json::from_str::<Said>(text.as_str()) else { continue };
                match said {
                    Said::Watch { panes } => {
                        let wanted: std::collections::HashSet<String> = panes
                            .into_iter()
                            .filter(|id| crate::pane::valid_id(id))
                            .filter(|id| matches!(app.store.pane(id), Ok(Some(_))))
                            .take(crate::desk::EVERYWHERE as usize)
                            .collect();
                        watching.retain(|id, (_, task)| {
                            let keep = wanted.contains(id);
                            if !keep {
                                task.abort();
                            }
                            keep
                        });
                        for id in wanted {
                            if watching.contains_key(&id) {
                                continue;
                            }
                            let live = app.panes.get(&id);
                            let (first, rx) = live.attach();
                            let task = tokio::spawn(forward(live.clone(), first, rx, out.clone()));
                            watching.insert(id, (live, task));
                        }
                    }
                    // Only for a pane this page is watching: a page cannot type
                    // into a pane it is not showing.
                    Said::In { p, d } => {
                        if let Some((live, _)) = watching.get(&p) {
                            live.input(d.as_bytes(), &app.panes);
                        }
                    }
                    Said::Size { p, c, r } => {
                        if let Some((live, _)) = watching.get(&p) {
                            live.resize(c, r);
                        }
                    }
                }
            }
        }
    }
    for (_, (_, task)) in watching {
        task.abort();
    }
}

/// Did this request come from snyvi's own page?
///
/// The first check of its kind in this server, and the reason section 7 of
/// `docs/TERMINAL.md` counts it as new work: until now every endpoint either
/// carried the token or answered with something a foreign page cannot read back
/// anyway. This one is a side effect that arrives from a click.
///
/// It cannot be the token, because the page has none. The token exists so that
/// a random local process cannot inject a document, and putting it into HTML
/// that any local process can `GET` would be the end of that. So the token is
/// accepted -- it is how the CLI and the tests reach this -- and a same-origin
/// POST is accepted beside it.
///
/// `Origin` rather than `Sec-Fetch-Site`: a browser sets `Origin` on every POST,
/// same-origin included, and has done for far longer, so a window whose engine
/// predates fetch metadata still gets the button. Where the newer header is
/// present it is read too, and anything but `same-origin` is refused outright.
/// A page on another origin is refused by both; curl sends neither and needs the
/// token.
fn from_this_page(headers: &HeaderMap) -> bool {
    if let Some(site) = headers.get("sec-fetch-site").and_then(|v| v.to_str().ok()) {
        if site != "same-origin" {
            return false;
        }
    }
    let Some(origin) = headers.get(header::ORIGIN).and_then(|v| v.to_str().ok()) else {
        return false;
    };
    let port = config::port();
    ["127.0.0.1", "localhost", "[::1]"]
        .iter()
        .any(|h| origin == format!("http://{h}:{port}"))
}

/// A read from this page, which carries no `Origin`: a browser sets it on
/// every POST and every cross-origin request, but not on a same-origin GET, so
/// `from_this_page` alone refuses the desk list the window asks for.
///
/// `Host` stands in for it. A page on another origin cannot get here without an
/// `Origin` -- the capability header makes its request a CORS one -- and a page
/// that rebinds its own name to 127.0.0.1 sends that name as `Host`. Where
/// fetch metadata is sent, it has to say `same-origin` as well.
fn same_origin_read(headers: &HeaderMap) -> bool {
    if headers.contains_key(header::ORIGIN) {
        return false;
    }
    if let Some(site) = headers.get("sec-fetch-site").and_then(|v| v.to_str().ok()) {
        if site != "same-origin" {
            return false;
        }
    }
    let Some(host) = headers.get(header::HOST).and_then(|v| v.to_str().ok()) else {
        return false;
    };
    let port = config::port();
    ["127.0.0.1", "localhost", "[::1]"]
        .iter()
        .any(|h| host == format!("{h}:{port}"))
}

/// Where the capability rides on an HTTP request.
///
/// A header, for the reason the socket refuses the query string: a query
/// parameter lands in the request path and so in anything that logs one. A
/// header is the one place a page can put a secret on a `fetch` it composes
/// itself, and `EventSource`'s inability to set one is what kept the window
/// count on a query string -- a count, which grants nothing.
const CAPABILITY_HEADER: &str = "x-snyvi-capability";

/// May this request touch a desk? A sentence if not, and nothing if so.
///
/// Three refusals, the same three the socket makes, in the same order: not the
/// query string, not another page, and not without a live capability. A browser
/// tab gets past none of them, which is the premise the whole feature rests on
/// -- so this takes the capabilities and the request, and no `App`, leaving
/// nothing a forgeable signal could reach it through.
fn desk_refusal(
    caps: &crate::capability::Capabilities,
    headers: &HeaderMap,
    q: &std::collections::HashMap<String, String>,
) -> Option<&'static str> {
    if q.contains_key(crate::desktop::CAPABILITY_KEY) || q.contains_key("capability") {
        return Some("the capability is not a query parameter");
    }
    if !from_this_page(headers) && !same_origin_read(headers) {
        return Some("not from this page");
    }
    let given = headers
        .get(CAPABILITY_HEADER)
        .and_then(|v| v.to_str().ok())
        .unwrap_or_default();
    (!caps.verify(given)).then_some("no capability")
}

/// The gate as a handler uses it: the refusal, already a response.
fn refuse_desk(
    app: &App,
    headers: &HeaderMap,
    q: &std::collections::HashMap<String, String>,
) -> Option<Response> {
    desk_refusal(&app.capabilities, headers, q)
        .map(|why| (StatusCode::FORBIDDEN, Json(json!({ "error": why }))).into_response())
}

#[derive(Deserialize)]
struct NewDeskBody {
    /// A browse root's id, and the path of a folder inside it -- the two things
    /// every directory row in the sidebar already carries. None is a desk on
    /// no folder in particular, which starts in the home directory.
    #[serde(default)]
    root: Option<String>,
    #[serde(default)]
    path: String,
    #[serde(default)]
    name: Option<String>,
}

#[derive(Deserialize)]
struct LayoutBody {
    col: f64,
    row: f64,
}

#[derive(Deserialize)]
struct NewPaneBody {
    /// What to re-run when the reader asks for it. Nothing here means a shell,
    /// and nothing here starts anything: Phase 3 spawns, this phase records.
    #[serde(default)]
    cmd: Option<String>,
}

/// Every desk, with its panes, and how much of the global cap is spent.
async fn desks(
    State(app): S,
    headers: HeaderMap,
    Query(q): Query<std::collections::HashMap<String, String>>,
) -> Response {
    if let Some(no) = refuse_desk(&app, &headers, &q) {
        return no;
    }
    match (app.store.desks(), app.store.panes_open()) {
        (Ok(desks), Ok(panes)) => Json(json!({
            "desks": with_status(&app, &desks),
            // So a pane's header can say `~/snyvi` rather than the whole path.
            "home": dirs::home_dir(),
            "panes": panes,
            "cap": crate::desk::EVERYWHERE,
            "per_desk": crate::desk::PER_DESK,
        }))
        .into_response(),
        (Err(e), _) | (_, Err(e)) => err(e),
    }
}

/// The desks, each pane carrying what its runtime says about it: running or
/// not, blocked or not, and the rest of what the rail draws.
fn with_status(app: &App, desks: &[crate::desk::Desk]) -> serde_json::Value {
    let mut v = serde_json::to_value(desks).unwrap_or_default();
    for d in v.as_array_mut().into_iter().flatten() {
        for p in d["panes"].as_array_mut().into_iter().flatten() {
            let id = p["id"].as_str().unwrap_or_default().to_string();
            p["status"] = serde_json::to_value(app.panes.status(&id)).unwrap_or_default();
        }
    }
    v
}

/// A new desk, on a folder or on none.
///
/// The folder arrives as a root id and a relative path rather than as an
/// absolute one, so it goes through `resolve` -- the same guard the terminal
/// button and every byte `browse_file` reads go through, which is what keeps a
/// path from the page inside the root it names.
async fn create_desk(
    State(app): S,
    headers: HeaderMap,
    Query(q): Query<std::collections::HashMap<String, String>>,
    Json(b): Json<NewDeskBody>,
) -> Response {
    if let Some(no) = refuse_desk(&app, &headers, &q) {
        return no;
    }
    // No folder is the home directory, which the daemon names and the page
    // does not: nothing from the page reaches the filesystem on this path.
    let (dir, fallback) = match &b.root {
        Some(root) => match app.browse.resolve(root, &b.path) {
            Ok(dir) => (dir, None),
            Err(_) => {
                return (
                    StatusCode::BAD_REQUEST,
                    Json(json!({ "error": "no such folder" })),
                )
                    .into_response()
            }
        },
        None => match dirs::home_dir() {
            Some(home) => (home, Some("desk")),
            None => {
                return (
                    StatusCode::BAD_REQUEST,
                    Json(json!({ "error": "there is no home directory to start in" })),
                )
                    .into_response()
            }
        },
    };
    if !dir.is_dir() {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "a desk is rooted at a folder" })),
        )
            .into_response();
    }
    // A desk on the home directory would otherwise be named after the user.
    let name = b
        .name
        .as_deref()
        .and_then(clean_name)
        .or(fallback.map(String::from));
    match app
        .store
        .create_desk(&dir.to_string_lossy(), name.as_deref())
    {
        Ok(desk) => {
            desks_moved(&app);
            (StatusCode::CREATED, Json(json!({ "desk": desk }))).into_response()
        }
        Err(e) => err(e),
    }
}

/// The documents the panes on a desk have sent, for the rail's Documents
/// list. Forty is more than a rail shows without scrolling and fewer than a
/// long day of a file being watched produces; the library has the rest.
async fn desk_docs(
    State(app): S,
    headers: HeaderMap,
    Path(id): Path<i64>,
    Query(q): Query<std::collections::HashMap<String, String>>,
) -> Response {
    if let Some(no) = refuse_desk(&app, &headers, &q) {
        return no;
    }
    match app.store.desk_docs(id, 40) {
        Ok(docs) => Json(json!({ "docs": docs })).into_response(),
        Err(e) => err(e),
    }
}

/// A desk's own list, which is the reader's and not an agent's: `/api/notes`
/// is the other kind, and the two never meet. Behind the same gate as the rest
/// of a desk, so what someone wrote on theirs is as unreachable from a tab as
/// their panes are.
///
/// None of the four writes below tells the other windows. A list is typed into
/// one window at a time, a keystroke is not an event worth waking every page
/// for, and the rail asks again whenever its desk is drawn -- the same trade
/// `desk_layout` makes for a divider being dragged.
async fn desk_notes(
    State(app): S,
    headers: HeaderMap,
    Path(id): Path<i64>,
    Query(q): Query<std::collections::HashMap<String, String>>,
) -> Response {
    if let Some(no) = refuse_desk(&app, &headers, &q) {
        return no;
    }
    match app.store.desk_notes(id) {
        Ok(notes) => Json(json!({ "notes": notes })).into_response(),
        Err(e) => err(e),
    }
}

async fn add_desk_note(
    State(app): S,
    headers: HeaderMap,
    Path(id): Path<i64>,
    Query(q): Query<std::collections::HashMap<String, String>>,
    Json(b): Json<NoteTextBody>,
) -> Response {
    if let Some(no) = refuse_desk(&app, &headers, &q) {
        return no;
    }
    match app.store.add_desk_note(id, &b.text) {
        // One refusal for three states -- no such desk, an empty line, a full
        // list -- because the page has just been told the count and can say
        // which it is; the daemon repeating it would be two sources for one
        // sentence.
        Ok(Some(note)) => (StatusCode::CREATED, Json(json!({ "note": note }))).into_response(),
        Ok(None) => (
            StatusCode::CONFLICT,
            Json(json!({ "error": format!("a desk keeps {} notes", crate::desk::NOTES_PER_DESK) })),
        )
            .into_response(),
        Err(e) => err(e),
    }
}

/// Rewrite a line, tick it off, or both. An emptied line is taken off the list
/// rather than kept as a blank row, which is what `desk::set_note` does with it.
async fn set_desk_note(
    State(app): S,
    headers: HeaderMap,
    Path((id, note)): Path<(i64, i64)>,
    Query(q): Query<std::collections::HashMap<String, String>>,
    Json(b): Json<NoteEditBody>,
) -> Response {
    if let Some(no) = refuse_desk(&app, &headers, &q) {
        return no;
    }
    match app.store.set_desk_note(id, note, b.text.as_deref(), b.done) {
        Ok(true) => Json(json!({ "ok": true })).into_response(),
        Ok(false) => StatusCode::NOT_FOUND.into_response(),
        Err(e) => err(e),
    }
}

/// Take a line off the list. The row is kept and `restore` puts it back: this
/// path deletes nothing, which is why it does not ask twice the way closing a
/// desk does.
async fn remove_desk_note(
    State(app): S,
    headers: HeaderMap,
    Path((id, note)): Path<(i64, i64)>,
    Query(q): Query<std::collections::HashMap<String, String>>,
) -> Response {
    if let Some(no) = refuse_desk(&app, &headers, &q) {
        return no;
    }
    match app.store.remove_desk_note(id, note) {
        Ok(true) => Json(json!({ "ok": true })).into_response(),
        Ok(false) => StatusCode::NOT_FOUND.into_response(),
        Err(e) => err(e),
    }
}

async fn restore_desk_note(
    State(app): S,
    headers: HeaderMap,
    Path((id, note)): Path<(i64, i64)>,
    Query(q): Query<std::collections::HashMap<String, String>>,
) -> Response {
    if let Some(no) = refuse_desk(&app, &headers, &q) {
        return no;
    }
    match app.store.restore_desk_note(id, note) {
        Ok(true) => Json(json!({ "ok": true })).into_response(),
        Ok(false) => StatusCode::NOT_FOUND.into_response(),
        Err(e) => err(e),
    }
}

async fn rename_desk(
    State(app): S,
    headers: HeaderMap,
    Path(id): Path<i64>,
    Query(q): Query<std::collections::HashMap<String, String>>,
    Json(b): Json<RenameBody>,
) -> Response {
    if let Some(no) = refuse_desk(&app, &headers, &q) {
        return no;
    }
    let Some(name) = clean_name(&b.name) else {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "a name cannot be empty" })),
        )
            .into_response();
    };
    match app.store.rename_desk(id, &name) {
        Ok(true) => {
            desks_moved(&app);
            Json(json!({ "ok": true, "name": name })).into_response()
        }
        Ok(false) => StatusCode::NOT_FOUND.into_response(),
        Err(e) => err(e),
    }
}

/// The two divider fractions, which are the whole of a desk's geometry.
async fn desk_layout(
    State(app): S,
    headers: HeaderMap,
    Path(id): Path<i64>,
    Query(q): Query<std::collections::HashMap<String, String>>,
    Json(b): Json<LayoutBody>,
) -> Response {
    if let Some(no) = refuse_desk(&app, &headers, &q) {
        return no;
    }
    match app.store.set_desk_layout(id, b.col, b.row) {
        // Silent: a drag ends hundreds of times an hour and no other window
        // needs to be told where this one's divider came to rest.
        Ok(true) => Json(json!({ "ok": true })).into_response(),
        Ok(false) => StatusCode::NOT_FOUND.into_response(),
        Err(e) => err(e),
    }
}

async fn delete_desk(
    State(app): S,
    headers: HeaderMap,
    Path(id): Path<i64>,
    Query(q): Query<std::collections::HashMap<String, String>>,
) -> Response {
    if let Some(no) = refuse_desk(&app, &headers, &q) {
        return no;
    }
    let panes: Vec<String> = app
        .store
        .desk(id)
        .ok()
        .flatten()
        .map(|d| d.panes.into_iter().map(|p| p.id).collect())
        .unwrap_or_default();
    match app.store.delete_desk(id) {
        Ok(true) => {
            for p in &panes {
                app.panes.close(p);
            }
            desks_moved(&app);
            Json(json!({ "ok": true })).into_response()
        }
        Ok(false) => StatusCode::NOT_FOUND.into_response(),
        Err(e) => err(e),
    }
}

/// A pane on a desk, in the lowest free slot, rooted where the desk is.
///
/// The cwd is the desk's own and is not taken from the caller: a desk is
/// already a folder the reader chose, and a second place for a path to come
/// from would be a second place to guard.
async fn open_pane(
    State(app): S,
    headers: HeaderMap,
    Path(id): Path<i64>,
    Query(q): Query<std::collections::HashMap<String, String>>,
    Json(b): Json<NewPaneBody>,
) -> Response {
    if let Some(no) = refuse_desk(&app, &headers, &q) {
        return no;
    }
    let Ok(Some(desk)) = app.store.desk(id) else {
        return StatusCode::NOT_FOUND.into_response();
    };
    let cmd = b.cmd.unwrap_or_default();
    match app.store.open_pane(desk.id, &desk.root, cmd.trim()) {
        Ok(crate::desk::Opened::Pane(pane)) => {
            desks_moved(&app);
            (StatusCode::CREATED, Json(json!({ "pane": pane }))).into_response()
        }
        // Full, twice, and the two say different things because the reader has
        // to do something different about them: another desk takes the next
        // pane, or something has to be closed first.
        Ok(crate::desk::Opened::DeskFull) => (
            StatusCode::CONFLICT,
            Json(json!({ "error": format!("this desk holds {}", crate::desk::PER_DESK), "full": "desk" })),
        )
            .into_response(),
        Ok(crate::desk::Opened::NoRoomLeft) => (
            StatusCode::CONFLICT,
            Json(json!({ "error": format!("{} panels is the whole of it", crate::desk::EVERYWHERE), "full": "everywhere" })),
        )
            .into_response(),
        Ok(crate::desk::Opened::NoSuchDesk) => StatusCode::NOT_FOUND.into_response(),
        Err(e) => err(e),
    }
}

async fn close_pane(
    State(app): S,
    headers: HeaderMap,
    Path(id): Path<String>,
    Query(q): Query<std::collections::HashMap<String, String>>,
) -> Response {
    if let Some(no) = refuse_desk(&app, &headers, &q) {
        return no;
    }
    match app.store.close_pane(&id) {
        Ok(true) => {
            app.panes.close(&id);
            desks_moved(&app);
            Json(json!({ "ok": true })).into_response()
        }
        Ok(false) => StatusCode::NOT_FOUND.into_response(),
        Err(e) => err(e),
    }
}

/// Tell the windows that the list changed.
///
/// A nudge and nothing in it. The event stream goes to every page, tabs
/// included, and a pane's command and its folder are the desk's business, not
/// a tab's: so a window hearing this asks `/api/desks` again, with its
/// capability, and a tab hearing it can ask nothing.
fn desks_moved(app: &App) {
    emit(app, "desks", json!({}));
}

#[derive(Deserialize)]
struct StartBody {
    /// What to run, as typed into the pane's `Start`. Absent means what the
    /// pane ran last; empty means the shell.
    #[serde(default)]
    cmd: Option<String>,
    #[serde(default = "default_cols")]
    cols: u16,
    #[serde(default = "default_rows")]
    rows: u16,
    /// The accent the window wears, `#rrggbb`, as its CSS resolved it. The
    /// pane's prompt is drawn in it; absent means snyvi's own.
    #[serde(default)]
    accent: String,
}
fn default_cols() -> u16 {
    80
}
fn default_rows() -> u16 {
    24
}

/// Start a pane's process. The only way one starts: this request, from a
/// click in a window holding the capability. Nothing on a timer, nothing at
/// daemon start, and nothing derived from a document -- premise 3.
async fn start_pane(
    State(app): S,
    headers: HeaderMap,
    Path(id): Path<String>,
    Query(q): Query<std::collections::HashMap<String, String>>,
    Json(b): Json<StartBody>,
) -> Response {
    if let Some(no) = refuse_desk(&app, &headers, &q) {
        return no;
    }
    let Ok(Some(placed)) = app.store.pane(&id) else {
        return StatusCode::NOT_FOUND.into_response();
    };
    let cmd = b.cmd.unwrap_or_else(|| placed.pane.cmd.clone());
    if cmd.trim() != placed.pane.cmd {
        let _ = app.store.set_pane_cmd(&id, &cmd);
    }
    let live = app.panes.get(&id);
    let start = crate::pane::Start {
        cwd: &placed.pane.cwd,
        cmd: &cmd,
        desk: &placed.desk_name,
        slot: placed.pane.slot,
        cols: b.cols,
        rows: b.rows,
        accent: &b.accent,
    };
    match live.start(start, &app.panes) {
        Ok(status) => Json(json!({ "status": status })).into_response(),
        Err(e) => (
            StatusCode::CONFLICT,
            Json(json!({ "error": e.to_string() })),
        )
            .into_response(),
    }
}

/// Hang up on a pane's process. The pane stays, stopped, with `Start` offered.
async fn stop_pane(
    State(app): S,
    headers: HeaderMap,
    Path(id): Path<String>,
    Query(q): Query<std::collections::HashMap<String, String>>,
) -> Response {
    if let Some(no) = refuse_desk(&app, &headers, &q) {
        return no;
    }
    let Ok(Some(_)) = app.store.pane(&id) else {
        return StatusCode::NOT_FOUND.into_response();
    };
    app.panes.get(&id).stop();
    Json(json!({ "ok": true })).into_response()
}

/// An image pasted into a pane. A terminal cannot take a bitmap, so snyvi does
/// what it does with everything else: the image is received as a document,
/// named for the pane it came from, and what goes back to the page is a path
/// the page then types into the pane as the reader's paste.
///
/// A path and not the document's URL: the program on the other end is almost
/// always an agent, and an agent opens a file with its own tools and has no
/// reason to be able to fetch from this daemon. The file sits beside the
/// store, in `pastes/`, named by its content so pasting it twice is one file.
/// A sandboxed agent may not be allowed to read there; that is the one open
/// question this leaves, and `docs/DESK.md` says so.
async fn paste_image(
    State(app): S,
    headers: HeaderMap,
    Path(id): Path<String>,
    Query(q): Query<std::collections::HashMap<String, String>>,
    body: axum::body::Bytes,
) -> Response {
    if let Some(no) = refuse_desk(&app, &headers, &q) {
        return no;
    }
    let Ok(Some(placed)) = app.store.pane(&id) else {
        return StatusCode::NOT_FOUND.into_response();
    };
    let ext = match headers
        .get(header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .unwrap_or_default()
    {
        "image/png" => "png",
        "image/jpeg" => "jpg",
        "image/gif" => "gif",
        "image/webp" => "webp",
        _ => {
            return (
                StatusCode::UNSUPPORTED_MEDIA_TYPE,
                Json(json!({ "error": "an image, as png, jpeg, gif or webp" })),
            )
                .into_response()
        }
    };
    if body.is_empty() {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "an empty paste" })),
        )
            .into_response();
    }
    let dir = app.paths.data_dir.join("pastes");
    let name = format!("{}.{ext}", &blake3::hash(&body).to_hex()[..16]);
    let file = dir.join(&name);
    if let Err(e) = std::fs::create_dir_all(&dir).and_then(|_| std::fs::write(&file, &body)) {
        return err(anyhow::anyhow!("keeping the pasted image: {e}"));
    }
    let payload = Payload {
        path: Some(file.to_string_lossy().to_string()),
        title: Some(format!(
            "Pasted into {} [{}]",
            placed.desk_name, placed.pane.slot
        )),
        workflow: Some(format!("{} pastes", placed.desk_name)),
        cwd: Some(placed.root.clone()),
        origin: Some("paste".into()),
        pane: Some(id.clone()),
        ..Default::default()
    };
    let app2 = app.clone();
    match tokio::task::spawn_blocking(move || {
        receive::receive(&app2.store, &app2.renderer, payload)
    })
    .await
    {
        Ok(Ok(received)) => {
            let doc = received.doc;
            emit(
                &app,
                "doc",
                json!({ "doc": doc, "url": format!("{}/d/{}", config::base_url(), doc.id), "existing": received.existing, "supersedes": received.supersedes, "waiting": waiting(&app) }),
            );
            Json(json!({ "id": doc.id, "path": file })).into_response()
        }
        Ok(Err(e)) => (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": e.to_string() })),
        )
            .into_response(),
        Err(e) => err(anyhow::anyhow!(e)),
    }
}

/// Open the machine's own terminal, in the directory the reader is looking at.
///
/// The only thing this takes from the caller is an id snyvi already holds; the
/// directory is looked up here, no command is passed, and nothing comes back.
/// `docs/TERMINAL.md` has the argument, and section 3 of it has what is
/// deliberately absent.
async fn terminal(State(app): S, headers: HeaderMap, Json(b): Json<TerminalBody>) -> Response {
    if !from_this_page(&headers) && !authorized(&app, &headers) {
        return (
            StatusCode::FORBIDDEN,
            Json(json!({ "error": "not from this page, and no token" })),
        )
            .into_response();
    }
    let dir = if let Some(id) = b.root.as_deref() {
        // `resolve` is what keeps a path from the caller inside the root it
        // names -- the same guard `browse_file` reads its bytes through. A file
        // opens beside itself; the root opens at the root.
        app.browse
            .resolve(id, b.path.as_deref().unwrap_or(""))
            .ok()
            .and_then(|p| {
                if p.is_dir() {
                    Some(p)
                } else {
                    p.parent().map(|d| d.to_path_buf())
                }
            })
    } else if let Some(id) = b.doc.as_deref() {
        app.store
            .get(id)
            .ok()
            .flatten()
            .and_then(|d| doc_folder(&app, &d))
    } else {
        None
    };
    let Some(dir) = dir.filter(|d| d.is_dir()) else {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "no folder to open" })),
        )
            .into_response();
    };
    // `open_terminal` refuses without a display as well; asking here is only so
    // that the two ways of having no terminal say different things.
    if !platform::has_display() {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(json!({ "error": "no desktop session to open a terminal in" })),
        )
            .into_response();
    }
    if platform::open_terminal(&dir) {
        Json(json!({ "dir": dir })).into_response()
    } else {
        (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(json!({ "error": "no terminal found on this machine" })),
        )
            .into_response()
    }
}

async fn browse_open(State(app): S, headers: HeaderMap, Json(b): Json<OpenBody>) -> Response {
    if !authorized(&app, &headers) {
        return (
            StatusCode::UNAUTHORIZED,
            Json(json!({ "error": "missing or invalid token" })),
        )
            .into_response();
    }
    match app.browse.open(std::path::Path::new(&b.path)) {
        Ok(root) => {
            let url = format!("{}/b/{}", config::base_url(), root.id);
            emit(&app, "browse", json!({ "roots": app.browse.list() }));
            (
                StatusCode::CREATED,
                Json(json!({ "root": root, "url": url })),
            )
                .into_response()
        }
        Err(e) => (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": e.to_string() })),
        )
            .into_response(),
    }
}

/// The sidebar's `+` beside Folders: the desktop's own folder dialog, and the
/// folder it answers with opened for browsing.
///
/// Behind the same gate as the desks, because it is the same kind of act: a
/// page reaching the filesystem. The page names nothing -- it asks, and the
/// path comes from the reader's hand in a dialog the desktop draws. A browser
/// tab is refused before a dialog is shown, and one dialog is open at a time,
/// so a page cannot stack them on the reader's screen.
async fn browse_pick(
    State(app): S,
    headers: HeaderMap,
    Query(q): Query<std::collections::HashMap<String, String>>,
) -> Response {
    if let Some(no) = refuse_desk(&app, &headers, &q) {
        return no;
    }
    static PICKING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
    if PICKING.swap(true, std::sync::atomic::Ordering::SeqCst) {
        return (
            StatusCode::CONFLICT,
            Json(json!({ "error": "a folder dialog is already open" })),
        )
            .into_response();
    }
    // Cleared by dropping, not by the line after the await: a reader who closes
    // the window while the dialog is up drops this handler's future where it
    // waits, and a flag cleared below that line would stay true for the life of
    // the daemon -- one abandoned dialog and the `+` never works again.
    struct Done;
    impl Drop for Done {
        fn drop(&mut self) {
            PICKING.store(false, std::sync::atomic::Ordering::SeqCst);
        }
    }
    let _done = Done;
    let picked = tokio::task::spawn_blocking(crate::platform::pick_folder).await;
    match picked {
        Ok(Ok(Some(dir))) => match app.browse.open(&dir) {
            Ok(root) => {
                let url = format!("{}/b/{}", config::base_url(), root.id);
                emit(&app, "browse", json!({ "roots": app.browse.list() }));
                (
                    StatusCode::CREATED,
                    Json(json!({ "root": root, "url": url })),
                )
                    .into_response()
            }
            Err(e) => (
                StatusCode::BAD_REQUEST,
                Json(json!({ "error": e.to_string() })),
            )
                .into_response(),
        },
        // Closed without a choice: nothing to say, and nothing opened.
        Ok(Ok(None)) => StatusCode::NO_CONTENT.into_response(),
        Ok(Err(why)) => {
            (StatusCode::NOT_IMPLEMENTED, Json(json!({ "error": why }))).into_response()
        }
        Err(e) => err(anyhow::anyhow!(e)),
    }
}

async fn browse_list(State(app): S) -> Response {
    Json(app.browse.list()).into_response()
}

async fn browse_close(State(app): S, Path(id): Path<String>) -> Response {
    if app.browse.close(&id) {
        emit(&app, "browse", json!({ "roots": app.browse.list() }));
        Json(json!({ "ok": true })).into_response()
    } else {
        StatusCode::NOT_FOUND.into_response()
    }
}

async fn browse_tree(State(app): S, Path(id): Path<String>, Query(q): Query<PathQ>) -> Response {
    match app.browse.entries(&id, q.path.as_deref().unwrap_or("")) {
        Ok(entries) => Json(entries).into_response(),
        Err(e) => (
            StatusCode::NOT_FOUND,
            Json(json!({ "error": e.to_string() })),
        )
            .into_response(),
    }
}

async fn browse_file(State(app): S, Path(id): Path<String>, Query(q): Query<PathQ>) -> Response {
    let rel = q.path.unwrap_or_default();
    let app2 = app.clone();
    let rel2 = rel.clone();
    let id2 = id.clone();
    // Rendering is CPU work; keep it off the async executor.
    let res =
        tokio::task::spawn_blocking(move || app2.browse.file(&id2, &rel2, &app2.renderer)).await;
    match res {
        Ok(Ok(view)) => {
            let root = app.browse.get(&id);
            Json(json!({ "file": view, "root": root })).into_response()
        }
        Ok(Err(e)) => (
            StatusCode::NOT_FOUND,
            Json(json!({ "error": e.to_string() })),
        )
            .into_response(),
        Err(e) => err(anyhow::anyhow!(e)),
    }
}

async fn browse_raw(State(app): S, Path(id): Path<String>, Query(q): Query<PathQ>) -> Response {
    serve_browsed(&app, &id, q.path.as_deref().unwrap_or("")).await
}

/// The same bytes under a path-shaped URL. A framed page is loaded from here so that
/// its own relative stylesheets, scripts and images resolve against the file's
/// directory instead of against `/api/browse/<id>/`.
async fn browse_raw_path(State(app): S, Path((id, rel)): Path<(String, String)>) -> Response {
    serve_browsed(&app, &id, &rel).await
}

/// Headers that make a file safe to frame.
///
/// A page is somebody else's code: the frame denies it our origin, and this denies it
/// the network, so it cannot report home with whatever it can see. A PDF is not code
/// at all — it goes to the browser's own viewer, which refuses to run inside a
/// sandbox, so it is framed unsandboxed and `nosniff` plus its content type are what
/// keep it from ever being treated as a page. Anything else is served inert.
fn protect(headers: &mut HeaderMap, ext: &str) {
    let policy = match render::preview_kind(ext) {
        Some("html") => "connect-src 'none'; form-action 'none'; frame-ancestors 'self'",
        Some("pdf") => "frame-ancestors 'self'",
        _ => "sandbox; default-src 'none'",
    };
    if let Ok(v) = HeaderValue::from_str(policy) {
        headers.insert(header::CONTENT_SECURITY_POLICY, v);
    }
    headers.insert(
        header::X_CONTENT_TYPE_OPTIONS,
        HeaderValue::from_static("nosniff"),
    );
}

async fn serve_browsed(app: &Arc<App>, id: &str, rel: &str) -> Response {
    let Ok(path) = app.browse.resolve(id, rel) else {
        return StatusCode::NOT_FOUND.into_response();
    };
    let Ok(bytes) = tokio::fs::read(&path).await else {
        return StatusCode::NOT_FOUND.into_response();
    };
    let mime = mime_guess::from_path(&path)
        .first_or_octet_stream()
        .to_string();
    let mut headers = HeaderMap::new();
    let mut set = |k: header::HeaderName, v: &str| {
        if let Ok(v) = HeaderValue::from_str(v) {
            headers.insert(k, v);
        }
    };
    set(header::CONTENT_TYPE, &mime);
    set(header::CACHE_CONTROL, "private, max-age=60");
    protect(&mut headers, &render::ext_of(&path.to_string_lossy()));
    (headers, bytes).into_response()
}

/// Declarations in a browsed file. Parsing is repeated rather than cached: it is
/// off the first-paint path and the rail asks for it only once per file.
async fn browse_outline(State(app): S, Path(id): Path<String>, Query(q): Query<PathQ>) -> Response {
    let rel = q.path.unwrap_or_default();
    let Ok(path) = app.browse.resolve(&id, &rel) else {
        return StatusCode::NOT_FOUND.into_response();
    };
    drop(path);
    let app2 = app.clone();
    let res =
        tokio::task::spawn_blocking(move || app2.browse.outline(&id, &rel, &app2.renderer)).await;
    match res {
        Ok(items) => Json(items.unwrap_or_default()).into_response(),
        Err(e) => err(anyhow::anyhow!(e)),
    }
}

async fn browse_find(State(app): S, Path(id): Path<String>, Query(q): Query<FindQ>) -> Response {
    let app2 = app.clone();
    let query = q.q.unwrap_or_default();
    let limit = q.limit.unwrap_or(40).min(200);
    match tokio::task::spawn_blocking(move || app2.browse.find(&id, &query, limit)).await {
        Ok(Ok(hits)) => Json(hits).into_response(),
        Ok(Err(e)) => (
            StatusCode::NOT_FOUND,
            Json(json!({ "error": e.to_string() })),
        )
            .into_response(),
        Err(e) => err(anyhow::anyhow!(e)),
    }
}

async fn shell_browse(State(app): S, Path(id): Path<String>) -> Response {
    browse_shell(app, id, String::new()).await
}

async fn shell_browse_file(State(app): S, Path((id, path)): Path<(String, String)>) -> Response {
    browse_shell(app, id, path).await
}

async fn browse_shell(app: Arc<App>, id: String, path: String) -> Response {
    let Some(root) = app.browse.get(&id) else {
        return (
            StatusCode::NOT_FOUND,
            Html("<h1>That folder is no longer open</h1>"),
        )
            .into_response();
    };
    // Land on the README when no file was asked for.
    let path = if path.is_empty() {
        app.browse.landing(&id).unwrap_or_default()
    } else {
        path
    };
    let title = if path.is_empty() {
        root.name.clone()
    } else {
        path.clone()
    };
    let boot = json!({
        "view": "browse",
        "tree": app.store.projects().unwrap_or_default(),
        "browse": app.browse.list(),
        "browseRoot": root,
        "browsePath": path,
        "version": VERSION,
    });
    shell(&app, boot, "", &title)
}

fn authorized(app: &App, headers: &HeaderMap) -> bool {
    let bearer = headers
        .get(header::AUTHORIZATION)
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.strip_prefix("Bearer "))
        .map(str::trim);
    let alt = headers
        .get("x-snyvi-token")
        .and_then(|v| v.to_str().ok())
        .map(str::trim);
    bearer
        .or(alt)
        .map(|t| constant_eq(t, &app.token.read().unwrap()))
        .unwrap_or(false)
}

fn constant_eq(a: &str, b: &str) -> bool {
    a.len() == b.len()
        && a.bytes()
            .zip(b.bytes())
            .fold(0u8, |acc, (x, y)| acc | (x ^ y))
            == 0
}

fn err(e: anyhow::Error) -> Response {
    (
        StatusCode::INTERNAL_SERVER_ERROR,
        Json(json!({ "error": e.to_string() })),
    )
        .into_response()
}

#[cfg(test)]
mod tests {
    use super::{
        desk_refusal, hello_allows, Ui, ABOUT_JS, APP_CSS, APP_JS, BOOT_JS, DESK_JS, FIND_JS,
        FRAME_JS, GAME_JS, INDEX_HTML, MENU_JS, MMD_JS,
    };
    use crate::capability::Capabilities;
    use axum::http::{header, HeaderMap, HeaderValue};

    /// The one decision in this server that stands between a web page and a
    /// shell. Every shape that is not a live capability under the key that
    /// means it has to be a refusal, including the shapes that look close.
    #[test]
    fn only_a_frame_carrying_a_live_capability_opens_a_desk() {
        let caps = Capabilities::default();
        let cap = caps.mint().unwrap();

        assert!(hello_allows(
            &caps,
            Some(&format!(r#"{{"capability":"{cap}"}}"#))
        ));

        // Silence until the deadline, which is what a socket opened by
        // something with nothing to present does.
        assert!(!hello_allows(&caps, None));
        // A capability that was never minted, and the empty one.
        assert!(!hello_allows(
            &caps,
            Some(&format!(r#"{{"capability":"{}"}}"#, "b".repeat(64)))
        ));
        assert!(!hello_allows(&caps, Some(r#"{"capability":""}"#)));
        // The right secret under the wrong key is not a hello, and neither is a
        // bare string: the frame has to be the shape the protocol says.
        assert!(!hello_allows(
            &caps,
            Some(&format!(r#"{{"token":"{cap}"}}"#))
        ));
        assert!(!hello_allows(&caps, Some(&format!(r#""{cap}""#))));
        assert!(!hello_allows(&caps, Some("")));
        assert!(!hello_allows(&caps, Some("not json at all")));
    }

    /// `window=1` is forgeable, so the desk path must never read it. The two
    /// window signals were allowed to coexist on exactly this condition: the
    /// count answers "how many are reading", the capability answers "may this
    /// page run a shell", and the second never consults the first. `EventSource`
    /// cannot set a header, which is why the count still rides a query string;
    /// this test is what makes that harmless rather than a second way in.
    #[test]
    fn the_window_count_is_never_consulted_on_the_desk_path() {
        let src = include_str!("server.rs");
        let from = src
            .find("async fn desk_socket")
            .expect("the desk socket should be in this file");
        let to = src[from..]
            .find("\nfn hello_allows")
            .expect("hello_allows follows the socket")
            + from;
        let path = &src[from..to];

        for forgeable in ["has_window", "windows", "is_window", "EventsQ"] {
            assert!(
                !path.contains(forgeable),
                "the desk path reads `{forgeable}`, which a browser tab can forge"
            );
        }
        // And the gate it does go through takes no app at all, so there is
        // nothing for a count to reach it through even by accident.
        assert!(
            src.contains(
                "fn hello_allows(caps: &crate::capability::Capabilities, frame: Option<&str>)"
            ),
            "the desk gate should see a capability and a frame, and nothing else"
        );
    }

    /// The same three refusals as the socket, on the routes a desk is made
    /// and named over. The capability rides in a header because that is the
    /// one place a page can put a secret on a request it composes itself --
    /// and the query string, where it would be logged, is refused at the place
    /// the attempt is made rather than quietly ignored.
    #[test]
    fn a_desk_route_takes_its_capability_from_a_header_and_nowhere_else() {
        let caps = Capabilities::default();
        let cap = caps.mint().unwrap();
        let none = std::collections::HashMap::new();
        let ours = |cap: &str| {
            let mut h = HeaderMap::new();
            h.insert(
                header::ORIGIN,
                HeaderValue::from_str(&crate::config::base_url()).unwrap(),
            );
            h.insert("sec-fetch-site", HeaderValue::from_static("same-origin"));
            if !cap.is_empty() {
                h.insert(
                    super::CAPABILITY_HEADER,
                    HeaderValue::from_str(cap).unwrap(),
                );
            }
            h
        };

        assert_eq!(desk_refusal(&caps, &ours(&cap), &none), None);

        // A page of ours, and no capability: a browser tab, which is the case
        // the whole feature rests on refusing.
        assert_eq!(desk_refusal(&caps, &ours(""), &none), Some("no capability"));
        assert_eq!(
            desk_refusal(&caps, &ours(&"c".repeat(64)), &none),
            Some("no capability")
        );

        // The right secret, in the wrong place.
        let query = std::collections::HashMap::from([("cap".to_string(), cap.clone())]);
        assert_eq!(
            desk_refusal(&caps, &ours(&cap), &query),
            Some("the capability is not a query parameter")
        );
        let query = std::collections::HashMap::from([("capability".to_string(), cap.clone())]);
        assert_eq!(
            desk_refusal(&caps, &ours(&cap), &query),
            Some("the capability is not a query parameter")
        );

        // Another origin, and a local process with no browser at all: neither
        // is this page, whatever it is holding.
        let mut elsewhere = ours(&cap);
        elsewhere.insert(
            header::ORIGIN,
            HeaderValue::from_static("http://evil.example"),
        );
        assert_eq!(
            desk_refusal(&caps, &elsewhere, &none),
            Some("not from this page")
        );
        let mut bare = HeaderMap::new();
        bare.insert(
            super::CAPABILITY_HEADER,
            HeaderValue::from_str(&cap).unwrap(),
        );
        assert_eq!(
            desk_refusal(&caps, &bare, &none),
            Some("not from this page")
        );

        // The window's own GET: a browser sends no `Origin` on a same-origin
        // read, so `Host` is what says it is ours. The live window found this;
        // the desk list was refused and every desk read "No such desk".
        let read = |host: &str, site: Option<&'static str>| {
            let mut h = HeaderMap::new();
            h.insert(header::HOST, HeaderValue::from_str(host).unwrap());
            if let Some(s) = site {
                h.insert("sec-fetch-site", HeaderValue::from_static(s));
            }
            h.insert(
                super::CAPABILITY_HEADER,
                HeaderValue::from_str(&cap).unwrap(),
            );
            h
        };
        let here = format!("127.0.0.1:{}", crate::config::port());
        assert_eq!(
            desk_refusal(&caps, &read(&here, Some("same-origin")), &none),
            None
        );
        assert_eq!(desk_refusal(&caps, &read(&here, None), &none), None);
        // A name rebound to 127.0.0.1 is still its own name in `Host`.
        let rebound = format!("evil.example:{}", crate::config::port());
        assert_eq!(
            desk_refusal(&caps, &read(&rebound, Some("same-origin")), &none),
            Some("not from this page")
        );
        assert_eq!(
            desk_refusal(&caps, &read(&here, Some("cross-site")), &none),
            Some("not from this page")
        );
    }

    /// A gate helps only if every route is behind it, and a route added later
    /// is exactly the one that will forget. So the file is read: each desk
    /// handler must reach the gate before it reaches the store.
    #[test]
    fn every_desk_route_is_behind_the_gate() {
        // A checkout on Windows can have CRLF line endings, and the end of a
        // handler is found by its newlines.
        let src = include_str!("server.rs").replace("\r\n", "\n");
        let src = src.as_str();
        for handler in [
            "async fn desks(",
            "async fn create_desk(",
            "async fn browse_pick(",
            "async fn rename_desk(",
            "async fn desk_layout(",
            "async fn delete_desk(",
            "async fn desk_docs(",
            "async fn desk_notes(",
            "async fn add_desk_note(",
            "async fn set_desk_note(",
            "async fn remove_desk_note(",
            "async fn restore_desk_note(",
            "async fn open_pane(",
            "async fn close_pane(",
            "async fn start_pane(",
            "async fn stop_pane(",
            "async fn paste_image(",
        ] {
            let from = src
                .find(handler)
                .unwrap_or_else(|| panic!("{handler} is a route in this file"));
            let body = &src[from..];
            let end = body.find("\n}\n").expect("a handler ends");
            let body = &body[..end];
            let gate = body
                .find("refuse_desk")
                .expect("a desk handler goes through the gate");
            let store = body.find("app.store").unwrap_or(usize::MAX);
            assert!(gate < store, "{handler} reaches the store before the gate");
        }
        // The folder dialog is a page reaching the filesystem, the same as a
        // desk: no dialog is shown to a page that has not passed the gate.
        let pick = &src[src.find("async fn browse_pick(").unwrap()..];
        assert!(
            pick.find("refuse_desk").unwrap() < pick.find("pick_folder").unwrap(),
            "browse_pick shows a dialog before the gate"
        );
        // And the routes themselves: every path a desk is reached by is one of
        // the handlers above.
        for route in [
            r#".route("/api/desks", get(desks).post(create_desk))"#,
            r#".route("/api/browse/pick", post(browse_pick))"#,
            r#".route("/api/desks/{id}/rename", post(rename_desk))"#,
            r#".route("/api/desks/{id}/layout", post(desk_layout))"#,
            r#".route("/api/desks/{id}/delete", post(delete_desk))"#,
            r#".route("/api/desks/{id}/panes", post(open_pane))"#,
            r#".route("/api/desks/{id}/docs", get(desk_docs))"#,
            r#".route("/api/desks/{id}/notes", get(desk_notes).post(add_desk_note))"#,
            r#".route("/api/desks/{id}/notes/{note}", post(set_desk_note))"#,
            r#".route("/api/desks/{id}/notes/{note}/remove", post(remove_desk_note))"#,
            r#".route("/api/desks/{id}/notes/{note}/restore", post(restore_desk_note))"#,
            r#".route("/api/panes/{id}/delete", post(close_pane))"#,
            r#".route("/api/panes/{id}/start", post(start_pane))"#,
            r#".route("/api/panes/{id}/stop", post(stop_pane))"#,
            r#""/api/panes/{id}/paste""#,
            "post(paste_image)",
        ] {
            assert!(src.contains(route), "the route table should hold {route}");
        }
    }

    /// The capability is read off the fragment and presented in a frame. If it
    /// ever reaches a URL the page builds, it reaches the daemon's request path
    /// and whatever logs one -- so the page's own source is where that line is
    /// held.
    #[test]
    fn the_page_never_puts_the_capability_in_a_url() {
        assert!(
            APP_JS.contains("/api/desk"),
            "the desk socket should be opened from here"
        );
        for (name, src) in [("app.js", APP_JS), ("desk.js", DESK_JS)] {
            for bad in ["cap=${", "capability=${", "?cap=", "&cap=", "?capability="] {
                assert!(
                    !src.contains(bad),
                    "the capability is in a URL in {name}: {bad}"
                );
            }
        }
    }

    /// The desk view is the second chunk, and its bargain is the diagram
    /// driver's: one import, made when a desk is opened -- and only past the
    /// point where a tab has been given its sentence and sent away, so a page
    /// with no capability never fetches the code that paints a pane.
    #[test]
    fn the_page_asks_for_the_desk_view_only_in_a_window_opening_a_desk() {
        assert_eq!(APP_JS.matches("import(`/assets/desk.js").count(), 1);
        let import = APP_JS.find("import(`/assets/desk.js").unwrap();
        let sentence = APP_JS
            .find("This is a browser tab, so it has no capability")
            .expect("a tab is told why there is no desk");
        let refusal = APP_JS[..sentence]
            .rfind("if (!capability)")
            .expect("the sentence is what a page without the capability gets");
        assert!(refusal < import, "the import sits past the tab's refusal");
        assert!(sentence < import);
        for seam in [
            "export function open(",
            "export function update(",
            "export function close(",
        ] {
            assert!(DESK_JS.contains(seam), "desk.js should export `{seam}`");
        }
    }

    /// The game is the fourth chunk, and the smallest bargain of them: one
    /// import, in the rocket's click handler and nowhere else, so a page
    /// whose rocket is never pressed never fetches a game.
    #[test]
    fn the_page_asks_for_the_game_only_when_the_rocket_is_pressed() {
        assert_eq!(APP_JS.matches("import(`/assets/game.js").count(), 1);
        let import = APP_JS.find("import(`/assets/game.js").unwrap();
        let press = APP_JS
            .find(r##"$("#btn-game")"##)
            .expect("the rocket is the button the game is behind");
        assert!(press < import, "the import sits inside the rocket's press");
        for seam in [
            "export function open(",
            "export function close(",
            "export function isOpen(",
        ] {
            assert!(GAME_JS.contains(seam), "game.js should export `{seam}`");
        }
    }

    /// The fifth chunk, and the one the budget was over by: the about panel
    /// and the reset dialog. Two buttons, one import, and a page that opens
    /// neither never fetches either. `bench/bytes.mjs` is what noticed they
    /// were being carried by every first paint.
    #[test]
    fn the_page_asks_for_the_panels_only_when_one_is_opened() {
        assert_eq!(APP_JS.matches("import(`/assets/about.js").count(), 1);
        let import = APP_JS.find("import(`/assets/about.js").unwrap();
        for button in [r##"$("#btn-about")"##, r##"$("#btn-reset")"##] {
            let press = APP_JS
                .find(button)
                .unwrap_or_else(|| panic!("{button} is a button a panel is behind"));
            assert!(
                import < press,
                "the press reaches the import, not the other way"
            );
        }
        assert!(
            ABOUT_JS.contains("export function open("),
            "about.js should export `open`"
        );
        // The panels themselves must not have stayed behind in the page.
        for gone in ["/api/about", "#about-facts", "#reset-go"] {
            assert!(
                !APP_JS.contains(gone),
                "`{gone}` belongs to the chunk now, not to app.js"
            );
        }
    }

    /// The driver is a chunk, and the page's half of that bargain is that it
    /// asks for the chunk only when a document actually holds a diagram. An
    /// import that escaped that check would be eager again -- 11.6 KB gzipped
    /// back on every page load, for a feature most documents do not use, and
    /// nothing would say so but `bench/bytes.mjs` on the next push.
    #[test]
    fn the_page_asks_for_the_diagram_driver_only_when_a_document_holds_one() {
        assert_eq!(
            APP_JS.matches("import(`/assets/mmd.js").count(),
            1,
            "one import, so there is one place the laziness can be lost"
        );
        assert!(
            APP_JS.contains(r#"if (docEl.querySelector("pre.mermaid")) mmdLoad()"#),
            "the import should sit behind the check for a diagram in this document"
        );
        // The machinery itself must not have found its way back into the page.
        for gone in [
            "mermaid.run",
            "mermaidLib",
            "mmdRender",
            "mmdReserve",
            "mmdDrain",
            "mmdQueue",
        ] {
            assert!(!APP_JS.contains(gone), "`{gone}` is back in app.js");
        }
        // And the module is what holds it, behind the four names the page knows.
        for kept in [
            "export function prepare(",
            "export function retheme(",
            "export function escape(",
            "export function key(",
        ] {
            assert!(MMD_JS.contains(kept), "mmd.js should export `{kept}`");
        }
    }

    /// The dev loop's whole promise is that the file on disk is the one being
    /// served, and its whole safety is that a daemon without `SNYVI_UI_DIR`
    /// cannot be made to read one. Both halves, plus the fallback that keeps a
    /// page rendering while an editor has the file renamed out from under it.
    #[test]
    fn a_live_ui_serves_the_file_on_disk_and_a_shipped_one_cannot() {
        let dir = std::env::temp_dir().join(format!("snyvi-ui-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let css = dir.join("app.css");
        std::fs::write(&css, "body { --probe: 1 }").unwrap();

        let live = Ui {
            dir: Some(dir.clone()),
        };
        assert_eq!(live.text("app.css", APP_CSS), "body { --probe: 1 }");
        assert!(live.live());
        // A different file on disk is a different bundle, which is what makes
        // an open page reload without the daemon restarting.
        let before = live.version("shipped");
        std::fs::write(&css, "body { --probe: 2 }").unwrap();
        assert_ne!(live.version("shipped"), before);
        // Gone mid-edit: the compiled-in copy, not an empty stylesheet.
        std::fs::remove_file(&css).unwrap();
        assert_eq!(live.text("app.css", APP_CSS), APP_CSS);

        let shipped = Ui { dir: None };
        assert!(!shipped.live());
        assert_eq!(shipped.text("app.css", APP_CSS), APP_CSS);
        assert_eq!(shipped.version("shipped"), "shipped");
        std::fs::remove_dir_all(&dir).ok();
    }

    /// `$("#btn-wrap").addEventListener` on an element that is not in the page throws on
    /// boot and takes the whole UI with it, so every id the script uses without checking
    /// first must exist in the markup. A guarded `const x = $("#id"); if (x)` is fine.
    ///
    /// Every chunk and not only `app.js`: the panels, the find bar and the game
    /// were moved out of the first paint, and an id one of them reaches for is
    /// no longer caught at boot -- it throws when the chunk loads, which is
    /// later, and in front of someone.
    #[test]
    fn every_id_the_script_uses_unguarded_is_in_the_page() {
        let mut missing = Vec::new();
        for (file, src) in [
            ("app.js", APP_JS),
            ("desk.js", DESK_JS),
            ("frame.js", FRAME_JS),
            ("game.js", GAME_JS),
            ("about.js", ABOUT_JS),
            ("find.js", FIND_JS),
            ("menu.js", MENU_JS),
        ] {
            for (i, _) in src.match_indices("$(\"#") {
                let rest = &src[i + 4..];
                let end = rest.find('"').expect("unterminated selector");
                let id = &rest[..end];
                let used_at_once = rest[end..].starts_with("\").");
                if used_at_once && !INDEX_HTML.contains(&format!("id=\"{id}\"")) {
                    missing.push(format!("{file}: {id}"));
                }
            }
        }
        assert!(missing.is_empty(), "not in index.html: {missing:?}");
    }

    /// The page asks for every chunk as `/assets/x.js?v=`, and they are served
    /// immutable for a year -- so a chunk left out of the hash that makes `?v=`
    /// is a chunk a browser keeps across the change that was meant to replace
    /// it. `Ui::version` lists them for a live directory; this is the hash that
    /// ships, and `about.js` and `find.js` were once added to the first and not
    /// the second. Held together here so the next chunk cannot be half-added.
    #[test]
    fn the_hash_behind_the_version_covers_every_chunk_the_page_can_fetch() {
        let src = include_str!("server.rs");
        let from = src.find("let asset_v = {").expect("the startup hash");
        let to = from + src[from..].find("\n    };").expect("the end of it");
        let block = &src[from..to];
        for chunk in [
            "INDEX_HTML",
            "APP_CSS",
            "APP_JS",
            "DESK_JS",
            "FRAME_JS",
            "GAME_JS",
            "ABOUT_JS",
            "FIND_JS",
            "MENU_JS",
        ] {
            assert!(
                block.contains(chunk),
                "{chunk} is served immutable under ?v= but is not in the hash that makes it"
            );
        }
    }

    /// A name is drawn on one line in the tree, and it arrives from a field a paste can
    /// fill with anything.
    #[test]
    fn a_name_is_cleaned_before_it_is_stored() {
        use super::clean_name;
        assert_eq!(clean_name("  Auth work  ").unwrap(), "Auth work");
        assert_eq!(clean_name("Auth\n\twork").unwrap(), "Auth work");
        assert_eq!(clean_name("Auth   work").unwrap(), "Auth work");
        assert!(clean_name("").is_none());
        assert!(clean_name("   \n ").is_none(), "whitespace is not a name");
        // Counted in characters, so a multi-byte name is not cut mid-character.
        let long = "é".repeat(400);
        assert_eq!(clean_name(&long).unwrap().chars().count(), 120);
    }

    /// The pre-paint script and the app must agree on the keys, or a saved setting is
    /// written by one and never read by the other.
    #[test]
    fn settings_written_by_the_app_are_applied_before_first_paint() {
        for key in ["theme", "font", "side", "wide", "wrap"] {
            let k = format!("snyvi.{key}");
            assert!(APP_JS.contains(&k), "{k} is not used by app.js");
            assert!(BOOT_JS.contains(&k), "{k} is not applied by boot.js");
        }
    }
}