localharness 0.10.27

A Rust-native agent SDK for Gemini. 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
//! 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, KeyboardEvent, MouseEvent};

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,
    Reset,
    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,
    RevealSecurity,
    HideSecurity,
    ResetArm,
    ResetConfirm,
    ResetCancel,
    PricingSave,
    ToggleFiles,
    ToggleFinancial,
    ToggleTerminal,
    ToggleView,
    ShowTab(String),
    FeedbackOpen,
    FeedbackClose,
    FeedbackSubmit,
    LhTransfer,
    AddDevice,
    ClaimCredits,
    AgentActToggle(String),
    AgentSendLh(String),
    SavePrompt,
    SaveToolAllowlist,
    ResetToolAllowlist,
}

impl Action {
    fn parse(name: &str, arg: Option<String>) -> Option<Action> {
        Some(match name {
            "send" => Action::Send,
            "reset" => Action::Reset,
            "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,
            "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-open" => Action::FeedbackOpen,
            "feedback-close" => Action::FeedbackClose,
            "feedback-submit" => Action::FeedbackSubmit,
            "lh-transfer" => Action::LhTransfer,
            "add-device" => Action::AddDevice,
            "claim-credits" => Action::ClaimCredits,
            "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,
            _ => 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| {
        if event.key() != "Enter" {
            return;
        }
        let Some(target) = event.target() else { return };
        let Ok(el) = target.dyn_into::<Element>() else { return };
        if 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();

    Ok(())
}

/// 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) {
    set_create_button_busy(true);

    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. If the registry charges LH for
        //      `register(name)` and the user can't cover it, bail
        //      before burning sponsor gas on a guaranteed revert.
        //      A fresh identity auto-claims daily credits in the
        //      background; the user may need to wait for that to
        //      land, or hit the "claim daily" button.
        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::Reset => reset_pressed(),
        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::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).await;
            });
        }
        Action::ClaimHere => {
            wasm_bindgen_futures::spawn_local(async move {
                match super::owner::claim().await {
                    Ok(id) => {
                        web_sys::console::log_1(&JsValue::from_str(&format!(
                            "claimed with owner id {id}"
                        )));
                        // Re-render the tenant chrome now that we own it.
                        if let super::tenant::Host::Tenant(name) = super::tenant::current() {
                            super::paint_tenant(super::tenant::Host::Tenant(name.clone()), name)
                                .await;
                        }
                    }
                    Err(err) => {
                        dom::swap_inner(
                            "claim-msg",
                            &format!(
                                "<span style=\"color:var(--error)\">claim failed: {err}</span>"
                            ),
                        );
                    }
                }
            });
        }
        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",
                        &format!(
                            "<span style=\"color:var(--error)\">identity setup failed: {err}</span>"
                        ),
                    );
                    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, _tx)) => {
                        let _ = super::owner::claim().await;
                        super::paint_tenant(
                            super::tenant::Host::Tenant(name.clone()),
                            name,
                        )
                        .await;
                    }
                    Err(err) => {
                        dom::swap_inner(
                            "claim-msg",
                            &format!(
                                "<span style=\"color:var(--error)\">claim failed: {err}</span>"
                            ),
                        );
                    }
                }
            });
        }
        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",
                        &format!(
                            "<span style=\"color:var(--error)\">import failed: {err}</span>"
                        ),
                    );
                    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",
                                &format!(
                                    "<span style=\"color:var(--error)\">reveal failed: {err}</span>\
                                     <button type=\"button\" data-action=\"reveal-seed\" class=\"ghost\">retry</button>"
                                ),
                            ),
                        }
                    });
                }
            }
        }
        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 {
                        let wallet = match super::wallet_store::create_and_persist().await {
                            Ok(w) => w,
                            Err(err) => {
                                dom::swap_inner(
                                    "identity-msg",
                                    &format!(
                                        "<span style=\"color:var(--error)\">create failed: {err}</span>"
                                    ),
                                );
                                return;
                            }
                        };
                        run_initial_credit_claim(wallet.signer.clone()).await;
                        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",
                                    &format!(
                                        "<span style=\"color:var(--error)\">create failed: {err}</span>"
                                    ),
                                );
                            }
                        }
                    });
                }
            }
        }
        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.trim().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",
                                    &format!(
                                        "<span style=\"color:var(--error)\">import failed: {err}</span>"
                                    ),
                                );
                            }
                        }
                    });
                }
                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",
                                    &format!(
                                        "<span style=\"color:var(--error)\">import failed: {err}</span>"
                                    ),
                                );
                            }
                        }
                    });
                }
            }
        }
        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}"
                    )));
                }
                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::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::FeedbackOpen => feedback_open(),
        Action::FeedbackClose => feedback_close(),
        Action::FeedbackSubmit => feedback_submit(),
        Action::LhTransfer => lh_transfer_pressed(),
        Action::AddDevice => add_device_pressed(),
        Action::ClaimCredits => claim_credits_pressed(),
        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(),
    }
}

