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 // CREATE_NO_WINDOW, never DETACHED_PROCESS: the latter leaves a
254 // visible console window on Windows 11 (see utils::proc).
255 cmd.creation_flags(crate::utils::CREATE_NO_WINDOW | crate::utils::CREATE_NEW_PROCESS_GROUP);
256 }
257 cmd.spawn()
258}
259
260/// `ollama` from PATH, falling back to the platform installer's default
261/// locations (PATH edits don't reach already-running shells, and the macOS
262/// app bundle never touches PATH). Also the definition of "installed" used
263/// by `detector::is_installed`, so the startup preflight and the autostart
264/// can never disagree about whether Ollama exists.
265pub(crate) fn find_binary() -> Option<PathBuf> {
266 if let Ok(path) = which::which("ollama") {
267 return Some(path);
268 }
269 known_install_paths().into_iter().find(|p| p.is_file())
270}
271
272#[cfg(target_os = "windows")]
273fn known_install_paths() -> Vec<PathBuf> {
274 let mut paths = Vec::new();
275 if let Some(base) = std::env::var_os("LOCALAPPDATA") {
276 paths.push(
277 PathBuf::from(base)
278 .join("Programs")
279 .join("Ollama")
280 .join("ollama.exe"),
281 );
282 }
283 if let Some(base) = std::env::var_os("ProgramFiles") {
284 paths.push(PathBuf::from(base).join("Ollama").join("ollama.exe"));
285 }
286 paths
287}
288
289#[cfg(target_os = "macos")]
290fn known_install_paths() -> Vec<PathBuf> {
291 vec![
292 PathBuf::from("/opt/homebrew/bin/ollama"),
293 PathBuf::from("/usr/local/bin/ollama"),
294 PathBuf::from("/Applications/Ollama.app/Contents/Resources/ollama"),
295 ]
296}
297
298#[cfg(all(unix, not(target_os = "macos")))]
299fn known_install_paths() -> Vec<PathBuf> {
300 vec![
301 PathBuf::from("/usr/local/bin/ollama"),
302 PathBuf::from("/usr/bin/ollama"),
303 ]
304}
305
306/// `http://localhost:11434` → `localhost:11434` (scheme and any path/query
307/// stripped). The adapter's `normalize_url` guarantees a scheme is present,
308/// but parse defensively.
309fn authority_of(base_url: &str) -> &str {
310 let rest = base_url
311 .split_once("://")
312 .map(|(_, rest)| rest)
313 .unwrap_or(base_url);
314 rest.split(['/', '?', '#']).next().unwrap_or(rest)
315}
316
317/// Host part of an authority: `localhost:11434` → `localhost`,
318/// `[::1]:11434` → `[::1]` (brackets kept; `classify_host` strips them).
319/// Note: whether `ollama serve` itself accepts a bracketed IPv6 OLLAMA_HOST
320/// is unverified — IPv6-loopback autostart is best-effort.
321fn host_of(authority: &str) -> &str {
322 if let Some(end) = authority.rfind(']') {
323 return &authority[..=end];
324 }
325 authority.split(':').next().unwrap_or(authority)
326}
327
328#[cfg(test)]
329mod tests {
330 use super::*;
331
332 #[test]
333 fn authority_strips_scheme_and_path() {
334 assert_eq!(authority_of("http://localhost:11434"), "localhost:11434");
335 assert_eq!(authority_of("http://127.0.0.1:11434/v1"), "127.0.0.1:11434");
336 assert_eq!(
337 authority_of("https://ollama.example.com/api?x=1"),
338 "ollama.example.com"
339 );
340 assert_eq!(authority_of("localhost:11434"), "localhost:11434");
341 }
342
343 #[test]
344 fn host_extracts_from_authority() {
345 assert_eq!(host_of("localhost:11434"), "localhost");
346 assert_eq!(host_of("127.0.0.1:8080"), "127.0.0.1");
347 assert_eq!(host_of("[::1]:11434"), "[::1]");
348 assert_eq!(host_of("localhost"), "localhost");
349 }
350
351 #[tokio::test]
352 async fn remote_urls_are_never_started() {
353 // The whole gate: autostart must refuse to act for a non-loopback
354 // URL — no spawn, no health probe against third parties. (LAN/private
355 // hosts count as remote too: mermaid can't start a server there.)
356 // Checked BEFORE the test-build kill-switch, so this asserts the real
357 // production gate order.
358 for url in [
359 "https://ollama.example.com",
360 "http://192.168.1.50:11434",
361 "http://10.0.0.7:11434",
362 ] {
363 match ensure_running(url, None).await {
364 Err(AutostartError::NotLocal) => {},
365 other => panic!("{url} must be NotLocal, got {other:?}"),
366 }
367 }
368 }
369
370 #[tokio::test]
371 async fn test_builds_never_spawn_even_for_loopback() {
372 // The cfg!(test) hard-off: a loopback URL in a unit-test build stops
373 // at Disabled before the lock/probe/spawn machinery. This is what
374 // makes default-config adapters (autostart=true, localhost:11434)
375 // safe in every present and future test on machines with Ollama
376 // installed.
377 match ensure_running("http://127.0.0.1:11434", None).await {
378 Err(AutostartError::Disabled) => {},
379 other => panic!("expected Disabled in test builds, got {other:?}"),
380 }
381 }
382
383 #[tokio::test]
384 async fn notice_fires_only_when_a_spawn_is_committed() {
385 // The gate paths that return before a spawn (NotLocal, Disabled)
386 // must NOT invoke `notify` — the notice's contract is "a start is
387 // actually happening", so a remote URL or a killed switch stays
388 // silent and no false "Starting…" line ever reaches the user.
389 use std::sync::atomic::{AtomicBool, Ordering};
390 let called = AtomicBool::new(false);
391 let notify = |_: &str| called.store(true, Ordering::SeqCst);
392 let _ = ensure_running("https://ollama.example.com", Some(¬ify)).await;
393 let _ = ensure_running("http://127.0.0.1:11434", Some(¬ify)).await;
394 assert!(
395 !called.load(Ordering::SeqCst),
396 "notify must not fire on NotLocal/Disabled paths"
397 );
398 }
399
400 #[test]
401 fn hints_are_actionable_and_passthrough_variants_are_silent() {
402 assert!(AutostartError::NotLocal.hint().is_none());
403 assert!(AutostartError::Disabled.hint().is_none());
404 let not_installed = AutostartError::NotInstalled.hint().expect("hint");
405 assert!(not_installed.contains("https://ollama.com/download"));
406 let unhealthy = AutostartError::Unhealthy("boom".into())
407 .hint()
408 .expect("hint");
409 assert!(unhealthy.contains("boom"));
410 }
411
412 #[test]
413 fn install_candidates_exist_per_platform() {
414 // Shape check only — never spawns. Windows may legitimately return an
415 // empty list if the env vars are unset; unix lists are static.
416 let paths = known_install_paths();
417 #[cfg(not(target_os = "windows"))]
418 assert!(!paths.is_empty());
419 for p in paths {
420 assert!(p.to_string_lossy().to_lowercase().contains("ollama"));
421 }
422 }
423}