oxi-tui 0.17.0

Terminal UI widgets and theme system for oxi, built on ratatui
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
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
//! ChatView widget — scrollable message list with streaming support.
//!
//! Renders layout entries directly into the frame buffer. Only visible
//! entries (those within the scroll viewport) are rendered, avoiding the
//! overhead of a virtual buffer. Scroll offset is managed directly.
//!
//! Benefits:
//! - Tool/error boxes use Block::bordered() — real ratatui borders
//! - Text uses Paragraph::wrap(Wrap) — proper word-wrapping
//! - No virtual buffer — direct rendering, no double-write
//! - Layout caching — only recomputes when state actually changes
//! - Truncation at ingest — no height inflation from monster inputs

use std::collections::HashMap;

use parking_lot::RwLock;
use ratatui::{
    buffer::Buffer,
    layout::Rect,
    style::{Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Clear, Paragraph, StatefulWidget, Widget, Wrap},
};
use tui_markdown;

use crate::table_renderer::render_markdown_table;
use crate::text::truncate_to_width as truncate_str;
use crate::theme::ThemeStyles;
use crate::Theme;

// ── Limits (truncation at ingest) ──────────────────────────────────────

const MAX_TOOL_ARG_CHARS: usize = 50_000;
const MAX_TOOL_ARG_LINES: usize = 200;
const MAX_TOOL_RESULT_CHARS: usize = 50_000;
const MAX_TOOL_RESULT_LINES: usize = 100;
const MAX_TEXT_CHARS: usize = 500_000;

fn clamp_str(s: String, max_chars: usize, max_lines: usize) -> String {
    let n = s.chars().count();
    let lines = s.lines().count();
    if n <= max_chars && lines <= max_lines {
        return s;
    }
    let truncated: String = s.chars().take(max_chars).collect();
    let truncated_lines: Vec<&str> = truncated.lines().take(max_lines).collect();
    let mut result = truncated_lines.join("\n");
    // Add overflow marker if we cut anything
    if n > max_chars || lines > max_lines {
        result.push_str("\n ...");
    }
    result
}

// ── Tool Call Tracker ─────────────────────────────────────────────────

#[derive(Debug, Default)]
struct ToolCallTracker {
    active: HashMap<String, usize>,
}

impl ToolCallTracker {
    fn register(&mut self, id: String, index: usize) -> bool {
        if self.active.contains_key(&id) {
            return false;
        }
        self.active.insert(id, index);
        true
    }
    fn find_and_remove(&mut self, id: &str) -> Option<usize> {
        self.active.remove(id)
    }
    fn remove(&mut self, id: &str) {
        self.active.remove(id);
    }
    fn get(&self, id: &str) -> Option<usize> {
        self.active.get(id).copied()
    }
    fn clear(&mut self) {
        self.active.clear();
    }
}

// ── Types ──────────────────────────────────────────────────────────────

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToolCallStatus {
    Requested,
    Executing,
    Done,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MessageRole {
    User,
    Assistant,
    System,
}

#[derive(Debug, Clone)]
pub enum ContentBlock {
    Text {
        content: String,
    },
    Thinking {
        content: String,
        collapsed: bool,
    },
    ToolCall {
        id: String,
        name: String,
        arguments: String,
        result: Option<(String, bool)>,
        status: ToolCallStatus,
        /// Formatted execution duration (e.g. "1.2s").
        duration: Option<String>,
    },
    ToolResult {
        tool_name: String,
        content: String,
        is_error: bool,
    },
    Error {
        title: String,
        message: String,
        retryable: bool,
    },
    Image {
        mime_type: String,
        base64_data: String,
    },
}

#[derive(Debug, Clone)]
pub struct ChatMessage {
    pub role: MessageRole,
    pub content_blocks: Vec<ContentBlock>,
    pub timestamp: i64,
}

#[derive(Debug, Clone)]
pub struct StreamingState {
    pub message: ChatMessage,
}

// ── Layout Cache ──────────────────────────────────────────────────────
//
// Caches the result of compute_layout(). Invalidated when any of these change:
// - messages.len()
// - streaming content block count
// - spinner_frame
// - width
//
// Uses parking_lot::RwLock so multiple readers can access concurrently.

#[derive(Default)]
struct LayoutCache {
    /// Last known messages count
    msg_count: usize,
    /// Last known streaming block count
    streaming_len: usize,
    /// Last known streaming text character count (detects content growth)
    streaming_text_len: usize,
    /// Last known spinner frame
    spinner_frame: usize,
    /// Last known width
    width: u16,
    /// Cached layout entries (None = needs recompute)
    entries: Option<Vec<LayoutEntry>>,
    /// Cached total content height
    total_height: u16,
}

impl std::fmt::Debug for LayoutCache {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("LayoutCache")
            .field("msg_count", &self.msg_count)
            .field("streaming_len", &self.streaming_len)
            .field("streaming_text_len", &self.streaming_text_len)
            .field("spinner_frame", &self.spinner_frame)
            .field("width", &self.width)
            .field("entries", &self.entries.as_ref().map(|v| v.len()))
            .field("total_height", &self.total_height)
            .finish()
    }
}

// ── ChatViewState ──────────────────────────────────────────────────────

#[derive(Debug, Default)]
pub struct ChatViewState {
    pub messages: Vec<ChatMessage>,
    pub streaming: Option<StreamingState>,
    pub spinner_frame: usize,
    pub content_height: u16,
    pub last_code_block: Option<String>,
    pub pending_images: Vec<(String, String)>,
    tool_tracker: ToolCallTracker,
    /// Vertical scroll offset (0 = top)
    pub scroll_offset: u16,
    /// When true, auto-scroll to bottom on each render (streaming)
    pub auto_scroll: bool,
    /// Layout cache — guarded by RwLock
    layout_cache: RwLock<LayoutCache>,
}

impl ChatViewState {
    pub fn new() -> Self {
        Self::default()
    }

    /// Scroll to bottom of content. `visible_height` is the viewport height.
    pub fn scroll_to_bottom(&mut self, visible_height: u16) {
        self.auto_scroll = true;
        if self.content_height > visible_height {
            self.scroll_offset = self.content_height - visible_height;
        } else {
            self.scroll_offset = 0;
        }
    }
    pub fn scroll_up(&mut self, n: u16) {
        self.auto_scroll = false;
        self.scroll_offset = self.scroll_offset.saturating_sub(n);
    }
    pub fn scroll_down(&mut self, n: u16) {
        let max = self.max_scroll_offset();
        self.scroll_offset = (self.scroll_offset + n).min(max);
    }
    pub fn scroll_to_top(&mut self) {
        self.auto_scroll = false;
        self.scroll_offset = 0;
    }
    /// Maximum scroll offset (content_height - 1 visible line, so
    /// at least one line is always visible).
    fn max_scroll_offset(&self) -> u16 {
        // We don't know visible_height here, so return content_height.
        // The caller clamps via visible_height.
        self.content_height
    }
    /// Clamp scroll_offset to [0, content_height - visible_height].
    fn clamp_scroll(&mut self, visible_height: u16) {
        let max_off = self.content_height.saturating_sub(visible_height);
        self.scroll_offset = self.scroll_offset.min(max_off);
    }

