koda-cli 0.2.22

A high-performance AI coding agent for macOS and Linux
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
//! Conversation transcript generator.
//!
//! Converts a session's `Message` slice into a Markdown document for
//! clipboard copy or file export. Two modes:
//!
//! - **Verbose** (default) โ€” full fidelity: timestamps, token counts,
//!   all tool output (including Bash), session metadata header.
//! - **Summary** (`--summary`) โ€” concise, human-readable: hides Bash
//!   output, omits token counts and timestamps.
//!
//! ## Verbose format
//!
//! ```text
//! # Koda Session โ€” My Task
//!
//! | Field | Value |
//! |---|---|
//! | Session | abc123 |
//! | Model | claude-sonnet-4-20250514 |
//! | Started | 2026-04-10 10:32 UTC |
//!
//! ---
//!
//! ## ๐Ÿง‘ User  <sub>10:32:01</sub>
//! What does this function do?
//!
//! ## ๐Ÿค– Assistant  <sub>10:32:05</sub>
//! The function `foo()` does โ€ฆ
//!
//! <sub>tokens: 1234 prompt ยท 567 completion ยท 890 cache-read</sub>
//!
//! ### ๐Ÿ“„ **Read** `src/main.rs`
//!
//! (full tool output shown)
//! ```

use koda_core::persistence::{Message, Role};
use koda_core::tools::{ToolEffect, classify_tool};
use std::collections::HashMap;

/// Session metadata for the verbose transcript header.
///
/// Assembled by the caller (`handle_export`) from live config โ€” not stored
/// in the DB (see #878 design discussion).
#[derive(Debug, Default)]
pub struct SessionMeta {
    pub session_id: String,
    pub title: Option<String>,
    pub started_at: Option<String>,
    pub model: String,
    pub provider: String,
    pub project_root: String,
}

/// Maximum content lines to include per tool result in summary mode.
const SUMMARY_RESULT_LINES: usize = 10;

/// Maximum content lines to include per tool result in verbose mode.
const VERBOSE_RESULT_LINES: usize = 50;

/// Bash command truncation limit in summary mode.
const SUMMARY_BASH_CHARS: usize = 80;

/// Bash command truncation limit in verbose mode (effectively unlimited).
const VERBOSE_BASH_CHARS: usize = 500;

/// Env-var name for opting out of markdown hyperlinks in transcripts.
///
/// Default behavior: emit hyperlinks. Setting this to `"off"`, `"0"`,
/// or `"false"` disables them so paths render as plain text. Useful for
/// downstream consumers that munge markdown links into something less
/// readable than the bare path.
const HYPERLINK_KILL_SWITCH: &str = "KODA_TRANSCRIPT_HYPERLINKS";

fn hyperlinks_enabled() -> bool {
    !matches!(
        std::env::var(HYPERLINK_KILL_SWITCH).ok().as_deref(),
        Some("off" | "0" | "false" | "no")
    )
}

/// Format the current UTC time as `YYYY-MM-DD HH:MM UTC` for the transcript header.
fn format_utc_now() -> String {
    let dt = crate::util::utc_now();
    format!(
        "{:04}-{:02}-{:02} {:02}:{:02} UTC",
        dt.year(),
        dt.month() as u8,
        dt.day(),
        dt.hour(),
        dt.minute(),
    )
}

