collet 0.1.1

Relentless agentic coding orchestrator with zero-drop agent loops
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
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
use ratatui::prelude::*;
use ratatui::widgets::{Paragraph, Wrap};
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};

use crate::tui::state::{DiffClickRegion, MessageRole, MessagesRenderCache, UiState};
use crate::tui::theme::Theme;

/// Word-wrap `text` so each visual line fits within `max_width` columns.
/// Returns a Vec of owned strings, each ≤ max_width wide.
/// Splits on spaces; if a single word exceeds max_width it is hard-split.
fn wrap_to_width(text: &str, max_width: usize) -> Vec<String> {
    if max_width == 0 {
        return vec![text.to_string()];
    }
    let mut result = Vec::new();
    for input_line in text.lines() {
        if input_line.is_empty() {
            result.push(String::new());
            continue;
        }
        let mut current = String::new();
        let mut current_w = 0usize;
        for word in input_line.split_inclusive(' ') {
            let word_w = UnicodeWidthStr::width(word);
            if current_w + word_w > max_width && !current.is_empty() {
                result.push(current.trim_end().to_string());
                current = String::new();
                current_w = 0;
            }
            // Hard-split word if it alone exceeds max_width
            if word_w > max_width {
                let mut buf = String::new();
                let mut buf_w = 0usize;
                for ch in word.chars() {
                    let cw = ch.width().unwrap_or(1);
                    if buf_w + cw > max_width && !buf.is_empty() {
                        result.push(buf.clone());
                        buf.clear();
                        buf_w = 0;
                    }
                    buf.push(ch);
                    buf_w += cw;
                }
                if !buf.is_empty() {
                    current.push_str(&buf);
                    current_w += buf_w;
                }
            } else {
                current.push_str(word);
                current_w += word_w;
            }
        }
        if !current.is_empty() {
            result.push(current.trim_end().to_string());
        }
    }
    result
}

/// Render a slice of `messages[from_idx..]` into `lines`, updating `user_box_ranges`
/// and `click_regions`. Returns the `prev_is_user` state after the last rendered message
/// (needed for incremental cache extension).
fn build_assistant_label(provider_name: &str, model_name: &str, swarm_names: &[String]) -> String {
    let model_part = if model_name.is_empty() {
        String::new()
    } else {
        format!(" ({}/{})", provider_name, model_name)
    };
    let coordinator = format!("Coordinator{}", model_part);
    if swarm_names.is_empty() {
        coordinator
    } else {
        let agents: Vec<String> = swarm_names
            .iter()
            .map(|n| {
                let mut chars = n.chars();
                match chars.next() {
                    None => String::new(),
                    Some(c) => c.to_uppercase().to_string() + chars.as_str(),
                }
            })
            .collect();
        format!("{}, {}{}", coordinator, agents.join("|"), model_part)
    }
}

struct RenderSliceParams<'a> {
    messages: &'a [crate::tui::state::ChatMessage],
    from_idx: usize,
    prev_is_user: bool,
    inner_width: usize,
    theme: &'a Theme,
    provider_name: &'a str,
    model_name: &'a str,
    swarm_names: &'a [String],
    collab_mode_label: &'a str,
}

fn render_messages_slice(
    p: &RenderSliceParams<'_>,
    lines: &mut Vec<Line<'static>>,
    user_box_ranges: &mut Vec<(usize, usize)>,
    click_regions: &mut Vec<DiffClickRegion>,
) -> bool {
    let messages = p.messages;
    let from_idx = p.from_idx;
    let mut prev_is_user = p.prev_is_user;
    let inner_width = p.inner_width;
    let theme = p.theme;
    let provider_name = p.provider_name;
    let model_name = p.model_name;
    let swarm_names = p.swarm_names;
    let collab_mode_label = p.collab_mode_label;
    for (i, msg) in messages.iter().enumerate().skip(from_idx) {
        let is_user = matches!(msg.role, MessageRole::User | MessageRole::Queued);

        // Blank separator between non-user messages.
        if i > 0 && !is_user && !prev_is_user {
            lines.push(Line::from(""));
        }

        match &msg.role {
            MessageRole::Tool {
                name,
                success,
                args_summary,
            } => {
                let (icon, color) = if *success {
                    ("", theme.success)
                } else {
                    ("", theme.error)
                };
                let max_summary_w = inner_width.saturating_sub(name.len() + 6);
                let summary = tool_one_liner(name, args_summary, &msg.content, max_summary_w);
                // Skip bash tool calls where there is genuinely nothing to show:
                // summary is empty AND args_summary contains no command value.
                if name == "bash" && summary.is_empty() {
                    let has_cmd = extract_json_field(args_summary, "command")
                        .map(|c| !c.is_empty())
                        .unwrap_or(false);
                    if !has_cmd {
                        // The blank separator was already pushed above; remove it so
                        // skipped entries don't leave trailing blank lines.
                        if i > 0 && !prev_is_user {
                            lines.pop();
                        }
                        prev_is_user = false;
                        continue;
                    }
                }
                let mut spans = vec![
                    Span::styled(format!("  {icon} "), Style::default().fg(color)),
                    Span::styled(name.clone(), Style::default().fg(color).bold()),
                ];
                if !summary.is_empty() {
                    spans.push(Span::styled(
                        format!("  {summary}"),
                        Style::default().fg(theme.text_muted),
                    ));
                }
                lines.push(Line::from(spans));
                if name == "file_edit" {
                    render_mini_diff(args_summary, inner_width, theme, lines, click_regions);
                } else if name == "file_write" {
                    render_write_preview(args_summary, inner_width, theme, lines, click_regions);
                }
            }
            MessageRole::User => {
                lines.push(Line::from(""));
                let box_start = lines.len();
                lines.push(Line::from(""));
                const USER_PREFIX: usize = 4;
                let content_w = inner_width.saturating_sub(USER_PREFIX);
                let text = msg.content.text_content();
                for content_line in text.lines() {
                    for wrapped in wrap_to_width(content_line, content_w) {
                        lines.push(Line::from(vec![
                            Span::raw("    "),
                            Span::styled(wrapped, Style::default().fg(theme.user)),
                        ]));
                    }
                }
                lines.push(Line::from(""));
                user_box_ranges.push((box_start, lines.len()));
                lines.push(Line::from(""));
            }
            MessageRole::Queued => {
                lines.push(Line::from(""));
                let box_start = lines.len();
                lines.push(Line::from(""));
                const QUEUED_PREFIX: usize = 6;
                let content_w = inner_width.saturating_sub(QUEUED_PREFIX);
                let text = msg.content.text_content();
                for (line_idx, content_line) in text.lines().enumerate() {
                    for wrapped in wrap_to_width(content_line, content_w) {
                        if line_idx == 0 {
                            lines.push(Line::from(vec![
                                Span::styled("", Style::default().fg(theme.text_muted)),
                                Span::styled(wrapped, Style::default().fg(theme.text_dim)),
                            ]));
                        } else {
                            lines.push(Line::from(vec![
                                Span::raw("      "),
                                Span::styled(wrapped, Style::default().fg(theme.text_dim)),
                            ]));
                        }
                    }
                }
                lines.push(Line::from(""));
                user_box_ranges.push((box_start, lines.len()));
                lines.push(Line::from(""));
            }
            MessageRole::Assistant => {
                let label = build_assistant_label(provider_name, model_name, swarm_names);
                render_role_header(&label, theme.assistant, theme, lines);
                lines.push(Line::from(""));
                let text = msg.content.text_content();
                render_markdown(&text, lines, theme, inner_width);
            }
            MessageRole::System => {
                let sys_text = msg.content.text_content();
                if sys_text.starts_with("🤖 Agent:")
                    || sys_text.contains("에이전트 전환")
                    || sys_text.starts_with("⚙ Mode:")
                    || sys_text.starts_with("🔄")
                {
                    prev_is_user = false;
                    continue;
                }
                if sys_text == "##WELCOME##" {
                    render_welcome_tips(lines, theme, inner_width, collab_mode_label);
                    prev_is_user = false;
                    continue;
                }
                const SYS_PREFIX: usize = 4;
                let content_w = inner_width.saturating_sub(SYS_PREFIX);
                let wrapped_all: Vec<String> = sys_text
                    .lines()
                    .flat_map(|l| wrap_to_width(l, content_w))
                    .collect();
                let pad = "    ";
                for (idx, wl) in wrapped_all.iter().enumerate() {
                    if idx == 0 {
                        lines.push(Line::from(vec![
                            Span::styled("", Style::default().fg(theme.system).bold()),
                            Span::styled(wl.clone(), Style::default().fg(theme.text_dim)),
                        ]));
                    } else {
                        lines.push(Line::from(Span::styled(
                            format!("{pad}{wl}"),
                            Style::default().fg(theme.text_dim),
                        )));
                    }
                }
            }
        }

        prev_is_user = is_user;
    }
    prev_is_user
}

