opencrabs 0.3.75

The autonomous, self-improving AI agent. Single Rust binary. Every channel. Install with: cargo install opencrabs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
//! Chat message rendering
//!
//! Main chat view and thinking indicator.

use super::super::app::{App, DisplayMessage};
use super::super::markdown::parse_markdown;
use super::tools::{render_approve_menu, render_inline_approval, render_tool_group};
use super::utils::wrap_line_with_padding;
use ratatui::{
    Frame,
    layout::Rect,
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Clear, Padding, Paragraph},
};
use unicode_width::UnicodeWidthStr;
use uuid::Uuid;

/// Render reasoning/thinking text as plain lines, preserving literal newlines.
/// Unlike `parse_markdown`, single `\n` is honoured instead of being collapsed.
///
/// Wrapped continuations use an empty padding so they align flush-left with
/// the paragraph's first line after the caller prepends its own outer indent.
/// Previously the continuation padding was "  " which, combined with the
/// caller's outer "  " prefix, produced an ugly 4-space indent on wrapped
/// continuations while paragraph starts sat at 2 — inconsistent and distracting
/// in long thinking blocks (screenshot 2026-04-19 08:15).
pub(crate) fn reasoning_to_lines(text: &str, max_width: usize) -> Vec<Line<'static>> {
    let mut result = Vec::new();
    for l in text.split('\n') {
        let line = Line::from(Span::raw(l.to_string()));
        for wrapped in wrap_line_with_padding(line, max_width, "") {
            result.push(wrapped);
        }
    }
    result
}

/// Given the anchored message's first line index (`line_top`) in the freshly
/// rendered transcript, the screen row its header should stay on (`anchor_row`),
/// and the maximum from-bottom scroll, return the `(scroll_offset, auto_scroll)`
/// that pins the header in place across an expand/collapse (#728).
///
/// `scroll_offset` is measured from the bottom, so it is derived from the
/// desired top visible line: `max_scroll - (line_top - anchor_row)`. When the
/// anchor resolves to the very bottom, `auto_scroll` is re-armed so subsequent
/// streaming keeps sticking to the bottom.
pub(crate) fn anchored_scroll_offset(
    line_top: usize,
    anchor_row: usize,
    max_scroll: usize,
) -> (usize, bool) {
    let desired_top = line_top.saturating_sub(anchor_row);
    (
        max_scroll.saturating_sub(desired_top),
        desired_top >= max_scroll,
    )
}

/// Whether this frame's extra lines are content that arrived at the bottom,
/// so the from-bottom scroll offset must absorb them to keep the viewport
/// still.
///
/// `expand_pending` is the important one. A click or ctrl+o that opened a
/// block also grows `total_lines`, but that growth is the user's own doing and
/// happens where they are looking, not appended below them. Treating it as new
/// content scrolled the view up by exactly the number of lines the block added,
/// which for a large tool group is several pages. The anchor restore further
/// down overwrites the offset, but ONLY when the anchored row still has lines
/// this frame: a row hidden by the turn fold resolves to nothing, and then the
/// compensation was the last word and the jump stood (#743 follow-up).
pub(crate) fn should_compensate_for_growth(
    auto_scroll: bool,
    scroll_offset: usize,
    prev_lines: usize,
    total_lines: usize,
    expand_pending: bool,
) -> bool {
    !auto_scroll
        && !expand_pending
        && scroll_offset > 0
        && prev_lines > 0
        && total_lines > prev_lines
}

/// Live-turn spinner suffix. Pure so it can be tested directly.
///
/// `turn_tokens` is the whole turn's streamed output (reasoning + completion
/// text across every tool iteration), so it is labeled "this turn" — it is NOT
/// the size of the current thought, and pairing the bare number with
/// "is thinking..." made it read that way (#741). The ctx budget is
/// deliberately NOT shown here: it already lives in the footer under the input,
/// so repeating it on the spinner was redundant (#744).
pub(crate) fn format_turn_spinner_meta(elapsed_secs: u64, turn_tokens: u32) -> Option<String> {
    let mut parts: Vec<String> = Vec::new();
    if elapsed_secs > 0 {
        parts.push(format!("{elapsed_secs}s"));
    }
    if turn_tokens > 0 {
        parts.push(format!("{turn_tokens} tok this turn"));
    }
    (!parts.is_empty()).then(|| format!(" ({})", parts.join(" · ")))
}

/// A run of consecutive tool-call groups found by [`scan_tool_stack`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ToolStack {
    /// How many `tool_group` messages are in the run.
    pub count: usize,
    /// Total tool calls across every group in the run.
    pub total_calls: usize,
    /// Exclusive end index of the run in the message list.
    pub end: usize,
}

/// Scan forward from `start` over a run of consecutive tool-call groups.
///
/// Thinking-only assistant messages (empty visible text, reasoning in
/// `details`) sit BETWEEN tool groups during a multi-step turn, so they are
/// stepped over without breaking the run — otherwise a turn that thinks between
/// every tool call would never stack. Any other message ends the run.
///
/// Extracted from `render_chat` so the grouping is unit-testable on its own
/// (#743 step 1). The renderer previously inlined this loop, so the only test
/// coverage was a hand-maintained COPY of the logic in `tui_tool_stack_test`,
/// which could drift from the real renderer without failing. Pure: no `App`, no
/// terminal, no side effects.
///
/// `start` must index a message that has a `tool_group`; callers only reach
/// this after that check.
pub(crate) fn scan_tool_stack(messages: &[DisplayMessage], start: usize) -> ToolStack {
    let mut count = 0;
    let mut total_calls = 0;
    let mut end = start;
    // The run always begins with the group at `start`.
    if let Some(g) = messages.get(start).and_then(|m| m.tool_group.as_ref()) {
        count = 1;
        total_calls = g.calls.len();
        end = start + 1;
    }
    while end < messages.len() {
        let m = &messages[end];
        if let Some(ref g) = m.tool_group {
            count += 1;
            total_calls += g.calls.len();
            end += 1;
        } else if m.role == "assistant" && m.content.trim().is_empty() && m.details.is_some() {
            // Thinking-only: step over it, keep the run alive.
            end += 1;
        } else {
            break;
        }
    }
    ToolStack {
        count,
        total_calls,
        end,
    }
}

/// One turn's span in the message list: `[start, end)` (#757).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct TurnRange {
    /// Index of the turn's first message (the user message that opened it).
    pub start: usize,
    /// Exclusive end — the index of the next turn's user message, or the list end.
    pub end: usize,
}

/// Split the message list into turns (#757).
///
/// `DisplayMessage` carries no turn marker, so a turn is inferred from the
/// structure of the conversation: it opens at a `user` message and runs until
/// the next `user` message, absorbing the assistant text, thinking-only
/// messages, tool groups, and any system/error rows the turn produced in
/// between. Every per-turn feature (one collapsible block, a per-turn header, a
/// single expand state) needs this.
///
/// Messages that precede the first user message — history-paging markers, a
/// restored transcript's leading rows — form their own leading range so nothing
/// is dropped. Pure: no `App`, no terminal, no side effects.
pub(crate) fn turn_ranges(messages: &[DisplayMessage]) -> Vec<TurnRange> {
    if messages.is_empty() {
        return Vec::new();
    }
    let mut out: Vec<TurnRange> = Vec::new();
    let mut start = 0usize;
    for (i, m) in messages.iter().enumerate() {
        // A user message opens a new turn, closing the one before it. `i > start`
        // keeps the very first message (and each freshly-opened turn) from
        // closing a zero-length range, and makes back-to-back user messages
        // split into one turn each.
        if m.role == "user" && i > start {
            out.push(TurnRange { start, end: i });
            start = i;
        }
    }
    out.push(TurnRange {
        start,
        end: messages.len(),
    });
    out
}

