use std::path::PathBuf;
use std::sync::Arc;
use serde::Deserialize;
use serde_json::{Value, json};
use crate::jsonrpc::{ConnectionContext, Router, RpcError};
use crate::session::SessionRegistry;
use super::executor::{TaskRunParams, spawn_task_run};
use super::mock_llm::build_llm_client;
pub fn register(
router: &mut Router,
registry: Arc<SessionRegistry>,
project: PathBuf,
agents_dir: PathBuf,
) {
router.register("task.run", move |params: Value, _ctx: ConnectionContext| {
let registry = Arc::clone(®istry);
let project = project.clone();
let agents_dir = agents_dir.clone();
async move { task_run(registry, params, project, agents_dir).await }
});
}
#[derive(Deserialize)]
struct TaskRunRequestParams {
task_description: String,
#[serde(default)]
agent_name: Option<String>,
#[serde(default)]
#[allow(dead_code)]
context: Option<String>,
#[serde(default)]
model_override: Option<String>,
#[serde(default)]
session_id: Option<String>,
#[serde(default)]
mode: Option<String>,
#[serde(default)]
deadline_secs: Option<u64>,
}
async fn task_run(
registry: Arc<SessionRegistry>,
params: Value,
project: PathBuf,
agents_dir: PathBuf,
) -> Result<Value, RpcError> {
let p: TaskRunRequestParams = serde_json::from_value(params)
.map_err(|e| RpcError::invalid_params(format!("task.run: {e}")))?;
if p.task_description.trim().is_empty() {
return Err(RpcError::invalid_argument(
"task_description must not be empty",
));
}
let agent_name = p.agent_name.unwrap_or_else(|| "pm".to_string());
let session_id = match &p.session_id {
Some(id) => {
registry.status(id)?; id.clone()
}
None => {
let session = registry.create(
p.task_description.clone(),
Some(agent_name.clone()),
Some(project.display().to_string()),
);
session.id
}
};
let mode = crate::mode::resolve_mode(p.mode.as_deref(), &project);
registry.set_mode(&session_id, mode)?;
let llm = build_llm_client()?;
let task_params = TaskRunParams {
session_id: session_id.clone(),
task: p.task_description,
agent_name,
project,
agents_dir,
model_override: p.model_override,
mode,
deadline_secs: p.deadline_secs,
};
spawn_task_run(registry, llm, task_params)?;
Ok(json!({ "session_id": session_id, "status": "running", "mode": mode.as_str() }))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::jsonrpc::Request;
use tokio::sync::mpsc;
fn test_ctx() -> ConnectionContext {
let (tx, _rx) = mpsc::unbounded_channel();
ConnectionContext::new(tx)
}
fn agents_dir() -> tempfile::TempDir {
let tmp = tempfile::tempdir().expect("agents tempdir");
std::fs::write(
tmp.path().join("pm.toml"),
"[agent]\nname = \"pm\"\nmodel = \"openai/gpt-4o-mini\"\n[system_prompt]\ncontent = \"You are the PM.\"\n",
)
.expect("write pm.toml");
std::fs::write(
tmp.path().join("python-engineer.toml"),
"[agent]\nname = \"python-engineer\"\nmodel = \"deepseek/deepseek-chat\"\n[system_prompt]\ncontent = \"engineer\"\n",
)
.expect("write python-engineer.toml");
tmp
}
#[tokio::test]
async fn register_wires_task_run() {
let _guard = super::super::mock_llm::MOCK_LLM_ENV_LOCK.lock().await;
unsafe {
std::env::set_var(
super::super::mock_llm::MOCK_LLM_ENV,
super::super::mock_llm::MOCK_LLM_ECHO,
);
}
let registry = Arc::new(SessionRegistry::new());
let agents = agents_dir();
let project = tempfile::tempdir().expect("project tempdir");
let mut router = Router::new();
register(
&mut router,
registry,
project.path().to_path_buf(),
agents.path().to_path_buf(),
);
let req = Request {
jsonrpc: Some("2.0".to_string()),
id: Some(json!(1)),
method: "task.run".to_string(),
params: Some(json!({"task_description": "say hi"})),
};
let resp = router.dispatch(req, &test_ctx()).await;
unsafe {
std::env::remove_var(super::super::mock_llm::MOCK_LLM_ENV);
}
assert!(
resp.error.is_none(),
"task.run should succeed, got {:?}",
resp.error
);
assert_eq!(resp.result.unwrap()["status"], "running");
}
#[tokio::test]
async fn task_run_rejects_empty_task_description() {
let registry = Arc::new(SessionRegistry::new());
let agents = agents_dir();
let project = tempfile::tempdir().expect("project tempdir");
let err = task_run(
registry,
json!({"task_description": " "}),
project.path().to_path_buf(),
agents.path().to_path_buf(),
)
.await
.unwrap_err();
assert_eq!(err.code, -32003);
}
#[tokio::test]
async fn task_run_creates_session_when_none_given() {
let _guard = super::super::mock_llm::MOCK_LLM_ENV_LOCK.lock().await;
unsafe {
std::env::set_var(
super::super::mock_llm::MOCK_LLM_ENV,
super::super::mock_llm::MOCK_LLM_ECHO,
);
}
let registry = Arc::new(SessionRegistry::new());
let agents = agents_dir();
let project = tempfile::tempdir().expect("project tempdir");
let result = task_run(
Arc::clone(®istry),
json!({"task_description": "say hi"}),
project.path().to_path_buf(),
agents.path().to_path_buf(),
)
.await;
unsafe {
std::env::remove_var(super::super::mock_llm::MOCK_LLM_ENV);
}
let value = result.expect("task.run should succeed");
let session_id = value["session_id"].as_str().expect("session_id string");
assert!(
registry.status(session_id).is_ok(),
"a new session must have been created"
);
}
#[tokio::test]
async fn task_run_resolves_and_reports_mode() {
let _mock_guard = super::super::mock_llm::MOCK_LLM_ENV_LOCK.lock().await;
let _mode_guard = crate::mode::MODE_ENV_LOCK.lock().await;
unsafe {
std::env::set_var(
super::super::mock_llm::MOCK_LLM_ENV,
super::super::mock_llm::MOCK_LLM_ECHO,
);
std::env::remove_var(crate::mode::MODE_ENV_VAR);
}
let agents = agents_dir();
let project = tempfile::tempdir().expect("project tempdir");
let registry = Arc::new(SessionRegistry::new());
let value = task_run(
Arc::clone(®istry),
json!({"task_description": "say hi"}),
project.path().to_path_buf(),
agents.path().to_path_buf(),
)
.await
.expect("task.run should succeed");
assert_eq!(value["mode"], "daily-driver");
let session_id = value["session_id"].as_str().unwrap().to_string();
assert_eq!(
registry.status(&session_id).unwrap().mode,
Some(crate::mode::HarnessMode::DailyDriver)
);
let project2 = tempfile::tempdir().expect("project tempdir");
std::fs::create_dir_all(project2.path().join(".claude")).expect("mkdir");
std::fs::write(
project2.path().join(".claude").join("settings.json"),
r#"{"code_harness": {"mode": "parity"}}"#,
)
.expect("write settings.json");
let registry2 = Arc::new(SessionRegistry::new());
let value2 = task_run(
Arc::clone(®istry2),
json!({"task_description": "say hi"}),
project2.path().to_path_buf(),
agents.path().to_path_buf(),
)
.await
.expect("task.run should succeed");
assert_eq!(value2["mode"], "parity");
let registry3 = Arc::new(SessionRegistry::new());
let value3 = task_run(
Arc::clone(®istry3),
json!({"task_description": "say hi", "mode": "daily-driver"}),
project2.path().to_path_buf(),
agents.path().to_path_buf(),
)
.await
.expect("task.run should succeed");
assert_eq!(
value3["mode"], "daily-driver",
"task.run's mode param must override settings.json"
);
unsafe {
std::env::set_var(crate::mode::MODE_ENV_VAR, "parity");
}
let registry4 = Arc::new(SessionRegistry::new());
let value4 = task_run(
Arc::clone(®istry4),
json!({"task_description": "say hi", "mode": "daily-driver"}),
project2.path().to_path_buf(),
agents.path().to_path_buf(),
)
.await
.expect("task.run should succeed");
assert_eq!(
value4["mode"], "parity",
"TRUSTY_CODE_MODE must win over a task.run mode param"
);
unsafe {
std::env::remove_var(super::super::mock_llm::MOCK_LLM_ENV);
std::env::remove_var(crate::mode::MODE_ENV_VAR);
}
}
#[tokio::test]
async fn task_run_unknown_session_id_errors() {
let registry = Arc::new(SessionRegistry::new());
let agents = agents_dir();
let project = tempfile::tempdir().expect("project tempdir");
let err = task_run(
registry,
json!({"task_description": "say hi", "session_id": "does-not-exist"}),
project.path().to_path_buf(),
agents.path().to_path_buf(),
)
.await
.unwrap_err();
assert_eq!(err.code, -32007);
}
#[tokio::test]
async fn task_run_sessionful_reuses_existing_session() {
let _guard = super::super::mock_llm::MOCK_LLM_ENV_LOCK.lock().await;
unsafe {
std::env::set_var(
super::super::mock_llm::MOCK_LLM_ENV,
super::super::mock_llm::MOCK_LLM_ECHO,
);
}
let registry = Arc::new(SessionRegistry::new());
let existing = registry.create("say hi".to_string(), None, None);
let agents = agents_dir();
let project = tempfile::tempdir().expect("project tempdir");
let result = task_run(
Arc::clone(®istry),
json!({"task_description": "say hi", "session_id": existing.id}),
project.path().to_path_buf(),
agents.path().to_path_buf(),
)
.await;
unsafe {
std::env::remove_var(super::super::mock_llm::MOCK_LLM_ENV);
}
let value = result.expect("task.run should succeed");
assert_eq!(value["session_id"], existing.id);
}
#[tokio::test]
async fn task_run_second_call_after_finish_continues_the_session() {
let _guard = super::super::mock_llm::MOCK_LLM_ENV_LOCK.lock().await;
unsafe {
std::env::set_var(
super::super::mock_llm::MOCK_LLM_ENV,
super::super::mock_llm::MOCK_LLM_ECHO,
);
}
let registry = Arc::new(SessionRegistry::new());
let agents = agents_dir();
let project = tempfile::tempdir().expect("project tempdir");
let first = task_run(
Arc::clone(®istry),
json!({"task_description": "say hi"}),
project.path().to_path_buf(),
agents.path().to_path_buf(),
)
.await
.expect("first task.run should succeed");
let session_id = first["session_id"].as_str().unwrap().to_string();
let deadline = tokio::time::Instant::now() + tokio::time::Duration::from_secs(5);
loop {
let status = registry.status(&session_id).expect("session must exist");
if status.status.is_terminal() {
break;
}
assert!(
tokio::time::Instant::now() < deadline,
"first run did not reach a terminal state within 5s"
);
tokio::time::sleep(tokio::time::Duration::from_millis(20)).await;
}
let second = task_run(
Arc::clone(®istry),
json!({"task_description": "say hi again", "session_id": session_id}),
project.path().to_path_buf(),
agents.path().to_path_buf(),
)
.await;
unsafe {
std::env::remove_var(super::super::mock_llm::MOCK_LLM_ENV);
}
let value = second.expect("a second task.run on a Finished session must be accepted");
assert_eq!(value["session_id"], session_id);
assert_eq!(value["status"], "running");
}
}