/// Render the welcome/tips panel shown on first launch (before any user message).
fn render_welcome_tips(
    lines: &mut Vec<Line<'static>>,
    theme: &Theme,
    inner_width: usize,
    collab_mode: &str,
) {
    let accent = theme.system;
    let dim = theme.text_dim;
    let text = theme.text;
    let muted = theme.text_muted;

    // ── Header ──────────────────────────────────────────────────────────────
    lines.push(Line::from(""));
    lines.push(Line::from(vec![
        Span::styled("  ", Style::default()),
        Span::styled("COLLET", Style::default().fg(accent).bold()),
        Span::styled(
            "  —  Relentless agentic coding orchestrator",
            Style::default().fg(dim),
        ),
    ]));
    lines.push(Line::from(""));

    // ── Arbor section ───────────────────────────────────────────────────────
    let bar = "".repeat(inner_width.saturating_sub(4).min(48));
    lines.push(Line::from(vec![Span::styled(
        format!("  {bar}"),
        Style::default().fg(muted),
    )]));
    lines.push(Line::from(""));
    lines.push(Line::from(vec![
        Span::styled("  Arbor  ", Style::default().fg(accent).bold()),
        Span::styled("(current agent)  ", Style::default().fg(muted)),
        Span::styled(
            "autonomous — selects agents & strategy automatically",
            Style::default().fg(dim),
        ),
    ]));
    lines.push(Line::from(""));

    // ── Swarm modes ─────────────────────────────────────────────────────────
    lines.push(Line::from(vec![Span::styled(
        format!("  {bar}"),
        Style::default().fg(muted),
    )]));
    lines.push(Line::from(""));
    let (mode_label, mode_style) = match collab_mode {
        "fork" => ("fork", Style::default().fg(theme.success).bold()),
        "hive" => ("hive", Style::default().fg(theme.warning).bold()),
        "flock" => ("flock", Style::default().fg(theme.accent).bold()),
        _ => ("none", Style::default().fg(muted)),
    };
    lines.push(Line::from(vec![
        Span::styled("  Swarm  ", Style::default().fg(accent).bold()),
        Span::styled("current: ", Style::default().fg(dim)),
        Span::styled(mode_label, mode_style),
        Span::styled(
            "  (/fork · /hive · /flock to toggle)",
            Style::default().fg(muted),
        ),
    ]));
    for (cmd, desc) in [
        ("/fork", "parallel — split tasks, merge results"),
        ("/hive", "consensus — agents review each other"),
        ("/flock", "realtime  — agents coordinate live"),
    ] {
        lines.push(Line::from(vec![
            Span::styled(
                format!("    {cmd:<10}", cmd = cmd),
                Style::default().fg(text),
            ),
            Span::styled(desc, Style::default().fg(muted)),
        ]));
    }
    lines.push(Line::from(""));

    // ── Agent switching ─────────────────────────────────────────────────────
    lines.push(Line::from(vec![Span::styled(
        format!("  {bar}"),
        Style::default().fg(muted),
    )]));
    lines.push(Line::from(""));
    lines.push(Line::from(vec![
        Span::styled("  Agents", Style::default().fg(accent).bold()),
        Span::styled("  Tab / Shift+Tab", Style::default().fg(text)),
    ]));
    for (name, desc) in [
        ("arbor", "autonomous orchestrator (default)"),
        ("architect", "planning, design, task breakdown"),
        ("code", "implementation, tests, debugging"),
        ("ask", "Q&A — read-only, no code changes"),
    ] {
        lines.push(Line::from(vec![
            Span::styled(
                format!("    {name:<12}", name = name),
                Style::default().fg(text).bold(),
            ),
            Span::styled(desc, Style::default().fg(muted)),
        ]));
    }
    lines.push(Line::from(""));

    // ── @ mention ───────────────────────────────────────────────────────────
    lines.push(Line::from(vec![Span::styled(
        format!("  {bar}"),
        Style::default().fg(muted),
    )]));
    lines.push(Line::from(""));
    lines.push(Line::from(vec![
        Span::styled("  @", Style::default().fg(accent).bold()),
        Span::styled("  files, dirs, agents  ", Style::default().fg(text)),
        Span::styled("attach context or switch agent", Style::default().fg(muted)),
    ]));
    lines.push(Line::from(""));

    // ── / commands & skills ─────────────────────────────────────────────────
    lines.push(Line::from(vec![Span::styled(
        format!("  {bar}"),
        Style::default().fg(muted),
    )]));
    lines.push(Line::from(""));
    lines.push(Line::from(vec![
        Span::styled("  /", Style::default().fg(accent).bold()),
        Span::styled("  commands & skills  ", Style::default().fg(text)),
        Span::styled(
            "↑↓ to pick, Tab to expand, Enter to run",
            Style::default().fg(muted),
        ),
    ]));
    lines.push(Line::from(""));
    lines.push(Line::from(vec![Span::styled(
        format!("  {bar}"),
        Style::default().fg(muted),
    )]));
    lines.push(Line::from(""));
}

/// Compute the visual height (in terminal rows) for a single ratatui Line.
#[inline]
fn line_visual_height(line: &Line, render_width: usize) -> u16 {
    let span_width: usize = line
        .spans
        .iter()
        .flat_map(|s| s.content.chars())
        .map(|c| c.width().unwrap_or(1))
        .sum();
    if render_width == 0 || span_width == 0 {
        1
    } else {
        span_width.div_ceil(render_width) as u16
    }
}

