use super::*;
use crate::message::Message;
use crate::session::SessionStore;
use crate::tools::{Approver, ToolRegistry};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
fn store() -> (SessionStore, std::path::PathBuf) {
let dir = tempfile::tempdir().unwrap();
let path = dir.keep();
(SessionStore::new(path.join("sessions")), path)
}
fn tool_call(id: &str, tool: &str) -> crate::message::ToolCall {
crate::message::ToolCall {
id: id.to_string(),
kind: "function".to_string(),
function: crate::message::FunctionCall {
name: tool.to_string(),
arguments: "{}".to_string(),
},
}
}
fn call(id: &str, tool: &str) -> Pending {
Pending::new(
id,
tool,
format!("{tool} the thing"),
format!(r#"{{"path":"{tool}.txt"}}"#),
)
}
#[test]
fn a_deferral_is_stored_as_no_answer_at_all() {
assert_eq!(Decision::Allow.store().as_deref(), Some("allow"));
assert_eq!(
Decision::Deny("because".into()).store().as_deref(),
Some("deny:because")
);
assert_eq!(Decision::Defer.store(), None);
assert_eq!(Decision::parse("allow"), Decision::Allow);
assert_eq!(
Decision::parse("deny:no, that path is outside the workspace"),
Decision::Deny("no, that path is outside the workspace".into())
);
}
#[test]
fn an_answer_this_build_does_not_understand_is_a_denial() {
for stored in ["", "Allow", "allow ", "yes", "approve", "1", "ok"] {
match Decision::parse(stored) {
Decision::Deny(reason) => assert!(
reason.contains(stored.trim()) || reason.contains("does not understand"),
"{stored:?} denied with a reason that names it: {reason}"
),
other => panic!("{stored:?} must not read as {other:?}"),
}
}
assert_eq!(Decision::parse("allow"), Decision::Allow);
assert_eq!(Decision::parse("deny:"), Decision::Deny(String::new()));
}
#[test]
fn call_number_zero_is_refused_rather_than_answered_with_the_first_call() {
let (store, _dir) = store();
store.append("s1", &Message::user("do one thing")).unwrap();
let seq = store
.append_seq(
"s1",
&Message::assistant_tool_calls(None, vec![tool_call("c1", "write_file")]),
)
.unwrap();
record(&store, "s1", seq, &[call("c1", "write_file")]).unwrap();
let err = answer(&store, "s1", 0, &Decision::Allow).expect_err("0 is not a call");
assert!(err.to_string().contains("start at 1"), "{err}");
assert!(
waiting(&store, "s1").unwrap()[0].is_waiting(),
"nothing was answered by the refusal"
);
answer(&store, "s1", 1, &Decision::Allow).unwrap();
assert!(
waiting(&store, "s1").unwrap().is_empty(),
"the answer landed and nothing keeps waiting"
);
assert_eq!(
store.pending_calls("s1").unwrap()[0]
.decision
.as_ref()
.map(|d| d.store()),
Some(Some("allow".into())),
"the row is answered, not deleted"
);
}
#[test]
fn recorded_calls_wait_in_the_order_the_model_made_them() {
let (store, _dir) = store();
store
.append("s1", &Message::user("touch two files"))
.unwrap();
let seq = store
.append_seq(
"s1",
&Message::assistant_tool_calls(
None,
vec![tool_call("c1", "write_file"), tool_call("c2", "patch")],
),
)
.unwrap();
record(
&store,
"s1",
seq,
&[call("c1", "write_file"), call("c2", "patch")],
)
.unwrap();
let waiting = waiting(&store, "s1").unwrap();
assert_eq!(waiting.len(), 2);
assert_eq!(waiting[0].call.tool, "write_file");
assert_eq!(waiting[1].call.tool, "patch");
assert!(waiting.iter().all(PendingCall::is_waiting));
}
#[test]
fn an_answer_lands_on_the_call_it_was_meant_for_and_the_others_keep_waiting() {
let (store, _dir) = store();
store.append("s1", &Message::user("do two things")).unwrap();
let seq = store
.append_seq(
"s1",
&Message::assistant_tool_calls(
None,
vec![tool_call("c1", "write_file"), tool_call("c2", "shell")],
),
)
.unwrap();
record(
&store,
"s1",
seq,
&[call("c1", "write_file"), call("c2", "shell")],
)
.unwrap();
answer(&store, "s1", 2, &Decision::Allow).unwrap();
let waiting = waiting(&store, "s1").unwrap();
assert_eq!(waiting.len(), 1);
assert_eq!(waiting[0].call.call_id, "c1");
assert_eq!(
decision_for(&store, "s1", "c2").unwrap(),
Some(Decision::Allow),
"the answer has to be findable by the call it belongs to"
);
assert_eq!(decision_for(&store, "s1", "c1").unwrap(), None);
}
#[test]
fn an_index_nobody_answered_is_refused_rather_than_ignored() {
let (store, _dir) = store();
store.append("s1", &Message::user("one thing")).unwrap();
let seq = store
.append_seq(
"s1",
&Message::assistant_tool_calls(None, vec![tool_call("c1", "shell")]),
)
.unwrap();
record(&store, "s1", seq, &[call("c1", "shell")]).unwrap();
let e = answer(&store, "s1", 4, &Decision::Allow).expect_err("there is no fourth waiting call");
let text = e.to_string();
assert!(
text.contains("no waiting call 4") && text.contains("1 waiting"),
"the error has to say what is actually waiting: {text}"
);
assert_eq!(waiting(&store, "s1").unwrap().len(), 1);
}
#[test]
fn recording_the_same_calls_again_does_not_erase_a_decision_that_arrived() {
let (store, _dir) = store();
store.append("s1", &Message::user("write")).unwrap();
let seq = store
.append_seq(
"s1",
&Message::assistant_tool_calls(None, vec![tool_call("c1", "shell")]),
)
.unwrap();
record(&store, "s1", seq, &[call("c1", "shell")]).unwrap();
answer_all(&store, "s1", &Decision::Deny("not that program".into())).unwrap();
record(&store, "s1", seq, &[call("c1", "shell")]).unwrap();
assert_eq!(
decision_for(&store, "s1", "c1").unwrap(),
Some(Decision::Deny("not that program".into()))
);
assert!(waiting(&store, "s1").unwrap().is_empty());
}
#[test]
fn answering_everything_reports_how_many_it_answered() {
let (store, _dir) = store();
store.append("s1", &Message::user("three calls")).unwrap();
let seq = store
.append_seq(
"s1",
&Message::assistant_tool_calls(
None,
vec![
tool_call("a", "write_file"),
tool_call("b", "patch"),
tool_call("c", "shell"),
],
),
)
.unwrap();
record(
&store,
"s1",
seq,
&[
call("a", "write_file"),
call("b", "patch"),
call("c", "shell"),
],
)
.unwrap();
assert_eq!(answer_all(&store, "s1", &Decision::Allow).unwrap(), 3);
assert_eq!(answer_all(&store, "s1", &Decision::Allow).unwrap(), 0);
assert_eq!(store.clear_pending("s1").unwrap(), 3);
assert!(store.pending_calls("s1").unwrap().is_empty());
}
#[tokio::test]
async fn a_deferred_gate_runs_nothing_and_reports_that_nothing_was_answered() {
struct Deferring(Arc<AtomicUsize>);
#[async_trait::async_trait]
impl Approver for Deferring {
async fn decide(&self, _: &crate::approvals::Pending) -> Decision {
self.0.fetch_add(1, Ordering::SeqCst);
Decision::Defer
}
}
struct Ran(Arc<AtomicUsize>);
#[async_trait::async_trait]
impl crate::tools::Tool for Ran {
fn name(&self) -> &str {
"side_effect"
}
fn description(&self) -> &str {
"records that it ran"
}
fn parameters(&self) -> serde_json::Value {
serde_json::json!({"type": "object", "properties": {}})
}
async fn call(
&self,
_: serde_json::Value,
) -> std::result::Result<String, crate::tools::ToolError> {
self.0.fetch_add(1, Ordering::SeqCst);
Ok("ran".into())
}
}
let asked = Arc::new(AtomicUsize::new(0));
let ran = Arc::new(AtomicUsize::new(0));
let mut registry = ToolRegistry::new(4096);
registry.register(Arc::new(Ran(Arc::clone(&ran))), crate::config::Policy::Ask);
let outcome = registry
.dispatch("side_effect", "{}", &Deferring(Arc::clone(&asked)))
.await;
assert_eq!(asked.load(Ordering::SeqCst), 1, "the gate was asked");
assert_eq!(ran.load(Ordering::SeqCst), 0, "and nothing ran");
assert!(outcome.deferred, "the loop needs to know to stop");
assert!(outcome.is_error, "not running is not success");
assert!(!outcome.malformed, "a deferral is not a malformed call");
}