#![allow(dead_code)]
pub mod uds_mock;
#[allow(unused_imports)]
pub use uds_mock::{MockMemoryDaemon, spawn as spawn_mock_memory_daemon};
use std::process::Stdio;
use std::time::Duration;
use serde_json::{Value, json};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, Lines};
use tokio::process::{Child, ChildStdin, ChildStdout};
use tokio::time::timeout;
const WIRE_TIMEOUT: Duration = Duration::from_secs(5);
pub fn tcode_command() -> std::process::Command {
let mut cmd = std::process::Command::new(env!("CARGO_BIN_EXE_tcode"));
cmd.env(trusty_common::test_harness::FORCE_ENV, "1");
cmd
}
pub fn project_with_agents() -> tempfile::TempDir {
let tmp = tempfile::tempdir().expect("project tempdir");
let agents = tmp.path().join(".claude").join("agents");
std::fs::create_dir_all(&agents).expect("mkdir agents");
std::fs::write(
agents.join("pm.md"),
"---\nname: pm\nmodel: openai/gpt-4o-mini\n---\n\nYou are the PM. Delegate work to python-engineer.\n",
)
.expect("write pm.md");
std::fs::write(
agents.join("python-engineer.md"),
"---\nname: python-engineer\nmodel: deepseek/deepseek-chat\n---\n\nYou are a Python engineer.\n",
)
.expect("write python-engineer.md");
tmp
}
pub fn home_with_user_level_agents() -> tempfile::TempDir {
let tmp = tempfile::tempdir().expect("home tempdir");
let agents = tmp.path().join(".claude").join("agents");
std::fs::create_dir_all(&agents).expect("mkdir user-level agents");
std::fs::write(
agents.join("pm.md"),
"---\nname: pm\nmodel: openai/gpt-4o-mini\n---\n\nYou are the PM. Delegate work to python-engineer.\n",
)
.expect("write pm.md");
std::fs::write(
agents.join("python-engineer.md"),
"---\nname: python-engineer\nmodel: deepseek/deepseek-chat\n---\n\nYou are a Python engineer.\n",
)
.expect("write python-engineer.md");
tmp
}
pub struct StdioSession {
child: Child,
stdin: ChildStdin,
lines: Lines<BufReader<ChildStdout>>,
}
impl StdioSession {
pub fn spawn() -> Self {
Self::spawn_inner(Some(std::path::Path::new(".")), None, None, &[], &[])
}
pub fn spawn_with_mock_llm(project: &std::path::Path) -> Self {
Self::spawn_inner(
Some(project),
Some(trusty_code::task::mock_llm::MOCK_LLM_ECHO),
None,
&[],
&[],
)
}
pub fn spawn_with_mock_llm_variant(project: &std::path::Path, mock_llm_value: &str) -> Self {
Self::spawn_inner(Some(project), Some(mock_llm_value), None, &[], &[])
}
pub fn spawn_with_mock_llm_variant_and_env(
project: &std::path::Path,
mock_llm_value: &str,
envs: &[(&str, &str)],
) -> Self {
Self::spawn_inner(Some(project), Some(mock_llm_value), None, envs, &[])
}
pub fn spawn_with_mock_llm_variant_and_envs(
project: &std::path::Path,
mock_llm_value: &str,
extra_envs: &[(&str, &str)],
) -> Self {
Self::spawn_inner(Some(project), Some(mock_llm_value), None, &[], extra_envs)
}
pub fn spawn_projectless_with_mock_llm(home: &std::path::Path) -> Self {
Self::spawn_inner(
None,
Some(trusty_code::task::mock_llm::MOCK_LLM_ECHO),
Some(home),
&[],
&[],
)
}
fn spawn_inner(
project: Option<&std::path::Path>,
mock_llm_value: Option<&str>,
home: Option<&std::path::Path>,
envs: &[(&str, &str)],
extra_envs: &[(&str, &str)],
) -> Self {
let mut cmd = tokio::process::Command::new(env!("CARGO_BIN_EXE_tcode"));
cmd.arg("serve");
cmd.env(trusty_common::test_harness::FORCE_ENV, "1");
for (key, value) in extra_envs {
cmd.env(key, value);
}
if let Some(project) = project {
cmd.arg("--project").arg(project);
}
cmd.arg("--stdio");
if let Some(home) = home {
cmd.env("HOME", home);
}
if let Some(value) = mock_llm_value {
cmd.env(trusty_code::task::mock_llm::MOCK_LLM_ENV, value);
}
for (key, value) in envs {
cmd.env(key, value);
}
let mut child = cmd
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.kill_on_drop(true)
.spawn()
.expect("spawn `tcode serve --stdio`");
let stdin = child.stdin.take().expect("child stdin");
let stdout = child.stdout.take().expect("child stdout");
let lines = BufReader::new(stdout).lines();
Self {
child,
stdin,
lines,
}
}
pub async fn write_request(&mut self, id: i64, method: &str, params: Value) {
let req = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params});
let mut line = serde_json::to_string(&req).expect("serialise request");
line.push('\n');
self.stdin
.write_all(line.as_bytes())
.await
.expect("write request line");
self.stdin.flush().await.expect("flush stdin");
}
pub async fn call(&mut self, id: i64, method: &str, params: Value) -> Value {
self.write_request(id, method, params).await;
timeout(WIRE_TIMEOUT, async {
loop {
let line = self.next_line().await;
if let Some(resp) = find_response(&line, id) {
return resp;
}
}
})
.await
.unwrap_or_else(|_| panic!("timed out waiting for a response to id={id} ({method})"))
}
pub async fn read_lines(&mut self, max_lines: usize) -> Vec<String> {
let mut collected = Vec::new();
let _ = timeout(WIRE_TIMEOUT, async {
while collected.len() < max_lines {
collected.push(self.next_line().await);
}
})
.await;
collected
}
async fn next_line(&mut self) -> String {
self.lines
.next_line()
.await
.expect("read stdout line")
.expect("tcode serve --stdio closed stdout unexpectedly")
}
pub async fn shutdown_via_eof_and_assert_clean_exit(mut self) {
drop(self.stdin);
let status = timeout(WIRE_TIMEOUT, self.child.wait())
.await
.expect("timed out waiting for the daemon to exit after stdin EOF")
.expect("wait() failed");
assert!(
status.success(),
"daemon must exit 0 on stdin EOF, got {status:?}"
);
}
}
pub struct HttpDaemon {
child: Child,
pub base_url: String,
}
pub async fn spawn_http_daemon() -> HttpDaemon {
spawn_http_daemon_with_env(std::path::Path::new("."), &[]).await
}
pub async fn spawn_http_daemon_with_env(
project: &std::path::Path,
envs: &[(&str, &str)],
) -> HttpDaemon {
let mut cmd = tokio::process::Command::new(env!("CARGO_BIN_EXE_tcode"));
cmd.arg("serve")
.arg("--project")
.arg(project)
.args(["--http", "--port", "0"]);
cmd.env(trusty_common::test_harness::FORCE_ENV, "1");
for (key, value) in envs {
cmd.env(key, value);
}
let mut child = cmd
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::piped())
.kill_on_drop(true)
.spawn()
.expect("spawn `tcode serve --http`");
let stderr = child.stderr.take().expect("child stderr");
let mut lines = BufReader::new(stderr).lines();
let base_url = timeout(WIRE_TIMEOUT, async {
loop {
let line = lines
.next_line()
.await
.expect("read stderr")
.expect("tcode serve --http closed stderr before reporting its address");
if let Some(addr) = line.split("listening on http://").nth(1) {
return format!("http://{}", addr.trim());
}
}
})
.await
.expect("timed out waiting for the daemon to report its bound address");
tokio::spawn(async move { while let Ok(Some(_)) = lines.next_line().await {} });
HttpDaemon { child, base_url }
}
impl HttpDaemon {
pub async fn shutdown_via_sigterm_and_assert_clean_exit(mut self) {
let pid = self.child.id().expect("child has a pid") as i32;
unsafe {
libc::kill(pid, libc::SIGTERM);
}
let status = timeout(WIRE_TIMEOUT, self.child.wait())
.await
.expect("timed out waiting for the daemon to exit after SIGTERM")
.expect("wait() failed");
assert!(
status.success(),
"daemon must exit 0 after graceful SIGTERM shutdown, got {status:?}"
);
}
}
pub fn find_response(line: &str, id: i64) -> Option<Value> {
let v: Value = serde_json::from_str(line).ok()?;
if v.get("id").and_then(|i| i.as_i64()) == Some(id) {
Some(v)
} else {
None
}
}
pub fn find_session_event(line: &str, session_id: &str) -> Option<Value> {
let v: Value = serde_json::from_str(line).ok()?;
if v.get("method").and_then(|m| m.as_str()) == Some("session.event")
&& v["params"]["session_id"].as_str() == Some(session_id)
{
Some(v["params"].clone())
} else {
None
}
}
pub async fn run_task_to_completion(daemon: &mut StdioSession, task_description: &str) -> String {
let run_resp = daemon
.call(1, "task.run", json!({"task_description": task_description}))
.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();
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(),
);
}
}
}
session_id
}
pub async fn open_sse(client: &reqwest::Client, url: &str) -> reqwest::Response {
let resp = client.get(url).send().await.expect("GET request");
assert!(
resp.status().is_success(),
"GET {url} returned {}",
resp.status()
);
resp
}
pub async fn read_sse_until(
resp: &mut reqwest::Response,
buffer: &mut Vec<u8>,
until_substr: &str,
total_timeout: Duration,
) {
if String::from_utf8_lossy(buffer).contains(until_substr) {
return;
}
let read = timeout(total_timeout, async {
while !String::from_utf8_lossy(buffer).contains(until_substr) {
match resp.chunk().await {
Ok(Some(chunk)) => buffer.extend_from_slice(&chunk),
_ => break,
}
}
})
.await;
assert!(
read.is_ok(),
"timed out waiting for {until_substr:?} in the SSE stream"
);
}
pub fn parse_sse_frames(text: &str) -> Vec<Value> {
text.lines()
.filter_map(|line| line.strip_prefix("data:"))
.filter_map(|rest| serde_json::from_str::<Value>(rest.trim()).ok())
.collect()
}
pub fn assert_envelopes_contiguous(envelopes: &[Value]) -> (u64, u64) {
assert!(
!envelopes.is_empty(),
"expected at least one envelope to check"
);
let mut previous: Option<u64> = None;
for envelope in envelopes {
for field in ["session_id", "seq", "at", "kind", "event"] {
assert!(
envelope.get(field).is_some(),
"envelope missing required field {field:?}: {envelope}"
);
}
let seq = envelope["seq"].as_u64().expect("seq must be a u64");
if let Some(prev) = previous {
assert_eq!(
seq,
prev + 1,
"seq must increase by exactly 1 with no gaps or duplicates: {envelope}"
);
}
previous = Some(seq);
}
let first = envelopes[0]["seq"].as_u64().unwrap();
let last = envelopes[envelopes.len() - 1]["seq"].as_u64().unwrap();
(first, last)
}