/// The turn containing `msg_idx`, if any (#757). Used to resolve a clicked or
/// anchored row back to its turn.
#[allow(dead_code)]
pub(crate) fn turn_of(messages: &[DisplayMessage], msg_idx: usize) -> Option<TurnRange> {
    turn_ranges(messages)
        .into_iter()
        .find(|t| msg_idx >= t.start && msg_idx < t.end)
}

/// What a turn actually did, for its header line (#759).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) struct TurnSummary {
    /// Total tool calls across every group in the turn.
    pub tool_calls: usize,
    /// How many of them failed.
    pub failed: usize,
    /// Wall time from the turn's first message to its last, in seconds.
    pub duration_secs: i64,
    /// Whether the turn produced an error row.
    pub has_error: bool,
}

/// Summarise a turn for its header (#759). Pure.
pub(crate) fn turn_summary(messages: &[DisplayMessage], turn: TurnRange) -> TurnSummary {
    let slice = &messages[turn.start.min(messages.len())..turn.end.min(messages.len())];
    let mut s = TurnSummary::default();
    for m in slice {
        if let Some(ref g) = m.tool_group {
            s.tool_calls += g.calls.len();
            s.failed += g.calls.iter().filter(|c| !c.success).count();
        }
        if m.role == "error" {
            s.has_error = true;
        }
    }
    if let (Some(first), Some(last)) = (slice.first(), slice.last()) {
        s.duration_secs = (last.timestamp - first.timestamp).num_seconds().max(0);
    }
    s
}

/// Format a turn's header line, or `None` when the turn isn't worth summarising
/// (#759).
///
/// A plain question-and-answer turn ran no tools, so a header would be pure
/// noise — only turns that actually did work get one. Mirrors the shape of the
/// Telegram flow header (status • N tool calls • duration); ctx is deliberately
/// absent because it already lives in the footer under the input (#744).
pub(crate) fn format_turn_header(summary: TurnSummary) -> Option<String> {
    if summary.tool_calls == 0 {
        return None;
    }
    let status = if summary.has_error || summary.failed > 0 {
        ""
    } else {
        ""
    };
    let calls = if summary.tool_calls == 1 {
        "1 tool call".to_string()
    } else {
        format!("{} tool calls", summary.tool_calls)
    };
    let mut parts = vec![calls];
    if summary.failed > 0 {
        parts.push(format!("{} failed", summary.failed));
    }
    if summary.duration_secs > 0 {
        parts.push(humanize_secs(summary.duration_secs));
    }
    Some(format!("{status} {}", parts.join(" · ")))
}

/// `45s` / `1m 30s` / `2h 5m`, matching the Telegram flow's duration style.
fn humanize_secs(secs: i64) -> String {
    match secs {
        s if s < 60 => format!("{s}s"),
        s if s < 3600 => {
            let (m, r) = (s / 60, s % 60);
            if r == 0 {
                format!("{m}m")
            } else {
                format!("{m}m {r}s")
            }
        }
        s => {
            let (h, m) = (s / 3600, (s % 3600) / 60);
            if m == 0 {
                format!("{h}h")
            } else {
                format!("{h}h {m}m")
            }
        }
    }
}

/// Index of the turn's final answer: the LAST message carrying visible
/// assistant text (#758). Everything before it is working-out.
pub(crate) fn final_answer_idx(messages: &[DisplayMessage], turn: TurnRange) -> Option<usize> {
    (turn.start..turn.end.min(messages.len())).rev().find(|&i| {
        let m = &messages[i];
        m.role == "assistant" && !m.content.trim().is_empty()
    })
}

/// The turn's final answer, but only once the turn has actually finished.
///
/// A running turn has not produced its answer yet: its newest text is the
/// latest STEP. [`final_answer_idx`] cannot tell the difference, since it just
/// takes the last non-empty assistant row, so mid-turn it kept promoting each
/// fresh intermediate text into the one slot the fold must always show. The
/// result was a single block of narration sitting exposed while the tool
/// groups and thinking on either side of it folded away.
///
/// Only the NEWEST turn can be unsettled; every earlier turn is finished by
/// definition and keeps its answer visible.
///
/// Nothing is hidden that the user cannot otherwise see: in-flight text renders
/// from the streaming buffer, with the reasoning excerpt and spinner beside it.
pub(crate) fn settled_final_answer_idx(
    messages: &[DisplayMessage],
    turn: TurnRange,
    is_newest: bool,
    is_processing: bool,
) -> Option<usize> {
    if is_newest && is_processing {
        return None;
    }
    final_answer_idx(messages, turn)
}

/// The one-line preview shown under a folded turn header: the description of
/// the last tool call the turn made, and whether it succeeded.
///
/// A collapsed tool group already renders its last call this way, so without
/// this a folded turn would be strictly LESS informative than the group it
/// replaced: the header alone says how many calls ran but never what they did.
/// `None` when the turn ran no tools, in which case there is no header either.
pub(crate) fn folded_turn_preview(
    messages: &[DisplayMessage],
    turn: TurnRange,
) -> Option<(String, bool)> {
    (turn.start..turn.end.min(messages.len()))
        .rev()
        .find_map(|i| {
            let last = messages[i].tool_group.as_ref()?.calls.last()?;
            Some((last.description.clone(), last.success))
        })
}

/// Whether row `idx` still renders while its turn is folded (#758).
///
/// Folding hides the turn's working-out — thinking, tool groups, and the
/// intermediate narration between them — and keeps what the user must still
/// see: their own question, the final answer, errors, and anything
/// interactive (an approval prompt or menu, which would otherwise become
/// unreachable). This mirrors the Telegram flow block, where the log folds and
/// the final answer stays a clean bubble.
pub(crate) fn visible_when_folded(
    messages: &[DisplayMessage],
    idx: usize,
    final_idx: Option<usize>,
) -> bool {
    let Some(m) = messages.get(idx) else {
        return false;
    };
    // Never hide something the user has to act on, or an error they must see.
    if m.approval.is_some() || m.approve_menu.is_some() {
        return true;
    }
    match m.role.as_str() {
        "user" | "error" | "history_marker" => true,
        _ => Some(idx) == final_idx,
    }
}

/// How many wrapped lines the live reasoning summary may occupy (#768). A hard
/// ceiling, so a long chain truncates instead of growing into a wall.
pub(crate) const THINKING_EXCERPT_LINES: usize = 3;

