Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust
29.5 KB
Raw Blame
//! Terminal hyperlinks (OSC 8). Markdown retains label metadata even when
//! the capability decision selects a visible URL fallback, matching TS's
//! fullscreen backend and keeping in-app hit testing available. Other UI
//! surfaces may gate their link presentation on terminal capabilities.
//! The renderer embeds the
//! zero-width sequences in span content; `width` skips them, the ratatui
//! paint path strips them (`to_ratatui_line`), and [`HyperlinkWriter`]
//! re-emits them around the painted link cells (the sequences must ride
//! inline with the cell bytes).

use std::cell::RefCell;
use std::io::{self, Write};

use crate::Line;

/// The chat paint backend: a crossterm backend over the stdout
/// [`HyperlinkWriter`], so painted link cells carry their OSC 8 regions.
/// Every draw must install its composed frame first ([`install_frame`]).
pub type LinkBackend = ratatui::backend::CrosstermBackend<HyperlinkWriter<std::io::Stdout>>;

#[must_use]
pub fn stdout_backend() -> LinkBackend {
    LinkBackend::new(HyperlinkWriter::new(std::io::stdout()))
}

/// OSC 8 open: starts a hyperlink region for `url`.
/// Byte-identical to the TS `hyperlink()` helper (`terminal-image.ts`).
#[must_use]
pub fn osc8_open(url: &str) -> String {
    format!("\x1b]8;;{url}\x1b\\")
}

/// OSC 8 close: ends the active hyperlink region.
pub const OSC8_CLOSE: &str = "\x1b]8;;\x1b\\";

#[must_use]
pub fn rewrite_drive_path(url: &str) -> String {
    let bytes = url.as_bytes();
    if url.len() >= 3
        && bytes[0].is_ascii_alphabetic()
        && bytes[1] == b':'
        && (bytes[2] == b'\\' || bytes[2] == b'/')
    {
        format!("file:///{}", url.replace('\\', "/"))
    } else {
        url.to_string()
    }
}

/// TS `case "link"` href resolution: drive-path rewrite, then a WHATWG
/// `new URL(target, baseUrl)` pass. Standalone callers have no base; the
/// session view supplies its own base through the crate-private Markdown context.
#[must_use]
pub fn resolve_link_href(token_href: &str) -> String {
    resolve_link_href_with_base(token_href, None)
}

pub(crate) fn resolve_link_href_with_base(token_href: &str, base: Option<&url::Url>) -> String {
    let target = rewrite_drive_path(token_href);
    if target.starts_with('#') {
        return sanitize_control_bytes(target);
    }
    match url::Url::parse(&target) {
        Ok(parsed) => parsed.to_string(),
        Err(_) => base
            .and_then(|base| base.join(&target).ok())
            .map_or_else(|| sanitize_control_bytes(target), |url| url.to_string()),
    }
}

/// The parse-bypass paths return the target raw. A raw C0/DEL byte there would ride
/// the OSC 8 `href` field as a second terminal escape (e.g. an OSC 52 clipboard
/// write), so those paths percent-encode the bytes first. Deliberate hardening past
/// parity (the TS renderer shares the hole); the markdown URL bracket reuses this
/// hardening.
pub(crate) fn sanitize_control_bytes(target: String) -> String {
    if !target
        .as_bytes()
        .iter()
        .any(|&b| matches!(b, 0x00..=0x1f | 0x7f))
    {
        return target;
    }
    let mut out = Vec::with_capacity(target.len());
    for byte in target.bytes() {
        if matches!(byte, 0x00..=0x1f | 0x7f) {
            out.extend_from_slice(format!("%{byte:02X}").as_bytes());
        } else {
            out.push(byte);
        }
    }
    // Only ASCII control bytes were replaced; the remaining bytes are the
    // original valid UTF-8 sequence.
    String::from_utf8(out).expect("utf-8 survives ASCII percent-encoding")
}

/// The env-based hyperlink-capability gate (TS `detectCapabilities`):
/// enabled only in terminals positively known to implement OSC 8, forced
/// off under tmux/screen, and off in unknown terminals (a swallowed OSC 8
/// hides the URL).
#[must_use]
pub fn hyperlinks_enabled() -> bool {
    if let Some(overridden) = OVERRIDE.with(|c| *c.borrow()) {
        return overridden;
    }
    let term_program = std::env::var("TERM_PROGRAM")
        .unwrap_or_default()
        .to_lowercase();
    let term = std::env::var("TERM").unwrap_or_default().to_lowercase();
    let in_tmux_or_screen = std::env::var_os("TMUX").is_some()
        || term.starts_with("tmux")
        || term.starts_with("screen");
    if in_tmux_or_screen {
        return false;
    }
    if std::env::var_os("KITTY_WINDOW_ID").is_some() || term_program == "kitty" {
        return true;
    }
    if term_program == "ghostty"
        || term.contains("ghostty")
        || std::env::var_os("GHOSTTY_RESOURCES_DIR").is_some()
    {
        return true;
    }
    if std::env::var_os("WEZTERM_PANE").is_some() || term_program == "wezterm" {
        return true;
    }
    if std::env::var_os("ITERM_SESSION_ID").is_some() || term_program == "iterm.app" {
        return true;
    }
    matches!(term_program.as_str(), "vscode" | "alacritty")
}

thread_local! {
    /// Test seam mirroring TS `setCapabilities`: force the capability decision; `None` restores
    /// detection.
    static OVERRIDE: RefCell<Option<bool>> = const { RefCell::new(None) };
}

pub fn set_hyperlinks_override(enabled: Option<bool>) {
    OVERRIDE.with(|c| *c.borrow_mut() = enabled);
}

/// One clickable region of a composed frame.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LinkRange {
    pub row: usize,
    pub start_col: usize,
    pub end_col: usize,
    pub url: String,
}

/// Scan a composed frame for OSC 8 sequences embedded in span content and
/// convert them into row/column ranges (the paint-time truth; visible
/// columns unaffected). A link left open at a row end extends to the row's
/// end and resumes at column 0 of the next row, matching the TS stream.
#[must_use]
pub fn frame_link_ranges(frame: &[Line]) -> Vec<LinkRange> {
    let mut ranges: Vec<LinkRange> = Vec::new();
    let mut carry: Option<(usize, usize, String)> = None;
    for row in 0..frame.len() {
        let mut col = 0usize;
        for span in &frame[row] {
            scan_span(&span.content, row, &mut col, &mut carry, &mut ranges);
        }
        if let Some((start_row, start_col, url)) = carry.take() {
            let _ = start_row;
            ranges.push(LinkRange {
                row,
                start_col,
                end_col: col,
                url: url.clone(),
            });
            if row + 1 < frame.len() {
                carry = Some((row + 1, 0, url));
            }
        }
    }
    ranges
}

fn scan_span(
    content: &str,
    row: usize,
    col: &mut usize,
    carry: &mut Option<(usize, usize, String)>,
    ranges: &mut Vec<LinkRange>,
) {
    let mut i = 0usize;
    while i < content.len() {
        if let Some(len) = crate::width::escape_len(&content[i..]) {
            let seq = &content[i..i + len];
            if seq.starts_with("\x1b]8;;") && !is_osc8_close(seq) {
                let url = &seq["\x1b]8;;".len()..];
                let url = url.strip_suffix("\x1b\\").unwrap_or(url);
                if let Some((start_row, start_col, url)) = carry.take() {
                    ranges.push(LinkRange {
                        row: start_row,
                        start_col,
                        end_col: *col,
                        url,
                    });
                }
                *carry = Some((row, *col, url.to_string()));
            } else if is_osc8_close(seq) {
                if let Some((start_row, start_col, url)) = carry.take() {
                    ranges.push(LinkRange {
                        row: start_row,
                        start_col,
                        end_col: *col,
                        url,
                    });
                }
            }
            i += len;
            continue;
        }
        let ch = content[i..].chars().next().expect("char at byte index");
        *col += crate::width::char_width(ch);
        i += ch.len_utf8();
    }
}

fn is_osc8_close(seq: &str) -> bool {
    seq == OSC8_CLOSE || seq == "\x1b]8;;\x07"
}

/// Remove OSC 8 sequences from a rendered line's span contents (the
/// paint path must not see the zero-width bytes; [`HyperlinkWriter`]
/// re-emits them at paint).
pub fn strip_osc8(line: &mut Line) {
    for span in line.iter_mut() {
        if span.content.contains("\x1b]8;;") {
            span.content = strip_osc8_content(&span.content);
        }
    }
}

/// Remove OSC 8 open/close sequences from a string, preserving every other
/// escape sequence (OSC 133 zone markers ride in the same contents).
///
/// # Panics
///
/// Cannot panic for any valid `str`: the scanner only ever advances by
/// whole escape sequences and chars.
#[must_use]
pub fn strip_osc8_content(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut i = 0usize;
    while i < text.len() {
        if let Some(len) = crate::width::escape_len(&text[i..]) {
            let seq = &text[i..i + len];
            let is_open = seq.starts_with("\x1b]8;;") && !is_osc8_close(seq);
            if !is_open && !is_osc8_close(seq) {
                out.push_str(seq);
            }
            i += len;
            continue;
        }
        let ch = text[i..].chars().next().expect("char at byte index");
        out.push(ch);
        i += ch.len_utf8();
    }
    out
}

thread_local! {
    /// The current frame's link ranges, installed by the paint entry points
    /// before each `Terminal::draw` and consumed by [`HyperlinkWriter`].
    static FRAME_LINKS: RefCell<Vec<LinkRange>> = const { RefCell::new(Vec::new()) };
}

/// Install the composed frame's link ranges for the next paint pass.
pub fn install_frame(frame: &[Line]) {
    let ranges = frame_link_ranges(frame);
    FRAME_LINKS.with(|cell| *cell.borrow_mut() = ranges);
}

fn current_frame_links() -> Vec<LinkRange> {
    FRAME_LINKS.with(|cell| cell.borrow().clone())
}

/// The URL of the link range covering one row/column cell, if any.
pub(crate) fn link_at(ranges: &[LinkRange], row: usize, col: usize) -> Option<&str> {
    ranges
        .iter()
        .find(|r| r.row == row && col >= r.start_col && col < r.end_col)
        .map(|r| r.url.as_str())
}

/// The URL a click at `row`/`col` opens.
pub(crate) fn url_at(ranges: &[LinkRange], row: usize, col: usize) -> Option<String> {
    link_at(ranges, row, col).map(str::to_string)
}

/// TS `openHyperlink`'s guard: a control byte never rides an opener
/// argument, and only http/https/file targets open — a terminal-origin
/// URL is still renderer output.
pub(crate) fn openable_href(url: &str) -> Option<String> {
    if url.chars().any(char::is_control) {
        return None;
    }
    let parsed = url::Url::parse(url).ok()?;
    match parsed.scheme() {
        "http" | "https" | "file" => Some(parsed.to_string()),
        _ => None,
    }
}

/// Terminal writer wrapper that injects OSC 8 hyperlink sequences around
/// the cells painted inside installed link ranges.
///
/// The backend byte stream is parsed on the fly: `MoveTo` updates the
/// tracked cursor, printable runs advance the column, other escapes pass
/// through; a run beginning inside a link region opens it first, and
/// `flush` always closes an open region.
pub struct HyperlinkWriter<W> {
    inner: W,
    pos: Option<(u16, u16)>,
    /// URL of the currently open OSC 8 region.
    active: Option<String>,
    /// Buffered bytes of a printable run awaiting its width.
    text: Vec<u8>,
    /// Buffered bytes of an escape sequence awaiting its terminator.
    escape: Vec<u8>,
    in_escape: bool,
}

impl<W: Write> HyperlinkWriter<W> {
    pub fn new(inner: W) -> Self {
        Self {
            inner,
            pos: None,
            active: None,
            text: Vec::new(),
            escape: Vec::new(),
            in_escape: false,
        }
    }

    /// The composed bytes so far (test accessor for in-memory writers).
    pub fn into_inner(self) -> W {
        self.inner
    }

    /// Write the OSC 8 close sequence if a region is open.
    fn close_active(&mut self) {
        if self.active.take().is_some() {
            let _ = self.inner.write_all(OSC8_CLOSE.as_bytes());
        }
    }

    /// Emit open/close sequences for a printable run starting at the tracked
    /// position: open when the run lands inside a link region, re-opening when
    /// the region changed.
    fn link_for_run(&mut self, ranges: &[LinkRange]) {
        let Some((row, col)) = self.pos else {
            self.close_active();
            return;
        };
        let desired = link_at(ranges, row as usize, col as usize);
        let same = self
            .active
            .as_deref()
            .is_some_and(|active| Some(active) == desired);
        if !same {
            self.close_active();
            if let Some(url) = desired {
                let _ = self.inner.write_all(osc8_open(url).as_bytes());
            }
        }
        if let Some(url) = desired {
            self.active = Some(url.to_string());
        }
    }

