synaps-tui 0.6.1

Terminal UI layer โ€” ratatui, crossterm, syntect, tachyonfx
Documentation
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
use synaps_cli::Session;
use synaps_cli::pricing::calculate_cost_optional_split;

// Type re-export shims from slice (a). Kept this release โ€” deleting is churn
// for no gain. One-release grace per design ยง5(f).
// TODO(P9-followup): drop re-exports; callers should import from transcript directly.
pub(crate) use super::transcript::{ChatMessage, TranscriptStore, THINKING_PLACEHOLDER};
// Test-only re-exports: production code reaches the cache via store methods;
// only ported cache tests name these types directly.
#[allow(unused_imports)]
pub(crate) use super::transcript::{CacheState, LineCache, MsgSlot, RenderCtx};
#[allow(unused_imports)]
pub(crate) use super::transcript::TimestampedMsg;

/// Central TUI state.
///
/// T199.2 boundary: `App` is **loop state**, not render input. The render
/// builder ([`super::draw::build_render_model`]) never takes `App`; it takes
/// [`super::view_model::ViewInputs`], which names the exact render-input
/// subset of these fields (input/chrome, session totals, panes, modal
/// projections). Fields NOT in `ViewInputs` โ€” per-turn accounting, history/
/// paste/tab bookkeeping, channel endpoints, async task handles โ€” are
/// invisible to the renderer by construction. Builder-requested mutations
/// come back as a [`super::view_model::RenderPatch`].
pub(crate) struct App {
    pub(crate) transcript: TranscriptStore,
    pub(crate) input: String,
    /// Cursor position as a **char index** (not byte index).
    /// Use `cursor_byte_pos()` to convert to byte offset for String operations.
    pub(crate) cursor_pos: usize,
    pub(crate) api_messages: Vec<synaps_cli::SharedMessage>,
    pub(crate) streaming: bool,
    pub(crate) input_history: Vec<String>,
    pub(crate) history_index: Option<usize>,
    pub(crate) input_stash: String,
    /// Tab-completion cycle state for slash commands.
    /// `Some((prefix, index, matching_commands))` when the user is cycling
    /// through matches via repeated Tab; cleared on any non-Tab keypress.
    /// See input.rs::handle_tab_complete.
    pub(crate) tab_cycle: Option<(String, usize, Vec<String>)>,
    pub(crate) input_tokens: u64,
    pub(crate) output_tokens: u64,
    pub(crate) total_input_tokens: u64,
    pub(crate) total_output_tokens: u64,
    pub(crate) total_cache_read_tokens: u64,
    pub(crate) total_cache_creation_tokens: u64,
    /// Per-TTL-bucket accumulators for cache writes.  Populated by
    /// `add_usage` when the API returns the 5m/1h split in `SessionEvent::Usage`.
    /// Zero when no split has arrived (e.g. cache_ttl=default, no writes yet).
    pub(crate) total_cache_write_5m: u64,
    pub(crate) total_cache_write_1h: u64,
    /// Most recent turn's actual context occupancy (what the API ingested
    /// this request): uncached input + cache read + cache creation. Unlike
    /// `total_*_tokens` which accumulate for cost tracking, this is reassigned
    /// every turn and reflects the current per-request context window use.
    /// Used by the context-usage bar in `draw.rs`.
    pub(crate) last_turn_context: u64,
    /// Context window size (in tokens) of the model that answered the most
    /// recent turn. Updated alongside `last_turn_context` so the bar's
    /// denominator adapts when users switch models mid-session. See
    /// `synaps_cli::models::context_window_for_model`.
    pub(crate) last_turn_context_window: u64,
    api_call_count: u32, // private: accounting, used only within app.rs
    pub(crate) session_cost: f64,
    pub(crate) session: Session,
    pub(crate) agent_name: String,
    pub(crate) needs_redraw: bool,
    /// When set, the next repaint bypasses the streaming redraw throttle.
    /// Set by user input (scroll/typing/cursor) so interaction stays instant
    /// even while the model is streaming; cleared after the paint.
    pub(crate) force_redraw: bool,
    pub(crate) logo_dismiss_t: Option<f64>,
    pub(crate) logo_build_t: Option<f64>,
    /// Active subagent status for the live panel
    pub(crate) subagents: Vec<SubagentState>,
    /// Counter for unique subagent IDs within a session
    /// Saved context from an aborted response โ€” injected into the next user message
    pub(crate) abort_context: Option<String>,
    /// Message queued while streaming โ€” auto-sent when current response finishes
    pub(crate) queued_message: Option<String>,
    /// Tracks paste state: snapshot of input before first paste, and total pasted char count
    pub(crate) input_before_paste: Option<String>,
    pub(crate) pasted_char_count: usize,
    /// Spinner frame counter (incremented on tick)
    pub(crate) spinner_frame: usize,
    /// Transient status text shown in the header bar (auto-cleared when streaming starts)
    pub(crate) status_text: Option<String>,
    /// GamblersDen child process โ€” spawned by /gamba, killed when streaming finishes
    pub(crate) gamba_child: Option<std::process::Child>,
    /// Active settings modal state (Some while /settings is open).
    pub(crate) settings: Option<super::settings::SettingsState>,
    /// Active plugins modal state (Some while /plugins is open).
    pub(crate) plugins: Option<super::plugins::PluginsModalState>,
    /// Active models router modal state (Some while /model or /models is open).
    pub(crate) models: Option<super::models::ModelsModalState>,
    /// Active /help find lightbox state.
    pub(crate) help_find: Option<synaps_cli::help::HelpFindState>,
    /// P7 modal-routing stack (finished, P7.8). The single source of input
    /// routing: `input.rs` dispatches on `modal_stack.top()`, one arm per
    /// `PaneId`. It is an *index over* the `Option<โ€ฆState>` modal fields above
    /// (+ the `secret_prompts` queue), never a new owner (ยง6). Every open/close
    /// site pushes/pops in lock-step; membership is cross-checked against the
    /// backing fields by `debug_assert_stack_sync`. Empty โ‡’ `top()` is
    /// `PaneId::Chat` โ‡’ input goes to the base chat pane.
    pub(crate) modal_stack: super::focus::ModalStack,
    /// P7.8 secret-prompt queue โ€” folded onto App from the `run()` local
    /// (ยง5). Drained from the mpsc channel via `poll_requests` in the tick
    /// arm; `is_active()` is mirrored by `modal_stack.contains(SecretPrompt)`
    /// via `reconcile_secret_prompt` (asserted by `debug_assert_stack_sync`).
    pub(crate) secret_prompts: synaps_cli::tools::SecretPromptQueue,
    /// Background compaction task โ€” polled in the event loop so /compact doesn't block.
    pub(crate) compact_task: Option<tokio::task::JoinHandle<Result<String, synaps_cli::error::RuntimeError>>>,
    /// Events buffered during streaming โ€” injected into api_messages after stream completes
    pub(crate) pending_events: Vec<String>,
    /// Consecutive auto-triggered model turns since the last real user send.
    /// Incremented by the event-reactor wake path; reset on Submit / queued user message.
    /// When this reaches AUTO_TURN_CAP the reactor parks and shows a system message.
    pub(crate) consecutive_auto_turns: u32,
    /// Cached model ping results: "provider/model" -> (status, latency_ms).
    pub(crate) model_health: std::collections::HashMap<String, (synaps_cli::runtime::openai::ping::PingStatus, u64)>,
    /// Print ping results to chat as they arrive (set by /ping command).
    pub(crate) ping_print: bool,
    pub(crate) ping_pending: usize,
    /// Channel for receiving async ping results.
    pub(crate) ping_tx: tokio::sync::mpsc::UnboundedSender<(String, synaps_cli::runtime::openai::ping::PingStatus, u64)>,
    pub(crate) ping_rx: tokio::sync::mpsc::UnboundedReceiver<(String, synaps_cli::runtime::openai::ping::PingStatus, u64)>,
    /// Channel for receiving expanded model-list API results.
    pub(crate) model_list_tx: tokio::sync::mpsc::UnboundedSender<(String, Result<Vec<super::models::ExpandedModelEntry>, String>)>,
    pub(crate) model_list_rx: tokio::sync::mpsc::UnboundedReceiver<(String, Result<Vec<super::models::ExpandedModelEntry>, String>)>,
    /// Suppress paste events arriving shortly after a right-click copy/paste.
    /// Terminals that auto-paste on right-click generate a spurious Event::Paste
    /// immediately after MouseDown(Right). We suppress only within a short TTL
    /// window (~150ms) to avoid eating legitimate Ctrl+V pastes.
    pub(crate) suppress_paste_until: Option<std::time::Instant>,
    /// Active sidecar instances keyed by plugin id (manifest name).
    ///
    /// Phase 8 8B: replaces the legacy single `Option<SidecarUiState>` so
    /// multiple plugin-claimed sidecars can be hosted concurrently.
    pub(crate) sidecars: std::collections::HashMap<String, super::sidecar::SidecarUiState>,
    /// Generic extension-provided active tasks rendered in the sticky progress area.
    /// Stored behind `Arc` so the per-frame snapshot is a refcount bump, not a deep clone.
    pub(crate) active_tasks: std::sync::Arc<synaps_cli::extensions::active_tasks::ActiveTasks>,
    /// Overlay toast provider used by core and extension-adjacent features.
    pub(crate) toasts: super::toast::ToastProvider,
    /// Channel for async extension loader progress events.
    pub(crate) extension_loader_rx: tokio::sync::mpsc::UnboundedReceiver<synaps_cli::extensions::loader::ExtensionLoaderEvent>,
    pub(crate) extension_loader_tx: tokio::sync::mpsc::UnboundedSender<synaps_cli::extensions::loader::ExtensionLoaderEvent>,
    pub(crate) extension_loader_running: bool,
    /// Channel for receiving widget events from background extension notification watchers.
    pub(crate) widget_rx: tokio::sync::mpsc::UnboundedReceiver<synaps_cli::extensions::widgets::ExtensionWidgetEvent>,
    pub(crate) widget_tx: tokio::sync::mpsc::UnboundedSender<synaps_cli::extensions::widgets::ExtensionWidgetEvent>,
    /// Live keybind registry โ€” held so /settings can hot-swap plugin toggle keys.
    pub(crate) keybinds: Option<std::sync::Arc<std::sync::RwLock<synaps_cli::skills::keybinds::KeybindRegistry>>>,
    /// Injectable clock (P6.2). Real in production, Test in the harness so
    /// time-dependent state (toast expiry, tool timers) stays deterministic.
    pub(crate) clock: super::clock::TuiClock,
}