/// Compute per-line visual heights and calculate scroll offset.
///
/// When only the welcome message exists, pads the output to bottom so it
/// appears near the input prompt. Stores cumulative heights and scroll offset
/// in the state for hit-testing and layout recovery.
fn compute_scroll_and_heights(
    state: &UiState,
    lines: &[Line],
    render_width: usize,
    view_height: u16,
    msg_line_count: usize,
) -> (Vec<u16>, u16) {
    // IMPORTANT: divide by the width that ratatui's Paragraph actually wraps
    // against (`render_area.width`), **not** the narrower pre-wrap width.
    // The two differ by 1 (the pre-wrap safety margin), and using the wrong
    // divisor causes non-pre-wrapped lines (e.g. code blocks in
    // `render_markdown`) to be over-counted by 1 row when their width sits
    // between the two values. The over-count accumulates into `cum` offsets
    // and makes user-message box backgrounds drift below the actual text.

    // Reuse cached heights for the message portion (already computed when
    // the render cache was built/extended). Only compute heights for new
    // streaming lines appended after the cached messages.
    let cached_msg_heights: Option<Vec<u16>> = {
        let c = state.messages_render_cache.borrow();
        c.as_ref().and_then(|cache| {
            if cache.width == render_width as u16 && cache.line_heights.len() == msg_line_count {
                Some(cache.line_heights.clone())
            } else {
                None
            }
        })
    };

    let line_heights: Vec<u16> = if let Some(cached) = cached_msg_heights {
        // Fast path: reuse cached message heights, only compute streaming tail.
        let mut heights = cached;
        for line in &lines[msg_line_count..] {
            heights.push(line_visual_height(line, render_width));
        }
        heights
    } else {
        // Slow path: compute all line heights from scratch.
        lines
            .iter()
            .map(|l| line_visual_height(l, render_width))
            .collect()
    };

    // Use u32 for accumulation to prevent overflow on very long conversations.
    let visual_height_raw: u32 = line_heights.iter().map(|&h| h as u32).sum();
    let visual_height_raw_u16 = visual_height_raw.min(u16::MAX as u32) as u16;
    let final_line_heights = if state.messages.len() == 1 && visual_height_raw_u16 < view_height {
        let pad = (view_height - visual_height_raw_u16) as usize;
        std::iter::repeat_n(1u16, pad).chain(line_heights).collect()
    } else {
        line_heights
    };

    let visual_height: u32 = final_line_heights
        .iter()
        .map(|&h| h as u32)
        .sum::<u32>()
        .saturating_add(2);
    let max_scroll = visual_height.saturating_sub(view_height as u32);
    // Clamp scroll_offset against max_scroll to prevent underflow when user
    // scrolled past the previous content length (e.g. after resize or compaction).
    let clamped_offset = (state.scroll_offset as u32).min(max_scroll) as u16;
    let scroll = (max_scroll - clamped_offset as u32).min(u16::MAX as u32) as u16;

    // Store layout info for click-to-expand hit testing.
    let mut cum: Vec<u16> = Vec::with_capacity(final_line_heights.len() + 1);
    let mut acc: u32 = 0;
    for &h in &final_line_heights {
        cum.push(acc.min(u16::MAX as u32) as u16);
        acc = acc.saturating_add(h as u32);
    }
    cum.push(acc.min(u16::MAX as u32) as u16);
    *state.last_line_cum_heights.borrow_mut() = cum;
    *state.last_render_scroll.borrow_mut() = scroll;

    (final_line_heights, scroll)
}

/// Render user message box backgrounds.
///
/// For each user message, fill the corresponding visual rows with the
/// surface background color.
fn render_user_message_boxes(
    user_box_ranges: &[(usize, usize)],
    line_heights: &[u16],
    scroll: u16,
    area: Rect,
    theme: &Theme,
    buf: &mut Buffer,
) {
    let mut cum: Vec<u16> = Vec::with_capacity(line_heights.len() + 1);
    let mut acc = 0u16;
    for &h in line_heights {
        cum.push(acc);
        acc = acc.saturating_add(h);
    }
    cum.push(acc);

    let view_height = area.height;
    for &(start_idx, end_idx) in user_box_ranges {
        // Bounds-check against cumulative heights to prevent panics on
        // cache-width mismatches after resize.
        let box_top = cum.get(start_idx).copied().unwrap_or(0) as i32 - scroll as i32;
        let box_bot = cum.get(end_idx).copied().unwrap_or(0) as i32 - scroll as i32;

        let vis_top = box_top.max(0).min(view_height as i32) as u16;
        let vis_bot = box_bot.max(0).min(view_height as i32) as u16;

        for row in vis_top..vis_bot {
            for col in 0..area.width {
                buf[(area.x + col, area.y + row)].set_bg(theme.bg_surface);
            }
        }
    }
}

