From d5a478e31c3296e544d53424a7a6c995e7dfb0f5 Mon Sep 17 00:00:00 2001 From: Felipe Coury Date: Mon, 16 Nov 2026 20:40:25 +0000 Subject: [PATCH] Preserve local Markdown document targets in transcript rendering (#61880) ## What changed Retain eligible local `.md` and `.markdown` link targets as document metadata and allow transcript hit testing to resolve them when `document_links` is enabled. The flag defaults to disabled, and document targets are excluded from terminal OSC-8 links. Preserve link metadata through narrow table layouts, account for grapheme widths when remapping header links, and retain literal backslashes in POSIX file URI targets. Keep validated workspace artifact links usable as terminal hyperlinks. ## Testing Add regression coverage for opt-in document hit testing, narrow table link ranges, styled emoji and escaped pipes, POSIX file URI backslashes, and validated workspace artifact links. GitOrigin-RevId: e5d12c8558f5210eb66c17b5be8b28b7e80d414f --- .../tui/src/history_cell/messages_tests.rs | 14 ++ .../tui/src/history_cell/spoken_artifacts.rs | 11 +- codex-rs/tui/src/markdown_render.rs | 126 ++++++++++++------ .../tui/src/markdown_render/local_links.rs | 32 ++++- .../src/markdown_render/table_key_value.rs | 119 ++++++++--------- codex-rs/tui/src/markdown_render_tests.rs | 85 ++++++++++++ codex-rs/tui/src/terminal_hyperlinks.rs | 23 ++++ codex-rs/tui/src/transcript_view.rs | 2 + codex-rs/tui/src/transcript_view/input.rs | 4 +- codex-rs/tui/src/transcript_view/text.rs | 6 +- .../src/transcript_view/text_tabs_tests.rs | 16 ++- .../tui/src/transcript_view/text_tests.rs | 42 +++++- codex-rs/tui/src/width.rs | 12 -- 13 files changed, 359 insertions(+), 133 deletions(-) diff --git a/codex-rs/tui/src/history_cell/messages_tests.rs b/codex-rs/tui/src/history_cell/messages_tests.rs index 2ce4062a3d..1f4cd71a39 100644 --- a/codex-rs/tui/src/history_cell/messages_tests.rs +++ b/codex-rs/tui/src/history_cell/messages_tests.rs @@ -403,6 +403,20 @@ fn spoken_artifacts_link_only_real_workspace_files_and_preserve_existing_urls() ordinary.display_hyperlink_lines(/*width*/ 90)[0].hyperlinks[0].destination, "https://example.com" ); + let report = workspace.path().join("report.md"); + std::fs::write(&report, "# Report").expect("report file"); + let linked = AgentMarkdownCell::new_spoken("[Report](report.md)".into(), workspace.path()); + let expected = url::Url::from_file_path(report.canonicalize().expect("canonical report")) + .expect("workspace file URL") + .to_string(); + assert_eq!( + linked.display_hyperlink_lines(/*width*/ 90)[0] + .hyperlinks + .iter() + .filter_map(crate::terminal_hyperlinks::TerminalHyperlink::terminal_destination) + .collect::>(), + vec![expected], + ); let bare = AgentMarkdownCell::new_spoken("src/lib.rs".to_string(), workspace.path()); assert_eq!( bare.display_hyperlink_lines(/*width*/ 40)[0] diff --git a/codex-rs/tui/src/history_cell/spoken_artifacts.rs b/codex-rs/tui/src/history_cell/spoken_artifacts.rs index c44cb43c7f..9e4ecd1bf9 100644 --- a/codex-rs/tui/src/history_cell/spoken_artifacts.rs +++ b/codex-rs/tui/src/history_cell/spoken_artifacts.rs @@ -56,11 +56,18 @@ pub(super) fn annotate_spoken_artifacts(lines: &mut [HyperlinkLine], cwd: &Path) let byte_start = token_start + token.len() - leading.len(); let byte_end = byte_start + candidate.len(); let columns = display_width(&text[..byte_start])..display_width(&text[..byte_end]); - if line.hyperlinks.iter().any(|existing| { + let overlaps = |existing: &TerminalHyperlink| { existing.columns.start < columns.end && columns.start < existing.columns.end - }) { + }; + if line + .hyperlinks + .iter() + .any(|existing| !existing.is_document() && overlaps(existing)) + { continue; } + line.hyperlinks + .retain(|existing| !existing.is_document() || !overlaps(existing)); line.hyperlinks .push(TerminalHyperlink::trusted_workspace_file(columns, file)); if let Some(source) = &line.source { diff --git a/codex-rs/tui/src/markdown_render.rs b/codex-rs/tui/src/markdown_render.rs index 242f472e10..82e9f274cf 100644 --- a/codex-rs/tui/src/markdown_render.rs +++ b/codex-rs/tui/src/markdown_render.rs @@ -52,11 +52,11 @@ use crate::render::line_utils::line_to_static; use crate::style::accent_color; use crate::style::table_separator_style; use crate::terminal_hyperlinks::HyperlinkLine; +use crate::terminal_hyperlinks::TerminalHyperlink; use crate::terminal_hyperlinks::remap_wrapped_line; use crate::terminal_hyperlinks::source_span_width; use crate::terminal_hyperlinks::visible_lines; use crate::terminal_hyperlinks::web_destination; -use crate::width::char_width; use crate::width::display_width; use crate::wrapping::RtOptions; use crate::wrapping::word_wrap_line; @@ -76,6 +76,7 @@ use ratatui::text::Text; use std::ops::Range; use std::path::Path; use std::path::PathBuf; +use unicode_segmentation::UnicodeSegmentation; mod inline_directives; mod list_spacing; @@ -2016,14 +2017,17 @@ impl<'a, 'policy> Writer<'a, 'policy> { let mut out = HyperlinkLine::new(Line::default()); let mut copy = None; let mut byte_offset = 1; + let mut output_column = 1; out.push_span("|".into(), /*destination*/ None); for cell in row { out.push_span(" ".into(), /*destination*/ None); byte_offset += 1; + output_column += 1; for (index, line) in cell.lines.iter().enumerate() { if index > 0 { out.push_span(" ".into(), /*destination*/ None); byte_offset += 1; + output_column += 1; } let text = line .line @@ -2031,43 +2035,78 @@ impl<'a, 'policy> Writer<'a, 'policy> { .iter() .map(|span| span.content.as_ref()) .collect::(); - let mut column = 0usize; - let mut current_destination = None; + // Link ranges count graphemes within each original span. Flattening + // the line can join graphemes across style boundaries. + let mut source_graphemes = line + .line + .spans + .iter() + .flat_map(|span| span.content.graphemes(/*is_extended*/ true)) + .peekable(); + let mut source_byte = 0; + let mut source_column = 0; + let mut current_link = None; + let mut run_start = output_column; let mut current_text = String::new(); let flush = |out: &mut HyperlinkLine, current_text: &mut String, - destination: Option<&str>| { - if !current_text.is_empty() { - out.push_span(Span::raw(std::mem::take(current_text)), destination); + link: Option<&TerminalHyperlink>, + columns: std::ops::Range| { + if current_text.is_empty() { + return; + } + let span = Span::raw(std::mem::take(current_text)); + out.push_span(span, /*destination*/ None); + if let Some(link) = link + && !columns.is_empty() + { + out.hyperlinks.push(link.with_columns(columns)); } }; - for (byte, ch) in text.char_indices() { - let destination = line + for (byte, grapheme) in text.grapheme_indices(/*is_extended*/ true) { + while let Some(source) = + source_graphemes.next_if(|source| source_byte + source.len() <= byte) + { + source_byte += source.len(); + source_column += display_width(source); + } + let link = line .hyperlinks .iter() - .find(|link| link.columns.contains(&column)) - .map(|link| link.destination.as_str()); - if destination != current_destination { - flush(&mut out, &mut current_text, current_destination); - current_destination = destination; + .find(|link| link.columns.contains(&source_column)); + if link != current_link { + flush( + &mut out, + &mut current_text, + current_link, + run_start..output_column, + ); + current_link = link; + run_start = output_column; } - if ch == '|' { - current_text.push_str("\\|"); + if grapheme.starts_with('|') { + current_text.push('\\'); byte_offset += 1; - } else { - current_text.push(ch); + output_column += 1; } + current_text.push_str(grapheme); if let Some(mut source) = line.source.clone() { - source.range = byte..byte + ch.len_utf8(); + source.range = byte..byte + grapheme.len(); crate::markdown_copy::table::append(&mut copy, &source, byte_offset); } - byte_offset += ch.len_utf8(); - column += char_width(ch); + byte_offset += grapheme.len(); + output_column += display_width(grapheme); } - flush(&mut out, &mut current_text, current_destination); + flush( + &mut out, + &mut current_text, + current_link, + run_start..output_column, + ); } out.push_span(" |".into(), /*destination*/ None); byte_offset += 2; + output_column += 2; } crate::markdown_copy::table::attach(&mut out, copy); out @@ -2297,27 +2336,14 @@ impl<'a, 'policy> Writer<'a, 'policy> { // Link destinations are rendered as " (url)" suffixes. When parsing table cells, // append the suffix into the active cell buffer rather than the outer paragraph // line to avoid detached url lines. + let span = Span::styled(link.destination.clone(), self.styles.link); if self.in_table_cell() { self.push_span_to_table_cell(" (".into()); - let mut destination = HyperlinkLine::new(Line::default()); - destination.push_span( - Span::styled(link.destination.clone(), self.styles.link), - web_destination(&link.destination).as_deref(), - ); - if let Some(table_state) = self.table_state.as_mut() - && let Some(cell) = table_state.current_cell.as_mut() - { - cell.push_annotated(destination, &self.copy_inline); - } + self.push_link_target(span, &link.destination); self.push_span_to_table_cell(")".into()); } else { self.push_span(" (".into()); - let mut destination = HyperlinkLine::new(Line::default()); - destination.push_span( - Span::styled(link.destination.clone(), self.styles.link), - web_destination(&link.destination).as_deref(), - ); - self.push_annotated(destination); + self.push_link_target(span, &link.destination); self.push_span(")".into()); } } else if let Some(local_target_display) = link.local_target_display { @@ -2346,7 +2372,7 @@ impl<'a, 'policy> Writer<'a, 'policy> { self.push_span_to_table_cell(" (".into()); } self.copy_inline.push(crate::markdown_copy::Inline::Literal); - self.push_span_to_table_cell(span); + self.push_link_target(span, &link.destination); self.copy_inline.pop(); if show_label { self.push_span_to_table_cell(")".into()); @@ -2368,7 +2394,7 @@ impl<'a, 'policy> Writer<'a, 'policy> { self.push_span(" (".into()); } self.copy_inline.push(crate::markdown_copy::Inline::Literal); - self.push_span(span); + self.push_link_target(span, &link.destination); self.copy_inline.pop(); if show_label { self.push_span(")".into()); @@ -2379,6 +2405,28 @@ impl<'a, 'policy> Writer<'a, 'policy> { } } + fn push_link_target(&mut self, span: Span<'static>, destination: &str) { + let mut target = HyperlinkLine::default(); + if let Some(path) = local_links::sidebar_file_link(destination) { + let width = span_width(&span); + target.line.push_span(span); + target + .hyperlinks + .push(TerminalHyperlink::document(0..width, path)); + } else { + target.push_span(span, Some(destination)); + } + if let Some(cell) = self + .table_state + .as_mut() + .and_then(|table| table.current_cell.as_mut()) + { + cell.push_annotated(target, &self.copy_inline); + } else { + self.push_annotated(target); + } + } + fn collecting_local_link_label(&self) -> bool { self.link .as_ref() diff --git a/codex-rs/tui/src/markdown_render/local_links.rs b/codex-rs/tui/src/markdown_render/local_links.rs index 70c30b763d..6ff2f30e6a 100644 --- a/codex-rs/tui/src/markdown_render/local_links.rs +++ b/codex-rs/tui/src/markdown_render/local_links.rs @@ -5,6 +5,7 @@ //! relative to the session working directory when possible. This module only formats destinations; //! it does not resolve files or infer execution-host paths from the frontend filesystem. +use codex_utils_path_uri::PathConvention; use codex_utils_path_uri::PathUri; use codex_utils_string::normalize_markdown_hash_location_suffix; use regex_lite::Regex; @@ -26,6 +27,26 @@ static HASH_LOCATION_SUFFIX_RE: LazyLock = Err(error) => panic!("invalid hash location regex: {error}"), }); +pub(crate) fn sidebar_file_link(destination: &str) -> Option { + if destination.len() > 8192 || destination.contains(['#', '?']) { + return None; + } + if destination.starts_with("file://") && Url::parse(destination).ok()?.has_host() { + return None; + } + let (path, location) = parse_local_link_target(destination)?; + let extension = path.rsplit_once('.')?.1; + (location.is_none() + && (extension.eq_ignore_ascii_case("md") || extension.eq_ignore_ascii_case("markdown")) + && path.len() <= 4096 + && !path.starts_with('~') + && !path.starts_with("//") + && !path.chars().any(char::is_control) + && (is_absolute_local_link_path(&path) || Url::parse(&path).is_err()) + && (is_local_path_like_link(destination) || Url::parse(destination).is_err())) + .then_some(path) +} + pub(super) fn is_local_path_like_link(dest_url: &str) -> bool { dest_url.starts_with("file://") || dest_url.starts_with('/') @@ -56,8 +77,8 @@ pub(super) fn render_local_link_target(dest_url: &str, cwd: Option<&Path>) -> Op /// Split a local-link destination into `(normalized_path_text, location_suffix)`. /// /// The returned path text never includes a trailing `#L..` or `:line[:col]` suffix. Path -/// normalization preserves `~/...` and rewrites path separators into display-stable forward -/// slashes. The suffix, when present, is returned separately in normalized markdown form. +/// normalization preserves home-relative paths and uses forward slashes as separators. +/// A backslash in a POSIX file URI is part of the filename and is preserved. /// /// Returns `None` only when the destination looks like a `file://` URL but cannot be parsed into a /// local path. Plain path-like inputs always return `Some(...)` even if they are relative. @@ -66,7 +87,12 @@ fn parse_local_link_target(dest_url: &str) -> Option<(String, Option)> { let url = Url::parse(dest_url).ok()?; // Infer the path's OS from the URI, not the host running the TUI. let path = PathUri::parse(&url[..url::Position::AfterPath]).ok()?; - let path_text = normalize_local_link_path_text(&path.inferred_native_path_string()); + let native_path = path.inferred_native_path_string(); + let path_text = if path.infer_path_convention() == Some(PathConvention::Posix) { + native_path + } else { + normalize_local_link_path_text(&native_path) + }; let location_suffix = url .fragment() .and_then(normalize_hash_location_suffix_fragment); diff --git a/codex-rs/tui/src/markdown_render/table_key_value.rs b/codex-rs/tui/src/markdown_render/table_key_value.rs index 303c7d44e0..03a429119c 100644 --- a/codex-rs/tui/src/markdown_render/table_key_value.rs +++ b/codex-rs/tui/src/markdown_render/table_key_value.rs @@ -173,23 +173,15 @@ fn render_aligned_field( .unwrap_or_else(|| cell_width(value).max(MIN_VALUE_WIDTH)); let wrapped_value = wrap_cell(value, value_width); for (line_index, value_line) in wrapped_value.into_iter().enumerate() { - let mut spans = Vec::new(); - let mut copy = None; - if line_index == 0 { - let label = header.plain_text(); - let label_source = label_line(header, label_style); - if let Some(source) = &label_source.source { - crate::markdown_copy::table::append(&mut copy, source, FIELD_LEADING_PADDING); - } - spans.push(Span::raw(" ".repeat(FIELD_LEADING_PADDING))); - spans.push(Span::styled(label.clone(), label_style)); - spans.push(Span::raw(" ".repeat( - label_width.saturating_sub(display_width(&label)) + FIELD_GAP, - ))); + let prefix = if line_index == 0 { + let mut label = label_line(header, label_style); + let padding = label_width.saturating_sub(label.source_width()) + FIELD_GAP; + label.line.push_span(Span::raw(" ".repeat(padding))); + prefix_line(" ".repeat(FIELD_LEADING_PADDING).into(), label) } else { - spans.push(Span::raw(" ".repeat(value_indent))); - } - push_prefixed_value_line(out, spans, value_line, copy); + HyperlinkLine::new(Line::raw(" ".repeat(value_indent))) + }; + out.push(join_lines(prefix, value_line)); } } @@ -210,74 +202,69 @@ fn render_stacked_field( &mut wrapped_labels, ); for label_line in remap_wrapped_line(&label, wrapped_labels) { - let mut spans = vec![Span::raw(" ".repeat(FIELD_LEADING_PADDING))]; - let mut copy = None; - if let Some(source) = &label_line.source { - crate::markdown_copy::table::append(&mut copy, source, FIELD_LEADING_PADDING); - } - spans.extend(label_line.line.spans); - let mut line = HyperlinkLine::new(Line::from(spans)); - crate::markdown_copy::table::attach(&mut line, copy); - out.push(line); + out.push(prefix_line( + " ".repeat(FIELD_LEADING_PADDING).into(), + label_line, + )); } let value_width = available_width .map(|width| width.saturating_sub(STACKED_VALUE_INDENT).max(1)) .unwrap_or_else(|| cell_width(value).max(1)); for value_line in wrap_cell(value, value_width) { - push_prefixed_value_line( - out, - vec![Span::raw(" ".repeat(STACKED_VALUE_INDENT))], + out.push(prefix_line( + " ".repeat(STACKED_VALUE_INDENT).into(), value_line, - /*copy*/ None, - ); + )); } } -fn push_prefixed_value_line( - out: &mut Vec, - mut prefix: Vec>, - mut value_line: HyperlinkLine, - mut copy: Option, -) { - let bytes = prefix.iter().map(|span| span.content.len()).sum(); - if let Some(source) = &value_line.source { - crate::markdown_copy::table::append(&mut copy, source, bytes); - } - let shift = prefix - .iter() - .map(|span| display_width(span.content.as_ref())) - .sum::(); - prefix.append(&mut value_line.line.spans); - let mut output_line = HyperlinkLine::new(Line::from(prefix)); - crate::markdown_copy::table::attach(&mut output_line, copy); - output_line - .hyperlinks - .extend(value_line.hyperlinks.into_iter().map(|mut link| { - link.columns = link.columns.start + shift..link.columns.end + shift; - link - })); - out.push(output_line); +fn prefix_line(prefix: Span<'static>, line: HyperlinkLine) -> HyperlinkLine { + join_lines(HyperlinkLine::new(Line::from(prefix)), line) } -fn label_line(header: &TableCell, style: Style) -> HyperlinkLine { - let mut line = HyperlinkLine::new(Line::from(Span::styled(header.plain_text(), style))); +fn join_lines(mut prefix: HyperlinkLine, mut line: HyperlinkLine) -> HyperlinkLine { let mut copy = None; - let mut offset = 0; - for header_line in &header.lines { - if let Some(source) = &header_line.source { - crate::markdown_copy::table::append(&mut copy, source, offset); - } - offset += header_line + if let Some(source) = &prefix.source { + crate::markdown_copy::table::append(&mut copy, source, /*offset*/ 0); + } + if let Some(source) = &line.source { + let bytes = prefix .line .spans .iter() .map(|span| span.content.len()) - .sum::() - + 1; + .sum(); + crate::markdown_copy::table::append(&mut copy, source, bytes); } - crate::markdown_copy::table::attach(&mut line, copy); - line + let shift = prefix.source_width(); + prefix.line.spans.append(&mut line.line.spans); + prefix + .hyperlinks + .extend(line.hyperlinks.into_iter().map(|mut link| { + link.columns = link.columns.start + shift..link.columns.end + shift; + link + })); + crate::markdown_copy::table::attach(&mut prefix, copy); + prefix +} + +fn label_line(header: &TableCell, style: Style) -> HyperlinkLine { + let mut label = HyperlinkLine::new(Line::default()); + for (index, line) in header.lines.iter().enumerate() { + if index > 0 { + label.line.push_span(Span::raw(" ")); + } + label = join_lines(label, line.clone()); + } + if label.hyperlinks.is_empty() { + label.line = Line::from(Span::styled(header.plain_text(), style)); + } else { + for span in &mut label.line.spans { + span.style = style; + } + } + label } fn wrap_cell(cell: &TableCell, width: usize) -> Vec { diff --git a/codex-rs/tui/src/markdown_render_tests.rs b/codex-rs/tui/src/markdown_render_tests.rs index 998e7d2d18..a1e1ca58a1 100644 --- a/codex-rs/tui/src/markdown_render_tests.rs +++ b/codex-rs/tui/src/markdown_render_tests.rs @@ -2186,3 +2186,88 @@ fn table_key_value_fallback_preserves_rich_values_and_themed_labels() { .any(|span| span.style.add_modifier.contains(Modifier::UNDERLINED)) })); } + +#[test] +fn narrow_header_only_table_retains_local_file_target() { + let rendered = render_markdown_lines_with_width_and_cwd( + "| 👩‍💻 [Guide](./guide.md) | A | B | C | D | E |\n| --- | --- | --- | --- | --- | --- |", + Some(32), + /*cwd*/ None, + ); + let first = &rendered[0]; + let text = first.line.to_string(); + assert!(text.starts_with("| 👩‍💻"), "{text}"); + let (before, _) = text.split_once("./guide.md").expect("visible file path"); + let column = crate::width::display_width(before); + let links = first + .hyperlinks + .iter() + .map(|link| { + ( + link.columns.clone(), + link.destination.as_str(), + link.terminal_destination(), + ) + }) + .collect::>(); + assert_eq!( + links, + vec![(column..column + "./guide.md".len(), "./guide.md", None)] + ); +} + +#[test] +fn narrow_header_only_table_preserves_link_columns_and_escaped_pipes() { + let rendered = super::render_markdown_lines_with_width_cwd_and_hidden_link_destinations( + "| 👩**‍💻** [Docs](https://example.com) | x\\|́y | B | C | D | E |\n| --- | --- | --- | --- | --- | --- |", + Some(/*width*/ 32), + /*cwd*/ None, + &|_| true, + ); + let first = &rendered[0]; + assert!(first.line.to_string().contains("x\\|́y")); + assert_eq!( + first + .hyperlinks + .iter() + .map(|link| (link.columns.clone(), link.destination.as_str())) + .collect::>(), + vec![(5..9, "https://example.com")] + ); +} + +#[test] +fn narrow_table_record_labels_keep_local_file_targets() { + let markdown = "| [Guide](./guide.md) | A | B | C | D | E | F | G |\n| --- | --- | --- | --- | --- | --- | --- | --- |\n| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |"; + for width in [20, 50] { + let rendered = + render_markdown_lines_with_width_and_cwd(markdown, Some(width), /*cwd*/ None); + let first = &rendered[0]; + let text = first.line.to_string(); + assert!(text.starts_with(" Guide"), "{text}"); + let (before, _) = text.split_once("./guide.md").expect("visible file path"); + let column = crate::width::display_width(before); + assert_eq!( + first + .hyperlinks + .iter() + .map(|link| (link.columns.clone(), link.destination.as_str())) + .collect::>(), + vec![(column..column + "./guide.md".len(), "./guide.md")], + ); + } +} + +#[test] +fn posix_file_uri_keeps_literal_backslash_in_preview_target() { + let rendered = render_markdown_lines_with_width_and_cwd( + "[Guide](file:///tmp/Guide%5Cnotes.md)", + /*width*/ None, + /*cwd*/ None, + ); + assert!(rendered[0].line.to_string().contains("/tmp/Guide/notes.md")); + assert_eq!( + rendered[0].hyperlinks[0].destination, + r"/tmp/Guide\notes.md" + ); +} diff --git a/codex-rs/tui/src/terminal_hyperlinks.rs b/codex-rs/tui/src/terminal_hyperlinks.rs index 9d4ef7c0ab..d875bc6a54 100644 --- a/codex-rs/tui/src/terminal_hyperlinks.rs +++ b/codex-rs/tui/src/terminal_hyperlinks.rs @@ -53,6 +53,8 @@ enum DestinationKind { Web, /// A generated visualization, validated workspace artifact, or locally viewed image. TrustedFile, + /// A local document target used only by an enabled workspace transcript. + Document, } /// An existing, inert source file proven to remain inside its session workspace. @@ -158,6 +160,26 @@ impl TerminalHyperlink { } } + pub(crate) fn document(columns: Range, path: String) -> Self { + Self { + columns, + destination: path, + destination_kind: DestinationKind::Document, + } + } + + pub(crate) fn is_document(&self) -> bool { + self.destination_kind == DestinationKind::Document + } + + pub(crate) fn reader_destination(&self, documents: bool) -> Option { + if documents && self.is_document() { + Some(self.destination.clone()) + } else { + self.terminal_destination() + } + } + pub(crate) fn with_columns(&self, columns: Range) -> Self { Self { columns, @@ -168,6 +190,7 @@ impl TerminalHyperlink { pub(crate) fn terminal_destination(&self) -> Option { match self.destination_kind { + DestinationKind::Document => None, DestinationKind::Web => web_destination(&self.destination), DestinationKind::TrustedFile => trusted_file_destination(&self.destination), } diff --git a/codex-rs/tui/src/transcript_view.rs b/codex-rs/tui/src/transcript_view.rs index fa7f333132..fa384afc32 100644 --- a/codex-rs/tui/src/transcript_view.rs +++ b/codex-rs/tui/src/transcript_view.rs @@ -91,6 +91,7 @@ struct VisibleRow { /// Shared scrolling and interaction state for compact and detailed transcript presentations. pub(crate) struct TranscriptView { pub(crate) image_protocol: Option, + pub(crate) document_links: bool, pub(crate) mouse_scroll_speed: f64, pending_mouse_scroll: f64, pub(crate) copy_on_select: bool, @@ -132,6 +133,7 @@ impl Default for TranscriptView { fn default() -> Self { Self { image_protocol: None, + document_links: false, mouse_scroll_speed: 1.0, pending_mouse_scroll: 0.0, copy_on_select: false, diff --git a/codex-rs/tui/src/transcript_view/input.rs b/codex-rs/tui/src/transcript_view/input.rs index 015f0342cf..b08b365a07 100644 --- a/codex-rs/tui/src/transcript_view/input.rs +++ b/codex-rs/tui/src/transcript_view/input.rs @@ -116,7 +116,9 @@ impl TranscriptView { return None; } let visible = self.visible.get(usize::from(row - self.area.y))?; - visible.layout.link_at(visible.row, column - self.area.x) + visible + .layout + .link_at(visible.row, column - self.area.x, self.document_links) } pub(crate) fn navigate_pager( diff --git a/codex-rs/tui/src/transcript_view/text.rs b/codex-rs/tui/src/transcript_view/text.rs index 01d38d3377..be983c8b8f 100644 --- a/codex-rs/tui/src/transcript_view/text.rs +++ b/codex-rs/tui/src/transcript_view/text.rs @@ -847,15 +847,15 @@ impl TextLayout { } } - /// Resolve the displayed link using the same destination policy as terminal OSC-8 output. - pub(super) fn link_at(&self, row: usize, column: u16) -> Option { + /// Resolve an OSC-8 destination or a document target when the workspace enables previews. + pub(super) fn link_at(&self, row: usize, column: u16, documents: bool) -> Option { let row = self.rows.get(row)?; let column = usize::from(column).checked_sub(row.first_column - row.prefix_columns)?; row.line .hyperlinks .iter() .find(|link| link.columns.contains(&column))? - .terminal_destination() + .reader_destination(documents) } fn visible_rows(&self, area: Rect, start_row: usize) -> impl Iterator { diff --git a/codex-rs/tui/src/transcript_view/text_tabs_tests.rs b/codex-rs/tui/src/transcript_view/text_tabs_tests.rs index 8d0168dee8..b6b84d3917 100644 --- a/codex-rs/tui/src/transcript_view/text_tabs_tests.rs +++ b/codex-rs/tui/src/transcript_view/text_tabs_tests.rs @@ -35,9 +35,15 @@ fn styled_tabs_use_row_stops_including_the_gutter() { ); assert_eq!( ( - layout.link_at(/*row*/ 0, /*column*/ 16).as_deref(), - layout.link_at(/*row*/ 0, /*column*/ 24).as_deref(), - layout.link_at(/*row*/ 0, /*column*/ 13).as_deref() + layout + .link_at(/*row*/ 0, /*column*/ 16, /*documents*/ false) + .as_deref(), + layout + .link_at(/*row*/ 0, /*column*/ 24, /*documents*/ false) + .as_deref(), + layout + .link_at(/*row*/ 0, /*column*/ 13, /*documents*/ false) + .as_deref() ), ( Some("https://example.com/one"), @@ -87,7 +93,9 @@ fn tab_stops_restart_after_wrapping_and_resize_preserves_source_and_links() { [(1, 3), (1, 8), (2, 2)], ); assert_eq!( - layout.link_at(/*row*/ 1, /*column*/ 8).as_deref(), + layout + .link_at(/*row*/ 1, /*column*/ 8, /*documents*/ false) + .as_deref(), Some("https://example.com/x") ); let wide = layout.rewrap(/*width*/ 40); diff --git a/codex-rs/tui/src/transcript_view/text_tests.rs b/codex-rs/tui/src/transcript_view/text_tests.rs index e017b13007..e8da56b51a 100644 --- a/codex-rs/tui/src/transcript_view/text_tests.rs +++ b/codex-rs/tui/src/transcript_view/text_tests.rs @@ -191,9 +191,14 @@ fn aligned_text_excludes_synthetic_leading_columns() { let mut line = HyperlinkLine::new(Line::default().right_aligned()); line.push_span("wide".into(), Some("https://example.com")); let layout = TextLayout::new(vec![line], /*width*/ 8); - assert_eq!(layout.link_at(/*row*/ 0, /*column*/ 3), None); assert_eq!( - layout.link_at(/*row*/ 0, /*column*/ 4).as_deref(), + layout.link_at(/*row*/ 0, /*column*/ 3, /*documents*/ false), + None + ); + assert_eq!( + layout + .link_at(/*row*/ 0, /*column*/ 4, /*documents*/ false) + .as_deref(), Some("https://example.com") ); assert_eq!( @@ -266,7 +271,8 @@ fn selected_revision_rewraps_both_directions_with_styles_and_indents() { restored.render(narrow_area, &mut restored_buffer, /*start_row*/ 0); assert_eq!(restored_buffer, original_buffer); assert_eq!( - wide.link_at(/*row*/ 0, /*column*/ 8).as_deref(), + wide.link_at(/*row*/ 0, /*column*/ 8, /*documents*/ false) + .as_deref(), Some("https://example.com") ); } @@ -419,3 +425,33 @@ fn background_stdin_copy_preserves_indentation_and_newlines() { assert!(layout.text().ends_with(stdin)); assert_eq!(layout.rewrap(/*width*/ 48).text(), layout.text()); } + +#[test] +fn rendered_markdown_file_targets_are_only_interactive_in_the_workspace() { + let markdown = "[Guide](./guide.md)\n\n| File |\n| --- |\n| [Notes](./notes.md) |"; + let lines = crate::markdown_render::render_markdown_lines_with_width_and_cwd( + markdown, + Some(40), + /*cwd*/ None, + ); + assert!( + lines + .iter() + .flat_map(|line| &line.hyperlinks) + .all(|link| link.terminal_destination().is_none()) + ); + let layout = TextLayout::new(lines, /*width*/ 40); + let destinations = |documents| { + let layout = &layout; + (0..layout.row_count()) + .flat_map(|row| { + (0..40).filter_map(move |column| layout.link_at(row, column, documents)) + }) + .collect::>() + }; + assert_eq!(destinations(false), std::collections::BTreeSet::new()); + assert_eq!( + destinations(true), + ["./guide.md".to_owned(), "./notes.md".to_owned()].into() + ); +} diff --git a/codex-rs/tui/src/width.rs b/codex-rs/tui/src/width.rs index 9c9fe3e55d..ba46928faa 100644 --- a/codex-rs/tui/src/width.rs +++ b/codex-rs/tui/src/width.rs @@ -12,7 +12,6 @@ //! fallback" rather than attempting wrapped rendering at zero width, which //! would produce empty or unstable output. -use unicode_width::UnicodeWidthChar; use unicode_width::UnicodeWidthStr; /// Returns the display width Ratatui uses for terminal text without its `u16` limit. @@ -24,15 +23,6 @@ pub(crate) fn display_width(text: &str) -> usize { .count() } -/// Returns a scalar's terminal width, treating halfwidth sound marks as visible cells. -pub(crate) fn char_width(ch: char) -> usize { - if matches!(ch, '\u{FF9E}' | '\u{FF9F}') { - 1 - } else { - UnicodeWidthChar::width(ch).unwrap_or(0) - } -} - /// Returns usable content width after reserving fixed columns. /// /// Guarantees a strict positive width (`Some(n)` where `n > 0`) or `None` when @@ -67,8 +57,6 @@ mod tests { assert_eq!(display_width("ガパ"), 4); assert_eq!(display_width("ガ゙"), 3); assert_eq!(display_width("界゙"), 3); - assert_eq!(char_width('\u{FF9E}'), 1); - assert_eq!(char_width('\u{FF9F}'), 1); let text = "a".repeat(65_536); assert_eq!(display_width(&text), 65_536);