    pub fn start_streaming(&mut self) {
        // Auto-commit any existing streaming before starting new.
        // This prevents tool execution results from being lost when
        // a new MessageStart arrives while tool results are streaming.
        if self.streaming.is_some() {
            self.finish_streaming();
        }
        self.streaming = Some(StreamingState {
            message: ChatMessage {
                role: MessageRole::Assistant,
                content_blocks: Vec::new(),
                timestamp: 0,
            },
        });
        self.tool_tracker.clear();
        // Streaming lifecycle changes should always invalidate layout.
        self.layout_cache.write().entries = None;
    }

    pub fn stream_text_delta(&mut self, delta: &str) {
        self.append_text(delta);
        self.update_last_code_block();
    }

    fn append_text(&mut self, text: &str) {
        if let Some(ref mut s) = self.streaming {
            // NOTE: We no longer drop pure-whitespace deltas. In the pi-mono
            // pattern, `new_text` is extracted from the provider's accumulated
            // snapshot, so spaces between words are legitimate content.
            // Dropping them caused Korean word-spacing to vanish (e.g.
            // "안녕 하세요" → "안녕하세요").
            //
            // Previously we filtered whitespace-only deltas to remove "noise
            // from providers around tool calls", but the proper fix is to
            // handle that at the provider layer, not at the TUI layer.

            if let Some(ContentBlock::Text { ref mut content }) =
                s.message.content_blocks.first_mut()
            {
                // Clamp total text size to prevent unbounded growth
                if content.chars().count() > MAX_TEXT_CHARS {
                    return;
                }
                let new_chars = text.chars().count();
                if content.chars().count() + new_chars > MAX_TEXT_CHARS {
                    // Truncate delta if it would exceed the limit
                    let remaining = MAX_TEXT_CHARS.saturating_sub(content.chars().count());
                    let taken: String = text.chars().take(remaining).collect();
                    content.push_str(&taken);
                } else {
                    content.push_str(text);
                }
            } else {
                let truncated = if text.chars().count() > MAX_TEXT_CHARS {
                    let c: String = text.chars().take(MAX_TEXT_CHARS).collect();
                    format!("{}\n ...", c)
                } else {
                    text.to_string()
                };
                s.message
                    .content_blocks
                    .insert(0, ContentBlock::Text { content: truncated });
            }
        }
    }

    pub fn is_streaming(&self) -> bool {
        self.streaming.is_some()
    }

    fn update_last_code_block(&mut self) {
        if let Some(ref s) = self.streaming {
            if let Some(ContentBlock::Text { ref content, .. }) = s.message.content_blocks.first() {
                if let Some(code) = extract_last_code_block(content) {
                    self.last_code_block = Some(code);
                }
            }
        }
    }

    pub fn refresh_last_code_block(&mut self) {
        if let Some(ref s) = self.streaming {
            if let Some(ContentBlock::Text { ref content, .. }) = s.message.content_blocks.first() {
                if let Some(code) = extract_last_code_block(content) {
                    self.last_code_block = Some(code);
                }
            }
        }
    }

    pub fn set_tool_status(&mut self, id: &str, status: ToolCallStatus) {
        if let Some(ref mut s) = self.streaming {
            if let Some(idx) = self.tool_tracker.get(id) {
                if let Some(ContentBlock::ToolCall {
                    status: ref mut curr,
                    ..
                }) = s.message.content_blocks.get_mut(idx)
                {
                    *curr = status;
                }
                self.layout_cache.write().entries = None;
            }
        }
    }

    pub fn stream_tool_call(
        &mut self,
        id: String,
        name: String,
        arguments: String,
        status: ToolCallStatus,
    ) {
        // If streaming has already finished (e.g., MessageEnd came before
        // ToolExecutionStart), start a new streaming message so the tool
        // call block is visible in the UI.
        if self.streaming.is_none() {
            self.start_streaming();
        }
        if let Some(ref mut s) = self.streaming {
            // Check if this tool call was already registered (e.g., from
            // a prior MessageUpdate that included ToolCall blocks).
            if let Some(existing_idx) = self.tool_tracker.get(&id) {
                if let Some(ContentBlock::ToolCall {
                    status: ref mut s, ..
                }) = s.message.content_blocks.get_mut(existing_idx)
                {
                    *s = status;
                }
                self.layout_cache.write().entries = None;
                return;
            }
            let idx = s.message.content_blocks.len();
            if !self.tool_tracker.register(id.clone(), idx) {
                return;
            }
            s.message.content_blocks.push(ContentBlock::ToolCall {
                id,
                name,
                arguments: clamp_str(arguments, MAX_TOOL_ARG_CHARS, MAX_TOOL_ARG_LINES),
                result: None,
                status,
                duration: None,
            });
            self.layout_cache.write().entries = None;
        }
    }

    pub fn stream_tool_result(
        &mut self,
        tool_call_id: Option<String>,
        tool_name: String,
        content: String,
        is_error: bool,
    ) {
        if self.streaming.is_none() {
            self.start_streaming();
        }
        if let Some(ref mut s) = self.streaming {
            if let Some(ref id) = tool_call_id {
                if let Some(idx) = self.tool_tracker.find_and_remove(id) {
                    if let Some(ContentBlock::ToolCall {
                        ref mut result,
                        ref mut status,
                        ..
                    }) = s.message.content_blocks.get_mut(idx)
                    {
                        *result = Some((
                            clamp_str(content, MAX_TOOL_RESULT_CHARS, MAX_TOOL_RESULT_LINES),
                            is_error,
                        ));
                        *status = ToolCallStatus::Done;
                        self.layout_cache.write().entries = None;
                        return;
                    }
                }
            }
            if let Some(ContentBlock::ToolCall {
                ref mut result,
                ref mut status,
                ..
            }) = s.message.content_blocks.last_mut()
            {
                *result = Some((
                    clamp_str(content, MAX_TOOL_RESULT_CHARS, MAX_TOOL_RESULT_LINES),
                    is_error,
                ));
                *status = ToolCallStatus::Done;
                if let Some(ref id) = tool_call_id {
                    self.tool_tracker.remove(id);
                }
                self.layout_cache.write().entries = None;
                return;
            }
            s.message.content_blocks.push(ContentBlock::ToolResult {
                tool_name,
                content: clamp_str(content, MAX_TOOL_RESULT_CHARS, MAX_TOOL_RESULT_LINES),
                is_error,
            });
            self.layout_cache.write().entries = None;
        }
    }

    pub fn stream_error(&mut self, title: String, message: String, retryable: bool) {
        if let Some(ref mut s) = self.streaming {
            s.message.content_blocks.push(ContentBlock::Error {
                title,
                message: clamp_str(message, 5000, 50),
                retryable,
            });
            self.layout_cache.write().entries = None;
        }
    }

