Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

65.8 KB
Raw Blame
//! Markdown rendering for the chat transcript: assistant text in, styled
//! ratatui lines out. Kept separate from the render loop so the block-level
//! theme lives in one place.

use ratatui::prelude::*;

/// Render a turn to styled lines: reasoning dimmed, answer prose passed through
/// markdown formatting. Native reasoning arrives as `segs` and is placed by its
/// offset; inline `<think>` markers are found inside the prose. `width` bounds
/// table wrapping.
pub(super) fn format_assistant_lines(
    prose: &str,
    segs: &[super::ReasoningSeg],
    width: u16,
    parse_tags: bool,
) -> Vec<Line<'static>> {
    let mut lines = Vec::new();
    for (reasoning, seg) in super::assistant_runs(prose, segs, parse_tags) {
        let next = if reasoning {
            reasoning_detail_lines(&seg)
        } else {
            answer_lines(&seg, width)
        };
        append_band(&mut lines, next);
    }
    lines
}

/// Columns the answer gutter takes: a dim `• ` on the first row, two blanks
/// on every row after it.
const ANSWER_GUTTER_COLS: u16 = 2;

/// An answer block as the transcript shows it: the markdown laid out at
/// `width - 2`, the first row behind a dim `• ` and every other row (code
/// boxes and tables included) indented two columns under it. Prose rows are
/// pre-wrapped here rather than left to the body `Paragraph`, whose wrap would
/// start each continuation at the left edge, outside the indent. The committed
/// row and the live tail both go through this, so nothing reflows when the
/// stream commits.
pub(super) fn answer_lines(text: &str, width: u16) -> Vec<Line<'static>> {
    let inner = width.saturating_sub(ANSWER_GUTTER_COLS).max(1);
    let mut out = Vec::new();
    for line in format_markdown_lines(text, inner) {
        if line.spans.iter().all(|s| s.content.is_empty()) {
            out.push(line);
            continue;
        }
        let rows = if super::fits_one_row(&line, inner) {
            vec![line.spans]
        } else {
            wrap_spans_at_words(line.spans, inner as usize)
        };
        for spans in rows {
            let gutter = if out.is_empty() {
                Span::styled("\u{2022} ", Style::new().dim())
            } else {
                Span::raw("  ")
            };
            let mut row = vec![gutter];
            row.extend(spans);
            out.push(Line::from(row).style(line.style));
        }
    }
    out
}

/// Append `next` under `lines`, separated by the blank row the committed path
/// puts between bands (`gap(Kind::Reasoning)` / `gap(Kind::Prose)` in
/// `push_assistant_blocks`). Reasoning and answer are different bands, so
/// without this the streaming answer sits flush against the summary above it and
/// then drops a row the moment the turn commits and the real gap goes in.
///
/// A run that rendered nothing appends nothing, so a hidden block leaves no
/// stray separator behind.
fn append_band(lines: &mut Vec<Line<'static>>, next: Vec<Line<'static>>) {
    if next.is_empty() {
        return;
    }
    if !lines.is_empty() {
        lines.push(Line::raw(""));
    }
    lines.extend(next);
}

/// Lines of an open reasoning block kept in the live tail: enough to see the
/// thought moving without letting a long chain of thought push the answer, and
/// the conversation above it, off the screen.
const LIVE_REASONING_TAIL_LINES: usize = 6;

/// Live tail rendering for the in-progress assistant buffer. With reasoning
/// folding on (`fold_reasoning`) the block is bounded rather than shown whole:
/// the open (unterminated) one keeps its last [`LIVE_REASONING_TAIL_LINES`]
/// lines when `stream_reasoning` is on, and a block that already closed shows
/// the same summary row `push_assistant_blocks` will commit for it, so nothing
/// jumps as the turn finalizes. With `stream_reasoning` off the open block is
/// hidden entirely and only the `[thinking]` header stands for it. When folding
/// is off this is identical to `format_assistant_lines`, so the existing
/// live-tail tests hold.
pub(super) fn live_assistant_lines(
    prose: &str,
    segs: &[super::ReasoningSeg],
    width: u16,
    fold_reasoning: bool,
    stream_reasoning: bool,
    parse_tags: bool,
) -> Vec<Line<'static>> {
    if !fold_reasoning {
        return format_assistant_lines(prose, segs, width, parse_tags);
    }
    let runs = super::assistant_runs(prose, segs, parse_tags);
    let last = runs.len().saturating_sub(1);
    let mut lines = Vec::new();
    for (i, (reasoning, seg)) in runs.into_iter().enumerate() {
        let next = if reasoning {
            // Only the trailing run can still be open; anything a later run
            // follows has ended and folds to its summary row.
            let body: Vec<&str> = seg.lines().filter(|l| !l.trim().is_empty()).collect();
            if body.is_empty() {
                continue;
            }
            if i < last {
                // Live: the duration is not yet known; the commit will restamp
                // this as `Thought for Ns`.
                vec![reasoning_summary_row(None)]
            } else if stream_reasoning {
                live_reasoning_tail(&body, width)
            } else {
                continue;
            }
        } else if seg.trim().is_empty() {
            continue;
        } else {
            answer_lines(&seg, width)
        };
        append_band(&mut lines, next);
    }
    lines
}

/// Columns the reasoning gutter takes. Subtracted from the width before the
/// live tail wraps, so a pre-wrapped row still fits and the terminal re-wraps
/// nothing.
const REASONING_GUTTER_COLS: usize = 2;

/// Character budget per reasoning step, roughly five chat lines. A paragraph
/// longer than this is subdivided so a model that streams one unbroken block
/// still produces settled steps instead of one ever-growing one.
const REASONING_STEP_MAX_CHARS: usize = 400;
/// A break earlier than this fraction of the budget would emit a stub step, so
/// `find_step_break` keeps looking past it.
const REASONING_MIN_STEP_RATIO: f32 = 0.4;

/// Split a reasoning trace into paragraph "steps": a blank (whitespace-only)
/// line starts a new step; a single newline stays within one (soft wrap / list
/// item). Trailing whitespace is trimmed and empty paragraphs dropped. Because
/// the caller passes the full accumulated text each streaming tick, the last
/// element is the paragraph currently being written and earlier ones are
/// settled -- re-segmenting a longer prefix leaves settled steps untouched.
pub(super) fn split_reasoning_paragraphs(text: &str) -> Vec<String> {
    let mut paras: Vec<String> = Vec::new();
    let mut cur: Vec<&str> = Vec::new();
    let mut flush = |cur: &mut Vec<&str>| {
        if !cur.is_empty() {
            paras.push(cur.join("\n").trim_end().to_string());
            cur.clear();
        }
    };
    for line in text.split('\n') {
        if line.trim().is_empty() {
            flush(&mut cur);
        } else {
            cur.push(line);
        }
    }
    flush(&mut cur);
    paras.retain(|p| !p.trim().is_empty());
    paras
}

/// Split a reasoning trace into steps that always advance: blank lines take
/// precedence, but any paragraph longer than `max_chars` is subdivided at the
/// best break so an unbroken block still settles into steps. Greedy from the
/// start, so a step's boundary depends only on the text before it and a growing
/// prefix leaves settled steps untouched. Port of the desktop's
/// `segmentReasoningSteps`.
pub(super) fn segment_reasoning_steps(text: &str) -> Vec<String> {
    segment_reasoning_steps_with(text, REASONING_STEP_MAX_CHARS)
}

fn segment_reasoning_steps_with(text: &str, max_chars: usize) -> Vec<String> {
    let min_chars = (max_chars as f32 * REASONING_MIN_STEP_RATIO) as usize;
    let mut steps: Vec<String> = Vec::new();
    for paragraph in split_reasoning_paragraphs(text) {
        let chars: Vec<char> = paragraph.chars().collect();
        let mut start = 0;
        while chars.len() - start > max_chars {
            let window = &chars[start..start + max_chars];
            let end = start + find_step_break(window, min_chars).unwrap_or(max_chars);
            let step: String = chars[start..end].iter().collect();
            let step = step.trim();
            if !step.is_empty() {
                steps.push(step.to_string());
            }
            start = end;
            while start < chars.len() && chars[start].is_whitespace() {
                start += 1;
            }
        }
        let tail: String = chars[start..].iter().collect();
        let tail = tail.trim();
        if !tail.is_empty() {
            steps.push(tail.to_string());
        }
    }
    steps
}

