rho-coding-agent 3.9.0

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

use pretty_assertions::assert_eq;
use rho_protocol::{
    self as wire, ContentBlock, ErrorCode, MessageId, SessionChange, SessionConfigureParams,
    SessionTreeParams, TreeRowContent,
};
use rho_sdk::model::Message;
use tempfile::TempDir;

use super::super::{
    test_sessions::{load, Load},
    LoadedSession, Sessions,
};
use super::rewind_to_wire;
use crate::{
    app::{
        daemon_host::{
            jobs::{JobRegistry, JobStore},
            wire::session_to_wire,
        },
        pull_requests::ScriptedForge,
    },
    session::tree::MessageKey,
};

/// Saves `text` as a prompt of `session`'s conversation, under `key` as a
/// live turn would save it, and has its feed take the saved rows.
async fn prompt(session: &LoadedSession, text: &str, key: Option<&str>) {
    let mut runtime = session.runtime.lock().await;
    let runtime = runtime.as_mut().unwrap();
    runtime
        .append_context(
            text.into(),
            Message::user_text(text),
            key.map(MessageKey::new),
            [],
        )
        .unwrap();
    super::super::turn::save_transcript(session, runtime);
}

/// The prompts a client attaching now is replayed, by text.
fn replayed(session: &LoadedSession) -> Vec<(String, MessageId)> {
    session
        .feed
        .reset_replay_for_tests()
        .into_iter()
        .filter_map(|event| match event {
            wire::SessionEvent::UserMessage {
                message, content, ..
            } => match content.as_slice() {
                [ContentBlock::Text { text }] => Some((text.clone(), message)),
                _ => None,
            },
            _ => None,
        })
        .collect()
}

// Covers: a client lists a session's tree with each turn's place in it, the
// row it follows and which row the conversation continues from, and finds
// each row's prompt in its transcript by the id a replay gives it, keyed by
// the live turn or not, on the branch it left too; a row it then selects is
// one the daemon takes.
// Owner: daemon session tree.
#[tokio::test]
async fn a_client_finds_each_tree_rows_prompt_in_its_replay() {
    let (root, home) = (TempDir::new().unwrap(), TempDir::new().unwrap());
    let sessions = Sessions::new(
        Arc::new(JobRegistry::open(JobStore::open(home.path()).unwrap())),
        home.path(),
        ScriptedForge::new(),
    );
    let session = load(&sessions, &root, Load::Saved).await;
    let tree = || sessions.tree(SessionTreeParams::new(session_to_wire(session.id.clone())));
    prompt(&session, "first", None).await;
    prompt(&session, "second", Some("live-key")).await;
    let before_branch = replayed(&session);
    let first = tree()
        .await
        .unwrap()
        .rows
        .into_iter()
        .find_map(|row| match row.content {
            TreeRowContent::Turn(turn) if turn.prompt.as_ref().unwrap().text == "first" => {
                Some(row.id)
            }
            _ => None,
        });
    sessions
        .configure(SessionConfigureParams {
            session: session_to_wire(session.id.clone()),
            change: SessionChange::SelectNode {
                node: first.unwrap().as_str().to_owned(),
            },
        })
        .await
        .unwrap();
    prompt(&session, "other", None).await;
    let after_branch = replayed(&session);

    let listed = tree().await.unwrap();
    let text_of = |id: &Option<wire::TreeNodeId>| {
        listed
            .rows
            .iter()
            .find(|row| Some(&row.id) == id.as_ref())
            .and_then(|row| match &row.content {
                TreeRowContent::Turn(turn) => Some(turn.prompt.as_ref().unwrap().text.clone()),
                _ => None,
            })
    };
    let turns = listed
        .rows
        .iter()
        .filter_map(|row| match &row.content {
            TreeRowContent::Turn(turn) => {
                let prompt = turn.prompt.clone().unwrap();
                Some(((prompt.text, prompt.message), text_of(&row.parent)))
            }
            _ => None,
        })
        .collect::<Vec<_>>();
    let id = |replay: &[(String, MessageId)], text: &str| {
        let (text, id) = replay.iter().find(|(shown, _)| shown == text).unwrap();
        (text.clone(), id.clone())
    };
    assert_eq!(
        (turns, text_of(&listed.current)),
        (
            vec![
                (id(&after_branch, "first"), None),
                (id(&before_branch, "second"), Some("first".to_owned())),
                (id(&after_branch, "other"), Some("first".to_owned())),
            ],
            Some("other".to_owned())
        )
    );
}