    pub fn stream_thinking(&mut self, content: String, collapsed: bool) {
        if let Some(ref mut s) = self.streaming {
            if let Some(ContentBlock::Thinking {
                content: existing, ..
            }) = s.message.content_blocks.last_mut()
            {
                existing.push_str(&content);
                *existing = clamp_str(existing.clone(), 50_000, 200);
            } else {
                s.message.content_blocks.push(ContentBlock::Thinking {
                    content: clamp_str(content, 50_000, 200),
                    collapsed,
                });
            }
            self.layout_cache.write().entries = None;
        }
    }

    pub fn stream_image(&mut self, mime_type: String, base64_data: String) {
        if let Some(ref mut s) = self.streaming {
            // Track for Ctrl+I viewer
            self.pending_images
                .push((base64_data.clone(), mime_type.clone()));
            s.message.content_blocks.push(ContentBlock::Image {
                mime_type,
                base64_data,
            });
            self.layout_cache.write().entries = None;
        }
    }

    pub fn finish_streaming(&mut self) {
        if let Some(mut s) = self.streaming.take() {
            // Drop whitespace-only blocks so they don't render as multi-line blank gaps.
            s.message.content_blocks.retain(|b| match b {
                ContentBlock::Text { content } => !content.trim().is_empty(),
                ContentBlock::Thinking { content, .. } => !content.trim().is_empty(),
                _ => true,
            });

            // Don't push empty assistant messages (they only add spacer rows).
            if !s.message.content_blocks.is_empty() {
                self.messages.push(s.message);
            }
        }
        self.tool_tracker.clear();
        // Invalidate cache
        let mut cache = self.layout_cache.write();
        cache.entries = None;
    }

    pub fn cancel_streaming(&mut self) {
        self.streaming = None;
        // Invalidate cache
        let mut cache = self.layout_cache.write();
        cache.entries = None;
    }

    /// Set the formatted duration for a tool call (by ID).
    pub fn set_tool_duration(&mut self, id: &str, dur_str: String) {
        if let Some(ref mut s) = self.streaming {
            for block in &mut s.message.content_blocks {
                if let ContentBlock::ToolCall {
                    id: ref bid,
                    ref mut duration,
                    ..
                } = block
                {
                    if bid == id {
                        *duration = Some(dur_str);
                        self.layout_cache.write().entries = None;
                        return;
                    }
                }
            }
        }
    }

    pub fn clear(&mut self) {
        self.messages.clear();
        self.streaming = None;
        self.scroll_offset = 0;
        self.auto_scroll = false;
        self.last_code_block = None;
        self.pending_images.clear();
        self.tool_tracker.clear();
        let mut cache = self.layout_cache.write();
        cache.entries = None;
    }

    pub fn push_message(&mut self, msg: ChatMessage) {
        self.messages.push(msg);
        let mut cache = self.layout_cache.write();
        cache.entries = None;
    }

    pub fn add_message(&mut self, msg: ChatMessage) {
        self.messages.push(msg);
        self.streaming = None;
        self.last_code_block = None;
        let mut cache = self.layout_cache.write();
        cache.entries = None;
    }

    pub fn push_system_message(&mut self, content: String) {
        self.messages.push(ChatMessage {
            role: MessageRole::System,
            content_blocks: vec![ContentBlock::Text { content }],
            timestamp: 0,
        });
        let mut cache = self.layout_cache.write();
        cache.entries = None;
    }

    /// Get cached layout entries, recomputing if needed.
    fn get_layout(&self, width: u16) -> Vec<LayoutEntry> {
        let msg_count = self.messages.len();
        let streaming_len = self
            .streaming
            .as_ref()
            .map(|s| s.message.content_blocks.len())
            .unwrap_or(0);
        let streaming_text_len = self
            .streaming
            .as_ref()
            .and_then(|s| s.message.content_blocks.first())
            .map(|b| match b {
                ContentBlock::Text { content } => content.len(),
                _ => 0,
            })
            .unwrap_or(0);
        let spinner = self.spinner_frame;

        {
            let cache = self.layout_cache.read();
            if cache.msg_count == msg_count
                && cache.streaming_len == streaming_len
                && cache.streaming_text_len == streaming_text_len
                && cache.spinner_frame == spinner
                && cache.width == width
            {
                if let Some(ref entries) = cache.entries {
                    return entries.clone();
                }
            }
        }

        // Recompute outside the read lock
        let entries = compute_layout(self, width);
        let total_height = entries
            .last()
            .map(|e| e.y.saturating_add(e.height))
            .unwrap_or(0);

        {
            let mut cache = self.layout_cache.write();
            cache.msg_count = msg_count;
            cache.streaming_len = streaming_len;
            cache.streaming_text_len = streaming_text_len;
            cache.spinner_frame = spinner;
            cache.width = width;
            cache.entries = Some(entries.clone());
            cache.total_height = total_height;
        }

        entries
    }
}

// ── Code block extraction ────────────────────────────────────────────

fn extract_last_code_block(text: &str) -> Option<String> {
    let mut result: Option<String> = None;
    let mut in_block = false;
    let mut block_content = String::new();
    for line in text.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with("```") {
            if in_block {
                let c = block_content.trim().to_string();
                if !c.is_empty() {
                    result = Some(c);
                }
                block_content.clear();
                in_block = false;
            } else {
                block_content.clear();
                in_block = true;
            }
        } else if in_block {
            if !block_content.is_empty() {
                block_content.push('\n');
            }
            block_content.push_str(line);
        }
    }
    result
}

/// Fix bare code fences (``` without a language) to ```text.
/// Tracks open/close state so closing fences are left as ```.
fn fix_bare_code_fences(content: &str) -> String {
    let mut result = String::with_capacity(content.len());
    let mut in_code = false;
    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with("```") {
            if in_code {
                // Closing fence — emit as-is
                result.push_str("```");
                in_code = false;
            } else {
                // Opening fence
                let lang = trimmed.strip_prefix("```").unwrap_or(trimmed).trim();
                if lang.is_empty() {
                    result.push_str("```text");
                } else {
                    result.push_str(trimmed);
                }
                in_code = true;
            }
        } else {
            result.push_str(line);
        }
        result.push('\n');
    }
    // Remove trailing newline if original didn't have one
    if !content.ends_with('\n') && result.ends_with('\n') {
        result.pop();
    }
    result
}

/// Parse markdown, extract tables, and render to styled Lines.
/// Tables are rendered using pulldown-cmark with width-aware column sizing.
/// `width` limits table width to prevent overflow.
fn md_lines(content: &str, width: u16) -> Vec<Line<'static>> {
    // Try table rendering first (pulldown-cmark based)
    let table_lines = render_markdown_table(content, width);
    if !table_lines.is_empty() {
        return table_lines;
    }

    // No table found, use regular markdown rendering
    render_markdown(content)
}

