rho-coding-agent 3.11.0

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

use pretty_assertions::assert_eq;
use ratatui::layout::Rect;
use rho_protocol::SessionId;

use super::{
    hidden_live, AgentRail, AgentRailTarget, ChildTarget, FinishedChildren, RailEntry, RailState,
    StartedSession, SubagentAttachTarget,
};
use crate::tui::attach_picker::WorkspaceRunFilter;
use crate::{
    subagent::{RunState, RunStatus},
    tools::agent::SubagentSnapshot,
};

fn snapshot(id: &str, agent_id: &str, state: RunState, elapsed_seconds: u64) -> SubagentSnapshot {
    SubagentSnapshot {
        prior_notices: Vec::new(),
        persistence: crate::session::SessionPersistence::Saved,
        id: id.to_owned(),
        agent_id: agent_id.to_owned(),
        title: None,
        elapsed: Duration::from_secs(elapsed_seconds),
        done: state.is_terminal(),
        status: RunStatus {
            state,
            last_activity: Some("read".into()),
            ..RunStatus::default()
        },
    }
}

// Covers: spinner agent count ignores finished, undelivered rows.
// Owner: pure unit (agent count)
#[test]
fn count_excludes_finished_rows() {
    let mut rail = AgentRail::default();
    rail.ingest_runs(vec![
        snapshot("live01", "worker", RunState::Running, 2),
        snapshot("done01", "explorer", RunState::Running, 3),
    ]);
    rail.ingest_runs(vec![
        snapshot("live01", "worker", RunState::Running, 2),
        snapshot("done01", "explorer", RunState::Error, 3),
    ]);
    assert_eq!(rail.count(), 1);
    assert_eq!(rail.desired_height(), 2);
    assert!(rail.candidates().iter().all(|c| c.run_id == "live01"));
}

// Covers: overflow rows collapse into one summary row that opens the attach picker.
// Owner: pure unit (overflow pointer)
#[test]
fn subagent_overflow_summary_opens_attach_picker() {
    let mut rail = AgentRail::default();
    rail.ingest_runs(vec![
        snapshot("aa0001", "worker", RunState::Running, 1),
        snapshot("aa0002", "explorer", RunState::Running, 1),
        snapshot("aa0003", "reviewer", RunState::Running, 1),
    ]);
    assert_eq!(rail.lines(80, 8, "attach", false).len(), 2);

    let area = Rect::new(0, 0, 80, 2);
    assert_eq!(
        rail.attach_target_at(area, 1, 1),
        Some(AgentRailTarget::OpenAttachPicker(
            WorkspaceRunFilter::RunningOnly
        ))
    );
    assert!(matches!(
        rail.attach_target_at(area, 1, 0),
        Some(AgentRailTarget::Child(ChildTarget::Run(_)))
    ));
}

/// What the rail lists, by id, and the finished children it folds.
#[derive(Debug, PartialEq)]
enum Listed {
    Child(String),
    Finished(FinishedChildren),
}

fn listed(rail: &AgentRail) -> Vec<Listed> {
    rail.rail
        .items()
        .iter()
        .map(|entry| match entry {
            RailEntry::Child(row) => Listed::Child(row.id.clone()),
            RailEntry::Finished(finished) => Listed::Finished(*finished),
        })
        .collect()
}

