eclipse-cli 0.13.4

Command-line interface for eclipse
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
//! What the TUI holds: the transcript, the composer, the readout, and the pending approval.
//!
//! No terminal I/O lives here, so all of it is testable without a terminal: keys go in
//! through [`App::on_key`] and events through [`App::on_event`], and the view renders the
//! result. That split is what keeps the drawing code honest.

use crate::approve::Choice;
use crate::status::Status;
use eclipse_core::commands::{self, Command, Completion, Front};
use eclipse_core::usage::TurnUsage;
use eclipse_core::AgentEvent;

/// One entry in the scrollback.
#[derive(Debug, Clone, PartialEq)]
pub enum Block {
    /// The pane the interface opens on. Drawn once and then scrolled past like anything else —
    /// it is a `Block`, not a separate layout region, because a header that never scrolls eats
    /// the screen on a short terminal.
    ///
    /// It carries facts, not a pre-rendered picture: the width is not known until drawing, and a
    /// banner that cannot reflow is a banner that wraps into nonsense at 80 columns.
    Welcome(Welcome),
    User(String),
    /// Assistant text. `done` is false while deltas are still arriving, which is what the
    /// spinner and the composer lock key off.
    Reply {
        text: String,
        done: bool,
    },
    /// Reasoning/thinking text emitted by a reasoning-capable model. Rendered dim,
    /// distinct from the reply so the answer stays readable next to it.
    Reasoning {
        text: String,
        done: bool,
    },
    Tool {
        /// The model's id for the call (`#366`): what pairs a result with its row. Two calls of one
        /// tool in a turn share a name, and matching by name put the mark on the wrong one.
        call_id: String,
        name: String,
        args: String,
        state: ToolState,
        output: String,
    },
    Note {
        kind: NoteKind,
        text: String,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToolState {
    Running,
    Ok,
    Failed,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NoteKind {
    Info,
    Warn,
    Error,
}

/// What the agent is doing right now, for the status line.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Activity {
    Idle,
    Requesting,
    Streaming,
    Tool(String),
}

/// A tool waiting for a decision. The reply channel is how the approval reaches the
/// runtime: the run is parked inside `Approver::approve` until the key arrives.
pub struct Approval {
    pub tool: String,
    pub summary: String,
    /// Which of the three answers the cursor is on.
    pub choice: Choice,
    pub reply: tokio::sync::oneshot::Sender<Choice>,
}

impl Approval {
    pub fn new(tool: String, summary: String, reply: tokio::sync::oneshot::Sender<Choice>) -> Self {
        Self {
            tool,
            summary,
            // The cursor rests on Deny: an accidental Enter must not run a command.
            choice: Choice::Deny,
            reply,
        }
    }

    /// Move the cursor, wrapping at both ends.
    pub fn move_by(&mut self, step: isize) {
        let n = Choice::ALL.len() as isize;
        let at = Choice::ALL
            .iter()
            .position(|c| *c == self.choice)
            .unwrap_or(Choice::ALL.len() - 1) as isize;
        let next = (at + step).rem_euclid(n) as usize;
        self.choice = Choice::ALL[next];
    }
}

/// What a key press asks the event loop to do.
#[derive(Debug, PartialEq, Eq)]
pub enum Action {
    None,
    /// Open this stored session: the loop loads it, because loading is I/O.
    Resume(String),
    /// Send this text to the model.
    Submit(String),
    /// Stop the run in flight; the prompt stays in the session.
    CancelRun,
    Quit,
    /// A slash command the loop handles; carries the command word.
    Command(String),
    /// Use this model from the next turn on, for this session only.
    /// `/model`: the chosen model, and the route its list came from (`None` for a lone route).
    PickModel(String, Option<String>),
    /// `/model` step one: ask this route what it serves.
    PickProvider(String),
}

#[derive(Debug, Default)]
pub struct History {
    entries: Vec<String>,
    /// Where up/down currently is; `None` means "at the line being written".
    at: Option<usize>,
    draft: String,
}

impl History {
    pub fn push(&mut self, line: &str) {
        if line.trim().is_empty() || self.entries.last().map(String::as_str) == Some(line) {
            return;
        }
        self.entries.push(line.to_string());
    }

    #[cfg(test)]
    pub fn entries(&self) -> &[String] {
        &self.entries
    }

    fn previous(&mut self, current: &str) -> Option<String> {
        if self.entries.is_empty() {
            return None;
        }
        let next = match self.at {
            None => {
                self.draft = current.to_string();
                self.entries.len() - 1
            }
            Some(0) => 0,
            Some(i) => i - 1,
        };
        self.at = Some(next);
        Some(self.entries[next].clone())
    }

    fn next(&mut self) -> Option<String> {
        let at = self.at?;
        if at + 1 >= self.entries.len() {
            self.at = None;
            return Some(std::mem::take(&mut self.draft));
        }
        self.at = Some(at + 1);
        Some(self.entries[at + 1].clone())
    }

    fn reset(&mut self) {
        self.at = None;
        self.draft.clear();
    }
}

pub struct App {
    pub blocks: Vec<Block>,
    /// How many transcript **blocks** have already been printed into the terminal's own
    /// scrollback. The screen shows only what comes after them; everything before is history the
    /// terminal owns, which is why scrolling, selecting and copying are the terminal's business
    /// and not this program's.
    ///
    /// A count of blocks rather than of lines, because a line count is not a place: `^T` and a
    /// resize both change the height of what was already printed, and a number that meant "line
    /// 412" would then point into a transcript rearranged around it. Block boundaries do not move.
    pub printed: usize,
    /// The fold state each printed block was rendered at — `None` until it is printed. A block in
    /// the scrollback cannot be folded or unfolded (a terminal has no way to rewrite it), so it
    /// keeps rendering as it was printed, and `^T` governs the tail. Without this, unfolding a
    /// block above the watermark inserts lines the printer has already passed, and the next frame
    /// prints them again.
    pub fold: Vec<Option<bool>>,
    /// `/reasoning`: what this screen draws, and the dial it writes to. `display` is the screen's
    /// own — the plain REPL and the dashboard each have theirs — and it is frozen per printed block
    /// in `frozen_display` for the same reason `fold` exists: a terminal only appends, so a block
    /// already in the scrollback cannot change height under the pointer.
    /// The dial and the screen's own mode; `None` in an interface built without a provider.
    pub reasoning: Option<crate::reasoning_cli::Live>,
    /// What the next request's route offers, as data: `/reasoning` answers for any level from this
    /// without touching the agent.
    pub reasoning_control: Option<eclipse_core::provider::Reasoning>,
    /// The mode each printed block was rendered at, frozen like `fold`.
    pub frozen_display: Vec<crate::reasoning_cli::Mode>,
    /// Set by `^T` when there is nothing left it can open in place: the printed, folded reasoning
    /// block whose text the next paint should append below everything. A terminal only appends, so
    /// this is the one honest way to show reasoning that is already behind the boundary.
    pub echo: Option<usize>,
    pub input: String,
    /// Cursor position in `input`, as a character index.
    pub cursor: usize,
    pub history: History,
    /// Whether reasoning is shown at its full length. Off by default: a reasoning model can
    /// spend a page and a half before it says anything, and the point of the block while it
    /// streams is "still working", not the text. Ctrl+T toggles it for every block at once —
    /// per-block toggles would need a focus the scrollback does not have.
    pub show_thinking: bool,
    pub status: Status,
    pub activity: Activity,
    pub approval: Option<Approval>,
    pub running: bool,
    pub session: Option<String>,
    pub profile: Option<String>,
    pub model: String,
    /// The `/resume` list, when it is up.
    pub picker: Option<Picker>,
    /// The slash-command list, when it is up. It owns a few keys, not the keyboard: anything it
    /// does not use goes to the line as usual.
    pub menu: Option<Menu>,
    /// Esc said no to the menu for the rest of this line. Without it the filter — which now runs on
    /// every keystroke, so a wrong letter can be taken back — would undo the one keystroke that
    /// means "I do not want this" (#253).
    pub menu_dismissed: bool,
    /// What the endpoint last said it serves; empty until `/model` asks.
    pub models: Vec<String>,
    /// True while `/model` is waiting on the endpoint's answer. Visible in the readout and
    /// named if a key is pressed in the meantime: a list that is one second away must not look
    /// like a keystroke that did nothing.
    pub listing_models: bool,
    pub workspace: String,
    pub quit: bool,
    /// Increments on every event, so the spinner has something to turn with.
    pub ticks: u64,
    /// Set when the last run failed, so the composer keeps the text that failed.
    pub last_error: Option<String>,
    /// Which profile, from which file, under which home, writing sessions where. Filled by the
    /// caller that read the config — `/profile` reports it rather than working out a path again.
    pub place: Option<eclipse_core::config::Where>,
    /// `/yolo`: the shared switch the readout reads. The value is the caller's flag, not a copy,
    /// so `/yolo off` takes the amber word off the bar on the next frame.
    pub yolo: crate::yolo::Yolo,
    /// The config file this interface was started with. `/settings` lists it, `/set` writes it.
    /// A field rather than an argument because `act` is called from tests all over the tree and
    /// threading a path through every one of them would be churn for one command.
    pub config_path: Option<std::path::PathBuf>,
    /// Pastes that were too big, or too multi-line, to sit in a one-line composer. The line shows
    /// a chip and this keeps the text, which goes back in on submit.
    pub pastes: Vec<Paste>,
    /// The update badge, while the installed version is behind the newest answer. This is a
    /// comparison, not a notice: it stays for as long as the install is behind, which is why it
    /// is a field the loop re-reads rather than a line pushed into the transcript.
    pub update: Option<eclipse_core::update::Behind>,
    /// Where the badge is read from. `None` when there is nothing to watch: `[update] check =
    /// "off"`, no install marker, or no state directory.
    pub update_watch: Option<eclipse_core::update::Watch>,
}

/// A paste held aside. `chip` is what the composer shows, and is what the line is searched for
/// when the text is put back — so a chip someone deleted stays deleted instead of coming back.
/// The paste rule is `eclipse_core::paste`'s, re-exported here so the TUI's own code and tests read
/// the names they always did — the dashboard's composer follows the same threshold (#220).
pub use eclipse_core::paste::{Paste, PASTE_INLINE_LIMIT};

/// What the opening pane says. Every field is something the agent actually knows — a banner
/// that lists skills nobody wrote is a lie on the first screen, so an empty `skills` draws
/// nothing at all.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Welcome {
    pub version: String,
    pub model: String,
    pub endpoint: String,
    pub profile: Option<String>,
    pub workspace: String,
    /// Advertised tools, grouped by where they came from: `builtin`, `plugin:<name>`,
    /// `skill:<name>`. The labels come from `ToolSource::label`, so a new source appears here
    /// without this type changing.
    pub groups: Vec<(String, Vec<String>)>,
    /// Skills that loaded, grouped by where they were found: `shared`, `profile:<p>`,
    /// `workspace`, `plugin:<name>`. The same shape as `groups`, but kept apart because a skill
    /// is not a tool and `tool_count` must not count it.
    pub skills: Vec<(String, Vec<String>)>,
    /// Whether approvals were automatic when the interface opened — `--yes` or
    /// `[cli] approval = "auto"`. The launch panel says it; the readout carries the live value,
    /// because a `/yolo` after this block was drawn would leave the block stale.
    pub approvals: bool,
}

impl Welcome {
    /// How many skills the pane lists.
    pub fn skill_count(&self) -> usize {
        self.skills.iter().map(|(_, names)| names.len()).sum()
    }
}

/// How long ago, in the words a person uses rather than milliseconds.
///
/// Deliberately coarse: "3 days" is what somebody needs to tell two sessions apart, and a
/// timestamp to the second is noise in a list they are scanning.
pub fn ago(updated_ms: u64) -> String {
    if updated_ms == 0 {
        return "never".to_string();
    }
    let now = eclipse_core::session::now_ms();
    let secs = now.saturating_sub(updated_ms) / 1000;
    match secs {
        0..=59 => "just now".to_string(),
        60..=3599 => format!("{}m ago", secs / 60),
        3600..=86_399 => format!("{}h ago", secs / 3600),
        86_400..=2_591_999 => format!("{}d ago", secs / 86_400),
        _ => format!("{}mo ago", secs / 2_592_000),
    }
}

/// Rebuild the visible transcript from a stored session.
///
/// The store keeps *messages*; the screen keeps *blocks*, and they are not the same shape. A
/// tool call and its result are two messages but one block, so the pairing happens here instead
/// of being hoped for at render time.
///
/// Returns the blocks and whether the session ends with a call that was never answered — the
/// signature of a run stopped mid-tool. The caller says so out loud, because the next run will
/// answer that call with a placeholder and the model would otherwise find a stranger's answer
/// in its own history.
pub fn blocks_from(records: &[eclipse_core::session::Record]) -> (Vec<Block>, bool) {
    use eclipse_core::message::Role;

    let mut blocks: Vec<Block> = Vec::new();
    // Call id -> index of the block still waiting for its result.
    let mut waiting: Vec<(String, usize)> = Vec::new();

    for record in records {
        let message = &record.message;
        match message.role {
            Role::System => {} // not part of the conversation the reader sees
            Role::User => {
                if let Some(text) = &message.content {
                    if !text.trim().is_empty() {
                        blocks.push(Block::User(text.clone()));
                    }
                }
            }
            Role::Assistant => {
                // An assistant turn can be prose, calls, or both; an empty content with calls
                // is the normal shape, so only non-blank text becomes a reply.
                if let Some(reasoning) = &message.reasoning {
                    if !reasoning.trim().is_empty() {
                        blocks.push(Block::Reasoning {
                            text: reasoning.clone(),
                            done: true,
                        });
                    }
                }
                if let Some(text) = &message.content {
                    if !text.trim().is_empty() {
                        blocks.push(Block::Reply {
                            text: text.clone(),
                            done: true,
                        });
                    }
                }
                for call in &message.tool_calls {
                    waiting.push((call.id.clone(), blocks.len()));
                    blocks.push(Block::Tool {
                        call_id: call.id.clone(),
                        name: call.function.name.clone(),
                        args: call.function.arguments.clone(),
                        state: ToolState::Running,
                        output: String::new(),
                    });
                }
            }
            Role::Tool => {
                let id = message.tool_call_id.clone().unwrap_or_default();
                let output = message.content.clone().unwrap_or_default();
                let slot = waiting
                    .iter()
                    .position(|(call_id, _)| *call_id == id)
                    .map(|i| waiting.remove(i).1);
                match slot {
                    Some(index) => {
                        if let Block::Tool {
                            state, output: out, ..
                        } = &mut blocks[index]
                        {
                            *out = output;
                            *state = ToolState::Ok;
                        }
                    }
                    // A result with no call: the transcript was written by something that
                    // disagreed with itself. Showing it is better than dropping it silently.
                    None => blocks.push(Block::Note {
                        kind: NoteKind::Warn,
                        text: format!("a tool result arrived with no matching call ({id})"),
                    }),
                }
            }
        }
    }

    // Whatever is still waiting was never answered: the run was stopped between the call and
    // its result. Showing it as "running" would spin forever, so it says what happened.
    for (_, index) in waiting.drain(..) {
        if let Block::Tool { state, output, .. } = &mut blocks[index] {
            *state = ToolState::Failed;
            *output = "no result: the run was interrupted before this call returned".to_string();
        }
    }

    let interrupted = blocks.iter().any(|b| {
        matches!(
            b,
            Block::Tool {
                state: ToolState::Failed,
                output,
                ..
            } if output.starts_with("no result:")
        )
    });
    (blocks, interrupted)
}

/// One row of the session picker: what a person needs to recognise the session they mean.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Picked {
    pub id: String,
    pub title: Option<String>,
    /// A short remark shown beside the label when the list has one — `current` for the model in
    /// use, `pinned` for a session no prune can take. Empty when there is nothing to add.
    pub note: String,
    /// When it was last touched, already formatted for display.
    pub ago: String,
    pub messages: usize,
    pub preview: String,
}

