rho-coding-agent 3.3.0

A fast Rust agent harness with a small footprint and opinionated defaults
use std::{ffi::OsString, num::NonZeroUsize, sync::MutexGuard, time::Duration};

use pretty_assertions::assert_eq;
use rho_sdk::{
    tool::{tool_progress_channel, Tool, ToolContext, ToolInvocation},
    CancellationToken, ToolCallId, Workspace,
};

use super::*;
use crate::{config::Config, subagent::RunState, tools::agent_output::MODEL_NOTIFICATION_BYTES};

/// Isolates delegated-run storage and agent discovery from the developer's own
/// home, so these tests see the same catalog everywhere they run.
struct IsolatedRhoHome {
    _dir: tempfile::TempDir,
    _guard: MutexGuard<'static, ()>,
    previous: Vec<(&'static str, Option<OsString>)>,
}

impl IsolatedRhoHome {
    fn new() -> Self {
        let guard = crate::paths::process_env_lock();
        let dir = tempfile::tempdir().expect("rho home tempdir");
        // `HOME` too: agent discovery reads `~/.rho/agents` and
        // `~/.agents/agents`, so a developer's own agents would otherwise
        // change what the catalog holds.
        let previous = ["RHO_HOME", "HOME"]
            .into_iter()
            .map(|name| {
                let previous = std::env::var_os(name);
                std::env::set_var(name, dir.path());
                (name, previous)
            })
            .collect();
        Self {
            _dir: dir,
            _guard: guard,
            previous,
        }
    }
}

impl Drop for IsolatedRhoHome {
    fn drop(&mut self) {
        for (name, previous) in &self.previous {
            match previous {
                Some(value) => std::env::set_var(name, value),
                None => std::env::remove_var(name),
            }
        }
    }
}

struct ManagerFixture {
    manager: SubagentManager,
    _rho_home: IsolatedRhoHome,
}

impl ManagerFixture {
    fn new(root: &Path) -> Self {
        let rho_home = IsolatedRhoHome::new();
        Self {
            manager: SubagentManager::new(
                Config::default(),
                root.join("rho.toml"),
                root.to_path_buf(),
                crate::app::subagent_pool::SubagentPool::Own,
            ),
            _rho_home: rho_home,
        }
    }

