mirror of
https://github.com/openai/codex.git
synced 2026-11-23 23:10:47 +00:00
## What changed - Open PNG, JPEG, GIF, and WebP file links as sidebar image previews, fitted to the available space with format and dimension labels. Show a fallback when terminal graphics are unavailable, and preserve text previews for files such as Git LFS pointers. - In the owned transcript, place completed, saved image results after the assistant's answer, with larger, left-aligned previews and a clickable `Generated image` label. Preserve this ordering during replay and history pagination, including interrupted turns. - Reuse native Kitty image IDs and move existing placements without retransmitting their pixels. Probe Kitty graphics support in `herdr` before enabling previews. ## Testing Add regression coverage for sidebar preview fallbacks, generated-image ordering, pagination and search, preview layout, Kitty placement reuse, and graphics probe replies interleaved with pasted input. GitOrigin-RevId: 22d8aa2724f17bfa7f8280a2d11d4a7e2cb66728
272 lines
11 KiB
Rust
272 lines
11 KiB
Rust
//! Local file-link destination parsing and display for Markdown transcripts.
|
||
//!
|
||
//! Local Markdown links preserve their labels. Since ordinary file destinations have no trusted
|
||
//! navigation capability, the renderer also displays their target, shortening absolute paths
|
||
//! 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;
|
||
use std::path::Path;
|
||
use std::sync::LazyLock;
|
||
use url::Url;
|
||
|
||
static COLON_LOCATION_SUFFIX_RE: LazyLock<Regex> =
|
||
LazyLock::new(
|
||
|| match Regex::new(r":\d+(?::\d+)?(?:[-–]\d+(?::\d+)?)?$") {
|
||
Ok(regex) => regex,
|
||
Err(error) => panic!("invalid location suffix regex: {error}"),
|
||
},
|
||
);
|
||
|
||
static HASH_LOCATION_SUFFIX_RE: LazyLock<Regex> =
|
||
LazyLock::new(|| match Regex::new(r"^L\d+(?:C\d+)?(?:-L\d+(?:C\d+)?)?$") {
|
||
Ok(regex) => regex,
|
||
Err(error) => panic!("invalid hash location regex: {error}"),
|
||
});
|
||
|
||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||
pub(crate) struct SourceLocation {
|
||
pub(crate) line: usize,
|
||
pub(crate) column: usize,
|
||
}
|
||
|
||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||
pub(crate) struct FileLink {
|
||
pub(crate) path: String,
|
||
pub(crate) location: Option<SourceLocation>,
|
||
}
|
||
|
||
impl FileLink {
|
||
pub(crate) fn is_image(&self) -> bool {
|
||
self.location.is_none() && crate::sidebar_image::supports_path(&self.path)
|
||
}
|
||
}
|
||
|
||
pub(crate) fn is_markdown_file(path: &str) -> bool {
|
||
path.rsplit_once('.').is_some_and(|(_, ext)| {
|
||
ext.eq_ignore_ascii_case("md") || ext.eq_ignore_ascii_case("markdown")
|
||
})
|
||
}
|
||
|
||
pub(crate) fn sidebar_file_link(destination: &str) -> Option<FileLink> {
|
||
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)?;
|
||
if destination.contains('#') && location.is_none() {
|
||
return None;
|
||
}
|
||
let location = if let Some(suffix) = location {
|
||
let start = suffix.strip_prefix(':')?.split(['-', '–']).next()?;
|
||
let (line, column) = start.split_once(':').unwrap_or((start, "1"));
|
||
Some(SourceLocation {
|
||
line: line.parse::<usize>().ok()?.max(1),
|
||
column: column.parse::<usize>().ok()?.max(1),
|
||
})
|
||
} else {
|
||
None
|
||
};
|
||
(!path.is_empty()
|
||
&& !path.ends_with('/')
|
||
&& 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()))
|
||
.then_some(FileLink { path, location })
|
||
}
|
||
|
||
pub(super) fn is_local_path_like_link(dest_url: &str) -> bool {
|
||
dest_url.starts_with("file://")
|
||
|| dest_url.starts_with('/')
|
||
|| dest_url.starts_with("~/")
|
||
|| dest_url.starts_with("./")
|
||
|| dest_url.starts_with("../")
|
||
|| dest_url.starts_with("\\\\")
|
||
|| matches!(
|
||
dest_url.as_bytes(),
|
||
[drive, b':', separator, ..]
|
||
if drive.is_ascii_alphabetic() && matches!(separator, b'/' | b'\\')
|
||
)
|
||
}
|
||
|
||
/// Parse a local link target into normalized path text plus an optional location suffix.
|
||
///
|
||
/// This accepts the path shapes Codex emits today: `file://` URLs, absolute and relative paths,
|
||
/// `~/...`, Windows paths, and `#L..C..` or `:line:col` suffixes.
|
||
pub(super) fn render_local_link_target(dest_url: &str, cwd: Option<&Path>) -> Option<String> {
|
||
let (path_text, location_suffix) = parse_local_link_target(dest_url)?;
|
||
let mut rendered = display_local_link_path(&path_text, cwd);
|
||
if let Some(location_suffix) = location_suffix {
|
||
rendered.push_str(&location_suffix);
|
||
}
|
||
Some(rendered)
|
||
}
|
||
|
||
/// 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 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.
|
||
fn parse_local_link_target(dest_url: &str) -> Option<(String, Option<String>)> {
|
||
if dest_url.starts_with("file://") {
|
||
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 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);
|
||
return Some((path_text, location_suffix));
|
||
}
|
||
|
||
let mut path_text = dest_url;
|
||
let mut location_suffix = None;
|
||
// Prefer `#L..` style fragments when both forms are present so URLs like `path#L10` do not
|
||
// get misparsed as a plain path ending in `:10`.
|
||
if let Some((candidate_path, fragment)) = dest_url.rsplit_once('#')
|
||
&& let Some(normalized) = normalize_hash_location_suffix_fragment(fragment)
|
||
{
|
||
path_text = candidate_path;
|
||
location_suffix = Some(normalized);
|
||
}
|
||
if location_suffix.is_none()
|
||
&& let Some(suffix) = extract_colon_location_suffix(path_text)
|
||
{
|
||
let path_len = path_text.len().saturating_sub(suffix.len());
|
||
path_text = &path_text[..path_len];
|
||
location_suffix = Some(suffix);
|
||
}
|
||
|
||
let decoded_path_text =
|
||
urlencoding::decode(path_text).unwrap_or(std::borrow::Cow::Borrowed(path_text));
|
||
Some((
|
||
normalize_local_link_path_text(&decoded_path_text),
|
||
location_suffix,
|
||
))
|
||
}
|
||
|
||
/// Normalize a hash fragment like `L12` or `L12C3-L14C9` into the display suffix we render.
|
||
///
|
||
/// Returns `None` for fragments that are not location references. This deliberately ignores other
|
||
/// `#...` fragments so non-location hashes stay part of the path text.
|
||
fn normalize_hash_location_suffix_fragment(fragment: &str) -> Option<String> {
|
||
HASH_LOCATION_SUFFIX_RE
|
||
.is_match(fragment)
|
||
.then(|| format!("#{fragment}"))
|
||
.and_then(|suffix| normalize_markdown_hash_location_suffix(&suffix))
|
||
}
|
||
|
||
/// Extract a trailing `:line`, `:line:col`, or range suffix from a plain path-like string.
|
||
///
|
||
/// The suffix must occur at the end of the input; embedded colons elsewhere in the path are left
|
||
/// alone. This is what keeps Windows drive letters like `C:/...` from being misread as locations.
|
||
pub(super) fn extract_colon_location_suffix(path_text: &str) -> Option<String> {
|
||
COLON_LOCATION_SUFFIX_RE
|
||
.find(path_text)
|
||
.filter(|matched| matched.end() == path_text.len())
|
||
.map(|matched| matched.as_str().to_string())
|
||
}
|
||
|
||
/// Normalize local-path text into the transcript display form.
|
||
///
|
||
/// Display normalization is intentionally lexical: it does not touch the filesystem, resolve
|
||
/// symlinks, or collapse `.` / `..`. It only converts separators to forward slashes and rewrites
|
||
/// UNC-style `\\\\server\\share` inputs into `//server/share` so later prefix checks operate on a
|
||
/// stable representation.
|
||
fn normalize_local_link_path_text(path_text: &str) -> String {
|
||
// Render all local link paths with forward slashes so display and prefix stripping are stable
|
||
// across mixed Windows and Unix-style inputs.
|
||
if let Some(rest) = path_text.strip_prefix("\\\\") {
|
||
format!("//{}", rest.replace('\\', "/").trim_start_matches('/'))
|
||
} else {
|
||
path_text.replace('\\', "/")
|
||
}
|
||
}
|
||
|
||
fn is_absolute_local_link_path(path_text: &str) -> bool {
|
||
path_text.starts_with('/')
|
||
|| path_text.starts_with("//")
|
||
|| matches!(
|
||
path_text.as_bytes(),
|
||
[drive, b':', b'/', ..] if drive.is_ascii_alphabetic()
|
||
)
|
||
}
|
||
|
||
/// Remove trailing separators from a local path without destroying root semantics.
|
||
///
|
||
/// Roots like `/`, `//`, and `C:/` stay intact so callers can still distinguish "the root itself"
|
||
/// from "a path under the root".
|
||
fn trim_trailing_local_path_separator(path_text: &str) -> &str {
|
||
if path_text == "/" || path_text == "//" {
|
||
return path_text;
|
||
}
|
||
if matches!(path_text.as_bytes(), [drive, b':', b'/'] if drive.is_ascii_alphabetic()) {
|
||
return path_text;
|
||
}
|
||
path_text.trim_end_matches('/')
|
||
}
|
||
|
||
/// Strip `cwd_text` from the start of `path_text` when `path_text` is strictly underneath it.
|
||
///
|
||
/// Returns the relative remainder without a leading slash. If the path equals the cwd exactly, this
|
||
/// returns `None` so callers can keep rendering the full path instead of collapsing it to an empty
|
||
/// string.
|
||
fn strip_local_path_prefix<'a>(path_text: &'a str, cwd_text: &str) -> Option<&'a str> {
|
||
let path_text = trim_trailing_local_path_separator(path_text);
|
||
let cwd_text = trim_trailing_local_path_separator(cwd_text);
|
||
if path_text == cwd_text {
|
||
return None;
|
||
}
|
||
|
||
// Treat filesystem roots specially so `/tmp/x` under `/` becomes `tmp/x` instead of being
|
||
// left unchanged by the generic prefix-stripping branch.
|
||
if cwd_text == "/" || cwd_text == "//" {
|
||
return path_text.strip_prefix('/');
|
||
}
|
||
|
||
path_text
|
||
.strip_prefix(cwd_text)
|
||
.and_then(|rest| rest.strip_prefix('/'))
|
||
}
|
||
|
||
/// Choose the visible path text for a local link after normalization.
|
||
///
|
||
/// Relative paths (including `~/...`) stay relative. Absolute paths prefer cwd-relative display
|
||
/// and otherwise stay absolute: the frontend home may differ from the execution host's home.
|
||
/// This is display logic only, not filesystem canonicalization.
|
||
fn display_local_link_path(path_text: &str, cwd: Option<&Path>) -> String {
|
||
let path_text = normalize_local_link_path_text(path_text);
|
||
if !is_absolute_local_link_path(&path_text) {
|
||
return path_text;
|
||
}
|
||
|
||
if let Some(cwd) = cwd {
|
||
// Only the session cwd is known to refer to the execution host.
|
||
let cwd_text = normalize_local_link_path_text(&cwd.to_string_lossy());
|
||
if let Some(stripped) = strip_local_path_prefix(&path_text, &cwd_text) {
|
||
return stripped.to_string();
|
||
}
|
||
}
|
||
|
||
path_text
|
||
}
|
||
|
||
#[cfg(test)]
|
||
#[path = "local_links_tests.rs"]
|
||
mod tests;
|