rho-coding-agent 3.9.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! File paths in the transcript drawn as links to the files.
//!
//! A path links only once it is known to be a file in the session's
//! workspace. Rendering never touches the file system: it reads
//! [`PathIndex`] through a [`PathLinker`], links the paths known to be files,
//! and reports every other mention. The history cache queues those for a
//! [`PathCheck`], which runs off the UI thread; its result re-renders the
//! entries that mention a newly found file. A linked path keeps its text as
//! written, with its folders and position dimmer than its file name, and
//! carries a `file://` URL that the terminal backend writes as an OSC 8
//! hyperlink. With icons on, a Nerd Font file-type icon comes before it,
//! outside the link.

mod icons;
mod target;

pub(super) use icons::is_icon_run;

use std::{
    collections::{HashMap, HashSet},
    path::{Path, PathBuf},
    sync::Arc,
};

use ratatui::style::{Modifier, Style};

use super::{text_links::LinkedRun, theme::Theme};

#[cfg(test)]
#[path = "path_links_tests.rs"]
mod tests;

/// What is known about one workspace-relative path.
#[derive(Clone, Debug, PartialEq, Eq)]
enum Known {
    /// Queued for, or inside, a check.
    Checking,
    /// A file; its `file://` URL.
    File(Arc<str>),
    /// Not a file, or the check failed. Checked again when a turn ends.
    Missing,
}

/// The paths the transcript mentions and which of them are files in the
/// workspace, as far as checks have found.
#[derive(Debug)]
pub(super) struct PathIndex {
    workspace: PathBuf,
    known: HashMap<String, Known>,
    /// Paths waiting for the next check, in the order rendering met them.
    queued: Vec<String>,
}

impl PathIndex {
    pub(super) fn new(workspace: PathBuf) -> Self {
        Self {
            workspace,
            known: HashMap::new(),
            queued: Vec::new(),
        }
    }

    pub(super) fn workspace(&self) -> &Path {
        &self.workspace
    }

    /// The URL of `path` when it is known to be a file.
    fn file_url(&self, path: &str) -> Option<&Arc<str>> {
        match self.known.get(path) {
            Some(Known::File(url)) => Some(url),
            Some(Known::Checking | Known::Missing) | None => None,
        }
    }

    /// Queues the paths in `mentioned` that were never looked up.
    pub(super) fn want<'a>(&mut self, mentioned: impl IntoIterator<Item = &'a str>) {
        for path in mentioned {
            if !self.known.contains_key(path) {
                self.known.insert(path.to_owned(), Known::Checking);
                self.queued.push(path.to_owned());
            }
        }
    }

    /// Queues every path a check found missing, or that a running check may
    /// have looked up too early: the turn that just ended may have written it.
    pub(super) fn recheck_missing(&mut self) {
        let queued: HashSet<&str> = self.queued.iter().map(String::as_str).collect();
        let mut recheck = Vec::new();
        for (path, known) in &mut self.known {
            let in_flight = *known == Known::Checking && !queued.contains(path.as_str());
            if *known == Known::Missing || in_flight {
                *known = Known::Checking;
                recheck.push(path.clone());
            }
        }
        self.queued.extend(recheck);
    }

    /// Takes every queued path as one check, if any are queued.
    pub(super) fn take_check(&mut self) -> Option<PathCheck> {
        (!self.queued.is_empty()).then(|| PathCheck {
            workspace: self.workspace.clone(),
            paths: std::mem::take(&mut self.queued),
        })
    }

    /// Records `checked` and returns the paths it found to be files. A check
    /// of another workspace, from before the session moved, changes nothing.
    pub(super) fn apply(&mut self, checked: CheckedPaths) -> Vec<String> {
        if checked.workspace != self.workspace {
            return Vec::new();
        }
        let mut found = Vec::new();
        for (path, url) in checked.paths {
            let known = match url {
                Some(url) => {
                    found.push(path.clone());
                    Known::File(url)
                }
                None => Known::Missing,
            };
            self.known.insert(path, known);
        }
        found
    }
}

/// Paths to look up in a workspace. [`Self::run`] blocks on the file system.
#[derive(Debug)]
pub(super) struct PathCheck {
    workspace: PathBuf,
    paths: Vec<String>,
}

/// What a [`PathCheck`] found: each path's URL when it is a file.
#[derive(Debug)]
pub(super) struct CheckedPaths {
    workspace: PathBuf,
    paths: Vec<(String, Option<Arc<str>>)>,
}

impl PathCheck {
    /// Looks up every path. Blocks; run it off the UI thread. A path links
    /// when it resolves, symlinks and `..` followed, to a file inside the
    /// workspace; the URL names that file.
    pub(super) fn run(self) -> CheckedPaths {
        let host = file_url_host();
        let root = self.workspace.canonicalize().ok();
        let paths = self
            .paths
            .into_iter()
            .map(|path| {
                let url = root.as_deref().and_then(|root| {
                    let file = self.workspace.join(&path).canonicalize().ok()?;
                    (file.starts_with(root) && file.is_file())
                        .then(|| file_url(&file, host.as_deref()))
                        .flatten()
                });
                (path, url)
            })
            .collect();
        CheckedPaths {
            workspace: self.workspace,
            paths,
        }
    }
}