/// 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",
                    &format!("<span style=\"color:var(--accent)\">{summary}</span>"),
                );
            }
            Err(err) => {
                dom::swap_inner(
                    "prompt-msg",
                    &format!("<span style=\"color:var(--error)\">{err}</span>"),
                );
            }
        }
    });
}

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",
                    &format!("<span style=\"color:var(--accent)\">✓ saved · {summary} · takes effect on next session</span>"),
                );
            }
            Err(err) => {
                dom::swap_inner(
                    "tool-allowlist-msg",
                    &format!("<span style=\"color:var(--error)\">{err}</span>"),
                );
            }
        }
    });
}

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",
                    &format!("<span style=\"color:var(--error)\">{err}</span>"),
                );
            }
        }
    });
}

/// 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,
                    &format!("<div class=\"admin-msg-slot\"><span style=\"color:var(--error)\">{err}</span></div>"),
                );
            }
        });
    } 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();
    if !is_address_hex(&to_raw) {
        return; // silent no-op per [[feedback-no-explanatory-validation]]
    }
    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,
                    &format!(
                        "<span style=\"color:var(--accent)\">✓ sent (tx {short})</span>"
                    ),
                );
                // Re-paint to refresh the balance line.
                let _ = paint_agent_act_panel(token_id).await;
            }
            Err(err) => {
                dom::swap_inner(
                    &msg_id,
                    &format!("<span style=\"color:var(--error)\">{err}</span>"),
                );
            }
        }
    });
}

/// User-initiated daily credit claim from the admin dropdown.
/// Sponsored Tempo tx; reverts on-chain if already claimed today
/// (chain emits `AlreadyClaimedToday` error). On success, refreshes
/// the balance pill.
fn claim_credits_pressed() {
    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(
        "claim-credits-msg",
        "<span style=\"color:var(--muted)\">signing + submitting…</span>",
    );
    if let Some(btn) = dom::by_id("claim-credits-btn") {
        let _ = btn.set_attribute("disabled", "");
    }
    wasm_bindgen_futures::spawn_local(async move {
        let fee_payer = match super::sponsor::signer() {
            Ok(k) => k,
            Err(err) => {
                dom::swap_inner(
                    "claim-credits-msg",
                    &format!("<span style=\"color:var(--error)\">sponsor: {err}</span>"),
                );
                return;
            }
        };
        match super::registry::claim_daily_sponsored(
            &signer,
            &fee_payer,
            super::registry::ALPHA_USD_ADDRESS,
        )
        .await
        {
            Ok(tx_hash) => {
                let short = tx_short_hash(&tx_hash);
                dom::swap_inner(
                    "claim-credits-msg",
                    &format!(
                        "<span style=\"color:var(--accent)\">✓ claimed (tx {short})</span>"
                    ),
                );
                refresh_credits_pill().await;
            }
            Err(err) => {
                let pretty = if err.contains("AlreadyClaimedToday")
                    || err.to_lowercase().contains("already claimed")
                {
                    "already claimed today".to_string()
                } else {
                    err
                };
                dom::swap_inner(
                    "claim-credits-msg",
                    &format!("<span style=\"color:var(--error)\">{pretty}</span>"),
                );
                if let Some(btn) = dom::by_id("claim-credits-btn") {
                    let _ = btn.remove_attribute("disabled");
                }
            }
        }
    });
}

