oxicode-agent 0.71.0

Agent runtime with tool-calling loop for AI coding assistants
Documentation
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
//! Concurrency tests for SharedState and ToolRegistry.
//! Verifies thread-safety of shared mutable state under concurrent access.

use async_trait::async_trait;
use oxicode_agent::AgentTool;
use oxicode_agent::state::SharedState;
use oxicode_agent::tools::ToolRegistry;
use serde_json::{Value, json};
use std::sync::Arc;
use std::thread;
use tokio::sync::oneshot;

// ── Helper: simple tool for testing ──────────────────────────────

struct TestTool {
    name: String,
}

impl TestTool {
    fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
        }
    }
}

#[async_trait]
impl AgentTool for TestTool {
    fn name(&self) -> &str {
        &self.name
    }
    fn label(&self) -> &str {
        "Test Tool"
    }
    fn description(&self) -> &str {
        "A test tool"
    }
    fn parameters_schema(&self) -> Value {
        json!({ "type": "object", "properties": {} })
    }
    async fn execute(
        &self,
        _tool_call_id: &str,
        _params: Value,
        _signal: Option<oneshot::Receiver<()>>,
        _ctx: &oxicode_agent::ToolContext,
    ) -> Result<oxicode_agent::AgentToolResult, String> {
        Ok(oxicode_agent::AgentToolResult::success("test result"))
    }
}

// ═══════════════════════════════════════════════════════════════════
// SharedState Concurrent Reads
// ═══════════════════════════════════════════════════════════════════

#[test]
fn test_shared_state_concurrent_reads() {
    let shared = Arc::new(SharedState::new());

    // Pre-populate with messages
    shared.update(|s| {
        for i in 0..50 {
            s.add_user_message(format!("Message {}", i));
        }
    });

    let mut handles = Vec::new();

    for thread_id in 0..16 {
        let shared_clone = Arc::clone(&shared);
        handles.push(thread::spawn(move || {
            // Each thread reads the state multiple times
            for _ in 0..100 {
                let state = shared_clone.get_state();
                assert_eq!(
                    state.messages.len(),
                    50,
                    "thread {} sees all messages",
                    thread_id
                );
                assert_eq!(state.iteration, 0);
            }
        }));
    }

    for handle in handles {
        handle.join().expect("thread should not panic");
    }
}

#[test]
fn test_shared_state_concurrent_writes() {
    let shared = Arc::new(SharedState::new());
    let message_count = 100;

    let mut handles = Vec::new();

    for thread_id in 0..8 {
        let shared_clone = Arc::clone(&shared);
        handles.push(thread::spawn(move || {
            for i in 0..message_count {
                shared_clone.update(|s| {
                    s.add_user_message(format!("Thread {} msg {}", thread_id, i));
                });
            }
        }));
    }

    for handle in handles {
        handle.join().expect("thread should not panic");
    }

    let state = shared.get_state();
    assert_eq!(
        state.messages.len(),
        8 * message_count,
        "all messages from all threads should be present"
    );
}

#[test]
fn test_shared_state_concurrent_read_write() {
    let shared = Arc::new(SharedState::new());

    // Pre-populate
    shared.update(|s| {
        s.add_user_message("Initial".to_string());
    });

    let mut handles = Vec::new();

    // Writers
    for i in 0..4 {
        let shared_clone = Arc::clone(&shared);
        handles.push(thread::spawn(move || {
            for j in 0..50 {
                shared_clone.update(|s| {
                    s.add_user_message(format!("Writer {} msg {}", i, j));
                });
            }
        }));
    }

    // Readers
    for _ in 0..4 {
        let shared_clone = Arc::clone(&shared);
        handles.push(thread::spawn(move || {
            for _ in 0..100 {
                let state = shared_clone.get_state();
                // Should always see at least the initial message
                assert!(!state.messages.is_empty());
            }
        }));
    }

    for handle in handles {
        handle.join().expect("thread should not panic");
    }

    let state = shared.get_state();
    // 1 initial + 4 writers * 50 messages = 201
    assert_eq!(state.messages.len(), 201);
}