    fn manager(&self) -> SubagentManager {
        self.manager.clone()
    }
}

fn manager(root: &Path) -> ManagerFixture {
    ManagerFixture::new(root)
}

fn invocation(arguments: serde_json::Value) -> ToolInvocation {
    ToolInvocation::new(ToolCallId::from_string("call-1").unwrap(), arguments)
}

fn tool_context(root: &Path) -> ToolContext {
    let (progress, _receiver) = tool_progress_channel(NonZeroUsize::new(4).unwrap());
    ToolContext::new(
        Some(Workspace::new(root).unwrap()),
        CancellationToken::new(),
        progress,
    )
}

async fn call_agent(tool: &AgentTool, root: &Path, arguments: serde_json::Value) -> ToolOutput {
    tool.call(invocation(arguments), tool_context(root))
        .await
        .expect("agent tool call")
}

fn notification(id: &str, agent_id: &str, state: RunState) -> SubagentNotification {
    SubagentNotification {
        snapshot: SubagentSnapshot {
            prior_notices: Vec::new(),
            persistence: crate::session::SessionPersistence::Saved,
            id: id.into(),
            agent_id: agent_id.into(),
            title: None,
            elapsed: Duration::from_secs(5),
            status: crate::subagent::RunStatus {
                state,
                turns: 1,
                input_tokens: Some(10),
                output_tokens: Some(2),
                result: Some(format!("{id} result")),
                ..crate::subagent::RunStatus::default()
            },
            done: true,
        },
    }
}

#[test]
fn notification_prompts_bound_many_large_utf8_results_and_keep_run_statuses() {
    let notifications = (0..96)
        .map(|index| {
            let id = format!("run{index:03}");
            let mut notification = notification(&id, "worker", RunState::Ok);
            notification.snapshot.status.result = Some("🦀".repeat(12 * 1024));
            notification
        })
        .collect::<Vec<_>>();

    let model = notification_prompt(&notifications);

    assert!(
        model.len() <= MODEL_NOTIFICATION_BYTES,
        "{}-byte notification exceeded the {}-byte budget",
        model.len(),
        MODEL_NOTIFICATION_BYTES
    );
    for index in 0..notifications.len() {
        assert!(
            model.contains(&format!("agent run{index:03} (worker): ok")),
            "missing status for run {index}"
        );
    }
    assert_eq!(model, notification_prompt(&notifications));
}

async fn spawn_background_run(manager: &SubagentManager, root: &Path) -> String {
    let tool = AgentTool::new(
        manager.clone(),
        root,
        /*catalog*/ None,
        crate::workspace::ProjectTrusts::UNTRUSTED,
    );
    let output = call_agent(
        &tool,
        root,
        serde_json::json!({
            "agent_id": "default",
            "prompt": "background task",
        }),
    )
    .await;
    // Parse the start receipt. Do not use list().last(): list sorts by elapsed,
    // so equal-duration runs make "last" non-deterministic across HashMap order.
    let content = output.content();
    let id = content
        .strip_prefix("agent ")
        .and_then(|rest| rest.split_once(' ').map(|(id, _)| id))
        .expect("background start receipt names the run id");
    assert_eq!(id.len(), 6, "run id should be 6 hex chars: {content}");
    id.to_string()
}

#[tokio::test]
async fn running_queries_are_scoped_to_the_parent_session() {
    let root = tempfile::tempdir().unwrap();
    let fixture = manager(root.path());
    let manager = fixture.manager();
    manager.bind_parent_session(
        "session-1",
        /*storage*/ None,
        crate::session::SessionPersistence::Saved,
    );
    let id = spawn_background_run(&manager, root.path()).await;

    assert!(!manager.has_running_for_session("session-2"));
    assert!(!manager.has_active_or_pending_notification("session-2"));

    manager.stop(&id).await.unwrap();
}

#[tokio::test]
async fn observed_terminal_run_is_not_redelivered() {
    let root = tempfile::tempdir().unwrap();
    let fixture = manager(root.path());
    let manager = fixture.manager();
    manager.bind_parent_session(
        "session-1",
        /*storage*/ None,
        crate::session::SessionPersistence::Saved,
    );
    let id = spawn_background_run(&manager, root.path()).await;
    let snapshot = manager.wait_done(&id).await.unwrap();
    assert!(snapshot.done);
    // Reading the terminal snapshot counts as delivery.
    let observed = manager.observe(&id).unwrap();
    assert!(observed.done);
    assert!(manager.take_notifications("session-1").is_empty());
    assert!(!manager.has_active_or_pending_notification("session-1"));
}

#[tokio::test]
async fn unobserved_terminal_runs_drain_as_one_batch() {
    let root = tempfile::tempdir().unwrap();
    let fixture = manager(root.path());
    let manager = fixture.manager();
    manager.bind_parent_session(
        "session-1",
        /*storage*/ None,
        crate::session::SessionPersistence::Saved,
    );
    let first = spawn_background_run(&manager, root.path()).await;
    let second = spawn_background_run(&manager, root.path()).await;
    manager.wait_done(&first).await.unwrap();
    manager.wait_done(&second).await.unwrap();
    let batch = manager.take_notifications("session-1");
    let ids = batch
        .iter()
        .map(|notification| notification.snapshot.id.clone())
        .collect::<Vec<_>>();
    assert_eq!(ids, vec![first, second], "batch drains in launch order");
    assert!(
        manager.take_notifications("session-1").is_empty(),
        "a drained batch is observed and never redelivered"
    );
}

#[tokio::test]
async fn restored_notifications_can_drain_again() {
    let root = tempfile::tempdir().unwrap();
    let fixture = manager(root.path());
    let manager = fixture.manager();
    manager.bind_parent_session(
        "session-1",
        /*storage*/ None,
        crate::session::SessionPersistence::Saved,
    );
    let id = spawn_background_run(&manager, root.path()).await;
    manager.wait_done(&id).await.unwrap();
    let batch = manager.take_notifications("session-1");
    assert_eq!(batch.len(), 1);
    manager.restore_notifications(&batch);
    let again = manager.take_notifications("session-1");
    assert_eq!(
        again
            .iter()
            .map(|notification| notification.snapshot.id.clone())
            .collect::<Vec<_>>(),
        vec![id]
    );
}

// Covers: launches resolve the definition from disk, so an agent deleted
// mid-session (for example from `/agents`) stops launching even though the
// startup catalog listed it.
// Owner: agent tool launch
#[tokio::test]
async fn deleted_agent_no_longer_launches() {
    let root = tempfile::tempdir().unwrap();
    let fixture = manager(root.path());
    let home = std::path::PathBuf::from(std::env::var_os("HOME").expect("isolated home"));
    let agents = home.join(".rho/agents");
    std::fs::create_dir_all(&agents).unwrap();
    let path = agents.join("doomed.md");
    std::fs::write(&path, "---\ndescription: doomed\n---\nbody\n").unwrap();
    let tool = AgentTool::new(
        fixture.manager(),
        root.path(),
        /*catalog*/ None,
        crate::workspace::ProjectTrusts::UNTRUSTED,
    );
    std::fs::remove_file(&path).unwrap();

    let error = tool
        .call(
            invocation(serde_json::json!({"agent_id": "doomed", "prompt": "task"})),
            tool_context(root.path()),
        )
        .await
        .expect_err("deleted agent must not launch");

    assert_eq!(error.kind(), ToolErrorKind::InvalidArguments);
}

#[tokio::test]
async fn concurrent_background_launches_register_together() {
    let root = tempfile::tempdir().unwrap();
    let fixture = manager(root.path());
    let manager = fixture.manager();
    manager.bind_parent_session(
        "session-1",
        /*storage*/ None,
        crate::session::SessionPersistence::Saved,
    );
    let tool = AgentTool::new(
        manager.clone(),
        root.path(),
        /*catalog*/ None,
        crate::workspace::ProjectTrusts::UNTRUSTED,
    );
    let first = call_agent(
        &tool,
        root.path(),
        serde_json::json!({
            "agent_id": "default",
            "prompt": "first background task",
        }),
    );
    let second = call_agent(
        &tool,
        root.path(),
        serde_json::json!({
            "agent_id": "default",
            "prompt": "second background task",
        }),
    );
    let (first, second) = tokio::join!(first, second);
    let runs = manager.list();
    assert_eq!(runs.len(), 2, "both background launches should register");
    let ids = runs.iter().map(|run| run.id.as_str()).collect::<Vec<_>>();
    assert!(ids.iter().any(|id| first.content().contains(id)));
    assert!(ids.iter().any(|id| second.content().contains(id)));
}

// Covers: the agent list must not name any agent's model. The conversation
// model can switch and a catalog name can arrive after this list is written, and
// rewriting it would change what the caller was already told. Each run reports
// its own model instead.
// Owner: agent tool description.
#[test]
fn agent_list_never_names_an_agent_model() {
    let root = tempfile::tempdir().unwrap();
    let fixture = manager(root.path());
    let manager = fixture.manager();
    let tool = AgentTool::new(
        manager.clone(),
        root.path(),
        /*catalog*/ None,
        crate::workspace::ProjectTrusts::UNTRUSTED,
    );
    let baseline = tool.spec().description;

    let agents = baseline
        .split_once("\n\nAgents:\n")
        .expect("the description lists agents")
        .1;
    assert_eq!(
        agents
            .lines()
            .map(|line| line.split_once(": ").expect("id then description").0)
            .collect::<Vec<_>>(),
        vec!["explorer", "reviewer", "worker"]
    );
    assert!(!agents.contains("openai/gpt-5.5"), "{agents}");

    manager.update_selection(
        "anthropic",
        "claude-fable-5",
        rho_sdk::ReasoningLevel::High,
        "anthropic-api-key",
    );

    assert_eq!(
        tool.spec().description,
        baseline,
        "a model switch must not rewrite the agent list"
    );
}