pub fn render(state: &UiState, area: Rect, buf: &mut Buffer) {
    // Worker attached view — render worker stream instead of main chat
    if let Some((agent_id, detail)) = state.attached_worker_detail() {
        render_worker_view(state, area, buf, agent_id, detail);
        return;
    }

    let theme = &state.theme;
    // Effective render width: subtract 2 (1 right padding + 1 safety margin).
    // Pre-wrap uses this so lines never bleed into adjacent buffer cells.
    let inner_width = area.width.saturating_sub(2) as usize;
    let inner_width_u16 = inner_width as u16;

    *state.last_output_area.borrow_mut() = area;

    // ── Messages render cache ─────────────────────────────────────────────
    // Old messages never change once finalized. Re-wrap only when width or
    // theme changes, or when new messages have been added since last render.
    let message_count = state.messages.len();
    let theme_bg = theme.bg;
    let provider_name = state.provider_name.as_str();
    let model_name = state.model_name.as_str();
    let swarm_names: Vec<String> = state
        .swarm_status
        .as_ref()
        .map(|s| s.agents.iter().map(|a| a.name.clone()).collect())
        .unwrap_or_default();

    // `cache_rebuilt` tracks whether click regions changed this frame.
    // When false (full cache hit) we skip the RefCell borrow + Vec clone entirely.
    let (mut lines, user_box_line_ranges, cache_rebuilt) = {
        let mut cache_ref = state.messages_render_cache.borrow_mut();

        // Determine cache validity.
        let cache_matches = cache_ref.as_ref().is_some_and(|c| {
            c.width == inner_width_u16
                && c.theme_bg == theme_bg
                && c.provider_name == provider_name
                && c.model_name == model_name
                && c.swarm_names == swarm_names
                && c.collab_mode_label == state.collab_mode_label
        });
        let cached_count = cache_ref.as_ref().map_or(0, |c| c.message_count);

        if cache_matches && cached_count == message_count {
            // Full cache hit: clone pre-rendered lines (cheaper than re-wrapping).
            // Click regions are unchanged — no RefCell update needed this frame.
            let c = cache_ref.as_ref().expect("cache_matches guarantees Some");
            (c.lines.clone(), c.user_box_ranges.clone(), false)
        } else if cache_matches && cached_count < message_count {
            // Partial cache hit: extend cache with only the new messages.
            let cached = cache_ref.as_ref().expect("cache_matches guarantees Some");
            let prev_was_user = cached.last_was_user;
            let mut lines = cached.lines.clone();
            let mut user_box_ranges = cached.user_box_ranges.clone();
            let mut click_regions = cached.click_regions.clone();

            let last_was_user = render_messages_slice(
                &RenderSliceParams {
                    messages: &state.messages,
                    from_idx: cached_count,
                    prev_is_user: prev_was_user,
                    inner_width,
                    theme,
                    provider_name,
                    model_name,
                    swarm_names: &swarm_names,
                    collab_mode_label: &state.collab_mode_label,
                },
                &mut lines,
                &mut user_box_ranges,
                &mut click_regions,
            );

            // Pre-compute line heights for the message portion (avoids
            // O(n) char-width scan on every subsequent frame).
            let msg_line_heights: Vec<u16> = lines
                .iter()
                .map(|l| line_visual_height(l, area.width as usize))
                .collect();

            *cache_ref = Some(MessagesRenderCache {
                width: inner_width_u16,
                theme_bg,
                provider_name: provider_name.to_string(),
                model_name: model_name.to_string(),
                swarm_names: swarm_names.clone(),
                collab_mode_label: state.collab_mode_label.clone(),
                message_count,
                lines: lines.clone(),
                user_box_ranges: user_box_ranges.clone(),
                click_regions: click_regions.clone(),
                last_was_user,
                line_heights: msg_line_heights,
            });
            // Emit updated click regions once (cache was extended).
            *state.diff_click_regions.borrow_mut() = click_regions;
            (lines, user_box_ranges, true)
        } else {
            // Cache miss (width/theme change or first render): rebuild from scratch.
            let mut lines = Vec::new();
            let mut user_box_ranges = Vec::new();
            let mut click_regions = Vec::new();

            let last_was_user = render_messages_slice(
                &RenderSliceParams {
                    messages: &state.messages,
                    from_idx: 0,
                    prev_is_user: false,
                    inner_width,
                    theme,
                    provider_name,
                    model_name,
                    swarm_names: &swarm_names,
                    collab_mode_label: &state.collab_mode_label,
                },
                &mut lines,
                &mut user_box_ranges,
                &mut click_regions,
            );

            let msg_line_heights: Vec<u16> = lines
                .iter()
                .map(|l| line_visual_height(l, area.width as usize))
                .collect();

            *cache_ref = Some(MessagesRenderCache {
                width: inner_width_u16,
                theme_bg,
                provider_name: provider_name.to_string(),
                model_name: model_name.to_string(),
                swarm_names: swarm_names.clone(),
                collab_mode_label: state.collab_mode_label.clone(),
                message_count,
                lines: lines.clone(),
                user_box_ranges: user_box_ranges.clone(),
                click_regions: click_regions.clone(),
                last_was_user,
                line_heights: msg_line_heights,
            });
            // Emit click regions for the newly built cache.
            *state.diff_click_regions.borrow_mut() = click_regions;
            (lines, user_box_ranges, true)
        }
    };

    // `cache_rebuilt` is false on full cache hits — click regions unchanged, skip update.
    let _ = cache_rebuilt; // used above inside the block; suppresses unused-variable lint

    // Record message line count before streaming lines are appended.
    // Used by compute_scroll_and_heights to reuse cached line heights.
    let msg_line_count = lines.len();

    // Streaming buffer with animated spinner
    if !state.streaming_buffer.is_empty() {
        if !state.messages.is_empty() {
            lines.push(Line::from(""));
        }
        let thinking_spans = state.spinner.thinking_label("Generating", theme);
        let mut title_spans = vec![Span::styled(
            "",
            Style::default().fg(theme.assistant).bold(),
        )];
        title_spans.extend(thinking_spans);
        title_spans.push(Span::styled(
            format!(
                " ({}{})",
                format_elapsed(state.elapsed_secs),
                retry_suffix(state)
            ),
            Style::default().fg(theme.text_muted),
        ));
        lines.push(Line::from(title_spans));
        lines.push(Line::from("")); // padding between header and content

        // ── Streaming buffer render cache ─────────────────────────────────
        // render_markdown is O(n) in buffer length.  With unbounded channel
        // tokens arrive faster than the frame budget, so re-parsing the full
        // buffer every frame causes latency spikes on long responses.
        //
        // Throttled cache: re-render only when ≥200 new bytes arrive or width
        // changes.  This turns most frames into cheap cache hits during fast
        // streaming, at the cost of a few tokens of display delay.
        const REPARSE_THRESHOLD: usize = 200;
        let buf_len = state.streaming_buffer.len();
        let cached = {
            let c = state.streaming_render_cache.borrow();
            c.as_ref()
                .and_then(|&(cached_len, cached_w, ref cached_lines)| {
                    if cached_w == inner_width_u16
                        && (cached_len == buf_len
                            || buf_len.saturating_sub(cached_len) < REPARSE_THRESHOLD)
                    {
                        Some(cached_lines.clone())
                    } else {
                        None
                    }
                })
        };
        if let Some(cached_lines) = cached {
            lines.extend(cached_lines);
        } else {
            let start = lines.len();
            render_markdown(&state.streaming_buffer, &mut lines, theme, inner_width);
            let new_lines = lines[start..].to_vec();
            *state.streaming_render_cache.borrow_mut() =
                Some((buf_len, inner_width_u16, new_lines));
        }

        lines.push(Line::from("")); // bottom padding for streaming area
    } else if state.agent_busy {
        if !state.messages.is_empty() {
            lines.push(Line::from(""));
        }
        let thinking_spans = state.spinner.thinking_label(&state.status_msg, theme);
        let mut title_spans = Vec::from(thinking_spans.as_slice());
        title_spans.push(Span::styled(
            format!(
                " ({}{})",
                format_elapsed(state.elapsed_secs),
                retry_suffix(state)
            ),
            Style::default().fg(if state.stream_retry > 0 {
                theme.warning
            } else {
                theme.text_muted
            }),
        ));
        lines.push(Line::from(title_spans));

        // Hive mode: show per-agent status inline under the spinner
        if let Some(ref hive) = state.swarm_status {
            for entry in &hive.agents {
                let (status_color, status_icon) = match &entry.status {
                    crate::tui::state::SwarmAgentStatus::Pending => (theme.text_muted, "·"),
                    crate::tui::state::SwarmAgentStatus::Running => (theme.accent, ""),
                    crate::tui::state::SwarmAgentStatus::Paused => (theme.warning, ""),
                    crate::tui::state::SwarmAgentStatus::Completed { success: true } => {
                        (theme.success, "")
                    }
                    crate::tui::state::SwarmAgentStatus::Completed { success: false } => {
                        (theme.error, "")
                    }
                };
                let preview = if entry.task_preview.is_empty() {
                    entry.name.as_str()
                } else {
                    entry.task_preview.as_str()
                };
                let max_w = inner_width.saturating_sub(8);
                let truncated = if preview.len() > max_w {
                    let boundary = preview
                        .char_indices()
                        .map(|(i, _)| i)
                        .take_while(|&i| i <= max_w.saturating_sub(1))
                        .last()
                        .unwrap_or(0);
                    format!("{}", &preview[..boundary])
                } else {
                    preview.to_string()
                };
                lines.push(Line::from(vec![
                    Span::styled(
                        format!("    {} ", status_icon),
                        Style::default().fg(status_color),
                    ),
                    Span::styled(
                        format!("[{}] ", entry.agent_id),
                        Style::default().fg(theme.text_muted),
                    ),
                    Span::styled(truncated, Style::default().fg(theme.text_dim)),
                    Span::styled(
                        if entry.tool_calls > 0 {
                            format!("  ({}t)", entry.tool_calls)
                        } else {
                            String::new()
                        },
                        Style::default().fg(theme.text_muted),
                    ),
                ]));
            }
        }

        lines.push(Line::from("")); // bottom padding for thinking indicator
    } else if let Some(ref hive) = state.swarm_status {
        // Workers were dispatched (agent_busy = false) but swarm is still running.
        // Show a lightweight indicator so the output area doesn't go blank.
        if !state.messages.is_empty() {
            lines.push(Line::from(""));
        }
        lines.push(Line::from(vec![
            Span::styled("", Style::default().fg(theme.accent)),
            Span::styled(
                format!("Workers running  ({})", format_elapsed(state.elapsed_secs)),
                Style::default().fg(theme.text_muted),
            ),
        ]));
        for entry in &hive.agents {
            let (status_color, status_icon) = match &entry.status {
                crate::tui::state::SwarmAgentStatus::Pending => (theme.text_muted, "·"),
                crate::tui::state::SwarmAgentStatus::Running => (theme.accent, ""),
                crate::tui::state::SwarmAgentStatus::Paused => (theme.warning, ""),
                crate::tui::state::SwarmAgentStatus::Completed { success: true } => {
                    (theme.success, "")
                }
                crate::tui::state::SwarmAgentStatus::Completed { success: false } => {
                    (theme.error, "")
                }
            };
            let preview = if entry.task_preview.is_empty() {
                entry.agent_id.as_str()
            } else {
                entry.task_preview.as_str()
            };
            let max_w = inner_width.saturating_sub(8);
            let truncated = if preview.len() > max_w {
                let boundary = preview
                    .char_indices()
                    .map(|(i, _)| i)
                    .take_while(|&i| i <= max_w.saturating_sub(1))
                    .last()
                    .unwrap_or(0);
                format!("{}", &preview[..boundary])
            } else {
                preview.to_string()
            };
            lines.push(Line::from(vec![
                Span::styled(
                    format!("    {} ", status_icon),
                    Style::default().fg(status_color),
                ),
                Span::styled(
                    format!("[{}] ", entry.agent_id),
                    Style::default().fg(theme.text_muted),
                ),
                Span::styled(truncated, Style::default().fg(theme.text_dim)),
            ]));
        }
        lines.push(Line::from(""));
    }

    // Trailing padding
    const BOTTOM_PAD: u16 = 3;
    for _ in 0..BOTTOM_PAD {
        lines.push(Line::from(""));
    }

    // Height prediction must use the same width as ratatui's Paragraph render
    // area below (area.width - 1 for right padding), not the narrower
    // pre-wrap width, otherwise long lines over-count rows by 1.
    let render_width = area.width.saturating_sub(1) as usize;
    let (line_heights, scroll) =
        compute_scroll_and_heights(state, &lines, render_width, area.height, msg_line_count);

    // ── Fill output area background (theme-aware) ────────────────────────
    for row in area.y..area.y + area.height {
        for col in area.x..area.x + area.width {
            buf[(col, row)].set_bg(theme.bg);
        }
    }

    // ── Render text (Paragraph handles all text + scroll) ────────────────
    // Apply 1-cell right padding to prevent text from bleeding into sidebar border.
    let render_area = Rect {
        width: area.width.saturating_sub(1),
        ..area
    };
    // Wrap enabled as safety net — pre-wrapped lines shouldn't need it,
    // but prevents any edge-case overflow into adjacent buffer cells.
    Paragraph::new(lines)
        .wrap(Wrap { trim: false })
        .scroll((scroll, 0))
        .render(render_area, buf);

    render_user_message_boxes(
        &user_box_line_ranges,
        &line_heights,
        scroll,
        area,
        theme,
        buf,
    );
}

