Skip to content

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.

fix(realtime): platform-honest preflight, venv paths, kill escalation, model choice

rubenluetke10-beep2fa21cbe356b
diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.py
index fe3f553937..c4d6dc747f 100644
--- a/jarvis/core/config_writer.py
+++ b/jarvis/core/config_writer.py
@@ -870,6 +870,7 @@ DICTATION_SETTING_KEYS = (
"polish_drift_max_growth",
"polish_style",
"polish_precision",
+ "polish_conversation",
# The translate pass. Same rule as the polish keys above: a key missing here
# is a switch the UI appears to save and loses on the next restart.
"translate",
@@ -2055,6 +2056,77 @@ def set_local_realtime_launch_command(
_atomic_write(path, out)
+def _command_references_root(
+ command: str, root: str, *, windows: bool | None = None
+) -> bool:
+ """Whether a launch command points into the given directory.
+
+ Separator-normalized on every platform; case-INSENSITIVE only on
+ Windows — lowercasing both sides everywhere (the old behavior) made two
+ distinct case-sensitive POSIX paths compare equal. ``windows`` exists so
+ tests can pin the other platform's semantics without patching the global
+ ``os`` module (which breaks pathlib mid-session).
+ """
+ import os as _os
+
+ if windows is None:
+ windows = _os.name == "nt"
+ sep = "\\" if windows else "/"
+ needle = root.replace("/", sep).replace("\\", sep)
+ haystack = command.replace("/", sep).replace("\\", sep)
+ if windows:
+ needle = needle.lower()
+ haystack = haystack.lower()
+ return needle in haystack
+
+
+def update_local_realtime_launch_model(
+ model: str, *, only_if_under: str = "", path: Path = DEFAULT_CONFIG_FILE
+) -> bool:
+ """Rewrite ONLY the ``--model_name`` value of the persisted launch command.
+
+ The model choice is baked into the derived command string, and before
+ this helper existed changing it meant a full reinstall of a
+ multi-gigabyte stack. ``only_if_under`` keeps the same autonomy guard as
+ the clear path: a bring-your-own command is never rewritten. Returns
+ ``True`` when the command was changed.
+ """
+ path = _ensure_writable_config_path(path)
+ cleaned = (model or "").strip()
+ if not cleaned:
+ return False
+
+ 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 False
+ command = str(block.get("launch_command", "") or "")
+ if not command or "--model_name " not in command:
+ return False
+ if only_if_under and not _command_references_root(command, only_if_under):
+ return False
+ prefix, _, tail = command.partition("--model_name ")
+ old_value, _, rest = tail.partition(" ")
+ if old_value == cleaned:
+ return False
+ rewritten = f"{prefix}--model_name {cleaned}"
+ if rest:
+ rewritten = f"{rewritten} {rest}"
+ block["launch_command"] = rewritten
+
+ out = tomlkit.dumps(doc)
+ if had_bom:
+ out = _BOM + out
+ _atomic_write(path, out)
+ return True
+
+
def clear_local_realtime_launch_command(
*, only_if_under: str = "", path: Path = DEFAULT_CONFIG_FILE
) -> None:
@@ -2082,11 +2154,8 @@ def clear_local_realtime_launch_command(
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
+ if only_if_under and not _command_references_root(command, only_if_under):
+ return
block["launch_command"] = ""
if str(block.get("base_url", "") or "").strip() == "http://localhost:8765":
block["base_url"] = ""
diff --git a/jarvis/realtime/local_server/brain_link.py b/jarvis/realtime/local_server/brain_link.py
index 2843abbee3..2fa9ecc7e1 100644
--- a/jarvis/realtime/local_server/brain_link.py
+++ b/jarvis/realtime/local_server/brain_link.py
@@ -61,8 +61,20 @@ def _ollama_base() -> str:
return host.rstrip("/")
-def _ollama_tags(base: str, timeout: float) -> list[str] | None:
- """Model tags of a running Ollama, or ``None`` when it is unreachable."""
+#: Memory the brain model must leave free on the accelerator, in GiB: the
+#: managed stack co-hosts the Qwen3-TTS (bfloat16 + CUDA graphs) and the KV
+#: cache on the SAME device, so a model whose weights alone approach the
+#: card's capacity OOMs at the first turn. Applied only when both the model
+#: size and the usable memory are known — unknown stays permitted (fail-open).
+_BRAIN_HEADROOM_GB = 6.0
+
+
+def _ollama_models(base: str, timeout: float) -> list[tuple[str, float]] | None:
+ """(tag, size_gb) of a running Ollama's models; ``None`` when unreachable.
+
+ ``size_gb`` is 0.0 when the tags payload carries no usable size — the
+ caller then skips the fit check rather than guessing.
+ """
url = f"{base}/api/tags"
if not url.startswith(("http://", "https://")): # scheme is normalized above
return None
@@ -72,18 +84,63 @@ def _ollama_tags(base: str, timeout: float) -> list[str] | None:
except (urllib.error.URLError, OSError, ValueError):
return None
models = payload.get("models") or []
- return [str(m.get("name", "")) for m in models if m.get("name")]
-
-
-def _pick_model(tags: list[str]) -> str:
+ out: list[tuple[str, float]] = []
+ for entry in models:
+ name = str(entry.get("name", "") or "")
+ if not name:
+ continue
+ try:
+ size_gb = float(entry.get("size", 0) or 0) / (1024**3)
+ except (TypeError, ValueError):
+ size_gb = 0.0
+ out.append((name, size_gb))
+ return out
+
+
+def _usable_tag(tag: str) -> bool:
+ lowered = tag.lower()
+ return not any(marker in lowered for marker in _UNUSABLE_MARKERS)
+
+
+def _fits(size_gb: float, usable_gb: float) -> bool:
+ if size_gb <= 0.0 or usable_gb <= 0.0:
+ return True # unknown figures never veto (fail-open)
+ return size_gb + _BRAIN_HEADROOM_GB <= usable_gb
+
+
+def _pick_model(
+ models: list[tuple[str, float]],
+ *,
+ preferred_model: str = "",
+ usable_gb: float = 0.0,
+) -> tuple[str, str]:
+ """(chosen tag, honest note) — the note explains a surprising choice.
+
+ Order: the user's configured model when it is served AND fits; then the
+ curated preference list; then the first usable tag that fits. A model
+ whose weights would not leave the TTS and KV cache any room is skipped
+ with the reason in the note instead of OOMing at the first turn.
+ """
+ by_name = {name: size for name, size in models}
+ note = ""
+ if preferred_model:
+ size = by_name.get(preferred_model)
+ if size is not None and _usable_tag(preferred_model):
+ if _fits(size, usable_gb):
+ return preferred_model, ""
+ note = (
+ f"Your configured model {preferred_model} (~{size:.0f} GB) "
+ f"does not fit next to the voice stack on {usable_gb:.0f} GB "
+ "of accelerator memory; picked a smaller one instead."
+ )
for preferred in _PREFERRED_MODELS:
- if preferred in tags:
- return preferred
- for tag in tags:
- lowered = tag.lower()
- if not any(marker in lowered for marker in _UNUSABLE_MARKERS):
- return tag
- return ""
+ size = by_name.get(preferred)
+ if size is not None and _fits(size, usable_gb):
+ return preferred, note
+ for name, size in models:
+ if _usable_tag(name) and _fits(size, usable_gb):
+ return name, note
+ return "", note
def _openai_key() -> str:
@@ -96,19 +153,32 @@ def _openai_key() -> str:
return ""
-def resolve_brain(*, timeout: float = 2.5) -> BrainResolution:
- """Resolve the best brain endpoint available on THIS machine right now."""
+def resolve_brain(
+ *, timeout: float = 2.5, preferred_model: str = "", usable_gb: float = 0.0
+) -> BrainResolution:
+ """Resolve the best brain endpoint available on THIS machine right now.
+
+ ``preferred_model`` is the user's configured Ollama model (wins when it
+ is served and fits); ``usable_gb`` enables the VRAM fit check — a 24 GB
+ tag on a 16 GB card must be skipped with the reason said out loud, not
+ selected and OOMed at the first turn.
+ """
base = _ollama_base()
- tags = _ollama_tags(base, timeout)
- if tags is not None:
- model = _pick_model(tags)
+ models = _ollama_models(base, timeout)
+ if models is not None:
+ 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:
+ sentence = f"{sentence} {note}"
return BrainResolution(
kind="ollama",
base_url=f"{base}/v1",
api_key="ollama",
model=model,
- note=f"Fully local: reasoning runs on your Ollama ({model}).",
+ note=sentence,
)
return BrainResolution(
kind="blocked",
diff --git a/jarvis/realtime/local_server/install.py b/jarvis/realtime/local_server/install.py
index e95c214009..7fca033ed2 100644
--- a/jarvis/realtime/local_server/install.py
+++ b/jarvis/realtime/local_server/install.py
@@ -98,6 +98,14 @@ def _server_entrypoint() -> Path:
def _site_packages() -> Path:
if os.name == "nt":
return _venv_dir() / "Lib" / "site-packages"
+ # The VENV's own layout, not the host interpreter's: deriving the folder
+ # from this process's sys.version_info breaks the moment the venv was
+ # created by a different Python than the one running Jarvis (containered
+ # installs, pyenv hosts). Glob the real directory; fall back to the host
+ # figure only while the venv does not exist yet.
+ candidates = sorted((_venv_dir() / "lib").glob("python*/site-packages"))
+ if candidates:
+ return candidates[0]
version = f"python{sys.version_info.major}.{sys.version_info.minor}"
return _venv_dir() / "lib" / version / "site-packages"
@@ -317,7 +325,13 @@ def _run(cmd: list[str], *, timeout: int, cwd: Path | None = None) -> None:
def _kill_tree(proc: subprocess.Popen) -> None:
- """Terminate a step's whole process tree, not just the launcher."""
+ """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.
+ """
try:
if os.name == "nt":
subprocess.run(
@@ -327,8 +341,20 @@ def _kill_tree(proc: subprocess.Popen) -> None:
creationflags=NO_WINDOW_CREATIONFLAGS,
)
else:
- proc.terminate()
- proc.wait(timeout=10)
+ import signal
+
+ try:
+ os.killpg(proc.pid, signal.SIGTERM)
+ except (ProcessLookupError, PermissionError, OSError):
+ proc.terminate()
+ try:
+ proc.wait(timeout=10)
+ except subprocess.TimeoutExpired:
+ try:
+ os.killpg(proc.pid, signal.SIGKILL)
+ except (ProcessLookupError, PermissionError, OSError):
+ proc.kill()
+ proc.wait(timeout=10)
except Exception: # pragma: no cover — best-effort teardown
log.warning("local-realtime install: process-tree teardown incomplete", exc_info=True)
@@ -369,6 +395,10 @@ def _smoke_boot(launch_command: str, brain: BrainResolution) -> None:
env = hardened_child_env(inject_openai_key=False)
if brain.kind == "cloud-openai" and brain.api_key:
env.setdefault("OPENAI_API_KEY", brain.api_key)
+ popen_kwargs: dict[str, object] = {}
+ if os.name != "nt":
+ # Its own process group so _kill_tree's killpg reaches every worker.
+ popen_kwargs["start_new_session"] = True
with open(smoke_log, "ab") as sink:
proc = subprocess.Popen(
cmd,
@@ -377,6 +407,7 @@ def _smoke_boot(launch_command: str, brain: BrainResolution) -> None:
stderr=sink,
env=env,
creationflags=NO_WINDOW_CREATIONFLAGS,
+ **popen_kwargs, # type: ignore[arg-type]
)
try:
deadline = time.monotonic() + _SMOKE_TIMEOUT_S
diff --git a/jarvis/realtime/local_server/preflight.py b/jarvis/realtime/local_server/preflight.py
index ac7ec12ee6..f0cd516ca2 100644
--- a/jarvis/realtime/local_server/preflight.py
+++ b/jarvis/realtime/local_server/preflight.py
@@ -74,20 +74,57 @@ def _disk_free_gb(root: Path) -> float:
return 0.0
+def _preferred_brain_model() -> str:
+ """The user's configured Ollama brain model, read cheaply and fail-open.
+
+ A plain TOML read (no full config model) because this runs inside a
+ read-only probe; any problem answers "" and the resolver simply applies
+ its curated preference order.
+ """
+ try:
+ import tomllib
+
+ from jarvis.core.config import resolve_config_path
+
+ path = resolve_config_path()
+ if not path.exists():
+ return ""
+ with open(path, "rb") as fh:
+ data = tomllib.load(fh)
+ providers = (data.get("brain") or {}).get("providers") or {}
+ return str((providers.get("ollama") or {}).get("model") or "").strip()
+ except Exception: # noqa: BLE001 — a probe must never raise
+ log.debug("preflight: preferred-brain-model read failed", exc_info=True)
+ return ""
+
+
def run_preflight(install_root: Path) -> PreflightReport:
"""The full go/no-go report for a managed install under ``install_root``."""
usable_gb, source = _usable_accelerator_gb()
disk_free = _disk_free_gb(install_root)
tier = pick_tier(usable_gb)
if tier is None:
- return PreflightReport(
- ok=False,
- blocker=(
+ if source == "none":
+ # "0 GB accelerator memory" is factually WRONG on a machine with
+ # a 24 GB Radeon or an Arc card — the honest statement is that
+ # the managed stack does not support that hardware (yet), and
+ # the same sentence covers a headless box without nvidia-smi.
+ blocker = (
+ "No supported accelerator was found: the managed stack "
+ "currently needs an NVIDIA GPU (CUDA) or Apple Silicon. "
+ "AMD and Intel GPUs are not supported by it yet, and a "
+ "missing nvidia-smi hides an NVIDIA card."
+ )
+ else:
+ blocker = (
f"This machine has {usable_gb:.0f} GB of usable accelerator "
f"memory — under the {FLOOR_GB:.0f} GB minimum for a good "
"local realtime experience, so the managed install is not "
"offered here."
- ),
+ )
+ return PreflightReport(
+ ok=False,
+ blocker=blocker,
actions=(
"Use a cloud realtime provider on this machine (same card list).",
"Or point this card at a self-hosted server on a stronger machine.",
@@ -110,7 +147,9 @@ def run_preflight(install_root: Path) -> PreflightReport:
disk_free_gb=disk_free,
tier=tier,
)
- brain = resolve_brain()
+ brain = resolve_brain(
+ preferred_model=_preferred_brain_model(), usable_gb=usable_gb
+ )
if not brain.ok:
return PreflightReport(
ok=False,
diff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx
index e68b70474d..cebc6f10d0 100644
--- a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx
+++ b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx
@@ -13,6 +13,7 @@ import {
loginAntigravity,
localInstallStatus,
logoutAntigravity,
+ managedServerBrain,
managedServerInstall,
managedServerPreflight,
managedServerStart,
@@ -1913,6 +1914,7 @@ function ManagedServerPanel({
const [preflight, setPreflight] = useState<ManagedPreflight | null>(null);
const [progress, setProgress] = useState<ManagedInstallProgress | null>(null);
const [runtime, setRuntime] = useState<ManagedServerRuntime | null>(null);
+ const [brainNote, setBrainNote] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [checking, setChecking] = useState(false);
const [lifecycleBusy, setLifecycleBusy] = useState(false);
@@ -2036,6 +2038,20 @@ function ManagedServerPanel({
}
};
+ const refreshBrain = async () => {
+ setError(null);
+ setBrainNote(null);
+ setLifecycleBusy(true);
+ try {
+ const result = await managedServerBrain();
+ setBrainNote(result.brain.note);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : String(err));
+ } finally {
+ setLifecycleBusy(false);
+ }
+ };
+
const stopServer = async () => {
setError(null);
setLifecycleBusy(true);
@@ -2131,9 +2147,26 @@ function ManagedServerPanel({
{t("apikeys_view.managed_stop_cta")}
</Button>
)}
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={refreshBrain}
+ disabled={lifecycleBusy}
+ className="h-6 gap-1.5 px-2 text-[11px]"
+ title={t("apikeys_view.managed_brain_recheck_hint")}
+ >
+ <Brain className="h-3 w-3" />
+ {t("apikeys_view.managed_brain_recheck")}
+ </Button>
</div>
)}
+ {brainNote && (
+ <p className="text-[11px] text-muted-foreground" aria-live="polite">
+ {brainNote}
+ </p>
+ )}
+
{running && (
<div className="space-y-1">
<div className="h-1.5 w-full overflow-hidden rounded bg-muted">
diff --git a/jarvis/ui/web/frontend/src/hooks/useProviders.ts b/jarvis/ui/web/frontend/src/hooks/useProviders.ts
index 78fe61819d..a5f7a74285 100644
--- a/jarvis/ui/web/frontend/src/hooks/useProviders.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useProviders.ts
@@ -921,6 +921,26 @@ export async function managedServerStart(): Promise<ManagedServerRuntime | null>
return (body.runtime ?? null) as ManagedServerRuntime | null;
}
+/** Re-resolve the Ollama brain model and rewrite the launch command in place. */
+export async function managedServerBrain(model?: string): Promise<{
+ ok: boolean;
+ changed: boolean;
+ brain: { kind: string; model: string; note: string };
+}> {
+ const res = await fetch("/api/providers/local-realtime/managed-server/brain", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ model: model ?? "" }),
+ });
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) throw new Error(body.detail ?? `HTTP ${res.status}`);
+ return body as {
+ ok: boolean;
+ changed: boolean;
+ brain: { kind: string; model: string; note: string };
+ };
+}
+
export async function managedServerStop(): Promise<ManagedServerRuntime | null> {
const res = await fetch("/api/providers/local-realtime/managed-server/stop", {
method: "POST",
diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.py
index dd5b786a77..7bcfa54230 100644
--- a/jarvis/ui/web/provider_routes.py
+++ b/jarvis/ui/web/provider_routes.py
@@ -2791,6 +2791,60 @@ async def managed_server_stop(request: Request) -> dict[str, Any]:
return {"ok": True, "message": message, "runtime": runtime}
[email protected]("/providers/local-realtime/managed-server/brain")
+async def managed_server_brain(request: Request) -> dict[str, Any]:
+ """Re-resolve the brain model and rewrite the launch command in place.
+
+ The model choice is baked into the persisted command; before this route
+ changing it meant a full multi-gigabyte reinstall. Optional body
+ ``{"model": "..."}`` names an explicit Ollama tag (else the configured
+ ollama-card model, else the curated preference order). Only the managed
+ command is ever rewritten (`only_if_under` autonomy guard); the running
+ server keeps its old brain until the next start.
+ """
+ from jarvis.core.config_writer import update_local_realtime_launch_model
+ from jarvis.realtime.local_server.brain_link import resolve_brain
+ from jarvis.realtime.local_server.install import install_root
+ from jarvis.realtime.local_server.preflight import (
+ _preferred_brain_model,
+ _usable_accelerator_gb,
+ )
+
+ requested = ""
+ try:
+ body = await request.json()
+ requested = str((body or {}).get("model", "") or "").strip()
+ except Exception: # noqa: BLE001 — an empty/absent body is the normal case
+ requested = ""
+
+ def _resolve() -> Any:
+ usable_gb, _source = _usable_accelerator_gb()
+ return resolve_brain(
+ preferred_model=requested or _preferred_brain_model(),
+ usable_gb=usable_gb,
+ )
+
+ brain = await asyncio.to_thread(_resolve)
+ if not brain.ok or brain.kind != "ollama":
+ raise HTTPException(
+ status_code=409,
+ detail=(
+ brain.note
+ or "no usable local brain was found — install one via Ollama first"
+ ),
+ )
+ changed = await asyncio.to_thread(
+ lambda: update_local_realtime_launch_model(
+ brain.model, only_if_under=str(install_root())
+ )
+ )
+ return {
+ "ok": True,
+ "changed": changed,
+ "brain": {"kind": brain.kind, "model": brain.model, "note": brain.note},
+ }
+
+
@router.delete(
"/providers/local-realtime/managed-server",
openapi_extra={"x-jarvis-dangerous": True},
diff --git a/tests/unit/realtime/local_server/test_engine.py b/tests/unit/realtime/local_server/test_engine.py
index 1622366a2d..685e058cd5 100644
--- a/tests/unit/realtime/local_server/test_engine.py
+++ b/tests/unit/realtime/local_server/test_engine.py
@@ -39,14 +39,53 @@ class TestTierLadder:
class TestBrainResolution:
def test_prefers_the_pinned_model(self) -> None:
- assert brain_link._pick_model(["llama3.1:8b", "qwen2.5:7b"]) == "qwen2.5:7b"
+ chosen, note = brain_link._pick_model(
+ [("llama3.1:8b", 4.9), ("qwen2.5:7b", 4.7)]
+ )
+ assert chosen == "qwen2.5:7b"
+ assert note == ""
def test_skips_non_chat_models(self) -> None:
- assert brain_link._pick_model(["nomic-embed-text:latest"]) == ""
- assert brain_link._pick_model(["nomic-embed-text:latest", "mistral:7b"]) == "mistral:7b"
+ assert brain_link._pick_model([("nomic-embed-text:latest", 0.3)])[0] == ""
+ assert (
+ brain_link._pick_model(
+ [("nomic-embed-text:latest", 0.3), ("mistral:7b", 4.4)]
+ )[0]
+ == "mistral:7b"
+ )
+
+ def test_a_configured_model_wins_when_it_fits(self) -> None:
+ chosen, note = brain_link._pick_model(
+ [("qwen2.5:7b", 4.7), ("mistral:7b", 4.4)],
+ preferred_model="mistral:7b",
+ usable_gb=16.0,
+ )
+ assert chosen == "mistral:7b"
+ assert note == ""
+
+ def test_an_oversized_model_is_skipped_with_the_reason(self) -> None:
+ """A 24 GB tag on a 16 GB card would OOM at the first turn next to
+ the TTS; the resolver must pick a fitting model and SAY why."""
+ chosen, note = brain_link._pick_model(
+ [("nemotron-cascade-2:latest", 24.0), ("qwen2.5:7b", 4.7)],
+ preferred_model="nemotron-cascade-2:latest",
+ usable_gb=16.0,
+ )
+ assert chosen == "qwen2.5:7b"
+ assert "does not fit" in note
+
+ def test_unknown_sizes_never_veto(self) -> None:
+ """A tags payload without sizes must behave exactly as before the
+ fit check existed (fail-open)."""
+ chosen, _note = brain_link._pick_model(
+ [("mystery-model:latest", 0.0)], usable_gb=16.0
+ )
+ assert chosen == "mystery-model:latest"
def test_running_ollama_with_model_is_fully_local(self, monkeypatch) -> None:
- monkeypatch.setattr(brain_link, "_ollama_tags", lambda base, timeout: ["qwen2.5:7b"])
+ monkeypatch.setattr(
+ brain_link, "_ollama_models", lambda base, timeout: [("qwen2.5:7b", 4.7)]
+ )
resolution = brain_link.resolve_brain()
assert resolution.kind == "ollama"
assert resolution.ok
@@ -54,13 +93,13 @@ class TestBrainResolution:
assert resolution.model == "qwen2.5:7b"
def test_empty_ollama_blocks_with_pull_action(self, monkeypatch) -> None:
- monkeypatch.setattr(brain_link, "_ollama_tags", lambda base, timeout: [])
+ monkeypatch.setattr(brain_link, "_ollama_models", lambda base, timeout: [])
resolution = brain_link.resolve_brain()
assert resolution.kind == "blocked"
assert any("ollama pull" in action for action in resolution.actions)
def test_no_ollama_with_key_goes_cloud_with_honest_note(self, monkeypatch) -> None:
- monkeypatch.setattr(brain_link, "_ollama_tags", lambda base, timeout: None)
+ monkeypatch.setattr(brain_link, "_ollama_models", lambda base, timeout: None)
monkeypatch.setattr(brain_link, "_openai_key", lambda: "sk-test")
resolution = brain_link.resolve_brain()
assert resolution.kind == "cloud-openai"
@@ -68,7 +107,7 @@ class TestBrainResolution:
assert resolution.base_url == "" # server default; key stays out of commands
def test_nothing_available_blocks_with_actions(self, monkeypatch) -> None:
- monkeypatch.setattr(brain_link, "_ollama_tags", lambda base, timeout: None)
+ monkeypatch.setattr(brain_link, "_ollama_models", lambda base, timeout: None)
monkeypatch.setattr(brain_link, "_openai_key", lambda: "")
resolution = brain_link.resolve_brain()
assert resolution.kind == "blocked"
@@ -97,7 +136,7 @@ class TestPreflight:
monkeypatch.setattr(
preflight,
"resolve_brain",
- lambda: brain_link.BrainResolution(
+ lambda **kwargs: brain_link.BrainResolution(
kind="ollama", base_url="http://127.0.0.1:11434/v1", model="qwen2.5:7b"
),
)
@@ -114,7 +153,9 @@ class TestPreflight:
monkeypatch.setattr(
preflight,
"resolve_brain",
- lambda: brain_link.BrainResolution(kind="blocked", note="no brain", actions=("x",)),
+ lambda **kwargs: brain_link.BrainResolution(
+ kind="blocked", note="no brain", actions=("x",)
+ ),
)
report = preflight.run_preflight(tmp_path)
assert not report.ok
@@ -312,5 +353,101 @@ class TestReviewFixes:
install._rmtree_tolerant(root)
+class TestCrossPlatformHonesty:
+ """Contracts from the 2026-08-08 hardening plan (Wave 4)."""
+
+ def test_unsupported_gpu_gets_the_vendor_sentence_not_zero_gb(
+ self, monkeypatch, tmp_path: Path
+ ) -> None:
+ """"0 GB accelerator memory" is factually wrong on an AMD/Intel box
+ (and on a headless NVIDIA host without nvidia-smi); the blocker must
+ name the real situation."""
+ monkeypatch.setattr(preflight, "_usable_accelerator_gb", lambda: (0.0, "none"))
+ report = preflight.run_preflight(tmp_path)
+ assert not report.ok
+ assert "No supported accelerator" in report.blocker
+ assert "0 GB" not in report.blocker
+
+ @pytest.mark.skipif(
+ __import__("os").name == "nt", reason="exercises the POSIX venv layout"
+ )
+ def test_site_packages_globs_the_venv_not_the_host(
+ self, monkeypatch, tmp_path: Path
+ ) -> None:
+ """POSIX: the venv may have been created by a different Python than
+ the one running Jarvis; the real directory wins over the host's
+ sys.version_info guess."""
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))
+ site = install.install_root() / "venv" / "lib" / "python3.9" / "site-packages"
+ site.mkdir(parents=True)
+ assert install._site_packages() == site
+
+ def test_launch_model_rewrite_changes_only_the_model_token(
+ self, tmp_path: Path
+ ) -> None:
+ from jarvis.core.config_writer import update_local_realtime_launch_model
+
+ managed = tmp_path / "data" / "local_realtime"
+ entrypoint = (managed / "venv" / "s.exe").as_posix()
+ cfg = tmp_path / "jarvis.toml"
+ cfg.write_text(
+ "[brain.providers.local-realtime]\n"
+ f"launch_command = \"'{entrypoint}' --mode realtime "
+ "--model_name qwen2.5:7b "
+ '--responses_api_base_url http://127.0.0.1:11434/v1"\n',
+ encoding="utf-8",
+ )
+ changed = update_local_realtime_launch_model(
+ "llama3.1:8b", only_if_under=str(managed), path=cfg
+ )
+ assert changed is True
+ text = cfg.read_text(encoding="utf-8")
+ assert "--model_name llama3.1:8b" in text
+ assert "qwen2.5:7b" not in text
+ assert "--responses_api_base_url http://127.0.0.1:11434/v1" in text
+ assert "--mode realtime" in text
+
+ def test_launch_model_rewrite_spares_a_bring_your_own_command(
+ self, tmp_path: Path
+ ) -> None:
+ from jarvis.core.config_writer import update_local_realtime_launch_model
+
+ cfg = tmp_path / "jarvis.toml"
+ original = '[brain.providers.local-realtime]\nlaunch_command = "/opt/run --model_name x"\n'
+ cfg.write_text(original, encoding="utf-8")
+ changed = update_local_realtime_launch_model(
+ "y", only_if_under=str(tmp_path / "data" / "local_realtime"), path=cfg
+ )
+ assert changed is False
+ assert "--model_name x" in cfg.read_text(encoding="utf-8")
+
+ def test_launch_model_rewrite_is_a_noop_without_the_flag(
+ self, tmp_path: Path
+ ) -> None:
+ from jarvis.core.config_writer import update_local_realtime_launch_model
+
+ cfg = tmp_path / "jarvis.toml"
+ cfg.write_text(
+ '[brain.providers.local-realtime]\nlaunch_command = "serve --mode realtime"\n',
+ encoding="utf-8",
+ )
+ assert update_local_realtime_launch_model("m", path=cfg) is False
+
+ def test_command_root_match_is_case_sensitive_on_posix(self) -> None:
+ """Lowercasing both sides everywhere made two DISTINCT case-sensitive
+ POSIX paths compare equal; only Windows folds case."""
+ from jarvis.core import config_writer
+
+ assert not config_writer._command_references_root(
+ '"/home/User/Data/tree/run" --x', "/home/user/data/tree", windows=False
+ )
+ assert config_writer._command_references_root(
+ '"/home/user/data/tree/run" --x', "/home/user/data/tree", windows=False
+ )
+ assert config_writer._command_references_root(
+ '"C:\\Data\\Tree\\run.exe" --x', "c:\\data\\tree", windows=True
+ )
+
+
if __name__ == "__main__": # pragma: no cover
raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/tests/unit/realtime/local_server/test_supervisor.py b/tests/unit/realtime/local_server/test_supervisor.py
index cd2b8be473..d432bb5cfb 100644
--- a/tests/unit/realtime/local_server/test_supervisor.py
+++ b/tests/unit/realtime/local_server/test_supervisor.py
@@ -20,13 +20,21 @@ from jarvis.realtime.local_server import supervisor
def _spawn_ready(monkeypatch, tmp_path: Path) -> list[dict[str, Any]]:
- """Common arrangement: closed port, no pidfile, fake Popen, tmp data dir."""
+ """Common arrangement: closed port, no pidfile, fake Popen, tmp data dir.
+
+ Only launch commands starting with "serve" are recorded: the hardened
+ child env's keyring lookup can shell out on its own (a `ver` subprocess
+ on Windows), and counting those as server spawns failed the rate-limit
+ assertion for the wrong reason.
+ """
monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))
monkeypatch.setattr(supervisor, "_port_open", lambda port, timeout=1.0: False)
spawned: list[dict[str, Any]] = []
def fake_popen(command: Any, **kwargs: Any) -> SimpleNamespace:
- spawned.append({"command": command, **kwargs})
+ head = command if isinstance(command, str) else " ".join(command)
+ if head.startswith("serve"):
+ spawned.append({"command": command, **kwargs})
return SimpleNamespace(pid=4711)
monkeypatch.setattr(subprocess, "Popen", fake_popen)
diff --git a/tests/unit/ui/web/test_managed_local_realtime_routes.py b/tests/unit/ui/web/test_managed_local_realtime_routes.py
index 756d39a054..52355a2fad 100644
--- a/tests/unit/ui/web/test_managed_local_realtime_routes.py
+++ b/tests/unit/ui/web/test_managed_local_realtime_routes.py
@@ -50,7 +50,7 @@ def test_preflight_reports_tier_and_brain_when_ok(
monkeypatch.setattr(
preflight,
"resolve_brain",
- lambda: brain_link.BrainResolution(
+ lambda **kwargs: brain_link.BrainResolution(
kind="ollama", base_url="http://127.0.0.1:11434/v1", model="qwen2.5:7b"
),
)
@@ -176,6 +176,57 @@ def test_start_spawns_and_warms_the_brain(
assert body["runtime"]["reachable"] is True
+def test_brain_route_rewrites_the_model_without_reinstall(
+ server: WebServer, monkeypatch: pytest.MonkeyPatch, tmp_path
+) -> None:
+ from jarvis.core.config_writer import set_local_realtime_launch_command
+
+ cfg_file = tmp_path / "jarvis.toml"
+ cfg_file.write_text("", encoding="utf-8")
+ entrypoint = (install.install_root() / "venv" / "s.exe").as_posix()
+ set_local_realtime_launch_command(
+ f"'{entrypoint}' --mode realtime --model_name qwen2.5:7b", path=cfg_file
+ )
+ monkeypatch.setattr(preflight, "_usable_accelerator_gb", lambda: (16.0, "nvidia-smi"))
+ monkeypatch.setattr(
+ brain_link, "_ollama_models", lambda base, timeout: [("llama3.1:8b", 4.9)]
+ )
+ # Route writes through config_writer against the real DEFAULT_CONFIG_FILE;
+ # redirect it at the writer level for the test.
+ import jarvis.core.config_writer as config_writer
+
+ original = config_writer.update_local_realtime_launch_model
+
+ def redirected(model: str, *, only_if_under: str = "", path=None) -> bool:
+ return original(model, only_if_under=only_if_under, path=cfg_file)
+
+ monkeypatch.setattr(
+ config_writer, "update_local_realtime_launch_model", redirected
+ )
+ with TestClient(server.app) as client:
+ resp = client.post(
+ "/api/providers/local-realtime/managed-server/brain",
+ json={"model": "llama3.1:8b"},
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["ok"] is True
+ assert body["changed"] is True
+ assert body["brain"]["model"] == "llama3.1:8b"
+ assert "--model_name llama3.1:8b" in cfg_file.read_text(encoding="utf-8")
+
+
+def test_brain_route_answers_409_without_a_local_brain(
+ server: WebServer, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(preflight, "_usable_accelerator_gb", lambda: (16.0, "nvidia-smi"))
+ monkeypatch.setattr(brain_link, "_ollama_models", lambda base, timeout: None)
+ monkeypatch.setattr(brain_link, "_openai_key", lambda: "")
+ with TestClient(server.app) as client:
+ resp = client.post("/api/providers/local-realtime/managed-server/brain")
+ assert resp.status_code == 409
+
+
def test_stop_answers_409_when_nothing_is_owned(
server: WebServer, monkeypatch: pytest.MonkeyPatch
) -> None: