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
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2026 Mark Wells <contact@markwells.dev>
//! Flat line generation: converts pipeline [`DisplayEntry`] trees into a
//! linear sequence of [`FlatLine`]s suitable for viewport slicing and rendering.
//!
//! The main entry point is [`PanelState::flat_lines()`], which runs the full
//! display pipeline (pair merge → scope collapse → run collapse) and then
//! flattens the result, expanding scopes and detail lines as needed.
use std::rc::Rc;
use super::format::{
format_collapsed_plain, format_message_plain, format_pair_plain, format_scope_plain,
};
use super::panel::{PanelState, frontmatter_lines};
use super::pipeline::{DisplayEntry, SegmentPosition, pair_merge, run_collapse, scope_collapse};
/// A line in the flattened view — message header, detail, or collapsed run.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FlatLine {
/// A message header (the one-line summary).
MessageHeader {
/// Index into the messages vec (request index for pairs).
message_index: usize,
/// If this header is a merged pair, the response message index.
paired_response: Option<usize>,
},
/// A detail line within an expanded message.
Detail {
/// Index into the messages vec (request index for pairs).
message_index: usize,
/// Index of this detail line within the expansion.
detail_index: usize,
},
/// A collapsed run header (summary of N consecutive messages).
CollapsedHeader {
/// Index of the first message in the run.
start_index: usize,
/// Index of the last message in the run (inclusive).
end_index: usize,
/// Number of messages in the run.
count: usize,
},
/// A scope header (parent of grouped children).
ScopeHeader {
/// The parent `DisplayEntry` (for rendering the summary line).
parent: Rc<DisplayEntry>,
/// Number of child entries in the scope.
child_count: usize,
/// Segment position within a segmented scope.
position: SegmentPosition,
/// Expansion key (first child's message index for this segment).
expansion_key: usize,
},
/// A `---` separator line between frontmatter and children.
Separator,
/// An indented child line within an expanded scope.
ScopeChild {
/// Depth level for indentation.
depth: usize,
/// Message index of the scope parent (expansion key).
scope_parent_index: usize,
/// The inner `FlatLine` (`MessageHeader`, `CollapsedHeader`, etc.).
inner: Box<Self>,
},
}
impl PanelState<'_> {
/// Build a flat list of lines: message headers interleaved with detail
/// lines for any expanded messages. Uses pair merge then run collapse
/// to combine adjacent request/response pairs and consecutive same-key
/// messages into single lines.
#[must_use]
#[allow(
clippy::too_many_lines,
reason = "scope collapse adds a fourth variant arm"
)]
pub fn flat_lines(&self) -> Vec<FlatLine> {
let lower_pattern = self.filter_pattern.as_ref().map(|p| p.to_lowercase());
let merged = pair_merge(&self.messages);
let scoped = scope_collapse(merged, &self.messages);
let entries = run_collapse(scoped, &self.messages);
let mut lines = Vec::new();
for entry in &entries {
match entry {
DisplayEntry::Single {
index,
parent_id: _,
} => {
let index = *index;
let msg = &self.messages[index];
if let Some(ref pat) = lower_pattern {
let plain = format_message_plain(msg);
if !plain.to_lowercase().contains(pat) {
continue;
}
}
lines.push(FlatLine::MessageHeader {
message_index: index,
paired_response: None,
});
if self.expanded.contains(&index) {
let count = frontmatter_lines(msg, self.theme).len();
for detail_index in 0..count {
lines.push(FlatLine::Detail {
message_index: index,
detail_index,
});
}
}
}
DisplayEntry::Paired {
request_index,
response_index,
parent_id: _,
} => {
let request_index = *request_index;
let response_index = *response_index;
let req = &self.messages[request_index];
let resp = &self.messages[response_index];
if let Some(ref pat) = lower_pattern {
let plain = format_pair_plain(req, resp);
if !plain.to_lowercase().contains(pat) {
continue;
}
}
lines.push(FlatLine::MessageHeader {
message_index: request_index,
paired_response: Some(response_index),
});
if self.expanded.contains(&request_index) {
let count = frontmatter_lines(req, self.theme).len();
for detail_index in 0..count {
lines.push(FlatLine::Detail {
message_index: request_index,
detail_index,
});
}
}
}
DisplayEntry::Collapsed {
start_index,
end_index,
count,
parent_id: _,
} => {
let start_index = *start_index;
let end_index = *end_index;
let count = *count;
if let Some(ref pat) = lower_pattern {
let plain =
format_collapsed_plain(&self.messages, start_index, end_index, count);
if !plain.to_lowercase().contains(pat) {
continue;
}
}
if self.expanded.contains(&start_index) {
// Show individual messages when expanded.
for idx in start_index..=end_index {
lines.push(FlatLine::MessageHeader {
message_index: idx,
paired_response: None,
});
if self.expanded.contains(&idx) {
let msg = &self.messages[idx];
let detail_count = frontmatter_lines(msg, self.theme).len();
for detail_index in 0..detail_count {
lines.push(FlatLine::Detail {
message_index: idx,
detail_index,
});
}
}
}
} else {
lines.push(FlatLine::CollapsedHeader {
start_index,
end_index,
count,
});
}
}
DisplayEntry::Scope {
parent,
children,
position,
} => {
let child_count = children.len();
if let Some(ref pat) = lower_pattern {
let plain =
format_scope_plain(parent, child_count, *position, &self.messages);
if !plain.to_lowercase().contains(pat) {
continue;
}
}
let scope_key = entry.expansion_index();
lines.push(FlatLine::ScopeHeader {
parent: Rc::clone(parent),
child_count,
position: *position,
expansion_key: scope_key,
});
if self.expanded.contains(&scope_key) {
self.emit_scope_frontmatter(parent, 1, scope_key, &mut lines);
self.flatten_scope_children(children, scope_key, 1, &mut lines);
}
}
}
}
lines
}
/// Emit frontmatter `Detail` lines and a `Separator` for a scope parent.
///
/// Extracts the request message index from the parent entry, generates
/// frontmatter lines, and pushes them as `ScopeChild` wrappers. If the
/// parent has a non-empty payload, a `Separator` is appended after the
/// last detail line.
fn emit_scope_frontmatter(
&self,
parent: &DisplayEntry,
depth: usize,
scope_parent_index: usize,
lines: &mut Vec<FlatLine>,
) {
let msg_index = match parent {
DisplayEntry::Single { index, .. } => Some(*index),
DisplayEntry::Paired { request_index, .. } => Some(*request_index),
_ => None,
};
if let Some(mi) = msg_index {
let fm_count = frontmatter_lines(&self.messages[mi], self.theme).len();
for detail_index in 0..fm_count {
lines.push(FlatLine::ScopeChild {
depth,
scope_parent_index,
inner: Box::new(FlatLine::Detail {
message_index: mi,
detail_index,
}),
});
}
if fm_count > 0 {
lines.push(FlatLine::ScopeChild {
depth,
scope_parent_index,
inner: Box::new(FlatLine::Separator),
});
}
}
}
/// Check whether a `DisplayEntry` matches a lowercased filter pattern.
fn entry_matches_filter(&self, entry: &DisplayEntry, pattern: &str) -> bool {
let plain = match entry {
DisplayEntry::Single { index, .. } => format_message_plain(&self.messages[*index]),
DisplayEntry::Paired {
request_index,
response_index,
..
} => format_pair_plain(
&self.messages[*request_index],
&self.messages[*response_index],
),
DisplayEntry::Collapsed {
start_index,
end_index,
count,
..
} => format_collapsed_plain(&self.messages, *start_index, *end_index, *count),
DisplayEntry::Scope {
parent,
children,
position,
} => format_scope_plain(parent, children.len(), *position, &self.messages),
};
plain.to_lowercase().contains(pattern)
}
/// Emit a `ScopeChild(MessageHeader)` with optional frontmatter detail lines.
fn emit_scope_child_message(
&self,
message_index: usize,
paired_response: Option<usize>,
depth: usize,
scope_parent_index: usize,
lines: &mut Vec<FlatLine>,
) {
lines.push(FlatLine::ScopeChild {
depth,
scope_parent_index,
inner: Box::new(FlatLine::MessageHeader {
message_index,
paired_response,
}),
});
if self.expanded.contains(&message_index) {
let msg = &self.messages[message_index];
let count = frontmatter_lines(msg, self.theme).len();
for detail_index in 0..count {
lines.push(FlatLine::ScopeChild {
depth,
scope_parent_index,
inner: Box::new(FlatLine::Detail {
message_index,
detail_index,
}),
});
}
}
}
/// Flatten scope children into `ScopeChild` flat lines.
///
/// Applies filtering and run collapse at depth before emitting lines.
fn flatten_scope_children(
&self,
children: &[DisplayEntry],
scope_parent_index: usize,
depth: usize,
lines: &mut Vec<FlatLine>,
) {
let lower_pattern = self.filter_pattern.as_ref().map(|p| p.to_lowercase());
let owned: Vec<DisplayEntry> = lower_pattern.as_ref().map_or_else(
|| children.to_vec(),
|pat| {
children
.iter()
.filter(|c| self.entry_matches_filter(c, pat))
.cloned()
.collect()
},
);
let collapsed_children = run_collapse(owned, &self.messages);
for child in &collapsed_children {
match child {
DisplayEntry::Single { index, .. } => {
self.emit_scope_child_message(*index, None, depth, scope_parent_index, lines);
}
DisplayEntry::Paired {
request_index,
response_index,
..
} => {
self.emit_scope_child_message(
*request_index,
Some(*response_index),
depth,
scope_parent_index,
lines,
);
}
DisplayEntry::Collapsed {
start_index,
end_index,
count,
..
} => {
if self.expanded.contains(start_index) {
for idx in *start_index..=*end_index {
self.emit_scope_child_message(
idx,
None,
depth,
scope_parent_index,
lines,
);
}
} else {
lines.push(FlatLine::ScopeChild {
depth,
scope_parent_index,
inner: Box::new(FlatLine::CollapsedHeader {
start_index: *start_index,
end_index: *end_index,
count: *count,
}),
});
}
}
DisplayEntry::Scope {
parent: nested_parent,
children: nested_children,
position: nested_position,
} => {
let nested_child_count = nested_children.len();
let nested_key = child.expansion_index();
lines.push(FlatLine::ScopeChild {
depth,
scope_parent_index,
inner: Box::new(FlatLine::ScopeHeader {
parent: Rc::clone(nested_parent),
child_count: nested_child_count,
position: *nested_position,
expansion_key: nested_key,
}),
});
if self.expanded.contains(&nested_key) {
self.emit_scope_frontmatter(nested_parent, depth + 1, nested_key, lines);
self.flatten_scope_children(nested_children, nested_key, depth + 1, lines);
}
}
}
}
}
}
#[cfg(test)]
#[allow(
clippy::expect_used,
clippy::panic,
reason = "tests use expect/panic for readable assertions"
)]
mod tests {
use super::*;
use crate::config::IconConfig;
use crate::session::SessionMessage;
use crate::tui::icons::IconSet;
use crate::tui::panel::{PanelState, frontmatter_lines};
use crate::tui::theme::Theme;
fn test_theme() -> Theme {
Theme::new()
}
fn test_icons() -> IconSet {
IconSet::from_config(IconConfig::default())
}
fn make_message(r#type: &str, method: &str, server: &str) -> SessionMessage {
SessionMessage {
id: 0,
r#type: r#type.to_string(),
method: method.to_string(),
server: server.to_string(),
client: "catenary".to_string(),
request_id: None,
parent_id: None,
timestamp: chrono::Utc::now(),
payload: serde_json::json!({}),
}
}
fn make_non_collapsing_messages(n: usize) -> Vec<SessionMessage> {
(0..n)
.map(|i| make_message("hook", &format!("test-{i}"), "catenary"))
.collect()
}
fn make_message_with_payload(
r#type: &str,
method: &str,
server: &str,
payload: serde_json::Value,
) -> SessionMessage {
SessionMessage {
id: 0,
r#type: r#type.to_string(),
method: method.to_string(),
server: server.to_string(),
client: "catenary".to_string(),
request_id: None,
parent_id: None,
timestamp: chrono::Utc::now(),
payload,
}
}
fn make_hook_diag_message(file: &str, count: u64) -> SessionMessage {
make_message_with_payload(
"hook",
"post-tool",
"catenary",
serde_json::json!({
"file": file,
"count": count,
"preview": "\t:12:1 [error] rustc: something"
}),
)
}
fn make_message_with_id_parent(
id: i64,
r#type: &str,
method: &str,
server: &str,
request_id: Option<i64>,
parent_id: Option<i64>,
) -> SessionMessage {
SessionMessage {
id,
r#type: r#type.to_string(),
method: method.to_string(),
server: server.to_string(),
client: "catenary".to_string(),
request_id,
parent_id,
timestamp: chrono::Utc::now(),
payload: serde_json::json!({}),
}
}
#[test]
fn test_flat_lines_no_expansion() {
let theme = test_theme();
let icons = test_icons();
let mut panel = PanelState::new("test".to_string(), &theme, &icons);
let messages = make_non_collapsing_messages(5);
panel.load_messages(messages);
let flat = panel.flat_lines();
assert_eq!(flat.len(), 5);
for (i, fl) in flat.iter().enumerate() {
assert_eq!(
*fl,
FlatLine::MessageHeader {
message_index: i,
paired_response: None,
}
);
}
}
#[test]
fn test_flat_lines_one_expanded() {
let theme = test_theme();
let icons = test_icons();
let mut panel = PanelState::new("test".to_string(), &theme, &icons);
let messages = vec![
make_message("lsp", "initialized", "rust-analyzer"),
make_hook_diag_message("/src/lib.rs", 3),
make_message("mcp", "tools/list", "catenary"),
];
panel.load_messages(messages);
panel.expanded.insert(1);
let flat = panel.flat_lines();
let detail_count = frontmatter_lines(&panel.messages[1], &theme).len();
assert!(detail_count > 0, "hook diag message should have details");
assert_eq!(flat.len(), 3 + detail_count);
assert_eq!(
flat[0],
FlatLine::MessageHeader {
message_index: 0,
paired_response: None,
}
);
assert_eq!(
flat[1],
FlatLine::MessageHeader {
message_index: 1,
paired_response: None,
}
);
for i in 0..detail_count {
assert_eq!(
flat[2 + i],
FlatLine::Detail {
message_index: 1,
detail_index: i
}
);
}
assert_eq!(
flat[2 + detail_count],
FlatLine::MessageHeader {
message_index: 2,
paired_response: None,
}
);
}
#[test]
fn test_frontmatter_lines_paired_uses_request() {
// Expand a Paired entry. Detail lines should contain the request
// payload, not the response payload.
let theme = test_theme();
let icons = test_icons();
let mut req = SessionMessage {
id: 1,
r#type: "lsp".to_string(),
method: "textDocument/hover".to_string(),
server: "rust-analyzer".to_string(),
client: "catenary".to_string(),
request_id: None,
parent_id: None,
timestamp: chrono::Utc::now(),
payload: serde_json::json!({"params": {"uri": "file:///src/main.rs"}}),
};
req.request_id = None;
let resp = SessionMessage {
id: 2,
r#type: "lsp".to_string(),
method: "textDocument/hover".to_string(),
server: "rust-analyzer".to_string(),
client: "catenary".to_string(),
request_id: Some(1),
parent_id: None,
timestamp: chrono::Utc::now(),
payload: serde_json::json!({"result": {"contents": "fn main()"}}),
};
let mut panel = PanelState::new("test".to_string(), &theme, &icons);
panel.load_messages(vec![req, resp]);
// Expand the paired entry (request index = 0).
panel.expanded.insert(0);
let flat = panel.flat_lines();
// Collect all Detail line texts.
let detail_text: String = flat
.iter()
.filter_map(|fl| {
if let FlatLine::Detail {
message_index,
detail_index,
} = fl
{
let lines = frontmatter_lines(&panel.messages[*message_index], &theme);
lines.get(*detail_index).map(|line| {
line.spans
.iter()
.map(|s| s.content.as_ref())
.collect::<String>()
})
} else {
None
}
})
.collect();
assert!(
detail_text.contains("main.rs"),
"detail should contain request payload: {detail_text}"
);
assert!(
!detail_text.contains("fn main()"),
"detail should NOT contain response payload: {detail_text}"
);
}
#[test]
fn test_scope_flat_lines_collapsed() {
let theme = test_theme();
let icons = test_icons();
let messages = vec![
make_message_with_id_parent(1, "mcp", "tools/call", "catenary", None, None),
make_message_with_id_parent(
2,
"lsp",
"workspace/symbol",
"rust-analyzer",
None,
Some(1),
),
make_message_with_id_parent(3, "lsp", "workspace/symbol", "taplo", None, Some(1)),
];
let mut panel = PanelState::new("test".to_string(), &theme, &icons);
panel.load_messages(messages);
let flat = panel.flat_lines();
assert_eq!(flat.len(), 1, "collapsed scope should be 1 line: {flat:?}");
assert!(
matches!(flat[0], FlatLine::ScopeHeader { child_count: 2, .. }),
"should be ScopeHeader with 2 children: {:?}",
flat[0]
);
}
#[test]
fn test_scope_flat_lines_expanded() {
let theme = test_theme();
let icons = test_icons();
let messages = vec![
make_message_with_id_parent(1, "mcp", "tools/call", "catenary", None, None),
make_message_with_id_parent(
2,
"lsp",
"workspace/symbol",
"rust-analyzer",
None,
Some(1),
),
make_message_with_id_parent(3, "lsp", "workspace/symbol", "taplo", None, Some(1)),
];
let mut panel = PanelState::new("test".to_string(), &theme, &icons);
panel.load_messages(messages);
panel.expanded.insert(0);
let flat = panel.flat_lines();
assert_eq!(flat.len(), 3, "expanded scope should be 3 lines: {flat:?}");
assert!(
matches!(flat[0], FlatLine::ScopeHeader { .. }),
"first should be ScopeHeader"
);
assert!(
matches!(
flat[1],
FlatLine::ScopeChild {
depth: 1,
scope_parent_index: 0,
..
}
),
"second should be ScopeChild at depth 1: {:?}",
flat[1]
);
assert!(
matches!(
flat[2],
FlatLine::ScopeChild {
depth: 1,
scope_parent_index: 0,
..
}
),
"third should be ScopeChild at depth 1: {:?}",
flat[2]
);
}
fn make_message_with_id_parent_payload(
id: i64,
r#type: &str,
method: &str,
server: &str,
request_id: Option<i64>,
parent_id: Option<i64>,
payload: serde_json::Value,
) -> SessionMessage {
SessionMessage {
id,
r#type: r#type.to_string(),
method: method.to_string(),
server: server.to_string(),
client: "catenary".to_string(),
request_id,
parent_id,
timestamp: chrono::Utc::now(),
payload,
}
}
#[test]
fn test_scope_frontmatter_emission() {
// Scope parent with non-empty payload. Expand. Verify:
// ScopeHeader → ScopeChild(Detail)... → ScopeChild(Separator) → ScopeChild(MessageHeader).
let theme = test_theme();
let icons = test_icons();
let messages = vec![
make_message_with_id_parent_payload(
1,
"mcp",
"tools/call",
"catenary",
None,
None,
serde_json::json!({"params": {"name": "grep"}}),
),
make_message_with_id_parent(
2,
"lsp",
"workspace/symbol",
"rust-analyzer",
None,
Some(1),
),
];
let fm_count = frontmatter_lines(&messages[0], &theme).len();
assert!(fm_count > 0, "parent should have frontmatter lines");
let mut panel = PanelState::new("test".to_string(), &theme, &icons);
panel.load_messages(messages);
panel.expanded.insert(0); // expansion key = parent index
let flat = panel.flat_lines();
// Expected: ScopeHeader + fm_count Detail lines + 1 Separator + 1 child MessageHeader
let expected_len = 1 + fm_count + 1 + 1;
assert_eq!(
flat.len(),
expected_len,
"expected {expected_len} lines (1 header + {fm_count} frontmatter + 1 separator + 1 child): {flat:?}"
);
assert!(matches!(flat[0], FlatLine::ScopeHeader { .. }));
// Frontmatter detail lines
for i in 0..fm_count {
assert!(
matches!(
&flat[1 + i],
FlatLine::ScopeChild { inner, .. }
if matches!(inner.as_ref(), FlatLine::Detail { .. })
),
"line {} should be ScopeChild(Detail): {:?}",
1 + i,
flat[1 + i]
);
}
// Separator
assert!(
matches!(
&flat[1 + fm_count],
FlatLine::ScopeChild { inner, .. }
if matches!(inner.as_ref(), FlatLine::Separator)
),
"line {} should be ScopeChild(Separator): {:?}",
1 + fm_count,
flat[1 + fm_count]
);
// Child message header
assert!(
matches!(
&flat[2 + fm_count],
FlatLine::ScopeChild { inner, .. }
if matches!(inner.as_ref(), FlatLine::MessageHeader { .. })
),
"last line should be ScopeChild(MessageHeader): {:?}",
flat[2 + fm_count]
);
}
#[test]
fn test_scope_frontmatter_empty_payload() {
// Scope parent with empty payload — no frontmatter or separator.
let theme = test_theme();
let icons = test_icons();
let messages = vec![
make_message_with_id_parent(1, "mcp", "tools/call", "catenary", None, None),
make_message_with_id_parent(
2,
"lsp",
"workspace/symbol",
"rust-analyzer",
None,
Some(1),
),
make_message_with_id_parent(3, "lsp", "workspace/symbol", "taplo", None, Some(1)),
];
let mut panel = PanelState::new("test".to_string(), &theme, &icons);
panel.load_messages(messages);
panel.expanded.insert(0);
let flat = panel.flat_lines();
// ScopeHeader + 2 children, no frontmatter or separator
assert_eq!(
flat.len(),
3,
"empty payload scope should have no frontmatter: {flat:?}"
);
assert!(matches!(flat[0], FlatLine::ScopeHeader { .. }));
// No Separator anywhere
let has_separator = flat.iter().any(|fl| {
matches!(fl, FlatLine::ScopeChild { inner, .. } if matches!(inner.as_ref(), FlatLine::Separator))
});
assert!(
!has_separator,
"empty payload scope should have no separator"
);
}
#[test]
fn test_separator_in_flat_lines() {
// Verify Separator appears between last frontmatter Detail and first child.
let theme = test_theme();
let icons = test_icons();
let messages = vec![
make_message_with_id_parent_payload(
1,
"mcp",
"tools/call",
"catenary",
None,
None,
serde_json::json!({"params": {"name": "glob"}}),
),
make_message_with_id_parent(
2,
"lsp",
"workspace/symbol",
"rust-analyzer",
None,
Some(1),
),
make_message_with_id_parent(3, "lsp", "workspace/symbol", "taplo", None, Some(1)),
];
let fm_count = frontmatter_lines(&messages[0], &theme).len();
assert!(fm_count > 0, "parent should have frontmatter");
let mut panel = PanelState::new("test".to_string(), &theme, &icons);
panel.load_messages(messages);
panel.expanded.insert(0);
let flat = panel.flat_lines();
// Find the separator
let sep_idx = flat.iter().position(|fl| {
matches!(fl, FlatLine::ScopeChild { inner, .. } if matches!(inner.as_ref(), FlatLine::Separator))
});
assert!(sep_idx.is_some(), "should have a separator: {flat:?}");
let sep_idx = sep_idx.expect("checked above");
// Line before separator should be a Detail
assert!(
matches!(
&flat[sep_idx - 1],
FlatLine::ScopeChild { inner, .. }
if matches!(inner.as_ref(), FlatLine::Detail { .. })
),
"line before separator should be Detail: {:?}",
flat[sep_idx - 1]
);
// Line after separator should be a MessageHeader (first child)
assert!(
matches!(
&flat[sep_idx + 1],
FlatLine::ScopeChild { inner, .. }
if matches!(inner.as_ref(), FlatLine::MessageHeader { .. })
),
"line after separator should be MessageHeader: {:?}",
flat[sep_idx + 1]
);
}
// ── Run collapse at depth tests ─────────────────────────────────────
fn make_progress_with_parent(id: i64, server: &str, parent_id: i64) -> SessionMessage {
SessionMessage {
id,
r#type: "lsp".to_string(),
method: "$/progress".to_string(),
server: server.to_string(),
client: "catenary".to_string(),
request_id: None,
parent_id: Some(parent_id),
timestamp: chrono::Utc::now(),
payload: serde_json::json!({"token": "ra/indexing"}),
}
}
#[test]
fn test_run_collapse_at_depth_progress() {
// Scope with a non-collapsing child + 10 same-token progress children.
// Expand scope. Progress children collapse into a single CollapsedHeader.
let theme = test_theme();
let icons = test_icons();
let mut messages = vec![
make_message_with_id_parent(1, "mcp", "tools/call", "catenary", None, None),
// Non-collapsing child (hook → collapse_key = None).
make_message_with_id_parent(2, "hook", "PreToolUse", "catenary", None, Some(1)),
];
for i in 0..10 {
messages.push(make_progress_with_parent(10 + i, "rust-analyzer", 1));
}
let mut panel = PanelState::new("test".to_string(), &theme, &icons);
panel.load_messages(messages);
// Expansion key = parent index = 0.
panel.expanded.insert(0);
let flat = panel.flat_lines();
// ScopeHeader + hook child + 1 CollapsedHeader (10 progress tokens).
assert_eq!(
flat.len(),
3,
"10 same-key progress should collapse: {flat:?}"
);
assert!(
matches!(flat[0], FlatLine::ScopeHeader { .. }),
"first should be ScopeHeader: {:?}",
flat[0]
);
assert!(
matches!(
&flat[2],
FlatLine::ScopeChild {
depth: 1,
inner,
..
} if matches!(inner.as_ref(), FlatLine::CollapsedHeader { count: 10, .. })
),
"third should be ScopeChild(CollapsedHeader(10)): {:?}",
flat[2]
);
}
#[test]
fn test_run_collapse_at_depth_mixed() {
// Scope: adjacent req/resp pair, 5 progress tokens, another pair.
// Expand scope. Verify: Paired, Collapsed(5), Paired.
let theme = test_theme();
let icons = test_icons();
let messages = vec![
// Scope parent
make_message_with_id_parent(1, "mcp", "tools/call", "catenary", None, None),
// Adjacent pair 1
make_message_with_id_parent(
2,
"lsp",
"textDocument/hover",
"rust-analyzer",
None,
Some(1),
),
make_message_with_id_parent(
3,
"lsp",
"textDocument/hover",
"rust-analyzer",
Some(2),
Some(1),
),
// 5 progress tokens
make_progress_with_parent(4, "rust-analyzer", 1),
make_progress_with_parent(5, "rust-analyzer", 1),
make_progress_with_parent(6, "rust-analyzer", 1),
make_progress_with_parent(7, "rust-analyzer", 1),
make_progress_with_parent(8, "rust-analyzer", 1),
// Adjacent pair 2
make_message_with_id_parent(
9,
"lsp",
"textDocument/definition",
"rust-analyzer",
None,
Some(1),
),
make_message_with_id_parent(
10,
"lsp",
"textDocument/definition",
"rust-analyzer",
Some(9),
Some(1),
),
];
let mut panel = PanelState::new("test".to_string(), &theme, &icons);
panel.load_messages(messages);
// Expansion key = parent index.
panel.expanded.insert(0);
let flat = panel.flat_lines();
// ScopeHeader + Paired + Collapsed(5) + Paired = 4 lines.
assert_eq!(
flat.len(),
4,
"expected header + pair + collapsed + pair: {flat:?}"
);
// Line 1: Paired (hover)
assert!(
matches!(
&flat[1],
FlatLine::ScopeChild { inner, .. }
if matches!(inner.as_ref(), FlatLine::MessageHeader { paired_response: Some(_), .. })
),
"line 1 should be paired: {:?}",
flat[1]
);
// Line 2: Collapsed(5 progress)
assert!(
matches!(
&flat[2],
FlatLine::ScopeChild { inner, .. }
if matches!(inner.as_ref(), FlatLine::CollapsedHeader { count: 5, .. })
),
"line 2 should be collapsed(5): {:?}",
flat[2]
);
// Line 3: Paired (definition)
assert!(
matches!(
&flat[3],
FlatLine::ScopeChild { inner, .. }
if matches!(inner.as_ref(), FlatLine::MessageHeader { paired_response: Some(_), .. })
),
"line 3 should be paired: {:?}",
flat[3]
);
}
#[test]
fn test_pair_merge_at_depth() {
// Scope with 2 adjacent messages forming a req/resp pair.
// Expand scope. Children show 1 paired line.
let theme = test_theme();
let icons = test_icons();
let messages = vec![
make_message_with_id_parent(1, "mcp", "tools/call", "catenary", None, None),
make_message_with_id_parent(
2,
"lsp",
"textDocument/hover",
"rust-analyzer",
None,
Some(1),
),
make_message_with_id_parent(
3,
"lsp",
"textDocument/hover",
"rust-analyzer",
Some(2),
Some(1),
),
];
let mut panel = PanelState::new("test".to_string(), &theme, &icons);
panel.load_messages(messages);
panel.expanded.insert(0);
let flat = panel.flat_lines();
// ScopeHeader + 1 Paired child.
assert_eq!(flat.len(), 2, "expected header + 1 paired child: {flat:?}");
assert!(
matches!(
&flat[1],
FlatLine::ScopeChild {
depth: 1,
inner,
..
} if matches!(
inner.as_ref(),
FlatLine::MessageHeader { message_index: 1, paired_response: Some(2) }
)
),
"child should be paired(1, 2): {:?}",
flat[1]
);
}
#[test]
fn test_nested_collapse_expansion() {
// Scope with a non-collapsing child + 10 same-key children → collapsed
// run. Expand scope, then expand the collapsed run. Individual messages
// appear at same depth, replacing the collapsed header.
let theme = test_theme();
let icons = test_icons();
let mut messages = vec![
make_message_with_id_parent(1, "mcp", "tools/call", "catenary", None, None),
make_message_with_id_parent(2, "hook", "PreToolUse", "catenary", None, Some(1)),
];
for i in 0..10 {
messages.push(make_progress_with_parent(10 + i, "rust-analyzer", 1));
}
let mut panel = PanelState::new("test".to_string(), &theme, &icons);
panel.load_messages(messages);
// Expand scope (parent index = 0).
panel.expanded.insert(0);
let flat = panel.flat_lines();
assert_eq!(flat.len(), 3, "scope + hook child + collapsed run");
// Expand the collapsed run.
let collapsed_start = match &flat[2] {
FlatLine::ScopeChild { inner, .. } => match inner.as_ref() {
FlatLine::CollapsedHeader { start_index, .. } => *start_index,
other => panic!("expected CollapsedHeader, got {other:?}"),
},
other => panic!("expected ScopeChild, got {other:?}"),
};
panel.expanded.insert(collapsed_start);
let flat = panel.flat_lines();
// Count MessageHeader children — should be 11 (hook + 10 progress).
let msg_header_count = flat
.iter()
.filter(|fl| {
matches!(
fl,
FlatLine::ScopeChild { depth: 1, inner, .. }
if matches!(inner.as_ref(), FlatLine::MessageHeader { .. })
)
})
.count();
assert_eq!(
msg_header_count, 11,
"expanded run should show hook child + 10 individual messages: {flat:?}"
);
// No CollapsedHeader remains.
let has_collapsed = flat.iter().any(|fl| {
matches!(
fl,
FlatLine::ScopeChild { inner, .. }
if matches!(inner.as_ref(), FlatLine::CollapsedHeader { .. })
)
});
assert!(
!has_collapsed,
"expanded run should have no CollapsedHeader: {flat:?}"
);
}
#[test]
fn test_filter_at_depth() {
// Scope with children from 3 servers (interleaved). Filter on
// one server. Expand scope. Non-matching children hidden,
// remaining same-server entries run-collapsed.
//
// Tool name includes "rust-analyzer" so the scope header
// passes the root-level filter too.
let theme = test_theme();
let icons = test_icons();
let messages = vec![
make_message_with_id_parent_payload(
1,
"mcp",
"tools/call",
"catenary",
None,
None,
serde_json::json!({"params": {"name": "search-rust-analyzer"}}),
),
// Interleaved: ra, taplo, ts, ra, taplo, ts
make_message_with_id_parent(
2,
"lsp",
"workspace/symbol",
"rust-analyzer",
None,
Some(1),
),
make_message_with_id_parent(3, "lsp", "workspace/symbol", "taplo", None, Some(1)),
make_message_with_id_parent(4, "lsp", "workspace/symbol", "ts-server", None, Some(1)),
make_message_with_id_parent(
5,
"lsp",
"workspace/symbol",
"rust-analyzer",
None,
Some(1),
),
make_message_with_id_parent(6, "lsp", "workspace/symbol", "taplo", None, Some(1)),
make_message_with_id_parent(7, "lsp", "workspace/symbol", "ts-server", None, Some(1)),
];
let mut panel = PanelState::new("test".to_string(), &theme, &icons);
panel.load_messages(messages);
panel.filter_pattern = Some("rust-analyzer".to_string());
panel.expanded.insert(0);
let flat = panel.flat_lines();
// Should contain exactly one CollapsedHeader with count 2
// (the two rust-analyzer entries). Other lines are frontmatter.
let collapsed: Vec<_> = flat
.iter()
.filter(|fl| {
matches!(
fl,
FlatLine::ScopeChild { inner, .. }
if matches!(inner.as_ref(), FlatLine::CollapsedHeader { .. })
)
})
.collect();
assert_eq!(
collapsed.len(),
1,
"should have exactly 1 collapsed run: {flat:?}"
);
assert!(
matches!(
collapsed[0],
FlatLine::ScopeChild { inner, .. }
if matches!(inner.as_ref(), FlatLine::CollapsedHeader { count: 2, .. })
),
"should be collapsed(2): {:?}",
collapsed[0]
);
// No individual MessageHeader children (all filtered non-ra entries
// removed, remaining ra entries collapsed).
let has_msg_headers = flat.iter().any(|fl| {
matches!(
fl,
FlatLine::ScopeChild { inner, .. }
if matches!(inner.as_ref(), FlatLine::MessageHeader { .. })
)
});
assert!(
!has_msg_headers,
"no individual MessageHeaders expected: {flat:?}"
);
}
#[test]
fn test_depth_indentation() {
// Scope with children. Expand scope. Render panel. Verify
// depth-1 children render with 4-space indent in the output.
use ratatui::Terminal;
use ratatui::backend::TestBackend;
let theme = test_theme();
let icons = test_icons();
let messages = vec![
{
let mut m =
make_message_with_id_parent(1, "mcp", "tools/call", "catenary", None, None);
m.payload = serde_json::json!({"params": {"name": "grep"}});
m
},
make_message_with_id_parent(
2,
"lsp",
"workspace/symbol",
"rust-analyzer",
None,
Some(1),
),
];
let mut panel = PanelState::new("test1234".to_string(), &theme, &icons);
panel.load_messages(messages);
panel.expanded.insert(0);
let backend = TestBackend::new(80, 20);
let mut terminal = Terminal::new(backend).expect("terminal creation");
terminal
.draw(|f| {
let area = f.area();
crate::tui::panel::render_panel(&panel, area, f.buffer_mut(), true);
})
.expect("draw");
let buf = terminal.backend().buffer().clone();
// Find the scope header row (contains "children") and the child
// row (contains "workspace/symbol"). The child should be indented
// 4+ spaces beyond the header.
let mut header_indent = None;
let mut child_indent = None;
for y in 0..buf.area.height {
let mut row = String::new();
for x in 0..buf.area.width {
row.push_str(buf[(x, y)].symbol());
}
if header_indent.is_none() && row.contains("child") {
let leading = row.len() - row.trim_start().len();
header_indent = Some(leading);
} else if child_indent.is_none() && row.contains("workspace/symbol") {
let leading = row.len() - row.trim_start().len();
child_indent = Some(leading);
}
}
let header_indent = header_indent.expect("should find scope header row");
let child_indent = child_indent.expect("should find child row");
assert!(
child_indent >= header_indent + 4,
"child should be indented 4+ spaces beyond header: header={header_indent}, child={child_indent}"
);
}
}