impl Picked {
    /// The line the cursor is on.
    pub fn label(&self) -> String {
        match &self.title {
            Some(title) if !title.trim().is_empty() => title.clone(),
            _ => {
                let preview = self.preview.trim();
                if preview.is_empty() {
                    "untitled".to_string()
                } else {
                    preview.to_string()
                }
            }
        }
    }
}

/// What a [`Picker`] is choosing between. The list looks the same; what Enter does does not.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PickerKind {
    /// `/resume`: a stored session.
    #[default]
    Sessions,
    /// `/model`, first step: which route to ask, when the configuration has more than one.
    Provider,
    /// `/model`, second step: a model the chosen endpoint serves.
    Model,
    /// `/tasks`: a background run. Enter opens its session, which is what a task is.
    Tasks,
}

/// The list `/resume` and `/model` put up. Owns the keyboard while it is up, exactly like an
/// approval: a stray key must not switch the session — or the model — out from under a person.
#[derive(Debug, Clone, Default)]
pub struct Picker {
    pub kind: PickerKind,
    /// The words in the title: what is being chosen.
    pub title: &'static str,
    /// The rows the query lets through — what is drawn and what the cursor moves over.
    pub items: Vec<Picked>,
    /// Every row handed over, unfiltered. Kept so a backspace restores rows without asking the
    /// store again, and so the count can say "3 of 12" instead of lying about how many exist.
    pub all: Vec<Picked>,
    /// What has been typed to narrow the list. Empty shows everything.
    pub query: String,
    pub cursor: usize,
    /// `/model`'s first step, carried into the second: which route the list of models came from.
    /// `None` when there was only one route to ask, so the two steps collapse into the old one.
    pub route: Option<String>,
}