/// Char offset just past the best break in `window` (`None` when none is usable
/// at or past `min_chars`). Preference: last sentence end, then last line break,
/// then last word boundary. A sentence end must be followed by whitespace inside
/// the window, matching the desktop's `[.!?...](?=\s)` lookahead.
fn find_step_break(window: &[char], min_chars: usize) -> Option<usize> {
    let mut sentence: Option<usize> = None;
    for i in 0..window.len() {
        let ends_sentence = matches!(window[i], '.' | '!' | '?' | '。' | '!' | '?');
        let followed_by_space = window.get(i + 1).is_some_and(|c| c.is_whitespace());
        if ends_sentence && followed_by_space {
            sentence = Some(i + 1);
        }
    }
    if let Some(s) = sentence.filter(|s| *s >= min_chars) {
        return Some(s);
    }
    if let Some(nl) = window.iter().rposition(|&c| c == '\n').filter(|nl| *nl >= min_chars) {
        return Some(nl + 1);
    }
    (min_chars..window.len())
        .rev()
        .find(|&i| window[i].is_whitespace())
        .map(|i| i + 1)
}

fn reasoning_row(body: Vec<Span<'static>>) -> Line<'static> {
    let mut spans = vec![Span::styled("┊ ", Style::new().dark_gray())];
    spans.extend(body);
    Line::from(spans)
}

fn reasoning_body_span(text: String) -> Span<'static> {
    Span::styled(text, Style::new().dim().italic())
}

/// A reasoning block's full dimmed lines (`┊ ` gutter, dim italic body),
/// segmented into steps: a blank rail row separates each paragraph step so the
/// expanded trace reads as discrete thoughts rather than one wall of text,
/// matching the desktop's stepped rail.
pub(super) fn reasoning_detail_lines(seg: &str) -> Vec<Line<'static>> {
    let mut out = Vec::new();
    for step in segment_reasoning_steps(seg) {
        if !out.is_empty() {
            // A bare rail row (gutter, no body) sets each step apart.
            out.push(reasoning_row(Vec::new()));
        }
        for line in step.lines() {
            out.push(reasoning_row(vec![reasoning_body_span(line.to_string())]));
        }
    }
    out
}

/// The open block's tail, bounded to [`LIVE_REASONING_TAIL_LINES`] *rendered*
/// rows rather than source lines. Reasoning usually arrives as one long
/// paragraph, so a source-line cap bounded nothing on screen: the block's
/// height moved with however far the newest line had wrapped, jittering by a
/// row or two as it grew. Wrapping here also gives every continuation its own
/// gutter instead of letting it start under the margin.
fn live_reasoning_tail(body: &[&str], width: u16) -> Vec<Line<'static>> {
    let max = (width as usize)
        .saturating_sub(REASONING_GUTTER_COLS)
        .max(1);
    let rows: Vec<Vec<Span<'static>>> = body
        .iter()
        .flat_map(|l| wrap_spans_at_words(vec![reasoning_body_span(l.to_string())], max))
        .collect();
    rows[rows.len().saturating_sub(LIVE_REASONING_TAIL_LINES)..]
        .iter()
        .map(|spans| reasoning_row(spans.clone()))
        .collect()
}

/// The bounded scrolling tail of a committed reasoning block, identical to what
/// the live stream showed: the last [`LIVE_REASONING_TAIL_LINES`] rendered rows.
/// Used while the newest step lingers expanded before it folds, so the view does
/// not jump from a scrolling tail to the whole block and back to a summary.
pub(super) fn reasoning_tail_lines(seg: &str, width: u16) -> Vec<Line<'static>> {
    let body: Vec<&str> = seg.lines().filter(|l| !l.trim().is_empty()).collect();
    if body.is_empty() {
        return Vec::new();
    }
    live_reasoning_tail(&body, width)
}

/// Collapsed summary row for a folded reasoning block, in the desktop's
/// `Thought for Ns` wording. The duration is known once the block closes;
/// before that (the live settled-summary) and on replay of a journal written
/// without it, `None` reads as a plain `Thought`.
pub(super) fn reasoning_summary_row(dur: Option<std::time::Duration>) -> Line<'static> {
    // A sub-second block reads as `Thought` rather than `Thought for 0s`; the
    // duration is only worth showing once it rounds to a second.
    let label = match dur.map(|d| d.as_secs()).filter(|s| *s >= 1) {
        Some(secs) => format!("Thought for {}", super::format_elapsed(secs)),
        None => "Thought".to_string(),
    };
    reasoning_row(vec![reasoning_body_span(label)])
}

/// Render answer prose to styled lines. Every block -- prose, code fences,
/// pipe tables -- comes from one `pulldown-cmark` pass, so cell and code
/// contents are extracted by the parser rather than by matching raw lines.
fn format_markdown_lines(text: &str, width: u16) -> Vec<Line<'static>> {
    use pulldown_cmark::{Event, Options, Parser, Tag};

    #[cfg(test)]
    super::tally(&super::MD_PARSES);
    let mut opts = Options::empty();
    opts.insert(Options::ENABLE_STRIKETHROUGH);
    opts.insert(Options::ENABLE_TASKLISTS);
    opts.insert(Options::ENABLE_TABLES);

    let events: Vec<Event> = Parser::new_ext(text, opts).collect();
    let mut r = Renderer::new(width);
    // A fence that has not closed yet is still being streamed: its body changes
    // on every delta, so highlighting it is re-done from scratch each frame and
    // cannot be cached. Leave the open block plain and highlight it once the
    // closing fence lands.
    if has_open_fence(text) {
        let blocks = events
            .iter()
            .filter(|e| matches!(e, Event::Start(Tag::CodeBlock(_))))
            .count();
        r.plain_code_block = Some(blocks);
    }
    for event in events {
        r.handle(event);
    }
    r.finish()
}

/// True when `text` ends inside a fenced code block, i.e. an odd number of
/// fence markers have been seen. Cheap enough to run per frame; it only reads
/// line starts.
fn has_open_fence(text: &str) -> bool {
    let mut open: Option<char> = None;
    for line in text.lines() {
        let t = line.trim_start();
        let marker = if t.starts_with("```") {
            Some('`')
        } else if t.starts_with("~~~") {
            Some('~')
        } else {
            None
        };
        match (open, marker) {
            // A fence closes only with its own character.
            (Some(c), Some(m)) if c == m => open = None,
            (None, Some(m)) => open = Some(m),
            _ => {}
        }
    }
    open.is_some()
}

/// Render a code block as a boxed panel (same frame as `diff_lines`), the
/// language tag (when present) as a dim header row and the body
/// syntax-highlighted. Long lines wrap rather than truncate: dropping the tail
/// of a line of code loses the part that usually matters most.
fn render_code_block(body: &[&str], lang: &str, width: usize, plain: bool) -> Vec<Line<'static>> {
    let max = super::panel_inner(width, "");
    let mut rows: Vec<Line<'static>> = Vec::with_capacity(body.len() + 1);
    if !lang.is_empty() {
        rows.push(Line::styled(
            lang.to_string(),
            Style::new().dark_gray().italic(),
        ));
    }
    let rendered = if plain {
        body.iter()
            .map(|l| vec![Span::raw(l.to_string())])
            .collect()
    } else {
        super::highlight::block(body, lang)
    };
    for spans in rendered {
        for chunk in wrap_spans(spans, max) {
            rows.push(Line::from(chunk));
        }
    }
    super::boxed_panel(rows, width, "")
}

