mermaid_cli/ollama/server.rs
1//! Local Ollama server lifecycle — detect a dead loopback server and start it.
2//!
3//! The product rule: the user should never have to leave mermaid to run
4//! `ollama serve`. When a request to a *local* Ollama URL is refused, we
5//! locate the binary, start `ollama serve` detached (it outlives mermaid and
6//! ignores the TUI's Ctrl+C), wait for the URL to become healthy, and let the
7//! caller retry. Remote URLs are never touched — you can't start a server on
8//! someone else's machine.
9//!
10//! Only *intent* paths auto-start (chat, model listing the user asked for,
11//! startup preflight). Diagnostics (`mermaid status` / `doctor`) observe
12//! without healing — see the `autostart` flag their `BackendConfig`s set.
13//! Runtime kill-switch: `MERMAID_OLLAMA_AUTOSTART=0` disables autostart
14//! process-wide (containers/CI where spawning a GPU server is unwanted);
15//! unit-test builds are hard-disabled so no test can ever spawn a real
16//! server through a default-config adapter.
17//!
18//! Concurrency: attempts are serialized process-wide behind a tokio `Mutex`,
19//! and a failed attempt is remembered for a short cooldown so concurrent
20//! callers (chat + model list on a cold boot) can't spawn-storm. A marker is
21//! armed at spawn time too, so a caller cancelled mid-wait (Esc during a
22//! turn) can't let the next caller double-spawn against a still-booting
23//! child. Holding the lock across awaits is deliberate; a cancelled caller
24//! drops its future, releases the lock, and leaves the spawned server
25//! running — the server is a system resource, not turn-scoped work.
26
27use std::path::PathBuf;
28use std::process::Stdio;
29use std::time::{Duration, Instant};
30
31use crate::utils::classify_host;
32
33/// How long a failed start attempt suppresses new attempts. Long enough that
34/// the retry storm of a single turn (chat + probes) collapses into one
35/// attempt, short enough that "I just installed Ollama, try again" works.
36const COOLDOWN: Duration = Duration::from_secs(15);
37/// How long a freshly spawned `ollama serve` gets to become reachable.
38/// Cold start (GPU discovery included) is typically 1–5s.
39const STARTUP_DEADLINE: Duration = Duration::from_secs(15);
40const POLL_INTERVAL: Duration = Duration::from_millis(300);
41
42/// Why autostart couldn't produce a healthy server.
43#[derive(Debug, Clone)]
44pub enum AutostartError {
45 /// The URL isn't loopback — autostart doesn't apply. Callers should
46 /// surface their original connection error untouched.
47 NotLocal,
48 /// Autostart is switched off for this process (`MERMAID_OLLAMA_AUTOSTART=0`
49 /// or a unit-test build). Same pass-through contract as `NotLocal`.
50 Disabled,
51 /// No `ollama` binary on PATH or in the platform's default install
52 /// locations.
53 NotInstalled,
54 /// A start was attempted (or recently attempted) but the URL never became
55 /// reachable; carries the specific failure.
56 Unhealthy(String),
57}
58
59impl AutostartError {
60 /// Human hint to append to the caller's connection error, or `None` when
61 /// the error should pass through untouched (`NotLocal` / `Disabled`).
62 pub fn hint(&self) -> Option<String> {
63 match self {
64 AutostartError::NotLocal | AutostartError::Disabled => None,
65 AutostartError::NotInstalled => Some(
66 "Ollama doesn't appear to be installed (not on PATH or in the default \
67 install locations) — install it from https://ollama.com/download"
68 .to_string(),
69 ),
70 AutostartError::Unhealthy(detail) => Some(format!("auto-start failed: {detail}")),
71 }
72 }
73}
74
75/// Serialized attempt state: the last failed attempt and its error, kept for
76/// [`COOLDOWN`] so repeated connection failures don't re-spawn in a loop.
77struct AttemptState {
78 last_failure: Option<(Instant, AutostartError)>,
79}
80
81/// Process-wide single-flight + cooldown. Deliberately NOT keyed by URL:
82/// every Ollama adapter in this process derives its URL from the single
83/// `config.ollama.host:port`, so there is exactly one authority to guard. If
84/// mermaid ever grows multi-endpoint Ollama support, key this by authority.
85static STATE: std::sync::LazyLock<tokio::sync::Mutex<AttemptState>> =
86 std::sync::LazyLock::new(|| tokio::sync::Mutex::new(AttemptState { last_failure: None }));
87
88/// Runtime kill-switch (see module docs). `cfg!(test)` hard-disables in unit
89/// tests so a default-config adapter (`ollama_autostart: true` pointing at
90/// localhost) can never start a real server on a contributor machine.
91fn autostart_disabled() -> bool {
92 cfg!(test) || std::env::var_os("MERMAID_OLLAMA_AUTOSTART").is_some_and(|v| v == "0")
93}
94
95/// The single user-visible line surfaced at the moment a start is actually
96/// attempted. Owned here (next to the spawn) so every trigger path — TUI
97/// chat, headless `mermaid run`, CLI model list — shows identical wording,
98/// and so it can say the part users can't otherwise discover: the server is
99/// detached and deliberately outlives mermaid.
100pub const STARTING_NOTICE: &str =
101 "Starting the local Ollama server (it stays running after mermaid exits)…";
102
103/// Make sure a *local* Ollama server is listening at `base_url`, starting
104/// `ollama serve` if needed. `Ok(())` means the URL answered a health probe
105/// (whether it was already up or we just started it) and a retry is
106/// worthwhile.
107///
108/// `notify` is invoked with [`STARTING_NOTICE`] exactly once, at the moment
109/// a spawn is committed to — never for `NotLocal`/`Disabled`, never when the
110/// probe finds the server already healthy, never when the binary is missing.
111/// Callers route it to their user-visible surface (stream status line,
112/// stderr); the up-to-15s wait behind a generic spinner, the invisible
113/// detached process, and file-only tracing are otherwise all silent.
114pub async fn ensure_running(
115 base_url: &str,
116 notify: Option<&(dyn Fn(&str) + Sync)>,
117) -> Result<(), AutostartError> {
118 let authority = authority_of(base_url).to_string();
119 if !classify_host(host_of(&authority)).is_loopback() {
120 return Err(AutostartError::NotLocal);
121 }
122 if autostart_disabled() {
123 return Err(AutostartError::Disabled);
124 }
125 let Ok(client) = reqwest::Client::builder()
126 .timeout(Duration::from_secs(1))
127 .build()
128 else {
129 return Err(AutostartError::Unhealthy(
130 "could not build a health-probe HTTP client".to_string(),
131 ));
132 };
133
134 let mut state = STATE.lock().await;
135 // Probe FIRST, cooldown second: another caller may have revived the
136 // server while we waited for the lock, and a server the user started by
137 // hand must be picked up instantly even inside the cooldown window.
138 if healthy(&client, base_url).await {
139 state.last_failure = None;
140 return Ok(());
141 }
142 if let Some((at, err)) = &state.last_failure
143 && at.elapsed() < COOLDOWN
144 {
145 return Err(err.clone());
146 }
147
148 let outcome = start_and_wait(&mut state, &client, base_url, &authority, notify).await;
149 state.last_failure = match &outcome {
150 Ok(()) => None,
151 Err(e) => Some((Instant::now(), e.clone())),
152 };
153 outcome
154}
155
156/// Locate the binary, spawn `ollama serve` detached, and poll `base_url`
157/// until it answers or the deadline passes.
158async fn start_and_wait(
159 state: &mut AttemptState,
160 client: &reqwest::Client,
161 base_url: &str,
162 authority: &str,
163 notify: Option<&(dyn Fn(&str) + Sync)>,
164) -> Result<(), AutostartError> {
165 let Some(binary) = find_binary() else {
166 return Err(AutostartError::NotInstalled);
167 };
168 // The spawn is committed — this is the one moment the user hears about
169 // it (tracing below lands in the log file, invisible in normal use).
170 if let Some(notify) = notify {
171 notify(STARTING_NOTICE);
172 }
173 tracing::info!(
174 binary = %binary.display(),
175 authority,
176 "ollama is not running — starting `ollama serve`"
177 );
178 let mut child = spawn_serve(&binary, authority).map_err(|e| {
179 AutostartError::Unhealthy(format!(
180 "could not launch `{} serve`: {e}",
181 binary.display()
182 ))
183 })?;
184 // Arm the cooldown NOW, not only on failure: if our caller is cancelled
185 // mid-wait (future dropped, lock released), the next caller must see a
186 // recent attempt and wait out the boot instead of double-spawning a
187 // second `serve` that just loses the port bind. The health-probe-first
188 // order above still picks the booted server up instantly.
189 state.last_failure = Some((
190 Instant::now(),
191 AutostartError::Unhealthy(
192 "`ollama serve` was started moments ago and may still be coming up — retry shortly"
193 .to_string(),
194 ),
195 ));
196
197 let deadline = Instant::now() + STARTUP_DEADLINE;
198 loop {
199 if healthy(client, base_url).await {
200 tracing::info!(%base_url, "ollama serve is up");
201 return Ok(());
202 }
203 // A dead child means it will never become healthy — report the exit
204 // instead of polling out the full deadline (also reaps the process,
205 // so no zombie lingers on unix).
206 if let Ok(Some(status)) = child.try_wait() {
207 return Err(AutostartError::Unhealthy(format!(
208 "`ollama serve` exited immediately ({status}) — is another server \
209 holding the port, or is OLLAMA_HOST misconfigured?"
210 )));
211 }
212 if Instant::now() >= deadline {
213 return Err(AutostartError::Unhealthy(format!(
214 "started `ollama serve` but {base_url} was not reachable within {}s",
215 STARTUP_DEADLINE.as_secs()
216 )));
217 }
218 tokio::time::sleep(POLL_INTERVAL).await;
219 }
220}
221
222/// One cheap liveness probe: `GET /api/version` with the client's short
223/// timeout.
224async fn healthy(client: &reqwest::Client, base_url: &str) -> bool {
225 let url = format!("{}/api/version", base_url);
226 matches!(client.get(&url).send().await, Ok(r) if r.status().is_success())
227}
228
229/// Spawn `ollama serve` detached: null stdio, its own process group (so the
230/// TUI's Ctrl+C doesn't kill it), no console on Windows. The server
231/// deliberately outlives mermaid — it's a shared system service, and killing
232/// it on exit would break other Ollama clients.
233fn spawn_serve(binary: &std::path::Path, authority: &str) -> std::io::Result<std::process::Child> {
234 let mut cmd = std::process::Command::new(binary);
235 cmd.arg("serve")
236 // Bind exactly where mermaid expects the server. An inherited
237 // OLLAMA_HOST pointing somewhere else (e.g. 0.0.0.0 for LAN
238 // exposure) would start a server we then can't reach at `base_url`;
239 // users who want a custom bind manage the server themselves and can
240 // set `auto_start = false`.
241 .env("OLLAMA_HOST", authority)
242 .stdin(Stdio::null())
243 .stdout(Stdio::null())
244 .stderr(Stdio::null());
245 #[cfg(unix)]
246 {
247 use std::os::unix::process::CommandExt;
248 cmd.process_group(0);
249 }
250 #[cfg(windows)]
251 {
252 use std::os::windows::process::CommandExt;
253 cmd.creation_flags(crate::utils::DETACHED_PROCESS | crate::utils::CREATE_NEW_PROCESS_GROUP);
254 }
255 cmd.spawn()
256}
257
258/// `ollama` from PATH, falling back to the platform installer's default
259/// locations (PATH edits don't reach already-running shells, and the macOS
260/// app bundle never touches PATH). Also the definition of "installed" used
261/// by `detector::is_installed`, so the startup preflight and the autostart
262/// can never disagree about whether Ollama exists.
263pub(crate) fn find_binary() -> Option<PathBuf> {
264 if let Ok(path) = which::which("ollama") {
265 return Some(path);
266 }
267 known_install_paths().into_iter().find(|p| p.is_file())
268}
269
270#[cfg(target_os = "windows")]
271fn known_install_paths() -> Vec<PathBuf> {
272 let mut paths = Vec::new();
273 if let Some(base) = std::env::var_os("LOCALAPPDATA") {
274 paths.push(
275 PathBuf::from(base)
276 .join("Programs")
277 .join("Ollama")
278 .join("ollama.exe"),
279 );
280 }
281 if let Some(base) = std::env::var_os("ProgramFiles") {
282 paths.push(PathBuf::from(base).join("Ollama").join("ollama.exe"));
283 }
284 paths
285}
286
287#[cfg(target_os = "macos")]
288fn known_install_paths() -> Vec<PathBuf> {
289 vec![
290 PathBuf::from("/opt/homebrew/bin/ollama"),
291 PathBuf::from("/usr/local/bin/ollama"),
292 PathBuf::from("/Applications/Ollama.app/Contents/Resources/ollama"),
293 ]
294}
295
296#[cfg(all(unix, not(target_os = "macos")))]
297fn known_install_paths() -> Vec<PathBuf> {
298 vec![
299 PathBuf::from("/usr/local/bin/ollama"),
300 PathBuf::from("/usr/bin/ollama"),
301 ]
302}
303
304/// `http://localhost:11434` → `localhost:11434` (scheme and any path/query
305/// stripped). The adapter's `normalize_url` guarantees a scheme is present,
306/// but parse defensively.
307fn authority_of(base_url: &str) -> &str {
308 let rest = base_url
309 .split_once("://")
310 .map(|(_, rest)| rest)
311 .unwrap_or(base_url);
312 rest.split(['/', '?', '#']).next().unwrap_or(rest)
313}
314
315/// Host part of an authority: `localhost:11434` → `localhost`,
316/// `[::1]:11434` → `[::1]` (brackets kept; `classify_host` strips them).
317/// Note: whether `ollama serve` itself accepts a bracketed IPv6 OLLAMA_HOST
318/// is unverified — IPv6-loopback autostart is best-effort.
319fn host_of(authority: &str) -> &str {
320 if let Some(end) = authority.rfind(']') {
321 return &authority[..=end];
322 }
323 authority.split(':').next().unwrap_or(authority)
324}
325
326#[cfg(test)]
327mod tests {
328 use super::*;
329
330 #[test]
331 fn authority_strips_scheme_and_path() {
332 assert_eq!(authority_of("http://localhost:11434"), "localhost:11434");
333 assert_eq!(authority_of("http://127.0.0.1:11434/v1"), "127.0.0.1:11434");
334 assert_eq!(
335 authority_of("https://ollama.example.com/api?x=1"),
336 "ollama.example.com"
337 );
338 assert_eq!(authority_of("localhost:11434"), "localhost:11434");
339 }
340
341 #[test]
342 fn host_extracts_from_authority() {
343 assert_eq!(host_of("localhost:11434"), "localhost");
344 assert_eq!(host_of("127.0.0.1:8080"), "127.0.0.1");
345 assert_eq!(host_of("[::1]:11434"), "[::1]");
346 assert_eq!(host_of("localhost"), "localhost");
347 }
348
349 #[tokio::test]
350 async fn remote_urls_are_never_started() {
351 // The whole gate: autostart must refuse to act for a non-loopback
352 // URL — no spawn, no health probe against third parties. (LAN/private
353 // hosts count as remote too: mermaid can't start a server there.)
354 // Checked BEFORE the test-build kill-switch, so this asserts the real
355 // production gate order.
356 for url in [
357 "https://ollama.example.com",
358 "http://192.168.1.50:11434",
359 "http://10.0.0.7:11434",
360 ] {
361 match ensure_running(url, None).await {
362 Err(AutostartError::NotLocal) => {},
363 other => panic!("{url} must be NotLocal, got {other:?}"),
364 }
365 }
366 }
367
368 #[tokio::test]
369 async fn test_builds_never_spawn_even_for_loopback() {
370 // The cfg!(test) hard-off: a loopback URL in a unit-test build stops
371 // at Disabled before the lock/probe/spawn machinery. This is what
372 // makes default-config adapters (autostart=true, localhost:11434)
373 // safe in every present and future test on machines with Ollama
374 // installed.
375 match ensure_running("http://127.0.0.1:11434", None).await {
376 Err(AutostartError::Disabled) => {},
377 other => panic!("expected Disabled in test builds, got {other:?}"),
378 }
379 }
380
381 #[tokio::test]
382 async fn notice_fires_only_when_a_spawn_is_committed() {
383 // The gate paths that return before a spawn (NotLocal, Disabled)
384 // must NOT invoke `notify` — the notice's contract is "a start is
385 // actually happening", so a remote URL or a killed switch stays
386 // silent and no false "Starting…" line ever reaches the user.
387 use std::sync::atomic::{AtomicBool, Ordering};
388 let called = AtomicBool::new(false);
389 let notify = |_: &str| called.store(true, Ordering::SeqCst);
390 let _ = ensure_running("https://ollama.example.com", Some(¬ify)).await;
391 let _ = ensure_running("http://127.0.0.1:11434", Some(¬ify)).await;
392 assert!(
393 !called.load(Ordering::SeqCst),
394 "notify must not fire on NotLocal/Disabled paths"
395 );
396 }
397
398 #[test]
399 fn hints_are_actionable_and_passthrough_variants_are_silent() {
400 assert!(AutostartError::NotLocal.hint().is_none());
401 assert!(AutostartError::Disabled.hint().is_none());
402 let not_installed = AutostartError::NotInstalled.hint().expect("hint");
403 assert!(not_installed.contains("https://ollama.com/download"));
404 let unhealthy = AutostartError::Unhealthy("boom".into())
405 .hint()
406 .expect("hint");
407 assert!(unhealthy.contains("boom"));
408 }
409
410 #[test]
411 fn install_candidates_exist_per_platform() {
412 // Shape check only — never spawns. Windows may legitimately return an
413 // empty list if the env vars are unset; unix lists are static.
414 let paths = known_install_paths();
415 #[cfg(not(target_os = "windows"))]
416 assert!(!paths.is_empty());
417 for p in paths {
418 assert!(p.to_string_lossy().to_lowercase().contains("ollama"));
419 }
420 }
421}