/// Where `needle` appears in `hay` as a subsequence, case-insensitively: the position of the last
/// character it consumed, so a tighter match sorts earlier, or `None` when a character is missing.
///
/// Subsequence rather than substring because that is how people type at a list: `mx` finds
/// "max", `sess` finds "session search". Spaces in the query are separators, not characters —
/// a trailing space from a fat-fingered word must not empty the list.
fn fuzzy_at(needle: &str, hay: &str) -> Option<usize> {
    let hay: Vec<char> = hay.chars().flat_map(char::to_lowercase).collect();
    let mut from = 0;
    let mut last = 0;
    for want in needle.chars().flat_map(char::to_lowercase) {
        if want.is_whitespace() {
            continue;
        }
        let found = hay.get(from..)?.iter().position(|c| *c == want)?;
        last = from + found;
        from = last + 1;
    }
    Some(last)
}

impl Picker {
    /// Build a list with everything visible. The one way a `Picker` is made, so `all` can never
    /// disagree with the rows on screen.
    fn of(
        kind: PickerKind,
        title: &'static str,
        items: Vec<Picked>,
        cursor: usize,
        route: Option<String>,
    ) -> Self {
        Self {
            kind,
            title,
            all: items.clone(),
            items,
            query: String::new(),
            cursor,
            route,
        }
    }

    pub fn move_by(&mut self, delta: isize) {
        if self.items.is_empty() {
            return;
        }
        let last = self.items.len() - 1;
        let next = self.cursor as isize + delta;
        self.cursor = next.clamp(0, last as isize) as usize;
    }

    pub fn current(&self) -> Option<&Picked> {
        self.items.get(self.cursor)
    }

    /// Narrow the list to what the query still matches. The cursor goes back to the top: it was
    /// pointing at a row of the old list, and that row may no longer be there.
    pub fn type_char(&mut self, c: char) {
        if c.is_control() {
            return;
        }
        self.query.push(c);
        self.refilter();
    }

    /// Remove the last character. False when there was nothing to remove, so the caller can
    /// decide what an empty backspace means (it closes the list).
    pub fn backspace(&mut self) -> bool {
        if self.query.pop().is_none() {
            return false;
        }
        self.refilter();
        true
    }

    /// Drop the query and show everything again. False when there was no query, so `esc` can
    /// mean "clear" once and "close" the second time.
    pub fn clear_query(&mut self) -> bool {
        if self.query.is_empty() {
            return false;
        }
        self.query.clear();
        self.refilter();
        true
    }

    fn refilter(&mut self) {
        self.cursor = 0;
        if self.query.trim().is_empty() {
            self.items = self.all.clone();
            return;
        }
        // Rank by how tight the match is, then by the order the list came in — which for
        // sessions is recency, so two equally good matches still put the newer one first.
        let mut scored: Vec<(usize, usize, Picked)> = self
            .all
            .iter()
            .enumerate()
            .filter_map(|(i, p)| {
                let hay = format!("{} {} {}", p.label(), p.preview, p.id);
                fuzzy_at(&self.query, &hay).map(|at| (at, i, p.clone()))
            })
            .collect();
        scored.sort_by_key(|(at, i, _)| (*at, *i));
        self.items = scored.into_iter().map(|(_, _, p)| p).collect();
    }

    /// `12 stored` — or `3 of 12 stored` while a query is narrowing it, so the count never
    /// pretends the list is shorter than it is.
    pub fn count_label(&self) -> String {
        let what = match self.kind {
            PickerKind::Sessions => "stored",
            PickerKind::Provider => "configured",
            PickerKind::Model => "served",
            PickerKind::Tasks => "tasks",
        };
        if self.query.trim().is_empty() {
            format!("{} {}", self.all.len(), what)
        } else {
            format!("{} of {} {}", self.items.len(), self.all.len(), what)
        }
    }

    /// The name under the cursor, for tests that care which row a key landed on.
    #[cfg(test)]
    pub fn cursor_name(&self) -> Option<&str> {
        self.current().map(|p| p.id.as_str())
    }
}

/// The slash-command list that opens above the line on `/` or Tab: the commands whose word
/// starts with what has been typed so far.
#[derive(Debug, Clone, Default)]
pub struct Menu {
    pub items: Vec<&'static Command>,
    pub cursor: usize,
}

impl Menu {
    pub fn move_by(&mut self, delta: isize) {
        if self.items.is_empty() {
            return;
        }
        let last = self.items.len() - 1;
        let next = self.cursor as isize + delta;
        self.cursor = next.clamp(0, last as isize) as usize;
    }

    pub fn current(&self) -> Option<&'static Command> {
        self.items.get(self.cursor).copied()
    }
}

impl Welcome {
    /// The number of tools actually offered to the model, not the number registered.
    pub fn tool_count(&self) -> usize {
        self.groups.iter().map(|(_, names)| names.len()).sum()
    }
}

impl App {
    pub fn new(status: Status, model: &str, workspace: &str, profile: Option<String>) -> Self {
        Self {
            blocks: Vec::new(),
            reasoning: None,
            reasoning_control: None,
            frozen_display: Vec::new(),
            input: String::new(),
            cursor: 0,
            history: History::default(),
            printed: 0,
            fold: Vec::new(),
            echo: None,
            show_thinking: false,
            session: status.session.clone(),
            status,
            activity: Activity::Idle,
            approval: None,
            running: false,
            profile,
            model: model.to_string(),
            models: Vec::new(),
            listing_models: false,
            picker: None,
            menu: None,
            menu_dismissed: false,
            workspace: workspace.to_string(),
            quit: false,
            ticks: 0,
            last_error: None,
            place: None,
            yolo: crate::yolo::Yolo::new(false),
            config_path: None,
            pastes: Vec::new(),
            update: None,
            update_watch: None,
        }
    }

    /// Ask the disk whether the badge has changed, and say so. Called on a tick: the check that
    /// fills the cache runs in the background, so an answer that lands a second into the run has
    /// to reach the screen without the loop waiting for it.
    pub fn reread_update(&mut self) -> bool {
        let Some(watch) = &self.update_watch else {
            return false;
        };
        let now = watch.read();
        if now == self.update {
            return false;
        }
        self.update = now;
        true
    }

    /// Show the session list. Replaces whatever the screen held: this is a switch, not a layer.
    pub fn set_sessions(&mut self, items: Vec<Picked>) {
        if items.is_empty() {
            self.note(
                NoteKind::Info,
                "no sessions yet — this one becomes the first when you send something",
            );
            self.picker = None;
            return;
        }
        self.picker = Some(Picker::of(PickerKind::Sessions, "session", items, 0, None));
    }

    /// Re-read the reasoning dial into the read-out (`#264`).
    ///
    /// Called from the painter rather than from `/reasoning`'s arm: the dial is shared with the
    /// agent, `/model` can change what a level *becomes*, and a read-out refreshed at one call site
    /// eventually disagrees with another. The expensive half — resolving the provider profile into
    /// a sentence — only runs when the level, the origin or the override state actually moved, so
    /// an idle screen costs two mutex reads a frame.
    pub fn refresh_effort(&mut self) {
        let Some(report) = self.effort_report() else {
            self.status.effort = None;
            return;
        };
        if self.status.effort.as_ref().is_some_and(|e| {
            e.label == report.label
                && e.session == report.session
                && e.by_default == report.by_default
        }) {
            return;
        }
        self.status.effort = Some(report);
    }

    /// The dial's answer for this screen, with the route's declared default in hand (`#276`).
    ///
    /// The same three answers `Agent::reasoning_report()` gives — session, file, backend default —
    /// built from the dial and the control this interface already holds, so `/reasoning`, the
    /// read-out and `/status` cannot describe the same dial differently.
    pub fn effort_report(&self) -> Option<eclipse_core::reasoning::InForce> {
        let live = self.reasoning.as_ref()?;
        Some(eclipse_core::reasoning::report_for(
            &live.dial,
            self.reasoning_control.as_ref(),
        ))
    }

    /// `/tasks`: the background runs (#225).
    ///
    /// The rows are `/resume`'s shape, because a task is a session: Enter opens the transcript the
    /// run is writing. What differs is the note — the state and how long ago it was last seen —
    /// and the detail line, which is the session id and the last thing the run did.
    pub fn set_tasks(&mut self, tasks: Vec<eclipse_core::tasks::Task>) {
        if tasks.is_empty() {
            self.note(
                NoteKind::Info,
                "no background tasks — `/bg <prompt>` starts one",
            );
            self.picker = None;
            return;
        }
        let items: Vec<Picked> = tasks
            .into_iter()
            .map(|t| {
                let state = t.state_now();
                Picked {
                    id: t.session.clone(),
                    title: Some(t.prompt.clone()),
                    note: format!("{} · {}", state.word(), ago(t.updated_ms)),
                    ago: ago(t.updated_ms),
                    messages: 0,
                    // The pid while the process is alive (it is how a task is stopped) and
                    // whatever it last did once it is not.
                    preview: if t.settled() {
                        if t.detail.is_empty() {
                            t.last.clone()
                        } else {
                            format!("{} ({})", t.last, t.detail)
                        }
                    } else {
                        format!("pid {} · {}", t.pid, t.last)
                    },
                }
            })
            .collect();
        self.picker = Some(Picker::of(PickerKind::Tasks, "task", items, 0, None));
    }

