use crate::support;
use serde_json::json;
use support::{StdioSession, find_session_event, project_with_agents, run_task_to_completion};
#[tokio::test]
async fn task_run_streams_live_tool_events_to_completion() {
let project = project_with_agents();
let mut daemon = StdioSession::spawn_with_mock_llm(project.path());
let run_resp = daemon
.call(1, "task.run", json!({"task_description": "say hi"}))
.await;
assert!(run_resp["error"].is_null(), "task.run failed: {run_resp}");
let session_id = run_resp["result"]["session_id"]
.as_str()
.expect("task.run must return a session_id")
.to_string();
assert_eq!(run_resp["result"]["status"], "running");
let attach_resp = daemon
.call(2, "session.attach", json!({"session_id": session_id}))
.await;
assert!(
attach_resp["error"].is_null(),
"attach failed: {attach_resp}"
);
let mut kinds: Vec<String> = attach_resp["result"]["events"]
.as_array()
.expect("attach must return a replay events array")
.iter()
.map(|e| {
e["kind"]
.as_str()
.expect("kind must be a string")
.to_string()
})
.collect();
let mut iterations = 0;
while !kinds.iter().any(|k| k == "session_done") {
iterations += 1;
assert!(
iterations < 20,
"gave up waiting for session_done after {iterations} read rounds; kinds so far: {kinds:?}"
);
let lines = daemon.read_lines(20).await;
assert!(
!lines.is_empty(),
"timed out waiting for more events; kinds so far: {kinds:?}"
);
for line in &lines {
if let Some(envelope) = find_session_event(line, &session_id) {
kinds.push(
envelope["kind"]
.as_str()
.expect("kind must be a string")
.to_string(),
);
}
}
}
let tool_started = kinds.iter().filter(|k| *k == "tool_started").count();
let tool_finished = kinds.iter().filter(|k| *k == "tool_finished").count();
assert_eq!(
tool_started, 2,
"expected tool_started for delegate_to_agent + bash: {kinds:?}"
);
assert_eq!(
tool_finished, 2,
"expected tool_finished for delegate_to_agent + bash: {kinds:?}"
);
assert!(
!kinds.iter().any(|k| k == "tool_error"),
"the scripted mock run must complete without a fatal tool error: {kinds:?}"
);
let status_resp = daemon
.call(3, "session.status", json!({"session_id": session_id}))
.await;
assert!(
status_resp["error"].is_null(),
"status failed: {status_resp}"
);
assert_eq!(status_resp["result"]["status"], "finished");
daemon.shutdown_via_eof_and_assert_clean_exit().await;
}
#[tokio::test]
async fn task_run_rejects_a_second_overlapping_run() {
let project = project_with_agents();
let mut daemon = StdioSession::spawn_with_mock_llm(project.path());
let create_resp = daemon
.call(1, "session.create", json!({"task": "e2e overlap task"}))
.await;
assert!(
create_resp["error"].is_null(),
"create failed: {create_resp}"
);
let session_id = create_resp["result"]["id"]
.as_str()
.expect("session.create must return an id")
.to_string();
let first = daemon
.call(
2,
"task.run",
json!({"task_description": "say hi", "session_id": session_id}),
)
.await;
assert!(
first["error"].is_null(),
"first task.run must succeed: {first}"
);
let second = daemon
.call(
3,
"task.run",
json!({"task_description": "say hi again", "session_id": session_id}),
)
.await;
assert!(
second["error"].is_object(),
"a second overlapping task.run must be rejected: {second}"
);
assert_eq!(second["error"]["code"], -32003);
daemon.shutdown_via_eof_and_assert_clean_exit().await;
}
#[tokio::test]
async fn task_run_then_get_transcript_exposes_turns_usage_and_cost() {
let project = project_with_agents();
let mut daemon = StdioSession::spawn_with_mock_llm(project.path());
let session_id = run_task_to_completion(&mut daemon, "say hi").await;
let transcript_resp = daemon
.call(
3,
"session.get_transcript",
json!({"session_id": session_id}),
)
.await;
assert!(
transcript_resp["error"].is_null(),
"get_transcript failed: {transcript_resp}"
);
let result = &transcript_resp["result"];
assert_eq!(result["session_id"], session_id);
let turns = result["turns"].as_array().expect("turns must be an array");
assert!(
!turns.is_empty(),
"a completed run must have recorded turns"
);
let roles: Vec<&str> = turns.iter().map(|t| t["role"].as_str().unwrap()).collect();
assert!(roles.contains(&"pm"), "expected a pm turn: {roles:?}");
assert!(
roles.contains(&"python-engineer"),
"expected a python-engineer turn: {roles:?}"
);
let all_tool_calls: Vec<&str> = turns
.iter()
.flat_map(|t| t["tool_calls"].as_array().unwrap())
.map(|c| c.as_str().unwrap())
.collect();
assert!(
all_tool_calls.contains(&"delegate_to_agent"),
"expected the pm's delegate_to_agent call in the transcript: {all_tool_calls:?}"
);
assert!(
all_tool_calls.contains(&"bash"),
"expected the engineer's bash call in the transcript: {all_tool_calls:?}"
);
assert!(
result["usage"]["prompt_tokens"].as_u64().unwrap() > 0,
"expected non-zero aggregate prompt_tokens: {}",
result["usage"]
);
assert!(
result["usage"]["completion_tokens"].as_u64().unwrap() > 0,
"expected non-zero aggregate completion_tokens: {}",
result["usage"]
);
assert!(
result["cost_usd"].as_f64().unwrap() > 0.0,
"expected a priced, non-zero cost_usd: {}",
result["cost_usd"]
);
daemon.shutdown_via_eof_and_assert_clean_exit().await;
}
#[tokio::test]
async fn projectless_task_runs_end_to_end() {
let home = support::home_with_user_level_agents();
let mut daemon = StdioSession::spawn_projectless_with_mock_llm(home.path());
let session_id = run_task_to_completion(&mut daemon, "just chat, no project").await;
let status = daemon
.call(3, "session.status", json!({"session_id": session_id}))
.await;
assert!(status["error"].is_null(), "session.status failed: {status}");
let result = &status["result"];
assert_eq!(
result["binding"]["state"], "projectless",
"a daemon started without --project must report the projectless binding: {result}"
);
assert!(
result["binding"]["root"].is_null(),
"projectless must carry a null root: {result}"
);
assert!(
result["project"].is_null(),
"projectless must have no derived project label: {result}"
);
assert_eq!(
result["status"], "finished",
"a projectless run must reach `finished`, not fail: {result}"
);
daemon.shutdown_via_eof_and_assert_clean_exit().await;
}
#[tokio::test]
async fn non_git_project_binds_as_directory_not_projectless() {
let project = project_with_agents();
let mut daemon = StdioSession::spawn_with_mock_llm(project.path());
let session_id = run_task_to_completion(&mut daemon, "say hi").await;
let status = daemon
.call(3, "session.status", json!({"session_id": session_id}))
.await;
let result = &status["result"];
assert_eq!(
result["binding"]["state"], "directory",
"a non-git dir MUST bind as `directory` — binding is not gated on .git: {result}"
);
assert_ne!(
result["binding"]["state"], "projectless",
"a non-git dir is NOT projectless: {result}"
);
assert!(
!result["binding"]["root"].is_null(),
"a bound non-git dir must carry its root: {result}"
);
assert!(
!result["project"].is_null(),
"a bound project must have a derived label: {result}"
);
daemon.shutdown_via_eof_and_assert_clean_exit().await;
}
#[tokio::test]
async fn git_project_binds_as_git_repo() {
let project = project_with_agents();
let ok = std::process::Command::new("git")
.arg("-C")
.arg(project.path())
.arg("init")
.output()
.expect("git init must run")
.status
.success();
assert!(ok, "git init must succeed");
let mut daemon = StdioSession::spawn_with_mock_llm(project.path());
let session_id = run_task_to_completion(&mut daemon, "say hi").await;
let status = daemon
.call(3, "session.status", json!({"session_id": session_id}))
.await;
let result = &status["result"];
assert_eq!(
result["binding"]["state"], "git_repo",
"a git worktree must bind as `git_repo`: {result}"
);
assert!(
!result["binding"]["root"].is_null(),
"a bound git repo must carry its root: {result}"
);
daemon.shutdown_via_eof_and_assert_clean_exit().await;
}