/// Break a styled row into chunks of at most `max` columns, splitting spans
/// where needed and carrying each span's style onto its continuation.
fn wrap_spans(spans: Vec<Span<'static>>, max: usize) -> Vec<Vec<Span<'static>>> {
    use unicode_width::UnicodeWidthStr;

    let max = max.max(1);
    let mut out: Vec<Vec<Span<'static>>> = Vec::new();
    let mut row: Vec<Span<'static>> = Vec::new();
    let mut used = 0;
    for span in spans {
        let style = span.style;
        let mut rest: &str = &span.content;
        while !rest.is_empty() {
            let room = max - used;
            let mut take = 0usize;
            let mut split = 0usize;
            for (i, ch) in rest.char_indices() {
                let next = ch.to_string().width();
                if take + next > room {
                    break;
                }
                take += next;
                split = i + ch.len_utf8();
            }
            if split == 0 {
                // A wide glyph cannot fit in the remaining cell. Move it to
                // the next visual row instead of allowing it to overrun the
                // panel frame.
                if used > 0 {
                    out.push(std::mem::take(&mut row));
                    used = 0;
                    continue;
                }
                let (head, tail) = rest.split_at(rest.chars().next().unwrap().len_utf8());
                row.push(Span::styled(head.to_string(), style));
                rest = tail;
                out.push(std::mem::take(&mut row));
                continue;
            }
            let (head, tail) = rest.split_at(split);
            row.push(Span::styled(head.to_string(), style));
            used += take;
            rest = tail;
            if used >= max && !rest.is_empty() {
                out.push(std::mem::take(&mut row));
                used = 0;
            }
        }
    }
    if !row.is_empty() || out.is_empty() {
        out.push(row);
    }
    out
}

/// Like `wrap_spans`, but breaking at a space where one is in reach so prose
/// does not split mid-word. A token longer than `max` is still split hard, since
/// there is nowhere else to break it. Used by the system rows, whose gutter has
/// to line up under itself on every continuation.
pub(super) fn wrap_spans_at_words(
    spans: Vec<Span<'static>>,
    max: usize,
) -> Vec<Vec<Span<'static>>> {
    let max = max.max(1);
    // Per-character styles: the wrap points are character positions, and each
    // span's style has to survive being cut at one.
    let cells: Vec<(char, Style)> = spans
        .iter()
        .flat_map(|s| {
            let style = s.style;
            s.content.chars().map(move |c| (c, style))
        })
        .collect();
    let mut out: Vec<Vec<Span<'static>>> = Vec::new();
    let mut start = 0;
    while start < cells.len() {
        let mut end = (start + max).min(cells.len());
        if end < cells.len() {
            if let Some(space) = cells[start..end].iter().rposition(|(c, _)| *c == ' ') {
                if space > 0 {
                    end = start + space;
                }
            }
        }
        out.push(merge_cells(&cells[start..end]));
        start = end;
        // Swallow the break's spaces so a continuation does not open with them.
        while matches!(cells.get(start), Some((' ', _))) {
            start += 1;
        }
    }
    if out.is_empty() {
        out.push(Vec::new());
    }
    out
}

/// Re-collapse per-character cells into one span per run of equal style.
fn merge_cells(cells: &[(char, Style)]) -> Vec<Span<'static>> {
    let mut runs: Vec<(String, Style)> = Vec::new();
    for (c, style) in cells {
        match runs.last_mut() {
            Some((text, run_style)) if run_style == style => text.push(*c),
            _ => runs.push((c.to_string(), *style)),
        }
    }
    runs.into_iter()
        .map(|(text, style)| Span::styled(text, style))
        .collect()
}

/// Heading ladder. Weight and hue carry the level -- no `#` markers and no
/// filled background, so headings sit in the same palette as the rest of the
/// transcript (cyan accent, `dark_gray` structure).
fn heading_style(level: u8) -> Style {
    match level {
        1 => Style::new().cyan().bold().underlined(),
        2 => Style::new().cyan().bold(),
        3 => Style::new().bold(),
        _ => Style::new().bold().dim(),
    }
}

/// Incremental markdown -> `Line` writer. Text accumulates into `spans` until a
/// block boundary flushes it; `prefixes` re-emit blockquote gutters and list
/// indents at the head of every new line.
struct Renderer {
    width: u16,
    out: Vec<Line<'static>>,
    spans: Vec<Span<'static>>,
    prefixes: Vec<(String, Style)>,
    blocks: Vec<Style>,
    inlines: Vec<Style>,
    /// One slot per open list; `Some(n)` counts an ordered list's next number.
    lists: Vec<Option<u64>>,
    /// A list marker was just emitted, so the item's first paragraph continues
    /// on that line instead of opening a new one.
    item_open: bool,
    link: Option<Link>,
    code: Option<CodeBlock>,
    table: Option<TableBuilder>,
    /// 1-based index of the code block to render without highlighting (the
    /// still-streaming one); `None` highlights every block.
    plain_code_block: Option<usize>,
    code_blocks_seen: usize,
}

/// An open link. `text` accumulates the anchor's own content so an autolink
/// (anchor text == URL) doesn't print the URL twice. Tracked as text rather
/// than a span index because line prefixes share the span vector.
struct Link {
    url: String,
    text: String,
}

struct CodeBlock {
    lang: String,
    body: String,
}

/// One table cell: each character with the style it was parsed under. Kept
/// per-character because comfy-table lays the grid out from plain strings and
/// may wrap a cell across rows, so styles are re-applied to its output
/// afterwards (see `render_table`).
type Cell = Vec<(char, Style)>;

/// Cells of a table being parsed.
#[derive(Default)]
struct TableBuilder {
    header: Vec<Cell>,
    rows: Vec<Vec<Cell>>,
    row: Vec<Cell>,
    cell: Cell,
    in_head: bool,
}

fn cell_text(cell: &Cell) -> String {
    cell.iter().map(|(c, _)| *c).collect()
}

/// Trim surrounding whitespace, keeping each character paired with its style.
fn trim_cell(mut cell: Cell) -> Cell {
    while cell.first().is_some_and(|(c, _)| c.is_whitespace()) {
        cell.remove(0);
    }
    while cell.last().is_some_and(|(c, _)| c.is_whitespace()) {
        cell.pop();
    }
    cell
}

impl Renderer {
    fn new(width: u16) -> Self {
        Self {
            width,
            out: Vec::new(),
            spans: Vec::new(),
            prefixes: Vec::new(),
            blocks: Vec::new(),
            inlines: Vec::new(),
            lists: Vec::new(),
            item_open: false,
            link: None,
            code: None,
            table: None,
            plain_code_block: None,
            code_blocks_seen: 0,
        }
    }