#[test]
fn test_shared_state_concurrent_usage_tracking() {
    let shared = Arc::new(SharedState::new());

    let mut handles = Vec::new();
    for _thread_id in 0..8 {
        let shared_clone = Arc::clone(&shared);
        handles.push(thread::spawn(move || {
            for _ in 0..100 {
                shared_clone.update(|s| {
                    s.record_usage(10, 5);
                });
            }
        }));
    }

    for handle in handles {
        handle.join().expect("thread should not panic");
    }

    let state = shared.get_state();
    assert_eq!(state.input_tokens, 8 * 100 * 10);
    assert_eq!(state.output_tokens, 8 * 100 * 5);
    assert_eq!(state.total_tokens, 8 * 100 * 15);
}

#[test]
fn test_shared_state_concurrent_reset() {
    let shared = Arc::new(SharedState::new());

    shared.update(|s| {
        s.add_user_message("Before reset".to_string());
    });

    let shared_clone = Arc::clone(&shared);
    let resetter = thread::spawn(move || {
        shared_clone.reset();
    });

    resetter.join().expect("reset thread");
    let state = shared.get_state();
    assert_eq!(state.messages.len(), 0);
}

// ═══════════════════════════════════════════════════════════════════
// ToolRegistry Concurrent Access
// ═══════════════════════════════════════════════════════════════════

#[test]
fn test_tool_registry_concurrent_access() {
    let registry = Arc::new(ToolRegistry::new());
    let mut handles = Vec::new();

    // Concurrent registrations
    for i in 0..20 {
        let reg_clone = Arc::clone(&registry);
        handles.push(thread::spawn(move || {
            reg_clone.register(TestTool::new(&format!("tool_{}", i)));
        }));
    }

    for handle in handles {
        handle.join().expect("register thread should not panic");
    }

    // Verify all tools were registered
    let names = registry.names();
    assert_eq!(names.len(), 20, "all 20 tools should be registered");

    // Verify each tool can be retrieved
    for i in 0..20 {
        let tool = registry.get(&format!("tool_{}", i));
        assert!(tool.is_some(), "tool_{} should be registered", i);
    }

    // Now do concurrent lookups
    let mut lookup_handles = Vec::new();
    for i in 0..20 {
        let reg_clone = Arc::clone(&registry);
        lookup_handles.push(thread::spawn(move || {
            for _ in 0..100 {
                let tool = reg_clone.get(&format!("tool_{}", i));
                assert!(tool.is_some(), "concurrent lookup for tool_{}", i);
                assert_eq!(tool.unwrap().name(), format!("tool_{}", i));
            }
        }));
    }

    for handle in lookup_handles {
        handle.join().expect("lookup thread should not panic");
    }
}

#[test]
fn test_tool_registry_concurrent_register_and_lookup() {
    let registry = Arc::new(ToolRegistry::new());

    // Start with a few tools
    registry.register(TestTool::new("initial_1"));
    registry.register(TestTool::new("initial_2"));

    let mut handles = Vec::new();

    // Some threads register new tools
    for i in 0..10 {
        let reg_clone = Arc::clone(&registry);
        handles.push(thread::spawn(move || {
            reg_clone.register(TestTool::new(&format!("concurrent_{}", i)));
        }));
    }

    // Some threads look up existing tools
    for _ in 0..10 {
        let reg_clone = Arc::clone(&registry);
        handles.push(thread::spawn(move || {
            // Should always be able to find initial tools
            let tool = reg_clone.get("initial_1");
            assert!(tool.is_some());
            let tool = reg_clone.get("initial_2");
            assert!(tool.is_some());
        }));
    }

    for handle in handles {
        handle.join().expect("thread should not panic");
    }

    // Final check: all tools should be present
    let names = registry.names();
    assert!(names.contains(&"initial_1".to_string()));
    assert!(names.contains(&"initial_2".to_string()));
    for i in 0..10 {
        assert!(
            names.contains(&format!("concurrent_{}", i)),
            "concurrent_{} should be registered",
            i
        );
    }
}

