use blyte_agent::fs::LocalFs;
use blyte_agent::shell::LocalShell;
use blyte_agent::tools::{distil, execute, specs, OUTPUT_LINE_BUDGET};
use serde_json::json;
fn ws() -> tempfile::TempDir {
tempfile::tempdir().unwrap()
}
#[test]
fn no_tool_offers_a_background_mode() {
let specs = specs();
for t in &specs {
assert!(
!t.name.starts_with("job_"),
"job control tool present: {}",
t.name
);
let props = t.parameters.get("properties").and_then(|p| p.as_object());
for key in props.into_iter().flatten().map(|(k, _)| k.as_str()) {
assert!(
!matches!(key, "run_in_background" | "background" | "async" | "detach"),
"tool `{}` offers a background parameter `{key}`",
t.name
);
}
}
assert!(
specs.iter().any(|t| t.name == "bash"),
"bash must exist to be constrained"
);
}
#[test]
fn bash_blocks_until_the_command_finishes() {
let d = ws();
let r = execute(
d.path(),
&LocalShell,
&LocalFs,
"bash",
&json!({"command": "sleep 1; echo done"}),
);
assert!(
r.content.contains("done"),
"must return the output, not a job handle: {r:?}"
);
assert!(!r.is_error);
}
#[test]
fn bash_always_states_the_exit_code() {
let d = ws();
let r = execute(
d.path(),
&LocalShell,
&LocalFs,
"bash",
&json!({"command": "exit 3"}),
);
assert!(r.content.starts_with("exit 3"), "got {:?}", r.content);
assert!(r.is_error, "a failing command must be marked an error");
}
#[test]
fn a_path_escaping_the_workspace_is_refused() {
let d = ws();
for bad in ["../../../etc/passwd", "/etc/passwd"] {
let r = execute(
d.path(),
&LocalShell,
&LocalFs,
"read",
&json!({"path": bad}),
);
assert!(
r.is_error && r.content.contains("escapes the workspace"),
"{bad} must be refused, got {r:?}"
);
}
}
#[test]
fn a_new_file_outside_the_workspace_is_refused_even_though_it_does_not_exist_yet() {
let d = ws();
let r = execute(
d.path(),
&LocalShell,
&LocalFs,
"write",
&json!({"path": "../escaped.txt", "content": "x"}),
);
assert!(r.is_error, "writing outside the workspace must fail: {r:?}");
}
#[test]
fn edit_refuses_an_ambiguous_match_instead_of_guessing() {
let d = ws();
std::fs::write(d.path().join("a.rs"), "let x = 1;\nlet x = 1;\n").unwrap();
let r = execute(
d.path(),
&LocalShell,
&LocalFs,
"edit",
&json!({"path": "a.rs", "old": "let x = 1;", "new": "let x = 2;"}),
);
assert!(
r.is_error && r.content.contains("appears 2 times"),
"got {r:?}"
);
assert_eq!(
std::fs::read_to_string(d.path().join("a.rs")).unwrap(),
"let x = 1;\nlet x = 1;\n",
"a refused edit must not modify the file"
);
}
#[test]
fn edit_says_to_read_first_when_the_target_is_absent() {
let d = ws();
std::fs::write(d.path().join("a.rs"), "fn main() {}\n").unwrap();
let r = execute(
d.path(),
&LocalShell,
&LocalFs,
"edit",
&json!({"path": "a.rs", "old": "nope", "new": "x"}),
);
assert!(
r.is_error && r.content.contains("Read it first"),
"got {r:?}"
);
}
#[test]
fn read_numbers_lines_so_edits_can_be_precise() {
let d = ws();
std::fs::write(d.path().join("a.rs"), "one\ntwo\nthree\n").unwrap();
let r = execute(
d.path(),
&LocalShell,
&LocalFs,
"read",
&json!({"path": "a.rs", "start_line": 2, "end_line": 3}),
);
assert!(r.content.contains("2\ttwo"), "got {:?}", r.content);
assert!(!r.content.contains("one"), "range must be respected");
}
#[test]
fn distil_keeps_the_tail_because_test_runners_summarise_at_the_end() {
let text: String = (1..=5000).map(|i| format!("line {i}\n")).collect();
let out = distil(&text, OUTPUT_LINE_BUDGET);
assert!(out.contains("line 1"), "head kept");
assert!(
out.contains("line 5000"),
"TAIL kept -- the summary lives here"
);
assert!(
out.contains("elided by blyte"),
"elision must be stated, not silent"
);
assert!(out.lines().count() < OUTPUT_LINE_BUDGET + 10);
}
#[test]
fn distil_leaves_short_output_untouched() {
assert_eq!(distil("a\nb\nc", OUTPUT_LINE_BUDGET), "a\nb\nc");
}
fn seeded() -> tempfile::TempDir {
let d = ws();
std::fs::create_dir_all(d.path().join("src/deep")).unwrap();
std::fs::create_dir_all(d.path().join("node_modules/junk")).unwrap();
std::fs::write(
d.path().join("src/main.rs"),
"fn main() { parse_array(); }\n",
)
.unwrap();
std::fs::write(
d.path().join("src/deep/array.rs"),
"fn parse_array() {}\n// multicolumn\n",
)
.unwrap();
std::fs::write(
d.path().join("src/notes.md"),
"parse_array is the entry point\n",
)
.unwrap();
std::fs::write(
d.path().join("node_modules/junk/array.rs"),
"fn parse_array() {}\n",
)
.unwrap();
d
}
#[test]
fn glob_finds_files_recursively() {
let d = seeded();
let r = execute(
d.path(),
&LocalShell,
&LocalFs,
"glob",
&json!({"pattern": "src/**/*.rs"}),
);
assert!(!r.is_error, "{r:?}");
assert!(r.content.contains("src/main.rs"), "got {}", r.content);
assert!(
r.content.contains("src/deep/array.rs"),
"** must recurse: {}",
r.content
);
}
#[test]
fn glob_reports_no_match_rather_than_returning_empty() {
let d = seeded();
let r = execute(
d.path(),
&LocalShell,
&LocalFs,
"glob",
&json!({"pattern": "*.nope"}),
);
assert!(!r.is_error);
assert!(r.content.contains("no files match"), "got {}", r.content);
}
#[test]
fn grep_returns_path_line_and_text() {
let d = seeded();
let r = execute(
d.path(),
&LocalShell,
&LocalFs,
"grep",
&json!({"pattern": "parse_array"}),
);
assert!(!r.is_error, "{r:?}");
assert!(
r.content.contains("src/main.rs:1:"),
"must carry path:line: {}",
r.content
);
}
#[test]
fn grep_honours_gitignore_so_node_modules_does_not_drown_the_result() {
let d = seeded();
let have_rg = std::process::Command::new("rg")
.arg("--version")
.output()
.map(|o| o.status.success())
.unwrap_or(false);
if !have_rg {
return;
}
std::fs::write(d.path().join(".gitignore"), "node_modules/\n").unwrap();
std::process::Command::new("git")
.args(["init", "-q"])
.current_dir(d.path())
.output()
.unwrap();
let r = execute(
d.path(),
&LocalShell,
&LocalFs,
"grep",
&json!({"pattern": "parse_array"}),
);
assert!(
!r.content.contains("node_modules"),
"ignored paths must stay out: {}",
r.content
);
}
#[test]
fn grep_can_be_restricted_by_glob() {
let d = seeded();
let r = execute(
d.path(),
&LocalShell,
&LocalFs,
"grep",
&json!({"pattern": "parse_array", "glob": "*.md"}),
);
assert!(r.content.contains("notes.md"), "got {}", r.content);
assert!(
!r.content.contains("main.rs"),
"glob must restrict: {}",
r.content
);
}
#[test]
fn grep_says_when_it_capped_rather_than_implying_completeness() {
let d = ws();
let many: String = (0..500).map(|i| format!("needle {i}\n")).collect();
std::fs::write(d.path().join("big.txt"), many).unwrap();
let r = execute(
d.path(),
&LocalShell,
&LocalFs,
"grep",
&json!({"pattern": "needle"}),
);
assert!(
r.content.contains("capped at"),
"a truncated search must not read as complete: {}",
&r.content[r.content.len().saturating_sub(200)..]
);
}
#[test]
fn grep_patterns_with_shell_metacharacters_are_passed_verbatim() {
let d = ws();
std::fs::write(d.path().join("a.rs"), "let x = \"a b\";\nprice $5\n").unwrap();
let r = execute(
d.path(),
&LocalShell,
&LocalFs,
"grep",
&json!({"pattern": r"price \$5"}),
);
assert!(r.content.contains("a.rs:2:"), "got {}", r.content);
}
#[test]
fn grep_outside_the_workspace_is_refused() {
let d = ws();
let r = execute(
d.path(),
&LocalShell,
&LocalFs,
"grep",
&json!({"pattern": "x", "path": "../.."}),
);
assert!(
r.is_error && r.content.contains("escapes the workspace"),
"{r:?}"
);
}
#[test]
fn the_environment_probe_finds_the_tools_that_are_actually_here() {
let d = ws();
let bins = blyte_agent::tools::available_binaries(&LocalShell, d.path()).unwrap();
assert!(
bins.iter().any(|b| b == "git"),
"git is present on any dev machine: {bins:?}"
);
assert!(!bins.iter().any(|b| b == "definitely-not-a-real-binary"));
}
#[derive(Default)]
struct FakeShell {
seen: std::sync::Mutex<Vec<String>>,
}
impl blyte_agent::shell::Shell for FakeShell {
fn exec(
&self,
command: &str,
_cwd: &std::path::Path,
_t: std::time::Duration,
) -> Result<blyte_agent::shell::Output, String> {
self.seen.lock().unwrap().push(command.to_string());
Ok(blyte_agent::shell::Output {
stdout: "ran elsewhere\n".into(),
stderr: String::new(),
exit_code: 0,
})
}
fn describe(&self) -> String {
"a fake".into()
}
}
#[test]
fn bash_goes_through_the_seam_not_the_host() {
let d = ws();
let fake = FakeShell::default();
let r = execute(
d.path(),
&fake,
&LocalFs,
"bash",
&json!({"command": "npm test"}),
);
assert!(
r.content.contains("ran elsewhere"),
"output must come from the seam: {r:?}"
);
assert_eq!(
fake.seen.lock().unwrap().as_slice(),
&["npm test".to_string()]
);
}
struct NotLocal;
impl blyte_agent::fs::Fs for NotLocal {
fn read(&self, p: &std::path::Path) -> Result<String, String> {
LocalFs.read(p)
}
fn write(&self, p: &std::path::Path, c: &str) -> Result<(), String> {
LocalFs.write(p, c)
}
fn canonicalize(&self, p: &std::path::Path) -> Result<std::path::PathBuf, String> {
LocalFs.canonicalize(p)
}
}
#[test]
fn search_tools_also_go_through_the_seam() {
let d = ws();
let fake = FakeShell::default();
execute(
d.path(),
&fake,
&NotLocal,
"glob",
&json!({"pattern": "**/*.rs"}),
);
execute(
d.path(),
&fake,
&NotLocal,
"grep",
&json!({"pattern": "needle"}),
);
let seen = fake.seen.lock().unwrap();
assert!(
seen.len() >= 2,
"both searches must reach the executor: {seen:?}"
);
assert!(seen
.iter()
.any(|c| c.contains("ls-files") || c.contains("*.rs")));
assert!(seen.iter().any(|c| c.contains("needle")));
}
#[test]
fn the_probe_reports_what_the_execution_environment_has_not_the_host() {
let d = ws();
let fake = FakeShell::default();
let bins = blyte_agent::tools::available_binaries(&fake, d.path()).unwrap();
assert!(
bins.contains(&"ran elsewhere".to_string()) || !bins.is_empty(),
"probe must be answered by the executor, got {bins:?}"
);
assert!(fake
.seen
.lock()
.unwrap()
.iter()
.any(|c| c.contains("command -v")));
}
#[test]
fn the_environment_is_probed_in_one_round_trip() {
let d = ws();
let fake = FakeShell::default();
blyte_agent::tools::available_binaries(&fake, d.path()).unwrap();
assert_eq!(
fake.seen.lock().unwrap().len(),
1,
"the whole probe must be one command, not one per binary"
);
}
#[test]
fn posix_guaranteed_utilities_are_not_advertised() {
use blyte_agent::tools::{ACCELERATORS, TOOLCHAINS};
for noise in ["sed", "awk", "find", "xargs", "grep"] {
assert!(
!ACCELERATORS.contains(&noise) && !TOOLCHAINS.contains(&noise),
"{noise} is POSIX-guaranteed and should not be advertised"
);
}
assert!(
ACCELERATORS.contains(&"rg"),
"rg changes search strategy, so it is worth stating"
);
}
#[derive(Default)]
struct FakeFs {
files: std::sync::Mutex<std::collections::HashMap<String, String>>,
}
impl blyte_agent::fs::Fs for FakeFs {
fn read(&self, path: &std::path::Path) -> Result<String, String> {
self.files
.lock()
.unwrap()
.get(&path.to_string_lossy().to_string())
.cloned()
.ok_or_else(|| format!("no such file: {}", path.display()))
}
fn write(&self, path: &std::path::Path, content: &str) -> Result<(), String> {
self.files
.lock()
.unwrap()
.insert(path.to_string_lossy().to_string(), content.to_string());
Ok(())
}
fn canonicalize(&self, path: &std::path::Path) -> Result<std::path::PathBuf, String> {
Ok(path.to_path_buf())
}
}
#[test]
fn write_lands_on_the_seam_not_the_host_disk() {
let d = ws();
let fake = FakeFs::default();
let r = execute(
d.path(),
&LocalShell,
&fake,
"write",
&json!({"path": "src/new.rs", "content": "fn x() {}"}),
);
assert!(!r.is_error, "{r:?}");
assert!(
!d.path().join("src/new.rs").exists(),
"must NOT have touched the host disk"
);
assert_eq!(
fake.files.lock().unwrap().values().next().unwrap(),
"fn x() {}"
);
}
#[test]
fn read_comes_from_the_seam() {
let d = ws();
let fake = FakeFs::default();
let p = d
.path()
.join("only-in-the-seam.rs")
.to_string_lossy()
.to_string();
fake.files
.lock()
.unwrap()
.insert(p, "fn seam() {}\n".into());
let r = execute(
d.path(),
&LocalShell,
&fake,
"read",
&json!({"path": "only-in-the-seam.rs"}),
);
assert!(
r.content.contains("fn seam()"),
"read must consult the seam: {r:?}"
);
}
#[test]
fn edit_reads_and_writes_through_the_same_seam() {
let d = ws();
let fake = FakeFs::default();
let p = d.path().join("a.rs").to_string_lossy().to_string();
fake.files
.lock()
.unwrap()
.insert(p.clone(), "let x = 1;\n".into());
let r = execute(
d.path(),
&LocalShell,
&fake,
"edit",
&json!({"path": "a.rs", "old": "let x = 1;", "new": "let x = 2;"}),
);
assert!(!r.is_error, "{r:?}");
assert_eq!(fake.files.lock().unwrap()[&p], "let x = 2;\n");
assert!(
!d.path().join("a.rs").exists(),
"the host must be untouched"
);
}
#[test]
fn the_escape_check_is_evaluated_against_the_seam() {
let d = ws();
let fake = FakeFs::default();
let r = execute(
d.path(),
&LocalShell,
&fake,
"write",
&json!({"path": "../../escaped.rs", "content": "x"}),
);
assert!(
r.is_error && r.content.contains("escapes the workspace"),
"{r:?}"
);
assert!(
fake.files.lock().unwrap().is_empty(),
"a refused write must write nothing anywhere"
);
}
#[test]
fn shell_and_fs_are_independently_composable() {
let d = ws();
let fake_shell = FakeShell::default();
std::fs::write(d.path().join("host.rs"), "on the host\n").unwrap();
let r = execute(
d.path(),
&fake_shell,
&LocalFs,
"read",
&json!({"path": "host.rs"}),
);
assert!(
r.content.contains("on the host"),
"local fs with a remote shell must work: {r:?}"
);
let c = execute(
d.path(),
&fake_shell,
&LocalFs,
"bash",
&json!({"command": "true"}),
);
assert!(
c.content.contains("ran elsewhere"),
"and the shell still goes elsewhere: {c:?}"
);
}
#[test]
fn traversal_is_refused_even_when_canonicalize_does_not_normalise() {
let d = ws();
let fake = FakeFs::default();
for escape in [
"../../escaped.rs",
"sub/../../../escaped.rs",
"./../escaped.rs",
] {
let r = execute(
d.path(),
&LocalShell,
&fake,
"write",
&json!({"path": escape, "content": "x"}),
);
assert!(r.is_error, "{escape} must be refused, got {r:?}");
}
assert!(
fake.files.lock().unwrap().is_empty(),
"no refused write may land"
);
}
#[test]
fn legitimate_dot_segments_inside_the_workspace_still_work() {
let d = ws();
std::fs::create_dir_all(d.path().join("src/a")).unwrap();
std::fs::write(d.path().join("src/b.rs"), "inside\n").unwrap();
let r = execute(
d.path(),
&LocalShell,
&LocalFs,
"read",
&json!({"path": "src/a/../b.rs"}),
);
assert!(!r.is_error && r.content.contains("inside"), "{r:?}");
}
static DISPATCH_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
struct ResetDispatch;
impl Drop for ResetDispatch {
fn drop(&mut self) {
blyte_agent::tools::set_dispatch_cmd(None);
}
}
#[test]
fn dispatch_tool_runs_stub_command_and_echoes_json() {
let _lock = DISPATCH_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let _guard = ResetDispatch;
blyte_agent::tools::set_dispatch_cmd(Some("cat".into()));
let tool_specs = specs();
assert!(tool_specs.iter().any(|t| t.name == "dispatch"));
let d = ws();
let r = execute(
d.path(),
&LocalShell,
&LocalFs,
"dispatch",
&json!({"task": "implement feature X", "gate": "cargo test", "max_seconds": 60}),
);
assert!(!r.is_error, "expected success, got {r:?}");
let v: serde_json::Value =
serde_json::from_str(&r.content).expect("stdout should be valid json");
assert_eq!(v["task"], "implement feature X");
assert_eq!(v["gate"], "cargo test");
assert_eq!(v["max_seconds"], 60);
}
#[test]
fn dispatch_tool_failing_command_gives_error_result() {
let _lock = DISPATCH_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let _guard = ResetDispatch;
blyte_agent::tools::set_dispatch_cmd(Some(
"sh -c 'echo failed to execute task >&2; exit 1'".into(),
));
let d = ws();
let r = execute(
d.path(),
&LocalShell,
&LocalFs,
"dispatch",
&json!({"task": "fail", "gate": "false"}),
);
assert!(r.is_error, "expected error, got {r:?}");
assert!(
r.content.contains("failed to execute task"),
"content was: {:?}",
r.content
);
}
#[test]
fn dispatch_tool_sets_dispatch_parent_env() {
let _lock = DISPATCH_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let _guard = ResetDispatch;
std::env::set_var("BLYTE_SESSION", "test-orch-session-123");
blyte_agent::tools::set_dispatch_cmd(Some("sh -c 'echo parent=$BLYTE_DISPATCH_PARENT'".into()));
let d = ws();
let r = execute(
d.path(),
&LocalShell,
&LocalFs,
"dispatch",
&json!({"task": "test", "gate": "true"}),
);
assert!(!r.is_error, "expected success, got {r:?}");
assert!(
r.content.contains("parent=test-orch-session-123"),
"content was: {:?}",
r.content
);
}
#[test]
fn dispatch_tool_stdin_write_failure_returns_error_outcome() {
let _lock = DISPATCH_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let _guard = ResetDispatch;
blyte_agent::tools::set_dispatch_cmd(Some("exec <&-; exit 0".into()));
let d = ws();
let large_task = "x".repeat(512 * 1024);
let r = execute(
d.path(),
&LocalShell,
&LocalFs,
"dispatch",
&json!({"task": large_task, "gate": "true"}),
);
assert!(
r.is_error,
"expected error on stdin write failure, got {r:?}"
);
assert!(
r.content.contains("stdin") && r.content.contains("write"),
"expected error message naming stdin write failure, got: {:?}",
r.content
);
}
#[test]
fn dispatch_tool_reports_the_command_failure_when_it_exits_before_reading() {
let _lock = DISPATCH_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let _guard = ResetDispatch;
blyte_agent::tools::set_dispatch_cmd(Some(
"exec <&-; echo failed to execute task >&2; exit 1".into(),
));
let d = ws();
let large_task = "x".repeat(512 * 1024);
let r = execute(
d.path(),
&LocalShell,
&LocalFs,
"dispatch",
&json!({"task": large_task, "gate": "false"}),
);
assert!(r.is_error, "expected error, got {r:?}");
assert!(
r.content.contains("failed to execute task"),
"expected command stderr in content, got: {:?}",
r.content
);
assert!(
r.content.contains("failed to write arguments to stdin"),
"expected stdin write error in content, got: {:?}",
r.content
);
}
#[cfg(unix)]
#[test]
fn dispatch_tool_reports_signal_termination_without_fabricating_exit_code() {
let _lock = DISPATCH_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let _guard = ResetDispatch;
blyte_agent::tools::set_dispatch_cmd(Some("cat >/dev/null; kill -9 $$".into()));
let d = ws();
let r = execute(
d.path(),
&LocalShell,
&LocalFs,
"dispatch",
&json!({"task": "killed", "gate": "false"}),
);
assert!(r.is_error, "expected error, got {r:?}");
assert!(
r.content.contains("without exit code") && r.content.contains("signal"),
"expected signal termination without exit code, got: {:?}",
r.content
);
assert!(
!r.content.contains("exit 1"),
"must not fabricate exit 1 for a signal-killed process, got: {:?}",
r.content
);
}
static PEER_TOOLS_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
struct ResetPeerTools;
impl Drop for ResetPeerTools {
fn drop(&mut self) {
blyte_agent::tools::set_peer_tools(None);
}
}
struct FakePeerTools {
surfaces_result: Result<String, String>,
tell_result: Result<String, String>,
tell_calls: std::sync::Mutex<Vec<(String, String)>>,
}
impl FakePeerTools {
fn ok(surfaces_text: &str, tell_text: &str) -> std::sync::Arc<Self> {
std::sync::Arc::new(Self {
surfaces_result: Ok(surfaces_text.to_string()),
tell_result: Ok(tell_text.to_string()),
tell_calls: std::sync::Mutex::new(Vec::new()),
})
}
fn tell_err(err_text: &str) -> std::sync::Arc<Self> {
std::sync::Arc::new(Self {
surfaces_result: Ok(String::new()),
tell_result: Err(err_text.to_string()),
tell_calls: std::sync::Mutex::new(Vec::new()),
})
}
}
impl blyte_agent::tools::PeerTools for FakePeerTools {
fn surfaces(&self) -> Result<String, String> {
self.surfaces_result.clone()
}
fn tell(&self, name: &str, message: &str) -> Result<String, String> {
self.tell_calls
.lock()
.unwrap()
.push((name.to_string(), message.to_string()));
self.tell_result.clone()
}
}
#[test]
fn peer_tools_are_listed_only_when_registered() {
let _lock = PEER_TOOLS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let _guard = ResetPeerTools;
blyte_agent::tools::set_peer_tools(None);
let before = specs();
assert!(!before.iter().any(|t| t.name == "surfaces"));
assert!(!before.iter().any(|t| t.name == "tell"));
blyte_agent::tools::set_peer_tools(Some(FakePeerTools::ok("ok", "delivered")));
let during = specs();
let surfaces_spec = during.iter().find(|t| t.name == "surfaces").unwrap();
assert_eq!(
surfaces_spec.description,
"List the surfaces running on this machine: name, repository, branch and what each is doing."
);
assert_eq!(
surfaces_spec.parameters["properties"]
.as_object()
.unwrap()
.len(),
0
);
let tell_spec = during.iter().find(|t| t.name == "tell").unwrap();
assert_eq!(
tell_spec.description,
"Send a message to another running surface by name. Its model reads it between turns as a message from this surface, not from its user. Returns delivered or held."
);
let tell_props = tell_spec.parameters["properties"].as_object().unwrap();
assert_eq!(tell_props["name"]["type"], "string");
assert_eq!(tell_props["message"]["type"], "string");
assert_eq!(tell_spec.parameters["required"], json!(["name", "message"]));
blyte_agent::tools::set_peer_tools(None);
let after = specs();
assert!(!after.iter().any(|t| t.name == "surfaces"));
assert!(!after.iter().any(|t| t.name == "tell"));
}
#[test]
fn surfaces_tool_returns_the_registered_text() {
let _lock = PEER_TOOLS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let _guard = ResetPeerTools;
let fake = FakePeerTools::ok("api-2 repo/api main idle", "delivered");
blyte_agent::tools::set_peer_tools(Some(fake));
let d = ws();
let r = execute(d.path(), &LocalShell, &LocalFs, "surfaces", &json!({}));
assert!(!r.is_error, "expected ok, got {r:?}");
assert_eq!(r.content, "api-2 repo/api main idle");
}
#[test]
fn tell_tool_passes_name_and_message() {
let _lock = PEER_TOOLS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let _guard = ResetPeerTools;
let fake = FakePeerTools::ok("", "delivered");
blyte_agent::tools::set_peer_tools(Some(fake.clone()));
let d = ws();
let r = execute(
d.path(),
&LocalShell,
&LocalFs,
"tell",
&json!({"name": "api-2", "message": "please rebase"}),
);
assert!(!r.is_error, "expected ok, got {r:?}");
assert_eq!(r.content, "delivered");
assert_eq!(
fake.tell_calls.lock().unwrap().as_slice(),
&[("api-2".to_string(), "please rebase".to_string())]
);
}
#[test]
fn tell_tool_reports_the_error_text() {
let _lock = PEER_TOOLS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let _guard = ResetPeerTools;
let fake = FakePeerTools::tell_err("no running surface named ghost");
blyte_agent::tools::set_peer_tools(Some(fake));
let d = ws();
let r = execute(
d.path(),
&LocalShell,
&LocalFs,
"tell",
&json!({"name": "ghost", "message": "hello"}),
);
assert!(r.is_error, "expected error, got {r:?}");
assert_eq!(r.content, "no running surface named ghost");
}
#[test]
fn tell_tool_refuses_blank_arguments() {
let _lock = PEER_TOOLS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let _guard = ResetPeerTools;
let fake = FakePeerTools::ok("", "delivered");
blyte_agent::tools::set_peer_tools(Some(fake.clone()));
let d = ws();
for bad in [
json!({}),
json!({"name": "api-2"}),
json!({"message": "hello"}),
json!({"name": "", "message": "hello"}),
json!({"name": " ", "message": "hello"}),
json!({"name": "api-2", "message": ""}),
json!({"name": "api-2", "message": " \t\n "}),
json!({"name": 123, "message": "hello"}),
json!({"name": "api-2", "message": true}),
] {
let r = execute(d.path(), &LocalShell, &LocalFs, "tell", &bad);
assert!(r.is_error, "expected error for {bad}, got {r:?}");
assert_eq!(
r.content, "tell needs a name and a message",
"unexpected error for {bad}"
);
}
assert!(
fake.tell_calls.lock().unwrap().is_empty(),
"stand-in must not be called for invalid arguments"
);
}
#[test]
fn peer_tools_unregistered_say_so() {
let _lock = PEER_TOOLS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let _guard = ResetPeerTools;
blyte_agent::tools::set_peer_tools(None);
let d = ws();
let s = execute(d.path(), &LocalShell, &LocalFs, "surfaces", &json!({}));
assert!(s.is_error, "expected error, got {s:?}");
assert_eq!(s.content, "the surfaces tool is not available here");
let t = execute(
d.path(),
&LocalShell,
&LocalFs,
"tell",
&json!({"name": "api-2", "message": "hello"}),
);
assert!(t.is_error, "expected error, got {t:?}");
assert_eq!(t.content, "the tell tool is not available here");
}