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 round-2 review findings — cancellation leaks, wrong-profile judges, busy truthfulness

Ruben Lütkeed893d6731c5
diff --git a/jarvis/codex_app_server.py b/jarvis/codex_app_server.py
index 32b77e0b8d..0cf517e2b9 100644
--- a/jarvis/codex_app_server.py
+++ b/jarvis/codex_app_server.py
@@ -240,6 +240,27 @@ class CodexAppServerRPCError(CodexAppServerError):
super().__init__(f"Codex app-server rejected {method}{suffix}.")
+# SSOT for the subscription-status reason-code vocabulary. Mirrors (five-layer
+# anti-drift guard, BUG-008 class): the payload assert in
+# ``jarvis/ui/web/provider_routes.py``, the TS union in ``useProviders.ts``,
+# the card's ternary in ``ProviderTierSection.tsx``, and one
+# ``apikeys_codex.status_*`` i18n key per member in de/en/es.
+# "busy" is 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.
+CodexSubscriptionReasonCode = Literal[
+ "ready",
+ "login_required",
+ "lifecycle_unavailable",
+ "not_installed",
+ "setup_invalid",
+ "busy",
+]
+CODEX_SUBSCRIPTION_REASON_CODES: Final = frozenset(
+ get_args(CodexSubscriptionReasonCode)
+)
+
+
@dataclass(frozen=True, slots=True)
class CodexAppServerCapability:
"""PII-free snapshot of whether the subscription transport may start."""
@@ -249,17 +270,7 @@ class CodexAppServerCapability:
binary_path: str | None
version: str | None
reason: str
- reason_code: Literal[
- "ready",
- "login_required",
- "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"
+ reason_code: CodexSubscriptionReasonCode = "setup_invalid"
@dataclass(frozen=True, slots=True)
@@ -452,7 +463,7 @@ def _is_trusted_codex_runtime_binary(
target = _TRUSTED_CODEX_TARGETS.get(
(sys.platform, _normalized_machine())
)
- return target is not None and _sha256_file(canonical) == target[3]
+ return target is not None and _sha256_file_cached(canonical) == target[3]
except OSError: # An unreadable binary is reported as an unavailable capability.
return False
@@ -806,6 +817,43 @@ def _sha256_file(path: Path) -> str:
return digest.hexdigest()
+_SHA256_CACHE_MAX_ENTRIES: Final = 16
+_sha256_cache: dict[str, tuple[tuple[int, int, int, int], str]] = {}
+_sha256_cache_lock = threading.Lock()
+
+
+def _sha256_file_cached(path: Path) -> str:
+ """Memoized ``_sha256_file`` keyed on the file's identity signature.
+
+ Hashing the ~100 MB native Codex binary dominates the cost of every status
+ probe, and probes run on each UI refresh. The signature (device, inode,
+ size, mtime_ns) is read fresh on every call, so a replaced or modified
+ executable is re-hashed; ``_sha256_file`` itself still guards the actual
+ read against mid-read swaps whenever it runs.
+ """
+ try:
+ identity = path.stat()
+ except OSError:
+ return _sha256_file(path)
+ key = os.path.normcase(str(path))
+ signature = (
+ identity.st_dev,
+ identity.st_ino,
+ identity.st_size,
+ identity.st_mtime_ns,
+ )
+ with _sha256_cache_lock:
+ entry = _sha256_cache.get(key)
+ if entry is not None and entry[0] == signature:
+ return entry[1]
+ digest = _sha256_file(path)
+ with _sha256_cache_lock:
+ if len(_sha256_cache) >= _SHA256_CACHE_MAX_ENTRIES:
+ _sha256_cache.clear()
+ _sha256_cache[key] = (signature, digest)
+ return digest
+
+
def _codex_package_roots(launcher: Path) -> list[Path]:
"""Return local npm package roots without invoking npm or trusting PATH order."""
search_dirs = [launcher.parent, *list(launcher.parents)[:8]]
@@ -881,7 +929,7 @@ def _trusted_native_codex_binary(resolved_binary: str, version: str | None) -> s
seen.add(key)
if _is_link_or_reparse(canonical) or not canonical.is_file():
continue
- if _sha256_file(canonical) == expected_hash:
+ if _sha256_file_cached(canonical) == expected_hash:
return str(canonical)
except OSError: # Unreadable installation candidates are skipped during discovery.
continue
@@ -1003,6 +1051,18 @@ def _read_codex_capability(binary_path: str | None) -> CodexAppServerCapability:
reason=str(exc),
reason_code="setup_invalid",
)
+ if login_mode == "probe_failed":
+ # The CLI could not be asked (spawn failure or timeout). That is a
+ # transiently unknown state — publishing it as "login required" would
+ # flip a connected card to "not connected" on one slow subprocess.
+ return CodexAppServerCapability(
+ available=False,
+ chatgpt_authenticated=False,
+ binary_path=resolved_binary,
+ version=version,
+ reason="The Codex login status probe failed; retrying shortly.",
+ reason_code="busy",
+ )
chatgpt_login = logged_in and login_mode == "chatgpt"
return CodexAppServerCapability(
available=True,
@@ -1409,16 +1469,22 @@ 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.
- 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
+ binary_path = self._binary_path
+
+ def _probe_and_publish() -> CodexAppServerCapability:
+ # 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. Probe AND publish stay in the worker thread: the
+ # login mutex can be held across filesystem work, and the
+ # event loop must never block on it.
+ capability = _read_codex_capability(binary_path)
+ with _subscription_login_lock:
+ _store_subscription_snapshot_locked(binary_path, capability)
+ return capability
+
+ return await asyncio.to_thread(_probe_and_publish)
except TimeoutError: # The returned status reports this bounded probe failure.
return CodexAppServerCapability(
available=False,
@@ -1466,9 +1532,25 @@ class CodexAppServerClient:
expected=False,
)
- # Off the event loop: reserving may wait out a running status probe.
- await asyncio.to_thread(_reserve_subscription_transport, self)
+ # Off the event loop: reserving may wait out a running status
+ # probe. The flag is set BEFORE the await: asyncio.to_thread does
+ # not stop the worker on cancellation, so a cancel landing on the
+ # await after the thread reserved would otherwise strand the
+ # reservation forever (every later status answers busy, and even
+ # disconnect-and-logout hands the orphaned lock back). With the
+ # flag already set, _close_process releases the orphan —
+ # _release_subscription_transport is a safe no-op when the thread
+ # never got as far as reserving.
self._profile_transport_reserved = True
+ try:
+ await asyncio.to_thread(_reserve_subscription_transport, self)
+ except asyncio.CancelledError:
+ # The worker may still complete the reservation after this
+ # cancel; keep the flag so a later close releases either way.
+ raise
+ except BaseException:
+ self._profile_transport_reserved = False
+ raise
try:
capability = await self.capability_status()
@@ -1516,10 +1598,16 @@ 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()
+
+ def _announce_ready() -> None:
+ # Status callers waiting out the "voice is starting"
+ # window can now read the ready transport state directly.
+ # Off-loop: the login mutex can be held across filesystem
+ # work by a probe thread.
+ with _subscription_login_lock:
+ _subscription_state_changed.notify_all()
+
+ await asyncio.to_thread(_announce_ready)
except BaseException:
await self._close_process(
CodexAppServerDisconnected("Codex app-server initialization failed."),
@@ -2656,8 +2744,11 @@ class CodexAppServerClient:
self._ready = False
self._close_lifeline()
if self._profile_transport_reserved:
- _release_subscription_transport(self)
+ # Flag first, release off-loop: the login mutex can be held
+ # across filesystem work, and the worker thread finishes the
+ # release even if this coroutine is cancelled at the await.
self._profile_transport_reserved = False
+ await asyncio.to_thread(_release_subscription_transport, self)
return
self._process = None
self._ready = False
@@ -2715,8 +2806,9 @@ class CodexAppServerClient:
tree.close()
self._close_lifeline()
if self._profile_transport_reserved:
- _release_subscription_transport(self)
+ # Flag first, release off-loop (see the early-return branch above).
self._profile_transport_reserved = False
+ await asyncio.to_thread(_release_subscription_transport, self)
if not expected:
log.warning("Codex app-server connection reset")
@@ -2751,6 +2843,9 @@ _shared_clients: dict[
tuple[str, asyncio.AbstractEventLoop], CodexAppServerClient
] = {}
_shared_clients_lock = threading.Lock()
+# Invariant: this lock is also acquired from event-loop threads, so nothing
+# slow may ever run under it — no IO, no CLI spawn, no untimed Condition.wait.
+# The cross-process profile lock acquired under it is strictly non-blocking.
_subscription_login_lock = threading.Lock()
_subscription_login_in_flight = False
_subscription_login_process: Any | None = None
@@ -2765,7 +2860,9 @@ _subscription_mutation_process_lock: Any | None = None
# 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
+# Slightly above the login flow's 5s status polling so a poll usually hits
+# the cache instead of paying a fresh CLI probe on every tick.
+_SUBSCRIPTION_SNAPSHOT_CACHE_TTL_S: Final = 8.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
@@ -2778,6 +2875,12 @@ _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 when the cached entry memoizes a RAISED probe (not a real status). A
+# failure memo exists only to keep coalesced waiters off a broken CLI within
+# the fresh TTL; it must never be served as "what was true before" on the
+# stale path, or one transient hiccup would paint the card broken for the
+# whole next busy window.
+_subscription_snapshot_cache_is_failure = False
# 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
@@ -2804,6 +2907,8 @@ def _cached_subscription_snapshot_locked(
return None
if _subscription_snapshot_cache_key != _subscription_cache_key(binary_path):
return None
+ if allow_stale and _subscription_snapshot_cache_is_failure:
+ return None
age = time.monotonic() - _subscription_snapshot_cache_at
limit = (
_SUBSCRIPTION_SNAPSHOT_STALE_MAX_S
@@ -2818,13 +2923,17 @@ def _cached_subscription_snapshot_locked(
def _store_subscription_snapshot_locked(
binary_path: str | None,
snapshot: CodexAppServerCapability,
+ *,
+ is_failure: bool = False,
) -> None:
global _subscription_snapshot_cache, _subscription_snapshot_cache_key
global _subscription_snapshot_cache_at
+ global _subscription_snapshot_cache_is_failure
_subscription_snapshot_cache = snapshot
_subscription_snapshot_cache_key = _subscription_cache_key(binary_path)
_subscription_snapshot_cache_at = time.monotonic()
+ _subscription_snapshot_cache_is_failure = is_failure
# Waiters parked on a busy window get the fresh result immediately.
_subscription_state_changed.notify_all()
@@ -2833,10 +2942,12 @@ def _invalidate_subscription_snapshot_locked() -> None:
"""Drop the cached status after anything that can change the profile."""
global _subscription_snapshot_cache, _subscription_snapshot_cache_key
global _subscription_snapshot_cache_at
+ global _subscription_snapshot_cache_is_failure
_subscription_snapshot_cache = None
_subscription_snapshot_cache_key = ""
_subscription_snapshot_cache_at = 0.0
+ _subscription_snapshot_cache_is_failure = False
def _await_status_probe_completion_locked() -> None:
@@ -2974,12 +3085,16 @@ def get_shared_codex_app_server(
return client
-def _local_subscription_auth_snapshot_locked() -> CodexAppServerCapability | None:
+def _local_subscription_auth_snapshot_locked(
+ binary_path: str | None = None,
+) -> CodexAppServerCapability | None:
"""Return an in-memory status while the dedicated profile is already owned.
The caller holds ``_subscription_login_lock``. Starting another Codex CLI
against the same profile during login, logout, startup, or a live transport
can race its auth and runtime files, so these states must never be probed.
+ ``binary_path`` only fills cosmetic fields (the version chip) from the
+ cache; ownership decisions never depend on it.
"""
if _subscription_login_in_flight:
return CodexAppServerCapability(
@@ -3011,13 +3126,23 @@ def _local_subscription_auth_snapshot_locked() -> CodexAppServerCapability | Non
)
ready_client = next((client for client in active_clients if client.ready), None)
if ready_client is not None:
+ cached = _subscription_snapshot_cache
+ cached_version = (
+ cached.version
+ if cached is not None
+ and _subscription_snapshot_cache_key
+ == _subscription_cache_key(binary_path)
+ else None
+ )
return CodexAppServerCapability(
available=True,
chatgpt_authenticated=True,
binary_path=(
ready_client._trusted_binary_path or ready_client._binary_path
),
- version=None,
+ # Cosmetic: keep the version chip alive during a call instead
+ # of blanking it while the profile cannot be probed.
+ version=cached_version,
reason="Dedicated ChatGPT subscription voice is active.",
reason_code="ready",
)
@@ -3048,7 +3173,7 @@ def codex_subscription_auth_snapshot(
deadline = time.monotonic() + _SUBSCRIPTION_SNAPSHOT_WAIT_TIMEOUT_S
with _subscription_state_changed:
while True:
- local_snapshot = _local_subscription_auth_snapshot_locked()
+ local_snapshot = _local_subscription_auth_snapshot_locked(binary_path)
if local_snapshot is not None:
if local_snapshot.reason_code != "busy":
return local_snapshot
@@ -3101,7 +3226,10 @@ def codex_subscription_auth_snapshot(
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.
+ # its caller sees the real error. A RAISED probe is "transiently
+ # unknown" (busy), never a proven-broken setup: presenting one
+ # antivirus-slowed hash or tempdir hiccup as "reconnect your account"
+ # is the exact lie this pipeline exists to prevent.
with _subscription_login_lock:
_store_subscription_snapshot_locked(
binary_path,
@@ -3111,10 +3239,10 @@ def codex_subscription_auth_snapshot(
binary_path=None,
version=None,
reason=(
- "Codex status probe failed "
- f"({type(exc).__name__})."
+ "The Codex status probe failed "
+ f"({type(exc).__name__}); retrying shortly."
),
- reason_code="setup_invalid",
+ reason_code="busy",
),
)
raise
@@ -3271,10 +3399,21 @@ def start_codex_subscription_login(
_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()
+ # the profile would wedge as "login in progress". The guarded process
+ # has no kill(); its guardian owns the OS profile lock, so ask it to
+ # reap and release (the documented guardian path), then restore a
+ # clean not-logged-in state.
+ release_guard = getattr(process, "release_profile_lock", None)
+ if callable(release_guard):
+ try:
+ release_guard()
+ except (OSError, RuntimeError) as exc:
+ log.warning(
+ "Login guard release failed after reaper launch failure (%s)",
+ type(exc).__name__,
+ )
+ if log_dir is not None:
+ shutil.rmtree(log_dir, ignore_errors=True)
with _subscription_login_lock:
if _subscription_login_process is process:
_subscription_login_process = None
@@ -3312,7 +3451,13 @@ def _delete_codex_subscription_auth_locked() -> tuple[bool, str | None]:
def logout_codex_subscription(
binary_path: str | None = None,
) -> tuple[bool, str | None]:
- """Delete only the dedicated file-backed login; missing is success."""
+ """Delete only the dedicated file-backed login; missing is success.
+
+ Synchronous and potentially slow (it can wait out a status probe and does
+ filesystem work under the profile lock) — call it from a worker thread,
+ never on the event loop. The HTTP route uses the async
+ ``disconnect_and_logout_codex_subscription`` wrapper instead.
+ """
global _subscription_mutation_process_lock, _subscription_profile_mutating
del binary_path # Kept for the stable route/helper signature.
@@ -3369,38 +3514,62 @@ def _begin_subscription_disconnect_mutation() -> None:
_invalidate_subscription_snapshot_locked()
+def _finish_subscription_disconnect_mutation() -> None:
+ """Release the disconnect claim; runs off-loop (the mutex may be busy)."""
+ global _subscription_mutation_process_lock, _subscription_profile_mutating
+ global _subscription_transport_process_lock
+
+ with _subscription_login_lock:
+ if _subscription_active_transports:
+ if _subscription_transport_process_lock is not None:
+ log.error(
+ "Subscription voice has two process-lock owners during logout"
+ )
+ _release_subscription_mutation_process_lock_locked()
+ else:
+ _subscription_transport_process_lock = (
+ _subscription_mutation_process_lock
+ )
+ _subscription_mutation_process_lock = None
+ else:
+ _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(
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)
+ # ``claimed`` binds cleanup to OUR claim only: _begin... raising because a
+ # FOREIGN owner is mutating must not clear that owner's state, so the flag
+ # flips inside the worker AFTER the claim succeeded. Cancellation cannot
+ # strand the claim: a worker thread keeps running through a cancel, and
+ # the finally waits for it to settle before deciding, then shields the
+ # release so a second cancellation cannot interrupt it.
+ claimed = False
+
+ def _claim() -> None:
+ nonlocal claimed
+ _begin_subscription_disconnect_mutation()
+ claimed = True
+
+ claim_future = asyncio.get_running_loop().run_in_executor(None, _claim)
try:
+ await asyncio.shield(claim_future)
await close_shared_codex_app_servers()
return await asyncio.to_thread(_delete_codex_subscription_auth_locked)
finally:
- with _subscription_login_lock:
- if _subscription_active_transports:
- if _subscription_transport_process_lock is not None:
- log.error(
- "Subscription voice has two process-lock owners during logout"
- )
- _release_subscription_mutation_process_lock_locked()
- else:
- _subscription_transport_process_lock = (
- _subscription_mutation_process_lock
- )
- _subscription_mutation_process_lock = None
- else:
- _release_subscription_mutation_process_lock_locked()
- _subscription_profile_mutating = False
- _invalidate_subscription_snapshot_locked()
- _subscription_state_changed.notify_all()
+ if not claim_future.done():
+ with suppress(BaseException):
+ await asyncio.shield(claim_future)
+ if claimed:
+ await asyncio.shield(
+ asyncio.to_thread(_finish_subscription_disconnect_mutation)
+ )
async def codex_subscription_login_ready(binary_path: str | None = None) -> bool:
diff --git a/jarvis/codex_auth.py b/jarvis/codex_auth.py
index 603ccf405c..f78c15cf7e 100644
--- a/jarvis/codex_auth.py
+++ b/jarvis/codex_auth.py
@@ -912,7 +912,13 @@ class CodexAuthService:
raise
def login_status(self) -> tuple[bool, str]:
- """Return the CLI's PII-free login mode for this exact profile."""
+ """Return the CLI's PII-free login mode for this exact profile.
+
+ Mode ``probe_failed`` means the CLI could not be asked (spawn failure
+ or timeout) — a transiently unknown state, distinct from a CLI that
+ answered "not logged in". Callers that cache or publish this result
+ must not present ``probe_failed`` as a missing login.
+ """
binary = self._resolve_binary()
if binary is None:
return False, "unknown"
@@ -926,8 +932,8 @@ class CodexAuthService:
env=self._subprocess_environment(),
)
except (FileNotFoundError, subprocess.TimeoutExpired, OSError):
- # The status probe is unavailable and therefore fails closed.
- return False, "unknown"
+ # The probe itself failed; the login state is unknown, not absent.
+ return False, "probe_failed"
output = (proc.stdout or proc.stderr or "").strip()
if proc.returncode == 0 and output == "Logged in using ChatGPT":
return True, "chatgpt"
diff --git a/jarvis/plugins/realtime/codex_subscription.py b/jarvis/plugins/realtime/codex_subscription.py
index 23818cea21..972954a42e 100644
--- a/jarvis/plugins/realtime/codex_subscription.py
+++ b/jarvis/plugins/realtime/codex_subscription.py
@@ -758,6 +758,13 @@ class CodexSubscriptionRealtimeProvider:
status = app_server_module.codex_subscription_auth_snapshot(
binary_path or None
)
+ if getattr(status, "reason_code", "") == "busy":
+ # Transiently unknown, not "no login": failing closed here
+ # flips voice-mode availability (and its 400) on a healthy
+ # install. Fail open — opening a session runs the
+ # authoritative live account verification anyway, and a
+ # genuinely missing login still stops the call honestly.
+ return True
return bool(
getattr(status, "available", False)
and getattr(status, "chatgpt_authenticated", False)
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 bf09a2dd54..066b0aac4a 100644
--- a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx
@@ -478,6 +478,14 @@ describe("ProviderCard: ChatGPT subscription Realtime", () => {
name: "Connect with ChatGPT",
}) as HTMLButtonElement;
expect(connect.disabled).toBe(false);
+
+ // Clicking the card during busy must not demand a redo of a working
+ // login — it answers with the same neutral "checking" note.
+ fireEvent.click(screen.getByText("ChatGPT subscription (Codex)"));
+ expect(toastsOf("warning")).toEqual([]);
+ expect(toastsOf("info")).toEqual([
+ "Checking the ChatGPT voice status — one moment.",
+ ]);
});
it("surfaces the precise backend diagnosis on a real setup defect", () => {
diff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx
index cbed385359..942ef1a830 100644
--- a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx
+++ b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx
@@ -765,6 +765,13 @@ export function ProviderCard({
return;
}
if (!assumeConfigured && !descriptor.configured) {
+ // A transient busy probe means "state unknown for a moment" — telling
+ // the user to redo a working ChatGPT login here would contradict the
+ // card's own "checking" line (and the backend's 409 for this case).
+ if (descriptor.codex_status?.reason_code === "busy") {
+ pushToast("info", t("apikeys_codex.status_busy"));
+ return;
+ }
pushToast(
"warning",
descriptor.auth_mode === "codex"
@@ -1109,12 +1116,17 @@ export function ProviderCard({
dedicated compact control (two dropdowns), gated on the card
already having a stored credential like the other tiers' pickers
above. */}
- {descriptor.tier === "realtime" && descriptor.configured && (
- <RealtimeOptionsControl
- providerId={descriptor.id}
- healthActive={descriptor.active}
- />
- )}
+ {descriptor.tier === "realtime" &&
+ (descriptor.configured ||
+ // Keep the model/voice pickers mounted through a transient busy
+ // probe so the card does not visibly flicker while saying
+ // "one moment".
+ descriptor.codex_status?.reason_code === "busy") && (
+ <RealtimeOptionsControl
+ providerId={descriptor.id}
+ healthActive={descriptor.active}
+ />
+ )}
{/* Footer: the live connectivity test, visually separated from the
configuration body so "set up" and "verify" read as two steps. */}
@@ -1589,6 +1601,21 @@ export function AuthWidget({
);
}
+// Exhaustive by construction: adding a value to CodexStatus["reason_code"]
+// without a card mapping fails the TypeScript build here instead of silently
+// falling through to a wrong status line (the BUG-008 multi-layer enum class).
+const CODEX_STATUS_KEY_BY_REASON: Record<
+ NonNullable<NonNullable<ProviderDescriptor["codex_status"]>["reason_code"]>,
+ string
+> = {
+ ready: "apikeys_codex.status_ready",
+ login_required: "apikeys_codex.status_login_required",
+ lifecycle_unavailable: "apikeys_codex.status_lifecycle_unavailable",
+ not_installed: "apikeys_codex.status_not_installed",
+ setup_invalid: "apikeys_codex.status_setup_invalid",
+ busy: "apikeys_codex.status_busy",
+};
+
function CodexAuthWidget({
descriptor,
onChanged,
@@ -1608,17 +1635,11 @@ function CodexAuthWidget({
);
const subscriptionStatusKey = !status
? "apikeys_codex.status_loading"
- : status.reason_code === "ready"
- ? "apikeys_codex.status_ready"
- : status.reason_code === "lifecycle_unavailable"
- ? "apikeys_codex.status_lifecycle_unavailable"
- : status.reason_code === "setup_invalid"
- ? "apikeys_codex.status_setup_invalid"
- : 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";
+ : status.reason_code && status.reason_code !== "login_required"
+ ? CODEX_STATUS_KEY_BY_REASON[status.reason_code]
+ : !status.installed
+ ? "apikeys_codex.status_not_installed"
+ : "apikeys_codex.status_login_required";
useEffect(() => {
if (!loginPolling || loginReady) return;
diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.py
index b09a022c4f..04b8ac2306 100644
--- a/jarvis/ui/web/provider_routes.py
+++ b/jarvis/ui/web/provider_routes.py
@@ -22,6 +22,7 @@ import inspect
import logging
import time
from collections.abc import Mapping
+from types import SimpleNamespace
from typing import Any, Literal, get_args
from fastapi import APIRouter, HTTPException, Request, Response
@@ -599,9 +600,12 @@ def _spec_to_payload(
),
"active": active,
"cli_installed": (
- bool(codex_status["installed"])
- if codex_status is not None
- else _cli_installed(spec)
+ # During a transient busy window the isolated snapshot cannot say
+ # whether the CLI exists; answer from the PATH probe instead of
+ # rendering a false "not installed" install prompt.
+ _cli_installed(spec)
+ if codex_status is None or codex_status.get("reason_code") == "busy"
+ else bool(codex_status["installed"])
),
# Overlay, not a new tier (see the CU-own-provider plan): a brain
# provider can be BOTH the main Brain ("active") AND/OR the dedicated
@@ -882,9 +886,29 @@ def _codex_subscription_status_payload(binary_path: str | None) -> dict[str, Any
The live account and plan are verified when the user explicitly activates
the experimental provider or starts a call.
"""
- from jarvis.codex_app_server import codex_subscription_auth_snapshot
+ from jarvis.codex_app_server import (
+ CodexAppServerCapability,
+ codex_subscription_auth_snapshot,
+ )
- snapshot = codex_subscription_auth_snapshot(binary_path)
+ try:
+ snapshot = codex_subscription_auth_snapshot(binary_path)
+ except Exception as exc: # noqa: BLE001 — a raising probe must not 500 the screen
+ # The probe owner re-raises real errors by design; the routes built on
+ # this payload (the whole API-Keys screen among them) must degrade to
+ # a transient status instead of an empty screen (BUG-008 class).
+ log.warning("Codex subscription status probe failed: %s", type(exc).__name__)
+ snapshot = CodexAppServerCapability(
+ available=False,
+ chatgpt_authenticated=False,
+ binary_path=None,
+ version=None,
+ reason=(
+ f"The Codex status probe failed ({type(exc).__name__}); "
+ "retrying shortly."
+ ),
+ reason_code="busy",
+ )
installed = bool(snapshot.available or snapshot.version)
connected = bool(snapshot.available and snapshot.chatgpt_authenticated)
if connected:
@@ -1058,6 +1082,23 @@ async def _run_tier_test(
from jarvis.dictation.polish_probe import probe_polish_family
return await probe_polish_family(family, cfg, model=model or "")
+ if spec.id == "codex-subscription-realtime":
+ # This card is judged by the ISOLATED voice profile, never the
+ # ordinary Codex login: the default codex_status seam would answer
+ # "ok — Connected." for a user whose normal `codex login` works but
+ # whose voice profile was never connected (and "not connected" for
+ # the normal case of a voice-only login).
+ payload = await asyncio.to_thread(
+ _codex_subscription_status_payload,
+ getattr(getattr(cfg, "codex", None), "binary_path", "") or None,
+ )
+ isolated_status = SimpleNamespace(
+ connected=bool(payload.get("connected")),
+ message=str(payload.get("message") or ""),
+ )
+ return await _provider_test.run_provider_test(
+ spec, cfg, codex_status=lambda: isolated_status, model=model
+ )
return await _provider_test.run_provider_test(spec, cfg, model=model)
@@ -3715,7 +3756,18 @@ async def realtime_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
if callable(verify_activation):
result = verify_activation(_resolve_cfg(request))
if inspect.isawaitable(result):
- await result
+ # A cold activation gate can start app-server, whose RPCs each
+ # carry ~20s timeouts. Bound the whole HTTP response instead
+ # of letting a wedged gate hold the request open indefinitely.
+ await asyncio.wait_for(result, timeout=45.0)
+ except TimeoutError as exc:
+ raise HTTPException(
+ status_code=409,
+ detail=(
+ "The provider's activation check timed out. Try again in a "
+ "moment."
+ ),
+ ) from exc
except Exception as exc: # noqa: BLE001 - provider gate returns a safe 409
raise HTTPException(status_code=409, detail=str(exc)) from exc
diff --git a/jarvis/ui/web/setup_report_routes.py b/jarvis/ui/web/setup_report_routes.py
index 12468259c8..73a38fc5c7 100644
--- a/jarvis/ui/web/setup_report_routes.py
+++ b/jarvis/ui/web/setup_report_routes.py
@@ -120,9 +120,22 @@ def _credential_presence(request: Request) -> dict[str, bool]:
out: dict[str, bool] = {}
for spec in _providers.PROVIDERS:
try:
- present = bool(
- _providers._is_credential_present(spec, binary_path if spec.id == "codex" else None)
- )
+ if spec.id == "codex-subscription-realtime":
+ # This card is judged by the ISOLATED voice profile; the
+ # generic probe would read the ORDINARY Codex login and make
+ # the device-parity report lie in both directions. A busy
+ # snapshot reads as absent (fail-closed) — the report is a
+ # point-in-time diagnostic, not a gate.
+ payload = _providers._codex_subscription_status_payload(
+ binary_path
+ )
+ present = bool(payload.get("connected"))
+ else:
+ present = bool(
+ _providers._is_credential_present(
+ spec, binary_path if spec.id == "codex" else None
+ )
+ )
except Exception as exc: # noqa: BLE001 — an unreadable slot reads as absent
log.debug("setup-report: credential probe for %s failed: %s", spec.id, exc)
present = False
diff --git a/tests/unit/codex_app_server/test_transport.py b/tests/unit/codex_app_server/test_transport.py
index 1a8a2ab6f5..bf1919ad89 100644
--- a/tests/unit/codex_app_server/test_transport.py
+++ b/tests/unit/codex_app_server/test_transport.py
@@ -76,6 +76,7 @@ def isolated_profile_lifecycle(monkeypatch: pytest.MonkeyPatch) -> 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)
+ monkeypatch.setattr(transport, "_sha256_cache", {})
class FakeStdin:
@@ -1323,7 +1324,8 @@ def test_auth_snapshot_probe_failure_is_cached_for_waiters(
transport.codex_subscription_auth_snapshot("codex-test")
second = transport.codex_subscription_auth_snapshot("codex-test")
- assert second.reason_code == "setup_invalid"
+ # A RAISED probe is transiently unknown — never a proven-broken setup.
+ assert second.reason_code == "busy"
assert "OSError" in second.reason
assert reads == ["codex-test"]
@@ -1337,7 +1339,7 @@ def test_logout_waits_for_a_running_status_probe(
def slow_probe(_binary: str | None) -> CodexAppServerCapability:
started.set()
- release.wait(timeout=2.0)
+ assert release.wait(timeout=2.0)
return _ready_capability()
monkeypatch.setattr(transport, "_read_codex_capability", slow_probe)
@@ -1379,7 +1381,7 @@ def test_user_actions_report_a_probe_timeout_honestly(
def slow_probe(_binary: str | None) -> CodexAppServerCapability:
started.set()
- release.wait(timeout=2.0)
+ assert release.wait(timeout=2.0)
return _ready_capability()
monkeypatch.setattr(transport, "_read_codex_capability", slow_probe)
@@ -1451,6 +1453,129 @@ async def test_capability_status_feeds_the_snapshot_cache(
assert reads == ["codex-test"]
+def test_capability_maps_probe_failed_login_status_to_busy(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ """A CLI spawn failure or timeout is unknown state, never 'not logged in'."""
+ import jarvis.codex_auth as auth_module
+
+ class FakeAuthService:
+ def __init__(self, *_args: object, **_kwargs: object) -> None:
+ pass
+
+ def _resolve_binary(self) -> str:
+ return "codex-test"
+
+ def _probe_version(self, _binary: str) -> str:
+ return "codex-cli 0.146.0"
+
+ def login_status(self) -> tuple[bool, str]:
+ return False, "probe_failed"
+
+ monkeypatch.setattr(auth_module, "CodexAuthService", FakeAuthService)
+ monkeypatch.setattr(
+ transport,
+ "_trusted_native_codex_binary",
+ lambda binary, _version: binary,
+ )
+ monkeypatch.setattr(
+ transport,
+ "_validated_subscription_home",
+ lambda **_kwargs: tmp_path,
+ )
+
+ capability = transport._read_codex_capability(None)
+
+ assert capability.reason_code == "busy"
+ assert capability.available is False
+ assert capability.chatgpt_authenticated is False
+ assert "probe failed" in capability.reason
+
+
+async def test_disconnect_leaves_a_foreign_mutation_untouched(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A disconnect refused because ANOTHER owner mutates must not clear it."""
+
+ async def no_servers() -> None:
+ return None
+
+ monkeypatch.setattr(transport, "close_shared_codex_app_servers", no_servers)
+ monkeypatch.setattr(transport, "_subscription_profile_mutating", True)
+
+ with pytest.raises(CodexSubscriptionUnavailable):
+ await transport.disconnect_and_logout_codex_subscription()
+
+ # The foreign owner's claim survives the refused disconnect.
+ assert transport._subscription_profile_mutating is True
+
+
+def test_reaper_launch_failure_releases_guard_and_state(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ import jarvis.codex_auth as auth_module
+ import jarvis.core.private_directory as private_directory
+
+ released: list[str] = []
+
+ class FakeLoginProcess:
+ pid = 4711
+
+ def release_profile_lock(self) -> None:
+ released.append("released")
+
+ class FakeAuthService:
+ def __init__(self, *_args: object, **_kwargs: object) -> None:
+ pass
+
+ def start_login(self) -> FakeLoginProcess:
+ return FakeLoginProcess()
+
+ monkeypatch.setattr(auth_module, "CodexAuthService", FakeAuthService)
+ monkeypatch.setattr(
+ transport, "_prepare_subscription_login_home", lambda: tmp_path
+ )
+ monkeypatch.setattr(
+ transport,
+ "_read_codex_capability",
+ lambda _binary: _ready_capability(binary_path="codex-test"),
+ )
+ monkeypatch.setattr(
+ transport,
+ "_subscription_process_lock_path",
+ lambda: tmp_path / "lock" / "owner.lock",
+ )
+ monkeypatch.setattr(
+ private_directory,
+ "ensure_owner_only_directory",
+ lambda path, create=False: path,
+ )
+
+ def broken_reaper(_target: object) -> None:
+ raise RuntimeError("no threads left")
+
+ monkeypatch.setattr(
+ transport, "_launch_subscription_login_reaper", broken_reaper
+ )
+
+ with pytest.raises(RuntimeError, match="no threads left"):
+ transport.start_codex_subscription_login("codex-test")
+
+ # The guardian released the OS profile lock and the in-process state is
+ # clean again — no permanent "login in progress" wedge.
+ assert released == ["released"]
+ assert transport._subscription_login_in_flight is False
+ assert transport._subscription_profile_mutating is False
+ assert transport._subscription_login_process is None
+ assert (
+ transport.codex_subscription_auth_snapshot("codex-test").reason_code
+ == "ready"
+ )
+
+
@pytest.mark.asyncio
async def test_capability_worker_keeps_profile_reserved_until_it_finishes(
monkeypatch: pytest.MonkeyPatch,
@@ -1999,7 +2124,9 @@ def test_native_codex_version_and_hash_are_both_required(
)
},
)
- monkeypatch.setattr(transport, "_sha256_file", lambda _path: "approved-hash")
+ monkeypatch.setattr(
+ transport, "_sha256_file_cached", lambda _path: "approved-hash"
+ )
assert (
transport._trusted_native_codex_binary(
@@ -2010,13 +2137,30 @@ def test_native_codex_version_and_hash_are_both_required(
with pytest.raises(CodexSubscriptionUnavailable, match="requires Codex"):
transport._trusted_native_codex_binary(str(binary), "codex-cli 0.147.0")
- monkeypatch.setattr(transport, "_sha256_file", lambda _path: "wrong-hash")
+ monkeypatch.setattr(
+ transport, "_sha256_file_cached", lambda _path: "wrong-hash"
+ )
with pytest.raises(CodexSubscriptionUnavailable, match="approved build"):
transport._trusted_native_codex_binary(
str(binary), transport._SUPPORTED_CODEX_VERSION
)
+def test_sha256_memo_rehashes_when_the_file_identity_changes(
+ tmp_path: Path,
+) -> None:
+ binary = tmp_path / "codex.exe"
+ binary.write_bytes(b"first-content")
+
+ first = transport._sha256_file_cached(binary)
+ assert transport._sha256_file_cached(binary) == first
+
+ binary.write_bytes(b"second-content-of-a-different-size")
+ second = transport._sha256_file_cached(binary)
+ assert second != first
+ assert second == transport._sha256_file(binary)
+
+
def test_sha256_file_ignores_windows_fstat_ctime_semantics(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
diff --git a/tests/unit/realtime/test_codex_subscription.py b/tests/unit/realtime/test_codex_subscription.py
index 7bf133a42e..c4bc1562cc 100644
--- a/tests/unit/realtime/test_codex_subscription.py
+++ b/tests/unit/realtime/test_codex_subscription.py
@@ -318,6 +318,41 @@ async def test_orchestrator_capability_check_does_not_repeat_cli_auth_probe(
assert await provider.can_open_duplex_session() is True
+ ("reason_code", "available", "authenticated", "expected"),
+ [
+ ("ready", True, True, True),
+ ("login_required", False, False, False),
+ # Transiently unknown must fail OPEN: voice-mode availability flips
+ # (with a user-facing 400) on a fail-closed answer, while opening a
+ # session performs the authoritative live account verification anyway.
+ ("busy", False, False, True),
+ ],
+)
+def test_external_login_ready_fails_open_on_transient_busy(
+ monkeypatch: pytest.MonkeyPatch,
+ reason_code: str,
+ available: bool,
+ authenticated: bool,
+ expected: bool,
+) -> None:
+ from jarvis import codex_app_server
+
+ monkeypatch.setattr(
+ codex_app_server,
+ "codex_subscription_auth_snapshot",
+ lambda _binary: SimpleNamespace(
+ available=available,
+ chatgpt_authenticated=authenticated,
+ reason_code=reason_code,
+ ),
+ )
+
+ assert (
+ CodexSubscriptionRealtimeProvider.external_login_ready(None) is expected
+ )
+
+
@pytest.mark.asyncio
async def test_send_audio_uses_sideband_pcm_without_api_usage_accounting() -> None:
client = _Client()
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 33008d7e1c..5dfc866daf 100644
--- a/tests/unit/ui/test_provider_spec_codex_subscription_realtime.py
+++ b/tests/unit/ui/test_provider_spec_codex_subscription_realtime.py
@@ -132,6 +132,17 @@ async def test_section_health_accepts_keyring_only_chatgpt_login(
monkeypatch.setattr(codex_app_server, "codex_subscription_login_ready", ready)
monkeypatch.setattr(routes, "_run_tier_test", healthy_probe)
+ monkeypatch.setattr(
+ routes,
+ "_codex_subscription_status_payload",
+ lambda _binary_path: {
+ "installed": True,
+ "connected": True,
+ "mode": "chatgpt",
+ "message": "Dedicated ChatGPT subscription voice login is ready.",
+ "reason_code": "ready",
+ },
+ )
monkeypatch.setattr(
routes,
"_is_credential_present",
@@ -289,6 +300,141 @@ def test_subscription_status_payload_maps_busy_without_claiming_missing_install(
)
+def test_spec_payload_busy_does_not_claim_missing_cli(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """During busy the card must not render the install prompt via cli_installed."""
+ spec = get_spec("codex-subscription-realtime")
+ assert spec is not None
+ monkeypatch.setattr(routes.cfg_mod, "get_secret", lambda *_args, **_kwargs: None)
+ monkeypatch.setattr(routes, "_cli_installed", lambda _spec: True)
+
+ 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": False,
+ "connected": False,
+ "mode": "not_connected",
+ "message": "Dedicated subscription voice status is being checked or changed.",
+ "reason_code": "busy",
+ },
+ )
+
+ assert payload["codex_status"]["reason_code"] == "busy"
+ assert payload["cli_installed"] is True
+
+
+def test_status_payload_survives_a_raising_probe(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A raising probe must degrade to busy, not 500 the whole providers screen."""
+ from jarvis import codex_app_server
+
+ def explode(_binary_path: str | None) -> None:
+ raise OSError("cli exploded")
+
+ monkeypatch.setattr(
+ codex_app_server, "codex_subscription_auth_snapshot", explode
+ )
+
+ payload = routes._codex_subscription_status_payload(None)
+
+ assert payload["reason_code"] == "busy"
+ assert payload["connected"] is False
+ assert "OSError" in payload["message"]
+
+
+async def test_section_health_reports_busy_as_unknown(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A transient busy window is not an amber "needs setup" dot."""
+ spec = get_spec("codex-subscription-realtime")
+ assert spec is not None
+ 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",
+ },
+ )
+
+ health = await routes._tier_section_health(
+ SimpleNamespace(),
+ spec,
+ binary_path="codex-custom",
+ )
+
+ assert health.status == "unknown"
+ assert health.reason == "busy"
+
+
+async def test_tier_test_judges_the_isolated_voice_profile(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The Test button must never answer from the ordinary Codex login."""
+ spec = get_spec("codex-subscription-realtime")
+ assert spec is not None
+ monkeypatch.setattr(
+ routes,
+ "_codex_subscription_status_payload",
+ lambda _binary_path: {
+ "installed": True,
+ "connected": True,
+ "mode": "chatgpt",
+ "message": "Dedicated ChatGPT subscription voice login is ready.",
+ "reason_code": "ready",
+ },
+ )
+
+ captured: dict[str, object] = {}
+
+ async def capture_run(spec_arg, cfg_arg, **kwargs):
+ captured.update(kwargs)
+ status_fn = kwargs.get("codex_status")
+ assert callable(status_fn)
+ return SimpleNamespace(status="ok", detail=status_fn().message)
+
+ monkeypatch.setattr(
+ routes._provider_test, "run_provider_test", capture_run
+ )
+
+ result = await routes._run_tier_test(spec, SimpleNamespace())
+
+ assert result.status == "ok"
+ assert "subscription voice login is ready" in result.detail
+ assert "codex_status" in captured
+
+
+def test_reason_code_vocabulary_is_pinned() -> None:
+ """The five-layer enum contract: this list mirrors the TS union in
+ useProviders.ts and the card mapping in ProviderTierSection.tsx — grow
+ them together or the UI silently misrenders a new backend state."""
+ from typing import get_args, get_type_hints
+
+ from jarvis.codex_app_server import CodexAppServerCapability
+
+ hints = get_type_hints(CodexAppServerCapability)
+ assert set(get_args(hints["reason_code"])) == {
+ "ready",
+ "login_required",
+ "lifecycle_unavailable",
+ "not_installed",
+ "setup_invalid",
+ "busy",
+ }
+
+
@pytest.mark.asyncio
async def test_realtime_activation_requires_experimental_acknowledgement(
monkeypatch: pytest.MonkeyPatch,