localharness 0.28.0

A Rust-native agent SDK with pluggable LLM backends (Gemini today). Streaming, custom tools, safety policies, background triggers — zero external binaries.
Documentation
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
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
//! Event delegation.
//!
//! HTMX-style — one click listener and one keydown listener at the
//! document level. UI elements declare intent through `data-action`
//! attributes; dispatch looks up the closest ancestor with one and
//! routes into a Rust handler. **No per-element closures.**
//!
//! Adding a new interaction is a 3-step process:
//! 1. Add `data-action="..."` to the relevant element in
//!    [`super::templates`].
//! 2. Add a variant to [`Action`] and parse it in [`Action::parse`].
//! 3. Handle the new variant in [`dispatch`].

use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use web_sys::{Document, Element, HtmlElement, KeyboardEvent, MouseEvent};

use crate::encoding::{
    bytes_to_hex_str, parse_address, parse_token_amount, short_addr, tx_short_hash,
};
use crate::filesystem::Filesystem;

use super::dom;
use super::templates;

/// Every user interaction maps to one of these. The closed enum makes
/// it obvious from one file what the app actually does. Variants with
/// payloads pull the value from the element's `data-arg` attribute.
#[derive(Debug, Clone)]
enum Action {
    Send,
    SyncDevices,
    ClearKey,
    OpfsRefresh,
    OpfsWipe,
    OpfsWipeConfirm,
    OpfsWipeCancel,
    OpfsDelete(String),
    OpfsCloseViewer,
    OpfsNav(String),
    OpfsOpen(String),
    OpfsEdit(String),
    OpfsSave(String),
    ApexClaim,
    ClaimHere,
    ClaimOnChain,
    ImportOwner,
    RevealSeed,
    HideSeed,
    ImportSeed,
    CreateIdentity,
    ShowImport,
    CancelImport,
    HeaderAdminToggle,
    HeaderAdminClose,
    ShowAdminTab(String),
    SyncKey,
    RestoreKey,
    RevealSecurity,
    HideSecurity,
    ResetArm,
    ResetConfirm,
    ResetCancel,
    PricingSave,
    ToggleFiles,
    ToggleFinancial,
    ToggleTerminal,
    ToggleView,
    ShowTab(String),
    FeedbackSubmit,
    PairStart,
    PairCancel,
    PairApprove,
    PairReject,
    PairJoin,
    /// Option A: desktop shows a QR carrying its seed (encrypted under a
    /// one-time code) so another device can adopt the same identity.
    AddDevice,
    /// Option A: phone submits the one-time code to decrypt + import the
    /// seed that rode in the URL fragment.
    AdoptDevice,
    /// Trap fix: explicit "create a genuinely new identity" confirmation
    /// from the no-wallet identity-choice interstitial, carrying the name
    /// the user was trying to claim.
    CreateNewClaim(String),
    AgentActToggle(String),
    AgentSendLh(String),
    SavePrompt,
    SaveToolAllowlist,
    ResetToolAllowlist,
    SaveApiKey,
    ToggleDisplay,
    StopTurn,
    /// Set this subdomain's public face: "directory", "app", or "html".
    /// "app"/"html" also publish the device's local app.rl/index.html.
    SetPublicFace(String),
    /// Choose how the agent reaches the model: "credits" or "byok".
    SetModelAccess(String),
    /// Choose which LLM the in-tab agent uses (a `gemini-*` or `claude-*`
    /// model id). Persisted to `.lh_model`; read by `chat::start_session`.
    SetModel(String),
    /// Download the in-browser local model (Gemma 3 270M weights + tokenizer)
    /// from the HF CDN into OPFS — the one-time opt-in for on-device inference.
    DownloadLocalModel,
    /// Open (or renew) the caller's on-chain credit session.
    OpenSession,
    /// Redeem a one-time code for `$LH` credits.
    RedeemCode,
    /// Redeem a one-time code from the inline no-funds banner above the prompt.
    RedeemBanner,
    /// Prepay `$LH` into the per-request credit meter.
    DepositCredits,
    /// Escrow the owner's `$LH` behind a fresh bearer code + surface the
    /// `?invite=` share link (InviteFacet `createInvite`).
    CreateInvite,
    /// Escrow `$LH` to run a target agent on a fixed interval with no tab
    /// open (ScheduleFacet `scheduleJob`).
    ScheduleJob,
    /// Cancel a scheduled job + refund its remaining budget (ScheduleFacet
    /// `cancelJob`); the `data-arg` is the job id.
    CancelJob(String),
    /// Save this agent's per-call x402 price (`.lh_x402_price`).
    SaveX402Price,
    /// Consolidate this identity's subdomains into its MAIN's TBA.
    Consolidate,
    /// Unlink a device (remove its signer + index entry) — the X opens a
    /// typed confirmation; UnlinkConfirm performs it; UnlinkCancel aborts.
    UnlinkDevice(String),
    UnlinkConfirm(String),
    UnlinkCancel,
}

impl Action {
    fn parse(name: &str, arg: Option<String>) -> Option<Action> {
        Some(match name {
            "send" => Action::Send,
            "clear-key" => Action::ClearKey,
            "opfs-refresh" => Action::OpfsRefresh,
            "opfs-wipe" => Action::OpfsWipe,
            "opfs-wipe-confirm" => Action::OpfsWipeConfirm,
            "opfs-wipe-cancel" => Action::OpfsWipeCancel,
            "opfs-delete" => Action::OpfsDelete(arg.unwrap_or_default()),
            "opfs-close-viewer" => Action::OpfsCloseViewer,
            "opfs-nav" => Action::OpfsNav(arg.unwrap_or_default()),
            "opfs-open" => Action::OpfsOpen(arg.unwrap_or_default()),
            "opfs-edit" => Action::OpfsEdit(arg.unwrap_or_default()),
            "opfs-save" => Action::OpfsSave(arg.unwrap_or_default()),
            "apex-claim" => Action::ApexClaim,
            "claim-here" => Action::ClaimHere,
            "claim-on-chain" => Action::ClaimOnChain,
            "import-owner" => Action::ImportOwner,
            "reveal-seed" => Action::RevealSeed,
            "hide-seed" => Action::HideSeed,
            "import-seed" => Action::ImportSeed,
            "create-identity" => Action::CreateIdentity,
            "show-import" => Action::ShowImport,
            "cancel-import" => Action::CancelImport,
            "header-admin-toggle" => Action::HeaderAdminToggle,
            "header-admin-close" => Action::HeaderAdminClose,
            "show-admin-tab" => Action::ShowAdminTab(arg.unwrap_or_default()),
            "sync-key" => Action::SyncKey,
            "restore-key" => Action::RestoreKey,
            "reveal-security" => Action::RevealSecurity,
            "hide-security" => Action::HideSecurity,
            "reset-arm" => Action::ResetArm,
            "reset-confirm" => Action::ResetConfirm,
            "reset-cancel" => Action::ResetCancel,
            "pricing-save" => Action::PricingSave,
            "toggle-files" => Action::ToggleFiles,
            "toggle-financial" => Action::ToggleFinancial,
            "toggle-terminal" => Action::ToggleTerminal,
            "toggle-view" => Action::ToggleView,
            "show-tab" => Action::ShowTab(arg.unwrap_or_default()),
            "feedback-submit" => Action::FeedbackSubmit,
            "pair-start" => Action::PairStart,
            "add-device" => Action::AddDevice,
            "sync-devices" => Action::SyncDevices,
            "adopt-device" => Action::AdoptDevice,
            "create-new-claim" => Action::CreateNewClaim(arg.unwrap_or_default()),
            "pair-cancel" => Action::PairCancel,
            "pair-approve" => Action::PairApprove,
            "pair-reject" => Action::PairReject,
            "pair-join" => Action::PairJoin,
            "agent-act-toggle" => Action::AgentActToggle(arg.unwrap_or_default()),
            "agent-send-lh" => Action::AgentSendLh(arg.unwrap_or_default()),
            "save-prompt" => Action::SavePrompt,
            "save-tool-allowlist" => Action::SaveToolAllowlist,
            "reset-tool-allowlist" => Action::ResetToolAllowlist,
            "save-api-key" => Action::SaveApiKey,
            "toggle-display" => Action::ToggleDisplay,
            "stop-turn" => Action::StopTurn,
            "set-public-face" => Action::SetPublicFace(arg.unwrap_or_default()),
            "set-model-access" => Action::SetModelAccess(arg.unwrap_or_default()),
            "set-model" => Action::SetModel(arg.unwrap_or_default()),
            "download-local-model" => Action::DownloadLocalModel,
            "open-session" => Action::OpenSession,
            "redeem-code" => Action::RedeemCode,
            "redeem-banner" => Action::RedeemBanner,
            "deposit-credits" => Action::DepositCredits,
            "create-invite" => Action::CreateInvite,
            "schedule-job" => Action::ScheduleJob,
            "cancel-job" => Action::CancelJob(arg.unwrap_or_default()),
            "save-x402-price" => Action::SaveX402Price,
            "consolidate" => Action::Consolidate,
            "unlink-device" => Action::UnlinkDevice(arg.unwrap_or_default()),
            "unlink-confirm" => Action::UnlinkConfirm(arg.unwrap_or_default()),
            "unlink-cancel" => Action::UnlinkCancel,
            _ => return None,
        })
    }
}

pub(crate) fn install_delegated_listeners(doc: &Document) -> Result<(), JsValue> {
    let click = Closure::<dyn FnMut(_)>::new(move |event: MouseEvent| {
        let Some(target) = event.target() else { return };
        let Ok(mut node) = target.dyn_into::<Element>() else { return };

        // Walk up from the event target looking for [data-action].
        // Take any [data-arg] from the SAME element so the two travel
        // as a single intent.
        let action = loop {
            if let Some(name) = node.get_attribute("data-action") {
                let arg = node.get_attribute("data-arg");
                break Action::parse(&name, arg);
            }
            match node.parent_element() {
                Some(parent) => node = parent,
                None => break None,
            }
        };

        if let Some(action) = action {
            event.prevent_default();
            dispatch(action);
        }
    });
    doc.add_event_listener_with_callback("click", click.as_ref().unchecked_ref())?;
    click.forget(); // listener lives for the lifetime of the document

    // Delegated input handler — routes per-element. The matrix is
    // small enough to dispatch by id; if it grows further, switch to
    // a `data-input` attribute pattern matching the click handler.
    let input_handler = Closure::<dyn FnMut(_)>::new(move |event: web_sys::Event| {
        let Some(target) = event.target() else { return };
        let Ok(el) = target.dyn_into::<Element>() else { return };
        match el.id().as_str() {
            "key" => on_key_input(),
            "apex-input" => on_apex_input(),
            _ => {}
        }
    });
    doc.add_event_listener_with_callback("input", input_handler.as_ref().unchecked_ref())?;
    input_handler.forget();

    // Delegated submit handler — apex / claim forms route through
    // this. preventDefault before dispatch so the browser doesn't try
    // to GET the page with form fields in the query string.
    let submit_handler = Closure::<dyn FnMut(_)>::new(move |event: web_sys::Event| {
        let Some(target) = event.target() else { return };
        let Ok(form) = target.dyn_into::<Element>() else { return };
        if let Some(name) = form.get_attribute("data-action") {
            if let Some(action) = Action::parse(&name, form.get_attribute("data-arg")) {
                event.prevent_default();
                dispatch(action);
            }
        }
    });
    doc.add_event_listener_with_callback("submit", submit_handler.as_ref().unchecked_ref())?;
    submit_handler.forget();

    // Enter inside the prompt textarea sends; Shift+Enter inserts a
    // newline (default browser behavior — we only intercept the bare
    // Enter case). Cmd/Ctrl+Enter still sends as a convention some
    // users have muscle-memory for.
    let keydown = Closure::<dyn FnMut(_)>::new(move |event: KeyboardEvent| {
        let key = event.key();
        if key != "Enter" && key != " " {
            return;
        }
        let Some(target) = event.target() else { return };
        let Ok(el) = target.dyn_into::<Element>() else { return };

        // a11y: Enter/Space activates a focused role="button" carrying a
        // data-action — the non-<button> clickables (OPFS file/dir rows,
        // breadcrumbs); real <button>s activate natively. Walk up for
        // data-action exactly like the click handler, then dispatch.
        if el.get_attribute("role").as_deref() == Some("button") {
            let mut node = el.clone();
            let action = loop {
                if let Some(name) = node.get_attribute("data-action") {
                    break Action::parse(&name, node.get_attribute("data-arg"));
                }
                match node.parent_element() {
                    Some(parent) => node = parent,
                    None => break None,
                }
            };
            if let Some(action) = action {
                event.prevent_default();
                dispatch(action);
                return;
            }
        }

        // Enter inside the prompt textarea sends; Shift+Enter inserts a
        // newline (default); Cmd/Ctrl+Enter still sends.
        if key != "Enter" || el.id() != "prompt" {
            return;
        }
        let mod_held = event.meta_key() || event.ctrl_key();
        let allow_newline = event.shift_key();
        if mod_held || !allow_newline {
            event.prevent_default();
            dispatch(Action::Send);
        }
    });
    doc.add_event_listener_with_callback("keydown", keydown.as_ref().unchecked_ref())?;
    keydown.forget();

    // Delegated pointer tracking for the DISPLAY canvas. The display
    // cartridge ABI is poll-model (Orbclient-style): the cartridge reads
    // pointer_x/pointer_y each frame, so we just keep the latest cursor
    // position fresh. No-op when the canvas isn't mounted.
    let mousemove = Closure::<dyn FnMut(_)>::new(move |event: MouseEvent| {
        if dom::by_id("display-canvas").is_some() {
            super::display::set_pointer(event.client_x() as f64, event.client_y() as f64);
        }
    });
    doc.add_event_listener_with_callback("mousemove", mousemove.as_ref().unchecked_ref())?;
    mousemove.forget();

    // Primary-button state for the display. Press counts only when it
    // starts on the canvas; release clears regardless of where it lands.
    let mousedown = Closure::<dyn FnMut(_)>::new(move |event: MouseEvent| {
        if let Some(target) = event.target() {
            if let Ok(el) = target.dyn_into::<Element>() {
                if el.id() == "display-canvas" {
                    super::display::set_pointer(event.client_x() as f64, event.client_y() as f64);
                    super::display::set_pointer_down(true);
                }
            }
        }
    });
    doc.add_event_listener_with_callback("mousedown", mousedown.as_ref().unchecked_ref())?;
    mousedown.forget();

    let mouseup = Closure::<dyn FnMut(_)>::new(move |_event: MouseEvent| {
        super::display::set_pointer_down(false);
    });
    doc.add_event_listener_with_callback("mouseup", mouseup.as_ref().unchecked_ref())?;
    mouseup.forget();

    // Touch input — map the first touch to the same display pointer state
    // as the mouse, so drag-based cartridges (drawing) work on phones.
    // The canvas sets `touch-action: none` in CSS, so these don't need
    // non-passive preventDefault to stop the page scrolling under a draw.
    let touchstart = Closure::<dyn FnMut(_)>::new(move |event: web_sys::TouchEvent| {
        if let Some(target) = event.target() {
            if let Ok(el) = target.dyn_into::<Element>() {
                if el.id() == "display-canvas" {
                    if let Some(t) = event.touches().get(0) {
                        super::display::set_pointer(t.client_x() as f64, t.client_y() as f64);
                        super::display::set_pointer_down(true);
                    }
                }
            }
        }
    });
    doc.add_event_listener_with_callback("touchstart", touchstart.as_ref().unchecked_ref())?;
    touchstart.forget();

    let touchmove = Closure::<dyn FnMut(_)>::new(move |event: web_sys::TouchEvent| {
        if dom::by_id("display-canvas").is_some() {
            if let Some(t) = event.touches().get(0) {
                super::display::set_pointer(t.client_x() as f64, t.client_y() as f64);
            }
        }
    });
    doc.add_event_listener_with_callback("touchmove", touchmove.as_ref().unchecked_ref())?;
    touchmove.forget();

    let touchend = Closure::<dyn FnMut(_)>::new(move |_event: web_sys::TouchEvent| {
        super::display::set_pointer_down(false);
    });
    doc.add_event_listener_with_callback("touchend", touchend.as_ref().unchecked_ref())?;
    touchend.forget();

    install_keyboard_viewport_fix();

    Ok(())
}

/// Mobile soft-keyboard fix (FB#9). When the on-screen keyboard opens,
/// `dvh`/`vh` do NOT shrink (they track browser chrome, not the IME), so
/// the full-height `#root` grows taller than the visible area and the
/// browser scrolls the sticky header off the top. We listen on
/// `window.visualViewport` (the only viewport that tracks the keyboard)
/// and, while it is occluded, set CSS custom properties so `html,body,
/// #root` size to the VISIBLE height (`--lh-vh`) and the app is nudged
/// back into view (`--lh-vv-top`). A thin platform binding — it only
/// writes CSS variables / a class on <html>, building no DOM (same
/// spirit as the dom.rs helpers). No-op on desktop and when no
/// `visualViewport` exists. Chrome/Android is already handled by the
/// `interactive-widget=resizes-content` viewport meta; this covers iOS.
fn install_keyboard_viewport_fix() {
    let Some(win) = web_sys::window() else { return };
    let Some(vv) = win.visual_viewport() else { return };

    let apply = move || {
        let Some(win) = web_sys::window() else { return };
        let Some(vv) = win.visual_viewport() else { return };
        let Some(doc) = win.document() else { return };
        let Some(root) = doc.document_element() else { return };
        let Ok(html) = root.dyn_into::<HtmlElement>() else { return };
        let style = html.style();

        // Layout-viewport height to compare against (window.innerHeight).
        let layout_h = win
            .inner_height()
            .ok()
            .and_then(|v| v.as_f64())
            .unwrap_or(0.0);
        let visible_h = vv.height();
        let offset_top = vv.offset_top();

        // Keyboard is "open" once it eats a meaningful slice of the
        // viewport. A small threshold avoids reacting to the URL-bar
        // collapse (already covered by dvh) or sub-pixel jitter.
        let occluded = layout_h - visible_h > 120.0;

        if occluded {
            let _ = style.set_property("--lh-vh", &format!("{visible_h}px"));
            let _ = style.set_property("--lh-vv-top", &format!("{offset_top}px"));
            let _ = html.class_list().add_1("lh-kb");
        } else {
            let _ = html.class_list().remove_1("lh-kb");
            let _ = style.remove_property("--lh-vh");
            let _ = style.remove_property("--lh-vv-top");
        }
    };

    // Run once now (in case the page loads with the keyboard already up)
    // and on every visualViewport resize/scroll.
    apply();
    let cb = Closure::<dyn FnMut()>::new(apply);
    let _ = vv.add_event_listener_with_callback("resize", cb.as_ref().unchecked_ref());
    let _ = vv.add_event_listener_with_callback("scroll", cb.as_ref().unchecked_ref());
    cb.forget(); // lives for the document lifetime, like the other listeners
}

/// Persist the Gemini key from the input field to sessionStorage +
/// OPFS, and refresh the "(N chars)" hint.
fn on_key_input() {
    if let Some(input) = dom::input_by_id("key") {
        let value = input.value();
        if let Ok(Some(storage)) = dom::session_storage() {
            let _ = storage.set_item("gemini_api_key", &value);
        }
        refresh_keymeta();
        wasm_bindgen_futures::spawn_local(async move {
            super::key_store::save(&value).await;
        });
    }
}

/// States for the submit button. `Disabled` = grey, not clickable
/// (length out of range, registry check pending, name taken).
/// `Ready` = accent-green, clickable. `Failed` = red, disabled,
/// label swapped to "✗ failed" so a chain-reverted claim doesn't
/// silently look like nothing happened. The next keystroke into the
/// input clears the failed state via `on_apex_input`.
enum CreateBtnState {
    Disabled,
    Ready,
    Failed,
}

fn set_create_button_state(state: CreateBtnState) {
    match state {
        CreateBtnState::Disabled => set_create_button_classes(false, false, "create"),
        CreateBtnState::Ready => set_create_button_classes(true, false, "create"),
        CreateBtnState::Failed => set_create_button_classes(false, true, "✗ failed"),
    }
}

/// Set the create button to the failed state with a custom label
/// (e.g., "need 30 more LH"). Same red styling + disabled attribute
/// as `CreateBtnState::Failed`, but a more specific message.
/// Cleared on the next keystroke by `on_apex_input`.
fn set_create_button_failed_with(label: &str) {
    set_create_button_classes(false, true, label);
}

