Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent-tui): own the markdown renderer, highlight code blocks
Akarshan Biswasb55ed69737ea
diff --git a/.github/workflows/template-cli-build-linux-x64.yml b/.github/workflows/template-cli-build-linux-x64.ymlindex 87853c9b7..4187de1d1 100644--- a/.github/workflows/template-cli-build-linux-x64.yml+++ b/.github/workflows/template-cli-build-linux-x64.yml@@ -53,10 +53,12 @@ jobs:# The CLI must stay free of Tauri/GTK: this runner has no libwebkit2gtk,# so a regression here would surface as a confusing linker error later.+ # `onig`/`onig_sys` are syntect's default regex backend and link C code;+ # the highlighter is pinned to the pure-Rust `regex-fancy` engine instead.- name: Assert no GUI crates in the CLI dependency graphrun: |cd src-tauri- for crate in tauri gtk gdk muda wry webkit2gtk; do+ for crate in tauri gtk gdk muda wry webkit2gtk onig onig_sys; doif cargo tree --no-default-features --features cli -e normal -i "$crate" >/dev/null 2>&1; thenecho "::error::$crate is back in the jan CLI dependency graph"exit 1diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 46d4be5d1..ad9c3f6e9 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -42,6 +42,7 @@ dependencies = ["nix 0.30.1","once_cell","png 0.17.16",+ "pulldown-cmark","rand 0.8.7","ratatui","regex",@@ -53,6 +54,7 @@ dependencies = ["serde_yaml","sha2","sqlx",+ "syntect","tar","tauri","tauri-build",@@ -79,7 +81,6 @@ dependencies = ["tokio-util","toml 0.8.2","toml_edit 0.23.10+spec-1.0.0",- "tui-markdown","url","uuid","windows-sys 0.60.2",@@ -518,6 +519,15 @@ version = "1.8.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"+[[package]]+name = "bincode"+version = "1.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad"+dependencies = [+ "serde",+]+[[package]]name = "bit-set"version = "0.5.3"@@ -1645,12 +1655,6 @@ dependencies = ["zeroize",]-[[package]]-name = "diff"-version = "0.1.13"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8"-[[package]]name = "digest"version = "0.10.7"@@ -2087,6 +2091,17 @@ dependencies = ["regex",]+[[package]]+name = "fancy-regex"+version = "0.16.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "998b056554fbe42e03ae0e152895cd1a7e1002aec800fdc6635d20270260c46f"+dependencies = [+ "bit-set 0.8.0",+ "regex-automata",+ "regex-syntax",+]+[[package]]name = "fast-srgb8"version = "1.0.0"@@ -2398,12 +2413,6 @@ version = "0.3.32"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"-[[package]]-name = "futures-timer"-version = "3.0.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "af43fadb8a98512d547e37b4e92e0ced13e205c061b87b4623eff01d918d6968"-[[package]]name = "futures-util"version = "0.3.32"@@ -2540,15 +2549,6 @@ dependencies = ["windows-link 0.2.1",]-[[package]]-name = "getopts"-version = "0.2.24"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cfe4fbac503b8d1f88e6676011885f34b7174f46e59956bba534ba83abded4df"-dependencies = [- "unicode-width 0.2.2",-]-[[package]]name = "getrandom"version = "0.2.17"@@ -3397,15 +3397,6 @@ dependencies = ["either",]-[[package]]-name = "itertools"-version = "0.15.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc"-dependencies = [- "either",-]-[[package]]name = "itoa"version = "1.0.18"@@ -5159,16 +5150,6 @@ version = "0.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"-[[package]]-name = "pretty_assertions"-version = "1.4.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3ae130e2f271fbc2ac3a40fb1d07180839cdbbe443c7a27e1e3c13c5cac0116d"-dependencies = [- "diff",- "yansi",-]-[[package]]name = "proc-macro-crate"version = "1.3.1"@@ -5268,18 +5249,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e9f068eba8e7071c5f9511831b44f32c740d5adf574e990f946ddb53db2f314e"dependencies = ["bitflags 2.13.0",- "getopts","memchr",- "pulldown-cmark-escape","unicase",]-[[package]]-name = "pulldown-cmark-escape"-version = "0.11.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae"-[[package]]name = "pxfm"version = "0.1.30"@@ -5515,7 +5488,7 @@ dependencies = ["compact_str","critical-section","hashbrown 0.17.1",- "itertools 0.14.0",+ "itertools","kasuari","lru","palette",@@ -5580,7 +5553,7 @@ dependencies = ["hashbrown 0.17.1","indoc","instability",- "itertools 0.14.0",+ "itertools","line-clipping","ratatui-core","serde",@@ -5680,12 +5653,6 @@ version = "0.8.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"-[[package]]-name = "relative-path"-version = "1.9.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ba39f3699c378cd8970968dcbff9c43159ea4cfbd88d43c00b22f2ef10a435d2"-[[package]]name = "reqwest"version = "0.12.28"@@ -5894,35 +5861,6 @@ dependencies = ["zeroize",]-[[package]]-name = "rstest"-version = "0.26.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f5a3193c063baaa2a95a33f03035c8a72b83d97a54916055ba22d35ed3839d49"-dependencies = [- "futures-timer",- "futures-util",- "rstest_macros",-]--[[package]]-name = "rstest_macros"-version = "0.26.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9c845311f0ff7951c5506121a9ad75aec44d083c31583b2ea5a30bcb0b0abba0"-dependencies = [- "cfg-if",- "glob",- "proc-macro-crate 3.5.0",- "proc-macro2",- "quote",- "regex",- "relative-path",- "rustc_version",- "syn 2.0.118",- "unicode-ident",-]-[[package]]name = "rusqlite"version = "0.32.1"@@ -7034,6 +6972,24 @@ dependencies = ["syn 2.0.118",]+[[package]]+name = "syntect"+version = "5.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "656b45c05d95a5704399aeef6bd0ddec7b2b3531b7c9e900abbf7c4d2190c925"+dependencies = [+ "bincode",+ "fancy-regex 0.16.2",+ "flate2",+ "fnv",+ "once_cell",+ "regex-syntax",+ "serde",+ "serde_derive",+ "thiserror 2.0.18",+ "walkdir",+]+[[package]]name = "sys-locale"version = "0.3.2"@@ -7808,7 +7764,7 @@ dependencies = ["anyhow","base64 0.22.1","bitflags 2.13.0",- "fancy-regex",+ "fancy-regex 0.11.0","filedescriptor","finl_unicode","fixedbitset 0.4.2",@@ -8298,20 +8254,6 @@ version = "0.25.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31"-[[package]]-name = "tui-markdown"-version = "0.3.8"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c6779056a6ae2d46013edb3692be1eb55d2e1d3f0d1d454042163efe1b64baca"-dependencies = [- "itertools 0.15.0",- "pretty_assertions",- "pulldown-cmark",- "ratatui-core",- "rstest",- "tracing",-]-[[package]]name = "type1-encoding-parser"version = "0.1.1"@@ -8436,7 +8378,7 @@ version = "2.0.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "16b380a1238663e5f8a691f9039c73e1cdae598a30e9855f541d29b08b53e9a5"dependencies = [- "itertools 0.14.0",+ "itertools","unicode-segmentation","unicode-width 0.2.2",]@@ -9829,12 +9771,6 @@ dependencies = ["markup5ever 0.11.0",]-[[package]]-name = "yansi"-version = "1.0.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049"-[[package]]name = "yoke"version = "0.8.3"diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex e60cf130f..d9585a5c8 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -90,7 +90,7 @@ test-tauri = ["deep-link","hardware",]-cli = ["dep:env_logger", "dep:dialoguer", "dep:indicatif", "dep:console", "dep:ratatui", "dep:tui-markdown", "dep:comfy-table", "dep:arboard", "dep:png"]+cli = ["dep:env_logger", "dep:dialoguer", "dep:indicatif", "dep:console", "dep:ratatui", "dep:pulldown-cmark", "dep:syntect", "dep:comfy-table", "dep:arboard", "dep:png"][build-dependencies]tauri-build = { version = "2.0.2", features = [], optional = true }@@ -190,7 +190,16 @@ keyring = { version = "3", features = [aes-gcm = "0.10"machine-uid = "0.5"ratatui = { version = "0.30", optional = true, features = ["unstable-rendered-line-info"] }-tui-markdown = { version = "0.3.8", optional = true, default-features = false }+pulldown-cmark = { version = "0.13", optional = true, default-features = false }+# `regex-fancy` keeps this pure Rust: the default `onig` backend links libonig,+# which the headless CLI must not pull in. The raw `.sublime-syntax`/`.tmTheme`+# loaders (plist, yaml-rust, html) are off -- only the bundled dumps are used.+syntect = { version = "5.3", optional = true, default-features = false, features = [+ "parsing",+ "default-syntaxes",+ "default-themes",+ "regex-fancy",+] }comfy-table = { version = "7.2", default-features = false, optional = true }arboard = { version = "3", optional = true, features = ["wayland-data-control"] }png = { version = "0.17", optional = true }diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex 4da5f4839..d4dc51e84 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -6,6 +6,7 @@//! inline workflow elements (turn steps, tool calls/results). Gated tool calls//! are approved interactively via the shared `PermissionRegistry`.+use std::collections::HashMap;use std::future::pending;use std::io;use std::path::PathBuf;@@ -31,6 +32,13 @@ use ratatui::widgets::{Block, Borders, Paragraph, Wrap};use tokio::sync::mpsc;use tokio::task::JoinHandle;+mod highlight;+mod markdown;++use markdown::{+ format_assistant_lines, format_markdown_lines, reasoning_detail_lines, reasoning_summary_row,+};+use super::{sort_threads_recent, AgentSession, ResumeTarget};use crate::core::agent::events::{describe_tool_call, StreamEvent, Usage};use crate::core::agent::git;@@ -114,7 +122,12 @@ impl Pending {/// prompt box, unlike the tool-row-aligned result diff.fn diff_preview(&self, inner: u16) -> Vec<Line<'static>> {match &self.diff {- Some(d) => diff_lines(d, (inner as usize).saturating_sub(4).max(1), ""),+ Some(d) => diff_lines(+ d,+ (inner as usize).saturating_sub(4).max(1),+ "",+ self.path.as_deref(),+ ),None => Vec::new(),}}@@ -480,6 +493,10 @@ struct App {/// drained into the next checkpoint's snapshot and reset per turn. Only/// these exact paths are staged -- checkpoints never scan the repo.turn_touched: Vec<PathBuf>,+ /// Destination path of each in-flight `edit`/`write` call, keyed by call id,+ /// so the diff in its `ToolResult` (which carries no path) can be+ /// syntax-highlighted for the right language. Removed as results arrive.+ diff_paths: HashMap<String, String>,/// Base snapshot (working-tree state before the first turn) for the active/// thread. `Some` once snapshotting is armed; `None` = no workspace restore.base_snapshot: Option<String>,@@ -741,6 +758,7 @@ impl App {git_branch: git::current_branch(&project_root),project_root,turn_touched: Vec::new(),+ diff_paths: HashMap::new(),base_snapshot: None,checkpoints: Vec::new(),snap_queue: std::collections::VecDeque::new(),@@ -1630,6 +1648,7 @@ impl App {// exactly this file instead of scanning the whole repo.if let Some(p) = args.get("path").and_then(|v| v.as_str()) {self.turn_touched.push(self.project_root.join(p));+ self.diff_paths.insert(id.clone(), p.to_string());}// Diff-producing tools render standalone (call row & panel).self.finalize_tool_group();@@ -1687,7 +1706,8 @@ impl App {Span::styled(summarize_result(&content, max), Style::new().dim()),]));if let Some(diff) = diff {- for line in diff_lines(&diff, max, "│ ") {+ let lang = self.diff_paths.remove(&id);+ for line in diff_lines(&diff, max, "│ ", lang.as_deref()) {self.push(line);}}@@ -1893,6 +1913,9 @@ impl App {self.scrollback = 0;self.todo_call_this_turn = false;self.todo_ok_this_turn = false;+ // A call cancelled before its result would otherwise leave its path+ // behind for the life of the session.+ self.diff_paths.clear();}/// Flush the current turn and return its text as the final assistant answer.@@ -2174,23 +2197,52 @@ const COMMAND_LABEL_MAX: usize = 80;/// `max` and each row padded so the right border aligns. Collapses to/// `DIFF_MAX_ROWS` with a `(+N more)` tail before the closing rule. `gutter`/// indents the panel (tool-row alignment under a result; empty in the prompt).-fn diff_lines(diff: &str, max: usize, gutter: &'static str) -> Vec<Line<'static>> {+fn diff_lines(+ diff: &str,+ max: usize,+ gutter: &'static str,+ lang: Option<&str>,+) -> Vec<Line<'static>> {let all: Vec<&str> = diff.lines().collect();let shown = all.len().min(DIFF_MAX_ROWS);let truncated = all.len() > shown;- let mut rows: Vec<(String, Style)> = Vec::with_capacity(shown + 1);- for line in &all[..shown] {- let style = match line.as_bytes().first() {+ // Truncate before highlighting so the width arithmetic is unchanged.+ let kept: Vec<String> = all[..shown].iter().map(|l| truncate(l, max)).collect();+ // Highlight the body with the `-`/`+` markers stripped, so a multi-line+ // string or comment keeps its colour across the hunk instead of restarting+ // on every row; the markers are re-attached with their own colour below.+ // Hunk headers are not code and stay out of it.+ let bodies: Vec<&str> = kept.iter().map(|l| split_diff_marker(l).1).collect();+ let highlighted: Option<Vec<Vec<Span<'static>>>> = match lang {+ Some(l) if !l.is_empty() => Some(highlight::block(&bodies, l)),+ _ => None,+ };++ let mut rows: Vec<Line<'static>> = Vec::with_capacity(shown + 1);+ for (i, line) in kept.iter().enumerate() {+ let (marker, body) = split_diff_marker(line);+ let marker_style = match marker.as_bytes().first() {Some(b'-') => Style::new().red(),Some(b'+') => Style::new().green(),- Some(b'@') => Style::new().cyan().dim(),_ => Style::new().dim(),};- rows.push((truncate(line, max), style));+ if marker.starts_with('@') {+ rows.push(Line::styled(line.clone(), Style::new().cyan().dim()));+ continue;+ }+ let mut spans = Vec::with_capacity(2);+ if !marker.is_empty() {+ spans.push(Span::styled(marker.to_string(), marker_style));+ }+ match &highlighted {+ Some(h) => spans.extend(h[i].iter().cloned()),+ None => spans.push(Span::styled(body.to_string(), Style::new().dim())),+ }+ rows.push(Line::from(spans));}if truncated {- rows.push((+ rows.push(Line::styled(format!("(+{} more)", all.len() - shown),Style::new().dim(),));@@ -2198,12 +2250,30 @@ fn diff_lines(diff: &str, max: usize, gutter: &'static str) -> Vec<Line<'static>boxed_panel(rows, max, gutter)}-/// Frame `(text, style)` rows in a light box, right-padded to the widest row-/// (clamped to `max`). `gutter` prefixes every line to indent the panel.-fn boxed_panel(rows: Vec<(String, Style)>, max: usize, gutter: &'static str) -> Vec<Line<'static>> {+/// Split a diff row into its leading marker and the code after it. A `@@` hunk+/// header is returned whole as the marker, since none of it is code.+fn split_diff_marker(line: &str) -> (&str, &str) {+ if line.starts_with("@@") {+ return (line, "");+ }+ match line.as_bytes().first() {+ Some(b'-') | Some(b'+') | Some(b' ') => line.split_at(1),+ _ => ("", line),+ }+}++/// Total display width of a row's spans.+fn row_width(row: &Line<'_>) -> usize {+ row.spans.iter().map(|s| s.content.chars().count()).sum()+}++/// Frame styled rows in a light box, right-padded to the widest row (clamped to+/// `max`). Rows carry their own spans so style can vary within a row (syntax+/// highlighting); `gutter` prefixes every line to indent the panel.+fn boxed_panel(rows: Vec<Line<'static>>, max: usize, gutter: &'static str) -> Vec<Line<'static>> {let inner = rows.iter()- .map(|(t, _)| t.chars().count())+ .map(row_width).max().unwrap_or(0).clamp(1, max.max(1));@@ -2213,14 +2283,15 @@ fn boxed_panel(rows: Vec<(String, Style)>, max: usize, gutter: &'static str) ->Span::styled(gutter, border),Span::styled(format!("┌{}┐", "─".repeat(inner + 2)), border),]));- for (text, style) in rows {- let pad = inner.saturating_sub(text.chars().count());- out.push(Line::from(vec![+ for row in rows {+ let pad = inner.saturating_sub(row_width(&row));+ let mut spans = vec![Span::styled(gutter, border),Span::styled("│ ", border),- Span::styled(text, style),- Span::styled(format!("{} │", " ".repeat(pad)), border),- ]));+ ];+ spans.extend(row.spans);+ spans.push(Span::styled(format!("{} │", " ".repeat(pad)), border));+ out.push(Line::from(spans));}out.push(Line::from(vec![Span::styled(gutter, border),@@ -2426,9 +2497,9 @@ struct StartingPreview {/// Destination path, available well before the body since `path` is short/// and models emit it first.path: Option<String>,- /// Trailing lines of the file body, newest last. `None` until a `write`- /// call's `content` field opens.- tail: Option<Vec<String>>,+ /// Trailing lines of the file body, newest last, syntax-highlighted from+ /// `path`'s extension. `None` until a `write` call's `content` field opens.+ tail: Option<Vec<Vec<Span<'static>>>>,/// Body lines scrolled off the top of `tail`.skipped: usize,}@@ -2480,15 +2551,15 @@ impl StartingCall {// so a large body never materializes a line list it would discard.// `split` (not `lines`) so a trailing newline shows as the empty line// the model just opened, which is where the next content will land.- let mut tail: Vec<String> = body- .rsplit('\n')- .take(STREAM_TAIL_LINES)- .map(str::to_string)- .collect();+ let mut tail: Vec<&str> = body.rsplit('\n').take(STREAM_TAIL_LINES).collect();tail.reverse();let total = body.bytes().filter(|&b| b == b'\n').count() + 1;self.preview.skipped = total - tail.len();- self.preview.tail = Some(tail);+ // Highlighted here rather than in the row builder so the cost tracks+ // arriving bytes, not the frame rate: this window is a fresh cache key+ // on every delta, and highlighting 12 lines costs ~4.6ms.+ let lang = self.preview.path.clone().unwrap_or_default();+ self.preview.tail = Some(highlight::block(&tail, &lang));}}@@ -2624,15 +2695,16 @@ fn starting_call_lines(call: &mut StartingCall, frame: &str) -> Vec<Line<'static),]));}- for (offset, text) in tail.iter().enumerate() {- out.push(Line::from(vec![+ for (offset, code) in tail.iter().enumerate() {+ let mut spans = vec![Span::styled("│ ", Style::new().dark_gray()),Span::styled(format!("{:>gutter$} ", start + offset + 1, gutter = gutter),Style::new().dark_gray(),),- Span::raw(text.clone()),- ]));+ ];+ spans.extend(code.iter().cloned());+ out.push(Line::from(spans));}out.push(Line::from(vec![Span::styled("│ ", Style::new().dark_gray()),@@ -2695,7 +2767,7 @@ fn group_detail_lines(group: &ToolGroup, width: u16) -> Vec<Line<'static>> {]));}if let Some(diff) = &call.diff {- for line in diff_lines(diff, max, cont_gutter) {+ for line in diff_lines(diff, max, cont_gutter, None) {out.push(line);}}@@ -2910,20 +2982,6 @@ fn split_reasoning(text: &str) -> Vec<(bool, String)> {out}-/// Render assistant text to styled lines: reasoning dimmed, answer prose passed-/// through markdown formatting. `width` bounds table wrapping.-fn format_assistant_lines(text: &str, width: u16) -> Vec<Line<'static>> {- let mut lines = Vec::new();- for (reasoning, seg) in split_reasoning(text) {- if reasoning {- lines.extend(reasoning_detail_lines(&seg));- } else {- lines.extend(format_markdown_lines(&seg, width));- }- }- lines-}-/// True if `text` has any non-whitespace content in any reasoning/answer run.fn assistant_has_content(text: &str) -> bool {split_reasoning(text)@@ -2931,206 +2989,6 @@ fn assistant_has_content(text: &str) -> bool {.any(|(_, seg)| !seg.trim().is_empty())}-/// A reasoning block's full dimmed lines (`┊ ` gutter, dim italic body).-fn reasoning_detail_lines(seg: &str) -> Vec<Line<'static>> {- seg.lines()- .filter(|l| !l.trim().is_empty())- .map(|l| {- Line::from(vec![- Span::styled("┊ ", Style::new().dark_gray()),- Span::styled(l.to_string(), Style::new().dim().italic()),- ])- })- .collect()-}--/// Collapsed summary row for a folded reasoning block.-fn reasoning_summary_row(n: usize) -> Line<'static> {- let label = if n == 1 {- "reasoning (1 line)".to_string()- } else {- format!("reasoning ({n} lines)")- };- Line::from(vec![- Span::styled("┊ ", Style::new().dark_gray()),- Span::styled(label, Style::new().dim().italic()),- ])-}--fn table_cells(line: &str) -> Vec<String> {- line.trim()- .trim_matches('|')- .split('|')- .map(|c| c.trim().to_string())- .collect()-}--/// A `|---|:--:|` markdown table separator row.-fn is_table_separator(line: &str) -> bool {- let body = line.trim().trim_matches('|');- !body.is_empty()- && body.split('|').all(|c| {- let c = c.trim();- !c.is_empty() && c.contains('-') && c.chars().all(|ch| matches!(ch, '-' | ':' | ' '))- })-}--/// Render answer prose. Fenced code blocks and GitHub pipe tables are rendered-/// ourselves (`render_code_block`/`render_table`) because tui-markdown leaks the-/// ` ``` ` fences as literal text and has no table support; every other block-/// goes through tui-markdown (headings, bold/italic, lists, quotes).-fn format_markdown_lines(text: &str, width: u16) -> Vec<Line<'static>> {- let src: Vec<&str> = text.lines().collect();- let mut out = Vec::new();- let mut prose: Vec<&str> = Vec::new();- let mut i = 0;- while i < src.len() {- if let Some(lang) = src[i].trim_start().strip_prefix("```") {- flush_prose(&mut prose, &mut out);- let lang = lang.trim().to_string();- i += 1;- let start = i;- while i < src.len() && !src[i].trim_start().starts_with("```") {- i += 1;- }- out.extend(render_code_block(&src[start..i], &lang, (width as usize).saturating_sub(4)));- i += usize::from(i < src.len()); // consume closing fence when present- continue;- }- let is_table_head =- src[i].contains('|') && i + 1 < src.len() && is_table_separator(src[i + 1]);- if is_table_head {- flush_prose(&mut prose, &mut out);- let header = table_cells(src[i]);- let mut rows = Vec::new();- i += 2;- while i < src.len() && src[i].contains('|') && !src[i].trim().is_empty() {- rows.push(table_cells(src[i]));- i += 1;- }- out.extend(render_table(&header, &rows, width));- } else {- prose.push(src[i]);- i += 1;- }- }- flush_prose(&mut prose, &mut out);- out-}--/// Render a fenced code block as a boxed panel (same frame as `diff_lines`),-/// the language tag (when present) as a dim header row. Content bypasses-/// tui-markdown so code is never reinterpreted as markdown.-fn render_code_block(body: &[&str], lang: &str, max: usize) -> Vec<Line<'static>> {- let mut rows: Vec<(String, Style)> = Vec::with_capacity(body.len() + 1);- if !lang.is_empty() {- rows.push((lang.to_string(), Style::new().dark_gray().italic()));- }- for l in body {- rows.push((truncate(l, max), Style::new()));- }- boxed_panel(rows, max, "")-}--fn flush_prose(prose: &mut Vec<&str>, out: &mut Vec<Line<'static>>) {- if prose.is_empty() {- return;- }- out.extend(markdown_to_lines(&prose.join("\n")));- prose.clear();-}--/// Render a markdown block to owned ratatui lines via `tui-markdown`.-fn markdown_to_lines(text: &str) -> Vec<Line<'static>> {- let lines: Vec<Line<'static>> = tui_markdown::from_str(text)- .lines- .into_iter()- .map(own_line)- .collect();- merge_list_markers(lines)-}--/// tui-markdown renders loose list items with the marker (`1. `, `- `) alone on-/// one line and the item body on the next. Fold a lone-marker line into the-/// following line so list items read as `1. body`.-fn merge_list_markers(lines: Vec<Line<'static>>) -> Vec<Line<'static>> {- let mut out: Vec<Line<'static>> = Vec::with_capacity(lines.len());- let mut iter = lines.into_iter().peekable();- while let Some(line) = iter.next() {- if is_lone_list_marker(&line) && iter.peek().is_some() {- let body = iter.next().unwrap();- let mut spans = line.spans;- spans.extend(body.spans);- let mut merged = Line::from(spans);- merged.alignment = body.alignment;- out.push(merged);- } else {- out.push(line);- }- }- out-}--/// True if the line is nothing but a list marker: `1.`/`12.` or a `-`/`*`/`•`-/// bullet (trailing spaces allowed).-fn is_lone_list_marker(line: &Line<'_>) -> bool {- let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();- let t = text.trim();- if matches!(t, "-" | "*" | "•") {- return true;- }- matches!(t.strip_suffix('.'), Some(d) if !d.is_empty() && d.bytes().all(|b| b.is_ascii_digit()))-}--/// Deep-clone a borrowed `Line` into a `'static` one (own each span's text).-fn own_line(line: Line<'_>) -> Line<'static> {- let spans: Vec<Span<'static>> = line- .spans- .into_iter()- .map(|s| Span::styled(s.content.into_owned(), s.style))- .collect();- let mut owned = Line::from(spans);- owned.style = line.style;- owned.alignment = line.alignment;- owned-}--/// Strip the inline markdown markers that would otherwise show as literal text-/// inside table cells (comfy-table renders plain text).-fn strip_inline_md(s: &str) -> String {- s.replace("**", "").replace("__", "").replace('`', "")-}--/// 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: &[String], rows: &[Vec<String>], 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(|c| strip_inline_md(c)));- for r in rows {- table.add_row(r.iter().map(|c| strip_inline_md(c)));- }-- table- .to_string()- .lines()- .map(|l| {- let is_border = !l.chars().any(|c| c.is_alphanumeric());- if is_border {- Line::styled(l.to_string(), Style::new().dim())- } else {- Line::raw(l.to_string())- }- })- .collect()-}-fn spawn_run(args: &Arc<OrchestrationArgs>, body: serde_json::Value) -> CurrentRun {let (tx, rx) = mpsc::unbounded_channel::<StreamEvent>();let args = Arc::clone(args);@@ -3241,6 +3099,11 @@ pub async fn run(args.todo_registry = Some(todo_registry.clone());let args = Arc::new(args);+ // Deserializing syntect's syntax/theme dumps takes tens of milliseconds.+ // Doing it here, off the render loop, keeps the first code block of a+ // response from stalling a frame mid-stream.+ tokio::task::spawn_blocking(highlight::warm);+// `env_logger` writes to stderr, which is still the user's terminal once we// switch to the alternate screen -- a single `log::warn!` from anywhere// (MCP, http, a dependency) then paints raw text over the frame and stays@@ -6668,10 +6531,9 @@ mod tests {apply_resume, assistant_is_awaiting_user_answer, build_user_message, clipboard_path,diff_lines, group_activity, group_detail_lines, group_summary, handle_ask_key,handle_ask_mouse, handle_key, handle_mouse, image_mime, input_content_lines,- compact_tokens, finish_login, is_table_separator, load_image_file, message_text,- open_config_screen, parse_command, partial_json_field, starting_call_lines,- unescape_partial_json_string,- render_table, restore_goal, restore_run_mode, restore_todos, run_command,+ compact_tokens, finish_login, load_image_file, message_text, open_config_screen,+ parse_command, partial_json_field, restore_goal, restore_run_mode, restore_todos,+ run_command, starting_call_lines, unescape_partial_json_string,running_group_row, split_reasoning, subagent_activity, subagent_name_from_run_id,summarize_result, tilde_path, tokens_per_second, tool_activity, tool_finished,transcript_top_padding,@@ -7366,6 +7228,15 @@ mod tests {line.spans.iter().map(|s| s.content.as_ref()).collect()}+ /// Text of a streaming write preview's tail, dropping the highlight styles.+ fn tail_text(call: &super::StartingCall) -> Option<Vec<String>> {+ call.preview.tail.as_ref().map(|rows| {+ rows.iter()+ .map(|r| r.iter().map(|s| s.content.as_ref()).collect())+ .collect()+ })+ }+/// Like `line_text`, but marks the reverse-video block cursor with `▏` at its/// left edge so caret-position assertions survive the styled-space rendering./// The synthetic end-of-line filler space is represented by the marker alone.@@ -8357,9 +8228,95 @@ mod tests {assert_eq!(app.cursor, 2);}+ /// Non-frame, non-marker colours in a diff panel: what syntax highlighting+ /// contributes, as distinct from the red/green add-remove markers.+ fn diff_syntax_colours(lines: &[ratatui::text::Line]) -> Vec<ratatui::style::Color> {+ lines+ .iter()+ .flat_map(|l| l.spans.iter())+ .filter_map(|s| s.style.fg)+ .filter(|c| matches!(c, ratatui::style::Color::Rgb(..)))+ .collect()+ }++ #[test]+ fn a_write_diff_is_syntax_highlighted_from_its_path() {+ let diff = "+fn main() {\n+ let x = 1;\n+}";+ let out = diff_lines(diff, 80, "", Some("src/main.rs"));+ assert!(+ !diff_syntax_colours(&out).is_empty(),+ "diff body not highlighted: {:?}",+ out.iter().map(line_text).collect::<Vec<_>>()+ );+ // The add/remove markers must stay legible as such.+ let greens = out+ .iter()+ .flat_map(|l| l.spans.iter())+ .filter(|s| s.content.starts_with('+') && s.style.fg == Some(ratatui::style::Color::Green))+ .count();+ assert_eq!(greens, 3, "one green marker per added line");+ }++ #[test]+ fn a_diff_without_a_known_language_stays_plain() {+ let out = diff_lines("+ foo\n- bar", 80, "", None);+ assert!(+ diff_syntax_colours(&out).is_empty(),+ "unexpected highlighting without a language"+ );+ }++ #[test]+ fn a_hunk_header_is_not_syntax_highlighted() {+ let out = diff_lines("@@ -1,2 +1,3 @@\n+let x = 1;", 80, "", Some("a.rs"));+ let header = out+ .iter()+ .find(|l| line_text(l).contains("@@"))+ .expect("no hunk header row");+ assert!(+ header.spans.iter().all(|s| !matches!(s.style.fg, Some(ratatui::style::Color::Rgb(..)))),+ "hunk header was highlighted: {:?}",+ line_text(header)+ );+ }++ #[test]+ fn a_cancelled_write_does_not_leak_its_recorded_path() {+ let mut app = test_app();+ app.apply(StreamEvent::ToolCall {+ id: "c1".into(),+ name: "write".into(),+ args: json!({"path": "src/main.rs"}),+ });+ assert_eq!(app.diff_paths.len(), 1);+ app.begin_turn();+ assert!(app.diff_paths.is_empty(), "path outlived its turn");+ }++ #[test]+ fn a_completed_write_carries_its_path_into_the_result_diff() {+ let mut app = test_app();+ app.apply(StreamEvent::ToolCall {+ id: "c1".into(),+ name: "write".into(),+ args: json!({"path": "src/main.rs"}),+ });+ app.apply(StreamEvent::ToolResult {+ id: "c1".into(),+ content: "wrote 3 lines".into(),+ is_error: false,+ diff: Some("+fn main() {\n+ let x = 1;\n+}".into()),+ });+ assert!(+ !diff_syntax_colours(&app.transcript).is_empty(),+ "result diff not highlighted: {:?}",+ app.transcript.iter().map(line_text).collect::<Vec<_>>()+ );+ }+#[test]fn diff_lines_renders_all_when_under_cap() {- let out = diff_lines("- foo\n+ bar", 80, "│ ");+ let out = diff_lines("- foo\n+ bar", 80, "│ ", None);// 2 content rows framed by a top and bottom border.assert_eq!(out.len(), 4);assert!(line_text(&out[0]).contains('┌'), "top: {}", line_text(&out[0]));@@ -8376,7 +8333,7 @@ mod tests {.map(|i| format!("+ line {i}")).collect::<Vec<_>>().join("\n");- let out = diff_lines(&diff, 80, "│ ");+ let out = diff_lines(&diff, 80, "│ ", None);// DIFF_MAX_ROWS content rows + a `(+N more)` row, framed by 2 borders.assert_eq!(out.len(), DIFF_MAX_ROWS + 1 + 2);// The tail sits just above the closing border.@@ -9211,101 +9168,6 @@ mod tests {assert_eq!(super::truncate("short", 20), "short");}- #[test]- fn table_separator_detection() {- assert!(is_table_separator("|---|:--:|"));- assert!(is_table_separator(" --- | --- "));- assert!(!is_table_separator("| a | b |"));- assert!(!is_table_separator("plain text"));- }-- #[test]- fn loose_list_marker_merges_into_body_line() {- // tui-markdown splits loose-list markers onto their own line; the merge- // pass folds "1. " and "- " back onto the item body.- let md = "1. first item\n\n2. second item";- let lines: Vec<String> = super::markdown_to_lines(md)- .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::markdown_to_lines("- alpha\n\n- beta")- .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() {- // tui-markdown should strip the ** markers and keep the word.- let lines = super::markdown_to_lines("hello **world**");- 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:?}");- }-- fn joined(lines: &[ratatui::text::Line]) -> String {- lines- .iter()- .flat_map(|l| l.spans.iter())- .map(|s| s.content.as_ref())- .collect()- }-- #[test]- fn format_markdown_routes_table_through_comfy_table() {- let md = "| a | b |\n|---|---|\n| 1 | 2 |";- let lines = super::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(&super::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(&super::format_markdown_lines(md, 80));- assert!(!text.contains("```"), "fence leaked: {text}");- assert!(text.contains("fn main() {}"));- }-- #[test]- fn render_table_wraps_and_strips_inline_md() {- let header = vec!["name".to_string(), "note".to_string()];- let rows = vec![vec![- "**apple**".to_string(),- "a `very` long note that must wrap across several lines".to_string(),- ]];- let lines = render_table(&header, &rows, 30);- let text = joined(&lines);- assert!(text.contains("apple") && !text.contains('*'), "md not stripped: {text:?}");- assert!(!text.contains('`'), "backticks not stripped: {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 parse_command_splits_name_and_arg() {assert_eq!(parse_command("resume abc123"), ("resume", "abc123"));@@ -9625,20 +9487,20 @@ mod tests {call.args = r#"{"path":"a.html","content":"one\ntwo"#.into();call.refresh_preview();let first = call.preview_at;- assert_eq!(call.preview.tail.as_deref(), Some(["one".into(), "two".into()].as_slice()));+ assert_eq!(tail_text(&call), Some(vec!["one".to_string(), "two".to_string()]));// Same bytes: the cache holds and nothing is recomputed.- call.preview.tail = Some(vec!["sentinel".into()]);+ call.preview.tail = Some(vec![vec![ratatui::text::Span::raw("sentinel")]]);call.refresh_preview();- assert_eq!(call.preview.tail.as_deref(), Some(["sentinel".to_string()].as_slice()));+ assert_eq!(tail_text(&call), Some(vec!["sentinel".to_string()]));assert_eq!(call.preview_at, first);// New bytes invalidate it.call.args.push_str(r#"\nthree"#);call.refresh_preview();assert_eq!(- call.preview.tail.as_deref(),- Some(["one".into(), "two".into(), "three".into()].as_slice())+ tail_text(&call),+ Some(vec!["one".to_string(), "two".to_string(), "three".to_string()]));}@@ -9681,7 +9543,7 @@ mod tests {let call = &mut app.starting[0];call.refresh_preview();assert_eq!(call.preview.path.as_deref(), Some("a.html"));- assert_eq!(call.preview.tail.as_deref(), Some(["hello".to_string()].as_slice()));+ assert_eq!(tail_text(call), Some(vec!["hello".to_string()]));// A delta for an unknown call is dropped, not panicked on.app.apply(StreamEvent::ToolCallArgsDelta {@@ -10787,3 +10649,5 @@ mod tests {}++diff --git a/src-tauri/src/core/cli/tui/highlight.rs b/src-tauri/src/core/cli/tui/highlight.rsnew file mode 100644index 000000000..a206a4a10--- /dev/null+++ b/src-tauri/src/core/cli/tui/highlight.rs@@ -0,0 +1,296 @@+//! Syntax highlighting for code shown in the transcript.+//!+//! Foreground colours only: the theme's own background is discarded so a+//! highlighted block sits transparently inside the panel frame drawn around it+//! (and over whatever background the user's terminal has).++use std::collections::HashMap;+use std::hash::{Hash, Hasher};+use std::sync::{Mutex, OnceLock};++use ratatui::prelude::*;+use syntect::easy::HighlightLines;+use syntect::highlighting::{FontStyle, Style as SynStyle, Theme, ThemeSet};+use syntect::parsing::{SyntaxReference, SyntaxSet};++/// Width a tab expands to. Code panels are padded to a fixed inner width, so a+/// literal tab would be measured as one column and misalign the right border.+const TAB_WIDTH: usize = 4;++/// Highlighted lines for one block.+type Rows = Vec<Vec<Span<'static>>>;++/// Distinct code blocks kept highlighted. A long session would otherwise grow+/// the cache without bound; the whole map is dropped rather than evicted+/// per-entry because a rebuild costs one re-highlight of whatever is on screen.+const CACHE_MAX: usize = 128;++/// Memo for `block`, keyed on a hash of the language and body.+///+/// The render loop re-derives the entire visible transcript every frame, and a+/// streamed response re-derives it on every delta, so without this the earlier+/// code blocks of a response are re-highlighted continuously -- quadratic in+/// the length of the response. Measured on a 31KB code-heavy answer: 237ms per+/// frame uncached, against a 50ms frame budget. Highlighting dominates+/// everything else in this module by roughly two orders of magnitude (the same+/// answer's prose costs ~1ms), so it is the only part worth memoizing.+fn cache() -> &'static Mutex<HashMap<u64, Rows>> {+ static CACHE: OnceLock<Mutex<HashMap<u64, Rows>>> = OnceLock::new();+ CACHE.get_or_init(|| Mutex::new(HashMap::new()))+}++fn cache_key(body: &[&str], token: &str) -> u64 {+ let mut h = std::collections::hash_map::DefaultHasher::new();+ token.hash(&mut h);+ body.len().hash(&mut h);+ for line in body {+ line.hash(&mut h);+ }+ h.finish()+}++/// Deserializing the bundled dumps costs tens of milliseconds, so both are+/// initialized once. `warm` pays that cost off the render path.+fn syntaxes() -> &'static SyntaxSet {+ static SET: OnceLock<SyntaxSet> = OnceLock::new();+ SET.get_or_init(SyntaxSet::load_defaults_newlines)+}++fn theme() -> &'static Theme {+ static THEME: OnceLock<Theme> = OnceLock::new();+ THEME.get_or_init(|| {+ let mut set = ThemeSet::load_defaults();+ set.themes+ .remove("base16-ocean.dark")+ .expect("base16-ocean.dark is bundled with syntect")+ })+}++/// Load the syntax and theme dumps now, so the first code block in a response+/// doesn't stall the render loop deserializing them.+pub(super) fn warm() {+ syntaxes();+ theme();+}++/// Resolve a fence tag (`rust`, `sh`) or a file name (`main.rs`) to a syntax.+fn syntax_for(token: &str) -> Option<&'static SyntaxReference> {+ let set = syntaxes();+ let token = token.trim();+ if token.is_empty() {+ return None;+ }+ set.find_syntax_by_token(token)+ .or_else(|| {+ let ext = token.rsplit('.').next()?;+ set.find_syntax_by_extension(ext)+ })+ .or_else(|| set.find_syntax_by_name(token))+}++/// Highlight `body` into one span list per input line. `token` is a fence+/// language tag or a file name; an unrecognized one yields unstyled spans, so+/// callers get renderable output either way.+///+/// The highlighter is threaded across lines rather than reset per line, so a+/// block comment or multi-line string keeps its colour past the line it opened.+pub(super) fn block(body: &[&str], token: &str) -> Rows {+ let key = cache_key(body, token);+ if let Some(hit) = cache().lock().ok().and_then(|c| c.get(&key).cloned()) {+ return hit;+ }+ let rows = highlight_uncached(body, token);+ if let Ok(mut c) = cache().lock() {+ if c.len() >= CACHE_MAX {+ c.clear();+ }+ c.insert(key, rows.clone());+ }+ rows+}++fn highlight_uncached(body: &[&str], token: &str) -> Rows {+ let Some(syntax) = syntax_for(token) else {+ return body+ .iter()+ .map(|l| vec![Span::raw(expand_tabs(l))])+ .collect();+ };+ let mut h = HighlightLines::new(syntax, theme());+ body.iter()+ .map(|line| {+ let text = expand_tabs(line);+ // The `newlines` syntax set expects a line terminator to close+ // line-scoped contexts; it is stripped back off below.+ let terminated = format!("{text}\n");+ match h.highlight_line(&terminated, syntaxes()) {+ Ok(ranges) => ranges+ .iter()+ .map(|(style, piece)| (piece.trim_end_matches('\n'), *style))+ .filter(|(piece, _)| !piece.is_empty())+ .map(|(piece, style)| Span::styled(piece.to_string(), convert(style)))+ .collect(),+ Err(_) => vec![Span::raw(text)],+ }+ })+ .collect()+}++/// syntect style -> ratatui style, dropping the background (see module docs).+fn convert(s: SynStyle) -> Style {+ let mut out = Style::new().fg(Color::Rgb(s.foreground.r, s.foreground.g, s.foreground.b));+ if s.font_style.contains(FontStyle::BOLD) {+ out = out.bold();+ }+ if s.font_style.contains(FontStyle::ITALIC) {+ out = out.italic();+ }+ if s.font_style.contains(FontStyle::UNDERLINE) {+ out = out.underlined();+ }+ out+}++fn expand_tabs(s: &str) -> String {+ if !s.contains('\t') {+ return s.to_string();+ }+ let mut out = String::with_capacity(s.len());+ for ch in s.chars() {+ if ch == '\t' {+ let pad = TAB_WIDTH - (out.chars().count() % TAB_WIDTH);+ out.push_str(&" ".repeat(pad));+ } else {+ out.push(ch);+ }+ }+ out+}++#[cfg(test)]+mod tests {+ use super::{block, expand_tabs};+ use std::collections::HashSet;++ fn text(spans: &[ratatui::text::Span]) -> String {+ spans.iter().map(|s| s.content.as_ref()).collect()+ }++ #[test]+ fn known_language_gets_more_than_one_colour() {+ let rows = block(&["fn main() { let x = 1; }"], "rust");+ let colours: HashSet<_> = rows[0].iter().filter_map(|s| s.style.fg).collect();+ assert!(+ colours.len() > 1,+ "expected multiple token colours, got {colours:?}"+ );+ }++ #[test]+ fn content_survives_highlighting_verbatim() {+ let src = "fn main() { let x = 1; }";+ let rows = block(&[src], "rust");+ assert_eq!(text(&rows[0]), src);+ }++ #[test]+ fn unknown_language_falls_back_to_unstyled_text() {+ let rows = block(&["some ::: thing"], "not-a-language");+ assert_eq!(rows.len(), 1);+ assert_eq!(text(&rows[0]), "some ::: thing");+ assert!(rows[0].iter().all(|s| s.style.fg.is_none()));+ }++ #[test]+ fn empty_language_tag_falls_back_without_panicking() {+ let rows = block(&["plain text"], "");+ assert_eq!(text(&rows[0]), "plain text");+ }++ #[test]+ fn no_background_is_ever_emitted() {+ // A theme background would show as a colour block inside the panel.+ let rows = block(&["fn main() {}", "// comment"], "rust");+ assert!(+ rows.iter().flatten().all(|s| s.style.bg.is_none()),+ "a span carried a background"+ );+ }++ #[test]+ fn a_file_name_resolves_by_extension() {+ let rows = block(&["fn main() {}"], "src/main.rs");+ let colours: HashSet<_> = rows[0].iter().filter_map(|s| s.style.fg).collect();+ assert!(colours.len() > 1, "path token did not resolve to a syntax");+ }++ #[test]+ fn block_comment_state_carries_to_following_lines() {+ // Line 2 is only a comment by virtue of line 1 opening one; a+ // per-line highlighter would colour it as code.+ let rows = block(&["/* open", "still comment", "*/"], "rust");+ let first = rows[0].last().expect("line 1 spans").style.fg;+ let second = rows[1].first().expect("line 2 spans").style.fg;+ assert_eq!(first, second, "comment colour did not carry across lines");+ }++ #[test]+ fn line_count_is_preserved_including_blanks() {+ let rows = block(&["fn a() {}", "", "fn b() {}"], "rust");+ assert_eq!(rows.len(), 3);+ assert_eq!(text(&rows[1]), "");+ }++ #[test]+ fn tabs_expand_to_the_next_stop() {+ assert_eq!(expand_tabs("\tx"), " x");+ assert_eq!(expand_tabs("ab\tx"), "ab x");+ assert_eq!(expand_tabs("abcd\tx"), "abcd x");+ assert_eq!(expand_tabs("no tabs"), "no tabs");+ }++ #[test]+ fn highlighted_lines_contain_no_tabs() {+ let rows = block(&["\tlet x = 1;"], "rust");+ assert!(!text(&rows[0]).contains('\t'));+ }++ #[test]+ fn repeated_blocks_hit_the_cache_and_match_the_uncached_result() {+ let body = ["fn main() {", " let x = 1;", "}"];+ let fresh = super::highlight_uncached(&body, "rust");+ let first = block(&body, "rust");+ let second = block(&body, "rust");+ assert_eq!(first, second, "cache returned different rows");+ assert_eq!(first, fresh, "cached rows differ from a fresh highlight");+ }++ #[test]+ fn cache_key_distinguishes_language_and_content() {+ let body = ["let x = 1"];+ assert_ne!(+ super::cache_key(&body, "rust"),+ super::cache_key(&body, "python"),+ "same body in different languages must not share a key"+ );+ assert_ne!(+ super::cache_key(&["a"], "rust"),+ super::cache_key(&["b"], "rust")+ );+ // Line splits must matter: ["a", "b"] is not the same block as ["ab"].+ assert_ne!(+ super::cache_key(&["a", "b"], "rust"),+ super::cache_key(&["ab"], "rust")+ );+ }++ #[test]+ fn cache_stays_bounded() {+ for i in 0..(super::CACHE_MAX + 20) {+ let line = format!("let v{i} = {i};");+ block(&[line.as_str()], "rust");+ }+ let n = super::cache().lock().unwrap().len();+ assert!(n <= super::CACHE_MAX, "cache grew to {n}");+ }+}diff --git a/src-tauri/src/core/cli/tui/markdown.rs b/src-tauri/src/core/cli/tui/markdown.rsnew file mode 100644index 000000000..f3c1f7bce--- /dev/null+++ b/src-tauri/src/core/cli/tui/markdown.rs@@ -0,0 +1,1273 @@+//! 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 assistant text to styled lines: reasoning dimmed, answer prose passed+/// through markdown formatting. `width` bounds table wrapping.+pub(super) fn format_assistant_lines(text: &str, width: u16) -> Vec<Line<'static>> {+ let mut lines = Vec::new();+ for (reasoning, seg) in super::split_reasoning(text) {+ if reasoning {+ lines.extend(reasoning_detail_lines(&seg));+ } else {+ lines.extend(format_markdown_lines(&seg, width));+ }+ }+ lines+}++/// A reasoning block's full dimmed lines (`┊ ` gutter, dim italic body).+pub(super) fn reasoning_detail_lines(seg: &str) -> Vec<Line<'static>> {+ seg.lines()+ .filter(|l| !l.trim().is_empty())+ .map(|l| {+ Line::from(vec![+ Span::styled("┊ ", Style::new().dark_gray()),+ Span::styled(l.to_string(), Style::new().dim().italic()),+ ])+ })+ .collect()+}++/// Collapsed summary row for a folded reasoning block.+pub(super) fn reasoning_summary_row(n: usize) -> Line<'static> {+ let label = if n == 1 {+ "reasoning (1 line)".to_string()+ } else {+ format!("reasoning ({n} lines)")+ };+ Line::from(vec![+ Span::styled("┊ ", Style::new().dark_gray()),+ Span::styled(label, Style::new().dim().italic()),+ ])+}++/// 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.+pub(super) fn format_markdown_lines(text: &str, width: u16) -> Vec<Line<'static>> {+ use pulldown_cmark::{Event, Options, Parser, Tag};++ 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, max: usize, plain: bool) -> Vec<Line<'static>> {+ 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, max, "")+}++/// 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>>> {+ 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 take = rest.chars().count().min(room);+ let split = rest+ .char_indices()+ .nth(take)+ .map(|(i, _)| i)+ .unwrap_or(rest.len());+ let (head, tail) = rest.split_at(split);+ if !head.is_empty() {+ 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+}++/// 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()),+ 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 max = (self.width as usize).saturating_sub(4);+ let plain = self.plain_code_block == Some(self.code_blocks_seen);+ let panel = render_code_block(&body, &c.lang, max, 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::{format_markdown_lines, render_table};++ fn line_text(line: &ratatui::text::Line) -> String {+ line.spans.iter().map(|s| s.content.as_ref()).collect()+ }++ 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));+ }+}