/// The host a `file://` URL names, so a terminal can tell a file on this
/// machine from one on a machine reached over SSH. Windows keeps the host
/// empty: a host there would name a network share.
fn file_url_host() -> Option<String> {
    if cfg!(windows) {
        return None;
    }
    gethostname::gethostname().into_string().ok()
}

/// `path`'s `file://` URL, percent-encoded, naming `host` when it is a valid one.
fn file_url(path: &Path, host: Option<&str>) -> Option<Arc<str>> {
    let mut url = url::Url::from_file_path(path).ok()?;
    if let Some(host) = host {
        // A host name URLs cannot carry leaves the URL host-less.
        let _ = url.set_host(Some(host));
    }
    Some(url.as_str().into())
}

/// How a linked path is styled where it is drawn.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct PathLinkStyle {
    /// The file name.
    pub(super) name: Style,
    /// Its folders and `:line`.
    pub(super) quiet: Style,
}

impl PathLinkStyle {
    /// A transcript path: the name in the accent color, its folders and
    /// `:line` dimmer.
    pub(super) fn transcript() -> Self {
        let name = Theme::accent().remove_modifier(Modifier::UNDERLINED);
        Self {
            name,
            quiet: name.add_modifier(Modifier::DIM),
        }
    }

    /// A path on the user message bar, where the accent loses contrast: the
    /// bar's own colors, underlined, with the name bold.
    pub(super) fn user_message() -> Self {
        let quiet = Theme::user_message().add_modifier(Modifier::UNDERLINED);
        Self {
            name: quiet.add_modifier(Modifier::BOLD),
            quiet,
        }
    }
}

/// One render's view of a [`PathIndex`]: links the paths known to be files
/// and collects the other mentions, which the caller hands back to the index
/// with [`PathIndex::want`].
pub(super) struct PathLinker<'a> {
    index: Option<&'a PathIndex>,
    unlinked: Vec<String>,
    /// Draw a file-type icon before each linked path.
    icons: bool,
}

impl<'a> PathLinker<'a> {
    pub(super) fn new(index: &'a PathIndex) -> Self {
        Self {
            index: Some(index),
            unlinked: Vec::new(),
            icons: false,
        }
    }

    /// This linker, drawing a Nerd Font file-type icon before each path it
    /// links.
    pub(super) fn with_icons(self) -> Self {
        Self {
            icons: true,
            ..self
        }
    }

    /// A linker that links nothing and reports nothing, for text that is
    /// still streaming or is not transcript content.
    pub(super) fn off() -> Self {
        Self {
            index: None,
            unlinked: Vec::new(),
            icons: false,
        }
    }

    /// The mentions this render met that are not linked.
    pub(super) fn into_unlinked(self) -> Vec<String> {
        self.unlinked
    }

    /// Prose `text` in `base`, each linked path in its own runs.
    pub(super) fn prose(
        &mut self,
        text: &str,
        base: Style,
        style: PathLinkStyle,
    ) -> Vec<LinkedRun> {
        let Some(index) = self.index else {
            return vec![LinkedRun::plain(text, base)];
        };
        let mut runs = Vec::new();
        let mut shown = 0;
        for mention in target::prose_mentions(text, index.workspace()) {
            let Some(url) = self.link(index, mention.path) else {
                continue;
            };
            if shown < mention.range.start {
                runs.push(LinkedRun::plain(&text[shown..mention.range.start], base));
            }
            let written = &text[mention.range.clone()];
            runs.extend(self.link_runs(written, mention.path_len, url, style));
            shown = mention.range.end;
        }
        if shown < text.len() || runs.is_empty() {
            runs.push(LinkedRun::plain(&text[shown..], base));
        }
        runs
    }

    /// `text` as a link when all of it is one linked path, as an inline code
    /// span or a tool call's argument may be.
    pub(super) fn whole(&mut self, text: &str, style: PathLinkStyle) -> Option<Vec<LinkedRun>> {
        let index = self.index?;
        let mention = target::whole_mention(text, index.workspace())?;
        let url = self.link(index, mention.path)?;
        Some(self.link_runs(text, mention.path_len, url, style))
    }

    /// `path`'s URL if it is a known file; otherwise records it as unlinked.
    fn link(&mut self, index: &PathIndex, path: String) -> Option<Arc<str>> {
        let url = index.file_url(&path).cloned();
        if url.is_none() {
            self.unlinked.push(path);
        }
        url
    }

    /// `written`, a path then its position from `path_len` on, as runs: its
    /// icon when icons are on, unlinked, then its folders, file name, and
    /// position, linked.
    fn link_runs(
        &self,
        written: &str,
        path_len: usize,
        url: Arc<str>,
        style: PathLinkStyle,
    ) -> Vec<LinkedRun> {
        let (path, position) = written.split_at(path_len);
        let name_start = path
            .rfind(std::path::is_separator)
            .map_or(0, |slash| slash + 1);
        let (folders, name) = path.split_at(name_start);
        let icon = self
            .icons
            .then(|| LinkedRun::plain(icons::icon_run_text(name), style.name));
        let linked = [
            (folders, style.quiet),
            (name, style.name),
            (position, style.quiet),
        ]
        .into_iter()
        .filter(|(text, _)| !text.is_empty())
        .map(|(text, style)| LinkedRun::linked(text, style, Arc::clone(&url)));
        icon.into_iter().chain(linked).collect()
    }
}