summaryrefslogtreecommitdiffstats
path: root/tests/loop.rs
blob: ac137dae830736105b83c54ea5d96211d203ce7d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
use std::fs;
use std::io::{BufRead, BufReader, Read, Write};
use std::net::TcpListener;
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
use std::thread;

use serde_json::json;

use agent686::agent;
use agent686::config::Config;
use agent686::session::Session;
use agent686::ui::Approver;

fn sse(body: &str) -> String {
    format!(
        "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n{body}"
    )
}

/// Serves one canned SSE response per connection, in order.
fn serve_sequence(responses: Vec<String>) -> String {
    let listener = TcpListener::bind("127.0.0.1:0").unwrap();
    let addr = listener.local_addr().unwrap();
    thread::spawn(move || {
        for response in responses {
            let (mut stream, _) = listener.accept().unwrap();
            let mut reader = BufReader::new(stream.try_clone().unwrap());
            let mut 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:") {
                    length = value.trim().parse().unwrap_or(0);
                }
            }
            let mut body = vec![0u8; length];
            let _ = reader.read_exact(&mut body);
            let _ = stream.write_all(response.as_bytes());
            let _ = stream.flush();
        }
    });
    format!("http://{addr}")
}

fn temp_dir(tag: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("agent686-loop-{tag}-{}", std::process::id()));
    let _ = fs::remove_dir_all(&dir);
    fs::create_dir_all(&dir).unwrap();
    dir
}

#[test]
fn runs_a_tool_call_then_finishes_and_records_every_message() {
    let dir = temp_dir("write");
    let target = dir.join("hello.txt");
    let arguments = json!({
        "path": target.display().to_string(),
        "content": "hello from the mock\n"
    })
    .to_string();

    let tool_round = sse(&format!(
        "data: {}\n\ndata: [DONE]\n\n",
        json!({
            "choices": [{
                "delta": { "tool_calls": [{
                    "index": 0,
                    "id": "call_1",
                    "function": { "name": "write", "arguments": arguments }
                }]},
                "finish_reason": "tool_calls"
            }]
        })
    ));
    let final_round = sse(
        "data: {\"choices\":[{\"delta\":{\"content\":\"done\"},\"finish_reason\":\"stop\"}]}\n\n\
         data: [DONE]\n\n",
    );

    let base = serve_sequence(vec![tool_round, final_round]);

    std::env::set_var("AGENT686_DATA", dir.join("data"));

    let system = agent::system_prompt();
    let mut session = Session::create("test-model", &system).unwrap();
    let cfg = Config {
        base_url: base,
        api_key: "test-key".into(),
        model: "test-model".into(),
        session: session.id.clone(),
        yolo: true,
    };
    let mut history = agent::new_history(system);
    let mut approver = Approver::new(true);

    agent::run_turn(
        &cfg,
        &mut session,
        &mut history,
        "write a file",
        &AtomicBool::new(false),
        &mut approver,
    )
    .expect("turn should complete");

    assert_eq!(
        fs::read_to_string(&target).unwrap(),
        "hello from the mock\n"
    );

    // system, user, assistant(tool_calls), tool result, assistant(final)
    assert_eq!(history.len(), 5);
    assert_eq!(history[3]["role"], "tool");
    assert_eq!(history[3]["tool_call_id"], "call_1");

    let log = fs::read_to_string(session.path()).unwrap();
    let lines: Vec<&str> = log.lines().collect();
    assert_eq!(lines.len(), 5, "header plus four messages: {log}");
    assert!(lines[0].contains("\"t\":\"header\""));
    assert_eq!(lines[3].contains("\"role\":\"tool\""), true);
}

#[test]
fn a_denied_tool_call_is_returned_as_data() {
    let dir = temp_dir("denied");
    let target = dir.join("never.txt");
    let arguments = json!({
        "path": target.display().to_string(),
        "content": "should not exist"
    })
    .to_string();

    let tool_round = sse(&format!(
        "data: {}\n\ndata: [DONE]\n\n",
        json!({
            "choices": [{
                "delta": { "tool_calls": [{
                    "index": 0,
                    "id": "call_1",
                    "function": { "name": "write", "arguments": arguments }
                }]},
                "finish_reason": "tool_calls"
            }]
        })
    ));
    let final_round = sse(
        "data: {\"choices\":[{\"delta\":{\"content\":\"understood\"},\"finish_reason\":\"stop\"}]}\n\n\
         data: [DONE]\n\n",
    );

    let base = serve_sequence(vec![tool_round, final_round]);
    std::env::set_var("AGENT686_DATA", dir.join("data"));

    let system = agent::system_prompt();
    let mut session = Session::create("test-model", &system).unwrap();
    let cfg = Config {
        base_url: base,
        api_key: "test-key".into(),
        model: "test-model".into(),
        session: session.id.clone(),
        yolo: false,
    };
    let mut history = agent::new_history(system);
    // Not a terminal, so the approver must deny rather than block.
    let mut approver = Approver::new(false);

    agent::run_turn(
        &cfg,
        &mut session,
        &mut history,
        "write a file",
        &AtomicBool::new(false),
        &mut approver,
    )
    .expect("a denial is not a failed turn");

    assert!(!target.exists());
    assert_eq!(history[3]["role"], "tool");
    assert!(
        history[3]["content"]
            .as_str()
            .unwrap()
            .contains("denied by the user")
    );
    assert_eq!(history[4]["content"], "understood");
}