/// Render regular markdown (non-table content).
fn render_markdown(content: &str) -> Vec<Line<'static>> {
    let preprocessed = fix_bare_code_fences(content);
    let text: ratatui::text::Text<'_> = tui_markdown::from_str(&preprocessed);
    text.lines
        .into_iter()
        .map(|l| {
            let line_style = l.style;
            let spans: Vec<Span<'static>> = l
                .spans
                .into_iter()
                .map(|s| Span::styled(s.content.into_owned(), line_style.patch(s.style)))
                .collect();
            Line::from(spans)
        })
        .collect()
}

// ── Layout calculation ────────────────────────────────────────────────

/// Measure wrapped height using ratatui's Paragraph::line_count.
fn measure_wrapped_height(lines: &[Line<'_>], width: u16) -> u16 {
    if width < 1 {
        return lines.len() as u16;
    }
    let text: ratatui::text::Text = lines.iter().cloned().collect();
    let para = Paragraph::new(text).wrap(Wrap { trim: false });
    para.line_count(width) as u16
}

/// Calculate the layout: list of (y, height, block_ref) for each piece of content.
#[derive(Clone)]
struct LayoutEntry {
    y: u16,
    height: u16,
    kind: LayoutKind,
}

#[derive(Clone)]
enum LayoutKind {
    Spacer,
    Rule,
    #[allow(dead_code)]
    Label {
        text: String,
        style: Style,
    },
    Text {
        lines: Vec<Line<'static>>,
        is_user: bool,
    },
    ToolBox {
        name: String,
        arguments: String,
        result: Option<(String, bool)>,
        status: ToolCallStatus,
        duration: Option<String>,
    },
    ToolResultBox {
        tool_name: String,
        content: String,
        is_error: bool,
    },
    ErrorBox {
        title: String,
        message: String,
        retryable: bool,
    },
    Thinking {
        content: String,
        collapsed: bool,
    },
    Image {
        mime_type: String,
        size_str: String,
    },
    Spinner {
        frame: usize,
    },
}

/// Check if a content block renders as a bordered box (tool calls, errors).
/// Consecutive box blocks need spacers between them for visual separation.
fn is_box_block(block: &ContentBlock) -> bool {
    matches!(
        block,
        ContentBlock::ToolCall { .. }
            | ContentBlock::ToolResult { .. }
            | ContentBlock::Error { .. }
    )
}

fn compute_layout(state: &ChatViewState, width: u16) -> Vec<LayoutEntry> {
    let mut entries = Vec::new();
    let mut y: u16 = 0;

    let mut rendered_any_message = false;

    for msg in &state.messages {
        // Skip messages that have no visible content; they only create empty spacer rows.
        let has_visible_content = msg.content_blocks.iter().any(|b| match b {
            ContentBlock::Text { content } => !content.trim().is_empty(),
            ContentBlock::Thinking { content, .. } => !content.trim().is_empty(),
            _ => true,
        });
        if !has_visible_content {
            continue;
        }

        if rendered_any_message {
            // Gap between messages — use a spacer for breathing room
            entries.push(LayoutEntry {
                y,
                height: 1,
                kind: LayoutKind::Spacer,
            });
            y += 1;
        }
        rendered_any_message = true;

        // User messages: left accent border, no label needed (single-user context)
        if msg.role == MessageRole::User {
            entries.push(LayoutEntry {
                y,
                height: 1,
                kind: LayoutKind::Rule,
            });
            y += 1;
        }
        let mut prev_was_box = false;
        for block in &msg.content_blocks {
            // Skip whitespace-only blocks (defensive; finish_streaming also removes them).
            let is_empty = match block {
                ContentBlock::Text { content } => content.trim().is_empty(),
                ContentBlock::Thinking { content, .. } => content.trim().is_empty(),
                _ => false,
            };
            if is_empty {
                continue;
            }

            // Insert spacer between consecutive box-type blocks (tool calls, errors)
            let is_box = is_box_block(block);
            if is_box && prev_was_box {
                entries.push(LayoutEntry {
                    y,
                    height: 1,
                    kind: LayoutKind::Spacer,
                });
                y += 1;
            }
            prev_was_box = is_box;

            let kind = block_to_layout_kind(block, msg.role, width);
            let h = measure_kind(&kind, width);
            entries.push(LayoutEntry { y, height: h, kind });
            y += h;
        }
    }

    if let Some(ref streaming) = state.streaming {
        // Only add a spacer if we actually rendered any history messages.
        if rendered_any_message {
            entries.push(LayoutEntry {
                y,
                height: 1,
                kind: LayoutKind::Spacer,
            });
            y += 1;
        }
        let mut prev_was_box = false;
        for block in &streaming.message.content_blocks {
            // Skip whitespace-only blocks (prevents large blank gaps during tool-only turns).
            let is_empty = match block {
                ContentBlock::Text { content } => content.trim().is_empty(),
                ContentBlock::Thinking { content, .. } => content.trim().is_empty(),
                _ => false,
            };
            if is_empty {
                continue;
            }

            // Insert spacer between consecutive box-type blocks (tool calls, errors)
            let is_box = is_box_block(block);
            if is_box && prev_was_box {
                entries.push(LayoutEntry {
                    y,
                    height: 1,
                    kind: LayoutKind::Spacer,
                });
                y += 1;
            }
            prev_was_box = is_box;

            let kind = block_to_layout_kind(block, MessageRole::Assistant, width);
            let h = measure_kind(&kind, width);
            entries.push(LayoutEntry { y, height: h, kind });
            y += h;
        }
        entries.push(LayoutEntry {
            y,
            height: 1,
            kind: LayoutKind::Spinner {
                frame: state.spinner_frame,
            },
        });
        _ = y;
    }

    entries
}

fn block_to_layout_kind(block: &ContentBlock, role: MessageRole, width: u16) -> LayoutKind {
    match block {
        ContentBlock::Text { content } => {
            let lines = md_lines(content, width);
            LayoutKind::Text {
                lines,
                is_user: role == MessageRole::User,
            }
        }
        ContentBlock::Thinking { content, collapsed } => LayoutKind::Thinking {
            content: content.clone(),
            collapsed: *collapsed,
        },
        ContentBlock::ToolCall {
            name,
            arguments,
            result,
            status,
            duration,
            ..
        } => LayoutKind::ToolBox {
            name: name.clone(),
            arguments: arguments.clone(),
            result: result.clone(),
            status: *status,
            duration: duration.clone(),
        },
        ContentBlock::ToolResult {
            tool_name,
            content,
            is_error,
        } => LayoutKind::ToolResultBox {
            tool_name: tool_name.clone(),
            content: content.clone(),
            is_error: *is_error,
        },
        ContentBlock::Error {
            title,
            message,
            retryable,
        } => LayoutKind::ErrorBox {
            title: title.clone(),
            message: message.clone(),
            retryable: *retryable,
        },
        ContentBlock::Image {
            mime_type,
            base64_data,
        } => {
            let sz = base64_data.len() * 3 / 4;
            let sz_str = if sz >= 1_048_576 {
                format!("{:.1} MB", sz as f64 / 1_048_576.0)
            } else if sz >= 1024 {
                format!("{:.1} KB", sz as f64 / 1024.0)
            } else {
                format!("{} B", sz)
            };
            LayoutKind::Image {
                mime_type: mime_type.clone(),
                size_str: sz_str,
            }
        }
    }
}

fn measure_kind(kind: &LayoutKind, width: u16) -> u16 {
    match kind {
        LayoutKind::Spacer
        | LayoutKind::Rule
        | LayoutKind::Label { .. }
        | LayoutKind::Spinner { .. } => 1,
        LayoutKind::Text { lines, is_user } => {
            // User text: Block::borders(LEFT) takes 1 col, so inner = width-1
            // Assistant text: no block, renders at full width
            let w = if *is_user {
                width.saturating_sub(1)
            } else {
                width
            };
            measure_wrapped_height(lines, w)
        }
        LayoutKind::ToolBox {
            name,
            arguments,
            result,
            duration,
            ..
        } => {
            use crate::widgets::tool_renderer::{measure_call_height, measure_result_height};
            // inner width for the bordered block: borders take 2 cols
            let inner_w = width.saturating_sub(2) as usize;
            let call_h = measure_call_height(name, arguments, inner_w);
            let result_h = result.as_ref().map_or(0, |(r, is_err)| {
                if *is_err {
                    r.lines().count().min(4) as u16
                } else {
                    measure_result_height(name, r, false)
                }
            });
            // Block::ALL adds top + bottom border (2 rows) + separator if result exists
            let separator_h = if result.is_some() { 1 } else { 0 };
            // Duration label takes 0 extra rows (rendered inline with header)
            let _ = duration;
            2 + call_h + separator_h + result_h
        }
        LayoutKind::ToolResultBox { content, .. } => {
            // 1 header + content lines (max 4) + optional ellipsis
            let n = content.lines().count().min(4);
            1 + n as u16 + if content.lines().count() > 4 { 1 } else { 0 }
        }
        LayoutKind::ErrorBox {
            message, retryable, ..
        } => {
            // Block::bordered() adds top + bottom border (2 rows)
            let n = message.lines().count().min(4);
            2 + n as u16 + if *retryable { 1 } else { 0 }
        }
        LayoutKind::Thinking { content, collapsed } => {
            if *collapsed {
                // Use filtered content for preview — matches render
                let filtered = filter_tool_json(content);
                1 + if filtered.lines().next().is_some() {
                    1
                } else {
                    0
                }
            } else {
                // Use filtered content for measurement to match rendering
                let filtered = filter_tool_json(content);
                let md = md_lines(&filtered, width);
                1 + md.len() as u16
            }
        }
        LayoutKind::Image { .. } => 2,
    }
}

// ── Rendering into ScrollView ─────────────────────────────────────────

/// A wrapper widget that renders a single content block.
struct EntryWidget<'a> {
    entry: &'a LayoutKind,
    styles: &'a ThemeStyles,
}