fn set_create_button_classes(enabled: bool, failed: bool, label: &str) {
    let Some(btn) = dom::by_id("create-btn") else { return };
    let stripped: String = btn
        .class_name()
        .split_whitespace()
        .filter(|c| *c != "ready" && *c != "failed")
        .collect::<Vec<_>>()
        .join(" ");
    if enabled {
        let _ = btn.remove_attribute("disabled");
    } else {
        let _ = btn.set_attribute("disabled", "");
    }
    let class = if enabled {
        format!("{stripped} ready")
    } else if failed {
        format!("{stripped} failed")
    } else {
        stripped
    };
    btn.set_class_name(&class);
    btn.set_inner_html(label);
}

/// Live registry check as the user types a subdomain name. Sanitises
/// to the same charset the contract enforces. The ONLY visible output
/// is the submit button's state — disabled (default) or ready (the
/// accent-green CTA). No status text under the input, no error
/// messages. Per [[feedback-no-explanatory-validation]].
fn on_apex_input() {
    let Some(input) = dom::input_by_id("apex-input") else { return };
    let raw = input.value();
    let cleaned = super::tenant::sanitize(&raw);
    if cleaned != raw {
        // Reflect the canonical form so the user sees the live filter.
        input.set_value(&cleaned);
    }

    // Length check first — short-circuit before hitting the registry
    // for input we already know won't pass on-chain validation.
    if cleaned.len() < 3 || cleaned.len() > 32 {
        set_create_button_state(CreateBtnState::Disabled);
        return;
    }

    // Disable while the registry roundtrip is in flight, then enable
    // (with the .ready style) only on Status::Available.
    set_create_button_state(CreateBtnState::Disabled);
    let pending = cleaned.clone();
    wasm_bindgen_futures::spawn_local(async move {
        let result = super::registry::check_name(&pending).await;
        // Only act on the result if the input still matches what we
        // queried — otherwise the user typed more chars and a fresh
        // check is already in flight.
        let still_pending = dom::input_by_id("apex-input")
            .map(|i| super::tenant::sanitize(&i.value()) == pending)
            .unwrap_or(false);
        if !still_pending {
            return;
        }
        match result {
            Ok(super::registry::Status::Available) => {
                set_create_button_state(CreateBtnState::Ready);
            }
            _ => {
                // Taken, registry-not-deployed, or RPC error all map to
                // "not currently claimable" — no text, just keep
                // the button disabled.
                set_create_button_state(CreateBtnState::Disabled);
            }
        }
    });
}

/// Full apex claim flow: faucet → registration tx → confirm → redirect.
/// Silent except for the button itself — disabled with text "creating…"
/// while in flight, redirects on success, reverts to the input-driven
/// state on failure. All status/error chatter goes to `console.warn`
/// for debuggability. Per [[feedback-no-explanatory-validation]].
async fn run_apex_claim(name: String, create_if_missing: bool) {
    set_create_button_busy(true);

    // Trap fix: a device with NO wallet that claims a name used to silently
    // mint a brand-new seed (see the `None` branch below) — which is how a
    // returning user on a second device ended up owning a *different* EOA's
    // subdomains, splitting their identity. Now we refuse to mint silently:
    // if there's no wallet and the user hasn't explicitly chosen "create a
    // new identity", show the choice (create new / adopt existing) instead.
    let has_wallet = super::APP.with(|cell| cell.borrow().wallet.is_some());
    if !has_wallet && !create_if_missing {
        set_create_button_busy(false);
        dom::swap_outer("agents-list", &templates::identity_choice(&name).into_string());
        return;
    }

    let result: Result<String, String> = async {
        // 1. Re-confirm availability — the user might have been
        //    overtaken between live-check and submit.
        match super::registry::check_name(&name).await {
            Ok(super::registry::Status::Available) => {}
            Ok(other) => return Err(format!("name not available: {other:?}")),
            Err(err) => return Err(format!("check_name: {err}")),
        }

        // 2. Pull the wallet out of App state — or generate one in
        //    place. The subdomain IS the identity primitive: a visitor
        //    arriving at apex without a wallet is just one who hasn't
        //    claimed yet. Roll wallet creation into this submit so we
        //    never end up with a wallet that doesn't own anything
        //    on-chain.
        let cached = super::APP.with(|cell| {
            cell.borrow()
                .wallet
                .as_ref()
                .map(|w| (w.signer.clone(), wallet_address_hex(&w.address)))
        });
        let (signer, addr_hex) = match cached {
            Some(pair) => pair,
            None => match super::wallet_store::create_and_persist().await {
                Ok(wallet) => {
                    let pair = (wallet.signer.clone(), wallet.address_hex());
                    super::APP.with(|cell| cell.borrow_mut().wallet = Some(wallet));
                    pair
                }
                Err(err) => return Err(format!("wallet: {err}")),
            },
        };

        // 2.5. Cost-gate pre-check. Registration is currently free
        //      (on-chain `registrationCost` is 0), so this is a no-op
        //      today. It stays as a guard in case the cost gate is ever
        //      re-enabled: if the registry charges LH and the user can't
        //      cover it, bail before burning sponsor gas on a guaranteed
        //      revert.
        let cost = super::registry::registration_cost().await.unwrap_or(0);
        if cost > 0 {
            let bal = super::registry::token_balance_of(&addr_hex).await.unwrap_or(0);
            if bal < cost {
                let deficit_lh = (cost - bal) / 1_000_000_000_000_000_000u128;
                return Err(format!("__NEED_LH__{deficit_lh}"));
            }
        }

        // 3. Submit the claim as a sponsored Tempo tx. The bundle's
        //    sponsor wallet pays the fees in AlphaUSD; the user's
        //    fresh apex wallet signs as sender and never needs any
        //    native gas or any TIP-20 stablecoin. No faucet step.
        let fee_payer = super::sponsor::signer()
            .map_err(|e| format!("sponsor key: {e}"))?;
        super::registry::claim_and_maybe_set_main_sponsored(
            &signer,
            &fee_payer,
            &name,
            super::registry::ALPHA_USD_ADDRESS,
        )
        .await
        .map_err(|e| format!("claim_name: {e}"))
    }
    .await;

    match result {
        Ok(tx_hash) => {
            web_sys::console::log_1(&JsValue::from_str(&format!(
                "claimed {name} (tx {})",
                short_hash(&tx_hash)
            )));
            let target = format!("https://{name}.localharness.xyz/?claim=1");
            if let Ok(window) = dom::window() {
                let _ = window.location().assign(&target);
            }
        }
        Err(err) => {
            web_sys::console::warn_1(&JsValue::from_str(&format!("apex claim failed: {err}")));
            // Surface failure on the button itself so the user knows
            // the click had an effect — a silent reset to disabled
            // looks indistinguishable from "nothing happened" and
            // invites frustrated re-clicking. `on_apex_input` clears
            // the failed state on the next keystroke.
            //
            // Specific case: insufficient credits. Pre-check encodes
            // the deficit in the error string with a sentinel prefix
            // so we can show "need N more LH" instead of a generic
            // "✗ failed".
            if let Some(rest) = err.strip_prefix("__NEED_LH__") {
                set_create_button_failed_with(&format!("need {rest} more LH"));
            } else {
                set_create_button_state(CreateBtnState::Failed);
            }
        }
    }
}

/// Swap the create button between its idle state (whatever `.ready` /
/// `disabled` it had) and the in-flight "creating…" state. The
/// in-flight state is always disabled + label-swapped so the user
/// can't double-submit and can see something is happening without a
/// separate status string.
fn set_create_button_busy(busy: bool) {
    let Some(btn) = dom::by_id("create-btn") else { return };
    if busy {
        btn.set_inner_html("creating…");
        let _ = btn.set_attribute("disabled", "");
    } else {
        btn.set_inner_html("create");
    }
}

fn wallet_address_hex(addr: &[u8; 20]) -> String {
    let mut s = String::with_capacity(42);
    s.push_str("0x");
    for b in addr {
        s.push_str(&format!("{b:02x}"));
    }
    s
}

fn short_hash(tx_hash: &str) -> String {
    let stripped = tx_hash.trim_start_matches("0x");
    if stripped.len() < 12 {
        return tx_hash.to_string();
    }
    format!("{}{}", &stripped[..6], &stripped[stripped.len() - 4..])
}

/// Recompute the "(N chars)" hint next to the key input. Called from
/// both the input listener and the mount restore path, so it lives
/// here.
pub(crate) fn refresh_keymeta() {
    if let Some(input) = dom::input_by_id("key") {
        let html = templates::keymeta(&input.value()).into_string();
        dom::swap_inner("keymeta", &html);
    }
}