    /// `/model`: put the endpoint's list up as a menu, with the one in use marked and the cursor
    /// on it. A list you have to read and then type from is the thing this replaces — the number
    /// it prints is worth keeping only where there are no arrow keys.
    /// The same list, remembering which route it came from: the model is then set on that route
    /// rather than on whichever one the run would have used.
    pub fn open_models_from(&mut self, route: Option<String>, models: Vec<String>) {
        if models.is_empty() {
            self.note(
                NoteKind::Warn,
                "the endpoint named no models; set `[provider] model` by hand",
            );
            self.picker = None;
            return;
        }
        let current = self.model.clone();
        let items: Vec<Picked> = models
            .into_iter()
            .map(|name| Picked {
                note: if name == current {
                    "current".to_string()
                } else {
                    String::new()
                },
                title: Some(name.clone()),
                id: name,
                ago: String::new(),
                messages: 0,
                preview: String::new(),
            })
            .collect();
        // The cursor starts where the reader is looking: the model already in use.
        let cursor = items.iter().position(|p| p.id == current).unwrap_or(0);
        self.picker = Some(Picker::of(PickerKind::Model, "model", items, cursor, route));
    }

    /// `/model`'s first step: which route to ask. Only shown when there is more than one, because
    /// a menu with a single row is a question with one answer.
    ///
    /// The row's detail line is the endpoint, which is the thing that actually differs between
    /// two routes called `cheap` and `fast` when both point at the same box.
    pub fn open_providers(
        &mut self,
        routes: &[eclipse_core::router::RouteInfo],
        current: Option<&str>,
    ) {
        let items: Vec<Picked> = routes
            .iter()
            .map(|r| Picked {
                id: r.name.clone(),
                note: if Some(r.name.as_str()) == current {
                    "current".to_string()
                } else {
                    String::new()
                },
                title: Some(r.name.clone()),
                ago: String::new(),
                messages: 0,
                preview: r.endpoint.clone(),
            })
            .collect();
        let cursor = current
            .and_then(|c| items.iter().position(|p| p.id == c))
            .unwrap_or(0);
        self.picker = Some(Picker::of(
            PickerKind::Provider,
            "provider",
            items,
            cursor,
            None,
        ));
    }

    /// Empty the transcript and forget the watermark.
    ///
    /// The scrollback keeps what it already has; what changes is which lines the painter has yet to
    /// print. The watermark is a count into *this* list, so it cannot survive the list being
    /// replaced — kept, it makes the next transcript start at line N of a list that has fewer.
    pub fn clear_transcript(&mut self) {
        self.blocks.clear();
        self.printed = 0;
        self.fold.clear();
        self.echo = None;
    }

    /// Replace the transcript with a loaded session. The welcome pane goes: it describes a
    /// fresh start, and this is not one.
    pub fn apply_session(&mut self, id: String, blocks: Vec<Block>, interrupted: bool) {
        self.picker = None;
        self.clear_transcript();
        self.blocks = blocks;
        self.session = Some(id.clone());
        self.status.session = Some(id);
        if interrupted {
            self.note(
                NoteKind::Warn,
                "the last turn was interrupted mid-tool-call; continuing answers that call with \
                 a placeholder, which the model will see",
            );
        }
    }

    /// Back to a session that does not exist yet, without restarting.
    pub fn start_new_session(&mut self, welcome: Option<Welcome>) {
        self.picker = None;
        self.session = None;
        self.status.session = None;
        self.clear_transcript();
        if let Some(welcome) = welcome {
            self.blocks.push(Block::Welcome(welcome));
        }
    }

    /// What the endpoint said it serves, kept so `/model 2` means something.
    /// The endpoint's answer to `/model`: keep it for `/model <n>` and put it up as a menu.
    ///
    /// The numbers are kept even though the menu is the way in now, because a name is not always
    /// easy to type and `/model 3` is. What is gone is the need to read a list and retype it.
    /// The same, remembering which route answered: `/model <n>` then resolves against that list,
    /// and the model is set on that route.
    pub fn set_models_from(&mut self, route: Option<String>, models: Vec<String>) {
        if models.is_empty() {
            self.note(
                NoteKind::Warn,
                "the endpoint named no models; set `[provider] model` by hand",
            );
            self.models.clear();
            self.picker = None;
            return;
        }
        self.models = models.clone();
        self.open_models_from(route, models);
    }

    /// A number from the last listing, or an exact name.
    pub fn resolve_model(&self, arg: &str) -> Option<String> {
        if let Ok(n) = arg.parse::<usize>() {
            if let Some(name) = self.models.get(n.saturating_sub(1)) {
                return Some(name.clone());
            }
        }
        self.models.iter().find(|m| *m == arg).cloned()
    }

    /// Fold in what a probe found after a model switch: the window the endpoint advertises and
    /// the rail derived from it. A window of `0` means the probe got nothing, and then the
    /// readout keeps what it has rather than inventing a window or a threshold. A rail of `0`
    /// with a window is real — `compact_at = 0` is the threshold switched off.
    pub fn set_context(&mut self, window: usize, budget: usize) {
        if window > 0 {
            self.status.window = window;
            self.status.budget = budget;
        }
    }

    /// The name in the header is the model that will answer next; keep it honest.
    pub fn set_model_name(&mut self, name: &str) {
        self.model = name.to_string();
        // The readout at the bottom carries the same fact; it must not lag the header.
        self.status.model = name.to_string();
    }

    pub fn note(&mut self, kind: NoteKind, text: impl Into<String>) {
        self.blocks.push(Block::Note {
            kind,
            text: text.into(),
        });
    }

    /// True while a run is in flight: the composer refuses new prompts then, because the
    /// session is being written to by the run.
    pub fn busy(&self) -> bool {
        self.running
    }

    /// The last thing the model said, for a `--until` check after a loop tick (`#173`). `None`
    /// before the model has said anything, and never the empty placeholder a fold leaves.
    pub fn last_reply(&self) -> Option<String> {
        self.blocks.iter().rev().find_map(|b| match b {
            Block::Reply { text, .. } if !text.trim().is_empty() => Some(text.clone()),
            _ => None,
        })
    }

    /// Fold a runtime event into state. Every arm must be quiet: a run emits hundreds of
    /// deltas and the terminal is redrawn on the loop's schedule, not per event.
    /// Where a tool call's full output goes: `<state>/log/<session>.log`, beside the sessions it
    /// belongs to. The transcript prints one line per call and nothing else, so this file is what
    /// answers "what did that command actually print?" after the fact.
    fn tool_log_path(&self) -> Option<std::path::PathBuf> {
        let env = eclipse_core::config::process_env;
        let state = eclipse_core::config::state_dir_for(&env, self.profile.as_deref())?;
        let file = match &self.session {
            Some(id) => format!("{id}.log"),
            None => "unsaved.log".to_string(),
        };
        Some(state.join("log").join(file))
    }