/// Fetch the credit balance for the apex wallet and write it into
/// `#credits-balance`. Called on admin-open and after a successful
/// claim. Soft-fail — leaves the placeholder on error so UI stays clean.
pub(crate) async fn refresh_credits_pill() {
    let addr = super::APP.with(|cell| {
        cell.borrow().wallet.as_ref().map(|w| w.address_hex())
    });
    let Some(addr) = addr else { return };
    let Ok(balance_wei) = super::registry::token_balance_of(&addr).await else { return };
    let lh = balance_wei / 1_000_000_000_000_000_000u128;
    dom::swap_inner("credits-balance", &format!("{lh} LH"));
}

/// Link another device's EOA to the current user's MAIN. The clicked
/// device is the "authorizer" (its wallet IS the NFT holder of the
/// MAIN, or has been authorized previously); the pasted address is
/// the new device's wallet. One sponsored Tempo tx batches
/// `createTokenBoundAccount` (idempotent) + `addSigner`. User pays
/// nothing — sponsor pays AlphaUSD.
fn add_device_pressed() {
    let raw = dom::input_by_id("add-device-input")
        .map(|i| i.value().trim().to_string())
        .unwrap_or_default();
    if !is_address_hex(&raw) {
        // Silent no-op on bad input — per [[feedback-no-explanatory-validation]].
        return;
    }
    dom::swap_inner(
        "add-device-msg",
        "<span style=\"color:var(--muted)\">signing + submitting…</span>",
    );
    wasm_bindgen_futures::spawn_local(async move {
        match run_add_device(raw.clone()).await {
            Ok(tx_hash) => {
                let short = tx_short_hash(&tx_hash);
                dom::swap_inner(
                    "add-device-msg",
                    &format!(
                        "<span style=\"color:var(--accent)\">✓ added {} (tx {short})</span>",
                        short_addr(&raw)
                    ),
                );
                if let Some(input) = dom::input_by_id("add-device-input") {
                    input.set_value("");
                }
            }
            Err(err) => {
                dom::swap_inner(
                    "add-device-msg",
                    &format!("<span style=\"color:var(--error)\">{err}</span>"),
                );
            }
        }
    });
}

/// 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
}

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

/// $localharness transfer from the visitor's apex wallet to a recipient.
/// Reads the recipient + amount from the financial-card form, builds
/// `transfer(address,uint256)` calldata, signs via the apex signer
/// iframe, submits to Tempo Moderato. Caller's gas paid by the apex
/// wallet (visitor) — Tempo allows contract calls, so no native-transfer
/// ban hits this path.
fn lh_transfer_pressed() {
    let to_raw = dom::input_by_id("lh-transfer-to")
        .map(|i| i.value().trim().to_string())
        .unwrap_or_default();
    let amount_raw = dom::input_by_id("lh-transfer-amount")
        .map(|i| i.value().trim().to_string())
        .unwrap_or_default();
    if !is_address_hex(&to_raw) {
        dom::swap_inner(
            "lh-transfer-msg",
            "<span style=\"color:var(--error)\">recipient must be a 0x… address</span>",
        );
        return;
    }
    let Some(amount_wei) = parse_token_amount(&amount_raw) else {
        dom::swap_inner(
            "lh-transfer-msg",
            "<span style=\"color:var(--error)\">amount: positive number, up to 18 decimals</span>",
        );
        return;
    };
    if amount_wei == 0 {
        dom::swap_inner(
            "lh-transfer-msg",
            "<span style=\"color:var(--error)\">amount must be greater than zero</span>",
        );
        return;
    }

    // Visitor's apex address. The verify state's address (verified or
    // visitor) is the master wallet that the iframe signer controls.
    let from_hex = super::APP.with(|cell| {
        use super::VerifyState;
        match &cell.borrow().verify_state {
            VerifyState::Verified { address } => Some(address.clone()),
            VerifyState::Visitor { visitor_address, .. } => Some(visitor_address.clone()),
            _ => None,
        }
    });
    let Some(from_hex) = from_hex else {
        dom::swap_inner(
            "lh-transfer-msg",
            "<span style=\"color:var(--error)\">no apex identity yet — open admin to create one</span>",
        );
        return;
    };

    dom::swap_inner(
        "lh-transfer-msg",
        "<span style=\"color:var(--muted)\">signing + submitting…</span>",
    );
    wasm_bindgen_futures::spawn_local(async move {
        if let Err(err) = run_lh_transfer(from_hex, to_raw, amount_wei).await {
            dom::swap_inner(
                "lh-transfer-msg",
                &format!("<span style=\"color:var(--error)\">{err}</span>"),
            );
        }
    });
}

