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(realtime): managed install brings its own brain
rubenluetke10-beep4ad1b708bb77
diff --git a/jarvis/brain/ollama_pull.py b/jarvis/brain/ollama_pull.pyindex 3a2b5c51d2..c2b53f4f73 100644--- a/jarvis/brain/ollama_pull.py+++ b/jarvis/brain/ollama_pull.py@@ -121,6 +121,15 @@ RECOMMENDED_MODELS: tuple[RecommendedModel, ...] = (size_gb=6.6,purpose="The balanced default: chat, voice, and reliable tool calling.",),+ RecommendedModel(+ id="qwen2.5:7b",+ label="Qwen 2.5 7B",+ size_gb=4.7,+ # The measured brain of the local realtime voice stack (tiers.py+ # t0/t1): the managed install's brain-setup pulls THIS tag, so the+ # panel must list it too — two curated lists must not drift apart.+ purpose="The local realtime voice stack's measured brain model.",+ ),RecommendedModel(id="gpt-oss:20b",label="GPT-OSS 20B",diff --git a/jarvis/brain/ollama_runtime.py b/jarvis/brain/ollama_runtime.pyindex 277ad9ebf0..6c8ecd8c0a 100644--- a/jarvis/brain/ollama_runtime.py+++ b/jarvis/brain/ollama_runtime.py@@ -445,6 +445,35 @@ def _install_linux() -> str:return "install-script"+def ensure_runtime_blocking() -> tuple[bool, str]:+ """Install (when absent) and start Ollama, synchronously. ``(ok, detail)``.++ For callers that already run on their own worker thread with their own+ progress surface (the managed realtime install engine): same steps as+ the poll-shaped installer, but inline and never raising — the caller+ owns the phase reporting.+ """+ try:+ status = runtime_status()+ if status["running"]:+ return True, "Ollama is already running."+ if not status["installed"]:+ if os.name == "nt":+ method = _install_windows()+ elif sys.platform == "darwin":+ method = _install_macos()+ else:+ method = _install_linux()+ _record_marker(method)+ if not find_binary():+ return False, (+ "the Ollama installer finished but no binary was found"+ )+ return start_server()+ except Exception as exc: # noqa: BLE001 — honest sentence, never a raise+ return False, str(exc)++def _run_install() -> None:try:status = runtime_status()diff --git a/jarvis/realtime/local_server/install.py b/jarvis/realtime/local_server/install.pyindex 7fca033ed2..ed07d66522 100644--- a/jarvis/realtime/local_server/install.py+++ b/jarvis/realtime/local_server/install.py@@ -44,6 +44,7 @@ from jarvis.realtime.local_server.preflight import (log = logging.getLogger(__name__)_PINS_FILE = Path(__file__).parent / "pins" / f"core-{PATCH_TARGET_VERSION}.txt"+_SMOKE_MARKER_SCHEMA = 1#: torch flavor per probed hardware. The CUDA build ships from the PyTorch#: index; everything else takes the default wheels (macOS arm64 wheels carry@@ -114,6 +115,42 @@ def _smoke_marker() -> Path:return install_root() / "smoke_ok.json"+def _smoke_marker_valid() -> bool:+ """Validate the durable proof for this exact pinned server build."""+ try:+ payload = json.loads(_smoke_marker().read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return False+ if not isinstance(payload, dict):+ return False+ at = payload.get("at")+ valid_at = (+ isinstance(at, (int, float)) and not isinstance(at, bool) and at > 0.0+ )+ return (+ payload.get("schema") == _SMOKE_MARKER_SCHEMA+ and payload.get("patch_version") == PATCH_TARGET_VERSION+ and valid_at+ and isinstance(payload.get("tier"), str)+ and bool(payload.get("tier"))+ and payload.get("brain") in {"ollama", "cloud-openai"}+ and isinstance(payload.get("preflight"), dict)+ )+++def _invalidate_smoke_marker() -> None:+ """Remove old success proof before any reinstall can mutate the venv."""+ _smoke_marker().unlink(missing_ok=True)+++def _write_smoke_marker(payload: dict[str, object]) -> None:+ """Durably publish success only after the smoke child was fully reaped."""+ from jarvis.realtime.local_server.supervisor import _atomic_write_json++ if not _atomic_write_json(_smoke_marker(), payload):+ raise OSError("could not atomically write the managed-server smoke marker")++@dataclassclass _State:phase: str = "idle"@@ -219,7 +256,7 @@ def server_status() -> dict[str, object]:"venv": _venv_python().exists(),"entrypoint": _server_entrypoint().exists(),"patch": patch_state(_site_packages()) == "patched",- "smoke_boot": _smoke_marker().exists(),+ "smoke_boot": _smoke_marker_valid(),}ready = all(components.values())command = _configured_launch_command()@@ -264,6 +301,7 @@ def derive_launch_command(brain: BrainResolution, *, memory_source: str) -> str:parts = [f'"{_server_entrypoint()}"',"--mode realtime",+ "--ws_host 127.0.0.1","--tts qwen3",f"--qwen3_tts_device {tts_device}","--qwen3_tts_dtype bfloat16",@@ -291,6 +329,12 @@ def _run(cmd: list[str], *, timeout: int, cwd: Path | None = None) -> None:"""env = dict(os.environ)env.setdefault("PYTHONIOENCODING", "utf-8")+ popen_kwargs: dict[str, object] = {}+ if os.name != "nt":+ # The timeout path kills this process group. Without a fresh session,+ # pip's build-backend children can outlive the launcher and continue+ # mutating the venv after the lifecycle lease is released.+ popen_kwargs["start_new_session"] = Trueproc = subprocess.Popen(cmd,stdout=subprocess.PIPE,@@ -301,6 +345,7 @@ def _run(cmd: list[str], *, timeout: int, cwd: Path | None = None) -> None:cwd=str(cwd) if cwd else None,env=env,creationflags=NO_WINDOW_CREATIONFLAGS,+ **popen_kwargs, # type: ignore[arg-type])def _pump() -> None:@@ -324,14 +369,16 @@ def _run(cmd: list[str], *, timeout: int, cwd: Path | None = None) -> None:raise RuntimeError(f"step failed (exit {code}): {' '.join(cmd[:3])}…")-def _kill_tree(proc: subprocess.Popen) -> None:+def _kill_tree(proc: subprocess.Popen) -> bool:"""Terminate a step's whole process tree, not just the launcher.- POSIX: the smoke boot spawns with ``start_new_session=True``, so the pid- is its process-group leader — SIGTERM the group, grace, then SIGKILL what- remains. Terminating only the launcher (the old behavior) orphaned the- server's worker processes, which then kept the GPU and the smoke port.+ POSIX: every installer child spawns with ``start_new_session=True``, so+ the pid is its process-group leader — SIGTERM the group, grace, then+ SIGKILL what remains. Terminating only the launcher (the old behavior)+ orphaned build backends and server workers."""+ if proc.poll() is not None:+ return Truetry:if os.name == "nt":subprocess.run(@@ -340,6 +387,11 @@ def _kill_tree(proc: subprocess.Popen) -> None:timeout=30,creationflags=NO_WINDOW_CREATIONFLAGS,)+ try:+ proc.wait(timeout=10)+ except subprocess.TimeoutExpired:+ return False+ return proc.poll() is not Noneelse:import signal@@ -355,8 +407,10 @@ def _kill_tree(proc: subprocess.Popen) -> None:except (ProcessLookupError, PermissionError, OSError):proc.kill()proc.wait(timeout=10)- except Exception: # pragma: no cover — best-effort teardown+ return proc.poll() is not None+ except Exception: # pragma: no cover - teardown failure is reported by callerlog.warning("local-realtime install: process-tree teardown incomplete", exc_info=True)+ return Falsedef _port_open(port: int, timeout: float = 1.0) -> bool:@@ -371,7 +425,8 @@ def _smoke_boot(launch_command: str, brain: BrainResolution) -> None:"""Boot the freshly installed server once on a throwaway port.Proves the whole stack (imports, patched service, model downloads into- the HF cache, port bind) before the install may call itself ready.+ the HF cache, and a live model pool) before the install may call itself+ ready. A TCP bind alone is not model readiness.Mirrors the adapter's revive spawn exactly: raw string on Windows,shlex on POSIX, and the same hardening environment.@@ -390,7 +445,11 @@ def _smoke_boot(launch_command: str, brain: BrainResolution) -> None:# The one shared hardening env (faulthandler, unbuffered, HF symlinks on# Windows) — the same the supervisor gives the real server, so the smoke# boot proves the environment the production spawn will actually use.- from jarvis.realtime.local_server.supervisor import hardened_child_env+ from jarvis.realtime.local_server.supervisor import (+ _kill_by_install_root,+ hardened_child_env,+ probe_runtime,+ )env = hardened_child_env(inject_openai_key=False)if brain.kind == "cloud-openai" and brain.api_key:@@ -416,10 +475,11 @@ def _smoke_boot(launch_command: str, brain: BrainResolution) -> None:raise RuntimeError(f"server exited during smoke boot (code {proc.returncode}); see {smoke_log}")- if _port_open(_SMOKE_PORT):+ pool = probe_runtime(f"http://127.0.0.1:{_SMOKE_PORT}", timeout=1.0)+ if pool is not None:# The port pre-check above makes this OUR server; still# require the process to be alive at success so a crash- # racing the poll cannot slip through.+ # racing the pool response cannot slip through.if proc.poll() is not None:raise RuntimeError(f"server exited right after binding (code {proc.returncode}); "@@ -431,7 +491,12 @@ def _smoke_boot(launch_command: str, brain: BrainResolution) -> None:time.sleep(5)raise TimeoutError(f"server did not come up within {_SMOKE_TIMEOUT_S}s; see {smoke_log}")finally:- _kill_tree(proc)+ tree_stopped = _kill_tree(proc)+ _swept, survivors = _kill_by_install_root(install_root())+ if survivors or (not tree_stopped and proc.poll() is None):+ raise RuntimeError(+ f"smoke-boot process {proc.pid} survived teardown; see {smoke_log}"+ )def start_install(*, confirmed_brain: str = "") -> tuple[bool, str]:@@ -464,9 +529,110 @@ def start_install(*, confirmed_brain: str = "") -> tuple[bool, str]:def _run_install(confirmed_brain: str = "") -> None:+ """Hold the cross-process server lifecycle lease for the whole install."""+ from jarvis.realtime.local_server import supervisor++ with supervisor.lifecycle_guard() as guarded:+ if not guarded:+ _fail("another local-realtime lifecycle operation is already running")+ return+ _run_install_guarded(confirmed_brain)+++def _pull_brain_model(model: str) -> None:+ """Pull one Ollama model synchronously, forwarding progress into the state.++ The pull machinery is async and keeps its download task on the calling+ loop, so the WHOLE pull must live inside one ``asyncio.run`` — starting+ it in one loop and polling from another would orphan the task the+ moment the first loop closes.+ """+ import asyncio++ async def _pull_and_wait() -> None:+ from jarvis.brain.ollama_pull import pull_status, start_pull++ first = await start_pull(model)+ if str(first.get("state")) == "error":+ raise RuntimeError(str(first.get("message") or "model download failed"))+ deadline = time.monotonic() + 3600+ while time.monotonic() < deadline:+ status = await pull_status(model)+ state = str(status.get("state"))+ if state == "done":+ return+ if state == "error":+ raise RuntimeError(+ str(+ status.get("error")+ or status.get("message")+ or "model download failed"+ )+ )+ percent = float(status.get("percent") or 0.0)+ _set(+ "brain-setup",+ 6,+ f"downloading the brain model {model} ({percent:.0f}%)",+ )+ await asyncio.sleep(3)+ raise TimeoutError(f"the brain model download did not finish: {model}")++ asyncio.run(_pull_and_wait())+++def resolve_brain_for_install() -> BrainResolution:+ """The brain resolution the install engine trusts (own seam for tests)."""+ from jarvis.realtime.local_server.brain_link import resolve_brain+ from jarvis.realtime.local_server.preflight import (+ _preferred_brain_model,+ _usable_accelerator_gb,+ )++ usable_gb, _source = _usable_accelerator_gb()+ return resolve_brain(+ preferred_model=_preferred_brain_model(), usable_gb=usable_gb+ )+++def _setup_local_brain() -> None:+ """Make the Ollama brain real: runtime installed + running + model present.++ The single-click promise (maintainer directive 2026-08-08): selecting+ local models must never end in a terminal command. Raises with the+ honest platform reason when a silent setup is impossible — the install+ then fails with that exact sentence instead of a generic one.+ """+ from jarvis.brain import ollama_runtime+ from jarvis.realtime.local_server.brain_link import _PREFERRED_MODELS++ _set("brain-setup", 4, "setting up the local brain (Ollama)")+ ok, detail = ollama_runtime.ensure_runtime_blocking()+ if not ok:+ raise RuntimeError(detail)+ if resolve_brain_for_install().ok:+ return+ _set("brain-setup", 5, "no usable brain model yet — downloading one")+ _pull_brain_model(_PREFERRED_MODELS[0])+++def _run_install_guarded(confirmed_brain: str = "") -> None:try:_set("preflight", 2, "checking hardware, disk, and brain")report: PreflightReport = run_preflight(install_root())+ if (+ not report.ok+ and confirmed_brain == "ollama"+ and report.tier is not None+ and report.brain is not None+ and report.brain.kind == "blocked"+ ):+ # Hardware and disk are fine; only the BRAIN is missing — and+ # the user just confirmed a fully-local install. Set it up+ # (install/start Ollama, pull the model) and check again.+ _setup_local_brain()+ _set("preflight", 7, "re-checking after the brain setup")+ report = run_preflight(install_root())if not report.ok:_fail(report.blocker)return@@ -487,9 +653,22 @@ def _run_install(confirmed_brain: str = "") -> None:try:from jarvis.realtime.local_server import supervisor- supervisor.stop(owned_only=True, install_root=install_root())- except Exception: # noqa: BLE001 — best effort, the install continues- log.debug("install: pre-install server stop failed", exc_info=True)+ stopped, stop_message = supervisor._stop_owned_unlocked(+ owned_only=True,+ install_root=install_root(),+ )+ if not stopped and stop_message != "no owned server process found":+ _fail(f"could not stop the existing managed server: {stop_message}")+ return+ except Exception as exc: # noqa: BLE001 - never install under a live server+ log.warning("install: pre-install server stop failed", exc_info=True)+ _fail(f"could not stop the existing managed server safely: {exc}")+ return++ # From this point onward a failure means the previous installation is+ # no longer proven. Invalidate before the first venv mutation so a+ # failed reinstall can never leave stale "ready" evidence behind.+ _invalidate_smoke_marker()if not _venv_python().exists():_set("venv", 8, "creating the server's Python environment")@@ -519,17 +698,15 @@ def _run_install(confirmed_brain: str = "") -> None:_smoke_boot(launch_command, report.brain)_set("configure", 96, "writing the launch configuration")- _smoke_marker().write_text(- json.dumps(- {- "at": time.time(),- "tier": report.tier.key,- "brain": report.brain.kind,- "preflight": report_payload(report),- },- indent=2,- ),- encoding="utf-8",+ _write_smoke_marker(+ {+ "schema": _SMOKE_MARKER_SCHEMA,+ "patch_version": PATCH_TARGET_VERSION,+ "at": time.time(),+ "tier": report.tier.key,+ "brain": report.brain.kind,+ "preflight": report_payload(report),+ })from jarvis.core.config_writer import set_local_realtime_launch_command@@ -545,31 +722,6 @@ def _run_install(confirmed_brain: str = "") -> None:_fail(str(exc))-def _stop_managed_server(root: Path) -> None:- """Best-effort stop of any process running out of the install tree.-- Deleting a venv under a LIVE server is exactly the mid-tree abort the- 2026-08-07 screenshot showed (WinError 2 deep inside site-packages).- psutil is optional; without it the tolerant rmtree below still carries- the removal, just with more retries.- """- try:- import psutil # type: ignore[import-untyped]- except ImportError:- log.debug("uninstall: psutil unavailable — skipping process stop")- return- needle = str(root).lower()- for proc in psutil.process_iter(["pid", "exe", "cmdline"]):- try:- exe = (proc.info.get("exe") or "").lower()- cmdline = " ".join(proc.info.get("cmdline") or ()).lower()- if needle in exe or needle in cmdline:- proc.kill()- proc.wait(timeout=10)- except (psutil.Error, OSError): # pragma: no cover — best effort- continue--def _rmtree_tolerant(root: Path) -> None:"""Remove a multi-gigabyte tree without dying on races or stale handles.@@ -624,6 +776,16 @@ def _clear_managed_config(root: Path) -> None:def uninstall() -> tuple[bool, str]:+ """Serialize the entire removal against every server lifecycle action."""+ from jarvis.realtime.local_server import supervisor++ with supervisor.lifecycle_guard() as guarded:+ if not guarded:+ return False, "another local-realtime lifecycle operation is already running"+ return _uninstall_guarded()+++def _uninstall_guarded() -> tuple[bool, str]:"""Stop the managed server, delete its tree, and clear its config."""with _LOCK:if _STATE.thread is not None and _STATE.thread.is_alive():@@ -635,11 +797,16 @@ def uninstall() -> tuple[bool, str]:try:from jarvis.realtime.local_server import supervisor- supervisor.stop(owned_only=True, install_root=root)+ stopped, stop_message = supervisor._stop_owned_unlocked(+ owned_only=True,+ install_root=root,+ )+ if not stopped and stop_message != "no owned server process found":+ return False, f"could not stop the managed server safely: {stop_message}"supervisor.clear_pidfile()- except Exception: # noqa: BLE001 — the needle scan below still runs- log.debug("uninstall: supervisor stop failed", exc_info=True)- _stop_managed_server(root)+ except Exception as exc: # noqa: BLE001 - never delete under a live server+ log.warning("uninstall: supervisor stop failed", exc_info=True)+ return False, f"could not stop the managed server safely: {exc}"try:_rmtree_tolerant(root)except OSError as exc:diff --git a/jarvis/realtime/local_server/preflight.py b/jarvis/realtime/local_server/preflight.pyindex f0cd516ca2..2870ce442e 100644--- a/jarvis/realtime/local_server/preflight.py+++ b/jarvis/realtime/local_server/preflight.py@@ -179,6 +179,16 @@ def report_payload(report: PreflightReport) -> dict[str, object]:"ok": report.ok,"blocker": report.blocker,"actions": list(report.actions),+ # Hardware and disk pass but the BRAIN is blocked: the one blocked+ # state the install can fix ITSELF (install/start Ollama, pull the+ # model). The card keeps the Install button alive on this flag with+ # an honest note about the extra downloads.+ "brain_fixable": (+ not report.ok+ and tier is not None+ and report.brain is not None+ and report.brain.kind == "blocked"+ ),"usable_gb": round(report.usable_gb, 1),"memory_source": report.memory_source,"disk_free_gb": round(report.disk_free_gb, 1),diff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsxindex df19b5c7ea..b4693c68cd 100644--- a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx+++ b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx@@ -2000,7 +2000,11 @@ function ManagedServerPanel({const startInstall = async () => {setError(null);try {- const first = await managedServerInstall(preflight?.brain?.kind);+ // A fixable blocked brain is CONFIRMED as "ollama": the engine sets it+ // up first and its post-setup re-check must match this confirmation.+ const first = await managedServerInstall(+ preflight?.brain_fixable ? "ollama" : preflight?.brain?.kind,+ );setProgress(first);// A failure BEFORE the first poll tick (fast preflight error inside// the engine thread) would otherwise never render: the polling@@ -2205,7 +2209,7 @@ function ManagedServerPanel({</Button>)}- {!status.ready && !running && preflight && !preflight.ok && (+ {!status.ready && !running && preflight && !preflight.ok && !preflight.brain_fixable && (<div className="space-y-2 text-xs"><p className="text-amber-500">{preflight.blocker}</p><ul className="list-disc space-y-0.5 pl-4 text-muted-foreground">@@ -2213,40 +2217,39 @@ function ManagedServerPanel({<li key={action}>{action}</li>))}</ul>- {/* A blocked BRAIN is fixable right here: the local brain is- Ollama by design, so offer its install/start instead of only- printing the terminal command. Re-runs the preflight once the- runtime comes up. */}- {preflight.brain?.kind === "blocked" && (- <OllamaRuntimePanel- providerId="ollama"- onChanged={() => {- void check();- onChanged();- }}- />- )}</div>)}- {!status.ready && !running && preflight?.ok && preflight.tier && (- <div className="space-y-2 text-xs">- <div className="space-y-0.5 text-muted-foreground">- <p>- {preflight.tier.label} · {t("apikeys_view.managed_download_size")}{" "}- ~{preflight.tier.download_gb} GB ·{" "}- {t("apikeys_view.managed_latency")}{" "}- {preflight.tier.expected_latency}- </p>- <p>{preflight.stack_sentence}</p>- {preflight.brain && <p>{preflight.brain.note}</p>}+ {!status.ready &&+ !running &&+ preflight &&+ (preflight.ok || preflight.brain_fixable) &&+ preflight.tier && (+ <div className="space-y-2 text-xs">+ <div className="space-y-0.5 text-muted-foreground">+ <p>+ {preflight.tier.label} · {t("apikeys_view.managed_download_size")}{" "}+ ~{preflight.tier.download_gb} GB ·{" "}+ {t("apikeys_view.managed_latency")}{" "}+ {preflight.tier.expected_latency}+ </p>+ <p>{preflight.stack_sentence}</p>+ {preflight.brain && <p>{preflight.brain.note}</p>}+ {/* Blocked brain, but the install fixes it itself: say so+ honestly BEFORE the click — Ollama plus the brain model are+ extra downloads the tier size above does not include. */}+ {!preflight.ok && preflight.brain_fixable && (+ <p className="text-amber-500">+ {t("apikeys_view.managed_brain_setup_note")}+ </p>+ )}+ </div>+ <Button size="sm" onClick={startInstall} className="gap-2">+ <Download className="h-3.5 w-3.5" />+ {t("apikeys_view.managed_install_cta")}+ </Button></div>- <Button size="sm" onClick={startInstall} className="gap-2">- <Download className="h-3.5 w-3.5" />- {t("apikeys_view.managed_install_cta")}- </Button>- </div>- )}+ )}{anythingOnDisk && !running && (<Buttondiff --git a/jarvis/ui/web/frontend/src/hooks/useProviders.ts b/jarvis/ui/web/frontend/src/hooks/useProviders.tsindex 669e87b8f4..f2fa538cfd 100644--- a/jarvis/ui/web/frontend/src/hooks/useProviders.ts+++ b/jarvis/ui/web/frontend/src/hooks/useProviders.ts@@ -847,6 +847,8 @@ export interface ManagedPreflight {ok: boolean;blocker: string;actions: string[];+ /** Blocked ONLY by the missing brain — the install can fix that itself. */+ brain_fixable?: boolean;usable_gb: number;memory_source: string;disk_free_gb: number;diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex a54d3dd42d..005fca291a 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -1180,6 +1180,7 @@"managed_server_port_conflict": "Ein anderer Prozess belegt diesen Port","managed_start_cta": "Server starten","managed_stop_cta": "Server stoppen",+ "managed_brain_setup_note": "Richtet zuerst das lokale Denkmodell ein: installiert bei Bedarf Ollama und lädt das Modell herunter (mehrere zusätzliche GB).","ollama_install_cta": "Ollama installieren","ollama_install_confirm": "Erneut klicken, um Ollama jetzt zu installieren","ollama_install_hint": "Lädt die offizielle Ollama-Laufzeit von ollama.com und startet sie — ganz ohne Terminal. Lokale Modelle laufen vollständig auf diesem Rechner.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 03e36dcd7c..e9bfc390e1 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -1180,6 +1180,7 @@"managed_server_port_conflict": "Another process is serving this port","managed_start_cta": "Start server","managed_stop_cta": "Stop server",+ "managed_brain_setup_note": "Also sets up the local brain first: installs Ollama if needed and downloads the brain model (several extra GB).","ollama_install_cta": "Install Ollama","ollama_install_confirm": "Click again to install Ollama now","ollama_install_hint": "Downloads the official Ollama runtime from ollama.com and starts it — no terminal needed. Local models run entirely on this machine.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 708aa76306..f05508e5e1 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -1180,6 +1180,7 @@"managed_server_port_conflict": "Otro proceso está sirviendo en este puerto","managed_start_cta": "Iniciar servidor","managed_stop_cta": "Detener servidor",+ "managed_brain_setup_note": "Primero configura el cerebro local: instala Ollama si hace falta y descarga el modelo (varios GB adicionales).","ollama_install_cta": "Instalar Ollama","ollama_install_confirm": "Haz clic de nuevo para instalar Ollama ahora","ollama_install_hint": "Descarga el runtime oficial de Ollama desde ollama.com y lo inicia — sin terminal. Los modelos locales se ejecutan por completo en esta máquina.",diff --git a/tests/unit/realtime/local_server/test_engine.py b/tests/unit/realtime/local_server/test_engine.pyindex 685e058cd5..821ebbe5dc 100644--- a/tests/unit/realtime/local_server/test_engine.py+++ b/tests/unit/realtime/local_server/test_engine.py@@ -177,6 +177,7 @@ class TestDeriveLaunchCommand:assert "--responses_api_api_key ollama" in cmdassert "--qwen3_tts_device cuda" in cmdassert "--model_name qwen2.5:7b" in cmd+ assert "--ws_host 127.0.0.1" in cmddef test_cloud_command_never_carries_the_secret(self) -> None:brain = brain_link.BrainResolution(@@ -210,6 +211,33 @@ class TestServerStatusFailClosed:assert components["venv"] is True # type: ignore[index]assert components["patch"] is False # type: ignore[index]+ def test_corrupt_smoke_marker_is_not_readiness(self, monkeypatch, tmp_path: Path) -> None:+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ python = install._venv_python()+ entrypoint = install._server_entrypoint()+ python.parent.mkdir(parents=True)+ python.write_bytes(b"")+ entrypoint.write_bytes(b"")+ install._smoke_marker().write_text("", encoding="utf-8")+ monkeypatch.setattr(install, "patch_state", lambda path: "patched")++ status = install.server_status()++ assert status["ready"] is False+ assert status["components"]["smoke_boot"] is False # type: ignore[index]++ def test_smoke_marker_must_match_the_current_patch_version(+ self, monkeypatch, tmp_path: Path+ ) -> None:+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ install.install_root().mkdir(parents=True)+ install._smoke_marker().write_text(+ '{"schema": 1, "patch_version": "old", "at": 1, '+ '"tier": "t1-16gb", "brain": "ollama", "preflight": {}}',+ encoding="utf-8",+ )+ assert install._smoke_marker_valid() is False+def test_stale_config_earns_the_repair_sentence(self, monkeypatch, tmp_path: Path) -> None:@@ -276,6 +304,180 @@ class TestSnapshot:class TestReviewFixes:"""Contracts pinned by the 2026-08-07 code review."""+ def test_posix_install_steps_start_a_killable_process_group(self, monkeypatch) -> None:+ captured: dict[str, object] = {}++ class _Process:+ stdout: list[str] = []++ def wait(self, timeout: int) -> int:+ return 0++ def popen(*args, **kwargs):+ captured.update(kwargs)+ return _Process()++ monkeypatch.setattr(install.os, "name", "posix")+ monkeypatch.setattr(install.subprocess, "Popen", popen)+ install._run(["python", "-m", "pip", "install", "package"], timeout=30)+ assert captured["start_new_session"] is True++ def test_failed_reinstall_invalidates_the_previous_smoke_marker(+ self, monkeypatch, tmp_path+ ) -> None:+ from jarvis.realtime.local_server import supervisor++ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ install.install_root().mkdir(parents=True)+ install._venv_python().parent.mkdir(parents=True)+ install._venv_python().write_bytes(b"")+ install._write_smoke_marker(+ {+ "schema": install._SMOKE_MARKER_SCHEMA,+ "patch_version": install.PATCH_TARGET_VERSION,+ "at": 1.0,+ "tier": "t1-16gb",+ "brain": "ollama",+ "preflight": {},+ }+ )+ report = preflight.PreflightReport(+ ok=True,+ usable_gb=16.0,+ memory_source="nvidia-smi",+ disk_free_gb=100.0,+ tier=tiers.TIERS[1],+ stack_sentence="x",+ brain=brain_link.BrainResolution(kind="ollama", model="qwen2.5:7b"),+ )+ monkeypatch.setattr(install, "run_preflight", lambda root: report)+ monkeypatch.setattr(+ supervisor,+ "_stop_owned_unlocked",+ lambda **kwargs: (False, "no owned server process found"),+ )++ def failed_step(*args, **kwargs):+ raise RuntimeError("dependency install failed")++ monkeypatch.setattr(install, "_run", failed_step)+ install._run_install()++ assert not install._smoke_marker().exists()+ assert install.snapshot()["phase"] == "error"++ def test_smoke_boot_always_tears_down_its_child(self, monkeypatch, tmp_path) -> None:+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ install.install_root().mkdir(parents=True)++ class _Process:+ pid = 4711+ returncode = None++ def poll(self):+ return None++ process = _Process()+ monkeypatch.setattr(install.subprocess, "Popen", lambda *args, **kwargs: process)+ monkeypatch.setattr(+ "jarvis.realtime.local_server.supervisor.probe_runtime",+ lambda *args, **kwargs: {+ "size": 1,+ "in_use": 0,+ "available": 1,+ "stuck": 0,+ },+ )+ killed: list[object] = []+ monkeypatch.setattr(+ install, "_kill_tree", lambda proc: killed.append(proc) or True+ )++ install._smoke_boot(+ "serve --mode realtime",+ brain_link.BrainResolution(kind="ollama", model="qwen2.5:7b"),+ )++ assert killed == [process]++ def test_smoke_boot_fails_if_its_child_survives_teardown(+ self, monkeypatch, tmp_path+ ) -> None:+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ install.install_root().mkdir(parents=True)++ class _Process:+ pid = 4711+ returncode = None++ def poll(self):+ return None++ monkeypatch.setattr(+ install.subprocess,+ "Popen",+ lambda *args, **kwargs: _Process(),+ )+ monkeypatch.setattr(+ "jarvis.realtime.local_server.supervisor.probe_runtime",+ lambda *args, **kwargs: {+ "size": 1,+ "in_use": 0,+ "available": 1,+ "stuck": 0,+ },+ )+ monkeypatch.setattr(install, "_kill_tree", lambda proc: False)++ with pytest.raises(RuntimeError, match="survived teardown"):+ install._smoke_boot(+ "serve --mode realtime",+ brain_link.BrainResolution(kind="ollama", model="qwen2.5:7b"),+ )++ def test_install_holds_the_server_lifecycle_lease_for_its_body(+ self, monkeypatch, tmp_path+ ) -> None:+ from jarvis.realtime.local_server import supervisor++ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ outcomes: list[str] = []++ def guarded_body(confirmed_brain: str = "") -> None:+ outcomes.append(+ supervisor.ensure_running(+ launch_command="serve",+ base_url="http://127.0.0.1:8765",+ reason="lease-test",+ )+ )++ monkeypatch.setattr(install, "_run_install_guarded", guarded_body)+ install._run_install()+ assert outcomes == ["refused:spawn-in-progress"]++ def test_uninstall_holds_the_server_lifecycle_lease_for_its_body(+ self, monkeypatch, tmp_path+ ) -> None:+ from jarvis.realtime.local_server import supervisor++ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ outcomes: list[str] = []++ def guarded_body() -> tuple[bool, str]:+ outcomes.append(+ supervisor.ensure_running(+ launch_command="serve",+ base_url="http://127.0.0.1:8765",+ reason="lease-test",+ )+ )+ return True, "done"++ monkeypatch.setattr(install, "_uninstall_guarded", guarded_body)+ assert install.uninstall() == (True, "done")+ assert outcomes == ["refused:spawn-in-progress"]+def test_install_root_is_absolute_without_env(self, monkeypatch) -> None:monkeypatch.delenv("JARVIS_DATA_DIR", raising=False)assert install.install_root().is_absolute()@@ -353,6 +555,137 @@ class TestReviewFixes:install._rmtree_tolerant(root)+class TestBrainSetupChain:+ """Single-click promise: a confirmed local install sets up its own brain."""++ @staticmethod+ def _blocked_report() -> preflight.PreflightReport:+ return preflight.PreflightReport(+ ok=False,+ blocker="No brain available: neither a running Ollama nor an OpenAI key.",+ usable_gb=16.0,+ memory_source="nvidia-smi",+ disk_free_gb=100.0,+ tier=tiers.TIERS[0],+ brain=brain_link.BrainResolution(kind="blocked", note="no brain"),+ )++ def test_confirmed_ollama_runs_the_brain_setup(self, monkeypatch, tmp_path) -> None:+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ reports = [self._blocked_report(), self._blocked_report()]+ monkeypatch.setattr(install, "run_preflight", lambda root: reports.pop(0))+ calls: list[str] = []+ monkeypatch.setattr(+ install, "_setup_local_brain", lambda: calls.append("setup")+ )+ install._run_install("ollama")+ # Setup ran; the still-blocked re-check then failed honestly (which+ # also keeps this test off the heavy venv/pip tail).+ assert calls == ["setup"]+ assert install.snapshot()["phase"] == "error"++ def test_unconfirmed_blocked_brain_fails_without_setup(+ self, monkeypatch, tmp_path+ ) -> None:+ """Nothing installs without the user's explicit confirmation."""+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ monkeypatch.setattr(+ install, "run_preflight", lambda root: self._blocked_report()+ )+ calls: list[str] = []+ monkeypatch.setattr(+ install, "_setup_local_brain", lambda: calls.append("setup")+ )+ install._run_install("")+ assert calls == []+ assert install.snapshot()["phase"] == "error"++ def test_floor_blocked_never_runs_brain_setup(self, monkeypatch, tmp_path) -> None:+ """A machine under the VRAM floor cannot be fixed by installing+ Ollama — the honest hardware blocker must win."""+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ floor_blocked = preflight.PreflightReport(+ ok=False,+ blocker="under the minimum",+ usable_gb=4.0,+ memory_source="nvidia-smi",+ disk_free_gb=100.0,+ )+ monkeypatch.setattr(install, "run_preflight", lambda root: floor_blocked)+ calls: list[str] = []+ monkeypatch.setattr(+ install, "_setup_local_brain", lambda: calls.append("setup")+ )+ install._run_install("ollama")+ assert calls == []+ assert "minimum" in str(install.snapshot()["error"])++ def test_setup_pulls_the_preferred_model_when_missing(self, monkeypatch) -> None:+ from jarvis.brain import ollama_runtime++ monkeypatch.setattr(+ ollama_runtime, "ensure_runtime_blocking", lambda: (True, "running")+ )+ monkeypatch.setattr(+ install,+ "resolve_brain_for_install",+ lambda: brain_link.BrainResolution(kind="blocked", note="no model"),+ )+ pulled: list[str] = []+ monkeypatch.setattr(+ install, "_pull_brain_model", lambda model: pulled.append(model)+ )+ install._setup_local_brain()+ assert pulled == [brain_link._PREFERRED_MODELS[0]]++ def test_setup_skips_the_pull_when_a_brain_already_resolves(+ self, monkeypatch+ ) -> None:+ from jarvis.brain import ollama_runtime++ monkeypatch.setattr(+ ollama_runtime, "ensure_runtime_blocking", lambda: (True, "running")+ )+ monkeypatch.setattr(+ install,+ "resolve_brain_for_install",+ lambda: brain_link.BrainResolution(kind="ollama", model="qwen2.5:7b"),+ )+ pulled: list[str] = []+ monkeypatch.setattr(+ install, "_pull_brain_model", lambda model: pulled.append(model)+ )+ install._setup_local_brain()+ assert pulled == []++ def test_setup_raises_the_honest_platform_reason(self, monkeypatch) -> None:+ from jarvis.brain import ollama_runtime++ monkeypatch.setattr(+ ollama_runtime,+ "ensure_runtime_blocking",+ lambda: (False, "passwordless sudo is not available here"),+ )+ with pytest.raises(RuntimeError, match="sudo"):+ install._setup_local_brain()++ def test_payload_flags_the_fixable_brain(self) -> None:+ payload = preflight.report_payload(self._blocked_report())+ assert payload["brain_fixable"] is True+ floor_blocked = preflight.PreflightReport(+ ok=False, blocker="x", usable_gb=4.0, memory_source="nvidia-smi"+ )+ assert preflight.report_payload(floor_blocked)["brain_fixable"] is False++ def test_the_preferred_model_is_in_the_curated_pull_list(self) -> None:+ """The auto-pull target and the download panel must agree — two+ curated lists drifting apart ships a model the panel disowns."""+ from jarvis.brain.ollama_pull import RECOMMENDED_MODELS++ curated = {entry.id for entry in RECOMMENDED_MODELS}+ assert brain_link._PREFERRED_MODELS[0] in curated++class TestCrossPlatformHonesty:"""Contracts from the 2026-08-08 hardening plan (Wave 4)."""