    /// Best effort: a transcript that refuses to scroll because a log directory could not be created
    /// would be a worse trade than losing the log.
    fn log_tool(&self, name: &str, args: &str, output: &str, is_error: bool) {
        use std::io::Write as _;
        let Some(path) = self.tool_log_path() else {
            return;
        };
        if let Some(dir) = path.parent() {
            let _ = std::fs::create_dir_all(dir);
        }
        let Ok(mut file) = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&path)
        else {
            return;
        };
        let stamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        let _ = writeln!(
            file,
            "--- {stamp} {name} {} ---\n{name}({args})\n{}",
            if is_error { "ERROR" } else { "ok" },
            output.trim_end()
        );
    }

    pub fn on_event(&mut self, event: AgentEvent) {
        self.ticks = self.ticks.wrapping_add(1);
        match event {
            AgentEvent::Delta(text) => {
                self.activity = Activity::Streaming;
                match self.blocks.last_mut() {
                    Some(Block::Reply {
                        text: t,
                        done: false,
                    }) => t.push_str(&text),
                    _ => self.blocks.push(Block::Reply { text, done: false }),
                }
            }
            AgentEvent::ReasoningDelta(text) => match self.blocks.last_mut() {
                Some(Block::Reasoning {
                    text: t,
                    done: false,
                }) => t.push_str(&text),
                _ => self.blocks.push(Block::Reasoning { text, done: false }),
            },
            AgentEvent::ToolCallDelta { json, .. } => {
                // Partial arguments for the call currently being composed. Attach only to a
                // running Tool block; a fragment with no call waiting for it is noise.
                if let Some(Block::Tool {
                    args,
                    state: ToolState::Running,
                    ..
                }) = self.blocks.last_mut()
                {
                    args.push_str(&json);
                }
            }
            AgentEvent::Message(text) => {
                if let Some(Block::Reasoning { done, .. }) = self.blocks.last_mut() {
                    *done = true;
                }
                // The complete text supersedes whatever the deltas assembled.
                match self.blocks.last_mut() {
                    Some(Block::Reply { text: t, done }) => {
                        *t = text;
                        *done = true;
                    }
                    _ => self.blocks.push(Block::Reply { text, done: true }),
                }
                self.activity = Activity::Requesting;
            }
            AgentEvent::ToolCall {
                call_id,
                name,
                arguments,
            } => {
                if let Some(Block::Reasoning { done, .. }) = self.blocks.last_mut() {
                    *done = true;
                }
                self.activity = Activity::Tool(name.clone());
                self.blocks.push(Block::Tool {
                    call_id,
                    name,
                    args: arguments,
                    state: ToolState::Running,
                    output: String::new(),
                });
            }
            AgentEvent::ToolResult {
                call_id,
                name,
                output,
                is_error,
            } => {
                // The call this result answers, by id (`#366`). A fallback on the name is kept for
                // an event with no id, which nothing in this build sends — but a wrong mark is
                // worse than an unmatched row, so the id is tried first.
                let target = self
                    .blocks
                    .iter()
                    .position(|b| {
                        matches!(b, Block::Tool { call_id: c, state: ToolState::Running, .. } if !call_id.is_empty() && *c == call_id)
                    })
                    .or_else(|| {
                        self.blocks.iter().position(|b| {
                            matches!(b, Block::Tool { name: n, state: ToolState::Running, .. } if *n == name)
                        })
                    });
                let mut logged = None;
                if let Some(i) = target {
                    if let Block::Tool {
                        state,
                        output: o,
                        args,
                        ..
                    } = &mut self.blocks[i]
                    {
                        *state = if is_error {
                            ToolState::Failed
                        } else {
                            ToolState::Ok
                        };
                        logged = Some(args.clone());
                        *o = output.clone();
                    }
                }
                // The transcript prints one line per call, so this file is the only place the
                // output is kept in full.
                if let Some(args) = logged {
                    self.log_tool(&name, &args, &output, is_error);
                }
                self.activity = Activity::Requesting;
            }
            AgentEvent::TurnStats {
                usage,
                context_tokens,
                budget_tokens,
            } => {
                self.status
                    .record_with_context(usage, context_tokens, budget_tokens);
            }
            AgentEvent::SchemaRejected { error, retrying } => {
                let what = if retrying {
                    "reply did not match the schema; asking once more with the error"
                } else {
                    "reply still does not match the schema"
                };
                self.note(NoteKind::Warn, format!("{what}: {error}"));
            }
            AgentEvent::ContextTrimmed {
                turns,
                messages,
                judgement,
                ..
            } => {
                let mut text = format!(
                    "context: {turns} older turn(s), {messages} message(s) replaced by the \
                     compiled handoff"
                );
                match judgement {
                    eclipse_core::JudgementStatus::Off => {}
                    eclipse_core::JudgementStatus::Used { bullets } => {
                        text.push_str(&format!("; {bullets} judgement bullet(s) added"))
                    }
                    eclipse_core::JudgementStatus::Rejected(e) => {
                        text.push_str(&format!("; judgement rejected ({e})"))
                    }
                    eclipse_core::JudgementStatus::Failed(e) => {
                        text.push_str(&format!("; judgement failed ({e})"))
                    }
                }
                self.note(NoteKind::Warn, text);
            }
        }
    }

    /// The run finished (or failed). Unlocks the composer.
    /// Say where the answer came from when it did not come from the first route.
    pub fn on_routed(&mut self, hops: Vec<eclipse_core::router::Hop>) {
        if let Some(line) = eclipse_core::router::describe_hops(&hops) {
            self.note(NoteKind::Info, line);
        }
        self.status.record_hops(hops);
    }

    /// A run that delegated says how many children and what they cost, apart from the run's own
    /// usage.
    pub fn on_delegated(&mut self, children: &[eclipse_core::tools_delegate::ChildRun]) {
        if let Some(line) = eclipse_core::tools_delegate::describe_children(children) {
            self.note(NoteKind::Info, line);
        }
    }

    pub fn on_done(&mut self, outcome: Result<String, String>) {
        self.running = false;
        self.activity = Activity::Idle;
        if let Some(Block::Reply { done, .. }) = self
            .blocks
            .iter_mut()
            .rev()
            .find(|b| matches!(b, Block::Reply { .. }))
        {
            *done = true;
        }
        match outcome {
            Ok(id) => {
                self.session = Some(id);
                self.status.session = self.session.clone();
                self.last_error = None;
            }
            Err(e) => {
                self.note(NoteKind::Error, e.clone());
                self.last_error = Some(e);
            }
        }
    }

    pub fn answer_approval(&mut self, choice: Choice) {
        if let Some(a) = self.approval.take() {
            // A closed receiver means the run was cancelled meanwhile: nothing to tell.
            let _ = a.reply.send(choice);
        }
    }

    /// The answer the cursor is on, without moving it.
    pub fn pending_choice(&self) -> Option<Choice> {
        self.approval.as_ref().map(|a| a.choice)
    }

    // ---- the composer -------------------------------------------------------------

    pub fn insert(&mut self, ch: char) {
        let at = self.byte_at(self.cursor);
        self.input.insert(at, ch);
        self.cursor += 1;
        self.history.reset();
    }

    /// Take a paste from the terminal.
    ///
    /// Short single-line text goes into the line, because that is what a person pasting a path or
    /// a word means. Anything else becomes a numbered chip and is kept for `expand_pastes`: a
    /// composer is one line, so prose pasted into it would either be unreadable or — before
    /// bracketed paste was enabled — a submission per newline.
    pub fn take_paste(&mut self, text: &str) {
        // Terminals disagree about `\r`; a paste is text, so flatten it here rather than making
        // every reader below think about it.
        let text = text.replace("\r\n", "\n").replace('\r', "\n");
        let lines = text.lines().count().max(1);
        if lines == 1 && text.chars().count() <= PASTE_INLINE_LIMIT {
            self.insert_str(&text);
            return;
        }
        let chip = format!(
            "[Pasted #{}: {lines} line(s), {} chars]",
            self.pastes.len() + 1,
            text.chars().count()
        );
        self.insert_str(&chip);
        self.pastes.push(Paste { chip, text });
    }

    /// The line with its chips put back. A chip that is no longer in the line (deleted, or
    /// backspaced away as a unit) is not resurrected: the text was dropped with it.
    pub fn expand_pastes(&self, line: &str) -> String {
        let mut out = line.to_string();
        for paste in &self.pastes {
            if out.contains(&paste.chip) {
                out = out.replacen(&paste.chip, &paste.text, 1);
            }
        }
        out
    }

    /// The chip that ends exactly at the cursor, if any. `backspace` deletes it whole: a chip is
    /// one thing a person put there, and deleting it a character at a time was how you ended up
    /// with `[Pasted #1: 1,9` and a paste you could no longer see.
    fn chip_before_cursor(&self) -> Option<usize> {
        let at = self.byte_at(self.cursor);
        self.pastes
            .iter()
            .position(|p| self.input[..at].ends_with(&p.chip))
    }

    pub fn insert_str(&mut self, s: &str) {
        let at = self.byte_at(self.cursor);
        self.input.insert_str(at, s);
        self.cursor += s.chars().count();
        self.history.reset();
    }

    fn byte_at(&self, chars: usize) -> usize {
        self.input
            .char_indices()
            .nth(chars)
            .map(|(i, _)| i)
            .unwrap_or(self.input.len())
    }

    fn set_input(&mut self, text: String) {
        self.input = text;
        self.end();
        self.history.reset();
    }

    /// Open the menu for the line as it stands. Not while a picker or an approval is up, and
    /// only for a line that is a command word being typed.
    fn open_menu(&mut self, items: Vec<&'static Command>) {
        if self.picker.is_some() || self.approval.is_some() {
            return;
        }
        // Reaching here is an explicit ask — Tab — and an explicit ask outranks an earlier Esc:
        // Esc said "not the list as I type", not "never complete this line for me".
        self.menu_dismissed = false;
        // An empty list is still a menu: the line is a command word and nothing matches it, and
        // that is worth one row of screen rather than a menu that vanishes (#253).
        self.menu = Some(Menu { items, cursor: 0 });
    }

    /// Re-filter after the line changed. Keeps the highlight on the same command when it is still
    /// listed.
    ///
    /// The menu belongs to the line rather than to the keystroke that opened it: while the line is a
    /// command word the list is on screen, filtered, and when nothing matches it says so. This used
    /// to `take()` the menu and return on `Completion::None`, so the first wrong letter dropped it
    /// for the rest of the line and backspace had nothing left to refilter (#253).
    pub fn refilter_menu(&mut self) {
        if self.menu_dismissed || self.picker.is_some() || self.approval.is_some() {
            return;
        }
        // A space, or the `/` deleted: the line is prose now, and the menu goes for good.
        if !commands::is_command_word(&self.input) {
            self.menu = None;
            return;
        }
        // Where the highlight was, before the list it pointed into is replaced.
        let was = self.menu.take().and_then(|menu| menu.current());
        let items = commands::matching(&self.input, Front::Tui);
        let cursor = was
            .and_then(|c| items.iter().position(|i| *i == c))
            .unwrap_or(0);
        self.menu = Some(Menu { items, cursor });
    }

    /// Tab outside the menu: fill in a unique match, open the menu on several, else nothing.
    /// Only with the cursor at the end of the line, where completing cannot strand text.
    pub fn complete_command(&mut self) {
        if self.cursor != self.input.chars().count() {
            return;
        }
        match commands::complete(&self.input, Front::Tui) {
            Completion::Unique(c) => {
                let filled = c.fill(&self.input);
                self.set_input(filled);
            }
            Completion::Several(found) => self.open_menu(found),
            Completion::None => {}
        }
    }

    /// Put the highlighted command into the line and close the menu, without running it.
    pub fn accept_menu(&mut self) {
        if let Some(menu) = self.menu.take() {
            if let Some(c) = menu.current() {
                let filled = c.fill(&self.input);
                self.set_input(filled);
            }
        }
    }

    pub fn take(&mut self) -> String {
        let text = std::mem::take(&mut self.input);
        self.cursor = 0;
        self.menu_dismissed = false;
        self.history.reset();
        text
    }

    pub fn backspace(&mut self) {
        if self.cursor == 0 {
            return;
        }
        if let Some(idx) = self.chip_before_cursor() {
            let chip = self.pastes.remove(idx).chip;
            let at = self.byte_at(self.cursor);
            let start = at - chip.len();
            self.input.replace_range(start..at, "");
            self.cursor -= chip.chars().count();
            self.history.reset();
            return;
        }
        let end = self.byte_at(self.cursor);
        let start = self.byte_at(self.cursor - 1);
        self.input.replace_range(start..end, "");
        self.cursor -= 1;
        self.history.reset();
    }

    pub fn delete(&mut self) {
        if self.cursor >= self.input.chars().count() {
            return;
        }
        let start = self.byte_at(self.cursor);
        let end = self.byte_at(self.cursor + 1);
        self.input.replace_range(start..end, "");
        self.history.reset();
    }

    pub fn move_left(&mut self) {
        self.cursor = self.cursor.saturating_sub(1);
    }

    pub fn move_right(&mut self) {
        if self.cursor < self.input.chars().count() {
            self.cursor += 1;
        }
    }

    pub fn home(&mut self) {
        self.cursor = 0;
    }

    pub fn end(&mut self) {
        self.cursor = self.input.chars().count();
    }

    pub fn kill_line(&mut self) {
        self.input.clear();
        self.cursor = 0;
        // The line is gone, so the dismissal was about a line that no longer exists.
        self.menu_dismissed = false;
        self.menu = None;
    }

    pub fn earlier(&mut self) {
        if let Some(line) = self.history.previous(&self.input) {
            self.input = line;
            self.end();
        }
    }

    pub fn later(&mut self) {
        if let Some(line) = self.history.next() {
            self.input = line;
            self.end();
        }
    }

    /// Show reasoning in full, or fold it back to its preview. Printed blocks keep the state they
    /// were printed at; this governs the tail and everything printed from now on.
    pub fn toggle_thinking(&mut self) {
        self.show_thinking = !self.show_thinking;
    }

    /// The fold state block `index` renders at: its frozen one once printed, else the live flag.
    pub fn fold_for(&self, index: usize) -> bool {
        self.fold
            .get(index)
            .copied()
            .flatten()
            .unwrap_or(self.show_thinking)
    }

    /// What `/reasoning`'s display flag says for one block: its frozen value once printed, the live
    /// one before that. Same rule as [`App::fold_for`], for the same reason — a printed block cannot
    /// change height in the terminal's scrollback.
    pub fn display_for(&self, index: usize) -> crate::reasoning_cli::Mode {
        if index < self.printed {
            if let Some(frozen) = self.frozen_display.get(index) {
                return *frozen;
            }
        }
        self.reasoning
            .as_ref()
            .map(|live| live.display)
            .unwrap_or(crate::reasoning_cli::Mode::Folded)
    }

    /// Freeze everything before `upto` at the fold state it is about to be printed with.
    pub fn freeze_printed(&mut self, upto: usize) {
        if self.fold.len() < self.blocks.len() {
            self.fold.resize(self.blocks.len(), None);
        }
        for slot in self.fold.iter_mut().take(upto) {
            if slot.is_none() {
                *slot = Some(self.show_thinking);
            }
        }
        // The display mode is frozen with it, and only for the blocks being printed now: `/reasoning
        // hide` after a turn must not retract lines the terminal already holds, and `/reasoning
        // full` must not claim to open them.
        if self.frozen_display.len() < self.blocks.len() {
            self.frozen_display
                .resize(self.blocks.len(), crate::reasoning_cli::Mode::Folded);
        }
        let live = self
            .reasoning
            .as_ref()
            .map(|live| live.display)
            .unwrap_or(crate::reasoning_cli::Mode::Folded);
        for i in self.printed..upto {
            if let Some(slot) = self.frozen_display.get_mut(i) {
                *slot = live;
            }
        }
        self.printed = upto;
    }
}