/// Generate a Markdown transcript from a slice of session messages.
///
/// - `verbose = true` (default): full fidelity โ€” timestamps, token counts,
///   all tool output, session metadata header.
/// - `verbose = false` (`--summary`): concise, human-readable.
///
/// Returns the transcript as a `String`. The caller is responsible for
/// writing it to the clipboard or a file.
pub fn render(messages: &[Message], meta: &SessionMeta, verbose: bool) -> String {
    let mut out = String::with_capacity(if verbose { 16384 } else { 4096 });

    // Header
    let title = meta.title.as_deref().unwrap_or("Koda Session");
    let now = format_utc_now();
    out.push_str(&format!("# {title} โ€” {now}\n\n"));

    if verbose {
        render_metadata_table(&mut out, meta);
    }

    // Build tool_call_id โ†’ tool_name mapping for result correlation
    let mut tool_id_to_name: HashMap<String, String> = HashMap::new();
    for msg in messages {
        if msg.role == Role::Assistant
            && let Some(ref tc_json) = msg.tool_calls
            && let Ok(calls) = serde_json::from_str::<Vec<serde_json::Value>>(tc_json)
        {
            for call in calls {
                if let (Some(id), Some(name)) =
                    (call["id"].as_str(), call["function"]["name"].as_str())
                {
                    tool_id_to_name.insert(id.to_string(), name.to_string());
                }
            }
        }
    }

    for msg in messages {
        match msg.role {
            Role::System => {} // Skip โ€” internal plumbing

            Role::User => {
                out.push_str("---\n\n");
                render_role_header(&mut out, "\u{1f9d1} User", msg, verbose);
                if let Some(ref content) = msg.content {
                    out.push_str(content.trim());
                    out.push_str("\n\n");
                }
            }

            Role::Assistant => {
                render_role_header(&mut out, "๐Ÿค– Assistant", msg, verbose);

                // Thinking block (Claude extended thinking) โ€” before text
                if let Some(ref thinking) = msg.thinking_content
                    && !thinking.trim().is_empty()
                {
                    out.push_str("> ๐Ÿ’ญ **Thinking**\n");
                    for line in thinking.trim().lines() {
                        out.push_str("> ");
                        out.push_str(line);
                        out.push('\n');
                    }
                    out.push('\n');
                }

                // Text content
                if let Some(ref content) = msg.content {
                    let trimmed = content.trim();
                    if !trimmed.is_empty() {
                        out.push_str(trimmed);
                        out.push_str("\n\n");
                    }
                }

                // Tool call headers
                if let Some(ref tc_json) = msg.tool_calls
                    && let Ok(calls) = serde_json::from_str::<Vec<serde_json::Value>>(tc_json)
                {
                    let bash_limit = if verbose {
                        VERBOSE_BASH_CHARS
                    } else {
                        SUMMARY_BASH_CHARS
                    };
                    let link = hyperlinks_enabled();
                    for call in &calls {
                        let name = call["function"]["name"].as_str().unwrap_or("Tool");
                        let args_json = call["function"]["arguments"].as_str().unwrap_or("{}");
                        let detail = tool_detail_markdown(
                            name,
                            args_json,
                            bash_limit,
                            &meta.project_root,
                            link,
                        );
                        let icon = tool_icon(name);
                        out.push_str(&format!("### {icon} **{name}**"));
                        if !detail.is_empty() {
                            // Detail may already contain markdown link
                            // syntax (`[disp](uri)`); only the plain-text
                            // branches are wrapped in backticks. Linked
                            // detail is left bare so the link renders.
                            if detail.starts_with('[') {
                                out.push(' ');
                                out.push_str(&detail);
                            } else {
                                out.push_str(&format!(" `{detail}`"));
                            }
                        }
                        out.push('\n');
                    }
                    out.push('\n');
                }

                // Token counts (verbose only)
                if verbose {
                    render_token_counts(&mut out, msg);
                }
            }

            Role::Tool => {
                let tool_name = msg
                    .tool_call_id
                    .as_deref()
                    .and_then(|id| tool_id_to_name.get(id))
                    .map(|s| s.as_str())
                    .unwrap_or("");

                let content = msg.content.as_deref().unwrap_or("").trim();
                let total_lines = content.lines().count();

                if !content.is_empty() {
                    let effect = classify_tool(tool_name);
                    let max_lines = if verbose {
                        VERBOSE_RESULT_LINES
                    } else {
                        SUMMARY_RESULT_LINES
                    };

                    // Verbose: show all tool output. Summary: only read-only.
                    let show_content = verbose || effect == ToolEffect::ReadOnly;

                    if show_content {
                        out.push_str("**Output:**\n\n```\n");
                        let preview_lines: Vec<&str> = content.lines().take(max_lines).collect();
                        out.push_str(&preview_lines.join("\n"));
                        if total_lines > max_lines {
                            out.push_str(&format!("\nโ€ฆ ({} more lines)", total_lines - max_lines));
                        }
                        out.push_str("\n```\n\n");
                    } else if total_lines > 0 {
                        out.push_str(&format!(
                            "> _{total_lines} line(s) of output โ€” run tool to see full result_\n\n"
                        ));
                    }
                }
            }
        }
    }

    out
}

// โ”€โ”€ Verbose-mode helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

