Skip to main content

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