pub(crate) const SPINNER_FRAMES: &[&str] = &["โ ‹", "โ ™", "โ น", "โ ธ", "โ ผ", "โ ด", "โ ฆ", "โ ง", "โ ‡", "โ "];


#[derive(Clone)]
pub(crate) struct SubagentState {
    pub(crate) id: u64,
    pub(crate) name: String,
    pub(crate) status: String,
    pub(crate) start_time: std::time::Instant,
    pub(crate) done: bool,
    pub(crate) duration_secs: Option<f64>,
    /// Stamped when this entry transitions to done โ€” drives the 5s flash expiry.
    pub(crate) done_at: Option<std::time::Instant>,
}

impl App {
    /// Test-only convenience constructor: production-equivalent App backed by
    /// the real system clock. Production code uses `new_with_clock` directly.
    #[cfg(test)]
    pub(crate) fn new(session: Session) -> Self {
        Self::new_with_clock(session, super::clock::TuiClock::real())
    }

    /// Construct an App with an explicit clock (P6.2). `run()` passes
    /// `TuiClock::real()`; the harness passes `TuiClock::test()`.
    pub(crate) fn new_with_clock(session: Session, clock: super::clock::TuiClock) -> Self {
        let (ping_tx_init, ping_rx_init) = tokio::sync::mpsc::unbounded_channel();
        let (model_list_tx_init, model_list_rx_init) = tokio::sync::mpsc::unbounded_channel();
        let (extension_loader_tx_init, extension_loader_rx_init) = tokio::sync::mpsc::unbounded_channel();
        let (widget_tx_init, widget_rx_init) = tokio::sync::mpsc::unbounded_channel();
        Self {
            transcript: TranscriptStore::new(clock.clone()),
            input: String::new(),
            cursor_pos: 0,
            api_messages: Vec::new(),
            streaming: false,
            input_history: Vec::new(),
            history_index: None,
            input_stash: String::new(),
            tab_cycle: None,
            input_tokens: 0,
            output_tokens: 0,
            total_input_tokens: 0,
            total_output_tokens: 0,
            total_cache_read_tokens: 0,
            total_cache_creation_tokens: 0,
            total_cache_write_5m: 0,
            total_cache_write_1h: 0,
            last_turn_context: 0,
            last_turn_context_window: synaps_cli::models::context_window_for_model(
                synaps_cli::models::default_model(),
            ),
            api_call_count: 0,
            session_cost: 0.0,
            session,
            agent_name: synaps_cli::config::load_config()
                .agent_name
                .unwrap_or_else(|| "agent".to_string()),
            needs_redraw: true,
            force_redraw: false,
            logo_dismiss_t: None,
            logo_build_t: Some(0.0),
            subagents: Vec::new(),
            abort_context: None,
            queued_message: None,
            input_before_paste: None,
            pasted_char_count: 0,
            spinner_frame: 0,
            status_text: None,
            gamba_child: None,
            settings: None,
            plugins: None,
            models: None,
            help_find: None,
            // P7.3: wired but starts EMPTY โ€” pure no-op until P7.4 migrates a modal.
            modal_stack: super::focus::ModalStack::new(),
            // P7.8: folded off the `run()` local; production wires the mpsc
            // channel separately (mod.rs). Starts empty (no active prompt).
            secret_prompts: synaps_cli::tools::SecretPromptQueue::new(),
            compact_task: None,
            pending_events: Vec::new(),
            consecutive_auto_turns: 0,
            model_health: std::collections::HashMap::new(),
            ping_print: false,
            ping_pending: 0,
            ping_tx: ping_tx_init,
            ping_rx: ping_rx_init,
            model_list_tx: model_list_tx_init,
            model_list_rx: model_list_rx_init,
            suppress_paste_until: None,
            sidecars: std::collections::HashMap::new(),
            active_tasks: std::sync::Arc::new(synaps_cli::extensions::active_tasks::ActiveTasks::new()),
            toasts: super::toast::ToastProvider::new(clock.clone()),
            extension_loader_rx: extension_loader_rx_init,
            extension_loader_tx: extension_loader_tx_init,
            extension_loader_running: false,
            widget_rx: widget_rx_init,
            widget_tx: widget_tx_init,
            keybinds: None,
            clock,
        }
    }
    /// Build the text shown in the chat transcript for a submitted user message.
    /// Large pasted payloads are collapsed to a label, while any text typed before
    /// or after the pasted range remains visible.
    pub(crate) fn user_display_text_for_submission(&self, input: &str) -> String {
        if self.pasted_char_count == 0 {
            return input.to_string();
        }

        let before_paste = self.input_before_paste.as_deref().unwrap_or("");
        let before_chars = before_paste.chars().count();
        let total_chars = input.chars().count();
        let paste_chars = self.pasted_char_count.min(total_chars.saturating_sub(before_chars));
        let after_chars = total_chars.saturating_sub(before_chars + paste_chars);

        let paste_byte_start = input
            .char_indices()
            .nth(before_chars)
            .map(|(i, _)| i)
            .unwrap_or(input.len());
        let paste_byte_end = input
            .char_indices()
            .nth(before_chars + paste_chars)
            .map(|(i, _)| i)
            .unwrap_or(input.len());

        let pasted = &input[paste_byte_start..paste_byte_end];
        let after_paste = if after_chars == 0 {
            ""
        } else {
            &input[paste_byte_end..]
        };

        let line_count = pasted.lines().count();
        let paste_label = if line_count > 1 {
            format!("[Pasted {} lines]", line_count)
        } else {
            format!("[Pasted {} chars]", paste_chars)
        };

        match (before_paste.is_empty(), after_paste.is_empty()) {
            (true, true) => paste_label,
            (false, true) => format!("{} {}", before_paste.trim(), paste_label),
            (true, false) => format!("{} {}", paste_label, after_paste.trim()),
            (false, false) => format!(
                "{} {} {}",
                before_paste.trim(),
                paste_label,
                after_paste.trim()
            ),
        }
    }

    /// Restore SynapsCLI's TUI after casino (or failed spawn).
    /// Convert char-based cursor_pos to byte offset in self.input.
    pub(crate) fn cursor_byte_pos(&self) -> usize {
        self.input.char_indices()
            .nth(self.cursor_pos)
            .map(|(i, _)| i)
            .unwrap_or(self.input.len())
    }