/// Usage totals are rendered by the view; this keeps the arithmetic in one place.
pub fn cache_share(u: &TurnUsage) -> Option<f64> {
    let prompt = u.prompt_tokens?;
    let cached = u.cached_tokens?;
    if prompt == 0 {
        return None;
    }
    Some(cached as f64 / prompt as f64)
}

/// `12.3` for a token/s figure, `--` when the server said nothing we can divide by.
pub fn tokens_per_sec_text(u: &TurnUsage) -> String {
    match u.tokens_per_sec() {
        Some(t) => format!("{t:.0} t/s"),
        None => "--".to_string(),
    }
}

/// `$HOME/x` as `~/x`, cut to `room` characters. The header is one line and the workspace
/// is the least important thing on it.
pub fn short_path(path: &str, room: usize) -> String {
    let shown = match std::env::var("HOME") {
        Ok(home) if !home.is_empty() && path.starts_with(&home) => {
            format!("~{}", &path[home.len()..])
        }
        _ => path.to_string(),
    };
    if shown.chars().count() <= room {
        return shown;
    }
    // Keep the tail — the last directories identify a workspace better than the root does.
    let tail: String = shown
        .chars()
        .rev()
        .take(room.saturating_sub(2))
        .collect::<Vec<_>>()
        .into_iter()
        .rev()
        .collect();
    format!("…{tail}")
}

/// The context line: used/window, a bar with the compaction threshold marked, and the share of
/// the window. The wording and the arithmetic are `eclipse_core::contextbar`'s (`#264`) — the
/// dashboard draws this same string — so the denominator is the model's window here too, never the
/// rail, and a window nobody stated is said rather than drawn against.
pub fn context_text(status: &Status, width: usize) -> String {
    status.reading().text(width)
}