// Covers: a rewind held to a tip the conversation moved on from is
// `ConversationMoved`, before the checkpoint is looked at, so a client
// re-previews rather than reading a stale checkpoint as a bad one; held to
// the tip it is at, the checkpoint is judged as without a tip.
// Owner: daemon session tree.
#[tokio::test]
async fn a_rewind_held_to_a_tip_the_conversation_left_is_conversation_moved() {
    let (root, home) = (TempDir::new().unwrap(), TempDir::new().unwrap());
    let sessions = Sessions::new(
        Arc::new(JobRegistry::open(JobStore::open(home.path()).unwrap())),
        home.path(),
        ScriptedForge::new(),
    );
    let session = load(&sessions, &root, Load::Saved).await;
    let tree = || sessions.tree(SessionTreeParams::new(session_to_wire(session.id.clone())));
    prompt(&session, "previewed", None).await;
    let previewed = tree().await.unwrap().current.unwrap();
    prompt(&session, "unseen", None).await;
    let now = tree().await.unwrap().current.unwrap();
    let rewind = |tip: &wire::TreeNodeId| {
        sessions.rewind(wire::SessionRewindParams::new(
            session_to_wire(session.id.clone()),
            // No turn of this session took a checkpoint.
            previewed.clone(),
            tip.clone(),
        ))
    };

    let stale = rewind(&previewed).await.unwrap_err();
    let current = rewind(&now).await.unwrap_err();

    assert_eq!(
        (stale.code, current.code),
        (
            ErrorCode::ConversationMoved.code(),
            ErrorCode::InvalidParams.code()
        )
    );
}

// Covers: what a rewind answers says, per file, whether it was written,
// left, or failed, and whether the conversation moved to the row before the
// turn, stayed, or could not move, so a client reads the outcome rather than
// the notice or a detach.
// Owner: daemon session tree (rewind outcome on the wire).
#[test]
fn a_rewind_answers_what_became_of_each_file_and_the_conversation() {
    use std::path::PathBuf;

    use crate::{
        app::session_runtime::{RewoundConversation, SelectNodeError, WorkspaceRewind},
        session::{
            tree::NodeId,
            workspace_checkpoint::{RestoreAudit, RestoreAuditEntry, RestoreClassification},
        },
    };

    let node = |id: &str| NodeId::from_string(id).unwrap();
    let entry = |path: &str, classification, changed, error: Option<&str>| RestoreAuditEntry {
        path: PathBuf::from(path),
        classification,
        changed,
        error: error.map(str::to_owned),
    };
    let rewind = |conversation| WorkspaceRewind {
        turns: vec![node("first"), node("second")],
        audit: RestoreAudit {
            entries: vec![
                entry("/w/a", RestoreClassification::Modify, true, None),
                entry("/w/b", RestoreClassification::Conflict, false, None),
                entry("/w/c", RestoreClassification::Delete, false, Some("denied")),
            ],
            limitations: Vec::new(),
            uncaptured_turns: 1,
        },
        conversation,
    };

    let moved = rewind_to_wire(rewind(RewoundConversation::Moved { row: node("row") }));
    let outcomes = [
        RewoundConversation::Stayed,
        RewoundConversation::MoveFailed(SelectNodeError::Unsaved),
    ]
    .map(|conversation| rewind_to_wire(rewind(conversation)).conversation);

    let file =
        |path: &str, action, result| wire::RewoundFile::new(PathBuf::from(path), action, result);
    assert_eq!(
        (moved, outcomes),
        (
            wire::SessionRewindResponse::new(
                vec![
                    wire::TreeNodeId::new("first"),
                    wire::TreeNodeId::new("second")
                ],
                vec![
                    file(
                        "/w/a",
                        wire::RewindAction::Restore,
                        wire::RewoundFileResult::Written
                    ),
                    file(
                        "/w/b",
                        wire::RewindAction::Conflict,
                        wire::RewoundFileResult::Left
                    ),
                    file(
                        "/w/c",
                        wire::RewindAction::Delete,
                        wire::RewoundFileResult::Failed {
                            error: "denied".to_owned()
                        }
                    ),
                ],
                Vec::new(),
                1,
                wire::RewoundConversation::Moved {
                    to: wire::TreeNodeId::new("row")
                },
            ),
            [
                wire::RewoundConversation::Stayed,
                wire::RewoundConversation::MoveFailed {
                    error: "the session has no saved conversation yet".to_owned()
                },
            ]
        )
    );
}