diff --git a/docs/plan-2026-11-engineering.md b/docs/plan-2026-11-engineering.md index cf47d0f..9b364fe 100644 --- a/docs/plan-2026-11-engineering.md +++ b/docs/plan-2026-11-engineering.md @@ -38,7 +38,7 @@ - 不加 `rust-toolchain.toml`:AnyBot 是使用者自己從原始碼建的,釘住版本會逼每個人(和 `make update-server`)多下載一套 Rust;CI 的映像已經釘 1.98.1,Cargo.toml 的 rust-version 管最低版本。 - 做完:`cargo clippy --all-targets -- -D warnings` 過。 -### E7. 共用的假模型測試工具 ⬜ +### E7. 共用的假模型測試工具 ✅(providers.rs 自己的那一個看請求網址,留著) - 做法:`testkit.rs`(`cfg(test)`):一個假模型伺服器,OpenAI 和 Anthropic 兩種格式,照劇本回文字或工具呼叫,能注入 429/5xx(帶 Retry-After)、斷線、空回應;記下每個請求。把 agent.rs 和 app.rs 測試裡三份各自的假伺服器換成它。 - 做完:舊測試全換過來照樣過;新增注入錯誤的重試測試(接 P1)。 diff --git a/src/agent.rs b/src/agent.rs index 4c82a62..d03db80 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -5430,46 +5430,18 @@ echo 'done送出了' > done.html; (setsid pyt /// A made-up model that answers each request with the next (HTTP status, body) and keeps /// what each request said. + /// The shared fake model service (testkit.rs), answering these (status, body) in order. fn fake_http(replies: Vec<(u16, String)>) -> (u16, Arc>>) { - use std::io::{Read, Write}; - let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); - let port = l.local_addr().unwrap().port(); - let seen = Arc::new(Mutex::new(vec![])); - let seen2 = seen.clone(); - std::thread::spawn(move || { - for (status, body) in replies { - let Ok((mut s, _)) = l.accept() else { return }; - let mut req = Vec::new(); - let mut buf = [0u8; 8192]; - loop { - let n = s.read(&mut buf).unwrap_or(0); - if n == 0 { - break; - } - req.extend_from_slice(&buf[..n]); - let t = String::from_utf8_lossy(&req).to_string(); - if let Some(end) = t.find("\r\n\r\n") { - let len = t[..end].lines().find_map(|l| l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::().unwrap_or(0))).unwrap_or(0); - if req.len() >= end + 4 + len { - break; - } - } - } - seen2.lock().unwrap().push(String::from_utf8_lossy(&req).to_string()); - let head = if status == 200 { "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n".to_string() } else { format!("HTTP/1.1 {status} Error\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len()) }; - let _ = s.write_all(head.as_bytes()); - let _ = s.write_all(body.as_bytes()); - } - }); - (port, seen) + let f = crate::testkit::Fake::start(crate::testkit::Format::OpenAi, replies.into_iter().map(|(s, b)| crate::testkit::Reply::Raw(s, b)).collect(), None); + (f.port, f.raw) } fn sse_text(t: &str) -> (u16, String) { - (200, format!("data: {}\n\ndata: [DONE]\n\n", serde_json::json!({"choices": [{"delta": {"content": t}}]}))) + (200, crate::testkit::stream(crate::testkit::Format::OpenAi, &crate::testkit::Reply::text(t))) } fn sse_call(id: &str, name: &str, args: serde_json::Value) -> (u16, String) { - (200, format!("data: {}\n\ndata: [DONE]\n\n", serde_json::json!({"choices": [{"delta": {"tool_calls": [{"index": 0, "id": id, "function": {"name": name, "arguments": args.to_string()}}]}}]}))) + (200, crate::testkit::stream(crate::testkit::Format::OpenAi, &crate::testkit::Reply::call(id, name, args))) } const OVERFLOW_BODY: &str = r#"{"error":{"message":"This model's maximum context length is 8192 tokens. However, your messages resulted in 9000 tokens."}}"#; diff --git a/src/app.rs b/src/app.rs index 98f237f..006ced7 100644 --- a/src/app.rs +++ b/src/app.rs @@ -7744,37 +7744,10 @@ mod tests { } /// A fake model for one test: answers every request with "ok" and keeps each request's body. + /// The shared fake model service (testkit.rs): 「ok」 to everything, every request kept. fn fake_model() -> (u16, std::sync::Arc>>) { - use std::io::{Read, Write}; - let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); - let port = l.local_addr().unwrap().port(); - let captured = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); - let seen = captured.clone(); - std::thread::spawn(move || { - while let Ok((mut s, _)) = l.accept() { - let mut req = Vec::new(); - let mut buf = [0u8; 65536]; - let body = loop { - let n = s.read(&mut buf).unwrap_or(0); - if n == 0 { - break String::new(); - } - req.extend_from_slice(&buf[..n]); - let t = String::from_utf8_lossy(&req).to_string(); - if let Some(end) = t.find("\r\n\r\n") { - let len = t[..end].lines().find_map(|l| l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::().unwrap_or(0))).unwrap_or(0); - if req.len() >= end + 4 + len { - break t[end + 4..].to_string(); - } - } - }; - seen.lock().unwrap().push(serde_json::from_str(&body).unwrap_or_default()); - let out = format!("data: {}\n\ndata: [DONE]\n\n", serde_json::json!({"choices": [{"delta": {"content": "ok"}}]})); - let _ = s.write_all(b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n"); - let _ = s.write_all(out.as_bytes()); - } - }); - (port, captured) + let f = crate::testkit::Fake::openai(vec![]); + (f.port, f.bodies) } /// Wake a bot against the fake model and hand back the request it made. @@ -7897,36 +7870,10 @@ mod tests { } /// A fake model that answers with these deltas in turn (a tool call, words), then "ok". + /// The shared fake model service (testkit.rs) answering these OpenAI deltas in order, then 「ok」. fn scripted_model(script: Vec) -> u16 { - use std::io::{Read, Write}; - let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); - let port = l.local_addr().unwrap().port(); - std::thread::spawn(move || { - let mut script = script.into_iter(); - while let Ok((mut s, _)) = l.accept() { - let mut req = Vec::new(); - let mut buf = [0u8; 65536]; - loop { - let n = s.read(&mut buf).unwrap_or(0); - if n == 0 { - break; - } - req.extend_from_slice(&buf[..n]); - let t = String::from_utf8_lossy(&req).to_string(); - if let Some(end) = t.find("\r\n\r\n") { - let len = t[..end].lines().find_map(|l| l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::().unwrap_or(0))).unwrap_or(0); - if req.len() >= end + 4 + len { - break; - } - } - } - let delta = script.next().unwrap_or_else(|| serde_json::json!({"content": "ok"})); - let out = format!("data: {}\n\ndata: [DONE]\n\n", serde_json::json!({"choices": [{"delta": delta}]})); - let _ = s.write_all(b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n"); - let _ = s.write_all(out.as_bytes()); - } - }); - port + let raw = |d: serde_json::Value| crate::testkit::Reply::Raw(200, format!("data: {}\n\ndata: [DONE]\n\n", serde_json::json!({"choices": [{"delta": d}]}))); + crate::testkit::Fake::start(crate::testkit::Format::OpenAi, script.into_iter().map(raw).collect(), Some(crate::testkit::Reply::text("ok"))).port } /// Run the window's side until `done` holds (or 10 s). diff --git a/src/main.rs b/src/main.rs index 5fbad54..98eda6d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -75,6 +75,8 @@ mod always; mod secrets; mod logfile; mod net; +#[cfg(test)] +mod testkit; mod store; mod docindex; mod drops; diff --git a/src/testkit.rs b/src/testkit.rs new file mode 100644 index 0000000..c9b31b7 --- /dev/null +++ b/src/testkit.rs @@ -0,0 +1,217 @@ +//! 測試工具: one fake model service for every test that needs a model (agent.rs, app.rs and here), +//! instead of three servers each written in its own test module. It speaks OpenAI's chat +//! completions stream and Anthropic's messages stream, answers each request with the next +//! reply of a script — words, a tool call, an error status with Retry-After, a dropped +//! connection, an empty answer — and keeps every request it got. Like grok-build's +//! xai-grok-test-support. +//! +//! `cfg(test)` only. + +use serde_json::{json, Value}; +use std::io::{Read, Write}; +use std::sync::{Arc, Mutex}; + +/// One answer of the script. +#[derive(Clone, Debug)] +pub enum Reply { + /// Words. + Text(String), + /// A tool call (`args` is the arguments object). + Call { id: String, name: String, args: Value }, + /// An HTTP error: the status, a JSON body, and Retry-After (seconds) when given. + Fail { status: u16, body: String, retry_after: Option }, + /// The connection is closed without an answer. + Drop, + /// A stream with nothing in it (no words, no call). + Empty, + /// This status and body as they are (for a test that writes its own stream). + Raw(u16, String), +} + +impl Reply { + pub fn text(t: &str) -> Reply { + Reply::Text(t.into()) + } + pub fn call(id: &str, name: &str, args: Value) -> Reply { + Reply::Call { id: id.into(), name: name.into(), args } + } + pub fn busy(retry_after: u64) -> Reply { + Reply::Fail { status: 503, body: r#"{"error":{"message":"Server busy: queue longer than 10 seconds"}}"#.into(), retry_after: Some(retry_after) } + } +} + +/// Which provider's stream. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Format { + OpenAi, + Anthropic, +} + +/// A running fake model service. +pub struct Fake { + pub port: u16, + /// Every request as it came (headers and body). + pub raw: Arc>>, + /// Every request's body as JSON (Null when it wasn't). + pub bodies: Arc>>, +} + +impl Fake { + /// Answers the script in order; after it, `then` for every request (None: it stops listening, + /// and the next request finds nobody). + pub fn start(format: Format, script: Vec, then: Option) -> Fake { + let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = l.local_addr().unwrap().port(); + let (raw, bodies) = (Arc::new(Mutex::new(vec![])), Arc::new(Mutex::new(vec![]))); + let (raw2, bodies2) = (raw.clone(), bodies.clone()); + std::thread::spawn(move || { + let mut script = script.into_iter(); + loop { + let Some(reply) = script.next().or_else(|| then.clone()) else { return }; + let Ok((mut s, _)) = l.accept() else { return }; + let (head, body) = read_request(&mut s); + raw2.lock().unwrap().push(format!("{head}\r\n\r\n{body}")); + bodies2.lock().unwrap().push(serde_json::from_str(&body).unwrap_or(Value::Null)); + answer(&mut s, format, reply); + } + }); + Fake { port, raw, bodies } + } + + /// OpenAI's stream; after the script, 「ok」 for ever. + pub fn openai(script: Vec) -> Fake { + Fake::start(Format::OpenAi, script, Some(Reply::text("ok"))) + } + + /// Anthropic's stream; after the script, 「ok」 for ever. + pub fn anthropic(script: Vec) -> Fake { + Fake::start(Format::Anthropic, script, Some(Reply::text("ok"))) + } + + /// The address to give as a provider's base URL. + pub fn base(&self) -> String { + format!("http://127.0.0.1:{}/v1", self.port) + } + + pub fn requests(&self) -> usize { + self.raw.lock().unwrap().len() + } +} + +fn read_request(s: &mut std::net::TcpStream) -> (String, String) { + let mut req = Vec::new(); + let mut buf = [0u8; 65536]; + loop { + let n = s.read(&mut buf).unwrap_or(0); + if n == 0 { + break; + } + req.extend_from_slice(&buf[..n]); + let t = String::from_utf8_lossy(&req).to_string(); + if let Some(end) = t.find("\r\n\r\n") { + let len = t[..end].lines().find_map(|l| l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::().unwrap_or(0))).unwrap_or(0); + if req.len() >= end + 4 + len { + break; + } + } + } + let t = String::from_utf8_lossy(&req).to_string(); + match t.split_once("\r\n\r\n") { + Some((h, b)) => (h.to_string(), b.to_string()), + None => (t, String::new()), + } +} + +/// The stream for one reply, in the provider's format. +pub fn stream(format: Format, reply: &Reply) -> String { + let event = |name: &str, v: Value| format!("event: {name}\ndata: {v}\n\n"); + match (format, reply) { + (Format::OpenAi, Reply::Text(t)) => format!("data: {}\n\ndata: [DONE]\n\n", json!({"choices": [{"delta": {"content": t}}]})), + (Format::OpenAi, Reply::Call { id, name, args }) => format!("data: {}\n\ndata: [DONE]\n\n", json!({"choices": [{"delta": {"tool_calls": [{"index": 0, "id": id, "function": {"name": name, "arguments": args.to_string()}}]}}]})), + (Format::OpenAi, Reply::Empty) => "data: [DONE]\n\n".into(), + (Format::Anthropic, Reply::Text(t)) => [ + event("message_start", json!({"type": "message_start"})), + event("content_block_start", json!({"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}})), + event("content_block_delta", json!({"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": t}})), + event("content_block_stop", json!({"type": "content_block_stop", "index": 0})), + event("message_delta", json!({"type": "message_delta", "delta": {"stop_reason": "end_turn"}})), + event("message_stop", json!({"type": "message_stop"})), + ] + .concat(), + (Format::Anthropic, Reply::Call { id, name, args }) => [ + event("message_start", json!({"type": "message_start"})), + event("content_block_start", json!({"type": "content_block_start", "index": 0, "content_block": {"type": "tool_use", "id": id, "name": name, "input": {}}})), + event("content_block_delta", json!({"type": "content_block_delta", "index": 0, "delta": {"type": "input_json_delta", "partial_json": args.to_string()}})), + event("content_block_stop", json!({"type": "content_block_stop", "index": 0})), + event("message_delta", json!({"type": "message_delta", "delta": {"stop_reason": "tool_use"}})), + event("message_stop", json!({"type": "message_stop"})), + ] + .concat(), + (Format::Anthropic, Reply::Empty) => [event("message_start", json!({"type": "message_start"})), event("message_stop", json!({"type": "message_stop"}))].concat(), + (_, Reply::Raw(_, body)) => body.clone(), + (_, Reply::Fail { body, .. }) => body.clone(), + (_, Reply::Drop) => String::new(), + } +} + +fn answer(s: &mut std::net::TcpStream, format: Format, reply: Reply) { + let (status, extra) = match &reply { + Reply::Drop => return, + Reply::Fail { status, retry_after, .. } => (*status, retry_after.map(|r| format!("Retry-After: {r}\r\n")).unwrap_or_default()), + Reply::Raw(status, _) => (*status, String::new()), + _ => (200, String::new()), + }; + let body = stream(format, &reply); + let head = if status == 200 { + "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n".to_string() + } else { + format!("HTTP/1.1 {status} Error\r\nContent-Type: application/json\r\n{extra}Content-Length: {}\r\nConnection: close\r\n\r\n", body.len()) + }; + let _ = s.write_all(head.as_bytes()); + let _ = s.write_all(body.as_bytes()); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::providers::{ChatRequest, ProviderKind}; + use std::sync::atomic::AtomicBool; + + fn req(kind: ProviderKind, base: String) -> ChatRequest { + ChatRequest { kind, base_url: base, api_key: "k".into(), model: "m".into(), system: String::new(), history: vec![crate::model::Message::user("hi")], tools: vec![], session: String::new(), effort: String::new() } + } + + /// Both formats come out of the providers' own parsers as words and tool calls. + #[test] + fn both_streams_read_as_words_and_calls() { + for (format, kind) in [(Format::OpenAi, ProviderKind::Custom), (Format::Anthropic, ProviderKind::Anthropic)] { + let f = Fake::start(format, vec![Reply::text("你好"), Reply::call("c1", "list_dir", json!({"path": "x"}))], None); + let cancel = AtomicBool::new(false); + let out = crate::providers::run_step(&req(kind, f.base()), &cancel, &|_| {}).unwrap(); + assert_eq!(out.text, "你好", "{format:?}"); + let out = crate::providers::run_step(&req(kind, f.base()), &cancel, &|_| {}).unwrap(); + assert_eq!((out.tool_calls[0].name.as_str(), out.tool_calls[0].args.as_str()), ("list_dir", r#"{"path":"x"}"#), "{format:?}"); + assert_eq!(f.requests(), 2); + assert_eq!(f.bodies.lock().unwrap()[0]["model"], "m"); + } + } + + /// A busy answer with Retry-After is waited out and asked again; a dropped connection too. + #[test] + fn busy_and_dropped_answers_are_tried_again() { + let f = Fake::start(Format::OpenAi, vec![Reply::busy(1), Reply::Drop, Reply::text("好了")], None); + let cancel = AtomicBool::new(false); + let retries = Mutex::new(vec![]); + let t0 = std::time::Instant::now(); + let out = crate::providers::run_step(&req(ProviderKind::Custom, f.base()), &cancel, &|e| { + if let crate::providers::StreamEvent::Retrying(m) = e { + retries.lock().unwrap().push(m); + } + }) + .unwrap(); + assert_eq!(out.text, "好了"); + assert_eq!(f.requests(), 3); + assert!(retries.lock().unwrap().len() >= 2, "{:?}", retries.lock().unwrap()); + assert!(t0.elapsed() >= std::time::Duration::from_millis(900), "Retry-After: 1 was waited out ({:?})", t0.elapsed()); + } +}