    /// Emit the buffered printable run and advance the tracked column.
    fn flush_text(&mut self) -> io::Result<()> {
        use unicode_segmentation::UnicodeSegmentation;
        if self.text.is_empty() {
            return Ok(());
        }
        let chunk = std::mem::take(&mut self.text);
        let Ok(text) = std::str::from_utf8(&chunk) else {
            return self.inner.write_all(&chunk);
        };
        for grapheme in text.graphemes(true) {
            let width = crate::width::str_width(grapheme) as u16;
            // Terminals disagree on the width of a multi-codepoint two-column cluster (a VS16
            // emoji, a ZWJ sequence, a flag): blank both of its cells first, so a terminal that
            // advances one column keeps no stale cell beside the glyph.
            if let Some((row, col)) = self
                .pos
                .filter(|_| width == 2 && grapheme.chars().nth(1).is_some())
            {
                write!(self.inner, "  \x1b[{};{}H", row + 1, col + 1)?;
            }
            self.inner.write_all(grapheme.as_bytes())?;
            if let Some((_, col)) = self.pos.as_mut() {
                *col = col.saturating_add(width);
            }
        }
        Ok(())
    }
}

impl<W: Write> Write for HyperlinkWriter<W> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let ranges = current_frame_links();
        let no_links = ranges.is_empty();
        for &byte in buf {
            if self.in_escape {
                self.escape.push(byte);
                if !escape_complete(&self.escape) {
                    continue;
                }
                let seq = std::mem::take(&mut self.escape);
                self.in_escape = false;
                let is_move = seq.first() == Some(&0x1b)
                    && seq.get(1) == Some(&b'[')
                    && seq.last() == Some(&b'H');
                if is_move {
                    if !no_links {
                        self.close_active();
                    }
                    let params = &seq[2..seq.len() - 1];
                    let mut parts = params.split(|&b| b == b';');
                    let row = parts
                        .next()
                        .and_then(|p| std::str::from_utf8(p).ok())
                        .and_then(|p| p.parse::<u16>().ok());
                    let col = parts
                        .next()
                        .and_then(|p| std::str::from_utf8(p).ok())
                        .and_then(|p| p.parse::<u16>().ok());
                    match (row, col) {
                        (Some(row), Some(col)) => {
                            self.pos = Some((row.saturating_sub(1), col.saturating_sub(1)));
                        }
                        _ => self.pos = None,
                    }
                }
                self.inner.write_all(&seq)?;
                continue;
            }
            if byte == 0x1b {
                self.flush_text()?;
                self.in_escape = true;
                self.escape.push(byte);
                continue;
            }
            if self.text.is_empty() && !no_links {
                self.link_for_run(&ranges);
            }
            self.text.push(byte);
        }
        self.flush_text()?;
        Ok(buf.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        self.flush_text()?;
        if !self.escape.is_empty() {
            let seq = std::mem::take(&mut self.escape);
            self.in_escape = false;
            self.inner.write_all(&seq)?;
        }
        self.close_active();
        self.inner.flush()
    }
}

