rho-coding-agent 3.9.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
use std::collections::HashMap;

use anyhow::Context as _;
use rho_protocol::TreeNodeId;

use crate::tui::{daemon_requests::REWIND_FAILED, DefaultTerminal};

use crate::{
    app::{
        sdk_config::WorkspaceOptions,
        workspace_rewind::{
            classification_label, limitation_label, plans_full_restore, uncaptured_line,
            PlannedRewind,
        },
    },
    commands::CommandInvocation,
    session::{
        tree::{NodeId, SessionTree},
        workspace_checkpoint::{
            CheckpointFileBudgetExceeded, RestorePlan, RewoundTurns, WorkspaceCheckpointStore,
        },
    },
};

use super::{
    picker::OverlayChrome, App, ComposerMode, Entry, PickerBadge, PickerBadgeTone, PickerItem,
    PickerLayout, UiPicker,
};

/// What a rewind confirmation's one row holds as its value: the checkpoint,
/// and the conversation's node its preview was planned at, which the
/// rewind is held to.
#[derive(Debug, PartialEq, Eq)]
pub(super) struct RewindConfirmation {
    pub(super) checkpoint: NodeId,
    pub(super) tip: NodeId,
}

impl RewindConfirmation {
    pub(super) fn value(&self) -> String {
        format!("{} {}", self.checkpoint, self.tip)
    }

    /// Node ids are generated without spaces, so the tip is after the last.
    pub(super) fn parse(value: &str) -> anyhow::Result<Self> {
        let (checkpoint, tip) = value
            .rsplit_once(' ')
            .context("the rewind confirmation names no tip")?;
        Ok(Self {
            checkpoint: NodeId::from_string(checkpoint)?,
            tip: NodeId::from_string(tip)?,
        })
    }
}

impl App {
    /// The rewind confirmation on screen, if one is, whatever its filter
    /// hides.
    pub(super) fn open_rewind_confirmation(&self) -> Option<RewindConfirmation> {
        match self.input_ui.composer() {
            ComposerMode::Picker(picker) if picker.is_confirm_rewind() => picker
                .items
                .first()
                .and_then(|item| RewindConfirmation::parse(&item.value).ok()),
            _ => None,
        }
    }

    /// Plans the rewind confirmation on screen again once the session came
    /// to rest, so it never confirms a preview from before a turn that since
    /// ended, or a conversation a reattach replayed moved.
    pub(super) fn refresh_rewind_confirmation(&mut self) {
        if let Some(open) = self.open_rewind_confirmation() {
            self.preview_rewind_again(open.checkpoint.as_str(), "the session moved on");
        }
    }

    /// Previews the rewind of `checkpoint` again, as `why` asks, or closes
    /// the confirmation on screen, and says why, when it can no longer be
    /// previewed, as when the checkpoint left the branch. It reopens only
    /// over that checkpoint's confirmation or an empty composer: never over
    /// a draft, where the next Enter would confirm a rewind unseen, nor
    /// over another picker.
    pub(super) fn preview_rewind_again(&mut self, checkpoint: &str, why: &str) {
        let showing = match self.open_rewind_confirmation() {
            Some(open) => open.checkpoint.as_str() == checkpoint,
            None => {
                matches!(self.input_ui.composer(), ComposerMode::Input)
                    && self.input_ui.text().is_empty()
                    && self.input_ui.attachments().is_empty()
            }
        };
        if !showing {
            self.set_status(format!("{why}; run /rewind again"));
            return;
        }
        match self.submit_rewind_preview(checkpoint) {
            Ok(()) => self.set_status(format!("{why}; review the rewind again")),
            Err(error) => {
                self.input_ui.set_composer(ComposerMode::Input);
                self.set_status(format!(
                    "{why}; the rewind can no longer be previewed: {error:#}"
                ));
            }
        }
    }

    /// The followed session's checkpoint store, or `None` when it has saved
    /// nothing or keeps no checkpoints.
    fn checkpoint_store(&self) -> anyhow::Result<Option<WorkspaceCheckpointStore>> {
        match self.current_session_id() {
            Some(id) => crate::session::Session::workspace_checkpoint_store_by_id(
                &self.info.runtime.cwd,
                &id,
            ),
            None => Ok(None),
        }
    }

    /// The followed session's saved tree, or `None` when it has none.
    fn session_tree(&self) -> anyhow::Result<Option<SessionTree>> {
        self.current_session_id()
            .map(|id| crate::session::Session::tree_by_id(&self.info.runtime.cwd, &id))
            .transpose()
    }

    pub(super) fn execute_rewind_command(
        &mut self,
        invocation: CommandInvocation,
    ) -> anyhow::Result<()> {
        if self.info.session.no_save {
            self.set_status("workspace rewind unavailable with --no-save");
            return Ok(());
        }
        // The daemon holds the session open; its checkpoints and tree are
        // read from the files both share. A rewind undoes the turns of the
        // conversation's current branch, so only its checkpoints are listed.
        let tree = self.session_tree()?;
        let path = match &tree {
            Some(tree) => tree.active_path_ids()?,
            None => Vec::new(),
        };
        let checkpoints: Vec<_> = match self.checkpoint_store()? {
            Some(store) => store
                .list()?
                .into_iter()
                .filter(|checkpoint| path.contains(&checkpoint.node_id))
                .collect(),
            None => Vec::new(),
        };
        // A turn's checkpoint names the node the turn ended on, which later
        // saves, such as a settings change, may follow.
        let prompts: HashMap<_, _> = checkpoints
            .iter()
            .filter_map(|checkpoint| {
                let prompt = tree.as_ref()?.turn_prompt(&checkpoint.node_id)?;
                Some((checkpoint.node_id.clone(), prompt))
            })
            .collect();
        // The session takes the setting when it opens, so one opened after
        // a change may have checkpoints the configured setting would not
        // expect: the setting only explains an empty list. A config that
        // cannot be read explains nothing.
        if checkpoints.is_empty()
            && self
                .info
                .services
                .config_repository
                .load()
                .is_ok_and(|config| !config.workspace_rewind)
        {
            self.set_status(
                "workspace rewind is off; set behavior.workspace_rewind = true and start a new session",
            );
            return Ok(());
        }
        if checkpoints.is_empty() {
            self.set_status("this branch of the session has no workspace checkpoints");
            return Ok(());
        }
        if !invocation.args.is_empty() {
            let matching = checkpoints
                .iter()
                .filter(|checkpoint| checkpoint.node_id.as_str().starts_with(&invocation.args))
                .collect::<Vec<_>>();
            anyhow::ensure!(
                matching.len() == 1,
                "turn '{}' must match exactly one workspace checkpoint",
                invocation.args
            );
            return self.submit_rewind_preview(matching[0].node_id.as_str());
        }

        let items = checkpoints
            .into_iter()
            .rev()
            .map(|checkpoint| {
                let id = checkpoint.node_id.to_string();
                let short_id = &id[..id.len().min(8)];
                let preview = prompts
                    .get(&checkpoint.node_id)
                    .cloned()
                    .unwrap_or_else(|| format!("turn {short_id}"));
                PickerItem {
                    detail: Some(
                        format!(
                            "checkpoint time: {}\ntracked files: {}\noutcome: {:?}",
                            checkpoint.finalized_at, checkpoint.file_count, checkpoint.outcome
                        )
                        .into(),
                    ),
                    badge: (!checkpoint.limitations.is_empty()).then_some(PickerBadge {
                        text: "limited".into(),
                        tone: PickerBadgeTone::Warning,
                    }),
                    ..PickerItem::new(preview, id)
                }
            })
            .collect();
        let picker = UiPicker::rewind_checkpoint("Workspace rewind", items)
            .with_layout(PickerLayout::Overlay)
            .with_overlay_chrome(OverlayChrome {
                nav_label: " REWIND".into(),
                detail_label: Some("CHECKPOINT".into()),
                nav_keys_hint: "↑↓ turns".into(),
            })
            .with_confirm_verb("preview");
        self.input_ui.set_composer(ComposerMode::Picker(picker));
        self.set_status("select workspace checkpoint");
        Ok(())
    }