async fn run_lh_transfer(
    from_hex: String,
    to_hex: String,
    amount_wei: u128,
) -> Result<(), String> {
    let calldata = encode_transfer_calldata(&to_hex, amount_wei)?;
    let token_addr = parse_address(super::registry::LOCALHARNESS_TOKEN_ADDRESS)?;
    let call = crate::tempo_tx::TempoCall {
        to: token_addr,
        value_wei: 0,
        input: calldata,
    };
    // ERC-20 `transfer` inner ~52k; Tempo sponsorship overhead is
    // ~275k (fee_payer signature recovery + AlphaUSD fee transfer).
    // 500k is generous headroom — sponsor pays in AlphaUSD and only
    // consumed gas is debited, so over-budgeting costs nothing.
    let tx_hash = run_sponsored_tempo_call(&from_hex, vec![call], 500_000, "send $localharness")
        .await?;

    let short = tx_short_hash(&tx_hash);
    dom::swap_inner(
        "lh-transfer-msg",
        &format!("<span style=\"color:var(--accent)\">✓ sent (tx {short})</span>"),
    );
    if let Some(input) = dom::input_by_id("lh-transfer-amount") {
        input.set_value("");
    }
    // Refresh balance shown in the card. Cheap re-read; if it fails,
    // the next paint_tenant will pick it up. Don't bubble errors.
    if let super::tenant::Host::Tenant(name) = super::tenant::current() {
        super::paint_tenant(super::tenant::Host::Tenant(name.clone()), name).await;
    }
    Ok(())
}

/// 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> {
    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_digest_via_iframe(&sender_hash, 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}"))
}

fn is_address_hex(s: &str) -> bool {
    let stripped = s.trim_start_matches("0x").trim_start_matches("0X");
    stripped.len() == 40 && stripped.bytes().all(|b| b.is_ascii_hexdigit())
}

/// Parse a human-typed amount like `1.5` or `0.000001` into 18-decimal
/// token wei. Returns None on garbage input. Accepts up to 18 fractional
/// digits; truncates anything finer.
fn parse_token_amount(raw: &str) -> Option<u128> {
    let raw = raw.trim();
    if raw.is_empty() {
        return None;
    }
    let (whole_s, frac_s) = match raw.split_once('.') {
        Some((w, f)) => (w, f),
        None => (raw, ""),
    };
    let whole: u128 = if whole_s.is_empty() {
        0
    } else {
        whole_s.parse().ok()?
    };
    if frac_s.bytes().any(|b| !b.is_ascii_digit()) {
        return None;
    }
    let mut frac: u128 = 0;
    let mut scale: u128 = 1_000_000_000_000_000_000;
    for ch in frac_s.chars().take(18) {
        let d = ch.to_digit(10)? as u128;
        scale /= 10;
        frac = frac.checked_add(d.checked_mul(scale)?)?;
    }
    let whole_wei = whole.checked_mul(1_000_000_000_000_000_000)?;
    whole_wei.checked_add(frac)
}

