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): close every gap two adversarial reviews found in the busy-status change

Ruben Lütked680a61494e1
diff --git a/jarvis/codex_app_server.py b/jarvis/codex_app_server.py
index 91c474e14c..32b77e0b8d 100644
--- a/jarvis/codex_app_server.py
+++ b/jarvis/codex_app_server.py
@@ -1409,7 +1409,16 @@ class CodexAppServerClient:
# hard timeout. Do not wrap ``to_thread`` in ``wait_for``: cancelling
# that await leaves the worker thread running against CODEX_HOME and
# would release the profile mutation gate too early.
- return await asyncio.to_thread(_read_codex_capability, self._binary_path)
+ capability = await asyncio.to_thread(
+ _read_codex_capability, self._binary_path
+ )
+ # While this client reserves the transport, ordinary status probes
+ # answer "busy". Publishing this authoritative result keeps every
+ # concurrent status caller truthful during app-server startup and
+ # wakes waiters parked on the busy window.
+ with _subscription_login_lock:
+ _store_subscription_snapshot_locked(self._binary_path, capability)
+ return capability
except TimeoutError: # The returned status reports this bounded probe failure.
return CodexAppServerCapability(
available=False,
@@ -1457,7 +1466,8 @@ class CodexAppServerClient:
expected=False,
)
- _reserve_subscription_transport(self)
+ # Off the event loop: reserving may wait out a running status probe.
+ await asyncio.to_thread(_reserve_subscription_transport, self)
self._profile_transport_reserved = True
try:
@@ -1506,6 +1516,10 @@ class CodexAppServerClient:
trusted_binary_path=self._trusted_binary_path,
)
self._ready = True
+ # Status callers waiting out the "voice is starting" window can
+ # now read the ready transport state directly.
+ with _subscription_login_lock:
+ _subscription_state_changed.notify_all()
except BaseException:
await self._close_process(
CodexAppServerDisconnected("Codex app-server initialization failed."),
@@ -2753,47 +2767,97 @@ _subscription_mutation_process_lock: Any | None = None
# 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
+# A snapshot served while the profile is briefly owned elsewhere may be stale,
+# but never arbitrarily old: beyond this bound the caller reports busy instead
+# of a status another process may have changed long ago.
+_SUBSCRIPTION_SNAPSHOT_STALE_MAX_S: Final = 60.0
+# How long user actions (login, logout, call start) wait for a read-only
+# status probe to release the profile before failing honestly.
+_SUBSCRIPTION_PROBE_WAIT_S: Final = 5.0
_subscription_state_changed = threading.Condition(_subscription_login_lock)
_subscription_snapshot_cache: CodexAppServerCapability | None = None
+_subscription_snapshot_cache_key: str = ""
_subscription_snapshot_cache_at: float = 0.0
+# True only while codex_subscription_auth_snapshot itself owns the profile.
+# Distinguishes the read-only probe from real mutations (login/logout), so
+# user actions can wait out a probe instead of failing with a message that
+# blames a login that does not exist.
+_subscription_status_probe_active = False
+
+
+def _subscription_cache_key(binary_path: str | None) -> str:
+ return (binary_path or "").strip() or "<default>"
def _cached_subscription_snapshot_locked(
- *, allow_stale: bool
+ binary_path: str | None, *, 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.
+ owned elsewhere, bounded by ``_SUBSCRIPTION_SNAPSHOT_STALE_MAX_S``.
+ In-process mutations invalidate the cache, so a stale entry cannot outlive
+ a login, logout, or disconnect performed by this process; an entry only
+ ages past the TTL while another process owns the profile.
"""
if _subscription_snapshot_cache is None:
return None
- if allow_stale:
- return _subscription_snapshot_cache
+ if _subscription_snapshot_cache_key != _subscription_cache_key(binary_path):
+ return None
age = time.monotonic() - _subscription_snapshot_cache_at
- if age <= _SUBSCRIPTION_SNAPSHOT_CACHE_TTL_S:
+ limit = (
+ _SUBSCRIPTION_SNAPSHOT_STALE_MAX_S
+ if allow_stale
+ else _SUBSCRIPTION_SNAPSHOT_CACHE_TTL_S
+ )
+ if age <= limit:
return _subscription_snapshot_cache
return None
def _store_subscription_snapshot_locked(
+ binary_path: str | None,
snapshot: CodexAppServerCapability,
) -> None:
- global _subscription_snapshot_cache, _subscription_snapshot_cache_at
+ global _subscription_snapshot_cache, _subscription_snapshot_cache_key
+ global _subscription_snapshot_cache_at
_subscription_snapshot_cache = snapshot
+ _subscription_snapshot_cache_key = _subscription_cache_key(binary_path)
_subscription_snapshot_cache_at = time.monotonic()
+ # Waiters parked on a busy window get the fresh result immediately.
+ _subscription_state_changed.notify_all()
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
+ global _subscription_snapshot_cache, _subscription_snapshot_cache_key
+ global _subscription_snapshot_cache_at
_subscription_snapshot_cache = None
+ _subscription_snapshot_cache_key = ""
_subscription_snapshot_cache_at = 0.0
+def _await_status_probe_completion_locked() -> None:
+ """Wait briefly for a status probe to release the profile.
+
+ Caller holds ``_subscription_login_lock``. A status probe is read-only and
+ short; failing a user action because a background refresh happens to own
+ the profile — with an error naming a login that does not exist — is worse
+ than waiting the probe out.
+ """
+ deadline = time.monotonic() + _SUBSCRIPTION_PROBE_WAIT_S
+ while _subscription_status_probe_active:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise CodexSubscriptionUnavailable(
+ "A subscription-voice status check is still running. "
+ "Try again in a moment."
+ )
+ _subscription_state_changed.wait(timeout=remaining)
+
+
def _subscription_transport_pass_fds(
client: CodexAppServerClient,
) -> tuple[int, ...]:
@@ -2825,6 +2889,7 @@ def _reserve_subscription_transport(client: CodexAppServerClient) -> None:
global _subscription_transport_process_lock
with _subscription_login_lock:
+ _await_status_probe_completion_locked()
if _subscription_profile_mutating:
raise CodexSubscriptionUnavailable(
"The subscription-voice profile is being changed."
@@ -2925,6 +2990,18 @@ def _local_subscription_auth_snapshot_locked() -> CodexAppServerCapability | Non
reason="Dedicated ChatGPT subscription login is in progress.",
reason_code="login_required",
)
+ if _subscription_profile_mutating:
+ # Checked before the transport branch: during disconnect-and-logout
+ # both are set, and reporting the closing transport as still ready
+ # would be a lie for the whole teardown window.
+ return CodexAppServerCapability(
+ available=False,
+ chatgpt_authenticated=False,
+ binary_path=None,
+ version=None,
+ reason="Dedicated subscription voice status is being checked or changed.",
+ reason_code="busy",
+ )
if _subscription_active_transports:
with _shared_clients_lock:
active_clients = tuple(
@@ -2952,15 +3029,6 @@ def _local_subscription_auth_snapshot_locked() -> CodexAppServerCapability | Non
reason="Dedicated ChatGPT subscription voice is starting.",
reason_code="busy",
)
- if _subscription_profile_mutating:
- return CodexAppServerCapability(
- available=False,
- chatgpt_authenticated=False,
- binary_path=None,
- version=None,
- reason="Dedicated subscription voice status is being checked or changed.",
- reason_code="busy",
- )
return None
@@ -2975,6 +3043,7 @@ def codex_subscription_auth_snapshot(
stays contended past the bounded wait reports the transient ``busy`` state.
"""
global _subscription_mutation_process_lock, _subscription_profile_mutating
+ global _subscription_status_probe_active
deadline = time.monotonic() + _SUBSCRIPTION_SNAPSHOT_WAIT_TIMEOUT_S
with _subscription_state_changed:
@@ -2983,7 +3052,9 @@ def codex_subscription_auth_snapshot(
if local_snapshot is not None:
if local_snapshot.reason_code != "busy":
return local_snapshot
- cached = _cached_subscription_snapshot_locked(allow_stale=True)
+ cached = _cached_subscription_snapshot_locked(
+ binary_path, allow_stale=True
+ )
if cached is not None:
return cached
remaining = deadline - time.monotonic()
@@ -2991,7 +3062,9 @@ def codex_subscription_auth_snapshot(
return local_snapshot
_subscription_state_changed.wait(timeout=remaining)
continue
- cached = _cached_subscription_snapshot_locked(allow_stale=False)
+ cached = _cached_subscription_snapshot_locked(
+ binary_path, allow_stale=False
+ )
if cached is not None:
return cached
try:
@@ -3002,8 +3075,15 @@ def codex_subscription_auth_snapshot(
# 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)
+ stale = _cached_subscription_snapshot_locked(
+ binary_path, allow_stale=True
+ )
if stale is not None:
+ log.debug(
+ "Subscription profile owned by another process (%s); "
+ "serving the last known status.",
+ exc,
+ )
return stale
return CodexAppServerCapability(
available=False,
@@ -3014,16 +3094,39 @@ def codex_subscription_auth_snapshot(
reason_code="busy",
)
_subscription_profile_mutating = True
+ _subscription_status_probe_active = True
break
try:
snapshot = _read_codex_capability(binary_path)
+ except Exception as exc:
+ # Cache the failure briefly so waiters coalesced behind this probe do
+ # not each retry the broken CLI serially; the owner still raises so
+ # its caller sees the real error.
with _subscription_login_lock:
- _store_subscription_snapshot_locked(snapshot)
+ _store_subscription_snapshot_locked(
+ binary_path,
+ CodexAppServerCapability(
+ available=False,
+ chatgpt_authenticated=False,
+ binary_path=None,
+ version=None,
+ reason=(
+ "Codex status probe failed "
+ f"({type(exc).__name__})."
+ ),
+ reason_code="setup_invalid",
+ ),
+ )
+ raise
+ else:
+ with _subscription_login_lock:
+ _store_subscription_snapshot_locked(binary_path, snapshot)
return snapshot
finally:
with _subscription_login_lock:
_release_subscription_mutation_process_lock_locked()
_subscription_profile_mutating = False
+ _subscription_status_probe_active = False
_subscription_state_changed.notify_all()
@@ -3046,6 +3149,7 @@ def start_codex_subscription_login(
"Run Jarvis on a desktop to connect this dedicated profile."
)
with _subscription_login_lock:
+ _await_status_probe_completion_locked()
if _subscription_profile_mutating or _subscription_login_in_flight:
raise CodexSubscriptionUnavailable(
"A subscription-voice login is already in progress."
@@ -3059,6 +3163,7 @@ def start_codex_subscription_login(
)
_subscription_profile_mutating = True
_subscription_login_in_flight = True
+ _invalidate_subscription_snapshot_locked()
log_dir: Path | None = None
try:
@@ -3162,7 +3267,23 @@ def start_codex_subscription_login(
_invalidate_subscription_snapshot_locked()
_subscription_state_changed.notify_all()
- _launch_subscription_login_reaper(cleanup_login)
+ try:
+ _launch_subscription_login_reaper(cleanup_login)
+ except BaseException:
+ # Without a reaper the login flags would stay set until restart and
+ # the profile would wedge as "login in progress". Kill the orphaned
+ # login attempt and restore a clean not-logged-in state.
+ with suppress(Exception):
+ process.kill()
+ with _subscription_login_lock:
+ if _subscription_login_process is process:
+ _subscription_login_process = None
+ _subscription_login_in_flight = False
+ _subscription_profile_mutating = False
+ _release_subscription_mutation_process_lock_locked()
+ _invalidate_subscription_snapshot_locked()
+ _subscription_state_changed.notify_all()
+ raise
return process
@@ -3197,6 +3318,7 @@ def logout_codex_subscription(
del binary_path # Kept for the stable route/helper signature.
with _subscription_login_lock:
+ _await_status_probe_completion_locked()
if _subscription_profile_mutating or _subscription_login_in_flight:
raise CodexSubscriptionUnavailable(
"Subscription voice cannot log out while login is in progress."
@@ -3209,6 +3331,7 @@ def logout_codex_subscription(
_acquire_subscription_process_lock()
)
_subscription_profile_mutating = True
+ _invalidate_subscription_snapshot_locked()
try:
return _delete_codex_subscription_auth_locked()
finally:
@@ -3219,16 +3342,13 @@ def logout_codex_subscription(
_subscription_state_changed.notify_all()
-async def disconnect_and_logout_codex_subscription(
- binary_path: str | None = None,
-) -> tuple[bool, str | None]:
- """Atomically block starts, close the transport, and delete its login."""
+def _begin_subscription_disconnect_mutation() -> None:
+ """Claim the profile for disconnect; runs off-loop (it may wait briefly)."""
global _subscription_mutation_process_lock, _subscription_profile_mutating
global _subscription_transport_process_lock
- del binary_path # Kept for the stable route/helper signature.
-
with _subscription_login_lock:
+ _await_status_probe_completion_locked()
if _subscription_profile_mutating or _subscription_login_in_flight:
raise CodexSubscriptionUnavailable(
"Subscription voice cannot log out while login is in progress."
@@ -3246,6 +3366,20 @@ async def disconnect_and_logout_codex_subscription(
_acquire_subscription_process_lock()
)
_subscription_profile_mutating = True
+ _invalidate_subscription_snapshot_locked()
+
+
+async def disconnect_and_logout_codex_subscription(
+ binary_path: str | None = None,
+) -> tuple[bool, str | None]:
+ """Atomically block starts, close the transport, and delete its login."""
+ global _subscription_mutation_process_lock, _subscription_profile_mutating
+ global _subscription_transport_process_lock
+
+ del binary_path # Kept for the stable route/helper signature.
+
+ # Off the event loop: claiming the profile may wait out a status probe.
+ await asyncio.to_thread(_begin_subscription_disconnect_mutation)
try:
await close_shared_codex_app_servers()
return await asyncio.to_thread(_delete_codex_subscription_auth_locked)
diff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx
index 3cb93da66b..bf09a2dd54 100644
--- a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx
@@ -468,6 +468,16 @@ describe("ProviderCard: ChatGPT subscription Realtime", () => {
"The protected Codex voice profile needs attention. Review the setup guide, then reconnect.",
),
).toBeNull();
+ // The state chip next to the provider name must not shout "missing" (red)
+ // about an install the probe has not judged yet.
+ expect(screen.queryByText("missing")).toBeNull();
+ expect(screen.getByText("checking")).toBeTruthy();
+ // The connect action stays available: login validates itself and a busy
+ // flicker must not lock the user out of it.
+ const connect = screen.getByRole("button", {
+ name: "Connect with ChatGPT",
+ }) as HTMLButtonElement;
+ expect(connect.disabled).toBe(false);
});
it("surfaces the precise backend diagnosis on a real setup defect", () => {
@@ -490,7 +500,9 @@ describe("ProviderCard: ChatGPT subscription Realtime", () => {
"The protected Codex voice profile needs attention. Review the setup guide, then reconnect.",
),
).toBeTruthy();
- expect(screen.getByTestId("codex-setup-detail").textContent).toBe(
+ const detail = screen.getByTestId("codex-setup-detail").textContent ?? "";
+ expect(detail).toContain("Details:");
+ expect(detail).toContain(
"Subscription voice requires Codex CLI codex-cli 0.146.0.",
);
});
diff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx
index 4e236d75a6..ad93d82156 100644
--- a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx
+++ b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx
@@ -1751,6 +1751,9 @@ function CodexAuthWidget({
data-testid="codex-setup-detail"
className="mt-2 break-words border-t border-border/60 pt-2 font-mono text-[11px]"
>
+ <span className="mr-1 font-sans">
+ {t("apikeys_codex.setup_detail_label")}
+ </span>
{status.message}
</div>
)}
@@ -1772,7 +1775,11 @@ function CodexAuthWidget({
<Button
size="sm"
onClick={handleLogin}
- disabled={pending !== null || loginPolling || !status?.installed}
+ disabled={
+ pending !== null ||
+ loginPolling ||
+ (!status?.installed && status?.reason_code !== "busy")
+ }
>
<LogIn className="h-3.5 w-3.5" />
{t("apikeys_codex.connect_chatgpt")}
@@ -1952,6 +1959,11 @@ export function StatusBadge({ descriptor }: { descriptor: ProviderDescriptor })
if (descriptor.active) return <StateChip tone="active">active</StateChip>;
if (descriptor.auth_mode === "codex") {
const status = descriptor.codex_status;
+ // Transient: the status is being probed right now. Neither "missing" nor
+ // "not connected" is known yet, and the red chip on a healthy install was
+ // exactly the bug this state exists to prevent.
+ if (status?.reason_code === "busy")
+ return <StateChip tone="neutral">checking</StateChip>;
if (!status?.installed) return <StateChip tone="missing">missing</StateChip>;
if (descriptor.configured) return <StateChip tone="ready">ready</StateChip>;
return <StateChip tone="neutral">not connected</StateChip>;
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index c7406b1173..a35583477f 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -1910,6 +1910,7 @@
"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.",
+ "setup_detail_label": "Details:",
"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.json
index c36837300b..f0f3b51af0 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -1911,6 +1911,7 @@
"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.",
+ "setup_detail_label": "Details:",
"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.json
index 8ec37dc426..42a84aef9c 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -1910,6 +1910,7 @@
"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.",
+ "setup_detail_label": "Detalles:",
"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.ts
index 7af20a72a9..ca70085f07 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
@@ -133,6 +133,7 @@ describe("subscription Realtime voice copy", () => {
"apikeys_codex.status_lifecycle_unavailable",
"apikeys_codex.status_setup_invalid",
"apikeys_codex.status_busy",
+ "apikeys_codex.setup_detail_label",
"apikeys_codex.install_command_copied",
"apikeys_codex.connected_chatgpt",
"apikeys_codex.disconnect",
diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.py
index 9afefb5df9..ba7937ba28 100644
--- a/jarvis/ui/web/provider_routes.py
+++ b/jarvis/ui/web/provider_routes.py
@@ -475,10 +475,13 @@ def _spec_to_payload(
}
codex_status = None
if spec.auth_mode == "codex":
+ from_isolated_snapshot = (
+ spec.id == "codex-subscription-realtime"
+ and codex_subscription_status is not None
+ )
codex_status = (
dict(codex_subscription_status)
- if spec.id == "codex-subscription-realtime"
- and codex_subscription_status is not None
+ if from_isolated_snapshot
else CodexAuthService(_codex_binary_path()).status().to_dict()
)
if (
@@ -491,10 +494,20 @@ def _spec_to_payload(
codex_status["message"] = "Connected via ChatGPT."
else:
codex_status["mode"] = "not_connected"
- codex_status["message"] = (
- "ChatGPT subscription voice is not ready. "
- "Reconnect with ChatGPT and review the setup status."
- )
+ # The isolated snapshot's message carries the precise
+ # diagnosis (for example the exact required Codex version)
+ # that the card's detail line renders — keep it. A status
+ # read from the ORDINARY Codex profile is exactly what the
+ # authoritative override corrects, so its message must not
+ # survive; nor may an empty message reach the card.
+ if (
+ not from_isolated_snapshot
+ or not str(codex_status.get("message") or "").strip()
+ ):
+ codex_status["message"] = (
+ "ChatGPT subscription voice is not ready. "
+ "Reconnect with ChatGPT and review the setup status."
+ )
antigravity_status = None
if spec.id == "antigravity":
from jarvis.google_cli.auth_service import GoogleCliAuthService
@@ -1266,10 +1279,28 @@ async def _tier_section_health(
subject_id=spec.id,
)
try:
- configured = await _provider_credential_present_for_binary_async(
- spec,
- binary_path,
- )
+ if spec.id == "codex-subscription-realtime":
+ # One snapshot call answers both "configured?" and "busy?" — a
+ # second probe would wait out the same busy window twice.
+ codex_payload = await asyncio.to_thread(
+ _codex_subscription_status_payload, binary_path
+ )
+ if codex_payload.get("reason_code") == "busy":
+ # Transiently unknown is not "needs setup": the amber dot
+ # with "not connected" would contradict a card that says
+ # "checking — one moment".
+ return SectionHealth(
+ status=_section_health.UNKNOWN,
+ reason="busy",
+ detail=f"{spec.label}: status check in progress",
+ subject_id=spec.id,
+ )
+ configured = bool(codex_payload.get("connected"))
+ else:
+ configured = await _provider_credential_present_for_binary_async(
+ spec,
+ binary_path,
+ )
except Exception: # noqa: BLE001 — a probe failure is "not set up", not a crash
configured = False
if not configured:
@@ -1642,12 +1673,12 @@ async def section_health(request: Request, refresh: bool = False) -> SectionHeal
"""
while True:
cfg = _resolve_cfg(request)
- # The dictation subject is the one subject whose resolution blocks (see
- # ``_warm_active_polish``); every other one is an attribute read. Warm
- # it off the loop BEFORE the snapshot is taken, because the snapshot
- # feeds the cache fingerprint and this route is polled.
+ # Subject resolution can block: dictation warms a keyring-backed memo
+ # (see ``_warm_active_polish``) and the realtime subject may run the
+ # Codex subscription snapshot when a fallback chain names it. Both
+ # belong off the loop, because this route is polled.
await _warm_active_polish(request)
- subjects = _section_health_subjects(request, cfg)
+ subjects = await asyncio.to_thread(_section_health_subjects, request, cfg)
fingerprint = _section_health_fingerprint(request, cfg, subjects)
cache = getattr(request.app.state, "_section_health_cache", None)
now = time.time()
@@ -1703,7 +1734,9 @@ async def section_health(request: Request, refresh: bool = False) -> SectionHeal
current_cfg = _resolve_cfg(request)
await _warm_active_polish(request)
- current_subjects = _section_health_subjects(request, current_cfg)
+ current_subjects = await asyncio.to_thread(
+ _section_health_subjects, request, current_cfg
+ )
current_fingerprint = _section_health_fingerprint(
request, current_cfg, current_subjects
)
@@ -3698,7 +3731,24 @@ async def realtime_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
"the experimental transport before activating it."
),
)
- credential_present = await _provider_credential_present_async(spec, request)
+ if spec.id == "codex-subscription-realtime":
+ # One snapshot call answers both "configured?" and "busy?". A busy
+ # window is transient — telling the user to "connect first" while the
+ # card says "checking" would send them to re-do a working login.
+ codex_payload = await asyncio.to_thread(
+ _codex_subscription_status_payload, _codex_binary_path(request)
+ )
+ if codex_payload.get("reason_code") == "busy":
+ raise HTTPException(
+ status_code=409,
+ detail=(
+ "The ChatGPT subscription voice status is being checked. "
+ "Try again in a moment."
+ ),
+ )
+ credential_present = bool(codex_payload.get("connected"))
+ else:
+ credential_present = await _provider_credential_present_async(spec, request)
if not credential_present:
raise HTTPException(
status_code=409,
diff --git a/tests/unit/codex_app_server/test_transport.py b/tests/unit/codex_app_server/test_transport.py
index bab36a37b2..1a8a2ab6f5 100644
--- a/tests/unit/codex_app_server/test_transport.py
+++ b/tests/unit/codex_app_server/test_transport.py
@@ -73,7 +73,9 @@ def isolated_profile_lifecycle(monkeypatch: pytest.MonkeyPatch) -> None:
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_key", "")
monkeypatch.setattr(transport, "_subscription_snapshot_cache_at", 0.0)
+ monkeypatch.setattr(transport, "_subscription_status_probe_active", False)
class FakeStdin:
@@ -1252,6 +1254,203 @@ def test_auth_snapshot_contended_process_lock_serves_last_known_status(
assert cold.available is False
+def _ready_capability(binary_path: str = "codex-test") -> CodexAppServerCapability:
+ return CodexAppServerCapability(
+ available=True,
+ chatgpt_authenticated=True,
+ binary_path=binary_path,
+ version="codex-cli 0.146.0",
+ reason="ready",
+ reason_code="ready",
+ )
+
+
+def test_auth_snapshot_stale_cache_has_an_age_ceiling(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A foreign lock serves the last known status only up to a bounded age."""
+ monkeypatch.setattr(
+ transport, "_read_codex_capability", lambda _binary: _ready_capability()
+ )
+ 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_STALE_MAX_S - 1.0
+ )
+
+ beyond = transport.codex_subscription_auth_snapshot("codex-test")
+ assert beyond.reason_code == "busy"
+
+
+def test_auth_snapshot_cache_is_keyed_by_binary_path(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Correcting a configured binary path must not serve the old binary's result."""
+ reads: list[str | None] = []
+
+ def probe(binary: str | None) -> CodexAppServerCapability:
+ reads.append(binary)
+ return _ready_capability(binary_path=str(binary))
+
+ monkeypatch.setattr(transport, "_read_codex_capability", probe)
+
+ transport.codex_subscription_auth_snapshot("codex-a")
+ transport.codex_subscription_auth_snapshot("codex-a")
+ assert reads == ["codex-a"]
+
+ transport.codex_subscription_auth_snapshot("codex-b")
+ assert reads == ["codex-a", "codex-b"]
+
+
+def test_auth_snapshot_probe_failure_is_cached_for_waiters(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A raising probe must not make coalesced waiters re-run the broken CLI."""
+ reads: list[str | None] = []
+
+ def probe(binary: str | None) -> CodexAppServerCapability:
+ reads.append(binary)
+ raise OSError("cli exploded")
+
+ monkeypatch.setattr(transport, "_read_codex_capability", probe)
+
+ with pytest.raises(OSError):
+ transport.codex_subscription_auth_snapshot("codex-test")
+
+ second = transport.codex_subscription_auth_snapshot("codex-test")
+ assert second.reason_code == "setup_invalid"
+ assert "OSError" in second.reason
+ assert reads == ["codex-test"]
+
+
+def test_logout_waits_for_a_running_status_probe(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A background status refresh must delay logout, not fail it."""
+ started = threading.Event()
+ release = threading.Event()
+
+ def slow_probe(_binary: str | None) -> CodexAppServerCapability:
+ started.set()
+ release.wait(timeout=2.0)
+ return _ready_capability()
+
+ monkeypatch.setattr(transport, "_read_codex_capability", slow_probe)
+ monkeypatch.setattr(
+ transport,
+ "_delete_codex_subscription_auth_locked",
+ lambda: (True, None),
+ )
+
+ prober = threading.Thread(
+ target=lambda: transport.codex_subscription_auth_snapshot("codex-test")
+ )
+ prober.start()
+ assert started.wait(timeout=1.0)
+
+ results: list[tuple[bool, str | None]] = []
+ logout_worker = threading.Thread(
+ target=lambda: results.append(transport.logout_codex_subscription())
+ )
+ logout_worker.start()
+ logout_worker.join(timeout=0.3)
+ # Still waiting on the probe — the old behavior raised immediately with
+ # "login is in progress", blaming a login that did not exist.
+ assert logout_worker.is_alive() is True
+
+ release.set()
+ prober.join(timeout=2.0)
+ logout_worker.join(timeout=2.0)
+ assert logout_worker.is_alive() is False
+ assert results == [(True, None)]
+
+
+def test_user_actions_report_a_probe_timeout_honestly(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(transport, "_SUBSCRIPTION_PROBE_WAIT_S", 0.05)
+ started = threading.Event()
+ release = threading.Event()
+
+ def slow_probe(_binary: str | None) -> CodexAppServerCapability:
+ started.set()
+ release.wait(timeout=2.0)
+ return _ready_capability()
+
+ monkeypatch.setattr(transport, "_read_codex_capability", slow_probe)
+ prober = threading.Thread(
+ target=lambda: transport.codex_subscription_auth_snapshot("codex-test")
+ )
+ prober.start()
+ assert started.wait(timeout=1.0)
+
+ with pytest.raises(
+ CodexSubscriptionUnavailable, match="status check is still running"
+ ):
+ transport.logout_codex_subscription()
+
+ release.set()
+ prober.join(timeout=2.0)
+
+
+async def test_disconnect_invalidates_snapshot_cache(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ reads: list[str | None] = []
+
+ def probe(binary: str | None) -> CodexAppServerCapability:
+ reads.append(binary)
+ return _ready_capability()
+
+ async def no_servers() -> None:
+ return None
+
+ monkeypatch.setattr(transport, "_read_codex_capability", probe)
+ monkeypatch.setattr(transport, "close_shared_codex_app_servers", no_servers)
+ monkeypatch.setattr(
+ transport,
+ "_delete_codex_subscription_auth_locked",
+ lambda: (True, None),
+ )
+
+ assert transport.codex_subscription_auth_snapshot("codex-test").reason_code == "ready"
+
+ ok, error = await transport.disconnect_and_logout_codex_subscription()
+ assert (ok, error) == (True, None)
+
+ # Disconnect changed the profile; the cached "ready" must not survive it.
+ assert transport.codex_subscription_auth_snapshot("codex-test").reason_code == "ready"
+ assert reads == ["codex-test", "codex-test"]
+
+
+async def test_capability_status_feeds_the_snapshot_cache(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The transport-start probe publishes its result for concurrent callers."""
+ reads: list[str | None] = []
+
+ def probe(binary: str | None) -> CodexAppServerCapability:
+ reads.append(binary)
+ return _ready_capability(binary_path="trusted-codex-test")
+
+ monkeypatch.setattr(transport, "_read_codex_capability", probe)
+ client = CodexAppServerClient("codex-test")
+
+ capability = await client.capability_status()
+ assert capability.reason_code == "ready"
+
+ snapshot = transport.codex_subscription_auth_snapshot("codex-test")
+ assert snapshot.reason_code == "ready"
+ assert reads == ["codex-test"]
+
+
@pytest.mark.asyncio
async 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.py
index 5e6c7e2e21..33008d7e1c 100644
--- a/tests/unit/ui/test_provider_spec_codex_subscription_realtime.py
+++ b/tests/unit/ui/test_provider_spec_codex_subscription_realtime.py
@@ -155,8 +155,6 @@ 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
@@ -167,15 +165,21 @@ 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
-
+ # The route judges this provider by the isolated-profile snapshot, never
+ # the ordinary Codex login. An api-key-mode login yields no dedicated
+ # ChatGPT-authenticated profile, so the snapshot answers not-connected.
+ # Patching the payload keeps this unit test off the real CLI and
+ # independent of the host's login state.
monkeypatch.setattr(
- codex_app_server, "codex_subscription_login_ready", not_ready
+ routes,
+ "_codex_subscription_status_payload",
+ lambda _binary_path: {
+ "installed": True,
+ "connected": False,
+ "mode": "not_connected",
+ "message": "Connect the dedicated ChatGPT subscription voice login.",
+ "reason_code": "login_required",
+ },
)
with pytest.raises(HTTPException) as caught:
@@ -192,6 +196,99 @@ async def test_realtime_activation_rejects_codex_api_key_mode(
assert "Connect or configure this provider first" in str(caught.value.detail)
+async def test_realtime_activation_reports_busy_instead_of_demanding_reconnect(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A transient busy window must not tell the user to redo a working login."""
+ monkeypatch.setattr(routes, "_codex_binary_path", lambda *_args: "codex")
+ monkeypatch.setattr(
+ routes,
+ "_codex_subscription_status_payload",
+ lambda _binary_path: {
+ "installed": False,
+ "connected": False,
+ "mode": "not_connected",
+ "message": "Dedicated subscription voice status is being checked or changed.",
+ "reason_code": "busy",
+ },
+ )
+
+ with pytest.raises(HTTPException) as caught:
+ await routes.realtime_switch(
+ routes.SwitchBody(
+ provider="codex-subscription-realtime",
+ persist=False,
+ accept_experimental=True,
+ ),
+ object(),
+ )
+
+ assert caught.value.status_code == 409
+ detail = str(caught.value.detail)
+ assert "being checked" in detail
+ assert "Connect or configure" not in detail
+
+
+def test_spec_payload_preserves_the_isolated_snapshot_diagnosis(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The precise setup diagnosis must survive into /api/providers."""
+ spec = get_spec("codex-subscription-realtime")
+ assert spec is not None
+ monkeypatch.setattr(routes.cfg_mod, "get_secret", lambda *_args, **_kwargs: None)
+
+ payload = routes._spec_to_payload(
+ spec,
+ active_brain=None,
+ active_tts=None,
+ active_stt=None,
+ active_realtime=None,
+ codex_subscription_ready=False,
+ codex_subscription_status={
+ "installed": True,
+ "connected": False,
+ "mode": "not_connected",
+ "message": "Subscription voice requires Codex CLI codex-cli 0.146.0.",
+ "reason_code": "setup_invalid",
+ },
+ )
+
+ assert payload["codex_status"]["reason_code"] == "setup_invalid"
+ assert (
+ payload["codex_status"]["message"]
+ == "Subscription voice requires Codex CLI codex-cli 0.146.0."
+ )
+
+
+def test_subscription_status_payload_maps_busy_without_claiming_missing_install(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from jarvis import codex_app_server
+
+ snapshot = codex_app_server.CodexAppServerCapability(
+ available=False,
+ chatgpt_authenticated=False,
+ binary_path=None,
+ version=None,
+ reason="Dedicated subscription voice status is being checked or changed.",
+ reason_code="busy",
+ )
+ monkeypatch.setattr(
+ codex_app_server,
+ "codex_subscription_auth_snapshot",
+ lambda _binary_path: snapshot,
+ )
+
+ payload = routes._codex_subscription_status_payload(None)
+
+ assert payload["reason_code"] == "busy"
+ assert payload["connected"] is False
+ assert payload["message"] == (
+ "Dedicated subscription voice status is being checked or changed."
+ )
+
+
@pytest.mark.asyncio
async def test_realtime_activation_requires_experimental_acknowledgement(
monkeypatch: pytest.MonkeyPatch,