weavr 1.1.0

Claude Code transcript exporter — beautiful, self-contained HTML and Markdown
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
//! Tool card and message content renderers.
//!
//! Each renderer produces an HTML string that is embedded in a message card.
//! The card chrome (header, border, dot) is applied by [`wrap_card`].

use crate::model::tool::ToolInput;

use super::html_escape;

// ---------------------------------------------------------------------------
// v3 row primitives — dot class constants
// ---------------------------------------------------------------------------

/// Dot class for assistant text, thinking, and skill rows (gray).
pub const DOT_ASSISTANT: &str = "dot--assistant";

/// Dot class for tool calls and sub-agent rows (green).
pub const DOT_TOOL: &str = "dot--tool";

/// Render a flat v3 timeline row: `● <label> [meta]`.
///
/// This is the shared primitive used by all event row renderers. Use
/// [`DOT_ASSISTANT`] for gray (assistant text / thinking / skill) or
/// [`DOT_TOOL`] for green (tool calls / sub-agents). `meta` is optional
/// secondary annotation (e.g. a file path, arg summary); pass `""` to omit.
pub fn render_row(dot_class: &str, label: &str, meta: &str) -> String {
    let meta_html = if meta.is_empty() {
        String::new()
    } else {
        format!(r#"<span class="row-meta">{}</span>"#, meta)
    };
    format!(
        r#"<div class="timeline-row"><div class="dot {dot_class}"></div><span class="row-label">{label}</span>{meta_html}</div>"#
    )
}

// ---------------------------------------------------------------------------
// Card wrapper
// ---------------------------------------------------------------------------

/// Visible text length (chars) at or above which a card's body becomes
/// expandable with a "Show more" toggle. Measured on stripped text so
/// short content wrapped in heavy markup (e.g. a thinking block) does
/// not falsely trigger the toggle.
const EXPAND_THRESHOLD: usize = 300;

/// Count visible (non-tag) characters in an HTML fragment.
///
/// This gives a far better proxy for "how much will the user actually
/// read" than `body.len()`, which inflates with every wrapping `<div>`
/// or class attribute.
fn visible_text_length(html: &str) -> usize {
    let mut count = 0usize;
    let mut in_tag = false;
    for c in html.chars() {
        match c {
            '<' => in_tag = true,
            '>' => in_tag = false,
            _ if !in_tag => count += 1,
            _ => {}
        }
    }
    count
}

/// Wrap content in a message card with a colored header.
///
/// Cards are open by default; clicking the header (or its chevron)
/// toggles the body. Long bodies (≥ [`EXPAND_THRESHOLD`] chars) are
/// additionally wrapped in a fade-gradient container with an in-body
/// `Show more / Show less` toggle so the card can be skimmed without
/// fully expanding. `meta` is right-aligned in the header (e.g. a
/// timestamp); pass `""` for inner / nested cards.
pub fn wrap_card(
    role: &str,
    dot_class: &str,
    header_class: &str,
    body: &str,
    is_error: bool,
    meta: &str,
) -> String {
    let error_class = if is_error { " message-card--error" } else { "" };
    let meta_html = if meta.is_empty() {
        String::new()
    } else {
        format!(r#"<span class="message-card-meta">{}</span>"#, meta)
    };

    let body_html = if visible_text_length(body) >= EXPAND_THRESHOLD {
        format!(
            r#"<div class="body-collapsible" data-collapsible>
  <div class="body-collapsible-content">{body}</div>
  <button type="button" class="show-more-btn" data-show-more>Show more</button>
</div>"#
        )
    } else {
        body.to_string()
    };

    format!(
        r#"<div class="message-card{error_class}" data-card-collapse>
  <div class="message-card-header {header_class}" data-card-toggle>
    <div class="message-card-header-left">
      <div class="message-dot {dot_class}"></div>
      <span class="message-card-role">{role}</span>
    </div>
    <div class="message-card-header-right">
      {meta_html}
      <span class="message-card-chevron" aria-hidden="true">&#x25BE;</span>
    </div>
  </div>
  <div class="message-card-body">{body_html}</div>
</div>"#,
    )
}

// ---------------------------------------------------------------------------
// User / assistant text
// ---------------------------------------------------------------------------

/// Render a user message as plain text (escaped HTML).
pub fn render_user_message(msg: &crate::model::content::Message) -> String {
    let text: String = msg
        .content
        .iter()
        .filter_map(|item| {
            if let crate::model::content::ContentItem::Text { text } = item {
                Some(text.as_str())
            } else {
                None
            }
        })
        .collect::<Vec<_>>()
        .join("\n");
    render_user_message_text(&text)
}

/// Render plain text for a user message (escaped, no markdown).
pub fn render_user_message_text(text: &str) -> String {
    let escaped = html_escape(text);
    format!("<p>{}</p>", escaped.replace('\n', "<br>"))
}

/// Render a thinking block as a collapsible card.
pub fn render_thinking(thinking: &str) -> String {
    let label = if thinking.is_empty() {
        "Thinking".to_string()
    } else {
        // Estimate duration: Claude generates ~100 tok/s during thinking, ~4 chars/tok.
        let secs = (thinking.chars().count() / 400).max(1);
        format!("Thought for ~{}s", secs)
    };
    let snippet: String = thinking.chars().take(200).collect();
    let escaped = html_escape(&snippet);
    let more = if thinking.len() > 200 { "" } else { "" };
    format!(
        r#"<details class="thinking-block" open>
  <summary class="thinking-summary">{label}</summary>
  <div class="thinking-content">{escaped}{more}</div>
</details>"#,
    )
}

// ---------------------------------------------------------------------------
// Tool dispatch
// ---------------------------------------------------------------------------

/// Render a tool_use card (dispatches by name).
pub fn render_tool_use(name: &str, input: &serde_json::Value, _id: &str) -> String {
    let ti = ToolInput::from_name_and_input(name, input.clone());
    match &ti {
        ToolInput::Bash(b) => render_bash(b, false),
        ToolInput::Read(r) => render_read(r),
        ToolInput::Write(w) => render_write(w),
        ToolInput::Edit(e) => render_edit_card(e),
        ToolInput::MultiEdit(me) => render_multiedit(me),
        ToolInput::Glob(g) => render_glob(g),
        ToolInput::Grep(g) => render_grep(g),
        ToolInput::TodoWrite(tw) => render_todo_write(tw),
        ToolInput::AskUserQuestion(aq) => render_ask_user_question(aq),
        ToolInput::WebSearch(ws) => render_web_search(ws),
        ToolInput::WebFetch(wf) => render_web_fetch(wf),
        ToolInput::ScheduleWakeup(sw) => render_schedule_wakeup(sw),
        ToolInput::CronCreate(cc) => render_cron_create(cc),
        ToolInput::CronDelete(cd) => render_cron_delete(cd),
        ToolInput::CronList(_) => render_cron_list(),
        ToolInput::Monitor(m) => render_monitor(m),
        ToolInput::Task(t) => render_task(t),
        ToolInput::Team(t) => render_team(t),
        ToolInput::SendMessage(sm) => render_send_message(sm),
        ToolInput::Skill(s) => render_skill(s),
        ToolInput::ExitPlanMode(ep) => render_exit_plan_mode(ep),
        ToolInput::Generic { name, input } => render_generic(name, input),
    }
}

/// Render a tool_result block.
pub fn render_tool_result(content: &str, is_error: bool) -> String {
    let error_class = if is_error { " tool-result--error" } else { "" };
    let escaped = html_escape(content);
    format!(
        r#"<div class="tool-result{error_class}">
  <div class="tool-result-label">OUT:</div>
  <div class="tool-result-content">{}</div>
</div>"#,
        escaped.replace('\n', "<br>")
    )
}

/// Render an embedded image as an `<img>` tag with base64 data.
pub fn render_image(source: &crate::model::content::ImageSource) -> String {
    format!(
        r#"<img class="embedded-image" src="data:{};{},{}" alt="Attached image" loading="lazy">"#,
        source.media_type, source.source_type, source.data
    )
}

// ---------------------------------------------------------------------------
// Individual tool renderers
// ---------------------------------------------------------------------------

fn render_bash(b: &crate::model::tool::BashInput, _is_error: bool) -> String {
    let desc = b.description.as_deref().unwrap_or("");
    let bg = if b.run_in_background.unwrap_or(false) {
        r#" <span class="badge badge--bg">background</span>"#
    } else {
        ""
    };
    let title =
        if desc.is_empty() { format!("Bash{}", bg) } else { format!("Bash — {} {}", desc, bg) };
    wrap_card(
        &title,
        "message-dot--tool",
        "message-card-header--tool",
        &tool_io_row("IN", &html_escape(&b.command)),
        false,
        "",
    )
}

fn render_read(r: &crate::model::tool::ReadInput) -> String {
    let meta = match (r.offset, r.limit) {
        (Some(off), Some(lim)) => format!("lines {}-{}", off, off + lim),
        (Some(off), None) => format!("from line {}", off),
        _ => String::new(),
    };
    let title = format!("Read — {}", r.file_path);
    let body = if meta.is_empty() {
        tool_io_row("FILE", &r.file_path)
    } else {
        format!(
            r#"{}<div class="tool-io-footer">{}</div>"#,
            tool_io_row("FILE", &r.file_path),
            meta
        )
    };
    wrap_card(&title, "message-dot--tool", "message-card-header--tool", &body, false, "")
}

fn render_write(w: &crate::model::tool::WriteInput) -> String {
    let diff = crate::render::diff::render_unified_diff("", &w.content);
    let summary = crate::render::diff::render_change_summary(diff.added, diff.removed);
    let body = format!("{}{}", summary, diff.html);
    wrap_card(
        &format!("Write — {}", w.file_path),
        "message-dot--tool",
        "message-card-header--diff",
        &body,
        false,
        "",
    )
}

fn render_edit_card(e: &crate::model::tool::EditInput) -> String {
    let diff = crate::render::diff::render_unified_diff(&e.old_string, &e.new_string);
    let summary = crate::render::diff::render_change_summary(diff.added, diff.removed);
    let body = format!("{}{}", summary, diff.html);
    wrap_card(
        &format!("Edit — {}", e.file_path),
        "message-dot--tool",
        "message-card-header--diff",
        &body,
        false,
        "",
    )
}

fn render_multiedit(me: &crate::model::tool::MultiEditInput) -> String {
    let diffs: Vec<String> = me
        .edits
        .iter()
        .map(|op| {
            let d = crate::render::diff::render_unified_diff(&op.old_string, &op.new_string);
            let s = crate::render::diff::render_change_summary(d.added, d.removed);
            format!(r#"<div class="multiedit-op">{}{}</div>"#, s, d.html)
        })
        .collect();
    wrap_card(
        &format!("MultiEdit — {} ({} edits)", me.file_path, me.edits.len()),
        "message-dot--tool",
        "message-card-header--diff",
        &diffs.join(""),
        false,
        "",
    )
}

fn render_glob(g: &crate::model::tool::GlobInput) -> String {
    let path = g.path.as_deref().unwrap_or(".");
    wrap_card(
        "Glob",
        "message-dot--tool",
        "message-card-header--tool",
        &format!("{}{}", tool_io_row("PATTERN", &g.pattern), tool_io_row("PATH", path)),
        false,
        "",
    )
}

fn render_grep(g: &crate::model::tool::GrepInput) -> String {
    let path = g.path.as_deref().unwrap_or(".");
    let inc = g.include.as_deref().unwrap_or("*");
    wrap_card(
        "Grep",
        "message-dot--tool",
        "message-card-header--tool",
        &format!(
            "{}{}{}",
            tool_io_row("PATTERN", &g.pattern),
            tool_io_row("PATH", path),
            tool_io_row("INCLUDE", inc)
        ),
        false,
        "",
    )
}

fn render_todo_write(tw: &crate::model::tool::TodoWriteInput) -> String {
    let items: Vec<String> = tw
        .todos
        .iter()
        .map(|t| {
            let chip = status_chip(&t.status);
            let checked = if t.status == "completed" { " checked" } else { "" };
            format!(
                r#"<div class="todo-item"><input type="checkbox"{} disabled> <span class="todo-content">{}</span> <span class="todo-priority">P:{}</span> {}</div>"#,
                checked, t.content, t.priority, chip
            )
        })
        .collect();
    wrap_card(
        "TodoWrite",
        "message-dot--thinking",
        "message-card-header--thinking",
        &items.join(""),
        false,
        "",
    )
}

fn status_chip(status: &str) -> String {
    let (color, label) = match status {
        "completed" => ("#03DAC6", "done"),
        "in_progress" => ("#F59E0B", "in progress"),
        "pending" => ("#737373", "pending"),
        _ => ("#737373", status),
    };
    format!(
        r#"<span class="status-chip" style="background:{}20;color:{};border:1px solid {}40">{}</span>"#,
        color, color, color, label
    )
}

fn render_ask_user_question(aq: &crate::model::tool::AskUserQuestionInput) -> String {
    let qs: Vec<String> = aq
        .questions
        .iter()
        .map(|q| {
            let opts: Vec<String> = q
                .options
                .iter()
                .map(|o| {
                    format!(
                        r#"<span class="question-option">{}</span>"#,
                        o.label
                    )
                })
                .collect();
            format!(
                r#"<div class="question-block"><div class="question-text">{}</div><div class="question-options">{}</div></div>"#,
                q.question, opts.join("")
            )
        })
        .collect();
    wrap_card(
        "AskUserQuestion",
        "message-dot--thinking",
        "message-card-header--thinking",
        &qs.join(""),
        false,
        "",
    )
}

fn render_web_search(ws: &crate::model::tool::WebSearchInput) -> String {
    wrap_card(
        "WebSearch",
        "message-dot--tool",
        "message-card-header--tool",
        &tool_io_row("QUERY", &ws.query),
        false,
        "",
    )
}

fn render_web_fetch(wf: &crate::model::tool::WebFetchInput) -> String {
    let prompt = wf.prompt.as_deref().unwrap_or("");
    wrap_card(
        "WebFetch",
        "message-dot--tool",
        "message-card-header--tool",
        &format!("{}{}", tool_io_row("URL", &wf.url), tool_io_row("PROMPT", prompt)),
        false,
        "",
    )
}

fn render_schedule_wakeup(sw: &crate::model::tool::ScheduleWakeupInput) -> String {
    let prompt = sw.prompt.as_deref().unwrap_or("");
    wrap_card(
        "ScheduleWakeup",
        "message-dot--tool",
        "message-card-header--tool",
        &format!(
            "{}{}{}",
            tool_io_row("DELAY", &format!("{}s", sw.delay_seconds)),
            tool_io_row("REASON", &sw.reason),
            tool_io_row("PROMPT", prompt)
        ),
        false,
        "",
    )
}

fn render_cron_create(cc: &crate::model::tool::CronCreateInput) -> String {
    wrap_card(
        "CronCreate",
        "message-dot--tool",
        "message-card-header--tool",
        &format!("{}{}", tool_io_row("CRON", &cc.cron), tool_io_row("PROMPT", &cc.prompt)),
        false,
        "",
    )
}

fn render_cron_delete(cd: &crate::model::tool::CronDeleteInput) -> String {
    wrap_card(
        "CronDelete",
        "message-dot--tool",
        "message-card-header--tool",
        &tool_io_row("ID", &cd.id),
        false,
        "",
    )
}

fn render_cron_list() -> String {
    wrap_card(
        "CronList",
        "message-dot--tool",
        "message-card-header--tool",
        "Listing all cron jobs.",
        false,
        "",
    )
}

fn render_monitor(m: &crate::model::tool::MonitorInput) -> String {
    wrap_card(
        "Monitor",
        "message-dot--tool",
        "message-card-header--tool",
        &format!(
            "{}{}{}{}",
            tool_io_row("DESC", &m.description),
            tool_io_row("TIMEOUT", &format!("{}ms", m.timeout_ms)),
            tool_io_row("PERSISTENT", &m.persistent.to_string()),
            tool_io_row("CMD", &m.command)
        ),
        false,
        "",
    )
}

fn render_task(t: &crate::model::tool::TaskInput) -> String {
    let desc = t.description.as_deref().unwrap_or("");
    let sub = t.subagent_type.as_deref().unwrap_or("");
    wrap_card(
        "Task / Agent",
        "message-dot--thinking",
        "message-card-header--thinking",
        &format!("{}{}", tool_io_row("DESC", desc), tool_io_row("AGENT", sub)),
        false,
        "",
    )
}

fn render_team(t: &crate::model::tool::TeamInput) -> String {
    let name = t.name.as_deref().unwrap_or("");
    wrap_card(
        "Team",
        "message-dot--tool",
        "message-card-header--tool",
        &tool_io_row("NAME", name),
        false,
        "",
    )
}

fn render_send_message(sm: &crate::model::tool::SendMessageInput) -> String {
    let agent = sm.agent_id.as_deref().unwrap_or("");
    wrap_card(
        "SendMessage",
        "message-dot--tool",
        "message-card-header--tool",
        &format!("{}{}", tool_io_row("TO", agent), tool_io_row("MSG", &sm.message)),
        false,
        "",
    )
}

fn render_skill(s: &crate::model::tool::SkillInput) -> String {
    let args = s.args.as_deref().unwrap_or("");
    let title = if s.skill.is_empty() { "Skill".to_string() } else { s.skill.clone() };
    wrap_card(
        &title,
        "message-dot--tool",
        "message-card-header--tool",
        &format!("{}{}", tool_io_row("SKILL", &s.skill), tool_io_row("ARGS", args)),
        false,
        "",
    )
}

fn render_exit_plan_mode(_ep: &crate::model::tool::ExitPlanModeInput) -> String {
    wrap_card(
        "ExitPlanMode",
        "message-dot--tool",
        "message-card-header--tool",
        "Plan approved — exiting plan mode.",
        false,
        "",
    )
}

fn render_generic(name: &str, input: &serde_json::Value) -> String {
    let rows: Vec<String> = input
        .as_object()
        .map(|obj| {
            obj.iter()
                .map(|(k, v)| {
                    let val =
                        if v.is_string() { v.as_str().unwrap().to_string() } else { v.to_string() };
                    tool_io_row(&k.to_uppercase(), &val)
                })
                .collect()
        })
        .unwrap_or_default();
    let body = if rows.is_empty() { input.to_string() } else { rows.join("") };
    wrap_card(name, "message-dot--file", "message-card-header--diff", &body, false, "")
}

// ---------------------------------------------------------------------------
// Shared HTML helpers
// ---------------------------------------------------------------------------

/// Render a single `<div class="tool-io">` label/value row.
fn tool_io_row(label: &str, value: &str) -> String {
    format!(
        r#"<div class="tool-io"><span class="tool-io-label">{label}:</span><span class="tool-io-value">{value}</span></div>"#
    )
}

/// Return the last path component (basename) of a file path.
///
/// Works with both `/unix/style` and `\windows\style` separators.
fn basename(path: &str) -> &str {
    path.rsplit(['/', '\\']).next().filter(|s| !s.is_empty()).unwrap_or(path)
}

// ---------------------------------------------------------------------------
// v3 event renderers — T5: Thinking row
// ---------------------------------------------------------------------------

/// Render a thinking event as a v3 gray dot-row with inline expand.
///
/// Empty/blank thinking → disabled static row (no body, no toggle).
/// Non-empty thinking → `<details>` row that expands inline on click,
/// with an estimated duration label ("Thought for ~Xs") derived from
/// character count (~100 tok/s × 4 chars/tok).
pub fn render_thinking_row(text: &str) -> String {
    if text.trim().is_empty() {
        format!(
            r#"<div class="timeline-row"><div class="dot {DOT_ASSISTANT}"></div><span class="row-label thinking-disabled">Thinking</span></div>"#
        )
    } else {
        let secs = (text.chars().count() / 400).max(1);
        let label = format!("Thought for ~{}s &#x203A;", secs);
        let content = html_escape(text);
        format!(
            r#"<details class="thinking-row"><summary class="timeline-row"><div class="dot {DOT_ASSISTANT}"></div><span class="row-label">{label}</span></summary><div class="thinking-body"><pre class="thinking-pre">{content}</pre></div></details>"#
        )
    }
}

// ---------------------------------------------------------------------------
// v3 event renderers — T6: Unified tool call row + IN/OUT presence
// ---------------------------------------------------------------------------

/// Render a [`ToolCallEvent`] as a v3 timeline row.
///
/// Each tool gets a green dot-row with its primary arg. Clicking expands
/// IN and/or OUT sections; sections are only emitted when data is present.
pub fn render_tool_call_event(tce: &crate::conversation::ToolCallEvent) -> String {
    let ti = ToolInput::from_name_and_input(&tce.name, tce.input.clone());
    let result = tce.result.as_ref();
    match &ti {
        ToolInput::Bash(b) => render_bash_event(b, result),
        ToolInput::Read(r) => render_read_event(r, result, &tce.id),
        ToolInput::Write(w) => render_write_event(w),
        ToolInput::Edit(e) => render_edit_event(e),
        ToolInput::MultiEdit(me) => render_multiedit_event(me),
        ToolInput::Skill(s) => render_skill_event(s, result, &tce.id),
        _ => render_generic_tool_event(&tce.name, &tce.input, result),
    }
}

/// Wrap tool content in a `<details>` dot-row with expandable body.
///
/// Falls back to a plain non-expandable row when `body` is empty.
fn render_tool_details_row(dot_class: &str, label: &str, body: &str) -> String {
    if body.is_empty() {
        format!(
            r#"<div class="timeline-row"><div class="dot {dot_class}"></div><span class="row-label">{label}</span></div>"#
        )
    } else {
        format!(
            r#"<details class="tool-details"><summary class="timeline-row"><div class="dot {dot_class}"></div><span class="row-label">{label}</span></summary><div class="tool-details-body">{body}</div></details>"#
        )
    }
}

/// Render a labeled `tool-section` with a `<pre>` body.
///
/// Only call when content is non-empty; callers gate on data presence.
fn render_tool_section(label: &str, content: &str, is_error: bool) -> String {
    let error_class = if is_error { " tool-section--error" } else { "" };
    // Wrap in .tool-section-pre-wrap so JS can detect overflow and add .is-clamped
    // for the fade + click-to-modal affordance (T20).
    format!(
        r#"<div class="tool-section{error_class}"><div class="tool-section-label">{label}</div><div class="tool-section-pre-wrap"><pre class="tool-section-body">{}</pre></div></div>"#,
        html_escape(content)
    )
}

fn render_bash_event(
    b: &crate::model::tool::BashInput,
    result: Option<&crate::conversation::ToolResult>,
) -> String {
    let desc = b.description.as_deref().unwrap_or("").trim();
    let bg_badge = if b.run_in_background.unwrap_or(false) {
        r#" <span class="badge badge--bg">bg</span>"#
    } else {
        ""
    };
    // Escape text portions first, then insert the badge HTML so it renders correctly.
    let label = if !desc.is_empty() {
        format!("<strong>Bash</strong> — {}{bg_badge}", html_escape(desc))
    } else {
        let preview: String = b.command.chars().take(60).collect();
        let ellipsis = if b.command.chars().count() > 60 { "" } else { "" };
        format!("<strong>Bash</strong>{bg_badge}{}{ellipsis}", html_escape(&preview))
    };

    let in_section = render_tool_section("IN", &b.command, false);
    let out_section =
        result.map(|r| render_tool_section("OUT", &r.content, r.is_error)).unwrap_or_default();

    render_tool_details_row(DOT_TOOL, &label, &format!("{in_section}{out_section}"))
}

// ---------------------------------------------------------------------------
// v3 event renderers — T7: Read row → modal (file contents)
// ---------------------------------------------------------------------------

fn render_read_event(
    r: &crate::model::tool::ReadInput,
    result: Option<&crate::conversation::ToolResult>,
    id: &str,
) -> String {
    let line_range = match (r.offset, r.limit) {
        (Some(off), Some(lim)) => format!(":{}-{}", off, off + lim),
        (Some(off), None) => format!(":{}", off),
        _ => String::new(),
    };
    let full_path_escaped = html_escape(&r.file_path);
    let base_escaped = html_escape(basename(&r.file_path));
    let meta_html = if line_range.is_empty() {
        String::new()
    } else {
        format!(r#" <span class="row-meta">{line_range}</span>"#)
    };

    if let Some(res) = result {
        // Has result: basename opens modal; full path in tooltip.
        let template_id = format!("read-{id}");
        let contents_html = render_file_modal_body(&r.file_path, &res.content);
        let label = format!(
            r#"<strong>Read</strong> — <button type="button" class="file-link" data-modal="{template_id}" data-tooltip="{full_path_escaped}">{base_escaped}</button>{meta_html}"#
        );
        format!(
            r#"<div class="timeline-row"><div class="dot {DOT_TOOL}"></div><span class="row-label">{label}</span></div><template id="{template_id}">{contents_html}</template>"#
        )
    } else {
        // No result: plain row, basename shown, full path in tooltip.
        let label = format!(
            r#"<strong>Read</strong> — <span data-tooltip="{full_path_escaped}">{base_escaped}</span>{meta_html}"#
        );
        format!(
            r#"<div class="timeline-row"><div class="dot {DOT_TOOL}"></div><span class="row-label">{label}</span></div>"#
        )
    }
}

fn render_write_event(w: &crate::model::tool::WriteInput) -> String {
    let diff = crate::render::diff::render_unified_diff("", &w.content);
    let summary = crate::render::diff::render_change_summary(diff.added, diff.removed);
    let body = format!("{summary}{}", diff.html);
    let label = file_tool_label("Write", &w.file_path);
    render_tool_details_row(DOT_TOOL, &label, &body)
}

fn render_edit_event(e: &crate::model::tool::EditInput) -> String {
    let diff = crate::render::diff::render_unified_diff(&e.old_string, &e.new_string);
    let summary = crate::render::diff::render_change_summary(diff.added, diff.removed);
    let body = format!("{summary}{}", diff.html);
    let label = file_tool_label("Edit", &e.file_path);
    render_tool_details_row(DOT_TOOL, &label, &body)
}

fn render_multiedit_event(me: &crate::model::tool::MultiEditInput) -> String {
    let diffs: Vec<String> = me
        .edits
        .iter()
        .map(|op| {
            let d = crate::render::diff::render_unified_diff(&op.old_string, &op.new_string);
            let s = crate::render::diff::render_change_summary(d.added, d.removed);
            format!(r#"<div class="multiedit-op">{s}{}</div>"#, d.html)
        })
        .collect();
    let label =
        format!("{} ({} edits)", file_tool_label("MultiEdit", &me.file_path), me.edits.len());
    render_tool_details_row(DOT_TOOL, &label, &diffs.join(""))
}

/// Build a `Tool — <basename>` label with the full path in a `data-tooltip`.
fn file_tool_label(tool: &str, file_path: &str) -> String {
    let full = html_escape(file_path);
    let base = html_escape(basename(file_path));
    format!(r#"<strong>{tool}</strong> — <span data-tooltip="{full}">{base}</span>"#)
}

/// Render the modal body for a Read tool result.
///
/// Markdown files are rendered via comrak after stripping line numbers;
/// all other files get a `<pre>` block (line numbers preserved).
fn render_file_modal_body(file_path: &str, content: &str) -> String {
    if is_markdown_path(file_path) {
        crate::render::markdown::render(&strip_line_numbers(content))
    } else {
        format!(r#"<pre class="file-contents">{}</pre>"#, html_escape(content))
    }
}

/// Return `true` when the file extension indicates a Markdown document.
fn is_markdown_path(path: &str) -> bool {
    let lower = path.to_lowercase();
    lower.ends_with(".md") || lower.ends_with(".markdown")
}

/// Strip `cat -n` style line-number prefixes (`   N\t`) from each line.
///
/// The Claude Code Read tool returns content with leading whitespace-padded
/// line numbers followed by a tab. Stripping these before markdown rendering
/// restores proper heading/list/fence recognition.
fn strip_line_numbers(content: &str) -> String {
    content
        .lines()
        .map(|line| {
            // Trim leading spaces, check for digits + tab pattern.
            let s = line.trim_start_matches(' ');
            let digit_end = s.find(|c: char| !c.is_ascii_digit()).unwrap_or(0);
            if digit_end > 0 && s.as_bytes().get(digit_end) == Some(&b'\t') {
                s[digit_end + 1..].to_string()
            } else {
                line.to_string()
            }
        })
        .collect::<Vec<_>>()
        .join("\n")
}

/// Try to load a skill's SKILL.md (or command .md) from the filesystem.
///
/// Search order:
///   1. `~/.claude/plugins/marketplaces/*/skills/{short_name}/SKILL.md`
///   2. `~/.claude/plugins/marketplaces/*/.claude/commands/{short_name}.md`
///   3. `~/.agents/skills/{name}/SKILL.md`
///   4. `~/.claude/skills/{name}/SKILL.md`
fn try_load_skill_file(skill_name: &str) -> Option<String> {
    let home = std::env::var("HOME").ok()?;
    let short = skill_name.split(':').next_back().unwrap_or(skill_name);

    // 1 + 2: marketplace plugins
    let mp_base = format!("{home}/.claude/plugins/marketplaces");
    if let Ok(entries) = std::fs::read_dir(&mp_base) {
        for entry in entries.flatten() {
            let base = entry.path();
            // SKILL.md inside skills/{short}/
            let skill_path = base.join("skills").join(short).join("SKILL.md");
            if let Ok(c) = std::fs::read_to_string(&skill_path) {
                return Some(c);
            }
            // command .md
            let cmd_path = base.join(".claude").join("commands").join(format!("{short}.md"));
            if let Ok(c) = std::fs::read_to_string(&cmd_path) {
                return Some(c);
            }
        }
    }

    // 3: ~/.agents/skills
    for name in &[short, skill_name] {
        let p = format!("{home}/.agents/skills/{name}/SKILL.md");
        if let Ok(c) = std::fs::read_to_string(&p) {
            return Some(c);
        }
    }

    // 4: ~/.claude/skills
    for name in &[short, skill_name] {
        let p = format!("{home}/.claude/skills/{name}/SKILL.md");
        if let Ok(c) = std::fs::read_to_string(&p) {
            return Some(c);
        }
    }

    None
}

// ---------------------------------------------------------------------------
// v3 event renderers — T8: Skill row → modal
// ---------------------------------------------------------------------------

fn render_skill_event(
    s: &crate::model::tool::SkillInput,
    result: Option<&crate::conversation::ToolResult>,
    id: &str,
) -> String {
    let skill_name = if s.skill.is_empty() { "Skill".to_string() } else { html_escape(&s.skill) };
    let row_label = format!("<strong>{skill_name}</strong> skill");

    // The Skill tool result is always a short "Launching skill: ..." confirmation —
    // the actual SKILL.md content is injected into the model context separately.
    // Try to load the real content from disk so the modal shows something useful.
    let disk_content = try_load_skill_file(&s.skill);
    let has_modal = result.is_some() || disk_content.is_some();

    if has_modal {
        let template_id = format!("skill-{id}");
        let md_source = disk_content
            .as_deref()
            .unwrap_or_else(|| result.map(|r| r.content.as_str()).unwrap_or(""));
        let rendered_md = crate::render::markdown::render(md_source);
        let body_html = format!(r#"<div class="skill-body markdown-body">{rendered_md}</div>"#);
        format!(
            r#"<div class="timeline-row"><div class="dot {DOT_ASSISTANT}"></div><span class="row-label"><button type="button" class="skill-link" data-modal="{template_id}">{row_label}</button></span></div><template id="{template_id}">{body_html}</template>"#
        )
    } else {
        format!(
            r#"<div class="timeline-row"><div class="dot {DOT_ASSISTANT}"></div><span class="row-label">{row_label}</span></div>"#
        )
    }
}

fn render_generic_tool_event(
    name: &str,
    input: &serde_json::Value,
    result: Option<&crate::conversation::ToolResult>,
) -> String {
    let label = format!("<strong>{}</strong>", html_escape(name));
    let in_rows: Vec<String> = input
        .as_object()
        .map(|obj| {
            obj.iter()
                .map(|(k, v)| {
                    let val = if v.is_string() {
                        v.as_str().unwrap().to_string()
                    } else {
                        v.to_string()
                    };
                    format!(
                        r#"<div class="tool-row-kv"><span class="tool-kv-key">{}</span><span class="tool-kv-val">{}</span></div>"#,
                        k,
                        html_escape(&val)
                    )
                })
                .collect()
        })
        .unwrap_or_default();
    let in_section = if in_rows.is_empty() {
        String::new()
    } else {
        render_tool_section("IN", &in_rows.join(""), false)
    };
    let out_section =
        result.map(|r| render_tool_section("OUT", &r.content, r.is_error)).unwrap_or_default();
    render_tool_details_row(DOT_TOOL, &label, &format!("{in_section}{out_section}"))
}

// ---------------------------------------------------------------------------
// v3 event renderers — T10: Sub-agent row + IN prompt
// ---------------------------------------------------------------------------

/// Render a sub-agent spawn event as a green dot-row `Agent: <desc>`.
///
/// Expands inline to show the IN prompt. No nested transcript is rendered.
pub fn render_sub_agent_row(sa: &crate::conversation::SubAgentEvent) -> String {
    let desc = sa.input.get("description").and_then(|v| v.as_str()).unwrap_or(&sa.name);
    let label = format!("Agent: {}", html_escape(desc));

    let prompt = sa.input.get("prompt").and_then(|v| v.as_str()).unwrap_or("");
    if prompt.is_empty() {
        format!(
            r#"<div class="timeline-row"><div class="dot {DOT_TOOL}"></div><span class="row-label">{label}</span></div>"#
        )
    } else {
        let in_section = render_tool_section("IN", prompt, false);
        render_tool_details_row(DOT_TOOL, &label, &in_section)
    }
}

// ---------------------------------------------------------------------------
// v3 event renderers — T11: Images — horizontal thumbnails → modal
// ---------------------------------------------------------------------------

/// Render a group of images as horizontally-stacked thumbnails.
///
/// Clicking a thumbnail opens it full-size in the shared modal.
/// `card_id` is the parent card's anchor and is used to generate unique IDs.
pub fn render_images_thumbnail_row(
    images: &[crate::model::content::ImageSource],
    card_id: &str,
) -> String {
    let thumbs: String = images
        .iter()
        .enumerate()
        .map(|(i, img)| {
            let src =
                format!("data:{};{},{}", img.media_type, img.source_type, img.data);
            let template_id = format!("img-{card_id}-{i}");
            format!(
                r#"<button type="button" class="img-thumb-btn" data-modal="{template_id}"><img class="img-thumb" src="{src}" alt="Image {num}" loading="lazy"></button><template id="{template_id}"><img class="img-modal-full" src="{src}" alt="Image {num}"></template>"#,
                num = i + 1,
            )
        })
        .collect();
    format!(
        r#"<div class="timeline-row images-row"><div class="img-thumbnails">{thumbs}</div></div>"#
    )
}

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

    #[test]
    fn render_bash_card() {
        let html = render_bash(
            &crate::model::tool::BashInput {
                command: "cargo build".into(),
                description: Some("Build project".into()),
                run_in_background: None,
                timeout: None,
                dangerously_disable_sandbox: None,
            },
            false,
        );
        assert!(html.contains("Bash — Build project"));
        assert!(html.contains("cargo build"));
        assert!(html.contains("message-card"));
    }

    #[test]
    fn render_read_card() {
        let html = render_read(&crate::model::tool::ReadInput {
            file_path: "src/main.rs".into(),
            offset: Some(10),
            limit: Some(20),
            pages: None,
        });
        assert!(html.contains("src/main.rs"));
        assert!(html.contains("lines 10-30"));
    }

    #[test]
    fn render_tool_result_with_error() {
        let html = render_tool_result("command failed", true);
        assert!(html.contains("tool-result--error"));
        assert!(html.contains("command failed"));
    }

    #[test]
    fn render_generic_unknown_tool() {
        let html = render_generic("FutureTool", &serde_json::json!({"key1": "val1", "key2": 42}));
        assert!(html.contains("FutureTool"));
        assert!(html.contains("KEY1"));
        assert!(html.contains("val1"));
    }

    #[test]
    fn all_tool_names_render_without_panic() {
        let names = [
            "Bash",
            "Read",
            "Write",
            "Edit",
            "MultiEdit",
            "Glob",
            "Grep",
            "TodoWrite",
            "AskUserQuestion",
            "WebSearch",
            "WebFetch",
            "ScheduleWakeup",
            "CronCreate",
            "CronList",
            "CronDelete",
            "Task",
            "Agent",
            "SendMessage",
            "Skill",
            "ExitPlanMode",
            "Monitor",
            "TeamCreate",
            "TeamDelete",
        ];
        for name in &names {
            let input = serde_json::json!({"dummy": "test"});
            let html = render_tool_use(name, &input, "t1");
            assert!(!html.is_empty(), "render_tool_use should produce output for {}", name);
            // Generic fallback should never panic.
            assert!(html.contains("message-card"), "{} should produce a card", name);
        }
    }

    // B2 tests — unified diff wiring

    #[test]
    fn edit_card_renders_unified_diff_with_summary() {
        let html = render_edit_card(&crate::model::tool::EditInput {
            file_path: "src/main.rs".into(),
            old_string: "a\nb\n".into(),
            new_string: "a\nc\n".into(),
            replace_all: false,
        });
        // Contains diff lines.
        assert!(html.contains("diff-line--add"), "should have added line");
        assert!(html.contains("diff-line--del"), "should have deleted line");
        // Contains change summary with correct counts (new format: +X · −Y).
        assert!(html.contains("diff-count--add"), "should have add count class");
        assert!(html.contains("diff-count--del"), "should have del count class");
        // File-path header preserved.
        assert!(html.contains("Edit — src/main.rs"), "file-path header should show");
        // Old plain-text blocks are absent.
        assert!(!html.contains("old_string"), "should not contain raw old_string label");
        assert!(!html.contains("new_string"), "should not contain raw new_string label");
    }

    #[test]
    fn write_card_renders_pure_add_diff() {
        let html = render_write(&crate::model::tool::WriteInput {
            file_path: "new_file.rs".into(),
            content: "line one\nline two\n".into(),
        });
        // Only added lines, no deleted lines.
        assert!(html.contains("diff-line--add"));
        assert!(!html.contains("diff-line--del"));
        // Summary contains diff counts (new format: +X · −Y).
        assert!(html.contains("diff-count--add"), "should have add count class");
        assert!(html.contains("+2 lines"), "should show +2 lines");
        // File-path header preserved.
        assert!(html.contains("Write — new_file.rs"));
    }

    #[test]
    fn multiedit_card_renders_diff_per_edit() {
        let html = render_multiedit(&crate::model::tool::MultiEditInput {
            file_path: "src/lib.rs".into(),
            edits: vec![
                crate::model::tool::EditOp {
                    old_string: "x\n".into(),
                    new_string: "y\n".into(),
                    replace_all: false,
                },
                crate::model::tool::EditOp {
                    old_string: "".into(),
                    new_string: "z\n".into(),
                    replace_all: false,
                },
            ],
        });
        assert!(html.contains("MultiEdit — src/lib.rs"));
        // Both edits rendered.
        assert!(html.contains("multiedit-op"));
        // First edit has a change.
        assert!(html.contains("diff-line--add"));
        assert!(html.contains("diff-line--del"));
    }

    // -----------------------------------------------------------------------
    // D2 tests — skill card header
    // -----------------------------------------------------------------------

    #[test]
    fn skill_card_header_shows_full_skill_name() {
        let html = render_skill(&crate::model::tool::SkillInput {
            skill: "agent-skills:interview-me".into(),
            args: Some("".into()),
        });
        // Card header should contain the full skill name, not generic "Skill".
        assert!(html.contains("agent-skills:interview-me"));
        assert!(!html.contains(r#">Skill</span>"#), "should not use generic Skill label");
    }

    #[test]
    fn skill_card_header_falls_back_when_empty() {
        let html = render_skill(&crate::model::tool::SkillInput {
            skill: String::new(),
            args: None,
        });
        // Falls back to generic "Skill" when the skill name is empty.
        assert!(html.contains(">Skill<"), "should fall back to generic Skill label");
    }

    // -----------------------------------------------------------------------
    // T2 — render_row + dot class constants
    // -----------------------------------------------------------------------

    #[test]
    fn render_row_assistant_dot_class() {
        let html = render_row(DOT_ASSISTANT, "Thinking", "");
        assert!(html.contains("dot--assistant"), "must use DOT_ASSISTANT class");
        assert!(html.contains("timeline-row"), "must use timeline-row wrapper");
        assert!(html.contains("Thinking"), "label must appear in output");
        assert!(!html.contains("row-meta"), "no meta span when meta is empty");
    }

    #[test]
    fn render_row_tool_dot_class() {
        let html = render_row(DOT_TOOL, "Bash", "cargo build");
        assert!(html.contains("dot--tool"), "must use DOT_TOOL class");
        assert!(html.contains("Bash"), "label must appear");
        assert!(html.contains("row-meta"), "meta span must appear when meta is provided");
        assert!(html.contains("cargo build"), "meta value must appear");
    }

    #[test]
    fn render_row_meta_omitted_when_empty() {
        let html = render_row(DOT_ASSISTANT, "Some label", "");
        assert!(!html.contains("row-meta"), "row-meta span must be absent for empty meta");
    }

    #[test]
    fn dot_constants_distinct() {
        assert_ne!(DOT_ASSISTANT, DOT_TOOL, "dot constants must differ");
        assert_eq!(DOT_ASSISTANT, "dot--assistant");
        assert_eq!(DOT_TOOL, "dot--tool");
    }

    // -----------------------------------------------------------------------
    // T5 — thinking row
    // -----------------------------------------------------------------------

    #[test]
    fn thinking_row_non_empty_is_details_with_gray_dot() {
        let html = render_thinking_row("deep thought");
        assert!(html.contains("<details"), "non-empty thinking must use <details>");
        assert!(html.contains("dot--assistant"), "must use gray dot");
        assert!(html.contains("Thought for"), "label must show estimated duration");
        assert!(html.contains("deep thought"), "thinking content must appear");
    }

    #[test]
    fn thinking_row_empty_is_disabled_static_row() {
        let html = render_thinking_row("");
        assert!(!html.contains("<details"), "empty thinking must NOT use <details>");
        assert!(html.contains("thinking-disabled"), "must have disabled class");
        assert!(html.contains("Thinking"), "label must appear");
        assert!(html.contains("dot--assistant"), "must use gray dot");
    }

    #[test]
    fn thinking_row_whitespace_treated_as_empty() {
        let html = render_thinking_row("   \n  ");
        assert!(!html.contains("<details"), "whitespace thinking treated as empty");
        assert!(html.contains("thinking-disabled"));
    }

    // -----------------------------------------------------------------------
    // T6 — render_tool_call_event unified row + IN/OUT presence
    // -----------------------------------------------------------------------

    #[test]
    fn tool_call_bash_with_result_shows_in_and_out() {
        let tce = crate::conversation::ToolCallEvent {
            id: "b1".to_string(),
            name: "Bash".to_string(),
            input: serde_json::json!({"command": "cargo build", "description": "build"}),
            result: Some(crate::conversation::ToolResult {
                content: "Compiling...".to_string(),
                is_error: false,
            }),
        };
        let html = render_tool_call_event(&tce);
        assert!(html.contains("dot--tool"), "bash must use green dot");
        assert!(html.contains("Bash"), "Bash label must appear");
        assert!(html.contains("cargo build"), "command must appear in IN section");
        assert!(html.contains("Compiling"), "result must appear in OUT section");
        assert!(html.contains("tool-section"), "must have tool-section divs");
    }

    #[test]
    fn tool_call_bash_without_result_has_no_out_section() {
        let tce = crate::conversation::ToolCallEvent {
            id: "b1".to_string(),
            name: "Bash".to_string(),
            input: serde_json::json!({"command": "ls"}),
            result: None,
        };
        let html = render_tool_call_event(&tce);
        // IN section present (command is always there).
        assert!(html.contains("ls"), "command must appear");
        // OUT section absent when no result.
        assert!(!html.contains(">OUT<"), "no OUT section when result is None");
    }

    #[test]
    fn tool_call_in_only_no_result_no_out_block() {
        let tce = crate::conversation::ToolCallEvent {
            id: "g1".to_string(),
            name: "Glob".to_string(),
            input: serde_json::json!({"pattern": "*.rs", "path": "src/"}),
            result: None,
        };
        let html = render_tool_call_event(&tce);
        assert!(html.contains("Glob"), "tool name must appear");
        assert!(!html.contains(">OUT<"), "no OUT section when result is None");
    }

    // -----------------------------------------------------------------------
    // T7 — Read row → modal
    // -----------------------------------------------------------------------

    #[test]
    fn read_event_with_result_has_clickable_filename_and_template() {
        let tce = crate::conversation::ToolCallEvent {
            id: "r1".to_string(),
            name: "Read".to_string(),
            input: serde_json::json!({"file_path": "src/main.rs", "offset": 10, "limit": 20}),
            result: Some(crate::conversation::ToolResult {
                content: "fn main() {}".to_string(),
                is_error: false,
            }),
        };
        let html = render_tool_call_event(&tce);
        assert!(html.contains("file-link"), "filename must have file-link class");
        assert!(html.contains("data-modal="), "filename must trigger modal");
        assert!(html.contains("src/main.rs"), "file path must appear");
        assert!(html.contains("<template"), "template element must be present");
        assert!(html.contains("fn main()"), "file contents must appear in template");
        assert!(html.contains(":10-30"), "line range must appear in row");
    }

    #[test]
    fn read_event_without_result_has_no_link() {
        let tce = crate::conversation::ToolCallEvent {
            id: "r2".to_string(),
            name: "Read".to_string(),
            input: serde_json::json!({"file_path": "src/lib.rs"}),
            result: None,
        };
        let html = render_tool_call_event(&tce);
        assert!(html.contains("src/lib.rs"), "file path must appear");
        assert!(!html.contains("file-link"), "no link when result is absent");
        assert!(!html.contains("data-modal"), "no modal trigger when result is absent");
    }

    // -----------------------------------------------------------------------
    // T8 — Skill row → modal
    // -----------------------------------------------------------------------

    #[test]
    fn skill_event_with_result_shows_full_name_and_modal() {
        // Use a skill name that won't resolve to a real file on disk.
        let tce = crate::conversation::ToolCallEvent {
            id: "s1".to_string(),
            name: "Skill".to_string(),
            input: serde_json::json!({"skill": "test-fake-skill-zzz:nonexistent", "args": ""}),
            result: Some(crate::conversation::ToolResult {
                content: "Skill output here".to_string(),
                is_error: false,
            }),
        };
        let html = render_tool_call_event(&tce);
        assert!(html.contains("test-fake-skill-zzz:nonexistent"), "full skill name must appear");
        assert!(html.contains("skill"), "row must say 'skill'");
        assert!(html.contains("dot--assistant"), "skill uses gray dot");
        assert!(html.contains("skill-link"), "skill name must be a link");
        assert!(html.contains("data-modal="), "must trigger modal");
        assert!(html.contains("<template"), "template element must be present");
        assert!(html.contains("Skill output here"), "skill body in template");
    }

    #[test]
    fn skill_event_without_result_and_no_disk_file_shows_name_no_link() {
        // Use a skill name that cannot resolve to a real file on disk.
        let tce = crate::conversation::ToolCallEvent {
            id: "s2".to_string(),
            name: "Skill".to_string(),
            input: serde_json::json!({"skill": "test-fake-skill-zzz:nonexistent", "args": null}),
            result: None,
        };
        let html = render_tool_call_event(&tce);
        assert!(html.contains("test-fake-skill-zzz:nonexistent"), "full skill name must appear");
        assert!(!html.contains("skill-link"), "no link when no result and no disk file");
        assert!(html.contains("dot--assistant"), "skill uses gray dot");
    }

    // -----------------------------------------------------------------------
    // T9 — Edit/Write use new diff format
    // -----------------------------------------------------------------------

    #[test]
    fn tool_call_edit_shows_unified_diff() {
        let tce = crate::conversation::ToolCallEvent {
            id: "e1".to_string(),
            name: "Edit".to_string(),
            input: serde_json::json!({"file_path": "src/a.rs", "old_string": "a\n", "new_string": "b\n", "replace_all": false}),
            result: None,
        };
        let html = render_tool_call_event(&tce);
        assert!(html.contains("diff-line--add"), "must have add diff line");
        assert!(html.contains("diff-line--del"), "must have del diff line");
        assert!(html.contains("diff-count--add"), "must have summary add class");
        // T18: event row shows basename with full path in tooltip.
        assert!(html.contains("data-tooltip=\"src/a.rs\""), "full path must appear in tooltip");
        assert!(html.contains(">a.rs<"), "basename must appear as visible text");
    }

    // -----------------------------------------------------------------------
    // T18 — File-name basename + tooltip
    // -----------------------------------------------------------------------

    #[test]
    fn basename_helper_returns_last_segment() {
        assert_eq!(basename("src/render/tools/mod.rs"), "mod.rs");
        assert_eq!(basename("mod.rs"), "mod.rs");
        assert_eq!(basename("/abs/path/file.txt"), "file.txt");
        assert_eq!(basename("dir\\windows\\file.rs"), "file.rs");
        assert_eq!(basename(""), "");
    }

    #[test]
    fn read_event_shows_basename_with_full_path_tooltip() {
        let tce = crate::conversation::ToolCallEvent {
            id: "r10".to_string(),
            name: "Read".to_string(),
            input: serde_json::json!({"file_path": "src/render/html.rs"}),
            result: Some(crate::conversation::ToolResult {
                content: "// html module".to_string(),
                is_error: false,
            }),
        };
        let html = render_tool_call_event(&tce);
        assert!(html.contains("data-tooltip=\"src/render/html.rs\""), "full path in tooltip");
        assert!(html.contains(">html.rs<") || html.contains("html.rs\""), "basename visible");
        assert!(!html.contains(">src/render/html.rs<"), "full path not as visible text");
    }

    #[test]
    fn read_event_no_result_shows_basename_with_tooltip() {
        let tce = crate::conversation::ToolCallEvent {
            id: "r11".to_string(),
            name: "Read".to_string(),
            input: serde_json::json!({"file_path": "src/lib.rs"}),
            result: None,
        };
        let html = render_tool_call_event(&tce);
        assert!(html.contains("data-tooltip=\"src/lib.rs\""), "full path in tooltip");
        assert!(html.contains(">lib.rs<"), "basename in visible text");
    }

    #[test]
    fn write_event_shows_basename_with_tooltip() {
        let tce = crate::conversation::ToolCallEvent {
            id: "w10".to_string(),
            name: "Write".to_string(),
            input: serde_json::json!({"file_path": "src/main.rs", "content": "fn main() {}"}),
            result: None,
        };
        let html = render_tool_call_event(&tce);
        assert!(html.contains("data-tooltip=\"src/main.rs\""), "full path in tooltip");
        assert!(html.contains(">main.rs<"), "basename visible");
    }

    #[test]
    fn multiedit_event_shows_basename_with_tooltip() {
        let tce = crate::conversation::ToolCallEvent {
            id: "me10".to_string(),
            name: "MultiEdit".to_string(),
            input: serde_json::json!({"file_path": "src/render/mod.rs", "edits": [{"old_string": "a", "new_string": "b", "replace_all": false}]}),
            result: None,
        };
        let html = render_tool_call_event(&tce);
        assert!(html.contains("data-tooltip=\"src/render/mod.rs\""), "full path in tooltip");
        assert!(html.contains(">mod.rs<"), "basename visible");
    }

    // -----------------------------------------------------------------------
    // T20 — IN/OUT clamp: pre-wrap div present
    // -----------------------------------------------------------------------

    #[test]
    fn tool_section_wraps_pre_in_pre_wrap() {
        let html = render_tool_section("IN", "some content", false);
        assert!(html.contains("tool-section-pre-wrap"), "must have pre-wrap container");
        assert!(html.contains("<pre class=\"tool-section-body\">"), "pre inside wrap");
    }

    #[test]
    fn tool_section_error_wraps_pre_in_pre_wrap() {
        let html = render_tool_section("OUT", "error output", true);
        assert!(html.contains("tool-section--error"), "error class on outer div");
        assert!(html.contains("tool-section-pre-wrap"), "pre-wrap present even for errors");
    }

    // -----------------------------------------------------------------------
    // T21 — Modal markdown via comrak
    // -----------------------------------------------------------------------

    // -----------------------------------------------------------------------
    // T24 — Skill body ONLY in modal template, no inline dump
    // -----------------------------------------------------------------------

    #[test]
    fn skill_event_body_only_in_template_not_inline() {
        let tce = crate::conversation::ToolCallEvent {
            id: "sk99".to_string(),
            name: "Skill".to_string(),
            input: serde_json::json!({"skill": "test-fake-skill-zzz:nonexistent", "args": ""}),
            result: Some(crate::conversation::ToolResult {
                content: "## Build Skill body content here".to_string(),
                is_error: false,
            }),
        };
        let html = render_tool_call_event(&tce);
        // Row must show skill name button (gray dot).
        assert!(html.contains("test-fake-skill-zzz:nonexistent"), "row must show skill name");
        assert!(html.contains("skill"), "row must contain 'skill' label");
        assert!(html.contains("dot--assistant"), "skill uses gray dot");
        assert!(html.contains("skill-link"), "row must have modal trigger");
        // Body must be inside <template>, not floating outside.
        let template_start = html.find("<template").expect("template must be present");
        let template_end = html.find("</template>").expect("</template> must be present");
        // Content before <template> must not contain the body text.
        let before_template = &html[..template_start];
        assert!(
            !before_template.contains("Build Skill body"),
            "body must not appear before <template>"
        );
        // Content inside template must contain the body.
        let inside_template = &html[template_start..template_end];
        assert!(inside_template.contains("Build Skill body"), "body must be inside <template>");
    }

    #[test]
    fn skill_event_body_is_markdown_not_escaped() {
        let tce = crate::conversation::ToolCallEvent {
            id: "sk10".to_string(),
            name: "Skill".to_string(),
            input: serde_json::json!({"skill": "test-fake-skill-zzz:nonexistent", "args": ""}),
            result: Some(crate::conversation::ToolResult {
                content: "# Plan\n\n- step one\n- step two\n".to_string(),
                is_error: false,
            }),
        };
        let html = render_tool_call_event(&tce);
        // Markdown rendered: headings and list items produce HTML tags.
        assert!(html.contains("<h1>") || html.contains("<h1 "), "heading rendered as <h1>");
        assert!(html.contains("<li>"), "list items rendered as <li>");
        // Raw markdown not escaped as literal text.
        assert!(!html.contains("# Plan"), "raw MD heading must not appear literally");
    }

    #[test]
    fn read_event_md_file_body_is_markdown_rendered() {
        let tce = crate::conversation::ToolCallEvent {
            id: "rm10".to_string(),
            name: "Read".to_string(),
            input: serde_json::json!({"file_path": "README.md"}),
            result: Some(crate::conversation::ToolResult {
                content: "# Hello\n\nWorld paragraph.\n".to_string(),
                is_error: false,
            }),
        };
        let html = render_tool_call_event(&tce);
        assert!(html.contains("<h1>") || html.contains("<h1 "), "markdown file rendered as HTML");
        assert!(!html.contains("# Hello"), "raw heading must not appear literally");
    }

    #[test]
    fn read_event_code_file_body_stays_pre() {
        let tce = crate::conversation::ToolCallEvent {
            id: "rc10".to_string(),
            name: "Read".to_string(),
            input: serde_json::json!({"file_path": "src/main.rs"}),
            result: Some(crate::conversation::ToolResult {
                content: "fn main() {}".to_string(),
                is_error: false,
            }),
        };
        let html = render_tool_call_event(&tce);
        assert!(html.contains("<pre"), "code file stays in <pre>");
        assert!(html.contains("fn main"), "code content preserved");
    }

    // -----------------------------------------------------------------------
    // T10 — Sub-agent row
    // -----------------------------------------------------------------------

    #[test]
    fn sub_agent_row_shows_agent_description_green_dot() {
        let sa = crate::conversation::SubAgentEvent {
            tool_call_id: "t1".to_string(),
            name: "Task".to_string(),
            input: serde_json::json!({"description": "search codebase", "prompt": "find *.rs"}),
            result: None,
        };
        let html = render_sub_agent_row(&sa);
        assert!(html.contains("Agent:"), "must show Agent: prefix");
        assert!(html.contains("search codebase"), "description must appear");
        assert!(html.contains("dot--tool"), "must use green dot");
        assert!(html.contains("find *.rs"), "IN prompt must appear");
        assert!(html.contains("<details"), "must be expandable for non-empty prompt");
    }

    #[test]
    fn sub_agent_row_no_prompt_is_plain_row() {
        let sa = crate::conversation::SubAgentEvent {
            tool_call_id: "t2".to_string(),
            name: "Agent".to_string(),
            input: serde_json::json!({"description": "do work"}),
            result: None,
        };
        let html = render_sub_agent_row(&sa);
        assert!(html.contains("do work"), "description must appear");
        assert!(!html.contains("<details"), "no prompt → no expandable details");
    }

    // -----------------------------------------------------------------------
    // T11 — Images thumbnails → modal
    // -----------------------------------------------------------------------

    #[test]
    fn images_thumbnail_row_renders_horizontal_layout() {
        let images = vec![
            crate::model::content::ImageSource {
                source_type: "base64".to_string(),
                media_type: "image/png".to_string(),
                data: "abc123".to_string(),
            },
            crate::model::content::ImageSource {
                source_type: "base64".to_string(),
                media_type: "image/png".to_string(),
                data: "def456".to_string(),
            },
        ];
        let html = render_images_thumbnail_row(&images, "msg-5");
        assert!(html.contains("img-thumbnails"), "must have thumbnails container");
        assert!(html.contains("img-thumb"), "must have thumbnail class");
        assert_eq!(html.matches("img-thumb-btn").count(), 2, "two thumbnails for two images");
        assert_eq!(html.matches("<template").count(), 2, "two templates for two images");
        assert!(html.contains("data-modal="), "thumbnails must trigger modal");
        assert!(html.contains("img-modal-full"), "full-size img in template");
    }
}