    pub(super) fn submit_rewind_preview(&mut self, value: &str) -> anyhow::Result<()> {
        let node_id = NodeId::from_string(value)?;
        // Planned here against the files as they are; the daemon plans again
        // when it restores.
        let store = self
            .checkpoint_store()?
            .ok_or_else(|| anyhow::anyhow!("workspace rewind is unavailable for this session"))?;
        let root = self.info.runtime.cwd.clone();
        let workspace = WorkspaceOptions { root: root.clone() }
            .build_workspace(&self.info.runtime.added_dirs)?;
        let tree = self
            .session_tree()?
            .ok_or_else(|| anyhow::anyhow!("the session has no saved conversation yet"))?;
        let planned = PlannedRewind::new(&store, &workspace, &node_id, &tree)?;
        let detail = rewind_preview_text(&planned.turns, &planned.plan, &root);
        let confirmation = RewindConfirmation {
            checkpoint: node_id,
            tip: planned.tip,
        };
        let blocked = !plans_full_restore(&planned.plan);
        let item = PickerItem {
            detail: Some(detail.into()),
            badge: blocked.then_some(PickerBadge {
                text: "partial".into(),
                tone: PickerBadgeTone::Warning,
            }),
            ..PickerItem::new(
                if blocked {
                    "Confirm safe paths; conflicts stay unchanged".into()
                } else {
                    "Confirm workspace rewind".into()
                },
                confirmation.value(),
            )
        };
        let picker = UiPicker::confirm_rewind("Confirm workspace rewind", vec![item])
            .with_layout(PickerLayout::Overlay)
            .with_overlay_chrome(OverlayChrome {
                nav_label: " CONFIRM".into(),
                detail_label: Some("RESTORE PREVIEW".into()),
                nav_keys_hint: "Esc cancel".into(),
            })
            .with_confirm_verb("rewind");
        self.input_ui.set_composer(ComposerMode::Picker(picker));
        self.set_status("confirm workspace rewind");
        Ok(())
    }

    /// The daemon restores the files, says what became of each, and has
    /// every client replay the conversation it returned to.
    pub(super) async fn submit_rewind_confirmation(
        &mut self,
        value: &str,
        _terminal: &mut DefaultTerminal,
    ) -> anyhow::Result<()> {
        let RewindConfirmation { checkpoint, tip } = RewindConfirmation::parse(value)?;
        self.input_ui.set_composer(ComposerMode::Input);
        if let Err(error) = self.info.session.daemon.rewind(
            TreeNodeId::new(checkpoint.as_str()),
            TreeNodeId::new(tip.as_str()),
        ) {
            self.insert_entry(&Entry::Error(format!("{REWIND_FAILED}: {error}")));
        }
        Ok(())
    }
}

fn rewind_preview_text(
    turns: &RewoundTurns,
    plan: &RestorePlan,
    workspace: &std::path::Path,
) -> String {
    let target = turns.turns()[0].as_str();
    let short_id = &target[..target.len().min(8)];
    let mut lines = vec![
        format!("target turn: {short_id}"),
        format!("timestamp: {}", turns.finalized_at()),
        match turns.turns().len() - 1 {
            0 => "turns undone: this one".into(),
            later => format!("turns undone: this one and {later} later on this branch"),
        },
        if plans_full_restore(plan) {
            "conversation: return to before this turn and preserve the existing branch".into()
        } else {
            "conversation: unchanged, because some paths will not be restored".into()
        },
    ];
    for entry in &plan.entries {
        lines.push(format!(
            "{}  {}",
            classification_label(entry.classification),
            rho_tools::compact_display_path(workspace, &entry.path.to_string_lossy())
        ));
    }
    for entry in &plan.entries {
        if let Some(CheckpointFileBudgetExceeded { asked, limit }) = entry.over_budget {
            lines.push(format!(
                "warning  per-file capture budget: limit {limit} bytes, asked {asked} bytes ({})",
                rho_tools::compact_display_path(workspace, &entry.path.to_string_lossy())
            ));
        }
    }
    if plan.entries.is_empty() {
        lines.push("skip  no native file changes were captured".into());
    }
    lines.extend(uncaptured_line(plan.uncaptured_turns));
    for limitation in &plan.limitations {
        lines.push(format!(
            "warning  {} effects from '{}' cannot be restored",
            limitation_label(&limitation.kind),
            limitation.source
        ));
    }
    lines.join("\n")
}