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
//! Application state for the TUI.
//!
//! Implements the Model part of The Elm Architecture (TEA).
//! Contains all state needed to render the UI and respond to events.
use std::collections::HashMap;
use std::fmt;
use std::path::PathBuf;
use std::time::Instant;
use throbber_widgets_tui::ThrobberState;
use crate::build::tokens::TokenUsage;
use crate::subprocess::StreamEvent;
use crate::tui::conversation::ConversationBuffer;
/// A group of consecutive tool uses under a common header.
///
/// This provides Claude CLI-like grouped display where consecutive
/// tool uses are grouped under "Claude (Iteration N)" headers.
#[derive(Debug, Clone)]
pub struct MessageGroup {
/// Display header (e.g., "Claude (Iteration 1)")
pub header: String,
/// All messages in this group
pub messages: Vec<Message>,
/// Whether the group is expanded to show all messages
pub expanded: bool,
/// Maximum messages to show when collapsed (default 3)
pub max_visible: usize,
/// Iteration this group belongs to
pub iteration: u32,
}
impl MessageGroup {
/// Create a new message group for an iteration.
pub fn new(iteration: u32) -> Self {
Self {
header: format!("Claude (Iteration {})", iteration),
messages: Vec::new(),
expanded: false,
max_visible: 3,
iteration,
}
}
/// Add a message to the group.
pub fn push(&mut self, message: Message) {
self.messages.push(message);
}
/// Check if the group is empty.
pub fn is_empty(&self) -> bool {
self.messages.is_empty()
}
/// Get the number of messages in the group.
pub fn len(&self) -> usize {
self.messages.len()
}
/// Toggle the expanded state.
pub fn toggle_expanded(&mut self) {
self.expanded = !self.expanded;
}
/// Get the number of hidden messages when collapsed.
pub fn hidden_count(&self) -> usize {
if self.expanded || self.messages.len() <= self.max_visible {
0
} else {
self.messages.len() - self.max_visible
}
}
/// Get visible messages based on expanded state.
/// When collapsed, shows the MOST RECENT (last) messages.
pub fn visible_messages(&self) -> &[Message] {
if self.expanded || self.messages.len() <= self.max_visible {
&self.messages
} else {
// Show the last N messages (most recent)
let start = self.messages.len() - self.max_visible;
&self.messages[start..]
}
}
}
/// A group of consecutive system/log messages.
///
/// Groups system messages together to reduce visual noise.
/// Shows only the most recent N messages when collapsed.
#[derive(Debug, Clone)]
pub struct SystemGroup {
/// All system messages in this group
pub messages: Vec<Message>,
/// Whether the group is expanded to show all messages
pub expanded: bool,
/// Maximum messages to show when collapsed (default 3)
pub max_visible: usize,
/// Iteration this group belongs to
pub iteration: u32,
}
impl SystemGroup {
/// Create a new system group for an iteration.
pub fn new(iteration: u32) -> Self {
Self {
messages: Vec::new(),
expanded: false,
max_visible: 3,
iteration,
}
}
/// Add a message to the group.
pub fn push(&mut self, message: Message) {
self.messages.push(message);
}
/// Check if the group is empty.
pub fn is_empty(&self) -> bool {
self.messages.is_empty()
}
/// Get the number of messages in the group.
pub fn len(&self) -> usize {
self.messages.len()
}
/// Toggle the expanded state.
pub fn toggle_expanded(&mut self) {
self.expanded = !self.expanded;
}
/// Get the number of hidden messages when collapsed.
pub fn hidden_count(&self) -> usize {
if self.expanded || self.messages.len() <= self.max_visible {
0
} else {
self.messages.len() - self.max_visible
}
}
/// Get visible messages based on expanded state.
/// When collapsed, shows the MOST RECENT (last) messages.
pub fn visible_messages(&self) -> &[Message] {
if self.expanded || self.messages.len() <= self.max_visible {
&self.messages
} else {
// Show the last N messages (most recent)
let start = self.messages.len() - self.max_visible;
&self.messages[start..]
}
}
}
/// Display item - either a Claude group or a system message group.
#[derive(Debug, Clone)]
pub enum DisplayItem {
/// A group of tool/assistant messages
Group(MessageGroup),
/// A group of system/log messages
SystemGroup(SystemGroup),
}
impl DisplayItem {
/// Get the iteration this item belongs to.
pub fn iteration(&self) -> u32 {
match self {
DisplayItem::Group(g) => g.iteration,
DisplayItem::SystemGroup(g) => g.iteration,
}
}
}
/// Message role/type in the conversation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MessageRole {
/// User prompt/input.
User,
/// Claude's text response.
Assistant,
/// Tool use (with tool name).
Tool(String),
/// System/log message.
System,
}
impl MessageRole {
/// Get display label for the role.
pub fn label(&self) -> &str {
match self {
MessageRole::User => "You",
MessageRole::Assistant => "Claude",
MessageRole::Tool(_) => "Tool",
MessageRole::System => "System",
}
}
/// Parse from string (for backwards compatibility).
#[allow(clippy::should_implement_trait)]
pub fn from_str(s: &str) -> Self {
match s {
"user" => MessageRole::User,
"assistant" => MessageRole::Assistant,
"system" => MessageRole::System,
s if s.starts_with("tool:") => {
MessageRole::Tool(s.strip_prefix("tool:").unwrap_or("unknown").to_string())
}
_ => MessageRole::System,
}
}
}
impl fmt::Display for MessageRole {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
MessageRole::User => write!(f, "user"),
MessageRole::Assistant => write!(f, "assistant"),
MessageRole::Tool(name) => write!(f, "tool:{}", name),
MessageRole::System => write!(f, "system"),
}
}
}
/// A message in the conversation history.
#[derive(Debug, Clone)]
pub struct Message {
/// Role/type of the message.
pub role: MessageRole,
/// Content of the message.
pub content: String,
/// Which iteration this message belongs to.
pub iteration: u32,
/// Whether this message is collapsed in the view.
pub collapsed: bool,
/// Number of content lines (cached for performance).
pub line_count: usize,
}
impl Message {
/// Create a new message.
pub fn new(role: impl Into<String>, content: impl Into<String>, iteration: u32) -> Self {
let content_str: String = content.into();
let line_count = content_str.lines().count().max(1);
Self {
role: MessageRole::from_str(&role.into()),
content: content_str,
iteration,
collapsed: false,
line_count,
}
}
/// Create a new message with MessageRole directly.
pub fn with_role(role: MessageRole, content: impl Into<String>, iteration: u32) -> Self {
let content_str: String = content.into();
let line_count = content_str.lines().count().max(1);
// Tool messages start collapsed by default for cleaner output
let collapsed = matches!(role, MessageRole::Tool(_));
Self {
role,
content: content_str,
iteration,
collapsed,
line_count,
}
}
/// Toggle collapsed state.
pub fn toggle_collapsed(&mut self) {
self.collapsed = !self.collapsed;
}
}
/// Application state (TEA Model).
///
/// Contains all state needed to render the TUI and respond to events.
#[derive(Debug)]
pub struct App {
// Status bar state
/// Current iteration number (1-indexed).
pub current_iteration: u32,
/// Maximum number of iterations allowed.
pub max_iterations: u32,
/// Current task number within iteration.
pub current_task: u32,
/// Total number of tasks in current iteration.
pub total_tasks: u32,
/// Context usage as a ratio (0.0 to 1.0).
pub context_usage: f64,
/// Name of the model being used (e.g., "claude-sonnet-4-20250514").
pub model_name: String,
/// Name of the project.
pub project_name: String,
/// Path to the log file.
pub log_path: Option<PathBuf>,
// Output view state
/// All messages in the conversation (raw, for backwards compatibility).
pub messages: Vec<Message>,
/// Display items (grouped view) for rendering.
pub display_items: Vec<DisplayItem>,
/// Current group being built (accumulates tool uses).
current_group: Option<MessageGroup>,
/// Current system group being built (accumulates system messages).
current_system_group: Option<SystemGroup>,
/// Current vertical scroll offset.
pub scroll_offset: u16,
/// Currently selected group/item index (for expand/collapse navigation).
pub selected_group: Option<usize>,
// Navigation state
/// Which iteration we're currently viewing (for history browsing).
pub viewing_iteration: u32,
/// Whether the build is paused.
pub is_paused: bool,
/// Whether the application should quit.
pub should_quit: bool,
/// Maximum system messages to keep expanded (rolling limit).
pub max_system_expanded: usize,
// Token tracking state
/// Cumulative token usage across all iterations.
pub total_tokens: TokenUsage,
// Conversation view state (enhanced TUI)
/// Full conversation history for enhanced display.
pub conversation: ConversationBuffer,
/// Scroll offset for conversation view.
pub conversation_scroll: usize,
/// Whether to show enhanced conversation view.
pub show_conversation: bool,
// Backwards compatibility - keep for existing code
/// Currently selected message index (deprecated, use selected_group).
pub selected_message: Option<usize>,
// Thinking block collapse state
/// Tracks which thinking blocks are collapsed by index.
pub thinking_collapsed: HashMap<usize, bool>,
// Session timing
/// When the session started (for timer display).
pub session_start: Instant,
// Spinner state for LLM streaming indication
/// Animated spinner state for streaming indication.
pub spinner_state: ThrobberState,
/// Whether Claude is currently streaming a response.
pub is_streaming: bool,
}
impl Default for App {
fn default() -> Self {
Self {
current_iteration: 0,
max_iterations: 1,
current_task: 0,
total_tasks: 0,
context_usage: 0.0,
model_name: String::new(),
project_name: String::new(),
log_path: None,
messages: Vec::new(),
display_items: Vec::new(),
current_group: None,
current_system_group: None,
scroll_offset: 0,
selected_group: None,
viewing_iteration: 0,
is_paused: false,
should_quit: false,
max_system_expanded: 5,
total_tokens: TokenUsage::default(),
conversation: ConversationBuffer::new(1000),
conversation_scroll: 0,
show_conversation: false,
selected_message: None,
thinking_collapsed: HashMap::new(),
session_start: Instant::now(),
spinner_state: ThrobberState::default(),
is_streaming: false,
}
}
}
impl App {
/// Create a new App with the given configuration.
pub fn new(
max_iterations: u32,
model_name: impl Into<String>,
project_name: impl Into<String>,
) -> Self {
Self {
max_iterations,
model_name: model_name.into(),
project_name: project_name.into(),
..Default::default()
}
}
/// Update the app state based on an event.
pub fn update(&mut self, event: AppEvent) {
match event {
AppEvent::ScrollUp => {
self.scroll_offset = self.scroll_offset.saturating_sub(1);
}
AppEvent::ScrollDown => {
self.scroll_offset = self.scroll_offset.saturating_add(1);
}
AppEvent::PrevIteration => {
if self.viewing_iteration > 1 {
self.viewing_iteration -= 1;
self.scroll_offset = 0; // Reset scroll on iteration change
self.selected_message = None;
self.selected_group = None;
}
}
AppEvent::NextIteration => {
if self.viewing_iteration < self.current_iteration {
self.viewing_iteration += 1;
self.scroll_offset = 0; // Reset scroll on iteration change
self.selected_message = None;
self.selected_group = None;
}
}
AppEvent::TogglePause => {
self.is_paused = !self.is_paused;
}
AppEvent::Quit => {
self.should_quit = true;
}
AppEvent::SelectPrevMessage => {
self.select_prev_group();
}
AppEvent::SelectNextMessage => {
self.select_next_group();
}
AppEvent::ToggleMessage => {
self.toggle_selected_group();
}
AppEvent::ToggleConversation => {
self.show_conversation = !self.show_conversation;
}
AppEvent::ToggleThinkingCollapse => {
self.toggle_all_thinking_collapsed();
}
AppEvent::ConversationScrollUp(lines) => {
self.conversation_scroll = self.conversation_scroll.saturating_sub(lines);
}
AppEvent::ConversationScrollDown(lines) => {
self.conversation_scroll = (self.conversation_scroll + lines)
.min(self.conversation.len().saturating_sub(1));
}
AppEvent::StreamEvent(stream_event) => {
// Extract conversation items from the stream event
let items = stream_event.extract_conversation_items();
// Start streaming if we receive any content
if !items.is_empty() && !self.is_streaming {
self.start_streaming();
}
for item in items {
self.conversation.push(item);
}
// Auto-scroll to keep recent items visible
if self.conversation.len() > 20 {
self.conversation_scroll = self.conversation.len().saturating_sub(20);
}
}
AppEvent::ClaudeOutput(content) => {
// Finalize any pending system group first
self.finalize_system_group();
// Add assistant message to current group
let msg = Message::new("assistant", content.clone(), self.current_iteration);
self.messages.push(msg.clone());
self.add_to_current_group(msg);
}
AppEvent::ToolMessage { tool_name, content } => {
// Finalize any pending system group first
self.finalize_system_group();
// Add tool message to current group
let msg = Message::with_role(
MessageRole::Tool(tool_name),
content.clone(),
self.current_iteration,
);
self.messages.push(msg.clone());
self.add_to_current_group(msg);
}
AppEvent::ContextUsage(ratio) => {
self.context_usage = ratio.clamp(0.0, 1.0);
}
AppEvent::TokenUsage {
input_tokens,
output_tokens,
cache_creation_input_tokens,
cache_read_input_tokens,
} => {
// Token events contain per-message values; we accumulate across all messages and iterations
self.total_tokens.input_tokens += input_tokens;
self.total_tokens.output_tokens += output_tokens;
self.total_tokens.cache_creation_input_tokens += cache_creation_input_tokens;
self.total_tokens.cache_read_input_tokens += cache_read_input_tokens;
}
AppEvent::IterationStart { iteration } => {
// Finalize current groups before starting new iteration
self.finalize_current_group();
self.finalize_system_group();
self.current_iteration = iteration;
self.viewing_iteration = iteration;
self.scroll_offset = 0;
self.selected_message = None;
self.selected_group = None;
// Start a new group for this iteration
self.current_group = Some(MessageGroup::new(iteration));
}
AppEvent::IterationComplete { tasks_done } => {
// Finalize current groups
self.finalize_current_group();
self.finalize_system_group();
self.current_task = tasks_done;
self.viewing_iteration = self.current_iteration;
self.selected_message = None;
self.selected_group = None;
// Stop streaming spinner when iteration completes
self.stop_streaming();
}
AppEvent::LogMessage(content) => {
// Finalize Claude group first (system messages interrupt Claude output)
self.finalize_current_group();
// Add to current system group
let msg = Message::new("system", content.clone(), self.current_iteration);
self.messages.push(msg.clone());
self.add_to_system_group(msg);
}
AppEvent::Render => {
// Render events don't change state, just trigger redraw
}
}
}
/// Add a message to the current group, creating one if needed.
fn add_to_current_group(&mut self, msg: Message) {
if self.current_group.is_none() {
self.current_group = Some(MessageGroup::new(self.current_iteration));
}
if let Some(ref mut group) = self.current_group {
group.push(msg);
}
}
/// Finalize the current group and add it to display_items.
fn finalize_current_group(&mut self) {
if let Some(group) = self.current_group.take() {
if !group.is_empty() {
self.display_items.push(DisplayItem::Group(group));
}
}
}
/// Add a message to the current system group, creating one if needed.
fn add_to_system_group(&mut self, msg: Message) {
if self.current_system_group.is_none() {
self.current_system_group = Some(SystemGroup::new(self.current_iteration));
}
if let Some(ref mut group) = self.current_system_group {
group.push(msg);
}
}
/// Finalize the current system group and add it to display_items.
fn finalize_system_group(&mut self) {
if let Some(group) = self.current_system_group.take() {
if !group.is_empty() {
self.display_items.push(DisplayItem::SystemGroup(group));
}
}
}
/// Get display items for the currently viewed iteration.
pub fn display_items_for_viewing(&self) -> Vec<&DisplayItem> {
let items: Vec<&DisplayItem> = self
.display_items
.iter()
.filter(|item| item.iteration() == self.viewing_iteration)
.collect();
// Include current in-progress group if viewing current iteration
// (handled separately in rendering since current_group is Option)
items
}
/// Check if there's an in-progress group for the viewing iteration.
pub fn current_group_for_viewing(&self) -> Option<&MessageGroup> {
if self.viewing_iteration == self.current_iteration {
self.current_group.as_ref()
} else {
None
}
}
/// Check if there's an in-progress system group for the viewing iteration.
pub fn current_system_group_for_viewing(&self) -> Option<&SystemGroup> {
if self.viewing_iteration == self.current_iteration {
self.current_system_group.as_ref()
} else {
None
}
}
/// Scroll down by one line, clamped to content length.
pub fn scroll_down(&mut self, viewport_height: u16, content_height: u16) {
let max_offset = content_height.saturating_sub(viewport_height);
self.scroll_offset = (self.scroll_offset + 1).min(max_offset);
}
/// Scroll up by one line.
pub fn scroll_up(&mut self) {
self.scroll_offset = self.scroll_offset.saturating_sub(1);
}
/// Auto-scroll to bottom (for following live output).
pub fn scroll_to_bottom(&mut self, viewport_height: u16, content_height: u16) {
let max_offset = content_height.saturating_sub(viewport_height);
self.scroll_offset = max_offset;
}
/// Add a new message and auto-scroll if at bottom.
pub fn add_message(&mut self, role: MessageRole, content: String, viewport_height: u16) {
let was_at_bottom = self.is_at_bottom(viewport_height);
let content_lines = content.lines().count().max(1);
self.messages.push(Message {
role,
content,
iteration: self.current_iteration,
collapsed: false,
line_count: content_lines,
});
// Auto-collapse old system messages beyond limit
self.enforce_system_rolling_limit();
if was_at_bottom {
// Content height increased, but we handle this on next render
// Just mark that we should scroll
}
}
/// Add a message with role from string (backwards compatibility).
pub fn add_message_str(&mut self, role: &str, content: String, viewport_height: u16) {
self.add_message(MessageRole::from_str(role), content, viewport_height);
}
/// Add a tool use message.
pub fn add_tool_message(&mut self, tool_name: String, content: String, viewport_height: u16) {
self.add_message(MessageRole::Tool(tool_name), content, viewport_height);
}
/// Enforce rolling limit for system messages - collapse old ones beyond limit.
fn enforce_system_rolling_limit(&mut self) {
let iteration = self.current_iteration;
let limit = self.max_system_expanded;
// Find all system message indices for current iteration (newest first)
let system_indices: Vec<usize> = self
.messages
.iter()
.enumerate()
.filter(|(_, m)| m.iteration == iteration && matches!(m.role, MessageRole::System))
.map(|(i, _)| i)
.rev()
.collect();
// Auto-collapse messages beyond the limit
for (i, &msg_idx) in system_indices.iter().enumerate() {
if i >= limit {
self.messages[msg_idx].collapsed = true;
}
}
}
/// Get indices of messages for the currently viewed iteration.
pub fn message_indices_for_viewing(&self) -> Vec<usize> {
self.messages
.iter()
.enumerate()
.filter(|(_, m)| m.iteration == self.viewing_iteration)
.map(|(i, _)| i)
.collect()
}
/// Toggle collapse state of the currently selected message.
pub fn toggle_selected_message(&mut self) {
if let Some(sel_idx) = self.selected_message {
let indices = self.message_indices_for_viewing();
if sel_idx < indices.len() {
let msg_idx = indices[sel_idx];
self.messages[msg_idx].toggle_collapsed();
}
}
}
/// Select next message in the current iteration.
pub fn select_next_message(&mut self) {
let indices = self.message_indices_for_viewing();
if indices.is_empty() {
return;
}
self.selected_message = match self.selected_message {
None => Some(0),
Some(i) if i + 1 < indices.len() => Some(i + 1),
Some(i) => Some(i), // Stay at last
};
}
/// Select previous message in the current iteration.
pub fn select_prev_message(&mut self) {
let indices = self.message_indices_for_viewing();
if indices.is_empty() {
return;
}
self.selected_message = match self.selected_message {
None => Some(indices.len().saturating_sub(1)),
Some(0) => Some(0), // Stay at first
Some(i) => Some(i - 1),
};
}
/// Get the count of display items for the viewing iteration (including current groups).
fn display_item_count_for_viewing(&self) -> usize {
let count = self
.display_items
.iter()
.filter(|item| item.iteration() == self.viewing_iteration)
.count();
// Add 1 for current in-progress group if viewing current iteration
let mut extra = 0;
if self.viewing_iteration == self.current_iteration {
if self.current_group.is_some() {
extra += 1;
}
if self.current_system_group.is_some() {
extra += 1;
}
}
count + extra
}
/// Select next group/item in the current iteration.
pub fn select_next_group(&mut self) {
let count = self.display_item_count_for_viewing();
if count == 0 {
return;
}
self.selected_group = match self.selected_group {
None => Some(0),
Some(i) if i + 1 < count => Some(i + 1),
Some(i) => Some(i), // Stay at last
};
}
/// Select previous group/item in the current iteration.
pub fn select_prev_group(&mut self) {
let count = self.display_item_count_for_viewing();
if count == 0 {
return;
}
self.selected_group = match self.selected_group {
None => Some(count.saturating_sub(1)),
Some(0) => Some(0), // Stay at first
Some(i) => Some(i - 1),
};
}
/// Toggle expand/collapse of the currently selected group.
pub fn toggle_selected_group(&mut self) {
if let Some(sel_idx) = self.selected_group {
let items_for_iter: Vec<usize> = self
.display_items
.iter()
.enumerate()
.filter(|(_, item)| item.iteration() == self.viewing_iteration)
.map(|(i, _)| i)
.collect();
if sel_idx < items_for_iter.len() {
let item_idx = items_for_iter[sel_idx];
match &mut self.display_items[item_idx] {
DisplayItem::Group(ref mut group) => group.toggle_expanded(),
DisplayItem::SystemGroup(ref mut group) => group.toggle_expanded(),
}
} else {
// Handle current in-progress groups
let in_progress_offset = sel_idx - items_for_iter.len();
if in_progress_offset == 0 && self.current_group.is_some() {
if let Some(ref mut group) = self.current_group {
group.toggle_expanded();
}
} else if (in_progress_offset == 0 && self.current_group.is_none())
|| (in_progress_offset == 1 && self.current_group.is_some())
{
if let Some(ref mut group) = self.current_system_group {
group.toggle_expanded();
}
}
}
}
}
/// Check if scroll is at the bottom of content.
fn is_at_bottom(&self, viewport_height: u16) -> bool {
let content_height = self.content_height_for_iteration(self.viewing_iteration);
let max_offset = content_height.saturating_sub(viewport_height);
self.scroll_offset >= max_offset
}
/// Calculate the content height for a given iteration.
/// Accounts for collapsed messages (1 line when collapsed).
pub fn content_height_for_iteration(&self, iteration: u32) -> u16 {
self.messages
.iter()
.filter(|m| m.iteration == iteration)
.map(|m| {
if m.collapsed {
1 // Collapsed message shows as single line "Role > (N lines)"
} else {
m.line_count as u16 + 2 // +1 for role line, +1 for blank separator
}
})
.sum()
}
/// Toggle the collapsed state of a thinking block.
///
/// # Arguments
///
/// * `index` - The index of the thinking block in the conversation buffer.
pub fn toggle_thinking_collapse(&mut self, index: usize) {
let current = self
.thinking_collapsed
.get(&index)
.copied()
.unwrap_or(false);
self.thinking_collapsed.insert(index, !current);
}
/// Check if a thinking block is collapsed.
///
/// # Arguments
///
/// * `index` - The index of the thinking block in the conversation buffer.
///
/// # Returns
///
/// `true` if the thinking block is collapsed, `false` otherwise.
pub fn is_thinking_collapsed(&self, index: usize) -> bool {
self.thinking_collapsed
.get(&index)
.copied()
.unwrap_or(false)
}
/// Toggle collapsed state for all thinking blocks.
///
/// If any thinking block is expanded, collapse all. Otherwise, expand all.
pub fn toggle_all_thinking_collapsed(&mut self) {
// Check if any thinking block is currently expanded (not in map or false)
let any_expanded =
self.thinking_collapsed.values().any(|&v| !v) || self.thinking_collapsed.is_empty();
// If any are expanded, collapse all known ones
// If all are collapsed, expand all
for value in self.thinking_collapsed.values_mut() {
*value = any_expanded;
}
}
/// Start the streaming spinner.
///
/// Call this when Claude begins streaming a response.
pub fn start_streaming(&mut self) {
self.is_streaming = true;
}
/// Stop the streaming spinner.
///
/// Call this when Claude finishes streaming a response.
pub fn stop_streaming(&mut self) {
self.is_streaming = false;
}
/// Advance the spinner animation by one frame.
///
/// Should be called on each tick (e.g., 30 FPS) to animate the spinner.
/// Only advances when is_streaming is true.
pub fn tick_spinner(&mut self) {
if self.is_streaming {
self.spinner_state.calc_next();
}
}
}
/// Events that can occur in the application.
///
/// These are converted from raw crossterm events or sent from subprocess handlers.
#[derive(Debug, Clone)]
pub enum AppEvent {
// Keyboard/mouse navigation
/// Scroll up one line.
ScrollUp,
/// Scroll down one line.
ScrollDown,
/// View previous iteration's messages.
PrevIteration,
/// View next iteration's messages.
NextIteration,
/// Toggle pause state.
TogglePause,
/// Request application quit.
Quit,
// Message selection (for collapse/expand)
/// Select previous message.
SelectPrevMessage,
/// Select next message.
SelectNextMessage,
/// Toggle collapse state of selected message.
ToggleMessage,
// Conversation view events
/// Toggle enhanced conversation view display.
ToggleConversation,
/// Toggle all thinking blocks collapsed/expanded.
ToggleThinkingCollapse,
/// Scroll conversation up by N lines.
ConversationScrollUp(usize),
/// Scroll conversation down by N lines.
ConversationScrollDown(usize),
/// Raw stream event for conversation extraction.
StreamEvent(StreamEvent),
// Subprocess events
/// New output from Claude (text).
ClaudeOutput(String),
/// Tool use message (tool_name, content).
ToolMessage { tool_name: String, content: String },
/// Updated context usage ratio (0.0 to 1.0).
ContextUsage(f64),
/// Token usage update from build loop.
TokenUsage {
input_tokens: u64,
output_tokens: u64,
cache_creation_input_tokens: u64,
cache_read_input_tokens: u64,
},
/// New iteration is starting.
IterationStart {
/// The iteration number (1-indexed).
iteration: u32,
},
/// An iteration completed with the given number of tasks done.
IterationComplete {
/// Number of tasks completed in this iteration.
tasks_done: u32,
},
/// Log message from build loop (displayed as system message).
LogMessage(String),
// Timer events
/// Time to render a new frame.
Render,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_app_new() {
let app = App::new(10, "claude-sonnet-4-20250514", "my-project");
assert_eq!(app.max_iterations, 10);
assert_eq!(app.model_name, "claude-sonnet-4-20250514");
assert_eq!(app.project_name, "my-project");
assert_eq!(app.current_iteration, 0);
assert!(!app.is_paused);
assert!(!app.should_quit);
}
#[test]
fn test_app_update_scroll() {
let mut app = App {
scroll_offset: 5,
..Default::default()
};
app.update(AppEvent::ScrollUp);
assert_eq!(app.scroll_offset, 4);
app.update(AppEvent::ScrollDown);
assert_eq!(app.scroll_offset, 5);
// Test saturation at 0
app.scroll_offset = 0;
app.update(AppEvent::ScrollUp);
assert_eq!(app.scroll_offset, 0);
}
#[test]
fn test_app_update_quit() {
let mut app = App::default();
assert!(!app.should_quit);
app.update(AppEvent::Quit);
assert!(app.should_quit);
}
#[test]
fn test_app_update_toggle_pause() {
let mut app = App::default();
assert!(!app.is_paused);
app.update(AppEvent::TogglePause);
assert!(app.is_paused);
app.update(AppEvent::TogglePause);
assert!(!app.is_paused);
}
#[test]
fn test_app_update_context_usage() {
let mut app = App::default();
app.update(AppEvent::ContextUsage(0.5));
assert!((app.context_usage - 0.5).abs() < f64::EPSILON);
// Test clamping
app.update(AppEvent::ContextUsage(1.5));
assert!((app.context_usage - 1.0).abs() < f64::EPSILON);
app.update(AppEvent::ContextUsage(-0.5));
assert!((app.context_usage - 0.0).abs() < f64::EPSILON);
}
#[test]
fn test_app_update_token_usage_accumulates() {
let mut app = App::default();
// First token event
app.update(AppEvent::TokenUsage {
input_tokens: 1000,
output_tokens: 500,
cache_creation_input_tokens: 200,
cache_read_input_tokens: 100,
});
assert_eq!(app.total_tokens.input_tokens, 1000);
assert_eq!(app.total_tokens.output_tokens, 500);
assert_eq!(app.total_tokens.cache_creation_input_tokens, 200);
assert_eq!(app.total_tokens.cache_read_input_tokens, 100);
// Second token event - should ACCUMULATE, not overwrite
app.update(AppEvent::TokenUsage {
input_tokens: 2500,
output_tokens: 1300,
cache_creation_input_tokens: 300,
cache_read_input_tokens: 200,
});
// Verify accumulated values (1000+2500, 500+1300, 200+300, 100+200)
assert_eq!(app.total_tokens.input_tokens, 3500);
assert_eq!(app.total_tokens.output_tokens, 1800);
assert_eq!(app.total_tokens.cache_creation_input_tokens, 500);
assert_eq!(app.total_tokens.cache_read_input_tokens, 300);
}
#[test]
fn test_app_update_claude_output() {
let mut app = App {
current_iteration: 1,
..Default::default()
};
app.update(AppEvent::ClaudeOutput("Hello".to_string()));
assert_eq!(app.messages.len(), 1);
assert_eq!(app.messages[0].role, MessageRole::Assistant);
assert_eq!(app.messages[0].content, "Hello");
assert_eq!(app.messages[0].iteration, 1);
}
#[test]
fn test_message_new() {
let msg = Message::new("user", "test message", 3);
assert_eq!(msg.role, MessageRole::User);
assert_eq!(msg.content, "test message");
assert_eq!(msg.iteration, 3);
assert!(!msg.collapsed);
assert_eq!(msg.line_count, 1);
}
#[test]
fn test_message_with_role() {
let msg = Message::with_role(MessageRole::Tool("Read".to_string()), "file contents", 1);
assert_eq!(msg.role, MessageRole::Tool("Read".to_string()));
assert_eq!(msg.content, "file contents");
// Tool messages start collapsed by default
assert!(msg.collapsed);
}
#[test]
fn test_message_with_role_non_tool_not_collapsed() {
let msg = Message::with_role(MessageRole::Assistant, "response", 1);
// Non-tool messages start expanded
assert!(!msg.collapsed);
}
#[test]
fn test_message_toggle_collapsed() {
let mut msg = Message::new("assistant", "test", 1);
assert!(!msg.collapsed);
msg.toggle_collapsed();
assert!(msg.collapsed);
msg.toggle_collapsed();
assert!(!msg.collapsed);
}
#[test]
fn test_app_event_variants() {
// Ensure all variants are constructible
let _ = AppEvent::ScrollUp;
let _ = AppEvent::ScrollDown;
let _ = AppEvent::PrevIteration;
let _ = AppEvent::NextIteration;
let _ = AppEvent::TogglePause;
let _ = AppEvent::Quit;
let _ = AppEvent::SelectPrevMessage;
let _ = AppEvent::SelectNextMessage;
let _ = AppEvent::ToggleMessage;
let _ = AppEvent::ClaudeOutput("test".to_string());
let _ = AppEvent::ToolMessage {
tool_name: "Read".to_string(),
content: "file".to_string(),
};
let _ = AppEvent::ContextUsage(0.5);
let _ = AppEvent::TokenUsage {
input_tokens: 100,
output_tokens: 50,
cache_creation_input_tokens: 20,
cache_read_input_tokens: 10,
};
let _ = AppEvent::IterationComplete { tasks_done: 3 };
let _ = AppEvent::LogMessage("log".to_string());
let _ = AppEvent::Render;
}
#[test]
fn test_scroll_down_clamped() {
let mut app = App {
scroll_offset: 0,
..Default::default()
};
// Content of 10 lines, viewport of 5 lines => max offset is 5
app.scroll_down(5, 10);
assert_eq!(app.scroll_offset, 1);
// Scroll to the edge
app.scroll_offset = 5;
app.scroll_down(5, 10);
// Should stay at 5 (clamped)
assert_eq!(app.scroll_offset, 5);
}
#[test]
fn test_scroll_down_empty_content() {
let mut app = App {
scroll_offset: 0,
..Default::default()
};
// Empty content (0 lines), viewport of 10 lines => max offset is 0
app.scroll_down(10, 0);
assert_eq!(app.scroll_offset, 0);
}
#[test]
fn test_scroll_up_saturating() {
let mut app = App {
scroll_offset: 0,
..Default::default()
};
app.scroll_up();
assert_eq!(app.scroll_offset, 0); // Should not go negative
app.scroll_offset = 5;
app.scroll_up();
assert_eq!(app.scroll_offset, 4);
}
#[test]
fn test_scroll_to_bottom() {
let mut app = App {
scroll_offset: 0,
..Default::default()
};
// Content of 20 lines, viewport of 5 lines => max offset is 15
app.scroll_to_bottom(5, 20);
assert_eq!(app.scroll_offset, 15);
}
#[test]
fn test_content_height_for_iteration() {
let mut app = App {
current_iteration: 1,
..Default::default()
};
// Add messages with multiline content
app.messages.push(Message::new("assistant", "Line 1", 1));
app.messages
.push(Message::new("assistant", "Line 1\nLine 2\nLine 3", 1));
app.messages
.push(Message::new("assistant", "Different iteration", 2));
// Iteration 1:
// - "Line 1" = 1 line + 2 (role + blank) = 3
// - "Line 1\nLine 2\nLine 3" = 3 lines + 2 (role + blank) = 5
// Total = 8
let height = app.content_height_for_iteration(1);
assert_eq!(height, 8);
}
#[test]
fn test_content_height_collapsed() {
let mut app = App {
current_iteration: 1,
..Default::default()
};
// Add a multiline message and collapse it
app.messages
.push(Message::new("assistant", "Line 1\nLine 2\nLine 3", 1));
app.messages[0].collapsed = true;
// Collapsed message shows as 1 line
let height = app.content_height_for_iteration(1);
assert_eq!(height, 1);
}
#[test]
fn test_system_rolling_limit() {
let mut app = App {
current_iteration: 1,
max_system_expanded: 3,
..Default::default()
};
// Add 5 system messages
for i in 0..5 {
app.messages
.push(Message::new("system", format!("Log {}", i), 1));
}
app.enforce_system_rolling_limit();
// First 2 should be collapsed, last 3 should be expanded
assert!(app.messages[0].collapsed);
assert!(app.messages[1].collapsed);
assert!(!app.messages[2].collapsed);
assert!(!app.messages[3].collapsed);
assert!(!app.messages[4].collapsed);
}
#[test]
fn test_select_next_prev_message() {
let mut app = App {
viewing_iteration: 1,
..Default::default()
};
app.messages.push(Message::new("assistant", "msg1", 1));
app.messages.push(Message::new("assistant", "msg2", 1));
app.messages.push(Message::new("assistant", "msg3", 1));
// Initially no selection
assert_eq!(app.selected_message, None);
// Select next (first message)
app.select_next_message();
assert_eq!(app.selected_message, Some(0));
// Select next (second message)
app.select_next_message();
assert_eq!(app.selected_message, Some(1));
// Select prev (first message)
app.select_prev_message();
assert_eq!(app.selected_message, Some(0));
// Select prev at boundary (stay at first)
app.select_prev_message();
assert_eq!(app.selected_message, Some(0));
}
#[test]
fn test_toggle_selected_message() {
let mut app = App {
viewing_iteration: 1,
..Default::default()
};
app.messages.push(Message::new("assistant", "msg1", 1));
app.selected_message = Some(0);
assert!(!app.messages[0].collapsed);
app.toggle_selected_message();
assert!(app.messages[0].collapsed);
}
#[test]
fn test_message_role_from_str() {
assert_eq!(MessageRole::from_str("user"), MessageRole::User);
assert_eq!(MessageRole::from_str("assistant"), MessageRole::Assistant);
assert_eq!(MessageRole::from_str("system"), MessageRole::System);
assert_eq!(
MessageRole::from_str("tool:Read"),
MessageRole::Tool("Read".to_string())
);
assert_eq!(MessageRole::from_str("unknown"), MessageRole::System); // Default
}
#[test]
fn test_message_role_label() {
assert_eq!(MessageRole::User.label(), "You");
assert_eq!(MessageRole::Assistant.label(), "Claude");
assert_eq!(MessageRole::System.label(), "System");
assert_eq!(MessageRole::Tool("Read".to_string()).label(), "Tool");
}
#[test]
fn test_toggle_conversation() {
let mut app = App::default();
assert!(!app.show_conversation);
app.update(AppEvent::ToggleConversation);
assert!(app.show_conversation);
app.update(AppEvent::ToggleConversation);
assert!(!app.show_conversation);
}
#[test]
fn test_conversation_scroll_up() {
let mut app = App {
conversation_scroll: 20,
..Default::default()
};
app.update(AppEvent::ConversationScrollUp(10));
assert_eq!(app.conversation_scroll, 10);
app.update(AppEvent::ConversationScrollUp(15));
assert_eq!(app.conversation_scroll, 0); // Saturates at 0
}
#[test]
fn test_conversation_scroll_down() {
use crate::tui::conversation::ConversationItem;
let mut app = App::default();
// Push some items so we have content to scroll
for i in 0..30 {
app.conversation
.push(ConversationItem::Text(format!("Item {}", i)));
}
app.conversation_scroll = 0;
app.update(AppEvent::ConversationScrollDown(10));
assert_eq!(app.conversation_scroll, 10);
app.update(AppEvent::ConversationScrollDown(100));
// Should cap at len() - 1
assert_eq!(app.conversation_scroll, 29);
}
#[test]
fn test_conversation_buffer_in_default_app() {
let app = App::default();
assert_eq!(app.conversation.len(), 0);
assert_eq!(app.conversation_scroll, 0);
assert!(!app.show_conversation);
}
#[test]
fn test_thinking_collapsed_default() {
let app = App::default();
assert!(app.thinking_collapsed.is_empty());
assert!(!app.is_thinking_collapsed(0));
assert!(!app.is_thinking_collapsed(42));
}
#[test]
fn test_toggle_thinking_collapse() {
let mut app = App::default();
// Initially not collapsed
assert!(!app.is_thinking_collapsed(0));
// Toggle to collapsed
app.toggle_thinking_collapse(0);
assert!(app.is_thinking_collapsed(0));
// Toggle back to expanded
app.toggle_thinking_collapse(0);
assert!(!app.is_thinking_collapsed(0));
}
#[test]
fn test_toggle_all_thinking_collapsed() {
let mut app = App::default();
// Set some thinking blocks with different states
app.thinking_collapsed.insert(0, false); // expanded
app.thinking_collapsed.insert(1, true); // collapsed
app.thinking_collapsed.insert(2, false); // expanded
// Since some are expanded, toggle should collapse all
app.toggle_all_thinking_collapsed();
assert!(app.is_thinking_collapsed(0));
assert!(app.is_thinking_collapsed(1));
assert!(app.is_thinking_collapsed(2));
// Now all are collapsed, toggle should expand all
app.toggle_all_thinking_collapsed();
assert!(!app.is_thinking_collapsed(0));
assert!(!app.is_thinking_collapsed(1));
assert!(!app.is_thinking_collapsed(2));
}
}