fn dispatch(action: Action) {
    match action {
        Action::Send => {
            // Chat is async; defer to a spawn_local future so the
            // click handler returns immediately.
            wasm_bindgen_futures::spawn_local(async move {
                super::chat::run_send().await;
            });
        }
        Action::ClearKey => clear_key_pressed(),
        Action::OpfsRefresh => {
            wasm_bindgen_futures::spawn_local(async move {
                super::opfs::refresh().await;
            });
        }
        Action::OpfsCloseViewer => super::opfs::close_viewer(),
        Action::ToggleDisplay => super::opfs::toggle_display(),
        Action::StopTurn => super::chat::request_stop_turn(),
        Action::SetPublicFace(choice) => {
            wasm_bindgen_futures::spawn_local(async move {
                run_set_public_face(&choice).await;
            });
        }
        Action::OpfsNav(target) => {
            wasm_bindgen_futures::spawn_local(async move {
                super::opfs::navigate(&target).await;
            });
        }
        Action::OpfsOpen(name) => {
            wasm_bindgen_futures::spawn_local(async move {
                super::opfs::open_file(&name).await;
            });
        }
        Action::OpfsEdit(name) => {
            wasm_bindgen_futures::spawn_local(async move {
                super::opfs::edit_file(&name).await;
            });
        }
        Action::OpfsSave(name) => {
            wasm_bindgen_futures::spawn_local(async move {
                super::opfs::save_file(&name).await;
            });
        }
        Action::ApexClaim => {
            // Silent no-op on invalid input — the create button is
            // disabled by `on_apex_input` when length is out of range,
            // so this branch only ever fires for valid names. Per
            // [[feedback-no-explanatory-validation]].
            let raw = dom::input_by_id("apex-input")
                .map(|i| i.value())
                .unwrap_or_default();
            let cleaned = super::tenant::sanitize(&raw);
            if cleaned.len() < 3 || cleaned.len() > 32 {
                return;
            }
            wasm_bindgen_futures::spawn_local(async move {
                run_apex_claim(cleaned, false).await;
            });
        }
        Action::CreateNewClaim(name) => {
            let cleaned = super::tenant::sanitize(&name);
            if cleaned.len() < 3 || cleaned.len() > 32 {
                return;
            }
            wasm_bindgen_futures::spawn_local(async move {
                run_apex_claim(cleaned, true).await;
            });
        }
        Action::ClaimHere => {
            wasm_bindgen_futures::spawn_local(async move {
                let super::tenant::Host::Tenant(name) = super::tenant::current() else {
                    return;
                };
                // The hint is the on-chain owner address this device
                // controls. Resolve it from the chain (authoritative) and
                // remember it so the next load paints the studio first.
                let addr = super::registry::owner_of_name(&name)
                    .await
                    .ok()
                    .flatten();
                match addr {
                    Some(addr) => {
                        let _ = super::owner::remember(&addr).await;
                        super::paint_tenant(
                            super::tenant::Host::Tenant(name.clone()),
                            name,
                        )
                        .await;
                    }
                    None => {
                        dom::swap_inner(
                            "claim-msg",
                            &dom::msg_span(dom::Msg::Error, "claim failed: name has no on-chain owner"),
                        );
                    }
                }
            });
        }
        Action::ClaimOnChain => {
            // Tenant-side first-claim: ensure apex wallet exists (without
            // overwriting an existing one — that would nuke other NFTs),
            // run the on-chain register tx via the signer iframe, then
            // set the local OPFS marker + re-paint as owner. This kills
            // the previous "bounce to apex first" interstitial.
            let Some(name) = (match super::tenant::current() {
                super::tenant::Host::Tenant(n) => Some(n),
                _ => None,
            }) else {
                return;
            };
            dom::swap_inner(
                "claim-msg",
                "<span style=\"color:var(--muted)\">ensuring identity at apex…</span>",
            );
            wasm_bindgen_futures::spawn_local(async move {
                if let Err(err) = super::verify::create_wallet_via_iframe(false).await {
                    dom::swap_inner(
                        "claim-msg",
                        &dom::msg_span(dom::Msg::Error, &format!("identity setup failed: {err}")),
                    );
                    return;
                }
                dom::swap_inner(
                    "claim-msg",
                    "<span style=\"color:var(--muted)\">claiming on-chain…</span>",
                );
                match super::verify::claim_name_via_iframe(&name).await {
                    Ok((owner_addr, _tx)) => {
                        // Remember the just-registered owner address as the
                        // local first-paint hint (the chain stays authority).
                        let _ = super::owner::remember(&owner_addr).await;
                        super::paint_tenant(
                            super::tenant::Host::Tenant(name.clone()),
                            name,
                        )
                        .await;
                    }
                    Err(err) => {
                        dom::swap_inner(
                            "claim-msg",
                            &dom::msg_span(dom::Msg::Error, &format!("claim failed: {err}")),
                        );
                    }
                }
            });
        }
        Action::ImportOwner => {
            let raw = dom::input_by_id("import-uuid")
                .map(|i| i.value().trim().to_string())
                .unwrap_or_default();
            if raw.len() < 32 {
                dom::swap_inner(
                    "claim-msg",
                    "<span style=\"color:var(--error)\">paste a full UUID (36 chars with dashes)</span>",
                );
                return;
            }
            wasm_bindgen_futures::spawn_local(async move {
                let fs = super::shared_opfs();
                if let Err(err) = fs.write_atomic(".lh_owner", raw.as_bytes()).await {
                    dom::swap_inner(
                        "claim-msg",
                        &dom::msg_span(dom::Msg::Error, &format!("import failed: {err}")),
                    );
                    return;
                }
                if let super::tenant::Host::Tenant(name) = super::tenant::current() {
                    super::paint_tenant(super::tenant::Host::Tenant(name.clone()), name).await;
                }
            });
        }
        Action::RevealSeed => {
            // Apex: read mnemonic directly from cached wallet (sync).
            // Tenant: round-trip through the apex signer iframe so the
            // seed never leaves apex OPFS unannounced.
            match super::tenant::current() {
                super::tenant::Host::Apex => {
                    let phrase = super::APP.with(|cell| {
                        cell.borrow()
                            .wallet
                            .as_ref()
                            .map(|w| w.mnemonic.to_string())
                    });
                    if let Some(p) = phrase {
                        dom::swap_inner(
                            "seed-reveal",
                            &super::templates::seed_phrase(&p).into_string(),
                        );
                    }
                }
                _ => {
                    dom::swap_inner(
                        "seed-reveal",
                        "<span style=\"color:var(--muted)\">fetching…</span>",
                    );
                    wasm_bindgen_futures::spawn_local(async move {
                        match super::verify::reveal_seed_via_iframe().await {
                            Ok(phrase) => dom::swap_inner(
                                "seed-reveal",
                                &super::templates::seed_phrase(&phrase).into_string(),
                            ),
                            Err(err) => dom::swap_inner(
                                "seed-reveal",
                                &maud::html! {
                                    span style="color:var(--error)" { "reveal failed: " (err) }
                                    button type="button" data-action="reveal-seed" class="ghost" { "retry" }
                                }
                                .into_string(),
                            ),
                        }
                    });
                }
            }
        }
        Action::HideSeed => {
            dom::swap_inner(
                "seed-reveal",
                r#"<button type="button" data-action="reveal-seed">I have a pen and paper — reveal</button>"#,
            );
        }
        Action::CreateIdentity => {
            // Apex: generate locally + bootstrap-fund + re-paint.
            // Tenant: route through the apex signer iframe so the wallet
            // lands at apex OPFS, then re-paint tenant chrome so
            // verification picks up the new owner.
            dom::swap_inner(
                "identity-msg",
                "<span style=\"color:var(--muted)\">generating identity…</span>",
            );
            match super::tenant::current() {
                super::tenant::Host::Apex => {
                    wasm_bindgen_futures::spawn_local(async move {
                        if let Err(err) = super::wallet_store::create_and_persist().await {
                            dom::swap_inner(
                                "identity-msg",
                                &dom::msg_span(dom::Msg::Error, &format!("create failed: {err}")),
                            );
                            return;
                        }
                        super::paint_apex(super::tenant::Host::Apex).await;
                    });
                }
                host => {
                    // Explicit "create" button from tenant admin: pass
                    // overwrite=true because the user has clicked the
                    // create action with intent (just like at apex).
                    wasm_bindgen_futures::spawn_local(async move {
                        match super::verify::create_wallet_via_iframe(true).await {
                            Ok(_addr) => {
                                if let super::tenant::Host::Tenant(name) = &host {
                                    super::paint_tenant(host.clone(), name.clone()).await;
                                }
                            }
                            Err(err) => {
                                dom::swap_inner(
                                    "identity-msg",
                                    &dom::msg_span(dom::Msg::Error, &format!("create failed: {err}")),
                                );
                            }
                        }
                    });
                }
            }
        }
        Action::ShowImport => {
            // Reveal the import textarea in place of the secondary
            // button — the ImportSeed action handler picks it up from
            // there.
            dom::swap_outer(
                "import-slot",
                &templates::import_seed_inline().into_string(),
            );
            if let Some(textarea) = dom::textarea_by_id("import-seed") {
                let _ = textarea.focus();
            }
        }
        Action::ImportSeed => {
            let phrase = dom::textarea_by_id("import-seed")
                .map(|t| t.value())
                .unwrap_or_default();
            if phrase.split_whitespace().count() != 12 {
                dom::swap_inner(
                    "seed-msg",
                    "<span style=\"color:var(--error)\">expected exactly 12 words</span>",
                );
                return;
            }
            // Apex: write directly to apex OPFS, re-paint apex.
            // Tenant: route through signer iframe so the seed lands at
            // apex OPFS even though we're on a subdomain origin. This is
            // how cross-device pairing works — paste your desktop seed on
            // mobile and the master identity now lives on both devices.
            match super::tenant::current() {
                super::tenant::Host::Apex => {
                    wasm_bindgen_futures::spawn_local(async move {
                        match super::wallet_store::import(&phrase).await {
                            Ok(_) => {
                                super::paint_apex(super::tenant::Host::Apex).await;
                            }
                            Err(err) => {
                                dom::swap_inner(
                                    "seed-msg",
                                    &dom::msg_span(dom::Msg::Error, &format!("import failed: {err}")),
                                );
                            }
                        }
                    });
                }
                host => {
                    wasm_bindgen_futures::spawn_local(async move {
                        match super::verify::import_seed_via_iframe(&phrase).await {
                            Ok(_addr) => {
                                if let super::tenant::Host::Tenant(name) = &host {
                                    super::paint_tenant(host.clone(), name.clone()).await;
                                }
                            }
                            Err(err) => {
                                dom::swap_inner(
                                    "seed-msg",
                                    &dom::msg_span(dom::Msg::Error, &format!("import failed: {err}")),
                                );
                            }
                        }
                    });
                }
            }
        }
        Action::OpfsDelete(name) => {
            // Direct delete — no per-row confirm. Mistakes can be
            // recovered by re-creating the file; the wipe button is
            // the heavyweight "everything" confirm flow.
            wasm_bindgen_futures::spawn_local(async move {
                let fs = super::shared_opfs();
                if let Err(err) = fs.delete(&name).await {
                    web_sys::console::warn_1(&JsValue::from_str(&format!(
                        "delete({name}): {err}"
                    )));
                }
                // Deleting the conversation history wipes the on-screen
                // transcript instantly — no page refresh. (on-chain feedback)
                if name == ".lh_history.json" {
                    dom::swap_inner("transcript", "");
                }
                super::opfs::refresh().await;
            });
        }
        Action::OpfsWipe => {
            // Arm the wipe — swap the button into an inline confirm
            // pair (yes / no). The actual wipe runs via OpfsWipeConfirm.
            dom::swap_outer(
                "opfs-wipe-slot",
                &templates::opfs_wipe_confirm_inline().into_string(),
            );
        }
        Action::OpfsWipeConfirm => {
            // Restore the slot first so the in-flight wipe doesn't
            // leave stale confirm buttons visible.
            dom::swap_outer(
                "opfs-wipe-slot",
                &templates::opfs_wipe_armed_inline().into_string(),
            );
            wasm_bindgen_futures::spawn_local(async move {
                super::opfs::wipe().await;
            });
        }
        Action::OpfsWipeCancel => {
            dom::swap_outer(
                "opfs-wipe-slot",
                &templates::opfs_wipe_armed_inline().into_string(),
            );
        }
        Action::CancelImport => {
            dom::swap_outer("import-slot", r#"<div id="import-slot"></div>"#);
        }
        Action::HeaderAdminToggle => header_admin_toggle(),
        Action::HeaderAdminClose => header_admin_close(),
        Action::ShowAdminTab(name) => show_admin_tab(&name),
        Action::SyncKey => {
            wasm_bindgen_futures::spawn_local(async move { run_sync_key().await });
        }
        Action::RestoreKey => {
            wasm_bindgen_futures::spawn_local(async move { run_restore_key().await });
        }
        Action::RevealSecurity => {
            dom::swap_outer(
                "security-slot",
                &templates::admin_security_expanded().into_string(),
            );
        }
        Action::HideSecurity => {
            dom::swap_outer(
                "security-slot",
                &templates::admin_security_collapsed().into_string(),
            );
        }
        Action::ResetArm => {
            dom::swap_outer(
                "reset-confirm-slot",
                &templates::reset_confirm_inline().into_string(),
            );
        }
        Action::ResetCancel => {
            dom::swap_outer(
                "reset-confirm-slot",
                &templates::reset_armed_inline().into_string(),
            );
        }
        Action::ResetConfirm => reset_confirm_pressed(),
        Action::PricingSave => pricing_save_pressed(),
        Action::ToggleFiles => toggle_layout_class("files-collapsed"),
        Action::ToggleFinancial => toggle_layout_class("financial-collapsed"),
        Action::ToggleTerminal => toggle_layout_class("terminal-collapsed"),
        Action::ToggleView => toggle_layout_class("view-collapsed"),
        Action::ShowTab(name) => show_mobile_tab(&name),
        Action::FeedbackSubmit => super::feedback::feedback_submit(),
        Action::PairStart => pair_start_pressed(),
        Action::AddDevice => add_device_pressed(),
        Action::SyncDevices => run_sync_devices(),
        Action::AdoptDevice => adopt_device_pressed(),
        Action::PairCancel => pair_cancel_pressed(),
        Action::PairApprove => pair_approve_pressed(),
        Action::PairReject => pair_reject_pressed(),
        Action::PairJoin => {
            if let Some(code) = super::read_query_param("pair") {
                pair_join_pressed(code);
            }
        }
        Action::AgentActToggle(token_id) => agent_act_toggle_pressed(token_id),
        Action::AgentSendLh(token_id) => agent_send_lh_pressed(token_id),
        Action::SavePrompt => save_prompt_pressed(),
        Action::SaveToolAllowlist => save_tool_allowlist_pressed(),
        Action::ResetToolAllowlist => reset_tool_allowlist_pressed(),
        Action::SaveApiKey => save_api_key_pressed(),
        Action::SetModelAccess(mode) => run_set_model_access(mode),
        Action::SetModel(model) => run_set_model(model),
        Action::DownloadLocalModel => run_download_local_model(),
        Action::OpenSession => open_session_pressed(),
        Action::RedeemCode => redeem_code_pressed(),
        Action::RedeemBanner => redeem_banner_pressed(),
        Action::DepositCredits => deposit_credits_pressed(),
        Action::CreateInvite => create_invite_pressed(),
        Action::ScheduleJob => schedule_job_pressed(),
        Action::CancelJob(id) => cancel_job_pressed(id),
        Action::SaveX402Price => save_x402_price_pressed(),
        Action::Consolidate => consolidate_pressed(),
        Action::UnlinkDevice(addr) => unlink_device_prompt(addr),
        Action::UnlinkConfirm(addr) => unlink_confirm_pressed(addr),
        Action::UnlinkCancel => unlink_cancel_pressed(),
    }
}

/// Persist the textarea content as the per-origin custom system
/// prompt. Empty/whitespace-only content deletes the file, reverting
/// to the bundle's default. The change takes effect on the next
/// session start — surfaced inline so the user knows what to expect.
fn save_prompt_pressed() {
    let Some(textarea) = dom::textarea_by_id("prompt-input") else { return };
    let content = textarea.value();
    dom::swap_inner(
        "prompt-msg",
        "<span style=\"color:var(--muted)\">saving…</span>",
    );
    wasm_bindgen_futures::spawn_local(async move {
        match super::system_prompt::save(&content).await {
            Ok(()) => {
                let trimmed = content.trim();
                let summary = if trimmed.is_empty() {
                    "✓ saved · using default on next session"
                } else {
                    "✓ saved · takes effect on next session"
                };
                dom::swap_inner(
                    "prompt-msg",
                    &dom::msg_span(dom::Msg::Accent, &format!("{summary}")),
                );
            }
            Err(err) => {
                dom::swap_inner(
                    "prompt-msg",
                    &dom::msg_span(dom::Msg::Error, &format!("{err}")),
                );
            }
        }
    });
}

fn save_tool_allowlist_pressed() {
    use crate::types::BuiltinTool;
    let mut enabled = Vec::new();
    if let Some(doc) = web_sys::window().and_then(|w| w.document()) {
        if let Ok(checkboxes) = doc.query_selector_all(".tool-checkbox") {
            for i in 0..checkboxes.length() {
                if let Some(el) = checkboxes.get(i) {
                    let input: web_sys::HtmlInputElement = JsCast::unchecked_into(el);
                    if input.checked() {
                        if let Some(name) = input.get_attribute("data-tool") {
                            if let Some(tool) = BuiltinTool::ALL.iter().find(|t| t.wire_name() == name) {
                                enabled.push(*tool);
                            }
                        }
                    }
                }
            }
        }
    }
    dom::swap_inner(
        "tool-allowlist-msg",
        "<span style=\"color:var(--muted)\">saving…</span>",
    );
    wasm_bindgen_futures::spawn_local(async move {
        match super::tool_allowlist::save(&enabled).await {
            Ok(()) => {
                let summary = super::tool_allowlist::summary(&enabled);
                dom::swap_inner(
                    "tool-allowlist-msg",
                    &dom::msg_span(dom::Msg::Accent, &format!("✓ saved · {summary} · takes effect on next session")),
                );
            }
            Err(err) => {
                dom::swap_inner(
                    "tool-allowlist-msg",
                    &dom::msg_span(dom::Msg::Error, &format!("{err}")),
                );
            }
        }
    });
}

fn reset_tool_allowlist_pressed() {
    dom::swap_inner(
        "tool-allowlist-msg",
        "<span style=\"color:var(--muted)\">resetting…</span>",
    );
    if let Some(doc) = web_sys::window().and_then(|w| w.document()) {
        if let Ok(checkboxes) = doc.query_selector_all(".tool-checkbox") {
            for i in 0..checkboxes.length() {
                if let Some(el) = checkboxes.get(i) {
                    let input: web_sys::HtmlInputElement = JsCast::unchecked_into(el);
                    input.set_checked(true);
                }
            }
        }
    }
    wasm_bindgen_futures::spawn_local(async move {
        match super::tool_allowlist::save(&[]).await {
            Ok(()) => {
                dom::swap_inner(
                    "tool-allowlist-msg",
                    "<span style=\"color:var(--accent)\">✓ reset · all tools enabled · takes effect on next session</span>",
                );
            }
            Err(err) => {
                dom::swap_inner(
                    "tool-allowlist-msg",
                    &dom::msg_span(dom::Msg::Error, &format!("{err}")),
                );
            }
        }
    });
}

/// Save the API key from the centered modal, then dismiss the modal.
fn save_api_key_pressed() {
    let Some(input) = dom::input_by_id("api-key-input") else { return };
    let value = input.value().trim().to_string();
    if value.is_empty() {
        return;
    }
    if let Ok(Some(storage)) = dom::session_storage() {
        let _ = storage.set_item("gemini_api_key", &value);
    }
    dom::swap_inner(
        "api-key-msg",
        "<span style=\"color:var(--muted)\">checking…</span>",
    );
    wasm_bindgen_futures::spawn_local(async move {
        super::key_store::save(&value).await;
        super::opfs::refresh().await;
        // Validate against Gemini so a bad key is caught here, not
        // mid-turn. A definitive rejection keeps the modal open; a valid
        // key OR an inconclusive check (network/CORS) closes it — we
        // never block the user on a flaky probe.
        if let Some(false) = gemini_key_is_valid(&value).await {
            dom::swap_inner(
                "api-key-msg",
                "<span style=\"color:var(--error)\">key rejected — check it</span>",
            );
            return;
        }
        if let Some(el) = dom::by_id("api-key-modal") {
            if let Some(parent) = el.parent_element() {
                let _ = parent.remove_child(&el);
            }
        }
        // Auto-sync to the MAIN slot on-chain (best-effort, seed-bearing
        // devices only) so other subdomains + linked devices pick it up
        // without re-entry. Fire-and-forget after the modal closes.
        if let super::tenant::Host::Tenant(name) = super::tenant::current() {
            auto_sync_gemini_key(name, value).await;
        }
    });
}

/// Probe whether a Gemini API key works via a cheap `models.list` GET
/// (no token cost). `Some(true/false)` is definitive; `None` means the
/// check was inconclusive (network/CORS) and the caller should not block
/// on it. Browser→Gemini CORS is already proven by the chat path.
async fn gemini_key_is_valid(key: &str) -> Option<bool> {
    let url = format!("https://generativelanguage.googleapis.com/v1beta/models?key={key}");
    match reqwest::Client::new().get(&url).send().await {
        Ok(resp) => Some(resp.status().is_success()),
        Err(_) => None,
    }
}

/// Expand or collapse the inline act-panel under an agent row.
/// First open fetches TBA balance + paints the panel; subsequent
/// toggles just flip the `hidden` attribute on the existing DOM.
fn agent_act_toggle_pressed(token_id_str: String) {
    let Ok(token_id) = token_id_str.parse::<u64>() else { return };
    let panel_id = format!("agent-act-{token_id}");
    let Some(panel) = dom::by_id(&panel_id) else { return };
    let was_hidden = panel.has_attribute("hidden");
    if was_hidden {
        // First-paint flow: fetch TBA + balance, render the form.
        panel.set_inner_html(
            "<div class=\"admin-msg-slot\"><span style=\"color:var(--muted)\">loading…</span></div>",
        );
        let _ = panel.remove_attribute("hidden");
        wasm_bindgen_futures::spawn_local(async move {
            if let Err(err) = paint_agent_act_panel(token_id).await {
                let panel_id = format!("agent-act-{token_id}");
                dom::swap_inner(
                    &panel_id,
                    &maud::html! {
                        div class="admin-msg-slot" {
                            span style="color:var(--error)" { (err) }
                        }
                    }
                    .into_string(),
                );
            }
        });
    } else {
        let _ = panel.set_attribute("hidden", "");
    }
}

async fn paint_agent_act_panel(token_id: u64) -> Result<(), String> {
    let tba = super::registry::tba_of_token_id(token_id)
        .await
        .map_err(|e| format!("tba: {e}"))?
        .ok_or_else(|| "no TBA".to_string())?;
    let balance = super::registry::token_balance_of(&tba).await.unwrap_or(0);
    let html = templates::agent_act_panel(token_id, &tba, balance).into_string();
    let panel_id = format!("agent-act-{token_id}");
    dom::swap_inner(&panel_id, &html);
    Ok(())
}

/// User clicked "send" in an inline act-panel. Reads the recipient
/// and amount inputs scoped to this token_id, fires a sponsored
/// `tba.execute(credits, 0, transfer(...), 0)` tempo tx. The user's
/// apex wallet signs as one of the TBA's authorized signers (it IS
/// the NFT owner). Sponsor pays AlphaUSD.
fn agent_send_lh_pressed(token_id_str: String) {
    let Ok(token_id) = token_id_str.parse::<u64>() else { return };
    let msg_id = format!("agent-act-msg-{token_id}");

    let to_raw = dom::input_by_id(&format!("agent-send-to-{token_id}"))
        .map(|i| i.value().trim().to_string())
        .unwrap_or_default();
    let amt_raw = dom::input_by_id(&format!("agent-send-amt-{token_id}"))
        .map(|i| i.value().trim().to_string())
        .unwrap_or_default();
    // Route the recipient through the SAME hardened choke point as send_lh /
    // the per-turn payment (`classify_recipient`), which refuses the zero
    // address (a transfer there burns the TBA's $LH irrecoverably). The act
    // panel only accepts a raw address, so anything that classifies as a Name
    // (wrong length, non-hex) is a silent no-op too — per
    // [[feedback-no-explanatory-validation]].
    let Ok(crate::encoding::Recipient::Address(to_raw)) =
        crate::encoding::classify_recipient(&to_raw)
    else {
        return; // empty, zero-address, or not a 40-hex address → silent no-op
    };
    let Some(amount_wei) = parse_token_amount(&amt_raw) else { return };
    if amount_wei == 0 {
        return;
    }

    let signer = super::APP.with(|cell| {
        cell.borrow().wallet.as_ref().map(|w| w.signer.clone())
    });
    let Some(signer) = signer else { return };

    dom::swap_inner(
        &msg_id,
        "<span style=\"color:var(--muted)\">signing + submitting…</span>",
    );

    wasm_bindgen_futures::spawn_local(async move {
        let msg_id = format!("agent-act-msg-{token_id}");
        let result = async {
            let tba = super::registry::tba_of_token_id(token_id)
                .await
                .map_err(|e| format!("tba: {e}"))?
                .ok_or_else(|| "no TBA".to_string())?;
            let fee_payer = super::sponsor::signer()?;
            super::registry::tba_transfer_lh_sponsored(
                &signer,
                &fee_payer,
                token_id,
                &tba,
                &to_raw,
                amount_wei,
                super::registry::ALPHA_USD_ADDRESS,
            )
            .await
        }
        .await;
        match result {
            Ok(tx_hash) => {
                let short = tx_short_hash(&tx_hash);
                dom::swap_inner(
                    &msg_id,
                    &dom::msg_span(dom::Msg::Accent, &format!("✓ sent (tx {short})")),
                );
                // Re-paint to refresh the balance line.
                let _ = paint_agent_act_panel(token_id).await;
            }
            Err(err) => {
                dom::swap_inner(
                    &msg_id,
                    &dom::msg_span(dom::Msg::Error, &format!("{err}")),
                );
            }
        }
    });
}

/// Fetch the credit balance for the apex wallet and write it into
/// `#credits-balance`. Called on admin-open. Soft-fail — leaves the
/// placeholder on error so the UI stays clean.
pub(crate) async fn refresh_credits_pill() {
    // Use the credit identity (master wallet, else local device key) so
    // the balance + session reflect what the proxy will actually see.
    let Some(addr) = super::chat::credit_address_existing().await else { return };
    // "Credits" = total spendable $LH = wallet balance + the per-request meter
    // (the wallet auto-deposits into the meter on the next turn; the proxy
    // debits the meter per call). 2-decimal so a per-call debit (0.01–0.20 LH)
    // is visibly subtracted; goes up on redeem. (The session-status + separate
    // meter line are gone — metering is the only billing surface now.)
    // Timeout-capped: the browser-fetch transport has no timeout, so a dead
    // RPC would leave the pill stuck on its `…` placeholder forever. On a
    // timeout (or read error) show a dash rather than spinning.
    let wallet = super::net::read(super::registry::token_balance_of(&addr))
        .await
        .ok()
        .and_then(Result::ok);
    let meter = super::net::read(super::registry::credit_balance_of(&addr))
        .await
        .ok()
        .and_then(Result::ok);
    match (wallet, meter) {
        (Some(wallet), Some(meter)) => {
            let total = wallet + meter;
            let whole = total / 1_000_000_000_000_000_000u128;
            let cents = (total % 1_000_000_000_000_000_000u128) / 10_000_000_000_000_000u128;
            dom::swap_inner("credits-balance", &format!("{whole}.{cents:02} LH"));
        }
        _ => dom::swap_inner("credits-balance", ""),
    }
    warn_if_sponsor_low().await;
}

/// Show or hide the inline no-funds funding banner (`#fund-banner` in the
/// terminal). Credit access is now GATED — a session costs `$LH` and the
/// daily allowance is disabled — so an identity with zero `$LH` (zero wallet
/// balance + zero meter) can't reach the model and would otherwise hit a
/// silent proxy rejection on first send. When that's the case, surface a
/// one-click redeem CTA right above the prompt; once funded, clear it.
///
/// No-ops gracefully: if the banner slot isn't in the DOM (apex, public
/// face) there's nothing to fill, and a missing identity (no wallet/device
/// key yet) leaves the banner empty rather than nagging a marketing visit.
/// BYOK users (own key) aren't gated on `$LH`, so the banner stays hidden
/// for them too.
pub(crate) async fn refresh_fund_banner() {
    // Only meaningful where the terminal chrome exists.
    if dom::by_id("fund-banner").is_none() {
        return;
    }
    // BYOK reaches the model without `$LH` — don't show a funding nag.
    let is_credits = local_storage()
        .and_then(|s| s.get_item("lh_model_access").ok().flatten())
        .map(|m| m != "byok")
        .unwrap_or(true);
    if !is_credits {
        dom::swap_inner("fund-banner", "");
        return;
    }
    // Resolve the credit identity WITHOUT minting one (an unfunded marketing
    // visit shouldn't generate a device key just to be told it's broke).
    let Some(addr) = super::chat::credit_address_existing().await else {
        dom::swap_inner("fund-banner", "");
        return;
    };
    let wallet = super::registry::token_balance_of(&addr).await.unwrap_or(0);
    let meter = super::registry::credit_balance_of(&addr).await.unwrap_or(0);
    if wallet == 0 && meter == 0 {
        dom::swap_inner("fund-banner", &templates::fund_banner_body().into_string());
    } else {
        dom::swap_inner("fund-banner", "");
    }
}

/// Soft per-origin sponsored-tx rate cap — a testnet abuse guard. Rolling
/// window kept in localStorage; bypassable (clear storage) but bounds
/// runaway loops + casual drain. The real mainnet fix is the sponsor-key
/// rewrite. Returns Err when the window is saturated.
const SPONSOR_RL_WINDOW_SECS: u64 = 3600;
const SPONSOR_RL_MAX: usize = 60;

fn sponsor_rate_guard() -> Result<(), String> {
    let Some(storage) = web_sys::window().and_then(|w| w.local_storage().ok().flatten()) else {
        return Ok(()); // no storage available → don't block the user
    };
    let now = (js_sys::Date::now() / 1000.0) as u64;
    let prev = storage
        .get_item("lh_sponsor_rl")
        .ok()
        .flatten()
        .unwrap_or_default();
    let mut stamps: Vec<u64> = prev
        .split(',')
        .filter_map(|s| s.trim().parse::<u64>().ok())
        .filter(|t| now.saturating_sub(*t) < SPONSOR_RL_WINDOW_SECS)
        .collect();
    if stamps.len() >= SPONSOR_RL_MAX {
        return Err("too many sponsored actions in a short window — wait a bit".into());
    }
    stamps.push(now);
    let joined = stamps
        .iter()
        .map(|t| t.to_string())
        .collect::<Vec<_>>()
        .join(",");
    let _ = storage.set_item("lh_sponsor_rl", &joined);
    Ok(())
}

/// Best-effort sponsor fee-token balance monitor — warns in the console
/// when the shared sponsor wallet runs low so the operator can refill.
/// Cheap single eth_call; never blocks.
pub(crate) async fn warn_if_sponsor_low() {
    const LOW_THRESHOLD_WEI: u128 = 5_000_000_000_000_000_000; // ~5 AlphaUSD
    let Ok(signer) = super::sponsor::signer() else {
        return;
    };
    let addr = crate::wallet::address(&signer);
    let addr_hex = format!(
        "0x{}",
        addr.iter().map(|b| format!("{b:02x}")).collect::<String>()
    );
    if let Ok(bal) =
        super::registry::erc20_balance_of(super::registry::ALPHA_USD_ADDRESS, &addr_hex).await
    {
        if bal < LOW_THRESHOLD_WEI {
            let whole = bal / 1_000_000_000_000_000_000u128;
            web_sys::console::warn_1(&JsValue::from_str(&format!(
                "sponsor fee-token LOW: ~{whole} AlphaUSD at {addr_hex} — refill soon"
            )));
        }
    }
}

/// Flip platform-credits vs BYOK, persist it, and repaint the section.
fn run_set_model_access(mode: String) {
    if let Some(storage) =
        web_sys::window().and_then(|w| w.local_storage().ok().flatten())
    {
        let _ = storage.set_item("lh_model_access", &mode);
    }
    // Repaint the admin credits section if it's open.
    if dom::by_id("credits-section").is_some() {
        dom::swap_outer(
            "credits-section",
            &super::templates::admin_credits_section().into_string(),
        );
    }
    // If the api-key modal happens to be open (BYOK-without-key path),
    // switching to credits dismisses it. No terminal status text — credits
    // is the default and the account tab holds the controls.
    if mode == "credits" {
        if let Some(el) = dom::by_id("api-key-modal") {
            if let Some(parent) = el.parent_element() {
                let _ = parent.remove_child(&el);
            }
        }
    }
    wasm_bindgen_futures::spawn_local(async {
        refresh_credits_pill().await;
    });
}

/// Persist the chosen LLM model id (`.lh_model`) and reflect the active
/// button in the selector. The change takes effect on the NEXT session
/// start (`chat::start_session` reads `.lh_model`), so a turn already
/// streaming keeps its backend — note that in `#model-msg`.
fn run_set_model(model: String) {
    wasm_bindgen_futures::spawn_local(async move {
        super::model::save(&model).await;
        refresh_model_selector().await;
        let label = super::model::MODELS
            .iter()
            .find(|(id, _)| *id == model)
            .map(|(_, l)| *l)
            .unwrap_or("model");
        dom::swap_inner(
            "model-msg",
            &format!("{label} — applies on your next message"),
        );
    });
}

/// Ungated HF CDN URLs for the local Gemma 3 270M model files (the `unsloth`
/// mirror — no license click-through, CORS-permissive across the
/// huggingface.co → cas-bridge.xethub.hf.co redirect chain).
const LOCAL_WEIGHTS_URL: &str =
    "https://huggingface.co/unsloth/gemma-3-270m/resolve/main/model.safetensors";
const LOCAL_TOKENIZER_URL: &str =
    "https://huggingface.co/unsloth/gemma-3-270m/resolve/main/tokenizer.json";

/// OPFS destinations for the downloaded files. MUST match the paths the local
/// backend reads (`backends::local::connection::{WEIGHTS_PATH, TOKENIZER_PATH}`)
/// — kept as literals here so the download works whether or not the heavy
/// `local` feature is compiled into this bundle.
const LOCAL_WEIGHTS_OPFS: &str = ".lh_local_model.safetensors";
const LOCAL_TOKENIZER_OPFS: &str = ".lh_local_tokenizer.json";

/// Download the in-browser local model (Gemma 3 270M weights + tokenizer) from
/// the HF CDN into OPFS, streaming with a byte-progress message. One-time opt-in
/// — once the files are in OPFS the local backend loads them on session start.
fn run_download_local_model() {
    use futures_util::StreamExt as _;
    wasm_bindgen_futures::spawn_local(async move {
        let fs = super::shared_opfs();

        // Fetch one URL, streaming chunks into a buffer and reporting progress
        // into `#local-model-msg`, then persist to OPFS via write_atomic.
        async fn fetch_to_opfs(
            fs: &std::sync::Arc<crate::filesystem::OpfsFilesystem>,
            url: &str,
            opfs_path: &str,
            label: &str,
        ) -> Result<(), String> {
            use crate::filesystem::Filesystem as _;
            let resp = reqwest::Client::new()
                .get(url)
                .send()
                .await
                .map_err(|e| format!("fetch {label}: {e}"))?;
            if !resp.status().is_success() {
                return Err(format!("fetch {label}: HTTP {}", resp.status().as_u16()));
            }
            let total = resp.content_length();
            let mut buf: Vec<u8> = Vec::with_capacity(total.unwrap_or(0) as usize);
            let mut stream = resp.bytes_stream();
            while let Some(chunk) = stream.next().await {
                let chunk = chunk.map_err(|e| format!("download {label}: {e}"))?;
                buf.extend_from_slice(&chunk);
                let got_mb = buf.len() / (1024 * 1024);
                let msg = match total {
                    Some(t) => {
                        let pct = (buf.len() as f64 / t as f64 * 100.0) as u32;
                        format!("downloading {label}: {got_mb} MB ({pct}%)")
                    }
                    None => format!("downloading {label}: {got_mb} MB"),
                };
                dom::swap_inner("local-model-msg", &msg);
            }
            fs.write_atomic(opfs_path, &buf)
                .await
                .map_err(|e| format!("save {label}: {e}"))?;
            Ok(())
        }

        dom::swap_inner("local-model-msg", "starting download…");
        let result = async {
            fetch_to_opfs(&fs, LOCAL_TOKENIZER_URL, LOCAL_TOKENIZER_OPFS, "tokenizer").await?;
            fetch_to_opfs(&fs, LOCAL_WEIGHTS_URL, LOCAL_WEIGHTS_OPFS, "weights").await?;
            Ok::<(), String>(())
        }
        .await;
        match result {
            Ok(()) => dom::swap_inner(
                "local-model-msg",
                "local model ready — select Local (Gemma) and send a message",
            ),
            Err(e) => {
                web_sys::console::warn_1(&JsValue::from_str(&format!("local model download: {e}")));
                dom::swap_inner("local-model-msg", &dom::msg_span(dom::Msg::Error, &e));
            }
        }
    });
}

/// Mark the persisted model's button `active` in `#model-selector-row`.
/// No-op when the selector isn't mounted. Mirrors `refresh_public_face_status`
/// (async-fill after the synchronous template paint).
async fn refresh_model_selector() {
    if dom::by_id("model-selector-row").is_none() {
        return;
    }
    let chosen = super::model::load().await;
    if let Some(doc) = web_sys::window().and_then(|w| w.document()) {
        if let Ok(buttons) = doc.query_selector_all("#model-selector-row button[data-model]") {
            for i in 0..buttons.length() {
                if let Some(el) = buttons.get(i) {
                    let btn: web_sys::Element = JsCast::unchecked_into(el);
                    let is_active = btn.get_attribute("data-model").as_deref() == Some(&chosen);
                    btn.set_class_name(if is_active { "ghost active" } else { "ghost" });
                }
            }
        }
    }
}

/// Open (or renew) the caller's credit session — local key signs the
/// sponsored tx (no iframe), sponsor pays fees.
fn open_session_pressed() {
    dom::swap_inner(
        "credits-msg",
        "<span style=\"color:var(--muted)\">opening session…</span>",
    );
    wasm_bindgen_futures::spawn_local(async move {
        let result = async {
            sponsor_rate_guard()?;
            let (signer, _) = super::chat::credit_signer()
                .await
                .ok_or_else(|| "no identity".to_string())?;
            let fee_payer = super::sponsor::signer()?;
            super::registry::open_session_sponsored(
                &signer,
                &fee_payer,
                super::registry::ALPHA_USD_ADDRESS,
            )
            .await
        }
        .await;
        match result {
            Ok(_) => {
                dom::swap_inner(
                    "credits-msg",
                    "<span style=\"color:var(--muted)\">session opened</span>",
                );
                refresh_credits_pill().await;
            }
            Err(e) => {
                web_sys::console::warn_1(&JsValue::from_str(&format!("open session: {e}")));
                dom::swap_inner(
                    "credits-msg",
                    "<span style=\"color:var(--error)\">couldn't open session</span>",
                );
            }
        }
    });
}

/// Redeem a one-time code from the admin credits section (`#redeem-code`),
/// writing status into `#credits-msg`.
fn redeem_code_pressed() {
    redeem_from("redeem-code", "credits-msg");
}

/// Redeem a one-time code from the inline no-funds banner
/// (`#fund-redeem-code`), writing status into `#fund-msg`. Same sponsored
/// `redeem` path as the admin field — just a different input/message slot.
fn redeem_banner_pressed() {
    redeem_from("fund-redeem-code", "fund-msg");
}

/// Shared redeem flow — local key signs, sponsor pays. Reads the code from
/// `input_id`, reports into `msg_id`, then re-funds the meter + refreshes
/// the balance pill and the no-funds banner. Used by both the admin credits
/// field and the inline funding banner so there's ONE redeem path.
fn redeem_from(input_id: &'static str, msg_id: &'static str) {
    let Some(input) = dom::input_by_id(input_id) else { return };
    let code = input.value().trim().to_string();
    if code.is_empty() {
        return;
    }
    dom::swap_inner(
        msg_id,
        "<span style=\"color:var(--muted)\">redeeming…</span>",
    );
    wasm_bindgen_futures::spawn_local(async move {
        let result = async {
            // No sponsor_rate_guard here: a redeem requires a valid, unused,
            // owner-loaded single-use code, so it's inherently un-spammable
            // (the guard was the one thing differing from the invite-link
            // path, which redeems fine). Keeps manual + invite identical.
            let (signer, _) = super::chat::credit_signer()
                .await
                .ok_or_else(|| "no identity".to_string())?;
            let fee_payer = super::sponsor::signer()?;
            super::registry::redeem_sponsored(
                &signer,
                &fee_payer,
                &code,
                super::registry::ALPHA_USD_ADDRESS,
            )
            .await
        }
        .await;
        match result {
            Ok(_) => {
                dom::swap_inner(
                    msg_id,
                    "<span style=\"color:var(--muted)\">redeemed</span>",
                );
                // Move the redeemed $LH straight into the per-request meter so
                // it's billable + the balance reflects it now (not next turn).
                super::chat::ensure_credit_meter().await;
                refresh_credits_pill().await;
                // Now-funded → drop the no-funds banner (if it was up).
                refresh_fund_banner().await;
            }
            Err(e) => {
                web_sys::console::warn_1(&JsValue::from_str(&format!("redeem: {e}")));
                dom::swap_inner(
                    msg_id,
                    &dom::msg_span(dom::Msg::Error, &format!("redeem failed: {e}")),
                );
            }
        }
    });
}

/// localStorage handle (best-effort).
fn local_storage() -> Option<web_sys::Storage> {
    web_sys::window().and_then(|w| w.local_storage().ok().flatten())
}

/// The redeem code stashed from an `?invite=CODE` link, if any.
fn pending_invite_code() -> Option<String> {
    local_storage()?
        .get_item("lh_pending_invite")
        .ok()
        .flatten()
        .filter(|s| !s.is_empty())
}

/// Auto-claim a pending invite code (captured from an `?invite=CODE`
/// link) into the visitor's credit identity, so an invitee lands with a
/// credited `$LH` balance instead of typing a code.
///
/// TWO code shapes share the one `?invite=` router (distinguished by
/// prefix — `design/invites.md` §5.1):
/// - **`inv-…`** → an InviteFacet BEARER invite: the on-chain `$LH` was
///   ESCROWED by another HOLDER; `acceptInvite(code)` pays it out to the
///   newcomer (`accept_invite_sponsored`). This is the growth primitive.
/// - **anything else** (`lh-…` etc.) → an owner-minted RedeemFacet code:
///   `redeem(code)` MINTS `$LH` to the caller (`redeem_sponsored`). The
///   pre-existing path, untouched.
///
/// `allow_generate`: on the apex (identity hub) we pass `false` so we
/// wait for the visitor to create/import their MAIN before crediting it
/// (the code stays pending across the repaint); on tenant/other origins
/// we pass `true` and credit the local device key. Idempotent: the code
/// is cleared after any committed attempt so a refresh can't double-spend.
pub(crate) async fn try_redeem_pending_invite(allow_generate: bool) {
    let Some(code) = pending_invite_code() else {
        return;
    };
    // On the apex, only redeem once an identity actually exists — don't
    // silently mint a device key on a marketing-style visit. Leave the
    // code pending; the post-create `paint_apex` re-fires this.
    if !allow_generate && super::chat::credit_address_existing().await.is_none() {
        return;
    }
    let Some((signer, _)) = super::chat::credit_signer().await else {
        return;
    };
    let Ok(fee_payer) = super::sponsor::signer() else {
        return;
    };
    // Commit: clear the pending code first so a concurrent repaint or a
    // refresh can't fire a second (double-spend) accept/redeem of the same
    // code.
    if let Some(s) = local_storage() {
        let _ = s.remove_item("lh_pending_invite");
    }
    // Bearer InviteFacet invite (escrow payout) vs owner-minted redeem code.
    let is_invite = code.starts_with("inv-");
    dom::set_status(
        if is_invite { "accepting invite…" } else { "redeeming invite…" },
        false,
    );
    let result = if is_invite {
        super::registry::accept_invite_sponsored(
            &signer,
            &fee_payer,
            &code,
            super::registry::ALPHA_USD_ADDRESS,
        )
        .await
    } else {
        super::registry::redeem_sponsored(
            &signer,
            &fee_payer,
            &code,
            super::registry::ALPHA_USD_ADDRESS,
        )
        .await
    };
    match result {
        Ok(_) => {
            // Land them on platform credits (the default) and refresh the
            // balance pill so the new $LH shows immediately.
            if let Some(s) = local_storage() {
                let _ = s.set_item("lh_model_access", "credits");
            }
            dom::set_status(
                if is_invite {
                    "invite accepted — $LH added"
                } else {
                    "invite redeemed — platform credits added"
                },
                false,
            );
            refresh_credits_pill().await;
            // Now funded → drop the no-funds banner if the chrome is up.
            refresh_fund_banner().await;
        }
        Err(e) => {
            web_sys::console::warn_1(&JsValue::from_str(&format!("invite claim: {e}")));
            dom::set_status(
                "invite couldn't be claimed (it may be used or expired)",
                true,
            );
            // Claim failed (e.g. used/expired code) → the visitor may still be
            // unfunded; surface the manual redeem CTA so they have a recovery path.
            refresh_fund_banner().await;
        }
    }
}

/// Prepay `$LH` into the per-request credit meter (whole-LH amount).
fn deposit_credits_pressed() {
    let Some(input) = dom::input_by_id("deposit-amount") else {
        return;
    };
    // Silent no-op on empty/invalid (no explanatory-validation text).
    let Ok(whole) = input.value().trim().parse::<u128>() else {
        return;
    };
    if whole == 0 {
        return;
    }
    let Some(amount_wei) = whole.checked_mul(1_000_000_000_000_000_000u128) else {
        return;
    };
    dom::swap_inner(
        "credits-msg",
        "<span style=\"color:var(--muted)\">depositing…</span>",
    );
    wasm_bindgen_futures::spawn_local(async move {
        let result = async {
            sponsor_rate_guard()?;
            let (signer, _) = super::chat::credit_signer()
                .await
                .ok_or_else(|| "no identity".to_string())?;
            let fee_payer = super::sponsor::signer()?;
            super::registry::deposit_credits_sponsored(
                &signer,
                &fee_payer,
                amount_wei,
                super::registry::ALPHA_USD_ADDRESS,
            )
            .await
        }
        .await;
        match result {
            Ok(_) => {
                dom::swap_inner(
                    "credits-msg",
                    "<span style=\"color:var(--muted)\">credits added</span>",
                );
                refresh_credits_pill().await;
            }
            Err(e) => {
                web_sys::console::warn_1(&JsValue::from_str(&format!("deposit: {e}")));
                dom::swap_inner(
                    "credits-msg",
                    "<span style=\"color:var(--error)\">deposit failed</span>",
                );
            }
        }
    });
}

/// Default invite lifetime when the owner doesn't specify one: 7 days
/// (matches the CLI's `INVITE_DEFAULT_TTL_SECS`). After it expires
/// unclaimed the funder reclaims the escrow (`invite reclaim`).
const INVITE_DEFAULT_TTL_SECS: u64 = 7 * 24 * 3600;

/// Generate a fresh, link-safe bearer invite code: `inv-<amount>-<10
/// base32 chars>`. Mirrors the CLI's `gen_invite_code` EXACTLY (same
/// Crockford-ish alphabet, same 10-char CSPRNG tail) so a browser-minted
/// code is indistinguishable from a CLI one — both hash via
/// `registry::invite_code_hash` and both route through the `inv-` `?invite=`
/// branch. The plaintext is the bearer secret; only its keccak hash is
/// stored on-chain.
fn gen_invite_code(amount_label: &str) -> String {
    // Crockford base32 minus the visually-ambiguous 0/1/i/l/o/u.
    const ALPHABET: &[u8; 32] = b"abcdefghjkmnpqrstvwxyz23456789ab";
    let bytes = super::registry::random_x402_nonce(); // 32 CSPRNG bytes (getrandom/js)
    let mut tail = String::with_capacity(10);
    for &b in bytes.iter().take(10) {
        tail.push(ALPHABET[(b & 0x1f) as usize] as char);
    }
    format!("inv-{amount_label}-{tail}")
}

/// Escrow the owner's `$LH` behind a fresh bearer code and surface the
/// `?invite=` share link (InviteFacet `createInvite`). The funder is the
/// credit identity (local key) — same signing path as redeem/deposit, so
/// `create_invite_sponsored` is called directly (sponsor pays the fee).
/// Silent no-op on empty/invalid amount (no explanatory-validation text);
/// success swaps `#invite-result` for the share-link panel.
fn create_invite_pressed() {
    let Some(input) = dom::input_by_id("invite-amount") else {
        return;
    };
    let raw = input.value().trim().to_string();
    // Silent no-op on empty/invalid/zero (no explanatory-validation text).
    let Some(amount_wei) = crate::encoding::parse_token_amount(&raw) else {
        return;
    };
    if amount_wei == 0 {
        return;
    }
    // Link-safe label for the human-readable middle of the code: keep only
    // digits + the decimal point (the `?invite=` router keys ONLY on the
    // `inv-` prefix, so this part is cosmetic but must stay URL-clean).
    let amount_label: String = raw
        .chars()
        .filter(|c| c.is_ascii_digit() || *c == '.')
        .collect();
    let code = gen_invite_code(&amount_label);
    let code_hash = super::registry::invite_code_hash(&code);
    dom::swap_inner(
        "invite-result",
        "<span style=\"color:var(--muted)\">creating invite…</span>",
    );
    wasm_bindgen_futures::spawn_local(async move {
        let result = async {
            sponsor_rate_guard()?;
            let (signer, _) = super::chat::credit_signer()
                .await
                .ok_or_else(|| "no identity".to_string())?;
            let fee_payer = super::sponsor::signer()?;
            super::registry::create_invite_sponsored(
                &signer,
                &fee_payer,
                code_hash,
                amount_wei,
                INVITE_DEFAULT_TTL_SECS,
                super::registry::ALPHA_USD_ADDRESS,
            )
            .await
        }
        .await;
        match result {
            Ok(_) => {
                // The escrow left the funder's spendable balance — reflect it.
                refresh_credits_pill().await;
                // The apex is the canonical landing origin for `?invite=` links
                // (standalone `…/?invite=CODE`), so share that.
                let link = format!("https://localharness.xyz/?invite={code}");
                dom::swap_inner(
                    "invite-result",
                    &templates::invite_result_panel(&code, &link).into_string(),
                );
            }
            Err(e) => {
                web_sys::console::warn_1(&JsValue::from_str(&format!("create invite: {e}")));
                dom::swap_inner(
                    "invite-result",
                    &dom::msg_span(dom::Msg::Error, "invite couldn't be created (need $LH to escrow)"),
                );
            }
        }
    });
}

/// ScheduleFacet's on-chain minimum cadence (mirrors the CLI's
/// `SCHEDULE_MIN_INTERVAL_SECS`). The facet rejects anything faster.
const SCHEDULE_MIN_INTERVAL_SECS: u64 = 60;
/// Run cap used when the optional "runs" input is left blank (mirrors the
/// CLI's `SCHEDULE_DEFAULT_RUNS`).
const SCHEDULE_DEFAULT_RUNS: u32 = 100;

/// Parse a human cadence (`60s` / `5m` / `1h`, bare number = seconds) into
/// seconds, enforcing the 60s floor. Mirrors the CLI's `parse_interval`
/// EXACTLY so the browser + CLI accept the same strings. `None` on garbage
/// or sub-minimum (handled by a silent no-op — no explanatory-validation).
fn parse_schedule_interval(raw: &str) -> Option<u64> {
    let s = raw.trim().to_ascii_lowercase();
    if s.is_empty() {
        return None;
    }
    let (num_part, mult) = match s.strip_suffix('s') {
        Some(n) => (n, 1u64),
        None => match s.strip_suffix('m') {
            Some(n) => (n, 60u64),
            None => match s.strip_suffix('h') {
                Some(n) => (n, 3600u64),
                None => (s.as_str(), 1u64), // bare number = seconds
            },
        },
    };
    let secs = num_part.parse::<u64>().ok()?.checked_mul(mult)?;
    (secs >= SCHEDULE_MIN_INTERVAL_SECS).then_some(secs)
}

/// Render seconds as a compact cadence (`90s` / `5m` / `2h` / `1h30m`) for
/// the jobs list. Pure mirror of the CLI's `fmt_interval`.
fn fmt_schedule_interval(secs: u64) -> String {
    if secs == 0 {
        return "0s".to_string();
    }
    if secs % 3600 == 0 {
        return format!("{}h", secs / 3600);
    }
    if secs >= 3600 {
        let h = secs / 3600;
        let m = (secs % 3600) / 60;
        let rest_s = secs % 60;
        if rest_s == 0 {
            return format!("{h}h{m}m");
        }
    }
    if secs % 60 == 0 {
        return format!("{}m", secs / 60);
    }
    format!("{secs}s")
}

/// Schedule a recurring job from the admin panel (mirrors
/// `create_invite_pressed`). Reads the target/task/interval/budget/runs
/// inputs, resolves the target name→id, escrows the budget behind
/// `scheduleJob` in ONE sponsored tx, then swaps `#schedule-result` for the
/// success panel + refreshes the jobs list. Bad/empty input is a SILENT
/// no-op (no explanatory-validation text).
fn schedule_job_pressed() {
    let target = dom::input_by_id("schedule-target")
        .map(|i| i.value().trim().to_string())
        .unwrap_or_default();
    let task = dom::input_by_id("schedule-task")
        .map(|i| i.value().trim().to_string())
        .unwrap_or_default();
    let interval_raw = dom::input_by_id("schedule-interval")
        .map(|i| i.value())
        .unwrap_or_default();
    let budget_raw = dom::input_by_id("schedule-budget")
        .map(|i| i.value())
        .unwrap_or_default();
    let runs_raw = dom::input_by_id("schedule-runs")
        .map(|i| i.value().trim().to_string())
        .unwrap_or_default();

    // Silent no-ops on missing/invalid fields (no explanatory text).
    if target.is_empty() || task.is_empty() {
        return;
    }
    let Some(interval_secs) = parse_schedule_interval(&interval_raw) else {
        return;
    };
    let Some(budget_wei) = crate::encoding::parse_token_amount(&budget_raw) else {
        return;
    };
    if budget_wei == 0 {
        return;
    }
    // Optional run cap: blank → default; garbage/zero → silent no-op.
    let max_runs = if runs_raw.is_empty() {
        SCHEDULE_DEFAULT_RUNS
    } else {
        match runs_raw.parse::<u32>() {
            Ok(n) if n > 0 => n,
            _ => return,
        }
    };

    dom::swap_inner(
        "schedule-result",
        "<span style=\"color:var(--muted)\">scheduling…</span>",
    );
    wasm_bindgen_futures::spawn_local(async move {
        let result = async {
            sponsor_rate_guard()?;
            let target_id = super::registry::id_of_name(&target).await?;
            if target_id == 0 {
                return Err("target agent not found".to_string());
            }
            let (signer, _) = super::chat::credit_signer()
                .await
                .ok_or_else(|| "no identity".to_string())?;
            let fee_payer = super::sponsor::signer()?;
            super::registry::schedule_job_sponsored(
                &signer,
                &fee_payer,
                target_id,
                task.as_bytes(),
                interval_secs,
                budget_wei,
                max_runs,
                super::registry::ALPHA_USD_ADDRESS,
            )
            .await
        }
        .await;
        match result {
            Ok(_) => {
                // The escrow left the funder's spendable balance — reflect it.
                refresh_credits_pill().await;
                // New job id = the last entry in jobsOf(caller). Read it back so
                // the success panel + list reflect the freshly-mined job.
                let new_id = match super::chat::credit_address_existing().await {
                    Some(addr) => super::registry::jobs_of(&addr)
                        .await
                        .ok()
                        .and_then(|ids| ids.last().copied())
                        .unwrap_or(0),
                    None => 0,
                };
                dom::swap_inner(
                    "schedule-result",
                    &templates::schedule_result_panel(new_id).into_string(),
                );
                refresh_jobs_list().await;
            }
            Err(e) => {
                web_sys::console::warn_1(&JsValue::from_str(&format!("schedule job: {e}")));
                dom::swap_inner(
                    "schedule-result",
                    &dom::msg_span(
                        dom::Msg::Error,
                        "job couldn't be scheduled (need $LH to escrow)",
                    ),
                );
            }
        }
    });
}

/// Cancel a scheduled job from the admin list (ScheduleFacet `cancelJob`
/// refunds the remaining escrowed `$LH`). Then refresh the list + credits.
fn cancel_job_pressed(job_id_raw: String) {
    let Ok(job_id) = job_id_raw.trim().parse::<u64>() else {
        return;
    };
    dom::swap_inner(
        "schedule-result",
        "<span style=\"color:var(--muted)\">cancelling…</span>",
    );
    wasm_bindgen_futures::spawn_local(async move {
        let result = async {
            sponsor_rate_guard()?;
            let (signer, _) = super::chat::credit_signer()
                .await
                .ok_or_else(|| "no identity".to_string())?;
            let fee_payer = super::sponsor::signer()?;
            super::registry::cancel_job_sponsored(
                &signer,
                &fee_payer,
                job_id,
                super::registry::ALPHA_USD_ADDRESS,
            )
            .await
        }
        .await;
        match result {
            Ok(_) => {
                dom::swap_inner(
                    "schedule-result",
                    &dom::msg_span(dom::Msg::Muted, "cancelled — remaining $LH refunded"),
                );
                refresh_credits_pill().await;
                refresh_jobs_list().await;
            }
            Err(e) => {
                web_sys::console::warn_1(&JsValue::from_str(&format!("cancel job: {e}")));
                dom::swap_inner(
                    "schedule-result",
                    &dom::msg_span(dom::Msg::Error, "couldn't cancel that job"),
                );
            }
        }
    });
}

/// Read the caller's `jobsOf(...)` + paint the "your jobs" list into
/// `#schedule-jobs` (per job: target name, cadence, next run, budget,
/// runs-left, status + a cancel button for Active/Paused jobs). Soft-fails
/// to a quiet line. Called on admin open + after schedule/cancel. No-op if
/// the slot isn't mounted or no identity exists yet.
pub(crate) async fn refresh_jobs_list() {
    if dom::by_id("schedule-jobs").is_none() {
        return;
    }
    let Some(addr) = super::chat::credit_address_existing().await else {
        return;
    };
    let ids = match super::registry::jobs_of(&addr).await {
        Ok(v) => v,
        Err(_) => {
            dom::swap_inner("schedule-jobs", "");
            return;
        }
    };
    if ids.is_empty() {
        dom::swap_inner(
            "schedule-jobs",
            &dom::msg_span(dom::Msg::Muted, "no scheduled jobs"),
        );
        return;
    }
    let now = (js_sys::Date::now() / 1000.0) as u64;
    // Resolve each job's record + target name. Sequential reads — fine at the
    // handful-of-jobs scale; the index is short.
    let mut rows: Vec<maud::Markup> = Vec::new();
    for id in ids {
        let Ok(job) = super::registry::get_job(id).await else {
            continue;
        };
        let target = super::registry::name_of_id(job.target_id)
            .await
            .ok()
            .filter(|n| !n.is_empty())
            .unwrap_or_else(|| format!("token#{}", job.target_id));
        let budget_whole = job.budget_wei / 1_000_000_000_000_000_000u128;
        let budget_cents =
            (job.budget_wei % 1_000_000_000_000_000_000u128) / 10_000_000_000_000_000u128;
        let cadence = fmt_schedule_interval(job.interval);
        let status = job.status_label();
        let next = if job.next_run == 0 {
            "".to_string()
        } else if job.next_run <= now {
            "due".to_string()
        } else {
            let delta = job.next_run - now;
            format!("in {}", fmt_schedule_interval(delta.max(1)))
        };
        // Only Active(0) / Paused(1) jobs can still be cancelled for a refund.
        let cancellable = matches!(job.status, 0 | 1);
        // Inline styles (monochrome, var-driven) keep this self-contained in
        // src/app/ — the same convention `refresh_signer_list` uses for its
        // on-chain-sourced rows. maud `(…)` escapes the RPC-sourced target.
        rows.push(maud::html! {
            div style="border-top:1px solid var(--border);padding:6px 0;font-size:11px;color:var(--fg)" {
                div style="display:flex;align-items:center;gap:8px" {
                    code style="color:var(--muted)" { "#" (id) }
                    span style="flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" { (target) }
                    span style="color:var(--muted)" { (status) }
                    @if cancellable {
                        button type="button" data-action="cancel-job" data-arg=(id.to_string())
                            .ghost style="padding:0 6px" { "cancel" }
                    }
                }
                div style="display:flex;flex-wrap:wrap;gap:10px;color:var(--muted);margin-top:2px" {
                    span { "every " (cadence) }
                    span { "next " (next) }
                    span { (budget_whole) "." (format!("{budget_cents:02}")) " LH" }
                    span { (job.runs_left) " runs left" }
                }
            }
        });
    }
    let html = maud::html! {
        div style="margin-top:8px" { @for r in &rows { (r) } }
    }
    .into_string();
    dom::swap_inner("schedule-jobs", &html);
}

/// Save this agent's per-call x402 price (whole `$LH` → wei in
/// `.lh_x402_price`). Empty / 0 deletes the file (free).
fn save_x402_price_pressed() {
    let Some(input) = dom::input_by_id("x402-price-input") else {
        return;
    };
    let raw = input.value().trim().to_string();
    wasm_bindgen_futures::spawn_local(async move {
        use crate::filesystem::Filesystem;
        let fs = super::shared_opfs();
        let result: Result<(), String> = async {
            if raw.is_empty() || raw == "0" {
                let _ = fs.delete(".lh_x402_price").await;
                return Ok(());
            }
            let whole: u128 = raw.parse().map_err(|_| "bad amount".to_string())?;
            let wei = whole
                .checked_mul(1_000_000_000_000_000_000u128)
                .ok_or_else(|| "overflow".to_string())?;
            fs.write_atomic(".lh_x402_price", wei.to_string().as_bytes())
                .await
                .map_err(|e| e.to_string())
        }
        .await;
        match result {
            Ok(()) => dom::swap_inner(
                "x402-price-msg",
                "<span style=\"color:var(--muted)\">saved</span>",
            ),
            Err(e) => {
                web_sys::console::warn_1(&JsValue::from_str(&format!("x402 price: {e}")));
                dom::swap_inner(
                    "x402-price-msg",
                    "<span style=\"color:var(--error)\">save failed</span>",
                );
            }
        }
    });
}

async fn refresh_signer_list() {
    let addr = super::APP.with(|cell| {
        cell.borrow().wallet.as_ref().map(|w| w.address_hex())
    });
    // On a linked device (no local master wallet) fall back to the
    // linked-owner pointer, so the on-chain device list shows the same
    // global state the seed-holding device sees.
    let addr = match addr {
        Some(a) => a,
        None => match super::wallet_store::load_linked_owner().await {
            Some(o) => o,
            None => return,
        },
    };

    let main_id = match super::registry::main_of(&addr).await {
        Ok(id) if id > 0 => id,
        _ => {
            dom::swap_inner("signer-list", "no MAIN set");
            return;
        }
    };

    // Read the on-chain enumerable index in ONE call — no log scraping.
    match super::registry::devices_of(main_id).await {
        Ok(signers) if signers.is_empty() => {
            dom::swap_inner("signer-list", "owner only (no linked devices)");
        }
        Ok(signers) => {
            // Device addresses come back from an RPC node; maud escapes both
            // the displayed `short` and the `data-arg` so a hostile node can't
            // inject markup (the `data-arg` lands back in the click dispatcher).
            let html = maud::html! {
                @for s in &signers {
                    @let short = if s.len() > 10 {
                        format!("{}{}", &s[..6], &s[s.len()-4..])
                    } else {
                        s.clone()
                    };
                    div style="display:flex;justify-content:center;align-items:center;gap:8px;color:var(--fg);font-size:11px;margin:2px 0" {
                        code { (short) }
                        button type="button" class="modal-close" data-action="unlink-device"
                            data-arg=(s) title="unlink" { "×" }
                    }
                }
            }
            .into_string();
            dom::swap_inner("signer-list", &html);
        }
        Err(_) => {
            dom::swap_inner("signer-list", "");
        }
    }
}

/// A device that announced with the matching code, awaiting the owner's
/// explicit approval before enrollment (see `pair_start_pressed`).
struct PendingPair {
    device: String,
    device_pubkey: Vec<u8>,
    token_id: u64,
    owner_hex: String,
}

thread_local! {
    static PENDING_PAIR: std::cell::RefCell<Option<PendingPair>> =
        const { std::cell::RefCell::new(None) };
}

/// Desktop side of device pairing. Generate a one-time code, show it +
/// the deep link to open on the other device, then poll the on-chain
/// pairing rendezvous. When the phone announces (its fresh device key as
/// `msg.sender` of a sponsored tx), we learn its address from the log
/// and — after the owner confirms it matches — enroll it via `addSigner`.
/// No 0x ever copied between machines.
fn pair_start_pressed() {
    // The user's MAIN name is what the phone will open (its own
    // subdomain). Resolve it from the apex wallet's MAIN.
    wasm_bindgen_futures::spawn_local(async move {
        let owner_hex = super::APP
            .with(|cell| cell.borrow().wallet.as_ref().map(|w| w.address_hex()));
        let Some(owner_hex) = owner_hex else {
            dom::swap_inner("pair-msg", &dom::msg_span(dom::Msg::Error, "no identity"));
            return;
        };
        let token_id = match super::registry::main_of(&owner_hex).await {
            Ok(id) if id != 0 => id,
            _ => {
                dom::swap_inner(
                    "pair-msg",
                    &dom::msg_span(dom::Msg::Error, "claim a subdomain first"),
                );
                return;
            }
        };
        let name = match super::registry::name_of_id(token_id).await {
            Ok(n) if !n.is_empty() => n,
            _ => {
                dom::swap_inner("pair-msg", &dom::msg_span(dom::Msg::Error, "no MAIN name"));
                return;
            }
        };

        // One-time code: 6 uppercase base32-ish chars from CSPRNG.
        let code = generate_pair_code();
        let pair_url = format!("https://{name}.localharness.xyz/?pair={code}");
        dom::swap_outer(
            "pair-slot",
            &templates::pair_panel(&code, &pair_url).into_string(),
        );
        dom::swap_inner("pair-msg", "");

        // Poll the rendezvous: ~5 min at 3s intervals.
        let code_hash = super::registry::pairing_code_hash(&code);
        let mut found: Option<(String, Vec<u8>)> = None;
        for _ in 0..100 {
            // Stop if the user cancelled (panel swapped away).
            if dom::by_id("pair-slot")
                .map(|el| !el.class_name().contains("pair-active"))
                .unwrap_or(true)
            {
                return;
            }
            match super::registry::find_pairing_device(&code_hash).await {
                Ok(Some(pair)) => {
                    found = Some(pair);
                    break;
                }
                _ => {}
            }
            super::registry::sleep_ms(3000).await;
        }

        let Some((device, device_pubkey)) = found else {
            dom::swap_inner(
                "pair-msg",
                &dom::msg_span(dom::Msg::Error, "timed out — try again"),
            );
            dom::swap_outer(
                "pair-slot",
                &r#"<div id="pair-slot" class="pair-slot"><button id="pair-btn" type="button" data-action="add-device" class="ghost">add a device</button></div>"#,
            );
            return;
        };

        // SECURITY: do NOT auto-enroll. A device matching the code hash has
        // announced, but granting it signer control over the MAIN must be an
        // explicit owner decision — so the user can compare the address shown
        // here against the one on the device they're holding (out-of-band
        // verification on top of the code + the ~5-min window). Stash the
        // pending device and ask; enrollment happens in `pair_approve_pressed`.
        PENDING_PAIR.with(|p| {
            *p.borrow_mut() = Some(PendingPair {
                device: device.clone(),
                device_pubkey,
                token_id,
                owner_hex,
            });
        });
        dom::swap_outer(
            "pair-slot",
            &templates::pair_confirm_panel(&device).into_string(),
        );
        dom::swap_inner("pair-msg", "");
    });
}

/// Owner approved the announced device — enroll it as a signer on the
/// MAIN's TBA (+ share the ECIES-wrapped Gemini key). The deliberate
/// confirmation is the out-of-band check that the address matches the
/// device the user is actually holding.
fn pair_approve_pressed() {
    let Some(pending) = PENDING_PAIR.with(|p| p.borrow_mut().take()) else {
        return;
    };
    dom::swap_inner("pair-msg", &dom::msg_span(dom::Msg::Accent, "enrolling…"));
    wasm_bindgen_futures::spawn_local(async move {
        let PendingPair { device, device_pubkey, token_id, owner_hex } = pending;
        match run_add_device(device.clone()).await {
            Ok(tx_hash) => {
                let short = tx_short_hash(&tx_hash);
                dom::swap_inner(
                    "pair-msg",
                    &dom::msg_span(
                        dom::Msg::Accent,
                        &format!("✓ linked {} (tx {short})", short_addr(&device)),
                    ),
                );
                dom::swap_outer(
                    "pair-slot",
                    &r#"<div id="pair-slot" class="pair-slot"><button id="pair-btn" type="button" data-action="pair-start" class="ghost">link another device</button></div>"#,
                );
                // ECIES-wrap the MAIN Gemini key to this device's pubkey and
                // post it on-chain, so the phone gets the key WITHOUT ever
                // importing the seed. Best-effort.
                if !device_pubkey.is_empty() {
                    if wrap_and_post_key_to_device(token_id, &owner_hex, &device, &device_pubkey)
                        .await
                        .is_ok()
                    {
                        dom::swap_inner(
                            "pair-msg",
                            &dom::msg_span(
                                dom::Msg::Accent,
                                &format!(
                                    "✓ linked {} + shared your key — it's ready to use",
                                    short_addr(&device)
                                ),
                            ),
                        );
                    }
                }
                refresh_signer_list().await;
            }
            Err(err) => {
                dom::swap_inner("pair-msg", &dom::msg_span(dom::Msg::Error, &format!("{err}")));
            }
        }
    });
}

/// Owner rejected the announced device — discard it and reset the panel.
fn pair_reject_pressed() {
    PENDING_PAIR.with(|p| *p.borrow_mut() = None);
    dom::swap_outer(
        "pair-slot",
        &r#"<div id="pair-slot" class="pair-slot"><button id="pair-btn" type="button" data-action="add-device" class="ghost">add a device</button></div>"#,
    );
    dom::swap_inner("pair-msg", &dom::msg_span(dom::Msg::Error, "rejected that device"));
}

/// Cancel an in-progress pairing — swap the panel back to the button.
/// The poll loop notices the missing `.pair-active` class and exits.
fn pair_cancel_pressed() {
    dom::swap_outer(
        "pair-slot",
        &r#"<div id="pair-slot" class="pair-slot"><button id="pair-btn" type="button" data-action="add-device" class="ghost">add a device</button></div>"#,
    );
    dom::swap_inner("pair-msg", "");
}

/// Derive a 32-byte transport key from a one-time pairing code. Keccak256
/// of the uppercased code — deterministic on both devices, so the desktop
/// can `seal_with_raw_key` and the phone can `open_with_raw_key`.
fn code_key(code: &str) -> [u8; 32] {
    use sha3::{Digest, Keccak256};
    let mut h = Keccak256::new();
    h.update(b"localharness/v0/adopt");
    h.update(code.trim().to_uppercase().as_bytes());
    let mut out = [0u8; 32];
    out.copy_from_slice(&h.finalize());
    out
}

fn hex_to_bytes(s: &str) -> Option<Vec<u8>> {
    let s = s.trim().trim_start_matches("0x");
    if s.is_empty() || s.len() % 2 != 0 {
        return None;
    }
    (0..s.len())
        .step_by(2)
        .map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok())
        .collect()
}