/// Whether a turn has working-out that folding would hide.
///
/// Deliberately independent of the turn's CURRENT fold state. The header is
/// the only control that can collapse a turn again, so deriving its existence
/// from `folded` made an expanded turn erase its own header: a turn with no
/// tool calls gets no header from [`format_turn_header`], so the step-count
/// fallback was all it had, and that fallback used to require `folded`. One
/// click and the turn was open with nothing on screen to close it (#743
/// follow-up).
pub(crate) fn turn_has_hideable(
    messages: &[DisplayMessage],
    turn: TurnRange,
    final_idx: Option<usize>,
) -> bool {
    (turn.start..turn.end.min(messages.len()))
        .any(|idx| !visible_when_folded(messages, idx, final_idx))
}

/// Whether a turn renders folded.
///
/// Folded is the DEFAULT, always — including while the turn is still running.
/// The turn's working-out (thinking, tool groups, intermediate narration) lives
/// behind the header; nothing should ever render as a wall. Live progress is
/// unaffected because in-flight streaming text and the active tool group render
/// from their own state after the message loop, not from these finalized rows.
///
/// An explicit click on the header overrides this for one turn, in either
/// direction, remembered by anchor id.
pub(crate) fn turn_is_folded(
    overrides: &std::collections::HashMap<Uuid, bool>,
    anchor_id: Uuid,
) -> bool {
    match overrides.get(&anchor_id) {
        Some(expanded) => !expanded,
        None => true,
    }
}

/// One turn's header row, resolved before the render loop walks the messages.
struct TurnHeader {
    /// `✓ 39 tool calls · 3m 57s`
    base: String,
    /// The trailing affordance, which names ctrl+o only on the newest turn.
    hint: &'static str,
    /// Last call description and success, shown only while folded.
    preview: Option<(String, bool)>,
}