/// True when the buffered escape sequence is complete (final byte seen).
fn escape_complete(seq: &[u8]) -> bool {
    if seq.len() < 2 {
        return false;
    }
    match seq[1] {
        // CSI: parameter/intermediate bytes then a final byte. The
        // introducer `[` itself sits in the final-byte range, so a lone
        // `ESC [` is incomplete.
        b'[' => {
            if seq.len() < 3 {
                return false;
            }
            let body_complete = seq[2..seq.len() - 1]
                .iter()
                .all(|&b| (0x20..=0x3f).contains(&b));
            body_complete && seq.last().is_some_and(|&c| (0x40..=0x7e).contains(&c))
        }
        // OSC and friends end at BEL, or at ESC \ (ST).
        b']' | b'P' | b'^' | b'X' | b'_' => {
            if matches!(seq.last(), Some(b'\x07')) {
                return true;
            }
            seq.len() >= 3 && seq[seq.len() - 2] == 0x1b && seq[seq.len() - 1] == b'\\'
        }
        _ => false,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Span;

    fn line(text: &str) -> Line {
        vec![Span::raw(text)]
    }

    #[test]
    fn resolve_link_href_canonicalizes_parseable_targets() {
        // The deployed renderer always sets baseUrl, so every parseable
        // non-fragment href goes through `new URL().href` (hosts gain a trailing
        // `/`, scheme and host lower-case); unparseable targets and fragments
        // pass raw.
        assert_eq!(
            resolve_link_href("https://x.dev/a?b=1"),
            "https://x.dev/a?b=1"
        );
        assert_eq!(resolve_link_href("https://bare.dev"), "https://bare.dev/");
        assert_eq!(
            resolve_link_href("HTTPS://UPPER.COM/PATH"),
            "https://upper.com/PATH"
        );
        assert_eq!(resolve_link_href("mailto:[email protected]"), "mailto:[email protected]");
        assert_eq!(resolve_link_href("c:\\src"), "file:///c:/src");
        assert_eq!(resolve_link_href("see docs"), "see docs");
        assert_eq!(resolve_link_href("#section"), "#section");
    }

    #[test]
    fn parse_bypass_targets_percent_encode_control_bytes() {
        // Fragment and unparseable targets reach the OSC 8 href raw; a raw control
        // byte there would ride the terminal stream as a second escape (an OSC 52
        // clipboard write), so those paths percent-encode C0 and DEL first.
        assert_eq!(resolve_link_href("#a]52;cb"), "#a%1B]52;c%07b");
        assert_eq!(resolve_link_href("not a url]8;;x"), "not a url%1B]8;;x");
        assert_eq!(resolve_link_href("#s"), "#s%7F");
        // Printable fragments stay untouched, byte-identical to TS.
        assert_eq!(resolve_link_href("#section"), "#section");
    }

    #[test]
    fn openable_href_gates_the_click_opener() {
        assert_eq!(
            openable_href("https://example.com/docs"),
            Some("https://example.com/docs".to_string())
        );
        assert_eq!(
            openable_href("http://example.com"),
            Some("http://example.com/".to_string())
        );
        assert_eq!(
            openable_href("file:///home/user/notes"),
            Some("file:///home/user/notes".to_string())
        );
        assert_eq!(openable_href("mailto:[email protected]"), None);
        assert_eq!(openable_href("ftp://example.com/f"), None);
        assert_eq!(openable_href("not a url"), None);
        assert_eq!(openable_href("https://example.com/a\x1bb"), None);
    }

    #[test]
    fn url_at_resolves_the_covering_range() {
        let ranges = vec![LinkRange {
            row: 2,
            start_col: 4,
            end_col: 8,
            url: "https://example.com".to_string(),
        }];
        assert_eq!(
            url_at(&ranges, 2, 5),
            Some("https://example.com".to_string())
        );
        assert_eq!(
            url_at(&ranges, 2, 4),
            Some("https://example.com".to_string())
        );
        assert_eq!(url_at(&ranges, 2, 8), None, "the end column is outside");
        assert_eq!(url_at(&ranges, 3, 5), None, "another row");
    }

    #[test]
    fn osc8_helpers_match_ts_format() {
        assert_eq!(
            osc8_open("https://x.dev/a"),
            "\x1b]8;;https://x.dev/a\x1b\\"
        );
        assert_eq!(OSC8_CLOSE, "\x1b]8;;\x1b\\");
        assert_eq!(
            rewrite_drive_path("c:\\src\\main.rs"),
            "file:///c:/src/main.rs"
        );
        assert_eq!(rewrite_drive_path("https://x.dev"), "https://x.dev");
    }

    #[test]
    fn frame_link_ranges_cover_label_cells() {
        let row0 = vec![
            Span::raw("see "),
            Span::raw(osc8_open("https://x.dev/a")),
            Span::raw("the docs"),
            Span::raw(OSC8_CLOSE),
        ];
        let row1 = vec![Span::raw("tail row")];
        let ranges = frame_link_ranges(&[row0, row1]);
        assert_eq!(
            ranges,
            vec![LinkRange {
                row: 0,
                start_col: 4,
                end_col: 12,
                url: "https://x.dev/a".to_string(),
            }]
        );
    }

    #[test]
    fn open_link_wraps_to_row_end_and_next_row() {
        let frame = vec![
            vec![Span::raw(osc8_open("https://x.dev")), Span::raw("abc")],
            vec![Span::raw("def"), Span::raw(OSC8_CLOSE)],
        ];
        let ranges = frame_link_ranges(&frame);
        assert_eq!(
            ranges,
            vec![
                LinkRange {
                    row: 0,
                    start_col: 0,
                    end_col: 3,
                    url: "https://x.dev".to_string(),
                },
                LinkRange {
                    row: 1,
                    start_col: 0,
                    end_col: 3,
                    url: "https://x.dev".to_string(),
                },
            ]
        );
    }

    #[test]
    fn strip_removes_only_osc8() {
        let mut line = vec![
            Span::raw(crate::osc133::ZONE_START),
            Span::raw("pre "),
            Span::raw(format!("{}txt{}", osc8_open("https://x"), OSC8_CLOSE)),
        ];
        strip_osc8(&mut line);
        let joined: String = line.iter().map(|s| s.content.as_str()).collect();
        assert_eq!(joined, "\x1b]133;A\x07pre txt");
        assert_eq!(
            strip_osc8_content("a\x1b]8;;https://y\x1b\\b\x1b]8;;\x1b\\c"),
            "abc"
        );
    }

    /// Drive the writer against a byte sink: returns everything written.
    fn paint(ranges_frame: &[Line], chunks: &[&[u8]]) -> String {
        install_frame(ranges_frame);
        let mut writer = HyperlinkWriter::new(Vec::new());
        for chunk in chunks {
            writer.write_all(chunk).expect("write");
        }
        writer.flush().expect("flush");
        install_frame(&[]);
        String::from_utf8(writer.into_inner()).expect("utf-8")
    }

    /// The bytes the chat paint writes for consecutive frames of one row each: every frame
    /// passes `to_ratatui_line` and the [`HyperlinkWriter`], as `app::draw` does.
    fn paint_frames(frames: &[&str], width: u16) -> Vec<u8> {
        #[derive(Clone, Default)]
        struct Sink(std::rc::Rc<RefCell<Vec<u8>>>);
        impl Write for Sink {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                self.0.borrow_mut().extend_from_slice(buf);
                Ok(buf.len())
            }
            fn flush(&mut self) -> io::Result<()> {
                Ok(())
            }
        }
        let sink = Sink::default();
        let area = ratatui::layout::Rect::new(0, 0, width, 1);
        let mut terminal = ratatui::Terminal::with_options(
            ratatui::backend::CrosstermBackend::new(HyperlinkWriter::new(sink.clone())),
            ratatui::TerminalOptions {
                viewport: ratatui::Viewport::Fixed(area),
            },
        )
        .unwrap();
        for text in frames {
            let line = crate::markdown::to_ratatui_line(&vec![crate::Span::raw(*text)]);
            terminal
                .draw(|frame| frame.render_widget(line, area))
                .unwrap();
        }
        let bytes = sink.0.borrow().clone();
        bytes
    }

    /// A minimal terminal that measures graphemes with `columns` (the width choice vt100 cannot
    /// model): it follows cursor moves, skips the other escape sequences, and records the first
    /// row's cells.
    fn screen_row(bytes: &[u8], width: usize, columns: impl Fn(&str) -> usize) -> Vec<String> {
        use unicode_segmentation::UnicodeSegmentation;
        let text = std::str::from_utf8(bytes).unwrap();
        let mut row = vec![" ".to_string(); width];
        let mut col = 0;
        let mut rest = text;
        while !rest.is_empty() {
            if let Some(len) = crate::width::escape_len(rest) {
                let sequence = &rest[..len];
                if let Some(position) = sequence
                    .strip_prefix("\x1b[")
                    .and_then(|s| s.strip_suffix('H'))
                {
                    col = position
                        .split(';')
                        .nth(1)
                        .and_then(|c| c.parse::<usize>().ok())
                        .unwrap_or(1)
                        - 1;
                }
                rest = &rest[len..];
                continue;
            }
            let grapheme = rest.graphemes(true).next().unwrap();
            let advance = columns(grapheme);
            if advance > 0 && col < width {
                row[col] = grapheme.to_string();
                for cell in row.iter_mut().skip(col + 1).take(advance - 1) {
                    cell.clear();
                }
            }
            col += advance;
            rest = &rest[grapheme.len()..];
        }
        row
    }

    /// A terminal that gives the soft hyphen a column (glibc `wcwidth`, pyte) and one that gives
    /// it none (iTerm2) paint the same row: the hyphen never reaches the terminal.
    #[test]
    fn a_soft_hyphen_never_shifts_the_cells_after_it() {
        let bytes = paint_frames(&["a\u{ad}b"], 4);
        let row = screen_row(&bytes, 4, |grapheme| {
            usize::from(grapheme == "\u{ad}") + crate::width::str_width(grapheme)
        });
        assert_eq!(
            row[..2],
            ["a", "b"],
            "the row a one-column soft hyphen terminal paints"
        );
    }

    /// A terminal that measures a VS16 emoji one column wide (vt100, like iTerm2) keeps no stale
    /// character in the second cell the paint assigns it.
    #[test]
    fn a_two_column_cluster_leaves_no_stale_cell_on_a_narrow_measuring_terminal() {
        let bytes = paint_frames(&["abcd", "\u{26a0}\u{fe0f}cd"], 4);
        let mut parser = vt100::Parser::new(1, 4, 0);
        parser.process(&bytes);
        let screen = parser.screen();
        assert_eq!(screen.cell(0, 0).unwrap().contents(), "\u{26a0}\u{fe0f}");
        let second = screen.cell(0, 1).unwrap().contents();
        assert!(
            second.trim().is_empty(),
            "the second cell still shows the previous frame's {second:?}"
        );
    }

    #[test]
    fn writer_injects_open_close_around_link_cells() {
        // Link covers the `cd` label at columns 4..6 of row 0.
        let frame = vec![vec![
            Span::raw("    "),
            Span::raw(osc8_open("https://z")),
            Span::raw("cd"),
            Span::raw(OSC8_CLOSE),
        ]];
        let out = paint(&frame, &[b"\x1b[1;3Hab", b"\x1b[1;5Hcd", b"\x1b[1;8Hxy"]);
        assert_eq!(
            out,
            "\x1b[1;3Hab\x1b[1;5H\x1b]8;;https://z\x1b\\cd\x1b]8;;\x1b\\\x1b[1;8Hxy"
        );
    }

    #[test]
    fn fallback_capability_keeps_markdown_label_metadata_and_hit_testing() {
        set_hyperlinks_override(Some(false));
        let style = crate::markdown::MarkdownStyle::default();
        let frame = vec![crate::markdown::render_inline(
            "[docs](https://example.com)",
            &style,
        )];
        let ranges = frame_link_ranges(&frame);
        assert_eq!(link_at(&ranges, 0, 0), Some("https://example.com/"));
        assert_eq!(
            link_at(&ranges, 0, 4),
            None,
            "fallback URL is outside the label's region"
        );
        // The actual render has separate label/body and dim fallback spans.
        // Pin that boundary; this is not a test of splitting a homogeneous
        // writer chunk across a link range in the middle of its bytes.
        let out = paint(&frame, &[b"\x1b[1;1Hdocs", b" (https://example.com)"]);
        assert!(out.contains(&format!(
            "{}docs{}",
            osc8_open("https://example.com/"),
            OSC8_CLOSE
        )));
        assert!(out.ends_with(" (https://example.com)"));
        set_hyperlinks_override(None);
    }

    #[test]
    fn writer_keeps_region_open_across_style_changes() {
        // The link covers columns 0..4; a color SGR lands between the two
        // fragments, so the region must stay open across the SGR bytes.
        let frame = vec![vec![
            Span::raw(osc8_open("https://z")),
            Span::raw("abcd"),
            Span::raw(OSC8_CLOSE),
        ]];
        let out = paint(&frame, &[b"\x1b[1;1Hab\x1b[38;2;1;2;3mcd"]);
        assert_eq!(
            out,
            "\x1b[1;1H\x1b]8;;https://z\x1b\\ab\x1b[38;2;1;2;3mcd\x1b]8;;\x1b\\"
        );
    }

    #[test]
    fn writer_without_links_passes_stream_through() {
        let out = paint(&[line("no links here")], &[b"\x1b[1;1Hplain"]);
        assert_eq!(out, "\x1b[1;1Hplain");
    }
}