rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
use pretty_assertions::assert_eq;
use rho_sdk::model::{ContentBlock, Message};

use super::SelectNodeError;
use crate::{
    app::session_runtime::{test_support::idle_runtime, SessionRuntime},
    config::Config,
    session::{
        tree::{NodeId, SessionTreeItemContent},
        workspace_checkpoint::CheckpointOutcome,
    },
};

/// The text of each user message the model would read.
fn user_texts(runtime: &SessionRuntime) -> Vec<String> {
    runtime
        .built
        .session
        .history()
        .into_iter()
        .filter_map(|message| match message {
            Message::User(blocks) => Some(
                blocks
                    .iter()
                    .filter_map(|block| match block {
                        ContentBlock::Text(text) => Some(text.as_str()),
                        _ => None,
                    })
                    .collect::<String>(),
            ),
            _ => None,
        })
        .collect()
}

fn leaf(runtime: &SessionRuntime) -> Option<NodeId> {
    let stored = runtime.storage.file().expect("the session is saved");
    stored
        .active_checkpoint_target()
        .unwrap()
        .map(|(node, _)| node)
}

// Covers: selecting a node moves what the model reads, not only the file's
// leaf, back to that node, so the next turn continues from it; a node the
// tree does not hold, or a leaf the file could not record, changes neither.
// Owner: session runtime tree selection
#[tokio::test]
async fn selecting_a_node_moves_the_model_conversation_and_the_leaf_to_it() {
    let home = tempfile::tempdir().unwrap();
    let config = Config::with_model("test", "model", "none");
    let mut runtime = idle_runtime(home.path(), &config).await;
    let add = |runtime: &mut SessionRuntime, text: &str| {
        runtime
            .append_context(
                text.into(),
                Message::user_text(text),
                /*display_key*/ None,
                [],
            )
            .unwrap();
        leaf(runtime).expect("the row saved a node")
    };
    let first = add(&mut runtime, "first");
    let second = add(&mut runtime, "second");

    let unknown = NodeId::from_string("no-such-node").unwrap();
    let stored = runtime.storage.file().unwrap().clone();
    stored.fail_next_leaf_commit_for_tests();
    let unrecorded = runtime.select_node(&first, &config).await.is_err();
    let after_failed_write = (user_texts(&runtime), leaf(&runtime));
    let refused = matches!(
        runtime.select_node(&unknown, &config).await,
        Err(SelectNodeError::UnknownNode(_))
    );
    let after_refusal = (user_texts(&runtime), leaf(&runtime));
    let selected = runtime
        .select_node(&first, &config)
        .await
        .map_err(|error| error.to_string());

    let both = (vec!["first".to_owned(), "second".to_owned()], Some(second));
    assert_eq!(
        (
            (refused, unrecorded),
            after_refusal,
            after_failed_write,
            selected,
            user_texts(&runtime),
            leaf(&runtime)
        ),
        (
            (true, true),
            both.clone(),
            both,
            Ok(()),
            vec!["first".to_owned()],
            Some(first),
        )
    );
    runtime.shutdown().await;
}

// Covers: the tree lists each turn's workspace checkpoint on the row its
// turn started on: a prompt's, and after it that of a turn that carried the
// row on without a prompt, as one delivering background results does; a
// turn that compacted part way, and so ended on the compaction's row, on
// its prompt's row still.
// Owner: session runtime tree rows
#[tokio::test]
async fn each_checkpoint_lists_on_the_row_its_turn_started_on() {
    let home = tempfile::tempdir().unwrap();
    let config = Config::with_model("test", "model", "none");
    let mut runtime = idle_runtime(home.path(), &config).await;
    runtime.built.tools.take_checkpoints_for_tests();
    let save = |runtime: &mut SessionRuntime, display: Message| {
        runtime
            .append_context("context".into(), display, /*display_key*/ None, [])
            .unwrap();
        leaf(runtime).expect("the row saved a node")
    };
    // Each turn opens its checkpoint, saves, and closes it on its last node.
    let turn = |runtime: &mut SessionRuntime, saves: &dyn Fn(&mut SessionRuntime) -> NodeId| {
        runtime.begin_workspace_checkpoint().unwrap();
        let last = saves(runtime);
        runtime.finalize_workspace_checkpoint(CheckpointOutcome::Completed);
        last
    };
    save(&mut runtime, Message::user_text("before"));
    let prompted = turn(&mut runtime, &|runtime| {
        save(runtime, Message::user_text("first"))
    });
    let delivered = turn(&mut runtime, &|runtime| {
        save(runtime, Message::assistant_text("delivered"))
    });
    let compacted = turn(&mut runtime, &|runtime| {
        save(runtime, Message::user_text("second"));
        // A step that compacted, saved as the SDK saves it.
        let stored = runtime.storage.file().unwrap().clone();
        let live = runtime.built.session.snapshot();
        let compacted = rho_sdk::SessionSnapshot::new(
            live.session_id().clone(),
            rho_sdk::Revision::from_u64(live.revision().get() + 1),
            live.history().to_vec(),
            live.provider().clone(),
            rho_sdk::CompactionState::from_parts(1, 1, None),
        );
        stored.save_snapshot(&compacted, &[]).unwrap();
        leaf(runtime).unwrap()
    });

    let rows = runtime
        .tree_rows()
        .unwrap()
        .into_iter()
        .map(|row| {
            let shown = match row.item.content {
                SessionTreeItemContent::Turn { prompt, .. } => {
                    prompt.and_then(|prompt| prompt.text)
                }
                _ => None,
            };
            let checkpoints = row
                .checkpoints
                .into_iter()
                .map(|checkpoint| checkpoint.node_id);
            (shown, checkpoints.collect::<Vec<_>>())
        })
        .collect::<Vec<_>>();
    assert_eq!(
        rows,
        [
            (Some("before".to_owned()), vec![]),
            (Some("first".to_owned()), vec![prompted, delivered]),
            (Some("second".to_owned()), vec![compacted]),
            (None, vec![]),
        ]
    );
    runtime.shutdown().await;
}