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
fix(realtime): close the ten managed-install review findings
rubenluetke10-beep05d1934f3268
diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.pyindex a0ed48beee..62bc3e0ba3 100644--- a/jarvis/core/config_writer.py+++ b/jarvis/core/config_writer.py@@ -2054,6 +2054,48 @@ def set_local_realtime_launch_command(_atomic_write(path, out)+def clear_local_realtime_launch_command(+ *, only_if_under: str = "", path: Path = DEFAULT_CONFIG_FILE+) -> None:+ """Clear the managed server's launch command after an uninstall.++ ``only_if_under`` guards user autonomy: when given, the command is only+ cleared if it references that directory (the managed install tree) — a+ hand-authored bring-your-own command stays untouched. The default+ ``base_url`` this module pinned is cleared alongside, so a removed+ server stops looking "configured" to the activation path; a custom URL+ survives.+ """+ path = _ensure_writable_config_path(path)++ with _WRITE_LOCK:+ raw = path.read_text(encoding="utf-8")+ had_bom = raw.startswith(_BOM)+ if had_bom:+ raw = raw[len(_BOM) :]+ doc: TOMLDocument = tomlkit.parse(raw)++ block = doc.get("brain", {}).get("providers", {}).get("local-realtime")+ if block is None:+ return+ command = str(block.get("launch_command", "") or "")+ if not command:+ return+ if only_if_under:+ needle = only_if_under.replace("/", "\\").lower()+ haystack = command.replace("/", "\\").lower()+ if needle not in haystack:+ return+ block["launch_command"] = ""+ if str(block.get("base_url", "") or "").strip() == "http://localhost:8765":+ block["base_url"] = ""++ out = tomlkit.dumps(doc)+ if had_bom:+ out = _BOM + out+ _atomic_write(path, out)++def set_telephony_config(values: dict[str, object], *, path: Path = DEFAULT_CONFIG_FILE) -> None:"""Patch ``[integrations.twilio]`` with the given non-secret fields.diff --git a/jarvis/plugins/realtime/openai_realtime.py b/jarvis/plugins/realtime/openai_realtime.pyindex fd9cfbb548..633ba6c7fa 100644--- a/jarvis/plugins/realtime/openai_realtime.py+++ b/jarvis/plugins/realtime/openai_realtime.py@@ -1527,6 +1527,25 @@ class LocalRealtimeProvider:# (live 2026-08-07), which would brick the server's own model# fetches. Copies cost disk, not correctness.child_env.setdefault("HF_HUB_DISABLE_SYMLINKS", "1")+ # The managed install's cloud-brain path deliberately keeps the+ # OpenAI key OUT of the persisted launch command (secrets never+ # enter jarvis.toml); the server's OpenAI client reads it from+ # this spawn environment instead. Keyring-held keys are not in+ # os.environ, so inject here — otherwise every turn of a+ # cloud-brained managed server 401s although the install was+ # green (review 2026-08-07). Ollama-brained and keyless servers+ # simply never look at it.+ if not child_env.get("OPENAI_API_KEY"):+ try:+ get_secret = importlib.import_module("jarvis.core.config").get_secret # AP-1+ key = get_secret("openai_api_key", env_fallback="OPENAI_API_KEY") or ""+ if key:+ child_env["OPENAI_API_KEY"] = key+ except Exception: # noqa: BLE001 — a secretless host is a valid host+ log.debug(+ "local-realtime: OpenAI key lookup for spawn env failed",+ exc_info=True,+ )subprocess.Popen( # noqa: S603 — the maintainer configured this commandcommand,stdin=subprocess.DEVNULL,diff --git a/jarvis/realtime/local_server/install.py b/jarvis/realtime/local_server/install.pyindex fad356b6f2..8d5c394a4b 100644--- a/jarvis/realtime/local_server/install.py+++ b/jarvis/realtime/local_server/install.py@@ -64,8 +64,19 @@ _PHASES = ("idle", "preflight", "venv", "deps", "patch", "smoke", "configure", "def install_root() -> Path:- """Permanent home of the managed server, under the Jarvis data dir."""- return Path(os.environ.get("JARVIS_DATA_DIR") or "data") / "local_realtime"+ """Permanent home of the managed server, under the Jarvis data dir.++ Absolute on purpose (review 2026-08-07): a CWD-relative ``data`` made+ the persisted launch command break under any other working directory+ (service starts, shortcuts, CLI) and made status probes read a+ different tree than the installer wrote.+ """+ env_dir = os.environ.get("JARVIS_DATA_DIR")+ if env_dir and env_dir.strip():+ return Path(env_dir.strip()).resolve() / "local_realtime"+ from jarvis.core.config import DATA_DIR # absolute PROJECT_ROOT/data++ return DATA_DIR / "local_realtime"def _venv_dir() -> Path:@@ -203,7 +214,13 @@ def derive_launch_command(brain: BrainResolution, *, memory_source: str) -> str:def _run(cmd: list[str], *, timeout: int, cwd: Path | None = None) -> None:- """Run a build step, streaming its output into the progress tail."""+ """Run a build step, streaming its output into the progress tail.++ The deadline is enforced by ``wait(timeout=…)`` on the process itself,+ never by the output stream: a step that stalls SILENTLY (a hung pip+ download emits nothing) previously blocked forever in ``readline`` and+ left the install "running" with no cancel path (review 2026-08-07).+ """env = dict(os.environ)env.setdefault("PYTHONIOENCODING", "utf-8")proc = subprocess.Popen(@@ -217,18 +234,24 @@ def _run(cmd: list[str], *, timeout: int, cwd: Path | None = None) -> None:env=env,creationflags=NO_WINDOW_CREATIONFLAGS,)- deadline = time.monotonic() + timeout- assert proc.stdout is not None- for line in proc.stdout:- line = line.rstrip()- if line:- with _LOCK:- _STATE.detail = line[:200]- _STATE.log_tail.append(line[:200])- if time.monotonic() > deadline:- _kill_tree(proc)- raise TimeoutError(f"step timed out after {timeout}s: {' '.join(cmd[:3])}…")- code = proc.wait(timeout=60)++ def _pump() -> None:+ assert proc.stdout is not None+ for line in proc.stdout:+ line = line.rstrip()+ if line:+ with _LOCK:+ _STATE.detail = line[:200]+ _STATE.log_tail.append(line[:200])++ pump = threading.Thread(target=_pump, name="local-realtime-install-pump", daemon=True)+ pump.start()+ try:+ code = proc.wait(timeout=timeout)+ except subprocess.TimeoutExpired:+ _kill_tree(proc)+ raise TimeoutError(f"step timed out after {timeout}s: {' '.join(cmd[:3])}…") from None+ pump.join(timeout=10)if code != 0:raise RuntimeError(f"step failed (exit {code}): {' '.join(cmd[:3])}…")@@ -265,7 +288,16 @@ def _smoke_boot(launch_command: str, brain: BrainResolution) -> None:the HF cache, port bind) before the install may call itself ready.Mirrors the adapter's revive spawn exactly: raw string on Windows,shlex on POSIX, and the same hardening environment.++ The probe port must be FREE before the spawn: an unrelated listener on+ it would answer the readiness poll and record a success the freshly+ built server never earned (review 2026-08-07)."""+ if _port_open(_SMOKE_PORT):+ raise RuntimeError(+ f"smoke-boot port {_SMOKE_PORT} is already in use by another "+ "process — close it and retry the install"+ )with_port = f"{launch_command} --ws_port {_SMOKE_PORT}"cmd: str | list[str] = with_port if os.name == "nt" else shlex.split(with_port)smoke_log = install_root() / "smoke_boot.log"@@ -295,6 +327,14 @@ def _smoke_boot(launch_command: str, brain: BrainResolution) -> None:f"server exited during smoke boot (code {proc.returncode}); see {smoke_log}")if _port_open(_SMOKE_PORT):+ # 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.+ if proc.poll() is not None:+ raise RuntimeError(+ f"server exited right after binding (code {proc.returncode}); "+ f"see {smoke_log}"+ )returnelapsed = int(time.monotonic() - (deadline - _SMOKE_TIMEOUT_S))_set("smoke", 70 + min(25, elapsed // 30), "waiting for first boot (downloads models)")@@ -304,8 +344,15 @@ def _smoke_boot(launch_command: str, brain: BrainResolution) -> None:_kill_tree(proc)-def start_install() -> tuple[bool, str]:- """Kick off (or resume) the managed install. Returns immediately."""+def start_install(*, confirmed_brain: str = "") -> tuple[bool, str]:+ """Kick off (or resume) the managed install. Returns immediately.++ ``confirmed_brain`` is the brain kind the user saw in the preflight+ they confirmed ("ollama" / "cloud-openai"). The install re-resolves the+ brain and must FAIL if the kind changed in between — silently swapping+ a confirmed "fully local" setup for cloud reasoning would bypass the+ exact honesty note this flow exists for (review 2026-08-07).+ """with _LOCK:if _STATE.thread is not None and _STATE.thread.is_alive():return False, "an install is already running"@@ -315,13 +362,18 @@ def start_install() -> tuple[bool, str]:_STATE.detail = ""_STATE.started_at = time.time()_STATE.finished_at = 0.0- thread = threading.Thread(target=_run_install, name="local-realtime-install", daemon=True)+ thread = threading.Thread(+ target=_run_install,+ name="local-realtime-install",+ args=(confirmed_brain.strip(),),+ daemon=True,+ )_STATE.thread = threadthread.start()return True, "install started"-def _run_install() -> None:+def _run_install(confirmed_brain: str = "") -> None:try:_set("preflight", 2, "checking hardware, disk, and brain")report: PreflightReport = run_preflight(install_root())@@ -329,6 +381,14 @@ def _run_install() -> None:_fail(report.blocker)returnassert report.brain is not None and report.tier is not None+ if confirmed_brain and report.brain.kind != confirmed_brain:+ _fail(+ "the reasoning setup changed since your confirmation (was "+ f"{confirmed_brain}, now {report.brain.kind}: "+ f"{report.brain.note}) — run the check again and confirm "+ "the new setup"+ )+ returninstall_root().mkdir(parents=True, exist_ok=True)if not _venv_python().exists():@@ -385,20 +445,99 @@ def _run_install() -> 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.++ FileNotFoundError mid-walk (AV scanner, racing delete) is ignored;+ read-only files get one chmod+retry; transient locks get three whole+ attempts. Windows additionally takes the extended-length path prefix so+ deep node_modules-style paths cannot fail on MAX_PATH.+ """+ import shutil+ import stat++ target = str(root)+ if os.name == "nt" and not target.startswith("\\\\?\\"):+ target = f"\\\\?\\{root.resolve()}"++ def _onerror(func, path, exc_info) -> None:+ exc = exc_info[1]+ if isinstance(exc, FileNotFoundError):+ return+ try:+ os.chmod(path, stat.S_IWRITE)+ func(path)+ except FileNotFoundError:+ return++ last_error: OSError | None = None+ for attempt in range(3):+ if not root.exists():+ return+ try:+ shutil.rmtree(target, onerror=_onerror)+ return+ except OSError as exc: # a still-held handle — give it a moment+ last_error = exc+ time.sleep(2 * (attempt + 1))+ if root.exists() and last_error is not None:+ raise last_error+++def _clear_managed_config(root: Path) -> None:+ """Drop OUR launch command from jarvis.toml after a removal.++ Only a command pointing into the deleted tree is cleared — a+ bring-your-own launch command the user authored stays untouched.+ Without this, every later call spawned a nonexistent entry point and+ then sat out the full 120 s patient-reconnect window on a server the+ user had just removed (review 2026-08-07).+ """+ from jarvis.core.config_writer import clear_local_realtime_launch_command++ clear_local_realtime_launch_command(only_if_under=str(root))++def uninstall() -> tuple[bool, str]:- """Delete the managed install tree and its readiness marker."""+ """Stop the managed server, delete its tree, and clear its config."""with _LOCK:if _STATE.thread is not None and _STATE.thread.is_alive():return False, "an install is running; wait for it to finish first"- import shutil-root = install_root()if not root.exists():+ _clear_managed_config(root)return True, "nothing installed"+ _stop_managed_server(root)try:- shutil.rmtree(root)+ _rmtree_tolerant(root)except OSError as exc:return False, f"could not remove {root}: {exc}"+ _clear_managed_config(root)with _LOCK:_STATE.phase = "idle"_STATE.percent = 0diff --git a/jarvis/realtime/local_server/preflight.py b/jarvis/realtime/local_server/preflight.pyindex a810a3c6ca..d37ff3f605 100644--- a/jarvis/realtime/local_server/preflight.py+++ b/jarvis/realtime/local_server/preflight.py@@ -63,7 +63,11 @@ def _usable_accelerator_gb() -> tuple[float, str]:except Exception: # pragma: no cover — nvidia-smi quirks must not crash preflightlog.debug("preflight: NVIDIA probe failed", exc_info=True)gpus = []- vram_mb = sum(g.vram_mb for g in gpus)+ # The LARGEST single device, never the fleet sum: the whole stack runs+ # on one GPU (--num_pipelines 1, one TTS device), so two 8 GB cards are+ # an 8 GB machine for this feature — summing them would defeat the+ # 12 GB floor and OOM at first call (review 2026-08-07).+ vram_mb = max((g.vram_mb for g in gpus), default=0)if vram_mb > 0:return vram_mb / 1024.0, "nvidia-smi"if sys.platform == "darwin" and platform.machine() == "arm64":diff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsxindex cd87d2eb2e..28feb91d8b 100644--- a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx+++ b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx@@ -1799,6 +1799,11 @@ function ManagedServerPanel({if (!status) return null;+ // The Remove control must survive a PARTIAL state: after a failed+ // uninstall (or interrupted install) `ready` is false but gigabytes are+ // still on disk — gating removal on `ready` would strand them forever.+ const anythingOnDisk = Object.values(status.components ?? {}).some(Boolean);+const check = async () => {setError(null);setChecking(true);@@ -1814,7 +1819,14 @@ function ManagedServerPanel({const startInstall = async () => {setError(null);try {- setProgress(await managedServerInstall());+ const first = await managedServerInstall(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+ // effect only runs while `running` is true.+ if (!first.running && first.phase === "error" && first.error) {+ setError(first.error);+ }} catch (err) {setError(err instanceof Error ? err.message : String(err));}@@ -1914,7 +1926,7 @@ function ManagedServerPanel({</div>)}- {status.ready && !running && (+ {anythingOnDisk && !running && (<Buttonsize="sm"variant="ghost"diff --git a/jarvis/ui/web/frontend/src/hooks/useProviders.ts b/jarvis/ui/web/frontend/src/hooks/useProviders.tsindex 6d3aa56191..79a733aa6c 100644--- a/jarvis/ui/web/frontend/src/hooks/useProviders.ts+++ b/jarvis/ui/web/frontend/src/hooks/useProviders.ts@@ -862,9 +862,16 @@ export async function managedServerPreflight(): Promise<ManagedPreflight> {return body as ManagedPreflight;}-export async function managedServerInstall(): Promise<ManagedInstallProgress> {+export async function managedServerInstall(+ confirmedBrain?: string,+): Promise<ManagedInstallProgress> {const res = await fetch("/api/providers/local-realtime/managed-server/install", {method: "POST",+ headers: { "Content-Type": "application/json" },+ // The brain kind the user just confirmed in the preflight — the engine+ // fails the install if it re-resolves differently (no silent+ // local→cloud swap).+ body: JSON.stringify({ confirmed_brain: confirmedBrain ?? "" }),});const body = await res.json().catch(() => ({}));if (!res.ok) throw new Error(body.detail ?? `HTTP ${res.status}`);diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.pyindex 43b40831b3..ad28684888 100644--- a/jarvis/ui/web/provider_routes.py+++ b/jarvis/ui/web/provider_routes.py@@ -2681,17 +2681,30 @@ async def managed_server_preflight() -> dict[str, Any]:@router.post("/providers/local-realtime/managed-server/install")-async def managed_server_install() -> dict[str, Any]:+async def managed_server_install(request: Request) -> dict[str, Any]:"""Start (or join) the one-click managed server install.Returns immediately with the poll-shaped progress snapshot; the heavylifting (venv, pinned packages, vendored patch, first smoke boot thatdownloads the models) runs in a background thread. A second call whilea run is in flight joins it instead of starting a duplicate.++ The optional body ``{"confirmed_brain": "ollama"}`` carries the brain+ kind the user saw in the preflight; the engine fails the install if the+ re-resolved brain differs, so a confirmed "fully local" can never+ silently become cloud reasoning."""from jarvis.realtime.local_server.install import snapshot, start_install- started, message = await asyncio.to_thread(start_install)+ confirmed_brain = ""+ try:+ body = await request.json()+ confirmed_brain = str((body or {}).get("confirmed_brain", "") or "")+ except Exception: # noqa: BLE001 — an empty/absent body is the normal case+ confirmed_brain = ""+ started, message = await asyncio.to_thread(+ lambda: start_install(confirmed_brain=confirmed_brain)+ )payload = snapshot()payload["started"] = startedpayload["message"] = messagediff --git a/tests/unit/realtime/local_server/test_engine.py b/tests/unit/realtime/local_server/test_engine.pyindex 95377a5f11..4b14aace18 100644--- a/tests/unit/realtime/local_server/test_engine.py+++ b/tests/unit/realtime/local_server/test_engine.py@@ -187,5 +187,85 @@ class TestSnapshot:assert set(snap) == {"phase", "percent", "detail", "error", "running", "log_tail"}+class TestReviewFixes:+ """Contracts pinned by the 2026-08-07 code review."""++ def test_install_root_is_absolute_without_env(self, monkeypatch) -> None:+ monkeypatch.delenv("JARVIS_DATA_DIR", raising=False)+ assert install.install_root().is_absolute()++ def test_multi_gpu_uses_largest_device_not_the_sum(self, monkeypatch) -> None:+ from jarvis.hardware import detection++ monkeypatch.setattr(+ detection,+ "_detect_nvidia_gpus",+ lambda: [detection.GPUInfo("A", 8192), detection.GPUInfo("B", 8192)],+ )+ usable, source = preflight._usable_accelerator_gb()+ assert source == "nvidia-smi"+ assert usable == pytest.approx(8.0) # two 8 GB cards are an 8 GB machine++ def test_brain_kind_change_fails_the_install(self, monkeypatch, tmp_path) -> None:+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))+ report = preflight.PreflightReport(+ ok=True,+ usable_gb=16.0,+ memory_source="nvidia-smi",+ disk_free_gb=100.0,+ tier=tiers.TIERS[0],+ stack_sentence="x",+ brain=brain_link.BrainResolution(kind="cloud-openai", model="gpt-5.4-mini"),+ )+ monkeypatch.setattr(install, "run_preflight", lambda root: report)+ install._run_install("ollama")+ snap = install.snapshot()+ assert snap["phase"] == "error"+ assert "changed since your confirmation" in str(snap["error"])++ def test_uninstall_clears_only_the_managed_launch_command(self, tmp_path) -> None:+ from jarvis.core.config_writer import clear_local_realtime_launch_command++ cfg = tmp_path / "jarvis.toml"+ managed = tmp_path / "data" / "local_realtime"+ entrypoint = (managed / "venv" / "s.exe").as_posix()+ cfg.write_text(+ "[brain.providers.local-realtime]\n"+ f"launch_command = \"'{entrypoint}' --mode realtime\"\n"+ 'base_url = "http://localhost:8765"\n',+ encoding="utf-8",+ )+ clear_local_realtime_launch_command(only_if_under=str(managed), path=cfg)+ text = cfg.read_text(encoding="utf-8")+ assert 'launch_command = ""' in text+ assert 'base_url = ""' in text++ def test_clear_spares_a_bring_your_own_command(self, tmp_path) -> None:+ from jarvis.core.config_writer import clear_local_realtime_launch_command++ cfg = tmp_path / "jarvis.toml"+ cfg.write_text(+ "[brain.providers.local-realtime]\n"+ 'launch_command = "/opt/myserver/run --mode realtime"\n'+ 'base_url = "http://192.168.1.5:9000"\n',+ encoding="utf-8",+ )+ clear_local_realtime_launch_command(+ only_if_under=str(tmp_path / "data" / "local_realtime"), path=cfg+ )+ text = cfg.read_text(encoding="utf-8")+ assert "/opt/myserver/run" in text+ assert "192.168.1.5:9000" in text++ def test_tolerant_rmtree_survives_vanishing_files(self, tmp_path) -> None:+ root = tmp_path / "tree"+ (root / "sub").mkdir(parents=True)+ (root / "sub" / "a.txt").write_text("x", encoding="utf-8")+ install._rmtree_tolerant(root)+ assert not root.exists()+ # Idempotent on an already-gone tree.+ install._rmtree_tolerant(root)++if __name__ == "__main__": # pragma: no coverraise SystemExit(pytest.main([__file__, "-q"]))diff --git a/tests/unit/ui/web/test_managed_local_realtime_routes.py b/tests/unit/ui/web/test_managed_local_realtime_routes.pyindex 2528905629..f708713a22 100644--- a/tests/unit/ui/web/test_managed_local_realtime_routes.py+++ b/tests/unit/ui/web/test_managed_local_realtime_routes.py@@ -63,17 +63,39 @@ def test_preflight_reports_tier_and_brain_when_ok(assert body["brain"]["kind"] == "ollama"-def test_install_returns_immediately_with_snapshot(+def test_install_returns_immediately_and_forwards_confirmed_brain(server: WebServer, monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.setattr(install, "start_install", lambda: (True, "install started"))+ seen: dict[str, str] = {}++ def _fake_start(*, confirmed_brain: str = "") -> tuple[bool, str]:+ seen["confirmed_brain"] = confirmed_brain+ return True, "install started"++ monkeypatch.setattr(install, "start_install", _fake_start)with TestClient(server.app) as client:- resp = client.post("/api/providers/local-realtime/managed-server/install")+ resp = client.post(+ "/api/providers/local-realtime/managed-server/install",+ json={"confirmed_brain": "ollama"},+ )body = resp.json()assert resp.status_code == 200assert body["started"] is Trueassert body["message"] == "install started"assert "phase" in body and "percent" in body+ assert seen["confirmed_brain"] == "ollama"+++def test_install_accepts_an_empty_body(+ server: WebServer, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(+ install, "start_install", lambda confirmed_brain="": (True, "install started")+ )+ with TestClient(server.app) as client:+ resp = client.post("/api/providers/local-realtime/managed-server/install")+ assert resp.status_code == 200+ assert resp.json()["started"] is Truedef test_status_pairs_progress_with_failclosed_probe(server: WebServer) -> None: