summaryrefslogtreecommitdiffstats
path: root/tests
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--tests/loop.rs192
-rw-r--r--tests/mock.rs5
-rw-r--r--tests/tools.rs142
3 files changed, 339 insertions, 0 deletions
diff --git a/tests/loop.rs b/tests/loop.rs
new file mode 100644
index 0000000..d77d890
--- /dev/null
+++ b/tests/loop.rs
@@ -0,0 +1,192 @@
1use std::fs;
2use std::io::{BufRead, BufReader, Read, Write};
3use std::net::TcpListener;
4use std::path::PathBuf;
5use std::sync::atomic::AtomicBool;
6use std::thread;
7
8use serde_json::json;
9
10use agent686::agent;
11use agent686::config::Config;
12use agent686::session::Session;
13use agent686::ui::Approver;
14
15fn sse(body: &str) -> String {
16 format!(
17 "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n{body}"
18 )
19}
20
21/// Serves one canned SSE response per connection, in order.
22fn serve_sequence(responses: Vec<String>) -> String {
23 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
24 let addr = listener.local_addr().unwrap();
25 thread::spawn(move || {
26 for response in responses {
27 let (mut stream, _) = listener.accept().unwrap();
28 let mut reader = BufReader::new(stream.try_clone().unwrap());
29 let mut length = 0usize;
30 loop {
31 let mut line = String::new();
32 if reader.read_line(&mut line).unwrap_or(0) == 0 {
33 break;
34 }
35 if line == "\r\n" || line == "\n" {
36 break;
37 }
38 if let Some(value) = line.to_ascii_lowercase().strip_prefix("content-length:") {
39 length = value.trim().parse().unwrap_or(0);
40 }
41 }
42 let mut body = vec![0u8; length];
43 let _ = reader.read_exact(&mut body);
44 let _ = stream.write_all(response.as_bytes());
45 let _ = stream.flush();
46 }
47 });
48 format!("http://{addr}")
49}
50
51fn temp_dir(tag: &str) -> PathBuf {
52 let dir = std::env::temp_dir().join(format!("agent686-loop-{tag}-{}", std::process::id()));
53 let _ = fs::remove_dir_all(&dir);
54 fs::create_dir_all(&dir).unwrap();
55 dir
56}
57
58#[test]
59fn runs_a_tool_call_then_finishes_and_records_every_message() {
60 let dir = temp_dir("write");
61 let target = dir.join("hello.txt");
62 let arguments = json!({
63 "path": target.display().to_string(),
64 "content": "hello from the mock\n"
65 })
66 .to_string();
67
68 let tool_round = sse(&format!(
69 "data: {}\n\ndata: [DONE]\n\n",
70 json!({
71 "choices": [{
72 "delta": { "tool_calls": [{
73 "index": 0,
74 "id": "call_1",
75 "function": { "name": "write", "arguments": arguments }
76 }]},
77 "finish_reason": "tool_calls"
78 }]
79 })
80 ));
81 let final_round = sse(
82 "data: {\"choices\":[{\"delta\":{\"content\":\"done\"},\"finish_reason\":\"stop\"}]}\n\n\
83 data: [DONE]\n\n",
84 );
85
86 let base = serve_sequence(vec![tool_round, final_round]);
87
88 std::env::set_var("AGENT686_DATA", dir.join("data"));
89
90 let system = agent::system_prompt();
91 let mut session = Session::create("test-model", &system).unwrap();
92 let cfg = Config {
93 base_url: base,
94 api_key: "test-key".into(),
95 model: "test-model".into(),
96 session: session.id.clone(),
97 yolo: true,
98 };
99 let mut history = agent::new_history(system);
100 let mut approver = Approver::new(true);
101
102 agent::run_turn(
103 &cfg,
104 &mut session,
105 &mut history,
106 "write a file",
107 &AtomicBool::new(false),
108 &mut approver,
109 )
110 .expect("turn should complete");
111
112 assert_eq!(
113 fs::read_to_string(&target).unwrap(),
114 "hello from the mock\n"
115 );
116
117 // system, user, assistant(tool_calls), tool result, assistant(final)
118 assert_eq!(history.len(), 5);
119 assert_eq!(history[3]["role"], "tool");
120 assert_eq!(history[3]["tool_call_id"], "call_1");
121
122 let log = fs::read_to_string(session.path()).unwrap();
123 let lines: Vec<&str> = log.lines().collect();
124 assert_eq!(lines.len(), 5, "header plus four messages: {log}");
125 assert!(lines[0].contains("\"t\":\"header\""));
126 assert_eq!(lines[3].contains("\"role\":\"tool\""), true);
127}
128
129#[test]
130fn a_denied_tool_call_is_returned_as_data() {
131 let dir = temp_dir("denied");
132 let target = dir.join("never.txt");
133 let arguments = json!({
134 "path": target.display().to_string(),
135 "content": "should not exist"
136 })
137 .to_string();
138
139 let tool_round = sse(&format!(
140 "data: {}\n\ndata: [DONE]\n\n",
141 json!({
142 "choices": [{
143 "delta": { "tool_calls": [{
144 "index": 0,
145 "id": "call_1",
146 "function": { "name": "write", "arguments": arguments }
147 }]},
148 "finish_reason": "tool_calls"
149 }]
150 })
151 ));
152 let final_round = sse(
153 "data: {\"choices\":[{\"delta\":{\"content\":\"understood\"},\"finish_reason\":\"stop\"}]}\n\n\
154 data: [DONE]\n\n",
155 );
156
157 let base = serve_sequence(vec![tool_round, final_round]);
158 std::env::set_var("AGENT686_DATA", dir.join("data"));
159
160 let system = agent::system_prompt();
161 let mut session = Session::create("test-model", &system).unwrap();
162 let cfg = Config {
163 base_url: base,
164 api_key: "test-key".into(),
165 model: "test-model".into(),
166 session: session.id.clone(),
167 yolo: false,
168 };
169 let mut history = agent::new_history(system);
170 // Not a terminal, so the approver must deny rather than block.
171 let mut approver = Approver::new(false);
172
173 agent::run_turn(
174 &cfg,
175 &mut session,
176 &mut history,
177 "write a file",
178 &AtomicBool::new(false),
179 &mut approver,
180 )
181 .expect("a denial is not a failed turn");
182
183 assert!(!target.exists());
184 assert_eq!(history[3]["role"], "tool");
185 assert!(
186 history[3]["content"]
187 .as_str()
188 .unwrap()
189 .contains("denied by the user")
190 );
191 assert_eq!(history[4]["content"], "understood");
192}
diff --git a/tests/mock.rs b/tests/mock.rs
index 80d965b..52dec7c 100644
--- a/tests/mock.rs
+++ b/tests/mock.rs
@@ -73,6 +73,7 @@ fn config(base_url: String) -> Config {
73 api_key: "test-key".into(), 73 api_key: "test-key".into(),
74 model: "test-model".into(), 74 model: "test-model".into(),
75 session: "testsession".into(), 75 session: "testsession".into(),
76 yolo: true,
76 } 77 }
77} 78}
78 79
@@ -94,6 +95,7 @@ fn streams_text_reasoning_and_usage() {
94 let outcome = provider::chat( 95 let outcome = provider::chat(
95 &config(base), 96 &config(base),
96 &[json!({ "role": "user", "content": "hi" })], 97 &[json!({ "role": "user", "content": "hi" })],
98 &[],
97 &AtomicBool::new(false), 99 &AtomicBool::new(false),
98 &mut sink, 100 &mut sink,
99 ) 101 )
@@ -133,6 +135,7 @@ fn assembles_tool_call_arguments_byte_for_byte() {
133 let outcome = provider::chat( 135 let outcome = provider::chat(
134 &config(base), 136 &config(base),
135 &[json!({ "role": "user", "content": "read a.txt" })], 137 &[json!({ "role": "user", "content": "read a.txt" })],
138 &[],
136 &AtomicBool::new(false), 139 &AtomicBool::new(false),
137 &mut sink, 140 &mut sink,
138 ) 141 )
@@ -161,6 +164,7 @@ fn surfaces_provider_error_text() {
161 let error = provider::chat( 164 let error = provider::chat(
162 &config(base), 165 &config(base),
163 &[json!({ "role": "user", "content": "hi" })], 166 &[json!({ "role": "user", "content": "hi" })],
167 &[],
164 &AtomicBool::new(false), 168 &AtomicBool::new(false),
165 &mut sink, 169 &mut sink,
166 ) 170 )
@@ -184,6 +188,7 @@ fn honours_a_cancelled_turn() {
184 let error = provider::chat( 188 let error = provider::chat(
185 &config(base), 189 &config(base),
186 &[json!({ "role": "user", "content": "hi" })], 190 &[json!({ "role": "user", "content": "hi" })],
191 &[],
187 &AtomicBool::new(true), 192 &AtomicBool::new(true),
188 &mut sink, 193 &mut sink,
189 ) 194 )
diff --git a/tests/tools.rs b/tests/tools.rs
new file mode 100644
index 0000000..0189af8
--- /dev/null
+++ b/tests/tools.rs
@@ -0,0 +1,142 @@
1use std::fs;
2use std::path::PathBuf;
3use std::time::Duration;
4
5use serde_json::json;
6
7use agent686::tools::{self, shell};
8
9fn temp_dir(tag: &str) -> PathBuf {
10 let dir = std::env::temp_dir().join(format!("agent686-test-{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 edit_refuses_ambiguous_and_missing_text() {
18 let dir = temp_dir("edit-ambiguous");
19 let path = dir.join("a.txt");
20 fs::write(&path, "alpha\nbeta\nalpha\n").unwrap();
21
22 let error = tools::plan("edit", &json!({ "path": path, "old": "alpha", "new": "gamma" }))
23 .err()
24 .expect("ambiguous edit must fail");
25 assert!(error.contains("appears 2 times"), "{error}");
26 assert!(error.contains("lines 1, 3"), "{error}");
27
28 let error = tools::plan("edit", &json!({ "path": path, "old": "nope", "new": "x" }))
29 .err()
30 .expect("missing text must fail");
31 assert!(error.contains("was not found"), "{error}");
32
33 // The file is untouched by a refused plan.
34 assert_eq!(fs::read_to_string(&path).unwrap(), "alpha\nbeta\nalpha\n");
35}
36
37#[test]
38fn edit_applies_exactly_one_replacement() {
39 let dir = temp_dir("edit-apply");
40 let path = dir.join("main.c");
41 fs::write(&path, "int main(void) {\n return 0;\n}\n").unwrap();
42
43 let change = tools::plan(
44 "edit",
45 &json!({ "path": path, "old": " return 0;", "new": " return 1;" }),
46 )
47 .expect("unique edit should plan");
48
49 let preview = change.preview();
50 assert!(preview.contains("- return 0;"), "{preview}");
51 assert!(preview.contains("+ return 1;"), "{preview}");
52
53 let outcome = change.apply().expect("apply should succeed");
54 assert!(outcome.contains("1 replacement at line 2"), "{outcome}");
55 assert_eq!(
56 fs::read_to_string(&path).unwrap(),
57 "int main(void) {\n return 1;\n}\n"
58 );
59}
60
61#[test]
62fn write_does_not_create_parent_directories() {
63 let dir = temp_dir("write-parent");
64 let path = dir.join("missing").join("file.txt");
65 let change = tools::plan("write", &json!({ "path": path, "content": "hi" })).unwrap();
66 let error = change.apply().err().expect("apply must fail");
67 assert!(error.contains("parent directory does not exist"), "{error}");
68}
69
70#[test]
71fn read_numbers_lines_and_reports_truncation() {
72 let dir = temp_dir("read");
73 let path = dir.join("f.txt");
74 fs::write(&path, "one\ntwo\nthree\nfour\n").unwrap();
75
76 let text = tools::run("read", &json!({ "path": path, "limit": 2 })).unwrap();
77 assert!(text.contains(" 1\tone"), "{text}");
78 assert!(text.contains(" 2\ttwo"), "{text}");
79 assert!(text.contains("2 more line(s); continue with offset=3"), "{text}");
80 assert!(!text.contains("three"), "{text}");
81}
82
83#[test]
84fn grep_finds_lines_and_honours_case() {
85 let dir = temp_dir("grep");
86 let path = dir.join("f.txt");
87 fs::write(&path, "alpha\nbeta\nALPHA\n").unwrap();
88
89 let text = tools::run("grep", &json!({ "pattern": "alpha", "path": dir })).unwrap();
90 assert_eq!(text.lines().count(), 1, "{text}");
91
92 let text = tools::run(
93 "grep",
94 &json!({ "pattern": "alpha", "path": dir, "ignore_case": true }),
95 )
96 .unwrap();
97 assert_eq!(text.lines().count(), 2, "{text}");
98}
99
100#[test]
101fn glob_supports_double_star_and_bare_names() {
102 let dir = temp_dir("glob");
103 fs::create_dir_all(dir.join("sub/deep")).unwrap();
104 fs::write(dir.join("a.rs"), "").unwrap();
105 fs::write(dir.join("sub/b.rs"), "").unwrap();
106 fs::write(dir.join("sub/deep/c.rs"), "").unwrap();
107 fs::write(dir.join("sub/note.txt"), "").unwrap();
108
109 let text = tools::run("glob", &json!({ "pattern": "**/*.rs", "path": dir })).unwrap();
110 assert_eq!(text.lines().count(), 3, "{text}");
111
112 let text = tools::run("glob", &json!({ "pattern": "*.rs", "path": dir })).unwrap();
113 assert_eq!(text.lines().count(), 3, "{text}");
114
115 let text = tools::run("glob", &json!({ "pattern": "sub/*.rs", "path": dir })).unwrap();
116 assert_eq!(text.lines().count(), 1, "{text}");
117 assert!(text.contains("b.rs"), "{text}");
118}
119
120#[test]
121fn bash_reports_exit_code_and_times_out() {
122 let text = tools::run("bash", &json!({ "cmd": "echo hi; exit 3" })).unwrap();
123 assert!(text.contains("hi"), "{text}");
124 assert!(text.contains("[exit 3]"), "{text}");
125
126 let text = shell::bash(&json!({ "cmd": "sleep 5" }), Duration::from_millis(150)).unwrap();
127 assert!(text.contains("timed out after"), "{text}");
128}
129
130#[test]
131fn bash_rejects_a_missing_cwd() {
132 let error = tools::run("bash", &json!({ "cmd": "true", "cwd": "/nonexistent-dir-xyz" }))
133 .err()
134 .expect("missing cwd must fail");
135 assert!(error.contains("cwd is not a directory"), "{error}");
136}
137
138#[test]
139fn unknown_tool_is_an_error_not_a_panic() {
140 let error = tools::run("teleport", &json!({})).err().unwrap();
141 assert!(error.contains("unknown tool"), "{error}");
142}