// Covers: finished children, runs and sessions alike, fold into one row
// after the live ones, which never gives way to them, counting those that
// failed and those that were stopped; it does not count among the agents,
// and a click on it opens `/attach` on every child rather than attaching
// one; it gives way while working children fill the rail; with none
// finished there is no such row.
// Owner: pure unit (agent rail rows)
#[test]
fn finished_children_fold_into_one_row_after_the_live_ones() {
    let mut rail = AgentRail::default();
    rail.ingest_runs(vec![
        snapshot("aa0001", "worker", RunState::Ok, 4),
        snapshot("aa0002", "explorer", RunState::Running, 1),
        snapshot("aa0003", "reviewer", RunState::Error, 2),
        snapshot("aa0004", "planner", RunState::Stopped, 2),
    ]);
    rail.ingest_sessions(vec![StartedSession {
        session: SessionId::new("5054a7c5-68a7-4d13-8a3e-0f6d944aa81b"),
        agent: None,
        title: "Bench the parser".into(),
        state: RailState::Idle,
        elapsed: None,
    }]);
    assert_eq!(
        listed(&rail),
        [
            Listed::Child("aa0002".into()),
            Listed::Finished(FinishedChildren {
                count: 4,
                failed: 1,
                stopped: 1,
            }),
        ]
    );
    assert_eq!(rail.count(), 1);
    let area = Rect::new(0, 0, 80, 2);
    assert_eq!(
        rail.attach_target_at(area, 1, 1),
        Some(AgentRailTarget::OpenAttachPicker(WorkspaceRunFilter::All))
    );

    // Working children that fill the rail keep every slot: the finished
    // row gives way, and no overflow row takes one.
    rail.ingest_runs(vec![
        snapshot("aa0001", "worker", RunState::Ok, 4),
        snapshot("aa0002", "explorer", RunState::Running, 1),
        snapshot("aa0005", "writer", RunState::Running, 1),
    ]);
    let run = |id: &str, agent: &str| {
        Some(AgentRailTarget::Child(ChildTarget::Run(
            SubagentAttachTarget {
                run_id: id.into(),
                agent_id: agent.into(),
            },
        )))
    };
    assert_eq!(
        [
            rail.attach_target_at(area, 1, 0),
            rail.attach_target_at(area, 1, 1),
        ],
        [run("aa0002", "explorer"), run("aa0005", "writer")]
    );
    assert_eq!(rail.lines(80, 2, "attach", false).len(), 2);

    rail.ingest_runs(vec![snapshot("aa0002", "explorer", RunState::Running, 1)]);
    rail.ingest_sessions(Vec::new());
    assert_eq!(listed(&rail), [Listed::Child("aa0002".into())]);
}

// Covers: the overflow row counts the live children it hides, which its
// click lists, and not the finished children of a finished row it hides.
// Owner: pure unit (agent rail overflow)
#[test]
fn overflow_counts_the_live_children_it_hides() {
    let live = |id: &str| {
        let mut rail = AgentRail::default();
        rail.ingest_runs(vec![snapshot(id, "worker", RunState::Running, 1)]);
        rail.rail.items()[0].clone()
    };
    let finished = RailEntry::Finished(FinishedChildren {
        count: 3,
        failed: 0,
        stopped: 0,
    });
    let entries = [live("aa0001"), live("aa0002"), finished];
    for (case, shown, want) in [
        ("one live shown", vec![&entries[0]], 1),
        ("nothing shown", vec![], 2),
        ("both live shown", vec![&entries[0], &entries[1]], 0),
        ("all shown", entries.iter().collect(), 0),
    ] {
        assert_eq!(hidden_live(&entries, &shown), want, "{case}");
    }
}

// Covers: a session the followed session started is a rail row after the
// runs: it counts among the agents while its turn works or waits on a
// person, a click on it follows the session, and `/attach`, which opens
// runs, does not offer it; between turns it no longer counts, and folds
// into the finished row.
// Owner: pure unit (agent rail rows)
#[test]
fn a_started_session_is_an_agent_rail_row() {
    let session = SessionId::new("5054a7c5-68a7-4d13-8a3e-0f6d944aa81b");
    let started = |state| StartedSession {
        session: session.clone(),
        agent: None,
        title: "Bench the parser".into(),
        state,
        elapsed: Some(Duration::from_secs(2)),
    };
    let mut rail = AgentRail::default();
    rail.ingest_runs(vec![snapshot("aa0001", "worker", RunState::Running, 4)]);
    let area = Rect::new(0, 0, 80, 2);
    let seen = |rail: &mut AgentRail, state| {
        rail.ingest_sessions(vec![started(state)]);
        (
            rail.count(),
            rail.attach_target_at(area, 1, 1),
            rail.candidates()
                .into_iter()
                .map(|candidate| candidate.run_id)
                .collect::<Vec<_>>(),
        )
    };
    let followed = Some(AgentRailTarget::Child(ChildTarget::Session(
        session.clone(),
    )));
    let runs = vec!["aa0001".to_owned()];

    assert_eq!(
        [
            seen(&mut rail, RailState::Working),
            seen(&mut rail, RailState::NeedsInput),
            seen(&mut rail, RailState::Idle),
        ],
        [
            (2, followed.clone(), runs.clone()),
            (2, followed, runs.clone()),
            (
                1,
                Some(AgentRailTarget::OpenAttachPicker(WorkspaceRunFilter::All)),
                runs,
            ),
        ]
    );
}