    /// Number of chars in self.input (for bounds checking cursor_pos).
    pub(crate) fn input_char_count(&self) -> usize {
        self.input.chars().count()
    }

    /// Calculate the number of visual lines the input needs, given an inner width.
    /// Returns (total_lines, cursor_row, cursor_col) for layout and cursor placement.
    ///
    pub(crate) async fn save_session(&mut self) {
        if self.api_messages.is_empty() {
            return;
        }
        self.session.api_messages = self.api_messages.clone();
        self.session.total_input_tokens = self.total_input_tokens;
        self.session.total_output_tokens = self.total_output_tokens;
        self.session.session_cost = self.session_cost;
        self.session.abort_context = self.abort_context.clone();
        self.session.updated_at = chrono::Utc::now();
        self.session.auto_title();
        if let Err(e) = self.session.save().await {
            eprintln!("\x1b[31m[ERROR] Failed to save session: {}\x1b[0m", e);
        }
    }

    #[allow(clippy::too_many_arguments)]
    pub(crate) fn add_usage(
        &mut self,
        input_tokens: u64,
        output_tokens: u64,
        cache_read: u64,
        cache_creation: u64,
        cache_creation_5m: Option<u64>,
        cache_creation_1h: Option<u64>,
        model: &str,
        context_window_override: Option<u64>,
    ) {
        self.input_tokens = input_tokens;
        self.output_tokens = output_tokens;
        self.total_input_tokens += input_tokens;
        self.total_output_tokens += output_tokens;
        self.total_cache_read_tokens += cache_read;
        self.total_cache_creation_tokens += cache_creation;
        // Accumulate per-TTL-bucket write totals for /stats and footer display.
        if let Some(c5) = cache_creation_5m { self.total_cache_write_5m += c5; }
        if let Some(c1) = cache_creation_1h { self.total_cache_write_1h += c1; }
        // Per-turn context occupancy (bar numerator): what the API actually
        // ingested this request. Output tokens are generated, not ingested,
        // so they don't count toward current-window use. Reassigned, not accumulated.
        self.last_turn_context = input_tokens + cache_read + cache_creation;
        // Per-turn bar denominator โ€” the context window of the model that
        // answered this turn. Tracked alongside so mid-session model swaps
        // (e.g. main thread Opus โ†’ subagent Sonnet) recalibrate the bar.
        // If the user configured an explicit context_window, honour it.
        self.last_turn_context_window = context_window_override
            .unwrap_or_else(|| synaps_cli::models::context_window_for_model(model));
        self.api_call_count += 1;
        // Delegate cost calculation to the single source of truth in `pricing`.
        // Split-aware: 1h cache writes bill at 2.0x when the TTL split arrived.
        self.session_cost += calculate_cost_optional_split(
            model, input_tokens, output_tokens, cache_read,
            cache_creation, cache_creation_5m, cache_creation_1h,
        );
    }

    // โ”€โ”€ Slice (bโ€ฒ) delegating wrappers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    //
    // Content mutations, tool routing, and the invalidate family moved to
    // TranscriptStore (transcript.rs). These wrappers keep identical
    // signatures so call sites don't churn (locked decision #3); redraw
    // signaling (`needs_redraw`) stays here on App.

    pub(crate) fn push_msg(&mut self, msg: ChatMessage) {
        self.transcript.push_msg(msg);
        self.needs_redraw = true;
    }

    /// Delegates to [`TranscriptStore::cap_resumed_display`]. Note: does not
    /// signal a redraw โ€” verbatim-preserves the pre-move behavior (the method
    /// never invalidated; it runs at resume before any cache exists).
    pub(crate) fn cap_resumed_display(&mut self, cap: usize) {
        self.transcript.cap_resumed_display(cap);
    }

    /// Mark the cached message lines stale โ€” they'll be rebuilt on the next draw.
    /// Call this after any mutation that changes how `messages` renders.
    /// Use for structural changes (theme, width, message list reshuffle). For
    /// streaming deltas prefer `invalidate_last()` which is O(1).
    pub(crate) fn invalidate(&mut self) {
        self.transcript.invalidate();
        self.needs_redraw = true;
    }

    /// Mark only the tail message dirty. O(1) during streaming.
    pub(crate) fn invalidate_last(&mut self) {
        self.transcript.invalidate_last();
        self.needs_redraw = true;
    }


    /// Request a redraw without invalidating the line cache (e.g. for
    /// panel-only changes like spinner/timer updates, scroll, cursor blink).
    pub(crate) fn request_redraw(&mut self) {
        self.needs_redraw = true;
    }

    /// Request an immediate repaint that bypasses the streaming redraw throttle.
    /// Use for user-driven changes (scroll, typing, cursor, paste, resize) that
    /// must feel instant even while the model is streaming. Streaming text
    /// deltas use the throttled `request_redraw` / `invalidate` paths.
    pub(crate) fn request_immediate_redraw(&mut self) {
        self.needs_redraw = true;
        self.force_redraw = true;
    }

    /// Advance spinner/animation state.
    ///
    /// Returns true only when text generated from `render_lines` may have changed
    /// and the cached message lines must be rebuilt. Full-screen overlays and
    /// header/panel spinners are redrawn from current state without touching the
    /// message cache, avoiding unnecessary whole-terminal clears on every frame.
    pub(crate) fn advance_animations(&mut self) -> bool {
        self.spinner_frame = self.spinner_frame.wrapping_add(1);
        if self.spinner_frame % 3 != 0 {
            return false;
        }

        self.transcript.uses_spinner()
    }

    /// True when a full terminal clear is needed before an animated redraw.
    ///
    /// The message pane is already cleared locally in `draw()` before rendering
    /// the transcript, and rendered lines are clamped to terminal display width.
    /// Calling `terminal.clear()` on streaming animation frames repaints the
    /// whole alternate screen and causes visible flicker, so animation ticks
    /// should not request a full-screen clear.
    pub(crate) fn needs_clear_for_animation_redraw(&self) -> bool {
        false
    }

    // โ”€โ”€ Tool-event routing โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    //
    // Routing logic lives in TranscriptStore (transcript.rs) since slice (bโ€ฒ);
    // these are signature-identical delegates.

    /// Delegates to [`TranscriptStore::on_tool_use_start`].
    pub(crate) fn on_tool_use_start(&mut self, tool_id: String, tool_name: String) {
        self.transcript.on_tool_use_start(tool_id, tool_name);
        self.needs_redraw = true;
    }

    /// Delegates to [`TranscriptStore::on_tool_use_delta`].
    pub(crate) fn on_tool_use_delta(&mut self, tool_id: &str, delta: &str) {
        self.transcript.on_tool_use_delta(tool_id, delta);
        self.needs_redraw = true;
    }

    /// Delegates to [`TranscriptStore::on_tool_use_finalized`].
    pub(crate) fn on_tool_use_finalized(&mut self, tool_id: String, tool_name: String, input_str: String) {
        self.transcript.on_tool_use_finalized(tool_id, tool_name, input_str);
        self.needs_redraw = true;
    }

    /// Delegates to [`TranscriptStore::on_tool_result_delta`].
    pub(crate) fn on_tool_result_delta(&mut self, tool_id: String, delta: String) {
        self.transcript.on_tool_result_delta(tool_id, delta);
        self.needs_redraw = true;
    }

    /// Delegates to [`TranscriptStore::on_tool_result`].
    pub(crate) fn on_tool_result(&mut self, tool_id: String, result: String) {
        self.transcript.on_tool_result(tool_id, result);
        self.needs_redraw = true;
    }

