use std::io::{BufRead, BufReader, Read, Write}; use std::net::TcpListener; use std::sync::atomic::AtomicBool; use std::sync::mpsc; use std::thread; use std::time::Duration; use serde_json::json; use agent686::config::Config; use agent686::provider::{self, Error, Outcome, Sink}; #[derive(Default)] struct Collector { text: String, reasoning: String, finished: bool, } impl Sink for Collector { fn text(&mut self, s: &str) { self.text.push_str(s); } fn reasoning(&mut self, s: &str) { self.reasoning.push_str(s); } fn done(&mut self, _outcome: &Outcome, _elapsed: Duration) { self.finished = true; } } /// Serves exactly one request on a random port, then closes. Returns the base /// URL and a receiver for the request as the client sent it. fn serve_once(response: &'static str) -> (String, mpsc::Receiver) { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = listener.local_addr().unwrap(); let (tx, rx) = mpsc::channel(); thread::spawn(move || { let (mut stream, _) = listener.accept().unwrap(); let mut reader = BufReader::new(stream.try_clone().unwrap()); let mut request = String::new(); let mut content_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:") { content_length = value.trim().parse().unwrap_or(0); } request.push_str(&line); } let mut body = vec![0u8; content_length]; let _ = reader.read_exact(&mut body); request.push_str(&String::from_utf8_lossy(&body)); let _ = tx.send(request); let _ = stream.write_all(response.as_bytes()); let _ = stream.flush(); }); (format!("http://{addr}"), rx) } fn config(base_url: String) -> Config { Config { base_url, api_key: "test-key".into(), model: "test-model".into(), session: "testsession".into(), } } #[test] fn streams_text_reasoning_and_usage() { const SSE: &str = concat!( "HTTP/1.1 200 OK\r\n", "Content-Type: text/event-stream\r\n", "Connection: close\r\n", "\r\n", "data: {\"choices\":[{\"delta\":{\"reasoning_content\":\"thinking\"}}]}\n\n", "data: {\"choices\":[{\"delta\":{\"content\":\"Hello\"}}]}\n\n", "data: {\"choices\":[{\"delta\":{\"content\":\" from mock\"},\"finish_reason\":\"stop\"}]}\n\n", "data: {\"choices\":[],\"usage\":{\"prompt_tokens\":5,\"completion_tokens\":2}}\n\n", "data: [DONE]\n\n", ); let (base, rx) = serve_once(SSE); let mut sink = Collector::default(); let outcome = provider::chat( &config(base), &[json!({ "role": "user", "content": "hi" })], &AtomicBool::new(false), &mut sink, ) .expect("chat should succeed"); assert_eq!(outcome.content, "Hello from mock"); assert_eq!(outcome.reasoning, "thinking"); assert_eq!(sink.text, "Hello from mock"); assert_eq!(sink.reasoning, "thinking"); assert!(sink.finished); assert_eq!(outcome.usage.unwrap()["completion_tokens"], 2); let request = rx.recv().unwrap().to_ascii_lowercase(); assert!( request.contains("x-opencode-session: testsession"), "session header missing from request:\n{request}" ); assert!(request.contains("user-agent: agent686/")); assert!(request.contains("\"stream\":true")); assert!(request.contains("\"include_usage\":true")); } #[test] fn assembles_tool_call_arguments_byte_for_byte() { const SSE: &str = concat!( "HTTP/1.1 200 OK\r\n", "Content-Type: text/event-stream\r\n", "Connection: close\r\n", "\r\n", "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"call_1\",\"function\":{\"name\":\"read\",\"arguments\":\"{\\\"path\\\":\"}}]}}]}\n\n", "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"\\\"a.txt\\\"}\"}}]}}]}\n\n", "data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"tool_calls\"}]}\n\n", "data: [DONE]\n\n", ); let (base, _rx) = serve_once(SSE); let mut sink = Collector::default(); let outcome = provider::chat( &config(base), &[json!({ "role": "user", "content": "read a.txt" })], &AtomicBool::new(false), &mut sink, ) .expect("chat should succeed"); assert_eq!(outcome.tool_calls.len(), 1); let call = &outcome.tool_calls[0]; assert_eq!(call.id, "call_1"); assert_eq!(call.name, "read"); assert_eq!(call.arguments, r#"{"path":"a.txt"}"#); assert_eq!(outcome.finish.as_deref(), Some("tool_calls")); } #[test] fn surfaces_provider_error_text() { const RESPONSE: &str = concat!( "HTTP/1.1 401 Unauthorized\r\n", "Content-Type: application/json\r\n", "Connection: close\r\n", "\r\n", "{\"error\":{\"type\":\"authentication_error\",\"code\":\"api_key_expired\",", "\"message\":\"This API key has expired.\"}}", ); let (base, _rx) = serve_once(RESPONSE); let mut sink = Collector::default(); let error = provider::chat( &config(base), &[json!({ "role": "user", "content": "hi" })], &AtomicBool::new(false), &mut sink, ) .expect_err("should fail"); match error { Error::Status { code, message } => { assert_eq!(code, 401); assert!(message.contains("This API key has expired."), "{message}"); assert!(message.contains("api_key_expired"), "{message}"); } other => panic!("unexpected error: {other:?}"), } } #[test] fn honours_a_cancelled_turn() { const SSE: &str = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\ndata: {\"choices\":[{\"delta\":{\"content\":\"x\"}}]}\n\n"; let (base, _rx) = serve_once(SSE); let mut sink = Collector::default(); let error = provider::chat( &config(base), &[json!({ "role": "user", "content": "hi" })], &AtomicBool::new(true), &mut sink, ) .expect_err("cancelled turn should abort"); assert!(matches!(error, Error::Aborted)); }