A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
underline links and show the url beside them (#3186)
kt2d6c7b52ce1d
diff --git a/crates/pa-tui/src/chat.rs b/crates/pa-tui/src/chat.rsindex fe6d7b2d67..d3d055d65e 100644--- a/crates/pa-tui/src/chat.rs+++ b/crates/pa-tui/src/chat.rs@@ -12,7 +12,7 @@ use crate::snapshot::RetryStartReason;use crate::theme::{Theme, ThemeBg, ThemeColor};use crate::width::str_width;use crate::{Line, Span};-use ratatui::style::Style;+use ratatui::style::{Modifier, Style};/// How much detail the conversation shows (TS `setChatDetail` levels).#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -371,10 +371,21 @@ pub fn render_user_block(// The user block colors everything `userMessageText` on the block// background; markdown structure (wrapping) is kept, its own colors// are not. The masked placeholders restore to their token colors- // over that base.+ // over that base, and the link affordance survives the restyle:+ // the underlined label keeps the underline, the URL bracket keeps+ // the dim link slot.let restyled: Line = line.into_iter()- .map(|span| Span::styled(span.content, bg.patch(body)))+ .map(|span| {+ let mut style = bg.patch(body);+ if span.style.add_modifier.contains(Modifier::UNDERLINED) {+ style = style.add_modifier(Modifier::UNDERLINED);+ }+ if span.style.fg == md.link_url.fg {+ style = style.patch(md.link_url);+ }+ Span::styled(span.content, style)+ }).collect();row.extend(mask.restore_line(theme, &restyled));rows.push(pad_to(row, width, bg));diff --git a/crates/pa-tui/src/chat/tests.rs b/crates/pa-tui/src/chat/tests.rsindex 13ab48d4b4..aea5822960 100644--- a/crates/pa-tui/src/chat/tests.rs+++ b/crates/pa-tui/src/chat/tests.rs@@ -160,6 +160,36 @@ fn row_runs(row: &Line) -> Vec<(String, Style)> {runs}+#[test]+fn user_block_keeps_the_link_affordance() {+ // A markdown link in the user block: the label underlines over the+ // user-message color, the URL bracket keeps the dim link slot, and+ // the OSC 8 wrap rides the label — all on the block background.+ crate::hyperlinks::set_hyperlinks_override(Some(true));+ let (bg, body, _, _, _) = user_block_styles();+ let link_url = bg.patch(theme().fg_style(ThemeColor::MdLinkUrl));+ let rows = render_user_block("see [docs](https://x.dev/a)", &theme(), " ", 60);+ assert_eq!(rows.len(), 3);+ assert_eq!(+ row_runs(&rows[1]),+ vec![+ (" ".to_string(), bg),+ ("see ".to_string(), body),+ (+ format!(+ "{}docs{}",+ crate::hyperlinks::osc8_open("https://x.dev/a"),+ crate::hyperlinks::OSC8_CLOSE+ ),+ body.add_modifier(ratatui::style::Modifier::UNDERLINED)+ ),+ (" [https://x.dev/a]".to_string(), link_url),+ (" ".repeat(60 - 28), bg),+ ]+ );+ crate::hyperlinks::set_hyperlinks_override(None);+}+#[test]fn user_block_highlights_argument_tokens() {// TS `PromptTokenMask`: the argument tokens render in their owndiff --git a/crates/pa-tui/src/hyperlinks.rs b/crates/pa-tui/src/hyperlinks.rsindex d444b91416..e48124c75d 100644--- a/crates/pa-tui/src/hyperlinks.rs+++ b/crates/pa-tui/src/hyperlinks.rs@@ -93,8 +93,10 @@ pub fn resolve_link_href(token_href: &str) -> String {/// parsing percent-encodes on every parseable target in both products./// The TS renderer shares the hole (its fragment and unparseable targets/// reach `hyperlink()` unsanitized); this is deliberate hardening past-/// parity on an input class no battery covers.-fn sanitize_control_bytes(target: String) -> String {+/// parity on an input class no battery covers. The markdown URL bracket+/// applies the same hardening to the destination it renders as visible+/// text.+pub(crate) fn sanitize_control_bytes(target: String) -> String {if !target.as_bytes().iter()diff --git a/crates/pa-tui/src/markdown.rs b/crates/pa-tui/src/markdown.rsindex 4d4cc7c30f..6a04e8adf4 100644--- a/crates/pa-tui/src/markdown.rs+++ b/crates/pa-tui/src/markdown.rs@@ -480,6 +480,33 @@ fn highlighted_code_lines())}+/// Heading spans: inline-rendered, tapered to the heading color with+/// the link affordance kept — an underlined label stays underlined and+/// the URL bracket keeps its dim `link_url` slot, tracked by origin+/// (the inline pass reports the bracket indices). A code or body span+/// that merely renders in the `link_url` style (a theme whose colors+/// collide) tapers to the heading color like any other span. Shared by+/// the paint path and the row count, so a wrapped heading counts+/// exactly what it paints.+fn heading_spans(text: &str, style: &MarkdownStyle) -> Vec<Span> {+ let (mut spans, url_slots) = inline::render_inline_with_url_slots(text, style);+ // The slot indices arrive ascending, so one cursor walks them in+ // step with the span iteration — a link-heavy heading stays linear.+ let mut url_slot = 0;+ for (i, s) in spans.iter_mut().enumerate() {+ if url_slots.get(url_slot) == Some(&i) {+ url_slot += 1;+ continue;+ }+ let underlined = s.style.add_modifier.contains(Modifier::UNDERLINED);+ s.style = style.heading;+ if underlined {+ s.style = s.style.add_modifier(Modifier::UNDERLINED);+ }+ }+ spans+}+fn render_block(block: &Block,next: Option<&Block>,@@ -497,11 +524,8 @@ fn render_block(// alone (probe vs the installed 0.9.5 binary: `# H1`, `## H2`,// and `### H3` all render bare mdHeading).let text = block.lines.first().cloned().unwrap_or_default();- let mut spans = render_inline(&text, style);- for s in &mut spans {- s.style = style.heading;- }- out.push(spans);+ let spans = heading_spans(&text, style);+ wrap_spans(&spans, width, style.heading, out);if blank_after(false) {out.push(Vec::new());}diff --git a/crates/pa-tui/src/markdown/geometry.rs b/crates/pa-tui/src/markdown/geometry.rsindex 521868112c..2deeabbfbc 100644--- a/crates/pa-tui/src/markdown/geometry.rs+++ b/crates/pa-tui/src/markdown/geometry.rs@@ -1,7 +1,7 @@//! Geometry uses the same wrapping traversal as painted Markdown rows.use super::{- block_cache_key, parse_blocks, render_inline, wrapped_span_count, Block, BlockKind,- MarkdownBlockCache, MarkdownStyle,+ block_cache_key, heading_spans, parse_blocks, render_inline, wrapped_span_count, Block,+ BlockKind, MarkdownBlockCache, MarkdownStyle,};use crate::{Line, Span};use ratatui::style::Style;@@ -99,7 +99,11 @@ pub(crate) fn markdown_row_count_tagged(continue;}let count = match &block.kind {- BlockKind::Heading => 1 + usize::from(blank_after(next, false)),+ BlockKind::Heading => {+ let text = block.lines.first().cloned().unwrap_or_default();+ wrapped_span_count(&heading_spans(&text, style), width)+ + usize::from(blank_after(next, false))+ }BlockKind::Hr => 1,BlockKind::Code { .. } => {block.lines.len().max(1) + usize::from(blank_after(next, false))diff --git a/crates/pa-tui/src/markdown/inline.rs b/crates/pa-tui/src/markdown/inline.rsindex 86f70f9f55..2c614cfa10 100644--- a/crates/pa-tui/src/markdown/inline.rs+++ b/crates/pa-tui/src/markdown/inline.rs@@ -4,14 +4,31 @@ use ratatui::style::Modifier;/// Inline rendering: bold, italic, strikethrough, code, links.#[must_use]pub fn render_inline(text: &str, style: &MarkdownStyle) -> Line {+ render_inline_with_url_slots(text, style).0+}++/// The same inline render, plus the `link_url` slot indices: which+/// spans of the returned line carry a link's `[url]` bracket, in+/// ascending span order. Style-tapering callers (headings) preserve+/// those spans by origin — a code or body span that merely renders in+/// the `link_url` style (a theme whose colors collide) is not a slot+/// and tapers like any other span.+#[must_use]+pub(crate) fn render_inline_with_url_slots(+ text: &str,+ style: &MarkdownStyle,+) -> (Line, Vec<usize>) {render_inline_ctx(text, style, false)}/// `in_link` mirrors marked's `lexer.state.inLink`: set while a link/// label's tokens are produced, and the gfm bare-url rule is skipped-/// inside one (the angle `autolink` rule is not).-fn render_inline_ctx(text: &str, style: &MarkdownStyle, in_link: bool) -> Line {+/// inside one (the angle `autolink` rule is not). The second return+/// half lists the `[url]` bracket indices inside the returned spans,+/// remapped across every recursive extend.+fn render_inline_ctx(text: &str, style: &MarkdownStyle, in_link: bool) -> (Line, Vec<usize>) {let mut spans: Vec<Span> = Vec::new();+ let mut url_slots: Vec<usize> = Vec::new();let bytes: Vec<char> = text.chars().collect();// Byte offset per char index: the autolink rules run on a slice of the// original text (zero-copy) instead of a copy of the remaining tail,@@ -80,7 +97,31 @@ fn render_inline_ctx(text: &str, style: &MarkdownStyle, in_link: bool) -> Line {if j + 1 < bytes.len() && bytes[j] == ']' && bytes[j + 1] == '(' {let mut k = j + 2;let mut url = String::new();- while k < bytes.len() && bytes[k] != ')' {+ // CommonMark link destination: parentheses ride only as+ // a balanced pair (TS marked's lexer), so the destination+ // ends at the `)` that closes it — not at the first `)`+ // inside, which a Wikipedia-style url carries. A+ // backslash-escaped char rides through verbatim and+ // never counts toward the balance either (so `\(` does+ // not swallow the real closer); unescaping stays out of+ // this port's inline subset.+ let mut paren_depth = 0usize;+ while k < bytes.len() {+ if bytes[k] == ')' && paren_depth == 0 {+ break;+ }+ if bytes[k] == '\\' && k + 1 < bytes.len() {+ url.push(bytes[k]);+ k += 1;+ url.push(bytes[k]);+ k += 1;+ continue;+ }+ if bytes[k] == '(' {+ paren_depth += 1;+ } else if bytes[k] == ')' {+ paren_depth -= 1;+ }url.push(bytes[k]);k += 1;}@@ -93,19 +134,16 @@ fn render_inline_ctx(text: &str, style: &MarkdownStyle, in_link: bool) -> Line {if italic {modifier |= style.italic;}- // The observed TS binary output (0.9.5, the parity ground- // truth) renders the link label with the body color only:- // the link color is shadowed by the body color applied- // inside the label, and the underline wrapper never- // reaches the wire. `modifier` carries the emphasis context.+ // The label renders underlined (the standard+ // terminal link affordance); `modifier` carries the+ // emphasis context.let href = crate::hyperlinks::resolve_link_href(&url);- let mut label_spans = render_inline_ctx(&label, style, true);+ let (mut label_spans, mut label_slots) = render_inline_ctx(&label, style, true);for s in &mut label_spans {- s.style = s.style.add_modifier(modifier);+ s.style = s.style.add_modifier(modifier | Modifier::UNDERLINED);}if crate::hyperlinks::hyperlinks_enabled() {- // OSC 8: the label is clickable, the URL never- // printed inline (TS `hyperlink()`).+ // OSC 8: the label stays clickable (TS `hyperlink()`).let open = crate::hyperlinks::osc8_open(&href);if let Some(first) = label_spans.first_mut() {first.content.insert_str(0, &open);@@ -113,16 +151,29 @@ fn render_inline_ctx(text: &str, style: &MarkdownStyle, in_link: bool) -> Line {if let Some(last) = label_spans.last_mut() {last.content.push_str(crate::hyperlinks::OSC8_CLOSE);}- spans.extend(label_spans);- } else {- spans.extend(label_spans);- // Legacy form: the URL shows after the text unless- // the label is the URL (mailto stripped for the- // comparison, like autolinked emails).- let comparison = url.strip_prefix("mailto:").unwrap_or(url.as_str());- if label != url && label != comparison {- spans.push(Span::styled(format!(" ({url})"), style.link_url));- }+ }+ let offset = spans.len();+ for slot in &mut label_slots {+ *slot += offset;+ }+ url_slots.append(&mut label_slots);+ spans.extend(label_spans);+ // The URL rides beside every link, in both the OSC 8+ // and legacy forms — after the wrap, so the region+ // covers the label only — in the dim `link_url` slot,+ // unless the label already is the URL (mailto stripped+ // for the comparison, like autolinked emails).+ let comparison = url.strip_prefix("mailto:").unwrap_or(url.as_str());+ if label != url && label != comparison {+ // The bracket renders the destination as visible+ // text, so it gets the same control-byte hardening+ // the OSC 8 target gets (`resolve_link_href`): an+ // escape byte smuggled into an attacker-chosen url+ // can never re-enter the terminal as a live+ // OSC/CSI sequence.+ let shown = crate::hyperlinks::sanitize_control_bytes(url.clone());+ url_slots.push(spans.len());+ spans.push(Span::styled(format!(" [{shown}]"), style.link_url));}i = k + 1;continue;@@ -160,7 +211,13 @@ fn render_inline_ctx(text: &str, style: &MarkdownStyle, in_link: bool) -> Line {flush!();if doubled {bold = !bold;- let mut inner_spans = render_inline_ctx(&inner, style, in_link);+ let (mut inner_spans, mut inner_slots) =+ render_inline_ctx(&inner, style, in_link);+ let offset = spans.len();+ for slot in &mut inner_slots {+ *slot += offset;+ }+ url_slots.append(&mut inner_slots);for s in &mut inner_spans {s.style = s.style.add_modifier(style.bold);}@@ -168,7 +225,13 @@ fn render_inline_ctx(text: &str, style: &MarkdownStyle, in_link: bool) -> Line {bold = !bold;} else {italic = !italic;- let mut inner_spans = render_inline_ctx(&inner, style, in_link);+ let (mut inner_spans, mut inner_slots) =+ render_inline_ctx(&inner, style, in_link);+ let offset = spans.len();+ for slot in &mut inner_slots {+ *slot += offset;+ }+ url_slots.append(&mut inner_slots);for s in &mut inner_spans {s.style = s.style.add_modifier(style.italic);}@@ -184,7 +247,13 @@ fn render_inline_ctx(text: &str, style: &MarkdownStyle, in_link: bool) -> Line {let inner: String = bytes[i + 2..close].iter().collect();if !inner.trim().is_empty() {flush!();- let mut inner_spans = render_inline_ctx(&inner, style, in_link);+ let (mut inner_spans, mut inner_slots) =+ render_inline_ctx(&inner, style, in_link);+ let offset = spans.len();+ for slot in &mut inner_slots {+ *slot += offset;+ }+ url_slots.append(&mut inner_slots);for s in &mut inner_spans {s.style = s.style.add_modifier(style.strikethrough);}@@ -209,8 +278,8 @@ fn render_inline_ctx(text: &str, style: &MarkdownStyle, in_link: bool) -> Line {flush!();// The token carries one plain text token, so the label is a// single body-colored run carrying the current emphasis (the- // theme.link/underline wrapper never reaches the wire in the- // deployed binary, like explicit link labels).+ // theme.link color never reaches the wire, like explicit link+ // labels).let mut m = Modifier::empty();if bold {m |= style.bold;@@ -218,23 +287,31 @@ fn render_inline_ctx(text: &str, style: &MarkdownStyle, in_link: bool) -> Line {if italic {m |= style.italic;}- let label = Span::styled(token.text.clone(), base.add_modifier(m));+ // Every link render underlines (the standard link+ // affordance), both capability forms.+ let mut label = Span::styled(+ token.text.clone(),+ base.add_modifier(m | Modifier::UNDERLINED),+ );if crate::hyperlinks::hyperlinks_enabled() {- // OSC 8: the label is clickable, the URL never printed- // inline (TS `hyperlink()`).let href = crate::hyperlinks::resolve_link_href(&token.href);- let mut content = label.content;- content.insert_str(0, &crate::hyperlinks::osc8_open(&href));- content.push_str(crate::hyperlinks::OSC8_CLOSE);- spans.push(Span::styled(content, label.style));- } else {- spans.push(label);- // Legacy form: the URL shows after the label unless the- // label already is it (mailto stripped), TS token.href.- let comparison = token.href.strip_prefix("mailto:").unwrap_or(&token.href);- if token.text != token.href && token.text != comparison {- spans.push(Span::styled(format!(" ({})", token.href), style.link_url));- }+ label+ .content+ .insert_str(0, &crate::hyperlinks::osc8_open(&href));+ label.content.push_str(crate::hyperlinks::OSC8_CLOSE);+ }+ spans.push(label);+ // The URL rides beside the label in the dim `link_url` slot+ // unless the label already shows it (the mailto-stripped+ // comparison, TS token.href). The bare-url regex tail only+ // excludes whitespace, so an escape byte can ride a bare+ // url token's href into this visible span — the bracket gets+ // the same control-byte hardening the OSC 8 target gets.+ let comparison = token.href.strip_prefix("mailto:").unwrap_or(&token.href);+ if token.text != token.href && token.text != comparison {+ let shown = crate::hyperlinks::sanitize_control_bytes(token.href.clone());+ url_slots.push(spans.len());+ spans.push(Span::styled(format!(" [{shown}]"), style.link_url));}i += token.raw.chars().count();continue;@@ -246,7 +323,7 @@ fn render_inline_ctx(text: &str, style: &MarkdownStyle, in_link: bool) -> Line {if spans.is_empty() {spans.push(Span::raw(""));}- spans+ (spans, url_slots)}/// Run the marked autolink rules on the text starting at `rest` (thediff --git a/crates/pa-tui/src/markdown/tests.rs b/crates/pa-tui/src/markdown/tests.rsindex c8c06dfbc6..4b45055f21 100644--- a/crates/pa-tui/src/markdown/tests.rs+++ b/crates/pa-tui/src/markdown/tests.rs@@ -259,6 +259,82 @@ fn heading_and_paragraph() {assert_eq!(adjacent.len(), 3);}+#[test]+fn heading_link_wraps_keeps_the_affordance_and_counts() {+ crate::hyperlinks::set_hyperlinks_override(Some(true));+ let style = MarkdownStyle::default();+ // A heading that fits: one row, the label underlined in the+ // heading color, the bracket in the dim `link_url` slot.+ let lines = render_markdown("# [docs](https://x.dev/a)", 40, &style);+ assert_eq!(lines.len(), 1);+ let label = &lines[0][0];+ assert!(label.style.add_modifier.contains(Modifier::UNDERLINED));+ assert_eq!(label.style.fg, style.heading.fg);+ let bracket = lines[0].last().expect("bracket span");+ assert_eq!(bracket.style.fg, style.link_url.fg);+ let visible: String = lines[0]+ .iter()+ .map(|s| crate::hyperlinks::strip_osc8_content(&s.content))+ .collect();+ assert_eq!(visible, "docs [https://x.dev/a]");+ // A narrow heading wraps like any row: the bracket — closing `]`+ // included — lands on its own row instead of clipping, and the+ // count==paint row math holds at every width.+ let rows = render_markdown("# [docs](https://x.dev/a)", 20, &style);+ assert_eq!(rows.len(), 2, "rows: {rows:?}");+ let visible: Vec<String> = rows+ .iter()+ .map(|l| {+ l.iter()+ .map(|s| crate::hyperlinks::strip_osc8_content(&s.content))+ .collect::<String>()+ })+ .collect();+ assert_eq!(+ visible,+ vec!["docs".to_string(), "[https://x.dev/a]".to_string()]+ );+ for width in 1..40 {+ assert_eq!(+ markdown_row_count("# [docs](https://x.dev/a)", width, &style),+ render_markdown("# [docs](https://x.dev/a)", width, &style).len(),+ "count==paint at width {width}"+ );+ }+ // The clickable region survives the wrap: the label cells only.+ let ranges = crate::hyperlinks::frame_link_ranges(&rows);+ assert_eq!(ranges.len(), 1, "one clickable region: {ranges:?}");+ assert_eq!(+ (ranges[0].row, ranges[0].start_col, ranges[0].end_col),+ (0, 0, 4)+ );+ assert_eq!(ranges[0].url, "https://x.dev/a");+ crate::hyperlinks::set_hyperlinks_override(None);+}++#[test]+fn heading_tapers_code_and_body_that_merely_match_the_link_url_style() {+ // A theme can collide `mdCode`/`mdBody` onto the same color as+ // `mdLinkUrl`; the taper reads the bracket slots by origin, not by+ // style equality, so such spans take the heading color and only a+ // genuine link's bracket keeps the `link_url` slot.+ let mut style = MarkdownStyle::default();+ style.code = style.link_url;+ style.body = style.link_url;+ crate::hyperlinks::set_hyperlinks_override(Some(false));+ let lines = render_markdown("# `c` [d](https://x.dev/a)", 40, &style);+ assert_eq!(+ lines,+ vec![vec![+ Span::styled("c", style.heading),+ Span::styled(" ", style.heading),+ Span::styled("d", style.heading.add_modifier(Modifier::UNDERLINED)),+ Span::styled(" [https://x.dev/a]", style.link_url),+ ]]+ );+ crate::hyperlinks::set_hyperlinks_override(None);+}+#[test]fn paragraph_keeps_final_line_trailing_whitespace() {// The TS lexer's paragraph token carries the block's trailing@@ -479,13 +555,13 @@ fn list_render() {#[test]fn inline_bold_code_link() {- // Pin the terminal-capability gate: a link renders the legacy- // `label (url)` form when OSC 8 hyperlinks are unavailable.+ // Pin the terminal-capability gate: without OSC 8 support the link+ // renders the legacy `label [url]` observability form (no wrap).crate::hyperlinks::set_hyperlinks_override(Some(false));let style = MarkdownStyle::default();let spans = render_inline("a **b** `c` [d](http://e)", &style);let texts: Vec<&str> = spans.iter().map(|s| s.content.as_str()).collect();- assert_eq!(texts, vec!["a ", "b", " ", "c", " ", "d", " (http://e)"]);+ assert_eq!(texts, vec!["a ", "b", " ", "c", " ", "d", " [http://e]"]);crate::hyperlinks::set_hyperlinks_override(None);}@@ -500,12 +576,12 @@ fn legacy_link_row_is_underlined_and_shows_the_url() {vec!["see ".to_string(),"docs".to_string(),- " (https://x.dev/a)".to_string()+ " [https://x.dev/a]".to_string()]);- // The observed TS binary output styles the label with the body- // color only (the underline wrapper never reaches the wire).- assert!(!spans[1].style.add_modifier.contains(Modifier::UNDERLINED));+ // The label underlines on every link render and keeps the body+ // color; the bracket rides in the dim `link_url` slot.+ assert!(spans[1].style.add_modifier.contains(Modifier::UNDERLINED));assert_eq!(spans[1].style.fg, style.body.fg);assert_eq!(spans[2].style.fg, style.link_url.fg);// The URL is not repeated when the label is the URL, and mailto@@ -520,31 +596,203 @@ fn legacy_link_row_is_underlined_and_shows_the_url() {}#[test]-fn osc8_gated_link_row_wraps_the_label_in_a_hyperlink() {+fn osc8_gated_link_row_wraps_the_label_in_a_hyperlink_and_shows_the_url() {crate::hyperlinks::set_hyperlinks_override(Some(true));let style = MarkdownStyle::default();let spans = render_inline("see [docs](https://x.dev/a)", &style);let joined: String = spans.iter().map(|s| s.content.as_str()).collect();+ // The OSC 8 region wraps the label (the escape bytes intact, the+ // label underlined); the URL bracket shows after the region,+ // outside it, in the dim `link_url` slot.assert_eq!(joined,format!(- "see {}docs{}",+ "see {}docs{} [https://x.dev/a]",crate::hyperlinks::osc8_open("https://x.dev/a"),crate::hyperlinks::OSC8_CLOSE));- // The sequences are zero-width: the row measures like the plain text- // and never prints the URL inline.- assert_eq!(- joined.chars().filter(|&c| c == '(').count(),- 0,- "osc8 rows must not inline the url: {joined}"+ assert!(+ spans[1].style.add_modifier.contains(Modifier::UNDERLINED),+ "the label underlines: {joined}");- assert_eq!(str_width(&joined), str_width("see docs"));- // Windows drive-letter targets classify as file paths.+ assert_eq!(spans[2].style.fg, style.link_url.fg);+ // The sequences are zero-width: the row measures like the plain+ // text plus the bracketed URL.+ assert_eq!(str_width(&joined), str_width("see docs [https://x.dev/a]"));+ // Windows drive-letter targets classify as file paths; the label is+ // the URL, so no bracket follows it.let drive = render_inline("[c:\\src](c:\\src)", &style);let joined: String = drive.iter().map(|s| s.content.as_str()).collect();assert!(joined.contains("file:///c:/src"), "drive path: {joined}");+ assert!(+ !joined.contains(" ["),+ "no bracket when the label is the url: {joined}"+ );+ crate::hyperlinks::set_hyperlinks_override(None);+}++#[test]+fn balanced_parens_in_a_link_destination_stay_intact() {+ // CommonMark link destinations keep balanced parentheses (TS+ // marked's lexer): the destination ends at its own closing `)`, so+ // a Wikipedia-style url renders whole in the bracket and the OSC 8+ // target, with no stray `)` leaking into the text.+ crate::hyperlinks::set_hyperlinks_override(Some(false));+ let style = MarkdownStyle::default();+ let url = "https://en.wikipedia.org/wiki/Function_(mathematics)";+ let spans = render_inline(&format!("[math]({url})"), &style);+ assert_eq!(+ spans,+ vec![+ Span::styled("math", style.body.add_modifier(Modifier::UNDERLINED)),+ Span::styled(format!(" [{url}]"), style.link_url),+ ]+ );+ crate::hyperlinks::set_hyperlinks_override(None);+ crate::hyperlinks::set_hyperlinks_override(Some(true));+ let spans = render_inline(&format!("[math]({url})"), &style);+ assert_eq!(+ spans,+ vec![+ Span::styled(+ format!(+ "{}math{}",+ crate::hyperlinks::osc8_open(url),+ crate::hyperlinks::OSC8_CLOSE+ ),+ style.body.add_modifier(Modifier::UNDERLINED),+ ),+ Span::styled(format!(" [{url}]"), style.link_url),+ ]+ );+ crate::hyperlinks::set_hyperlinks_override(None);+}++#[test]+fn escaped_parens_never_open_or_close_the_link_destination() {+ // A backslash-escaped paren rides through the destination verbatim+ // without counting toward the paren balance (CommonMark): `\(` does+ // not swallow the real closer, and `\)` alone never closes —+ // `[a](b\)` is plain text, exactly like the reference parser.+ crate::hyperlinks::set_hyperlinks_override(Some(false));+ let style = MarkdownStyle::default();+ let spans = render_inline("[a](b\\(c)", &style);+ assert_eq!(+ spans,+ vec![+ Span::styled("a", style.body.add_modifier(Modifier::UNDERLINED)),+ Span::styled(" [b\\(c]", style.link_url),+ ]+ );+ let plain = render_inline("[a](b\\)", &style);+ assert_eq!(plain.len(), 1);+ assert_eq!(plain[0].content, "[a](b\\)");+ crate::hyperlinks::set_hyperlinks_override(None);+}++#[test]+fn the_url_bracket_scrubs_terminal_control_bytes() {+ // The bracket renders the destination as visible text; a raw escape+ // byte smuggled into an attacker-chosen url must never re-enter the+ // terminal as a live OSC/CSI sequence. The bracket percent-encodes+ // control bytes, the same hardening the OSC 8 target gets through+ // `resolve_link_href`.+ crate::hyperlinks::set_hyperlinks_override(Some(true));+ let style = MarkdownStyle::default();+ let url = "https://x.dev/\u{1b}]52;c;base64";+ let spans = render_inline(&format!("[a]({url})"), &style);+ let bracket = spans.last().expect("bracket span");+ assert_eq!(bracket.content, " [https://x.dev/%1B]52;c;base64]");+ // The bare-url autolink form hardens the same way: the regex tail+ // only excludes whitespace, so the escape byte rides the token's+ // href (the www form's href gains its scheme, so the bracket shows).+ let www = render_inline("www.x.dev/\u{1b}]52;c=base64", &style);+ let bracket = www.last().expect("bracket span");+ assert_eq!(bracket.content, " [http://www.x.dev/%1B]52;c=base64]");+ assert!(+ !bracket.content.contains('\u{1b}'),+ "no raw escape byte in the visible bracket"+ );+ crate::hyperlinks::set_hyperlinks_override(None);+}++#[test]+fn link_url_bracket_wraps_and_counts_like_text() {+ crate::hyperlinks::set_hyperlinks_override(Some(true));+ let style = MarkdownStyle::default();+ let text = "see [docs](https://x.dev/a) tail";+ // The bracketed URL is visible text: the width accounting includes+ // it, so the row count and the painted rows agree at every width+ // (the count==paint invariant, the layout math).+ for width in 1..48 {+ let rows = markdown_row_count(text, width, &style);+ let painted = render_markdown(text, width, &style);+ assert_eq!(painted.len(), rows, "count==paint at width {width}");+ }+ // At width 18 the bracket cannot share the row with "see docs"+ // (8 + 17 > 18), so it wraps onto its own row; the tail follows it.+ let rows = render_markdown(text, 18, &style);+ let visible: Vec<String> = rows+ .iter()+ .map(|l| {+ l.iter()+ .map(|s| crate::hyperlinks::strip_osc8_content(&s.content))+ .collect::<String>()+ })+ .collect();+ assert_eq!(+ visible,+ vec![+ "see docs".to_string(),+ "[https://x.dev/a]".to_string(),+ "tail".to_string()+ ],+ "the bracket wraps like normal text"+ );+ crate::hyperlinks::set_hyperlinks_override(None);+}++#[test]+fn long_link_url_wraps_without_breaking_the_clickable_region() {+ crate::hyperlinks::set_hyperlinks_override(Some(true));+ let style = MarkdownStyle::default();+ let url = format!("https://x.dev/{}", "a".repeat(40));+ let rows = render_markdown(&format!("[docs]({url})"), 12, &style);+ // The bracket word is far over the wrap width: it breaks across+ // rows at the width, every row within it.+ assert!(rows.len() >= 4, "rows: {rows:?}");+ for row in &rows {+ let joined: String = row.iter().map(|s| s.content.as_str()).collect();+ assert!(str_width(&joined) <= 12, "row over the width: {joined:?}");+ }+ // The clickable region survives the wrap intact: exactly the label+ // cells link (the escape bytes never split mid-sequence; the+ // bracket part rides outside the region).+ let ranges = crate::hyperlinks::frame_link_ranges(&rows);+ assert_eq!(ranges.len(), 1, "one clickable region: {ranges:?}");+ assert_eq!(ranges[0].row, 0);+ assert_eq!(ranges[0].start_col, 0);+ assert_eq!(ranges[0].end_col, str_width("docs"));+ assert_eq!(ranges[0].url, url);+ // The full URL shows beside the label, across the wrapped rows.+ let visible: String = rows+ .iter()+ .flat_map(|l| l.iter())+ .map(|s| crate::hyperlinks::strip_osc8_content(&s.content))+ .collect();+ // The wrap drops the boundary gap (a wrapped row never carries its+ // leading/trailing space), so the bracket word begins at the row+ // start: `docs` then the bracketed URL across the rows.+ assert_eq!(visible, format!("docs[{url}]"));+ // Count==paint with the long bracket at every wrap width.+ for width in 1..40 {+ assert_eq!(+ markdown_row_count(&format!("[docs]({url})"), width, &style),+ render_markdown(&format!("[docs]({url})"), width, &style).len(),+ "count==paint at width {width}"+ );+ }crate::hyperlinks::set_hyperlinks_override(None);}@@ -563,8 +811,15 @@ fn bare_url_autolinks_osc8() {));// The label is one zero-width-wrapped run; the URL never prints- // twice and no legacy suffix appears.+ // twice and no bracket follows it (the label already is the URL).assert_eq!(str_width(&joined), str_width("see https://x.dev/a?b=1 now"));+ assert!(!joined.contains(" ["), "no bracket on a bare url: {joined}");+ // The clickable bare label underlines (the observability ruling's+ // standard link affordance; the bracket part is redundant here).+ assert!(+ spans[1].style.add_modifier.contains(Modifier::UNDERLINED),+ "the bare autolink label underlines: {joined}"+ );crate::hyperlinks::set_hyperlinks_override(None);}@@ -626,17 +881,39 @@ fn bare_url_autolink_forms() {}#[test]-fn www_autolink_gains_scheme_and_legacy_suffix() {- // Legacy form: token.text != token.href for a www autolink, so the- // resolved href shows after the label (TS legacy branch).- crate::hyperlinks::set_hyperlinks_override(Some(false));+fn www_autolink_gains_scheme_and_shows_the_url_in_both_forms() {+ // A www autolink's href gains the scheme, so the target differs+ // from the label and the bracket shows in BOTH capability forms.let style = MarkdownStyle::default();+ crate::hyperlinks::set_hyperlinks_override(Some(false));let spans = render_inline("www.example.com/path", &style);let texts: Vec<&str> = spans.iter().map(|s| s.content.as_str()).collect();assert_eq!(texts,- vec!["www.example.com/path", " (http://www.example.com/path)"]+ vec!["www.example.com/path", " [http://www.example.com/path]"]+ );+ assert!(+ spans[0].style.add_modifier.contains(Modifier::UNDERLINED),+ "the legacy autolink label underlines"+ );+ assert_eq!(spans[1].style.fg, style.link_url.fg);+ crate::hyperlinks::set_hyperlinks_override(None);+ crate::hyperlinks::set_hyperlinks_override(Some(true));+ let spans = render_inline("www.example.com/path", &style);+ let joined: String = spans.iter().map(|s| s.content.as_str()).collect();+ assert_eq!(+ joined,+ format!(+ "{}www.example.com/path{} [http://www.example.com/path]",+ crate::hyperlinks::osc8_open("http://www.example.com/path"),+ crate::hyperlinks::OSC8_CLOSE+ )+ );+ assert!(+ spans[0].style.add_modifier.contains(Modifier::UNDERLINED),+ "the OSC 8 autolink label underlines");+ assert_eq!(spans[1].style.fg, style.link_url.fg);crate::hyperlinks::set_hyperlinks_override(None);}@@ -701,7 +978,7 @@ fn bare_url_is_not_autolinked_inside_a_link_label() {let style = MarkdownStyle::default();let spans = render_inline("[see https://in.dev/x](https://out.dev/y)", &style);let texts: Vec<&str> = spans.iter().map(|s| s.content.as_str()).collect();- assert_eq!(texts, vec!["see https://in.dev/x", " (https://out.dev/y)"]);+ assert_eq!(texts, vec!["see https://in.dev/x", " [https://out.dev/y]"]);crate::hyperlinks::set_hyperlinks_override(None);}diff --git a/crates/pa-tui/tests/replay_tables.rs b/crates/pa-tui/tests/replay_tables.rsindex 2856f527f2..3e327f933c 100644--- a/crates/pa-tui/tests/replay_tables.rs+++ b/crates/pa-tui/tests/replay_tables.rs@@ -1,5 +1,5 @@//! Replay-path markdown rendering: a session with a table and links renders-//! the same box/table rows and the legacy `label (url)` link form the live+//! the same box/table rows and the legacy `label [url]` link form the live//! path shows (the TS product under a plain tmux pane renders links the//! same way: the terminal-capability gate forces the legacy form there).// Pedantic-gate exceptions (every other pedantic warning in this crate is@@ -75,14 +75,15 @@ fn replayed_table_renders_boxed_aligned_rows() {flat.contains("└───────────┴─────────┴───────────────────┘"),"bottom border: {flat}");- // Links render the legacy form under the gate (tmux parity).+ // Links render the legacy observability form under the gate (tmux+ // parity): the label, then the bracketed URL in the dim slot.assert!(- flat.contains("docs (https://example.com/docs)"),+ flat.contains("docs [https://example.com/docs]"),"link row: {flat}");// The second link wraps mid-row at this width, so only its URL tail// stays contiguous.- assert!(flat.contains("example.com/log)"), "link row 2: {flat}");+ assert!(flat.contains("example.com/log]"), "link row 2: {flat}");}#[test]