/// ABI-encode `transfer(address,uint256)` — selector + padded address +
/// padded amount. Keccak the signature here so we don't depend on a
/// constant elsewhere.
fn encode_transfer_calldata(to_hex: &str, amount_wei: u128) -> Result<Vec<u8>, String> {
    use sha3::{Digest, Keccak256};
    let mut hasher = Keccak256::new();
    hasher.update(b"transfer(address,uint256)");
    let digest = hasher.finalize();
    let mut selector = [0u8; 4];
    selector.copy_from_slice(&digest[..4]);

    let to_bytes = parse_address(to_hex)?;
    let mut to_padded = [0u8; 32];
    to_padded[12..].copy_from_slice(&to_bytes);
    let mut amount_padded = [0u8; 32];
    amount_padded[16..].copy_from_slice(&amount_wei.to_be_bytes());

    let mut out = Vec::with_capacity(4 + 32 + 32);
    out.extend_from_slice(&selector);
    out.extend_from_slice(&to_padded);
    out.extend_from_slice(&amount_padded);
    Ok(out)
}

fn parse_address(hex: &str) -> Result<[u8; 20], String> {
    let stripped = hex.trim_start_matches("0x").trim_start_matches("0X");
    if stripped.len() != 40 {
        return Err(format!("address must be 40 hex chars, got {}", stripped.len()));
    }
    let mut out = [0u8; 20];
    let bytes = stripped.as_bytes();
    for i in 0..20 {
        let hi = hex_nibble(bytes[i * 2])?;
        let lo = hex_nibble(bytes[i * 2 + 1])?;
        out[i] = (hi << 4) | lo;
    }
    Ok(out)
}

fn hex_nibble(b: u8) -> Result<u8, String> {
    match b {
        b'0'..=b'9' => Ok(b - b'0'),
        b'a'..=b'f' => Ok(b - b'a' + 10),
        b'A'..=b'F' => Ok(b - b'A' + 10),
        _ => Err(format!("non-hex byte {b}")),
    }
}

fn bytes_to_hex_str(bytes: &[u8]) -> String {
    let mut s = String::with_capacity(2 + bytes.len() * 2);
    s.push_str("0x");
    for b in bytes {
        s.push_str(&format!("{b:02x}"));
    }
    s
}

fn tx_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..])
}

/// 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);

    // Apex shows a credit balance pill. Fire-and-forget the on-chain
    // read so the rest of the dropdown paints immediately; the pill
    // updates from "…" to "N LH" when the call resolves.
    if matches!(super::tenant::current(), super::tenant::Host::Apex) {
        wasm_bindgen_futures::spawn_local(async move {
            refresh_credits_pill().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);
                }
            }
            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");
            }
        });
    }
}

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

/// 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);

    // 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", "edit", "chat", "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(" "));
    }
}

/// Inject the feedback modal into the body (overlays everything).
fn feedback_open() {
    let Ok(doc) = dom::document() else { return };
    let Some(body) = doc.body() else { return };
    // If a modal already exists, focus the textarea instead of stacking.
    if let Some(_existing) = doc.get_element_by_id("feedback-modal") {
        if let Some(t) = dom::textarea_by_id("feedback-text") {
            let _ = t.focus();
        }
        return;
    }
    let _ = body.insert_adjacent_html(
        "beforeend",
        &templates::feedback_modal().into_string(),
    );
    if let Some(t) = dom::textarea_by_id("feedback-text") {
        let _ = t.focus();
    }
}

fn feedback_close() {
    if let Some(el) = dom::by_id("feedback-modal") {
        if let Some(parent) = el.parent_element() {
            let _ = parent.remove_child(&el);
        }
    }
}