/// Render the chat messages
pub(super) fn render_chat(f: &mut Frame, app: &mut App, area: Rect) {
    let mut lines: Vec<Line> = Vec::new();
    // Track which message index each rendered line belongs to (for click-to-copy)
    let mut line_to_msg: Vec<Option<usize>> = Vec::new();

    let content_width = area.width.saturating_sub(4) as usize; // borders + padding

    // Track how many messages to skip (already rendered as part of a stack)
    let mut skip_count: usize = 0;

    // Per-turn folding (#758) + header (#759). A turn's working-out — thinking,
    // tool groups, intermediate narration — folds into one header line, leaving
    // the question, the final answer, errors and anything interactive visible.
    // EVERY turn folds by default, the running one included; only an explicit
    // click or ctrl+o opens one.
    let all_turns = turn_ranges(&app.messages);
    // idx → header text, and idx → the turn anchor it toggles.
    let mut turn_headers: std::collections::HashMap<usize, TurnHeader> =
        std::collections::HashMap::new();
    // ctrl+o acts on the newest turn only, so only its header may advertise it.
    let newest_start = all_turns.last().map(|t| t.start);
    let mut header_anchor: std::collections::HashMap<usize, Uuid> =
        std::collections::HashMap::new();
    // idx → false when that row is folded away this frame.
    let mut row_visible: std::collections::HashMap<usize, bool> = std::collections::HashMap::new();
    for t in &all_turns {
        let Some(anchor_id) = app.messages.get(t.start).map(|m| m.id) else {
            continue;
        };
        let folded = turn_is_folded(&app.turn_expanded, anchor_id);
        let summary = turn_summary(&app.messages, *t);
        let final_idx = settled_final_answer_idx(
            &app.messages,
            *t,
            newest_start == Some(t.start),
            app.is_processing,
        );

        let has_hideable = turn_has_hideable(&app.messages, *t, final_idx);

        if folded {
            for idx in t.start..t.end.min(app.messages.len()) {
                if !visible_when_folded(&app.messages, idx, final_idx) {
                    row_visible.insert(idx, false);
                }
            }
        }
        // A header is worth showing when the turn did work, or when it has
        // working-out to fold away (so the user can get it back, and put it
        // back).
        let hid_something = has_hideable;
        if let Some(base) = format_turn_header(summary)
            .or_else(|| hid_something.then(|| format!("{} steps", t.end.saturating_sub(t.start))))
        {
            let newest = newest_start == Some(t.start);
            let hint = match (folded, newest) {
                (true, true) => " (click / ctrl+o to expand)",
                (true, false) => " (click to expand)",
                (false, true) => " (click / ctrl+o to fold)",
                (false, false) => " (click to fold)",
            };
            let at = if app.messages.get(t.start).is_some_and(|m| m.role == "user") {
                t.start + 1
            } else {
                t.start
            };
            if at < t.end {
                turn_headers.insert(
                    at,
                    TurnHeader {
                        base,
                        hint,
                        // Only a folded turn needs the preview: an open one is
                        // already showing the calls themselves.
                        preview: folded
                            .then(|| folded_turn_preview(&app.messages, *t))
                            .flatten(),
                    },
                );
                header_anchor.insert(at, anchor_id);
            }
        }
    }
    let mut line_to_turn: Vec<Option<Uuid>> = Vec::new();

    // Iterate by index to allow mutable access to render_cache while reading messages
    for msg_idx in 0..app.messages.len() {
        // Skip messages already rendered as part of a stacked group
        if skip_count > 0 {
            skip_count -= 1;
            continue;
        }

        // Turn header, above the turn's first non-user row. Mapped to no
        // MESSAGE (so line→message routing for click/drag is untouched) but to
        // its turn anchor, so a click on this row folds/unfolds the turn (#758).
        if let Some(header) = turn_headers.get(&msg_idx) {
            // Same cyan weight the tool-group header carried before folding —
            // a folded turn must not be LESS visible than the rows it replaced.
            lines.push(Line::from(vec![
                Span::styled(
                    format!("  {}", header.base),
                    Style::default()
                        .fg(Color::Cyan)
                        .add_modifier(Modifier::BOLD),
                ),
                Span::styled(
                    header.hint.to_string(),
                    Style::default().fg(Color::Rgb(100, 100, 100)),
                ),
            ]));
            line_to_msg.resize(lines.len(), None);
            line_to_turn.resize(lines.len(), None);
            if let (Some(anchor), Some(slot)) =
                (header_anchor.get(&msg_idx), line_to_turn.last_mut())
            {
                *slot = Some(*anchor);
            }
            // Last call under the header, styled exactly like the collapsed
            // tool group's preview so folding loses no information.
            if let Some((description, success)) = &header.preview {
                let style = if *success {
                    Style::default()
                        .fg(Color::DarkGray)
                        .add_modifier(Modifier::ITALIC)
                } else {
                    Style::default()
                        .fg(Color::Red)
                        .add_modifier(Modifier::ITALIC)
                };
                lines.push(Line::from(vec![
                    Span::styled("    └─ ", Style::default().fg(Color::DarkGray)),
                    Span::styled(description.clone(), style),
                ]));
                line_to_msg.resize(lines.len(), None);
                line_to_turn.resize(lines.len(), None);
                if let (Some(anchor), Some(slot)) =
                    (header_anchor.get(&msg_idx), line_to_turn.last_mut())
                {
                    // The preview row toggles the turn too, so a click near the
                    // header does what it looks like it should.
                    *slot = Some(*anchor);
                }
            }
            // Breathing room: without it the header sits flush against the
            // answer below and reads as part of it.
            lines.push(Line::from(""));
            line_to_msg.resize(lines.len(), None);
            line_to_turn.resize(lines.len(), None);
        }

        // Folded away this frame — the turn header above can bring it back.
        if row_visible.get(&msg_idx) == Some(&false) {
            continue;
        }

        let lines_before = lines.len();

        // Render inline approval messages
        if let Some(ref approval) = app.messages[msg_idx].approval {
            render_inline_approval(&mut lines, approval, content_width);
            lines.push(Line::from(""));
            line_to_msg.resize(lines.len(), None);
            continue;
        }

        // Render /approve policy menu
        if let Some(ref menu) = app.messages[msg_idx].approve_menu {
            render_approve_menu(&mut lines, menu, content_width);
            lines.push(Line::from(""));
            line_to_msg.resize(lines.len(), None);
            continue;
        }

        // Render history paging marker
        if app.messages[msg_idx].role == "history_marker" {
            lines.push(Line::from(Span::styled(
                app.messages[msg_idx].content.clone(),
                Style::default()
                    .fg(Color::DarkGray)
                    .add_modifier(Modifier::ITALIC),
            )));
            lines.push(Line::from(""));
            line_to_msg.resize(lines.len(), None);
            continue;
        }

        // Render tool call groups (finalized) — stack consecutive groups
        if let Some(ref group) = app.messages[msg_idx].tool_group {
            // Look ahead over the run of consecutive tool groups. The scan is
            // extracted so it can be unit-tested directly (#743 step 1).
            let stack = scan_tool_stack(&app.messages, msg_idx);
            let stack_count = stack.count;
            let stack_total_calls = stack.total_calls;
            let lookahead = stack.end;

            if stack_count >= 3 {
                // Stacked: render a single collapsed summary for all groups
                let dot = "";
                let stack_expanded = group.expanded; // Use first group's expanded state
                let header = if stack_total_calls == stack_count {
                    format!("{} tool calls", stack_total_calls)
                } else {
                    format!("{} tool calls ({} groups)", stack_total_calls, stack_count)
                };
                let mut header_spans = vec![Span::styled(
                    format!("  {} {}", dot, header),
                    Style::default()
                        .fg(Color::Cyan)
                        .add_modifier(Modifier::BOLD),
                )];
                header_spans.push(Span::styled(
                    if stack_expanded {
                        " (ctrl+o to collapse)"
                    } else {
                        " (ctrl+o to expand)"
                    },
                    Style::default().fg(Color::Rgb(100, 100, 100)),
                ));
                lines.push(Line::from(header_spans));

                if stack_expanded {
                    // Show each group's last call as a tree entry
                    let mut group_idx = 0;
                    for i in msg_idx..lookahead {
                        if let Some(ref g) = app.messages[i].tool_group {
                            let connector = if group_idx == stack_count - 1 {
                                "└─"
                            } else {
                                "├─"
                            };
                            if let Some(last) = g.calls.last() {
                                let style = if last.success {
                                    Style::default()
                                        .fg(Color::DarkGray)
                                        .add_modifier(Modifier::ITALIC)
                                } else {
                                    Style::default()
                                        .fg(Color::Red)
                                        .add_modifier(Modifier::ITALIC)
                                };
                                lines.push(Line::from(vec![
                                    Span::styled(
                                        format!("    {} ", connector),
                                        Style::default().fg(Color::DarkGray),
                                    ),
                                    Span::styled(last.description.clone(), style),
                                ]));
                            }
                            group_idx += 1;
                        }
                    }
                } else {
                    // Collapsed: show last group's last call
                    if let Some(last) = group.calls.last() {
                        let style = if last.success {
                            Style::default()
                                .fg(Color::DarkGray)
                                .add_modifier(Modifier::ITALIC)
                        } else {
                            Style::default()
                                .fg(Color::Red)
                                .add_modifier(Modifier::ITALIC)
                        };
                        lines.push(Line::from(vec![
                            Span::styled(
                                "    └─ ".to_string(),
                                Style::default().fg(Color::DarkGray),
                            ),
                            Span::styled(last.description.clone(), style),
                        ]));
                    }
                }

                lines.push(Line::from(""));
                // Map the stack's lines to THIS group's message (#726) so a click
                // toggles the block under the cursor (and toggles it back next
                // click). Mapping them to None made a tool-group click hit an
                // adjacent message's line instead — expanding a block elsewhere.
                line_to_msg.resize(lines.len(), Some(msg_idx));

                // Skip all messages in the stack (tool groups + thinking-only assistants)
                skip_count = lookahead - msg_idx - 1;
                continue;
            }

            render_tool_group(&mut lines, group, false, app.animation_frame, content_width);
            lines.push(Line::from(""));
            // Map the group's lines to its message so a click toggles it (#726).
            line_to_msg.resize(lines.len(), Some(msg_idx));
            continue;
        }

        if app.messages[msg_idx].role == "system" {
            // System messages: visible yellow label, split on newlines so
            // multi-line content actually renders (not clipped to one line).
            let system_style = Style::default()
                .fg(Color::Rgb(200, 170, 60))
                .add_modifier(Modifier::ITALIC);

            for (i, text_line) in app.messages[msg_idx].content.lines().enumerate() {
                let mut spans = vec![Span::styled("  ", Style::default())];
                if i == 0 {
                    spans.push(Span::styled("", system_style));
                } else {
                    spans.push(Span::styled("   ", Style::default()));
                }
                spans.push(Span::styled(text_line.to_string(), system_style));

                // Show expand/collapse hint on the first line only
                if i == 0 && app.messages[msg_idx].details.is_some() {
                    let hint = if app.messages[msg_idx].expanded {
                        " (ctrl+o to collapse)"
                    } else {
                        " (ctrl+o to expand)"
                    };
                    spans.push(Span::styled(
                        hint,
                        Style::default().fg(Color::Rgb(120, 120, 120)),
                    ));
                }
                let line = Line::from(spans);
                for wrapped in wrap_line_with_padding(line, content_width, "    ") {
                    lines.push(wrapped);
                }
            }

            // Show expanded details (e.g. tool output, compaction summary)
            if app.messages[msg_idx].expanded
                && let Some(ref details) = app.messages[msg_idx].details
            {
                for detail_line in details.lines() {
                    // Check for diff lines (+/-) and color accordingly
                    let (style, line_text): (Style, &str) =
                        if let Some(stripped) = detail_line.strip_prefix("+ ") {
                            (Style::default().fg(Color::Green), stripped)
                        } else if let Some(stripped) = detail_line.strip_prefix("- ") {
                            (Style::default().fg(Color::Red), stripped)
                        } else {
                            (Style::default().fg(Color::DarkGray), detail_line)
                        };

                    lines.push(Line::from(vec![
                        Span::styled("    ", Style::default()),
                        Span::styled(line_text.to_string(), style),
                    ]));
                }
            }
            lines.push(Line::from(""));
            // System messages are mapped to their index for copy
            for _ in lines_before..lines.len() {
                line_to_msg.push(Some(msg_idx));
            }
            continue;
        }

        if app.messages[msg_idx].role == "error" {
            // Error messages: distinctive red treatment so a user
            // scrolling through chat history sees instantly that the
            // turn failed (vs. a turn that completed quietly with no
            // text). Without this, a 5xx-exhaustion looks identical
            // to a successful empty-completion turn — a user reports
            // "the agent silently dropped my request" when in fact
            // self-heal already gave up and tried to tell them.
            // Reported 2026-06-01: a 502 fallback chain exhausted,
            // `TuiEvent::Error` fired, `show_error` showed a 2.5s
            // toast that vanished, the user only saw their prompt +
            // tool call + Thinking with no completion.
            let err_style = Style::default()
                .fg(Color::Rgb(220, 70, 70))
                .add_modifier(Modifier::BOLD);
            let body_style = Style::default().fg(Color::Rgb(220, 130, 130));
            for (i, text_line) in app.messages[msg_idx].content.lines().enumerate() {
                let mut spans = vec![Span::styled("  ", Style::default())];
                if i == 0 {
                    spans.push(Span::styled("❌ Error: ", err_style));
                } else {
                    spans.push(Span::styled("   ", Style::default()));
                }
                spans.push(Span::styled(text_line.to_string(), body_style));
                lines.push(Line::from(spans));
            }
            lines.push(Line::from(""));
            for _ in lines_before..lines.len() {
                line_to_msg.push(Some(msg_idx));
            }
            continue;
        }

        // Dot/arrow message differentiation (no role labels needed)
        let is_user = app.messages[msg_idx].role == "user";
        // Highlight selected message with subtle background
        let is_selected = app.selected_message_idx == Some(msg_idx);
        let msg_bg: Option<Color> = if is_selected {
            Some(Color::Rgb(40, 45, 55))
        } else if is_user {
            Some(Color::Rgb(40, 44, 56))
        } else {
            None
        };

        // Parse and render message content as markdown (cached per message + width)
        let msg_id = app.messages[msg_idx].id;
        let cache_key = (msg_id, content_width as u16);
        if !app.render_cache.contains_key(&cache_key) {
            let parsed = parse_markdown(
                &app.messages[msg_idx].content,
                content_width.saturating_sub(2),
            );
            app.render_cache.insert(cache_key, parsed);
        }
        let content_lines = app.render_cache[&cache_key].clone();
        for (i, line) in content_lines.into_iter().enumerate() {
            let mut padded_spans = if i == 0 {
                if is_user {
                    // User: arrow prefix
                    vec![Span::styled(
                        "\u{276F} ",
                        Style::default().fg(Color::Rgb(100, 100, 100)),
                    )]
                } else {
                    // Assistant: colored dot prefix
                    vec![Span::styled(
                        "\u{25CF} ",
                        Style::default()
                            .fg(Color::Rgb(120, 120, 120))
                            .add_modifier(Modifier::BOLD),
                    )]
                }
            } else {
                vec![Span::raw("  ")]
            };
            padded_spans.extend(line.spans);
            let padded_line = Line::from(padded_spans);
            for wrapped in wrap_line_with_padding(padded_line, content_width, "  ") {
                if let Some(bg) = msg_bg {
                    // Apply bg to all spans and pad to full line width.
                    // Force white text on user messages so the dark bg
                    // remains readable on light terminal themes.
                    let mut spans: Vec<Span> = wrapped
                        .spans
                        .into_iter()
                        .map(|s| {
                            let style = if is_user {
                                // Keep the span's own markdown colour when it has
                                // one (inline code, headings, links, coloured bold);
                                // only force white on default-fg text so it stays
                                // readable on the dark user-message bg for light
                                // terminal themes.
                                if s.style.fg.is_some() {
                                    s.style.bg(bg)
                                } else {
                                    s.style.bg(bg).fg(Color::White)
                                }
                            } else {
                                s.style.bg(bg)
                            };
                            Span::styled(s.content, style)
                        })
                        .collect();
                    let line_width: usize = spans.iter().map(|s| s.content.width()).sum();
                    let remaining = content_width.saturating_sub(line_width);
                    if remaining > 0 {
                        spans.push(Span::styled(" ".repeat(remaining), Style::default().bg(bg)));
                    }
                    lines.push(Line::from(spans));
                } else {
                    lines.push(wrapped);
                }
            }
        }

        // Render reasoning details on assistant messages (collapsible).
        // Only show the label when details actually contain visible content —
        // an empty/whitespace `Some("")` produces a phantom Thinking label
        // that the user can't ever expand into anything useful.
        let has_reasoning = app.messages[msg_idx]
            .details
            .as_ref()
            .is_some_and(|d| !d.trim().is_empty());
        if !is_user && has_reasoning {
            lines.push(Line::from(""));
            // 3-state expand cycle for reasoning (#727): collapsed -> capped ->
            // full -> collapsed, via a click on the block or Ctrl+O.
            let expanded = app.messages[msg_idx].expanded;
            let full = app.messages[msg_idx].expanded_full;
            let hint_text = match (expanded, full) {
                (false, _) => "  ▸ Thinking (click / ctrl+o to expand)",
                (true, false) => "  ▾ Thinking (click / ctrl+o for full)",
                (true, true) => "  ▾ Thinking (click / ctrl+o to collapse)",
            };
            // Thinking label — no visible background
            let hint_span = Span::styled(
                hint_text.to_string(),
                Style::default()
                    .fg(Color::DarkGray)
                    .add_modifier(Modifier::ITALIC),
            );
            lines.push(Line::from(vec![hint_span]));
            if expanded && let Some(ref details) = app.messages[msg_idx].details {
                lines.push(Line::from(""));
                // Reserve the outer 2-space indent in the wrap budget so
                // reasoning_to_lines produces lines that already fit
                // `content_width - 2`. Then we prepend the outer "  "
                // prefix and push as-is — no second wrap pass. Previously
                // the caller added the prefix, exceeded content_width,
                // triggered a re-wrap, and broke at wrong word boundaries
                // (e.g. `like.this.and.this` artifacts, inconsistent
                // 2-vs-4-space continuation indent).
                let inner_width = content_width.saturating_sub(2);
                let reasoning_lines = reasoning_to_lines(details, inner_width);
                let reasoning_style = Style::default()
                    .fg(Color::DarkGray)
                    .add_modifier(Modifier::ITALIC);
                // Capped state: show only the first REASONING_CAP lines so a
                // 2-page thinking block never floods the viewport (#727). Full
                // state shows everything.
                const REASONING_CAP: usize = 10;
                let total = reasoning_lines.len();
                let show = if full {
                    total
                } else {
                    total.min(REASONING_CAP)
                };
                for line in reasoning_lines.into_iter().take(show) {
                    let mut padded_spans = vec![Span::styled("  ", Style::default())];
                    for span in line.spans {
                        padded_spans.push(Span::styled(span.content.to_string(), reasoning_style));
                    }
                    lines.push(Line::from(padded_spans));
                }
                if !full && total > show {
                    lines.push(Line::from(vec![Span::styled(
                        format!("{} more lines (click / ctrl+o for full)", total - show),
                        Style::default()
                            .fg(Color::Rgb(100, 100, 100))
                            .add_modifier(Modifier::ITALIC),
                    )]));
                }
            }
        }

        // Map all lines from this message to its index
        let msg_lines_end = lines.len();
        for _ in lines_before..msg_lines_end {
            line_to_msg.push(Some(msg_idx));
        }

        // Spacing between messages
        lines.push(Line::from(""));
        line_to_msg.push(None);
    }

    let has_pending_approval = app.has_pending_approval();

    // Add streaming response if present (hide when approval is pending).
    // Also hide when user has scrolled up (auto_scroll=false) so the viewport
    // stays pinned to the content they are reading.
    if !has_pending_approval
        && app.auto_scroll
        && let Some(ref response) = app.streaming_response
    {
        // Render reasoning/thinking content above the response text (dimmed style)
        if let Some(ref reasoning) = app.streaming_reasoning {
            lines.push(Line::from(vec![
                Span::styled("  ", Style::default()),
                Span::styled(
                    "Thinking...",
                    Style::default()
                        .fg(Color::DarkGray)
                        .add_modifier(Modifier::ITALIC | Modifier::BOLD),
                ),
            ]));
            // See comment at the expanded-message reasoning site above.
            // Cap thinking display to last N lines (rolling window) to avoid
            // swallowing the entire viewport during long thinking phases.
            const MAX_THINKING_LINES: usize = 12;
            let inner_width = content_width.saturating_sub(2);
            let reasoning_lines = reasoning_to_lines(reasoning, inner_width);
            let reasoning_style = Style::default()
                .fg(Color::DarkGray)
                .add_modifier(Modifier::ITALIC);
            let start_idx = reasoning_lines.len().saturating_sub(MAX_THINKING_LINES);
            if start_idx > 0 {
                lines.push(Line::from(Span::styled(
                    format!("{} more lines", start_idx),
                    Style::default().fg(Color::DarkGray),
                )));
            }
            for line in reasoning_lines.into_iter().skip(start_idx) {
                let mut padded_spans = vec![Span::styled("  ", Style::default())];
                for span in line.spans {
                    padded_spans.push(Span::styled(span.content.to_string(), reasoning_style));
                }
                lines.push(Line::from(padded_spans));
            }
            lines.push(Line::from("")); // separator between reasoning and response
        }

        // Cache parsed markdown for the streaming buffer — re-parse only when
        // the buffer grows. This avoids O(n²) markdown parsing during streaming
        // (previously re-parsed the entire growing buffer on every render frame).
        let current_len = response.len();
        let streaming_lines = if let Some((cached_len, ref cached)) = app.streaming_render_cache {
            if cached_len == current_len {
                cached.clone()
            } else {
                let clean = crate::utils::sanitize::strip_llm_artifacts(response);
                let parsed = parse_markdown(&clean, content_width.saturating_sub(2));
                app.streaming_render_cache = Some((current_len, parsed.clone()));
                parsed
            }
        } else {
            let clean = crate::utils::sanitize::strip_llm_artifacts(response);
            let parsed = parse_markdown(&clean, content_width);
            app.streaming_render_cache = Some((current_len, parsed.clone()));
            parsed
        };
        for line in streaming_lines {
            let mut padded_spans = vec![Span::raw("  ")];
            padded_spans.extend(line.spans);
            let padded_line = Line::from(padded_spans);
            for wrapped in wrap_line_with_padding(padded_line, content_width, "  ") {
                lines.push(wrapped);
            }
        }

        // Blank line to separate content from status spinner
        lines.push(Line::from(""));

        // Spinner at BOTTOM of streaming content so it's always visible
        let spinner_frames = ["", "", "", "", "", "", "", "", "", ""];
        let frame = spinner_frames[app.animation_frame % spinner_frames.len()];

        let elapsed = app
            .processing_started_at
            .map(|t| t.elapsed().as_secs())
            .unwrap_or(0);

        let mut spans = vec![
            Span::styled(
                format!("{} ", frame),
                Style::default()
                    .fg(Color::Rgb(120, 120, 120))
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                "🦀 OpenCrabs ",
                Style::default()
                    .fg(Color::Gray)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                "is responding...",
                Style::default().fg(Color::Rgb(215, 100, 20)),
            ),
        ];
        if let Some(meta) = format_turn_spinner_meta(elapsed, app.streaming_output_tokens) {
            spans.push(Span::styled(meta, Style::default().fg(Color::DarkGray)));
        }
        lines.push(Line::from(spans));
    }

    // Render standalone reasoning during thinking-only phase
    // (before first text token — Kimi K2.5, DeepSeek-R1, etc.)
    // streaming_response=None but reasoning is already streaming in
    // Hide when user has scrolled up so the viewport stays frozen.
    if !has_pending_approval
        && app.auto_scroll
        && app.streaming_response.is_none()
        && let Some(ref reasoning) = app.streaming_reasoning
    {
        // Show a short latest-sentence excerpt of the live reasoning instead of
        // a scrolling 12-line window, so a long thought reads as one status line
        // rather than a wall (#742). The full reasoning stays available on the
        // finalized message's 3-state expand.
        let excerpt = crate::utils::string::thinking_excerpt_capped(
            reasoning,
            crate::utils::string::THINKING_EXCERPT_CHARS,
        )
        .unwrap_or_else(|| "Thinking…".to_string());
        // Wrap across at most 3 lines (#768). One line cut a multi-step chain
        // off mid-thought; the ceiling is what keeps this a status line and not
        // the scrolling window #742 replaced.
        let style = Style::default()
            .fg(Color::DarkGray)
            .add_modifier(Modifier::ITALIC);
        let wrapped = wrap_line_with_padding(
            Line::from(Span::styled(excerpt, style)),
            content_width.saturating_sub(5),
            "",
        );
        let overflows = wrapped.len() > THINKING_EXCERPT_LINES;
        for (i, wrapped_line) in wrapped.into_iter().take(THINKING_EXCERPT_LINES).enumerate() {
            // Continuations align under the first line's text, past the emoji.
            let prefix = if i == 0 { "  🧠 " } else { "     " };
            let mut spans = vec![Span::styled(prefix, Style::default().fg(Color::DarkGray))];
            spans.extend(wrapped_line.spans);
            if overflows && i == THINKING_EXCERPT_LINES - 1 {
                spans.push(Span::styled("", style));
            }
            lines.push(Line::from(spans));
        }

        // Blank line to separate reasoning from status spinner
        lines.push(Line::from(""));

        // Spinner at BOTTOM of reasoning content so it's always visible
        let spinner_frames = ["", "", "", "", "", "", "", "", "", ""];
        let frame = spinner_frames[app.animation_frame % spinner_frames.len()];
        let elapsed = app
            .processing_started_at
            .map(|t| t.elapsed().as_secs())
            .unwrap_or(0);
        let mut header_spans = vec![
            Span::styled(
                format!("{} ", frame),
                Style::default()
                    .fg(Color::Rgb(120, 120, 120))
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                "🦀 OpenCrabs ",
                Style::default()
                    .fg(Color::Gray)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                "is thinking...",
                Style::default().fg(Color::Rgb(215, 100, 20)),
            ),
        ];
        if let Some(meta) = format_turn_spinner_meta(elapsed, app.streaming_output_tokens) {
            header_spans.push(Span::styled(meta, Style::default().fg(Color::DarkGray)));
        }
        lines.push(Line::from(header_spans));
    }

    // Inline "OpenCrabs is thinking..." spinner during tool execution / waiting
    // (no streaming text or reasoning yet). Renders ABOVE the tool group so the
    // user always sees the spinner on top of the processing indicator.
    // Hide when user has scrolled up so the viewport stays frozen.
    if !has_pending_approval
        && app.auto_scroll
        && app.is_processing
        && app.streaming_response.is_none()
        && app.streaming_reasoning.is_none()
    {
        let spinner_frames = ["", "", "", "", "", "", "", "", "", ""];
        let frame = spinner_frames[app.animation_frame % spinner_frames.len()];
        let elapsed = app
            .processing_started_at
            .map(|t| t.elapsed().as_secs())
            .unwrap_or(0);
        let mut spans = vec![
            Span::styled(
                format!("  {} ", frame),
                Style::default()
                    .fg(Color::Rgb(120, 120, 120))
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                "OpenCrabs is thinking...",
                Style::default().fg(Color::Rgb(215, 100, 20)),
            ),
        ];
        if let Some(meta) = format_turn_spinner_meta(elapsed, app.streaming_output_tokens) {
            spans.push(Span::styled(
                meta,
                Style::default().fg(Color::Rgb(100, 100, 100)),
            ));
        }
        lines.push(Line::from(spans));
    }

    // Render active tool group (live, during processing) — below spinner
    // so it's always visible at the bottom with auto-scroll.
    // Hide when user has scrolled up so the viewport stays frozen.
    if app.auto_scroll
        && let Some(ref group) = app.active_tool_group
    {
        let is_active = group.calls.iter().any(|c| !c.completed);
        render_tool_group(
            &mut lines,
            group,
            is_active,
            app.animation_frame,
            content_width,
        );
    }

    // Show error message if present
    if let Some(ref error) = app.error_message {
        lines.push(Line::from(""));
        let prefix = "  Error: ";
        let prefix_len = prefix.len();
        let wrap_w = content_width.saturating_sub(prefix_len + 2).max(20);
        let mut first = true;
        for raw_line in error.lines() {
            let mut current = String::new();
            for word in raw_line.split_whitespace() {
                if current.len() + word.len() + 1 > wrap_w {
                    if first {
                        lines.push(Line::from(vec![
                            Span::styled(
                                prefix,
                                Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
                            ),
                            Span::styled(current.clone(), Style::default().fg(Color::Red)),
                        ]));
                        first = false;
                    } else {
                        lines.push(Line::from(Span::styled(
                            format!("{}{}", " ".repeat(prefix_len), current),
                            Style::default().fg(Color::Red),
                        )));
                    }
                    current.clear();
                }
                if !current.is_empty() {
                    current.push(' ');
                }
                current.push_str(word);
            }
            if !current.is_empty() || first {
                if first {
                    lines.push(Line::from(vec![
                        Span::styled(
                            prefix,
                            Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
                        ),
                        Span::styled(current.clone(), Style::default().fg(Color::Red)),
                    ]));
                    first = false;
                } else {
                    lines.push(Line::from(Span::styled(
                        format!("{}{}", " ".repeat(prefix_len), current),
                        Style::default().fg(Color::Red),
                    )));
                }
            }
        }
        lines.push(Line::from(""));
    }

    // Show notification if present (auto-dismiss after 2s)
    if let Some(ref note) = app.notification {
        if app
            .notification_shown_at
            .is_some_and(|t| t.elapsed() < std::time::Duration::from_secs(2))
        {
            lines.push(Line::from(""));
            lines.push(Line::from(vec![
                Span::styled("  ", Style::default()),
                Span::styled(
                    note.clone(),
                    Style::default()
                        .fg(Color::Cyan)
                        .add_modifier(Modifier::BOLD),
                ),
            ]));
            lines.push(Line::from(""));
        } else {
            app.notification = None;
            app.notification_shown_at = None;
        }
    }

    // Show SSH password dialog inline (like approval dialogs).
    // Same shape as the sudo dialog, different label.
    if let Some(ref ssh_req) = app.ssh_pending {
        lines.push(Line::from(""));
        lines.push(Line::from(vec![
            Span::styled(
                "  \u{1F511} ",
                Style::default().fg(Color::Rgb(75, 160, 215)),
            ),
            Span::styled(
                "SSH password required",
                Style::default()
                    .fg(Color::Rgb(75, 160, 215))
                    .add_modifier(Modifier::BOLD),
            ),
        ]));
        let target_display = if ssh_req.target.len() > 60 {
            format!("{}...", ssh_req.target.chars().take(57).collect::<String>())
        } else {
            ssh_req.target.clone()
        };
        lines.push(Line::from(vec![
            Span::styled("  Target:   ", Style::default().fg(Color::DarkGray)),
            Span::styled(target_display, Style::default().fg(Color::Reset)),
        ]));
        lines.push(Line::from(vec![
            Span::styled("  Password: ", Style::default().fg(Color::DarkGray)),
            Span::styled(
                "\u{2022}".repeat(app.ssh_input.len()),
                Style::default().fg(Color::Reset),
            ),
            Span::styled("\u{2588}", Style::default().fg(Color::Rgb(120, 120, 120))),
        ]));
        lines.push(Line::from(vec![
            Span::styled(
                "  [Enter] ",
                Style::default()
                    .fg(Color::Cyan)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled("Submit  ", Style::default().fg(Color::DarkGray)),
            Span::styled(
                "[Esc] ",
                Style::default()
                    .fg(Color::Cyan)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled("Cancel", Style::default().fg(Color::DarkGray)),
        ]));
        lines.push(Line::from(""));
    }

    // Show sudo password dialog inline (like approval dialogs)
    if let Some(ref sudo_req) = app.sudo_pending {
        lines.push(Line::from(""));
        lines.push(Line::from(vec![
            Span::styled(
                "  \u{1F512} ",
                Style::default().fg(Color::Rgb(215, 100, 20)),
            ),
            Span::styled(
                "sudo password required",
                Style::default()
                    .fg(Color::Rgb(215, 100, 20))
                    .add_modifier(Modifier::BOLD),
            ),
        ]));
        // Show the command being run
        let cmd_display = if sudo_req.command.len() > 60 {
            format!(
                "{}...",
                sudo_req.command.chars().take(57).collect::<String>()
            )
        } else {
            sudo_req.command.clone()
        };
        lines.push(Line::from(vec![
            Span::styled("  Command: ", Style::default().fg(Color::DarkGray)),
            Span::styled(cmd_display, Style::default().fg(Color::Reset)),
        ]));
        // Password input (masked with dots)
        lines.push(Line::from(vec![
            Span::styled("  Password: ", Style::default().fg(Color::DarkGray)),
            Span::styled(
                "\u{2022}".repeat(app.sudo_input.len()),
                Style::default().fg(Color::Reset),
            ),
            Span::styled("\u{2588}", Style::default().fg(Color::Rgb(120, 120, 120))),
        ]));
        // Help line
        lines.push(Line::from(vec![
            Span::styled(
                "  [Enter] ",
                Style::default()
                    .fg(Color::Cyan)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled("Submit  ", Style::default().fg(Color::DarkGray)),
            Span::styled(
                "[Esc] ",
                Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
            ),
            Span::styled("Cancel", Style::default().fg(Color::DarkGray)),
        ]));
        lines.push(Line::from(""));
    }

    // Pad line_to_msg for any remaining lines (streaming, errors, etc.)
    line_to_msg.resize(lines.len(), None);
    app.chat_line_to_msg = line_to_msg;
    // Same length as the line map so a row index is valid in both (#758).
    line_to_turn.resize(app.chat_line_to_msg.len(), None);
    app.chat_line_to_turn = line_to_turn;

    // Calculate scroll offset — lines are pre-wrapped so count is accurate
    let total_lines = lines.len();

    // Compensate for new content appended at the bottom while user is scrolled up.
    // Only add the delta (new lines since last render), not the total, to avoid
    // the accumulation bug that inflated scroll_offset by 1000+ in seconds.
    // Skip if prev_rendered_lines == 0 (first render) to avoid massive jump.
    if should_compensate_for_growth(
        app.auto_scroll,
        app.scroll_offset,
        app.prev_rendered_lines,
        total_lines,
        app.chat_expand_anchor.is_some() || app.chat_expand_anchor_turn.is_some(),
    ) {
        let delta = total_lines - app.prev_rendered_lines;
        app.scroll_offset += delta;
        tracing::debug!(
            "[SCROLL] compensated: scroll_offset += {} (delta), now {}",
            delta,
            app.scroll_offset
        );
    }
    app.prev_rendered_lines = total_lines;

    // Only 1 row of top padding (Borders::NONE + Padding::new(1,1,1,0)); no border rows
    let visible_height = area.height.saturating_sub(1) as usize;
    let max_scroll = total_lines.saturating_sub(visible_height);

    // Expand/collapse anchor (#728): a click or ctrl+o that grew/shrank a block
    // pinned its header to the screen row it sat on. Restore it there instead of
    // letting the fixed-from-bottom offset jump the viewport — the block expands
    // in place. Overrides the streaming compensation above for this one frame.
    if let Some((anchor_idx, anchor_row)) = app.chat_expand_anchor.take()
        && let Some(line_top) = app
            .chat_line_to_msg
            .iter()
            .position(|m| *m == Some(anchor_idx))
    {
        let (offset, auto) = anchored_scroll_offset(line_top, anchor_row as usize, max_scroll);
        app.scroll_offset = offset;
        // At the very bottom, re-arm auto-scroll so streaming keeps sticking.
        app.auto_scroll = auto;
    }

    // Same pin for a turn header, resolved through the turn map because a
    // header line belongs to no message (#743 follow-up). Folding a turn hides
    // its whole working-out, so this is the case where an unpinned viewport
    // jumps furthest.
    if let Some((anchor, anchor_row)) = app.chat_expand_anchor_turn.take()
        && let Some(line_top) = app
            .chat_line_to_turn
            .iter()
            .position(|t| *t == Some(anchor))
    {
        let (offset, auto) = anchored_scroll_offset(line_top, anchor_row as usize, max_scroll);
        app.scroll_offset = offset;
        app.auto_scroll = auto;
    }

    // Cap scroll_offset at max_scroll so it never exceeds the scrollable range.
    // Without this, streaming compensation + mouse coalescing can inflate
    // scroll_offset to hundreds while max_scroll is ~80, making the user
    // scroll down hundreds of times to get back to the visible area.
    let before_cap = app.scroll_offset;
    app.scroll_offset = app.scroll_offset.min(max_scroll);
    if before_cap != app.scroll_offset {
        tracing::debug!(
            "[SCROLL] capped: {} -> {} (max_scroll={})",
            before_cap,
            app.scroll_offset,
            max_scroll
        );
    }

    let actual_scroll_offset = max_scroll.saturating_sub(app.scroll_offset);

    // Scroll state: ONE trace line, only when something actually changed.
    // The old per-frame DEBUG pair (start+end, ~10 lines/second while the
    // TUI is open) was over a million lines a day — 95% of the log file —
    // while carrying values that were identical frame after frame (#400).
    {
        {
            type ScrollSnapshot = (usize, usize, usize, bool, usize);
            static LAST_SCROLL_LOG: std::sync::Mutex<Option<ScrollSnapshot>> =
                std::sync::Mutex::new(None);
            let snapshot = (
                app.scroll_offset,
                total_lines,
                actual_scroll_offset,
                app.auto_scroll,
                max_scroll,
            );
            let mut last = LAST_SCROLL_LOG.lock().unwrap_or_else(|e| e.into_inner());
            if last.map(|l| l != snapshot).unwrap_or(true) {
                {
                    tracing::trace!(
                        "[SCROLL] offset={} total={} actual={} auto={} max={} height={}",
                        app.scroll_offset,
                        total_lines,
                        actual_scroll_offset,
                        app.auto_scroll,
                        max_scroll,
                        visible_height
                    );
                    *last = Some(snapshot);
                }
            }
        }
    }

    // Store render info for click-to-copy + drag-selection coordinate mapping
    app.chat_render_scroll = actual_scroll_offset;
    app.chat_area_y = area.y;
    app.chat_area_x = area.x;
    app.chat_area_width = area.width;
    app.chat_area_height = area.height;
    // Snapshot plain-text of each rendered line for drag-select extraction.
    app.chat_rendered_lines = lines
        .iter()
        .map(|l| {
            l.spans
                .iter()
                .map(|s| s.content.as_ref())
                .collect::<String>()
        })
        .collect();

    let chat = Paragraph::new(lines)
        .block(
            Block::default()
                .borders(Borders::NONE)
                .padding(Padding::new(1, 1, 1, 0)),
        )
        .scroll(((actual_scroll_offset.min(u16::MAX as usize)) as u16, 0));

    // Clear the area first to prevent stale buffer content from bleeding through.
    // Ratatui's Paragraph only writes cells where it has text; cells beyond line
    // ends or below the last line retain old content from the double-buffer.
    f.render_widget(Clear, area);
    f.render_widget(chat, area);

    // Drag-selection highlight overlay: invert fg/bg for cells inside the
    // selection rectangle (reading-order), clipped to the chat area.
    if let (Some(a), Some(b)) = (app.drag_anchor, app.drag_current) {
        let (start, end) = if (a.1, a.0) <= (b.1, b.0) {
            (a, b)
        } else {
            (b, a)
        };
        let buf = f.buffer_mut();
        let x0 = area.x;
        let y0 = area.y;
        let x1 = area.x.saturating_add(area.width);
        let y1 = area.y.saturating_add(area.height);
        let highlight = Style::default().add_modifier(Modifier::REVERSED);
        if start.1 == end.1 {
            let y = start.1;
            if y >= y0 && y < y1 {
                let sx = start.0.max(x0);
                let ex = end.0.min(x1.saturating_sub(1));
                for x in sx..=ex {
                    if let Some(cell) = buf.cell_mut((x, y)) {
                        cell.set_style(highlight);
                    }
                }
            }
        } else {
            for y in start.1..=end.1 {
                if y < y0 || y >= y1 {
                    continue;
                }
                let sx = if y == start.1 { start.0 } else { x0 };
                let ex = if y == end.1 {
                    end.0.min(x1.saturating_sub(1))
                } else {
                    x1.saturating_sub(1)
                };
                for x in sx.max(x0)..=ex {
                    if let Some(cell) = buf.cell_mut((x, y)) {
                        cell.set_style(highlight);
                    }
                }
            }
        }
    }
}