    /// Capture all assistant output since the last user message as abort context.
    /// This gets injected into the next user message so the model knows what it
    /// was doing before the abort.
    pub(crate) fn capture_abort_context(&mut self) {
        let mut parts: Vec<String> = Vec::new();

        // Walk backwards from the end to find content since last user message
        for tmsg in self.transcript.messages().iter().rev() {
            match &tmsg.msg {
                ChatMessage::User(_) => break, // stop at the last user message
                ChatMessage::Thinking(t)
                    if !t.is_empty() => {
                        // Truncate thinking to avoid bloating context
                        let preview: String = t.chars().take(500).collect();
                        parts.push(format!("[thinking]: {}", preview));
                    }
                ChatMessage::Text(t)
                    if !t.is_empty() => {
                        parts.push(format!("[response]: {}", t));
                    }
                ChatMessage::ToolUse { tool_name, input, .. } => {
                    // Truncate input to keep context lean
                    let input_preview: String = input.chars().take(200).collect();
                    parts.push(format!("[tool_use]: {} โ€” {}", tool_name, input_preview));
                }
                ChatMessage::ToolResult { content, .. }
                    if !content.is_empty() => {
                        let preview: String = content.chars().take(300).collect();
                        parts.push(format!("[tool_result]: {}", preview));
                    }
                _ => {}
            }
        }

        if parts.is_empty() {
            self.abort_context = None;
            return;
        }

        parts.reverse(); // chronological order
        self.abort_context = Some(format!(
            "[ABORT CONTEXT โ€” your previous response was interrupted. Here's what you completed before the abort:]\n\n{}\n\n[END ABORT CONTEXT โ€” continue from where you left off or adjust based on the user's new message]",
            parts.join("\n")
        ));
    }

    pub(crate) fn history_up(&mut self) {
        if self.input_history.is_empty() { return; }
        match self.history_index {
            None => {
                self.input_stash = self.input.clone();
                self.history_index = Some(self.input_history.len() - 1);
            }
            Some(i) if i > 0 => {
                self.history_index = Some(i - 1);
            }
            _ => return,
        }
        if let Some(idx) = self.history_index {
            self.input = self.input_history[idx].clone();
            self.cursor_pos = self.input.chars().count();
        }
    }

    pub(crate) fn history_down(&mut self) {
        if let Some(i) = self.history_index {
            if i + 1 < self.input_history.len() {
                self.history_index = Some(i + 1);
                self.input = self.input_history[i + 1].clone();
            } else {
                self.history_index = None;
                self.input = self.input_stash.clone();
                self.input_stash.clear();
            }
            self.cursor_pos = self.input.chars().count();
        }
    }

    pub(crate) fn append_or_update_text(&mut self, text: &str) {
        self.transcript.append_or_update_text(text);
        self.needs_redraw = true;
    }

    pub(crate) fn append_or_update_thinking(&mut self, text: &str) {
        self.transcript.append_or_update_thinking(text);
        self.needs_redraw = true;
    }

    /// Delegates to [`TranscriptStore::drop_empty_thinking`].
    pub(crate) fn drop_empty_thinking(&mut self) {
        self.transcript.drop_empty_thinking();
        self.needs_redraw = true;
    }

    pub(crate) fn handle_theme_command(&mut self, arg: &str) {
        let descriptions: &[(&str, &str)] = &[
            ("default",        "cool teal on dark blue-gray"),
            ("night-city",     "premium neon-noir โ€” cyberpunk/blade runner"),
            ("neon-rain",      "cyberpunk hot pink + cyan"),
            ("amber",          "warm CRT retro terminal"),
            ("phosphor",       "green monochrome CRT"),
            ("solarized-dark", "Ethan Schoonover's classic"),
            ("blood",          "dark red, Doom/horror"),
            ("ocean",          "deep sea bioluminescence"),
            ("rose-pine",      "elegant muted purples/pinks"),
            ("nord",           "arctic frost blues"),
            ("dracula",        "purple/pink/cyan vibrant"),
            ("monokai",        "classic orange/pink/green"),
            ("gruvbox",        "warm earthy tones"),
            ("catppuccin",     "soft pastels, cozy dark"),
            ("tokyo-night",    "dark blue-purple, soft accents"),
            ("sunset",         "warm oranges/pinks dusk"),
            ("ice",            "frozen arctic pale blues"),
            ("forest",         "deep greens and browns"),
            ("lavender",       "rich purple/violet"),
        ];

        if arg.is_empty() {
            self.push_msg(ChatMessage::System("Available themes:".to_string()));
            for (name, desc) in descriptions {
                self.push_msg(ChatMessage::System(format!("  {:<15} โ€” {}", name, desc)));
            }
            let themes_dir = synaps_cli::config::base_dir().join("themes");
            if let Ok(entries) = std::fs::read_dir(&themes_dir) {
                let mut custom: Vec<String> = entries
                    .filter_map(|e| e.ok())
                    .map(|e| e.file_name().to_string_lossy().to_string())
                    .filter(|n| !descriptions.iter().any(|(d, _)| *d == n.as_str()))
                    .collect();
                custom.sort();
                for name in &custom {
                    self.push_msg(ChatMessage::System(format!("  {:<15} โ€” custom", name)));
                }
            }
            self.push_msg(ChatMessage::System(String::new()));
            self.push_msg(ChatMessage::System("Usage: /theme <name> to set. Restart to apply.".to_string()));
        } else {
            let name = arg.trim();
            let is_valid = descriptions.iter().any(|(n, _)| *n == name)
                || synaps_cli::config::base_dir().join("themes").join(name).exists();

            if is_valid {
                match synaps_cli::config::write_config_value("theme", name) {
                    Ok(_) => {
                        let new_theme = super::theme::load_theme_by_name(name)
                            .unwrap_or_default();
                        super::theme::set_theme(new_theme);
                        self.push_msg(ChatMessage::System(
                            format!("Theme applied: {}", name)
                        ));
                        self.invalidate();
                    }
                    Err(e) => {
                        self.push_msg(ChatMessage::Error(
                            format!("failed to write config: {}", e)
                        ));
                    }
                }
            } else {
                self.push_msg(ChatMessage::Error(
                    format!("unknown theme: '{}'. Use /theme to list available themes.", name)
                ));
            }
        }
    }

}