impl<'a> EntryWidget<'a> {
    fn new(entry: &'a LayoutKind, styles: &'a ThemeStyles) -> Self {
        Self { entry, styles }
    }
}

impl Widget for EntryWidget<'_> {
    fn render(self, rect: Rect, buf: &mut Buffer) {
        match &self.entry {
            LayoutKind::Spacer => { /* empty line, already cleared */ }
            LayoutKind::Rule => {
                let line = "\u{2500}".repeat(rect.width as usize); //                Line::from(Span::styled(line, self.styles.border)).render(rect, buf);
            }
            LayoutKind::Label { text, style } => {
                Paragraph::new(Line::from(Span::styled(text.clone(), *style))).render(rect, buf);
            }
            LayoutKind::Text { lines, is_user } => {
                let text: ratatui::text::Text = lines.iter().cloned().collect();
                if *is_user {
                    let block = Block::default()
                        .borders(Borders::LEFT)
                        .border_style(self.styles.user_border);
                    let inner = block.inner(rect);
                    block.render(rect, buf);
                    Paragraph::new(text)
                        .wrap(Wrap { trim: false })
                        .render(inner, buf);
                } else {
                    // Don't set .style() here — markdown Spans already carry
                    // their own styling (bold, italic, code, headings).
                    // Paragraph::style() would override all per-Span styles.
                    Paragraph::new(text)
                        .wrap(Wrap { trim: false })
                        .render(rect, buf);
                }
            }
            LayoutKind::ToolBox {
                name,
                arguments,
                result,
                status,
                duration,
            } => {
                use crate::widgets::tool_renderer::{format_tool_call, format_tool_result};

                let (icon, border_style) = match status {
                    ToolCallStatus::Requested => (
                        "\u{25CB}", // ○ (hollow circle — universal)
                        self.styles.muted,
                    ),
                    ToolCallStatus::Executing => (
                        "\u{25CF}", // ● (filled circle — running)
                        self.styles.warning,
                    ),
                    ToolCallStatus::Done => {
                        let is_error = result.as_ref().is_some_and(|(_, e)| *e);
                        if is_error {
                            ("\u{2718}", self.styles.error)
                        } else {
                            ("\u{2713}", self.styles.success)
                        }
                    }
                };

                let has_result = result.is_some();

                // Determine background style based on status
                let bg_style = match status {
                    ToolCallStatus::Requested => self.styles.tool_pending_bg,
                    ToolCallStatus::Executing => self.styles.tool_executing_bg,
                    ToolCallStatus::Done => {
                        let is_error = result.as_ref().is_some_and(|(_, e)| *e);
                        if is_error {
                            self.styles.tool_error_bg
                        } else {
                            self.styles.tool_success_bg
                        }
                    }
                };

                // Box with all borders + status background
                let block = Block::default()
                    .borders(Borders::ALL)
                    .border_style(border_style)
                    .style(bg_style);
                let inner = block.inner(rect);
                block.render(rect, buf);
                // Clear any stale content in the inner area before rendering.
                Clear.render(inner, buf);

                let max_w = inner.width as usize;
                let mut content_lines: Vec<Line<'static>> = Vec::new();

                // Format tool call using new renderer
                let call_lines = format_tool_call(name, arguments, max_w, self.styles);
                for (i, line) in call_lines.into_iter().enumerate() {
                    if i == 0 {
                        // Prepend icon to first line, append duration if available
                        let icon_style = border_style.add_modifier(Modifier::BOLD);
                        let name_style = border_style.add_modifier(Modifier::BOLD);
                        let spans = line.spans.into_iter().collect::<Vec<_>>();
                        let mut new_spans = vec![Span::styled(format!("{} ", icon), icon_style)];
                        for span in spans {
                            new_spans.push(Span::styled(
                                span.content.clone(),
                                span.style.patch(name_style),
                            ));
                        }
                        // Append duration to header line (right-aligned conceptually)
                        if let Some(ref dur) = duration {
                            new_spans.push(Span::styled(
                                format!("  {}", dur),
                                self.styles.muted,
                            ));
                        }
                        content_lines.push(Line::from(new_spans));
                    } else {
                        content_lines.push(line);
                    }
                }

                // Separator line between call and result
                if has_result {
                    content_lines.push(Line::from(Span::styled(
                        "\u{2500}".repeat(max_w.saturating_sub(2)),
                        border_style,
                    )));
                }

                // Format result using new renderer
                if let Some((result_content, is_err)) = result {
                    let result_lines =
                        format_tool_result(name, result_content, *is_err, max_w, self.styles);
                    content_lines.extend(result_lines);
                }

                let text: ratatui::text::Text = content_lines.into_iter().collect();
                // No wrap — content is pre-truncated to max_w by format functions.
                // Wrapping would cause measured height mismatches, clipping the result.
                let para = Paragraph::new(text);
                para.render(inner, buf);
            }
            LayoutKind::ToolResultBox {
                tool_name,
                content,
                is_error,
            } => {
                let (icon, border_style) = if *is_error {
                    ("\u{2718}", self.styles.error)
                } else {
                    ("\u{2713}", self.styles.success)
                };
                let label = if tool_name.is_empty() {
                    icon.to_string()
                } else {
                    format!("{} {}", icon, tool_name)
                };

                let block = Block::default()
                    .borders(Borders::LEFT)
                    .border_style(border_style);
                let inner = block.inner(rect);
                block.render(rect, buf);
                // Clear any stale content in the inner area before rendering.
                Clear.render(inner, buf);

                let max_w = inner.width as usize;
                let mut lines: Vec<Line<'static>> = vec![Line::from(Span::styled(
                    format!("  {}", label),
                    border_style.add_modifier(Modifier::BOLD),
                ))];
                for l in content.lines().take(4) {
                    let display = truncate_str(l, max_w.saturating_sub(2));
                    lines.push(Line::from(Span::styled(
                        format!("  {}", display),
                        self.styles.normal,
                    )));
                }
                if content.lines().count() > 4 {
                    lines.push(Line::from(Span::styled("  \u{2026}", self.styles.muted)));
                }
                let text: ratatui::text::Text = lines.into_iter().collect();
                Clear.render(inner, buf);
                Paragraph::new(text).render(inner, buf);
            }
            LayoutKind::ErrorBox {
                title,
                message,
                retryable,
            } => {
                let block = Block::bordered()
                    .border_style(self.styles.error)
                    .title(Span::styled(
                        format!(" error: {} ", title),
                        Style::default()
                            .fg(ratatui::style::Color::White)
                            .add_modifier(Modifier::BOLD),
                    ));
                let inner = block.inner(rect);
                block.render(rect, buf);

                let max_w = inner.width as usize;
                let mut lines: Vec<Line<'static>> = Vec::new();
                for l in message.lines().take(4) {
                    let display = truncate_str(l, max_w);
                    lines.push(Line::from(Span::styled(display, self.styles.normal)));
                }
                if *retryable {
                    lines.push(Line::from(Span::styled(
                        "retry: this error may be temporary",
                        self.styles.muted,
                    )));
                }
                let text: ratatui::text::Text = lines.into_iter().collect();
                // No wrap — pre-truncated to exact width
                Clear.render(inner, buf);
                Paragraph::new(text).render(inner, buf);
            }
            LayoutKind::Thinking { content, collapsed } => {
                let filtered = filter_tool_json(content);
                let mut lines: Vec<Line<'static>> = Vec::new();

                let header_style = self.styles.accent;
                if *collapsed {
                    lines.push(Line::from(Span::styled(
                        "\u{25B8} thinking".to_string(),
                        header_style,
                    )));
                    if let Some(first) = filtered.lines().next() {
                        lines.push(Line::from(Span::styled(
                            format!("  {}", first),
                            self.styles.muted.add_modifier(Modifier::ITALIC),
                        )));
                    }
                } else {
                    lines.push(Line::from(Span::styled(
                        "\u{25BE} thinking".to_string(),
                        header_style,
                    )));
                    let thinking_style = self.styles.muted.add_modifier(Modifier::ITALIC);
                    let md_rendered = md_lines(&filtered, rect.width);
                    for md_line in md_rendered {
                        let spans: Vec<Span<'static>> = md_line
                            .spans
                            .into_iter()
                            .map(|s| {
                                let combined = thinking_style.patch(s.style);
                                Span::styled(s.content.into_owned(), combined)
                            })
                            .collect();
                        lines.push(Line::from(spans));
                    }
                }
                let text: ratatui::text::Text = lines.into_iter().collect();
                Paragraph::new(text).render(rect, buf);
            }
            LayoutKind::Image {
                mime_type,
                size_str,
            } => {
                let lines = vec![
                    Line::from(Span::styled(
                        format!("[image: {}, {}]", mime_type, size_str),
                        self.styles.normal,
                    )),
                    Line::from(Span::styled(
                        "  Ctrl+I -> open in viewer",
                        self.styles.muted,
                    )),
                ];
                let text: ratatui::text::Text = lines.into_iter().collect();
                Clear.render(rect, buf);
                Paragraph::new(text).render(rect, buf);
            }
            LayoutKind::Spinner { frame } => {
                // Moon phase spinner ◐ ◓ ◑ ◒
                let sp = ["\u{25D0}", "\u{25D3}", "\u{25D1}", "\u{25D2}"];
                let ch = sp[frame % sp.len()];
                Paragraph::new(Line::from(Span::styled(
                    format!("  {} Working...", ch),
                    self.styles.accent,
                )))
                .render(rect, buf);
            }
        }
    }
}

