aboutsummaryrefslogtreecommitdiffstats
path: root/tests
diff options
context:
space:
mode:
authorsalmonik <salmonik@tuta.io>2026-11-15 14:59:31 +0100
committersalmonik <salmonik@tuta.io>2026-11-15 14:59:31 +0100
commitf192c40b2a3643a9ab97303310db8dbc7547ee35 (patch)
tree1b2133afa1b3318f8c0da032a7da278691e577ca /tests
parentM1-M5: sessions, six tools, approvals, prompt, Ctrl-C, target gate (diff)
downloadagent686-f192c40b2a3643a9ab97303310db8dbc7547ee35.tar.gz
agent686-f192c40b2a3643a9ab97303310db8dbc7547ee35.zip
Robustness: retry with backoff, explained errors, --list, --session creates
- four attempts on 408/425/429/500/502/503/504 and transport errors, honouring Retry-After - backoff is interruptible so Ctrl-C is not held for up to 8s - context overflow, auth failure and rate limit messages say what to do - --list shows id/model/messages/age without needing a key - --session <id> creates the session when the id does not exist - probes recorded: session header is mandatory, consecutive user messages allowed
Diffstat (limited to 'tests')
-rw-r--r--tests/mock.rs131
-rw-r--r--tests/sessions.rs69
2 files changed, 200 insertions, 0 deletions
diff --git a/tests/mock.rs b/tests/mock.rs
index 52dec7c..9b3cd5a 100644
--- a/tests/mock.rs
+++ b/tests/mock.rs
@@ -195,3 +195,134 @@ fn honours_a_cancelled_turn() {
195 .expect_err("cancelled turn should abort"); 195 .expect_err("cancelled turn should abort");
196 assert!(matches!(error, Error::Aborted)); 196 assert!(matches!(error, Error::Aborted));
197} 197}
198
199/// Serves one canned response per connection, in order, and records each
200/// request so retries can be asserted.
201fn serve_times(responses: Vec<&'static str>) -> (String, mpsc::Receiver<String>) {
202 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
203 let addr = listener.local_addr().unwrap();
204 let (tx, rx) = mpsc::channel();
205 thread::spawn(move || {
206 for response in responses {
207 let (mut stream, _) = listener.accept().unwrap();
208 let mut reader = BufReader::new(stream.try_clone().unwrap());
209 let mut request = String::new();
210 let mut length = 0usize;
211 loop {
212 let mut line = String::new();
213 if reader.read_line(&mut line).unwrap_or(0) == 0 {
214 break;
215 }
216 if line == "\r\n" || line == "\n" {
217 break;
218 }
219 if let Some(value) = line.to_ascii_lowercase().strip_prefix("content-length:") {
220 length = value.trim().parse().unwrap_or(0);
221 }
222 request.push_str(&line);
223 }
224 let mut body = vec![0u8; length];
225 let _ = reader.read_exact(&mut body);
226 request.push_str(&String::from_utf8_lossy(&body));
227 let _ = tx.send(request);
228 let _ = stream.write_all(response.as_bytes());
229 let _ = stream.flush();
230 }
231 });
232 (format!("http://{addr}"), rx)
233}
234
235#[test]
236fn retries_a_rate_limit_and_keeps_the_same_session_header() {
237 const LIMITED: &str = concat!(
238 "HTTP/1.1 429 Too Many Requests\r\n",
239 "Retry-After: 0\r\n",
240 "Content-Type: application/json\r\n",
241 "Connection: close\r\n",
242 "\r\n",
243 "{\"error\":{\"code\":\"rate_limited\",\"message\":\"slow down\"}}",
244 );
245 const OK: &str = concat!(
246 "HTTP/1.1 200 OK\r\n",
247 "Content-Type: text/event-stream\r\n",
248 "Connection: close\r\n",
249 "\r\n",
250 "data: {\"choices\":[{\"delta\":{\"content\":\"second try\"},\"finish_reason\":\"stop\"}]}\n\n",
251 "data: [DONE]\n\n",
252 );
253
254 let (base, rx) = serve_times(vec![LIMITED, OK]);
255 let mut sink = Collector::default();
256 let outcome = provider::chat(
257 &config(base),
258 &[json!({ "role": "user", "content": "hi" })],
259 &[],
260 &AtomicBool::new(false),
261 &mut sink,
262 )
263 .expect("retry should succeed");
264
265 assert_eq!(outcome.content, "second try");
266
267 let first = rx.recv().expect("first request").to_ascii_lowercase();
268 let second = rx.recv().expect("second request").to_ascii_lowercase();
269 assert!(first.contains("x-opencode-session: testsession"), "{first}");
270 assert!(second.contains("x-opencode-session: testsession"), "{second}");
271}
272
273#[test]
274fn does_not_retry_a_permanent_client_error() {
275 const BAD: &str = concat!(
276 "HTTP/1.1 400 Bad Request\r\n",
277 "Content-Type: application/json\r\n",
278 "Connection: close\r\n",
279 "\r\n",
280 "{\"error\":{\"message\":\"maximum context length exceeded\"}}",
281 );
282 let (base, rx) = serve_times(vec![BAD]);
283 let mut sink = Collector::default();
284 let error = provider::chat(
285 &config(base),
286 &[json!({ "role": "user", "content": "hi" })],
287 &[],
288 &AtomicBool::new(false),
289 &mut sink,
290 )
291 .expect_err("400 should fail");
292
293 match error {
294 Error::Status { code, message } => {
295 assert_eq!(code, 400);
296 assert!(
297 message.contains("start a new session"),
298 "should explain overflow: {message}"
299 );
300 }
301 other => panic!("unexpected error: {other:?}"),
302 }
303 assert!(rx.recv().is_ok(), "exactly one request should be sent");
304}
305
306#[test]
307fn auth_failure_says_where_the_key_lives() {
308 const UNAUTHORIZED: &str = concat!(
309 "HTTP/1.1 401 Unauthorized\r\n",
310 "Content-Type: application/json\r\n",
311 "Connection: close\r\n",
312 "\r\n",
313 "{\"error\":{\"code\":\"api_key_expired\",\"message\":\"This API key has expired.\"}}",
314 );
315 let (base, _rx) = serve_times(vec![UNAUTHORIZED]);
316 let mut sink = Collector::default();
317 let error = provider::chat(
318 &config(base),
319 &[json!({ "role": "user", "content": "hi" })],
320 &[],
321 &AtomicBool::new(false),
322 &mut sink,
323 )
324 .expect_err("401 should fail");
325
326 let message = format!("{error}");
327 assert!(message.contains("OPENCODE_API_KEY"), "{message}");
328}
diff --git a/tests/sessions.rs b/tests/sessions.rs
new file mode 100644
index 0000000..8d17fc5
--- /dev/null
+++ b/tests/sessions.rs
@@ -0,0 +1,69 @@
1use std::fs;
2use std::path::PathBuf;
3use std::process::Command;
4
5use serde_json::json;
6
7use agent686::session::{self, Session};
8
9fn temp_dir(tag: &str) -> PathBuf {
10 let dir = std::env::temp_dir().join(format!("agent686-sess-{tag}-{}", std::process::id()));
11 let _ = fs::remove_dir_all(&dir);
12 fs::create_dir_all(&dir).unwrap();
13 dir
14}
15
16#[test]
17fn sessions_create_list_and_replay() {
18 let dir = temp_dir("roundtrip");
19 std::env::set_var("AGENT686_DATA", &dir);
20
21 let system = json!({ "role": "system", "content": "frozen" });
22 let mut alpha = Session::create_as("alpha".into(), "model-a", &system).unwrap();
23 assert!(
24 Session::create_as("alpha".into(), "model-a", &system).is_err(),
25 "duplicate ids must not overwrite a session"
26 );
27
28 alpha
29 .append(&json!({ "role": "user", "content": "hello" }), None)
30 .unwrap();
31 alpha
32 .append(
33 &json!({ "role": "assistant", "content": "hi" }),
34 Some("because"),
35 )
36 .unwrap();
37
38 assert!(session::exists("alpha"));
39 assert!(!session::exists("nope"));
40
41 let listed = session::list().unwrap();
42 assert_eq!(listed.len(), 1);
43 assert_eq!(listed[0].id, "alpha");
44 assert_eq!(listed[0].model, "model-a");
45 assert_eq!(listed[0].messages, 2);
46
47 let (reopened, system_back, messages) = Session::open("alpha").unwrap();
48 assert_eq!(reopened.id, "alpha");
49 assert_eq!(system_back["content"], "frozen");
50 assert_eq!(messages.len(), 2);
51 assert_eq!(messages[1]["content"], "hi");
52 // Reasoning is stored beside the message but must not be replayed.
53 assert!(messages[1].get("_reasoning").is_none());
54}
55
56#[test]
57fn cli_lists_sessions_without_a_key() {
58 let dir = temp_dir("cli");
59 let output = Command::new(env!("CARGO_BIN_EXE_agent686"))
60 .env("AGENT686_DATA", &dir)
61 .env_remove("OPENCODE_API_KEY")
62 .arg("--list")
63 .output()
64 .unwrap();
65
66 assert!(output.status.success(), "{output:?}");
67 let stdout = String::from_utf8_lossy(&output.stdout);
68 assert!(stdout.contains("no sessions"), "{stdout}");
69}