synaps-tui 0.3.5

Terminal UI layer — ratatui, crossterm, syntect, tachyonfx
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
//! Chat TUI binary — event loop, terminal setup, module wiring.

mod app;
mod commands;
mod draw;
mod gamba;
mod help_find;
mod helpers;
mod highlight;
mod input;
mod lifecycle;
mod lightbox;
mod markdown;
mod models;
mod plugins;
mod render;
mod render_model;
mod render_thread;
mod settings;
mod sidecar;
mod signals;
mod stream_handler;
mod theme;
mod toast;
mod viewport;

use app::{App, ChatMessage, THINKING_PLACEHOLDER};
use commands::CommandAction;
use draw::{boot_effect, build_render_model, quit_effect};
use helpers::{apply_setting, fetch_usage, rebuild_display_messages};
use input::InputAction;
use lifecycle::setup_terminal;
use render_thread::spawn_render_thread;
use stream_handler::StreamAction;

use crossterm::event::EventStream;
use futures::StreamExt;
use serde_json::json;
use std::sync::atomic::Ordering;
use std::time::Instant;
use synaps_cli::core::session_index::SessionIndexRecord;
use synaps_cli::runtime::compaction::compact_conversation;
use synaps_cli::{CancellationToken, Result, Runtime, Session, StreamEvent};

