Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(ollama): the server can be stopped, read and probed — and every role talks to the same host
rubenluetke10-beepa5f035ab3ad5
diff --git a/docs/os-parity.md b/docs/os-parity.mdindex 88eaea5a8a..afde0fb970 100644--- a/docs/os-parity.md+++ b/docs/os-parity.md@@ -247,7 +247,7 @@ experiences today.| P-28 | Low | Local realtime | The one-click managed install AND the 2026-08-08 supervisor (prewarm, pidfile ownership, start/stop routes, Ollama keep-alive warm ping) are built cross-platform — pathlib, `os.name` venv layout with a POSIX `lib/python*/site-packages` glob, per-hardware torch flavor, `start_new_session` + `killpg` SIGTERM→SIGKILL escalation on POSIX, `HF_HUB_DISABLE_SYMLINKS` Windows-only — but have only been RUN on the Windows dev box. The preflight's accelerator probe knows two sources: NVIDIA VRAM (nvidia-smi) and Apple-Silicon unified memory (total RAM); the derived launch command maps them to `cuda`/`mps`; an AMD/Intel/no-nvidia-smi host gets the honest "no supported accelerator" blocker (unit-tested) | `jarvis/realtime/local_server/{preflight,install,supervisor}.py` | Any host under 12 GB usable accelerator memory (including every GPU-less/headless box) gets the honest blocker with a cloud pointer instead of an install — verified by unit tests. macOS Apple-Silicon: preflight and install should work but the smoke boot (`--qwen3_tts_device mps`) is UNVERIFIED on real hardware; a failure is honest (install ends in an error state naming the smoke log, readiness stays fail-closed). Linux+NVIDIA: expected to work via the same cu130 wheel index, unverified; the supervisor's POSIX kill/spawn branches are unit-tested but not live-run. The bring-your-own-server URL socket keeps full parity everywhere || P-30 | Medium | Local STT on the GPU | The on-device CTranslate2 recognizer (faster-whisper) needs the cuBLAS 12 / cuDNN 9 runtime wheels, which the `[full]` profile deliberately does not carry. Without them the engine self-heals onto the CPU and, until 2026-08-22, nothing but a log line said so (36 silent fallbacks in one live log; the cloud fallback then ran at ~1× realtime). The wheels are now the opt-in `[cuda]` extra, the provider card reports the accelerator truth (`accelerator_status`: requested device, effective device, reason code) and offers the install from inside the app (`POST /api/local-gpu/libraries`), and the library probe is a pure on-disk look — the out-of-process inference probe (AP-25) remains the only verdict on whether the GPU WORKS | `jarvis/plugins/stt/fwhisper.py::cuda_runtime_libraries_present`, `GPU_LIBRARY_PACKAGES`, `jarvis/speech/local_models.py::accelerator_status`, `jarvis/speech/local_install.py::start_gpu_libraries_install` | Windows: verified live on the dev box (install → `ctranslate2.get_cuda_device_count() == 1`, base/cuda decode). Linux: the same wheels land in `nvidia/cublas/lib`; the probe also accepts a system-wide CUDA via `ctypes.util.find_library("cublas")` — expected to work, UNVERIFIED on real hardware. macOS: no CUDA exists; the card says `unsupported_os` and the recognizer runs on the CPU with no install offered. Headless/GPU-less Linux: libraries absent → honest `cuda_libraries_missing` when the config asks for `cuda`, silent when it asks for `cpu` |-| P-32 | Low | Local models | The in-app Ollama runtime install (the plug-and-go path for local models: detect → install → start → pull, no terminal) has one silent path per OS and an honest refusal elsewhere: Windows uses winget or the official per-user OllamaSetup.exe (built, not yet live-run on a machine WITHOUT Ollama); macOS automates only Homebrew — a dmg drag cannot be scripted honestly, so brew-less Macs get the download pointer; Linux runs the official install.sh only when non-interactive sudo exists (the script escalates internally; without it the refusal names the one terminal command instead of hanging on an invisible password prompt). Detection and start are cross-platform | `jarvis/brain/ollama_runtime.py`, `jarvis/ui/web/provider_routes.py` (ollama-runtime routes), `jarvis/realtime/local_server/install.py::_setup_local_brain` | Every OS gets the same three-state truth (not installed / stopped / running) and the same buttons; only the INSTALL leg differs. Refusals are one honest sentence with the exact fixing action. All install legs are unit-tested with fakes; no leg has been live-run on a machine without Ollama yet — the cold-machine drill is the recorded release gate |+| P-32 | Low | Local models | The in-app Ollama runtime install (the plug-and-go path for local models: detect → install → start → pull, no terminal) has one silent path per OS and an honest refusal elsewhere: Windows uses winget or the official per-user OllamaSetup.exe (built, not yet live-run on a machine WITHOUT Ollama); macOS automates only Homebrew — a dmg drag cannot be scripted honestly, so brew-less Macs get the download pointer; Linux runs the official install.sh only when non-interactive sudo exists (the script escalates internally; without it the refusal names the one terminal command instead of hanging on an invisible password prompt). Detection and start are cross-platform. **Stop** (2026-08-24) touches only the pid Jarvis itself spawned, recorded in `DATA_DIR/ollama_server.pid` beside the log: psutil `terminate` then `kill` after 8 s on all three OSes; a tray-app / terminal / systemd server gets the sentence "not started by Jarvis — stop it where you started it", a recycled pid is never signalled. **Log** = the last N lines of `DATA_DIR/ollama_server.log` (UTF-8, lossy-safe) — the file exists only for a server Jarvis started, identical on every OS. **Test** = `probe_host(base_url)` GET `/api/version` with a 3 s budget → version + latency, pure HTTP, any OS, any remote host. `runtime_status` adds `host_kind` (local vs remote by loopback / own hostname), `models_dir` (`OLLAMA_MODELS`, else Windows `%USERPROFILE%\.ollama\models`, macOS `~/.ollama/models`, Linux `/usr/share/ollama/.ollama/models` when present else `~/.ollama/models`) and `version`. The env guide is copyable text per OS (Windows `setx`, macOS `launchctl setenv`, Linux `systemctl edit ollama.service` drop-in) — the app never edits the OS environment. The voice brain (`brain_link`), the wiki embedder and the ack brain fall back to the one configured Ollama address (`resolve_provider_endpoint("ollama")` → `OLLAMA_HOST` → localhost) when their own key is empty, so a remote host is set once | `jarvis/brain/ollama_runtime.py`, `jarvis/ui/web/provider_routes.py` (ollama-runtime routes), `jarvis/realtime/local_server/install.py::_setup_local_brain`, `jarvis/realtime/local_server/brain_link.py::_ollama_base`, `jarvis/ultrawiki/embeddings.py::_make_ollama`, `jarvis/brain/ack_brain/config.py::OllamaAckProviderConfig.resolved_endpoint` | Every OS gets the same three-state truth (not installed / stopped / running) and the same buttons; only the INSTALL leg differs. Refusals are one honest sentence with the exact fixing action. All install legs are unit-tested with fakes; no leg has been live-run on a machine without Ollama yet — the cold-machine drill is the recorded release gate. Stop / log / test / env guide / models_dir are unit-tested per OS with fakes (`tests/unit/brain/test_ollama_runtime.py`); a remote `host_kind` hides the local-only controls, so a LAN GPU box is managed on its own machine || P-32 | Info | Local models | Per-model options (a derived profile alias via `/api/create` carrying `num_ctx`, placement and sampling; a `keep_alive` warm ping via `/api/generate`; `think` as `reasoning_effort` on `/v1`) are pure HTTP against the Ollama server root — no OS-specific leg, no subprocess, identical on Windows, macOS, Linux (headless included) and against a remote host | `jarvis/brain/ollama_profiles.py`, `jarvis/plugins/brain/ollama.py`, `jarvis/core/config_writer.py::set_ollama_model_options` | Same behaviour everywhere; the server does the work, Jarvis only names the alias. Unit-tested with an `httpx.MockTransport` fake server; `reasoning_effort` -> `think` verified live on Ollama 0.32.15 || P-31 | Low | Detached views | The "own window" detach (Agentic IDE / Voice into a second pywebview window) creates the window at RUNTIME, after `webview.start()`. pywebview documents runtime multi-window, and the code path is OS-neutral (worker-thread create, distinct title, shared backend), but it has only been RUN against the Windows/WebView2 backend; whether the cocoa and GTK backends accept a runtime `create_window` is unverified from this machine. Browser-lock auth in the second window additionally relies on a shared cookie jar, which is verified for WebView2 only | `jarvis/ui/desktop_app.py::open_detached_window`, `jarvis/platform/probes.py::webview_backend_available`, `jarvis/ui/web/desktop_routes.py` | Every failure is honest and keeps the feature usable: a shell whose backend refuses the runtime create answers `ok: false` with the solo URL and the frontend opens it in the user's real browser tab (via open-external); plain-browser clients open the tab directly; headless answers `no_desktop_shell` the same way. macOS/Linux desktop live check pending: detach, close main, reattach, tray-reopen — on success this row shrinks to the cookie-jar note or disappears || P-33 | Low | Music control (YouTube Music) | With the default **background player** (`jarvis/platform/music_player.py` + `music_player_host.py`: a pywebview companion window with its own persistent profile, driven over stdin/stdout JSON lines) pause / resume / next / previous / volume / "what is playing" go through the player's page directly and need only a display plus the `[desktop]` extra (pywebview) — verified live on Windows/WebView2 (a hidden window does NOT start media; minimized does, hence the minimized start); macOS WKWebView and Linux GTK/Qt WebKit are the same code, unverified from this machine, and autoplay policy there may need one press of play (the tool shows the window and says so). In **browser mode**, and wherever the player cannot run, the same verbs go through the OS media session — the registry the keyboard's media keys use — because Google publishes no remote-playback API. Windows reads and steers it through WinRT (`winrt-Windows.Media.Control`, in the `[desktop]` extra; measured live 2026-08-18 against YouTube Music in Chrome, including the two-tabs-same-app-id case) and falls back to blind media keys without the extra. Linux has no binding in the base install and needs the `playerctl` CLI (MPRIS); macOS has no public API at all and needs the Homebrew `nowplaying-cli`, whose MediaRemote access Apple has been narrowing on recent releases | `jarvis/platform/media_session.py::make_media_session_controller`, `WindowsMediaSession`, `LinuxMediaSession`, `MacMediaSession`, `jarvis/plugins/tool/youtube_music_rest.py::_control` | Playing (search + open the `music.youtube.com` deep link) works on every desktop OS. Without the CLI, `now_playing` and the transport verbs answer with the exact install command instead of a fake success, and the play deep link plus the library actions (like, playlists) stay fully usable. Headless: no player exists, so the tool returns the link and says so. Linux `playerctl` and macOS `nowplaying-cli` backends are unit-tested with fake CLI output, not live-run from this machine |diff --git a/jarvis/brain/ack_brain/config.py b/jarvis/brain/ack_brain/config.pyindex 774b1f8392..d71f52a4bb 100644--- a/jarvis/brain/ack_brain/config.py+++ b/jarvis/brain/ack_brain/config.py@@ -14,6 +14,7 @@ Maps the [ack_brain] section of jarvis.toml. Two switches, opposite defaults:it on", which described the pre-2026-06-21 shape and contradicted the fielddefaults below.)"""+from __future__ import annotationsfrom typing import Literal@@ -30,7 +31,11 @@ from pydantic import BaseModel, ConfigDict, Field# "gemini" with a warning. Letting users pin a separate flash provider# stays possible by setting one of the four concrete names.SUPPORTED_PROVIDERS: tuple[str, ...] = (- "follow_brain", "gemini", "grok", "openai", "ollama",+ "follow_brain",+ "gemini",+ "grok",+ "openai",+ "ollama",)@@ -63,9 +68,25 @@ class OpenAIAckProviderConfig(_ProviderBase):class OllamaAckProviderConfig(_ProviderBase):- """Local Ollama provider config - no API key, just an HTTP endpoint."""+ """Local Ollama provider config - no API key, just an HTTP endpoint.++ ``endpoint`` empty (the default) means the ONE Ollama address every role+ shares — ``[brain.providers.ollama].base_url`` when set, else+ ``OLLAMA_HOST``, else localhost — resolved by :meth:`resolved_endpoint`+ at request time, never at config-load time (the config is still being+ built then). A non-empty value pins this role to its own server.+ """++ endpoint: str = Field(default="")++ def resolved_endpoint(self) -> str:+ """The server root this role talks to (own value, else the shared one)."""+ own = (self.endpoint or "").strip().rstrip("/")+ if own:+ return own+ from jarvis.brain.ollama_pull import server_root # lazy: config must not import it- endpoint: str = Field(default="http://localhost:11434", min_length=1)+ return server_root().rstrip("/")class _ProvidersBundle(BaseModel):@@ -88,9 +109,7 @@ class _ProvidersBundle(BaseModel):default_factory=lambda: GeminiAckProviderConfig(model="gemini-flash-latest"))grok: GrokAckProviderConfig = Field(- default_factory=lambda: GrokAckProviderConfig(- model="grok-4.20-0309-non-reasoning"- )+ default_factory=lambda: GrokAckProviderConfig(model="grok-4.20-0309-non-reasoning"))openai: OpenAIAckProviderConfig = Field(default_factory=lambda: OpenAIAckProviderConfig(model="gpt-5-mini")diff --git a/jarvis/brain/ack_brain/providers/ollama.py b/jarvis/brain/ack_brain/providers/ollama.pyindex a536823df7..6b0af14432 100644--- a/jarvis/brain/ack_brain/providers/ollama.py+++ b/jarvis/brain/ack_brain/providers/ollama.py@@ -8,6 +8,7 @@ The HTTP client uses a short connect timeout (2s) so an unreachableendpoint falls through to ``None`` quickly instead of stalling thevoice pipeline."""+from __future__ import annotationsimport logging@@ -40,7 +41,7 @@ class OllamaFlashAck:timeout = httpx.Timeout(connect=2.0, read=5.0, write=2.0, pool=2.0)async with httpx.AsyncClient(timeout=timeout) as client:response = await client.post(- f"{self._config.endpoint.rstrip('/')}/api/chat",+ f"{self._config.resolved_endpoint()}/api/chat",json={"model": self._config.model,"messages": [diff --git a/jarvis/brain/ollama_runtime.py b/jarvis/brain/ollama_runtime.pyindex 63ae8216e5..fa677d21fa 100644--- a/jarvis/brain/ollama_runtime.py+++ b/jarvis/brain/ollama_runtime.py@@ -9,7 +9,13 @@ button instead of a command line:"installed but not running" / "running"), which pure HTTP probes cannotdistinguish.- :func:`start_server` — spawn ``ollama serve`` detached and wait for its- port.+ port; the child's pid is recorded beside the log so :func:`stop_server`+ can later stop THAT process and nothing else.+- :func:`stop_server` / :func:`tail_log` / :func:`probe_host` /+ :func:`env_guide` — the Server panel's read-and-control surface: stop+ only what Jarvis spawned, show the log tail, test any host address, and+ hand out per-OS environment recipes as copyable text (the app never edits+ the OS environment itself).- :func:`start_install` / :func:`install_snapshot` — a poll-shaped installer(same skeleton as the managed realtime server install): winget or theofficial per-user installer on Windows, Homebrew on macOS, the official@@ -127,12 +133,98 @@ def _server_version(timeout: float = _VERSION_TIMEOUT_S) -> str | None:return version or "unknown"-def runtime_status() -> dict[str, object]:- """The honest runtime picture: ``{installed, binary, running, version, detail}``.+#: ``0.0.0.0`` is a bind address; a client that typed it means this machine.+_LOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1", "::1", "0.0.0.0", ""}) # noqa: S104+++def host_kind(base_url: str) -> str:+ """``"local"`` when ``base_url`` points at this machine, else ``"remote"``.++ Loopback names, any ``127.x`` address, and this machine's own hostname+ count as local; everything else is a server somewhere on the network+ whose install/start/stop/log belong to that machine.+ """+ host = (urlsplit(base_url).hostname or "").strip().lower().strip("[]")+ if host in _LOOPBACK_HOSTS or host.startswith("127."):+ return "local"+ try:+ own = socket.gethostname().strip().lower()+ except OSError:+ # Without a resolvable own hostname the only honest answer is that+ # the address is not one of the loopback spellings.+ log.debug("ollama-runtime: gethostname failed", exc_info=True)+ return "remote"+ if own and (host == own or host == f"{own}.local" or host.split(".")[0] == own):+ return "local"+ return "remote"+++def _current_os() -> str:+ """``"windows"`` / ``"macos"`` / ``"linux"`` for this process."""+ if os.name == "nt":+ return "windows"+ if sys.platform == "darwin":+ return "macos"+ return "linux"+++_OS_ALIASES = {+ "nt": "windows",+ "win32": "windows",+ "windows": "windows",+ "darwin": "macos",+ "mac": "macos",+ "macos": "macos",+ "linux": "linux",+ "posix": "linux",+}- A pure HTTP probe cannot tell "not installed" from "installed but- stopped" — and those two states need OPPOSITE buttons (install vs- start), so the distinction is the whole point of this function.++def _normalize_os(os_name: str | None) -> str:+ """Map any common OS spelling to ``windows`` / ``macos`` / ``linux``.++ Empty means "this process"; an unknown name is treated as Linux, the+ family every headless server belongs to.+ """+ key = (os_name or "").strip().lower()+ if not key:+ return _current_os()+ return _OS_ALIASES.get(key, "linux")+++def models_dir(os_name: str | None = None) -> Path:+ """Where Ollama keeps its weights: ``OLLAMA_MODELS`` or the OS default.++ Defaults follow the vendor: the user's ``.ollama/models`` on Windows+ (under ``%USERPROFILE%``) and macOS (under ``~``); on Linux the service+ user's ``/usr/share/ollama/.ollama/models`` when that directory exists,+ else the current user's ``~/.ollama/models``. Pure pathlib — nothing is+ created.+ """+ env_dir = (os.environ.get("OLLAMA_MODELS") or "").strip()+ if env_dir:+ return Path(env_dir).expanduser()+ which = _normalize_os(os_name)+ if which == "linux":+ service_dir = Path("/usr/share/ollama/.ollama/models")+ try:+ if service_dir.is_dir():+ return service_dir+ except OSError:+ # An unreadable mount means "not this one"; fall through.+ log.debug("ollama-runtime: service models dir unreadable", exc_info=True)+ return Path.home() / ".ollama" / "models"+++def runtime_status() -> dict[str, object]:+ """The honest runtime picture.++ ``{installed, binary, running, version, detail, base_url, host_kind,+ models_dir}``. A pure HTTP probe cannot tell "not installed" from+ "installed but stopped" — and those two states need OPPOSITE buttons+ (install vs start), so the distinction is the whole point of this+ function. ``host_kind`` tells the panel whether install/start/stop/log+ even apply here: a remote server is managed on its own machine."""binary = find_binary()version = _server_version()@@ -144,12 +236,16 @@ def runtime_status() -> dict[str, object]:detail = "Ollama is installed but not running."else:detail = "Ollama is not installed on this machine."+ base_url = _server_root()return {"installed": installed,"binary": binary,"running": running,"version": version or "","detail": detail,+ "base_url": base_url,+ "host_kind": host_kind(base_url),+ "models_dir": str(models_dir()),}@@ -188,6 +284,53 @@ def _install_marker() -> Path:return _data_dir() / "ollama_installed_by_jarvis.json"+def _log_path() -> Path:+ return _data_dir() / "ollama_server.log"+++def _pid_file() -> Path:+ return _data_dir() / "ollama_server.pid"+++def _record_pid(pid: int, binary: str) -> None:+ """Remember which process Jarvis spawned so ``stop_server`` stops only that."""+ try:+ _pid_file().parent.mkdir(parents=True, exist_ok=True)+ _pid_file().write_text(+ json.dumps({"pid": int(pid), "binary": binary, "at": time.time()}),+ encoding="utf-8",+ )+ except OSError:+ # Bookkeeping only: the server still runs, stop just loses its handle.+ log.warning("ollama-runtime: could not record the server pid", exc_info=True)+++def _recorded_pid() -> int | None:+ """The pid Jarvis spawned, or ``None`` when no record exists."""+ try:+ raw = _pid_file().read_text(encoding="utf-8")+ except FileNotFoundError:+ return None+ except OSError:+ log.debug("ollama-runtime: pid file unreadable", exc_info=True)+ return None+ try:+ pid = int(json.loads(raw).get("pid", 0))+ except (ValueError, AttributeError, TypeError):+ log.debug("ollama-runtime: pid file malformed", exc_info=True)+ return None+ return pid or None+++def _forget_pid() -> None:+ try:+ _pid_file().unlink()+ except FileNotFoundError:+ return+ except OSError:+ log.debug("ollama-runtime: pid file not removed", exc_info=True)++def start_server() -> tuple[bool, str]:"""Spawn ``ollama serve`` detached and wait for its port. ``(ok, detail)``.@@ -202,7 +345,7 @@ def start_server() -> tuple[bool, str]:return False, "Ollama is not installed — install it first."sink = Nonetry:- log_path = _data_dir() / "ollama_server.log"+ log_path = _log_path()log_path.parent.mkdir(parents=True, exist_ok=True)sink = open(log_path, "ab") # noqa: SIM115 — handed to the childexcept OSError:@@ -211,13 +354,13 @@ def start_server() -> tuple[bool, str]:if os.name != "nt":popen_kwargs["start_new_session"] = Truetry:- subprocess.Popen( # noqa: S603 — fixed argv, resolved binary+ child = subprocess.Popen( # noqa: S603 — fixed argv, resolved binary[binary, "serve"],stdin=subprocess.DEVNULL,stdout=sink or subprocess.DEVNULL,stderr=subprocess.STDOUT,creationflags=NO_WINDOW_CREATIONFLAGS,- **popen_kwargs, # type: ignore[arg-type]+ **popen_kwargs, # type: ignore[arg-type, call-overload])except OSError as exc:# Not swallowed: the reason travels back as this function's own@@ -226,6 +369,7 @@ def start_server() -> tuple[bool, str]:finally:if sink is not None:sink.close()+ _record_pid(child.pid, binary)port = _server_port()deadline = time.monotonic() + _START_WAIT_Swhile time.monotonic() < deadline:@@ -238,6 +382,228 @@ def start_server() -> tuple[bool, str]:)+# ── Stop / log / probe / environment guide ───────────────────────────────++_STOP_WAIT_S = 8.0+_PROBE_TIMEOUT_S = 3.0++_NOT_OURS = (+ "This Ollama was not started by Jarvis, so Jarvis will not stop it — "+ "stop it where you started it (the Ollama tray app, your terminal, or "+ "the system service)."+)+++def _process_is_ollama(proc: object) -> bool:+ """True when ``proc`` still is an Ollama binary (guards pid reuse)."""+ try:+ name = str(proc.name() or "").lower() # type: ignore[attr-defined]+ except Exception: # noqa: BLE001 — psutil raises its own family on a gone/denied process+ log.debug("ollama-runtime: process name unavailable", exc_info=True)+ return False+ return "ollama" in name+++def stop_server() -> tuple[bool, str]:+ """Stop the ``ollama serve`` Jarvis itself spawned. ``(ok, detail)``.++ Only the recorded pid is ever touched: a server the user started from+ the tray app, a terminal, or systemd gets one honest sentence instead of+ a silent no-op or a foreign kill. A recorded pid that already died is+ forgotten so the next answer is honest again.+ """+ pid = _recorded_pid()+ if pid is None:+ return False, _NOT_OURS+ import psutil # lazy (AP-26)++ try:+ proc = psutil.Process(pid)+ except psutil.NoSuchProcess:+ _forget_pid()+ return False, (+ f"The Ollama that Jarvis started (pid {pid}) is no longer running. "+ "If a server is still answering, it was started elsewhere."+ )+ except psutil.Error as exc:+ return False, f"Could not inspect the Ollama process Jarvis started ({exc})."+ if not _process_is_ollama(proc):+ # The pid was recycled by the OS for an unrelated program.+ _forget_pid()+ return False, (+ f"Pid {pid} no longer belongs to Ollama; the server Jarvis started "+ "is gone. If a server is still answering, it was started elsewhere."+ )+ try:+ proc.terminate()+ try:+ proc.wait(timeout=_STOP_WAIT_S)+ except psutil.TimeoutExpired:+ log.warning("ollama-runtime: pid %s ignored terminate; killing", pid)+ proc.kill()+ proc.wait(timeout=_STOP_WAIT_S)+ except psutil.NoSuchProcess:+ # It exited between the check and the signal — that IS the goal.+ log.debug("ollama-runtime: pid %s exited before the signal", pid)+ except psutil.Error as exc:+ return False, f"Could not stop Ollama (pid {pid}): {exc}."+ _forget_pid()+ return True, "Ollama stopped."+++def tail_log(lines: int = 40) -> list[str]:+ """The last ``lines`` of the server log Jarvis writes; ``[]`` when none."""+ if lines <= 0:+ return []+ try:+ with open(_log_path(), "rb") as handle:+ tail = deque(handle, maxlen=lines)+ except FileNotFoundError:+ return []+ except OSError:+ log.debug("ollama-runtime: server log unreadable", exc_info=True)+ return []+ return [raw.decode("utf-8", errors="replace").rstrip("\r\n") for raw in tail]+++async def probe_host(base_url: str, *, transport: object | None = None) -> dict[str, object]:+ """Ask ``base_url`` for its version: ``{ok, version, latency_ms, detail}``.++ Used before a new server address is saved, so a typo is caught by one+ sentence instead of by every role failing later. Never raises.+ ``transport`` is the test seam (an ``httpx`` transport); production+ passes nothing.+ """+ from jarvis.plugins.brain.ollama import normalize_server_root # lazy (AP-26)++ root = normalize_server_root(base_url)+ url = f"{root}/api/version"+ if not url.startswith(("http://", "https://")):+ return {+ "ok": False,+ "version": "",+ "latency_ms": 0,+ "detail": f"{base_url!r} is not an http(s) address.",+ }+ import httpx # lazy (AP-26)++ started = time.monotonic()+ try:+ async with httpx.AsyncClient(+ timeout=_PROBE_TIMEOUT_S,+ transport=transport, # type: ignore[arg-type]+ ) as client:+ response = await client.get(url)+ latency_ms = int((time.monotonic() - started) * 1000)+ response.raise_for_status()+ version = str(response.json().get("version", "") or "") or "unknown"+ except httpx.HTTPStatusError as exc:+ latency_ms = int((time.monotonic() - started) * 1000)+ return {+ "ok": False,+ "version": "",+ "latency_ms": latency_ms,+ "detail": (+ f"{root} answered HTTP {exc.response.status_code} on /api/version "+ "— that is not an Ollama server."+ ),+ }+ except (httpx.HTTPError, ValueError, AttributeError) as exc:+ latency_ms = int((time.monotonic() - started) * 1000)+ reason = str(exc) or exc.__class__.__name__+ return {+ "ok": False,+ "version": "",+ "latency_ms": latency_ms,+ "detail": f"No Ollama answered at {root} ({reason}).",+ }+ return {+ "ok": True,+ "version": version,+ "latency_ms": latency_ms,+ "detail": f"Ollama {version} answered in {latency_ms} ms.",+ }+++#: (key, purpose, example value) — one plain sentence each. The value is an+#: example the user edits, not a setting the app applies.+_ENV_KEYS: tuple[tuple[str, str, str], ...] = (+ (+ "OLLAMA_HOST",+ "The address the server listens on; 0.0.0.0 lets other machines reach it.",+ "0.0.0.0", # noqa: S104 — the documented value the USER pastes, not a bind here+ ),+ (+ "OLLAMA_MODELS",+ "The folder where downloaded model weights are stored.",+ "/path/to/models",+ ),+ (+ "OLLAMA_KEEP_ALIVE",+ "How long a model stays loaded in memory after its last request.",+ "30m",+ ),+ (+ "OLLAMA_NUM_PARALLEL",+ "How many requests one loaded model serves at the same time.",+ "1",+ ),+ (+ "OLLAMA_MAX_LOADED_MODELS",+ "How many models may sit in memory at once.",+ "2",+ ),+ (+ "OLLAMA_FLASH_ATTENTION",+ "Turns the faster attention kernel on (1) or off (0) on supported GPUs.",+ "1",+ ),+ (+ "OLLAMA_KV_CACHE_TYPE",+ "The precision of the context cache; q8_0 halves its memory with little loss.",+ "q8_0",+ ),+)++_RESTART_HINTS = {+ "windows": "Quit Ollama from the tray icon and start it again.",+ "macos": "Quit the Ollama menu-bar app and start it again.",+ "linux": "Run: sudo systemctl restart ollama",+}+++def _env_command(which: str, key: str, value: str) -> str:+ if which == "windows":+ return f"setx {key} {value}"+ if which == "macos":+ return f"launchctl setenv {key} {value}"+ return (+ f'sudo systemctl edit ollama.service # add under [Service]: Environment="{key}={value}"'+ )+++def env_guide(os_name: str | None = None) -> list[dict[str, str]]:+ """Copyable per-OS recipes for Ollama's server environment variables.++ Each row is ``{key, purpose, command, restart}``. The app never edits the+ OS environment: the user pastes the line, then restarts the server. The+ Linux recipe targets the systemd unit the official installer creates;+ Windows ``setx`` reaches processes started afterwards; macOS+ ``launchctl setenv`` reaches apps launched after it.+ """+ which = _normalize_os(os_name)+ restart = _RESTART_HINTS[which]+ return [+ {+ "key": key,+ "purpose": purpose,+ "command": _env_command(which, key, value),+ "restart": restart,+ }+ for key, purpose, value in _ENV_KEYS+ ]++# ── Poll-shaped installer ────────────────────────────────────────────────_PHASES = ("idle", "downloading", "installing", "starting", "done", "error")@@ -305,9 +671,7 @@ def start_install() -> tuple[bool, str]:_STATE.percent = 0_STATE.error = ""_STATE.detail = ""- thread = threading.Thread(- target=_run_install, name="ollama-runtime-install", daemon=True- )+ thread = threading.Thread(target=_run_install, name="ollama-runtime-install", daemon=True)_STATE.thread = threadthread.start()return True, "install started"@@ -341,9 +705,7 @@ def _run_command(cmd: list[str], *, timeout: int) -> None:with _LOCK:_STATE.log_tail.append(line[:200])if result.returncode != 0:- raise RuntimeError(- f"step failed (exit {result.returncode}): {' '.join(cmd[:2])}…"- )+ raise RuntimeError(f"step failed (exit {result.returncode}): {' '.join(cmd[:2])}…")def _download(url: str, target: Path) -> None:@@ -354,9 +716,7 @@ def _download(url: str, target: Path) -> None:target.parent.mkdir(parents=True, exist_ok=True)staging = target.with_suffix(target.suffix + ".part")- with httpx.stream(- "GET", url, follow_redirects=True, timeout=_DOWNLOAD_TIMEOUT_S- ) as response:+ with httpx.stream("GET", url, follow_redirects=True, timeout=_DOWNLOAD_TIMEOUT_S) as response:response.raise_for_status()total = int(response.headers.get("Content-Length", 0) or 0)done = 0@@ -477,9 +837,7 @@ def ensure_runtime_blocking() -> tuple[bool, str]:method = _install_linux()_record_marker(method)if not find_binary():- return False, (- "the Ollama installer finished but no binary was found"- )+ return False, ("the Ollama installer finished but no binary was found")return start_server()except Exception as exc: # noqa: BLE001 — honest sentence, never a raisereturn False, str(exc)@@ -501,8 +859,7 @@ def _run_install() -> None:_record_marker(method)if not find_binary():raise RuntimeError(- "the installer finished but no Ollama binary was found — "- "see the log tail above"+ "the installer finished but no Ollama binary was found — see the log tail above")_set("starting", 85, "starting Ollama")ok, detail = start_server()diff --git a/jarvis/realtime/local_server/brain_link.py b/jarvis/realtime/local_server/brain_link.pyindex 202e43e6a9..608ce3ddbc 100644--- a/jarvis/realtime/local_server/brain_link.py+++ b/jarvis/realtime/local_server/brain_link.py@@ -80,12 +80,30 @@ class BrainResolution:def _ollama_base() -> str:+ """The Ollama root the voice brain talks to.++ ``OLLAMA_HOST`` wins when set (the vendor's own convention); otherwise+ the ONE server address every other role resolves — the configured+ ``[brain.providers.ollama].base_url`` override or the vendor default —+ so a remote setup no longer splits the voice brain from chat, wiki and+ ack. The lazy import keeps this module free of config on import.+ """host = (os.environ.get("OLLAMA_HOST") or "").strip()- if not host:+ if host:+ if not host.startswith(("http://", "https://")):+ host = f"http://{host}"+ return host.rstrip("/")+ try:+ from jarvis.brain.ollama_pull import server_root # lazy (AP-26)++ return server_root().rstrip("/") or _OLLAMA_DEFAULT+ except Exception: # noqa: BLE001 — an unreadable config must not take the voice brain down+ log.warning(+ "brain-link: shared Ollama address unavailable, using %s",+ _OLLAMA_DEFAULT,+ exc_info=True,+ )return _OLLAMA_DEFAULT- if not host.startswith(("http://", "https://")):- host = f"http://{host}"- return host.rstrip("/")#: Memory the brain model must leave free on the accelerator, in GiB: the@@ -269,9 +287,7 @@ def resolve_brain(base = _ollama_base()models = _ollama_models(base, timeout)if models is not None:- model, note = _pick_model(- models, preferred_model=preferred_model, usable_gb=usable_gb- )+ model, note = _pick_model(models, preferred_model=preferred_model, usable_gb=usable_gb)if model:sentence = f"Fully local: reasoning runs on your Ollama ({model})."if note:diff --git a/jarvis/ultrawiki/embeddings.py b/jarvis/ultrawiki/embeddings.pyindex cfa1c2df18..1ce8b646ed 100644--- a/jarvis/ultrawiki/embeddings.py+++ b/jarvis/ultrawiki/embeddings.py@@ -467,11 +467,37 @@ class CohereEmbedding(_HttpEmbedding):return vectors+def _shared_ollama_root() -> str:+ """The one Ollama address every role shares (override -> OLLAMA_HOST -> localhost)."""+ from jarvis.brain.ollama_pull import server_root # lazy (AP-26)++ return server_root()++def _make_ollama(cfg: Any) -> OllamaEmbedding:- endpoint = _DEFAULT_OLLAMA_ENDPOINT+ """Build the Ollama embedder on the address the wiki config names.++ ``[ultrawiki].ollama_endpoint`` still wins when the user set it to+ something of their own. Empty, or left at the shipped localhost default,+ means "the same server as everything else": the configured+ ``[brain.providers.ollama].base_url`` override (or ``OLLAMA_HOST``), so a+ remote Ollama setup no longer leaves the wiki silently talking to a+ localhost that has nothing on it.+ """+ endpoint = ""ultrawiki = getattr(cfg, "ultrawiki", None)if ultrawiki is not None:- endpoint = getattr(ultrawiki, "ollama_endpoint", endpoint) or endpoint+ endpoint = str(getattr(ultrawiki, "ollama_endpoint", "") or "").strip()+ if not endpoint or endpoint.rstrip("/") == _DEFAULT_OLLAMA_ENDPOINT:+ try:+ endpoint = _shared_ollama_root()+ except Exception: # noqa: BLE001 — the wiki must build even when config cannot be read+ log.warning(+ "ultrawiki: shared Ollama address unavailable, using %s",+ _DEFAULT_OLLAMA_ENDPOINT,+ exc_info=True,+ )+ endpoint = _DEFAULT_OLLAMA_ENDPOINTreturn OllamaEmbedding(endpoint=endpoint)diff --git a/tests/unit/brain/test_ollama_runtime.py b/tests/unit/brain/test_ollama_runtime.pyindex d650f10edb..dab4b52f07 100644--- a/tests/unit/brain/test_ollama_runtime.py+++ b/tests/unit/brain/test_ollama_runtime.py@@ -107,9 +107,7 @@ def test_start_spawns_detached_and_waits_for_the_port(monkeypatch) -> None:def test_start_reports_a_server_that_never_binds(monkeypatch) -> None:monkeypatch.setattr(ollama_runtime, "_server_version", lambda timeout=1.5: None)monkeypatch.setattr(ollama_runtime, "find_binary", lambda: "/usr/bin/ollama")- monkeypatch.setattr(- subprocess, "Popen", lambda argv, **kwargs: SimpleNamespace(pid=1)- )+ monkeypatch.setattr(subprocess, "Popen", lambda argv, **kwargs: SimpleNamespace(pid=1))monkeypatch.setattr(ollama_runtime, "_port_open", lambda port, timeout=1.0: False)monkeypatch.setattr(ollama_runtime, "_START_WAIT_S", 0.1)ok, detail = ollama_runtime.start_server()@@ -134,9 +132,7 @@ def test_linux_without_sudo_refuses_with_the_one_command(monkeypatch) -> None:def test_macos_without_brew_refuses_with_the_dmg_pointer(monkeypatch) -> None:monkeypatch.setattr(ollama_runtime.shutil, "which", lambda name: None)- monkeypatch.setattr(- ollama_runtime.Path, "exists", lambda self: False, raising=False- )+ monkeypatch.setattr(ollama_runtime.Path, "exists", lambda self: False, raising=False)with pytest.raises(RuntimeError, match="ollama.com/download"):ollama_runtime._install_macos()@@ -152,9 +148,7 @@ def test_macos_intel_brew_prefix_is_found_without_path(monkeypatch) -> None:raising=False,)commands: list[list[str]] = []- monkeypatch.setattr(- ollama_runtime, "_run_command", lambda cmd, timeout: commands.append(cmd)- )+ monkeypatch.setattr(ollama_runtime, "_run_command", lambda cmd, timeout: commands.append(cmd))assert ollama_runtime._install_macos() == "homebrew"assert commands[0][0] == "/usr/local/bin/brew"@@ -184,14 +178,13 @@ def test_windows_falls_back_to_the_official_installer(monkeypatch, tmp_path) ->monkeypatch.setattr(ollama_runtime,"_download",- lambda url, target: downloads.append(url) or target.parent.mkdir(- parents=True, exist_ok=True- )- or target.write_bytes(b"exe"),- )- monkeypatch.setattr(- ollama_runtime, "_run_command", lambda cmd, timeout: commands.append(cmd)+ lambda url, target: (+ downloads.append(url)+ or target.parent.mkdir(parents=True, exist_ok=True)+ or target.write_bytes(b"exe")+ ),)+ monkeypatch.setattr(ollama_runtime, "_run_command", lambda cmd, timeout: commands.append(cmd))assert ollama_runtime._install_windows() == "installer-exe"assert downloads == [ollama_runtime._WINDOWS_INSTALLER_URL]assert "/VERYSILENT" in commands[0]@@ -225,9 +218,7 @@ def test_installed_but_stopped_only_starts(monkeypatch) -> None:monkeypatch.setattr(ollama_runtime, "_install_windows", lambda: installs.append("x") or "winget")- monkeypatch.setattr(- ollama_runtime, "start_server", lambda: (True, "Ollama started.")- )+ monkeypatch.setattr(ollama_runtime, "start_server", lambda: (True, "Ollama started."))ollama_runtime._run_install()assert installs == [] # nothing was installed — it only needed a startassert ollama_runtime.install_snapshot()["phase"] == "done"@@ -239,9 +230,7 @@ def test_a_failing_step_lands_in_the_error_state(monkeypatch) -> None:"runtime_status",lambda: {"installed": True, "running": False, "detail": "", "version": "", "binary": "b"},)- monkeypatch.setattr(- ollama_runtime, "start_server", lambda: (False, "did not bind")- )+ monkeypatch.setattr(ollama_runtime, "start_server", lambda: (False, "did not bind"))ollama_runtime._run_install()snap = ollama_runtime.install_snapshot()assert snap["phase"] == "error"@@ -252,9 +241,7 @@ def test_second_start_install_joins_instead_of_duplicating(monkeypatch) -> None:import threadingrelease = threading.Event()- monkeypatch.setattr(- ollama_runtime, "_run_install", lambda: release.wait(timeout=5)- )+ monkeypatch.setattr(ollama_runtime, "_run_install", lambda: release.wait(timeout=5))started, _ = ollama_runtime.start_install()assert started is Truejoined, message = ollama_runtime.start_install()@@ -267,7 +254,275 @@ def test_marker_records_the_method(tmp_path: Path) -> None:ollama_runtime._record_marker("winget")import json- payload = json.loads(- (tmp_path / "ollama_installed_by_jarvis.json").read_text(encoding="utf-8")- )+ payload = json.loads((tmp_path / "ollama_installed_by_jarvis.json").read_text(encoding="utf-8"))assert payload["method"] == "winget"+++# ── stop_server: only the pid Jarvis spawned ─────────────────────────────+class _FakeProcess:+ """A psutil.Process stand-in: alive until terminated, named like Ollama."""++ instances: list[_FakeProcess] = []++ def __init__(self, pid: int, name: str = "ollama.exe") -> None:+ self.pid = pid+ self._name = name+ self.terminated = False+ self.killed = False+ _FakeProcess.instances.append(self)++ def name(self) -> str:+ return self._name++ def terminate(self) -> None:+ self.terminated = True++ def kill(self) -> None:+ self.killed = True++ def wait(self, timeout: float | None = None) -> int:+ return 0+++def test_start_records_the_spawned_pid_beside_the_log(monkeypatch, tmp_path) -> None:+ monkeypatch.setattr(ollama_runtime, "_server_version", lambda timeout=1.5: None)+ monkeypatch.setattr(ollama_runtime, "find_binary", lambda: "/usr/bin/ollama")+ monkeypatch.setattr(subprocess, "Popen", lambda argv, **kwargs: SimpleNamespace(pid=4711))+ monkeypatch.setattr(ollama_runtime, "_port_open", lambda port, timeout=1.0: True)+ ok, _ = ollama_runtime.start_server()+ assert ok is True+ import json++ record = json.loads((tmp_path / "ollama_server.pid").read_text(encoding="utf-8"))+ assert record["pid"] == 4711+ assert ollama_runtime._recorded_pid() == 4711+++def test_stop_without_a_pid_file_refuses_honestly() -> None:+ """A server Jarvis did not start is never touched — the sentence says+ where to stop it instead of pretending nothing is running."""+ ok, detail = ollama_runtime.stop_server()+ assert ok is False+ assert "not started by Jarvis" in detail+ assert "stop it where you started it" in detail+++def test_stop_with_a_dead_pid_forgets_the_record(monkeypatch, tmp_path) -> None:+ import psutil++ ollama_runtime._record_pid(99999, "/usr/bin/ollama")++ def gone(pid: int) -> _FakeProcess:+ raise psutil.NoSuchProcess(pid)++ monkeypatch.setattr(psutil, "Process", gone)+ ok, detail = ollama_runtime.stop_server()+ assert ok is False+ assert "no longer running" in detail+ assert not (tmp_path / "ollama_server.pid").exists()+ # The next answer is the plain "not ours" sentence again.+ assert "not started by Jarvis" in ollama_runtime.stop_server()[1]+++def test_stop_terminates_only_the_recorded_ollama_process(monkeypatch, tmp_path) -> None:+ import psutil++ _FakeProcess.instances.clear()+ ollama_runtime._record_pid(4711, "/usr/bin/ollama")+ monkeypatch.setattr(psutil, "Process", _FakeProcess)+ ok, detail = ollama_runtime.stop_server()+ assert ok is True+ assert detail == "Ollama stopped."+ assert [p.pid for p in _FakeProcess.instances] == [4711]+ assert _FakeProcess.instances[0].terminated is True+ assert not (tmp_path / "ollama_server.pid").exists()+++def test_stop_refuses_a_recycled_pid(monkeypatch, tmp_path) -> None:+ """The OS may hand a dead server's pid to an unrelated program; that+ program is never signalled."""+ import psutil++ _FakeProcess.instances.clear()+ ollama_runtime._record_pid(4711, "/usr/bin/ollama")+ monkeypatch.setattr(psutil, "Process", lambda pid: _FakeProcess(pid, "python.exe"))+ ok, detail = ollama_runtime.stop_server()+ assert ok is False+ assert "no longer belongs to Ollama" in detail+ assert _FakeProcess.instances[0].terminated is False+ assert not (tmp_path / "ollama_server.pid").exists()+++# ── tail_log ─────────────────────────────────────────────────────────────+def test_tail_log_without_a_log_is_empty() -> None:+ assert ollama_runtime.tail_log() == []+++def test_tail_log_returns_the_last_lines_utf8_safe(tmp_path) -> None:+ lines = [f"line {i}" for i in range(50)]+ body = "\n".join(lines) + "\n"+ (tmp_path / "ollama_server.log").write_bytes(body.encode("utf-8") + b"bad \xff byte\n")+ tail = ollama_runtime.tail_log(lines=3)+ assert tail == ["line 48", "line 49", "bad \ufffd byte"]+ assert ollama_runtime.tail_log(lines=0) == []+++# ── probe_host ───────────────────────────────────────────────────────────+async def test_probe_host_reports_version_and_latency() -> None:+ import httpx++ seen: list[str] = []++ def handler(request: httpx.Request) -> httpx.Response:+ seen.append(str(request.url))+ return httpx.Response(200, json={"version": "0.32.15"})++ result = await ollama_runtime.probe_host(+ "gpu-box:11434/v1", transport=httpx.MockTransport(handler)+ )+ assert seen == ["http://gpu-box:11434/api/version"]+ assert result["ok"] is True+ assert result["version"] == "0.32.15"+ assert isinstance(result["latency_ms"], int)+ assert "0.32.15" in str(result["detail"])+++async def test_probe_host_names_a_non_ollama_answer() -> None:+ import httpx++ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(404, text="nope")++ result = await ollama_runtime.probe_host(+ "http://web-server:8080", transport=httpx.MockTransport(handler)+ )+ assert result["ok"] is False+ assert "HTTP 404" in str(result["detail"])+ assert "not an Ollama server" in str(result["detail"])+++async def test_probe_host_unreachable_is_one_sentence() -> None:+ import httpx++ def handler(request: httpx.Request) -> httpx.Response:+ raise httpx.ConnectError("connection refused")++ result = await ollama_runtime.probe_host(+ "http://127.0.0.1:9", transport=httpx.MockTransport(handler)+ )+ assert result["ok"] is False+ assert result["version"] == ""+ assert "No Ollama answered at http://127.0.0.1:9" in str(result["detail"])+++# ── env_guide per OS ─────────────────────────────────────────────────────+_ENV_EXPECTED_KEYS = [+ "OLLAMA_HOST",+ "OLLAMA_MODELS",+ "OLLAMA_KEEP_ALIVE",+ "OLLAMA_NUM_PARALLEL",+ "OLLAMA_MAX_LOADED_MODELS",+ "OLLAMA_FLASH_ATTENTION",+ "OLLAMA_KV_CACHE_TYPE",+]+++ ("os_name", "marker"),+ [+ ("windows", "setx OLLAMA_HOST "),+ ("macos", "launchctl setenv OLLAMA_HOST "),+ ("linux", "systemctl edit ollama.service"),+ ],+)+def test_env_guide_recipes_per_os(os_name: str, marker: str) -> None:+ rows = ollama_runtime.env_guide(os_name)+ assert [row["key"] for row in rows] == _ENV_EXPECTED_KEYS+ assert marker in rows[0]["command"]+ for row in rows:+ assert set(row) == {"key", "purpose", "command", "restart"}+ assert row["purpose"].endswith(".") # one plain sentence each+ assert row["key"] in row["command"]+++def test_env_guide_linux_uses_a_systemd_drop_in() -> None:+ row = ollama_runtime.env_guide("linux")[0]+ assert 'Environment="OLLAMA_HOST=0.0.0.0"' in row["command"]+ assert "systemctl restart ollama" in row["restart"]+++def test_env_guide_accepts_platform_spellings() -> None:+ assert ollama_runtime.env_guide("darwin")[0]["command"].startswith("launchctl")+ assert ollama_runtime.env_guide("win32")[0]["command"].startswith("setx")+ assert ollama_runtime.env_guide("nt")[0]["command"].startswith("setx")+++# ── models_dir per OS ────────────────────────────────────────────────────+def test_models_dir_env_override_wins(monkeypatch, tmp_path) -> None:+ monkeypatch.setenv("OLLAMA_MODELS", str(tmp_path / "weights"))+ assert ollama_runtime.models_dir("linux") == tmp_path / "weights"+++def test_models_dir_windows_and_macos_default_to_the_home_folder(monkeypatch, tmp_path) -> None:+ monkeypatch.delenv("OLLAMA_MODELS", raising=False)+ monkeypatch.setattr(ollama_runtime.Path, "home", classmethod(lambda cls: tmp_path))+ assert ollama_runtime.models_dir("windows") == tmp_path / ".ollama" / "models"+ assert ollama_runtime.models_dir("macos") == tmp_path / ".ollama" / "models"+++def test_models_dir_linux_prefers_the_service_user_when_present(monkeypatch, tmp_path) -> None:+ monkeypatch.delenv("OLLAMA_MODELS", raising=False)+ monkeypatch.setattr(ollama_runtime.Path, "home", classmethod(lambda cls: tmp_path))+ monkeypatch.setattr(+ ollama_runtime.Path,+ "is_dir",+ lambda self: self.as_posix() == "/usr/share/ollama/.ollama/models",+ raising=False,+ )+ assert ollama_runtime.models_dir("linux").as_posix() == "/usr/share/ollama/.ollama/models"+ monkeypatch.setattr(ollama_runtime.Path, "is_dir", lambda self: False, raising=False)+ assert ollama_runtime.models_dir("linux") == tmp_path / ".ollama" / "models"+++def test_models_dir_follows_the_running_os_by_default(monkeypatch, tmp_path) -> None:+ monkeypatch.delenv("OLLAMA_MODELS", raising=False)+ monkeypatch.setattr(ollama_runtime, "_current_os", lambda: "macos")+ monkeypatch.setattr(ollama_runtime.Path, "home", classmethod(lambda cls: tmp_path))+ assert ollama_runtime.models_dir() == tmp_path / ".ollama" / "models"+++# ── host_kind + runtime_status shape ─────────────────────────────────────+ ("url", "kind"),+ [+ ("http://127.0.0.1:11434", "local"),+ ("http://localhost:11434", "local"),+ ("http://[::1]:11434", "local"),+ ("http://0.0.0.0:11434", "local"),+ ("http://gpu-box.lan:11434", "remote"),+ ("https://ollama.example.com", "remote"),+ ],+)+def test_host_kind(url: str, kind: str) -> None:+ assert ollama_runtime.host_kind(url) == kind+++def test_host_kind_treats_this_machines_name_as_local(monkeypatch) -> None:+ monkeypatch.setattr(ollama_runtime.socket, "gethostname", lambda: "Studio-PC")+ assert ollama_runtime.host_kind("http://studio-pc:11434") == "local"+ assert ollama_runtime.host_kind("http://studio-pc.local:11434") == "local"+++def test_runtime_status_carries_host_kind_models_dir_and_version(monkeypatch) -> None:+ monkeypatch.setattr(ollama_runtime, "find_binary", lambda: "/usr/bin/ollama")+ monkeypatch.setattr(ollama_runtime, "_server_version", lambda timeout=1.5: "0.32.15")+ monkeypatch.setattr(ollama_runtime, "_server_root", lambda: "http://gpu-box:11434")+ monkeypatch.setenv("OLLAMA_MODELS", "/srv/weights")+ status = ollama_runtime.runtime_status()+ assert status["version"] == "0.32.15"+ assert status["host_kind"] == "remote"+ assert status["base_url"] == "http://gpu-box:11434"+ assert Path(str(status["models_dir"])) == Path("/srv/weights")diff --git a/tests/unit/realtime/test_brain_link.py b/tests/unit/realtime/test_brain_link.pynew file mode 100644index 0000000000..0ca3cb9e16--- /dev/null+++ b/tests/unit/realtime/test_brain_link.py@@ -0,0 +1,40 @@+"""The voice brain talks to the SAME Ollama as every other role.++Pins the address resolution of ``brain_link._ollama_base``: ``OLLAMA_HOST``+keeps the vendor's own convention, and without it the configured+``[brain.providers.ollama].base_url`` override reaches the voice brain too —+a remote setup no longer splits the voice brain from chat, wiki and ack.+"""++from __future__ import annotations++import pytest++from jarvis.brain import ollama_pull+from jarvis.realtime.local_server import brain_link++[email protected](autouse=True)+def _no_env_host(monkeypatch):+ monkeypatch.delenv("OLLAMA_HOST", raising=False)+++def test_env_host_still_wins_and_is_normalized(monkeypatch) -> None:+ monkeypatch.setenv("OLLAMA_HOST", "gpu-box:11434/")+ monkeypatch.setattr(+ ollama_pull, "server_root", lambda: pytest.fail("config must not be consulted")+ )+ assert brain_link._ollama_base() == "http://gpu-box:11434"+++def test_without_env_the_shared_configured_root_is_used(monkeypatch) -> None:+ monkeypatch.setattr(ollama_pull, "server_root", lambda: "http://lan-box:11434/")+ assert brain_link._ollama_base() == "http://lan-box:11434"+++def test_an_unreadable_config_falls_back_to_the_vendor_default(monkeypatch) -> None:+ def boom() -> str:+ raise RuntimeError("config unreadable")++ monkeypatch.setattr(ollama_pull, "server_root", boom)+ assert brain_link._ollama_base() == brain_link._OLLAMA_DEFAULTdiff --git a/tests/unit/ultrawiki/test_embeddings.py b/tests/unit/ultrawiki/test_embeddings.pyindex cfcc3f38f0..5cdb5669ba 100644--- a/tests/unit/ultrawiki/test_embeddings.py+++ b/tests/unit/ultrawiki/test_embeddings.py@@ -481,3 +481,40 @@ def test_a_body_without_a_code_still_yields_an_honest_error(fake_secrets):import asyncioasyncio.run(backend.embed(["hello"], model="m"))+++# ---------------------------------------------------------------------------+# One Ollama address for every role (jarvis.ultrawiki.embeddings._make_ollama)+# ---------------------------------------------------------------------------+++def test_make_ollama_falls_back_to_the_shared_root_when_the_wiki_key_is_empty(+ monkeypatch,+):+ monkeypatch.setattr(emb, "_shared_ollama_root", lambda: "http://lan-box:11434")+ cfg = SimpleNamespace(ultrawiki=SimpleNamespace(ollama_endpoint=""))+ assert emb._make_ollama(cfg)._endpoint == "http://lan-box:11434"+++def test_make_ollama_treats_the_shipped_localhost_default_as_unset(monkeypatch):+ """The config ships ``http://localhost:11434`` as its default; a user who+ moved the brain to a remote box did not choose that value, so the wiki+ follows the brain instead of talking to an empty localhost."""+ monkeypatch.setattr(emb, "_shared_ollama_root", lambda: "http://lan-box:11434")+ cfg = SimpleNamespace(ultrawiki=SimpleNamespace(ollama_endpoint=emb._DEFAULT_OLLAMA_ENDPOINT))+ assert emb._make_ollama(cfg)._endpoint == "http://lan-box:11434"+++def test_make_ollama_keeps_an_explicit_wiki_endpoint(monkeypatch):+ monkeypatch.setattr(emb, "_shared_ollama_root", lambda: pytest.fail("own value must win"))+ cfg = SimpleNamespace(ultrawiki=SimpleNamespace(ollama_endpoint="http://box:9999"))+ assert emb._make_ollama(cfg)._endpoint == "http://box:9999"+++def test_make_ollama_survives_an_unreadable_config(monkeypatch):+ def boom() -> str:+ raise RuntimeError("config unreadable")++ monkeypatch.setattr(emb, "_shared_ollama_root", boom)+ cfg = SimpleNamespace(ultrawiki=SimpleNamespace(ollama_endpoint=""))+ assert emb._make_ollama(cfg)._endpoint == emb._DEFAULT_OLLAMA_ENDPOINT