    fn finish(mut self) -> Vec<Line<'static>> {
        self.end_line();
        self.out
    }

    /// Block styles apply under inline ones, so emphasis inside a heading keeps
    /// the heading's colour.
    fn style(&self) -> Style {
        let mut s = Style::default();
        for b in self.blocks.iter().chain(self.inlines.iter()) {
            s = s.patch(*b);
        }
        s
    }

    fn push(&mut self, text: impl Into<String>, style: Style) {
        if self.spans.is_empty() {
            for (t, s) in &self.prefixes {
                if !t.is_empty() {
                    self.spans.push(Span::styled(t.clone(), *s));
                }
            }
        }
        let text = text.into();
        if let Some(l) = &mut self.link {
            l.text.push_str(&text);
        }
        self.spans.push(Span::styled(text, style));
    }

    fn push_styled(&mut self, text: impl Into<String>) {
        let style = self.style();
        self.push(text, style);
    }

    fn end_line(&mut self) {
        if !self.spans.is_empty() {
            self.out.push(Line::from(std::mem::take(&mut self.spans)));
        }
    }

    /// Close the current line and separate the next block with one blank line
    /// (suppressed at the very top and never doubled).
    fn gap(&mut self) {
        self.end_line();
        let blank = self
            .out
            .last()
            .map(|l| l.spans.iter().all(|s| s.content.trim().is_empty()))
            .unwrap_or(true);
        if !blank {
            self.out.push(Line::default());
        }
    }

    /// Text inside a code block or table cell is collected, not emitted as
    /// spans. Returns true when the text was consumed that way.
    fn sink_text(&mut self, text: &str) -> bool {
        let style = self.style();
        self.sink_styled(text, style)
    }

    fn sink_styled(&mut self, text: &str, style: Style) -> bool {
        if let Some(c) = &mut self.code {
            c.body.push_str(text);
            return true;
        }
        let Some(t) = &mut self.table else {
            return false;
        };
        t.cell.extend(text.chars().map(|c| (c, style)));
        // Keep the anchor accumulator fed so autolink detection behaves the same
        // inside a cell as outside one.
        if let Some(l) = &mut self.link {
            l.text.push_str(text);
        }
        true
    }

    fn handle(&mut self, event: pulldown_cmark::Event<'_>) {
        use pulldown_cmark::Event;
        match event {
            Event::Start(tag) => self.start(tag),
            Event::End(tag) => self.end(tag),
            Event::Text(t) => {
                if !self.sink_text(&t) {
                    self.push_styled(t.into_string());
                }
            }
            Event::Code(c) => {
                let style = self.style().patch(Style::new().cyan());
                if self.sink_styled(&c, style) {
                    return;
                }
                self.push(c.into_string(), style);
            }
            // Not dropped: rendering the source keeps content the model emitted
            // visible rather than silently swallowing it.
            Event::Html(h) | Event::InlineHtml(h) => {
                let style = self.style().patch(Style::new().dim());
                self.push(h.into_string().trim_end().to_string(), style);
            }
            Event::InlineMath(m) | Event::DisplayMath(m) => self.push_styled(m.into_string()),
            Event::FootnoteReference(name) => {
                let style = self.style().patch(Style::new().dim());
                self.push(format!("[^{name}]"), style);
            }
            // A soft break is not a line break: joining lets the Paragraph
            // widget reflow the paragraph at the real terminal width.
            Event::SoftBreak => {
                if !self.sink_text(" ") {
                    self.push_styled(" ");
                }
            }
            Event::HardBreak => self.end_line(),
            // Routed through `push` so a rule inside a blockquote keeps its
            // gutter, with the prefix width discounted so it still fits.
            Event::Rule => {
                self.gap();
                let used: usize = self.prefixes.iter().map(|(t, _)| t.chars().count()).sum();
                let w = (self.width as usize).saturating_sub(used).max(4);
                self.push("\u{2500}".repeat(w), Style::new().dark_gray());
                self.end_line();
            }
            Event::TaskListMarker(checked) => {
                let mark = if checked { "[x] " } else { "[ ] " };
                let style = self.style().patch(if checked {
                    Style::new().green()
                } else {
                    Style::new().dark_gray()
                });
                self.push(mark, style);
            }
        }
    }

    fn start(&mut self, tag: pulldown_cmark::Tag<'_>) {
        use pulldown_cmark::{CodeBlockKind, Tag};
        match tag {
            Tag::Paragraph => {
                if self.item_open {
                    self.item_open = false;
                } else {
                    self.gap();
                }
            }
            Tag::Heading { level, .. } => {
                self.gap();
                self.blocks.push(heading_style(level as u8));
            }
            Tag::BlockQuote(_) => {
                self.gap();
                self.prefixes
                    .push(("\u{2502} ".to_string(), Style::new().dark_gray()));
                self.blocks.push(Style::new().italic());
            }
            Tag::CodeBlock(kind) => {
                self.gap();
                let lang = match kind {
                    // Only the first word of an info string names the language
                    // (```rust,ignore); the rest is tooling metadata.
                    CodeBlockKind::Fenced(l) => l
                        .split(|c: char| c == ',' || c.is_whitespace())
                        .next()
                        .unwrap_or("")
                        .to_string(),
                    CodeBlockKind::Indented => String::new(),
                };
                self.code_blocks_seen += 1;
                self.code = Some(CodeBlock {
                    lang,
                    body: String::new(),
                });
            }
            Tag::List(start) => {
                if self.lists.is_empty() {
                    self.gap();
                }
                self.lists.push(start);
            }
            Tag::Item => {
                self.end_line();
                // Top-level items sit flush left; each nested level adds two.
                let pad = if self.lists.len() > 1 { "  " } else { "" };
                self.prefixes.push((pad.to_string(), Style::default()));
                match self.lists.last_mut() {
                    Some(Some(n)) => {
                        let marker = format!("{n}. ");
                        *n += 1;
                        self.push(marker, Style::new().cyan());
                    }
                    _ => self.push("- ", Style::new().cyan()),
                }
                self.item_open = true;
            }
            Tag::Emphasis => self.inlines.push(Style::new().italic()),
            Tag::Strong => self
                .inlines
                .push(Style::new().bold().fg(super::theme::strong_accent())),
            Tag::Strikethrough => self.inlines.push(Style::new().crossed_out()),
            Tag::Link { dest_url, .. } | Tag::Image { dest_url, .. } => {
                self.link = Some(Link {
                    url: dest_url.into_string(),
                    text: String::new(),
                });
                self.inlines.push(Style::new().cyan().underlined());
            }
            Tag::MetadataBlock(_) => self.blocks.push(Style::new().dim()),
            Tag::Table(_) => {
                self.gap();
                self.table = Some(TableBuilder::default());
            }
            Tag::TableHead => {
                if let Some(t) = &mut self.table {
                    t.in_head = true;
                }
            }
            Tag::TableRow | Tag::TableCell => {
                if let Some(t) = &mut self.table {
                    t.cell.clear();
                }
            }
            Tag::FootnoteDefinition(_)
            | Tag::HtmlBlock
            | Tag::Subscript
            | Tag::Superscript
            | Tag::DefinitionList
            | Tag::DefinitionListTitle
            | Tag::DefinitionListDefinition => {}
        }
    }

    fn end(&mut self, tag: pulldown_cmark::TagEnd) {
        use pulldown_cmark::TagEnd;
        match tag {
            TagEnd::Paragraph => self.end_line(),
            TagEnd::Heading(_) => {
                self.end_line();
                self.blocks.pop();
            }
            TagEnd::BlockQuote(_) => {
                self.end_line();
                self.prefixes.pop();
                self.blocks.pop();
            }
            TagEnd::CodeBlock => {
                if let Some(c) = self.code.take() {
                    let body: Vec<&str> = c.body.lines().collect();
                    let plain = self.plain_code_block == Some(self.code_blocks_seen);
                    let panel = render_code_block(&body, &c.lang, self.width as usize, plain);
                    self.out.extend(panel);
                }
            }
            TagEnd::List(_) => {
                self.end_line();
                self.lists.pop();
            }
            TagEnd::Item => {
                self.end_line();
                self.prefixes.pop();
                self.item_open = false;
            }
            TagEnd::Emphasis | TagEnd::Strong | TagEnd::Strikethrough => {
                self.inlines.pop();
            }
            TagEnd::MetadataBlock(_) => {
                self.end_line();
                self.blocks.pop();
            }
            TagEnd::TableCell => {
                if let Some(t) = &mut self.table {
                    let cell = trim_cell(std::mem::take(&mut t.cell));
                    if t.in_head {
                        t.header.push(cell);
                    } else {
                        t.row.push(cell);
                    }
                }
            }
            TagEnd::TableHead => {
                if let Some(t) = &mut self.table {
                    t.in_head = false;
                }
            }
            TagEnd::TableRow => {
                if let Some(t) = &mut self.table {
                    let row = std::mem::take(&mut t.row);
                    t.rows.push(row);
                }
            }
            TagEnd::Table => {
                if let Some(t) = self.table.take() {
                    let table = render_table(&t.header, &t.rows, self.width);
                    self.out.extend(table);
                }
            }
            TagEnd::Link | TagEnd::Image => {
                self.inlines.pop();
                if let Some(l) = self.link.take() {
                    // Inside a table the URL is dropped rather than appended:
                    // cells are width-constrained, and a full URL would dominate
                    // the column. The anchor text is already in the cell.
                    if self.table.is_none() && l.text.trim() != l.url {
                        let dim = Style::new().dark_gray();
                        self.push(format!(" ({})", l.url), dim);
                    }
                }
            }
            _ => {}
        }
    }
}