/// Build a compact one-liner for a tool call.
///
/// Strategy by tool type:
/// - `bash`: extract the command from args_summary (JSON `command` field)
/// - `file_read` / `file_write` / `file_edit`: extract path from args_summary
/// - `search`: extract the pattern from args_summary
/// - fallback: first non-empty line of result content
fn tool_one_liner(
    name: &str,
    args_summary: &str,
    content: &crate::api::Content,
    max_width: usize,
) -> String {
    if max_width == 0 {
        return String::new();
    }

    let content_text = content.text_content();

    let text = match name {
        "bash" => {
            // args_summary is JSON like {"command":"ls -la","timeout":5000}
            let cmd = extract_json_field(args_summary, "command").unwrap_or_default();
            if cmd.is_empty() {
                // Fallback: show first meaningful line of stdout
                first_meaningful_line(&content_text)
            } else {
                cmd
            }
        }
        "file_read" => extract_json_field(args_summary, "path")
            .map(|p| short_path(&p))
            .unwrap_or_else(|| first_meaningful_line(&content_text)),
        "file_write" => extract_json_field(args_summary, "path")
            .map(|p| format!("{}", short_path(&p)))
            .unwrap_or_else(|| first_meaningful_line(&content_text)),
        "file_edit" => extract_json_field(args_summary, "path")
            .map(|p| format!("{}", short_path(&p)))
            .unwrap_or_else(|| first_meaningful_line(&content_text)),
        "search" => extract_json_field(args_summary, "pattern")
            .map(|p| format!("/{p}/"))
            .unwrap_or_else(|| first_meaningful_line(&content_text)),
        _ => {
            // For MCP and other tools: try args first, then content
            let from_args = first_meaningful_line(args_summary);
            if !from_args.is_empty() && from_args != "{" && from_args != "}" {
                from_args
            } else {
                first_meaningful_line(&content_text)
            }
        }
    };

    if text.is_empty() {
        return String::new();
    }

    truncate_to_width(&text, max_width)
}