/// Test-only render delegates. Production rendering goes through
/// `TranscriptStore::sync_cache` (draw.rs); tests keep calling through App so
/// the incremental-cache regression suite ports with the move (slice d).
#[cfg(test)]
impl App {
    pub(crate) fn render_ctx(&self) -> RenderCtx<'_> {
        RenderCtx {
            spinner_frame: self.spinner_frame,
            streaming: self.streaming,
            agent_name: &self.agent_name,
        }
    }

    pub(crate) fn render_message_lines(&self, idx: usize, width: usize) -> MsgSlot {
        self.transcript.render_message_lines(idx, width, &self.render_ctx())
    }

    pub(crate) fn render_lines(&self, width: usize) -> Vec<ratatui::text::Line<'static>> {
        self.transcript.render_lines(width, &self.render_ctx())
    }
}

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

    fn test_app() -> App {
        App::new(Session::new("test-model", "low", None))
    }

    #[test]
    fn empty_thinking_placeholder_is_dropped_when_agent_moves_on() {
        // Spinner is driven by a Thinking(THINKING_PLACEHOLDER) block. If thinking stays
        // empty, producing text/tools must remove it so the spinner stops.
        let mut app = test_app();

        // Case 1: text follows empty thinking.
        app.push_msg(ChatMessage::Thinking(THINKING_PLACEHOLDER.to_string()));
        assert!(app.transcript.uses_spinner(), "placeholder should animate while present");
        app.append_or_update_text("here is the answer");
        assert!(
            !matches!(app.transcript.messages().last().map(|m| &m.msg), Some(ChatMessage::Thinking(_))),
            "empty thinking must be gone once text arrives"
        );
        assert!(!app.transcript.uses_spinner(), "spinner must stop after agent moves on");

        // Case 2: a tool follows empty thinking.
        let mut app = test_app();
        app.push_msg(ChatMessage::Thinking(THINKING_PLACEHOLDER.to_string()));
        app.on_tool_use_start("t1".to_string(), "bash".to_string());
        let thinking_count = app
            .transcript.messages()
            .iter()
            .filter(|m| matches!(m.msg, ChatMessage::Thinking(_)))
            .count();
        assert_eq!(thinking_count, 0, "empty thinking must be gone once a tool runs");

        // Case 3: real thinking content is preserved.
        let mut app = test_app();

        app.push_msg(ChatMessage::Thinking(THINKING_PLACEHOLDER.to_string()));
        app.append_or_update_thinking("actually reasoning");
        app.append_or_update_text("done");
        assert!(
            app.transcript.messages().iter().any(|m| matches!(&m.msg, ChatMessage::Thinking(t) if t == "actually reasoning")),
            "non-empty thinking must survive and not keep the โ€ฆ prefix"
        );
    }

    #[test]
    fn parallel_tool_results_pair_with_their_inputs() {
        let mut app = test_app();
        // Model fans out four tool calls โ€” all inputs arrive first.
        for id in ["t1", "t2", "t3", "t4"] {
            app.on_tool_use_finalized(id.to_string(), "bash".to_string(), "{}".to_string());
        }
        // Results return out of completion order; each must slot under its input.
        for id in ["t2", "t1", "t4", "t3"] {
            app.on_tool_result(id.to_string(), format!("out-{id}"));
        }
        let seq: Vec<(String, bool)> = app
            .transcript.messages()
            .iter()
            .filter_map(|m| match &m.msg {
                ChatMessage::ToolUse { tool_id, .. } => Some((tool_id.clone(), false)),
                ChatMessage::ToolResult { tool_id, .. } => Some((tool_id.clone(), true)),
                _ => None,
            })
            .collect();
        let expected = vec![
            ("t1".to_string(), false), ("t1".to_string(), true),
            ("t2".to_string(), false), ("t2".to_string(), true),
            ("t3".to_string(), false), ("t3".to_string(), true),
            ("t4".to_string(), false), ("t4".to_string(), true),
        ];
        assert_eq!(seq, expected, "parallel tool calls must render as inputโ†’output pairs");
    }

    #[test]
    fn tool_block_has_gutter_and_background() {
        let mut app = test_app();
        app.on_tool_use_finalized("t1".to_string(), "bash".to_string(), "{}".to_string());
        app.on_tool_result("t1".to_string(), "hello\nworld".to_string());
        let lines = app.render_lines(80);
        // No borders / shade glyphs.
        for l in &lines {
            let s: String = l.spans.iter().map(|sp| sp.content.as_ref()).collect();
            assert!(
                !s.chars().any(|c| matches!(c,
                    '\u{256D}' | '\u{256E}' | '\u{2570}' | '\u{256F}' | '\u{2502}'
                    | '\u{2591}' | '\u{2592}' | '\u{2593}')),
                "no borders or shade glyphs: {s:?}"
            );
        }
        // Panel lines carry a gutter bar โ–Ž and a unified background.
        let panel_line = lines
            .iter()
            .find(|l| l.spans.iter().any(|s| s.content.contains('\u{258E}')))
            .expect("a panel line with a gutter");
        assert!(
            panel_line.spans.iter().any(|s| s.style.bg.is_some()),
            "panel cells (incl. text) must share a background"
        );
        // The inset left margin stays transparent.
        if let Some(first) = panel_line.spans.first() {
            if !first.content.is_empty() && first.content.chars().all(|c| c == ' ') {
                assert!(first.style.bg.is_none(), "left margin must stay transparent");
            }
        }
    }

    #[test]
    fn active_tool_result_is_only_latest_incomplete_result() {
        let mut app = test_app();
        app.push_msg(ChatMessage::ToolUse {
            tool_id: "call_1".to_string(),
            tool_name: "bash".to_string(),
            input: "{}".to_string(),
        });
        app.push_msg(ChatMessage::ToolResult {
            tool_id: "call_1".to_string(),
            content: "first output".to_string(),
            elapsed_ms: None,
        });
        app.push_msg(ChatMessage::ToolUse {
            tool_id: "call_2".to_string(),
            tool_name: "bash".to_string(),
            input: "{}".to_string(),
        });
        app.push_msg(ChatMessage::ToolResult {
            tool_id: "call_2".to_string(),
            content: "second output".to_string(),
            elapsed_ms: None,
        });
        // Only call_2 is still in tool_start_times (call_1 is done)
        app.transcript.test_set_tool_start_time(Some(app.clock.now()));
        app.transcript.test_insert_tool_start_time("call_2".to_string(), app.clock.now());

        assert!(!app.transcript.is_active_tool_result(1), "completed historical result (call_1, not in tool_start_times) must render done");
        assert!(app.transcript.is_active_tool_result(3), "latest in-flight result (call_2, in tool_start_times) must be active");

        // Bonus: with BOTH in-flight (parallel), BOTH must be active
        let mut app2 = test_app();
        app2.push_msg(ChatMessage::ToolUse {
            tool_id: "p1".to_string(),
            tool_name: "bash".to_string(),
            input: "{}".to_string(),
        });
        app2.push_msg(ChatMessage::ToolResult {
            tool_id: "p1".to_string(),
            content: "".to_string(),
            elapsed_ms: None,
        });
        app2.push_msg(ChatMessage::ToolUse {
            tool_id: "p2".to_string(),
            tool_name: "bash".to_string(),
            input: "{}".to_string(),
        });
        app2.push_msg(ChatMessage::ToolResult {
            tool_id: "p2".to_string(),
            content: "".to_string(),
            elapsed_ms: None,
        });
        app2.transcript.test_set_tool_start_time(Some(app2.clock.now()));
        app2.transcript.test_insert_tool_start_time("p1".to_string(), app2.clock.now());
        app2.transcript.test_insert_tool_start_time("p2".to_string(), app2.clock.now());
        assert!(app2.transcript.is_active_tool_result(1), "parallel in-flight p1 mid-vec must be active");
        assert!(app2.transcript.is_active_tool_result(3), "parallel in-flight p2 last must be active");
    }

    #[test]
    fn completed_latest_tool_result_is_not_active() {
        let mut app = test_app();
        app.push_msg(ChatMessage::ToolUse {
            tool_id: "call_1".to_string(),
            tool_name: "bash".to_string(),
            input: "{}".to_string(),
        });
        app.push_msg(ChatMessage::ToolResult {
            tool_id: "call_1".to_string(),
            content: "done".to_string(),
            elapsed_ms: Some(25),
        });
        app.transcript.test_set_tool_start_time(Some(app.clock.now()));

        assert!(!app.transcript.is_active_tool_result(1));
    }

    #[test]
    fn animation_tick_for_subagent_panel_does_not_invalidate_message_cache() {
        let mut app = test_app();
        app.push_msg(ChatMessage::System("stable transcript".to_string()));
        {
            let w = 80;
            let per_msg: Vec<MsgSlot> = (0..app.transcript.message_count()).map(|i| app.render_message_lines(i, w)).collect();
            app.transcript.test_set_cache_clean(LineCache::new(w, per_msg));
        }
        app.subagents.push(SubagentState {
            id: 1,
            name: "tester".to_string(),
            status: "running".to_string(),
            start_time: app.clock.now(),
            done: false,
            duration_secs: None,
            done_at: None,
        });
        app.spinner_frame = 2;

        let invalidate_messages = app.advance_animations();

        assert!(!invalidate_messages, "subagent panel spinner redraw must not rebuild message cache");
        assert!(!app.needs_clear_for_animation_redraw(), "subagent-only animation must not force terminal.clear flicker");
        assert!(app.transcript.line_cache().is_some(), "message cache should remain valid for panel-only animation");
    }

    #[test]
    fn animation_tick_for_active_bash_result_invalidates_message_cache() {
        let mut app = test_app();
        app.push_msg(ChatMessage::ToolUse {
            tool_id: "call_1".to_string(),
            tool_name: "bash".to_string(),
            input: "{}".to_string(),
        });
        app.push_msg(ChatMessage::ToolResult {
            tool_id: "call_1".to_string(),
            content: String::new(),
            elapsed_ms: None,
        });
        app.transcript.test_set_tool_start_time(Some(app.clock.now()));
        app.transcript.test_insert_tool_start_time("call_1".to_string(), app.clock.now());
        {
            let w = 80;
            let per_msg: Vec<MsgSlot> = (0..app.transcript.message_count()).map(|i| app.render_message_lines(i, w)).collect();
            app.transcript.test_set_cache_clean(LineCache::new(w, per_msg));
        }
        app.spinner_frame = 2;

        let invalidate_messages = app.advance_animations();

        assert!(invalidate_messages, "active message-area bash animation must rebuild message cache");
        assert!(!app.needs_clear_for_animation_redraw(), "streaming animation must not force whole-terminal clear flicker");
    }

    #[test]
    fn spinner_tick_with_thinking_placeholder_marks_only_tail_dirty() {
        // After advancing the spinner while THINKING_PLACEHOLDER is present,
        // only the last message slot should be marked dirty (dirty_from == last index).
        // Earlier per_msg slots must be untouched on the next rebuild.
        let mut app = test_app();
        let w = 80;
        app.push_msg(ChatMessage::User("question".to_string()));
        app.push_msg(ChatMessage::Text("partial response".to_string()));
        app.push_msg(ChatMessage::Thinking(THINKING_PLACEHOLDER.to_string()));

        // Build full cache first (Clean = old Some + dirty_from None)
        {
            let per_msg: Vec<MsgSlot> = (0..app.transcript.message_count()).map(|i| app.render_message_lines(i, w)).collect();
            app.transcript.test_set_cache_clean(LineCache::new(w, per_msg));
        }
        let last = app.transcript.message_count() - 1;

        // Snapshot per_msg[0..last]
        let snapshot: Vec<Vec<String>> = app.transcript.line_cache().unwrap().per_msg[..last]
            .iter()
            .map(|slot| slot.lines().iter().map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect::<String>()).collect())
            .collect();

        // Advance spinner (spinner_frame % 3 == 0 triggers uses_spinner)
        app.spinner_frame = 2; // next wrapping_add gives 3, which % 3 == 0
        let needs_redraw = app.advance_animations();
        assert!(needs_redraw, "spinner must signal redraw while THINKING_PLACEHOLDER present");

        // The animation tick itself doesn't call invalidate โ€” the caller in mod.rs does.
        // We simulate that caller calling invalidate_last() (the new behaviour for slice 4).
        // But first assert dirty_from is still None (advance_animations doesn't set it).
        // Then we call invalidate_last() as the updated caller will.
        app.invalidate_last();
        assert_eq!(app.transcript.cache_dirty_from(), Some(last), "dirty watermark must point to tail message only");

        // Simulate draw.rs incremental rebuild
        {
            let fresh: Vec<MsgSlot> = (last..app.transcript.message_count())
                .map(|i| app.render_message_lines(i, w))
                .collect();
            let mut cs = app.transcript.test_take_cache();
            if let CacheState::Dirty(ref mut cache, _) = cs {
                for (offset, rendered) in fresh.into_iter().enumerate() {
                    cache.per_msg[last + offset] = rendered;
                }
            }
            // mark clean
            if let CacheState::Dirty(cache, _) = cs {
                app.transcript.test_set_cache_clean(cache);
            }
        }

        // per_msg[0..last] must be unchanged
        let after: Vec<Vec<String>> = app.transcript.line_cache().unwrap().per_msg[..last]
            .iter()
            .map(|slot| slot.lines().iter().map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect::<String>()).collect())
            .collect();
        assert_eq!(snapshot, after, "earlier per_msg slots must not change on spinner tick");
    }

    #[test]
    fn grouped_system_output_does_not_insert_rules_between_indented_lines() {
        let mut app = test_app();
        app.push_msg(ChatMessage::System("Extensions (1):".to_string()));
        app.push_msg(ChatMessage::System("  capture โ€” ok".to_string()));
        app.push_msg(ChatMessage::System("    tools: speak".to_string()));

        let lines = app.render_lines(80);
        let header_idx = lines
            .iter()
            .position(|line| line.spans.iter().any(|span| span.content.contains("Extensions (1):")))
            .expect("header system message should render");
        let child_idx = lines
            .iter()
            .position(|line| line.spans.iter().any(|span| span.content.contains("capture โ€” ok")))
            .expect("child system message should render");
        let grandchild_idx = lines
            .iter()
            .position(|line| line.spans.iter().any(|span| span.content.contains("tools: speak")))
            .expect("grandchild system message should render");

        // Related system messages should not have extra blank-line separators between them
        // (they flow as a continuous block).
        let has_separator = |slice: &[ratatui::text::Line]| {
            // Two consecutive blank lines indicate a separator was inserted
            slice.windows(2).any(|w| {
                let blank = |l: &ratatui::text::Line| l.spans.is_empty() || l.spans.iter().all(|s| s.content.is_empty());
                blank(&w[0]) && blank(&w[1])
            })
        };
        assert!(!has_separator(&lines[header_idx + 1..child_idx]));
        assert!(!has_separator(&lines[child_idx + 1..grandchild_idx]));
    }

    #[test]
    fn unrelated_consecutive_system_messages_get_blank_line_separator() {
        let mut app = test_app();
        app.push_msg(ChatMessage::System("first".to_string()));
        app.push_msg(ChatMessage::System("second".to_string()));

        let lines = app.render_lines(80);
        let first_idx = lines
            .iter()
            .position(|line| line.spans.iter().any(|span| span.content.contains("first")))
            .expect("first system message should render");
        let second_idx = lines
            .iter()
            .position(|line| line.spans.iter().any(|span| span.content.contains("second")))
            .expect("second system message should render");

        let between = &lines[first_idx + 1..second_idx];
        let is_blank = |line: &ratatui::text::Line| {
            line.spans.is_empty() || line.spans.iter().all(|span| span.content.is_empty())
        };
        assert!(between.iter().any(is_blank), "expected blank line between consecutive system messages");
    }

    #[test]
    fn pasted_message_display_preserves_text_typed_after_paste() {
        let mut app = test_app();
        app.input_before_paste = Some("before".to_string());
        app.pasted_char_count = "PASTED".chars().count();

        let display = app.user_display_text_for_submission("beforePASTED after");

        assert_eq!(display, "before [Pasted 6 chars] after");
    }

    // โ”€โ”€ Parallel tool-event routing (Bug 2 regression coverage) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    fn last_tool_use(app: &App, tool_id: &str) -> Option<(String, String)> {
        app.transcript.messages().iter().find_map(|m| match &m.msg {
            ChatMessage::ToolUse { tool_id: tid, tool_name, input } if tid == tool_id => {
                Some((tool_name.clone(), input.clone()))
            }
            _ => None,
        })
    }

    fn tool_use_start_partial(app: &App, tool_id: &str) -> Option<String> {
        app.transcript.messages().iter().find_map(|m| match &m.msg {
            ChatMessage::ToolUseStart { tool_id: tid, partial_input, .. } if tid == tool_id => {
                Some(partial_input.clone())
            }
            _ => None,
        })
    }

    fn tool_result_content(app: &App, tool_id: &str) -> Option<String> {
        app.transcript.messages().iter().find_map(|m| match &m.msg {
            ChatMessage::ToolResult { tool_id: tid, content, .. } if tid == tool_id => {
                Some(content.clone())
            }
            _ => None,
        })
    }

    #[test]
    fn parallel_tool_use_deltas_are_routed_by_tool_id() {
        // Regression: deltas from two interleaved parallel tool calls
        // must each land on their own ToolUseStart block. The pre-fix
        // behavior always appended to the most recent ToolUseStart,
        // corrupting the second tool's input with the first's deltas.
        let mut app = test_app();
        app.on_tool_use_start("call_a".to_string(), "bash".to_string());
        app.on_tool_use_start("call_b".to_string(), "read".to_string());

        // Codex sends deltas in interleaved order โ€” exercise that.
        app.on_tool_use_delta("call_b", "{\"path\":");
        app.on_tool_use_delta("call_a", "{\"command\":");
        app.on_tool_use_delta("call_a", "\"ls\"}");
        app.on_tool_use_delta("call_b", "\"a\"}");

        assert_eq!(
            tool_use_start_partial(&app, "call_a").as_deref(),
            Some(r#"{"command":"ls"}"#),
            "call_a partial input must accumulate only call_a's deltas"
        );
        assert_eq!(
            tool_use_start_partial(&app, "call_b").as_deref(),
            Some(r#"{"path":"a"}"#),
            "call_b partial input must accumulate only call_b's deltas"
        );
    }

    #[test]
    fn parallel_tool_use_finalize_collapses_matching_start() {
        // Regression: finalize event must replace the matching
        // ToolUseStart in place, not push a new ToolUse at the end โ€”
        // so on-screen order matches the order tools were called.
        let mut app = test_app();
        app.on_tool_use_start("call_a".to_string(), "bash".to_string());
        app.on_tool_use_start("call_b".to_string(), "read".to_string());

        app.on_tool_use_finalized(
            "call_a".to_string(),
            "bash".to_string(),
            r#"{"command":"ls"}"#.to_string(),
        );
        app.on_tool_use_finalized(
            "call_b".to_string(),
            "read".to_string(),
            r#"{"path":"a"}"#.to_string(),
        );

        // Both are now ToolUse, no lingering ToolUseStart.
        let lingering_starts = app
            .transcript.messages()
            .iter()
            .filter(|m| matches!(&m.msg, ChatMessage::ToolUseStart { .. }))
            .count();
        assert_eq!(
            lingering_starts, 0,
            "every ToolUseStart must collapse on finalize โ€” leftover starts cause perpetual bash-trace animations"
        );
        assert_eq!(
            last_tool_use(&app, "call_a"),
            Some(("bash".to_string(), r#"{"command":"ls"}"#.to_string()))
        );
        assert_eq!(
            last_tool_use(&app, "call_b"),
            Some(("read".to_string(), r#"{"path":"a"}"#.to_string()))
        );

        // On-screen order matches call order (call_a appears before call_b).
        let positions: Vec<&str> = app
            .transcript.messages()
            .iter()
            .filter_map(|m| match &m.msg {
                ChatMessage::ToolUse { tool_id, .. } => Some(tool_id.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(positions, vec!["call_a", "call_b"]);
    }

    #[test]
    fn parallel_tool_results_do_not_overwrite_each_other() {
        // Regression: two ToolResult events arriving back-to-back must
        // each land on their own block by tool_id. The pre-fix path
        // pushed the first as a new message and then *overwrote* it
        // with the second โ€” losing the first tool's output entirely.
        let mut app = test_app();
        app.on_tool_use_start("call_a".to_string(), "bash".to_string());
        app.on_tool_use_start("call_b".to_string(), "bash".to_string());
        app.on_tool_use_finalized(
            "call_a".to_string(),
            "bash".to_string(),
            "{}".to_string(),
        );
        app.on_tool_use_finalized(
            "call_b".to_string(),
            "bash".to_string(),
            "{}".to_string(),
        );

        app.on_tool_result("call_a".to_string(), "first output".to_string());
        app.on_tool_result("call_b".to_string(), "second output".to_string());

        assert_eq!(
            tool_result_content(&app, "call_a").as_deref(),
            Some("first output"),
            "call_a's result must survive โ€” was overwritten by call_b in the buggy implementation"
        );
        assert_eq!(
            tool_result_content(&app, "call_b").as_deref(),
            Some("second output")
        );
    }

    #[test]
    fn tool_result_delta_streams_into_matching_block() {
        let mut app = test_app();
        app.on_tool_use_start("call_a".to_string(), "bash".to_string());
        app.on_tool_use_start("call_b".to_string(), "bash".to_string());
        app.on_tool_use_finalized(
            "call_a".to_string(),
            "bash".to_string(),
            "{}".to_string(),
        );
        app.on_tool_use_finalized(
            "call_b".to_string(),
            "bash".to_string(),
            "{}".to_string(),
        );

        // Interleaved deltas โ€” must accumulate into the right block.
        app.on_tool_result_delta("call_a".to_string(), "alpha-".to_string());
        app.on_tool_result_delta("call_b".to_string(), "beta-".to_string());
        app.on_tool_result_delta("call_a".to_string(), "one".to_string());
        app.on_tool_result_delta("call_b".to_string(), "two".to_string());

        // Then finalize results.
        app.on_tool_result("call_a".to_string(), "alpha-one".to_string());
        app.on_tool_result("call_b".to_string(), "beta-two".to_string());

        assert_eq!(
            tool_result_content(&app, "call_a").as_deref(),
            Some("alpha-one")
        );
        assert_eq!(
            tool_result_content(&app, "call_b").as_deref(),
            Some("beta-two")
        );
    }

    #[test]
    fn parallel_tool_results_record_per_tool_elapsed_time() {
        let mut app = test_app();
        app.on_tool_use_start("call_a".to_string(), "bash".to_string());
        app.on_tool_use_start("call_b".to_string(), "bash".to_string());

        // Sleep deliberately tiny so Instant::elapsed > 0 is guaranteed.
        std::thread::sleep(std::time::Duration::from_millis(2));
        app.on_tool_result("call_a".to_string(), "a".to_string());
        std::thread::sleep(std::time::Duration::from_millis(2));
        app.on_tool_result("call_b".to_string(), "b".to_string());

        let a_elapsed = app.transcript.messages().iter().find_map(|m| match &m.msg {
            ChatMessage::ToolResult { tool_id, elapsed_ms, .. } if tool_id == "call_a" => *elapsed_ms,
            _ => None,
        });
        let b_elapsed = app.transcript.messages().iter().find_map(|m| match &m.msg {
            ChatMessage::ToolResult { tool_id, elapsed_ms, .. } if tool_id == "call_b" => *elapsed_ms,
            _ => None,
        });
        assert!(a_elapsed.is_some(), "call_a must record elapsed_ms from its own start_time");
        assert!(b_elapsed.is_some(), "call_b must record elapsed_ms from its own start_time");
    }

    // โ”€โ”€ FIX 9 regression tests โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    /// Test A: a REAL "โ€ฆ" (plain ellipsis) in model output must survive โ€” only
    /// the sentinel THINKING_PLACEHOLDER (ellipsis + ZWSP) triggers the drop.
    #[test]
    fn real_ellipsis_thinking_content_is_not_dropped() {
        let mut app = test_app();
        // Push the sentinel placeholder (what the stream start inserts)
        app.push_msg(ChatMessage::Thinking(THINKING_PLACEHOLDER.to_string()));
        // First delta is a plain "โ€ฆ" (model literally output ellipsis)
        app.append_or_update_thinking("โ€ฆ");
        // More text follows
        app.append_or_update_text("answer");
        // The Thinking block must survive with "โ€ฆ" content, not be dropped
        assert!(
            app.transcript.messages().iter().any(|m| matches!(&m.msg, ChatMessage::Thinking(t) if t == "โ€ฆ")),
            "real ellipsis thinking content must survive โ€” sentinel and real output are distinct"
        );
    }

    /// Test B: THINKING_PLACEHOLDER stranded by a System/Notice message on top
    /// must be cleaned up by drop_empty_thinking.
    #[test]
    fn placeholder_stranded_by_system_message_is_dropped() {
        let mut app = test_app();
        app.push_msg(ChatMessage::Thinking(THINKING_PLACEHOLDER.to_string()));
        // A Notice arrives on top (as happens in stream_handler::SessionEvent::Notice)
        app.push_msg(ChatMessage::System("retryingโ€ฆ".to_string()));
        // Now trigger the drop (e.g. text arrives / turn ends)
        app.drop_empty_thinking();
        let has_placeholder = app.transcript.messages().iter().any(|m| matches!(
            &m.msg, ChatMessage::Thinking(t) if t == THINKING_PLACEHOLDER
        ));
        assert!(!has_placeholder, "placeholder stranded under a System message must be removed by drop_empty_thinking");
    }

    /// Test C: aborting a stream must not leave a frozen placeholder spinner.
    #[test]
    fn abort_path_clears_thinking_placeholder() {
        let mut app = test_app();
        app.push_msg(ChatMessage::Thinking(THINKING_PLACEHOLDER.to_string()));
        // Simulate what the abort handler does: drop + push error
        app.drop_empty_thinking();
        app.push_msg(ChatMessage::Error("aborted".to_string()));
        let has_placeholder = app.transcript.messages().iter().any(|m| matches!(
            &m.msg, ChatMessage::Thinking(t) if t == THINKING_PLACEHOLDER
        ));
        assert!(!has_placeholder, "abort must remove thinking placeholder so spinner doesn't freeze");
    }

    #[test]
    fn render_lines_equals_concat_of_render_message_lines() {
        let mut app = test_app();
        app.push_msg(ChatMessage::User("hello world".to_string()));
        app.push_msg(ChatMessage::Thinking("some reasoning".to_string()));
        app.push_msg(ChatMessage::Text("here is the answer".to_string()));
        app.push_msg(ChatMessage::ToolUse {
            tool_id: "call_1".to_string(),
            tool_name: "bash".to_string(),
            input: r#"{"command":"ls"}"#.to_string(),
        });
        app.push_msg(ChatMessage::ToolResult {
            tool_id: "call_1".to_string(),
            content: "file1.txt\nfile2.txt".to_string(),
            elapsed_ms: Some(42),
        });

        let w = 80;
        let flat = app.render_lines(w);
        let concat: Vec<ratatui::text::Line<'static>> = (0..app.transcript.message_count())
            .flat_map(|i| app.render_message_lines(i, w).lines.expect("freshly rendered slot has lines"))
            .collect();

        // Compare by rendered string content (Line doesn't impl PartialEq for spans reliably)
        let to_str = |lines: &[ratatui::text::Line<'static>]| -> Vec<String> {
            lines.iter().map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect::<String>()).collect()
        };
        assert_eq!(to_str(&flat), to_str(&concat),
            "render_lines must equal concat of render_message_lines for each index");
    }

    #[test]
    fn line_cache_build_produces_heights_equal_to_render_lines_prefix_sums() {
        // P11 flat-kill port of the flat oracle: the LineCache build path
        // must produce cum_heights equal to the prefix sums of the reference
        // render (render_lines, the surviving ยง4 oracle), and the per_msg
        // concatenation must equal the reference render line-for-line.
        // PERMANENT test (red-team angle 5): this is the standing height
        // oracle now that the flat buffer is gone.
        let mut app = test_app();
        app.push_msg(ChatMessage::User("hi".to_string()));
        app.push_msg(ChatMessage::Text("hello back".to_string()));
        app.push_msg(ChatMessage::ToolUse {
            tool_id: "t1".to_string(),
            tool_name: "bash".to_string(),
            input: "{}".to_string(),
        });
        app.push_msg(ChatMessage::ToolResult {
            tool_id: "t1".to_string(),
            content: "output".to_string(),
            elapsed_ms: Some(10),
        });

        let w = 80;
        let expected_flat = app.render_lines(w);

        // Build a LineCache manually using the new struct
        let per_msg: Vec<MsgSlot> = (0..app.transcript.message_count())
            .map(|i| app.render_message_lines(i, w))
            .collect();
        let cache = LineCache::new(w, per_msg);

        let to_str = |lines: &[ratatui::text::Line<'static>]| -> Vec<String> {
            lines.iter().map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect::<String>()).collect()
        };
        // Height oracle: cum_heights โ‰ก prefix sums of the reference render.
        assert_eq!(cache.total_height(), expected_flat.len(),
            "total_height must equal the reference render's line count");
        let mut acc = 0usize;
        for (i, slot) in cache.per_msg.iter().enumerate() {
            assert_eq!(cache.cum_heights[i], acc, "cum_heights[{i}] must be the prefix sum");
            acc += slot.height();
        }
        // Content oracle: per_msg concatenation โ‰ก the reference render.
        let concat: Vec<ratatui::text::Line<'static>> =
            cache.per_msg.iter().flat_map(|e| e.lines().iter().cloned()).collect();
        assert_eq!(to_str(&expected_flat), to_str(&concat),
            "per_msg concatenation must equal render_lines output");
        assert!(cache.width == w);
    }

    /// Helper: builds a LineCache for an app at a given width, simulating what draw.rs does.
    fn build_cache(app: &App, width: usize) -> LineCache {
        let per_msg: Vec<MsgSlot> = (0..app.transcript.message_count())
            .map(|i| app.render_message_lines(i, width))
            .collect();
        LineCache::new(width, per_msg)
    }

    /// Helper: simulate the incremental rebuild from sync_cache (slice 3 logic,
    /// ported to CacheState in slice d).
    fn rebuild_incremental(app: &mut App, width: usize) {
        match app.transcript.test_take_cache() {
            CacheState::Dirty(mut cache, k) if cache.width == width => {
                // If per_msg length is out of sync with messages (insert/remove), re-render all from k.
                if cache.per_msg.len() != app.transcript.message_count() {
                    cache.per_msg.truncate(k);
                    for i in k..app.transcript.message_count() {
                        cache.per_msg.push(app.render_message_lines(i, width));
                    }
                } else {
                    // In-place partial re-render: only messages[k..]
                    for i in k..app.transcript.message_count() {
                        cache.per_msg[i] = app.render_message_lines(i, width);
                    }
                }
                // cum_heights is recomputed by test_set_cache_clean below.
                app.transcript.test_set_cache_clean(cache);
            }
            CacheState::Clean(cache) if cache.width == width => {
                // Clean at the right width โ€” nothing to do (old dirty_from == None path).
                app.transcript.test_set_cache_clean(cache);
            }
            _ => {
                let c = build_cache(app, width);
                app.transcript.test_set_cache_clean(c);
            }
        }
    }

    #[test]
    fn incremental_cache_does_not_re_render_unchanged_messages() {
        let mut app = test_app();
        let w = 80;
        // Build fixture: User + Thinking + Text (streaming last)
        app.push_msg(ChatMessage::User("hello".to_string()));
        app.push_msg(ChatMessage::Thinking("reasoning".to_string()));
        app.push_msg(ChatMessage::Text("partial answer".to_string()));

        // Full build
        app.transcript.test_set_cache_clean(build_cache(&app, w));

        let last = app.transcript.message_count() - 1; // index of Text message

        // Snapshot per_msg[0..last] content strings (before update)
        let snapshot: Vec<Vec<String>> = app.transcript.line_cache().unwrap().per_msg[..last]
            .iter()
            .map(|slot| slot.lines().iter().map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect::<String>()).collect())
            .collect();

        // Simulate append_or_update_text delta (modifies last message, marks tail dirty)
        if let Some(crate::tui::app::TimestampedMsg { msg: ChatMessage::Text(ref mut t), .. }) = app.transcript.test_last_msg_mut() {
            t.push_str(" โ€” more content appended");
        }
        app.transcript.invalidate_from(last); // invalidate_last equivalent (direct store call)

        // Incremental rebuild
        rebuild_incremental(&mut app, w);

        let cache = app.transcript.line_cache().unwrap();

        // per_msg[0..last] must be unchanged (content-equal to snapshot)
        let after: Vec<Vec<String>> = cache.per_msg[..last]
            .iter()
            .map(|slot| slot.lines().iter().map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect::<String>()).collect())
            .collect();
        assert_eq!(snapshot, after, "per_msg[0..last] must not change on tail-only invalidation");

        // per_msg[last] must have changed (the text grew)
        let last_strs: Vec<String> = cache.per_msg[last].lines().iter()
            .map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect::<String>())
            .collect();
        let contains_new = last_strs.iter().any(|s| s.contains("more content appended"));
        assert!(contains_new, "per_msg[last] must reflect the updated text");

        // Concatenated slots + cum_heights must equal the reference render
        // (the surviving ยง4 oracle โ€” flat is gone).
        let expected_flat = app.render_lines(w);
        let to_str = |lines: &[ratatui::text::Line<'static>]| -> Vec<String> {
            lines.iter().map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect::<String>()).collect()
        };
        let concat: Vec<ratatui::text::Line<'static>> =
            cache.per_msg.iter().flat_map(|e| e.lines().iter().cloned()).collect();
        assert_eq!(to_str(&expected_flat), to_str(&concat),
            "per_msg concatenation must equal full render_lines after incremental rebuild");
        assert_eq!(cache.total_height(), expected_flat.len(),
            "cum_heights total must track the reference render after incremental rebuild");
    }

    #[test]
    fn incremental_cache_handles_tool_result_insert() {
        let mut app = test_app();
        let w = 80;
        app.push_msg(ChatMessage::User("run something".to_string()));
        app.push_msg(ChatMessage::ToolUse {
            tool_id: "t1".to_string(),
            tool_name: "bash".to_string(),
            input: r#"{"command":"ls"}"#.to_string(),
        });

        app.transcript.test_set_cache_clean(build_cache(&app, w));

        // Insert a ToolResult after ToolUse (as push_tool_result does)
        let at = 2;
        app.transcript.test_insert_at(at, crate::tui::app::TimestampedMsg {
            msg: ChatMessage::ToolResult {
                tool_id: "t1".to_string(),
                content: "file.txt".to_string(),
                elapsed_ms: Some(5),
            },
            time: "00:00".to_string(),
        });
        app.transcript.invalidate_from(at);

        // Rebuild: since per_msg.len() (2) != messages.len() (3), should do full-from-k rebuild
        rebuild_incremental(&mut app, w);

        let cache = app.transcript.line_cache().unwrap();
        assert_eq!(cache.per_msg.len(), app.transcript.message_count(), "per_msg must track messages after insert");

        let expected_flat = app.render_lines(w);
        let to_str = |lines: &[ratatui::text::Line<'static>]| -> Vec<String> {
            lines.iter().map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect::<String>()).collect()
        };
        let concat: Vec<ratatui::text::Line<'static>> =
            cache.per_msg.iter().flat_map(|e| e.lines().iter().cloned()).collect();
        assert_eq!(to_str(&expected_flat), to_str(&concat),
            "per_msg concatenation must equal render_lines after insert + incremental rebuild");
        assert_eq!(cache.total_height(), expected_flat.len(),
            "cum_heights total must track the reference render after insert + incremental rebuild");
    }
}