// ── ChatView widget ────────────────────────────────────────────────────

pub struct ChatView<'a> {
    theme: &'a Theme,
}

impl<'a> ChatView<'a> {
    pub fn new(theme: &'a Theme) -> Self {
        Self { theme }
    }
}

impl StatefulWidget for ChatView<'_> {
    type State = ChatViewState;

    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        if area.width < 4 || area.height < 1 {
            return;
        }
        let styles = self.theme.to_styles();
        let width = area.width;

        // Outer layout already provides consistent horizontal margin.
        // No additional internal padding needed.
        let inner_width = width;

        // Get layout computed with inner_width for correct height measurements
        let layout = state.get_layout(inner_width);
        let total_height = layout
            .last()
            .map(|e| e.y.saturating_add(e.height))
            .unwrap_or(0);
        state.content_height = total_height;

        // Auto-scroll: update scroll_offset to show bottom of content
        if state.auto_scroll {
            state.scroll_to_bottom(area.height);
        } else {
            // Clamp scroll offset to valid range (in case content shrank)
            state.clamp_scroll(area.height);
        }

        // Render only visible entries directly into the buffer.
        // Skip entries fully above the viewport.
        let scroll_offset = state.scroll_offset;
        for entry in &layout {
            // Entry ends before the visible area starts
            if entry.y + entry.height <= scroll_offset {
                continue;
            }
            // Entry starts after the visible area ends
            if entry.y >= scroll_offset + area.height {
                break;
            }
            if entry.height == 0 {
                continue;
            }
            // Compute relative y within the viewport
            let rel_y = entry.y.saturating_sub(scroll_offset);
            let rect = Rect::new(area.x, area.y + rel_y, inner_width, entry.height);
            EntryWidget::new(&entry.kind, &styles).render(rect, buf);
        }
    }
}