fn tool_call(index: usize, id: &str, name: &str, arguments: serde_json::Value) -> serde_json::Value {
    json!({
        "index": index,
        "id": id,
        "function": { "name": name, "arguments": arguments.to_string() }
    })
}

#[test]
fn aborting_between_tool_calls_answers_every_call() {
    let dir = temp_dir("abort-mid-calls");
    let slow = sse(&format!(
        "data: {}\n\ndata: [DONE]\n\n",
        json!({
            "choices": [{
                "delta": { "tool_calls": [
                    tool_call(0, "call_a", "bash", json!({ "cmd": "sleep 0.5" })),
                    tool_call(1, "call_b", "write", json!({ "path": dir.join("b.txt"), "content": "b" })),
                    tool_call(2, "call_c", "write", json!({ "path": dir.join("c.txt"), "content": "c" }))
                ]},
                "finish_reason": "tool_calls"
            }]
        })
    ));
    // If the harness wrongly continues after the abort, it would consume this.
    let after = sse(
        "data: {\"choices\":[{\"delta\":{\"content\":\"should not be reached\"},\"finish_reason\":\"stop\"}]}\n\n\
         data: [DONE]\n\n",
    );

    let base = serve_sequence(vec![slow, after]);
    std::env::set_var("AGENT686_DATA", dir.join("data"));

    let system = agent::system_prompt();
    let mut session = Session::create("test-model", &system).unwrap();
    let cfg = Config {
        base_url: base,
        api_key: "test-key".into(),
        model: "test-model".into(),
        session: session.id.clone(),
        yolo: true,
    };
    let mut history = agent::new_history(system);
    let mut approver = Approver::new(true);
    let cancel = std::sync::Arc::new(AtomicBool::new(false));

    let flag = cancel.clone();
    thread::spawn(move || {
        thread::sleep(std::time::Duration::from_millis(150));
        flag.store(true, std::sync::atomic::Ordering::SeqCst);
    });

    let report = agent::run_turn(
        &cfg,
        &mut session,
        &mut history,
        "do three things",
        &cancel,
        &mut approver,
    )
    .expect("an abort is not an error");

    assert!(report.aborted);

    // Every announced tool call must have exactly one result, or the provider
    // rejects the session forever and the transcript cannot be rewritten.
    let answered: Vec<String> = history
        .iter()
        .filter(|message| message.get("role").and_then(|r| r.as_str()) == Some("tool"))
        .filter_map(|message| message.get("tool_call_id").and_then(|id| id.as_str()).map(|s| s.to_string()))
        .collect();
    assert_eq!(answered, vec!["call_a", "call_b", "call_c"], "{answered:?}");

    // The loop stopped: no assistant text was ever appended.
    assert_eq!(history.last().unwrap()["role"], "tool");
    assert!(fs::read_to_string(session.path()).unwrap().lines().count() >= 5);
}

#[test]
fn opening_a_session_with_unanswered_calls_repairs_it() {
    let dir = temp_dir("repair");
    std::env::set_var("AGENT686_DATA", dir.join("data"));

    let base = serve_sequence(vec![sse(
        "data: {\"choices\":[{\"delta\":{\"content\":\"carrying on\"},\"finish_reason\":\"stop\"}]}\n\n\
         data: [DONE]\n\n",
    )]);

    let system = agent::system_prompt();
    let mut session = Session::create("test-model", &system).unwrap();
    let mut history = agent::new_history(system);

    // A transcript shape left behind by an older build: two calls, one result.
    let assistant = json!({
        "role": "assistant",
        "content": null,
        "tool_calls": [
            { "id": "call_1", "type": "function", "function": { "name": "read", "arguments": "{}" } },
            { "id": "call_2", "type": "function", "function": { "name": "read", "arguments": "{}" } }
        ]
    });
    session.append(&assistant, None).unwrap();
    history.push(assistant);
    let partial = json!({ "role": "tool", "tool_call_id": "call_1", "content": "ok" });
    session.append(&partial, None).unwrap();
    history.push(partial);

    let cfg = Config {
        base_url: base,
        api_key: "test-key".into(),
        model: "test-model".into(),
        session: session.id.clone(),
        yolo: true,
    };
    let mut approver = Approver::new(true);
    agent::run_turn(
        &cfg,
        &mut session,
        &mut history,
        "go on",
        &AtomicBool::new(false),
        &mut approver,
    )
    .expect("repair should let the turn run");

    let repaired = history.iter().any(|message| {
        message.get("tool_call_id").and_then(|id| id.as_str()) == Some("call_2")
            && message
                .get("content")
                .and_then(|c| c.as_str())
                .is_some_and(|c| c.contains("interrupted"))
    });
    assert!(repaired, "missing result for call_2 should be synthesised");
}