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): a self-hosted card, so every tier has a keyless option
rubenluetke10-beepa35f29d00ca9
diff --git a/jarvis/brain/model_catalog.py b/jarvis/brain/model_catalog.pyindex f302ae62d5..575a4d8b5d 100644--- a/jarvis/brain/model_catalog.py+++ b/jarvis/brain/model_catalog.py@@ -496,6 +496,11 @@ REALTIME_MODELS: dict[str, list[ModelInfo]] = {"codex-subscription-realtime": _curated([("auto", "ChatGPT-Live (model chosen by OpenAI)")]),+ # local-realtime: the served model is whatever its operator loaded, so the+ # only honest curated entry is "ask the server". The adapter resolves it+ # through /v1/models at connect time (same as the local brain card), and a+ # user who wants a specific one pins it on the card.+ "local-realtime": _curated([("auto", "Chosen by your server")]),"openai-realtime": _curated([("gpt-realtime", "GPT Realtime (default)"),@@ -554,6 +559,11 @@ REALTIME_VOICES: dict[str, list[ModelInfo]] = {"sol",]),+ # A self-hosted server ships whatever voices its operator installed, and a+ # list of OpenAI voice names would be a guess the server then rejects. One+ # honest entry: the adapter sends no voice override and the server uses its+ # own default.+ "local-realtime": _curated([("auto", "Your server's own voice")]),"openai-realtime": _ids(["alloy",diff --git a/jarvis/brain/provider_test.py b/jarvis/brain/provider_test.pyindex 6207e3b8d7..155ea8fb78 100644--- a/jarvis/brain/provider_test.py+++ b/jarvis/brain/provider_test.py@@ -289,10 +289,21 @@ async def _default_realtime_probe(spec: Any, cfg: Any, *, timeout_s: float) -> fprovider_cls = load("jarvis.realtime", spec.id, protocol=RealtimeProvider)credentials = tuple(getattr(provider_cls, "credential_candidates", ()) or ())- api_key = get_secret_any(credentials)- if not api_key:+ api_key = get_secret_any(credentials) if credentials else None+ if credentials and not api_key:raise RuntimeError("No API key configured for the realtime provider")- provider = provider_cls(api_key=api_key)+ if api_key:+ provider = provider_cls(api_key=api_key)+ else:+ # A keyless card (a server the user hosts themselves) declares no+ # credential slots at all. Building it the key way would demand a+ # credential it does not have and report a working endpoint as broken —+ # so it is built the same way the session factory builds it, from its+ # own configuration.+ from_runtime_config = getattr(provider_cls, "from_runtime_config", None)+ provider = (+ from_runtime_config(cfg) if callable(from_runtime_config) else provider_cls()+ )session_config = RealtimeSessionConfig(instructions="Connection validation only. Do not respond until audio arrives.",language="en",diff --git a/jarvis/dictation/polish_client.py b/jarvis/dictation/polish_client.pyindex a40cbbffd2..d4066348a1 100644--- a/jarvis/dictation/polish_client.py+++ b/jarvis/dictation/polish_client.py@@ -131,12 +131,51 @@ class PolishFamily:secret_candidates: tuple[str, ...]default_model: strdefault_timeout_ms: int+ #: Provider card this family INHERITS its address from, or None for a+ #: hosted endpoint that never moves. A self-hosted server has exactly one+ #: address, and the user set it once on that provider's card; keeping a+ #: second copy here pinned to localhost meant that moving the server to+ #: another box silently left this feature talking to nothing. Data, not a+ #: name branch (AP-21).+ endpoint_provider: str | None = None@propertydef needs_key(self) -> bool:"""Whether this family is reachable only with a credential."""return bool(self.secret_candidates)+ @property+ def effective_base_url(self) -> str:+ """The address this family is ACTUALLY reached at right now.++ A hosted family is its declared ``base_url``. A family that inherits+ (``endpoint_provider``) follows whatever server the user configured on+ that card — including one on another machine. Falls back to the+ declared address when the lookup cannot be made, which is the previous+ behaviour and never worse than it.+ """+ if not self.endpoint_provider:+ return self.base_url+ try:+ from jarvis.core import config as cfg # noqa: PLC0415 — lazy (AP-26)+ from jarvis.plugins.brain.ollama import ( # noqa: PLC0415 — pure helpers+ default_server_root,+ normalize_server_root,+ )++ endpoint = cfg.resolve_provider_endpoint(+ self.endpoint_provider, vendor_default_base_url=default_server_root()+ )+ root = normalize_server_root(endpoint.base_url or default_server_root())+ return f"{root}/v1"+ except Exception: # noqa: BLE001 — an unreadable config keeps the default+ log.debug(+ "polish: could not resolve the %s endpoint; using %s",+ self.endpoint_provider,+ self.base_url,+ )+ return self.base_url+@propertydef runs_on_device(self) -> bool:"""Whether this family's endpoint is on THIS machine.@@ -147,10 +186,11 @@ class PolishFamily:"the endpoint is a loopback address" is about whether the user's wordstravel over a network at all — and that is the only thing:func:`resolve_polish_chain` may act on when the recognizer itself is- on-device. Derived from the declared ``base_url``, so a new family is- still one row and no name is ever branched on (AP-21).+ on-device. Read off the EFFECTIVE address: an Ollama server on another+ box in the house is keyless but not on-device, and claiming otherwise+ would be a privacy promise we do not keep."""- host = (urlsplit(self.base_url).hostname or "").strip().lower()+ host = (urlsplit(self.effective_base_url).hostname or "").strip().lower()return host in _LOOPBACK_HOSTS@@ -227,10 +267,13 @@ POLISH_FAMILIES: Final[tuple[PolishFamily, ...]] = (id="ollama",label="Ollama (local)",transport="openai_chat",+ # Declared address is the vendor default; the effective one follows the+ # Ollama card, so a server moved to another machine keeps working.base_url="http://localhost:11434/v1",secret_candidates=(),default_model="llama3.1:8b",default_timeout_ms=3000,+ endpoint_provider="ollama",),)@@ -717,7 +760,7 @@ class OpenAIChatPolishClient:"""import httpx- url = f"{self._family.base_url.rstrip('/')}/chat/completions"+ url = f"{self._family.effective_base_url.rstrip('/')}/chat/completions"headers = {"Content-Type": "application/json"}if self._api_key:headers["Authorization"] = f"Bearer {self._api_key}"diff --git a/jarvis/plugins/realtime/openai_realtime.py b/jarvis/plugins/realtime/openai_realtime.pyindex 4bcfda04f0..93ab471167 100644--- a/jarvis/plugins/realtime/openai_realtime.py+++ b/jarvis/plugins/realtime/openai_realtime.py@@ -12,6 +12,7 @@ import asyncioimport base64import jsonimport logging+import osimport timefrom collections.abc import AsyncIteratorfrom dataclasses import dataclass@@ -201,14 +202,23 @@ def _response_status_error(event: Any) -> str:return f"{summary}: {detail}"[:800] if detail else summary-def _session_payload(cfg: Any) -> dict[str, Any]:+def _session_payload(+ cfg: Any, *, transcription_model: str | None = "gpt-4o-mini-transcribe"+) -> dict[str, Any]:"""Build the current GA ``session.update`` payload.Audio output already includes a transcript side-channel, so the RealtimeAPI accepts ``[\"audio\"]`` only; requesting text and audio together isinvalid. PCM input and output are both explicitly declared as 24 kHz.++ ``transcription_model`` is ``None`` for a self-hosted server: a hosted+ OpenAI model id is meaningless there and naming one would have the server+ reject the whole session for a field the user never chose. The server then+ transcribes with whatever it ships."""- transcription: dict[str, Any] = {"model": "gpt-4o-mini-transcribe"}+ transcription: dict[str, Any] = (+ {"model": transcription_model} if transcription_model else {}+ )input_language = str(getattr(cfg, "input_language", "auto") or "auto")input_language = input_language.strip().lower().replace("_", "-").split("-", 1)[0]if input_language in {"de", "en", "es"}:@@ -222,7 +232,10 @@ def _session_payload(cfg: Any) -> dict[str, Any]:"format": {"type": "audio/pcm", "rate": _OUTPUT_RATE},}voice = str(getattr(cfg, "voice", "") or "").strip()- if voice:+ # "auto" is the picker's way of saying "no preference" (the only honest+ # entry a self-hosted card can offer); sending it as a voice NAME would+ # have the server reject a voice it does not have.+ if voice and voice != "auto":output["voice"] = voiceturn_detection_config: dict[str, Any] = {@@ -1079,6 +1092,69 @@ class _OpenAIRealtimeSession:await result+async def _open_realtime_session(+ client: Any,+ cfg: Any,+ *,+ model: str,+ transcription_model: str | None = "gpt-4o-mini-transcribe",+) -> _OpenAIRealtimeSession:+ """Open, configure and hand back a live session on ``client``.++ Shared by the hosted OpenAI card and the self-hosted one: they differ only+ in which endpoint the client points at, and every hard-won detail below —+ the cleanup after a failed ``__aenter__``, the session payload, the+ mid-call history seed — must stay identical for both, so it lives here+ once rather than in two drifting copies.+ """+ connection_cm = client.realtime.connect(model=model)+ try:+ connection = await connection_cm.__aenter__()+ except BaseException as exc:+ # ``__aenter__`` may allocate the WebSocket before failing or being+ # cancelled. Python does not call ``__aexit__`` for a failed enter,+ # so close both layers explicitly and preserve the original error.+ try:+ await connection_cm.__aexit__(type(exc), exc, exc.__traceback__)+ except BaseException: # noqa: BLE001 - cleanup must not mask root cause+ log.debug(+ "Realtime connection cleanup after failed enter failed",+ exc_info=True,+ )+ try:+ close = getattr(client, "close", None)+ if close is not None:+ result = close()+ if hasattr(result, "__await__"):+ await result+ except BaseException: # noqa: BLE001 - preserve failure/cancellation+ log.debug(+ "Realtime client cleanup after failed enter failed", exc_info=True+ )+ raise+ payload = _session_payload(cfg, transcription_model=transcription_model)+ session = _OpenAIRealtimeSession(+ connection=connection,+ connection_cm=connection_cm,+ client=client,+ session_id=str(uuid4()),+ session_payload=payload,+ connect_model=model,+ history_seed=tuple(getattr(cfg, "history", ()) or ()),+ )+ try:+ await connection.session.update(session=payload)+ await session.wait_until_ready()+ except BaseException:+ await session.close()+ raise+ # A mid-call open (cross-family fallback after another provider's transport+ # died) carries the call transcript; restore it so the conversation survives+ # the provider crossing (BUG-088).+ await session._seed_conversation_history(connection)+ return session++class OpenAIRealtimeProvider:"""Structural provider entry point for the OpenAI Realtime family."""@@ -1109,50 +1185,177 @@ class OpenAIRealtimeProvider:client = AsyncOpenAI(api_key=self._api_key)connect_model = str(getattr(cfg, "model", "") or _MODEL)- connection_cm = client.realtime.connect(model=connect_model)- try:- connection = await connection_cm.__aenter__()- except BaseException as exc:- # ``__aenter__`` may allocate the WebSocket before failing or being- # cancelled. Python does not call ``__aexit__`` for a failed enter,- # so close both layers explicitly and preserve the original error.- try:- await connection_cm.__aexit__(type(exc), exc, exc.__traceback__)- except BaseException: # noqa: BLE001 - cleanup must not mask root cause- log.debug(- "OpenAI Realtime connection cleanup after failed enter failed",- exc_info=True,- )- try:- close = getattr(client, "close", None)- if close is not None:- result = close()- if hasattr(result, "__await__"):- await result- except BaseException: # noqa: BLE001 - preserve failure/cancellation- log.debug(- "OpenAI Realtime client cleanup after failed enter failed",- exc_info=True,- )- raise- payload = _session_payload(cfg)- session = _OpenAIRealtimeSession(- connection=connection,- connection_cm=connection_cm,- client=client,- session_id=str(uuid4()),- session_payload=payload,- connect_model=connect_model,- history_seed=tuple(getattr(cfg, "history", ()) or ()),+ return await _open_realtime_session(client, cfg, model=connect_model)+++# ---------------------------------------------------------------------------+# Self-hosted realtime — the same protocol, the user's own endpoint+# ---------------------------------------------------------------------------++#: Connect timeout for the model probe against a self-hosted server. Short on+#: purpose: a server that is not there must not delay the fallback to whatever+#: else the install has.+_LOCAL_PROBE_TIMEOUT_S = 3.0+++def _normalize_local_root(url: str) -> str:+ """Normalize a user-entered server address to an ``…/v1`` API root.++ Accepts ``host:port``, a full URL, a trailing slash, or an already-complete+ ``…/v1``. ``0.0.0.0`` is a server BIND address and unusable as a client+ target on Windows, so it maps to localhost — the same normalization the+ local brain cards apply, kept local to this module because a plugin does+ not reach into the rest of the tree.+ """+ root = (url or "").strip().rstrip("/")+ if not root:+ return ""+ if "://" not in root:+ root = f"http://{root}"+ root = root.replace("://0.0.0.0", "://localhost")+ if root.endswith("/v1"):+ return root+ return f"{root}/v1"+++class LocalRealtimeProvider:+ """A self-hosted server that speaks the OpenAI Realtime WebSocket protocol.++ Realtime was the one tier with no local option at all: every card in it+ billed a hosted account, so an install running its brain, its recognizer+ and its voice on its own hardware still had to leave the machine for the+ low-latency voice mode — or give that mode up entirely.++ Deliberately protocol-shaped rather than product-shaped: it names no+ project and bundles no server, it speaks to whatever endpoint the user+ points it at, on this machine or on another box on the LAN.++ Keyless by design — the optional key is attached when the user stored one+ (a reverse proxy, a shared GPU host) and its absence is normal. The card is+ only ever a candidate once the user selected it AND configured a server+ URL: an unconfigured endpoint must never join the ambient fallback chain+ and swallow a turn.+ """++ name = "local-realtime"+ supports_realtime = True+ # Never an implicit stand-in: a self-hosted endpoint is a deliberate choice,+ # and quietly routing a call into one the user did not pick is the opposite+ # of what a local card is for.+ implicit_usage_fallback_allowed = False+ input_sample_rate = _INPUT_RATE+ output_sample_rate = _OUTPUT_RATE+ # No credential_candidates: this is the keyless path, so the factory builds+ # it through ``external_login_ready`` + ``from_runtime_config`` rather than+ # handing it a key.++ def __init__(+ self, *, base_url: str = "", api_key: str = "", model: str = ""+ ) -> None:+ self._base_url = _normalize_local_root(base_url)+ self._api_key = (api_key or "").strip()+ self._model = (model or "").strip()++ # -- factory wiring ----------------------------------------------------++ @staticmethod+ def _provider_config(cfg: Any) -> Any:+ """The card's stored settings, read defensively off the config object.++ Attribute access only — no imports from the rest of the tree, which is+ what keeps this module a plugin rather than a dependency.+ """+ providers = getattr(getattr(cfg, "brain", None), "providers", None) or {}+ getter = getattr(providers, "get", None)+ return getter("local-realtime") if callable(getter) else None++ @classmethod+ def external_login_ready(cls, cfg: Any = None) -> bool:+ """Whether a server address is configured. Synchronous and offline.++ The factory calls this on an audio loop, so it must never touch the+ network: the question here is "is there an endpoint to try at all",+ and ``open_session`` is what finds out whether it answers.+ """+ provider_cfg = cls._provider_config(cfg)+ return bool(+ _normalize_local_root(str(getattr(provider_cfg, "base_url", "") or ""))+ )++ @classmethod+ def from_runtime_config(cls, cfg: Any) -> LocalRealtimeProvider:+ provider_cfg = cls._provider_config(cfg)+ return cls(+ base_url=str(getattr(provider_cfg, "base_url", "") or ""),+ # ENV only — a credential never belongs in jarvis.toml (AP-12), and+ # most self-hosted servers need none at all. A user who put one+ # behind a proxy or started vLLM with --api-key exports it once.+ api_key=os.environ.get("JARVIS_LOCAL_REALTIME_API_KEY", ""),+ model=str(getattr(provider_cfg, "model", "") or ""),)++ # -- session -----------------------------------------------------------++ async def can_open_duplex_session(self) -> bool:+ return bool(self._base_url)++ async def _resolve_model(self) -> str:+ """The configured model, else the first one the server serves.++ A self-hosted realtime server names its model whatever its operator+ called it, so there is no default worth hardcoding. Asking+ ``/v1/models`` mirrors what the local brain card does and spares the+ user a field they would have to look up. A server that does not answer+ that endpoint is not an error — the connect below carries the honest+ failure.+ """+ if self._model:+ return self._model+ import httpx # lazy (AP-26)++ headers = {"Authorization": f"Bearer {self._api_key}"} if self._api_key else {}try:- await connection.session.update(session=payload)- await session.wait_until_ready()- except BaseException:- await session.close()- raise- # A mid-call open (cross-family fallback after another provider's- # transport died) carries the call transcript; restore it so the- # conversation survives the provider crossing (BUG-088).- await session._seed_conversation_history(connection)- return session+ async with httpx.AsyncClient(timeout=_LOCAL_PROBE_TIMEOUT_S) as client:+ resp = await client.get(f"{self._base_url}/models", headers=headers)+ resp.raise_for_status()+ served = [+ str(entry.get("id") or "").strip()+ for entry in (resp.json().get("data") or [])+ ]+ except Exception as exc: # noqa: BLE001 — the connect reports the real failure+ log.info(+ "local-realtime: /models probe failed at %s (%s); connecting with "+ "the protocol default",+ self._base_url,+ type(exc).__name__,+ )+ return _MODEL+ for name in served:+ if name:+ log.info("local-realtime: no model configured — using served %s", name)+ return name+ return _MODEL++ async def open_session(self, cfg: Any) -> _OpenAIRealtimeSession:+ if not self._base_url:+ raise RuntimeError(+ "No server URL configured for the self-hosted realtime provider "+ "— set it on the provider card first (e.g. http://localhost:8080)."+ )+ from openai import AsyncOpenAI # lazy (AP-26)++ client = AsyncOpenAI(+ # Most self-hosted servers ignore the key; the SDK still insists on+ # a non-empty one.+ api_key=self._api_key or "local",+ base_url=self._base_url,+ )+ connect_model = str(getattr(cfg, "model", "") or "").strip()+ if not connect_model or connect_model == "auto":+ # "auto" is what the card offers while the server's roster is+ # unknown; resolve it into a real name rather than sending a+ # placeholder the server would reject.+ connect_model = await self._resolve_model()+ return await _open_realtime_session(+ client, cfg, model=connect_model, transcription_model=None+ )diff --git a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsxindex 3964851673..30acd2c688 100644--- a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx@@ -718,6 +718,7 @@ function prettyProviderName(id: string): string {// backend's pretty label is unavailable (cosmetic fallback only)."openai-realtime": "OpenAI Realtime","gemini-live": "Gemini Live",+ "local-realtime": "Self-hosted realtime","unknown": "—",};return map[id] ?? id;diff --git a/jarvis/ui/web/provider_spec.py b/jarvis/ui/web/provider_spec.pyindex 9b472c4c84..bfa15dc407 100644--- a/jarvis/ui/web/provider_spec.py+++ b/jarvis/ui/web/provider_spec.py@@ -795,6 +795,31 @@ PROVIDERS: tuple[ProviderSpec, ...] = ("remain a compatibility fallback until a dedicated key is saved."),),+ # The local option this tier lacked entirely: every other realtime card+ # bills a hosted account, so an install running brain, recognizer and voice+ # on its own hardware still had to leave the machine for the low-latency+ # voice mode. Protocol-shaped, never product-shaped — it names no project+ # and bundles no server.+ ProviderSpec(+ id="local-realtime",+ label="Self-hosted realtime (OpenAI-compatible)",+ tier="realtime",+ auth_mode="none",+ secret_keys=(),+ dashboard_url=None,+ signup_url="https://platform.openai.com/docs/guides/realtime",+ supports_base_url=True,+ credential_help=(+ "Any server on your own machine or network that speaks the OpenAI "+ "Realtime WebSocket protocol. Enter its address (for example "+ "http://localhost:8080) — no cloud account, nothing leaves your "+ "network. The model and voice come from the server itself; leave "+ "them on 'auto' unless it serves several. This card is only used "+ "when you select it and set an address. If your server requires a "+ "token, export JARVIS_LOCAL_REALTIME_API_KEY — most need none."+ ),+ experimental=True,+ ),# grok-realtime was removed 2026-07-16 (BUG-064: the xAI realtime server# drops its session contract after any response cancel and goes deaf).)diff --git a/pyproject.toml b/pyproject.tomlindex 17f157ab71..b1ed23b48f 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -564,6 +564,10 @@ discord = "jarvis.channels.discord:DiscordChannel"codex-subscription-realtime = "jarvis.plugins.realtime.codex_subscription:CodexSubscriptionRealtimeProvider"openai-realtime = "jarvis.plugins.realtime.openai_realtime:OpenAIRealtimeProvider"gemini-live = "jarvis.plugins.realtime.gemini_live:GeminiLiveProvider"+# Self-hosted endpoint speaking the same realtime protocol — the local option+# this tier lacked entirely. Keyless; only ever used when explicitly selected+# with a server URL configured.+local-realtime = "jarvis.plugins.realtime.openai_realtime:LocalRealtimeProvider"[project.entry-points."jarvis.tool"]open-app = "jarvis.plugins.tool.open_app:OpenAppTool"diff --git a/tests/unit/realtime/test_local_realtime.py b/tests/unit/realtime/test_local_realtime.pynew file mode 100644index 0000000000..8bd3baca63--- /dev/null+++ b/tests/unit/realtime/test_local_realtime.py@@ -0,0 +1,183 @@+"""Self-hosted realtime: the local option this tier used to lack entirely.++Every other realtime card bills a hosted account, so an install running its+brain, its recognizer and its voice on its own hardware still had to leave the+machine for low-latency voice — or give that mode up. What these tests pin is+the part that makes a self-hosted card trustworthy rather than merely present:++ - it never joins a call it was not chosen for (an unconfigured endpoint must+ not swallow a turn from the provider that would have worked);+ - it sends the SERVER's own model and no hosted OpenAI model ids, because a+ field the user never chose must not be the reason a session is rejected;+ - a credential, if any, comes from the environment — never from jarvis.toml+ (AP-12).+"""++from __future__ import annotations++from types import SimpleNamespace+from typing import Any++import pytest++from jarvis.plugins.realtime.openai_realtime import (+ LocalRealtimeProvider,+ _normalize_local_root,+ _session_payload,+)+++def _cfg(base_url: str = "", model: str = "") -> SimpleNamespace:+ provider = SimpleNamespace(base_url=base_url, model=model)+ return SimpleNamespace(brain=SimpleNamespace(providers={"local-realtime": provider}))+++# ── Address handling ─────────────────────────────────────────────────────+ ("raw", "expected"),+ [+ ("http://localhost:8080", "http://localhost:8080/v1"),+ ("http://localhost:8080/", "http://localhost:8080/v1"),+ # An already-complete API root must not double up to /v1/v1.+ ("http://localhost:8080/v1", "http://localhost:8080/v1"),+ ("localhost:8080", "http://localhost:8080/v1"),+ # 0.0.0.0 is a server BIND address; as a client target it fails.+ ("0.0.0.0:8080", "http://localhost:8080/v1"),+ ("https://gpu.lan:8443", "https://gpu.lan:8443/v1"),+ ("", ""),+ (" ", ""),+ ],+)+def test_server_address_normalization(raw: str, expected: str) -> None:+ assert _normalize_local_root(raw) == expected+++# ── Never an uninvited candidate ─────────────────────────────────────────+def test_unconfigured_card_is_not_ready() -> None:+ """No address means nothing to try — and the factory must not build it,+ or a call would route into an endpoint the user never set up."""+ assert LocalRealtimeProvider.external_login_ready(_cfg()) is False+ assert LocalRealtimeProvider.external_login_ready(None) is False+++def test_configured_card_is_ready_without_touching_the_network() -> None:+ """The factory calls this on an audio loop: it answers "is there an+ endpoint at all", never "does it respond"."""+ assert LocalRealtimeProvider.external_login_ready(_cfg("http://localhost:8080")) is True+++def test_never_an_implicit_fallback() -> None:+ """A self-hosted endpoint is a deliberate choice; quietly routing a call+ into one the user did not pick is the opposite of what this card is for."""+ assert LocalRealtimeProvider.implicit_usage_fallback_allowed is False+++async def test_open_session_without_an_address_says_what_to_do() -> None:+ with pytest.raises(RuntimeError) as err:+ await LocalRealtimeProvider().open_session(SimpleNamespace())+ assert "server URL" in str(err.value)+++# ── Credentials come from the environment, never from the config file ────+def test_optional_key_is_read_from_the_environment(monkeypatch) -> None:+ monkeypatch.setenv("JARVIS_LOCAL_REALTIME_API_KEY", "sk-local-proxy")+ provider = LocalRealtimeProvider.from_runtime_config(_cfg("http://localhost:8080"))+ assert provider._api_key == "sk-local-proxy"+++def test_a_key_in_the_config_file_is_ignored(monkeypatch) -> None:+ """AP-12: a credential in jarvis.toml is a leak, so a stored one must not+ even be honoured."""+ monkeypatch.delenv("JARVIS_LOCAL_REALTIME_API_KEY", raising=False)+ cfg = _cfg("http://localhost:8080")+ cfg.brain.providers["local-realtime"].api_key = "sk-should-be-ignored"+ provider = LocalRealtimeProvider.from_runtime_config(cfg)+ assert provider._api_key == ""+++# ── The session payload carries nothing the server did not ask for ───────+def test_local_session_declares_no_hosted_transcription_model() -> None:+ """A hosted OpenAI model id is meaningless on a self-hosted server, and+ naming one would have it reject the whole session over a field the user+ never chose."""+ payload = _session_payload(SimpleNamespace(), transcription_model=None)+ assert payload["audio"]["input"]["transcription"] == {}+++def test_hosted_session_keeps_its_transcription_model() -> None:+ payload = _session_payload(SimpleNamespace())+ assert payload["audio"]["input"]["transcription"]["model"] == "gpt-4o-mini-transcribe"+++def test_auto_voice_is_a_preference_not_a_voice_name() -> None:+ """"auto" is the only honest entry a self-hosted card can offer; sending it+ as a voice NAME would have the server reject a voice it does not have."""+ assert "voice" not in _session_payload(SimpleNamespace(voice="auto"))["audio"]["output"]+ assert _session_payload(SimpleNamespace(voice="coral"))["audio"]["output"]["voice"] == (+ "coral"+ )+++# ── Model resolution: ask the server, do not invent a name ───────────────+class _FakeResponse:+ def __init__(self, payload: dict[str, Any]) -> None:+ self._payload = payload++ def raise_for_status(self) -> None:+ return None++ def json(self) -> dict[str, Any]:+ return self._payload+++class _FakeAsyncClient:+ payload: dict[str, Any] = {}+ fail: bool = False+ last_url: str | None = None++ def __init__(self, **kwargs: Any) -> None:+ pass++ async def __aenter__(self) -> _FakeAsyncClient:+ return self++ async def __aexit__(self, *exc: Any) -> None:+ return None++ async def get(self, url: str, headers: dict[str, str] | None = None) -> _FakeResponse:+ _FakeAsyncClient.last_url = url+ if _FakeAsyncClient.fail:+ raise RuntimeError("connection refused")+ return _FakeResponse(_FakeAsyncClient.payload)+++def fake_models(monkeypatch):+ import httpx++ monkeypatch.setattr(httpx, "AsyncClient", _FakeAsyncClient)+ _FakeAsyncClient.fail = False+ _FakeAsyncClient.payload = {}+ _FakeAsyncClient.last_url = None+ return _FakeAsyncClient+++async def test_model_comes_from_the_server_when_none_is_pinned(fake_models) -> None:+ fake_models.payload = {"data": [{"id": "moshi-v1"}, {"id": "other"}]}+ provider = LocalRealtimeProvider(base_url="http://localhost:8080")+ assert await provider._resolve_model() == "moshi-v1"+ assert fake_models.last_url == "http://localhost:8080/v1/models"+++async def test_a_pinned_model_skips_the_probe(fake_models) -> None:+ provider = LocalRealtimeProvider(base_url="http://localhost:8080", model="my-model")+ assert await provider._resolve_model() == "my-model"+ assert fake_models.last_url is None+++async def test_a_server_without_a_model_list_still_connects(fake_models) -> None:+ """The probe is a convenience, not a gate: the connect that follows carries+ the honest failure if there is one."""+ fake_models.fail = True+ provider = LocalRealtimeProvider(base_url="http://localhost:8080")+ assert await provider._resolve_model()diff --git a/tests/unit/web/test_local_only_install_has_every_tier.py b/tests/unit/web/test_local_only_install_has_every_tier.pynew file mode 100644index 0000000000..3d89298ba2--- /dev/null+++ b/tests/unit/web/test_local_only_install_has_every_tier.py@@ -0,0 +1,138 @@+"""A download whose only hardware is their own must reach every tier.++Personal Jarvis is aimed at an arbitrary downloader (CLAUDE.md section 3), and+a meaningful share of them will not enter a single cloud credential — that is+the whole point of the local providers. For those installs "mostly local" is+not a state the product should have: one keyless gap means the voice mode, the+recognizer or the low-latency path silently stops being available, and the user+learns that only when they try to speak.++Realtime was exactly that gap until 2026-08-05: brain, recognizer, voice and+wording all had a keyless card, and realtime had three cards that all billed a+hosted account. This is the gate that keeps the set complete — a new tier, or a+tier whose only local card is removed, fails here rather than in a user's+first-run.+"""++from __future__ import annotations++import pytest++from jarvis.ui.web.provider_spec import PROVIDERS, ProviderSpec, provider_billing++#: Every tier a voice-first install actually traverses. Deliberately a literal+#: list, not derived from PROVIDERS: deriving it would make a tier that lost+#: its last local card disappear from the check along with the coverage.+TIERS_A_LOCAL_INSTALL_NEEDS: tuple[str, ...] = (+ "brain",+ "stt",+ "tts",+ "realtime",+ "dictation",+)+++def _keyless_cards(tier: str) -> list[ProviderSpec]:+ """Cards in ``tier`` that need no credential at all.++ "Keyless" is the card's own auth mode — the same definition the brain+ resolver uses for its local tail and the model-probe budget uses for its+ load allowance, never a provider name (AP-21).+ """+ return [s for s in PROVIDERS if s.tier == tier and s.auth_mode == "none"]++[email protected]("tier", TIERS_A_LOCAL_INSTALL_NEEDS)+def test_every_tier_offers_a_keyless_local_card(tier: str) -> None:+ cards = _keyless_cards(tier)+ assert cards, (+ f"The '{tier}' tier has no keyless card, so an install with no cloud "+ "credential cannot use it at all. Ship a local option in the same "+ "change rather than leaving the tier hosted-only."+ )++[email protected]("tier", TIERS_A_LOCAL_INSTALL_NEEDS)+def test_keyless_cards_are_billed_as_local(tier: str) -> None:+ """The badge follows the auth mode, so a keyless card never renders as+ "billed per token" — the line a downloader reads before deciding."""+ for spec in _keyless_cards(tier):+ assert provider_billing(spec) == "local", spec.id+++def _inherits_an_address(spec: ProviderSpec) -> bool:+ """Whether this card follows a server address configured on another card.++ A self-hosted server has ONE address. The dictation-polish card reaches the+ same Ollama server the brain card points at, so it deliberately has no+ second field — but it must genuinely follow that address rather than keep a+ localhost copy that breaks the moment the server moves.+ """+ from jarvis.dictation.polish_client import POLISH_FAMILIES++ return any(+ family.id in spec.id and bool(family.endpoint_provider)+ for family in POLISH_FAMILIES+ )+++def test_a_self_hosted_card_says_where_its_server_lives() -> None:+ """A local card that cannot be pointed at a server is only usable on a+ default port nobody promised. Every keyless card either runs in-process+ (its own on-device runtime), exposes an editable server URL, or follows one+ the user already set on another card."""+ from jarvis.speech.local_models import get_local_provider++ for spec in PROVIDERS:+ if spec.auth_mode != "none":+ continue+ runs_in_process = get_local_provider(spec.id) is not None+ assert runs_in_process or spec.supports_base_url or _inherits_an_address(spec), (+ f"'{spec.id}' is keyless but neither ships an on-device runtime nor "+ "lets the user say where its server is."+ )+++def test_the_dictation_card_follows_the_server_the_user_configured() -> None:+ """The concrete case behind the rule above: a user who moved their Ollama+ to another box used to keep a second, invisible copy of the address here,+ pinned to localhost, and dictation polish silently talked to nothing."""+ from jarvis.core.config import BrainConfig, BrainProviderConfig, JarvisConfig+ from jarvis.dictation.polish_client import POLISH_FAMILIES++ family = next(f for f in POLISH_FAMILIES if f.endpoint_provider)+ import jarvis.core.config as cfg++ conf = JarvisConfig(+ brain=BrainConfig(+ providers={"ollama": BrainProviderConfig(base_url="http://gpu.lan:11434")}+ )+ )+ original = cfg.load_config+ cfg.load_config = lambda: conf # type: ignore[assignment]+ try:+ assert family.effective_base_url == "http://gpu.lan:11434/v1"+ # And a server on another machine is keyless but NOT on-device — the+ # privacy promise has to follow the address, not the billing model.+ assert family.runs_on_device is False+ finally:+ cfg.load_config = original # type: ignore[assignment]+++def test_the_realtime_tier_keeps_a_self_hosted_option() -> None:+ """Named explicitly because this tier is the one that was hosted-only, and+ because a self-hosted realtime card must never be an implicit fallback: a+ call routed into an endpoint the user did not choose is worse than the+ honest "no realtime provider available"."""+ from jarvis.core.registry import load+ from jarvis.realtime.protocol import RealtimeProvider++ local_cards = _keyless_cards("realtime")+ assert local_cards, "realtime lost its self-hosted card"+ for spec in local_cards:+ provider_cls = load("jarvis.realtime", spec.id, protocol=RealtimeProvider)+ assert getattr(provider_cls, "supports_realtime", False) is True+ assert getattr(provider_cls, "implicit_usage_fallback_allowed", True) is False+ # Keyless means no credential slots — a card that declared them would+ # be built the key way and demand one it does not have.+ assert not getattr(provider_cls, "credential_candidates", ())