use std::{path::Path, sync::Mutex, time::Duration};
use pretty_assertions::assert_eq;
use rho_sdk::{
model::ToolSpec,
tool::{Tool, ToolFuture, ToolInvocation, ToolOutput},
};
use serde_json::{json, Value};
use super::{super::background::Sources, signal::PARENT_ENDED, *};
use crate::tools::{
mcp::exported_name::namespaced_tool_name,
process::{ProcessLimits, ProcessManager, ProcessRole},
sdk_registry::{AppToolSet, StaticToolBundle},
workflow_tracker::WorkflowRunTracker,
};
const SERVER: &str = "t3-code";
const LONG_RUNNING_COMMAND: &str = "sleep 300";
const SERVICE_COMMAND: &str = "sleep 301";
const TEST_WAIT: Duration = Duration::from_secs(10);
const WATCHER_SESSION: &str = "5a7c9e1b-3d4f-4a6b-8c0d-2e4f6a8b0c1d";
type Calls = Arc<Mutex<Vec<(String, Value)>>>;
#[derive(Clone)]
enum Reply {
Now(Box<Result<ToolOutput, ToolError>>),
Never,
}
impl Reply {
fn now(result: Result<ToolOutput, ToolError>) -> Self {
Self::Now(Box::new(result))
}
}
struct T3Tool {
name: &'static str,
calls: Calls,
reply: Reply,
}
impl Tool for T3Tool {
fn spec(&self) -> ToolSpec {
ToolSpec {
name: namespaced_tool_name(SERVER, self.name),
description: String::new(),
input_schema: json!({"type": "object"}),
}
}
fn call<'a>(&'a self, invocation: ToolInvocation, _context: ToolContext) -> ToolFuture<'a> {
self.calls
.lock()
.unwrap()
.push((self.name.to_owned(), invocation.into_arguments()));
let reply = self.reply.clone();
Box::pin(async move {
match reply {
Reply::Now(result) => *result,
Reply::Never => std::future::pending().await,
}
})
}
}
struct Fixture {
_home: tempfile::TempDir,
dir: WakeDir,
tools: AppToolSet,
calls: Calls,
processes: ProcessManager,
workflows: WorkflowRunTracker,
wake: T3Wake,
}
impl Fixture {
fn new() -> Self {
Self::with_delegate(Reply::now(Ok(
ToolOutput::text("delegated").with_structured_content(json!({"taskId": "task-1"}))
)))
}
fn with_delegate(delegate: Reply) -> Self {
let calls = Calls::default();
let mut tools = AppToolSet::disabled();
tools.add_bundle(StaticToolBundle::new(
[
("delegate_task", delegate),
("task_status", Reply::now(Ok(ToolOutput::text("running")))),
(
"task_cancel",
Reply::now(Ok(ToolOutput::text("cancel requested"))),
),
]
.into_iter()
.map(|(name, reply)| {
Arc::new(T3Tool {
name,
calls: calls.clone(),
reply,
}) as Arc<dyn Tool>
})
.collect(),
));
let home = tempfile::tempdir().unwrap();
let dir = WakeDir::in_home(home.path());
let wake = T3Wake::new(dir.clone());
Self {
_home: home,
dir,
tools,
calls,
processes: ProcessManager::new(ProcessLimits::default()),
workflows: WorkflowRunTracker::new(),
wake,
}
}
fn processes(&self) -> &ProcessManager {
&self.processes
}
fn background(&self) -> AwaitedWork {
AwaitedWork::new(
BackgroundWait::HostWakes,
"parent".into(),
self.workflows.clone(),
Sources {
processes: Some(self.processes.clone()),
..Sources::default()
},
)
.expect("a host that wakes its session waits on its work")
}
async fn start_process(&self) -> String {
self.processes()
.start(LONG_RUNNING_COMMAND.into(), Path::new("."), None)
.await
.unwrap()
.process_id
}
async fn stop_process(&self, id: &str) {
let exited = self.processes().notified_owned();
self.processes().stop(id, Duration::ZERO).await.unwrap();
tokio::time::timeout(TEST_WAIT, exited).await.unwrap();
}
async fn prompt_ended(&mut self) {
self.prompt_ended_interrupted_by(&CancellationToken::new())
.await
.unwrap();
}
async fn prompt_ended_interrupted_by(
&mut self,
interrupt: &CancellationToken,
) -> anyhow::Result<()> {
let background = self.background();
self.wake
.prompt_ended(
SessionTools::of_tool_set_for_tests(&self.tools),
background,
interrupt,
)
.await
}
async fn notifier_settled(&mut self) {
let notifier = self.wake.armed.as_mut().unwrap().notifier.as_mut().unwrap();
tokio::time::timeout(TEST_WAIT, &mut notifier.task)
.await
.unwrap()
.unwrap();
}
fn take_calls(&self) -> Vec<(String, Value)> {
std::mem::take(&mut *self.calls.lock().unwrap())
}
fn delegated_signal(task: &Value) -> String {
task.as_str()
.unwrap()
.strip_prefix("/rho-wake ")
.unwrap()
.to_owned()
}
}
#[tokio::test]
async fn running_process_arms_one_watcher_that_wakes_on_exit() {
let mut fixture = Fixture::new();
let service = fixture
.processes()
.start_as(
SERVICE_COMMAND.into(),
Path::new("."),
None,
ProcessRole::Service,
)
.await
.unwrap()
.process_id;
let process = fixture.start_process().await;
fixture.prompt_ended().await;
let calls = fixture.take_calls();
let token = Fixture::delegated_signal(&calls[0].1["task"]);
assert_eq!(
calls,
vec![(
"delegate_task".to_owned(),
json!({
"task": format!("/rho-wake {token}"),
"title": format!("waiting: {LONG_RUNNING_COMMAND}"),
"mode": "async",
}),
)]
);
assert_eq!(
fixture.wake.prompt_started(Some("how is it going?")),
PromptOrigin::Other
);
fixture.prompt_ended().await;
assert_eq!(fixture.take_calls(), Vec::new());
fixture.stop_process(&service).await;
fixture.stop_process(&process).await;
fixture.notifier_settled().await;
assert_eq!(
fixture.wake.prompt_started(Some("still there?")),
PromptOrigin::Other
);
let signal = WakeSignal::parse(&fixture.dir, &token).unwrap();
let summary = tokio::time::timeout(
TEST_WAIT,
signal.wait(WATCHER_SESSION, &CancellationToken::new()),
)
.await
.unwrap();
let summary = summary.expect("the watcher receives the exit");
assert!(
summary.starts_with(LONG_RUNNING_COMMAND),
"the watcher reports the process, not that its parent ended: {summary}"
);
assert_eq!(
fixture.wake.prompt_started(Some(
"Delegated task task-1 reached a terminal state. Use task_status with taskId \
task-1 to read the result."
)),
PromptOrigin::WatcherNotice
);
fixture.processes().take_notifications();
fixture.prompt_ended().await;
assert_eq!(fixture.take_calls(), Vec::new(), "nothing left to watch");
}
#[tokio::test]
async fn work_delivered_in_prompt_retires_the_watcher() {
let mut fixture = Fixture::new();
let process = fixture.start_process().await;
fixture.prompt_ended().await;
let token = Fixture::delegated_signal(&fixture.take_calls()[0].1["task"]);
let signal = WakeSignal::parse(&fixture.dir, &token).unwrap();
assert_eq!(fixture.wake.prompt_started(None), PromptOrigin::Other);
fixture.stop_process(&process).await;
fixture.processes().take_notifications();
fixture.prompt_ended().await;
assert_eq!(
fixture.take_calls(),
vec![("task_cancel".to_owned(), json!({"taskId": "task-1"}))]
);
assert_eq!(fixture.wake.prompt_started(None), PromptOrigin::Other);
fixture.prompt_ended().await;
assert!(
!signal.parent_ended(),
"the cancelled watcher's lock is held"
);
}
#[tokio::test]
async fn workflow_completing_but_unpublished_arms_a_watcher() {
let mut fixture = Fixture::new();
let workflows = &fixture.workflows;
assert!(workflows.register_start("wf-run", "review", "digest", Some("parent".into())));
workflows.record_event(
"wf-run",
&crate::app::workflow_runtime::RuntimeEvent::Completed,
);
fixture.prompt_ended().await;
assert_eq!(
fixture
.take_calls()
.into_iter()
.map(|(tool, _)| tool)
.collect::<Vec<_>>(),
vec!["delegate_task"]
);
}
#[tokio::test]
async fn watcher_that_ended_unsignalled_is_replaced_or_released() {
let mut fixture = Fixture::new();
fixture.start_process().await;
fixture.prompt_ended().await;
let first = Fixture::delegated_signal(&fixture.take_calls()[0].1["task"]);
assert_eq!(
fixture.wake.prompt_started(Some(
"Delegated tasks task-1, task-9 reached terminal states."
)),
PromptOrigin::WatcherNotice
);
fixture.prompt_ended().await;
let second = Fixture::delegated_signal(&fixture.take_calls()[0].1["task"]);
assert_ne!(first, second, "a fresh watcher replaces the ended one");
let signal = WakeSignal::parse(&fixture.dir, &second).unwrap();
let Fixture { wake, .. } = fixture;
drop(wake);
let result = tokio::time::timeout(
TEST_WAIT,
signal.wait(WATCHER_SESSION, &CancellationToken::new()),
)
.await
.unwrap();
assert_eq!(result.as_deref(), Some(PARENT_ENDED));
}
#[tokio::test]
async fn interrupted_arming_gives_up_on_a_hung_host() {
let mut fixture = Fixture::with_delegate(Reply::Never);
fixture.start_process().await;
let interrupt = CancellationToken::new();
interrupt.cancel();
let armed = tokio::time::timeout(TEST_WAIT, fixture.prompt_ended_interrupted_by(&interrupt))
.await
.expect("an interrupted host call gives up");
let locks: Vec<_> = std::fs::read_dir(fixture.dir.path())
.unwrap()
.map(|entry| entry.unwrap().path())
.collect();
let held: Vec<_> = locks
.iter()
.map(|path| {
(
path.extension() == Some("lock".as_ref()),
!signal::released(path),
)
})
.collect();
let ended: Vec<_> = fixture
.wake
.ended
.iter()
.map(|ended| ended.task_id.clone())
.collect();
assert_eq!(
(armed.is_err(), fixture.wake.armed.is_none(), held, ended),
(true, true, vec![(true, true)], vec![None])
);
}
#[test]
fn finish_notice_names_its_task_whole() {
for (text, expected) in [
("task task-1 finished", true),
("Task \"task-1\" completed.", true),
("task-1", true),
("task task-12 finished", false),
("task subtask-1 finished", false),
("no task here", false),
] {
assert_eq!(names_task(text, "task-1"), expected, "{text}");
}
}
#[derive(Debug, PartialEq)]
enum Command {
Wake(String),
Rejected,
NotWake,
}
#[test]
fn wake_command_matches_only_a_uuid_token() {
let home = tempfile::tempdir().unwrap();
let dir = WakeDir::in_home(home.path());
let cases = [
(
"wake watcher",
Some("/rho-wake 0F4E2C3A-9B1D-4E5F-8A7B-6C5D4E3F2A1B"),
Command::Wake("0f4e2c3a-9b1d-4e5f-8a7b-6c5d4e3f2a1b".into()),
),
(
"wake token that could name a path",
Some("/rho-wake ../config.toml"),
Command::Rejected,
),
(
"wake prefix of a longer word",
Some("/rho-wakeup now"),
Command::NotWake,
),
("prompt without leading text", None, Command::NotWake),
];
for (label, text, expected) in cases {
let command = match wake_command(&dir, text) {
Some(Ok(signal)) => Command::Wake(signal.token().to_owned()),
Some(Err(_)) => Command::Rejected,
None => Command::NotWake,
};
assert_eq!(command, expected, "{label}");
}
}