rho-coding-agent 3.10.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Transcript path links in the running TUI: which workspace they link
//! into, the checks that find which mentions are files, and the links each
//! frame hands the terminal backend.

use std::io;

use ratatui::{
    buffer::{Buffer, CellDiffOption},
    layout::Rect,
    CompletedFrame,
};
use tokio::task::JoinError;

use super::{
    background_tasks::{TaskId, UiOutput},
    history_cache::{HistoryLineSlice, HistoryRenderSettings},
    path_links::CheckedPaths,
    synced_backend::ScreenLink,
    text_links::RowLink,
    App, DefaultTerminal,
};

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

/// Links painted over the history pane in the frame being drawn, with the
/// text each covered cell showed when painted. Overlays drawn later may
/// cover some; [`Self::finish`] keeps only the cells still showing it.
#[derive(Debug, Default)]
pub(super) struct PaintedLinks {
    painted: Vec<(ScreenLink, Vec<String>)>,
}

impl PaintedLinks {
    /// Records `links`, by row and column of `area`, over `buffer` as painted now.
    pub(super) fn record(&mut self, buffer: &Buffer, area: Rect, links: Vec<RowLink>) {
        for link in screen_links(&links, area) {
            let symbols = link
                .x
                .clone()
                .map(|x| buffer[(x, link.y)].symbol().to_owned())
                .collect();
            self.painted.push((link, symbols));
        }
    }

    /// The recorded links where `buffer` still shows the text they were
    /// painted over, each kept cell marked to be written every frame.
    pub(super) fn finish(self, buffer: &mut Buffer) -> Vec<ScreenLink> {
        let mut kept = Vec::new();
        for (link, symbols) in self.painted {
            let mut run: Option<u16> = None;
            for (x, symbol) in link.x.clone().zip(&symbols) {
                let cell = &mut buffer[(x, link.y)];
                if cell.symbol() == symbol {
                    cell.diff_option = CellDiffOption::AlwaysUpdate;
                    run.get_or_insert(x);
                } else if let Some(start) = run.take() {
                    kept.push(ScreenLink {
                        x: start..x,
                        ..link.clone()
                    });
                }
            }
            if let Some(start) = run {
                kept.push(ScreenLink {
                    x: start..link.x.end,
                    ..link
                });
            }
        }
        kept
    }
}

/// `links`, by row and column of `area`, as screen links clipped to it.
pub(super) fn screen_links(links: &[RowLink], area: Rect) -> Vec<ScreenLink> {
    let clip = |value: usize, limit: u16| u16::try_from(value).unwrap_or(u16::MAX).min(limit);
    links
        .iter()
        .filter_map(|link| {
            let row = u16::try_from(link.row)
                .ok()
                .filter(|&row| row < area.height)?;
            Some((row, link))
        })
        .map(|(row, link)| ScreenLink {
            y: area.y + row,
            x: area.x + clip(link.columns.start, area.width)
                ..area.x + clip(link.columns.end, area.width),
            url: link.url.clone(),
        })
        .filter(|link| !link.x.is_empty())
        .collect()
}

impl App {
    /// Draws a session frame, handing the links it paints to the backend.
    pub(super) fn draw_frame<'t>(
        &mut self,
        terminal: &'t mut DefaultTerminal,
    ) -> io::Result<CompletedFrame<'t>> {
        let hyperlinks = terminal.backend().frame_hyperlinks();
        terminal.draw(|frame| {
            self.painted_links = PaintedLinks::default();
            self.draw(frame);
            let painted = std::mem::take(&mut self.painted_links);
            hyperlinks.set(painted.finish(frame.buffer_mut()));
        })
    }

    /// Records the links on history rows `start..start + count`, painted in `area`.
    pub(super) fn record_history_links(
        &mut self,
        buffer: &Buffer,
        area: Rect,
        settings: HistoryRenderSettings,
        slice: HistoryLineSlice,
    ) {
        let links = self.history_links(settings, slice);
        self.painted_links.record(buffer, area, links);
    }

    /// The links on history rows `slice`, by row from `slice.start`. The
    /// session header above the transcript has none.
    pub(super) fn history_links(
        &mut self,
        settings: HistoryRenderSettings,
        slice: HistoryLineSlice,
    ) -> Vec<RowLink> {
        let header_len = self.visible_session_header_len(settings.width);
        let header_rows = header_len.saturating_sub(slice.start).min(slice.count);
        let transcript = HistoryLineSlice {
            start: slice.start.saturating_sub(header_len),
            count: slice.count - header_rows,
        };
        if transcript.count == 0 {
            return Vec::new();
        }
        let cwd = &self.info.runtime.cwd;
        let links = self
            .history
            .with_lines_and_images_mut(|cache, entries, images| {
                cache.visible_links(entries, settings, transcript, &|index, sources| {
                    images.ready_images(index, sources, cwd)
                })
            });
        links
            .into_iter()
            .map(|link| link.shifted(header_rows, 0))
            .collect()
    }

    /// Points path links at the session's workspace, which follows the
    /// session the TUI shows.
    pub(super) fn sync_path_workspace(&mut self) {
        let cwd = self.info.runtime.cwd.clone();
        self.history.lines_mut().set_path_workspace(&cwd);
    }

    /// Starts a check of the paths rendering queued, unless one is running.
    pub(super) fn start_path_check(&mut self) {
        if self.tasks.contains(|id| *id == TaskId::PathCheck) {
            return;
        }
        if let Some(check) = self.history.lines_mut().take_path_check() {
            self.tasks.spawn_blocking(
                TaskId::PathCheck,
                move || check.run(),
                |result| UiOutput::PathCheck(result).into(),
            );
        }
    }

    /// Applies a finished check; entries mentioning a found file re-render.
    pub(super) fn apply_path_check(&mut self, result: Result<CheckedPaths, JoinError>) -> bool {
        match result {
            Ok(checked) => {
                self.history.lines_mut().apply_path_check(checked);
                true
            }
            // A check that panicked or was cancelled links nothing more.
            Err(_) => false,
        }
    }
}