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
//! The chat-list overlay: a search filter, two sort orders, in-place rename,
//! create/clone/delete. Opens/closes via `Esc`. See spec §11.2.
//!
//! The widget is self-contained: it holds the list snapshot and input state, and
//! responds to key presses with [`ChatListAction`] (executed by `app` — the sole writer).
use ratatui::Frame;
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Style, Stylize};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Clear, List, ListItem, Paragraph};
use uuid::Uuid;
use crate::entities::chat::ChatSummary;
use crate::entities::subagent::RunOutcome;
use crate::features::chat_search_sort::{SortMode, filter_and_sort};
use crate::features::spellcheck::SpellChecker;
use crate::shared::i18n::Locale;
use crate::shared::keys;
use crate::shared::theme::Palette;
use crate::shared::title::sanitize_title;
use crate::shared::ui::{ListScroll, hotkey_grid, render_scrollbar};
use crate::shared::wrap;
use crate::widgets::help_dialog::{HelpContext, HelpSection};
use crate::widgets::input_box::{InputBox, RenderOpts};
/// The chat list's "Shortcuts" section (`F1`): one row per key `on_key`
/// matches — a new arm gets a row here, next door (AGENTS.md §3). The app
/// layer composes the dialog's tab from the screens' sections
/// (docs/history/help-hotkeys-context.md §6).
pub(crate) static HELP_SECTION: HelpSection = HelpSection {
title: "ui.help.sec.chat_list",
context: Some(HelpContext::ChatList),
// The groups: searching · acting on the selection · managing chats.
rows: &[
("ui.help.k.type", "ui.help.list_type"),
("Ctrl+F", "ui.help.list_scope"),
("Ctrl+G", "ui.help.list_messages"),
("Enter", "ui.help.list_open"),
("↑/↓", "ui.help.list_select"),
("Tab", "ui.help.list_sort"),
("Esc", "ui.help.list_close"),
("F2", "ui.help.list_rename"),
("F5", "ui.help.list_copy"),
("Ctrl+R", "ui.help.list_autotitle"),
("Ctrl+N", "ui.help.new_chat"),
("Ctrl+D", "ui.help.list_clone"),
("Del", "ui.help.list_delete"),
("Ctrl+O", "ui.help.subagents_fold"),
],
openers: &["Enter", "F2"],
};
/// The paged-selection-move step for `PageUp`/`PageDown`. Fixed,
/// since the actual list height is only known at render time.
const PAGE_STEP: usize = 10;
/// An action the overlay asks the upper layer to perform.
#[derive(Debug, Clone, PartialEq)]
pub enum ChatListAction {
/// Nothing (the press was handled inside the overlay).
None,
/// Close the overlay.
Close,
/// Quit the app (`Ctrl+Q`/`F10`).
Quit,
/// Make a chat active (and close the overlay).
Switch(Uuid),
/// Create a new chat.
New,
/// Clone a chat.
Clone(Uuid),
/// Copy the whole chat conversation to the clipboard.
Copy(Uuid),
/// Soft-delete a chat.
Delete(Uuid),
/// Rename a chat.
Rename { id: Uuid, title: String },
/// Auto-title: the model reads the conversation and comes up with a title.
AutoRename(Uuid),
/// Run a full-text search over chat **content** with this raw query (content
/// mode, `Ctrl+F`). The widget stays dumb: it never builds an FTS5 query —
/// that rule lives in one place, the orchestrator (see
/// docs/research/chat-content-search.md §7a). Results come back via
/// [`ChatListState::set_search_results`].
SearchContent(String),
/// Open the message-level search screen for the current query (content
/// mode, `Ctrl+G`). Like [`Self::SearchContent`] the widget stays dumb —
/// the query is raw. See docs/history/chat-search-stage2.md (stage 2b).
SearchMessages { query: String, sort: SortMode },
/// Open a chat **at its first message matching the query** (`Enter` in
/// content mode). Which message that is can only be answered by the
/// orchestrator, which owns both the index and the chat — the widget just
/// says which chat and what was searched for.
OpenFirstMatch { chat: Uuid, query: String },
/// Fold or unfold a chat's sub-agent transcripts in the list (`Ctrl+O`).
/// The absolute value, computed here from the summary the widget already
/// renders from: the orchestrator stores it on the chat (spec §11.2) and
/// the updated set comes back via the `ChatList` event — the list stays
/// open, like a rename.
SetChildrenExpanded { id: Uuid, expanded: bool },
}
/// One row of the list: a chat, or a sub-agent transcript nested under the
/// chat whose call made it (spec §11.2). The tree is two levels deep by
/// construction — a transcript never has transcripts — so a flat row list
/// with a parent link is the whole structure.
#[derive(Debug, Clone, PartialEq)]
pub struct Row {
pub id: Uuid,
pub title: String,
pub message_count: usize,
/// The chat this transcript belongs to; `None` for a chat.
pub parent: Option<Uuid>,
/// How the run ended (transcripts only); `None` on a transcript — it never said.
pub outcome: Option<RunOutcome>,
/// The run is in progress (`ChildSummary::running`): drawn as a *running*
/// mark where an outcome would go.
pub running: bool,
/// The run was started in the background (`ChildSummary::background`):
/// with no outcome and not running it reads *unfinished*, not
/// *interrupted* (spec §9.3.2).
pub background: bool,
/// A chat shown only because one of its transcripts matched the filter:
/// drawn dimmed, so the match and its context read differently.
pub dimmed: bool,
/// How many transcripts the stored fold is hiding under this row (chats
/// only; `0` — none). Drawn as a `▸ n` mark beside the count, so a folded
/// chat with transcripts doesn't look like a chat without any.
pub collapsed_children: usize,
/// A background run's result landed here while the chat was not open
/// (`ChatSummary::unread`, spec §9.3.2): the row says *unread* beside its
/// count and its dot takes the accent colour, until the chat is opened.
/// Chats only — a transcript's row says how its run ended instead.
pub unread: bool,
}
impl Row {
pub fn is_child(&self) -> bool {
self.parent.is_some()
}
}
/// What the search line searches. Title mode is the historical behaviour (a
/// substring of the title, filtered locally); content mode asks the
/// orchestrator for the chats whose **messages** match. Toggled with `Ctrl+F`.
/// See docs/research/chat-content-search.md §7 (fork F4).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SearchScope {
/// Substring of the chat title (the previous, and default, behaviour).
#[default]
Title,
/// Full-text search over message text.
Content,
}
impl SearchScope {
fn toggled(self) -> Self {
match self {
SearchScope::Title => SearchScope::Content,
SearchScope::Content => SearchScope::Title,
}
}
}
/// The overlay's input mode.
enum Mode {
/// Typing into the search line.
Search,
/// Renaming the selected chat in place. Text and cursor are driven by a
/// single-line [`InputBox`] (`set_single_line`) — this gives spellcheck,
/// word-wise navigation/deletion (`Ctrl+←/→`, `Ctrl+Backspace/Delete`),
/// `Ctrl+Home/End`, clear/restore (`Ctrl+K`), and clipboard paste "for free". `InputBox`
/// is large — boxed (clippy::large_enum_variant). `spell_dirty` marks
/// that the error highlighting needs recomputing (see [`Self::recheck_rename_spelling`]).
Rename {
id: Uuid,
input: Box<InputBox>,
spell_dirty: bool,
},
}
/// State of the chat-list overlay.
pub struct ChatListState {
/// A snapshot of all visible chats (updated from `AppEvent::ChatList`).
all: Vec<ChatSummary>,
query: String,
sort: SortMode,
/// What the query searches: the title (locally) or message content (via the
/// orchestrator). Toggled with `Ctrl+F`.
scope: SearchScope,
/// The chats the last content search matched — `None` means "no result yet,
/// show everything" (also what an unsearchable query yields, so content mode
/// with a too-short query behaves exactly like an empty one). Deliberately
/// kept across keystrokes: replacing it only when a new result arrives is
/// what stops the full list flashing between them.
results: Option<Vec<Uuid>>,
/// The query those `results` answer. Unused by stage 1's filter (a stale
/// result is still applied — showing the previous answer beats showing
/// everything), but stage 2 needs it to highlight matches.
results_query: String,
/// Selection index within the currently filtered list.
selected: usize,
/// The list's scroll position. Lives here rather than in a per-frame
/// `ListState` — see [`ListScroll`].
scroll: ListScroll,
mode: Mode,
/// The current operation error (auto-title/delete/clone) for the dedicated area.
/// Reset on the next key press.
error: Option<String>,
/// Operation confirmation (e.g. "copied") for the same area, but as
/// success. Reset on the next key press. Mutually exclusive with `error`.
notice: Option<String>,
}
impl ChatListState {
/// Opens the overlay with a list snapshot; selection — on the active chat.
pub fn new(chats: Vec<ChatSummary>, active: Option<Uuid>) -> Self {
let mut state = Self {
all: chats,
query: String::new(),
sort: SortMode::default(),
scope: SearchScope::default(),
results: None,
results_query: String::new(),
selected: 0,
scroll: ListScroll::default(),
mode: Mode::Search,
error: None,
notice: None,
};
if let Some(active) = active {
let visible = state.visible();
let idx = visible.iter().position(|c| c.id == active).or_else(|| {
// The active "chat" is a transcript its parent's fold is hiding
// (spec §11.2) — land on the parent rather than on the first row.
let parent = state
.all
.iter()
.find(|c| c.child_ids().any(|k| k == active))?;
visible.iter().position(|r| r.id == parent.id)
});
if let Some(idx) = idx {
state.selected = idx;
}
}
state
}
/// Updates the list snapshot (after changes to the chat set), keeping selection
/// on the same chat where possible. If the selected chat disappeared (e.g. deleted),
/// selection stays at the **same position** (the next chat in the list, or a
/// new last one when the last was deleted), rather than jumping to the first item —
/// as is conventional for lists.
pub fn set_chats(&mut self, chats: Vec<ChatSummary>) {
let current = self.selected_id();
let prev_index = self.selected;
self.all = chats;
let visible = self.visible();
self.selected = current
.and_then(|id| visible.iter().position(|c| c.id == id))
.unwrap_or(prev_index);
self.clamp_selection();
}
/// The current filtered/sorted list.
///
/// In content mode the title substring filter is deliberately **not**
/// applied: the query is answered by the index, and re-applying it to the
/// title would hide the very chats the search just found. The user's sort
/// still orders the result — stage 1 *filters* rather than ranks, because
/// trigram's `bm25` is weak (docs/research/chat-content-search.md §7a).
///
/// **The tree rule** (spec §11.2, docs/research/subagent-chats.md §3.7): a
/// row is shown iff it matches; a chat is additionally shown — dimmed —
/// when any of its transcripts matches. So a matched transcript never
/// appears without its parent, an unmatched one never pads a matched
/// parent, and text found only in the parent shows the parent alone.
/// Chats keep the sort mode; a chat's transcripts follow it in call order.
///
/// **The fold** ([`ChatSummary::children_expanded`], `Ctrl+O`): a chat's
/// transcripts are hidden while it is collapsed — but only when nothing is
/// being searched for. An explicit match is the user asking where something
/// is, so it outranks the fold and surfaces the transcript with its parent;
/// the blanket "everything matches" of an empty query (or a content search
/// with no answer yet) is exactly the context the fold exists to hide.
fn visible(&self) -> Vec<Row> {
let needle = self.query.trim().to_lowercase();
let matched: Option<std::collections::HashSet<Uuid>> = match self.scope {
SearchScope::Title => None,
SearchScope::Content => self
.results
.as_ref()
.map(|ids| ids.iter().copied().collect()),
};
let matches = |id: Uuid, title: &str| match self.scope {
SearchScope::Title => needle.is_empty() || title.to_lowercase().contains(&needle),
// No result yet (or an unsearchable query) — everything shows, as
// an empty query does.
SearchScope::Content => matched.as_ref().is_none_or(|set| set.contains(&id)),
};
// "Everything matches" — no effective filter, so what shows under a
// chat is decided by its stored fold rather than by the search.
let blanket = match self.scope {
SearchScope::Title => needle.is_empty(),
SearchScope::Content => matched.is_none(),
};
let mut rows = Vec::new();
for chat in filter_and_sort(&self.all, "", self.sort) {
let children: Vec<Row> = chat
.children
.iter()
.filter(|c| matches(c.id, &c.title))
.map(|c| Row {
id: c.id,
title: c.title.clone(),
message_count: c.message_count,
parent: Some(chat.id),
outcome: c.outcome,
running: c.running,
background: c.background,
dimmed: false,
collapsed_children: 0,
unread: false,
})
.collect();
let own = matches(chat.id, &chat.title);
if !own && children.is_empty() {
continue;
}
let folded = blanket && !chat.children_expanded;
rows.push(Row {
id: chat.id,
title: chat.title.clone(),
message_count: chat.message_count,
parent: None,
outcome: None,
running: false,
background: false,
dimmed: !own,
collapsed_children: if folded { children.len() } else { 0 },
unread: chat.unread,
});
if !folded {
rows.extend(children);
}
}
rows
}
/// The selected row, if the list isn't empty.
fn selected_row(&self) -> Option<Row> {
self.visible().get(self.selected).cloned()
}
/// Applies a content-search result (`AppEvent::ChatSearchResults`).
/// `chat_ids: None` means "not a searchable query" — show everything, like
/// an empty query. A result for an older query is still applied: the
/// previous answer is a better thing to show than the whole list.
pub fn set_search_results(&mut self, query: String, chat_ids: Option<Vec<Uuid>>) {
self.results_query = query;
self.results = chat_ids;
self.clamp_selection();
}
/// Reopens the list still searching message content for `query` — used
/// when the message-level results screen closes, so `Esc` returns to the
/// search the user was doing rather than to an empty list. The results
/// themselves are refetched by the caller (the same round-trip typing a
/// query does).
pub fn restore_content_query(&mut self, query: String) {
self.query = query;
self.scope = SearchScope::Content;
self.selected = 0;
}
/// Emits a content search for the current query — when the query changed in
/// content mode, or on switching into it.
fn search_action(&self) -> ChatListAction {
ChatListAction::SearchContent(self.query.clone())
}
/// What an edit to the query means: nothing in title mode (the filter is
/// local), a fresh content search otherwise.
fn query_changed(&self) -> ChatListAction {
match self.scope {
SearchScope::Title => ChatListAction::None,
SearchScope::Content => self.search_action(),
}
}
/// The selected chat's id (if the list isn't empty).
pub fn selected_id(&self) -> Option<Uuid> {
self.visible().get(self.selected).map(|c| c.id)
}
fn clamp_selection(&mut self) {
let len = self.visible().len();
if len == 0 {
self.selected = 0;
} else if self.selected >= len {
self.selected = len - 1;
}
}
/// Sets the error text for the overlay's dedicated area. Reset
/// on the next key press, so it doesn't stay hanging around forever.
pub fn set_error(&mut self, message: String) {
self.error = Some(message);
self.notice = None;
}
/// Sets an operation confirmation (success) for the same area. Reset
/// on the next key press.
pub fn set_notice(&mut self, message: String) {
self.notice = Some(message);
self.error = None;
}
/// Handles a key press, returning the action to perform.
pub fn on_key(&mut self, key: KeyEvent) -> ChatListAction {
if key.kind != KeyEventKind::Press {
return ChatListAction::None;
}
// Any key press clears a previously shown error/confirmation (they don't linger).
self.error = None;
self.notice = None;
match &mut self.mode {
Mode::Rename { .. } => self.on_key_rename(key),
Mode::Search => self.on_key_search(key),
}
}
fn on_key_search(&mut self, key: KeyEvent) -> ChatListAction {
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
// Ctrl shortcuts are matched by "physical" Latin key — work under
// any layout (see shared::keys). Any other Ctrl+character is swallowed,
// so it doesn't end up in the search line.
if ctrl && let Some(physical) = keys::hotkey_char(&key) {
return self.on_ctrl_search(physical);
}
match key.code {
KeyCode::F(10) => ChatListAction::Quit, // a second way to quit
KeyCode::Esc => ChatListAction::Close,
KeyCode::Enter => self.open_selected(),
KeyCode::Up => {
self.selected = self.selected.saturating_sub(1);
ChatListAction::None
}
KeyCode::Down => {
self.select_down(1);
ChatListAction::None
}
// Paged selection movement: step by a "page" (fixed,
// since the list height is only known at render time).
KeyCode::PageUp => {
self.selected = self.selected.saturating_sub(PAGE_STEP);
ChatListAction::None
}
KeyCode::PageDown => {
self.select_down(PAGE_STEP);
ChatListAction::None
}
// Jump to the first/last chat.
KeyCode::Home => {
self.selected = 0;
ChatListAction::None
}
KeyCode::End => {
self.selected = self.visible().len().saturating_sub(1);
ChatListAction::None
}
KeyCode::Tab => {
self.sort = self.sort.toggled();
self.clamp_selection();
ChatListAction::None
}
KeyCode::F(2) => {
self.start_rename();
ChatListAction::None
}
// Copy the whole conversation of the selected chat to the clipboard.
KeyCode::F(5) => match self.selected_id() {
Some(id) => ChatListAction::Copy(id),
None => ChatListAction::None,
},
KeyCode::Delete => match self.selected_id() {
Some(id) => ChatListAction::Delete(id),
None => ChatListAction::None,
},
// Editing the query: in title mode the filter is local (no action),
// in content mode every change asks the index for a fresh answer.
KeyCode::Backspace => {
self.query.pop();
self.selected = 0;
self.query_changed()
}
KeyCode::Char(c) => {
self.query.push(c);
self.selected = 0;
self.query_changed()
}
_ => ChatListAction::None,
}
}
/// A Ctrl shortcut in search mode, matched by "physical" Latin key
/// (see [`Self::on_key_search`]).
fn on_ctrl_search(&mut self, physical: char) -> ChatListAction {
match physical {
// Quitting works from the chat list too; moved to Ctrl+Q/F10 (Ctrl+C
// is freed up). See docs/history/input-selection-undo-mouse.md §B.
'q' => ChatListAction::Quit,
'n' => ChatListAction::New,
'd' => match self.selected_id() {
Some(id) => ChatListAction::Clone(id),
None => ChatListAction::None,
},
// Auto-title the selected chat, done by the model.
'r' => match self.selected_id() {
Some(id) => ChatListAction::AutoRename(id),
None => ChatListAction::None,
},
// Toggle title ↔ content search. Switching *into* content mode
// asks for results right away, so the mode takes effect on the
// text already typed; switching back needs no round-trip (the
// title filter is local).
'f' => {
self.scope = self.scope.toggled();
self.selected = 0;
match self.scope {
SearchScope::Content => self.search_action(),
SearchScope::Title => ChatListAction::None,
}
}
// Fold/unfold the selected chat's sub-agent transcripts. On a
// transcript row the toggle folds the list it is part of.
'o' => self.toggle_children(),
// Go from "which chats mention this" to "where exactly": the
// message-level results screen. Content mode only — in title
// mode the query is a title substring, which is not a thing to
// search message text for; the hint is hidden there too, so no
// advertised key is a no-op.
'g' => match self.scope {
SearchScope::Content => ChatListAction::SearchMessages {
query: self.query.clone(),
sort: self.sort,
},
SearchScope::Title => ChatListAction::None,
},
_ => ChatListAction::None,
}
}
/// `Ctrl+O`: folds/unfolds the selected chat's sub-agent transcripts
/// (spec §11.2). On a transcript row the parent's list is what folds —
/// selection moves to the parent first, so it never rests on a row the
/// fold is about to hide. A chat with no transcripts is a no-op, and the
/// hint for the key is not advertised there either.
fn toggle_children(&mut self) -> ChatListAction {
let Some(row) = self.selected_row() else {
return ChatListAction::None;
};
let id = row.parent.unwrap_or(row.id);
let Some(chat) = self.all.iter().find(|c| c.id == id) else {
return ChatListAction::None;
};
if chat.children.is_empty() {
return ChatListAction::None;
}
let expanded = !chat.children_expanded;
if !expanded
&& row.is_child()
&& let Some(idx) = self.visible().iter().position(|r| r.id == id)
{
self.selected = idx;
}
ChatListAction::SetChildrenExpanded { id, expanded }
}
/// `Enter`: opens the selected chat. In content mode the chat is opened
/// **at its first match** rather than at the tail: the user asked where
/// this text is, so landing on it is strictly more useful than landing at
/// the end of the conversation (stage 2a's jump). Title mode is unchanged.
fn open_selected(&self) -> ChatListAction {
match (self.selected_id(), self.scope) {
(Some(id), SearchScope::Content) if !self.query.trim().is_empty() => {
ChatListAction::OpenFirstMatch {
chat: id,
query: self.query.clone(),
}
}
(Some(id), _) => ChatListAction::Switch(id),
(None, _) => ChatListAction::None,
}
}
/// Moves the selection down by `step`, clamped to the list's last item.
fn select_down(&mut self, step: usize) {
let len = self.visible().len();
if len > 0 {
self.selected = (self.selected + step).min(len - 1);
}
}
/// `F2`: switches into rename mode for the selected chat (a no-op on an
/// empty list).
fn start_rename(&mut self) {
if let Some(chat) = self.visible().get(self.selected) {
// A single-line `InputBox` with the current title (cursor at the end).
// `set_single_line` — before `set_text` (the single-line invariant).
let mut input = InputBox::new();
input.set_single_line(true);
input.set_text(&chat.title);
self.mode = Mode::Rename {
id: chat.id,
input: Box::new(input),
spell_dirty: true,
};
}
}
fn on_key_rename(&mut self, key: KeyEvent) -> ChatListAction {
let Mode::Rename {
id,
input,
spell_dirty,
} = &mut self.mode
else {
return ChatListAction::None;
};
// All Ctrl combinations for the field (clear `Ctrl+K`, word-wise navigation `Ctrl+←/→`,
// word deletion `Ctrl+Backspace/Delete`, `Ctrl+Home/End`, undo/redo
// `Ctrl+Z/Y`) are handled by `InputBox` itself in `on_key` (layout-independent);
// it swallows unrecognized ones. `Ctrl+K` → `Edited` → flag the highlighting to recompute.
match key.code {
KeyCode::Esc => {
self.mode = Mode::Search;
ChatListAction::None
}
KeyCode::Enter => {
let id = *id;
let title = input.text();
let action = match sanitize_title(&title) {
Some(title) => ChatListAction::Rename { id, title },
None => ChatListAction::None,
};
self.mode = Mode::Search;
action
}
// Everything else (typing, word/character navigation, deletion, `Home/End`)
// is handled by `InputBox` itself; on an actual edit we flag the error
// highlighting for a recompute (cursor movement doesn't need it). See [`KeyOutcome`].
_ => {
if input.on_key(key).edited() {
*spell_dirty = true;
}
ChatListAction::None
}
}
}
/// Inserts clipboard text into the rename field (if it's open).
/// Line breaks collapse into a space (`InputBox` is single-line). Outside rename
/// mode — a no-op (paste isn't needed in the search line).
pub fn handle_paste(&mut self, text: &str) {
if let Mode::Rename {
input, spell_dirty, ..
} = &mut self.mode
{
input.insert_str(text);
*spell_dirty = true;
}
}
/// Recomputes spellcheck highlighting in the rename field, if it's
/// open and flagged "dirty" (after an edit/paste). Returns `true` if the
/// highlighting was updated (a repaint is needed). The widget doesn't own the checker —
/// `app` lends it (the owner lives in the chat screen). See spec §11.5.
pub fn recheck_rename_spelling(&mut self, spell: &SpellChecker) -> bool {
let Mode::Rename {
input, spell_dirty, ..
} = &mut self.mode
else {
return false;
};
if !*spell_dirty {
return false;
}
let ranges = vec![spell.misspellings(&input.text())];
input.set_misspelled(ranges);
*spell_dirty = false;
true
}
/// Draws the fullscreen chat-list window (`area`). `active` — the current
/// active chat (the marker). `&mut self` — the rename field draws an [`InputBox`]
/// (it needs `&mut` for scroll/cursor). See spec §11.2.
pub fn render(
&mut self,
frame: &mut Frame,
area: Rect,
active: Option<Uuid>,
palette: &Palette,
loc: &'static Locale,
) {
frame.render_widget(Clear, area);
// At the bottom — a status line with "keycaps" (like on the chat screen): a neat
// hotkey grid (the row count depends on width). Compute it ahead of time to
// reserve exactly the height it needs.
let status_lines = self.status_lines(palette, area.width as usize, loc);
let status_h = (status_lines.len() as u16).max(1);
let [main_area, status_area] =
Layout::vertical([Constraint::Min(3), Constraint::Length(status_h)]).areas(area);
// The list panel: a rounded border, title on the left, dialog count on the right.
let count = self.all.len();
let title = format!(
"{} {}",
palette.glyphs().chats_icon,
loc.t("ui.chatlist.title")
);
let block = palette.panel(title, true).title(
Line::from(Span::styled(
format!(
" {} ",
loc.tf("ui.chatlist.count", &[("n", &count.to_string())])
),
palette.muted_style(),
))
.right_aligned(),
);
let inner = block.inner(main_area);
frame.render_widget(block, main_area);
// Inside the panel: the search line (bordered, 3 rows), the list, and — if present —
// an operation-status line (error/confirmation).
let mut constraints = vec![Constraint::Length(3), Constraint::Min(1)];
if self.error.is_some() || self.notice.is_some() {
constraints.push(Constraint::Length(1));
}
let chunks = Layout::vertical(constraints).split(inner);
let (search_area, list_area) = (chunks[0], chunks[1]);
// --- the search line (bordered, with a `/` keycap on the right) OR the
// rename field (a single-line `InputBox`: spellcheck, word-wise navigation,
// a real cursor, horizontal scroll) ---
if let Mode::Rename { input, .. } = &mut self.mode {
input.render(
frame,
search_area,
RenderOpts::focused(loc.t("ui.chatlist.rename_title")),
palette,
);
} else {
self.render_search(frame, search_area, palette, loc);
}
// --- the list ---
let visible = self.visible();
let width = list_area.width as usize;
let items: Vec<ListItem> = visible
.iter()
.enumerate()
.map(|(i, c)| {
ListItem::new(self.item_line(c, i == self.selected, active, palette, width, loc))
})
.collect();
// Selection — a soft backdrop (like the tint in the mockup), not inverting the whole line;
// the selected row's green rail is added in `item_line`.
let list = List::new(items).highlight_style(Style::new().bg(palette.keycap_bg));
// The scroll position is carried over from the previous frame, which is
// what makes `↑` walk the selection up to the top row before the list
// starts scrolling — the mirror of `↓` (spec §11.2, [`ListScroll`]).
// The list has no block, so its whole height is drawn into.
self.scroll.render(
frame,
list,
list_area,
visible.len(),
list_area.height as usize,
(!visible.is_empty()).then_some(self.selected),
);
// The scrollbar on the "Chats" panel's right border — when there are more
// chats than the list's visible height. The bar occupies only the list's rows
// (the search line and status aren't touched); position — the list's actual offset after rendering.
render_scrollbar(
frame,
Rect {
x: main_area.x,
y: list_area.y,
width: main_area.width,
height: list_area.height,
},
visible.len(),
list_area.height as usize,
self.scroll.offset(),
true, // the panel border — in the focused color (panel(_, true))
palette,
);
// --- the operation-status area: error (red) or confirmation (success) ---
if let Some(err) = &self.error {
let line = Line::from(vec![
Span::from(format!("{} ", palette.glyphs().warn)).fg(palette.error),
Span::from(err.clone()).fg(palette.error),
]);
frame.render_widget(Paragraph::new(line), chunks[2]);
} else if let Some(notice) = &self.notice {
let line = Line::from(vec![
Span::from(format!("{} ", palette.glyphs().ok)).fg(palette.success),
Span::from(notice.clone()).fg(palette.success),
]);
frame.render_widget(Paragraph::new(line), chunks[2]);
}
// --- the status line (hotkeys, like on the chat screen) ---
frame.render_widget(Paragraph::new(status_lines), status_area);
}
/// Draws the bordered search line; on the right — the "/" keycap (a focus hint).
fn render_search(
&self,
frame: &mut Frame,
area: Rect,
palette: &Palette,
loc: &'static Locale,
) {
let glyphs = palette.glyphs();
let block = Block::default()
.borders(Borders::ALL)
.border_type(glyphs.border)
.border_style(palette.border_style(true));
let inner = block.inner(area);
frame.render_widget(block, area);
// The field, the current search mode, and the column for the "/" keycap
// on the right. The mode is shown because it changes what typing does
// (`Ctrl+F`, see [`SearchScope`]); it is accented in content mode — the
// departure from the historical behaviour — and muted in title mode.
let mode = mode_label(self.scope, loc);
let mode_w = display_width_str(mode) as u16 + 1;
let [field, mode_area, cap] = Layout::horizontal([
Constraint::Min(1),
Constraint::Length(mode_w),
Constraint::Length(3),
])
.areas(inner);
let mut spans = vec![
Span::styled(format!("{} ", glyphs.search), palette.muted_style()),
Span::styled(self.query.clone(), Style::new().fg(palette.text)),
Span::styled(glyphs.caret, palette.muted_style()),
];
if self.query.is_empty() {
spans.push(Span::styled(
match self.scope {
SearchScope::Title => loc.t("ui.chatlist.search_placeholder"),
SearchScope::Content => loc.t("ui.chatlist.search_placeholder_content"),
},
palette.muted_style(),
));
}
let mode_style = match self.scope {
SearchScope::Title => palette.muted_style(),
SearchScope::Content => Style::new().fg(palette.accent),
};
frame.render_widget(Paragraph::new(Line::from(spans)), field);
frame.render_widget(
Paragraph::new(Line::from(Span::styled(mode, mode_style))),
mode_area,
);
frame.render_widget(Paragraph::new(Line::from(palette.keycap("/"))), cap);
}
/// A chat row: the selected row's colored rail, a dot (green for the active chat),
/// the title on the left, and the message count right-aligned (`width` — the width
/// of the list area). A long title is truncated with an ellipsis.
fn item_line(
&self,
row: &Row,
is_selected: bool,
active: Option<Uuid>,
palette: &Palette,
width: usize,
loc: &'static Locale,
) -> Line<'static> {
let is_active = active == Some(row.id);
// The selected row's rail (2 columns) + the dot (2 columns) = the prefix;
// a transcript is indented under its parent with a `└` instead of the
// dot (WGL4, one column — docs/lessons.md §5).
let rail = if is_selected {
Span::styled("▌ ", Style::new().fg(palette.success))
} else {
Span::raw(" ")
};
// An unread chat's dot takes the accent colour — the one mark that
// survives a narrow list, where the label below is the first to go.
let dot_color = if is_active {
palette.success
} else if row.unread {
palette.accent
} else {
palette.border
};
let title_style = if is_active {
Style::new().fg(palette.text).bold()
} else if row.dimmed {
palette.muted_style()
} else {
Style::new().fg(palette.text)
};
let marker = if row.is_child() { " └ " } else { "● " };
// A transcript that did not complete says so beside its count.
let outcome = if row.is_child() {
run_state_key(row.outcome, row.running, row.background)
} else {
None
};
let mut count = loc.tf(
"ui.chatlist.messages",
&[("n", &row.message_count.to_string())],
);
if let Some(key) = outcome {
count = format!("{} · {count}", loc.t(key));
}
// A background run's result the user has not looked at yet (spec
// §9.3.2): said in words beside the count, cleared by opening.
if row.unread {
count = format!("{} · {count}", loc.t("ui.chatlist.unread"));
}
// A folded chat says how many transcripts it is hiding — without the
// mark it would look like a chat that has none (docs/lessons.md §4).
if row.collapsed_children > 0 {
count = format!(
"{} {} · {count}",
palette.glyphs().collapsed,
row.collapsed_children
);
}
let count_w = display_width_str(&count);
let prefix_w = 2 + marker.chars().count(); // the rail + the marker
const TRAIL: usize = 1; // right-hand margin
// Available width for the title (a minimum 1-column gap before the counter).
let max_title = width.saturating_sub(prefix_w + count_w + TRAIL + 1);
let (title, title_w) = wrap::truncate_to_width(&row.title, max_title);
let gap = width
.saturating_sub(prefix_w + title_w + count_w + TRAIL)
.max(1);
Line::from(vec![
rail,
Span::styled(marker.to_string(), Style::new().fg(dot_color)),
Span::styled(title, title_style),
Span::raw(" ".repeat(gap)),
Span::styled(count, palette.muted_style()),
])
}
/// Status (hotkey) lines at the bottom of the screen — like on the chat screen: "keycaps"
/// on a muted background + muted descriptions, laid out by the one hint grid
/// ([`hotkey_grid`]): right-aligned, columns lined up vertically, wrapping
/// to as many rows as `width` needs. In rename mode — a single hint line.
fn status_lines(
&self,
palette: &Palette,
width: usize,
loc: &'static Locale,
) -> Vec<Line<'static>> {
if let Mode::Rename { .. } = self.mode {
return vec![Line::from(vec![
palette.keycap("Enter"),
Span::styled(
format!(" {} ", loc.t("ui.chatlist.rename.save")),
palette.muted_style(),
),
palette.keycap("Esc"),
Span::styled(
format!(" {}", loc.t("ui.chatlist.rename.cancel")),
palette.muted_style(),
),
])];
}
// Pairs "key — description — is it dangerous" (order = read left-to-right,
// top-to-bottom). `Tab` carries the current sort mode. The grid is laid out by
// the shared helper `Palette::hotkey_grid` (the same one the chat's status bar uses).
let sort_desc = loc.tf("ui.chatlist.sort", &[("sort", sort_label(self.sort, loc))]);
// `Ctrl+F` carries the current search mode, the same way `Tab` carries
// the sort mode.
let search_desc = loc.tf(
"ui.chatlist.search_mode",
&[("mode", mode_label(self.scope, loc))],
);
// On a transcript the two keys that refuse are not advertised
// (spec §11.2): an advertised key that is a no-op is worse than a
// missing hint, and the refusal itself still names the way out.
let selected = self.selected_row();
let on_child = selected.as_ref().is_some_and(Row::is_child);
// `Ctrl+O` folds/unfolds the selected chat's transcripts — advertised
// only when it has any, with the direction it would take (the way
// `Tab` carries the sort). On a transcript row it names the parent's.
let fold = selected.as_ref().and_then(|r| {
let id = r.parent.unwrap_or(r.id);
let chat = self.all.iter().find(|c| c.id == id)?;
(!chat.children.is_empty()).then(|| {
if chat.children_expanded {
loc.t("ui.chatlist.hk.children_hide")
} else {
loc.t("ui.chatlist.hk.children_show")
}
})
});
let mut items: Vec<(&str, &str, bool)> =
vec![("↑↓ PgUp/Dn Home/End", loc.t("ui.chatlist.hk.select"), false)];
// `Enter` opens the selected row — on an empty list there is none, and
// the key does nothing (`open_selected` returns `None`).
if selected.is_some() {
items.push(("Enter", loc.t("ui.chatlist.hk.open"), false));
}
if let Some(desc) = fold {
items.push(("Ctrl+O", desc, false));
}
items.extend([
("Ctrl+F", search_desc.as_str(), false),
("F2", loc.t("ui.chatlist.hk.rename"), false),
("Ctrl+R", loc.t("ui.chatlist.hk.autoname"), false),
("Ctrl+N", loc.t("ui.chatlist.hk.new"), false),
]);
if !on_child {
items.push(("Ctrl+D", loc.t("ui.chatlist.hk.clone"), false));
}
items.push(("F5", loc.t("ui.chatlist.hk.copy"), false));
if !on_child {
items.push(("Del", loc.t("ui.chatlist.hk.delete"), true));
}
items.extend([
// `F1` opens the help from every screen and is the door to the full
// key list — including the hints this footer hides for the current
// row (docs/history/status-hints-unified.md §2.2). Its place is right before
// `Esc`, as on the chat bar.
("F1", loc.t("ui.chatlist.hk.help"), false),
("Esc", loc.t("ui.chatlist.hk.back"), false),
("Ctrl+Q", loc.t("ui.chatlist.hk.quit"), false),
("Tab", sort_desc.as_str(), false),
]);
// Only in content mode, because that is the only mode it does anything
// in — an advertised key that is a no-op is worse than a missing hint.
if self.scope == SearchScope::Content {
items.push(("Ctrl+G", loc.t("ui.chatlist.hk.search_messages"), false));
}
hotkey_grid(palette, &items, width)
}
}
/// The visible width of a string in terminal columns.
fn display_width_str(s: &str) -> usize {
wrap::display_width(&s.chars().collect::<Vec<_>>())
}
/// A localized search-mode label (the search line and the `Ctrl+F` hint).
/// The bundle key for a run's state beside its row — the one wording the
/// chat list and the tasks screen share (spec §11.2, §11.10). `None` for a
/// completed run: the list says nothing there, the tasks screen its own word.
/// A run with no outcome is *running* while its mirror says so, otherwise
/// *unfinished* when it was out in the background (the app was closed while
/// it ran) and *interrupted* when it was a turn's child.
pub(crate) fn run_state_key(
outcome: Option<RunOutcome>,
running: bool,
background: bool,
) -> Option<&'static str> {
match outcome {
Some(RunOutcome::Completed) => None,
None if running => Some("ui.chatlist.run.running"),
None if background => Some("ui.chatlist.run.unfinished"),
None => Some("ui.chatlist.run.interrupted"),
Some(RunOutcome::Cancelled) => Some("ui.chatlist.run.cancelled"),
Some(RunOutcome::TimedOut) => Some("ui.chatlist.run.timed_out"),
Some(RunOutcome::Failed) => Some("ui.chatlist.run.failed"),
Some(RunOutcome::RoundLimit) => Some("ui.chatlist.run.round_limit"),
}
}
fn mode_label(scope: SearchScope, loc: &'static Locale) -> &'static str {
match scope {
SearchScope::Title => loc.t("ui.chatlist.mode.title"),
SearchScope::Content => loc.t("ui.chatlist.mode.content"),
}
}
/// A localized sort-mode label for the indicator (`Tab` in the chat list).
fn sort_label(sort: SortMode, loc: &'static Locale) -> &'static str {
match sort {
SortMode::Created => loc.t("ui.sort.created"),
SortMode::Modified => loc.t("ui.sort.modified"),
}
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::Utc;
fn ru() -> &'static Locale {
crate::shared::i18n::locale(crate::shared::i18n::Lang::Ru)
}
fn key(code: KeyCode) -> KeyEvent {
KeyEvent::new(code, KeyModifiers::NONE)
}
fn ctrl(code: KeyCode) -> KeyEvent {
KeyEvent::new(code, KeyModifiers::CONTROL)
}
fn chat(title: &str) -> ChatSummary {
ChatSummary::fixture(title)
}
#[test]
fn typing_filters_and_enter_switches() {
let chats = vec![chat("Альфа"), chat("Бета")];
let beta_id = chats[1].id;
let mut s = ChatListState::new(chats, None);
for c in "Бет".chars() {
assert_eq!(s.on_key(key(KeyCode::Char(c))), ChatListAction::None);
}
// one chat remains — and it's the selected one
assert_eq!(s.selected_id(), Some(beta_id));
assert_eq!(
s.on_key(key(KeyCode::Enter)),
ChatListAction::Switch(beta_id)
);
}
#[test]
fn ctrl_f_toggles_search_mode_and_asks_for_content_results() {
let mut s = ChatListState::new(vec![chat("Альфа")], None);
for c in "тек".chars() {
assert_eq!(s.on_key(key(KeyCode::Char(c))), ChatListAction::None);
}
assert_eq!(s.scope, SearchScope::Title);
// Switching into content mode searches the text already typed, rather
// than waiting for the next keystroke.
assert_eq!(
s.on_key(ctrl(KeyCode::Char('f'))),
ChatListAction::SearchContent("тек".into())
);
assert_eq!(s.scope, SearchScope::Content);
// Also under a Cyrillic layout (physical F = Ctrl+а).
assert_eq!(s.on_key(ctrl(KeyCode::Char('а'))), ChatListAction::None);
assert_eq!(s.scope, SearchScope::Title, "and back again");
}
#[test]
fn editing_the_query_searches_in_content_mode_only() {
let mut s = ChatListState::new(vec![chat("Альфа")], None);
// Title mode: filtering is local, so no round-trip.
assert_eq!(s.on_key(key(KeyCode::Char('a'))), ChatListAction::None);
assert_eq!(s.on_key(key(KeyCode::Backspace)), ChatListAction::None);
s.on_key(ctrl(KeyCode::Char('f')));
assert_eq!(
s.on_key(key(KeyCode::Char('x'))),
ChatListAction::SearchContent("x".into())
);
assert_eq!(
s.on_key(key(KeyCode::Char('y'))),
ChatListAction::SearchContent("xy".into())
);
assert_eq!(
s.on_key(key(KeyCode::Backspace)),
ChatListAction::SearchContent("x".into())
);
}
#[test]
fn content_results_filter_the_list_and_ignore_the_title() {
// The point of content mode: a chat whose *title* does not contain the
// query still shows up, because its messages matched.
let chats = vec![chat("Альфа"), chat("Бета"), chat("Гамма")];
let (alpha, gamma) = (chats[0].id, chats[2].id);
let mut s = ChatListState::new(chats, None);
s.on_key(ctrl(KeyCode::Char('f')));
// Nothing back yet — everything is shown, exactly like an empty query.
for c in "нечто".chars() {
s.on_key(key(KeyCode::Char(c)));
}
assert_eq!(s.visible().len(), 3, "no result yet — show everything");
s.set_search_results("нечто".into(), Some(vec![alpha, gamma]));
let visible: Vec<Uuid> = s.visible().iter().map(|c| c.id).collect();
assert_eq!(visible.len(), 2);
assert!(visible.contains(&alpha) && visible.contains(&gamma));
// An unsearchable query (too short for trigram) filters nothing.
s.set_search_results("не".into(), None);
assert_eq!(s.visible().len(), 3);
// An empty result is an empty list — not "show everything".
s.set_search_results("нечто".into(), Some(vec![]));
assert!(s.visible().is_empty());
assert_eq!(s.selected_id(), None);
}
#[test]
fn stale_results_are_still_applied_rather_than_flashing_the_full_list() {
// Results arrive a keystroke or two behind what is typed. Showing the
// previous answer beats showing every chat between keystrokes.
let chats = vec![chat("Альфа"), chat("Бета")];
let alpha = chats[0].id;
let mut s = ChatListState::new(chats, None);
s.on_key(ctrl(KeyCode::Char('f')));
for c in "текст".chars() {
s.on_key(key(KeyCode::Char(c)));
}
s.set_search_results("тек".into(), Some(vec![alpha]));
assert_eq!(s.visible().len(), 1, "an older answer is still applied");
assert_eq!(s.selected_id(), Some(alpha));
}
/// Stage 2b: in content mode `Enter` opens the chat **at its first match**
/// rather than at its tail — the user asked where this text is. Title mode
/// keeps the historical plain switch.
#[test]
fn enter_opens_at_the_first_match_in_content_mode_only() {
let chats = vec![chat("Альфа")];
let id = chats[0].id;
let mut s = ChatListState::new(chats, None);
// Title mode — unchanged.
for c in "Аль".chars() {
s.on_key(key(KeyCode::Char(c)));
}
assert_eq!(s.on_key(key(KeyCode::Enter)), ChatListAction::Switch(id));
// Content mode — a jump, carrying the raw query for the orchestrator to
// resolve against the index.
s.on_key(ctrl(KeyCode::Char('f')));
assert_eq!(
s.on_key(key(KeyCode::Enter)),
ChatListAction::OpenFirstMatch {
chat: id,
query: "Аль".into()
}
);
// With nothing typed there is no match to open at — a plain switch.
for _ in 0..3 {
s.on_key(key(KeyCode::Backspace));
}
assert_eq!(s.on_key(key(KeyCode::Enter)), ChatListAction::Switch(id));
}
/// `Ctrl+G` hands the query to the message-level screen — and only in
/// content mode, where the hint for it is also the only place it is shown.
#[test]
fn ctrl_g_asks_for_message_search_in_content_mode_only() {
let mut s = ChatListState::new(vec![chat("Альфа")], None);
for c in "марк".chars() {
s.on_key(key(KeyCode::Char(c)));
}
assert_eq!(
s.on_key(ctrl(KeyCode::Char('g'))),
ChatListAction::None,
"title mode has no message search"
);
s.on_key(ctrl(KeyCode::Char('f')));
assert_eq!(
s.on_key(ctrl(KeyCode::Char('g'))),
ChatListAction::SearchMessages {
query: "марк".into(),
sort: SortMode::default(),
}
);
// Also under a Cyrillic layout (physical G = Ctrl+п).
assert_eq!(
s.on_key(ctrl(KeyCode::Char('п'))),
ChatListAction::SearchMessages {
query: "марк".into(),
sort: SortMode::default(),
}
);
}
#[test]
fn the_message_search_hint_is_shown_only_in_content_mode() {
use ratatui::Terminal;
use ratatui::backend::TestBackend;
let render = |state: &mut ChatListState| {
let mut term = Terminal::new(TestBackend::new(100, 24)).unwrap();
term.draw(|f| state.render(f, f.area(), None, &Palette::default(), ru()))
.unwrap();
format!("{:?}", term.backend().buffer())
};
let mut s = ChatListState::new(vec![chat("Альфа")], None);
assert!(
!render(&mut s).contains("Ctrl+G"),
"an advertised key that does nothing is worse than no hint"
);
s.on_key(ctrl(KeyCode::Char('f')));
assert!(render(&mut s).contains("Ctrl+G"));
}
/// Closing the message-level screen brings the list back **still searching**
/// — the user came from a content search, and an empty title-mode list would
/// throw that away.
#[test]
fn restore_content_query_reopens_the_list_in_content_mode() {
let chats = vec![chat("Альфа"), chat("Бета")];
let alpha = chats[0].id;
let mut s = ChatListState::new(chats, None);
s.restore_content_query("маркер".into());
assert_eq!(s.query, "маркер");
assert_eq!(s.scope, SearchScope::Content);
// The title filter is not applied in content mode, so until results
// arrive everything is shown — then they filter it.
assert_eq!(s.visible().len(), 2);
s.set_search_results("маркер".into(), Some(vec![alpha]));
assert_eq!(s.selected_id(), Some(alpha));
}
#[test]
fn title_mode_is_unaffected_by_content_results() {
// Everything above must leave the historical behaviour alone.
let chats = vec![chat("Альфа"), chat("Бета")];
let beta = chats[1].id;
let mut s = ChatListState::new(chats, None);
// A result that arrived while content mode was on…
s.on_key(ctrl(KeyCode::Char('f')));
s.set_search_results("q".into(), Some(vec![]));
// …must not survive the switch back to title search.
s.on_key(ctrl(KeyCode::Char('f')));
assert_eq!(s.visible().len(), 2);
for c in "Бет".chars() {
s.on_key(key(KeyCode::Char(c)));
}
assert_eq!(s.selected_id(), Some(beta));
}
#[test]
fn search_mode_is_visible_in_the_search_line() {
use ratatui::Terminal;
use ratatui::backend::TestBackend;
let render = |state: &mut ChatListState| {
let mut term = Terminal::new(TestBackend::new(80, 24)).unwrap();
term.draw(|f| state.render(f, f.area(), None, &Palette::default(), ru()))
.unwrap();
format!("{:?}", term.backend().buffer())
};
let mut s = ChatListState::new(vec![chat("Альфа")], None);
let dump = render(&mut s);
assert!(dump.contains("названия"), "{dump}");
s.on_key(ctrl(KeyCode::Char('f')));
let dump = render(&mut s);
assert!(
dump.contains("содержимое"),
"the mode must be visible — it changes what typing does: {dump}"
);
}
#[test]
fn esc_closes() {
let mut s = ChatListState::new(vec![chat("A")], None);
assert_eq!(s.on_key(key(KeyCode::Esc)), ChatListAction::Close);
}
#[test]
fn ctrl_q_and_f10_quit() {
let mut s = ChatListState::new(vec![chat("A")], None);
assert_eq!(s.on_key(ctrl(KeyCode::Char('q'))), ChatListAction::Quit);
// Also under a Cyrillic layout (physical Q = Ctrl+й).
assert_eq!(s.on_key(ctrl(KeyCode::Char('й'))), ChatListAction::Quit);
// F10 — a second way to quit.
assert_eq!(s.on_key(key(KeyCode::F(10))), ChatListAction::Quit);
// Ctrl+C is no longer quit (freed up for copying).
assert_ne!(s.on_key(ctrl(KeyCode::Char('c'))), ChatListAction::Quit);
}
#[test]
fn ctrl_n_and_ctrl_d_and_delete() {
let chats = vec![chat("A")];
let id = chats[0].id;
let mut s = ChatListState::new(chats, None);
assert_eq!(s.on_key(ctrl(KeyCode::Char('n'))), ChatListAction::New);
assert_eq!(
s.on_key(ctrl(KeyCode::Char('d'))),
ChatListAction::Clone(id)
);
assert_eq!(s.on_key(key(KeyCode::Delete)), ChatListAction::Delete(id));
}
#[test]
fn ctrl_shortcuts_work_under_cyrillic_layout() {
// Russian layout: Ctrl+т (physical N) — new, Ctrl+в (physical D) — clone.
let chats = vec![chat("A")];
let id = chats[0].id;
let mut s = ChatListState::new(chats, None);
assert_eq!(s.on_key(ctrl(KeyCode::Char('т'))), ChatListAction::New);
assert_eq!(
s.on_key(ctrl(KeyCode::Char('в'))),
ChatListAction::Clone(id)
);
// Cyrillic search text still gets typed (without Ctrl).
s.on_key(key(KeyCode::Char('я')));
assert_eq!(s.query, "я");
}
#[test]
fn f5_requests_copy_of_selected() {
let chats = vec![chat("A")];
let id = chats[0].id;
let mut s = ChatListState::new(chats, None);
assert_eq!(s.on_key(key(KeyCode::F(5))), ChatListAction::Copy(id));
}
#[test]
fn notice_is_set_and_cleared_on_next_key() {
let mut s = ChatListState::new(vec![chat("A")], None);
s.set_notice("скопировано".into());
assert_eq!(s.notice.as_deref(), Some("скопировано"));
// Setting an error clears a confirmation and vice versa (mutually exclusive).
s.set_error("боль".into());
assert!(s.notice.is_none());
s.set_notice("ок".into());
assert!(s.error.is_none());
// Any key press clears the confirmation.
s.on_key(key(KeyCode::Down));
assert!(s.notice.is_none());
}
#[test]
fn ctrl_r_requests_auto_rename_of_selected() {
let chats = vec![chat("A")];
let id = chats[0].id;
let mut s = ChatListState::new(chats, None);
assert_eq!(
s.on_key(ctrl(KeyCode::Char('r'))),
ChatListAction::AutoRename(id)
);
// Also under a Cyrillic layout (physical R = Ctrl+к).
assert_eq!(
s.on_key(ctrl(KeyCode::Char('к'))),
ChatListAction::AutoRename(id)
);
}
#[test]
fn f2_enters_rename_and_enter_commits() {
let chats = vec![chat("Старое")];
let id = chats[0].id;
let mut s = ChatListState::new(chats, None);
assert_eq!(s.on_key(key(KeyCode::F(2))), ChatListAction::None);
// clear the buffer and type a new name
for _ in 0.."Старое".chars().count() {
s.on_key(key(KeyCode::Backspace));
}
for c in "Новое".chars() {
s.on_key(key(KeyCode::Char(c)));
}
assert_eq!(
s.on_key(key(KeyCode::Enter)),
ChatListAction::Rename {
id,
title: "Новое".into()
}
);
}
#[test]
fn rename_cursor_moves_and_edits_in_middle() {
// The cursor in rename mode moves via arrows/Home/End, edits go
// at the cursor's position (not only at the end).
let chats = vec![chat("abc")];
let id = chats[0].id;
let mut s = ChatListState::new(chats, None);
s.on_key(key(KeyCode::F(2))); // buffer "abc", cursor at the end (3)
s.on_key(key(KeyCode::Home)); // cursor → 0
s.on_key(key(KeyCode::Char('X'))); // insert at the start → "Xabc", cursor 1
s.on_key(key(KeyCode::End)); // cursor → 4 (end)
s.on_key(key(KeyCode::Char('Y'))); // insert at the end → "XabcY", cursor 5
s.on_key(key(KeyCode::Home)); // cursor → 0
s.on_key(key(KeyCode::Right)); // cursor 1
s.on_key(key(KeyCode::Right)); // cursor 2 (before 'b')
s.on_key(key(KeyCode::Delete)); // delete 'b' in the middle → "XacY"
assert_eq!(
s.on_key(key(KeyCode::Enter)),
ChatListAction::Rename {
id,
title: "XacY".into()
}
);
}
#[test]
fn rename_supports_input_box_word_navigation() {
// The rename field is a single-line `InputBox`, so `Ctrl+Backspace`
// deletes the whole word (the old character-by-character buffer couldn't do this).
let chats = vec![chat("один два")];
let id = chats[0].id;
let mut s = ChatListState::new(chats, None);
s.on_key(key(KeyCode::F(2))); // two-word title, cursor at the end
s.on_key(ctrl(KeyCode::Backspace)); // delete the last word, leaving a trailing space
assert_eq!(
s.on_key(key(KeyCode::Enter)),
ChatListAction::Rename {
id,
title: "один".into() // sanitize_title strips the trailing space
}
);
}
#[test]
fn rename_clear_with_ctrl_k_undo_with_ctrl_z() {
// `Ctrl+K` clears the field, `Ctrl+Z` restores the text (the shared undo model, §C).
let chats = vec![chat("Старое имя")];
let id = chats[0].id;
let mut s = ChatListState::new(chats, None);
s.on_key(key(KeyCode::F(2)));
s.on_key(ctrl(KeyCode::Char('k'))); // delete all the text
s.on_key(ctrl(KeyCode::Char('z'))); // undo — restore what was deleted
assert_eq!(
s.on_key(key(KeyCode::Enter)),
ChatListAction::Rename {
id,
title: "Старое имя".into()
}
);
}
#[test]
fn rename_spellcheck_underlines_misspelled_word() {
use crate::features::spellcheck::SpellChecker;
use std::collections::HashSet;
let dict = spellbook::Dictionary::new("SET UTF-8\n", "1\nhello\n").unwrap();
let spell = SpellChecker::new(vec![dict], HashSet::new(), None);
let mut s = ChatListState::new(vec![chat("helo")], None);
s.on_key(key(KeyCode::F(2))); // enter rename mode, text "helo"
// The spelling recompute flags "helo" as an error (a non-empty range).
assert!(s.recheck_rename_spelling(&spell));
match &s.mode {
Mode::Rename {
input, spell_dirty, ..
} => {
assert!(!*spell_dirty, "the flag is reset after a recompute");
assert!(!input.misspelled_is_empty(), "the error must be underlined");
}
_ => panic!("expected rename mode"),
}
// Outside rename mode a recompute is a no-op.
s.on_key(key(KeyCode::Esc));
assert!(!s.recheck_rename_spelling(&spell));
}
#[test]
fn rename_paste_inserts_into_field() {
let chats = vec![chat("a")];
let id = chats[0].id;
let mut s = ChatListState::new(chats, None);
s.on_key(key(KeyCode::F(2))); // "a", cursor at the end
s.handle_paste("bc"); // paste from the clipboard
assert_eq!(
s.on_key(key(KeyCode::Enter)),
ChatListAction::Rename {
id,
title: "abc".into()
}
);
}
#[test]
fn rename_esc_cancels_without_action() {
let chats = vec![chat("Старое")];
let mut s = ChatListState::new(chats, None);
s.on_key(key(KeyCode::F(2)));
assert_eq!(s.on_key(key(KeyCode::Esc)), ChatListAction::None);
// back in search mode: typing filters again
s.on_key(key(KeyCode::Char('x')));
assert_eq!(s.selected_id(), None); // 'x' matched nothing
}
#[test]
fn page_up_down_move_selection_by_page() {
// 25 chats; PageDown moves by PAGE_STEP without going past the end, PageUp — backward.
let chats: Vec<ChatSummary> = (0..25).map(|i| chat(&format!("чат {i}"))).collect();
let mut s = ChatListState::new(chats, None);
assert_eq!(s.selected, 0);
s.on_key(key(KeyCode::PageDown));
assert_eq!(s.selected, PAGE_STEP);
s.on_key(key(KeyCode::PageDown));
assert_eq!(s.selected, 2 * PAGE_STEP);
// A third PageDown clamps to the last item (24), not overshooting the edge.
s.on_key(key(KeyCode::PageDown));
assert_eq!(s.selected, 24);
s.on_key(key(KeyCode::PageUp));
assert_eq!(s.selected, 24 - PAGE_STEP);
// PageUp from near the top saturates at 0 (no underflow).
s.on_key(key(KeyCode::PageUp));
s.on_key(key(KeyCode::PageUp));
assert_eq!(s.selected, 0);
}
/// `↑` must first walk the selection up to the window's top row and only
/// then scroll the list — the mirror image of what `↓` does. The offset
/// therefore has to survive between frames: rebuilt from zero, ratatui
/// recomputes it around the selection, and the list scrolls on every press.
#[test]
fn moving_up_walks_to_the_top_row_before_the_list_scrolls() {
use ratatui::Terminal;
use ratatui::backend::TestBackend;
// Explicitly descending timestamps: the sort is newest-first, so the
// list runs from -00 at its head to -29 at its tail regardless of how
// coarse the clock behind the fixture is.
let chats: Vec<ChatSummary> = (0..30)
.map(|i| ChatSummary {
modified_at: Utc::now() - chrono::Duration::seconds(i),
..chat(&format!("код-{i:02}"))
})
.collect();
let mut s = ChatListState::new(chats, None);
let mut term = Terminal::new(TestBackend::new(60, 20)).unwrap();
let mut render = |state: &mut ChatListState| {
term.draw(|f| state.render(f, f.area(), None, &Palette::default(), ru()))
.unwrap();
format!("{:?}", term.backend().buffer())
};
// Jump to the tail: the last chat is on the bottom row, the first one is
// scrolled out of the window.
s.on_key(key(KeyCode::End));
let tail = render(&mut s);
assert!(tail.contains("код-29"), "{tail}");
assert!(!tail.contains("код-00"), "{tail}");
// A single press moves the selection inside the window — the rows stay put.
s.on_key(key(KeyCode::Up));
let inside = render(&mut s);
assert!(
inside.contains("код-29"),
"the window must not scroll while the selection can still move inside it: {inside}"
);
// Only once the selection has reached the top row does the list scroll.
for _ in 0..29 {
s.on_key(key(KeyCode::Up));
}
let head = render(&mut s);
assert!(head.contains("код-00"), "{head}");
assert!(!head.contains("код-29"), "{head}");
}
#[test]
fn home_end_jump_to_first_and_last() {
let chats: Vec<ChatSummary> = (0..25).map(|i| chat(&format!("чат {i}"))).collect();
let mut s = ChatListState::new(chats, None);
s.on_key(key(KeyCode::End));
assert_eq!(s.selected, 24);
s.on_key(key(KeyCode::Home));
assert_eq!(s.selected, 0);
}
#[test]
fn home_end_on_empty_list_is_noop() {
let mut s = ChatListState::new(vec![], None);
assert_eq!(s.on_key(key(KeyCode::End)), ChatListAction::None);
assert_eq!(s.selected, 0);
assert_eq!(s.on_key(key(KeyCode::Home)), ChatListAction::None);
assert_eq!(s.selected, 0);
}
#[test]
fn page_down_on_empty_list_is_noop() {
let mut s = ChatListState::new(vec![], None);
assert_eq!(s.on_key(key(KeyCode::PageDown)), ChatListAction::None);
assert_eq!(s.selected, 0);
}
#[test]
fn tab_toggles_sort_indicator() {
let mut s = ChatListState::new(vec![chat("A")], None);
let before = s.sort;
s.on_key(key(KeyCode::Tab));
assert_ne!(s.sort, before);
}
#[test]
fn error_is_set_and_cleared_on_next_key() {
let mut s = ChatListState::new(vec![chat("A")], None);
s.set_error("боль".into());
assert_eq!(s.error.as_deref(), Some("боль"));
// Any key press clears the error.
s.on_key(key(KeyCode::Down));
assert!(s.error.is_none());
}
#[test]
fn render_with_error_does_not_panic() {
use ratatui::Terminal;
use ratatui::backend::TestBackend;
let mut state = ChatListState::new(vec![chat("Альфа")], None);
state.set_error("Недостаточно сообщений для авто-названия".into());
for (w, h) in [(80u16, 24u16), (20, 6)] {
let mut term = Terminal::new(TestBackend::new(w, h)).unwrap();
term.draw(|f| state.render(f, f.area(), None, &Palette::default(), ru()))
.unwrap();
}
}
#[test]
fn scrollbar_appears_only_when_list_overflows() {
use ratatui::Terminal;
use ratatui::backend::TestBackend;
// The "█" thumb on the panel's right border — only when there are more chats than the height.
let has_thumb = |term: &Terminal<TestBackend>| {
let buf = term.backend().buffer();
let x = buf.area.right() - 1; // the border column of the "Chats" panel
(buf.area.top()..buf.area.bottom()).any(|y| buf[(x, y)].symbol() == "█")
};
// Width 72 — the hotkey grid at the bottom is 2 columns (doesn't eat into the list's height).
let mut term = Terminal::new(TestBackend::new(72, 24)).unwrap();
let mut short = ChatListState::new(vec![chat("A"), chat("B")], None);
term.draw(|f| short.render(f, f.area(), None, &Palette::default(), ru()))
.unwrap();
assert!(!has_thumb(&term), "a short list — no scrollbar thumb");
let chats: Vec<ChatSummary> = (0..40).map(|i| chat(&format!("Чат {i}"))).collect();
let mut long = ChatListState::new(chats, None);
term.draw(|f| long.render(f, f.area(), None, &Palette::default(), ru()))
.unwrap();
assert!(has_thumb(&term), "a long list — with a scrollbar thumb");
}
#[test]
fn render_does_not_panic_on_small_and_normal_areas() {
use ratatui::Terminal;
use ratatui::backend::TestBackend;
let mut state = ChatListState::new(vec![chat("Альфа"), chat("Бета")], None);
for (w, h) in [(80u16, 24u16), (20, 6)] {
let mut term = Terminal::new(TestBackend::new(w, h)).unwrap();
term.draw(|f| state.render(f, f.area(), None, &Palette::default(), ru()))
.unwrap();
}
}
#[test]
fn set_chats_keeps_selection_on_same_chat() {
let chats = vec![chat("A"), chat("B"), chat("C")];
let b_id = chats[1].id;
let mut s = ChatListState::new(chats.clone(), None);
s.on_key(key(KeyCode::Down)); // select B (index 1 in Modified order ~ the source order)
let sel = s.selected_id();
// update the list with the same set — selection stays on the same chat
s.set_chats(chats);
assert_eq!(s.selected_id(), sel);
let _ = b_id;
}
#[test]
fn deleting_selected_keeps_position_not_first() {
// Deleting the selected chat (a re-emit of the list without it) leaves selection
// at the same position — the next chat in the list ends up under it, rather
// than jumping to the first item.
let chats = vec![chat("A"), chat("B"), chat("C")];
let mut s = ChatListState::new(chats, None);
s.on_key(key(KeyCode::Down)); // selection at position 1
assert_eq!(s.selected, 1);
// Take the order from the actual `visible` list (sorting may differ from
// insertion order) — so the test doesn't depend on close-together timestamps.
let victim_id = s.selected_id().unwrap();
let next_id = s.visible()[2].id; // will end up under position 1 after deletion
let remaining: Vec<ChatSummary> = s
.all
.iter()
.filter(|c| c.id != victim_id)
.cloned()
.collect();
s.set_chats(remaining);
assert_eq!(s.selected, 1, "the selection position is preserved");
assert_eq!(
s.selected_id(),
Some(next_id),
"under the selection — the former next chat, not the first one"
);
}
#[test]
fn deleting_last_selected_clamps_to_new_last() {
// Deleting the selected last chat moves selection to the new last one
// (not to the first).
let chats = vec![chat("A"), chat("B"), chat("C")];
let mut s = ChatListState::new(chats, None);
s.on_key(key(KeyCode::End)); // selection on the last one (position 2)
assert_eq!(s.selected, 2);
let victim_id = s.selected_id().unwrap();
let new_last_id = s.visible()[1].id; // will become the new last one
let remaining: Vec<ChatSummary> = s
.all
.iter()
.filter(|c| c.id != victim_id)
.cloned()
.collect();
s.set_chats(remaining);
assert_eq!(s.selected, 1, "selection clamps to the new last one");
assert_eq!(s.selected_id(), Some(new_last_id));
}
}
/// The two-level tree (spec §11.2, docs/research/subagent-chats.md §3.7): a
/// chat's sub-agent transcripts nest under it, in call order; the filter rule
/// shows a transcript only with its parent and a parent alone when only it
/// matches; the refusing keys are not advertised on a transcript. The stored
/// fold (`children_expanded`, `Ctrl+O`) hides the transcripts of a collapsed
/// chat — the default — unless a search matches one.
#[cfg(test)]
mod tree_tests {
use super::*;
use crate::entities::chat::ChildSummary;
use chrono::{Duration, Utc};
fn key(code: KeyCode) -> KeyEvent {
KeyEvent::new(code, KeyModifiers::NONE)
}
fn ctrl(c: char) -> KeyEvent {
KeyEvent::new(KeyCode::Char(c), KeyModifiers::CONTROL)
}
/// The status grid's text at width 200 (`ru` locale) — what the hint
/// assertions read.
fn status_text(s: &ChatListState) -> String {
let loc = crate::shared::i18n::locale(crate::shared::i18n::Lang::Ru);
s.status_lines(&Palette::default(), 200, loc)
.iter()
.flat_map(|l| l.spans.iter().map(|sp| sp.content.to_string()))
.collect()
}
/// One row's rendered text (width 60, `ru` locale).
fn row_text(s: &ChatListState, r: &Row) -> String {
let loc = crate::shared::i18n::locale(crate::shared::i18n::Lang::Ru);
s.item_line(r, false, None, &Palette::default(), 60, loc)
.spans
.iter()
.map(|sp| sp.content.to_string())
.collect()
}
fn child(title: &str, minutes: i64, outcome: Option<RunOutcome>) -> ChildSummary {
ChildSummary {
id: Uuid::new_v4(),
title: title.to_string(),
created_at: Utc::now() + Duration::minutes(minutes),
finished_at: None,
message_count: 3,
outcome,
running: false,
background: false,
}
}
/// The tree fixture, with the parent's transcripts **unfolded** — these
/// tests are about the tree's shape and the search rule; the fold's own
/// behaviour (collapsed is the default) lives in [`fold_tests`].
fn family() -> Vec<ChatSummary> {
let mut chats = collapsed_family();
chats[0].children_expanded = true;
chats
}
/// The same two chats with the stored default — a fold nobody has opened.
fn collapsed_family() -> Vec<ChatSummary> {
let mut plans = ChatSummary::fixture("Планы");
plans.created_at = Utc::now() - Duration::hours(1);
plans.modified_at = plans.created_at;
plans.message_count = 6;
plans.children = vec![
child("Критик", 1, Some(RunOutcome::Completed)),
child("Искатель", 2, Some(RunOutcome::TimedOut)),
];
let mut recipes = ChatSummary::fixture("Рецепты");
recipes.message_count = 2;
vec![plans, recipes]
}
#[test]
fn transcripts_follow_their_parent_in_call_order() {
let s = ChatListState::new(family(), None);
let titles: Vec<(String, bool)> = s
.visible()
.iter()
.map(|r| (r.title.clone(), r.is_child()))
.collect();
// Sorted by modified (the default): the newer chat first, then the
// older one with its two transcripts in the order the calls were made.
assert_eq!(
titles,
vec![
("Рецепты".to_string(), false),
("Планы".to_string(), false),
("Критик".to_string(), true),
("Искатель".to_string(), true),
]
);
let rows = s.visible();
assert_eq!(rows[2].parent, Some(rows[1].id));
assert_eq!(rows[3].outcome, Some(RunOutcome::TimedOut));
assert!(!rows[1].dimmed);
}
#[test]
fn a_matching_transcript_brings_its_parent_dimmed_and_nothing_else() {
let mut s = ChatListState::new(family(), None);
for c in "Иска".chars() {
s.on_key(key(KeyCode::Char(c)));
}
let rows = s.visible();
let titles: Vec<&str> = rows.iter().map(|r| r.title.as_str()).collect();
assert_eq!(titles, vec!["Планы", "Искатель"]);
assert!(rows[0].dimmed, "the parent is context, not a match");
assert!(!rows[1].dimmed);
}
#[test]
fn a_matching_parent_alone_shows_no_transcripts() {
let mut s = ChatListState::new(family(), None);
for c in "План".chars() {
s.on_key(key(KeyCode::Char(c)));
}
let titles: Vec<String> = s.visible().iter().map(|r| r.title.clone()).collect();
assert_eq!(titles, vec!["Планы".to_string()]);
}
#[test]
fn content_results_name_transcripts_directly() {
// The index answers with ids; a transcript's id stands for itself
// (the same membership test as a chat's).
let chats = family();
let critic = chats[0].children[0].id;
let recipes = chats[1].id;
let mut s = ChatListState::new(chats, None);
s.on_key(KeyEvent::new(KeyCode::Char('f'), KeyModifiers::CONTROL));
s.set_search_results("x".into(), Some(vec![critic, recipes]));
let rows = s.visible();
let titles: Vec<&str> = rows.iter().map(|r| r.title.as_str()).collect();
assert_eq!(titles, vec!["Рецепты", "Планы", "Критик"]);
assert!(rows[1].dimmed);
}
#[test]
fn keys_on_a_transcript_open_rename_and_copy_it() {
let chats = family();
let critic = chats[0].children[0].id;
let mut s = ChatListState::new(chats, Some(critic));
assert_eq!(
s.selected_id(),
Some(critic),
"opens selected on the active transcript"
);
assert_eq!(
s.on_key(key(KeyCode::Enter)),
ChatListAction::Switch(critic)
);
assert_eq!(s.on_key(key(KeyCode::F(5))), ChatListAction::Copy(critic));
assert_eq!(
s.on_key(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL)),
ChatListAction::AutoRename(critic)
);
s.on_key(key(KeyCode::F(2)));
assert!(matches!(&s.mode, Mode::Rename { id, .. } if *id == critic));
}
#[test]
fn the_hotkey_grid_drops_delete_and_clone_on_a_transcript() {
let chats = family();
let critic = chats[0].children[0].id;
let parent = chats[0].id;
let on_parent = ChatListState::new(chats.clone(), Some(parent));
assert!(status_text(&on_parent).contains("Del"));
assert!(status_text(&on_parent).contains("Ctrl+D"));
let on_child = ChatListState::new(chats, Some(critic));
assert!(!status_text(&on_child).contains("Del"));
assert!(!status_text(&on_child).contains("Ctrl+D"));
}
/// `F1` opens the help from here as from anywhere, and `Enter` needs a row
/// to open — an empty list has none, and `open_selected` returns nothing
/// (docs/history/status-hints-unified.md §2.2).
#[test]
fn the_hotkey_grid_advertises_help_and_drops_enter_on_an_empty_list() {
let loc = crate::shared::i18n::locale(crate::shared::i18n::Lang::Ru);
let full = ChatListState::new(family(), None);
assert!(status_text(&full).contains("F1"));
assert!(status_text(&full).contains(loc.t("ui.chatlist.hk.open")));
let empty = ChatListState::new(Vec::new(), None);
let text = status_text(&empty);
assert!(
!text.contains(loc.t("ui.chatlist.hk.open")),
"nothing to open: {text}"
);
assert!(
text.contains("F1"),
"the way to the full list stays: {text}"
);
}
/// The footer is right-aligned like every other screen's: the block hugs the
/// right edge, and a wrapped bottom row lands under the columns above
/// (docs/history/status-hints-unified.md §2.1).
#[test]
fn the_hotkey_grid_hugs_the_right_edge() {
let loc = crate::shared::i18n::locale(crate::shared::i18n::Lang::Ru);
let s = ChatListState::new(family(), None);
let rows: Vec<String> = s
.status_lines(&Palette::default(), 116, loc)
.iter()
.map(|l| l.spans.iter().map(|sp| sp.content.as_ref()).collect())
.collect();
assert!(rows.len() > 1, "the list is long enough to wrap: {rows:?}");
for r in &rows {
assert_eq!(wrap::display_width(&r.chars().collect::<Vec<_>>()), 116);
}
// The last row ends flush right, and the rows before it are padded to
// the same edge — that is what "one block in the corner" means.
assert!(
!rows.last().unwrap().ends_with(" "),
"the block ends at the edge: {:?}",
rows.last()
);
}
#[test]
fn a_transcript_row_is_indented_and_names_its_outcome() {
let chats = family();
let loc = crate::shared::i18n::locale(crate::shared::i18n::Lang::Ru);
let s = ChatListState::new(chats, None);
let rows = s.visible();
assert!(row_text(&s, &rows[1]).starts_with(" ● Планы"));
assert!(row_text(&s, &rows[2]).starts_with(" └ Критик"));
assert!(!row_text(&s, &rows[2]).contains(loc.t("ui.chatlist.run.cancelled")));
assert!(row_text(&s, &rows[3]).contains(loc.t("ui.chatlist.run.timed_out")));
}
/// A chat whose background run landed while it was not open is marked
/// *unread* in words beside its count (spec §9.3.2, §11.2); the mark is
/// the card's, so a snapshot that says read draws none — and a
/// transcript's row never carries it, whatever its parent says.
#[test]
fn an_unread_chat_says_so_beside_its_count() {
let loc = crate::shared::i18n::locale(crate::shared::i18n::Lang::Ru);
let mut chats = family();
chats[0].unread = true;
let s = ChatListState::new(chats, None);
let rows = s.visible();
let plans = rows.iter().find(|r| r.title == "Планы").unwrap();
assert!(plans.unread);
let text = row_text(&s, plans);
assert!(text.contains(loc.t("ui.chatlist.unread")), "{text}");
let critic = rows.iter().find(|r| r.title == "Критик").unwrap();
assert!(!critic.unread);
assert!(!row_text(&s, critic).contains(loc.t("ui.chatlist.unread")));
let recipes = rows.iter().find(|r| r.title == "Рецепты").unwrap();
assert!(!row_text(&s, recipes).contains(loc.t("ui.chatlist.unread")));
}
/// The stored fold (spec §11.2): a collapsed chat — the default — hides
/// its transcripts, and the row says how many it is hiding; without the
/// mark it would read as a chat that has none (docs/lessons.md §4).
#[test]
fn collapsed_by_default_hides_transcripts_and_marks_the_row() {
let s = ChatListState::new(collapsed_family(), None);
let rows = s.visible();
let titles: Vec<&str> = rows.iter().map(|r| r.title.as_str()).collect();
assert_eq!(titles, vec!["Рецепты", "Планы"]);
assert_eq!(rows[1].collapsed_children, 2);
assert_eq!(rows[0].collapsed_children, 0, "no transcripts — no mark");
let text = row_text(&s, &rows[1]);
assert!(text.contains("▸ 2 · "), "{text}");
}
/// `Ctrl+O` asks for the stored fold to flip — under any layout — and the
/// widget itself applies nothing: the updated summaries come back through
/// `set_chats`, the same round-trip a rename takes.
#[test]
fn ctrl_o_toggles_the_selected_chats_fold() {
let chats = collapsed_family();
let parent = chats[0].id;
let mut s = ChatListState::new(chats, Some(parent));
assert_eq!(
s.on_key(ctrl('o')),
ChatListAction::SetChildrenExpanded {
id: parent,
expanded: true
}
);
assert_eq!(s.visible().len(), 2, "nothing applied until the round-trip");
let mut chats = s.all.clone();
chats[0].children_expanded = true;
s.set_chats(chats);
let rows = s.visible();
assert_eq!(rows.len(), 4, "unfolded — the transcripts are rows again");
assert_eq!(rows[1].collapsed_children, 0, "an open fold needs no mark");
// Folding back — also under a Cyrillic layout (physical O = Ctrl+щ).
assert_eq!(
s.on_key(ctrl('щ')),
ChatListAction::SetChildrenExpanded {
id: parent,
expanded: false
}
);
}
/// On a transcript row `Ctrl+O` folds the parent's list, and the selection
/// parks on the parent — never on a row the fold is about to hide.
#[test]
fn ctrl_o_on_a_transcript_folds_the_parent_and_moves_selection() {
let chats = family();
let parent = chats[0].id;
let critic = chats[0].children[0].id;
let mut s = ChatListState::new(chats, Some(critic));
assert_eq!(s.selected_id(), Some(critic));
assert_eq!(
s.on_key(ctrl('o')),
ChatListAction::SetChildrenExpanded {
id: parent,
expanded: false
}
);
assert_eq!(s.selected_id(), Some(parent), "selection has moved up");
}
/// A chat with no transcripts has nothing to fold: the key is a quiet
/// no-op — and the hint for it is not advertised (see the hint test).
#[test]
fn ctrl_o_is_inert_on_a_chat_without_transcripts() {
let chats = collapsed_family();
let recipes = chats[1].id;
let mut s = ChatListState::new(chats, Some(recipes));
assert_eq!(s.on_key(ctrl('o')), ChatListAction::None);
}
/// A search outranks the fold: the user asked where something is, so a
/// matching transcript surfaces under a collapsed parent — and folds away
/// again when the query clears.
#[test]
fn a_search_surfaces_a_matching_transcript_despite_the_fold() {
let mut s = ChatListState::new(collapsed_family(), None);
for c in "Иска".chars() {
s.on_key(key(KeyCode::Char(c)));
}
let rows = s.visible();
let titles: Vec<&str> = rows.iter().map(|r| r.title.as_str()).collect();
assert_eq!(titles, vec!["Планы", "Искатель"]);
assert_eq!(
rows[0].collapsed_children, 0,
"while a search decides what shows, the fold has no mark to make"
);
for _ in 0.."Иска".chars().count() {
s.on_key(key(KeyCode::Backspace));
}
assert_eq!(s.visible().len(), 2, "an empty query folds them away again");
}
/// The same, from the index: a content result naming a transcript's id
/// surfaces it under its collapsed, dimmed parent.
#[test]
fn content_results_surface_a_transcript_despite_the_fold() {
let chats = collapsed_family();
let critic = chats[0].children[0].id;
let mut s = ChatListState::new(chats, None);
s.on_key(ctrl('f'));
s.set_search_results("x".into(), Some(vec![critic]));
let rows = s.visible();
let titles: Vec<&str> = rows.iter().map(|r| r.title.as_str()).collect();
assert_eq!(titles, vec!["Планы", "Критик"]);
assert!(rows[0].dimmed);
}
/// Opening the list while a fold-hidden transcript is the active
/// conversation cannot select its row — there is none — so the selection
/// lands on the parent rather than on the first row.
#[test]
fn opening_on_a_hidden_active_transcript_selects_the_parent() {
let chats = collapsed_family();
let parent = chats[0].id;
let critic = chats[0].children[0].id;
let s = ChatListState::new(chats, Some(critic));
assert_eq!(s.selected_id(), Some(parent));
}
/// The `Ctrl+O` hint carries the direction the key would take (the way
/// `Tab` carries the sort), follows the parent from a transcript row, and
/// is absent where the key would do nothing (docs/lessons.md §4).
#[test]
fn the_fold_hint_names_the_direction_and_skips_childless_chats() {
let loc = crate::shared::i18n::locale(crate::shared::i18n::Lang::Ru);
let chats = collapsed_family();
let (parent, recipes) = (chats[0].id, chats[1].id);
let collapsed = ChatListState::new(chats.clone(), Some(parent));
let t = status_text(&collapsed);
assert!(t.contains("Ctrl+O"), "{t}");
assert!(t.contains(loc.t("ui.chatlist.hk.children_show")), "{t}");
let fam = family();
let critic = fam[0].children[0].id;
let expanded = ChatListState::new(fam, Some(critic));
let t = status_text(&expanded);
assert!(
t.contains(loc.t("ui.chatlist.hk.children_hide")),
"a transcript row names its parent's fold: {t}"
);
let childless = ChatListState::new(chats, Some(recipes));
let t = status_text(&childless);
assert!(
!t.contains("Ctrl+O"),
"an advertised key that does nothing is worse than no hint: {t}"
);
}
}