/// Desktop side of Option A "add a device". Encrypt this device's seed
/// under a one-time code and render a QR of an apex URL whose FRAGMENT
/// carries the ciphertext (the fragment never leaves the browser / is
/// never sent to a server). The user reads the code off-screen and types
/// it on the other device to decrypt + import — no on-chain pairing, no
/// device keys, no redirect glue.
/// "Sync my devices" — run one P2P collaboration pass: announce this device,
/// discover the owner's other online devices via the on-chain signaling roster,
/// connect over WebRTC, and union-sync the shared folder. Best-effort; status
/// lands in `#pair-msg`. (Needs the SignalingFacet cut + a second device online.)
fn run_sync_devices() {
    dom::swap_inner(
        "pair-msg",
        "<span style=\"color:var(--muted)\">discovering devices…</span>",
    );
    wasm_bindgen_futures::spawn_local(async move {
        let msg = match super::teams_sync::sync_my_devices().await {
            Ok(0) => {
                "no other devices online — open this agent on another device and sync there too"
                    .to_string()
            }
            Ok(n) => format!("connected — syncing with {n} device(s)"),
            Err(e) => format!("sync failed: {e}"),
        };
        // `msg` can carry a sync/network error string (`sync failed: {e}`),
        // so escape it via maud rather than interpolating raw HTML.
        dom::swap_inner("pair-msg", &dom::msg_span(dom::Msg::Muted, &msg));
    });
}