/// Whether the prompt has gone past the compaction tripwire — the same reading, so the colour and
/// the shape cannot disagree about where the threshold is.
pub fn context_passed(status: &Status) -> bool {
    status.reading().passed()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::status;

    fn app() -> App {
        App::new(Status::new("m", "h:1", 1000, "/w".into()), "m", "/w", None)
    }

    /// `#366`: two calls of one tool in a turn are paired by id, not by name. The old match took
    /// the newest running row with that name, so the first call's output landed on the second row
    /// and the ✓/✗ moved with it — and replay, which pairs by id, then drew the transcript
    /// differently from the screen.
    #[test]
    fn two_calls_of_one_tool_pair_by_id_not_by_name() {
        let mut a = app();
        for (id, path) in [("a", "one"), ("b", "two")] {
            a.on_event(AgentEvent::ToolCall {
                call_id: id.into(),
                name: "read_file".into(),
                arguments: format!("{{\"path\":\"{path}\"}}"),
            });
        }
        // Out of order on purpose: the loop emits results in call order today, but keying on the
        // name is only right *because* of that, and a deferred or parallel dispatch would break it
        // silently. The id cannot be wrong about which call it answers.
        a.on_event(AgentEvent::ToolResult {
            call_id: "b".into(),
            name: "read_file".into(),
            output: "TWO".into(),
            is_error: true,
        });
        a.on_event(AgentEvent::ToolResult {
            call_id: "a".into(),
            name: "read_file".into(),
            output: "ONE".into(),
            is_error: false,
        });

        let tools: Vec<(String, String, ToolState)> = a
            .blocks
            .iter()
            .filter_map(|b| match b {
                Block::Tool {
                    call_id,
                    output,
                    state,
                    ..
                } => Some((call_id.clone(), output.clone(), *state)),
                _ => None,
            })
            .collect();
        assert_eq!(tools.len(), 2);
        assert_eq!(
            tools[0],
            ("a".to_string(), "ONE".to_string(), ToolState::Ok)
        );
        assert_eq!(
            tools[1],
            ("b".to_string(), "TWO".to_string(), ToolState::Failed)
        );
    }

    #[test]
    fn a_probed_window_replaces_the_readout_and_zero_leaves_it_alone() {
        let mut a = app();
        assert_eq!(a.status.budget, 1000);
        a.set_context(0, 0);
        assert_eq!(
            a.status.window, 0,
            "a failed probe does not invent a window"
        );
        assert_eq!(
            a.status.budget, 1000,
            "a missing window is not a budget of zero"
        );
        a.set_context(327_680, 278_528);
        assert_eq!(a.status.window, 327_680, "the model's own window wins");
        assert_eq!(a.status.budget, 278_528, "and its rail follows the window");
    }

    #[test]
    fn a_switched_model_with_the_threshold_off_keeps_its_window_and_drops_the_rail() {
        let mut a = app();
        a.set_context(327_680, 278_528);
        a.set_context(131_072, 0);
        assert_eq!(a.status.window, 131_072);
        assert_eq!(
            a.status.budget, 0,
            "compact_at = 0 is a switch-off, not a stale number from the last model"
        );
    }

    #[test]
    fn set_model_name_updates_the_readout_model_too() {
        let mut a = app();
        a.set_model_name("pc1/qwen-3.8-125b");
        assert_eq!(a.model, "pc1/qwen-3.8-125b");
        assert_eq!(
            a.status.model, "pc1/qwen-3.8-125b",
            "the bottom-left readout must not lag the header"
        );
    }

    #[test]
    fn deltas_grow_one_reply_and_the_final_message_settles_it() {
        let mut a = app();
        a.on_event(AgentEvent::Delta("Hel".into()));
        a.on_event(AgentEvent::Delta("lo".into()));
        assert_eq!(
            a.blocks,
            [Block::Reply {
                text: "Hello".into(),
                done: false
            }]
        );
        assert_eq!(a.activity, Activity::Streaming);
        a.on_event(AgentEvent::Message("Hello there".into()));
        assert_eq!(
            a.blocks,
            [Block::Reply {
                text: "Hello there".into(),
                done: true
            }],
            "the complete text wins over the deltas, and settles the block"
        );
    }

    #[test]
    fn a_tool_call_opens_a_block_and_its_result_closes_it() {
        let mut a = app();
        a.on_event(AgentEvent::ToolCall {
            call_id: "c1".into(),
            name: "read_file".into(),
            arguments: "{\"path\":\"x\"}".into(),
        });
        assert_eq!(a.activity, Activity::Tool("read_file".into()));
        a.on_event(AgentEvent::ToolResult {
            call_id: "c1".into(),
            name: "read_file".into(),
            output: "contents".into(),
            is_error: false,
        });
        match &a.blocks[0] {
            Block::Tool {
                state,
                output,
                args,
                ..
            } => {
                assert_eq!(*state, ToolState::Ok);
                assert_eq!(output, "contents");
                assert_eq!(args, "{\"path\":\"x\"}");
            }
            other => panic!("expected a tool block, got {other:?}"),
        }
    }

    #[test]
    fn two_calls_of_the_same_tool_close_in_order() {
        let mut a = app();
        for _ in 0..2 {
            a.on_event(AgentEvent::ToolCall {
                call_id: "c1".into(),
                name: "shell".into(),
                arguments: "{}".into(),
            });
        }
        a.on_event(AgentEvent::ToolResult {
            call_id: "c1".into(),
            name: "shell".into(),
            output: "first".into(),
            is_error: false,
        });
        a.on_event(AgentEvent::ToolResult {
            call_id: "c1".into(),
            name: "shell".into(),
            output: "second".into(),
            is_error: true,
        });
        let states: Vec<_> = a
            .blocks
            .iter()
            .filter_map(|b| match b {
                Block::Tool { state, output, .. } => Some((*state, output.clone())),
                _ => None,
            })
            .collect();
        assert_eq!(
            states,
            [
                (ToolState::Ok, "first".to_string()),
                (ToolState::Failed, "second".to_string())
            ],
            "the oldest running call is closed first, so a failure stays attached to its call"
        );
    }

    #[test]
    fn a_done_run_records_the_session_and_a_failure_does_not() {
        let mut a = app();
        a.running = true;
        a.on_done(Ok("s1".into()));
        assert_eq!(a.session.as_deref(), Some("s1"));
        assert!(!a.running);
        assert_eq!(a.activity, Activity::Idle);

        a.running = true;
        a.on_done(Err("boom".into()));
        assert_eq!(a.session.as_deref(), Some("s1"), "keeps the old session");
        assert!(a.last_error.is_some());
        assert!(matches!(
            a.blocks.last(),
            Some(Block::Note {
                kind: NoteKind::Error,
                ..
            })
        ));
    }

    #[test]
    fn stats_reach_the_readout() {
        let mut a = app();
        a.on_event(AgentEvent::TurnStats {
            usage: TurnUsage {
                prompt_tokens: Some(500),
                cached_tokens: Some(400),
                completion_tokens: Some(10),
                ..TurnUsage::default()
            },
            context_tokens: 500,
            budget_tokens: 1000,
        });
        assert_eq!(a.status.context_used(), Some(500));
        assert_eq!(a.status.budget, 1000);
        assert_eq!(a.status.totals.prompt_tokens, 500);
    }

    #[test]
    fn the_composer_tracks_a_char_cursor_not_a_byte_offset() {
        let mut a = app();
        a.insert_str("héllo");
        assert_eq!(a.cursor, 5);
        a.home();
        a.move_right();
        a.move_right();
        a.insert('X');
        assert_eq!(
            a.input, "héXllo",
            "inserting after a two-byte char must not split it"
        );
        a.backspace();
        assert_eq!(a.input, "héllo");
        a.delete();
        assert_eq!(a.input, "hélo");
    }

    #[test]
    fn history_walks_back_and_forward_and_restores_the_draft() {
        let mut h = History::default();
        h.push("one");
        h.push("two");
        assert_eq!(h.previous("draft"), Some("two".into()));
        assert_eq!(h.previous("two"), Some("one".into()));
        assert_eq!(h.previous("one"), Some("one".into()), "stops at the oldest");
        assert_eq!(h.next(), Some("two".into()));
        assert_eq!(h.next(), Some("draft".into()), "the draft comes back");
        assert_eq!(h.next(), None);
    }

    #[test]
    fn consecutive_duplicates_and_blanks_stay_out_of_history() {
        let mut h = History::default();
        for line in ["a", "a", "  ", "b"] {
            h.push(line);
        }
        assert_eq!(h.entries(), ["a", "b"]);
    }

    /// `#264`: the read-out follows the dial the agent holds, not a copy of `config.toml`. `/model`
    /// can change what a level *becomes*, so the resolution is re-asked too — but only when the
    /// level or the override state moved, because the tick is eleven frames a second.
    #[test]
    fn refresh_effort_follows_the_dial_rather_than_the_file() {
        let dial = std::sync::Arc::new(eclipse_core::reasoning::Dial::new(Some("low".into())));
        let mut app = app();
        app.reasoning = Some(crate::reasoning_cli::Live::bare(dial.clone()));

        app.refresh_effort();
        let first = app.status.effort.clone().expect("the dial is in force");
        assert_eq!(first.label, "low");
        assert!(!first.session, "the file's level is nobody's override");

        // `/reasoning high` in another surface of the same process: same `Arc`, so the read-out
        // follows without being told.
        dial.set_session(Some("high".into()));
        app.refresh_effort();
        let after = app.status.effort.clone().expect("still in force");
        assert_eq!(after.label, "high");
        assert!(after.session, "and it says the session is why");
        assert!(
            after.in_force.contains("this session"),
            "the long form names the override: {}",
            after.in_force
        );
    }

    #[test]
    fn context_text_is_honest_about_what_it_does_not_know() {
        let mut s = Status::new("m", "h:1", 0, "/w".into());
        assert_eq!(context_text(&s, 4), "ctx -- · no budget");
        s.budget = 1000;
        assert_eq!(
            context_text(&s, 4),
            "ctx --/1.0K â–‘â–‘â–‘â–‘",
            "a configured rail with no window is all there is to be a share of, and it is \
             still not marked"
        );
        s.context_tokens = Some(250);
        let text = context_text(&s, 4);
        assert!(text.starts_with("ctx 250/1.0K â–ˆ"), "{text}");
        assert!(text.ends_with("25%"), "{text}");
    }

    #[test]
    fn the_bar_denominator_is_the_window_not_the_compaction_threshold() {
        let mut s = Status::new("inkling-2-mini", "127.0.0.1:18045", 278_528, "/w".into());
        s.window = 327_680;
        assert_eq!(
            context_text(&s, 10),
            format!("ctx --/328K {}", status::bar_marked(0.0, 0.85, 10)),
            "328K, not 279K: the denominator is the model's window"
        );
        s.context_tokens = Some(12_300);
        let text = context_text(&s, 10);
        assert!(text.starts_with("ctx 12.3K/328K "), "{text}");
        assert!(
            text.contains(status::MARKER),
            "the tripwire is drawn: {text}"
        );
        assert_eq!(
            text,
            format!(
                "ctx 12.3K/328K {} 4%",
                status::bar_marked(12_300.0 / 327_680.0, 0.85, 10)
            ),
            "{text}"
        );
    }

    #[test]
    fn a_run_past_the_threshold_still_measures_against_the_window() {
        let mut s = Status::new("m", "h:1", 278_528, "/w".into());
        s.window = 327_680;
        s.context_tokens = Some(300_000);
        let text = context_text(&s, 10);
        assert!(
            text.contains("/328K "),
            "the window is still the whole bar: {text}"
        );
        assert!(text.ends_with("92%"), "the share is of the window: {text}");
        assert!(context_passed(&s), "past the tripwire: {text}");
        assert!(
            text.contains('â–“'),
            "the fill past the marker looks different, not just red: {text}"
        );
    }

    #[test]
    fn the_threshold_switched_off_draws_no_marker() {
        let mut s = Status::new("m", "h:1", 0, "/w".into());
        s.window = 327_680;
        s.context_tokens = Some(100_000);
        let text = context_text(&s, 10);
        assert!(!text.contains(status::MARKER), "compact_at = 0: {text}");
        assert!(!context_passed(&s));
        assert_eq!(
            text,
            format!(
                "ctx 100K/328K {} 31%",
                eclipse_core::contextbar::bar(0.3051, 10)
            )
        );
    }

    #[test]
    fn a_silent_server_reads_as_unknown_not_as_zero() {
        let u = TurnUsage::default();
        assert_eq!(tokens_per_sec_text(&u), "--");
        assert_eq!(cache_share(&u), None);
    }

    fn record(ts: u64, message: eclipse_core::message::Message) -> eclipse_core::session::Record {
        eclipse_core::session::Record { ts, message }
    }

    #[test]
    fn a_call_and_its_result_are_one_block_not_two() {
        use eclipse_core::message::{FunctionCall, Message, ToolCall};
        let records = vec![
            record(1, Message::user("go")),
            record(
                2,
                Message::assistant_tool_calls(
                    None,
                    vec![ToolCall {
                        id: "c1".into(),
                        kind: "function".into(),
                        function: FunctionCall {
                            name: "shell".into(),
                            arguments: "{\"command\":\"echo hi\"}".into(),
                        },
                    }],
                ),
            ),
            record(3, Message::tool_result("c1", "hi")),
            record(4, Message::assistant("done")),
        ];
        let (blocks, interrupted) = blocks_from(&records);
        assert_eq!(blocks.len(), 3, "user, one tool, reply: {blocks:#?}");
        assert!(!interrupted);
        match &blocks[1] {
            Block::Tool {
                name,
                state,
                output,
                ..
            } => {
                assert_eq!(name, "shell");
                assert_eq!(*state, ToolState::Ok);
                assert_eq!(output, "hi");
            }
            other => panic!("expected a tool block, got {other:?}"),
        }
    }

    #[test]
    fn a_session_cut_off_mid_tool_call_says_so_instead_of_spinning() {
        use eclipse_core::message::{FunctionCall, Message, ToolCall};
        let records = vec![
            record(1, Message::user("go")),
            record(
                2,
                Message::assistant_tool_calls(
                    None,
                    vec![ToolCall {
                        id: "c1".into(),
                        kind: "function".into(),
                        function: FunctionCall {
                            name: "shell".into(),
                            arguments: "{}".into(),
                        },
                    }],
                ),
            ),
        ];
        let (blocks, interrupted) = blocks_from(&records);
        assert!(interrupted, "the caller has to be able to say so");
        match &blocks[1] {
            Block::Tool { state, output, .. } => {
                assert_eq!(*state, ToolState::Failed, "not left running forever");
                assert!(output.starts_with("no result:"), "{output}");
            }
            other => panic!("expected a tool block, got {other:?}"),
        }
    }

    #[test]
    fn a_result_with_no_call_is_reported_rather_than_dropped() {
        use eclipse_core::message::Message;
        let records = vec![record(1, Message::tool_result("ghost", "surprise"))];
        let (blocks, _) = blocks_from(&records);
        assert!(
            blocks.iter().any(|b| matches!(
                b,
                Block::Note { kind: NoteKind::Warn, text } if text.contains("no matching call")
            )),
            "{blocks:#?}"
        );
    }

    #[test]
    fn the_picker_moves_within_its_list_and_stops_at_the_ends() {
        let mut app = app();
        app.set_sessions(vec![
            Picked {
                note: String::new(),
                id: "a".into(),
                title: None,
                ago: "just now".into(),
                messages: 1,
                preview: "first".into(),
            },
            Picked {
                note: String::new(),
                id: "b".into(),
                title: Some("named".into()),
                ago: "1m ago".into(),
                messages: 2,
                preview: "second".into(),
            },
        ]);
        let picker = app.picker.as_mut().unwrap();
        picker.move_by(-1);
        assert_eq!(picker.cursor, 0, "cannot move above the first");
        picker.move_by(1);
        assert_eq!(picker.current().unwrap().id, "b");
        picker.move_by(1);
        assert_eq!(picker.cursor, 1, "cannot move past the last");
        assert_eq!(
            picker.current().unwrap().label(),
            "named",
            "a title wins over a preview"
        );
    }

    /// A session list with enough rows to filter: two of them mention the same word, one is a
    /// child, and one title is only reachable by a subsequence.
    fn picked(id: &str, title: Option<&str>, preview: &str) -> Picked {
        Picked {
            note: String::new(),
            id: id.into(),
            title: title.map(|t| t.into()),
            ago: "1m ago".into(),
            messages: 3,
            preview: preview.into(),
        }
    }

    #[test]
    fn typing_narrows_the_picker_and_backspace_brings_the_rows_back() {
        let mut app = app();
        app.set_sessions(vec![
            picked("s1", Some("eclipse release"), ""),
            picked("s2", None, "the session search design"),
            picked("s3", Some("max horda"), ""),
        ]);
        let picker = app.picker.as_mut().unwrap();
        assert_eq!(picker.count_label(), "3 stored");

        for c in "sess".chars() {
            picker.type_char(c);
        }
        assert_eq!(
            picker.items.len(),
            2,
            "\"sess\" is a subsequence of both previews, so both survive"
        );
        assert_eq!(
            picker.cursor_name(),
            Some("s2"),
            "the tighter match ranks first: \"session\" is contiguous, \"eclipse release\" is not"
        );
        assert_eq!(picker.count_label(), "2 of 3 stored");

        // A query only one row can satisfy leaves exactly that row.
        picker.clear_query();
        for c in "srch".chars() {
            picker.type_char(c);
        }
        assert_eq!(picker.items.len(), 1);
        assert_eq!(picker.cursor_name(), Some("s2"));

        // `mx` is a subsequence of "max horda": that is the point of fuzzy rather than substring.
        picker.clear_query();
        picker.type_char('m');
        picker.type_char('x');
        assert_eq!(picker.cursor_name(), Some("s3"));

        // Deleting everything restores the full list, in its original order.
        while picker.backspace() {}
        assert!(!picker.backspace(), "an empty query has nothing to delete");
        assert_eq!(picker.items.len(), 3);
        assert_eq!(
            picker.count_label(),
            "3 stored",
            "the count goes back to the whole list"
        );
    }

    #[test]
    fn a_query_that_matches_nothing_leaves_an_empty_list_rather_than_a_stale_row() {
        let mut app = app();
        app.set_sessions(vec![picked("s1", Some("alpha"), "")]);
        let picker = app.picker.as_mut().unwrap();
        for c in "zzz".chars() {
            picker.type_char(c);
        }
        assert!(picker.items.is_empty());
        assert_eq!(picker.current(), None, "enter on nothing must not resume");
        assert_eq!(picker.count_label(), "0 of 1 stored");
        // A trailing space is a typo, not a character to match.
        picker.clear_query();
        picker.type_char('a');
        picker.type_char('l');
        picker.type_char(' ');
        assert_eq!(picker.items.len(), 1, "trailing space keeps the match");
    }

    #[test]
    fn an_empty_session_list_says_so_rather_than_opening_an_empty_modal() {
        let mut app = app();
        app.set_sessions(Vec::new());
        assert!(app.picker.is_none());
        assert!(app
            .blocks
            .iter()
            .any(|b| matches!(b, Block::Note { text, .. } if text.contains("no sessions yet"))));
    }
}