// ── Tests ──────────────────────────────────────────────────────────────

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

    #[test]
    fn scroll_bounds() {
        let mut s = ChatViewState::new();
        s.content_height = 100;
        // scroll_to_bottom with auto_scroll = true
        s.scroll_to_bottom(20);
        assert_eq!(s.scroll_offset, 80);
        assert!(s.auto_scroll);

        // Manual scroll overrides auto_scroll
        s.scroll_up(50);
        assert_eq!(s.scroll_offset, 30);
        assert!(!s.auto_scroll);

        s.scroll_down(10);
        assert_eq!(s.scroll_offset, 40);

        // Clamp at top
        s.scroll_up(100);
        assert_eq!(s.scroll_offset, 0);

        // clamp_scroll when content shrinks
        s.scroll_offset = 90;
        s.content_height = 30;
        s.clamp_scroll(20);
        assert_eq!(s.scroll_offset, 10);
    }

    #[test]
    fn streaming_lifecycle() {
        let mut s = ChatViewState::new();
        s.start_streaming();
        assert!(s.streaming.is_some());
        s.stream_text_delta("Hi");
        s.finish_streaming();
        assert!(s.streaming.is_none());
        assert_eq!(s.messages.len(), 1);
    }

    #[test]
    fn tool_call_lifecycle() {
        let mut s = ChatViewState::new();
        s.start_streaming();
        s.stream_tool_call(
            "t1".into(),
            "bash".into(),
            "ls".into(),
            ToolCallStatus::Executing,
        );
        s.stream_tool_result(Some("t1".into()), "bash".into(), "file.txt".into(), false);
        s.finish_streaming();
        match &s.messages[0].content_blocks[0] {
            ContentBlock::ToolCall {
                status, result, duration, ..
            } => {
                assert_eq!(*status, ToolCallStatus::Done);
                assert!(result.is_some());
                assert!(duration.is_none()); // not set in this test
            }
            _ => panic!("expected ToolCall"),
        }
    }

    #[test]
    fn image_tracking() {
        let mut s = ChatViewState::new();
        s.start_streaming();
        s.stream_image("image/png".into(), "AAAA".into());
        assert_eq!(s.pending_images.len(), 1);
        assert_eq!(s.pending_images[0].1, "image/png");
    }

    #[test]
    fn compute_layout_basic() {
        let mut s = ChatViewState::new();
        s.messages.push(ChatMessage {
            role: MessageRole::User,
            content_blocks: vec![ContentBlock::Text {
                content: "Hello".into(),
            }],
            timestamp: 0,
        });
        let layout = compute_layout(&s, 80);
        assert!(!layout.is_empty());
        assert!(layout.iter().any(|e| matches!(&e.kind, LayoutKind::Rule)));
    }

    #[test]
    fn fix_bare_code_fences_basic() {
        let input = "```\ncode\n```";
        let fixed = fix_bare_code_fences(input);
        assert!(fixed.starts_with("```text"));
    }

    #[test]
    fn clamp_str_no_truncate() {
        let short = "hello world".to_string();
        let result = clamp_str(short.clone(), 100, 10);
        assert_eq!(result, short);
    }

    #[test]
    fn clamp_str_truncates_chars() {
        let long = "x".repeat(100);
        let result = clamp_str(long.clone(), 10, 200);
        // 10 chars + "\n ..." = 16 chars, 2 lines
        assert!(result.starts_with("xxxxxxxxxx"));
        assert!(result.contains("..."));
    }

    #[test]
    fn clamp_str_truncates_lines() {
        let long = (0..20)
            .map(|i| format!("line{}", i))
            .collect::<Vec<_>>()
            .join("\n");
        let result = clamp_str(long.clone(), 10000, 5);
        assert!(result.lines().count() <= 6); // 5 + "...\n"
        assert!(result.ends_with(" ..."));
    }

    #[test]
    fn layout_cache_hit() {
        let mut s = ChatViewState::new();
        s.messages.push(ChatMessage {
            role: MessageRole::User,
            content_blocks: vec![ContentBlock::Text {
                content: "Hello".into(),
            }],
            timestamp: 0,
        });
        // First call — cache miss, recompute
        let layout1 = s.get_layout(80);
        // Second call with same params — cache hit
        let layout2 = s.get_layout(80);
        assert_eq!(layout1.len(), layout2.len());
        // Different width — cache miss
        let layout3 = s.get_layout(60);
        assert_eq!(layout1.len(), layout3.len()); // same content, different heights
    }

    #[test]
    fn text_truncation_on_ingest() {
        let mut s = ChatViewState::new();
        s.start_streaming();
        // Append a huge chunk
        let huge = "x".repeat(600_000);
        s.stream_text_delta(&huge);
        let content = match &s.streaming {
            Some(ref st) => match &st.message.content_blocks[0] {
                ContentBlock::Text { content } => content.clone(),
                _ => panic!("expected Text"),
            },
            None => panic!("expected streaming"),
        };
        // Content should be clamped to MAX_TEXT_CHARS (with overflow marker)
        assert!(
            content.chars().count() <= MAX_TEXT_CHARS + 10,
            "content len = {}",
            content.chars().count()
        );
    }
}

/// Filter JSON tool call arrays from thinking text.
/// GLM-5.1 writes tool call plans as `[{\"function\":...}]` inside
/// reasoning_content. We detect standalone JSON array lines (starting
/// with `[{\"` and ending with `]`) and remove them. Line-by-line
/// filtering avoids false positives from inline `[{\"` patterns in
/// normal reasoning text.
fn filter_tool_json(text: &str) -> String {
    text.lines()
        .filter(|line| {
            let trimmed = line.trim();
            // Only remove lines that are standalone JSON tool call arrays.
            // GLM pattern: [{"function":...}] on its own line.
            // Inline occurrences like "see [{"key": "val"}] here" are preserved.
            !(trimmed.starts_with("[{\"") && trimmed.ends_with(']'))
        })
        .filter(|l| !l.trim().is_empty())
        .collect::<Vec<_>>()
        .join("\n")
}

#[cfg(test)]
mod table_tests {
    use super::*;
    use crate::table_renderer::render_markdown_table;