/// Render the metadata table at the top of a verbose transcript.
fn render_metadata_table(out: &mut String, meta: &SessionMeta) {
    out.push_str("| Field | Value |\n|---|---|\n");
    out.push_str(&format!("| Session | `{}` |\n", meta.session_id));
    out.push_str(&format!("| Model | {} |\n", meta.model));
    out.push_str(&format!("| Provider | {} |\n", meta.provider));
    out.push_str(&format!("| Project | `{}` |\n", meta.project_root));
    if let Some(ref started) = meta.started_at {
        out.push_str(&format!("| Started | {started} |\n"));
    }
    out.push('\n');
}

/// Render a role header with an optional timestamp (verbose mode).
fn render_role_header(out: &mut String, label: &str, msg: &Message, verbose: bool) {
    out.push_str(&format!("## {label}"));
    if verbose && let Some(ref ts) = msg.created_at {
        // Show HH:MM:SS portion if it looks like an ISO timestamp.
        let time_part = ts.split('T').nth(1).and_then(|t| t.get(..8)).unwrap_or(ts);
        out.push_str(&format!("  <sub>{time_part}</sub>"));
    }
    out.push_str("\n\n");
}

/// Render token counts after an assistant message (verbose mode).
fn render_token_counts(out: &mut String, msg: &Message) {
    let mut parts: Vec<String> = Vec::new();
    if let Some(p) = msg.prompt_tokens {
        parts.push(format!("{p} prompt"));
    }
    if let Some(c) = msg.completion_tokens {
        parts.push(format!("{c} completion"));
    }
    if let Some(cr) = msg.cache_read_tokens
        && cr > 0
    {
        parts.push(format!("{cr} cache-read"));
    }
    if let Some(cc) = msg.cache_creation_tokens
        && cc > 0
    {
        parts.push(format!("{cc} cache-write"));
    }
    if let Some(t) = msg.thinking_tokens
        && t > 0
    {
        parts.push(format!("{t} thinking"));
    }
    if !parts.is_empty() {
        out.push_str(&format!("<sub>tokens: {}</sub>\n\n", parts.join(" ยท ")));
    }
}

/// Human-readable icon for each tool type.
fn tool_icon(name: &str) -> &'static str {
    match name {
        "Read" => "๐Ÿ“„",
        "Write" => "โœ๏ธ",
        "Edit" => "โœ๏ธ",
        "Delete" => "๐Ÿ—‘๏ธ",
        "Bash" => "๐Ÿ’ป",
        "Grep" => "๐Ÿ”",
        "List" | "Glob" => "๐Ÿ“",
        "WebFetch" => "๐ŸŒ",
        "TodoWrite" => "๐Ÿ“‹",
        "MemoryWrite" | "MemoryRead" => "๐Ÿง ",
        "InvokeAgent" => "๐Ÿค–",
        "AskUser" => "๐Ÿ’ฌ",
        _ => "๐Ÿ”ง",
    }
}

/// One-line summary of a tool call's arguments, with file paths and URLs
/// rendered as **markdown links** when hyperlinks are enabled.
///
/// Per-tool dispatch is delegated to [`crate::tool_header::detail_text`]
/// so the same `(name, args)` pair always produces the same human-readable
/// summary across the live TUI, history replay, and transcript export.
/// This wrapper only adds the markdown-link layer on top of the shared
/// plain-text summary.
///
/// `bash_limit` controls Bash command truncation (80 in summary, 500 in verbose).
/// `project_root` is used to resolve relative file paths into absolute
/// `file:///` URIs; if empty or the path is already absolute, no resolution
/// is performed.
fn tool_detail_markdown(
    name: &str,
    args_json: &str,
    bash_limit: usize,
    project_root: &str,
    link: bool,
) -> String {
    let args: serde_json::Value =
        serde_json::from_str(args_json).unwrap_or(serde_json::Value::Null);
    let raw = crate::tool_header::detail_text(name, &args, bash_limit);
    if !link || raw.is_empty() {
        return raw;
    }
    match name {
        "Read" | "Write" | "Edit" | "Delete" => {
            // `raw` is the file path; wrap as [path](file:///abs).
            let abs = absolute_path(&raw, project_root);
            format!("[{raw}]({})", file_uri(&abs))
        }
        "WebFetch" => format!("[{raw}]({raw})"),
        // Grep / Glob / List / Bash / generic: leave as plain text.
        // The directory portion of Grep is intentionally NOT linked
        // because the eye-catching part is the pattern, not the dir.
        _ => raw,
    }
}

/// Resolve `path` against `project_root` if relative; pass through if absolute.
///
/// We deliberately don't try to canonicalize (the file may not exist on
/// the machine viewing the transcript). The resulting string is best-effort.
fn absolute_path(path: &str, project_root: &str) -> String {
    if path.starts_with('/') || project_root.is_empty() {
        return path.to_string();
    }
    let root = project_root.trim_end_matches('/');
    format!("{root}/{path}")
}