/// Render a markdown table via comfy-table: `Dynamic` arrangement wraps long
/// cells within their column and keeps the whole table within `width`, fixing
/// the overflow/separator-wrap failure of naive padding. Border rows are dimmed.
fn render_table(header: &[Cell], rows: &[Vec<Cell>], width: u16) -> Vec<Line<'static>> {
    use comfy_table::{ContentArrangement, Table};

    let mut table = Table::new();
    table
        .load_preset(comfy_table::presets::UTF8_FULL)
        .set_content_arrangement(ContentArrangement::Dynamic)
        .set_width(width.max(20))
        .set_header(header.iter().map(cell_text));
    for r in rows {
        table.add_row(r.iter().map(cell_text));
    }
    let rendered = table.to_string();

    // Styles are re-applied to comfy-table's finished grid, which is laid out
    // from plain text. Alignment walks the *non-whitespace* characters of each
    // cell rather than counting columns, because the arrangement pads cells to
    // the column width and drops the space it wraps on -- neither of which the
    // source cell contains.
    let mut all: Vec<&[Cell]> = Vec::with_capacity(rows.len() + 1);
    all.push(header);
    all.extend(rows.iter().map(Vec::as_slice));

    let border = Style::new().dim();
    let mut out = Vec::new();
    // Index of the body row being emitted, and how far into each of its cells
    // the mapping has consumed.
    let mut group = 0usize;
    let mut cursors: Vec<usize> = Vec::new();
    let mut fresh = true;

    for line in rendered.lines() {
        let is_content = line.starts_with('\u{2502}');
        if !is_content {
            out.push(Line::styled(line.to_string(), border));
            if !fresh {
                group += 1;
            }
            fresh = true;
            cursors.clear();
            continue;
        }
        if fresh {
            fresh = false;
            cursors = vec![0; all.get(group).map(|r| r.len()).unwrap_or(0)];
        }
        out.push(Line::from(style_table_row(
            line,
            all.get(group).copied().unwrap_or(&[]),
            &mut cursors,
            border,
        )));
    }
    out
}

/// Re-apply cell styles to one rendered grid row. Vertical rules are emitted as
/// border spans; every other run takes its style from the matching cell,
/// advancing that column's cursor once per non-whitespace character.
fn style_table_row(
    line: &str,
    cells: &[Cell],
    cursors: &mut [usize],
    border: Style,
) -> Vec<Span<'static>> {
    let mut spans: Vec<Span<'static>> = Vec::new();
    let mut buf: Vec<(char, Style)> = Vec::new();
    let mut col: usize = 0;
    let mut started = false;

    let flush = |buf: &mut Vec<(char, Style)>, spans: &mut Vec<Span<'static>>| {
        for (style, run) in group_by_style(buf) {
            spans.push(Span::styled(run, style));
        }
        buf.clear();
    };

    for ch in line.chars() {
        if ch == '\u{2502}' || ch == '\u{2506}' {
            flush(&mut buf, &mut spans);
            spans.push(Span::styled(ch.to_string(), border));
            if started {
                col += 1;
            }
            started = true;
            continue;
        }
        let style = if ch.is_whitespace() {
            Style::default()
        } else {
            next_cell_style(cells, cursors, col)
        };
        buf.push((ch, style));
    }
    flush(&mut buf, &mut spans);
    spans
}

/// Style of the next unconsumed character in column `col`, advancing its cursor.
/// Falls back to the default style if the grid shows more characters than the
/// source cell held (a break character comfy-table introduced, say).
fn next_cell_style(cells: &[Cell], cursors: &mut [usize], col: usize) -> Style {
    let Some(cell) = cells.get(col) else {
        return Style::default();
    };
    let Some(cursor) = cursors.get_mut(col) else {
        return Style::default();
    };
    let style = cell
        .iter()
        .filter(|(c, _)| !c.is_whitespace())
        .nth(*cursor)
        .map(|(_, s)| *s)
        .unwrap_or_default();
    *cursor += 1;
    style
}