pub async fn run(
    continue_session: Option<Option<String>>,
    system: Option<String>,
    profile: Option<String>,
    no_extensions: bool,
) -> Result<()> {
    // ── Engine boot ──
    let boot = synaps_cli::engine::setup::boot(synaps_cli::engine::setup::EngineOpts {
        continue_session: continue_session.clone(),
        system,
        profile,
        no_extensions,
    })
    .await?;

    let mut runtime = boot.runtime;
    let mut config = boot.config;
    let registry = boot.registry;
    let keybind_registry = boot.keybind_registry;
    let mcp_server_count = boot.mcp_server_count;
    let system_prompt_path = boot.system_prompt_path;

    // Build App from engine boot results
    let mut app = if boot.continued {
        let mut app = App::new(boot.session.clone());
        app.api_messages = boot.api_messages;
        app.total_input_tokens = boot.total_input_tokens;
        app.total_output_tokens = boot.total_output_tokens;
        app.session_cost = boot.session_cost;
        app.abort_context = boot.abort_context;
        // mem::take avoids deep-cloning the full history just to satisfy
        // the borrow checker (P5 in REVIEW.md).
        let msgs = std::mem::take(&mut app.api_messages);
        rebuild_display_messages(&msgs, &mut app);
        app.api_messages = msgs;
        app.push_msg(ChatMessage::System(format!(
            "resumed session {}",
            boot.session.id
        )));
        if let Some(ref info) = boot.continue_info {
            if let Some(ref via) = info.resolved_via {
                app.push_msg(ChatMessage::System(format!(
                    "  ↳ resolved via {} '{}'",
                    via, info.query
                )));
            }
        }
        if app.abort_context.is_some() {
            app.push_msg(ChatMessage::System(
                "⚠ abort context from previous session will be injected into next message"
                    .to_string(),
            ));
        }
        app
    } else {
        App::new(boot.session)
    };
    app.keybinds = Some(keybind_registry.clone());
    app.last_turn_context_window = runtime.context_window();

    // Surface config parse warnings once at startup (unknown keys, bad values).
    for w in &config.warnings {
        app.push_msg(ChatMessage::System(format!("⚠ config: {}", w)));
    }

    // First-run guidance: no Anthropic credentials and no provider keys means
    // the first message will fail — tell the user up front instead.
    {
        let has_anthropic = synaps_cli::auth::load_auth()
            .ok()
            .flatten()
            .map(|a| a.anthropic.auth_type == "oauth" && !a.anthropic.access.is_empty())
            .unwrap_or(false)
            || std::env::var("ANTHROPIC_API_KEY").is_ok();
        if !has_anthropic && config.provider_keys.is_empty() {
            app.push_msg(ChatMessage::System(
                "👋 No credentials found. To get started:\n   • `synaps login` — sign in with Claude Pro/Max (OAuth)\n   • or set ANTHROPIC_API_KEY in your environment\n   • or add `provider.<name> = <key>` to ~/.synaps-cli/config (groq, openrouter, …) and pick with /model".to_string(),
            ));
        }
    }

    if mcp_server_count > 0 {
        tracing::info!(
            "{} MCP servers available (use connect_mcp_server to activate)",
            mcp_server_count
        );
    }

    // ── Terminal setup + render thread ──
    //
    // The Terminal is moved into the render thread immediately after creation.
    // The main task never touches it again.  All terminal I/O (draw, clear,
    // teardown) goes through `render_handle`.
    //
    // Terminal size for build_render_model: we call crossterm::terminal::size()
    // directly — it reads the TTY fd without needing the Terminal object.
    // See render_thread.rs module comment for the design rationale.
    let terminal = setup_terminal()?;
    let (render_handle, boot_done, exit_done) = spawn_render_thread(terminal);
    // Boot effect is sent via the command channel so the render thread owns it.
    render_handle.send_boot_fx(boot_effect());

    let mut event_reader = EventStream::new();
    let (shutdown_signal_tx, mut shutdown_signal_rx) = tokio::sync::mpsc::unbounded_channel();
    let shutdown_signal_task = signals::spawn_shutdown_signal_task(shutdown_signal_tx);
    let mut stream: Option<std::pin::Pin<Box<dyn futures::Stream<Item = StreamEvent> + Send>>> =
        None;
    let (secret_prompt_tx, secret_prompt_rx) = tokio::sync::mpsc::unbounded_channel();
    let secret_prompt_handle = synaps_cli::tools::SecretPromptHandle::new(secret_prompt_tx);
    let secret_prompt_rx = std::sync::Arc::new(std::sync::Mutex::new(secret_prompt_rx));
    let mut secret_prompts = synaps_cli::tools::SecretPromptQueue::new();
    let mut cancel_token: Option<CancellationToken> = None;
    let mut steer_tx: Option<tokio::sync::mpsc::UnboundedSender<String>> = None;

    // ── Engine-managed background tasks (inbox watcher, socket, extensions) ──
    let background = boot.background;
    let ext_mgr_shared = boot.ext_manager;

    // Legacy sidecar key migration
    migrate_sidecar_toggle_key_to_claimed_plugins(&registry.lifecycle_claims());

    if !boot.no_extensions {
        app.extension_loader_running = true;
        app.toasts.upsert(
            toast::Toast::new("extension-loader", "Discovering extensions…")
                .titled("Extensions")
                .at(toast::ToastPosition::TOP_CENTER)
                .ttl(None),
        );
        synaps_cli::extensions::loader::spawn_discover_and_load(
            std::sync::Arc::clone(&ext_mgr_shared),
            app.extension_loader_tx.clone(),
        );
    }

    // on_session_start hook already fired by engine::setup::boot()

    // ── Event loop ──
    // Track whether the render thread currently has an active boot or exit
    // effect.  The render thread owns the actual Effect values; we track
    // "has been sent and not yet done" on the main side for the tick throttle.
    let mut boot_fx_sent  = true;  // boot_effect() is sent at startup above
    let mut exit_fx_sent  = false;
    let mut last_draw = Instant::now() - std::time::Duration::from_secs(1);
    loop {
        // Only draw when something actually changed. During streaming, coalesce
        // redraws to ~10fps — deltas (and the spinner) arrive far faster than the
        // eye can read, and rebuilding/republishing the whole RenderModel per
        // frame is what burns a core (#131: ~60-69% of a core at 60fps; the
        // spinner only needs ~10fps). The `!app.streaming` short-circuit below
        // still renders the final/idle frame immediately, so end-of-turn state
        // never lags. (Was 16ms/60fps; before that 33ms/30fps.)
        let throttle = std::time::Duration::from_millis(100);
        if app.needs_redraw && (!app.streaming || last_draw.elapsed() >= throttle) {
            // Terminal lives on the render thread — get size via the crossterm
            // TTY syscall directly (doesn't need the Terminal object).
            // Skip the frame entirely if the reported size is 0×0 (terminal not
            // yet ready, or a transient resize event) — publishing a 0×0 model
            // would produce layout artifacts.
            let term_size = match crossterm::terminal::size() {
                Ok((w, h)) if w > 0 && h > 0 => ratatui::layout::Size { width: w, height: h },
                _ => continue,
            };
            app.needs_redraw = false;
            last_draw = Instant::now();
            if let Some(model) = build_render_model(
                &mut app,
                &runtime,
                &registry,
                &secret_prompts,
                term_size,
            ) {
                render_handle.publish(model);
            }
        }

        tokio::select! {

            // ── OS shutdown signals: Ctrl-C from terminal, SIGTERM from systemd/tmux/SSH ──
            signal = shutdown_signal_rx.recv() => {
                if let Some(signal) = signal {
                    tracing::info!(signal = signals::signal_label(signal), "chat UI shutdown signal received");
                    // All OS signals map to ImmediateExit (see signals.rs).
                    // The /quit command sends SpawnExitFx to the render thread
                    // and does NOT go through this path, so removing AnimatedExit
                    // from signals does not affect interactive quit.
                    let signals::ShutdownAction::ImmediateExit = signals::shutdown_action(signal);
                    tracing::info!("immediate exit on {:?}", signal);
                    // Cancel any in-flight stream so the tool/subagent is not
                    // orphaned for the full watchdog window.
                    if let Some(ref ct) = cancel_token { ct.cancel(); }
                    // Abort any in-flight compaction so it doesn't hold state
                    // open past the teardown budget.
                    if let Some(ref h) = app.compact_task { h.abort(); }
                    // Fall through to unified bounded-teardown below the loop.
                    break;
                }
            }

            // ── Ping results — fires when a model ping completes ──
            result = app.ping_rx.recv() => {
                match result {
                    Some((key, status, ms)) => {
                        if app.ping_print {
                            let detail = match status {
                                synaps_cli::runtime::openai::ping::PingStatus::Online => format!("{}ms", ms),
                                synaps_cli::runtime::openai::ping::PingStatus::RateLimited => "429 rate limited".to_string(),
                                synaps_cli::runtime::openai::ping::PingStatus::Unauthorized => "401 unauthorized".to_string(),
                                synaps_cli::runtime::openai::ping::PingStatus::NotFound => "404 not found".to_string(),
                                synaps_cli::runtime::openai::ping::PingStatus::Timeout => "timeout".to_string(),
                                synaps_cli::runtime::openai::ping::PingStatus::Error => "error".to_string(),
                            };
                            app.push_msg(ChatMessage::System(format!("  {} {:<50} — {}", status.icon(), key, detail)));
                            app.ping_pending = app.ping_pending.saturating_sub(1);
                            if app.ping_pending == 0 {
                                app.ping_print = false;
                            }
                        }
                        app.model_health.insert(key, (status, ms));
                        app.request_redraw();
                    }
                    None => {
                        // All ping tasks done (tx dropped) — stop printing
                        app.ping_print = false;
                    }
                }
            }

            // ── Expanded model-list results ──
            result = app.model_list_rx.recv() => {
                if let Some((provider_key, models_result)) = result {
                    if let Some(state) = app.models.as_mut() {
                        models::set_expanded_models(state, &provider_key, models_result);
                    }
                    app.request_redraw();
                }
            }

            // ── Async extension loader progress ──
            event = app.extension_loader_rx.recv(), if app.extension_loader_running => {
                if let Some(event) = event {
                    handle_extension_loader_event(&mut app, &runtime, event, &ext_mgr_shared).await;
                } else {
                    app.extension_loader_running = false;
                    app.toasts.dismiss("extension-loader");
                }
                app.request_redraw();
            }

            // ── Widget events from background extension notification watchers ──
            Some(widget_event) = app.widget_rx.recv() => {
                // Only redraw when the widget's VISIBLE content actually changed.
                // Plugins (d20/jawz-widget/synaps-tasks) re-send unchanged widgets
                // on a poll loop; redrawing on every one pinned the render loop at
                // ~30% CPU at idle (#119). The dirty-check in upsert/dismiss makes an
                // idle session genuinely idle.
                if handle_widget_event(&mut app, widget_event) {
                    app.request_redraw();
                }
            }

            // ── Sidecar events — multiplexed across all hosted sidecars (Phase 8 8B) ──
            sidecar_event = async {
                if app.sidecars.is_empty() {
                    let _: () = std::future::pending().await;
                    unreachable!()
                } else {
                    // Collect (plugin_id, &mut manager) and race them.
                    let mut futures = Vec::with_capacity(app.sidecars.len());
                    for (pid, v) in app.sidecars.iter_mut() {
                        let pid = pid.clone();
                        futures.push(Box::pin(async move {
                            let ev = v.manager.next_event().await;
                            (pid, ev)
                        }));
                    }
                    let ((pid, ev), _, _) = futures::future::select_all(futures).await;
                    (pid, ev)
                }
            } => {
                let (pid, sidecar_event) = sidecar_event;
                if let Some(event) = sidecar_event {
                    self::sidecar::handle_event(&mut app, &pid, event);
                    app.request_redraw();
                }
            }

            // ── Event bus wake — fires instantly when an event is pushed to the queue ──
            _ = runtime.event_queue().notified() => {
                let mut event_received = false;
                while let Some(event) = runtime.event_queue().pop() {
                    event_received = true;
                    let formatted = synaps_cli::events::format_event_for_agent(&event);
                    let severity_str = event.content.severity
                        .as_ref()
                        .map(|s| s.as_str().to_string())
                        .unwrap_or_else(|| "medium".to_string());
                    app.push_msg(ChatMessage::Event {
                        source: event.source.source_type.clone(),
                        severity: severity_str,
                        text: event.content.text.clone(),
                    });

                    if app.streaming || app.compact_task.is_some() {
                        // Steer into active stream if possible, otherwise buffer
                        let steered = steer_tx.as_ref()
                            .map(|tx| tx.send(formatted.clone()).is_ok())
                            .unwrap_or(false);
                        if !steered {
                            app.pending_events.push(formatted);
                        }
                    } else {
                        app.api_messages.push(serde_json::json!({
                            "role": "user",
                            "content": formatted
                        }));
                    }
                    app.invalidate();
                }

                // Auto-trigger model turn when idle — only if we actually received events
                if event_received && !app.streaming && stream.is_none() && app.compact_task.is_none() && !app.api_messages.is_empty() {
                    if let Some(last) = app.api_messages.last() {
                        if last["role"].as_str() == Some("user") {
                            let ct = CancellationToken::new();
                            let (s_tx, s_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
                            app.streaming = true;
                            app.spinner_frame = 0;
                            stream = Some(runtime.run_stream_with_messages(app.api_messages.clone(), ct.clone(), Some(s_rx), Some(secret_prompt_handle.clone()), false).await);
                            app.push_msg(ChatMessage::Thinking(THINKING_PLACEHOLDER.to_string()));
                            cancel_token = Some(ct);
                            steer_tx = Some(s_tx);
                        }
                    }
                }
            }

            // ── Tick: animations + spinner (~60fps when active) ──
            _ = tokio::time::sleep(std::time::Duration::from_millis(16)), if boot_fx_sent || exit_fx_sent || app.streaming || app.compact_task.is_some() || app.messages.is_empty() || app.logo_dismiss_t.is_some() || app.logo_build_t.is_some() || app.gamba_child.is_some() || secret_prompts.is_active() || !app.toasts.is_empty() || app.plugins.as_ref().is_some_and(|p| p.is_install_active()) => {
                // Active animations/effects always need a redraw each tick.
                // messages.is_empty() = idle logo screen — its color gradient
                // is time-based and needs ticking too (S206 regression: the
                // dirty-flag loop froze it until first keystroke).
                // Update local effect-sent flags from the render thread's done signals.
                if boot_fx_sent && boot_done.load(Ordering::Acquire) {
                    boot_fx_sent = false;
                }
                if exit_fx_sent || boot_fx_sent || app.streaming || app.logo_build_t.is_some() || app.logo_dismiss_t.is_some() || app.gamba_child.is_some() || app.messages.is_empty() {
                    app.request_redraw();
                }
                secret_prompts.poll_requests(&secret_prompt_rx);
                if app.toasts.tick() {
                    app.invalidate();
                }
                // Tick the in-flight plugin install spinner and reap the
                // background clone task once it finishes.
                let mut install_did_work = false;
                let mut install_finished = false;
                if let Some(plugins_state) = app.plugins.as_mut() {
                    if plugins_state.is_install_active() {
                        plugins_state.tick_install_spinner();
                        install_did_work = true;
                        if plugins_state.install_ready_to_reap() {
                            install_finished = true;
                        }
                    }
                }
                if install_finished {
                    if let Some(plugins_state) = app.plugins.as_mut() {
                        self::plugins::actions::complete_pending_install_clone(
                            plugins_state, &registry, &config,
                        ).await;
                    }
                }
                if install_did_work || install_finished {
                    app.invalidate();
                }
                let message_animation_needs_clear = app.needs_clear_for_animation_redraw();
                if message_animation_needs_clear
                    && crossterm::terminal::size().is_ok_and(|(w, h)| w > 0 && h > 0) {
                        render_handle.send_clear();
                    }
                if let Some(ref mut t) = app.logo_build_t {
                    *t += 0.025;
                    if *t >= 1.0 { app.logo_build_t = None; }
                    app.request_redraw();
                }
                if let Some(ref mut t) = app.logo_dismiss_t {
                    *t += 0.04;
                    if *t >= 1.0 { app.logo_dismiss_t = None; }
                    app.request_redraw();
                }
                if app.advance_animations() {
                    // Spinner ticks only affect the tail message (THINKING_PLACEHOLDER,
                    // active tool animation). Mark just the last slot dirty instead of
                    // full invalidation — O(1) instead of O(n) per frame.
                    app.invalidate_last();
                }
                if let Some(msg) = app.check_gamba_exited() {
                    // check_gamba_exited() already called restore_terminal();
                    // resume the render thread now that we own the terminal again.
                    render_handle.resume();
                    app.push_msg(ChatMessage::System(msg));
                    app.invalidate(); // invalidate already sets needs_redraw
                }
                // Poll background compaction task
                if app.compact_task.as_ref().is_some_and(|t| t.is_finished()) {
                    let handle = app.compact_task.take().unwrap();
                    let msg_count = app.api_messages.len();
                    match handle.await {
                        Ok(Ok(summary)) => {
                            let old_id = app.session.id.clone();
                            // Find chains pointing at the old head before we swap
                            let chains_to_advance = synaps_cli::chain::find_all_chains_by_head(&old_id)
                                .unwrap_or_default();
                            let new_session = Session::new_from_compaction(&app.session, summary.clone());
                            let new_id = new_session.id.clone();
                            // Save new session FIRST — if we crash after this but before
                            // saving old, the new session still exists and chain is intact
                            app.session = new_session;
                            app.api_messages = app.session.api_messages.clone();
                            app.total_input_tokens = 0;
                            app.total_output_tokens = 0;
                            app.session_cost = 0.0;
                            let msgs = app.api_messages.clone();
                            rebuild_display_messages(&msgs, &mut app);
                            app.save_session().await;
                            // Load old session fresh from disk and update its forward link
                            match synaps_cli::core::session::Session::load(&old_id) {
                                Ok(mut old_session) => {
                                    old_session.compacted_into = Some(new_id.clone());
                                    // Clear name from old session — it transferred to the new one
                                    old_session.name = None;
                                    old_session.save().await.ok();
                                }
                                Err(e) => {
                                    tracing::warn!("Failed to update old session {}: {}", old_id, e);
                                }
                            }
                            let compaction_event = synaps_cli::extensions::hooks::events::HookEvent::on_compaction(
                                &old_id,
                                &new_id,
                                &summary,
                                msg_count,
                                serde_json::json!({"source": "manual"}),
                            );
                            let _ = runtime.hook_bus().emit(&compaction_event).await;

                            // Advance any named chains that pointed at the old head
                            for ch in &chains_to_advance {
                                match synaps_cli::chain::save_chain(&ch.name, &new_id) {
                                    Ok(()) => {
                                        app.push_msg(ChatMessage::System(format!(
                                            "chain '{}' advanced: {}{}",
                                            ch.name, old_id, new_id
                                        )));
                                    }
                                    Err(e) => {
                                        app.push_msg(ChatMessage::Error(format!(
                                            "failed to advance chain '{}': {}", ch.name, e
                                        )));
                                    }
                                }
                            }
                            // Flush any events that arrived during compaction
                            for formatted in app.pending_events.drain(..) {
                                app.api_messages.push(serde_json::json!({
                                    "role": "user",
                                    "content": formatted
                                }));
                            }
                            if let Some(queued) = app.queued_message.take() {
                                app.api_messages.push(serde_json::json!({"role": "user", "content": queued}));
                                app.push_msg(ChatMessage::System(format!("queued message restored: {}", queued)));
                            }
                            app.push_msg(ChatMessage::System(format!(
                                "✓ compacted {} messages → new session {} (from {})",
                                msg_count, new_id, old_id
                            )));
                        }
                        Ok(Err(e)) => {
                            app.push_msg(ChatMessage::Error(format!("compaction failed: {}", e)));
                        }
                        Err(e) => {
                            app.push_msg(ChatMessage::Error(format!("compaction task panicked: {}", e)));
                        }
                    }
                    app.status_text = None;
                    app.invalidate();
                }
                if exit_done.load(Ordering::Acquire) {
                    break;
                }
                continue;
            }

            // ── Input: keyboard, mouse, paste ──
            maybe_event = event_reader.next(), if app.gamba_child.is_none() => {
                match maybe_event {
                    Some(Ok(event)) => {
                        if secret_prompts.is_active() {
                            match event {
                                crossterm::event::Event::Key(key) => match key.code {
                                    crossterm::event::KeyCode::Enter => secret_prompts.submit(),
                                    crossterm::event::KeyCode::Esc => secret_prompts.cancel(),
                                    crossterm::event::KeyCode::Backspace => secret_prompts.backspace(),
                                    crossterm::event::KeyCode::Char(c) => secret_prompts.push_char(c),
                                    _ => {}
                                },
                                crossterm::event::Event::Paste(text) => {
                                    for ch in text.chars() {
                                        secret_prompts.push_char(ch);
                                    }
                                }
                                _ => {}
                            }
                            app.request_redraw();
                            continue;
                        }
                        let is_streaming = app.streaming;
                        // Scope the registry read guard to this block so it is
                        // provably released before any later `.await`
                        // (clippy::await_holding_lock) — the guard never spans a
                        // yield point.
                        let action = {
                            let kb_guard = keybind_registry.read().expect("keybind registry poisoned");
                            input::handle_event(event, &mut app, &runtime, is_streaming, &registry, &kb_guard)
                        };
                        // Input events (keys, mouse, paste, resize) almost always
                        // change visible state (cursor, input buffer, scroll).
                        app.request_redraw();
                        match action {
                            InputAction::None => {}
                            InputAction::HelpFindOutcome => {}
                            InputAction::Quit => {
                                render_handle.send_exit_fx(quit_effect());
                                exit_fx_sent = true;
                            }
                            InputAction::Abort => {
                                if let Some(ref ct) = cancel_token { ct.cancel(); }
                                app.capture_abort_context();
                                if let Some(ref q) = app.queued_message.take() {
                                    app.push_msg(ChatMessage::System(format!("dequeued: {}", q)));
                                }
                                // Flush any events that arrived during streaming
                                for formatted in app.pending_events.drain(..) {
                                    app.api_messages.push(serde_json::json!({
                                        "role": "user",
                                        "content": formatted
                                    }));
                                }
                                stream = None;
                                cancel_token = None;
                                steer_tx = None;
                                app.streaming = false;
                                app.subagents.clear();
                                // Cancel all running reactive subagents
                                {
                                    let mut registry = runtime.subagent_registry().lock().unwrap();
                                    for handle in registry.iter_mut_handles() {
                                        if handle.status() == synaps_cli::runtime::subagent::SubagentStatus::Running {
                                            handle.cancel();
                                        }
                                    }
                                }
                                let abort_msg = if app.abort_context.is_some() {
                                    "aborted — context saved for next message"
                                } else {
                                    "aborted"
                                };
                                app.drop_empty_thinking();
                                app.push_msg(ChatMessage::Error(abort_msg.to_string()));
                                app.save_session().await;
                            }
                            InputAction::SlashCommand(cmd, arg) => {
                                let kb_snapshot = {
                                    let g = keybind_registry.read().expect("keybind registry poisoned");
                                    g.clone()
                                };
                                match commands::handle_command(&cmd, &arg, &mut app, &mut runtime, &system_prompt_path, &registry, &kb_snapshot).await {
                                    CommandAction::None => {}
                                    CommandAction::StartStream => {} // reserved for future use
                                    CommandAction::Quit => {
                                        render_handle.send_exit_fx(quit_effect());
                                        exit_fx_sent = true;
                                    }
                                    CommandAction::LaunchGamba => {
                                        drop(event_reader);
                                        // Pause the render thread BEFORE touching the terminal —
                                        // eliminates the stdout race between terminal.draw() and our mode changes.
                                        render_handle.pause();
                                        match app.launch_gamba() {
                                            Ok(()) => {}
                                            Err(msg) => {
                                                // launch failed — restore and resume
                                                render_handle.resume();
                                                app.push_msg(ChatMessage::Error(msg));
                                            }
                                        }
                                        // If gamba launched OK, resume is sent by reclaim/check_gamba_exited.
                                        event_reader = EventStream::new();
                                    }
                                    CommandAction::OpenModels => {
                                        app.models = Some(models::ModelsModalState::new());
                                    }
                                    CommandAction::OpenSettings => {
                                        app.settings = Some(settings::SettingsState::new());
                                    }
                                    CommandAction::OpenPlugins => {
                                        let path = synaps_cli::skills::state::PluginsState::default_path();
                                        match synaps_cli::skills::state::PluginsState::load_from(&path) {
                                            Ok(file) => {
                                                app.plugins = Some(plugins::PluginsModalState::new(file));
                                            }
                                            Err(e) => {
                                                app.push_msg(ChatMessage::Error(format!(
                                                    "failed to load plugins.json: {}", e
                                                )));
                                            }
                                        }
                                    }
                                    CommandAction::OpenHelpFind { query } => {
                                        let registry = synaps_cli::help::HelpRegistry::new(
                                            synaps_cli::help::builtin_entries(),
                                            registry.plugin_help_entries(),
                                        );
                                        app.help_find = Some(synaps_cli::help::HelpFindState::new(
                                            registry.entries().to_vec(),
                                            &query,
                                        ));
                                    }
                                    CommandAction::ReloadPlugins => {
                                        synaps_cli::skills::reload_registry(&registry, &config);
                                        app.push_msg(ChatMessage::System("plugins reloaded".to_string()));
                                    }
                                    CommandAction::LoadSkill { skill, arg } => {
                                        use synaps_cli::skills::tool::LoadSkillTool;

                                        let tool_use_id = format!("toolu_skill_{}", uuid::Uuid::new_v4().simple());
                                        let body = LoadSkillTool::format_body(&skill);

                                        app.api_messages.push(json!({
                                            "role": "assistant",
                                            "content": [{
                                                "type": "tool_use",
                                                "id": tool_use_id,
                                                "name": "load_skill",
                                                "input": {"skill": skill.name.clone()}
                                            }]
                                        }));
                                        app.api_messages.push(json!({
                                            "role": "user",
                                            "content": [{
                                                "type": "tool_result",
                                                "tool_use_id": tool_use_id,
                                                "content": body
                                            }]
                                        }));
                                        let display_name = match &skill.plugin {
                                            Some(p) => format!("{}:{}", p, skill.name),
                                            None => skill.name.clone(),
                                        };
                                        app.push_msg(ChatMessage::System(format!("loaded skill: {}", display_name)));

                                        if !arg.is_empty() {
                                            app.api_messages.push(json!({"role": "user", "content": arg.clone()}));
                                            app.push_msg(ChatMessage::User(arg));
                                        }
                                        // Start stream — mirror InputAction::Submit stream-start pattern.
                                        let ct = CancellationToken::new();
                                        let (s_tx, s_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
                                        app.status_text = Some("connecting…".to_string());
                                        app.streaming = true;
                                        app.spinner_frame = 0;
                                        let term_size = crossterm::terminal::size().map(|(w, h)| ratatui::layout::Size { width: w, height: h }).unwrap_or_default();
                                        if let Some(model) = build_render_model(&mut app, &runtime, &registry, &secret_prompts, term_size) {
                                            render_handle.publish(model);
                                        }
                                        stream = Some(runtime.run_stream_with_messages(app.api_messages.clone(), ct.clone(), Some(s_rx), Some(secret_prompt_handle.clone()), false).await);
                                        app.status_text = None;
                                        app.push_msg(ChatMessage::Thinking(THINKING_PLACEHOLDER.to_string()));
                                        cancel_token = Some(ct);
                                        steer_tx = Some(s_tx);
                                    }
                                    CommandAction::PluginCommand { command, arg } => {
                                        if matches!(
                                            command.backend,
                                            synaps_cli::skills::registry::RegisteredPluginCommandBackend::Interactive { .. }
                                        ) {
                                            let manager = ext_mgr_shared.read().await;
                                            commands::execute_interactive_plugin_command_events(
                                                &command,
                                                &arg,
                                                &manager,
                                                &mut app,
                                            ).await;
                                        } else {
                                            commands::execute_command_action(
                                                CommandAction::PluginCommand { command, arg },
                                                &mut app,
                                                &runtime,
                                            ).await;
                                        }
                                    }
                                    CommandAction::Compact { custom_instructions } => {
                                        // Need at least 2 full turns (user + assistant = 2 messages each).
                                        if app.api_messages.len() < 4 {
                                            app.push_msg(ChatMessage::System(
                                                "nothing to compact (need at least 2 turns)".to_string(),
                                            ));
                                        } else if app.compact_task.is_some() {
                                            app.push_msg(ChatMessage::System(
                                                "compaction already in progress".to_string(),
                                            ));
                                        } else {
                                            app.push_msg(ChatMessage::System(
                                                "compacting conversation...".to_string(),
                                            ));
                                            app.status_text = Some("compacting…".to_string());
                                            app.spinner_frame = 0;

                                            let msgs = app.api_messages.clone();
                                            let rt = runtime.clone();
                                            let instr = custom_instructions.clone();
                                            let handle = tokio::spawn(async move {
                                                compact_conversation(&msgs, &rt, instr.as_deref()).await
                                            });
                                            app.compact_task = Some(handle);
                                        }
                                    }
                                    CommandAction::Chain => {
                                        // Walk the parent_session chain backward from current session
                                        let mut chain: Vec<(String, String, usize)> = Vec::new(); // (id, title, msg_count)

                                        // Current session first
                                        chain.push((
                                            app.session.id.clone(),
                                            if app.session.title.is_empty() { "(untitled)".to_string() } else { app.session.title.clone() },
                                            app.api_messages.len(),
                                        ));

                                        // Walk backward through parents
                                        let mut current_parent = app.session.parent_session.clone();
                                        while let Some(ref parent_id) = current_parent {
                                            match synaps_cli::core::session::Session::load(parent_id) {
                                                Ok(parent) => {
                                                    let title = if parent.title.is_empty() { "(untitled)".to_string() } else { parent.title.clone() };
                                                    let msg_count = parent.api_messages.len();
                                                    chain.push((parent.id.clone(), title, msg_count));
                                                    current_parent = parent.parent_session.clone();
                                                }
                                                Err(_) => {
                                                    chain.push((parent_id.clone(), "(not found)".to_string(), 0));
                                                    break;
                                                }
                                            }
                                        }

                                        // Reverse so root is first
                                        chain.reverse();

                                        if chain.len() <= 1 {
                                            app.push_msg(ChatMessage::System("no compaction history — this is the root session".to_string()));
                                        } else {
                                            let mut lines = vec!["Session chain:".to_string()];
                                            for (i, (id, title, msgs)) in chain.iter().enumerate() {
                                                let marker = if i == chain.len() - 1 { " ← active" } else { "" };
                                                let short_id: String = id.chars().take(19).collect();
                                                let short_title: String = title.chars().take(40).collect();
                                                lines.push(format!("  {} {} ({} msgs) {}{}",
                                                    if i == 0 { "" } else { "" },
                                                    short_id, msgs, short_title, marker
                                                ));
                                            }
                                            app.push_msg(ChatMessage::System(lines.join("\n")));
                                        }

                                        // Show any named chain bookmarking the active head
                                        match synaps_cli::chain::find_all_chains_by_head(&app.session.id) {
                                            Ok(named) if !named.is_empty() => {
                                                let names: Vec<String> = named.iter().map(|c| format!("@{}", c.name)).collect();
                                                app.push_msg(ChatMessage::System(format!(
                                                    "bookmarked by: {}", names.join(", ")
                                                )));
                                            }
                                            _ => {}
                                        }
                                    }
                                    CommandAction::ChainList => {
                                        match synaps_cli::chain::list_chains() {
                                            Ok(chains) if chains.is_empty() => {
                                                app.push_msg(ChatMessage::System("no named chains".to_string()));
                                            }
                                            Ok(chains) => {
                                                app.push_msg(ChatMessage::System(format!("{} chain(s):", chains.len())));
                                                for c in chains {
                                                    let active = if c.head == app.session.id { " *" } else { "" };
                                                    app.push_msg(ChatMessage::System(format!(
                                                        "  @{}{}{}", c.name, c.head, active
                                                    )));
                                                }
                                            }
                                            Err(e) => {
                                                app.push_msg(ChatMessage::Error(format!("failed to list chains: {}", e)));
                                            }
                                        }
                                    }
                                    CommandAction::ChainName { name } => {
                                        match synaps_cli::chain::save_chain(&name, &app.session.id) {
                                            Ok(()) => {
                                                app.push_msg(ChatMessage::System(format!(
                                                    "chain '{}' → {}", name, app.session.id
                                                )));
                                            }
                                            Err(e) => {
                                                app.push_msg(ChatMessage::Error(format!("chain name failed: {}", e)));
                                            }
                                        }
                                    }
                                    CommandAction::ChainUnname { name } => {
                                        match synaps_cli::chain::delete_chain(&name) {
                                            Ok(()) => {
                                                app.push_msg(ChatMessage::System(format!("chain '{}' deleted", name)));
                                            }
                                            Err(e) => {
                                                app.push_msg(ChatMessage::Error(format!("chain unname failed: {}", e)));
                                            }
                                        }
                                    }
                                    CommandAction::Status => {
                                        if runtime.model().contains('/') {
                                            app.push_msg(ChatMessage::System("Usage stats are only available for Anthropic models.".to_string()));
                                        } else {
                                            app.push_msg(ChatMessage::System("Checking usage...".to_string()));
                                            match fetch_usage().await {
                                                Ok(lines) => {
                                                    for line in lines {
                                                        app.push_msg(ChatMessage::System(line));
                                                    }
                                                }
                                                Err(e) => app.push_msg(ChatMessage::Error(format!("Usage check failed: {}", e))),
                                            }
                                        }
                                    }
                                    CommandAction::ExtensionsStatus => {
                                        let manager = ext_mgr_shared.read().await;
                                        let snapshots = manager.capability_snapshots().await;
                                        let trust_view = manager.provider_trust_view();
                                        if snapshots.is_empty() {
                                            app.push_msg(ChatMessage::System("No extensions loaded.".to_string()));
                                        } else {
                                            app.push_msg(ChatMessage::System(format!("Extensions ({}):", snapshots.len())));
                                            for snap in &snapshots {
                                                app.push_msg(ChatMessage::System(format!(
                                                    "  {}{} (restarts: {})",
                                                    snap.id,
                                                    snap.health.as_str(),
                                                    snap.restart_count
                                                )));
                                                if !snap.hooks.is_empty() {
                                                    let rendered = snap
                                                        .hooks
                                                        .iter()
                                                        .map(|h| match &h.tool_filter {
                                                            Some(t) => format!("{}[{}]", h.kind, t),
                                                            None => h.kind.clone(),
                                                        })
                                                        .collect::<Vec<_>>()
                                                        .join(", ");
                                                    app.push_msg(ChatMessage::System(format!("    hooks: {}", rendered)));
                                                }
                                                if !snap.tools.is_empty() {
                                                    let rendered = snap
                                                        .tools
                                                        .iter()
                                                        .map(|t| t.name.clone())
                                                        .collect::<Vec<_>>()
                                                        .join(", ");
                                                    app.push_msg(ChatMessage::System(format!("    tools: {}", rendered)));
                                                }
                                                // Capability declarations (grouped from the `future` list).
                                                // Each entry has a free-form kind declared by the plugin
                                                // (e.g. "capture", "ocr", "agent"). Render grouped by kind so
                                                // future capability types surface without core changes.
                                                if !snap.future.is_empty() {
                                                    use std::collections::BTreeMap;
                                                    // kind -> name -> Vec<mode>
                                                    let mut by_kind: BTreeMap<String, BTreeMap<String, Vec<String>>> = BTreeMap::new();
                                                    for entry in &snap.future {
                                                        let bucket = by_kind.entry(entry.kind.clone()).or_default();
                                                        // entry.name is "<plugin-name> (<mode>)" in the legacy
                                                        // shim; preserve the existing display behaviour.
                                                        if let Some(open) = entry.name.rfind(" (") {
                                                            if entry.name.ends_with(')') {
                                                                let name = entry.name[..open].to_string();
                                                                let mode = entry.name[open + 2..entry.name.len() - 1].to_string();
                                                                bucket.entry(name).or_default().push(mode);
                                                                continue;
                                                            }
                                                        }
                                                        bucket.entry(entry.name.clone()).or_default();
                                                    }
                                                    for (kind, names) in &by_kind {
                                                        for (name, modes) in names {
                                                            let modes_str = modes.join("/");
                                                            if modes_str.is_empty() {
                                                                app.push_msg(ChatMessage::System(format!(
                                                                    "    {}: {}",
                                                                    kind, name
                                                                )));
                                                            } else {
                                                                app.push_msg(ChatMessage::System(format!(
                                                                    "    {}: {} [{}]",
                                                                    kind, name, modes_str
                                                                )));
                                                            }
                                                        }
                                                    }
                                                }
                                                for provider in &snap.providers {
                                                    let disabled_suffix = match trust_view.get(&provider.runtime_id) {
                                                        Some(false) => " [disabled]",
                                                        _ => "",
                                                    };
                                                    app.push_msg(ChatMessage::System(format!(
                                                        "    provider {}{}{}",
                                                        provider.runtime_id,
                                                        provider.display_name,
                                                        disabled_suffix
                                                    )));
                                                    for model in &provider.models {
                                                        let mut badges: Vec<&str> = Vec::new();
                                                        if model.tool_use { badges.push("tool-use"); }
                                                        if model.streaming { badges.push("streaming"); }
                                                        let label = if badges.is_empty() {
                                                            model.runtime_id.clone()
                                                        } else {
                                                            let suffix = badges.iter().map(|b| format!("[{}]", b)).collect::<Vec<_>>().join(" ");
                                                            format!("{} {}", model.runtime_id, suffix)
                                                        };
                                                        app.push_msg(ChatMessage::System(format!("      model {}", label)));
                                                    }
                                                }
                                                // Surface config diagnostics warnings (no values printed).
                                                if let Some(diag) = manager.config_diagnostics(&snap.id) {
                                                    let missing_required: Vec<&str> = diag
                                                        .entries
                                                        .iter()
                                                        .filter(|e| e.required && matches!(e.source, synaps_cli::extensions::config::ConfigSource::Missing))
                                                        .map(|e| e.key.as_str())
                                                        .collect();
                                                    if !missing_required.is_empty() {
                                                        app.push_msg(ChatMessage::System(format!(
                                                            "    ⚠ missing required config: {}",
                                                            missing_required.join(", ")
                                                        )));
                                                    }
                                                    // Group provider_missing by provider id.
                                                    let mut by_provider: std::collections::BTreeMap<&str, Vec<&str>> = std::collections::BTreeMap::new();
                                                    for (pid, key) in &diag.provider_missing {
                                                        by_provider.entry(pid.as_str()).or_default().push(key.as_str());
                                                    }
                                                    for (pid, keys) in by_provider {
                                                        app.push_msg(ChatMessage::System(format!(
                                                            "    ⚠ provider {} missing required config: {}",
                                                            pid,
                                                            keys.join(", ")
                                                        )));
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    CommandAction::ExtensionsConfig { id } => {
                                        let manager = ext_mgr_shared.read().await;
                                        let diags: Vec<synaps_cli::extensions::config::ExtensionConfigDiagnostics> = match &id {
                                            Some(want) => match manager.config_diagnostics(want) {
                                                Some(d) => vec![d],
                                                None => {
                                                    app.push_msg(ChatMessage::Error(format!(
                                                        "extension not found: {}",
                                                        want
                                                    )));
                                                    Vec::new()
                                                }
                                            },
                                            None => manager.all_config_diagnostics(),
                                        };
                                        if diags.is_empty() && id.is_none() {
                                            app.push_msg(ChatMessage::System("No extensions loaded.".to_string()));
                                        }
                                        for diag in diags {
                                            app.push_msg(ChatMessage::System(format!(
                                                "Extension {} config:",
                                                diag.extension_id
                                            )));
                                            if diag.entries.is_empty() {
                                                app.push_msg(ChatMessage::System("  (no manifest config entries)".to_string()));
                                            }
                                            for entry in &diag.entries {
                                                let source_label = match &entry.source {
                                                    synaps_cli::extensions::config::ConfigSource::EnvOverride(name) => format!("env override ({})", name),
                                                    synaps_cli::extensions::config::ConfigSource::SecretEnv(name) => format!("secret env ({})", name),
                                                    synaps_cli::extensions::config::ConfigSource::PluginConfig => "plugin config".to_string(),
                                                    synaps_cli::extensions::config::ConfigSource::LegacyConfigKey(name) => format!("legacy config key ({})", name),
                                                    synaps_cli::extensions::config::ConfigSource::Default => "default".to_string(),
                                                    synaps_cli::extensions::config::ConfigSource::Missing => "missing".to_string(),
                                                };
                                                let req = if entry.required { " [required]" } else { "" };
                                                app.push_msg(ChatMessage::System(format!(
                                                    "  {}{} — source: {}, has_value: {}",
                                                    entry.key, req, source_label, entry.has_value
                                                )));
                                                if let Some(desc) = &entry.description {
                                                    app.push_msg(ChatMessage::System(format!(
                                                        "    description: {}",
                                                        desc
                                                    )));
                                                }
                                            }
                                            for (pid, key) in &diag.provider_missing {
                                                app.push_msg(ChatMessage::System(format!(
                                                    "  ⚠ provider {} requires config '{}' (no manifest entry)",
                                                    pid, key
                                                )));
                                            }
                                        }
                                    }

                                    CommandAction::ExtensionsTrust(action) => {
                                        use crate::tui::commands::ExtensionsTrustAction;
                                        match action {
                                            ExtensionsTrustAction::List => {
                                                let manager = ext_mgr_shared.read().await;
                                                let providers = manager.provider_summaries();
                                                let trust = synaps_cli::extensions::trust::load_trust_state().unwrap_or_default();
                                                if providers.is_empty() {
                                                    app.push_msg(ChatMessage::System("No providers registered.".to_string()));
                                                } else {
                                                    app.push_msg(ChatMessage::System(format!("Provider trust ({}):", providers.len())));
                                                    for p in providers {
                                                        let suffix = match trust.disabled.get(&p.runtime_id) {
                                                            Some(entry) if entry.disabled => match &entry.reason {
                                                                Some(r) => format!(" [disabled ({})]", r),
                                                                None => " [disabled]".to_string(),
                                                            },
                                                            _ => " [enabled]".to_string(),
                                                        };
                                                        app.push_msg(ChatMessage::System(format!(
                                                            "  {}{}",
                                                            p.runtime_id, suffix
                                                        )));
                                                    }
                                                }
                                            }
                                            ExtensionsTrustAction::Enable { runtime_id } => {
                                                match synaps_cli::extensions::trust::load_trust_state() {
                                                    Ok(mut state) => {
                                                        synaps_cli::extensions::trust::enable_provider(&mut state, &runtime_id);
                                                        match synaps_cli::extensions::trust::save_trust_state(&state) {
                                                            Ok(()) => app.push_msg(ChatMessage::System(format!(
                                                                "Provider '{}' enabled.", runtime_id
                                                            ))),
                                                            Err(e) => app.push_msg(ChatMessage::Error(format!(
                                                                "failed to save trust state: {}", e
                                                            ))),
                                                        }
                                                    }
                                                    Err(e) => app.push_msg(ChatMessage::Error(format!(
                                                        "failed to load trust state: {}", e
                                                    ))),
                                                }
                                            }
                                            ExtensionsTrustAction::Disable { runtime_id, reason } => {
                                                match synaps_cli::extensions::trust::load_trust_state() {
                                                    Ok(mut state) => {
                                                        synaps_cli::extensions::trust::disable_provider(&mut state, &runtime_id, reason.clone());
                                                        match synaps_cli::extensions::trust::save_trust_state(&state) {
                                                            Ok(()) => {
                                                                let suffix = match &reason {
                                                                    Some(r) => format!(" [reason: {}]", r),
                                                                    None => String::new(),
                                                                };
                                                                app.push_msg(ChatMessage::System(format!(
                                                                    "Provider '{}' disabled.{}", runtime_id, suffix
                                                                )));
                                                            }
                                                            Err(e) => app.push_msg(ChatMessage::Error(format!(
                                                                "failed to save trust state: {}", e
                                                            ))),
                                                        }
                                                    }
                                                    Err(e) => app.push_msg(ChatMessage::Error(format!(
                                                        "failed to load trust state: {}", e
                                                    ))),
                                                }
                                            }
                                        }
                                    }
                                    CommandAction::ExtensionsAudit { tail } => {
                                        // Use bounded tail read — only the last N entries are
                                        // deserialised regardless of how large audit.jsonl has grown.
                                        let read_result = match tail {
                                            Some(n) => synaps_cli::extensions::audit::read_audit_entries_tail(n),
                                            None => synaps_cli::extensions::audit::read_audit_entries(),
                                        };
                                        match read_result {
                                            Ok(entries) => {
                                                let slice = entries;
                                                if slice.is_empty() {
                                                    app.push_msg(ChatMessage::System("No audit entries yet.".to_string()));
                                                } else {
                                                    app.push_msg(ChatMessage::System(format!("Audit ({} entries):", slice.len())));
                                                    for e in slice {
                                                        let stream_tag = if e.streamed { "[streamed]" } else { "[complete]" };
                                                        let class_part = match &e.error_class {
                                                            Some(c) => format!(" class={}", c),
                                                            None => String::new(),
                                                        };
                                                        let tools_part = if e.tools_requested > 0 {
                                                            format!(" tools={}", e.tools_requested)
                                                        } else {
                                                            String::new()
                                                        };
                                                        app.push_msg(ChatMessage::System(format!(
                                                            "  {} {}:{} {} outcome={}{}{}",
                                                            e.timestamp,
                                                            e.provider_id,
                                                            e.model_id,
                                                            stream_tag,
                                                            e.outcome,
                                                            class_part,
                                                            tools_part,
                                                        )));
                                                    }
                                                }
                                            }
                                            Err(e) => app.push_msg(ChatMessage::Error(format!(
                                                "failed to read audit log: {}", e
                                            ))),
                                        }
                                    }
                                    CommandAction::ExtensionsMemory(action) => {
                                        use crate::tui::commands::ExtensionsMemoryAction;
                                        match action {
                                            ExtensionsMemoryAction::Namespaces => {
                                                match synaps_cli::memory::store::list_namespaces() {
                                                    Ok(nss) if nss.is_empty() => {
                                                        app.push_msg(ChatMessage::System(
                                                            "No memory namespaces.".to_string(),
                                                        ));
                                                    }
                                                    Ok(nss) => {
                                                        app.push_msg(ChatMessage::System(format!(
                                                            "Memory namespaces ({}):", nss.len()
                                                        )));
                                                        for ns in nss {
                                                            app.push_msg(ChatMessage::System(format!("  {}", ns)));
                                                        }
                                                    }
                                                    Err(e) => app.push_msg(ChatMessage::Error(format!(
                                                        "failed to list memory namespaces: {}", e
                                                    ))),
                                                }
                                            }
                                            ExtensionsMemoryAction::Recent { namespace, limit } => {
                                                let q = synaps_cli::memory::store::MemoryQuery {
                                                    limit: Some(limit.unwrap_or(20)),
                                                    ..Default::default()
                                                };
                                                match synaps_cli::memory::store::query(&namespace, &q) {
                                                    Ok(records) if records.is_empty() => {
                                                        app.push_msg(ChatMessage::System(format!(
                                                            "No records in '{}'.", namespace
                                                        )));
                                                    }
                                                    Ok(records) => {
                                                        app.push_msg(ChatMessage::System(format!(
                                                            "Recent in '{}' ({}):", namespace, records.len()
                                                        )));
                                                        for rec in records {
                                                            // ISO8601 / RFC3339 UTC from epoch ms via chrono.
                                                            let ts = chrono::DateTime::<chrono::Utc>::from_timestamp_millis(
                                                                rec.timestamp_ms as i64,
                                                            )
                                                            .map(|dt| dt.to_rfc3339_opts(chrono::SecondsFormat::Secs, true))
                                                            .unwrap_or_else(|| rec.timestamp_ms.to_string());
                                                            // Truncate content at 80 chars (char-aware).
                                                            let mut content: String = rec.content.chars().take(80).collect();
                                                            if rec.content.chars().count() > 80 {
                                                                content.push('');
                                                            }
                                                            let tags = if rec.tags.is_empty() {
                                                                "[]".to_string()
                                                            } else {
                                                                format!("[{}]", rec.tags.join(", "))
                                                            };
                                                            // NOTE: meta intentionally not displayed (privacy).
                                                            app.push_msg(ChatMessage::System(format!(
                                                                "  {} {} {}", ts, tags, content
                                                            )));
                                                        }
                                                    }
                                                    Err(e) => app.push_msg(ChatMessage::Error(format!(
                                                        "failed to query memory '{}': {}", namespace, e
                                                    ))),
                                                }
                                            }
                                        }
                                    }

                                    CommandAction::Ping => {
                                        app.push_msg(ChatMessage::System("📡 Pinging models...".to_string()));
                                        app.ping_print = true;
                                        let client = runtime.http_client().clone();
                                        let provider_keys = synaps_cli::config::get_provider_keys();
                                        // Count how many models will be pinged
                                        let count: usize = synaps_cli::runtime::openai::registry::providers().iter()
                                            .filter(|s| synaps_cli::runtime::openai::registry::resolve_provider_model(s.key, s.default_model, &provider_keys).is_some())
                                            .map(|s| s.models.len())
                                            .sum();
                                        app.ping_pending = count;
                                        let health_tx = app.ping_tx.clone();
                                        tokio::spawn(async move {
                                            synaps_cli::runtime::openai::ping::ping_all_configured(
                                                &client, &provider_keys, health_tx,
                                            ).await;
                                        });
                                    }

                                    CommandAction::SidecarToggle { plugin_id } => {
                                        // Phase 8 8B: target either the
                                        // claim-supplied plugin id, or fall
                                        // back to the legacy single-slot
                                        // discovery for the unclaimed case.
                                        let all = synaps_cli::sidecar::discovery::discover_all();
                                        let target = plugin_id
                                            .clone()
                                            .or_else(|| all.first().map(|s| s.plugin_name.clone()));
                                        let Some(target_pid) = target else {
                                            app.push_msg(ChatMessage::Error(
                                                "sidecar unavailable: no plugin provides a sidecar binary".to_string()
                                            ));
                                            continue;
                                        };

                                        if app.sidecars.contains_key(&target_pid) {
                                            // Subsequent toggle on existing sidecar — arm flag is source of truth.
                                            let label = app.sidecars.get(&target_pid)
                                                .and_then(|s| s.display_name.as_deref())
                                                .unwrap_or("sidecar")
                                                .to_string();
                                            let v = app.sidecars.get_mut(&target_pid).unwrap();
                                            if v.armed {
                                                v.armed = false;
                                                if let Err(err) = v.manager.release().await {
                                                    app.push_msg(ChatMessage::Error(format!("{label} release failed: {err}")));
                                                }
                                                app.push_msg(ChatMessage::System(
                                                    format!("{label}: stopping — final transcript will be appended")
                                                ));
                                            } else {
                                                v.armed = true;
                                                if let Err(err) = v.manager.press().await {
                                                    v.armed = false;
                                                    app.push_msg(ChatMessage::Error(format!("{label} press failed: {err}")));
                                                }
                                            }
                                        } else {
                                            // Spawn new sidecar instance for target_pid.
                                            let Some(discovered) = all.into_iter().find(|s| s.plugin_name == target_pid) else {
                                                app.push_msg(ChatMessage::Error(format!(
                                                    "sidecar plugin '{}' not discoverable", target_pid,
                                                )));
                                                continue;
                                            };
                                            let (sidecar_plugin_info, sidecar_spawn_args) = {
                                                let manager = ext_mgr_shared.read().await;
                                                let info = manager.plugin_info(&target_pid).cloned();
                                                let args = match manager.sidecar_spawn_args(&target_pid).await {
                                                    Ok(a) => Some(a),
                                                    Err(err) => {
                                                        tracing::debug!(
                                                            plugin = %target_pid,
                                                            error = %err,
                                                            "sidecar.spawn_args RPC unavailable; using manifest defaults",
                                                        );
                                                        None
                                                    }
                                                };
                                                (info, args)
                                            };
                                            match self::sidecar::SidecarUiState::spawn_for(
                                                discovered,
                                                sidecar_spawn_args,
                                                sidecar_plugin_info.as_ref(),
                                            ).await {
                                                Ok(mut state) => {
                                                    let claims = registry.lifecycle_claims();
                                                    let display = pick_display_name_for_plugin(
                                                        &state.sidecar.plugin_name,
                                                        &claims,
                                                    );
                                                    state.set_display_name(display);
                                                    let label = state.display_name.clone()
                                                        .unwrap_or_else(|| "sidecar".to_string());
                                                    let plugin_key = state.sidecar.plugin_name.clone();
                                                    app.sidecars.insert(plugin_key.clone(), state);
                                                    app.push_msg(ChatMessage::System(
                                                        format!("{label} active — press the toggle again to stop")
                                                    ));
                                                    if let Some(v) = app.sidecars.get_mut(&plugin_key) {
                                                        v.armed = true;
                                                        if let Err(err) = v.manager.press().await {
                                                            v.armed = false;
                                                            v.status = self::sidecar::SidecarUiStatus::Error(err.to_string());
                                                            app.push_msg(ChatMessage::Error(format!("{label} press failed: {err}")));
                                                        }
                                                    }
                                                }
                                                Err(err) => {
                                                    app.push_msg(ChatMessage::Error(format!("sidecar unavailable: {err}")));
                                                }
                                            }
                                        }
                                    }

                                    CommandAction::SidecarStatus { plugin_id } => {
                                        // Phase 8 8B: show status for the
                                        // requested plugin, or — when None —
                                        // for the single legacy sidecar (or
                                        // the discovery hint when none have
                                        // been spawned).
                                        let line = if let Some(pid) = plugin_id.as_deref() {
                                            match app.sidecars.get(pid) {
                                                Some(v) => v.status_line(),
                                                None => match synaps_cli::sidecar::discovery::discover_all().into_iter().find(|s| s.plugin_name == pid) {
                                                    Some(s) => format!(
                                                        "sidecar: not yet started — sidecar available from plugin '{}' at {}",
                                                        s.plugin_name, s.binary.display()
                                                    ),
                                                    None => format!("sidecar: no plugin '{}' provides a sidecar", pid),
                                                },
                                            }
                                        } else if app.sidecars.len() == 1 {
                                            app.sidecars.values().next().unwrap().status_line()
                                        } else if app.sidecars.is_empty() {
                                            match synaps_cli::sidecar::discovery::discover() {
                                                Some(s) => format!(
                                                    "sidecar: not yet started — sidecar available from plugin '{}' at {}",
                                                    s.plugin_name, s.binary.display()
                                                ),
                                                None => "sidecar: no plugin provides a sidecar binary (install a plugin that declares provides.sidecar)".to_string(),
                                            }
                                        } else {
                                            // Multiple active — list each.
                                            let mut lines: Vec<String> = app.sidecars.values()
                                                .map(|v| v.status_line()).collect();
                                            lines.sort();
                                            lines.join("\n")
                                        };
                                        app.push_msg(ChatMessage::System(line));
                                    }

                                }
                            }
                            InputAction::Submit(input) => {
                                // Queue input during compaction — will be sent after session swap
                                if app.compact_task.is_some() {
                                    app.push_msg(ChatMessage::System(format!("queued: {}", input)));
                                    app.queued_message = Some(input);
                                    continue;
                                }
                                let display_text = app.user_display_text_for_submission(&input);
                                app.push_msg(ChatMessage::User(display_text));
                                app.input_before_paste = None;
                                app.pasted_char_count = 0;
                                // Inject abort context if previous response was interrupted
                                let api_content = if let Some(ref ctx) = app.abort_context {
                                    let combined = format!("{}\n\n{}", ctx, input);
                                    app.abort_context = None;
                                    combined
                                } else {
                                    input
                                };
                                app.api_messages.push(json!({"role": "user", "content": api_content}));
                                let ct = CancellationToken::new();
                                let (s_tx, s_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
                                app.status_text = Some("connecting…".to_string());
                                app.streaming = true;
                                app.spinner_frame = 0;
                                let term_size = crossterm::terminal::size().map(|(w, h)| ratatui::layout::Size { width: w, height: h }).unwrap_or_default();
                                if let Some(model) = build_render_model(&mut app, &runtime, &registry, &secret_prompts, term_size) {
                                    render_handle.publish(model);
                                }
                                stream = Some(runtime.run_stream_with_messages(app.api_messages.clone(), ct.clone(), Some(s_rx), Some(secret_prompt_handle.clone()), false).await);
                                app.status_text = None;
                                app.push_msg(ChatMessage::Thinking(THINKING_PLACEHOLDER.to_string()));
                                cancel_token = Some(ct);
                                steer_tx = Some(s_tx);
                            }
                            InputAction::StreamingInput(input) => {
                                // Check for streaming slash commands
                                if let Some(rest) = input.strip_prefix('/') {
                                    let raw_cmd = rest.split_whitespace().next().unwrap_or("");
                                    let streaming_cmds = commands::to_owned_commands(commands::STREAMING_COMMANDS);
                                    let cmd = commands::resolve_prefix(raw_cmd, &streaming_cmds);
                                    match commands::handle_streaming_command(&cmd, &input, &mut app) {
                                        CommandAction::None => {
                                            // Not a streaming-safe command. If it's still a KNOWN
                                            // command (settings, model, system, etc.), refuse with
                                            // a clear message — don't leak command text into the
                                            // model stream as steering input.
                                            let all_cmds = commands::all_commands_with_skills(&registry);
                                            let resolved_full = commands::resolve_prefix(raw_cmd, &all_cmds);
                                            if all_cmds.iter().any(|c| c == &resolved_full) {
                                                app.push_msg(ChatMessage::System(
                                                    format!("/{} can't run while streaming — press Esc to cancel first", resolved_full)
                                                ));
                                            } else {
                                                // Unknown slash text — treat as steering
                                                let steered = steer_tx.as_ref()
                                                    .map(|tx| tx.send(input.clone()).is_ok())
                                                    .unwrap_or(false);
                                                if steered {
                                                    app.push_msg(ChatMessage::System(format!("→ steering: {}", input)));
                                                } else {
                                                    app.push_msg(ChatMessage::System(format!("queued: {}", input)));
                                                }
                                                app.queued_message = Some(input);
                                            }
                                        }
                                        CommandAction::Quit => {
                                            render_handle.send_exit_fx(quit_effect());
                                            exit_fx_sent = true;
                                        }
                                        CommandAction::LaunchGamba => {
                                            drop(event_reader);
                                            // Pause the render thread BEFORE touching the terminal —
                                            // eliminates the stdout race between terminal.draw() and our mode changes.
                                            render_handle.pause();
                                            match app.launch_gamba() {
                                                Ok(()) => {}
                                                Err(msg) => {
                                                    // launch failed — restore and resume
                                                    render_handle.resume();
                                                    app.push_msg(ChatMessage::Error(msg));
                                                }
                                            }
                                            // If gamba launched OK, resume is sent by reclaim/check_gamba_exited.
                                            event_reader = EventStream::new();
                                        }
                                        CommandAction::StartStream => {}
                                        CommandAction::OpenModels => {}
                                        CommandAction::OpenSettings => {}
                                        CommandAction::OpenPlugins => {}
                                        CommandAction::OpenHelpFind { .. } => {}
                                        CommandAction::ReloadPlugins => {}
                                        // handle_streaming_command never returns LoadSkill, PluginCommand, or Compact.
                                        CommandAction::LoadSkill { .. } => {}
                                        CommandAction::PluginCommand { .. } => {}
                                        CommandAction::Compact { .. } => {}
                                        CommandAction::Chain => {}
                                        CommandAction::ChainList => {}
                                        CommandAction::ChainName { .. } => {}
                                        CommandAction::ChainUnname { .. } => {}
                                        CommandAction::Status => {}
                                        CommandAction::ExtensionsStatus => {}
                                        CommandAction::ExtensionsConfig { .. } => {}
                                        CommandAction::ExtensionsTrust(_) => {}
                                        CommandAction::ExtensionsAudit { .. } => {}
                                        CommandAction::ExtensionsMemory(_) => {}
                                        CommandAction::Ping => {}
                                        CommandAction::SidecarToggle { .. } => {}
                                        CommandAction::SidecarStatus { .. } => {}
                                    }
                                } else {
                                    // Normal text during streaming — steer/queue
                                    let steered = steer_tx.as_ref()
                                        .map(|tx| tx.send(input.clone()).is_ok())
                                        .unwrap_or(false);
                                    if steered {
                                        app.push_msg(ChatMessage::System(format!("→ steering: {}", input)));
                                    } else {
                                        app.push_msg(ChatMessage::System(format!("queued: {}", input)));
                                    }
                                    app.queued_message = Some(input);
                                }
                            }
                            InputAction::ModelsApply(model) => {
                                runtime.set_model(model.clone());
                                let applied = runtime.model().to_string();
                                let status = synaps_cli::engine::commands::persist_to_config("model", &applied);
                                app.session.model = applied.clone();
                                app.push_msg(ChatMessage::System(format!("model set to: {} {}", applied, status)));
                            }
                            InputAction::ModelsExpandProvider(provider_key) => {
                                if provider_key.contains(':') {
                                    let tx = app.model_list_tx.clone();
                                    let manager = synaps_cli::runtime::openai::extension_manager_for_routing();
                                    tokio::spawn(async move {
                                        let result = if let Some(manager) = manager {
                                            let manager = manager.read().await;
                                            if let Some(provider) = manager.provider(&provider_key) {
                                                Ok(provider.spec.models.iter().map(|model| {
                                                    let full_id = synaps_cli::extensions::providers::ProviderRegistry::model_runtime_id(
                                                        &provider.plugin_id,
                                                        &provider.provider_id,
                                                        &model.id,
                                                    );
                                                    let mut metadata = vec![format!("plugin {}", provider.plugin_id)];
                                                    metadata.push(format!("provider {}", provider.provider_id));
                                                    if let Some(context) = model.context_window {
                                                        metadata.push(if context >= 1_000_000 {
                                                            format!("{}M ctx", context / 1_000_000)
                                                        } else if context >= 1_000 {
                                                            format!("{}K ctx", context / 1_000)
                                                        } else {
                                                            format!("{context} ctx")
                                                        });
                                                    }
                                                    if model.capabilities.get("tool_use").and_then(|value| value.as_bool()).unwrap_or(false) {
                                                        metadata.push("tool-use".to_string());
                                                    }
                                                    models::ExpandedModelEntry::with_metadata(
                                                        full_id,
                                                        model.display_name.clone().unwrap_or_else(|| model.id.clone()),
                                                        false,
                                                        metadata,
                                                    )
                                                }).collect())
                                            } else {
                                                Err(format!("extension provider '{}' is not loaded", provider_key))
                                            }
                                        } else {
                                            Err("extension provider registry is not available".to_string())
                                        };
                                        let _ = tx.send((provider_key, result));
                                    });
                                    continue;
                                }
                                let client = runtime.http_client().clone();
                                let provider_keys = synaps_cli::config::get_provider_keys();
                                let tx = app.model_list_tx.clone();
                                tokio::spawn(async move {
                                    let result = synaps_cli::runtime::openai::catalog::fetch_catalog_models(
                                        &client,
                                        &provider_key,
                                        &provider_keys,
                                    ).await.map(|models| {
                                        models.into_iter().map(|model| {
                                            let full_id = model.runtime_id();
                                            let label = model.display_label().to_string();
                                            let mut metadata = Vec::new();
                                            if let Some(context) = model.context_tokens {
                                                metadata.push(if context >= 1_000_000 {
                                                    format!("{}M ctx", context / 1_000_000)
                                                } else if context >= 1_000 {
                                                    format!("{}K ctx", context / 1_000)
                                                } else {
                                                    format!("{context} ctx")
                                                });
                                            }
                                            match model.reasoning {
                                                synaps_cli::runtime::openai::catalog::ReasoningSupport::None => {}
                                                synaps_cli::runtime::openai::catalog::ReasoningSupport::Unknown => {}
                                                _ => metadata.push("thinking".to_string()),
                                            }
                                            if model.pricing.has_internal_reasoning_cost() {
                                                metadata.push("reasoning $".to_string());
                                            }
                                            models::ExpandedModelEntry::with_metadata(full_id, label, false, metadata)
                                        }).collect()
                                    });
                                    let _ = tx.send((provider_key, result));
                                });
                            }
                            InputAction::SettingsApply(key, value) => {
                                apply_setting(key, &value, &mut app, &mut runtime);
                            }
                            InputAction::PluginEditorOpen { plugin_id, category, field } => {
                                let manager = ext_mgr_shared.read().await;
                                match manager.settings_editor_open(&plugin_id, &category, &field).await
                                    .and_then(settings::plugin_editor::render_from_open_result)
                                {
                                    Ok(render) => {
                                        if let Some(state) = app.settings.as_mut() {
                                            state.row_error = None;
                                            state.edit_mode = Some(settings::ActiveEditor::PluginCustom {
                                                plugin_id: plugin_id.clone(),
                                                category: category.clone(),
                                                field: field.clone(),
                                                render: settings::plugin_editor::PluginEditorSession {
                                                    plugin_id,
                                                    category,
                                                    field,
                                                    render,
                                                },
                                            });
                                        }
                                    }
                                    Err(err) => {
                                        if let Some(state) = app.settings.as_mut() {
                                            state.row_error = Some((
                                                format!("plugin.{}.{}", plugin_id, field),
                                                err,
                                            ));
                                        }
                                    }
                                }
                            }
                            InputAction::PluginEditorKey { plugin_id, category, field, key } => {
                                let wire_key = settings::plugin_editor::key_to_wire(key);
                                if wire_key == "Enter" {
                                    let selected = app.settings.as_ref().and_then(|state| {
                                        match &state.edit_mode {
                                            Some(settings::ActiveEditor::PluginCustom { render, .. }) => {
                                                let cursor = render.render.cursor.unwrap_or(0);
                                                render.render.rows.get(cursor).and_then(|r| r.data.clone())
                                            }
                                            _ => None,
                                        }
                                    });
                                    if let Some(value) = selected {
                                        let manager = ext_mgr_shared.read().await;
                                        match manager.settings_editor_commit(&plugin_id, &category, &field, value.clone()).await {
                                            Ok(reply) => {
                                                let effect = settings::plugin_editor::effect_from_commit_reply(
                                                    &plugin_id,
                                                    &field,
                                                    reply,
                                                );
                                                match effect {
                                                    settings::plugin_editor::PluginEditorEffect::None => {}
                                                    settings::plugin_editor::PluginEditorEffect::ConfigWrite { plugin_id, key, value } => {
                                                        match synaps_cli::extensions::config_store::write_plugin_config(&plugin_id, &key, &value) {
                                                            Ok(()) => {
                                                                if let Some(state) = app.settings.as_mut() {
                                                                    state.edit_mode = None;
                                                                    state.row_error = Some((format!("plugin.{}.{}", plugin_id, key), "saved".to_string()));
                                                                }
                                                            }
                                                            Err(err) => {
                                                                if let Some(state) = app.settings.as_mut() {
                                                                    state.row_error = Some((format!("plugin.{}.{}", plugin_id, key), err.to_string()));
                                                                }
                                                            }
                                                        }
                                                    }
                                                    settings::plugin_editor::PluginEditorEffect::InvokeCommand { plugin_id, command, args } => {
                                                        if let Some(state) = app.settings.as_mut() {
                                                            state.edit_mode = None;
                                                            state.row_error = Some((format!("plugin.{}.{}", plugin_id, field), "download started".to_string()));
                                                        }
                                                        commands::execute_interactive_plugin_command_by_parts(
                                                            &plugin_id,
                                                            &command,
                                                            args,
                                                            &manager,
                                                            &mut app,
                                                        ).await;
                                                    }
                                                }
                                            }
                                            Err(err) => {
                                                if let Some(state) = app.settings.as_mut() {
                                                    state.row_error = Some((format!("plugin.{}.{}", plugin_id, field), err));
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    let manager = ext_mgr_shared.read().await;
                                    match manager.settings_editor_key(&plugin_id, &category, &field, &wire_key).await
                                        .and_then(settings::plugin_editor::render_from_key_result)
                                    {
                                        Ok(Some(render)) => {
                                            if let Some(settings::ActiveEditor::PluginCustom { render: session, .. }) =
                                                app.settings.as_mut().and_then(|s| s.edit_mode.as_mut())
                                            {
                                                session.render = render;
                                            }
                                        }
                                        Ok(None) => {}
                                        Err(err) => {
                                            if let Some(state) = app.settings.as_mut() {
                                                state.row_error = Some((format!("plugin.{}.{}", plugin_id, field), err));
                                            }
                                        }
                                    }
                                }
                            }
                            InputAction::PluginsOutcome(outcome) => {
                                if let Some(state) = app.plugins.as_mut() {
                                    use self::plugins::InputOutcome as PO;
                                    match outcome {
                                        PO::None | PO::Close => {}
                                        PO::AddMarketplace(url) => {
                                            plugins::actions::apply_add_marketplace(state, url).await;
                                        }
                                        PO::InstallRequested { marketplace, plugin } => {
                                            plugins::actions::apply_install(
                                                state, marketplace, plugin, &registry, &config,
                                            ).await;
                                        }
                                        PO::TrustAndInstall { plugin_name, host, source, summary } => {
                                            plugins::actions::apply_trust_and_install(
                                                state, plugin_name, host, source, summary, &registry, &config,
                                            ).await;
                                        }
                                        PO::Uninstall(name) => {
                                            plugins::actions::apply_uninstall(
                                                state, name, &registry, &config,
                                            ).await;
                                        }
                                        PO::Update(name) => {
                                            plugins::actions::apply_update(
                                                state, name, &registry, &config,
                                            ).await;
                                        }
        PO::RefreshMarketplace(name) => {
                                            plugins::actions::apply_refresh_marketplace(state, name).await;
                                        }
                                        PO::ConfirmPendingInstall => {
                                            plugins::actions::apply_confirm_pending_install(state, &registry, &config).await;
                                        }
                                        PO::CancelPendingInstall => {
                                            plugins::actions::apply_cancel_pending_install(state);
                                        }
                                        PO::ConfirmPendingUpdate => {
                                            plugins::actions::apply_confirm_pending_update(state, &registry, &config).await;
                                        }
                                        PO::CancelPendingUpdate => {
                                            plugins::actions::apply_cancel_pending_update(state);
                                        }
                                        PO::RemoveMarketplace(name) => {
                                            plugins::actions::apply_remove_marketplace(
                                                state, name, &registry, &config,
                                            ).await;
                                        }
                                        PO::TogglePlugin { name, enabled } => {
                                            plugins::actions::apply_toggle_plugin(
                                                state, name, enabled, &registry, &mut config,
                                            );
                                        }
                                        PO::EnablePluginRequested(name) => {
                                            plugins::actions::confirm_enable_plugin(state, name);
                                        }
                                    }
                                }
                            }
                            InputAction::OpenPluginsMarketplace => {
                                let path = synaps_cli::skills::state::PluginsState::default_path();
                                match synaps_cli::skills::state::PluginsState::load_from(&path) {
                                    Ok(file) => {
                                        app.plugins = Some(plugins::PluginsModalState::new_from_settings(file));
                                    }
                                    Err(e) => {
                                        if let Some(s) = app.settings.as_mut() {
                                            s.row_error = Some((
                                                "plugins".to_string(),
                                                format!("failed to load plugins.json: {}", e),
                                            ));
                                        }
                                    }
                                }
                            }
                            InputAction::PingModels => {
                                let client = runtime.http_client().clone();
                                let provider_keys = synaps_cli::config::get_provider_keys();
                                let health_tx = app.ping_tx.clone();
                                tokio::spawn(async move {
                                    synaps_cli::runtime::openai::ping::ping_all_configured(
                                        &client, &provider_keys, health_tx,
                                    ).await;
                                });
                            }
                        }
                    }
                    // FIX C (defense in depth): EventStream yields Err or None when
                    // crossterm detects the PTY is gone. Break cleanly here.
                    // NOTE: on some kernels crossterm's EPOLL loop can spin without ever
                    // yielding Err/None on a dead PTY (the confirmed busy-loop bug). The
                    // render thread's I/O error path is the backstop: it logs the error
                    // and keeps rendering until the main loop tears down (does NOT break
                    // the render loop on a single I/O error).
                    Some(Err(_)) | None => break,
                }
            }

            // ── Stream events from runtime ──
            maybe_event = async {
                if let Some(ref mut s) = stream {
                    s.next().await
                } else {
                    std::future::pending().await
                }
            } => {
                if let Some(event) = maybe_event {
                    let do_draw = stream_handler::needs_immediate_draw(&event);
                    let action = stream_handler::handle_stream_event(event, &mut app, &runtime).await;

                    match action {
                        StreamAction::Continue => {
                            // For Done/Error, clear stream state
                            if !app.streaming {
                                stream = None;
                                cancel_token = None;
                                steer_tx = None;
                                // Reclaim gamba if running — resume render thread
                                // after reclaim restores the terminal.
                                if let Some(msg) = app.reclaim_gamba() {
                                    render_handle.resume();
                                    app.push_msg(ChatMessage::System(msg));
                                    app.invalidate();
                                }
                            }
                        }
                        StreamAction::AutoSendQueued(queued) => {
                            // Drop old stream state (important for cleanup)
                            drop(stream.take());
                            drop(cancel_token.take());
                            drop(steer_tx.take());
                            // Reclaim gamba if running — resume render thread
                            // after reclaim restores the terminal.
                            if let Some(msg) = app.reclaim_gamba() {
                                render_handle.resume();
                                app.push_msg(ChatMessage::System(msg));
                                app.invalidate();
                            }
                            // Auto-send the queued message
                            app.push_msg(ChatMessage::User(queued.clone()));
                            app.scroll_back = 0;
                            app.scroll_pinned = true;
                            let api_content = if let Some(ref ctx) = app.abort_context {
                                let combined = format!("{}\n\n{}", ctx, queued);
                                app.abort_context = None;
                                combined
                            } else {
                                queued
                            };
                            app.api_messages.push(json!({"role": "user", "content": api_content}));
                            let ct = CancellationToken::new();
                            let (s_tx, s_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
                            app.status_text = Some("connecting…".to_string());
                            app.streaming = true;
                            app.spinner_frame = 0;
                            let term_size = crossterm::terminal::size().map(|(w, h)| ratatui::layout::Size { width: w, height: h }).unwrap_or_default();
                            if let Some(model) = build_render_model(&mut app, &runtime, &registry, &secret_prompts, term_size) {
                                render_handle.publish(model);
                            }
                            stream = Some(runtime.run_stream_with_messages(app.api_messages.clone(), ct.clone(), Some(s_rx), Some(secret_prompt_handle.clone()), false).await);
                            app.status_text = None;
                            app.push_msg(ChatMessage::Thinking(THINKING_PLACEHOLDER.to_string()));
                            cancel_token = Some(ct);
                            steer_tx = Some(s_tx);
                        }
                        StreamAction::AutoTriggerEvents => {
                            drop(stream.take());
                            drop(cancel_token.take());
                            drop(steer_tx.take());
                            let ct = CancellationToken::new();
                            let (s_tx, s_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
                            app.streaming = true;
                            app.spinner_frame = 0;
                            stream = Some(runtime.run_stream_with_messages(app.api_messages.clone(), ct.clone(), Some(s_rx), Some(secret_prompt_handle.clone()), false).await);
                            app.push_msg(ChatMessage::Thinking(THINKING_PLACEHOLDER.to_string()));
                            cancel_token = Some(ct);
                            steer_tx = Some(s_tx);
                        }
                    }

                    if do_draw {
                        let term_size = crossterm::terminal::size().map(|(w, h)| ratatui::layout::Size { width: w, height: h }).unwrap_or_default();
                        if let Some(model) = build_render_model(&mut app, &runtime, &registry, &secret_prompts, term_size) {
                            render_handle.publish(model);
                        }
                    }
                }
            }
        }
    }

    // ── PART 2: Bounded teardown — two sequential budgets.
    //
    // All timing constants are defined in signals.rs (single source of truth):
    //   SAVE_TIMEOUT_SECS  — session save + index record (data safety first)
    //   HOOKS_TIMEOUT_SECS — on_session_end hook emit (concurrent, fail-open)
    //   TEARDOWN_TIMEOUT_SECS = SAVE_TIMEOUT_SECS + HOOKS_TIMEOUT_SECS
    //
    // Session save ALWAYS runs first in its own timeout so slow extension
    // handlers cannot starve it.  Even if the hook budget is exhausted, the
    // session data on disk is already safe before hooks are attempted.
    {
        let session_id = app.session.id.clone();
        let api_messages = app.api_messages.clone();

        // ── STEP 1: Save session data — own bounded timeout, highest priority ──
        let save_fut = async {
            app.save_session().await;

            let mut index_record = SessionIndexRecord::end(&session_id);
            index_record.turns = Some(api_messages.len());
            if let Err(err) = synaps_cli::core::session_index::append_record(&index_record) {
                tracing::warn!("failed to append session end index record: {}", err);
            }
        };

        match tokio::time::timeout(
            std::time::Duration::from_secs(signals::SAVE_TIMEOUT_SECS),
            save_fut,
        )
        .await
        {
            Ok(()) => tracing::debug!("session save completed"),
            Err(_elapsed) => {
                tracing::warn!(
                    budget_secs = signals::SAVE_TIMEOUT_SECS,
                    "session save timed out — data may be incomplete"
                );
                lifecycle::emergency_teardown_terminal();
                std::process::exit(1);
            }
        }

        // ── STEP 2: Fire on_session_end hook — own bounded timeout, after save ──
        //
        // emit_concurrent() dispatches all on_session_end handlers simultaneously
        // under one shared timeout window instead of N×5 s serial.  This is safe
        // because on_session_end only allows `Continue` results — handlers are
        // independent fire-and-forget notification calls (deck, d20, jawz-widget,
        // synaps-tasks each write to their own stores; no ordering dependency).
        //
        // Ordering-safety evidence: HookKind::OnSessionEnd::allowed_action_names()
        // returns &["continue"] exclusively; allows_result() permits only Continue;
        // emit_concurrent() merges injections (N/A here) and treats timeouts as
        // continue (fail-open).  Serial ordering cannot matter when the return
        // value is always Continue and handlers touch disjoint state.
        let transcript = Some(api_messages);
        let hook_event = synaps_cli::extensions::hooks::events::HookEvent::on_session_end(
            &session_id,
            transcript,
        );
        match tokio::time::timeout(
            std::time::Duration::from_secs(signals::HOOKS_TIMEOUT_SECS),
            runtime.hook_bus().emit_concurrent(&hook_event),
        )
        .await
        {
            Ok(_) => tracing::debug!("on_session_end hooks completed"),
            Err(_elapsed) => {
                tracing::warn!(
                    budget_secs = signals::HOOKS_TIMEOUT_SECS,
                    "on_session_end hooks timed out — extensions may not have flushed"
                );
                // Session is already saved above — no data loss here.
                // Fall through to normal teardown.
            }
        }

        tracing::debug!("clean teardown completed");
    }

    // Let extension shutdown continue in the background; exit should not hang on
    // extension post/session-end cleanup or slow child-process teardown.
    let _extension_shutdown =
        synaps_cli::extensions::manager::ExtensionManager::shutdown_all_detached(
            std::sync::Arc::clone(&ext_mgr_shared),
        );
    // Stop the signal-listener thread (signal-hook handle, not a JoinHandle).
    shutdown_signal_task.close();

    // Shut down background tasks (inbox watcher, socket, session registry)
    background.shutdown();

    // ── Render-thread teardown ───────────────────────────────────────────────
    //
    // The render thread owns the Terminal.  We send it a Teardown command and
    // wait for the ack within the combined SAVE + HOOKS budget already spent
    // above.  If the ack doesn't arrive the thread is wedged (dead PTY); we
    // skip the join and let process exit reap it — see RenderHandle::teardown.
    // This self-bounding teardown replaced the old signal watchdog (#116).
    //
    // The render thread's do_teardown() calls emergency_teardown_terminal()
    // (disable_raw_mode + LeaveAlternateScreen + etc.) and show_cursor(), then
    // sends the ack and exits its loop.  The Terminal is dropped when the
    // thread exits — that's safe because crossterm teardown was already done.
    let teardown_budget = std::time::Duration::from_secs(
        signals::TEARDOWN_TIMEOUT_SECS.saturating_sub(signals::SAVE_TIMEOUT_SECS),
    )
    .max(std::time::Duration::from_secs(2));
    let acked = render_handle.teardown(teardown_budget);
    if !acked {
        tracing::warn!("render thread did not ack teardown within budget — watchdog is backstop");
        // emergency_teardown_terminal is a no-op if the terminal is already
        // restored, so calling it here is safe even if the render thread did
        // eventually finish teardown after the timeout.
        lifecycle::emergency_teardown_terminal();
    }

    Ok(())
}

fn handle_widget_event(
    app: &mut App,
    event: synaps_cli::extensions::widgets::ExtensionWidgetEvent,
) -> bool {
    use synaps_cli::extensions::widgets::WidgetEvent;
    match event.event {
        WidgetEvent::Upsert {
            id,
            lines,
            styled_lines,
            position,
            title,
            ttl_secs,
        } => {
            let pos = match position.as_str() {
                "top_left" => toast::ToastPosition::TOP_LEFT,
                "top_center" => toast::ToastPosition::TOP_CENTER,
                "top_right" => toast::ToastPosition::TOP_RIGHT,
                "middle_left" => toast::ToastPosition::MIDDLE_LEFT,
                "center" => toast::ToastPosition::CENTER,
                "middle_right" => toast::ToastPosition::MIDDLE_RIGHT,
                "bottom_left" => toast::ToastPosition::BOTTOM_LEFT,
                "bottom_center" => toast::ToastPosition::BOTTOM_CENTER,
                "bottom_right" => toast::ToastPosition::BOTTOM_RIGHT,
                _ => toast::ToastPosition::TOP_RIGHT,
            };
            let ttl = ttl_secs.map(std::time::Duration::from_secs);
            let mut t = toast::Toast::new(
                format!("widget:{}", id),
                lines.first().cloned().unwrap_or_default(),
            )
            .lines(lines)
            .at(pos)
            .ttl(ttl);
            // Convert styled_lines → rich ratatui Lines if present.
            if let Some(styled) = styled_lines {
                use ratatui::style::Style;
                use ratatui::text::{Line, Span};
                let rich: Vec<Line<'static>> = styled
                    .into_iter()
                    .map(|spans| {
                        Line::from(
                            spans
                                .into_iter()
                                .map(|s| {
                                    let mut style = Style::default();
                                    if let Some(ref fg) = s.fg {
                                        if let Some(c) = parse_hex_color(fg) {
                                            style = style.fg(c);
                                        }
                                    }
                                    if let Some(ref bg) = s.bg {
                                        if let Some(c) = parse_hex_color(bg) {
                                            style = style.bg(c);
                                        }
                                    }
                                    Span::styled(s.text, style)
                                })
                                .collect::<Vec<_>>(),
                        )
                    })
                    .collect();
                t = t.rich(rich);
            }
            if let Some(title) = title {
                t = t.titled(title);
            }
            app.toasts.upsert(t)
        }
        WidgetEvent::Dismiss { id } => {
            app.toasts.dismiss(&format!("widget:{}", id))
        }
    }
}

/// Parse a CSS-style hex color string (e.g. "#ff0000") into a ratatui Color.
fn parse_hex_color(s: &str) -> Option<ratatui::style::Color> {
    let s = s.strip_prefix('#')?;
    if s.len() != 6 {
        return None;
    }
    let r = u8::from_str_radix(&s[0..2], 16).ok()?;
    let g = u8::from_str_radix(&s[2..4], 16).ok()?;
    let b = u8::from_str_radix(&s[4..6], 16).ok()?;
    Some(ratatui::style::Color::Rgb(r, g, b))
}

fn handle_extension_loader_toast(app: &mut App, title: &str, lines: Vec<String>, persistent: bool) {
    app.toasts.upsert(
        toast::Toast::new("extension-loader", "")
            .titled(title)
            .lines(lines)
            .at(toast::ToastPosition::TOP_CENTER)
            .ttl(if persistent {
                None
            } else {
                Some(std::time::Duration::from_secs(5))
            }),
    );
    app.invalidate();
}

async fn handle_extension_loader_event(
    app: &mut App,
    runtime: &Runtime,
    event: synaps_cli::extensions::loader::ExtensionLoaderEvent,
    ext_mgr: &std::sync::Arc<
        tokio::sync::RwLock<synaps_cli::extensions::manager::ExtensionManager>,
    >,
) {
    use synaps_cli::extensions::loader::ExtensionLoaderEvent;
    match event {
        ExtensionLoaderEvent::Started => {
            handle_extension_loader_toast(
                app,
                "Extensions",
                vec!["Discovering extensions…".into()],
                true,
            );
        }
        ExtensionLoaderEvent::Loaded {
            plugin,
            loaded,
            failed,
        } => {
            handle_extension_loader_toast(
                app,
                "Extensions",
                vec![
                    format!(
                        "Loaded {loaded} extension{}",
                        if loaded == 1 { "" } else { "s" }
                    ),
                    format!("Latest: {plugin}"),
                    format!("Failures: {failed}"),
                ],
                true,
            );
        }
        ExtensionLoaderEvent::Failed {
            failure,
            loaded,
            failed,
        } => {
            handle_extension_loader_toast(
                app,
                "Extensions",
                vec![
                    format!("Loaded {loaded}, failed {failed}"),
                    format!("{}", failure.plugin),
                ],
                true,
            );
            app.push_msg(ChatMessage::System(format!(
                "⚠ Extension '{}' failed: {}",
                failure.plugin,
                failure.concise_message()
            )));
        }
        ExtensionLoaderEvent::Finished { loaded, failed } => {
            app.extension_loader_running = false;
            let handler_count = runtime.hook_bus().handler_count().await;
            tracing::info!(
                extensions = loaded.len(),
                failures = failed.len(),
                handlers = handler_count,
                "Extension discovery complete"
            );
            let lines = if failed.is_empty() {
                vec![format!(
                    "✓ Loaded {} extension{}",
                    loaded.len(),
                    if loaded.len() == 1 { "" } else { "s" }
                )]
            } else {
                vec![
                    format!(
                        "Loaded {} extension{}",
                        loaded.len(),
                        if loaded.len() == 1 { "" } else { "s" }
                    ),
                    format!("{} failed — see transcript", failed.len()),
                ]
            };
            handle_extension_loader_toast(app, "Extensions", lines, false);

            // Spawn a background notification watcher for each loaded extension.
            // The watcher forwards widget.* notifications to the TUI via widget_tx.
            let handlers = ext_mgr.read().await.handlers();
            for (ext_id, handler) in handlers {
                let widget_tx = app.widget_tx.clone();
                tokio::spawn(async move {
                    loop {
                        let (_sub_id, mut rx) = handler.subscribe_notifications().await;
                        while let Some(frame) = rx.recv().await {
                            if synaps_cli::extensions::widgets::is_widget_method(&frame.method) {
                                if let Ok(event) =
                                    synaps_cli::extensions::widgets::parse_widget_event(
                                        &frame.method,
                                        &frame.params,
                                    )
                                {
                                    let _ = widget_tx.send(
                                        synaps_cli::extensions::widgets::ExtensionWidgetEvent {
                                            extension_id: ext_id.clone(),
                                            event,
                                        },
                                    );
                                }
                            }
                        }
                        // rx closed (EOF/restart) — resubscribe after a brief delay
                        tokio::time::sleep(std::time::Duration::from_millis(500)).await;
                    }
                });
            }
        }
    }
}

/// Phase 8 slice 8A.8: when a plugin has staked a lifecycle claim and
/// declared a `settings_category`, copy the legacy global
/// `sidecar_toggle_key` value into the plugin-namespaced equivalent
/// (`plugins.{plugin}.{cat}._lifecycle_toggle_key`) so the user's
/// toggle-key choice follows them across the rename. Idempotent: any
/// claim whose new key is already set is skipped, and a missing legacy
/// value is a no-op.
fn migrate_sidecar_toggle_key_to_claimed_plugins(
    claims: &[synaps_cli::skills::registry::LifecycleClaim],
) {
    const LEGACY: &str = "sidecar_toggle_key";
    let Some(legacy_value) = synaps_cli::config::read_config_value(LEGACY) else {
        return;
    };
    let trimmed = legacy_value.trim();
    if trimmed.is_empty() {
        return;
    }
    for claim in claims {
        let Some(ref cat) = claim.settings_category else {
            continue;
        };
        let new_key = format!("plugins.{}.{}._lifecycle_toggle_key", claim.plugin, cat);
        if synaps_cli::config::read_config_value(&new_key).is_some() {
            continue;
        }
        match synaps_cli::config::write_config_value(&new_key, trimmed) {
            Ok(()) => tracing::info!(
                "sidecar migration: copied global `{}` → `{}` for plugin `{}`",
                LEGACY,
                new_key,
                claim.plugin,
            ),
            Err(err) => tracing::warn!(
                "sidecar migration: failed to copy `{}` → `{}`: {}",
                LEGACY,
                new_key,
                err,
            ),
        }
    }
}

/// Look up the display name for a sidecar's owning plugin from the
/// lifecycle-claim snapshot. Returns `None` if no claim matches.
///
/// Phase 8 8A.5 follow-up: used post-spawn to populate
/// [`SidecarUiState::display_name`] from the registry claim.
fn pick_display_name_for_plugin(
    plugin_name: &str,
    claims: &[synaps_cli::skills::registry::LifecycleClaim],
) -> Option<String> {
    claims
        .iter()
        .find(|c| c.plugin == plugin_name)
        .map(|c| c.display_name.clone())
}

#[cfg(test)]
mod migration_tests {
    use super::*;
    use serial_test::serial;
    use synaps_cli::skills::registry::LifecycleClaim;

    fn make_test_home(subdir: &str) -> std::path::PathBuf {
        let dir = std::path::PathBuf::from(format!("/tmp/synaps-mig-test-{}", subdir));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(dir.join(".synaps-cli")).unwrap();
        dir
    }

    fn with_home<F: FnOnce()>(home: &std::path::Path, f: F) {
        let original = std::env::var("HOME").ok();
        std::env::set_var("HOME", home);
        f();
        if let Some(h) = original {
            std::env::set_var("HOME", h);
        } else {
            std::env::remove_var("HOME");
        }
    }

    fn claim(plugin: &str, command: &str, cat: Option<&str>) -> LifecycleClaim {
        LifecycleClaim {
            plugin: plugin.to_string(),
            command: command.to_string(),
            settings_category: cat.map(str::to_string),
            display_name: command.to_string(),
            importance: 0,
        }
    }

    #[test]
    #[serial]
    fn migrate_copies_legacy_into_namespaced_key() {
        let home = make_test_home("copy-into-namespaced");
        let cfg = home.join(".synaps-cli/config");
        std::fs::write(&cfg, "sidecar_toggle_key = F2\n").unwrap();
        with_home(&home, || {
            migrate_sidecar_toggle_key_to_claimed_plugins(&[claim(
                "sample-sidecar",
                "capture",
                Some("capture"),
            )]);
            let v = synaps_cli::config::read_config_value(
                "plugins.sample-sidecar.capture._lifecycle_toggle_key",
            );
            assert_eq!(v.as_deref(), Some("F2"));
        });
    }

    #[test]
    #[serial]
    fn migrate_skips_when_new_key_already_set() {
        let home = make_test_home("skip-existing");
        let cfg = home.join(".synaps-cli/config");
        std::fs::write(
            &cfg,
            "sidecar_toggle_key = F2\nplugins.sample-sidecar.capture._lifecycle_toggle_key = F12\n",
        )
        .unwrap();
        with_home(&home, || {
            migrate_sidecar_toggle_key_to_claimed_plugins(&[claim(
                "sample-sidecar",
                "capture",
                Some("capture"),
            )]);
            let v = synaps_cli::config::read_config_value(
                "plugins.sample-sidecar.capture._lifecycle_toggle_key",
            );
            assert_eq!(
                v.as_deref(),
                Some("F12"),
                "must not overwrite a user-set value"
            );
        });
    }

    #[test]
    #[serial]
    fn migrate_is_noop_when_legacy_unset() {
        let home = make_test_home("noop-no-legacy");
        let cfg = home.join(".synaps-cli/config");
        std::fs::write(&cfg, "model = claude-sonnet-4-6\n").unwrap();
        with_home(&home, || {
            migrate_sidecar_toggle_key_to_claimed_plugins(&[claim(
                "sample-sidecar",
                "capture",
                Some("capture"),
            )]);
            assert!(synaps_cli::config::read_config_value(
                "plugins.sample-sidecar.capture._lifecycle_toggle_key"
            )
            .is_none());
        });
    }

    #[test]
    #[serial]
    fn migrate_skips_claim_without_settings_category() {
        let home = make_test_home("skip-no-category");
        let cfg = home.join(".synaps-cli/config");
        std::fs::write(&cfg, "sidecar_toggle_key = F8\n").unwrap();
        with_home(&home, || {
            migrate_sidecar_toggle_key_to_claimed_plugins(&[claim("p", "ocr", None)]);
            // No namespaced key written for a claim with no category.
            let contents = std::fs::read_to_string(&cfg).unwrap();
            assert!(
                !contents.contains("_lifecycle_toggle_key"),
                "no namespaced key should be written when settings_category is None: {contents}"
            );
        });
    }

    #[test]
    #[serial]
    fn migrate_handles_multiple_claims_in_one_pass() {
        let home = make_test_home("multi-claim");
        let cfg = home.join(".synaps-cli/config");
        std::fs::write(&cfg, "sidecar_toggle_key = C-V\n").unwrap();
        with_home(&home, || {
            migrate_sidecar_toggle_key_to_claimed_plugins(&[
                claim("sample-sidecar", "capture", Some("capture")),
                claim("ocr-plugin", "ocr", Some("ocr")),
            ]);
            assert_eq!(
                synaps_cli::config::read_config_value(
                    "plugins.sample-sidecar.capture._lifecycle_toggle_key"
                )
                .as_deref(),
                Some("C-V")
            );
            assert_eq!(
                synaps_cli::config::read_config_value(
                    "plugins.ocr-plugin.ocr._lifecycle_toggle_key"
                )
                .as_deref(),
                Some("C-V")
            );
        });
    }
}

#[cfg(test)]
mod display_name_helper_tests {
    use super::pick_display_name_for_plugin;
    use synaps_cli::skills::registry::LifecycleClaim;

    fn claim(plugin: &str, display: &str) -> LifecycleClaim {
        LifecycleClaim {
            plugin: plugin.into(),
            command: "capture".into(),
            settings_category: None,
            display_name: display.into(),
            importance: 0,
        }
    }

    #[test]
    fn pick_display_name_for_plugin_returns_match() {
        let claims = vec![claim("sample-sidecar", "Sample")];
        assert_eq!(
            pick_display_name_for_plugin("sample-sidecar", &claims),
            Some("Sample".to_string())
        );
    }

    #[test]
    fn pick_display_name_for_plugin_returns_none_for_unmatched() {
        let claims = vec![claim("sample-sidecar", "Sample")];
        assert_eq!(pick_display_name_for_plugin("unknown", &claims), None);
    }

    #[test]
    fn pick_display_name_for_plugin_returns_none_with_empty_claims() {
        assert_eq!(pick_display_name_for_plugin("sample-sidecar", &[]), None);
    }
}