use std::fs; use std::io::{BufRead, BufReader, Read, Write}; use std::net::TcpListener; use std::path::PathBuf; use std::sync::atomic::AtomicBool; use std::thread; use serde_json::json; /// Tests in this binary share process-wide environment variables. static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); use agent686::agent; use agent686::config::Config; use agent686::session::Session; use agent686::ui::Approver; fn sse(body: &str) -> String { format!( "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n{body}" ) } /// Serves one canned SSE response per connection, in order. fn serve_sequence(responses: Vec) -> String { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = listener.local_addr().unwrap(); thread::spawn(move || { for response in responses { let (mut stream, _) = listener.accept().unwrap(); let mut reader = BufReader::new(stream.try_clone().unwrap()); let mut length = 0usize; loop { let mut line = String::new(); if reader.read_line(&mut line).unwrap_or(0) == 0 { break; } if line == "\r\n" || line == "\n" { break; } if let Some(value) = line.to_ascii_lowercase().strip_prefix("content-length:") { length = value.trim().parse().unwrap_or(0); } } let mut body = vec![0u8; length]; let _ = reader.read_exact(&mut body); let _ = stream.write_all(response.as_bytes()); let _ = stream.flush(); } }); format!("http://{addr}") } fn temp_dir(tag: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!("agent686-loop-{tag}-{}", std::process::id())); let _ = fs::remove_dir_all(&dir); fs::create_dir_all(&dir).unwrap(); dir } #[test] fn runs_a_tool_call_then_finishes_and_records_every_message() { let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner()); let dir = temp_dir("write"); let target = dir.join("hello.txt"); let arguments = json!({ "path": target.display().to_string(), "content": "hello from the mock\n" }) .to_string(); let tool_round = sse(&format!( "data: {}\n\ndata: [DONE]\n\n", json!({ "choices": [{ "delta": { "tool_calls": [{ "index": 0, "id": "call_1", "function": { "name": "write", "arguments": arguments } }]}, "finish_reason": "tool_calls" }] }) )); let final_round = sse( "data: {\"choices\":[{\"delta\":{\"content\":\"done\"},\"finish_reason\":\"stop\"}]}\n\n\ data: [DONE]\n\n", ); let base = serve_sequence(vec![tool_round, final_round]); std::env::set_var("AGENT686_DATA", dir.join("data")); let system = agent::system_prompt(); let mut session = Session::create("test-model", &system).unwrap(); let cfg = Config { base_url: base, api_key: "test-key".into(), model: "test-model".into(), session: session.id.clone(), yolo: true, }; let mut history = agent::new_history(system); let mut approver = Approver::new(true); agent::run_turn( &cfg, &mut session, &mut history, "write a file", &AtomicBool::new(false), &mut approver, ) .expect("turn should complete"); assert_eq!( fs::read_to_string(&target).unwrap(), "hello from the mock\n" ); // system, user, assistant(tool_calls), tool result, assistant(final) assert_eq!(history.len(), 5); assert_eq!(history[3]["role"], "tool"); assert_eq!(history[3]["tool_call_id"], "call_1"); let log = fs::read_to_string(session.path()).unwrap(); let lines: Vec<&str> = log.lines().collect(); assert_eq!(lines.len(), 5, "header plus four messages: {log}"); assert!(lines[0].contains("\"t\":\"header\"")); assert_eq!(lines[3].contains("\"role\":\"tool\""), true); } #[test] fn a_denied_tool_call_is_returned_as_data() { let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner()); let dir = temp_dir("denied"); let target = dir.join("never.txt"); let arguments = json!({ "path": target.display().to_string(), "content": "should not exist" }) .to_string(); let tool_round = sse(&format!( "data: {}\n\ndata: [DONE]\n\n", json!({ "choices": [{ "delta": { "tool_calls": [{ "index": 0, "id": "call_1", "function": { "name": "write", "arguments": arguments } }]}, "finish_reason": "tool_calls" }] }) )); let final_round = sse( "data: {\"choices\":[{\"delta\":{\"content\":\"understood\"},\"finish_reason\":\"stop\"}]}\n\n\ data: [DONE]\n\n", ); let base = serve_sequence(vec![tool_round, final_round]); std::env::set_var("AGENT686_DATA", dir.join("data")); let system = agent::system_prompt(); let mut session = Session::create("test-model", &system).unwrap(); let cfg = Config { base_url: base, api_key: "test-key".into(), model: "test-model".into(), session: session.id.clone(), yolo: false, }; let mut history = agent::new_history(system); // Not a terminal, so the approver must deny rather than block. let mut approver = Approver::new(false); agent::run_turn( &cfg, &mut session, &mut history, "write a file", &AtomicBool::new(false), &mut approver, ) .expect("a denial is not a failed turn"); assert!(!target.exists()); assert_eq!(history[3]["role"], "tool"); assert!( history[3]["content"] .as_str() .unwrap() .contains("denied by the user") ); assert_eq!(history[4]["content"], "understood"); } fn tool_call(index: usize, id: &str, name: &str, arguments: serde_json::Value) -> serde_json::Value { json!({ "index": index, "id": id, "function": { "name": name, "arguments": arguments.to_string() } }) } #[test] fn aborting_between_tool_calls_answers_every_call() { let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner()); let dir = temp_dir("abort-mid-calls"); let slow = sse(&format!( "data: {}\n\ndata: [DONE]\n\n", json!({ "choices": [{ "delta": { "tool_calls": [ tool_call(0, "call_a", "bash", json!({ "cmd": "sleep 0.5" })), tool_call(1, "call_b", "write", json!({ "path": dir.join("b.txt"), "content": "b" })), tool_call(2, "call_c", "write", json!({ "path": dir.join("c.txt"), "content": "c" })) ]}, "finish_reason": "tool_calls" }] }) )); // If the harness wrongly continues after the abort, it would consume this. let after = sse( "data: {\"choices\":[{\"delta\":{\"content\":\"should not be reached\"},\"finish_reason\":\"stop\"}]}\n\n\ data: [DONE]\n\n", ); let base = serve_sequence(vec![slow, after]); std::env::set_var("AGENT686_DATA", dir.join("data")); let system = agent::system_prompt(); let mut session = Session::create("test-model", &system).unwrap(); let cfg = Config { base_url: base, api_key: "test-key".into(), model: "test-model".into(), session: session.id.clone(), yolo: true, }; let mut history = agent::new_history(system); let mut approver = Approver::new(true); let cancel = std::sync::Arc::new(AtomicBool::new(false)); let flag = cancel.clone(); thread::spawn(move || { thread::sleep(std::time::Duration::from_millis(150)); flag.store(true, std::sync::atomic::Ordering::SeqCst); }); let report = agent::run_turn( &cfg, &mut session, &mut history, "do three things", &cancel, &mut approver, ) .expect("an abort is not an error"); assert!(report.aborted); assert_eq!(report.writes, 0, "aborted calls must not count as writes"); assert_eq!(report.commands, 1); // Every announced tool call must have exactly one result, or the provider // rejects the session forever and the transcript cannot be rewritten. let answered: Vec = history .iter() .filter(|message| message.get("role").and_then(|r| r.as_str()) == Some("tool")) .filter_map(|message| message.get("tool_call_id").and_then(|id| id.as_str()).map(|s| s.to_string())) .collect(); assert_eq!(answered, vec!["call_a", "call_b", "call_c"], "{answered:?}"); // The loop stopped: no assistant text was ever appended. assert_eq!(history.last().unwrap()["role"], "tool"); assert!(fs::read_to_string(session.path()).unwrap().lines().count() >= 5); } #[test] fn opening_a_session_with_unanswered_calls_repairs_it() { let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner()); let dir = temp_dir("repair"); std::env::set_var("AGENT686_DATA", dir.join("data")); let base = serve_sequence(vec![sse( "data: {\"choices\":[{\"delta\":{\"content\":\"carrying on\"},\"finish_reason\":\"stop\"}]}\n\n\ data: [DONE]\n\n", )]); let system = agent::system_prompt(); let mut session = Session::create("test-model", &system).unwrap(); let mut history = agent::new_history(system); // A transcript shape left behind by an older build: two calls, one result. let assistant = json!({ "role": "assistant", "content": null, "tool_calls": [ { "id": "call_1", "type": "function", "function": { "name": "read", "arguments": "{}" } }, { "id": "call_2", "type": "function", "function": { "name": "read", "arguments": "{}" } } ] }); session.append(&assistant, None).unwrap(); history.push(assistant); let partial = json!({ "role": "tool", "tool_call_id": "call_1", "content": "ok" }); session.append(&partial, None).unwrap(); history.push(partial); let cfg = Config { base_url: base, api_key: "test-key".into(), model: "test-model".into(), session: session.id.clone(), yolo: true, }; let mut approver = Approver::new(true); agent::run_turn( &cfg, &mut session, &mut history, "go on", &AtomicBool::new(false), &mut approver, ) .expect("repair should let the turn run"); let repaired = history.iter().any(|message| { message.get("tool_call_id").and_then(|id| id.as_str()) == Some("call_2") && message .get("content") .and_then(|c| c.as_str()) .is_some_and(|c| c.contains("interrupted")) }); assert!(repaired, "missing result for call_2 should be synthesised"); } #[test] fn an_empty_bash_call_is_never_approved() { let dir = temp_dir("empty-bash"); let empty_call = sse(&format!( "data: {}\n\ndata: [DONE]\n\n", json!({ "choices": [{ "delta": { "tool_calls": [{ "index": 0, "id": "call_empty", "function": { "name": "bash", "arguments": "{}" } }]}, "finish_reason": "tool_calls" }] }) )); let final_round = sse( "data: {\"choices\":[{\"delta\":{\"content\":\"ok\"},\"finish_reason\":\"stop\"}]}\n\n\ data: [DONE]\n\n", ); let base = serve_sequence(vec![empty_call, final_round]); std::env::set_var("AGENT686_DATA", dir.join("data")); let system = agent::system_prompt(); let mut session = Session::create("test-model", &system).unwrap(); let cfg = Config { base_url: base, api_key: "test-key".into(), model: "test-model".into(), session: session.id.clone(), yolo: false, }; let mut history = agent::new_history(system); // Not a terminal: if this reaches the approval path it is denied, which the // assertion below would catch. let mut approver = Approver::new(false); agent::run_turn( &cfg, &mut session, &mut history, "run something", &AtomicBool::new(false), &mut approver, ) .expect("the turn should survive a malformed call"); let result = history[3]["content"].as_str().unwrap(); assert!(result.contains("`cmd` is required"), "{result}"); assert!(!result.contains("denied"), "must not reach an approval prompt: {result}"); }