fn feedback_submit() {
    let Some(textarea) = dom::textarea_by_id("feedback-text") else {
        return;
    };
    let text = textarea.value().trim().to_string();
    if text.is_empty() {
        return; // silent no-op per [[feedback-no-explanatory-validation]]
    }
    if text.len() > 2048 {
        dom::swap_inner(
            "feedback-msg",
            "<span style=\"color:var(--error)\">too long</span>",
        );
        return;
    }

    // Need an apex wallet to sign. The visitor address from verify
    // state is what the iframe signer controls.
    let from_hex = super::APP.with(|cell| {
        use super::VerifyState;
        match &cell.borrow().verify_state {
            VerifyState::Verified { address } => Some(address.clone()),
            VerifyState::Visitor { visitor_address, .. } => Some(visitor_address.clone()),
            _ => cell.borrow().wallet.as_ref().map(|w| w.address_hex()),
        }
    });
    let Some(from_hex) = from_hex else {
        dom::swap_inner(
            "feedback-msg",
            "<span style=\"color:var(--error)\">claim an identity first</span>",
        );
        return;
    };

    dom::swap_inner(
        "feedback-msg",
        "<span style=\"color:var(--muted)\">signing…</span>",
    );
    wasm_bindgen_futures::spawn_local(async move {
        // Mirror to local OPFS first so the user always has a copy
        // even if the on-chain leg fails. Best-effort — log and
        // continue on error.
        if let Err(err) = append_feedback_local(&text).await {
            web_sys::console::warn_1(&JsValue::from_str(&format!(
                "feedback local copy: {err}"
            )));
        }
        match submit_feedback_onchain(&from_hex, &text).await {
            Ok(tx_hash) => {
                let short = tx_short_hash(&tx_hash);
                dom::swap_inner(
                    "feedback-msg",
                    &format!(
                        "<span style=\"color:var(--accent)\">✓ on-chain (tx {short})</span>"
                    ),
                );
                if let Some(window) = web_sys::window() {
                    let cb = Closure::<dyn FnMut()>::new(|| {
                        feedback_close();
                    });
                    let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0(
                        cb.as_ref().unchecked_ref(),
                        1200,
                    );
                    cb.forget();
                }
            }
            Err(err) => {
                web_sys::console::warn_1(&JsValue::from_str(&format!(
                    "feedback on-chain: {err}"
                )));
                dom::swap_inner(
                    "feedback-msg",
                    "<span style=\"color:var(--error)\">on-chain submit failed (saved locally)</span>",
                );
            }
        }
    });
}

/// Sign + submit `FeedbackFacet.submitFeedback(text)` on the diamond
/// via the apex iframe signer. The event log on the registry is the
/// canonical store; the developer harvests via `eth_getLogs`. Caller's
/// gas paid by the apex wallet — Tempo allows contract calls.
async fn submit_feedback_onchain(from_hex: &str, text: &str) -> Result<String, String> {
    let calldata = encode_submit_feedback_calldata(text);
    let registry_addr = parse_address(super::registry::REGISTRY_ADDRESS)?;
    let call = crate::tempo_tx::TempoCall {
        to: registry_addr,
        value_wei: 0,
        input: calldata,
    };
    // String-emitting events scale with byte length (~12k base +
    // ~200 gas/byte log data). 2048-byte upper bound + base ~150k
    // for the inner call. Tempo sponsorship overhead adds ~275k.
    // 800k is generous headroom for any reasonable feedback length.
    run_sponsored_tempo_call(from_hex, vec![call], 800_000, "submit feedback").await
}

/// ABI-encode `submitFeedback(string)`. Layout: selector + offset(0x20)
/// + length + bytes (right-padded to 32-byte multiple).
fn encode_submit_feedback_calldata(text: &str) -> Vec<u8> {
    use sha3::{Digest, Keccak256};
    let mut hasher = Keccak256::new();
    hasher.update(b"submitFeedback(string)");
    let digest = hasher.finalize();
    let mut selector = [0u8; 4];
    selector.copy_from_slice(&digest[..4]);

    let bytes = text.as_bytes();
    let len = bytes.len();
    let padded_len = len.div_ceil(32) * 32;

    let mut out = Vec::with_capacity(4 + 32 + 32 + padded_len);
    out.extend_from_slice(&selector);
    // offset to dynamic head — 0x20 (one dynamic arg after a 32-byte slot)
    let mut offset = [0u8; 32];
    offset[31] = 0x20;
    out.extend_from_slice(&offset);
    // length
    let mut len_bytes = [0u8; 32];
    len_bytes[24..].copy_from_slice(&(len as u64).to_be_bytes());
    out.extend_from_slice(&len_bytes);
    // payload + zero-pad
    out.extend_from_slice(bytes);
    out.resize(4 + 32 + 32 + padded_len, 0);
    out
}

