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: bound local realtime warm-up resources

rubenluetke10-beep7396b50cc316
diff --git a/jarvis/realtime/factory.py b/jarvis/realtime/factory.py
index 684012fd76..f9ed193f6b 100644
--- a/jarvis/realtime/factory.py
+++ b/jarvis/realtime/factory.py
@@ -246,12 +246,15 @@ def _realtime_is_the_configured_voice_mode(cfg: Any) -> bool:
async def realtime_warm_selected_transports(cfg: Any) -> None:
- """Let every explicitly selected provider pre-open its transport.
+ """Pre-open the primary transport and only explicitly safe fallbacks.
A capability probe, never a provider-id check (AP-21): a provider that
- declares no ``warm_transport`` is simply skipped. Only explicitly selected
- primary/fallback providers are warmed — an installed-but-unselected plugin
- must not spawn a process or touch a credential on its own.
+ declares no ``warm_transport`` is simply skipped. The primary is always
+ eligible. A fallback must additionally declare
+ ``eager_warm_as_fallback=True``: preloading multiple native model stacks can
+ oversubscribe shared GPU/RAM even though only one call transport is used.
+ An installed-but-unselected plugin must never spawn a process or touch a
+ credential on its own.
Warming exists because the Codex subscription adapter otherwise spawns its
app-server and verifies the account INSIDE the first call's handshake
@@ -270,9 +273,18 @@ async def realtime_warm_selected_transports(cfg: Any) -> None:
"voice mode."
)
return
- for provider_id in _explicit_provider_ids(cfg):
+ for position, provider_id in enumerate(_explicit_provider_ids(cfg)):
try:
provider_cls = load(_GROUP, provider_id, protocol=RealtimeProvider)
+ if position > 0 and not bool(
+ getattr(provider_cls, "eager_warm_as_fallback", False)
+ ):
+ log.debug(
+ "Realtime fallback warm skipped for %s: provider did not "
+ "declare eager_warm_as_fallback.",
+ provider_id,
+ )
+ continue
warm = getattr(provider_cls, "warm_transport", None)
if callable(warm):
await warm(cfg)
diff --git a/jarvis/realtime/local_server/install.py b/jarvis/realtime/local_server/install.py
index 13b216e24d..0e32af14a9 100644
--- a/jarvis/realtime/local_server/install.py
+++ b/jarvis/realtime/local_server/install.py
@@ -777,6 +777,16 @@ def _run_install_guarded(confirmed_brain: str = "") -> None:
_set("smoke", 70, "first boot (downloads voice/hearing models once)")
launch_command = derive_launch_command(report.brain, memory_source=report.memory_source)
+ if report.brain.kind == "ollama":
+ # The OpenAI-compatible Ollama API cannot carry num_ctx per request.
+ # Create/use the managed 8k profile before the first smoke boot so
+ # installation itself cannot reserve a model's full native context
+ # and push the desktop into shared-GPU-memory paging.
+ from jarvis.realtime.local_server import supervisor as local_supervisor
+
+ launch_command = local_supervisor.prepare_voice_brain_command(
+ launch_command
+ )
_smoke_boot(launch_command, report.brain)
_set("configure", 96, "writing the launch configuration")
diff --git a/jarvis/realtime/local_server/supervisor.py b/jarvis/realtime/local_server/supervisor.py
index 30e55108e0..13464d4bde 100644
--- a/jarvis/realtime/local_server/supervisor.py
+++ b/jarvis/realtime/local_server/supervisor.py
@@ -74,6 +74,18 @@ _MAX_POOL_RESPONSE_BYTES = 64 * 1024
#: so only a genuinely idle multi-hour gap pays a reload.
BRAIN_KEEP_ALIVE = "2h"
+# Ollama's OpenAI-compatible endpoints cannot accept a per-request context
+# size. Current long-context models can therefore reserve their full native
+# window (qwen3.5:4b used 262,144 tokens and spilled 5+ GiB into shared GPU
+# memory on a 16 GiB card). The managed voice stack needs only a compact turn
+# history, so it runs through a deterministic Ollama profile with an explicit
+# bounded context. This leaves room for local TTS and prevents system-wide
+# WDDM paging while preserving the user's chosen base model.
+VOICE_BRAIN_CONTEXT_TOKENS = 8192
+_VOICE_MODEL_SUFFIX = "-voice-8k"
+_VOICE_MODEL_PREPARE_LOCK = threading.Lock()
+_prepared_voice_models: set[tuple[str, str, str]] = set()
+
_DEFAULT_PORT = 8765
_WINDOWS_NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0x08000000)
@@ -782,6 +794,14 @@ def ensure_running(*, launch_command: str, base_url: str, reason: str) -> str:
"local-realtime supervisor: removed %s orphan process(es) before spawn",
killed,
)
+ try:
+ command = prepare_voice_brain_command(command)
+ except RuntimeError as exc:
+ log.warning(
+ "local-realtime supervisor: bounded brain profile failed: %s",
+ exc,
+ )
+ return "refused:brain-context-profile"
clear_pidfile()
spawned_pid = _spawn(command, reason=reason)
if spawned_pid is None:
@@ -1359,6 +1379,7 @@ def warm_brain(*, launch_command: str, timeout: float = 5.0) -> bool:
first sentence after a pause pays a multi-second cold load. Best-effort:
a non-Ollama endpoint simply answers 404 and nothing changes.
"""
+ launch_command = _effective_owned_launch_command(launch_command)
model, brain_url = _brain_endpoint(launch_command)
if not model or not brain_url:
return False
@@ -1389,22 +1410,131 @@ def warm_brain(*, launch_command: str, timeout: float = 5.0) -> bool:
return True
+def prepare_voice_brain_command(
+ launch_command: str, *, timeout: float = 30.0
+) -> str:
+ """Return a managed-server command using a bounded Ollama context profile.
+
+ Ollama documents that its OpenAI-compatible API has no context-size field;
+ a model created with ``num_ctx`` is the supported control surface. Creating
+ this alias changes no weights and performs no download. Cloud/BYO commands
+ are returned unchanged.
+ """
+ model, brain_url, api_key = _brain_endpoint_details(launch_command)
+ if not model or not brain_url or api_key.lower() != "ollama":
+ return launch_command
+ root = brain_url[: -len("/v1")] if brain_url.endswith("/v1") else brain_url
+ if not root.startswith(("http://", "https://")):
+ return launch_command
+
+ source_model, voice_model = _voice_context_models(model)
+ cache_key = (root, source_model, voice_model)
+ with _VOICE_MODEL_PREPARE_LOCK:
+ if cache_key not in _prepared_voice_models:
+ payload = json.dumps(
+ {
+ "model": voice_model,
+ "from": source_model,
+ "parameters": {"num_ctx": VOICE_BRAIN_CONTEXT_TOKENS},
+ "stream": False,
+ }
+ ).encode("utf-8")
+ import urllib.error
+ import urllib.request
+
+ url = f"{root}/api/create"
+ request = urllib.request.Request( # noqa: S310 - scheme checked above
+ url, data=payload, headers={"Content-Type": "application/json"}
+ )
+ try:
+ with urllib.request.urlopen(request, timeout=timeout): # noqa: S310
+ pass
+ except (urllib.error.URLError, OSError, ValueError) as exc:
+ raise RuntimeError(
+ f"could not create the {VOICE_BRAIN_CONTEXT_TOKENS}-token "
+ f"Ollama voice profile for {source_model}: {exc}"
+ ) from exc
+ _prepared_voice_models.add(cache_key)
+ log.info(
+ "local-realtime supervisor: prepared bounded Ollama model %s "
+ "from %s (num_ctx=%s)",
+ voice_model,
+ source_model,
+ VOICE_BRAIN_CONTEXT_TOKENS,
+ )
+ return _replace_brain_model(launch_command, voice_model)
+
+
+def _voice_context_models(model: str) -> tuple[str, str]:
+ """Return ``(base, bounded_alias)`` for an Ollama model tag."""
+ cleaned = model.strip()
+ if ":" in cleaned:
+ name, tag = cleaned.rsplit(":", 1)
+ else:
+ name, tag = cleaned, "latest"
+ if tag.endswith(_VOICE_MODEL_SUFFIX):
+ return f"{name}:{tag[: -len(_VOICE_MODEL_SUFFIX)]}", cleaned
+ return cleaned, f"{name}:{tag}{_VOICE_MODEL_SUFFIX}"
+
+
+_MODEL_NAME_FLAG = re.compile(
+ r"(?<!\S)(?P<flag>--model_name)(?P<sep>\s+|=)"
+ r"(?P<value>\"[^\"]*\"|'[^']*'|\S+)",
+ re.IGNORECASE,
+)
+
+
+def _replace_brain_model(command: str, model: str) -> str:
+ """Replace only the managed server's model flag, preserving its quoting."""
+
+ def _replacement(match: re.Match[str]) -> str:
+ value = match.group("value")
+ quote = value[0] if value[:1] in {'"', "'"} else ""
+ rendered = f"{quote}{model}{quote}" if quote else model
+ return f"{match.group('flag')}{match.group('sep')}{rendered}"
+
+ return _MODEL_NAME_FLAG.sub(_replacement, command, count=1)
+
+
+def _effective_owned_launch_command(configured_command: str) -> str:
+ """Use the exact owned generation's command when warming its brain."""
+ configured_root = managed_install_root(configured_command)
+ if configured_root is None:
+ return configured_command
+ active_command = _verified_owned_command()
+ if (
+ active_command is not None
+ and managed_install_root(active_command) == configured_root
+ ):
+ return active_command
+ return configured_command
+
+
def _brain_endpoint(launch_command: str) -> tuple[str, str]:
"""(model, responses_api_base_url) parsed from a launch command."""
+ model, base, _api_key = _brain_endpoint_details(launch_command)
+ return model, base
+
+
+def _brain_endpoint_details(launch_command: str) -> tuple[str, str, str]:
+ """(model, Responses base URL, placeholder key) parsed from a command."""
try:
import shlex
tokens = shlex.split(launch_command or "", posix=os.name != "nt")
except ValueError:
- return "", ""
+ return "", "", ""
model = ""
base = ""
+ api_key = ""
for index, flag in enumerate(tokens[:-1]):
if flag == "--model_name":
model = tokens[index + 1].strip('"')
elif flag == "--responses_api_base_url":
base = tokens[index + 1].strip('"').rstrip("/")
- return model, base
+ elif flag == "--responses_api_api_key":
+ api_key = tokens[index + 1].strip('"')
+ return model, base, api_key
# ── Test support ─────────────────────────────────────────────────────────
@@ -1414,6 +1544,7 @@ def _reset_for_tests() -> None:
"""Reset module-level rate-limit and monitor state between tests."""
global _last_spawn_at, _monitor_thread, _monitor_stop, _monitor_key
_last_spawn_at = float("-inf")
+ _prepared_voice_models.clear()
with _MONITOR_LOCK:
if _monitor_stop is not None:
_monitor_stop.set()
diff --git a/tests/unit/realtime/local_server/test_supervisor.py b/tests/unit/realtime/local_server/test_supervisor.py
index a4f3ae8002..b53971b985 100644
--- a/tests/unit/realtime/local_server/test_supervisor.py
+++ b/tests/unit/realtime/local_server/test_supervisor.py
@@ -355,6 +355,43 @@ def test_an_owned_managed_zombie_is_replaced_after_startup_deadline(
assert spawned and "--ws_host 127.0.0.1" in spawned[0]
+def test_managed_spawn_uses_the_bounded_voice_brain_command(
+ monkeypatch, tmp_path
+) -> None:
+ """The resource-safe profile must reach Popen, not just a helper test."""
+ from jarvis.realtime.local_server import install
+
+ supervisor._reset_for_tests()
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))
+ entrypoint = install.install_root() / "venv" / "server.exe"
+ command = f'"{entrypoint}" --mode realtime --model_name qwen3.5:4b'
+ monkeypatch.setattr(supervisor, "probe_runtime", lambda *args, **kwargs: None)
+ monkeypatch.setattr(supervisor, "_port_open", lambda *args, **kwargs: False)
+ monkeypatch.setattr(supervisor, "_owned_process", lambda: (None, False))
+ monkeypatch.setattr(supervisor, "_kill_by_install_root", lambda root: (0, 0))
+ monkeypatch.setattr(
+ supervisor,
+ "prepare_voice_brain_command",
+ lambda candidate: candidate.replace("qwen3.5:4b", "qwen3.5:4b-voice-8k"),
+ )
+ spawned: list[str] = []
+ monkeypatch.setattr(
+ supervisor,
+ "_spawn",
+ lambda candidate, **kwargs: spawned.append(candidate) or 7331,
+ )
+ monkeypatch.setattr(supervisor, "_write_pidfile", lambda *args: True)
+
+ outcome = supervisor.ensure_running(
+ launch_command=command,
+ base_url="http://127.0.0.1:8765",
+ reason="test",
+ )
+
+ assert outcome == "spawned"
+ assert "--model_name qwen3.5:4b-voice-8k" in spawned[0]
+
+
def test_a_running_install_blocks_the_spawn(monkeypatch, tmp_path) -> None:
"""Spawning a half-installed venv proves nothing and locks files the
installer is about to replace."""
@@ -984,6 +1021,76 @@ def test_brain_endpoint_is_parsed_from_the_command() -> None:
assert base == "http://127.0.0.1:11434/v1"
+def test_voice_brain_command_creates_an_8k_ollama_profile(monkeypatch) -> None:
+ import urllib.request
+
+ requests: list[tuple[str, dict[str, Any]]] = []
+
+ class _Response:
+ def __enter__(self) -> _Response:
+ return self
+
+ def __exit__(self, *args: Any) -> None:
+ return None
+
+ def fake_urlopen(request: Any, timeout: float = 0.0) -> _Response:
+ requests.append((request.full_url, json.loads(request.data.decode("utf-8"))))
+ return _Response()
+
+ monkeypatch.setattr(urllib.request, "urlopen", fake_urlopen)
+
+ prepared = supervisor.prepare_voice_brain_command(_COMMAND)
+
+ assert "--model_name qwen2.5:7b-voice-8k" in prepared
+ assert requests == [
+ (
+ "http://127.0.0.1:11434/api/create",
+ {
+ "model": "qwen2.5:7b-voice-8k",
+ "from": "qwen2.5:7b",
+ "parameters": {"num_ctx": 8192},
+ "stream": False,
+ },
+ )
+ ]
+
+
+def test_voice_brain_profile_is_idempotent_across_restarts(monkeypatch) -> None:
+ import urllib.request
+
+ payloads: list[dict[str, Any]] = []
+
+ class _Response:
+ def __enter__(self) -> _Response:
+ return self
+
+ def __exit__(self, *args: Any) -> None:
+ return None
+
+ def fake_urlopen(request: Any, timeout: float = 0.0) -> _Response:
+ payloads.append(json.loads(request.data.decode("utf-8")))
+ return _Response()
+
+ monkeypatch.setattr(urllib.request, "urlopen", fake_urlopen)
+ aliased = _COMMAND.replace("qwen2.5:7b", "qwen2.5:7b-voice-8k")
+
+ assert supervisor.prepare_voice_brain_command(aliased) == aliased
+ assert payloads[0]["from"] == "qwen2.5:7b"
+ assert payloads[0]["model"] == "qwen2.5:7b-voice-8k"
+
+
+def test_cloud_brain_command_is_not_rewritten(monkeypatch) -> None:
+ import urllib.request
+
+ monkeypatch.setattr(
+ urllib.request,
+ "urlopen",
+ lambda *args, **kwargs: pytest.fail("cloud commands must not touch Ollama"),
+ )
+ cloud = _COMMAND.replace("--responses_api_api_key ollama", "")
+ assert supervisor.prepare_voice_brain_command(cloud) == cloud
+
+
def test_warm_brain_pings_ollama_with_keep_alive(monkeypatch) -> None:
import urllib.request
diff --git a/tests/unit/realtime/test_factory.py b/tests/unit/realtime/test_factory.py
index 9087859e68..4f508330e2 100644
--- a/tests/unit/realtime/test_factory.py
+++ b/tests/unit/realtime/test_factory.py
@@ -308,6 +308,7 @@ class _WarmProbe:
"""Minimal realtime provider exposing the optional warm capability."""
supports_realtime = True
+ eager_warm_as_fallback = True
def __init__(self) -> None:
self.calls = 0
@@ -340,6 +341,30 @@ async def test_warm_selected_transports_skips_providers_without_the_capability(
assert warm.calls == 1
+async def test_warm_selected_transports_does_not_prewarm_a_heavy_fallback(
+ monkeypatch,
+) -> None:
+ """An inactive fallback must not compete with the primary for GPU/RAM."""
+ primary = _WarmProbe()
+ fallback = _WarmProbe()
+ fallback.eager_warm_as_fallback = False
+ loaded = {"primary": primary, "heavy-fallback": fallback}
+ monkeypatch.setattr(
+ factory,
+ "_explicit_provider_ids",
+ lambda _cfg: ["primary", "heavy-fallback"],
+ )
+ monkeypatch.setattr(
+ factory, "load", lambda _group, pid, protocol=None: loaded[pid]
+ )
+
+ await factory.realtime_warm_selected_transports(_cfg())
+
+ assert primary.calls == 1
+ assert fallback.calls == 0
+
+
@pytest.mark.asyncio
async def test_warm_selected_transports_survives_one_broken_provider(
monkeypatch,
diff --git a/tests/unit/ui/web/test_realtime_transport_warm_boot_hook.py b/tests/unit/ui/web/test_realtime_transport_warm_boot_hook.py
index b8c66e4f6e..2dab5592e7 100644
--- a/tests/unit/ui/web/test_realtime_transport_warm_boot_hook.py
+++ b/tests/unit/ui/web/test_realtime_transport_warm_boot_hook.py
@@ -1,9 +1,9 @@
"""The web/headless boot path must warm the selected realtime transports.
-``realtime_warm_selected_transports`` pre-opens the transport of every
-explicitly selected realtime provider so its cold start (for a subscription
-transport: a spawned app-server plus a live account check) is not paid inside
-the user's first call. Its only caller used to be the desktop shell, which left
+``realtime_warm_selected_transports`` pre-opens the primary transport (plus any
+fallback that explicitly declares eager warming safe) so its cold start (for a
+subscription transport: a spawned app-server plus a live account check) is not
+paid inside the user's first call. Its only caller used to be the desktop shell, which left
``run.bat --headless`` and every browser-only install — headless Linux included
— paying that cost on every first call.