/// Coalesce adjacent characters sharing a style into one span each.
fn group_by_style(chars: &[(char, Style)]) -> Vec<(Style, String)> {
    let mut out: Vec<(Style, String)> = Vec::new();
    for (ch, style) in chars {
        match out.last_mut() {
            Some((s, run)) if *s == *style => run.push(*ch),
            _ => out.push((*style, ch.to_string())),
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::{
        answer_lines, format_markdown_lines, live_assistant_lines, render_table,
        segment_reasoning_steps, segment_reasoning_steps_with, split_reasoning_paragraphs,
        wrap_spans_at_words,
    };
    use ratatui::prelude::*;

    fn line_text(line: &ratatui::text::Line) -> String {
        line.spans.iter().map(|s| s.content.as_ref()).collect()
    }

    #[test]
    fn answer_leads_with_a_dim_bullet_and_indents_the_rest() {
        let md = concat!(
            "one two three four five six seven\n\n",
            "```rust\nfn main() {}\n```\n\n",
            "| a | b |\n|---|---|\n| 1 | 2 |",
        );
        let lines = answer_lines(md, 20);
        let first = &lines[0].spans[0];
        assert_eq!(first.content, "\u{2022} ");
        assert_eq!(first.style, Style::new().dim());
        for line in &lines[1..] {
            let text = line_text(line);
            assert!(
                text.is_empty() || text.starts_with("  "),
                "row escaped the indent: {text:?}"
            );
            assert!(line.width() <= 20, "row overflows: {text:?}");
        }
        let text: Vec<String> = lines.iter().map(line_text).collect();
        assert!(text.iter().any(|t| t.starts_with("  \u{250c}")), "code box: {text:?}");
        assert!(text.iter().any(|t| t.starts_with("  ") && t.contains('1')), "table: {text:?}");
    }

    /// The live tail lays the answer out exactly as the committed row does, so
    /// nothing reflows when the stream commits.
    #[test]
    fn live_answer_matches_the_committed_layout() {
        let md = "a long enough answer to wrap at this width\n\n- item";
        for fold in [false, true] {
            assert_eq!(live_assistant_lines(md, &[], 24, fold, true, true), answer_lines(md, 24));
        }
    }

    #[test]
    fn paragraphs_split_on_blank_lines_only() {
        // A single newline stays within a step (soft wrap / list item); a blank
        // line starts a new one.
        let steps = split_reasoning_paragraphs("first line\nsame step\n\nsecond step");
        assert_eq!(steps, vec!["first line\nsame step", "second step"]);
        // Trailing whitespace trimmed, blank-only input yields nothing.
        assert_eq!(split_reasoning_paragraphs("  \n\n  "), Vec::<String>::new());
        // A whitespace-only line (spaces) still separates.
        assert_eq!(
            split_reasoning_paragraphs("a\n   \nb"),
            vec!["a".to_string(), "b".to_string()]
        );
    }

    #[test]
    fn steps_are_the_paragraphs_when_short() {
        let steps = segment_reasoning_steps("Think A.\n\nThink B.");
        assert_eq!(steps, vec!["Think A.", "Think B."]);
    }

    #[test]
    fn a_long_unbroken_paragraph_subdivides() {
        // A short first sentence (period within the budget window) then a long
        // tail that overflows: the first step breaks just past the period, and
        // the overflowing tail is subdivided at a word boundary.
        let first = format!("{}.", "word ".repeat(20).trim_end()); // ~100 chars, ends "."
        let tail = "more ".repeat(60); // long, no punctuation
        let steps = segment_reasoning_steps_with(&format!("{first} {tail}"), 200);
        assert!(steps.len() >= 2, "did not subdivide: {steps:?}");
        assert!(
            steps[0].ends_with('.'),
            "first step did not break at the sentence end: {steps:?}"
        );
        // No step exceeds the budget, and none breaks mid-word.
        assert!(
            steps.iter().all(|s| s.chars().count() <= 200),
            "a step exceeded the budget: {steps:?}"
        );
        assert!(
            steps.iter().all(|s| !s.starts_with(' ') && !s.ends_with(' ')),
            "a step kept boundary whitespace: {steps:?}"
        );
    }

    #[test]
    fn segmentation_is_prefix_stable_while_streaming() {
        // The last element is the paragraph being written; settled ones do not
        // change as more text arrives, so a growing prefix keeps its steps.
        let a = segment_reasoning_steps("Done one.\n\nDone two.\n\nnow writing thi");
        let b = segment_reasoning_steps("Done one.\n\nDone two.\n\nnow writing this longer tail");
        assert_eq!(&a[..a.len() - 1], &b[..b.len() - 1], "settled steps drifted");
        assert_eq!(a[0], "Done one.");
        assert_eq!(a[1], "Done two.");
    }

    fn joined(lines: &[ratatui::text::Line]) -> String {
        lines
            .iter()
            .flat_map(|l| l.spans.iter())
            .map(|s| s.content.as_ref())
            .collect()
    }

    /// Style of the first span whose text contains `needle`.
    fn style_of(lines: &[ratatui::text::Line], needle: &str) -> ratatui::style::Style {
        lines
            .iter()
            .flat_map(|l| l.spans.iter())
            .find(|s| s.content.contains(needle))
            .unwrap_or_else(|| panic!("no span containing {needle:?} in {:?}", joined(lines)))
            .style
    }

    #[test]
    fn headings_drop_the_literal_hash_markers() {
        let lines = super::format_markdown_lines("# Title\n\n## Section\n\n### Sub", 40);
        let text = joined(&lines);
        assert!(!text.contains('#'), "hash markers leaked: {text:?}");
        assert!(text.contains("Title") && text.contains("Section") && text.contains("Sub"));
    }

    #[test]
    fn heading_levels_form_a_visible_ladder_without_a_filled_background() {
        let h1 = style_of(&super::format_markdown_lines("# Title", 40), "Title");
        let h2 = style_of(&super::format_markdown_lines("## Section", 40), "Section");
        let h4 = style_of(&super::format_markdown_lines("#### Deep", 40), "Deep");
        // A filled background bar clashes with the rest of the transcript.
        assert_eq!(h1.bg, None, "h1 should not paint a background");
        assert!(h1.add_modifier.contains(ratatui::style::Modifier::BOLD));
        assert_ne!(h1, h2, "h1 and h2 must be distinguishable");
        assert_ne!(h2, h4, "h2 and h4 must be distinguishable");
    }

    #[test]
    fn inline_code_uses_the_accent_colour_not_a_black_block() {
        let lines = super::format_markdown_lines("call `do_thing()` now", 40);
        let style = style_of(&lines, "do_thing()");
        assert_eq!(style.bg, None, "inline code should not paint a background");
        assert_eq!(style.fg, Some(ratatui::style::Color::Cyan));
        assert!(!joined(&lines).contains('`'), "backticks leaked");
    }

    #[test]
    fn ordered_list_markers_use_the_accent_colour() {
        let lines = super::format_markdown_lines("1. alpha\n2. beta", 40);
        // tui-markdown hardcoded light_blue here, bypassing any theme.
        assert_eq!(style_of(&lines, "1.").fg, Some(ratatui::style::Color::Cyan));
    }

    #[test]
    fn nested_lists_indent_by_depth() {
        let lines = super::format_markdown_lines("- outer\n  - inner", 40);
        let texts: Vec<String> = lines
            .iter()
            .map(line_text)
            .filter(|l| !l.trim().is_empty())
            .collect();
        assert_eq!(texts.len(), 2, "{texts:?}");
        let outer_indent = texts[0].len() - texts[0].trim_start().len();
        let inner_indent = texts[1].len() - texts[1].trim_start().len();
        assert!(
            inner_indent > outer_indent,
            "nested item not indented: {texts:?}"
        );
    }

    #[test]
    fn blockquote_uses_a_gutter_rather_than_a_literal_angle_bracket() {
        let lines = super::format_markdown_lines("> quoted wisdom", 40);
        let text = joined(&lines);
        assert!(!text.contains('>'), "raw angle bracket leaked: {text:?}");
        assert!(text.contains('\u{2502}'), "missing gutter glyph: {text:?}");
        assert!(text.contains("quoted wisdom"));
    }

    #[test]
    fn thematic_break_renders_as_a_rule_spanning_the_width() {
        let lines = super::format_markdown_lines("above\n\n---\n\nbelow", 20);
        let rule = lines
            .iter()
            .map(line_text)
            .find(|l| l.contains('\u{2500}'))
            .expect("no rule line rendered");
        assert!(!joined(&lines).contains("---"), "literal dashes leaked");
        assert!(rule.chars().count() > 3, "rule too short: {rule:?}");
        assert!(rule.chars().count() <= 20, "rule exceeds width: {rule:?}");
    }

    #[test]
    fn link_styles_the_anchor_text_and_dims_the_url() {
        let lines = super::format_markdown_lines("see [the docs](https://jan.ai)", 60);
        let text = joined(&lines);
        assert!(text.contains("the docs"), "anchor text lost: {text:?}");
        assert!(text.contains("https://jan.ai"), "url lost: {text:?}");
        let anchor = style_of(&lines, "the docs");
        assert!(
            anchor
                .add_modifier
                .contains(ratatui::style::Modifier::UNDERLINED),
            "anchor text not styled: {anchor:?}"
        );
    }

    #[test]
    fn autolink_does_not_repeat_the_url_twice() {
        let lines = super::format_markdown_lines("[https://jan.ai](https://jan.ai)", 60);
        let text = joined(&lines);
        assert_eq!(text.matches("https://jan.ai").count(), 1, "{text:?}");
    }

    /// Syntax-highlight colours only: the panel frame and the language label are
    /// both `DarkGray`, so they are excluded rather than counted as highlighting.
    fn code_colours(
        lines: &[ratatui::text::Line],
    ) -> std::collections::HashSet<ratatui::style::Color> {
        lines
            .iter()
            .flat_map(|l| l.spans.iter())
            .filter_map(|s| s.style.fg)
            .filter(|c| *c != ratatui::style::Color::DarkGray)
            .collect()
    }

    #[test]
    fn a_still_streaming_fence_is_not_highlighted() {
        // Highlighting an open block is thrown away on the next delta, so it is
        // deferred until the closing fence arrives.
        let open = format_markdown_lines("```rust\nfn main() { let x = 1; }", 60);
        assert!(
            code_colours(&open).is_empty(),
            "open fence was highlighted: {:?}",
            code_colours(&open)
        );
        assert!(joined(&open).contains("fn main()"), "body lost");
    }

    #[test]
    fn a_closed_fence_after_an_open_one_is_still_highlighted() {
        // Only the trailing open block is plain; earlier finished blocks keep
        // their colours.
        let md = "```rust\nfn done() { let x = 1; }\n```\n\n```rust\nfn open() { let y = 2; }";
        let lines = format_markdown_lines(md, 60);
        assert!(
            !code_colours(&lines).is_empty(),
            "the finished block lost its highlighting"
        );
    }

    #[test]
    fn open_fence_detection_tracks_the_marker_character() {
        assert!(super::has_open_fence("```rust\nx"));
        assert!(!super::has_open_fence("```rust\nx\n```"));
        assert!(super::has_open_fence("~~~py\nx"));
        assert!(!super::has_open_fence("~~~py\nx\n~~~"));
        // A tilde line does not close a backtick fence.
        assert!(super::has_open_fence("```rust\n~~~\nx"));
        assert!(!super::has_open_fence("no fences here"));
    }

    #[test]
    fn tilde_fences_are_boxed_like_backtick_fences() {
        let lines = format_markdown_lines("~~~python\nx = 1\n~~~", 40);
        let text = joined(&lines);
        assert!(!text.contains('~'), "tilde fence leaked: {text}");
        assert!(text.contains("x = 1"), "body lost: {text}");
        assert!(text.contains('\u{250c}'), "not boxed: {text}");
    }

    #[test]
    fn fence_info_string_with_attributes_still_resolves_the_language() {
        // ```rust,ignore is a valid info string; only the first word names the
        // language.
        let lines = format_markdown_lines("```rust,ignore\nfn main() { let x = 1; }\n```", 60);
        let colours = code_colours(&lines);
        assert!(colours.len() > 2, "not highlighted as rust: {colours:?}");
    }

    #[test]
    fn escaped_pipe_in_a_cell_does_not_split_the_column() {
        let md = "| expr | note |\n|---|---|\n| a \\| b | or |";
        let lines = format_markdown_lines(md, 40);
        let text = joined(&lines);
        assert!(text.contains("a | b"), "escaped pipe mishandled: {text}");
        // Three columns would appear if the escape were treated as a delimiter.
        let header_cols = lines
            .iter()
            .map(line_text)
            .find(|l| l.contains("expr"))
            .map(|l| l.matches('\u{2502}').count())
            .unwrap_or(0);
        assert_eq!(header_cols, 2, "column count changed: {text}");
    }

    #[test]
    fn literal_asterisks_in_a_cell_survive() {
        // The old string-stripping pass deleted every `**` it found, turning
        // "2 ** 3" into "2  3".
        let md = "| expr | value |\n|---|---|\n| 2 ** 3 | eight |";
        let text = joined(&format_markdown_lines(md, 40));
        assert!(text.contains("2 ** 3"), "literal asterisks lost: {text}");
    }

    /// Style of the first span whose text contains `needle`, searched across a
    /// rendered table (whose cells are split into per-style spans).
    fn cell_style(lines: &[ratatui::text::Line], needle: &str) -> ratatui::style::Style {
        lines
            .iter()
            .flat_map(|l| l.spans.iter())
            .find(|s| s.content.contains(needle))
            .unwrap_or_else(|| panic!("no span containing {needle:?} in {:?}", joined(lines)))
            .style
    }

    #[test]
    fn bold_in_a_cell_is_rendered_bold() {
        let md = "| name |\n|---|\n| **apple** |";
        let lines = format_markdown_lines(md, 40);
        assert!(
            cell_style(&lines, "apple")
                .add_modifier
                .contains(ratatui::style::Modifier::BOLD),
            "cell text not bold: {:?}",
            joined(&lines)
        );
    }

    #[test]
    fn inline_code_in_a_cell_keeps_the_accent_colour() {
        let md = "| expr |\n|---|\n| `total` |";
        let lines = format_markdown_lines(md, 40);
        assert_eq!(
            cell_style(&lines, "total").fg,
            Some(ratatui::style::Color::Cyan)
        );
    }

    #[test]
    fn link_text_in_a_cell_is_underlined() {
        let md = "| ref |\n|---|\n| [docs](https://jan.ai) |";
        let lines = format_markdown_lines(md, 40);
        assert!(cell_style(&lines, "docs")
            .add_modifier
            .contains(ratatui::style::Modifier::UNDERLINED));
    }

    #[test]
    fn plain_cell_text_stays_unstyled() {
        let md = "| name |\n|---|\n| apple |";
        let lines = format_markdown_lines(md, 40);
        let s = cell_style(&lines, "apple");
        assert_eq!(s.fg, None, "plain cell picked up a colour");
        assert!(s.add_modifier.is_empty(), "plain cell picked up a modifier");
    }

    #[test]
    fn cell_styles_survive_wrapping() {
        // comfy-table drops the space it breaks on, so style alignment cannot
        // rely on character counts alone.
        let md = "| note |\n|---|\n| some filler words then **emphatic** trailing words here |";
        let lines = format_markdown_lines(md, 24);
        assert!(
            cell_style(&lines, "emphatic")
                .add_modifier
                .contains(ratatui::style::Modifier::BOLD),
            "bold lost across a wrap: {:?}",
            lines.iter().map(line_text).collect::<Vec<_>>()
        );
    }

    #[test]
    fn table_borders_are_never_styled_as_content() {
        let md = "| a |\n|---|\n| **b** |";
        let lines = format_markdown_lines(md, 30);
        for l in &lines {
            for s in &l.spans {
                if s.content.contains('\u{2502}') || s.content.contains('\u{2506}') {
                    // Borders are dim by design; they must not inherit a cell's
                    // emphasis or colour.
                    assert!(
                        !s.style.add_modifier.intersects(
                            ratatui::style::Modifier::BOLD | ratatui::style::Modifier::UNDERLINED
                        ),
                        "border span inherited cell emphasis: {:?}",
                        s.content
                    );
                    assert_eq!(
                        s.style.fg, None,
                        "border span got a colour: {:?}",
                        s.content
                    );
                }
            }
        }
    }

    #[test]
    fn inline_markup_in_a_cell_is_parsed_not_stripped() {
        let md = "| name | note |\n|---|---|\n| **bold** | `code` |";
        let text = joined(&format_markdown_lines(md, 40));
        assert!(text.contains("bold") && !text.contains('*'), "{text}");
        assert!(text.contains("code") && !text.contains('`'), "{text}");
    }

    #[test]
    fn a_link_in_a_cell_keeps_its_anchor_text() {
        let md = "| ref |\n|---|\n| [the docs](https://jan.ai) |";
        let text = joined(&format_markdown_lines(md, 60));
        assert!(text.contains("the docs"), "anchor text lost: {text}");
        assert!(
            !text.contains("](") && !text.contains('['),
            "raw link syntax leaked into the cell: {text}"
        );
    }

    #[test]
    fn a_cell_link_url_does_not_escape_the_table() {
        // The URL suffix is written to the span buffer, which a table cell does
        // not use -- it would otherwise surface as a stray line after the grid.
        let md = "| ref |\n|---|\n| [the docs](https://jan.ai) |";
        let lines = format_markdown_lines(md, 60);
        let after_grid: Vec<String> = lines
            .iter()
            .map(line_text)
            .skip_while(|l| !l.starts_with('\u{2514}'))
            .skip(1)
            .filter(|l| !l.trim().is_empty())
            .collect();
        assert!(
            after_grid.is_empty(),
            "content leaked past the table: {after_grid:?}"
        );
    }

    #[test]
    fn fenced_code_is_syntax_highlighted() {
        let lines = format_markdown_lines("```rust\nfn main() { let x = 1; }\n```", 60);
        let colours = code_colours(&lines);
        assert!(
            colours.len() > 2,
            "code not highlighted, colours: {colours:?}"
        );
    }

    #[test]
    fn long_code_lines_wrap_instead_of_being_truncated() {
        let long = format!("let x = \"{}\";", "y".repeat(120));
        let md = format!("```rust\n{long}\n```");
        let lines = format_markdown_lines(&md, 40);
        let text = joined(&lines);
        assert!(!text.contains('\u{2026}'), "code was truncated: {text}");
        // Wrapping splits the run across rows, so count characters rather than
        // looking for a contiguous match.
        assert_eq!(
            text.matches('y').count(),
            120,
            "content lost while wrapping: {text}"
        );
        // Every rendered row, frame included, stays inside the width budget.
        for l in &lines {
            let w: usize = l.spans.iter().map(|s| s.content.chars().count()).sum();
            assert!(w <= 40, "row overflows width ({w}): {:?}", line_text(l));
        }
    }

    #[test]
    fn code_panel_rows_all_share_one_inner_width() {
        let md = "```rust\nfn a() {}\nfn bbbbbbbbbbbb() {}\n```";
        let widths: std::collections::HashSet<usize> = format_markdown_lines(md, 60)
            .iter()
            .map(|l| l.spans.iter().map(|s| s.content.chars().count()).sum())
            .collect();
        assert_eq!(widths.len(), 1, "panel borders misaligned: {widths:?}");
    }

    #[test]
    fn boxed_blocks_are_separated_from_neighbours_by_one_blank_line() {
        // Code panels and tables come from the line pre-pass, so they need the
        // same block separation the walker gives headings and paragraphs.
        let md = "intro\n\n```rs\nx = 1\n```\n\n| a | b |\n|---|---|\n| 1 | 2 |\n\noutro";
        let texts: Vec<String> = format_markdown_lines(md, 40)
            .iter()
            .map(line_text)
            .collect();
        let blank = |s: &String| s.trim().is_empty();
        for (i, t) in texts.iter().enumerate() {
            if t.starts_with('\u{250c}') && i > 0 {
                assert!(blank(&texts[i - 1]), "no gap above block at {i}: {texts:?}");
            }
            if t.starts_with('\u{2514}') && i + 1 < texts.len() {
                assert!(blank(&texts[i + 1]), "no gap below block at {i}: {texts:?}");
            }
        }
        assert!(texts.iter().any(|t| t.contains("intro")));
        assert!(texts.iter().any(|t| t.contains("outro")));
    }

    #[test]
    fn autolink_inside_a_blockquote_is_not_duplicated() {
        // The gutter prefix must not be mistaken for part of the anchor text.
        let lines = super::format_markdown_lines("> [https://jan.ai](https://jan.ai)", 60);
        let text = joined(&lines);
        assert_eq!(text.matches("https://jan.ai").count(), 1, "{text:?}");
    }

    #[test]
    fn rule_inside_a_blockquote_keeps_the_gutter() {
        let lines = super::format_markdown_lines("> before\n>\n> ---\n>\n> after", 30);
        let rule = lines
            .iter()
            .map(line_text)
            .find(|l| l.contains('\u{2500}'))
            .expect("no rule rendered");
        assert!(rule.contains('\u{2502}'), "gutter lost on rule: {rule:?}");
        assert!(rule.chars().count() <= 30, "rule overflows width: {rule:?}");
    }

    #[test]
    fn task_list_markers_render_checked_state() {
        let text = joined(&super::format_markdown_lines("- [x] done\n- [ ] todo", 40));
        assert!(text.contains("[x]") && text.contains("[ ]"), "{text:?}");
        assert!(text.contains("done") && text.contains("todo"));
    }

    #[test]
    fn soft_breaks_reflow_into_one_line() {
        // Author line breaks inside a paragraph are not hard breaks; joining them
        // lets the Paragraph widget wrap to the real terminal width.
        let lines = super::format_markdown_lines("first half\nsecond half", 80);
        let non_blank: Vec<String> = lines
            .iter()
            .map(line_text)
            .filter(|l| !l.trim().is_empty())
            .collect();
        assert_eq!(non_blank, ["first half second half"], "{non_blank:?}");
    }

    #[test]
    fn strikethrough_is_rendered_as_a_modifier() {
        let lines = super::format_markdown_lines("~~gone~~", 40);
        assert!(joined(&lines).contains("gone"));
        assert!(style_of(&lines, "gone")
            .add_modifier
            .contains(ratatui::style::Modifier::CROSSED_OUT));
    }

    #[test]
    fn indented_code_block_is_boxed_like_a_fence() {
        let lines = super::format_markdown_lines("text\n\n    let x = 1;\n", 40);
        let text = joined(&lines);
        assert!(text.contains("let x = 1;"), "code lost: {text:?}");
        assert!(text.contains('\u{250c}'), "not boxed: {text:?}");
    }

    #[test]
    fn a_pipe_in_prose_is_not_mistaken_for_a_table() {
        // The old detector fired on any line containing a pipe followed by a
        // dashes-and-colons line; the parser requires a real delimiter row.
        let text = joined(&format_markdown_lines(
            "use a | b in a shell\n--- maybe",
            40,
        ));
        assert!(text.contains("use a | b in a shell"), "{text:?}");
    }

    #[test]
    fn loose_list_marker_merges_into_body_line() {
        // Loose list items must keep the marker on the body line.
        let md = "1. first item\n\n2. second item";
        let lines: Vec<String> = super::format_markdown_lines(md, 40)
            .iter()
            .map(line_text)
            .filter(|l| !l.trim().is_empty())
            .collect();
        assert_eq!(lines, ["1. first item", "2. second item"], "{lines:?}");

        let bullets: Vec<String> = super::format_markdown_lines("- alpha\n\n- beta", 40)
            .iter()
            .map(line_text)
            .filter(|l| !l.trim().is_empty())
            .collect();
        assert_eq!(bullets, ["- alpha", "- beta"], "{bullets:?}");
    }

    #[test]
    fn markdown_renders_bold_and_keeps_text() {
        let lines = super::format_markdown_lines("hello **world**", 40);
        let text: String = lines
            .iter()
            .flat_map(|l| l.spans.iter())
            .map(|s| s.content.as_ref())
            .collect();
        assert!(text.contains("hello"), "got {text:?}");
        assert!(text.contains("world"), "got {text:?}");
        assert!(!text.contains("**"), "markers not stripped: {text:?}");
    }

    #[test]
    fn format_markdown_routes_table_through_comfy_table() {
        let md = "| a | b |\n|---|---|\n| 1 | 2 |";
        let lines = format_markdown_lines(md, 40);
        let text = joined(&lines);
        // No raw markdown pipes; cell content preserved; wrapped within width.
        assert!(text.contains('a') && text.contains('b') && text.contains('1'));
        assert!(lines
            .iter()
            .all(|l| joined(std::slice::from_ref(l)).chars().count() <= 40));
    }

    #[test]
    fn format_markdown_renders_code_fence_without_literal_backticks() {
        let md = "before\n\n```cpp\nconst bool x = true;\nif (x) { foo(); }\n```\n\nafter";
        let text = joined(&format_markdown_lines(md, 80));
        assert!(!text.contains("```"), "fence markers leaked: {text}");
        assert!(text.contains("const bool x = true;"));
        assert!(text.contains("if (x) { foo(); }"));
        assert!(text.contains("cpp"), "language tag missing: {text}");
        assert!(text.contains("before") && text.contains("after"));
        assert!(
            text.contains('┌') && text.contains('┘'),
            "missing box frame: {text}"
        );
    }

    #[test]
    fn format_markdown_handles_unterminated_code_fence() {
        let md = "```rust\nfn main() {}";
        let text = joined(&format_markdown_lines(md, 80));
        assert!(!text.contains("```"), "fence leaked: {text}");
        assert!(text.contains("fn main() {}"));
    }

    #[test]
    fn render_table_wraps_long_cells_within_the_width() {
        /// Unstyled cell, as the walker would build it from plain text.
        fn cell(s: &str) -> super::Cell {
            s.chars()
                .map(|c| (c, ratatui::style::Style::default()))
                .collect()
        }
        let header = vec![cell("name"), cell("note")];
        let rows = vec![vec![
            cell("apple"),
            cell("a very long note that must wrap across several lines"),
        ]];
        let lines = render_table(&header, &rows, 30);
        let text = joined(&lines);
        assert!(text.contains("apple"), "cell content lost: {text:?}");
        // Dynamic wrapping keeps every rendered row within the target width.
        assert!(lines
            .iter()
            .all(|l| joined(std::slice::from_ref(l)).chars().count() <= 30));
    }
    #[test]
    fn wrap_at_words_breaks_on_spaces_and_keeps_styles() {
        let spans = vec![
            Span::styled("3f7a91c2  ", Style::new().cyan()),
            Span::raw("fix the failing test in the parser"),
        ];
        let rows = wrap_spans_at_words(spans, 20);
        let text: Vec<String> = rows
            .iter()
            .map(|r| r.iter().map(|s| s.content.to_string()).collect())
            .collect();
        assert!(rows.len() > 1, "{text:?}");
        for row in &text {
            assert!(row.chars().count() <= 20, "{text:?}");
        }
        // No word is cut, and nothing is lost.
        let joined = text.join(" ");
        assert!(joined.contains("failing"), "{text:?}");
        assert!(joined.contains("parser"), "{text:?}");
        // The lead span's style survives the split.
        assert_eq!(rows[0][0].style.fg, Some(Color::Cyan));
    }

    #[test]
    fn wrap_at_words_splits_a_token_longer_than_the_width() {
        let long = "supercalifragilistic";
        let rows = wrap_spans_at_words(vec![Span::raw(long)], 8);
        assert_eq!(rows.len(), 3, "a token with no space must still fit");
        let joined: String = rows
            .iter()
            .flat_map(|r| r.iter().map(|s| s.content.to_string()))
            .collect();
        assert_eq!(joined, long);
    }
}