1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
//! State management for the TUI.
use ralph_proto::{Event, HatId};
use std::collections::HashMap;
use std::time::{Duration, Instant};
// ============================================================================
// TaskSummary - Summary of a single task for TUI display
// ============================================================================
/// Summary of a task for TUI display.
/// Contains only the fields needed for rendering.
#[derive(Debug, Clone, Default)]
pub struct TaskSummary {
/// Task identifier (e.g., "task-1737372000-a1b2").
pub id: String,
/// Task title/description.
pub title: String,
/// Task status (e.g., "open", "closed", "blocked").
pub status: String,
}
impl TaskSummary {
/// Creates a new task summary.
pub fn new(id: impl Into<String>, title: impl Into<String>, status: impl Into<String>) -> Self {
Self {
id: id.into(),
title: title.into(),
status: status.into(),
}
}
}
// ============================================================================
// TaskCounts - Aggregate task statistics for TUI display
// ============================================================================
/// Aggregate task statistics for TUI display.
#[derive(Debug, Clone, Default)]
pub struct TaskCounts {
/// Total number of tasks.
pub total: usize,
/// Number of open tasks.
pub open: usize,
/// Number of closed tasks.
pub closed: usize,
/// Number of ready (unblocked) tasks.
pub ready: usize,
}
impl TaskCounts {
/// Creates new task counts.
pub fn new(total: usize, open: usize, closed: usize, ready: usize) -> Self {
Self {
total,
open,
closed,
ready,
}
}
}
// ============================================================================
// SearchState - Search functionality for TUI content
// ============================================================================
/// Search state for finding and navigating matches in TUI content.
/// Tracks the current query, match positions, and navigation index.
#[derive(Debug, Default)]
pub struct SearchState {
/// Current search query (None when no active search).
pub query: Option<String>,
/// Match positions as (line_index, char_offset) pairs.
pub matches: Vec<(usize, usize)>,
/// Index into matches vector for current match.
pub current_match: usize,
/// Whether search input mode is active (user is typing query).
pub search_mode: bool,
}
impl SearchState {
/// Creates a new empty search state.
pub fn new() -> Self {
Self::default()
}
/// Clears all search state.
pub fn clear(&mut self) {
self.query = None;
self.matches.clear();
self.current_match = 0;
self.search_mode = false;
}
}
/// Whether guidance is being entered for the next or current iteration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GuidanceMode {
/// Guidance for the next iteration (queued, written before build_prompt)
Next,
/// Guidance for the current iteration (written immediately to events.jsonl)
Now,
}
/// Result of attempting to send guidance.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GuidanceResult {
/// Next-iteration guidance was queued successfully.
Queued,
/// Current-iteration guidance was written to events successfully.
Sent,
/// Guidance could not be queued/written.
Failed,
}
/// Observable state derived from loop events.
pub struct TuiState {
/// Which hat will process next event (ID + display name).
pub pending_hat: Option<(HatId, String)>,
/// Backend expected for the next iteration (used when metadata is missing).
pub pending_backend: Option<String>,
/// Current iteration number (0-indexed, display as +1).
pub iteration: u32,
/// Previous iteration number (for detecting changes).
pub prev_iteration: u32,
/// When loop began.
pub loop_started: Option<Instant>,
/// When current iteration began.
pub iteration_started: Option<Instant>,
/// Most recent event topic.
pub last_event: Option<String>,
/// Timestamp of last event.
pub last_event_at: Option<Instant>,
/// Whether to show help overlay.
pub show_help: bool,
/// Whether in scroll mode.
pub in_scroll_mode: bool,
/// Current search query (if in search input mode).
pub search_query: String,
/// Search direction (true = forward, false = backward).
pub search_forward: bool,
/// Maximum iterations from config.
pub max_iterations: Option<u32>,
/// Idle timeout countdown.
pub idle_timeout_remaining: Option<Duration>,
/// Map of event topics to hat display information (for custom hats).
/// Key: event topic (e.g., "review.security")
/// Value: (HatId, display name including emoji)
hat_map: HashMap<String, (HatId, String)>,
// ========================================================================
// Iteration Management (new fields for TUI refactor)
// ========================================================================
/// Content buffers for each iteration.
pub iterations: Vec<IterationBuffer>,
/// Index of the iteration currently being viewed (0-indexed).
pub current_view: usize,
/// Whether to automatically follow the latest iteration.
pub following_latest: bool,
/// Alert about a new iteration (shown when viewing history and new iteration arrives).
/// Contains the iteration number to alert about. Cleared when navigating to latest.
pub new_iteration_alert: Option<usize>,
// ========================================================================
// Search State
// ========================================================================
/// Search state for finding and navigating matches in iteration content.
pub search_state: SearchState,
// ========================================================================
// Completion State
// ========================================================================
/// Whether the loop has completed (received loop.terminate event).
pub loop_completed: bool,
/// Frozen elapsed time when loop completed (timer stops at this value).
pub final_iteration_elapsed: Option<Duration>,
/// Frozen total elapsed time when loop completed (footer timer stops).
pub final_loop_elapsed: Option<Duration>,
// ========================================================================
// Task Tracking State
// ========================================================================
/// Aggregate task counts for display in TUI widgets.
pub task_counts: TaskCounts,
/// Currently active task (if any) for display in TUI widgets.
pub active_task: Option<TaskSummary>,
// ========================================================================
// Guidance State
// ========================================================================
/// Active guidance input mode (None when not entering guidance).
pub guidance_mode: Option<GuidanceMode>,
/// Text being typed in guidance input.
pub guidance_input: String,
/// Queue of guidance messages for the next iteration (drained by loop_runner).
pub guidance_next_queue: Arc<Mutex<Vec<String>>>,
/// Path to events.jsonl for writing "now" guidance directly.
pub events_path: Option<std::path::PathBuf>,
/// Brief flash message after attempting to send guidance.
/// (mode, result, when)
pub guidance_flash: Option<(GuidanceMode, GuidanceResult, Instant)>,
// ========================================================================
// Subprocess Error State
// ========================================================================
/// Error message set when subprocess exits before sending any RPC events.
/// When set, the TUI displays an error state instead of empty content.
pub subprocess_error: Option<String>,
// ========================================================================
// RPC Text Accumulation State
// ========================================================================
/// Buffer for accumulating streaming text deltas received via RPC.
/// Text is rendered as a group when frozen (on tool call, error, or iteration end)
/// rather than rendering each small delta independently.
pub rpc_text_buffer: String,
/// Number of lines in the current iteration buffer that belong to the
/// current (unfrozen) text. When new text arrives, these lines are
/// replaced with a fresh render of the full accumulated text.
pub rpc_text_line_count: usize,
}
impl TuiState {
/// Creates empty state. Timer starts immediately at creation.
pub fn new() -> Self {
Self {
pending_hat: None,
pending_backend: None,
iteration: 0,
prev_iteration: 0,
loop_started: Some(Instant::now()),
iteration_started: None,
last_event: None,
last_event_at: None,
show_help: false,
in_scroll_mode: false,
search_query: String::new(),
search_forward: true,
max_iterations: None,
idle_timeout_remaining: None,
hat_map: HashMap::new(),
// Iteration management
iterations: Vec::new(),
current_view: 0,
following_latest: true,
new_iteration_alert: None,
// Search state
search_state: SearchState::new(),
// Completion state
loop_completed: false,
final_iteration_elapsed: None,
final_loop_elapsed: None,
// Task tracking state
task_counts: TaskCounts::default(),
active_task: None,
// Guidance state
guidance_mode: None,
guidance_input: String::new(),
guidance_next_queue: Arc::new(Mutex::new(Vec::new())),
events_path: None,
guidance_flash: None,
// Subprocess error state
subprocess_error: None,
// RPC text accumulation state
rpc_text_buffer: String::new(),
rpc_text_line_count: 0,
}
}
/// Creates state with a custom hat map for dynamic topic-to-hat resolution.
/// Timer starts immediately at creation.
pub fn with_hat_map(hat_map: HashMap<String, (HatId, String)>) -> Self {
Self {
pending_hat: None,
pending_backend: None,
iteration: 0,
prev_iteration: 0,
loop_started: Some(Instant::now()),
iteration_started: None,
last_event: None,
last_event_at: None,
show_help: false,
in_scroll_mode: false,
search_query: String::new(),
search_forward: true,
max_iterations: None,
idle_timeout_remaining: None,
hat_map,
// Iteration management
iterations: Vec::new(),
current_view: 0,
following_latest: true,
new_iteration_alert: None,
// Search state
search_state: SearchState::new(),
// Completion state
loop_completed: false,
final_iteration_elapsed: None,
final_loop_elapsed: None,
// Task tracking state
task_counts: TaskCounts::default(),
active_task: None,
// Guidance state
guidance_mode: None,
guidance_input: String::new(),
guidance_next_queue: Arc::new(Mutex::new(Vec::new())),
events_path: None,
guidance_flash: None,
// Subprocess error state
subprocess_error: None,
// RPC text accumulation state
rpc_text_buffer: String::new(),
rpc_text_line_count: 0,
}
}
/// Updates state based on event topic.
pub fn update(&mut self, event: &Event) {
let now = Instant::now();
let topic = event.topic.as_str();
self.last_event = Some(topic.to_string());
self.last_event_at = Some(now);
let custom_hat = self.hat_map.get(topic).cloned();
if let Some((hat_id, hat_display)) = custom_hat.clone() {
self.pending_hat = Some((hat_id, hat_display));
// Handle iteration timing for custom hats
if topic.starts_with("build.") {
self.iteration_started = Some(now);
}
}
// Fall back to hardcoded mappings for backward compatibility
match topic {
"task.start" => {
// Save state we want to preserve across reset
let saved_hat_map = std::mem::take(&mut self.hat_map);
let saved_loop_started = self.loop_started; // Preserve timer from TUI init
let saved_max_iterations = self.max_iterations;
// Preserve iteration buffers so TUI history survives across task restarts
let saved_iterations = std::mem::take(&mut self.iterations);
let saved_current_view = self.current_view;
let saved_following_latest = self.following_latest;
let saved_new_iteration_alert = self.new_iteration_alert.take();
let saved_pending_backend = self.pending_backend.clone();
let saved_guidance_next_queue = Arc::clone(&self.guidance_next_queue);
let saved_events_path = self.events_path.clone();
*self = Self::new();
self.hat_map = saved_hat_map;
self.loop_started = saved_loop_started; // Keep original timer
self.max_iterations = saved_max_iterations;
self.iterations = saved_iterations;
self.current_view = saved_current_view;
self.following_latest = saved_following_latest;
self.new_iteration_alert = saved_new_iteration_alert;
self.pending_backend = saved_pending_backend;
self.guidance_next_queue = saved_guidance_next_queue;
self.events_path = saved_events_path;
if let Some((hat_id, hat_display)) = custom_hat {
self.pending_hat = Some((hat_id, hat_display));
} else {
self.pending_hat = Some((HatId::new("planner"), "📋Planner".to_string()));
}
self.last_event = Some(topic.to_string());
self.last_event_at = Some(now);
}
"task.resume" => {
// Don't reset timer on resume - keep counting from TUI init
if custom_hat.is_none() {
self.pending_hat = Some((HatId::new("planner"), "📋Planner".to_string()));
}
}
"build.task" => {
if custom_hat.is_none() {
self.pending_hat = Some((HatId::new("builder"), "🔨Builder".to_string()));
}
// Resume the loop timer if a new iteration starts after a freeze.
self.final_loop_elapsed = None;
self.iteration_started = Some(now);
}
"build.done" => {
if custom_hat.is_none() {
self.pending_hat = Some((HatId::new("planner"), "📋Planner".to_string()));
}
self.prev_iteration = self.iteration;
self.iteration += 1;
self.finish_latest_iteration();
self.freeze_loop_elapsed();
}
"build.blocked" => {
if custom_hat.is_none() {
self.pending_hat = Some((HatId::new("planner"), "📋Planner".to_string()));
}
self.finish_latest_iteration();
self.freeze_loop_elapsed();
}
"loop.terminate" => {
self.pending_hat = None;
self.loop_completed = true;
// Freeze the iteration timer at its current value
self.final_iteration_elapsed = self.iteration_started.map(|start| start.elapsed());
// Freeze the total loop timer for the footer display
self.freeze_loop_elapsed();
self.finish_latest_iteration();
}
_ => {
// Unknown topic - don't change pending_hat
}
}
}
/// Returns formatted hat display (emoji + name).
pub fn get_pending_hat_display(&self) -> String {
self.pending_hat
.as_ref()
.map_or_else(|| "—".to_string(), |(_, display)| display.clone())
}
/// Time since loop started.
pub fn get_loop_elapsed(&self) -> Option<Duration> {
if let Some(final_elapsed) = self.final_loop_elapsed {
return Some(final_elapsed);
}
self.loop_started.map(|start| start.elapsed())
}
/// Time since iteration started, or frozen value if loop completed.
pub fn get_iteration_elapsed(&self) -> Option<Duration> {
if let Some(buffer) = self.current_iteration() {
if let Some(elapsed) = buffer.elapsed {
return Some(elapsed);
}
if let Some(started_at) = buffer.started_at {
return Some(started_at.elapsed());
}
}
if let Some(final_elapsed) = self.final_iteration_elapsed {
return Some(final_elapsed);
}
self.iteration_started.map(|start| start.elapsed())
}
/// True if event received in last 2 seconds.
pub fn is_active(&self) -> bool {
self.last_event_at
.is_some_and(|t| t.elapsed() < Duration::from_secs(2))
}
/// True if iteration changed since last check.
pub fn iteration_changed(&self) -> bool {
self.iteration != self.prev_iteration
}
// ========================================================================
// Task Tracking Methods
// ========================================================================
/// Returns a reference to the current task counts.
pub fn get_task_counts(&self) -> &TaskCounts {
&self.task_counts
}
/// Returns a reference to the active task, if any.
pub fn get_active_task(&self) -> Option<&TaskSummary> {
self.active_task.as_ref()
}
/// Updates the task counts.
pub fn set_task_counts(&mut self, counts: TaskCounts) {
self.task_counts = counts;
}
/// Sets the active task.
pub fn set_active_task(&mut self, task: Option<TaskSummary>) {
self.active_task = task;
}
/// Returns true if there are any open tasks.
pub fn has_open_tasks(&self) -> bool {
self.task_counts.open > 0
}
/// Returns a formatted string for task progress display (e.g., "3/5 tasks").
pub fn get_task_progress_display(&self) -> String {
if self.task_counts.total == 0 {
"No tasks".to_string()
} else {
format!(
"{}/{} tasks",
self.task_counts.closed, self.task_counts.total
)
}
}
// ========================================================================
// Iteration Management Methods
// ========================================================================
/// Starts a new iteration, creating a new IterationBuffer.
/// If following_latest is true, current_view is updated to the new iteration.
/// If not following, sets the new_iteration_alert to notify the user.
pub fn start_new_iteration(&mut self) {
self.start_new_iteration_with_metadata(None, None);
}
/// Starts a new iteration with optional metadata for hat and backend display.
pub fn start_new_iteration_with_metadata(
&mut self,
hat_display: Option<String>,
backend: Option<String>,
) {
// Reset text accumulation buffer for the new iteration
self.rpc_text_buffer.clear();
self.rpc_text_line_count = 0;
let hat_display = hat_display.or_else(|| {
self.pending_hat
.as_ref()
.map(|(_, display)| display.clone())
});
let backend = backend.or_else(|| self.pending_backend.clone());
let number = (self.iterations.len() + 1) as u32;
let mut buffer = IterationBuffer::new(number);
buffer.hat_display = hat_display;
buffer.backend = backend;
buffer.started_at = Some(Instant::now());
if buffer.backend.is_some() {
self.pending_backend = buffer.backend.clone();
}
self.iterations.push(buffer);
// Auto-follow if enabled
if self.following_latest {
self.current_view = self.iterations.len().saturating_sub(1);
} else {
// Alert user about new iteration when reviewing history
self.new_iteration_alert = Some(number as usize);
}
}
/// Finalizes the latest iteration's elapsed time if it isn't already set.
pub fn finish_latest_iteration(&mut self) {
let Some(buffer) = self.iterations.last_mut() else {
return;
};
if buffer.elapsed.is_some() {
return;
}
if let Some(started_at) = buffer.started_at {
buffer.elapsed = Some(started_at.elapsed());
}
}
/// Freeze total loop elapsed time for the footer if it is still ticking.
fn freeze_loop_elapsed(&mut self) {
if self.final_loop_elapsed.is_some() {
return;
}
self.final_loop_elapsed = self.loop_started.map(|start| start.elapsed());
}
/// Returns the hat display for the currently viewed iteration, if available.
pub fn current_iteration_hat_display(&self) -> Option<&str> {
self.current_iteration()
.and_then(|buffer| buffer.hat_display.as_deref())
}
/// Returns the backend display for the currently viewed iteration, if available.
pub fn current_iteration_backend(&self) -> Option<&str> {
self.current_iteration()
.and_then(|buffer| buffer.backend.as_deref())
}
/// Returns a reference to the currently viewed iteration buffer.
pub fn current_iteration(&self) -> Option<&IterationBuffer> {
self.iterations.get(self.current_view)
}
/// Returns a mutable reference to the currently viewed iteration buffer.
pub fn current_iteration_mut(&mut self) -> Option<&mut IterationBuffer> {
self.iterations.get_mut(self.current_view)
}
/// Returns a shared handle to the current iteration's lines buffer.
///
/// This allows stream handlers to write directly to the buffer,
/// enabling real-time streaming to the TUI during execution.
pub fn current_iteration_lines_handle(
&self,
) -> Option<std::sync::Arc<std::sync::Mutex<Vec<Line<'static>>>>> {
self.iterations
.get(self.current_view)
.map(|buffer| buffer.lines_handle())
}
/// Returns a shared handle to the latest iteration's lines buffer.
///
/// This should be used when writing output from the currently executing
/// iteration, regardless of which iteration the user is viewing.
/// This prevents output from being written to the wrong iteration when
/// the user is reviewing an older iteration.
pub fn latest_iteration_lines_handle(
&self,
) -> Option<std::sync::Arc<std::sync::Mutex<Vec<Line<'static>>>>> {
self.iterations.last().map(|buffer| buffer.lines_handle())
}
/// Navigates to the next iteration (if not at the last one).
/// If reaching the last iteration, re-enables following_latest and clears alerts.
pub fn navigate_next(&mut self) {
if self.iterations.is_empty() {
return;
}
let max_index = self.iterations.len().saturating_sub(1);
if self.current_view < max_index {
self.current_view += 1;
// Re-enable following when reaching the latest
if self.current_view == max_index {
self.following_latest = true;
self.new_iteration_alert = None;
}
}
}
/// Navigates to the previous iteration (if not at the first one).
/// Disables following_latest when navigating backwards.
pub fn navigate_prev(&mut self) {
if self.current_view > 0 {
self.current_view -= 1;
self.following_latest = false;
}
}
/// Returns the total number of iterations.
pub fn total_iterations(&self) -> usize {
self.iterations.len()
}
// ========================================================================
// Search Methods
// ========================================================================
/// Searches for the given query in the current iteration's content.
/// Populates matches with (line_index, char_offset) pairs.
/// Search is case-insensitive.
pub fn search(&mut self, query: &str) {
self.search_state.query = Some(query.to_string());
self.search_state.matches.clear();
self.search_state.current_match = 0;
// Check if we have an iteration to search
if self.iterations.get(self.current_view).is_none() {
return;
}
let query_lower = query.to_lowercase();
// Collect matches first (avoid borrow conflicts)
let matches: Vec<(usize, usize)> = self
.iterations
.get(self.current_view)
.and_then(|buffer| {
let lines = buffer.lines.lock().ok()?;
let mut found = Vec::new();
for (line_idx, line) in lines.iter().enumerate() {
// Get the text content of the line
let line_text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
let line_lower = line_text.to_lowercase();
// Find all occurrences in this line
let mut search_start = 0;
while let Some(pos) = line_lower[search_start..].find(&query_lower) {
let char_offset = search_start + pos;
found.push((line_idx, char_offset));
search_start = char_offset + query_lower.len();
}
}
Some(found)
})
.unwrap_or_default();
self.search_state.matches = matches;
// Jump to first match if any exist
if !self.search_state.matches.is_empty() {
self.jump_to_current_match();
}
}
/// Navigates to the next match, cycling back to the first if at the end.
pub fn next_match(&mut self) {
if self.search_state.matches.is_empty() {
return;
}
self.search_state.current_match =
(self.search_state.current_match + 1) % self.search_state.matches.len();
self.jump_to_current_match();
}
/// Navigates to the previous match, cycling to the last if at the beginning.
pub fn prev_match(&mut self) {
if self.search_state.matches.is_empty() {
return;
}
if self.search_state.current_match == 0 {
self.search_state.current_match = self.search_state.matches.len() - 1;
} else {
self.search_state.current_match -= 1;
}
self.jump_to_current_match();
}
/// Clears the search state.
pub fn clear_search(&mut self) {
self.search_state.clear();
}
/// Jumps to the current match by adjusting scroll_offset to show the match line.
fn jump_to_current_match(&mut self) {
if self.search_state.matches.is_empty() {
return;
}
let (line_idx, _) = self.search_state.matches[self.search_state.current_match];
// Adjust scroll to show the match line
// Use a default viewport height for calculation (will be overridden by actual render)
let viewport_height = 20;
if let Some(buffer) = self.current_iteration_mut() {
// If the match line is above the current view, scroll up to it
if line_idx < buffer.scroll_offset {
buffer.scroll_offset = line_idx;
}
// If the match line is below the current view, scroll down to show it
else if line_idx >= buffer.scroll_offset + viewport_height {
buffer.scroll_offset = line_idx.saturating_sub(viewport_height / 2);
}
}
}
// ========================================================================
// Guidance Methods
// ========================================================================
/// Enters guidance input mode.
pub fn start_guidance(&mut self, mode: GuidanceMode) {
self.guidance_mode = Some(mode);
self.guidance_input.clear();
self.guidance_flash = None;
}
/// Cancels guidance input without sending.
pub fn cancel_guidance(&mut self) {
self.guidance_mode = None;
self.guidance_input.clear();
}
/// Sends the current guidance input.
///
/// For `GuidanceMode::Next`, pushes to the shared queue (drained by loop_runner).
/// For `GuidanceMode::Now`, writes directly to events.jsonl.
///
/// Returns true if guidance was sent successfully.
pub fn send_guidance(&mut self) -> bool {
let input = self.guidance_input.trim().to_string();
if input.is_empty() {
self.cancel_guidance();
return false;
}
let mode = match self.guidance_mode {
Some(m) => m,
None => return false,
};
let (ok, result) = match mode {
GuidanceMode::Next => {
if let Ok(mut queue) = self.guidance_next_queue.lock() {
queue.push(input);
(true, GuidanceResult::Queued)
} else {
(false, GuidanceResult::Failed)
}
}
GuidanceMode::Now => {
let ok = self.write_guidance_event(&input);
if ok {
(true, GuidanceResult::Sent)
} else {
(false, GuidanceResult::Failed)
}
}
};
self.guidance_flash = Some((mode, result, Instant::now()));
self.guidance_mode = None;
self.guidance_input.clear();
ok
}
/// Writes a human.guidance event directly to events.jsonl.
fn write_guidance_event(&self, message: &str) -> bool {
let Some(ref path) = self.events_path else {
return false;
};
let timestamp = chrono::Utc::now().to_rfc3339();
let event = serde_json::json!({
"topic": "human.guidance",
"payload": message,
"ts": timestamp,
});
let line = match serde_json::to_string(&event) {
Ok(l) => l,
Err(_) => return false,
};
use std::io::Write;
let mut file = match std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(path)
{
Ok(f) => f,
Err(_) => return false,
};
file.write_all(line.as_bytes()).is_ok() && file.write_all(b"\n").is_ok()
}
/// Returns true if guidance input is currently active.
pub fn is_guidance_active(&self) -> bool {
self.guidance_mode.is_some()
}
/// Clears flash message if it has expired.
pub fn clear_expired_guidance_flash(&mut self) {
if let Some((_, _, when)) = self.guidance_flash
&& when.elapsed() >= Duration::from_secs(2)
{
self.guidance_flash = None;
}
}
/// Returns active guidance flash (mode + result) if still within display window (2 seconds).
pub fn active_guidance_flash(&self) -> Option<(GuidanceMode, GuidanceResult)> {
self.guidance_flash.and_then(|(mode, result, when)| {
if when.elapsed() < Duration::from_secs(2) {
Some((mode, result))
} else {
None
}
})
}
}
impl Default for TuiState {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// IterationBuffer - Content storage for a single iteration
// ============================================================================
use ratatui::text::Line;
use std::sync::{Arc, Mutex};
/// Stores formatted output content for a single Ralph iteration.
/// Each iteration has its own buffer with independent scroll state.
///
/// The `lines` field is wrapped in `Arc<Mutex<>>` to allow sharing
/// with stream handlers during execution, enabling real-time streaming
/// to the TUI instead of batch transfer after execution completes.
pub struct IterationBuffer {
/// Iteration number (1-indexed for display)
pub number: u32,
/// Formatted lines of output (shared for streaming)
pub lines: Arc<Mutex<Vec<Line<'static>>>>,
/// Scroll position within this buffer
pub scroll_offset: usize,
/// Whether to auto-scroll to bottom as new content arrives.
/// Starts true, becomes false when user scrolls up, restored when user
/// scrolls to bottom (G key) or manually scrolls down to reach bottom.
pub following_bottom: bool,
/// Hat display name (emoji + name) for this iteration.
pub hat_display: Option<String>,
/// Backend used for this iteration (e.g., "claude", "kiro").
pub backend: Option<String>,
/// When this iteration started (for elapsed time calculation).
pub started_at: Option<Instant>,
/// Frozen elapsed duration for this iteration (set when completed).
pub elapsed: Option<Duration>,
}
impl IterationBuffer {
/// Creates a new buffer for the given iteration number.
pub fn new(number: u32) -> Self {
Self {
number,
lines: Arc::new(Mutex::new(Vec::new())),
scroll_offset: 0,
following_bottom: true, // Start following bottom for auto-scroll
hat_display: None,
backend: None,
started_at: None,
elapsed: None,
}
}
/// Returns a shared handle to the lines buffer for streaming.
///
/// This allows stream handlers to write directly to the buffer,
/// enabling real-time streaming to the TUI.
pub fn lines_handle(&self) -> Arc<Mutex<Vec<Line<'static>>>> {
Arc::clone(&self.lines)
}
/// Appends a line to the buffer.
pub fn append_line(&mut self, line: Line<'static>) {
if let Ok(mut lines) = self.lines.lock() {
lines.push(line);
}
}
/// Returns the total number of lines in the buffer.
pub fn line_count(&self) -> usize {
self.lines.lock().map(|l| l.len()).unwrap_or(0)
}
/// Returns a clone of the visible lines based on scroll offset and viewport height.
///
/// Note: Returns owned Vec instead of slice due to interior mutability.
pub fn visible_lines(&self, viewport_height: usize) -> Vec<Line<'static>> {
let Ok(lines) = self.lines.lock() else {
return Vec::new();
};
if lines.is_empty() {
return Vec::new();
}
let start = self.scroll_offset.min(lines.len());
let end = (start + viewport_height).min(lines.len());
lines[start..end].to_vec()
}
/// Scrolls up by one line.
/// Disables auto-scroll since user is moving away from bottom.
pub fn scroll_up(&mut self) {
self.scroll_offset = self.scroll_offset.saturating_sub(1);
self.following_bottom = false;
}
/// Scrolls down by one line, respecting the viewport bounds.
/// Re-enables auto-scroll if user reaches the bottom.
pub fn scroll_down(&mut self, viewport_height: usize) {
let max_scroll = self.max_scroll_offset(viewport_height);
if self.scroll_offset < max_scroll {
self.scroll_offset += 1;
}
// Re-enable following if user scrolled to or past the bottom
if self.scroll_offset >= max_scroll {
self.following_bottom = true;
}
}
/// Scrolls to the top of the buffer.
/// Disables auto-scroll since user is moving away from bottom.
pub fn scroll_top(&mut self) {
self.scroll_offset = 0;
self.following_bottom = false;
}
/// Scrolls to the bottom of the buffer.
/// Re-enables auto-scroll since user explicitly went to bottom.
pub fn scroll_bottom(&mut self, viewport_height: usize) {
self.scroll_offset = self.max_scroll_offset(viewport_height);
self.following_bottom = true;
}
/// Calculates the maximum scroll offset for the given viewport height.
fn max_scroll_offset(&self, viewport_height: usize) -> usize {
self.lines
.lock()
.map(|l| l.len().saturating_sub(viewport_height))
.unwrap_or(0)
}
}
#[cfg(test)]
mod tests {
use super::*;
// ========================================================================
// IterationBuffer Tests
// ========================================================================
mod iteration_buffer {
use super::*;
use ratatui::text::Line;
#[test]
fn new_creates_buffer_with_correct_initial_state() {
let buffer = IterationBuffer::new(1);
assert_eq!(buffer.number, 1);
assert_eq!(buffer.line_count(), 0);
assert_eq!(buffer.scroll_offset, 0);
}
#[test]
fn append_line_adds_lines_in_order() {
let mut buffer = IterationBuffer::new(1);
buffer.append_line(Line::from("first"));
buffer.append_line(Line::from("second"));
buffer.append_line(Line::from("third"));
assert_eq!(buffer.line_count(), 3);
// Verify order by checking raw content
let lines = buffer.lines.lock().unwrap();
assert_eq!(lines[0].spans[0].content, "first");
assert_eq!(lines[1].spans[0].content, "second");
assert_eq!(lines[2].spans[0].content, "third");
}
#[test]
fn line_count_returns_correct_count() {
let mut buffer = IterationBuffer::new(1);
assert_eq!(buffer.line_count(), 0);
for i in 0..10 {
buffer.append_line(Line::from(format!("line {}", i)));
}
assert_eq!(buffer.line_count(), 10);
}
#[test]
fn visible_lines_returns_correct_slice_without_scroll() {
let mut buffer = IterationBuffer::new(1);
for i in 0..10 {
buffer.append_line(Line::from(format!("line {}", i)));
}
let visible = buffer.visible_lines(5);
assert_eq!(visible.len(), 5);
// Should be lines 0-4
assert_eq!(visible[0].spans[0].content, "line 0");
assert_eq!(visible[4].spans[0].content, "line 4");
}
#[test]
fn visible_lines_returns_correct_slice_with_scroll() {
let mut buffer = IterationBuffer::new(1);
for i in 0..10 {
buffer.append_line(Line::from(format!("line {}", i)));
}
buffer.scroll_offset = 3;
let visible = buffer.visible_lines(5);
assert_eq!(visible.len(), 5);
// Should be lines 3-7
assert_eq!(visible[0].spans[0].content, "line 3");
assert_eq!(visible[4].spans[0].content, "line 7");
}
#[test]
fn visible_lines_handles_viewport_larger_than_content() {
let mut buffer = IterationBuffer::new(1);
for i in 0..3 {
buffer.append_line(Line::from(format!("line {}", i)));
}
let visible = buffer.visible_lines(10);
assert_eq!(visible.len(), 3); // Only 3 lines exist
}
#[test]
fn visible_lines_handles_empty_buffer() {
let buffer = IterationBuffer::new(1);
let visible = buffer.visible_lines(5);
assert!(visible.is_empty());
}
#[test]
fn scroll_down_increases_offset() {
let mut buffer = IterationBuffer::new(1);
for i in 0..10 {
buffer.append_line(Line::from(format!("line {}", i)));
}
assert_eq!(buffer.scroll_offset, 0);
buffer.scroll_down(5); // viewport height 5
assert_eq!(buffer.scroll_offset, 1);
buffer.scroll_down(5);
assert_eq!(buffer.scroll_offset, 2);
}
#[test]
fn scroll_up_decreases_offset() {
let mut buffer = IterationBuffer::new(1);
for _ in 0..10 {
buffer.append_line(Line::from("line"));
}
buffer.scroll_offset = 5;
buffer.scroll_up();
assert_eq!(buffer.scroll_offset, 4);
buffer.scroll_up();
assert_eq!(buffer.scroll_offset, 3);
}
#[test]
fn scroll_up_does_not_underflow() {
let mut buffer = IterationBuffer::new(1);
buffer.append_line(Line::from("line"));
buffer.scroll_offset = 0;
buffer.scroll_up();
assert_eq!(buffer.scroll_offset, 0); // Should stay at 0
}
#[test]
fn scroll_down_does_not_overflow() {
let mut buffer = IterationBuffer::new(1);
for _ in 0..10 {
buffer.append_line(Line::from("line"));
}
// With 10 lines and viewport 5, max scroll is 5 (shows lines 5-9)
buffer.scroll_offset = 5;
buffer.scroll_down(5);
assert_eq!(buffer.scroll_offset, 5); // Should stay at max
}
#[test]
fn scroll_top_resets_to_zero() {
let mut buffer = IterationBuffer::new(1);
for _ in 0..10 {
buffer.append_line(Line::from("line"));
}
buffer.scroll_offset = 5;
buffer.scroll_top();
assert_eq!(buffer.scroll_offset, 0);
}
#[test]
fn scroll_bottom_sets_to_max() {
let mut buffer = IterationBuffer::new(1);
for _ in 0..10 {
buffer.append_line(Line::from("line"));
}
buffer.scroll_bottom(5); // viewport height 5
assert_eq!(buffer.scroll_offset, 5); // max = 10 - 5 = 5
}
#[test]
fn scroll_bottom_handles_small_content() {
let mut buffer = IterationBuffer::new(1);
for _ in 0..3 {
buffer.append_line(Line::from("line"));
}
buffer.scroll_bottom(5); // viewport larger than content
assert_eq!(buffer.scroll_offset, 0); // Can't scroll
}
#[test]
fn scroll_down_handles_empty_buffer() {
let mut buffer = IterationBuffer::new(1);
buffer.scroll_down(5);
assert_eq!(buffer.scroll_offset, 0);
}
// =====================================================================
// Auto-scroll (following_bottom) Tests
// =====================================================================
#[test]
fn following_bottom_is_true_initially() {
let buffer = IterationBuffer::new(1);
assert!(
buffer.following_bottom,
"New buffer should start with following_bottom = true"
);
}
#[test]
fn scroll_up_disables_following_bottom() {
let mut buffer = IterationBuffer::new(1);
for _ in 0..10 {
buffer.append_line(Line::from("line"));
}
buffer.scroll_offset = 5;
assert!(buffer.following_bottom);
buffer.scroll_up();
assert!(
!buffer.following_bottom,
"scroll_up should disable following_bottom"
);
}
#[test]
fn scroll_top_disables_following_bottom() {
let mut buffer = IterationBuffer::new(1);
for _ in 0..10 {
buffer.append_line(Line::from("line"));
}
assert!(buffer.following_bottom);
buffer.scroll_top();
assert!(
!buffer.following_bottom,
"scroll_top should disable following_bottom"
);
}
#[test]
fn scroll_bottom_enables_following_bottom() {
let mut buffer = IterationBuffer::new(1);
for _ in 0..10 {
buffer.append_line(Line::from("line"));
}
buffer.following_bottom = false;
buffer.scroll_bottom(5);
assert!(
buffer.following_bottom,
"scroll_bottom should enable following_bottom"
);
}
#[test]
fn scroll_down_to_bottom_enables_following_bottom() {
let mut buffer = IterationBuffer::new(1);
for _ in 0..10 {
buffer.append_line(Line::from("line"));
}
buffer.scroll_offset = 4; // One away from max (5 with viewport 5)
buffer.following_bottom = false;
buffer.scroll_down(5); // Now at max (5)
assert!(
buffer.following_bottom,
"scroll_down to bottom should enable following_bottom"
);
}
#[test]
fn scroll_down_not_at_bottom_keeps_following_false() {
let mut buffer = IterationBuffer::new(1);
for _ in 0..10 {
buffer.append_line(Line::from("line"));
}
buffer.scroll_offset = 0;
buffer.following_bottom = false;
buffer.scroll_down(5); // Now at 1, max is 5
assert!(
!buffer.following_bottom,
"scroll_down not reaching bottom should keep following_bottom false"
);
}
#[test]
fn autoscroll_scenario_content_grows_past_viewport() {
// This tests the core bug fix: content growing from small to large
let mut buffer = IterationBuffer::new(1);
// Start with small content that fits in viewport
for _ in 0..5 {
buffer.append_line(Line::from("line"));
}
// Simulate initial state: following_bottom = true, scroll_offset = 0
let viewport = 20;
assert!(buffer.following_bottom);
assert_eq!(buffer.scroll_offset, 0);
// Simulate auto-scroll logic: if following_bottom, scroll to bottom
if buffer.following_bottom {
let max_scroll = buffer.line_count().saturating_sub(viewport);
buffer.scroll_offset = max_scroll;
}
assert_eq!(buffer.scroll_offset, 0); // max_scroll is 0 when content < viewport
// Content grows past viewport size
for _ in 0..25 {
buffer.append_line(Line::from("more content"));
}
// Now we have 30 lines, viewport is 20, max_scroll = 10
// The bug was: scroll_offset = 0, but old logic checked if 0 >= 10-1 (false)
// With following_bottom flag, we just check the flag:
if buffer.following_bottom {
let max_scroll = buffer.line_count().saturating_sub(viewport);
buffer.scroll_offset = max_scroll;
}
// Now scroll_offset should be at the bottom
assert_eq!(
buffer.scroll_offset, 10,
"Auto-scroll should move to bottom when content grows past viewport"
);
}
}
// ========================================================================
// TuiState Tests (existing)
// ========================================================================
#[test]
fn iteration_changed_detects_boundary() {
let mut state = TuiState::new();
assert!(!state.iteration_changed(), "no change at start");
// Simulate build.done event (increments iteration)
let event = Event::new("build.done", "");
state.update(&event);
assert_eq!(state.iteration, 1);
assert_eq!(state.prev_iteration, 0);
assert!(state.iteration_changed(), "should detect iteration change");
}
#[test]
fn iteration_changed_resets_after_check() {
let mut state = TuiState::new();
let event = Event::new("build.done", "");
state.update(&event);
assert!(state.iteration_changed());
// Simulate clearing the flag (app.rs does this by updating prev_iteration)
state.prev_iteration = state.iteration;
assert!(!state.iteration_changed(), "flag should reset");
}
#[test]
fn multiple_iterations_tracked() {
let mut state = TuiState::new();
for i in 1..=3 {
let event = Event::new("build.done", "");
state.update(&event);
assert_eq!(state.iteration, i);
assert!(state.iteration_changed());
state.prev_iteration = state.iteration; // simulate app clearing flag
}
}
#[test]
fn custom_hat_topics_update_pending_hat() {
// Test that custom hat topics (not hardcoded) update pending_hat correctly
use std::collections::HashMap;
// Create a hat map for custom hats
let mut hat_map = HashMap::new();
hat_map.insert(
"review.security".to_string(),
(
HatId::new("security_reviewer"),
"🔒 Security Reviewer".to_string(),
),
);
hat_map.insert(
"review.correctness".to_string(),
(
HatId::new("correctness_reviewer"),
"🎯 Correctness Reviewer".to_string(),
),
);
let mut state = TuiState::with_hat_map(hat_map);
// Publish review.security event
let event = Event::new("review.security", "Review PR #123");
state.update(&event);
// Should update pending_hat to security reviewer
assert_eq!(
state.get_pending_hat_display(),
"🔒 Security Reviewer",
"Should display security reviewer hat for review.security topic"
);
// Publish review.correctness event
let event = Event::new("review.correctness", "Check logic");
state.update(&event);
// Should update to correctness reviewer
assert_eq!(
state.get_pending_hat_display(),
"🎯 Correctness Reviewer",
"Should display correctness reviewer hat for review.correctness topic"
);
}
#[test]
fn unknown_topics_keep_pending_hat_unchanged() {
// Test that unknown topics don't clear pending_hat
let mut state = TuiState::new();
// Set initial hat
state.pending_hat = Some((HatId::new("planner"), "📋Planner".to_string()));
// Publish unknown event
let event = Event::new("unknown.topic", "Some payload");
state.update(&event);
// Should keep the planner hat
assert_eq!(
state.get_pending_hat_display(),
"📋Planner",
"Unknown topics should not clear pending_hat"
);
}
#[test]
fn task_start_preserves_iterations_across_reset() {
// Regression test: task.start used to do *self = Self::new() which wiped
// iteration buffers, causing the header to show "iter 1/0" and losing all
// previous iteration output.
let mut state = TuiState::new();
// Create 3 iterations with content
state.start_new_iteration();
state.start_new_iteration();
state.start_new_iteration();
assert_eq!(state.total_iterations(), 3);
assert_eq!(state.current_view, 2); // following latest
// Navigate back to review history
state.navigate_prev();
assert_eq!(state.current_view, 1);
assert!(!state.following_latest);
// When task.start fires (e.g., new task planning session)
let event = Event::new("task.start", "New task");
state.update(&event);
// Then iterations are preserved
assert_eq!(
state.total_iterations(),
3,
"task.start should not wipe iteration buffers"
);
assert_eq!(
state.current_view, 1,
"task.start should preserve current_view position"
);
assert!(
!state.following_latest,
"task.start should preserve following_latest state"
);
}
#[test]
fn loop_terminate_freezes_iteration_timer() {
// Given a running iteration with elapsed time
let mut state = TuiState::new();
let start_event = Event::new("build.task", "");
state.update(&start_event);
// Verify timer is running
assert!(state.iteration_started.is_some());
let elapsed_before = state.get_iteration_elapsed().unwrap();
assert!(elapsed_before.as_nanos() > 0);
// When loop.terminate is received
let terminate_event = Event::new("loop.terminate", "");
state.update(&terminate_event);
// Then the timer is frozen
assert!(state.loop_completed);
assert!(state.final_iteration_elapsed.is_some());
// The elapsed time should be frozen (not increasing)
let frozen_elapsed = state.get_iteration_elapsed().unwrap();
std::thread::sleep(std::time::Duration::from_millis(10));
let elapsed_after_sleep = state.get_iteration_elapsed().unwrap();
assert_eq!(
frozen_elapsed, elapsed_after_sleep,
"Timer should be frozen after loop.terminate"
);
}
#[test]
fn loop_terminate_freezes_total_timer() {
let mut state = TuiState::new();
state.loop_started = Some(
std::time::Instant::now()
.checked_sub(std::time::Duration::from_secs(90))
.unwrap(),
);
let before = state.get_loop_elapsed().unwrap();
assert!(before.as_secs() >= 90);
let terminate_event = Event::new("loop.terminate", "");
state.update(&terminate_event);
let frozen = state.get_loop_elapsed().unwrap();
std::thread::sleep(std::time::Duration::from_millis(10));
let after = state.get_loop_elapsed().unwrap();
assert_eq!(
frozen, after,
"Loop elapsed time should be frozen after termination"
);
}
#[test]
fn build_done_freezes_total_timer() {
let mut state = TuiState::new();
state.loop_started = Some(
std::time::Instant::now()
.checked_sub(std::time::Duration::from_secs(42))
.unwrap(),
);
let before = state.get_loop_elapsed().unwrap();
assert!(before.as_secs() >= 42);
let done_event = Event::new("build.done", "");
state.update(&done_event);
let frozen = state.get_loop_elapsed().unwrap();
std::thread::sleep(std::time::Duration::from_millis(10));
let after = state.get_loop_elapsed().unwrap();
assert_eq!(
frozen, after,
"Loop elapsed time should be frozen after build.done"
);
}
#[test]
fn build_blocked_freezes_total_timer() {
let mut state = TuiState::new();
state.loop_started = Some(
std::time::Instant::now()
.checked_sub(std::time::Duration::from_secs(7))
.unwrap(),
);
let before = state.get_loop_elapsed().unwrap();
assert!(before.as_secs() >= 7);
let blocked_event = Event::new("build.blocked", "");
state.update(&blocked_event);
let frozen = state.get_loop_elapsed().unwrap();
std::thread::sleep(std::time::Duration::from_millis(10));
let after = state.get_loop_elapsed().unwrap();
assert_eq!(
frozen, after,
"Loop elapsed time should be frozen after build.blocked"
);
}
// ========================================================================
// TuiState Iteration Management Tests
// ========================================================================
mod tui_state_iterations {
use super::*;
#[test]
fn start_new_iteration_creates_first_buffer() {
// Given TuiState with 0 iterations
let mut state = TuiState::new();
assert_eq!(state.total_iterations(), 0);
// When start_new_iteration() is called
state.start_new_iteration();
// Then iterations.len() == 1 and new IterationBuffer exists
assert_eq!(state.total_iterations(), 1);
assert_eq!(state.iterations[0].number, 1);
}
#[test]
fn start_new_iteration_creates_subsequent_buffers() {
let mut state = TuiState::new();
state.start_new_iteration();
state.start_new_iteration();
state.start_new_iteration();
assert_eq!(state.total_iterations(), 3);
assert_eq!(state.iterations[0].number, 1);
assert_eq!(state.iterations[1].number, 2);
assert_eq!(state.iterations[2].number, 3);
}
#[test]
fn current_iteration_returns_correct_buffer() {
// Given TuiState with 3 iterations and current_view = 1
let mut state = TuiState::new();
state.start_new_iteration();
state.start_new_iteration();
state.start_new_iteration();
state.current_view = 1;
// When current_iteration() is called
let current = state.current_iteration();
// Then the buffer at index 1 is returned (iteration number 2)
assert!(current.is_some());
assert_eq!(current.unwrap().number, 2);
}
#[test]
fn current_iteration_returns_none_when_empty() {
let state = TuiState::new();
assert!(state.current_iteration().is_none());
}
#[test]
fn current_iteration_mut_allows_modification() {
let mut state = TuiState::new();
state.start_new_iteration();
// Add a line via mutable reference
if let Some(buffer) = state.current_iteration_mut() {
buffer.append_line(Line::from("test line"));
}
// Verify modification persisted
assert_eq!(state.current_iteration().unwrap().line_count(), 1);
}
#[test]
fn navigate_next_increases_current_view() {
// Given TuiState with current_view = 1 and 3 iterations
let mut state = TuiState::new();
state.start_new_iteration();
state.start_new_iteration();
state.start_new_iteration();
state.current_view = 1;
state.following_latest = false;
// When navigate_next() is called
state.navigate_next();
// Then current_view == 2
assert_eq!(state.current_view, 2);
}
#[test]
fn navigate_prev_decreases_current_view() {
// Given TuiState with current_view = 2
let mut state = TuiState::new();
state.start_new_iteration();
state.start_new_iteration();
state.start_new_iteration();
state.current_view = 2;
// When navigate_prev() is called
state.navigate_prev();
// Then current_view == 1
assert_eq!(state.current_view, 1);
}
#[test]
fn navigate_next_does_not_exceed_bounds() {
// Given TuiState with current_view = 2 and 3 iterations (max index 2)
let mut state = TuiState::new();
state.start_new_iteration();
state.start_new_iteration();
state.start_new_iteration();
state.current_view = 2;
// When navigate_next() is called
state.navigate_next();
// Then current_view stays at 2
assert_eq!(state.current_view, 2);
}
#[test]
fn navigate_prev_does_not_go_below_zero() {
// Given TuiState with current_view = 0
let mut state = TuiState::new();
state.start_new_iteration();
state.current_view = 0;
// When navigate_prev() is called
state.navigate_prev();
// Then current_view stays at 0
assert_eq!(state.current_view, 0);
}
#[test]
fn following_latest_initially_true() {
// Given new TuiState
// When created
let state = TuiState::new();
// Then following_latest == true
assert!(state.following_latest);
}
#[test]
fn following_latest_becomes_false_on_back_navigation() {
// Given TuiState with following_latest = true and current_view = 2
let mut state = TuiState::new();
state.start_new_iteration();
state.start_new_iteration();
state.start_new_iteration();
state.current_view = 2;
state.following_latest = true;
// When navigate_prev() is called
state.navigate_prev();
// Then following_latest == false
assert!(!state.following_latest);
}
#[test]
fn following_latest_restored_at_latest() {
// Given TuiState with following_latest = false
let mut state = TuiState::new();
state.start_new_iteration();
state.start_new_iteration();
state.start_new_iteration();
state.current_view = 1;
state.following_latest = false;
// When navigate_next() reaches the last iteration
state.navigate_next(); // 1 -> 2 (last)
// Then following_latest == true
assert!(state.following_latest);
}
#[test]
fn total_iterations_reports_count() {
// Given TuiState with 3 iterations
let mut state = TuiState::new();
state.start_new_iteration();
state.start_new_iteration();
state.start_new_iteration();
// When total_iterations() is called
// Then 3 is returned
assert_eq!(state.total_iterations(), 3);
}
#[test]
fn start_new_iteration_auto_follows_latest() {
let mut state = TuiState::new();
state.following_latest = true;
state.start_new_iteration();
state.start_new_iteration();
// When following latest, current_view should track new iterations
assert_eq!(state.current_view, 1); // Index of second iteration
}
// ========================================================================
// Per-Iteration Scroll Independence Tests (Task 08)
// ========================================================================
#[test]
fn per_iteration_scroll_independence() {
// Given iteration 1 with scroll_offset 5 and iteration 2 with scroll_offset 0
let mut state = TuiState::new();
state.start_new_iteration();
state.start_new_iteration();
// Set different scroll offsets for each iteration
state.iterations[0].scroll_offset = 5;
state.iterations[1].scroll_offset = 0;
// When switching between iterations
state.current_view = 0;
assert_eq!(
state.current_iteration().unwrap().scroll_offset,
5,
"iteration 1 should have scroll_offset 5"
);
state.navigate_next();
assert_eq!(
state.current_iteration().unwrap().scroll_offset,
0,
"iteration 2 should have scroll_offset 0"
);
// Then each iteration's scroll_offset is preserved
state.navigate_prev();
assert_eq!(
state.current_iteration().unwrap().scroll_offset,
5,
"iteration 1 should still have scroll_offset 5 after switching back"
);
}
#[test]
fn scroll_within_iteration_does_not_affect_others() {
// Given multiple iterations with different scroll offsets
let mut state = TuiState::new();
state.start_new_iteration();
state.start_new_iteration();
state.start_new_iteration();
// Add content to each iteration
for i in 0..3 {
for j in 0..20 {
state.iterations[i].append_line(Line::from(format!(
"iter {} line {}",
i + 1,
j
)));
}
}
// Set initial scroll offsets
state.iterations[0].scroll_offset = 3;
state.iterations[1].scroll_offset = 7;
state.iterations[2].scroll_offset = 10;
// When scrolling in iteration 2
state.current_view = 1;
state.current_iteration_mut().unwrap().scroll_down(10);
// Then only iteration 2's scroll changed
assert_eq!(
state.iterations[0].scroll_offset, 3,
"iteration 1 unchanged"
);
assert_eq!(
state.iterations[1].scroll_offset, 8,
"iteration 2 scrolled down"
);
assert_eq!(
state.iterations[2].scroll_offset, 10,
"iteration 3 unchanged"
);
}
// ========================================================================
// New Iteration Alert Tests (Task 07)
// ========================================================================
#[test]
fn new_iteration_alert_set_when_not_following() {
// Given following_latest = false and new iteration arrives
let mut state = TuiState::new();
state.start_new_iteration(); // Iteration 1
state.start_new_iteration(); // Iteration 2
state.navigate_prev(); // Go back to iteration 1, following_latest = false
// When start_new_iteration() is called
state.start_new_iteration(); // Iteration 3
// Then new_iteration_alert is set to the new iteration number
assert_eq!(state.new_iteration_alert, Some(3));
}
#[test]
fn new_iteration_alert_not_set_when_following() {
// Given following_latest = true
let mut state = TuiState::new();
state.following_latest = true;
state.start_new_iteration();
// When start_new_iteration() is called
state.start_new_iteration();
// Then new_iteration_alert remains None
assert_eq!(state.new_iteration_alert, None);
}
#[test]
fn alert_cleared_when_following_restored() {
// Given new_iteration_alert = Some(5)
let mut state = TuiState::new();
state.start_new_iteration();
state.start_new_iteration();
state.start_new_iteration();
state.current_view = 0;
state.following_latest = false;
state.new_iteration_alert = Some(3);
// When navigation restores following_latest = true
state.navigate_next(); // 0 -> 1
state.navigate_next(); // 1 -> 2 (last, restores following)
// Then new_iteration_alert is cleared to None
assert_eq!(state.new_iteration_alert, None);
}
#[test]
fn alert_not_cleared_on_partial_navigation() {
// Given new_iteration_alert = Some(3) and not at last iteration
let mut state = TuiState::new();
state.start_new_iteration();
state.start_new_iteration();
state.start_new_iteration();
state.current_view = 0;
state.following_latest = false;
state.new_iteration_alert = Some(3);
// When navigate_next() but not reaching last
state.navigate_next(); // 0 -> 1
// Then alert is still set (not at latest yet)
assert_eq!(state.new_iteration_alert, Some(3));
assert!(!state.following_latest);
}
#[test]
fn alert_updates_for_multiple_new_iterations() {
// Given not following and multiple new iterations arrive
let mut state = TuiState::new();
state.start_new_iteration(); // 1
state.start_new_iteration(); // 2
state.navigate_prev(); // Go back, stop following
state.start_new_iteration(); // 3 arrives
assert_eq!(state.new_iteration_alert, Some(3));
// When another iteration arrives
state.start_new_iteration(); // 4 arrives
// Then alert should show the newest
assert_eq!(state.new_iteration_alert, Some(4));
}
}
// ========================================================================
// SearchState Tests (Task 09)
// ========================================================================
mod search_state {
use super::*;
#[test]
fn search_finds_matches_in_lines() {
// Given current iteration with "error" in 3 lines
let mut state = TuiState::new();
state.start_new_iteration();
let buffer = state.current_iteration_mut().unwrap();
buffer.append_line(Line::from("First error occurred"));
buffer.append_line(Line::from("Normal line"));
buffer.append_line(Line::from("Another error here"));
buffer.append_line(Line::from("Final error message"));
// When search("error") is called
state.search("error");
// Then matches.len() >= 3
assert!(
state.search_state.matches.len() >= 3,
"expected at least 3 matches, got {}",
state.search_state.matches.len()
);
assert_eq!(state.search_state.query, Some("error".to_string()));
}
#[test]
fn search_is_case_insensitive() {
// Given current iteration with "Error" and "error"
let mut state = TuiState::new();
state.start_new_iteration();
let buffer = state.current_iteration_mut().unwrap();
buffer.append_line(Line::from("Error in uppercase"));
buffer.append_line(Line::from("error in lowercase"));
buffer.append_line(Line::from("ERROR all caps"));
// When search("error") is called
state.search("error");
// Then all 3 are found
assert_eq!(
state.search_state.matches.len(),
3,
"expected 3 case-insensitive matches"
);
}
#[test]
fn next_match_cycles_forward() {
// Given 3 matches and current_match = 2 (last)
let mut state = TuiState::new();
state.start_new_iteration();
let buffer = state.current_iteration_mut().unwrap();
buffer.append_line(Line::from("match one"));
buffer.append_line(Line::from("match two"));
buffer.append_line(Line::from("match three"));
state.search("match");
state.search_state.current_match = 2;
// When next_match() is called
state.next_match();
// Then current_match becomes 0 (cycles back)
assert_eq!(state.search_state.current_match, 0);
}
#[test]
fn prev_match_cycles_backward() {
// Given 3 matches and current_match = 0 (first)
let mut state = TuiState::new();
state.start_new_iteration();
let buffer = state.current_iteration_mut().unwrap();
buffer.append_line(Line::from("match one"));
buffer.append_line(Line::from("match two"));
buffer.append_line(Line::from("match three"));
state.search("match");
state.search_state.current_match = 0;
// When prev_match() is called
state.prev_match();
// Then current_match becomes 2 (cycles back)
assert_eq!(state.search_state.current_match, 2);
}
#[test]
fn search_jumps_to_match_line() {
// Given match at line 50
let mut state = TuiState::new();
state.start_new_iteration();
let buffer = state.current_iteration_mut().unwrap();
for i in 0..60 {
if i == 50 {
buffer.append_line(Line::from("target match here"));
} else {
buffer.append_line(Line::from(format!("line {}", i)));
}
}
// When search finds match at line 50
state.search("target");
// Then scroll_offset is updated so line 50 is visible
let buffer = state.current_iteration().unwrap();
// With viewport of ~20, scroll should position line 50 in view
assert!(
buffer.scroll_offset <= 50,
"scroll_offset {} should position line 50 in view",
buffer.scroll_offset
);
}
#[test]
fn clear_search_resets_state() {
// Given active search
let mut state = TuiState::new();
state.start_new_iteration();
let buffer = state.current_iteration_mut().unwrap();
buffer.append_line(Line::from("search term here"));
state.search("term");
assert!(state.search_state.query.is_some());
// When clear_search() is called
state.clear_search();
// Then query = None, matches cleared, search_mode = false
assert!(state.search_state.query.is_none());
assert!(state.search_state.matches.is_empty());
assert!(!state.search_state.search_mode);
}
#[test]
fn search_with_no_matches_sets_empty() {
// Given iteration with no matching content
let mut state = TuiState::new();
state.start_new_iteration();
let buffer = state.current_iteration_mut().unwrap();
buffer.append_line(Line::from("hello world"));
// When searching for non-existent term
state.search("xyz");
// Then matches is empty but query is set
assert_eq!(state.search_state.query, Some("xyz".to_string()));
assert!(state.search_state.matches.is_empty());
assert_eq!(state.search_state.current_match, 0);
}
#[test]
fn search_on_empty_iteration_handles_gracefully() {
// Given empty iteration
let mut state = TuiState::new();
state.start_new_iteration();
// When searching
state.search("anything");
// Then no panic, empty matches
assert!(state.search_state.matches.is_empty());
}
#[test]
fn next_match_with_no_matches_does_nothing() {
// Given no active search or empty matches
let mut state = TuiState::new();
state.start_new_iteration();
// When next_match is called
state.next_match();
// Then no panic, current_match stays 0
assert_eq!(state.search_state.current_match, 0);
}
#[test]
fn multiple_matches_on_same_line() {
// Given line with multiple occurrences
let mut state = TuiState::new();
state.start_new_iteration();
let buffer = state.current_iteration_mut().unwrap();
buffer.append_line(Line::from("error error error"));
// When searching
state.search("error");
// Then finds all 3 matches
assert_eq!(
state.search_state.matches.len(),
3,
"should find 3 matches on same line"
);
}
#[test]
fn next_match_updates_scroll_to_show_match() {
// Given many lines with matches spread out
let mut state = TuiState::new();
state.start_new_iteration();
let buffer = state.current_iteration_mut().unwrap();
for i in 0..100 {
if i % 30 == 0 {
buffer.append_line(Line::from("findme"));
} else {
buffer.append_line(Line::from(format!("line {}", i)));
}
}
state.search("findme");
// Navigate to second match (at line 30)
state.next_match();
// Then scroll should position line 30 in view
let buffer = state.current_iteration().unwrap();
// Match at line 30, scroll should be adjusted
assert!(buffer.scroll_offset <= 30, "scroll should show line 30");
}
#[test]
fn latest_iteration_lines_handle_returns_newest_iteration() {
// Given a user viewing iteration 1 while iteration 3 is executing
let mut state = TuiState::new();
state.start_new_iteration(); // iteration 1
state.start_new_iteration(); // iteration 2
state.start_new_iteration(); // iteration 3
// User navigates back to iteration 1
state.current_view = 0;
state.following_latest = false;
// When getting line handles
let current_handle = state.current_iteration_lines_handle();
let latest_handle = state.latest_iteration_lines_handle();
// Then current_iteration_lines_handle returns iteration 1's buffer
assert!(current_handle.is_some());
// And latest_iteration_lines_handle returns iteration 3's buffer
assert!(latest_handle.is_some());
// Write to latest and verify it doesn't affect current view
{
let latest = latest_handle.unwrap();
latest
.lock()
.unwrap()
.push(Line::from("output from iteration 3"));
}
// Current view (iteration 1) should be empty
let current = state.current_iteration().unwrap();
assert_eq!(
current.lines.lock().unwrap().len(),
0,
"iteration 1 should have no lines"
);
// Latest (iteration 3) should have the output
let latest_buffer = state.iterations.last().unwrap();
assert_eq!(
latest_buffer.lines.lock().unwrap().len(),
1,
"iteration 3 should have the output"
);
}
#[test]
fn output_goes_to_correct_iteration_when_user_reviewing_history() {
// This reproduces the bug: user is on page 3 of 6, but active agent writes to page 3
let mut state = TuiState::new();
// Create 6 iterations
for _ in 0..6 {
state.start_new_iteration();
}
// User navigates to iteration 3 (index 2)
state.current_view = 2;
state.following_latest = false;
// New iteration starts (iteration 7)
state.start_new_iteration();
// Get handle for writing output - MUST use latest, not current
let lines_handle = state.latest_iteration_lines_handle();
// Write output
{
let handle = lines_handle.unwrap();
handle
.lock()
.unwrap()
.push(Line::from("iteration 7 output"));
}
// Verify: iteration 3 (what user is viewing) should be unaffected
let iteration_3 = &state.iterations[2];
assert_eq!(
iteration_3.lines.lock().unwrap().len(),
0,
"iteration 3 (being viewed) should have no output"
);
// Verify: iteration 7 (latest) should have the output
let iteration_7 = state.iterations.last().unwrap();
assert_eq!(
iteration_7.lines.lock().unwrap().len(),
1,
"iteration 7 (latest) should have the output"
);
}
}
// ========================================================================
// Guidance Tests
// ========================================================================
mod guidance {
use super::*;
#[test]
fn start_guidance_sets_mode_and_clears_input() {
let mut state = TuiState::new();
state.guidance_input = "leftover".to_string();
state.start_guidance(GuidanceMode::Next);
assert_eq!(state.guidance_mode, Some(GuidanceMode::Next));
assert!(state.guidance_input.is_empty());
}
#[test]
fn start_guidance_now_mode() {
let mut state = TuiState::new();
state.start_guidance(GuidanceMode::Now);
assert_eq!(state.guidance_mode, Some(GuidanceMode::Now));
}
#[test]
fn cancel_guidance_clears_state() {
let mut state = TuiState::new();
state.start_guidance(GuidanceMode::Next);
state.guidance_input = "some text".to_string();
state.cancel_guidance();
assert!(state.guidance_mode.is_none());
assert!(state.guidance_input.is_empty());
}
#[test]
fn send_guidance_next_pushes_to_queue() {
let mut state = TuiState::new();
state.start_guidance(GuidanceMode::Next);
state.guidance_input = "check auth.rs".to_string();
assert!(state.send_guidance());
assert!(state.guidance_mode.is_none());
assert!(state.guidance_input.is_empty());
let queue = state.guidance_next_queue.lock().unwrap();
assert_eq!(queue.len(), 1);
assert_eq!(queue[0], "check auth.rs");
}
#[test]
fn send_guidance_empty_input_cancels() {
let mut state = TuiState::new();
state.start_guidance(GuidanceMode::Next);
state.guidance_input = " ".to_string();
assert!(!state.send_guidance());
let queue = state.guidance_next_queue.lock().unwrap();
assert!(queue.is_empty());
}
#[test]
fn send_guidance_sets_flash() {
let mut state = TuiState::new();
state.start_guidance(GuidanceMode::Next);
state.guidance_input = "test".to_string();
state.send_guidance();
assert!(state.guidance_flash.is_some());
assert_eq!(
state.active_guidance_flash(),
Some((GuidanceMode::Next, GuidanceResult::Queued))
);
}
#[test]
fn send_guidance_now_writes_to_events_file() {
let dir = tempfile::tempdir().unwrap();
let events_path = dir.path().join("events.jsonl");
let mut state = TuiState::new();
state.events_path = Some(events_path.clone());
state.start_guidance(GuidanceMode::Now);
state.guidance_input = "fix the bug now".to_string();
assert!(state.send_guidance());
let content = std::fs::read_to_string(&events_path).unwrap();
let event: serde_json::Value = serde_json::from_str(content.trim()).unwrap();
assert_eq!(event["topic"], "human.guidance");
assert_eq!(event["payload"], "fix the bug now");
assert!(event["ts"].is_string());
}
#[test]
fn send_guidance_now_without_events_path_fails() {
let mut state = TuiState::new();
state.events_path = None;
state.start_guidance(GuidanceMode::Now);
state.guidance_input = "test".to_string();
assert!(!state.send_guidance());
}
#[test]
fn is_guidance_active_reflects_mode() {
let mut state = TuiState::new();
assert!(!state.is_guidance_active());
state.start_guidance(GuidanceMode::Next);
assert!(state.is_guidance_active());
state.cancel_guidance();
assert!(!state.is_guidance_active());
}
#[test]
fn multiple_guidance_messages_queue_correctly() {
let mut state = TuiState::new();
state.start_guidance(GuidanceMode::Next);
state.guidance_input = "first".to_string();
state.send_guidance();
state.start_guidance(GuidanceMode::Next);
state.guidance_input = "second".to_string();
state.send_guidance();
let queue = state.guidance_next_queue.lock().unwrap();
assert_eq!(queue.len(), 2);
assert_eq!(queue[0], "first");
assert_eq!(queue[1], "second");
}
#[test]
fn task_start_preserves_guidance_queue() {
let mut state = TuiState::new();
state.start_new_iteration();
// Queue some guidance
state.start_guidance(GuidanceMode::Next);
state.guidance_input = "remember this".to_string();
state.send_guidance();
// Simulate task.start reset
let event = Event::new("task.start", "New task");
state.update(&event);
// Queue should be preserved (same Arc)
let queue = state.guidance_next_queue.lock().unwrap();
assert_eq!(queue.len(), 1);
assert_eq!(queue[0], "remember this");
}
}
}