/// Extract the first meaningful line from text, skipping JSON noise.
/// One row of the rendered diff: unchanged context, removed, or added.
enum DiffRow<'a> {
    Context(&'a str),
    Removed(&'a str),
    Added(&'a str),
}

/// Build a unified-diff-style row list from `old`/`new` strings.
///
/// Uses a common-prefix / common-suffix heuristic so the change block sits
/// between preserved context lines — the typical shape of a surgical edit.
/// This avoids the "all deletions first, all additions after" layout that
/// hides the new side whenever the old side alone fills the visible budget.
fn build_delta_rows<'a>(old: &'a str, new: &'a str) -> Vec<DiffRow<'a>> {
    let old_lines: Vec<&str> = old.lines().collect();
    let new_lines: Vec<&str> = new.lines().collect();

    // Common prefix length.
    let mut prefix = 0;
    while prefix < old_lines.len()
        && prefix < new_lines.len()
        && old_lines[prefix] == new_lines[prefix]
    {
        prefix += 1;
    }
    // Common suffix length (not overlapping the prefix on either side).
    let mut suffix = 0;
    while suffix < old_lines.len() - prefix
        && suffix < new_lines.len() - prefix
        && old_lines[old_lines.len() - 1 - suffix] == new_lines[new_lines.len() - 1 - suffix]
    {
        suffix += 1;
    }

    let mut rows: Vec<DiffRow<'a>> = Vec::new();
    // Trailing context from the prefix (up to 2 lines) — only if there is an
    // actual change to frame.
    let has_change = prefix < old_lines.len() - suffix || prefix < new_lines.len() - suffix;
    if has_change && prefix > 0 {
        let ctx_start = prefix.saturating_sub(2);
        for line in &old_lines[ctx_start..prefix] {
            rows.push(DiffRow::Context(line));
        }
    }
    for line in &old_lines[prefix..old_lines.len() - suffix] {
        rows.push(DiffRow::Removed(line));
    }
    for line in &new_lines[prefix..new_lines.len() - suffix] {
        rows.push(DiffRow::Added(line));
    }
    // Leading context from the suffix (up to 2 lines).
    if has_change && suffix > 0 {
        let ctx_len = suffix.min(2);
        let start = old_lines.len() - suffix;
        for line in &old_lines[start..start + ctx_len] {
            rows.push(DiffRow::Context(line));
        }
    }
    rows
}

/// Render a delta-style diff for file_edit (unified layout with context).
/// If truncated, appends a "click to expand" line and records a `DiffClickRegion`.
fn render_mini_diff(
    args_json: &str,
    max_width: usize,
    theme: &crate::tui::theme::Theme,
    lines: &mut Vec<Line<'static>>,
    click_regions: &mut Vec<DiffClickRegion>,
) {
    let Ok(v) = serde_json::from_str::<serde_json::Value>(args_json) else {
        return;
    };
    let old = v.get("old_string").and_then(|s| s.as_str()).unwrap_or("");
    let new = v.get("new_string").and_then(|s| s.as_str()).unwrap_or("");
    if old.is_empty() && new.is_empty() {
        return;
    }

    let pad = "      "; // 6 chars indent
    let content_w = max_width.saturating_sub(pad.len() + 2);
    let max_visible = 8; // max total diff rows shown inline

    let rows = build_delta_rows(old, new);
    if rows.is_empty() {
        return;
    }

    // Summary header: + added / − removed counts.
    let added = rows
        .iter()
        .filter(|r| matches!(r, DiffRow::Added(_)))
        .count();
    let removed = rows
        .iter()
        .filter(|r| matches!(r, DiffRow::Removed(_)))
        .count();
    if added + removed > 0 {
        lines.push(Line::from(Span::styled(
            format!("{pad}+{added} \u{2212}{removed}"),
            Style::default().fg(theme.text_muted),
        )));
    }

    // Truncate with preference for showing both sides of the change block.
    let total = rows.len();
    let truncated = total > max_visible;
    let shown: Vec<&DiffRow<'_>> = if truncated {
        pick_visible_rows(&rows, max_visible)
    } else {
        rows.iter().collect()
    };

    for row in &shown {
        let (symbol, text, fg, bg): (char, &str, Color, Option<Color>) = match row {
            DiffRow::Context(t) => (' ', t, theme.text_muted, None),
            DiffRow::Removed(t) => (
                '\u{2212}',
                t,
                theme.diff_remove_fg,
                Some(theme.diff_remove_bg),
            ),
            DiffRow::Added(t) => ('+', t, theme.diff_add_fg, Some(theme.diff_add_bg)),
        };
        let display = truncate_to_width(text.trim_end(), content_w);
        // Pad to fill content_w so the background stripe extends to the full line width.
        let text_w = UnicodeWidthStr::width(display.as_str());
        let fill = content_w.saturating_sub(text_w + 2); // +2 for "symbol "
        let line_str = format!("{pad}{symbol} {display}{:fill$}", "", fill = fill);
        let style = if let Some(bg_color) = bg {
            Style::default().fg(fg).bg(bg_color)
        } else {
            Style::default().fg(fg)
        };
        lines.push(Line::from(Span::styled(line_str, style)));
    }

    if truncated {
        let remaining = total - shown.len();
        let click_line_idx = lines.len();
        lines.push(Line::from(Span::styled(
            format!("{pad}  ... {remaining} more lines (click to expand)"),
            Style::default().fg(theme.text_muted).italic(),
        )));

        // Build popup content from the same `rows` already computed above
        // (avoids re-running a second diff algorithm that may diverge).
        let path = v.get("path").and_then(|s| s.as_str()).unwrap_or("file");
        let mut full_diff = String::new();
        for row in &rows {
            match row {
                DiffRow::Context(t) => full_diff.push_str(&format!("  {t}\n")),
                DiffRow::Removed(t) => full_diff.push_str(&format!("\u{2212} {t}\n")),
                DiffRow::Added(t) => full_diff.push_str(&format!("+ {t}\n")),
            }
        }

        click_regions.push(DiffClickRegion {
            line_index: click_line_idx,
            title: format!("file_edit \u{270E} {}", short_path(path)),
            content: full_diff,
        });
    }
}

/// Pick at most `budget` rows to display inline, biased to keep both the
/// removed and added sides of the change visible. Context lines are dropped
/// first, then whichever side is longest is trimmed.
fn pick_visible_rows<'a>(rows: &'a [DiffRow<'a>], budget: usize) -> Vec<&'a DiffRow<'a>> {
    if rows.len() <= budget {
        return rows.iter().collect();
    }
    // Indices by kind, in original order.
    let ctx: Vec<usize> = rows
        .iter()
        .enumerate()
        .filter(|(_, r)| matches!(r, DiffRow::Context(_)))
        .map(|(i, _)| i)
        .collect();
    let rem: Vec<usize> = rows
        .iter()
        .enumerate()
        .filter(|(_, r)| matches!(r, DiffRow::Removed(_)))
        .map(|(i, _)| i)
        .collect();
    let add: Vec<usize> = rows
        .iter()
        .enumerate()
        .filter(|(_, r)| matches!(r, DiffRow::Added(_)))
        .map(|(i, _)| i)
        .collect();

    // Start by allocating the full change block, then drop from the longest
    // side until we fit (leaving at least 1 of each if both exist).
    let mut keep_rem = rem.len();
    let mut keep_add = add.len();
    let min_rem = if rem.is_empty() { 0 } else { 1 };
    let min_add = if add.is_empty() { 0 } else { 1 };
    while keep_rem + keep_add > budget {
        if keep_rem > keep_add && keep_rem > min_rem {
            keep_rem -= 1;
        } else if keep_add > min_add {
            keep_add -= 1;
        } else if keep_rem > min_rem {
            keep_rem -= 1;
        } else {
            break;
        }
    }
    // Fill remaining budget with context lines closest to the change block.
    let remaining_budget = budget.saturating_sub(keep_rem + keep_add);
    let ctx_keep = ctx.len().min(remaining_budget);

    let mut keep: std::collections::BTreeSet<usize> = std::collections::BTreeSet::new();
    keep.extend(rem.iter().take(keep_rem));
    keep.extend(add.iter().take(keep_add));
    keep.extend(ctx.iter().take(ctx_keep));

    keep.into_iter().map(|i| &rows[i]).collect()
}

/// Render a compact preview for file_write: show first few lines of content.
/// If truncated, appends a "click to expand" line and records a `DiffClickRegion`.
fn render_write_preview(
    args_json: &str,
    max_width: usize,
    theme: &crate::tui::theme::Theme,
    lines: &mut Vec<Line<'static>>,
    click_regions: &mut Vec<DiffClickRegion>,
) {
    let Ok(v) = serde_json::from_str::<serde_json::Value>(args_json) else {
        return;
    };
    let content = v.get("content").and_then(|s| s.as_str()).unwrap_or("");
    if content.is_empty() {
        return;
    }

    let total_lines = content.lines().count();
    let pad = "      ";
    let content_w = max_width.saturating_sub(pad.len() + 2);
    let max_show = 6;

    for (i, line) in content.lines().enumerate() {
        if i >= max_show {
            break;
        }
        let display = truncate_to_width(line.trim_end(), content_w);
        let text_w = UnicodeWidthStr::width(display.as_str());
        let fill = content_w.saturating_sub(text_w + 2);
        let line_str = format!("{pad}+ {display}{:fill$}", "", fill = fill);
        lines.push(Line::from(Span::styled(
            line_str,
            Style::default().fg(theme.diff_add_fg).bg(theme.diff_add_bg),
        )));
    }

    if total_lines > max_show {
        let remaining = total_lines - max_show;
        let click_line_idx = lines.len();
        lines.push(Line::from(Span::styled(
            format!("{pad}  ... {remaining} more lines (click to expand)"),
            Style::default().fg(theme.text_muted).italic(),
        )));

        // Build unified-diff content for popup (new file = all additions).
        let path = v.get("path").and_then(|s| s.as_str()).unwrap_or("file");
        let mut full_content = String::new();
        full_content.push_str("--- /dev/null\n");
        full_content.push_str(&format!("+++ b/{path}\n"));
        full_content.push_str(&format!("@@ -0,0 +1,{total_lines} @@\n"));
        for line in content.lines() {
            full_content.push('+');
            full_content.push_str(line);
            full_content.push('\n');
        }

        click_regions.push(DiffClickRegion {
            line_index: click_line_idx,
            title: format!("file_write \u{2192} {}", short_path(path)),
            content: full_content,
        });
    }
}

fn first_meaningful_line(text: &str) -> String {
    // If text looks like a JSON object, try to extract a useful field
    if text.trim_start().starts_with('{')
        && let Ok(v) = serde_json::from_str::<serde_json::Value>(text)
    {
        // bash tool: prefer stdout, then stderr
        if let Some(stdout) = v.get("stdout").and_then(|s| s.as_str()) {
            let line = stdout
                .lines()
                .find(|l| !l.trim().is_empty())
                .unwrap_or("")
                .trim();
            if !line.is_empty() {
                return line.to_string();
            }
        }
        if let Some(stderr) = v.get("stderr").and_then(|s| s.as_str()) {
            let line = stderr
                .lines()
                .find(|l| !l.trim().is_empty())
                .unwrap_or("")
                .trim();
            if !line.is_empty() {
                return line.to_string();
            }
        }
        // Generic: try "result", "output", "message", "content" fields
        for key in &["result", "output", "message", "content", "text"] {
            if let Some(val) = v.get(key).and_then(|s| s.as_str()) {
                let line = val
                    .lines()
                    .find(|l| !l.trim().is_empty())
                    .unwrap_or("")
                    .trim();
                if !line.is_empty() {
                    return line.to_string();
                }
            }
        }
    }
    // Fallback: first non-JSON-noise line
    text.lines()
        .map(|l| l.trim())
        .find(|l| {
            !l.is_empty()
                && *l != "{"
                && *l != "}"
                && *l != "["
                && *l != "]"
                && *l != "{}"
                && !l.starts_with('"') // skip JSON field lines like "exit_code": 0,
        })
        .unwrap_or("")
        .to_string()
}

/// Extract a string field from a JSON-like string.
fn extract_json_field(json_str: &str, field: &str) -> Option<String> {
    serde_json::from_str::<serde_json::Value>(json_str)
        .ok()
        .and_then(|v| v.get(field).and_then(|f| f.as_str()).map(|s| s.to_string()))
}

/// Shorten a file path to just the last 2 components.
fn short_path(path: &str) -> String {
    let parts: Vec<&str> = path.rsplit('/').take(2).collect();
    if parts.len() == 2 {
        format!("{}/{}", parts[1], parts[0])
    } else {
        parts.first().unwrap_or(&path).to_string()
    }
}

/// Truncate a string to max_width, adding `…` if needed.
fn truncate_to_width(text: &str, max_width: usize) -> String {
    if text.len() <= max_width {
        text.to_string()
    } else {
        let boundary = text
            .char_indices()
            .map(|(i, _)| i)
            .take_while(|&i| i < max_width.saturating_sub(1))
            .last()
            .unwrap_or(0);
        format!("{}", &text[..boundary])
    }
}

/// Render a role header line: `  ✦ Name ─────────────────`
fn render_role_header(name: &str, color: Color, theme: &Theme, lines: &mut Vec<Line>) {
    let badge = format!("{name}");
    let sep = format!(" {}", "".repeat(40));
    lines.push(Line::from(vec![
        Span::styled(badge, Style::default().fg(color).bold()),
        Span::styled(sep, Style::default().fg(theme.border).dim()),
    ]));
}

/// Render Markdown-formatted text into styled ratatui Lines.
/// `width` is the full render area width; content is pre-wrapped to fit.
fn render_markdown(text: &str, lines: &mut Vec<Line>, theme: &Theme, width: usize) {
    let mut in_code_block = false;
    const BASE_INDENT: usize = 4; // "    "
    const BULLET_INDENT: usize = 6; // "    • "

    for line in text.lines() {
        let trimmed = line.trim();

        // Code block toggle
        if trimmed.starts_with("```") {
            in_code_block = !in_code_block;
            let label = if in_code_block {
                let lang = trimmed.strip_prefix("```").unwrap_or("").trim();
                if lang.is_empty() {
                    "    ╭── code ──".to_string()
                } else {
                    format!("    ╭── {lang} ──")
                }
            } else {
                "    ╰──────────".to_string()
            };
            lines.push(Line::from(Span::styled(
                label,
                Style::default().fg(theme.md_code).dim(),
            )));
            continue;
        }

        if in_code_block {
            // Code lines: no wrapping, scroll horizontally is not supported but at least show as-is
            lines.push(Line::from(Span::styled(
                format!("{line}"),
                Style::default().fg(theme.md_code),
            )));
            continue;
        }

        // Headers — wrap to width
        if let Some(rest) = trimmed
            .strip_prefix("### ")
            .or_else(|| trimmed.strip_prefix("## "))
            .or_else(|| trimmed.strip_prefix("# "))
        {
            let content_w = width.saturating_sub(BASE_INDENT);
            for wl in wrap_to_width(rest, content_w) {
                lines.push(Line::from(Span::styled(
                    format!("    {wl}"),
                    Style::default().fg(theme.md_header).bold(),
                )));
            }
        }
        // Bullet lists — wrap with hanging indent at bullet width
        else if trimmed.starts_with("- ") || trimmed.starts_with("* ") {
            let content = &trimmed[2..];
            let content_w = width.saturating_sub(BULLET_INDENT);
            let wrapped = wrap_to_width(content, content_w);
            let continuation_pad = " ".repeat(BULLET_INDENT);
            for (i, wl) in wrapped.iter().enumerate() {
                if i == 0 {
                    let mut spans =
                        vec![Span::styled("", Style::default().fg(theme.md_bullet))];
                    spans.extend(parse_inline_markdown(wl, theme));
                    lines.push(Line::from(spans));
                } else {
                    let mut spans = vec![Span::raw(continuation_pad.clone())];
                    spans.extend(parse_inline_markdown(wl, theme));
                    lines.push(Line::from(spans));
                }
            }
        }
        // Numbered lists — wrap with hanging indent
        else if trimmed.len() > 2
            && trimmed.as_bytes()[0].is_ascii_digit()
            && trimmed.contains(". ")
        {
            if let Some(dot_pos) = trimmed.find(". ") {
                let num = &trimmed[..dot_pos];
                if num.chars().all(|c| c.is_ascii_digit()) {
                    let content = &trimmed[dot_pos + 2..];
                    let num_prefix = format!("    {num}. ");
                    let prefix_w = UnicodeWidthStr::width(num_prefix.as_str());
                    let content_w = width.saturating_sub(prefix_w);
                    let wrapped = wrap_to_width(content, content_w);
                    let continuation_pad = " ".repeat(prefix_w);
                    for (i, wl) in wrapped.iter().enumerate() {
                        if i == 0 {
                            let mut spans = vec![Span::styled(
                                num_prefix.clone(),
                                Style::default().fg(theme.md_bullet),
                            )];
                            spans.extend(parse_inline_markdown(wl, theme));
                            lines.push(Line::from(spans));
                        } else {
                            let mut spans = vec![Span::raw(continuation_pad.clone())];
                            spans.extend(parse_inline_markdown(wl, theme));
                            lines.push(Line::from(spans));
                        }
                    }
                } else {
                    let content_w = width.saturating_sub(BASE_INDENT);
                    for wl in wrap_to_width(trimmed, content_w) {
                        let mut spans = vec![Span::raw("    ")];
                        spans.extend(parse_inline_markdown(&wl, theme));
                        lines.push(Line::from(spans));
                    }
                }
            }
        }
        // Normal text with inline markdown — wrap at BASE_INDENT
        else {
            let content_w = width.saturating_sub(BASE_INDENT);
            for wl in wrap_to_width(trimmed, content_w) {
                let mut spans = vec![Span::raw("    ")];
                spans.extend(parse_inline_markdown(&wl, theme));
                lines.push(Line::from(spans));
            }
        }
    }
}

/// Parse inline Markdown: **bold**, `code`, *italic*.
fn parse_inline_markdown(text: &str, theme: &Theme) -> Vec<Span<'static>> {
    let mut spans = Vec::new();
    let mut remaining = text;

    while !remaining.is_empty() {
        let bold_pos = remaining.find("**");
        let code_pos = remaining.find('`');

        let next = match (bold_pos, code_pos) {
            (Some(b), Some(c)) => {
                if b <= c {
                    ("**", b)
                } else {
                    ("`", c)
                }
            }
            (Some(b), None) => ("**", b),
            (None, Some(c)) => ("`", c),
            (None, None) => {
                spans.push(Span::styled(
                    remaining.to_string(),
                    Style::default().fg(theme.text),
                ));
                break;
            }
        };

        let (marker, pos) = next;

        if pos > 0 {
            spans.push(Span::styled(
                remaining[..pos].to_string(),
                Style::default().fg(theme.text),
            ));
        }

        let after = &remaining[pos + marker.len()..];

        if let Some(end) = after.find(marker) {
            let inner = &after[..end];
            let style = if marker == "**" {
                Style::default().fg(theme.text).bold()
            } else {
                Style::default().fg(theme.md_code).bg(theme.md_code_bg)
            };
            spans.push(Span::styled(inner.to_string(), style));
            remaining = &after[end + marker.len()..];
        } else {
            spans.push(Span::styled(
                remaining[pos..pos + marker.len()].to_string(),
                Style::default().fg(theme.text),
            ));
            remaining = after;
        }
    }

    spans
}