fn add_device_pressed() {
    let phrase = super::APP
        .with(|cell| cell.borrow().wallet.as_ref().map(|w| w.mnemonic.to_string()));
    let Some(phrase) = phrase else {
        dom::swap_inner("pair-msg", &dom::msg_span(dom::Msg::Error, "no identity on this device"));
        return;
    };
    wasm_bindgen_futures::spawn_local(async move {
        let code = generate_pair_code();
        let Some(ct) = super::encryption::seal_with_raw_key(&code_key(&code), phrase.as_bytes()).await
        else {
            dom::swap_inner("pair-msg", &dom::msg_span(dom::Msg::Error, "encrypt failed"));
            return;
        };
        let hex: String = ct.iter().map(|b| format!("{b:02x}")).collect();
        let url = format!("https://localharness.xyz/?adopt=1#s={hex}");
        dom::swap_outer("pair-slot", &templates::adopt_panel(&code, &url).into_string());
        dom::swap_inner("pair-msg", "");
    });
}

/// Phone side of Option A "add a device". Read the one-time code the user
/// typed + the ciphertext stashed in the hidden input (from the URL
/// fragment), decrypt, and import the seed — this device now IS the same
/// identity and owns every subdomain it holds. A full reload lands on the
/// clean apex with the wallet persisted.
fn adopt_device_pressed() {
    let code = dom::input_by_id("adopt-code").map(|i| i.value()).unwrap_or_default();
    let ct_hex = dom::input_by_id("adopt-ct").map(|i| i.value()).unwrap_or_default();
    if code.trim().is_empty() {
        return;
    }
    wasm_bindgen_futures::spawn_local(async move {
        let Some(ct) = hex_to_bytes(&ct_hex) else {
            dom::swap_inner("adopt-msg", &dom::msg_span(dom::Msg::Error, "bad link — rescan the QR"));
            return;
        };
        match super::encryption::open_with_raw_key(&code_key(&code), &ct).await {
            Some(bytes) => {
                let phrase = String::from_utf8_lossy(&bytes).into_owned();
                match super::wallet_store::import(phrase.trim()).await {
                    Ok(_) => {
                        if let Ok(window) = dom::window() {
                            let _ = window.location().set_href("https://localharness.xyz/");
                        }
                    }
                    Err(err) => {
                        dom::swap_inner("adopt-msg", &dom::msg_span(dom::Msg::Error, &format!("import failed: {err}")));
                    }
                }
            }
            None => {
                dom::swap_inner("adopt-msg", &dom::msg_span(dom::Msg::Error, "wrong code"));
            }
        }
    });
}