#[test]
fn test_tool_registry_concurrent_unregister() {
    let registry = Arc::new(ToolRegistry::new());

    // Register tools
    for i in 0..20 {
        registry.register(TestTool::new(&format!("tool_{}", i)));
    }

    let mut handles = Vec::new();

    // Concurrent unregistrations
    for i in 0..10 {
        let reg_clone = Arc::clone(&registry);
        handles.push(thread::spawn(move || {
            let removed = reg_clone.unregister(&format!("tool_{}", i));
            assert!(removed, "tool_{} should be removed", i);
        }));
    }

    // Concurrent lookups for non-removed tools
    for i in 10..20 {
        let reg_clone = Arc::clone(&registry);
        handles.push(thread::spawn(move || {
            let tool = reg_clone.get(&format!("tool_{}", i));
            assert!(tool.is_some(), "tool_{} should still exist", i);
        }));
    }

    for handle in handles {
        handle.join().expect("thread should not panic");
    }

    // Verify final state
    let names = registry.names();
    for i in 0..10 {
        assert!(
            !names.contains(&format!("tool_{}", i)),
            "tool_{} should be gone",
            i
        );
    }
    for i in 10..20 {
        assert!(
            names.contains(&format!("tool_{}", i)),
            "tool_{} should remain",
            i
        );
    }
}

#[test]
fn test_tool_registry_definitions_concurrent() {
    let registry = Arc::new(ToolRegistry::new());

    for i in 0..10 {
        registry.register(TestTool::new(&format!("def_tool_{}", i)));
    }

    let mut handles = Vec::new();
    for _ in 0..8 {
        let reg_clone = Arc::clone(&registry);
        handles.push(thread::spawn(move || {
            let defs = reg_clone.definitions();
            assert!(defs.len() >= 10);
        }));
    }

    for handle in handles {
        handle.join().expect("thread should not panic");
    }
}

// ═══════════════════════════════════════════════════════════════════
// AgentState Thread Safety
// ═══════════════════════════════════════════════════════════════════

#[test]
fn test_agent_state_iteration_concurrent() {
    let shared = Arc::new(SharedState::new());

    let mut handles = Vec::new();
    for _ in 0..8 {
        let shared_clone = Arc::clone(&shared);
        handles.push(thread::spawn(move || {
            for _ in 0..100 {
                shared_clone.update(|s| {
                    s.increment_iteration();
                });
            }
        }));
    }

    for handle in handles {
        handle.join().expect("thread should not panic");
    }

    let state = shared.get_state();
    assert_eq!(state.iteration, 800, "8 threads × 100 increments = 800");
}

#[test]
fn test_agent_state_clear_and_build() {
    let shared = Arc::new(SharedState::new());

    shared.update(|s| {
        s.add_user_message("msg1".to_string());
        s.add_assistant_message("resp1".to_string());
        s.add_user_message("msg2".to_string());
    });

    assert_eq!(shared.get_state().messages.len(), 3);

    shared.reset();
    assert_eq!(shared.get_state().messages.len(), 0);

    shared.update(|s| {
        s.add_user_message("after reset".to_string());
    });
    assert_eq!(shared.get_state().messages.len(), 1);
}

#[test]
fn test_agent_state_is_complete_concurrent() {
    let shared = Arc::new(SharedState::new());

    assert!(!shared.get_state().is_complete());

    shared.update(|s| {
        s.set_stop_reason(oxicode_agent::types::StopReason::Stop);
    });

    assert!(shared.get_state().is_complete());

    // Reset should clear it
    shared.reset();
    assert!(!shared.get_state().is_complete());
}