Skip to content

Craft Anything: understand how any software works, and craft your own.

Rust

Doctor says a local AI server is reachable only when it answers with its models (#45)

BFlat9fc20b129d67
diff --git a/crates/ai/src/detect.rs b/crates/ai/src/detect.rs
index 0ed37235..7c823e12 100644
--- a/crates/ai/src/detect.rs
+++ b/crates/ai/src/detect.rs
@@ -175,31 +175,10 @@ mod tests {
assert!(t.elapsed() < Duration::from_secs(1));
}
- /// A stand-in server on a free port that answers every request with `status` and `body`.
- fn serve(status: &'static str, body: &'static str) -> String {
- use std::io::{Read as _, Write as _};
- let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
- let base = format!("http://{}/v1", l.local_addr().unwrap());
- std::thread::spawn(move || {
- for mut s in l.incoming().flatten() {
- let (mut got, mut buf) = (Vec::new(), [0u8; 4096]);
- while !got.windows(4).any(|w| w == b"\r\n\r\n") {
- match s.read(&mut buf) {
- Ok(0) | Err(_) => break,
- Ok(n) => got.extend_from_slice(&buf[..n]),
- }
- }
- if !got.is_empty() {
- let _ = write!(s, "HTTP/1.1 {status}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", body.len());
- }
- }
- });
- base
- }
-
/// #30: another program on a model server's port isn't offered as one.
#[test]
fn only_a_server_that_lists_models_is_offered() {
+ use crate::tests::serve;
assert!(probe_local("llama.cpp server", &serve("404 Not Found", "404 page not found")).is_none(), "a Go web server's 404");
assert!(probe_local("llama.cpp server", &serve("200 OK", "<html><body>Admin</body></html>")).is_none(), "a web page");
let found = probe_local("llama.cpp server", &serve("200 OK", r#"{"object":"list","data":[{"id":"qwen3-8b"}]}"#)).unwrap();
diff --git a/crates/ai/src/lib.rs b/crates/ai/src/lib.rs
index bf2cadd8..eec439af 100644
--- a/crates/ai/src/lib.rs
+++ b/crates/ai/src/lib.rs
@@ -664,7 +664,12 @@ fn reach(e: &BackendEntry, key: Option<String>) -> Result<u64, String> {
}
BackendKind::OpenaiCompatible => {
let b = base.unwrap_or("http://127.0.0.1:11434/v1");
- if detect::port_open(b, Duration::from_millis(500)) { Ok(()) } else { Err(format!("nothing is listening at {b}")) }
+ if !detect::port_open(b, Duration::from_millis(500)) {
+ Err(format!("nothing is listening at {b}"))
+ } else {
+ // An open port isn't a model server: another program may hold it (#37).
+ openai::OpenAi::compatible(&e.config.name, b, key, &e.config.model).list_models(t).map(|_| ()).map_err(|x| x.message)
+ }
}
BackendKind::AgentCli => {
let program = e.options.command.clone().unwrap_or_else(|| cli_agents::program_for(&e.config.model));
diff --git a/crates/ai/src/tests.rs b/crates/ai/src/tests.rs
index 77797f95..49444f23 100644
--- a/crates/ai/src/tests.rs
+++ b/crates/ai/src/tests.rs
@@ -62,6 +62,40 @@ fn mock(responses: Vec<(u16, &'static str, String)>) -> (String, Arc<Mutex<Vec<S
(url, seen)
}
+/// A stand-in server on a free port that answers every request (and any number of them, unlike
+/// [`mock`]) with `status` and `body`; its `/v1` address.
+pub(crate) fn serve(status: &'static str, body: &'static str) -> String {
+ let l = TcpListener::bind("127.0.0.1:0").unwrap();
+ let base = format!("http://{}/v1", l.local_addr().unwrap());
+ std::thread::spawn(move || {
+ for mut s in l.incoming().flatten() {
+ let (mut got, mut buf) = (Vec::new(), [0u8; 4096]);
+ while !got.windows(4).any(|w| w == b"\r\n\r\n") {
+ match s.read(&mut buf) {
+ Ok(0) | Err(_) => break,
+ Ok(n) => got.extend_from_slice(&buf[..n]),
+ }
+ }
+ if !got.is_empty() {
+ let _ = write!(s, "HTTP/1.1 {status}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", body.len());
+ }
+ }
+ });
+ base
+}
+
+/// #37: doctor asks a local server for its models instead of trusting an open port.
+#[test]
+fn a_local_server_is_reachable_only_when_it_lists_models() {
+ let (h, _d) = hub();
+ add(&h, "Web page", BackendKind::OpenaiCompatible, &serve("404 Not Found", "404 page not found"), None);
+ add(&h, "Real", BackendKind::OpenaiCompatible, &serve("200 OK", r#"{"data":[{"id":"qwen3-8b"}]}"#), None);
+ let reach = h.check_reachability();
+ let of = |n: &str| reach.iter().find(|(name, _)| name == n).map(|(_, r)| r.clone()).unwrap();
+ assert!(of("Web page").is_err_and(|e| e.contains("404 page not found")), "{reach:?}");
+ assert!(of("Real").is_ok(), "{reach:?}");
+}
+
fn sse(events: &[Value]) -> String {
events.iter().map(|e| format!("event: {}\r\ndata: {}\r\n\r\n", e["type"].as_str().unwrap_or("message"), e)).collect()
}