Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(realtime): stop concurrent Codex status probes faking a broken setup
Ruben Lütke6af6054397c1
diff --git a/jarvis/codex_app_server.py b/jarvis/codex_app_server.pyindex 4be46adf25..91c474e14c 100644--- a/jarvis/codex_app_server.py+++ b/jarvis/codex_app_server.py@@ -32,6 +32,7 @@ import subprocessimport sysimport tempfileimport threading+import timeimport uuidfrom collections.abc import AsyncIterator, Mapping, Sequencefrom contextlib import suppress@@ -254,6 +255,10 @@ class CodexAppServerCapability:"lifecycle_unavailable","not_installed","setup_invalid",+ # Transient: the profile is briefly owned by another probe, a login /+ # logout, or a starting voice transport. Not a setup defect; callers+ # keep their last known state instead of asking the user to reconnect.+ "busy",] = "setup_invalid"@@ -2740,6 +2745,54 @@ _subscription_active_transports: set[int] = set()_subscription_transport_process_lock: Any | None = None_subscription_mutation_process_lock: Any | None = None+# Status probes must never report a broken setup just because the profile is+# briefly owned by another probe or mutation (the UI fires several concurrent+# refreshes; each losing caller used to flap the card to "needs attention").+# Concurrent callers wait on this condition (it shares _subscription_login_lock)+# and share the owner's result. The last completed probe is cached briefly so a+# refresh burst costs one CLI probe instead of one per request.+_SUBSCRIPTION_SNAPSHOT_CACHE_TTL_S: Final = 5.0+_SUBSCRIPTION_SNAPSHOT_WAIT_TIMEOUT_S: Final = 10.0+_subscription_state_changed = threading.Condition(_subscription_login_lock)+_subscription_snapshot_cache: CodexAppServerCapability | None = None+_subscription_snapshot_cache_at: float = 0.0+++def _cached_subscription_snapshot_locked(+ *, allow_stale: bool+) -> CodexAppServerCapability | None:+ """Return the last completed probe result; caller holds the login lock.++ ``allow_stale`` serves the last known status while the profile is briefly+ owned elsewhere; mutations invalidate the cache, so a stale entry can never+ outlive a login, logout, or disconnect.+ """+ if _subscription_snapshot_cache is None:+ return None+ if allow_stale:+ return _subscription_snapshot_cache+ age = time.monotonic() - _subscription_snapshot_cache_at+ if age <= _SUBSCRIPTION_SNAPSHOT_CACHE_TTL_S:+ return _subscription_snapshot_cache+ return None+++def _store_subscription_snapshot_locked(+ snapshot: CodexAppServerCapability,+) -> None:+ global _subscription_snapshot_cache, _subscription_snapshot_cache_at++ _subscription_snapshot_cache = snapshot+ _subscription_snapshot_cache_at = time.monotonic()+++def _invalidate_subscription_snapshot_locked() -> None:+ """Drop the cached status after anything that can change the profile."""+ global _subscription_snapshot_cache, _subscription_snapshot_cache_at++ _subscription_snapshot_cache = None+ _subscription_snapshot_cache_at = 0.0+def _subscription_transport_pass_fds(client: CodexAppServerClient,@@ -2800,6 +2853,7 @@ def _release_subscription_transport(client: CodexAppServerClient) -> None:_subscription_transport_process_lock = Noneif process_lock is not None:process_lock.close()+ _subscription_state_changed.notify_all()def _release_subscription_mutation_process_lock_locked() -> None:@@ -2896,7 +2950,7 @@ def _local_subscription_auth_snapshot_locked() -> CodexAppServerCapability | Nonbinary_path=None,version=None,reason="Dedicated ChatGPT subscription voice is starting.",- reason_code="setup_invalid",+ reason_code="busy",)if _subscription_profile_mutating:return CodexAppServerCapability(@@ -2905,7 +2959,7 @@ def _local_subscription_auth_snapshot_locked() -> CodexAppServerCapability | Nonbinary_path=None,version=None,reason="Dedicated subscription voice status is being checked or changed.",- reason_code="setup_invalid",+ reason_code="busy",)return None@@ -2913,33 +2967,64 @@ def _local_subscription_auth_snapshot_locked() -> CodexAppServerCapability | Nondef codex_subscription_auth_snapshot(binary_path: str | None = None,) -> CodexAppServerCapability:- """Return a lightweight snapshot without starting ``codex app-server``."""+ """Return a lightweight snapshot without starting ``codex app-server``.++ Concurrent callers never see a fake broken setup: while another probe or a+ profile mutation owns the profile, this serves the last completed result,+ or waits briefly for the owner and re-evaluates. Only a cold start that+ stays contended past the bounded wait reports the transient ``busy`` state.+ """global _subscription_mutation_process_lock, _subscription_profile_mutating- with _subscription_login_lock:- local_snapshot = _local_subscription_auth_snapshot_locked()- if local_snapshot is not None:- return local_snapshot- try:- _subscription_mutation_process_lock = (- _acquire_subscription_process_lock()- )- except CodexSubscriptionUnavailable as exc: # Expected lock failure becomes status.- return CodexAppServerCapability(- available=False,- chatgpt_authenticated=False,- binary_path=None,- version=None,- reason=str(exc),- reason_code="setup_invalid",- )- _subscription_profile_mutating = True+ deadline = time.monotonic() + _SUBSCRIPTION_SNAPSHOT_WAIT_TIMEOUT_S+ with _subscription_state_changed:+ while True:+ local_snapshot = _local_subscription_auth_snapshot_locked()+ if local_snapshot is not None:+ if local_snapshot.reason_code != "busy":+ return local_snapshot+ cached = _cached_subscription_snapshot_locked(allow_stale=True)+ if cached is not None:+ return cached+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ return local_snapshot+ _subscription_state_changed.wait(timeout=remaining)+ continue+ cached = _cached_subscription_snapshot_locked(allow_stale=False)+ if cached is not None:+ return cached+ try:+ _subscription_mutation_process_lock = (+ _acquire_subscription_process_lock()+ )+ except CodexSubscriptionUnavailable as exc:+ # Another process (a second Jarvis instance or CLI session)+ # briefly owns the profile. Serve the last known status; a+ # transient lock is not a setup defect.+ stale = _cached_subscription_snapshot_locked(allow_stale=True)+ if stale is not None:+ return stale+ return CodexAppServerCapability(+ available=False,+ chatgpt_authenticated=False,+ binary_path=None,+ version=None,+ reason=str(exc),+ reason_code="busy",+ )+ _subscription_profile_mutating = True+ breaktry:- return _read_codex_capability(binary_path)+ snapshot = _read_codex_capability(binary_path)+ with _subscription_login_lock:+ _store_subscription_snapshot_locked(snapshot)+ return snapshotfinally:with _subscription_login_lock:_release_subscription_mutation_process_lock_locked()_subscription_profile_mutating = False+ _subscription_state_changed.notify_all()def start_codex_subscription_login(@@ -3016,6 +3101,8 @@ def start_codex_subscription_login(_release_subscription_mutation_process_lock_locked()_subscription_profile_mutating = False_subscription_login_in_flight = False+ _invalidate_subscription_snapshot_locked()+ _subscription_state_changed.notify_all()raise CodexSubscriptionUnavailable(str(exc)) from excexcept BaseException:if log_dir is not None:@@ -3024,6 +3111,8 @@ def start_codex_subscription_login(_release_subscription_mutation_process_lock_locked()_subscription_profile_mutating = False_subscription_login_in_flight = False+ _invalidate_subscription_snapshot_locked()+ _subscription_state_changed.notify_all()raisewith _subscription_login_lock:@@ -3070,6 +3159,8 @@ def start_codex_subscription_login(_subscription_login_in_flight = False_subscription_profile_mutating = False_release_subscription_mutation_process_lock_locked()+ _invalidate_subscription_snapshot_locked()+ _subscription_state_changed.notify_all()_launch_subscription_login_reaper(cleanup_login)return process@@ -3124,6 +3215,8 @@ def logout_codex_subscription(with _subscription_login_lock:_release_subscription_mutation_process_lock_locked()_subscription_profile_mutating = False+ _invalidate_subscription_snapshot_locked()+ _subscription_state_changed.notify_all()async def disconnect_and_logout_codex_subscription(@@ -3172,6 +3265,8 @@ async def disconnect_and_logout_codex_subscription(else:_release_subscription_mutation_process_lock_locked()_subscription_profile_mutating = False+ _invalidate_subscription_snapshot_locked()+ _subscription_state_changed.notify_all()async def codex_subscription_login_ready(binary_path: str | None = None) -> bool:diff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsxindex 34cade0069..3ce8f808d4 100644--- a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx+++ b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx@@ -1620,9 +1620,11 @@ function CodexAuthWidget({? "apikeys_codex.status_lifecycle_unavailable": status.reason_code === "setup_invalid"? "apikeys_codex.status_setup_invalid"- : status.reason_code === "not_installed" || !status.installed- ? "apikeys_codex.status_not_installed"- : "apikeys_codex.status_login_required";+ : status.reason_code === "busy"+ ? "apikeys_codex.status_busy"+ : status.reason_code === "not_installed" || !status.installed+ ? "apikeys_codex.status_not_installed"+ : "apikeys_codex.status_login_required";useEffect(() => {if (!loginPolling || loginReady) return;@@ -1741,7 +1743,7 @@ function CodexAuthWidget({</div></div>- {!status?.installed && (+ {!status?.installed && status?.reason_code !== "busy" && (<div className="flex flex-wrap items-center gap-2"><code className="min-w-[220px] flex-1 rounded-md border border-border bg-muted/30 px-3 py-1.5 font-mono text-xs">{installCommand}diff --git a/jarvis/ui/web/frontend/src/hooks/useProviders.ts b/jarvis/ui/web/frontend/src/hooks/useProviders.tsindex 1998f69cb9..e7410d5ad7 100644--- a/jarvis/ui/web/frontend/src/hooks/useProviders.ts+++ b/jarvis/ui/web/frontend/src/hooks/useProviders.ts@@ -153,7 +153,11 @@ export interface CodexStatus {| "login_required"| "lifecycle_unavailable"| "not_installed"- | "setup_invalid";+ | "setup_invalid"+ // Transient: the profile is briefly owned by another status probe, a+ // login/logout, or a starting voice session. Not a setup defect — the UI+ // shows a neutral "checking" line and never the reconnect warning.+ | "busy";version?: string | null;accountLabel?: string | null;account_label?: string | null;diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 116e61078f..c7406b1173 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -1909,6 +1909,7 @@"status_not_installed": "Installiere zuerst die unterstützte Codex-Version und verbinde danach ChatGPT.","status_lifecycle_unavailable": "Subscription Voice ist auf diesem Betriebssystem noch nicht verfügbar. API Realtime und Standard-Voice funktionieren weiterhin.","status_setup_invalid": "Das geschützte Codex-Sprachprofil braucht Aufmerksamkeit. Prüfe die Anleitung und verbinde es danach neu.",+ "status_busy": "Der ChatGPT-Sprachstatus wird gerade geprüft — einen Moment.","install_command_copied": "Installationsbefehl kopiert","connected_chatgpt": "Über dein ChatGPT-Abo verbunden.","disconnect": "Trennen",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex eae7bbdbef..c36837300b 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -1910,6 +1910,7 @@"status_not_installed": "Install the supported Codex version before connecting ChatGPT.","status_lifecycle_unavailable": "Subscription voice is not yet available on this operating system. API Realtime and standard voice still work.","status_setup_invalid": "The protected Codex voice profile needs attention. Review the setup guide, then reconnect.",+ "status_busy": "Checking the ChatGPT voice status — one moment.","install_command_copied": "Install command copied","connected_chatgpt": "Connected through your ChatGPT subscription.","disconnect": "Disconnect",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 452f0563cd..8ec37dc426 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -1909,6 +1909,7 @@"status_not_installed": "Instala la versión compatible de Codex antes de conectar ChatGPT.","status_lifecycle_unavailable": "La voz por suscripción aún no está disponible en este sistema operativo. API Realtime y la voz estándar siguen funcionando.","status_setup_invalid": "El perfil protegido de voz de Codex necesita atención. Revisa la guía de configuración y vuelve a conectarlo.",+ "status_busy": "Comprobando el estado de voz de ChatGPT — un momento.","install_command_copied": "Comando de instalación copiado","connected_chatgpt": "Conectado mediante tu suscripción de ChatGPT.","disconnect": "Desconectar",diff --git a/jarvis/ui/web/frontend/src/i18n/voice-i18n-parity.test.ts b/jarvis/ui/web/frontend/src/i18n/voice-i18n-parity.test.tsindex e09fa38793..7af20a72a9 100644--- a/jarvis/ui/web/frontend/src/i18n/voice-i18n-parity.test.ts+++ b/jarvis/ui/web/frontend/src/i18n/voice-i18n-parity.test.ts@@ -132,6 +132,7 @@ describe("subscription Realtime voice copy", () => {"apikeys_codex.status_not_installed","apikeys_codex.status_lifecycle_unavailable","apikeys_codex.status_setup_invalid",+ "apikeys_codex.status_busy","apikeys_codex.install_command_copied","apikeys_codex.connected_chatgpt","apikeys_codex.disconnect",diff --git a/tests/unit/codex_app_server/test_transport.py b/tests/unit/codex_app_server/test_transport.pyindex 5b30967fe0..bab36a37b2 100644--- a/tests/unit/codex_app_server/test_transport.py+++ b/tests/unit/codex_app_server/test_transport.py@@ -12,6 +12,7 @@ import osimport shutilimport sysimport threading+import timefrom collections.abc import Callablefrom pathlib import Pathfrom types import SimpleNamespace@@ -71,6 +72,8 @@ def isolated_profile_lifecycle(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(transport, "_subscription_active_transports", set())monkeypatch.setattr(transport, "_subscription_transport_process_lock", None)monkeypatch.setattr(transport, "_subscription_mutation_process_lock", None)+ monkeypatch.setattr(transport, "_subscription_snapshot_cache", None)+ monkeypatch.setattr(transport, "_subscription_snapshot_cache_at", 0.0)class FakeStdin:@@ -1033,11 +1036,18 @@ def test_public_auth_snapshot_uses_live_state_without_cli_probe(def test_public_auth_snapshot_holds_profile_owner_for_entire_probe(monkeypatch: pytest.MonkeyPatch,) -> None:+ """A concurrent status call waits for the running probe and shares its result.++ The old contract returned ``setup_invalid`` to every losing caller, so a+ burst of UI refreshes rendered "profile needs attention" on a perfectly+ connected install (the reproduced desktop bug).+ """started = threading.Event()release = threading.Event()process_lock = FakeProfileProcessLock()reads: list[str | None] = []results: list[CodexAppServerCapability] = []+ concurrent_results: list[CodexAppServerCapability] = []monkeypatch.setattr(transport,@@ -1070,21 +1080,178 @@ def test_public_auth_snapshot_holds_profile_owner_for_entire_probe(worker.start()assert started.wait(timeout=1.0)- concurrent = transport.codex_subscription_auth_snapshot("codex-test")-- assert concurrent.reason_code == "setup_invalid"+ concurrent_worker = threading.Thread(+ target=lambda: concurrent_results.append(+ transport.codex_subscription_auth_snapshot("codex-test")+ )+ )+ concurrent_worker.start()+ # The concurrent caller must block on the running probe, not read the+ # profile itself and not answer with a fake broken-setup status.+ concurrent_worker.join(timeout=0.3)+ assert concurrent_worker.is_alive() is Trueassert reads == ["codex-test"]assert process_lock.closed is False+release.set()worker.join(timeout=2.0)+ concurrent_worker.join(timeout=2.0)assert worker.is_alive() is False+ assert concurrent_worker.is_alive() is Falseassert results[0].reason_code == "ready"+ # Exactly one CLI probe served both callers.+ assert reads == ["codex-test"]+ assert concurrent_results[0].reason_code == "ready"+ assert concurrent_results[0].chatgpt_authenticated is Trueassert process_lock.closed is Trueassert transport._subscription_profile_mutating is Falseassert transport._subscription_mutation_process_lock is None+def test_auth_snapshot_burst_coalesces_to_single_probe(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Six parallel status calls (the UI mount burst) cost one CLI probe."""+ reads: list[str | None] = []+ ready = CodexAppServerCapability(+ available=True,+ chatgpt_authenticated=True,+ binary_path="codex-test",+ version="codex-cli 0.146.0",+ reason="ready",+ reason_code="ready",+ )++ def probe(binary: str | None) -> CodexAppServerCapability:+ reads.append(binary)+ time.sleep(0.05)+ return ready++ monkeypatch.setattr(transport, "_read_codex_capability", probe)+ results: list[CodexAppServerCapability] = []+ results_lock = threading.Lock()++ def call() -> None:+ snapshot = transport.codex_subscription_auth_snapshot("codex-test")+ with results_lock:+ results.append(snapshot)++ workers = [threading.Thread(target=call) for _ in range(6)]+ for worker in workers:+ worker.start()+ for worker in workers:+ worker.join(timeout=3.0)++ assert all(not worker.is_alive() for worker in workers)+ assert len(reads) == 1+ assert len(results) == 6+ assert all(snapshot.reason_code == "ready" for snapshot in results)+++def test_auth_snapshot_cache_expires_and_reprobes(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ reads: list[str | None] = []+ ready = CodexAppServerCapability(+ available=True,+ chatgpt_authenticated=True,+ binary_path="codex-test",+ version="codex-cli 0.146.0",+ reason="ready",+ reason_code="ready",+ )++ def probe(binary: str | None) -> CodexAppServerCapability:+ reads.append(binary)+ return ready++ monkeypatch.setattr(transport, "_read_codex_capability", probe)++ first = transport.codex_subscription_auth_snapshot("codex-test")+ second = transport.codex_subscription_auth_snapshot("codex-test")+ assert first.reason_code == "ready"+ assert second.reason_code == "ready"+ # Within the TTL the second call is served from the cache.+ assert len(reads) == 1++ with transport._subscription_login_lock:+ transport._subscription_snapshot_cache_at = (+ time.monotonic() - transport._SUBSCRIPTION_SNAPSHOT_CACHE_TTL_S - 1.0+ )+ third = transport.codex_subscription_auth_snapshot("codex-test")+ assert third.reason_code == "ready"+ assert len(reads) == 2+++def test_logout_invalidates_auth_snapshot_cache(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ reads: list[str | None] = []+ ready = CodexAppServerCapability(+ available=True,+ chatgpt_authenticated=True,+ binary_path="codex-test",+ version="codex-cli 0.146.0",+ reason="ready",+ reason_code="ready",+ )++ def probe(binary: str | None) -> CodexAppServerCapability:+ reads.append(binary)+ return ready++ monkeypatch.setattr(transport, "_read_codex_capability", probe)+ monkeypatch.setattr(+ transport,+ "_delete_codex_subscription_auth_locked",+ lambda: (True, None),+ )++ assert transport.codex_subscription_auth_snapshot("codex-test").reason_code == "ready"+ assert len(reads) == 1++ assert transport.logout_codex_subscription() == (True, None)++ # Logout changed the profile, so the cached "ready" must not survive it.+ assert transport.codex_subscription_auth_snapshot("codex-test").reason_code == "ready"+ assert len(reads) == 2+++def test_auth_snapshot_contended_process_lock_serves_last_known_status(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A foreign process briefly owning the profile is not a broken setup."""+ ready = CodexAppServerCapability(+ available=True,+ chatgpt_authenticated=True,+ binary_path="codex-test",+ version="codex-cli 0.146.0",+ reason="ready",+ reason_code="ready",+ )+ monkeypatch.setattr(transport, "_read_codex_capability", lambda _binary: ready)+ assert transport.codex_subscription_auth_snapshot("codex-test").reason_code == "ready"++ def contended() -> FakeProfileProcessLock:+ raise CodexSubscriptionUnavailable("owned elsewhere")++ monkeypatch.setattr(transport, "_acquire_subscription_process_lock", contended)+ with transport._subscription_login_lock:+ transport._subscription_snapshot_cache_at = (+ time.monotonic() - transport._SUBSCRIPTION_SNAPSHOT_CACHE_TTL_S - 1.0+ )++ stale = transport.codex_subscription_auth_snapshot("codex-test")+ assert stale.reason_code == "ready"++ with transport._subscription_login_lock:+ transport._invalidate_subscription_snapshot_locked()+ cold = transport.codex_subscription_auth_snapshot("codex-test")+ assert cold.reason_code == "busy"+ assert cold.available is False++@pytest.mark.asyncioasync def test_capability_worker_keeps_profile_reserved_until_it_finishes(monkeypatch: pytest.MonkeyPatch,diff --git a/tests/unit/ui/test_provider_spec_codex_subscription_realtime.py b/tests/unit/ui/test_provider_spec_codex_subscription_realtime.pyindex a78881b622..5e6c7e2e21 100644--- a/tests/unit/ui/test_provider_spec_codex_subscription_realtime.py+++ b/tests/unit/ui/test_provider_spec_codex_subscription_realtime.py@@ -155,6 +155,8 @@ async def test_section_health_accepts_keyring_only_chatgpt_login(async def test_realtime_activation_rejects_codex_api_key_mode(monkeypatch: pytest.MonkeyPatch,) -> None:+ from jarvis import codex_app_server+class _Service:def __init__(self, *_args, **_kwargs) -> None:pass@@ -165,6 +167,17 @@ async def test_realtime_activation_rejects_codex_api_key_mode(monkeypatch.setattr(routes, "CodexAuthService", _Service)monkeypatch.setattr(routes, "_codex_binary_path", lambda *_args: "codex")+ # The route judges this provider by the dedicated-profile probe, never the+ # ordinary Codex login. An api-key-mode login yields no ChatGPT-authenticated+ # dedicated profile, so the probe answers False. Patching the probe keeps+ # this unit test off the real CLI and independent of the host's login state.+ async def not_ready(_binary_path: str | None = None) -> bool:+ return False++ monkeypatch.setattr(+ codex_app_server, "codex_subscription_login_ready", not_ready+ )+with pytest.raises(HTTPException) as caught:await routes.realtime_switch(routes.SwitchBody(@@ -291,6 +304,7 @@ async def test_subscription_voice_status_uses_isolated_snapshot((False, False, "codex-cli 0.146.0", "login_required"),(False, False, None, "not_installed"),(False, False, "codex-cli 0.147.0", "setup_invalid"),+ (False, False, None, "busy"),],)def test_subscription_status_has_stable_reason_codes(