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(voice): warm the subscription transport when it can help, and stop a config write from dropping a whole section
rubenluetke10-beep1fc9612fe88d
diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.pyindex c04c1aaa72..7808adcde2 100644--- a/jarvis/core/config_writer.py+++ b/jarvis/core/config_writer.py@@ -1372,6 +1372,20 @@ def _ensure_writable_config_path(path: Path) -> Path:path.parent.mkdir(parents=True, exist_ok=True)if not path.exists():path.write_text("", encoding="utf-8")+ # Say it. Creating this file is either a first run or a configuration+ # that has gone missing, and the two are indistinguishable from here —+ # but the CONSEQUENCE is the same either way and it is severe: every+ # writer below is a read-modify-write, so from an empty file onward the+ # config is silently rebuilt from nothing but the individual keys later+ # writes happen to touch. Everything the user had configured — provider+ # pins included — is simply absent, and without this line there was no+ # trace anywhere that it had ever existed (AP-30).+ log.warning(+ "Created a NEW empty configuration file at %s. If this is not a "+ "first run, the previous configuration is gone and in-app settings "+ "will be rebuilt from defaults as they are touched.",+ path,+ )return path@@ -2284,6 +2298,70 @@ def _strip_persona_name(path: Path) -> None:_atomic_write(path, out)+class ConfigSectionLossError(RuntimeError):+ """A config write would have removed whole top-level entries.++ Every writer in this module is a read-modify-write that sets or deletes a+ single key: none of them may make a top-level table disappear. When one+ would, the outgoing document is not an edit of the file on disk — it was+ built from a partial or empty parse — and completing the write destroys+ settings nobody asked to change.+ """+++def _top_level_names(raw: str) -> set[str] | None:+ """Top-level table/key names in ``raw``, or ``None`` when unparsable.++ ``None`` deliberately disables the loss guard rather than blocking a write:+ a file that cannot be parsed is exactly the file an in-app repair must+ still be able to overwrite.+ """+ text = raw[len(_BOM) :] if raw.startswith(_BOM) else raw+ if not text.strip():+ return set()+ try:+ return set(tomlkit.parse(text).keys())+ except Exception: # noqa: BLE001 — an unparsable file is not a veto+ log.debug("Config loss guard could not parse a TOML document.", exc_info=True)+ return None+++def _assert_no_top_level_loss(path: Path, content: str) -> None:+ """Refuse a write that would drop whole top-level entries.++ The maintainer's live ``jarvis.toml`` went from 53 KB (2026-07-17 backup,+ ``[brain.realtime]`` included) to 183 bytes holding only the keys that boot+ migrations and the wake/dictation writers happen to touch. No writer here+ can produce that from a populated file — but an empty or half-read one+ can, and nothing anywhere noticed. This guard turns that class of loss into+ a refused write with a named cause instead of a silent deletion.++ Legitimate removals stay legal: the worker-tier migration drops the NESTED+ ``[brain.sub_jarvis]`` table and the persona heal drops the NESTED+ ``[persona] name`` key, neither of which is a top-level entry.+ """+ try:+ existing = path.read_text(encoding="utf-8")+ except OSError:+ # No readable predecessor means nothing can be lost.+ return+ before = _top_level_names(existing)+ if not before:+ return+ after = _top_level_names(content)+ if after is None:+ return+ lost = before - after+ if not lost:+ return+ raise ConfigSectionLossError(+ f"Refusing to write {path}: it would remove the top-level "+ f"configuration entries {sorted(lost)}. A config writer only ever "+ "sets or clears a single key, so this write was built from an "+ "incomplete read of the file."+ )++def _atomic_write(path: Path, content: str) -> None:"""Atomic tempfile + replace, read-only-aware.@@ -2293,7 +2371,12 @@ def _atomic_write(path: Path, content: str) -> None:succeed; otherwise the call fails with ``[WinError 5] Zugriffverweigert``. We restore the flag in ``finally`` so the defense holdseven if the write itself raises.++ Before anything touches the file, :func:`_assert_no_top_level_loss` rejects+ a document that would delete top-level entries — the failure mode that+ silently took a provider pin (and everything else) off this machine."""+ _assert_no_top_level_loss(path, content)tmp = _write_unique_temp(path, content)was_read_only = Falsediff --git a/jarvis/overlay/surface.py b/jarvis/overlay/surface.pyindex 6a39f0f43f..ccf8cab360 100644--- a/jarvis/overlay/surface.py+++ b/jarvis/overlay/surface.py@@ -45,9 +45,9 @@ class OverlaySurface(Protocol):Implementations must degrade (log + no-op), never raise, and be idempotent —``start``/``stop`` may be called more than once, in any order. ``set_state``- accepts the orb's coarse lifecycle state (``"idle" | "listening" | "thinking"- | "speaking" | "error" | "paused"``); a backend that cannot render a given- state maps it to the nearest visual it can show.+ accepts the orb's coarse lifecycle state (``"idle" | "connecting" |+ "listening" | "thinking" | "speaking" | "error" | "paused"``); a backend that+ cannot render a given state maps it to the nearest visual it can show."""def start(self) -> None:@@ -70,8 +70,19 @@ class OverlaySurface(Protocol):# The orb's coarse lifecycle states (mirrors the modes ``ui/orb/bus_bridge.py``# drives: idle/listen/think/speak) plus the tray's error/paused. Backends map# these onto whatever visual vocabulary they own.+#+# ``connecting`` covers the window between accepting a call and the voice engine+# actually being able to carry it. A realtime provider can legitimately spend+# many seconds opening its transport, and until this state existed the only+# thing the surface could say during that window was ``listening`` — which+# claims the user is being heard while the provider has not accepted a single+# frame yet. It maps to the orb's ``think`` visual because that is the nearest+# thing the orb owns for "busy, not yet listening"; the orb has no dedicated+# connecting animation and inventing one is a rendering change, not a+# vocabulary change._ORB_STATE_TO_ORB_MODE: dict[str, str] = {"idle": "idle",+ "connecting": "think","listening": "listen","thinking": "think","speaking": "speak",@@ -81,7 +92,11 @@ _ORB_STATE_TO_ORB_MODE: dict[str, str] = {# The set of states for which the orb should be visible on screen. ``idle`` keeps# the orb hidden (the live behaviour: the orb pops on wake, hides when idle).-_VISIBLE_STATES: frozenset[str] = frozenset({"listening", "thinking", "speaking"})+# ``connecting`` is visible: it exists precisely so a slow transport open is+# something the user can SEE, instead of a silent gap behind a "listening" orb.+_VISIBLE_STATES: frozenset[str] = frozenset(+ {"connecting", "listening", "thinking", "speaking"}+)class TkColorKeyOverlay:diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.pyindex f2177ebea3..62ac36ad0a 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -69,6 +69,18 @@ _LOCK_ACQUIRE_TIMEOUT = 0.0#: window, far shorter than a user reaching for the wake word._REALTIME_WARM_DELAY_S = 5.0+#: How long the warm waits for voice to report itself usable before warming+#: anyway. Voice never becoming usable is normal on a host with no microphone,+#: and the browser/bridge surfaces can still place a call there — so the gate+#: bounds the wait instead of cancelling the warm.+_REALTIME_WARM_VOICE_GATE_S = 45.0++#: Floor between two warm attempts. The warm is re-armed after every call so a+#: transport that died mid-session is reopened before the next wake word; this+#: keeps a burst of short calls (or a rapid hangup loop) from re-verifying the+#: account once per call.+_REALTIME_WARM_MIN_INTERVAL_S = 20.0+def _local_voice_permission_granted(*,@@ -2115,6 +2127,25 @@ class DesktopApp:)speech_task.add_done_callback(_log_speech_and_orb_done)+ # === 1b) Realtime transport pre-warm, beside the wake listener ===+ # Deliberately NOT inside ``_heavy_backend_bg``: that task waits on+ # the wake-model gate AND the whole ``server.start()`` chain before+ # it schedules anything, so the warm could not begin until roughly+ # 30-40 s after launch — while the wake word is armed within ~1 s.+ # A user who spoke in that window paid the provider's full cold+ # start (documented 15-25 s for the ChatGPT-subscription transport)+ # inside their own call, with the bar already claiming to listen.+ #+ # AP-26 is preserved by construction: the worker below does nothing+ # until VoiceBootStatus reports ``voice_usable``, i.e. AFTER the+ # mark ``check_boot_budget.py`` measures, and nothing on the boot+ # path ever awaits it — so neither VOICE_USABLE nor APP_INTERACTIVE+ # can move because of it.+ loop.create_task(+ self._run_realtime_transport_warm(server.bus),+ name="realtime-transport-warm",+ )+# === 2) Everything else, BEHIND the live wake listener ==========# The heavy backend keeps its original internal order (server.start()# before brain/mcp/workflows/conductor) so no task that depended on a@@ -2236,37 +2267,6 @@ class DesktopApp:loop.create_task(_provision_wake_model(), name="wake-model-provision")- async def _warm_realtime_transport() -> None:- """Pre-open the selected realtime transport, off the boot path.-- Same slot and the same reasoning as the wake-model provision- above: created AFTER the app-interactive mark and after the- server start, so neither boot-budget mark can move (AP-26).- The extra delay keeps a process spawn and a network account- check out of the brain/MCP build's CPU and disk window.-- Without it, the Codex subscription adapter spawns its- app-server and verifies the account inside the first call's- handshake — measured 2026-08-02 at ~1.5 s of 3.0 s.- """- try:- await asyncio.sleep(_REALTIME_WARM_DELAY_S)- from jarvis.core.config import load_config- from jarvis.realtime.factory import (- realtime_warm_selected_transports,- )-- await realtime_warm_selected_transports(load_config())- except Exception: # noqa: BLE001 — warming never crashes boot- from loguru import logger as _warm_log- _warm_log.opt(exception=True).debug(- "Off-boot realtime transport warm skipped."- )-- loop.create_task(- _warm_realtime_transport(), name="realtime-transport-warm"- )-loop.create_task(_heavy_backend_bg(), name="heavy-backend")loop.call_soon(self._start_virtual_cursor)# Watch this loop from OFF it, for the rest of the process's life.@@ -2847,6 +2847,106 @@ class DesktopApp:logger.info("Quit scheduled (Terms declined; hard-exit fallback armed).")return True+ async def _run_realtime_transport_warm(self, bus: Any) -> None:+ """Keep the selected realtime transport pre-opened, for the whole session.++ A realtime provider backed by an external application login has a real+ cold start: it spawns its app-server, verifies the live account, and+ audits its profile before it can accept a single audio frame. Paid+ inside a call that cost is the difference between "it answers" and+ "it went quiet for twenty seconds", so it is paid out here instead.++ This is a WORKER, not a one-shot, because a warmed transport does not+ stay warm: the shared client is torn down on any transport error, and+ the previous single boot-time warm never noticed. Every completed call+ re-arms it, so a transport that died mid-session is reopened before the+ next wake word rather than during it.++ Never fatal and never silent: a failed warm only means the next call+ pays what it pays today, and it says so (AP-30). Cross-platform by+ construction — the work is a bus subscription plus whatever the+ provider's own capability probe does, and a host with no eligible+ provider simply warms nothing.+ """+ from loguru import logger as _warm_log++ # Bound once so every failure below reports through a plainly named+ # call: a logger reached through a chained ``.opt(...)`` is invisible+ # to the silent-handler gate, which is exactly the check that keeps+ # an advisory warm path from failing without a trace (AP-30).+ _warm_log_exc = _warm_log.opt(exception=True)++ from jarvis.core.events import VoiceBootStatus, VoiceSessionEnded++ warm_requested = asyncio.Event()+ voice_usable = asyncio.Event()+ last_completed = 0.0++ async def _on_voice_boot_status(evt: Any) -> None:+ if getattr(evt, "voice_usable", False):+ voice_usable.set()++ async def _on_voice_session_ended(evt: Any) -> None:+ # Re-arm on the way out of every call, whatever ended it: a+ # provider failure is exactly the case where the transport is most+ # likely to need reopening, and it is also the case that used to+ # leave the next call cold with nothing to fix it.+ del evt+ warm_requested.set()++ try:+ bus.subscribe(VoiceBootStatus, _on_voice_boot_status)+ bus.subscribe(VoiceSessionEnded, _on_voice_session_ended)+ except Exception: # noqa: BLE001 — a headless/bare bus keeps the warm+ _warm_log_exc.warning(+ "Realtime transport warm could not subscribe to the voice "+ "lifecycle; it will warm once and not re-arm after calls."+ )++ try:+ await asyncio.wait_for(+ voice_usable.wait(), timeout=_REALTIME_WARM_VOICE_GATE_S+ )+ except TimeoutError:+ # No microphone, a failed warm-up, or a headless host: the browser+ # and bridge surfaces can still start a call, so warm anyway.+ _warm_log.info(+ "Realtime transport warm: voice never reported usable within "+ "{:.0f}s; warming the transport anyway.",+ _REALTIME_WARM_VOICE_GATE_S,+ )+ # Keeps the process spawn and the account round trip out of the+ # brain/MCP build's CPU and disk window.+ await asyncio.sleep(_REALTIME_WARM_DELAY_S)+ warm_requested.set()++ while True:+ await warm_requested.wait()+ # ``time.monotonic`` rather than the loop clock: this worker must+ # not care which loop implementation it is running on.+ elapsed = time.monotonic() - last_completed+ if last_completed and elapsed < _REALTIME_WARM_MIN_INTERVAL_S:+ await asyncio.sleep(_REALTIME_WARM_MIN_INTERVAL_S - elapsed)+ warm_requested.clear()+ try:+ from jarvis.core.config import load_config+ from jarvis.realtime.factory import (+ realtime_warm_selected_transports,+ )++ # ``load_config`` parses TOML off disk; keep it off the loop+ # that also serves every WebSocket frame, route and pane.+ cfg = await asyncio.to_thread(load_config)+ await realtime_warm_selected_transports(cfg)+ except asyncio.CancelledError:+ raise+ except Exception: # noqa: BLE001 — warming is advisory, never fatal+ _warm_log_exc.warning(+ "Realtime transport warm failed; the next call pays the "+ "provider's cold start."+ )+ last_completed = time.monotonic()+async def _start_speech_and_orb(self,loop: asyncio.AbstractEventLoop,diff --git a/tests/unit/ui/test_desktop_backend_start_order.py b/tests/unit/ui/test_desktop_backend_start_order.pyindex 156ec0fd26..963b369988 100644--- a/tests/unit/ui/test_desktop_backend_start_order.py+++ b/tests/unit/ui/test_desktop_backend_start_order.py@@ -292,8 +292,18 @@ def test_desktop_voice_start_does_not_wait_for_brain_ready(monkeypatch, tmp_pathdef _cursor() -> None:events.append("cursor")+ async def _realtime_warm(*_args: Any, **_kwargs: Any) -> None:+ # The realtime transport warm is a long-lived, event-driven worker: it+ # waits for VoiceBootStatus and then parks on the post-call re-arm for+ # the rest of the session. ``_FakeLoop`` above runs every created+ # coroutine to completion, so the real one would never return here.+ # Its own coverage lives in test_desktop_realtime_transport_warm.py;+ # this test only cares that it is scheduled beside the wake listener.+ events.append("realtime_warm")+monkeypatch.setattr(app, "_start_speech_and_orb", _speech)monkeypatch.setattr(app, "_start_virtual_cursor", _cursor)+ monkeypatch.setattr(app, "_run_realtime_transport_warm", _realtime_warm)_FakeWebServer.events = eventstry:app._run_backend()