/// Append a feedback entry to `.lh_feedback.txt` in this origin's OPFS
/// as a local-first mirror. The canonical store is the on-chain event
/// log; this file is a per-device safety net for when the on-chain leg
/// is unreachable (offline, rate-limited, etc.). One line per entry:
/// `ISO-timestamp\tTEXT\n`.
async fn append_feedback_local(text: &str) -> Result<(), String> {
    use crate::filesystem::Filesystem;
    let fs = super::shared_opfs();
    let existing = fs.read(".lh_feedback.txt").await.unwrap_or_default();
    let now = js_sys::Date::new_0().to_iso_string().as_string().unwrap_or_default();
    let entry = format!("{now}\t{text}\n");
    let mut combined = existing;
    combined.extend_from_slice(entry.as_bytes());
    fs.write_atomic(".lh_feedback.txt", &combined)
        .await
        .map_err(|e| format!("{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.iter().any(|c| *c == 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);
}

/// One-shot first-day credit claim, fired right after a fresh apex
/// wallet is created so the user lands with a starter balance. The
/// call is sponsored — the user holds nothing, and the chain still
/// mints credits to the user's address because they're the
/// `msg.sender` of the inner `claimDaily()`. Soft-fail: if the chain
/// or sponsor hiccups, identity is still saved and the user can
/// retry from the admin "claim credits" button.
async fn run_initial_credit_claim(signer: k256::ecdsa::SigningKey) {
    dom::swap_inner(
        "identity-msg",
        "<span style=\"color:var(--muted)\">claiming starter credits…</span>",
    );
    let fee_payer = match super::sponsor::signer() {
        Ok(k) => k,
        Err(err) => {
            web_sys::console::warn_1(&JsValue::from_str(&format!("sponsor: {err}")));
            return;
        }
    };
    match super::registry::claim_daily_sponsored(
        &signer,
        &fee_payer,
        super::registry::ALPHA_USD_ADDRESS,
    )
    .await
    {
        Ok(tx) => {
            web_sys::console::log_1(&JsValue::from_str(&format!(
                "initial claimDaily tx: {tx}"
            )));
        }
        Err(err) => {
            web_sys::console::warn_1(&JsValue::from_str(&format!(
                "initial claimDaily: {err}"
            )));
        }
    }
}

/// Inline-confirmed reset: nuke every entry at OPFS root, reload.
/// Replaces the old `window.confirm()` flow per [[feedback-no-js-alerts]].
fn reset_confirm_pressed() {
    wasm_bindgen_futures::spawn_local(async move {
        let fs = super::shared_opfs();
        if let Ok(entries) = fs.read_dir("").await {
            for entry in entries {
                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",
                &format!(
                    "<span style=\"color:var(--error)\">{err}</span>"
                ),
            );
            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",
                    &format!(
                        "<span style=\"color:var(--error)\">save failed: {err}</span>"
                    ),
                );
            }
        }
    });
}

/// 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 reset_pressed() {
    super::APP.with(|cell| {
        let mut app = cell.borrow_mut();
        app.agent = None;
        app.session_key = None;
        app.turn_count = 0;
        app.pending_history = None;
    });
    dom::swap_inner("transcript", "");
    // No status text — clearing is silent.
    // Drop the persisted history too — a reload after reset starts
    // fresh, matching the user's expectation of "new conversation."
    wasm_bindgen_futures::spawn_local(async move {
        super::history::clear().await;
    });
    if let Some(prompt) = dom::textarea_by_id("prompt") {
        prompt.focus().ok();
    }
}

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);
}