/// Phone side. The device opened `<name>.localharness.xyz/?pair=CODE`.
/// Generate a fresh device keypair, persist it as this origin's wallet,
/// and announce on-chain (sponsored) so the desktop can enroll it.
pub(crate) fn pair_join_pressed(code: String) {
    dom::swap_inner(
        "pair-join-msg",
        "<span style=\"color:var(--muted)\">generating device key + announcing…</span>",
    );
    wasm_bindgen_futures::spawn_local(async move {
        match run_pair_join(&code).await {
            Ok(addr) => {
                dom::swap_inner(
                    "pair-join-msg",
                    &dom::msg_span(
                        dom::Msg::Accent,
                        &format!(
                            "✓ this device is {addr} — approve it on your other \
                             device (check the address matches), and you'll be \
                             redirected automatically."
                        ),
                    ),
                );
            }
            Err(err) => {
                dom::swap_inner(
                    "pair-join-msg",
                    &dom::msg_span(dom::Msg::Error, &format!("{err}")),
                );
            }
        }
    });
}

/// Generate the device key, persist it to this origin's OPFS so the
/// device can keep acting as a signer, and announce `keccak(code)`
/// on-chain via a sponsored tx.
async fn run_pair_join(code: &str) -> Result<String, String> {
    // A fresh device identity for THIS subdomain origin. Persist it so
    // future visits reuse the same enrolled key (the apex flow stores a
    // mnemonic; here a per-device random key is enough — it's a signer,
    // not the master seed).
    let wallet = crate::wallet::generate();
    let device_hex = wallet.address_hex();
    super::wallet_store::persist_device_key(&wallet.private_key_hex)
        .await
        .map_err(|e| format!("save device key: {e}"))?;

    let code_hash = super::registry::pairing_code_hash(code);
    // Announce our compressed pubkey so the desktop can ECIES-wrap the
    // Gemini key directly to us — we never need the master seed.
    let pubkey = crate::wallet::pubkey_compressed(&wallet.signer);
    let fee_payer = super::sponsor::signer()?;
    super::registry::announce_pairing_sponsored(
        &wallet.signer,
        &fee_payer,
        &code_hash,
        &pubkey,
        super::registry::ALPHA_USD_ADDRESS,
    )
    .await?;

    // Background: poll for the desktop's ECIES-wrapped Gemini key, decrypt
    // it with our device key, and save it locally — so this device never
    // prompts for an API key. Best-effort; the device still works as a
    // signer even if the desktop has no key to share.
    let device_signer = wallet.signer.clone();
    let device_addr = device_hex.clone();
    wasm_bindgen_futures::spawn_local(async move {
        let name = match super::tenant::current() {
            super::tenant::Host::Tenant(n) => n,
            _ => return,
        };
        // The identity (MAIN) this subdomain belongs to — so we can detect
        // when the desktop enrolls us into its on-chain device index, and so
        // we can hand the apex a pointer to this owner on redirect.
        let (main_id, owner_hex) = match super::registry::owner_of_name(&name).await {
            Ok(Some(owner)) => (super::registry::main_of(&owner).await.unwrap_or(0), owner),
            _ => (0, String::new()),
        };
        let slot_id = gemini_key_slot_id(&name).await.ok();
        let mut enrolled = false;
        let mut got_key = false;
        let mut post_enroll = 0u32;
        for _ in 0..60 {
            // 1) Enrollment confirmation: are we in the MAIN's device index
            //    yet? (The desktop writes it via linkDevice on enroll.) This
            //    is what tells the phone the link actually landed — instead
            //    of sitting forever on "finish on your other device".
            if !enrolled && main_id != 0 {
                if let Ok(devs) = super::registry::devices_of(main_id).await {
                    if devs.iter().any(|d| d.eq_ignore_ascii_case(&device_addr)) {
                        enrolled = true;
                        dom::swap_inner(
                            "pair-join-msg",
                            &dom::msg_span(dom::Msg::Accent, "✓ this device is now linked"),
                        );
                    }
                }
            }
            // 2) ECIES-wrapped Gemini key (best-effort — never required).
            if !got_key {
                if let Some(slot_id) = slot_id {
                    if let Ok(Some(blob)) =
                        super::registry::wrapped_device_key_of(slot_id, &device_addr).await
                    {
                        if let Some(pt) =
                            super::encryption::ecies_open(&device_signer, &blob).await
                        {
                            if let Ok(key) = String::from_utf8(pt) {
                                super::key_store::save(&key).await;
                                if let Ok(Some(storage)) = dom::session_storage() {
                                    let _ = storage.set_item("gemini_api_key", &key);
                                }
                                got_key = true;
                            }
                        }
                    }
                }
            }
            if enrolled {
                // Linked! The device is now an authorized signer, so opening
                // the subdomain lands it in the studio as an owner. Redirect
                // automatically rather than dead-ending on a message. Credits
                // are the default (no Gemini key needed to start); if the
                // desktop shared one via ECIES we grab it first, else give a
                // short grace window then go anyway.
                if got_key || post_enroll >= 2 {
                    dom::swap_inner(
                        "pair-join-msg",
                        &dom::msg_span(dom::Msg::Accent, "✓ linked — opening your subdomain…"),
                    );
                    if let Ok(window) = dom::window() {
                        // Route via the apex with a linked-owner pointer so the
                        // apex on THIS device learns which identity it belongs
                        // to (then it hops on to the subdomain). Falls back to a
                        // direct subdomain open if we never resolved the owner.
                        let url = if owner_hex.is_empty() {
                            format!("https://{name}.localharness.xyz/")
                        } else {
                            format!(
                                "https://localharness.xyz/?link_device={owner_hex}&then={name}"
                            )
                        };
                        let _ = window.location().set_href(&url);
                    }
                    return;
                }
                post_enroll += 1;
                dom::swap_inner(
                    "pair-join-msg",
                    &dom::msg_span(dom::Msg::Accent, "✓ linked — opening your subdomain…"),
                );
            }
            super::registry::sleep_ms(3000).await;
        }
    });

    Ok(device_hex)
}

/// Derive the seed-sync AES key from the LOCAL apex master wallet (no
/// iframe — this runs on the apex origin where the seed lives). Must
/// match `signer::seed_sync_key` byte-for-byte so a blob sealed by the
/// iframe path opens here. `None` if no wallet is loaded.
fn apex_seed_sync_key() -> Option<[u8; 32]> {
    use sha3::{Digest, Keccak256};
    super::APP.with(|cell| {
        let app = cell.borrow();
        let wallet = app.wallet.as_ref()?;
        let entropy = wallet.mnemonic.to_entropy();
        let mut hasher = Keccak256::new();
        hasher.update(b"localharness/v0/keysync");
        hasher.update(&entropy);
        let mut out = [0u8; 32];
        out.copy_from_slice(&hasher.finalize());
        Some(out)
    })
}

/// Desktop side. Read the MAIN's seed-sealed Gemini key from chain,
/// decrypt it with the local seed, ECIES-wrap it to the freshly-paired
/// device's pubkey, and post that blob under the device's per-device slot.
/// Errors (no key synced, no seed here) are returned so the caller can
/// silently skip — the device still enrolls as a signer regardless.
async fn wrap_and_post_key_to_device(
    main_id: u64,
    owner_hex: &str,
    device_hex: &str,
    device_pubkey: &[u8],
) -> Result<(), String> {
    let ct = super::registry::gemini_key_of(main_id)
        .await
        .map_err(|e| format!("read key: {e}"))?
        .ok_or_else(|| "no synced key".to_string())?;
    let seed_key = apex_seed_sync_key().ok_or_else(|| "no seed on this device".to_string())?;
    let plaintext = super::encryption::open_with_raw_key(&seed_key, &ct)
        .await
        .ok_or_else(|| "decrypt failed".to_string())?;
    let blob = super::encryption::ecies_seal(device_pubkey, &plaintext)
        .await
        .ok_or_else(|| "wrap failed".to_string())?;
    let signer = super::APP
        .with(|cell| cell.borrow().wallet.as_ref().map(|w| w.signer.clone()))
        .ok_or_else(|| "no wallet".to_string())?;
    let fee_payer = super::sponsor::signer()?;
    super::registry::set_device_wrapped_key_sponsored(
        &signer,
        &fee_payer,
        main_id,
        device_hex,
        &blob,
        super::registry::ALPHA_USD_ADDRESS,
    )
    .await?;
    let _ = owner_hex; // owner is implied by the local signer
    Ok(())
}

/// 6-char one-time pairing code (Crockford-ish base32, no ambiguous
/// chars) from the browser CSPRNG. Short enough to read aloud / type.
fn generate_pair_code() -> String {
    const ALPHABET: &[u8] = b"23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
    let mut bytes = [0u8; 6];
    let _ = getrandom::getrandom(&mut bytes);
    bytes
        .iter()
        .map(|b| ALPHABET[(*b as usize) % ALPHABET.len()] as char)
        .collect()
}

/// Resolve the current user's MAIN's TBA address, then submit a
/// sponsored Tempo tx that creates the TBA (if needed) + adds the new
/// device as an authorized signer.
async fn run_add_device(new_signer_hex: String) -> Result<String, String> {
    // Apex wallet — must be present (the button is only rendered when
    // the apex has a wallet, so failing here is an unusual race).
    let (signer, owner_hex) = super::APP
        .with(|cell| {
            cell.borrow()
                .wallet
                .as_ref()
                .map(|w| (w.signer.clone(), w.address_hex()))
        })
        .ok_or_else(|| "no apex identity".to_string())?;

    // Identify the user's MAIN. `mainOf` returns the tokenId or 0.
    let token_id = super::registry::main_of(&owner_hex)
        .await
        .map_err(|e| format!("mainOf: {e}"))?;
    if token_id == 0 {
        return Err("claim a subdomain first — it becomes your MAIN".into());
    }

    // Derive the MAIN's TBA address (counterfactual or already-deployed).
    let tba_addr = super::registry::tba_of_token_id(token_id)
        .await
        .map_err(|e| format!("tba lookup: {e}"))?
        .ok_or_else(|| "no TBA for MAIN".to_string())?;

    let fee_payer = super::sponsor::signer()?;
    super::registry::add_signer_sponsored(
        &signer,
        &fee_payer,
        token_id,
        &tba_addr,
        &new_signer_hex,
        super::registry::ALPHA_USD_ADDRESS,
    )
    .await
}

/// Resolve (local owner signer, owner hex, MAIN id, MAIN TBA). The
/// shared preamble for consolidate/unlink — both act on the MAIN's TBA.
async fn owner_main_tba() -> Result<(k256::ecdsa::SigningKey, String, u64, String), String> {
    let (signer, owner_hex) = super::APP
        .with(|c| {
            c.borrow()
                .wallet
                .as_ref()
                .map(|w| (w.signer.clone(), w.address_hex()))
        })
        .ok_or_else(|| "no identity".to_string())?;
    let main_id = super::registry::main_of(&owner_hex)
        .await
        .map_err(|e| format!("mainOf: {e}"))?;
    if main_id == 0 {
        return Err("set a MAIN first".into());
    }
    let main_name = super::registry::name_of_id(main_id)
        .await
        .map_err(|e| format!("name: {e}"))?;
    let main_tba = super::registry::tba_of_name(&main_name)
        .await
        .map_err(|e| format!("tba: {e}"))?
        .ok_or_else(|| "no MAIN TBA".to_string())?;
    Ok((signer, owner_hex, main_id, main_tba))
}

/// Consolidate this identity's OTHER subdomains into its MAIN's TBA — one
/// account owns them all, every linked device controls them. Moves NFTs,
/// so it's an explicit user action.
fn consolidate_pressed() {
    dom::swap_inner(
        "consolidate-msg",
        "<span style=\"color:var(--muted)\">consolidating…</span>",
    );
    wasm_bindgen_futures::spawn_local(async move {
        let result = async {
            let (signer, owner_hex, main_id, main_tba) = owner_main_tba().await?;
            let tokens = super::registry::list_owned_tokens(&owner_hex)
                .await
                .map_err(|e| format!("list: {e}"))?;
            let ids: Vec<u64> = tokens
                .iter()
                .map(|t| t.token_id)
                .filter(|id| *id != main_id)
                .collect();
            if ids.is_empty() {
                return Err("nothing to consolidate — only your MAIN".into());
            }
            let fee_payer = super::sponsor::signer()?;
            super::registry::consolidate_into_main_sponsored(
                &signer,
                &fee_payer,
                &main_tba,
                &ids,
                super::registry::ALPHA_USD_ADDRESS,
            )
            .await
        }
        .await;
        match result {
            Ok(_) => dom::swap_inner(
                "consolidate-msg",
                "<span style=\"color:var(--muted)\">✓ subdomains consolidated under your MAIN</span>",
            ),
            Err(e) => {
                web_sys::console::warn_1(&JsValue::from_str(&format!("consolidate: {e}")));
                dom::swap_inner(
                    "consolidate-msg",
                    "<span style=\"color:var(--error)\">consolidate failed</span>",
                );
            }
        }
    });
}

/// The X on a linked device. Removing a device's access is destructive
/// (revokes its signer authority + costs a sponsored tx + a re-pair to
/// undo), so a single accidental click must NOT do it — show a typed
/// confirmation in `#pair-msg` first. (Unlinking affects only THAT device;
/// the owner / other devices keep their access.)
fn unlink_device_prompt(device_hex: String) {
    let short = short_addr(&device_hex);
    dom::swap_inner(
        "pair-msg",
        &format!(
            "<div class=\"unlink-confirm\">\
               <div>remove <code>{short}</code>? type <b>yes</b> to confirm.</div>\
               <input id=\"unlink-confirm-input\" type=\"text\" autocomplete=\"off\" \
                 placeholder=\"yes\">\
               <div class=\"pair-confirm-actions\">\
                 <button type=\"button\" class=\"ghost\" data-action=\"unlink-cancel\">cancel</button>\
                 <button type=\"button\" class=\"button-link\" data-action=\"unlink-confirm\" \
                   data-arg=\"{device_hex}\">remove</button>\
               </div>\
             </div>"
        ),
    );
}

/// Abort an in-progress unlink — clear the confirmation prompt.
fn unlink_cancel_pressed() {
    dom::swap_inner("pair-msg", "");
}

/// Only unlink when the user typed `yes` in the confirmation input.
fn unlink_confirm_pressed(device_hex: String) {
    let typed = dom::input_by_id("unlink-confirm-input")
        .map(|i| i.value().trim().to_lowercase())
        .unwrap_or_default();
    if typed != "yes" {
        dom::swap_inner(
            "pair-msg",
            &dom::msg_span(dom::Msg::Error, "type yes to remove that device"),
        );
        return;
    }
    dom::swap_inner("pair-msg", &dom::msg_span(dom::Msg::Accent, "removing…"));
    wasm_bindgen_futures::spawn_local(async move {
        let result = async {
            let (signer, _owner, main_id, main_tba) = owner_main_tba().await?;
            let fee_payer = super::sponsor::signer()?;
            super::registry::remove_signer_sponsored(
                &signer,
                &fee_payer,
                main_id,
                &main_tba,
                &device_hex,
                super::registry::ALPHA_USD_ADDRESS,
            )
            .await
        }
        .await;
        match result {
            Ok(_) => {
                dom::swap_inner("pair-msg", "");
                refresh_signer_list().await
            }
            Err(e) => {
                dom::swap_inner(
                    "pair-msg",
                    &dom::msg_span(dom::Msg::Error, &format!("unlink failed: {e}")),
                );
            }
        }
    });
}

/// Release (recycle) a subdomain on-chain via the iframe-signed sponsored
/// path (the owner signs the sender hash through the apex signer). The
/// CALLER (tool / UI) MUST do the typed-confirmation gate BEFORE calling
/// this — this only performs the on-chain release.
pub(crate) async fn run_release_subdomain(name: &str) -> Result<String, String> {
    let token_id = match super::registry::check_name(name).await? {
        super::registry::Status::Taken { agent_id } => agent_id,
        _ => return Err(format!("'{name}' is not registered")),
    };
    let owner = super::registry::owner_of_name(name)
        .await
        .map_err(|e| format!("owner: {e}"))?
        .ok_or_else(|| "no on-chain owner".to_string())?;
    let diamond = parse_address(super::registry::REGISTRY_ADDRESS)?;
    let call = crate::tempo_tx::TempoCall {
        to: diamond,
        value_wei: 0,
        input: super::registry::release_name_calldata(token_id),
    };
    // A burn (clears the name's cold slots) runs ~100-150k inner + ~275k
    // sponsorship ≈ ~375-425k — a flat 400k had near-zero margin and silently
    // OOG-reverted (chain reverts, name stays `isTaken`, UI reports success:
    // the feedback/redeem OOG bug class). Over-budget is free (the sponsor is
    // billed on gas USED, not the limit), so headroom is the right call.
    run_sponsored_tempo_call(&owner, vec![call], 1_000_000, "release subdomain").await
}

/// Bulk-release (burn) several subdomains in ONE sponsored, iframe-signed
/// tx. `names` are resolved to token ids; the owner's MAIN is refused
/// up-front (and again on-chain). The CALLER (tool) MUST gate on a single
/// typed master confirmation BEFORE calling — this only performs the write.
/// Returns (released_names, tx_hash).
pub(crate) async fn run_bulk_release(
    names: &[String],
) -> Result<(Vec<String>, String), String> {
    if names.is_empty() {
        return Err("no subdomains to release".into());
    }
    // Resolve owner + MAIN from the current tenant, same preamble as
    // consolidate (owner_main_tba) but we only need the owner hex + MAIN id.
    let tenant = match super::tenant::current() {
        super::tenant::Host::Tenant(n) => n,
        _ => return Err("not running on a subdomain".into()),
    };
    let owner = super::registry::owner_of_name(&tenant)
        .await
        .map_err(|e| format!("owner: {e}"))?
        .ok_or_else(|| "no on-chain owner".to_string())?;
    let main_id = super::registry::main_of(&owner)
        .await
        .map_err(|e| format!("mainOf: {e}"))?;

    let diamond = parse_address(super::registry::REGISTRY_ADDRESS)?;
    let mut released: Vec<String> = Vec::with_capacity(names.len());
    let mut calls: Vec<crate::tempo_tx::TempoCall> = Vec::with_capacity(names.len());
    for raw in names {
        let name = raw.trim();
        if name.is_empty() {
            continue;
        }
        let token_id = match super::registry::check_name(name).await? {
            super::registry::Status::Taken { agent_id } => agent_id,
            _ => return Err(format!("'{name}' is not registered")),
        };
        if main_id != 0 && token_id == main_id {
            return Err(format!(
                "'{name}' is your MAIN identity and cannot be released"
            ));
        }
        // Defensive: only burn names this owner actually holds — a stray
        // name would revert the WHOLE batch on-chain (and waste sponsor gas).
        let holder = super::registry::owner_of_name(name)
            .await
            .map_err(|e| format!("owner of {name}: {e}"))?
            .ok_or_else(|| format!("no on-chain owner for '{name}'"))?;
        if holder.to_lowercase() != owner.to_lowercase() {
            return Err(format!("'{name}' is not owned by this identity"));
        }
        calls.push(crate::tempo_tx::TempoCall {
            to: diamond,
            value_wei: 0,
            input: super::registry::release_name_calldata(token_id),
        });
        released.push(name.to_string());
    }
    if calls.is_empty() {
        return Err("no subdomains to release after filtering".into());
    }
    // 1M base headroom + ~250k per extra burn (see release_names_sponsored).
    let gas = 1_000_000 + (calls.len() as u128).saturating_sub(1) * 250_000;
    let tx = run_sponsored_tempo_call(&owner, calls, gas, "bulk release subdomains").await?;
    Ok((released, tx))
}

/// Batch-register N subdomains in ONE sponsored, iframe-signed tx — the
/// sanctioned mass-registration path (vs. a sequential `create_subdomain`
/// loop, which spends N sponsored txs + N auto-continue iterations). Names
/// are sanitised, deduped, and availability-checked up front; an already-
/// taken or invalid name is SKIPPED (a single bad `register` would revert
/// the whole multicall on-chain and waste sponsor gas — same defensive
/// lesson as `run_bulk_release`'s holder check). Returns (registered_names,
/// tx_hash). The owner context is resolved from the current tenant.
pub(crate) async fn run_batch_create_subdomains(
    names: &[String],
) -> Result<(Vec<String>, String), String> {
    if names.is_empty() {
        return Err("no names to register".into());
    }
    // Resolve the owner EOA from the current tenant (same preamble as
    // run_bulk_release) — run_sponsored_tempo_call recovers + verifies the
    // sender address against this, so it must be the master wallet's address.
    let tenant = match super::tenant::current() {
        super::tenant::Host::Tenant(n) => n,
        _ => return Err("not running on a subdomain".into()),
    };
    let owner = super::registry::owner_of_name(&tenant)
        .await
        .map_err(|e| format!("owner: {e}"))?
        .ok_or_else(|| "no on-chain owner".to_string())?;

    let diamond = parse_address(super::registry::REGISTRY_ADDRESS)?;
    let mut registered: Vec<String> = Vec::with_capacity(names.len());
    let mut calls: Vec<crate::tempo_tx::TempoCall> = Vec::with_capacity(names.len());
    for raw in names {
        let cleaned = super::tenant::sanitize(raw);
        // Reject silently-mangled or out-of-range names rather than minting a
        // different name than asked. No explanatory text — just skip + report.
        if cleaned.len() < 3
            || cleaned.len() > 32
            || cleaned != raw.trim().to_ascii_lowercase()
        {
            continue;
        }
        if registered.iter().any(|n| n == &cleaned) {
            continue; // dedupe — a repeat register would revert the batch
        }
        // Availability pre-check: a register on a TAKEN name reverts the whole
        // multicall. Skip taken names (the tool reports which were skipped).
        match super::registry::check_name(&cleaned).await? {
            super::registry::Status::Available => {}
            _ => continue,
        }
        calls.push(crate::tempo_tx::TempoCall {
            to: diamond,
            value_wei: 0,
            input: super::registry::register_calldata(&cleaned),
        });
        registered.push(cleaned);
    }
    if calls.is_empty() {
        return Err("no valid, available names to register".into());
    }
    // Each register is a full cold ERC-721 mint (~1.32M inner each, per the
    // eth_estimateGas note in registry.rs) + ONE ~275k sponsorship overhead
    // for the tx. 1.5M/name covers the mint + cold-SSTORE variance + margin;
    // +400k one-time. Over-budget is FREE — the sponsor is billed on gas USED,
    // not the limit (same lesson as the redeem/feedback OOG bug class), so
    // headroom is correct.
    let gas = 400_000 + (calls.len() as u128) * 1_500_000;
    let tx = run_sponsored_tempo_call(&owner, calls, gas, "batch create subdomains").await?;
    // Inherit this device's Gemini key onto each new subdomain (best-effort,
    // detached — same as the single create_subdomain flow).
    for name in &registered {
        let n = name.clone();
        wasm_bindgen_futures::spawn_local(async move {
            sync_local_key_to_main(&n).await;
        });
    }
    Ok((registered, tx))
}

/// Sponsored Tempo tx orchestrator. Apex iframe signs `sender_hash`,
/// the bundle sponsor key signs `fee_payer_hash`, raw tx assembled
/// locally and submitted. User holds zero of anything — `fee_payer`
/// pays fees in AlphaUSD.
///
/// `from_hex` is the sender's EOA — it must own whatever balance the
/// calls touch (e.g. $LH for a `transfer`), but does NOT need native
/// gas or the fee_token.
pub(crate) async fn run_sponsored_tempo_call(
    from_hex: &str,
    calls: Vec<crate::tempo_tx::TempoCall>,
    gas_limit: u128,
    purpose: &str,
) -> Result<String, String> {
    sponsor_rate_guard()?;
    let sender_address = parse_address(from_hex)?;
    let fee_token_addr = parse_address(super::registry::ALPHA_USD_ADDRESS)?;
    let nonce = super::registry::next_nonce(from_hex).await
        .map_err(|e| format!("nonce: {e}"))?;
    let gas_price = super::registry::current_gas_price().await
        .map_err(|e| format!("gas price: {e}"))?;

    let tx = crate::tempo_tx::TempoTxBuilder::new(super::registry::CHAIN_ID)
        .max_priority_fee_per_gas(gas_price)
        .max_fee_per_gas(gas_price)
        .gas_limit(gas_limit)
        .nonce(nonce)
        .calls(calls)
        .fee_token(fee_token_addr)
        .sponsored()
        .build();

    let sender_hash = tx.sender_hash();
    let (claimed_addr, sender_sig) =
        super::verify::sign_tempo_tx_via_iframe(&tx, purpose)
            .await
            .map_err(|e| format!("signer: {e}"))?;

    // Defensive: the recovered address must match the expected sender
    // EOA. If it doesn't, the iframe signed with a different wallet
    // (XSS, race with a wallet swap, etc.) and submitting would burn
    // sponsor funds on a tx that doesn't even authorize the call.
    let recovered = crate::wallet::recover_address(&sender_sig, &sender_hash)
        .map_err(|e| format!("recover: {e}"))?;
    if recovered != sender_address {
        return Err(format!(
            "sender sig recovered 0x{} but expected {claimed_addr} ({from_hex})",
            recovered.iter().map(|b| format!("{b:02x}")).collect::<String>(),
        ));
    }

    let fee_payer = super::sponsor::signer()?;
    let fp_hash = tx.fee_payer_hash(&sender_address);
    let fp_sig = crate::wallet::sign_hash(&fee_payer, &fp_hash);
    let raw = tx.serialize_signed(&sender_sig, Some(&fp_sig));
    let raw_hex = bytes_to_hex_str(&raw);
    super::registry::submit_and_wait_receipt(&raw_hex).await
        .map_err(|e| format!("submit: {e}"))
}

/// Toggle the header admin dropdown. Origin determines content —
/// apex shows seed reveal + import + reset, tenant has the gemini
/// api key input + reset. After opening, pre-fill the api key from
/// sessionStorage / OPFS so the user sees their existing key
/// (admin opens and closes constantly; the input is fresh DOM each time).
fn header_admin_toggle() {
    let body = match super::tenant::current() {
        super::tenant::Host::Apex => templates::admin_dropdown_apex().into_string(),
        super::tenant::Host::Tenant(_) | super::tenant::Host::Other(_) => {
            templates::admin_dropdown_tenant().into_string()
        }
    };
    dom::swap_outer("header-admin-panel", &body);

    // Inject the stashed agent card (folded in from the retired right rail)
    // into the Account tab's #financial-slot. Built by kick_verification.
    if let Some(card) = super::APP.with(|c| c.borrow().financial_card_html.clone()) {
        if dom::by_id("financial-slot").is_some() {
            dom::swap_outer("financial-slot", &card);
        }
    }

    // Fill the Usage tab's subdomain count + token total. No-ops if the
    // slots aren't there.
    wasm_bindgen_futures::spawn_local(async move {
        refresh_usage_slot().await;
    });

    // Credit balance — on EVERY host (apex AND subdomains). Credits are
    // master-EOA-scoped, so a subdomain shows the SAME balance as the apex; the
    // old apex-only gate is exactly why subdomains showed a blank "…" / "—".
    // Fire-and-forget so the dropdown paints immediately; the pill resolves from
    // "…" to "N LH".
    wasm_bindgen_futures::spawn_local(async move {
        refresh_credits_pill().await;
    });
    // Recurring jobs list (ScheduleFacet) — no-ops if the slot isn't mounted
    // (no wallet) or no identity exists yet. Same fire-and-forget shape as
    // the credits pill so the dropdown paints immediately.
    wasm_bindgen_futures::spawn_local(async move {
        refresh_jobs_list().await;
    });
    // Device/signer management lives at the apex only.
    if matches!(super::tenant::current(), super::tenant::Host::Apex) {
        wasm_bindgen_futures::spawn_local(async move {
            refresh_signer_list().await;
        });
    }

    // Pre-fill api key from sessionStorage (sync) then refresh from
    // OPFS (async). Same pattern as the old in-chrome key restore.
    if matches!(
        super::tenant::current(),
        super::tenant::Host::Tenant(_) | super::tenant::Host::Other(_)
    ) {
        if let Ok(Some(storage)) = dom::session_storage() {
            if let Ok(Some(cached)) = storage.get_item("gemini_api_key") {
                if let Some(input) = dom::input_by_id("key") {
                    input.set_value(&cached);
                    refresh_keymeta();
                }
            }
        }
        wasm_bindgen_futures::spawn_local(async move {
            if let Some(persisted) = super::key_store::load().await {
                if let Some(input) = dom::input_by_id("key") {
                    input.set_value(&persisted);
                    refresh_keymeta();
                }
            }
            // Restore the saved custom prompt into the textarea so the
            // user can edit instead of re-typing.
            if let Some(prompt) = super::system_prompt::load().await {
                if let Some(textarea) = dom::textarea_by_id("prompt-input") {
                    textarea.set_value(&prompt);
                }
            }
            // Prefill the x402 price (stored as wei → shown as whole LH).
            {
                use crate::filesystem::Filesystem;
                if let Ok(bytes) = super::shared_opfs().read(".lh_x402_price").await {
                    if let Some(wei) = String::from_utf8(bytes)
                        .ok()
                        .and_then(|s| s.trim().parse::<u128>().ok())
                    {
                        if let Some(input) = dom::input_by_id("x402-price-input") {
                            input.set_value(&(wei / 1_000_000_000_000_000_000u128).to_string());
                        }
                    }
                }
            }
            if let Some(allowed) = super::tool_allowlist::load().await {
                if let Some(doc) = web_sys::window().and_then(|w| w.document()) {
                    if let Ok(checkboxes) = doc.query_selector_all(".tool-checkbox") {
                        for i in 0..checkboxes.length() {
                            if let Some(el) = checkboxes.get(i) {
                                let input: web_sys::HtmlInputElement = JsCast::unchecked_into(el);
                                if let Some(name) = input.get_attribute("data-tool") {
                                    let is_allowed = allowed.iter().any(|t| t.wire_name() == name);
                                    input.set_checked(is_allowed);
                                }
                            }
                        }
                    }
                }
                let summary = super::tool_allowlist::summary(&allowed);
                dom::swap_inner("tool-allowlist-status", &summary);
            } else {
                dom::swap_inner("tool-allowlist-status", "all tools enabled");
            }
            refresh_public_face_status().await;
            refresh_model_selector().await;
        });
    }
}

/// Read the subdomain's current on-chain public-face choice and reflect it
/// in the `#public-face-status` slot. No-op off a tenant or if the slot
/// isn't mounted.
async fn refresh_public_face_status() {
    let name = match super::tenant::current() {
        super::tenant::Host::Tenant(n) => n,
        _ => return,
    };
    if dom::by_id("public-face-status").is_none() {
        return;
    }
    // Timeout-capped so a dead RPC resolves to the directory-default label
    // instead of leaving the placeholder text up forever.
    let face = match super::net::read(super::registry::id_of_name(&name)).await {
        Ok(Ok(id)) if id != 0 => super::net::read(super::registry::public_face_of(id))
            .await
            .ok()
            .and_then(Result::ok)
            .flatten(),
        _ => None,
    };
    let label = match face.as_deref() {
        Some("app") => "currently: app",
        Some("html") => "currently: html",
        _ => "currently: directory (default)",
    };
    dom::swap_inner("public-face-status", label);
}

fn header_admin_close() {
    dom::swap_outer(
        "header-admin-panel",
        r#"<div id="header-admin-panel" hidden></div>"#,
    );
}

/// Switch the active admin tab by flipping the `tab-<name>` class on
/// `#admin-dialog` (CSS shows the matching `.panel-<name>`), and sync the
/// `.active` state on the tab buttons. Mirrors `show_mobile_tab`.
fn show_admin_tab(name: &str) {
    let Some(dialog) = dom::by_id("admin-dialog") else { return };
    let mut cls: Vec<String> = dialog
        .class_name()
        .split_whitespace()
        .filter(|c| !c.starts_with("tab-"))
        .map(String::from)
        .collect();
    cls.push(format!("tab-{name}"));
    dialog.set_class_name(&cls.join(" "));

    for tab in ["agent", "account", "usage", "feedback"] {
        let Some(el) = dom::by_id(&format!("admin-tab-btn-{tab}")) else { continue };
        let c = el.class_name();
        let mut classes: Vec<&str> = c.split_whitespace().filter(|x| *x != "active").collect();
        if tab == name {
            classes.push("active");
        }
        el.set_class_name(&classes.join(" "));
    }
}

/// Fill the admin Usage tab's `#usage-subdomains` slot with the on-chain
/// registered-subdomain count. Soft-fail (leaves a dash). No-op if the
/// slot isn't present.
pub(crate) async fn refresh_usage_slot() {
    // Tokens — synchronous read from App state (updated after each turn).
    if dom::by_id("usage-tokens").is_some() {
        let total = super::APP.with(|c| c.borrow().total_tokens);
        dom::swap_inner("usage-tokens", &format!("{total}"));
    }
    if dom::by_id("usage-subdomains").is_none() {
        return;
    }
    // YOUR owned subdomains — NOT the global registry total. `subdomain_count`
    // (nextId-1) counts every name ever minted, including released/burned ones,
    // so after a reset it stays high (the "still says 30" bug). Resolve the
    // owner from the current tenant (else the local wallet) and count what they
    // actually hold (released ids have ownerOfId=0, so they drop out).
    let owner = match super::tenant::current() {
        super::tenant::Host::Tenant(name) => {
            super::registry::owner_of_name(&name).await.ok().flatten()
        }
        _ => super::APP.with(|c| c.borrow().wallet.as_ref().map(|w| w.address_hex())),
    };
    let count = match owner {
        Some(owner_hex) => super::registry::list_owned_tokens(&owner_hex)
            .await
            .map(|t| t.len()),
        None => Ok(0),
    };
    match count {
        Ok(n) => dom::swap_inner("usage-subdomains", &format!("{n}")),
        Err(_) => dom::swap_inner("usage-subdomains", ""),
    }
}

/// Mobile-only: swap which `tab-<name>` class is on `#layout`.
/// CSS uses it to show exactly one panel at a time on narrow
/// viewports. Tab button styling syncs by toggling `.active`.
fn show_mobile_tab(name: &str) {
    let Some(layout) = dom::by_id("layout") else { return };
    let parts: Vec<String> = layout
        .class_name()
        .split_whitespace()
        .filter(|c| !c.starts_with("tab-"))
        .map(String::from)
        .collect();
    let mut new_cls = parts.join(" ");
    if !new_cls.is_empty() {
        new_cls.push(' ');
    }
    new_cls.push_str(&format!("tab-{name}"));
    layout.set_class_name(&new_cls);

    // The display tab shows the framebuffer; mount an idle surface if
    // nothing is already on it so the canvas exists when the tab opens.
    if name == "display" && dom::by_id("display-canvas").is_none() {
        dom::swap_inner(
            "view-content",
            &super::templates::display_surface().into_string(),
        );
    }

    // Reflect active state on each tab button by id — small fixed
    // set of tabs, no need for query_selector_all (which needs the
    // NodeList web-sys feature we don't enable).
    for tab in ["files", "chat", "display", "agent"] {
        let id = format!("tab-btn-{tab}");
        let Some(el) = dom::by_id(&id) else { continue };
        let cls = el.class_name();
        let mut classes: Vec<&str> =
            cls.split_whitespace().filter(|c| *c != "active").collect();
        if tab == name {
            classes.push("active");
        }
        el.set_class_name(&classes.join(" "));
    }
}

fn decode_hex_local(s: &str) -> Option<Vec<u8>> {
    let t = s.trim().trim_start_matches("0x").trim_start_matches("0X");
    if t.len() % 2 != 0 {
        return None;
    }
    (0..t.len())
        .step_by(2)
        .map(|i| u8::from_str_radix(t.get(i..i + 2)?, 16).ok())
        .collect()
}

/// #18: seal the current Gemini key with the seed-derived key (via the
/// apex iframe) and store the ciphertext on-chain under the gemini-key
/// metadata key (owner-signed, sponsored). A device that imports the seed
/// can then `restore` it without re-pasting.
async fn run_sync_key() {
    let msg = "key-sync-msg";
    let set_err = |m: &str| dom::swap_inner(msg, &dom::msg_span(dom::Msg::Error, &format!("{m}")));

    let name = match super::tenant::current() {
        super::tenant::Host::Tenant(n) => n,
        _ => {
            set_err("only on a subdomain");
            return;
        }
    };
    let owner_hex = super::APP.with(|cell| {
        use super::VerifyState;
        match &cell.borrow().verify_state {
            VerifyState::Verified { address } => Some(address.clone()),
            _ => None,
        }
    });
    let Some(owner_hex) = owner_hex else {
        set_err("verify as owner first");
        return;
    };
    let key = dom::input_by_id("key").map(|i| i.value()).unwrap_or_default();
    if key.trim().is_empty() {
        set_err("enter your key first");
        return;
    }

    dom::swap_inner(msg, "<span style=\"color:var(--muted)\">sealing…</span>");
    let ct_hex = match super::verify::seal_key_via_iframe(&key).await {
        Ok(h) => h,
        Err(e) => {
            set_err(&format!("seal: {e}"));
            return;
        }
    };
    let Some(ct) = decode_hex_local(&ct_hex) else {
        set_err("bad ciphertext from signer");
        return;
    };
    let id = match gemini_key_slot_id(&name).await {
        Ok(id) => id,
        Err(e) => {
            set_err(&e);
            return;
        }
    };
    let registry_addr = match parse_address(super::registry::REGISTRY_ADDRESS) {
        Ok(a) => a,
        Err(e) => {
            set_err(&e);
            return;
        }
    };
    let call = crate::tempo_tx::TempoCall {
        to: registry_addr,
        value_wei: 0,
        input: super::registry::encode_set_gemini_key(id, &ct),
    };
    let words = (ct.len() / 32 + 1) as u128;
    let gas = 1_200_000 + words * 40_000;
    dom::swap_inner(msg, "<span style=\"color:var(--muted)\">syncing on-chain…</span>");
    match run_sponsored_tempo_call(&owner_hex, vec![call], gas, "sync key").await {
        Ok(_) => dom::swap_inner(
            msg,
            &dom::msg_span(dom::Msg::Accent, "synced ✓ — import your seed on another device to restore"),
        ),
        Err(e) => set_err(&format!("sync failed: {e}")),
    }
}

/// #18: fetch this subdomain's on-chain key ciphertext, decrypt it with
/// the seed-derived key (via the apex iframe — requires the seed to be
/// present on this device), and set it as the active Gemini key.
async fn run_restore_key() {
    let msg = "key-sync-msg";
    let set_err = |m: &str| dom::swap_inner(msg, &dom::msg_span(dom::Msg::Error, &format!("{m}")));

    let name = match super::tenant::current() {
        super::tenant::Host::Tenant(n) => n,
        _ => {
            set_err("only on a subdomain");
            return;
        }
    };
    let id = match gemini_key_slot_id(&name).await {
        Ok(id) => id,
        Err(e) => {
            set_err(&e);
            return;
        }
    };
    dom::swap_inner(msg, "<span style=\"color:var(--muted)\">fetching…</span>");
    let ct = match super::registry::gemini_key_of(id).await {
        Ok(Some(b)) => b,
        Ok(None) => {
            set_err("no synced key on-chain yet");
            return;
        }
        Err(e) => {
            set_err(&format!("read: {e}"));
            return;
        }
    };
    let ct_hex = format!(
        "0x{}",
        ct.iter().map(|b| format!("{b:02x}")).collect::<String>()
    );
    let plaintext = match super::verify::open_key_via_iframe(&ct_hex).await {
        Ok(p) => p,
        Err(e) => {
            set_err(&format!("open: {e} — import your seed on this device first"));
            return;
        }
    };
    if let Some(input) = dom::input_by_id("key") {
        input.set_value(&plaintext);
    }
    super::key_store::save(&plaintext).await;
    refresh_keymeta();
    dom::swap_inner(
        msg,
        &dom::msg_span(dom::Msg::Accent, "restored ✓ — applies on next session"),
    );
}

/// The on-chain tokenId the Gemini-key blob lives under: the owner's
/// MAIN, so every subdomain the owner holds shares ONE key (per the
/// "the subdomain IS the primary owner" model — a new subdomain should
/// reuse the MAIN's key, not prompt for a fresh one). Falls back to the
/// current subdomain's own id if the owner has no MAIN set.
async fn gemini_key_slot_id(name: &str) -> Result<u64, String> {
    let owner = super::registry::owner_of_name(name)
        .await
        .map_err(|e| format!("owner: {e}"))?
        .ok_or_else(|| "name not registered on-chain".to_string())?;
    let main_id = super::registry::main_of(&owner).await.unwrap_or(0);
    if main_id != 0 {
        return Ok(main_id);
    }
    match super::registry::id_of_name(name).await {
        Ok(id) if id != 0 => Ok(id),
        _ => Err("no token id for name".into()),
    }
}

/// Best-effort: seal the Gemini key with the seed-derived key (via the
/// apex iframe) and store it on-chain under the owner's MAIN slot, so any
/// other subdomain / seed-bearing device auto-restores it. No-op on any
/// failure — most importantly when the seed isn't on this device (the
/// iframe seal fails), which is fine: nothing to sync from here.
async fn auto_sync_gemini_key(name: String, key: String) {
    let owner = match super::registry::owner_of_name(&name).await {
        Ok(Some(o)) => o,
        _ => return,
    };
    let slot_id = match gemini_key_slot_id(&name).await {
        Ok(id) => id,
        Err(_) => return,
    };
    // Seal with the seed-derived key via the apex iframe. Fails (and we
    // bail) on a device that doesn't hold the seed.
    let ct_hex = match super::verify::seal_key_via_iframe(&key).await {
        Ok(h) => h,
        Err(_) => return,
    };
    let Some(ct) = decode_hex_local(&ct_hex) else { return };
    let Ok(registry_addr) = parse_address(super::registry::REGISTRY_ADDRESS) else { return };
    let call = crate::tempo_tx::TempoCall {
        to: registry_addr,
        value_wei: 0,
        input: super::registry::encode_set_gemini_key(slot_id, &ct),
    };
    let words = (ct.len() / 32 + 1) as u128;
    let gas = 1_200_000 + words * 40_000;
    let _ = run_sponsored_tempo_call(&owner, vec![call], gas, "auto-sync key").await;
}

/// Proactively push THIS device's Gemini key to the owner's MAIN slot
/// on-chain so a just-created subdomain (and every other) inherits it
/// with no manual re-save. Best-effort + no-op without a local key or the
/// seed (the seal happens via the apex iframe). Called after a claim.
pub(crate) async fn sync_local_key_to_main(name: &str) {
    if let Some(key) = super::key_store::load().await {
        auto_sync_gemini_key(name.to_string(), key).await;
    }
}

/// Try to pull the owner's MAIN Gemini key from chain and decrypt it
/// with this device's seed (via the apex iframe). On success the key is
/// saved to this origin's OPFS + sessionStorage and `true` is returned,
/// so the caller can skip the api-key modal. Returns `false` (silently)
/// when there's no synced key OR this device lacks the seed (e.g. a phone
/// linked by device key only — that path will use the wrapped-key blob).
pub(crate) async fn try_auto_restore_gemini_key(name: &str) -> bool {
    if super::key_store::load().await.is_some() {
        return true;
    }
    let slot_id = match gemini_key_slot_id(name).await {
        Ok(id) => id,
        Err(_) => return false,
    };
    let ct = match super::registry::gemini_key_of(slot_id).await {
        Ok(Some(b)) => b,
        _ => return false,
    };
    let ct_hex = format!(
        "0x{}",
        ct.iter().map(|b| format!("{b:02x}")).collect::<String>()
    );
    let plaintext = match super::verify::open_key_via_iframe(&ct_hex).await {
        Ok(p) => p,
        Err(_) => return false,
    };
    super::key_store::save(&plaintext).await;
    if let Ok(Some(storage)) = dom::session_storage() {
        let _ = storage.set_item("gemini_api_key", &plaintext);
    }
    true
}

/// Set this subdomain's public face on-chain — `"directory"`, `"app"`, or
/// `"html"`. The choice lives under `keccak256("localharness.public_face")`
/// so every visitor honours it. For `"app"`/`"html"` we also publish the
/// device's local `app.rl`/`index.html` content in the SAME sponsored tx
/// (owner-signed through the apex iframe), so the chosen face is live
/// immediately. Owner-only.
async fn run_set_public_face(choice: &str) {
    let msg = "publish-app-msg";
    let set_err = |m: &str| {
        dom::swap_inner(msg, &dom::msg_span(dom::Msg::Error, m));
    };

    let name = match super::tenant::current() {
        super::tenant::Host::Tenant(n) => n,
        _ => {
            set_err("only on a subdomain");
            return;
        }
    };

    // The verified-EOA address IF this device verified as the on-chain
    // owner directly. May be None when the owner is a TBA we sign for
    // (consolidation) — that path is decided in the submit branch below.
    let verified_eoa = super::APP.with(|cell| {
        use super::VerifyState;
        match &cell.borrow().verify_state {
            VerifyState::Verified { address } => Some(address.clone()),
            _ => None,
        }
    });

    let id = match super::registry::id_of_name(&name).await {
        Ok(id) if id != 0 => id,
        _ => {
            set_err("name isn't registered on-chain");
            return;
        }
    };

    let registry_addr = match parse_address(super::registry::REGISTRY_ADDRESS) {
        Ok(a) => a,
        Err(e) => {
            set_err(&e);
            return;
        }
    };
    let mk = |input: Vec<u8>| crate::tempo_tx::TempoCall {
        to: registry_addr,
        value_wei: 0,
        input,
    };

    // Build the call batch + gas estimate for the chosen face. Storing
    // `bytes` costs ~20k gas per 32-byte word (cold SSTORE) on top of the
    // ~275k Tempo sponsorship + base call.
    let (calls, gas): (Vec<crate::tempo_tx::TempoCall>, u128) = match choice {
        "directory" => (
            vec![mk(super::registry::encode_set_public_face(id, "directory"))],
            500_000,
        ),
        "app" => {
            let fs = super::shared_opfs();
            let src = match fs.read("app.rl").await {
                Ok(b) if !b.is_empty() => String::from_utf8_lossy(&b).into_owned(),
                _ => {
                    set_err("no app.rl on this device — build one first (run_cartridge)");
                    return;
                }
            };
            let wasm = match crate::rustlite::compile(&src) {
                Ok(w) => w,
                Err(e) => {
                    set_err(&format!("compile: {e}"));
                    return;
                }
            };
            if wasm.len() > 16_384 {
                set_err("app wasm too large to publish (max 16 KB)");
                return;
            }
            (
                vec![
                    mk(super::registry::encode_set_app_wasm(id, &wasm)),
                    mk(super::registry::encode_set_public_face(id, "app")),
                ],
                // setMetadata stores bytes on-chain at ~7.6k gas/BYTE (measured
                // via debug_traceTransaction, 2026-06-03; same byte-storage cost
                // as the FeedbackFacet). The old `1.3M + words*40k` (~1.25k/byte)
                // was ~6x too low and OOG-reverted any non-trivial app publish.
                1_200_000 + wasm.len() as u128 * 8_500,
            )
        }
        "html" => {
            let fs = super::shared_opfs();
            let html = match fs.read("index.html").await {
                Ok(b) if !b.is_empty() => b,
                _ => {
                    set_err("no index.html on this device — create one first");
                    return;
                }
            };
            if html.len() > 24_576 {
                set_err("index.html too large to publish (max 24 KB)");
                return;
            }
            (
                vec![
                    mk(super::registry::encode_set_public_html(id, &html)),
                    mk(super::registry::encode_set_public_face(id, "html")),
                ],
                // Same ~7.6k gas/byte on-chain storage cost as the app branch.
                1_200_000 + html.len() as u128 * 8_500,
            )
        }
        _ => {
            set_err("unknown public face");
            return;
        }
    };

    dom::swap_inner(msg, "<span style=\"color:var(--muted)\">saving…</span>");

    // Decide the execution path from the on-chain owner:
    //  - owner is a TBA this device signs for (consolidation) → execute
    //    the setMetadata batch THROUGH the TBA, signed by our local key.
    //  - owner is our verified EOA → direct sponsored call (existing).
    let on_chain_owner = match super::registry::owner_of_name(&name).await {
        Ok(Some(o)) => o,
        _ => {
            set_err("name isn't registered on-chain");
            return;
        }
    };
    let local = super::chat::credit_signer().await;
    let is_signer = match &local {
        Some((_, addr)) => {
            let addr_hex = format!(
                "0x{}",
                addr.iter().map(|b| format!("{b:02x}")).collect::<String>()
            );
            super::registry::is_authorized_signer(&on_chain_owner, &addr_hex)
                .await
                .unwrap_or(false)
        }
        None => false,
    };
    let result = if is_signer {
        let (signer, _) = local.unwrap();
        let fee_payer = match super::sponsor::signer() {
            Ok(s) => s,
            Err(e) => {
                set_err(&e);
                return;
            }
        };
        let token_id = match super::registry::tba_token_id_of(&on_chain_owner).await {
            Ok(t) => t,
            Err(e) => {
                set_err(&e);
                return;
            }
        };
        let targets: Vec<([u8; 20], Vec<u8>)> =
            calls.iter().map(|c| (registry_addr, c.input.clone())).collect();
        super::registry::tba_execute_batch_sponsored(
            &signer,
            &fee_payer,
            token_id,
            &on_chain_owner,
            &targets,
            super::registry::ALPHA_USD_ADDRESS,
            gas + 800_000,
        )
        .await
    } else if let Some(owner_hex) =
        verified_eoa.filter(|a| a.eq_ignore_ascii_case(&on_chain_owner))
    {
        run_sponsored_tempo_call(&owner_hex, calls, gas, "public face").await
    } else {
        set_err("verify as owner first");
        return;
    };
    match result {
        Ok(_tx) => {
            let head = if choice == "directory" {
                "public face → directory ✓".to_string()
            } else {
                format!("published ✓ — {name}.localharness.xyz")
            };
            dom::swap_inner(
                msg,
                &maud::html! {
                    span style="color:var(--fg)" {
                        (head) " "
                        a href=(format!("https://{name}.localharness.xyz/"))
                          target="_blank" rel="noopener" style="color:var(--accent)" {
                            "open →"
                        }
                    }
                }
                .into_string(),
            );
            refresh_public_face_status().await;
        }
        Err(e) => set_err(&format!("failed: {e}")),
    }
}

/// Pure DOM class flip on `#layout` — used by the panel toggles
/// (files-collapsed, financial-collapsed) so a collapse + expand
/// doesn't lose any panel state (open file viewer, pricing edit
/// in-flight, etc.). CSS handles the actual hide/show.
fn toggle_layout_class(class: &str) {
    let Some(layout) = dom::by_id("layout") else { return };
    let current = layout.class_name();
    let trimmed = current.trim();
    let parts: Vec<&str> = trimmed.split_whitespace().collect();
    let new_cls = if parts.contains(&class) {
        parts.iter().filter(|c| **c != class).copied().collect::<Vec<_>>().join(" ")
    } else if parts.is_empty() {
        class.to_string()
    } else {
        format!("{} {class}", parts.join(" "))
    };
    layout.set_class_name(&new_cls);
}

/// Inline-confirmed reset: clear local app data at OPFS root, reload.
/// Identity-preserving — keeps the seed + owner hint (see the loop below).
/// Replaces the old `window.confirm()` flow per [[feedback-no-js-alerts]].
fn reset_confirm_pressed() {
    // Typed confirmation — reset still clears app data/keys, so require the
    // literal word, not just a second click. (It no longer touches the seed.)
    let typed = dom::input_by_id("reset-confirm-text")
        .map(|i| i.value().trim().to_string())
        .unwrap_or_default();
    if !typed.eq_ignore_ascii_case("RESET") {
        dom::swap_inner(
            "reset-confirm-msg",
            "<span style=\"color:var(--error)\">type RESET to confirm</span>",
        );
        return;
    }
    wasm_bindgen_futures::spawn_local(async move {
        let fs = super::shared_opfs();
        if let Ok(entries) = fs.read_dir("").await {
            for entry in entries {
                // Identity-preserving reset: KEEP the seed (`.lh_wallet`) and the
                // proven-owner hint (`.lh_owner`) so the device re-verifies on
                // reload instead of bricking. Everything else — history, app.rl,
                // cached keys, working files — is cleared. The seed is the ONLY
                // key to on-chain ownership; a local-only delete with no backup
                // was the brick (mobile especially: no signer-iframe path back).
                if entry.name == ".lh_wallet" || entry.name == ".lh_owner" {
                    continue;
                }
                let _ = fs.delete(&entry.name).await;
            }
        }
        if let Ok(window) = dom::window() {
            let _ = window.location().reload();
        }
    });
}

/// Parse the pricing-input as a decimal test-ETH amount, convert to
/// wei, persist via `pricing::save`, and re-paint the card so the
/// new value shows. Owner-only — the input is only rendered when
/// the verifier confirmed this visitor is the owner — but we still
/// re-check `verify_state` here as belt-and-suspenders against a
/// stale DOM.
fn pricing_save_pressed() {
    let Some(input) = dom::input_by_id("pricing-input") else {
        return;
    };
    let raw = input.value().trim().to_string();
    let wei = match parse_eth_to_wei(&raw) {
        Ok(w) => w,
        Err(err) => {
            dom::swap_inner(
                "pricing-msg",
                &dom::msg_span(dom::Msg::Error, &format!("{err}")),
            );
            return;
        }
    };

    let is_owner = super::APP.with(|cell| {
        matches!(cell.borrow().verify_state, super::VerifyState::Verified { .. })
    });
    if !is_owner {
        dom::swap_inner(
            "pricing-msg",
            "<span style=\"color:var(--error)\">only the verified owner can change pricing</span>",
        );
        return;
    }

    dom::swap_inner(
        "pricing-msg",
        "<span style=\"color:var(--muted)\">saving…</span>",
    );
    wasm_bindgen_futures::spawn_local(async move {
        match super::pricing::save(wei).await {
            Ok(()) => {
                super::APP
                    .with(|cell| cell.borrow_mut().pricing_wei = Some(wei));
                let html = templates::pricing_card_body(wei, true).into_string();
                dom::swap_outer("pricing-body", &html);
            }
            Err(err) => {
                dom::swap_inner(
                    "pricing-msg",
                    &dom::msg_span(dom::Msg::Error, &format!("save failed: {err}")),
                );
            }
        }
    });
}

/// Parse a decimal test-ETH amount ("0", "0.001", "1.5") into a wei
/// `u128`. Rejects negatives, NaN-shaped input, and values with more
/// than 18 fractional digits (wei is the precision floor).
fn parse_eth_to_wei(s: &str) -> Result<u128, String> {
    if s.is_empty() {
        return Ok(0);
    }
    let (whole_str, frac_str) = match s.split_once('.') {
        Some((w, f)) => (w, f),
        None => (s, ""),
    };
    if !whole_str.bytes().all(|b| b.is_ascii_digit()) {
        return Err("price must be a positive decimal".into());
    }
    if !frac_str.bytes().all(|b| b.is_ascii_digit()) {
        return Err("price must be a positive decimal".into());
    }
    if frac_str.len() > 18 {
        return Err("price has more precision than wei (18 decimals max)".into());
    }
    let whole: u128 = whole_str.parse().map_err(|e| format!("whole: {e}"))?;
    // Right-pad fraction to 18 digits then parse.
    let mut padded = String::with_capacity(18);
    padded.push_str(frac_str);
    while padded.len() < 18 {
        padded.push('0');
    }
    let frac: u128 = if padded.is_empty() {
        0
    } else {
        padded.parse().map_err(|e| format!("frac: {e}"))?
    };
    whole
        .checked_mul(1_000_000_000_000_000_000)
        .and_then(|w| w.checked_add(frac))
        .ok_or_else(|| "price too large".into())
}


// --- Action handlers ---------------------------------------------------

fn clear_key_pressed() {
    if let Some(input) = dom::input_by_id("key") {
        input.set_value("");
    }
    if let Ok(Some(storage)) = dom::session_storage() {
        let _ = storage.remove_item("gemini_api_key");
    }
    refresh_keymeta();
    if let Some(input) = dom::input_by_id("key") {
        input.focus().ok();
    }
    wasm_bindgen_futures::spawn_local(async move {
        super::key_store::clear().await;
    });
    dom::set_status("key cleared (sessionStorage + OPFS)", false);
}