    #[test]
    fn render_markdown_table_basic() {
        let md = "| Name | Age |\n|---|---|
| Alice | 30 |
| Bob | 25 |";
        let lines = render_markdown_table(md, 80);
        assert!(!lines.is_empty(), "Expected table lines, got empty");
        let text = lines.iter().map(|l| l.to_string()).collect::<String>();
        assert!(text.contains(''), "Expected top border, got: {}", text);
        assert!(text.contains(''), "Expected cell separator, got: {}", text);
        assert!(text.contains(''), "Expected bottom border, got: {}", text);
    }

    #[test]
    fn md_lines_with_table() {
        let md = "| Name | Age |
|---|---|---|
| Alice | 30 |
| Bob | 25 |";
        let lines = md_lines(md, 80);
        assert!(!lines.is_empty());
    }

    #[test]
    fn md_lines_without_table() {
        let md = "Hello **world**";
        let lines = md_lines(md, 80);
        assert!(!lines.is_empty());
    }
    #[test]
    fn test_empty_cells() {
        let md = "| Name | Value | Extra |
|---|---|---|
| Alice | | 100 |";
        let out = render_markdown_table(md, 60);
        let text: String = out.iter().map(|l| l.to_string()).collect::<Vec<_>>().join(
            "
",
        );
        assert!(text.contains("Alice"), "Has Alice");
        assert!(text.contains(""), "Has border");
    }

    #[test]
    fn test_single_column() {
        let md = "| Only |
|---|
| One |
| Two |";
        let out = render_markdown_table(md, 30);
        let text: String = out.iter().map(|l| l.to_string()).collect::<Vec<_>>().join(
            "
",
        );
        assert!(text.contains("Only"), "Has header");
        assert!(text.contains("One"), "Has data");
        println!("text={}", text);
        assert!(
            text.contains("└──────┘") || text.contains("└──┘"),
            "Has bottom border"
        );
    }

    #[test]
    fn test_cjk_characters() {
        let md = "| 이름 | 나이 | 도시 |
|---|---|---|
| 앨리스 | 30 | 서울 |";
        let out = render_markdown_table(md, 60);
        let text: String = out.iter().map(|l| l.to_string()).collect::<Vec<_>>().join(
            "
",
        );
        assert!(text.contains("이름"), "Has CJK");
        assert!(text.contains("앨리스"), "Has CJK data");
    }

    #[test]
    fn test_special_characters_in_cells() {
        let md = "| Name | Desc |
|---|---|
| Test | `code` |";
        let out = render_markdown_table(md, 50);
        let text: String = out.iter().map(|l| l.to_string()).collect::<Vec<_>>().join(
            "
",
        );
        assert!(text.contains("Test"), "Has Test");
    }

    #[test]
    fn test_no_header_row_separator_at_end() {
        let md = "| A | B |
|---|---|
| 1 | 2 |";
        let out = render_markdown_table(md, 30);
        // Should have: top border, header, sep, body, bottom border
        assert!(out.len() >= 5, "Should have at least 5 lines");
    }

    #[test]
    fn test_exact_output_format() {
        let md = "| A | B |
|---|---|
| X | Y |";
        let out = render_markdown_table(md, 30);
        let text: String = out.iter().map(|l| l.to_string()).collect::<Vec<_>>().join(
            "
",
        );
        // Check exact format
        assert_eq!(
            text,
            "┌───┬───┐
│ A │ B │
├───┼───┤
│ X │ Y │
└───┴───┘"
        );
    }
}
#[cfg(test)]
mod complete_table_verification {
    use crate::table_renderer::render_markdown_table;

    #[test]
    fn test_mixed_content_before_table() {
        let md = "Check out this table:\n\n| Name | Value |\n|---|---|\n| Alpha | 100 |";
        let out = render_markdown_table(md, 50);
        let text: String = out
            .iter()
            .map(|l| l.to_string())
            .collect::<Vec<_>>()
            .join("\n");
        assert!(text.contains("Check out"), "Before table");
        assert!(text.contains(''), "Table top");
        assert!(text.contains("Alpha"), "Table data");
    }

    #[test]
    fn test_mixed_content_after_table() {
        let md = "| A | B |\n|---|---|\n| X | Y |\n\nThat was the table.";
        let out = render_markdown_table(md, 50);
        let text: String = out
            .iter()
            .map(|l| l.to_string())
            .collect::<Vec<_>>()
            .join("\n");
        assert!(text.contains(''), "Table top");
        assert!(text.contains("That was the table"), "After table");
    }

    #[test]
    fn test_mixed_content_both_sides() {
        let md = "Start\n\n| H1 | H2 | H3 |\n|---|---|---|\n| C1 | C2 | C3 |\n\nEnd";
        let out = render_markdown_table(md, 60);
        let text: String = out
            .iter()
            .map(|l| l.to_string())
            .collect::<Vec<_>>()
            .join("\n");
        assert!(text.contains("Start"), "Before");
        assert!(text.contains("End"), "After");
        assert!(text.contains(''), "Table");
    }

    #[test]
    fn test_narrow_terminal() {
        let md = "| Name | Age | City |\n|---|---|---|\n| Alice | 30 | Seoul |";
        let out = render_markdown_table(md, 20);
        assert!(!out.is_empty());
        let text: String = out
            .iter()
            .map(|l| l.to_string())
            .collect::<Vec<_>>()
            .join("\n");
        assert!(text.contains("Name") || text.contains("") || text.contains("Alice"));
    }

    #[test]
    fn test_cell_wrapping() {
        let md = "| Short | Very Long Header Text Here |\n|---|---|\n| Data | Another long cell that needs wrapping |";
        let out = render_markdown_table(md, 50);
        let text: String = out
            .iter()
            .map(|l| l.to_string())
            .collect::<Vec<_>>()
            .join("\n");
        assert!(text.contains(''), "Table rendered");
        assert!(text.contains(''), "Has cell separators");
    }

    #[test]
    fn test_multiple_rows_separators() {
        let md = "| A | B |\n|---|---|\n| 1 | 2 |\n| 3 | 4 |\n| 5 | 6 |";
        let out = render_markdown_table(md, 40);
        let text: String = out
            .iter()
            .map(|l| l.to_string())
            .collect::<Vec<_>>()
            .join("\n");
        // Count separator lines (lines containing ├ or ┼)
        let separator_lines: Vec<&str> = text
            .lines()
            .filter(|l| l.contains('') || l.contains(''))
            .collect();
        // 4 data rows → 3 separators between them
        println!("\n{}", text);
        assert_eq!(separator_lines.len(), 3, "Should have 4 separator lines");
        // Check it's a proper table
        assert!(text.contains(""), "Has top border");
        assert!(text.contains(""), "Has bottom border");
    }

    #[test]
    fn test_header_bold_styling() {
        let md = "| Name | Value |\n|---|---|\n| X | Y |";
        let out = render_markdown_table(md, 50);
        assert!(
            out.len() >= 4,
            "Should have top border + header + separator + body"
        );
    }
}