/// Build a `file:///` URI from an absolute path with light percent-encoding.
///
/// Encodes the characters most likely to break markdown link parsing:
/// space, parenthesis, square bracket. Other characters are passed through
/// โ€” most viewers tolerate them, and full percent-encoding would pull in a
/// dependency for marginal benefit.
fn file_uri(abs_path: &str) -> String {
    let mut out = String::with_capacity(abs_path.len() + 8);
    out.push_str("file://");
    if !abs_path.starts_with('/') {
        out.push('/');
    }
    for ch in abs_path.chars() {
        match ch {
            ' ' => out.push_str("%20"),
            '(' => out.push_str("%28"),
            ')' => out.push_str("%29"),
            '[' => out.push_str("%5B"),
            ']' => out.push_str("%5D"),
            _ => out.push(ch),
        }
    }
    out
}

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

    fn make_msg(role: Role, content: &str) -> Message {
        Message {
            id: 0,
            session_id: "test".into(),
            role,
            content: Some(content.into()),
            full_content: None,
            tool_calls: None,
            tool_call_id: None,
            prompt_tokens: None,
            completion_tokens: None,
            cache_read_tokens: None,
            cache_creation_tokens: None,
            thinking_tokens: None,
            thinking_content: None,
            created_at: None,
        }
    }

    fn default_meta() -> SessionMeta {
        SessionMeta {
            session_id: "test-session".into(),
            title: None,
            started_at: None,
            model: "test-model".into(),
            provider: "test-provider".into(),
            project_root: "/tmp/project".into(),
        }
    }

    #[test]
    fn empty_messages_produces_header_only() {
        let meta = SessionMeta {
            title: Some("Test Session".into()),
            ..default_meta()
        };
        let out = render(&[], &meta, false);
        assert!(out.contains("# Test Session"));
        assert!(!out.contains("๐Ÿง‘ User"));
    }

    #[test]
    fn user_message_renders_correctly() {
        let msgs = vec![make_msg(Role::User, "hello koda")];
        let out = render(&msgs, &default_meta(), false);
        assert!(out.contains("๐Ÿง‘ User"));
        assert!(out.contains("hello koda"));
    }

    #[test]
    fn assistant_message_renders_correctly() {
        let msgs = vec![make_msg(Role::Assistant, "I can help!")];
        let out = render(&msgs, &default_meta(), false);
        assert!(out.contains("๐Ÿค– Assistant"));
        assert!(out.contains("I can help!"));
    }

    #[test]
    fn system_messages_skipped() {
        let msgs = vec![
            make_msg(Role::System, "secret prompt"),
            make_msg(Role::User, "hi"),
        ];
        let out = render(&msgs, &default_meta(), false);
        assert!(!out.contains("secret prompt"));
    }

    #[test]
    fn tool_read_result_shown_as_code_block() {
        let mut result_msg = make_msg(Role::Tool, "fn main() {}\n");
        result_msg.tool_call_id = Some("call_1".into());

        let mut assistant_msg = make_msg(Role::Assistant, "");
        assistant_msg.tool_calls = Some(
            serde_json::json!([{
                "id": "call_1",
                "function": { "name": "Read", "arguments": r#"{"file_path":"src/main.rs"}"# }
            }])
            .to_string(),
        );

        let msgs = vec![assistant_msg, result_msg];
        let out = render(&msgs, &default_meta(), false);
        assert!(out.contains("```"));
        assert!(out.contains("fn main()"));
    }

    #[test]
    fn bash_result_shows_summary_not_content() {
        let mut result_msg = make_msg(Role::Tool, "line1\nline2\nline3");
        result_msg.tool_call_id = Some("call_2".into());

        let mut assistant_msg = make_msg(Role::Assistant, "");
        assistant_msg.tool_calls = Some(
            serde_json::json!([{
                "id": "call_2",
                "function": { "name": "Bash", "arguments": r#"{"command":"ls"}"# }
            }])
            .to_string(),
        );

        let msgs = vec![assistant_msg, result_msg];
        let out = render(&msgs, &default_meta(), false);
        // Bash is mutating โ†’ summarised in summary mode, not shown verbatim
        assert!(!out.contains("line1"));
        assert!(out.contains("3 line(s) of output"));
    }

    #[test]
    fn thinking_content_renders_as_blockquote() {
        // thinking_content is Claude's chain-of-thought โ€” it is intentionally
        // included in the exported transcript as a blockquote so the user can
        // review the model's reasoning (#819).
        let mut msg = make_msg(Role::Assistant, "The answer is 42.");
        msg.thinking_content = Some("Let me think step by step: 6 x 7 = 42.".into());

        let out = render(&[msg], &default_meta(), false);
        assert!(
            out.contains("The answer is 42."),
            "response text must appear"
        );
        assert!(
            out.contains("Thinking"),
            "thinking block header must appear in transcript"
        );
        assert!(
            out.contains("Let me think step by step"),
            "thinking content must appear in transcript",
        );
    }

    #[test]
    fn verbose_header_includes_metadata() {
        let meta = SessionMeta {
            session_id: "sess-42".into(),
            title: Some("Debug Session".into()),
            started_at: Some("2026-04-14T12:00:00Z".into()),
            model: "claude-sonnet-4-20250514".into(),
            provider: "anthropic".into(),
            project_root: "/home/user/project".into(),
        };
        let out = render(&[], &meta, true);
        assert!(out.contains("sess-42"), "session ID in header");
        assert!(out.contains("claude-sonnet-4-20250514"), "model in header");
        assert!(out.contains("anthropic"), "provider in header");
        assert!(out.contains("/home/user/project"), "project root in header");
    }

    #[test]
    fn verbose_shows_token_counts() {
        let mut msg = make_msg(Role::Assistant, "The answer.");
        msg.prompt_tokens = Some(100);
        msg.completion_tokens = Some(50);
        msg.cache_read_tokens = Some(80);

        let out = render(&[msg], &default_meta(), true);
        assert!(out.contains("100 prompt"), "prompt tokens shown");
        assert!(out.contains("50 completion"), "completion tokens shown");
        assert!(out.contains("80 cache-read"), "cache-read tokens shown");
    }

    #[test]
    fn summary_hides_token_counts() {
        let mut msg = make_msg(Role::Assistant, "The answer.");
        msg.prompt_tokens = Some(100);
        msg.completion_tokens = Some(50);

        let out = render(&[msg], &default_meta(), false);
        assert!(!out.contains("100 prompt"));
    }

    #[test]
    fn verbose_shows_timestamps() {
        let mut msg = make_msg(Role::User, "hello");
        msg.created_at = Some("2026-04-14T09:15:30Z".into());

        let out = render(&[msg], &default_meta(), true);
        assert!(out.contains("09:15:30"), "timestamp shown in verbose");
    }

    #[test]
    fn summary_hides_timestamps() {
        let mut msg = make_msg(Role::User, "hello");
        msg.created_at = Some("2026-04-14T09:15:30Z".into());

        let out = render(&[msg], &default_meta(), false);
        assert!(!out.contains("09:15:30"), "timestamp hidden in summary");
    }

    #[test]
    fn bash_result_shown_in_verbose_mode() {
        let mut result_msg = make_msg(Role::Tool, "line1\nline2\nline3");
        result_msg.tool_call_id = Some("call_3".into());

        let mut assistant_msg = make_msg(Role::Assistant, "");
        assistant_msg.tool_calls = Some(
            serde_json::json!([{
                "id": "call_3",
                "function": { "name": "Bash", "arguments": r#"{"command":"ls"}"# }
            }])
            .to_string(),
        );

        let msgs = vec![assistant_msg, result_msg];
        let out = render(&msgs, &default_meta(), true);
        // Verbose mode shows all tool output, including Bash
        assert!(out.contains("line1"));
        assert!(out.contains("line3"));
    }

    // โ”€โ”€ Markdown hyperlink emission โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    /// Build an assistant message with a single tool call.
    fn assistant_with_call(name: &str, args_json: &str) -> Message {
        let mut m = make_msg(Role::Assistant, "");
        m.tool_calls = Some(
            serde_json::json!([{
                "id": "c1",
                "function": { "name": name, "arguments": args_json }
            }])
            .to_string(),
        );
        m
    }

    #[test]
    fn read_path_emits_markdown_link_with_file_uri() {
        let msg = assistant_with_call("Read", r#"{"file_path":"src/main.rs"}"#);
        let meta = SessionMeta {
            project_root: "/home/user/proj".into(),
            ..default_meta()
        };
        let out = render(&[msg], &meta, false);
        assert!(
            out.contains("[src/main.rs](file:///home/user/proj/src/main.rs)"),
            "relative path should resolve under project_root, got:\n{out}"
        );
    }

    #[test]
    fn absolute_read_path_skips_root_join() {
        let msg = assistant_with_call("Read", r#"{"file_path":"/etc/hosts"}"#);
        let meta = SessionMeta {
            project_root: "/home/user/proj".into(),
            ..default_meta()
        };
        let out = render(&[msg], &meta, false);
        assert!(
            out.contains("[/etc/hosts](file:///etc/hosts)"),
            "absolute path should pass through, got:\n{out}"
        );
    }

    #[test]
    fn webfetch_url_becomes_self_link() {
        let msg = assistant_with_call("WebFetch", r#"{"url":"https://example.com/x"}"#);
        let out = render(&[msg], &default_meta(), false);
        assert!(
            out.contains("[https://example.com/x](https://example.com/x)"),
            "URL should be a markdown self-link, got:\n{out}"
        );
    }

    #[test]
    fn bash_detail_stays_plain_codespan() {
        // Bash commands aren't paths or URLs โ€” keep them in backticks
        // so monospace formatting (and shell tokens) survive.
        let msg = assistant_with_call("Bash", r#"{"command":"git status"}"#);
        let out = render(&[msg], &default_meta(), false);
        assert!(out.contains("`git status`"), "got:\n{out}");
        assert!(
            !out.contains("](git status)"),
            "bash should never be linked"
        );
    }

    #[test]
    fn grep_detail_stays_plain_codespan() {
        let msg = assistant_with_call("Grep", r#"{"search_string":"TODO","directory":"src"}"#);
        let out = render(&[msg], &default_meta(), false);
        assert!(out.contains("`\"TODO\" in src`"), "got:\n{out}");
    }

    #[test]
    fn kill_switch_disables_hyperlinks() {
        // Save & restore so we don't leak env across tests in this thread.
        let prev = std::env::var(HYPERLINK_KILL_SWITCH).ok();
        // SAFETY: tests in this binary run in parallel by default; this env
        // var is only read by transcript code, and the only readers in this
        // file are `kill_switch_*` tests. Running them with `--test-threads=1`
        // is the official escape hatch if they ever flake.
        unsafe { std::env::set_var(HYPERLINK_KILL_SWITCH, "off") };
        let msg = assistant_with_call("Read", r#"{"file_path":"/x.rs"}"#);
        let out = render(&[msg], &default_meta(), false);
        unsafe {
            match prev {
                Some(v) => std::env::set_var(HYPERLINK_KILL_SWITCH, v),
                None => std::env::remove_var(HYPERLINK_KILL_SWITCH),
            }
        }
        assert!(out.contains("`/x.rs`"), "plain text expected, got:\n{out}");
        assert!(!out.contains("file:///"), "link should be suppressed");
    }

    #[test]
    fn dry_equivalence_with_tool_header_detail_text() {
        // Regression guard: transcript detail strings must agree with the
        // shared `tool_header::detail_text` for every supported tool. If
        // someone forks the dispatch back into this module, this test fails.
        use crate::tool_header::detail_text;
        let cases: Vec<(&str, serde_json::Value, usize)> = vec![
            ("Read", serde_json::json!({"file_path": "a.rs"}), 80),
            ("Bash", serde_json::json!({"command": "echo hi"}), 80),
            (
                "Grep",
                serde_json::json!({"search_string": "x", "directory": "."}),
                80,
            ),
            ("Glob", serde_json::json!({"pattern": "**/*.rs"}), 80),
            ("List", serde_json::json!({"directory": "src"}), 80),
            ("WebFetch", serde_json::json!({"url": "https://x"}), 80),
        ];
        for (name, args, bash) in cases {
            let from_helper = detail_text(name, &args, bash);
            // tool_detail_markdown with link=false is a pure pass-through.
            let from_transcript = tool_detail_markdown(name, &args.to_string(), bash, "", false);
            assert_eq!(
                from_helper, from_transcript,
                "transcript detail must match tool_header::detail_text for {name}"
            );
        }
    }

    #[test]
    fn file_uri_percent_encodes_breaking_chars() {
        // Spaces and brackets break naive markdown link parsers โ€” percent-
        // encode the most common offenders so links survive copy/paste.
        let uri = file_uri("/My Files/[draft].md");
        assert_eq!(uri, "file:///My%20Files/%5Bdraft%5D.md");
    }
}