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(providers): ollama runtime routes — status, install, start
rubenluetke10-beepb509e3607f83
diff --git a/jarvis/ui/web/frontend/src/hooks/useProviders.ts b/jarvis/ui/web/frontend/src/hooks/useProviders.tsindex a5f7a74285..669e87b8f4 100644--- a/jarvis/ui/web/frontend/src/hooks/useProviders.ts+++ b/jarvis/ui/web/frontend/src/hooks/useProviders.ts@@ -960,6 +960,63 @@ export async function managedServerUninstall(): Promise<void> {}}+/** Live picture of the Ollama runtime itself (mirror of ollama_runtime). */+export interface OllamaRuntimeStatus {+ installed: boolean;+ binary: string;+ running: boolean;+ version: string;+ /** One honest backend sentence — render verbatim. */+ detail: string;+}++/** Poll-shaped progress of the Ollama runtime installer. */+export interface OllamaRuntimeInstallProgress {+ phase: string;+ percent: number;+ detail: string;+ error: string;+ running: boolean;+ log_tail: string[];+ started?: boolean;+ message?: string;+}++export async function ollamaRuntime(providerId: string): Promise<{+ status: OllamaRuntimeStatus;+ install: OllamaRuntimeInstallProgress;+}> {+ const res = await fetch(`/api/providers/${providerId}/ollama-runtime`);+ const body = await res.json().catch(() => ({}));+ if (!res.ok) throw new Error(body.detail ?? `HTTP ${res.status}`);+ return body as {+ status: OllamaRuntimeStatus;+ install: OllamaRuntimeInstallProgress;+ };+}++export async function ollamaRuntimeInstall(+ providerId: string,+): Promise<OllamaRuntimeInstallProgress> {+ const res = await fetch(`/api/providers/${providerId}/ollama-runtime/install`, {+ method: "POST",+ });+ const body = await res.json().catch(() => ({}));+ if (!res.ok) throw new Error(body.detail ?? `HTTP ${res.status}`);+ return body as OllamaRuntimeInstallProgress;+}++export async function ollamaRuntimeStart(+ providerId: string,+): Promise<OllamaRuntimeStatus | null> {+ const res = await fetch(`/api/providers/${providerId}/ollama-runtime/start`, {+ method: "POST",+ });+ const body = await res.json().catch(() => ({}));+ if (!res.ok) throw new Error(body.detail ?? `HTTP ${res.status}`);+ return (body.status ?? null) as OllamaRuntimeStatus | null;+}+/** The job a local model fills — mirror of `ollama_pull.Role`. */export type PullableRole = "chat" | "vision" | "coder" | "embedding";diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.pyindex 7bcfa54230..9657bd5df1 100644--- a/jarvis/ui/web/provider_routes.py+++ b/jarvis/ui/web/provider_routes.py@@ -20,6 +20,7 @@ from __future__ import annotationsimport asyncioimport inspectimport logging+import threadingimport timefrom collections.abc import Mappingfrom types import SimpleNamespace@@ -2725,6 +2726,81 @@ def _local_realtime_card(request: Request) -> tuple[str, str]:)+_MANAGED_WARM_TASK_ATTR = "_managed_local_realtime_warm_task"+_MANAGED_WARM_CANCEL_ATTR = "_managed_local_realtime_warm_cancel"+++async def _finish_managed_server_warm(+ base_url: str,+ command: str,+ cancel_event: threading.Event,+) -> None:+ """Wait off-request for managed readiness, then warm its brain."""+ from jarvis.realtime.local_server import supervisor++ try:+ managed = await asyncio.to_thread(+ supervisor.is_managed_launch_command,+ command,+ )+ if not managed or cancel_event.is_set():+ return+ ready = await asyncio.to_thread(+ lambda: supervisor.wait_until_ready(+ base_url,+ timeout=supervisor.RUNTIME_READY_TIMEOUT_S,+ launch_command=command,+ cleanup_on_timeout=True,+ cancel_event=cancel_event,+ )+ )+ if ready and not cancel_event.is_set():+ await asyncio.to_thread(+ lambda: supervisor.warm_brain(launch_command=command)+ )+ except asyncio.CancelledError:+ cancel_event.set()+ raise+ except Exception: # noqa: BLE001 - background warming is best-effort+ log.warning("managed local-realtime warm-up failed", exc_info=True)+++def _schedule_managed_server_warm(request: Request, base_url: str, command: str) -> None:+ """Keep exactly one background readiness/warm task per web app."""+ state = request.app.state+ active = getattr(state, _MANAGED_WARM_TASK_ATTR, None)+ if active is not None and not active.done():+ return+ cancel_event = threading.Event()+ task = asyncio.create_task(+ _finish_managed_server_warm(base_url, command, cancel_event),+ name="managed-local-realtime-warm",+ )+ setattr(state, _MANAGED_WARM_TASK_ATTR, task)+ setattr(state, _MANAGED_WARM_CANCEL_ATTR, cancel_event)++ def _clear(done: asyncio.Task[None]) -> None:+ if getattr(state, _MANAGED_WARM_TASK_ATTR, None) is done:+ setattr(state, _MANAGED_WARM_TASK_ATTR, None)+ setattr(state, _MANAGED_WARM_CANCEL_ATTR, None)++ task.add_done_callback(_clear)+++async def _cancel_managed_server_warm(request: Request) -> None:+ """Join the warm worker before a deliberate server stop."""+ state = request.app.state+ cancel_event = getattr(state, _MANAGED_WARM_CANCEL_ATTR, None)+ if cancel_event is not None:+ cancel_event.set()+ task = getattr(state, _MANAGED_WARM_TASK_ATTR, None)+ if task is not None and not task.done():+ try:+ await task+ except asyncio.CancelledError:+ pass++@router.get("/providers/local-realtime/managed-server/status")async def managed_server_status(request: Request) -> dict[str, Any]:"""Install progress, the fail-closed readiness probe, AND the live runtime.@@ -2768,10 +2844,11 @@ async def managed_server_start(request: Request) -> dict[str, Any]:)if outcome.startswith("refused:"):raise HTTPException(status_code=409, detail=outcome)- # Make the brain model resident too — a started server whose brain still- # cold-loads on the first sentence is only half a start.- await asyncio.to_thread(lambda: supervisor.warm_brain(launch_command=command))runtime = await asyncio.to_thread(supervisor.status, base_url)+ # Return immediately even on a cold spawn. The background task waits for+ # the speech pool before warming Ollama, preserving GPU load order without+ # making the REST request pay a 120-second startup window.+ _schedule_managed_server_warm(request, base_url, command)return {"ok": True, "outcome": outcome, "runtime": runtime}@@ -2782,6 +2859,7 @@ async def managed_server_stop(request: Request) -> dict[str, Any]:from jarvis.realtime.local_server.install import install_rootbase_url, _command = _local_realtime_card(request)+ await _cancel_managed_server_warm(request)changed, message = await asyncio.to_thread(lambda: supervisor.stop(owned_only=True, install_root=install_root()))@@ -2929,6 +3007,58 @@ async def get_model_pull_status(provider_id: str, model: str) -> dict[str, Any]:return await pull_status(model)[email protected]("/providers/{provider_id}/ollama-runtime")+async def get_ollama_runtime(provider_id: str) -> dict[str, Any]:+ """The Ollama runtime picture behind a pull-capable card.++ Three honest states — not installed / installed but stopped / running —+ each needing a DIFFERENT button (install vs start), which a pure HTTP+ reachability probe cannot distinguish. Pairs the live status with the+ poll-shaped install progress so one fetch drives the whole panel.+ """+ _require_pull_capable(provider_id)+ from jarvis.brain.ollama_runtime import install_snapshot, runtime_status++ status = await asyncio.to_thread(runtime_status)+ return {"status": status, "install": install_snapshot()}+++ "/providers/{provider_id}/ollama-runtime/install",+ openapi_extra={"x-jarvis-dangerous": True},+)+async def start_ollama_runtime_install(provider_id: str) -> dict[str, Any]:+ """Install Ollama itself, without a terminal (§3: recoverable in-app).++ Dangerous-flagged: this installs third-party software (from official+ ollama.com artifacts only) and sits behind an explicit confirm in the+ UI. Returns immediately with the poll snapshot; a second call while an+ install runs joins it instead of duplicating it. Platforms where no+ silent install exists answer honestly through the snapshot's error.+ """+ _require_pull_capable(provider_id)+ from jarvis.brain.ollama_runtime import install_snapshot, start_install++ started, message = await asyncio.to_thread(start_install)+ payload = install_snapshot()+ payload["started"] = started+ payload["message"] = message+ return payload++[email protected]("/providers/{provider_id}/ollama-runtime/start")+async def start_ollama_runtime(provider_id: str) -> dict[str, Any]:+ """Start an installed-but-stopped Ollama and wait for its port."""+ _require_pull_capable(provider_id)+ from jarvis.brain.ollama_runtime import runtime_status, start_server++ ok, detail = await asyncio.to_thread(start_server)+ if not ok:+ raise HTTPException(status_code=409, detail=detail)+ status = await asyncio.to_thread(runtime_status)+ return {"ok": True, "detail": detail, "status": status}++@router.get("/providers/{provider_id}/cu-model")async def get_cu_model(provider_id: str, request: Request) -> CuModelResponse:"""Return the per-provider Computer-Use model selection (Phase 3).diff --git a/tests/unit/ui/web/test_ollama_runtime_routes.py b/tests/unit/ui/web/test_ollama_runtime_routes.pynew file mode 100644index 0000000000..5004f57799--- /dev/null+++ b/tests/unit/ui/web/test_ollama_runtime_routes.py@@ -0,0 +1,123 @@+"""Routes for the in-app Ollama runtime lifecycle (install / start / status).++Pins: the status route pairs the three-state runtime truth with the install+snapshot, the install route is dangerous-flagged and returns immediately,+the start route answers 409 with the honest reason when starting cannot+succeed, and none of it exists on cards whose server has no pull API.+"""++from __future__ import annotations++import pytest+from fastapi.testclient import TestClient++from jarvis.brain import ollama_runtime+from jarvis.core.bus import EventBus+from jarvis.core.config import JarvisConfig+from jarvis.ui.web.server import WebServer+++def server(tmp_path, monkeypatch: pytest.MonkeyPatch) -> WebServer:+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ ollama_runtime._reset_for_tests()+ cfg = JarvisConfig()+ cfg.ui.dev_mode = True+ srv = WebServer(cfg, bus=EventBus())+ srv.app.state.config = cfg+ yield srv+ ollama_runtime._reset_for_tests()+++def test_status_pairs_runtime_with_install_snapshot(+ server: WebServer, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(+ ollama_runtime,+ "runtime_status",+ lambda: {+ "installed": True,+ "binary": "x",+ "running": False,+ "version": "",+ "detail": "Ollama is installed but not running.",+ },+ )+ with TestClient(server.app) as client:+ resp = client.get("/api/providers/ollama/ollama-runtime")+ assert resp.status_code == 200+ body = resp.json()+ assert body["status"]["installed"] is True+ assert body["status"]["running"] is False+ assert body["install"]["phase"] == "idle"+++def test_runtime_routes_refuse_non_pull_capable_cards(server: WebServer) -> None:+ """A cloud card has no runtime to manage — 400, never a silent no-op."""+ with TestClient(server.app) as client:+ resp = client.get("/api/providers/openai/ollama-runtime")+ assert resp.status_code == 400+++def test_install_returns_immediately_with_the_snapshot(+ server: WebServer, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(+ ollama_runtime, "start_install", lambda: (True, "install started")+ )+ with TestClient(server.app) as client:+ resp = client.post("/api/providers/ollama/ollama-runtime/install")+ assert resp.status_code == 200+ body = resp.json()+ assert body["started"] is True+ assert body["message"] == "install started"+ assert "phase" in body+++def test_install_route_is_dangerous_flagged(server: WebServer) -> None:+ """Installing third-party software must carry the danger marker the CLI+ and permission layers key on."""+ schema = server.app.openapi()+ op = schema["paths"]["/api/providers/{provider_id}/ollama-runtime/install"][+ "post"+ ]+ assert op.get("x-jarvis-dangerous") is True+++def test_start_answers_409_with_the_honest_reason(+ server: WebServer, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(+ ollama_runtime,+ "start_server",+ lambda: (False, "Ollama is not installed — install it first."),+ )+ with TestClient(server.app) as client:+ resp = client.post("/api/providers/ollama/ollama-runtime/start")+ assert resp.status_code == 409+ assert "install" in resp.json()["detail"]+++def test_start_reports_the_fresh_status(+ server: WebServer, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(+ ollama_runtime, "start_server", lambda: (True, "Ollama started.")+ )+ monkeypatch.setattr(+ ollama_runtime,+ "runtime_status",+ lambda: {+ "installed": True,+ "binary": "x",+ "running": True,+ "version": "0.9.1",+ "detail": "Ollama is running (version 0.9.1).",+ },+ )+ with TestClient(server.app) as client:+ resp = client.post("/api/providers/ollama/ollama-runtime/start")+ assert resp.status_code == 200+ body = resp.json()+ assert body["ok"] is True+ assert body["status"]["running"] is True