/// Format elapsed seconds as human-readable: "5s", "2m 30s", "1h 5m".
fn format_elapsed(secs: u64) -> String {
    if secs < 60 {
        format!("{secs}s")
    } else if secs < 3600 {
        format!("{}m {}s", secs / 60, secs % 60)
    } else {
        format!("{}h {}m", secs / 3600, (secs % 3600) / 60)
    }
}

/// Returns " · retry N/M" string when a stream retry is in progress, empty otherwise.
fn retry_suffix(state: &crate::tui::state::UiState) -> String {
    if state.stream_retry > 0 {
        format!(
            " · retry {}/{}",
            state.stream_retry, state.stream_max_retries
        )
    } else {
        String::new()
    }
}

/// Render the "attached to worker" view — shows worker's full streaming output and tool log.
fn render_worker_view(
    state: &UiState,
    area: Rect,
    buf: &mut Buffer,
    agent_id: &str,
    detail: &crate::tui::state::WorkerDetailState,
) {
    let theme = &state.theme;
    let inner_width = area.width.saturating_sub(2) as usize;
    let mut lines: Vec<Line> = Vec::new();

    // Header: agent info
    let agent_info = state
        .swarm_status
        .as_ref()
        .and_then(|h| h.agents.iter().find(|a| a.agent_id == agent_id));

    let (agent_name, status_str, status_color) = if let Some(entry) = agent_info {
        let (color, label) = match &entry.status {
            crate::tui::state::SwarmAgentStatus::Pending => (theme.text_muted, "PENDING"),
            crate::tui::state::SwarmAgentStatus::Running => (theme.accent, "RUNNING"),
            crate::tui::state::SwarmAgentStatus::Paused => (theme.warning, "PAUSED"),
            crate::tui::state::SwarmAgentStatus::Completed { success: true } => {
                (theme.success, "COMPLETED")
            }
            crate::tui::state::SwarmAgentStatus::Completed { success: false } => {
                (theme.error, "FAILED")
            }
        };
        (entry.name.as_str(), label, color)
    } else {
        ("unknown", "UNKNOWN", theme.text_muted)
    };

    // ── Title bar ──
    lines.push(Line::from(vec![
        Span::styled("", Style::default().fg(status_color).bold()),
        Span::styled(
            format!("[{agent_id}] {agent_name}"),
            Style::default().fg(theme.accent).bold(),
        ),
        Span::styled(
            format!("  {status_str}"),
            Style::default().fg(status_color).bold(),
        ),
        Span::styled("  (Esc to detach)", Style::default().fg(theme.text_muted)),
    ]));

    // Task preview
    if let Some(entry) = agent_info {
        if !entry.task_preview.is_empty() {
            lines.push(Line::from(vec![
                Span::styled("  task: ", Style::default().fg(theme.text_muted)),
                Span::styled(
                    entry.task_preview.as_str().to_string(),
                    Style::default().fg(theme.text_dim),
                ),
            ]));
        }
        // Stats line
        let stats = format!(
            "  iter:{} tools:{} tokens:{}↑/{}",
            entry.iteration, entry.tool_calls, entry.input_tokens, entry.output_tokens
        );
        lines.push(Line::from(Span::styled(
            stats,
            Style::default().fg(theme.text_muted),
        )));
    }

    // Separator
    let sep: String = "".repeat(inner_width.min(80));
    lines.push(Line::from(Span::styled(
        format!("  {sep}"),
        Style::default().fg(theme.border),
    )));
    lines.push(Line::from(""));

    // ── Tool events log ──
    if !detail.tool_events.is_empty() {
        let recent_start = detail.tool_events.len().saturating_sub(10);
        for evt in &detail.tool_events[recent_start..] {
            let (icon, color) = if evt.result_preview == "running..." {
                ("", theme.accent)
            } else if evt.success {
                ("", theme.success)
            } else {
                ("", theme.error)
            };
            let args_short = if evt.args_preview.len() > 60 {
                let boundary = evt
                    .args_preview
                    .char_indices()
                    .take_while(|&(i, _)| i <= 60)
                    .last()
                    .map(|(i, _)| i)
                    .unwrap_or(0);
                format!("{}", &evt.args_preview[..boundary])
            } else {
                evt.args_preview.clone()
            };
            lines.push(Line::from(vec![
                Span::styled(format!("  {icon} "), Style::default().fg(color)),
                Span::styled(evt.name.clone(), Style::default().fg(theme.accent).bold()),
                Span::styled(
                    format!(" {args_short}"),
                    Style::default().fg(theme.text_dim),
                ),
            ]));
            if evt.result_preview != "running..." {
                let result_short = if evt.result_preview.len() > 80 {
                    let boundary = evt
                        .result_preview
                        .char_indices()
                        .take_while(|&(i, _)| i <= 80)
                        .last()
                        .map(|(i, _)| i)
                        .unwrap_or(0);
                    format!("{}", &evt.result_preview[..boundary])
                } else {
                    evt.result_preview.clone()
                };
                lines.push(Line::from(Span::styled(
                    format!("{result_short}"),
                    Style::default().fg(theme.text_muted),
                )));
            }
        }
        lines.push(Line::from(""));
    }

    // ── Streaming output ──
    if !detail.full_stream.is_empty() {
        render_markdown(&detail.full_stream, &mut lines, theme, inner_width);
    } else {
        lines.push(Line::from(Span::styled(
            "  Waiting for output...",
            Style::default().fg(theme.text_muted).italic(),
        )));
    }

    // Current tool indicator
    if let Some(entry) = agent_info
        && let Some(ref tool) = entry.current_tool
    {
        lines.push(Line::from(""));
        let thinking_spans = state
            .spinner
            .thinking_label(&format!("Running {tool}"), theme);
        lines.push(Line::from(thinking_spans));
    }

    // Bottom padding
    for _ in 0..3 {
        lines.push(Line::from(""));
    }

    // ── Scroll ──
    // Divide by the render width (area.width - 1) so height predictions
    // match what ratatui's Paragraph actually produces. See the comment on
    // `compute_scroll_and_heights` for details on why the pre-wrap width
    // must not be used here.
    let render_width = area.width.saturating_sub(1) as usize;
    let line_heights: Vec<u16> = lines
        .iter()
        .map(|l| line_visual_height(l, render_width))
        .collect();

    let visual_height: u16 = line_heights.iter().sum::<u16>().saturating_add(2);
    let view_height = area.height;
    let max_scroll = visual_height.saturating_sub(view_height);

    // Auto-scroll to bottom for attached worker
    let scroll = if detail.auto_scroll {
        max_scroll
    } else {
        max_scroll.saturating_sub(detail.scroll_offset)
    };

    // Fill background
    for row in area.y..area.y + area.height {
        for col in area.x..area.x + area.width {
            buf[(col, row)].set_bg(theme.bg);
        }
    }

    let render_area = Rect {
        width: area.width.saturating_sub(1),
        ..area
    };
    Paragraph::new(lines)
        .wrap(Wrap { trim: false })
        .scroll((scroll, 0))
        .render(render_area, buf);
}