aboutsummaryrefslogtreecommitdiffstats
path: root/tests
diff options
context:
space:
mode:
Diffstat (limited to 'tests')
-rw-r--r--tests/loop.rs135
-rw-r--r--tests/mock.rs116
2 files changed, 251 insertions, 0 deletions
diff --git a/tests/loop.rs b/tests/loop.rs
index d77d890..ac137da 100644
--- a/tests/loop.rs
+++ b/tests/loop.rs
@@ -190,3 +190,138 @@ fn a_denied_tool_call_is_returned_as_data() {
190 ); 190 );
191 assert_eq!(history[4]["content"], "understood"); 191 assert_eq!(history[4]["content"], "understood");
192} 192}
193
194fn tool_call(index: usize, id: &str, name: &str, arguments: serde_json::Value) -> serde_json::Value {
195 json!({
196 "index": index,
197 "id": id,
198 "function": { "name": name, "arguments": arguments.to_string() }
199 })
200}
201
202#[test]
203fn aborting_between_tool_calls_answers_every_call() {
204 let dir = temp_dir("abort-mid-calls");
205 let slow = sse(&format!(
206 "data: {}\n\ndata: [DONE]\n\n",
207 json!({
208 "choices": [{
209 "delta": { "tool_calls": [
210 tool_call(0, "call_a", "bash", json!({ "cmd": "sleep 0.5" })),
211 tool_call(1, "call_b", "write", json!({ "path": dir.join("b.txt"), "content": "b" })),
212 tool_call(2, "call_c", "write", json!({ "path": dir.join("c.txt"), "content": "c" }))
213 ]},
214 "finish_reason": "tool_calls"
215 }]
216 })
217 ));
218 // If the harness wrongly continues after the abort, it would consume this.
219 let after = sse(
220 "data: {\"choices\":[{\"delta\":{\"content\":\"should not be reached\"},\"finish_reason\":\"stop\"}]}\n\n\
221 data: [DONE]\n\n",
222 );
223
224 let base = serve_sequence(vec![slow, after]);
225 std::env::set_var("AGENT686_DATA", dir.join("data"));
226
227 let system = agent::system_prompt();
228 let mut session = Session::create("test-model", &system).unwrap();
229 let cfg = Config {
230 base_url: base,
231 api_key: "test-key".into(),
232 model: "test-model".into(),
233 session: session.id.clone(),
234 yolo: true,
235 };
236 let mut history = agent::new_history(system);
237 let mut approver = Approver::new(true);
238 let cancel = std::sync::Arc::new(AtomicBool::new(false));
239
240 let flag = cancel.clone();
241 thread::spawn(move || {
242 thread::sleep(std::time::Duration::from_millis(150));
243 flag.store(true, std::sync::atomic::Ordering::SeqCst);
244 });
245
246 let report = agent::run_turn(
247 &cfg,
248 &mut session,
249 &mut history,
250 "do three things",
251 &cancel,
252 &mut approver,
253 )
254 .expect("an abort is not an error");
255
256 assert!(report.aborted);
257
258 // Every announced tool call must have exactly one result, or the provider
259 // rejects the session forever and the transcript cannot be rewritten.
260 let answered: Vec<String> = history
261 .iter()
262 .filter(|message| message.get("role").and_then(|r| r.as_str()) == Some("tool"))
263 .filter_map(|message| message.get("tool_call_id").and_then(|id| id.as_str()).map(|s| s.to_string()))
264 .collect();
265 assert_eq!(answered, vec!["call_a", "call_b", "call_c"], "{answered:?}");
266
267 // The loop stopped: no assistant text was ever appended.
268 assert_eq!(history.last().unwrap()["role"], "tool");
269 assert!(fs::read_to_string(session.path()).unwrap().lines().count() >= 5);
270}
271
272#[test]
273fn opening_a_session_with_unanswered_calls_repairs_it() {
274 let dir = temp_dir("repair");
275 std::env::set_var("AGENT686_DATA", dir.join("data"));
276
277 let base = serve_sequence(vec![sse(
278 "data: {\"choices\":[{\"delta\":{\"content\":\"carrying on\"},\"finish_reason\":\"stop\"}]}\n\n\
279 data: [DONE]\n\n",
280 )]);
281
282 let system = agent::system_prompt();
283 let mut session = Session::create("test-model", &system).unwrap();
284 let mut history = agent::new_history(system);
285
286 // A transcript shape left behind by an older build: two calls, one result.
287 let assistant = json!({
288 "role": "assistant",
289 "content": null,
290 "tool_calls": [
291 { "id": "call_1", "type": "function", "function": { "name": "read", "arguments": "{}" } },
292 { "id": "call_2", "type": "function", "function": { "name": "read", "arguments": "{}" } }
293 ]
294 });
295 session.append(&assistant, None).unwrap();
296 history.push(assistant);
297 let partial = json!({ "role": "tool", "tool_call_id": "call_1", "content": "ok" });
298 session.append(&partial, None).unwrap();
299 history.push(partial);
300
301 let cfg = Config {
302 base_url: base,
303 api_key: "test-key".into(),
304 model: "test-model".into(),
305 session: session.id.clone(),
306 yolo: true,
307 };
308 let mut approver = Approver::new(true);
309 agent::run_turn(
310 &cfg,
311 &mut session,
312 &mut history,
313 "go on",
314 &AtomicBool::new(false),
315 &mut approver,
316 )
317 .expect("repair should let the turn run");
318
319 let repaired = history.iter().any(|message| {
320 message.get("tool_call_id").and_then(|id| id.as_str()) == Some("call_2")
321 && message
322 .get("content")
323 .and_then(|c| c.as_str())
324 .is_some_and(|c| c.contains("interrupted"))
325 });
326 assert!(repaired, "missing result for call_2 should be synthesised");
327}
diff --git a/tests/mock.rs b/tests/mock.rs
index 9b3cd5a..9b9a56d 100644
--- a/tests/mock.rs
+++ b/tests/mock.rs
@@ -326,3 +326,119 @@ fn auth_failure_says_where_the_key_lives() {
326 let message = format!("{error}"); 326 let message = format!("{error}");
327 assert!(message.contains("OPENCODE_API_KEY"), "{message}"); 327 assert!(message.contains("OPENCODE_API_KEY"), "{message}");
328} 328}
329
330#[test]
331fn a_truncated_stream_is_an_error_not_an_answer() {
332 const TRUNCATED: &str = concat!(
333 "HTTP/1.1 200 OK\r\n",
334 "Content-Type: text/event-stream\r\n",
335 "Connection: close\r\n",
336 "\r\n",
337 "data: {\"choices\":[{\"delta\":{\"content\":\"partial\"}}]}\n\n",
338 );
339 let (base, _rx) = serve_once(TRUNCATED);
340 let mut sink = Collector::default();
341 let error = provider::chat(
342 &config(base),
343 &[json!({ "role": "user", "content": "hi" })],
344 &[],
345 &AtomicBool::new(false),
346 &mut sink,
347 )
348 .expect_err("a stream without [DONE] or finish_reason must fail");
349
350 let message = format!("{error}");
351 assert!(message.contains("ended before completion"), "{message}");
352}
353
354#[test]
355fn a_non_sse_200_is_an_error_not_an_empty_answer() {
356 const JSON: &str = concat!(
357 "HTTP/1.1 200 OK\r\n",
358 "Content-Type: application/json\r\n",
359 "Connection: close\r\n",
360 "\r\n",
361 "{\"id\":\"x\",\"choices\":[{\"message\":{\"content\":\"hello\"}}]}",
362 );
363 let (base, _rx) = serve_once(JSON);
364 let mut sink = Collector::default();
365 let error = provider::chat(
366 &config(base),
367 &[json!({ "role": "user", "content": "hi" })],
368 &[],
369 &AtomicBool::new(false),
370 &mut sink,
371 )
372 .expect_err("a non-streaming body must not look like a blank answer");
373 assert!(format!("{error}").contains("ended before completion"));
374}
375
376#[test]
377fn finish_reason_without_done_marker_is_accepted() {
378 const SSE: &str = concat!(
379 "HTTP/1.1 200 OK\r\n",
380 "Content-Type: text/event-stream\r\n",
381 "Connection: close\r\n",
382 "\r\n",
383 "data: {\"choices\":[{\"delta\":{\"content\":\"ok\"},\"finish_reason\":\"stop\"}]}\n\n",
384 );
385 let (base, _rx) = serve_once(SSE);
386 let mut sink = Collector::default();
387 let outcome = provider::chat(
388 &config(base),
389 &[json!({ "role": "user", "content": "hi" })],
390 &[],
391 &AtomicBool::new(false),
392 &mut sink,
393 )
394 .expect("finish_reason is enough");
395 assert_eq!(outcome.content, "ok");
396}
397
398#[test]
399fn a_tool_call_without_an_index_still_assembles() {
400 const SSE: &str = concat!(
401 "HTTP/1.1 200 OK\r\n",
402 "Content-Type: text/event-stream\r\n",
403 "Connection: close\r\n",
404 "\r\n",
405 "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"id\":\"call_1\",\"function\":{\"name\":\"read\",\"arguments\":\"{\\\"path\\\":\\\"a\\\"}\"}}]},\"finish_reason\":\"tool_calls\"}]}\n\n",
406 "data: [DONE]\n\n",
407 );
408 let (base, _rx) = serve_once(SSE);
409 let mut sink = Collector::default();
410 let outcome = provider::chat(
411 &config(base),
412 &[json!({ "role": "user", "content": "hi" })],
413 &[],
414 &AtomicBool::new(false),
415 &mut sink,
416 )
417 .expect("chat should succeed");
418
419 assert_eq!(outcome.tool_calls.len(), 1);
420 assert_eq!(outcome.tool_calls[0].name, "read");
421 assert_eq!(outcome.tool_calls[0].arguments, "{\"path\":\"a\"}");
422}
423
424#[test]
425fn a_final_frame_without_a_newline_is_not_lost() {
426 const SSE: &str = concat!(
427 "HTTP/1.1 200 OK\r\n",
428 "Content-Type: text/event-stream\r\n",
429 "Connection: close\r\n",
430 "\r\n",
431 "data: {\"choices\":[{\"delta\":{\"content\":\"last\"},\"finish_reason\":\"stop\"}]}",
432 );
433 let (base, _rx) = serve_once(SSE);
434 let mut sink = Collector::default();
435 let outcome = provider::chat(
436 &config(base),
437 &[json!({ "role": "user", "content": "hi" })],
438 &[],
439 &AtomicBool::new(false),
440 &mut sink,
441 )
442 .expect("a trailing frame without a newline should still count");
443 assert_eq!(outcome.content, "last");
444}