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): close round-3 review findings — cancellation wedges, login-window truth, wrong-version guidance
Ruben Lütke1dd6b488a727
diff --git a/docs/codex-subscription-realtime-voice.md b/docs/codex-subscription-realtime-voice.mdindex f590d48d1e..a9dc8139bb 100644--- a/docs/codex-subscription-realtime-voice.md+++ b/docs/codex-subscription-realtime-voice.md@@ -86,8 +86,9 @@ The subscription transport never relabels those calls as ChatGPT-plan usage.The dedicated login lives under Jarvis's data directory in`codex-subscription-voice`. It is not the user's normal Codex profile. Jarvisallows only its marker plus the exact files the pinned Codex binary owns:-`auth.json`, a persistent UUID in `installation_id`, and the bounded-`tmp/arg0` process-launch tree. Codex sends that UUID as a pseudonymous+`auth.json`, a persistent UUID in `installation_id`, the CLI's tiny one-time+`.sandbox_migration` marker (size-bounded), and the bounded `tmp/arg0`+process-launch tree. Codex sends that UUID as a pseudonymousinstallation identifier. Jarvis never copies or links credentials into asecond runtime profile. Unexpected config, session, agent, or model files makestartup fail closed, and unsafe linked, reparse-point, or multiply-linkeddiff --git a/jarvis/codex_app_server.py b/jarvis/codex_app_server.pyindex 1c9598634a..688677d29b 100644--- a/jarvis/codex_app_server.py+++ b/jarvis/codex_app_server.py@@ -223,6 +223,15 @@ class CodexSubscriptionProfileMissing(CodexSubscriptionUnavailable):"""The dedicated subscription-voice profile does not exist yet."""+class CodexSubscriptionBinaryUnsupported(CodexSubscriptionUnavailable):+ """No installed Codex matches the pinned, hash-approved release.++ Maps to ``reason_code="not_installed"``: the actionable truth for a+ wrong-version or unknown build is "install the supported release", with+ the pinned install command — not "your profile needs attention".+ """++class CodexAppServerDisconnected(CodexAppServerError):"""The app-server process exited or its JSONL stream broke."""@@ -735,6 +744,19 @@ def _validated_subscription_home(_SUBSCRIPTION_PROFILE_MARKER,}:_validate_regular_private_file(entry)+ if entry.name == ".sandbox_migration":+ # A tiny one-time CLI marker; anything larger is not that file.+ try:+ oversized = entry.stat().st_size > 4096+ except OSError as exc:+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice profile could not be inspected."+ ) from exc+ if oversized:+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice profile contains an unexpected "+ "runtime file."+ )_validate_codex_runtime_state(canonical_home,@@ -827,7 +849,8 @@ def _sha256_file(path: Path) -> str:_SHA256_CACHE_MAX_ENTRIES: Final = 16-_sha256_cache: dict[str, tuple[tuple[int, int, int, int], str]] = {}+_SHA256_CACHE_TTL_S: Final = 60.0+_sha256_cache: dict[str, tuple[tuple[int, int, int, int, int], float, str]] = {}_sha256_cache_lock = threading.Lock()@@ -836,9 +859,11 @@ def _sha256_file_cached(path: Path) -> str:Hashing the ~100 MB native Codex binary dominates the cost of every statusprobe, 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.+ size, mtime_ns, ctime_ns) is read fresh on every call and the entry+ expires after a short TTL, bounding how long an in-place swap that forges+ the timestamps could ride a stale digest. This memo serves STATUS reads+ only — the copy that gets executed is re-hashed without the memo right+ before spawn (see ``ensure_started``)."""try:identity = path.stat()@@ -850,19 +875,41 @@ def _sha256_file_cached(path: Path) -> str:identity.st_ino,identity.st_size,identity.st_mtime_ns,+ # POSIX ctime changes on every write regardless of utimes-forgery; on+ # Windows this is creation time and merely harmless extra identity.+ identity.st_ctime_ns,)+ now = time.monotonic()with _sha256_cache_lock:entry = _sha256_cache.get(key)- if entry is not None and entry[0] == signature:- return entry[1]+ if (+ entry is not None+ and entry[0] == signature+ and now - entry[1] <= _SHA256_CACHE_TTL_S+ ):+ return entry[2]digest = _sha256_file(path)with _sha256_cache_lock:if len(_sha256_cache) >= _SHA256_CACHE_MAX_ENTRIES:_sha256_cache.clear()- _sha256_cache[key] = (signature, digest)+ _sha256_cache[key] = (signature, now, digest)return digest+def _verify_spawn_binary(binary_path: str) -> None:+ """Full, un-memoized hash check of the exact file about to be executed.++ The memoized hash is fine for status polling; the copy that runs with the+ user's ChatGPT identity gets one fresh verification right before spawn so+ a stale memo can never launder an in-place swap into execution.+ """+ target = _TRUSTED_CODEX_TARGETS.get((sys.platform, _normalized_machine()))+ if target is None or _sha256_file(Path(binary_path)) != target[3]:+ raise CodexSubscriptionUnavailable(+ "The Codex executable changed since it was verified."+ )++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]]@@ -901,7 +948,9 @@ def _trusted_native_codex_binary(resolved_binary: str, version: str | None) -> s"""target = _TRUSTED_CODEX_TARGETS.get((sys.platform, _normalized_machine()))if target is None:- raise CodexSubscriptionUnavailable(+ # A platform gate, not a setup defect: maps to lifecycle_unavailable,+ # whose card text says the feature is not available on this OS yet.+ raise CodexSubscriptionContainmentUnavailable("This operating-system architecture is not approved for the experimental ""Codex subscription voice transport.")@@ -951,23 +1000,30 @@ def _trusted_native_codex_binary(resolved_binary: str, version: str | None) -> s):# The launcher answered with a real but different release — name the# required one instead of a generic hash complaint.- raise CodexSubscriptionUnavailable(- f"Subscription voice requires Codex CLI {_SUPPORTED_CODEX_VERSION}."+ raise CodexSubscriptionBinaryUnsupported(+ "Subscription voice requires Codex CLI "+ f"{_SUPPORTED_CODEX_VERSION.removeprefix('codex-cli ')}.")- raise CodexSubscriptionUnavailable(+ raise CodexSubscriptionBinaryUnsupported("The installed Codex 0.146 executable does not match an official approved build.")+_CLI_VERSION_RE: Final = re.compile(+ r"codex-cli \d+\.\d+\.\d+(?:[-+][0-9A-Za-z.]+)?"+)++def _displayable_cli_version(raw: str | None) -> str | None:"""Return the probe output only when it is an actual version string.The npm launcher prints a localized shell error instead of a version when``node`` is missing; that text must never reach the UI's version chip or- count as an installed version.+ count as an installed version. The strict pattern also keeps ANSI noise+ and unbounded output off the chip."""text = " ".join(str(raw or "").split())- return text if text.startswith("codex-cli ") else None+ return text if _CLI_VERSION_RE.fullmatch(text) else Nonedef _read_codex_capability(binary_path: str | None) -> CodexAppServerCapability:@@ -1014,6 +1070,18 @@ def _read_codex_capability(binary_path: str | None) -> CodexAppServerCapability:reason=str(exc),reason_code="lifecycle_unavailable",)+ except CodexSubscriptionBinaryUnsupported as exc:+ # The pinned release is absent (wrong version or unknown build). The+ # actionable state is "install the supported release" — the card then+ # shows the pinned npm command instead of a profile warning.+ return CodexAppServerCapability(+ available=False,+ chatgpt_authenticated=False,+ binary_path=resolved,+ version=version,+ reason=str(exc),+ reason_code="not_installed",+ )except CodexSubscriptionUnavailable as exc:# Convert setup failure into a safe status snapshot.return CodexAppServerCapability(@@ -1499,7 +1567,13 @@ class CodexAppServerClient:return loopasync def capability_status(self) -> CodexAppServerCapability:- """Return a bounded, PII-free ChatGPT-login capability snapshot."""+ """Return a bounded, PII-free ChatGPT-login capability snapshot.++ The caller must already own the profile (``ensure_started`` reserves+ the transport first): this probe runs the Codex CLI against+ ``CODEX_HOME`` and racing it with a login, logout, or another probe+ can corrupt the profile's auth and runtime files.+ """try:# The subprocesses inside this synchronous probe each have their own# hard timeout. Do not wrap ``to_thread`` in ``wait_for``: cancelling@@ -1522,13 +1596,15 @@ class CodexAppServerClient:return await asyncio.to_thread(_probe_and_publish)except TimeoutError: # The returned status reports this bounded probe failure.+ # Transiently unknown — everywhere else a failed PROBE maps to+ # busy, never to a proven-broken setup.return CodexAppServerCapability(available=False,chatgpt_authenticated=False,binary_path=None,version=None,- reason="Codex login status timed out.",- reason_code="setup_invalid",+ reason="Codex login status timed out; retrying shortly.",+ reason_code="busy",)except Exception as exc: # noqa: BLE001 - status must degrade honestlylog.warning(@@ -1540,8 +1616,8 @@ class CodexAppServerClient:chatgpt_authenticated=False,binary_path=None,version=None,- reason="Codex login status could not be verified.",- reason_code="setup_invalid",+ reason="Codex login status could not be verified; retrying shortly.",+ reason_code="busy",)@property@@ -1569,38 +1645,69 @@ class CodexAppServerClient:)# 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.+ # probe. Cancellation safety lives entirely in worker threads: a+ # cancel can interrupt any await here (even a shielded one, on a+ # second cancel), so no loop-side variable may decide whether the+ # reservation needs releasing. The reserve worker records its own+ # outcome; on cancellation a detached worker waits for it to+ # settle and releases the orphan, so the profile can never stay+ # parked on "voice is starting" forever.+ reserve_settled = threading.Event()+ reserve_failed: list[BaseException] = []++ def _reserve() -> None:+ try:+ _reserve_subscription_transport(self)+ except BaseException as exc:+ reserve_failed.append(exc)+ raise+ finally:+ reserve_settled.set()++ def _abandon_reservation() -> None:+ if not reserve_settled.wait(timeout=60.0):+ log.error(+ "Cancelled subscription reserve never settled; "+ "leaving it for the next start or disconnect"+ )+ return+ self._profile_transport_reserved = False+ if not reserve_failed:+ _release_subscription_transport(self)+self._profile_transport_reserved = True+ reserve_future = asyncio.get_running_loop().run_in_executor(+ None, _reserve+ )try:- await asyncio.to_thread(_reserve_subscription_transport, self)+ await asyncio.shield(reserve_future)except asyncio.CancelledError:- # The worker may still complete the reservation after this- # cancel; keep the flag so a later close releases either way.+ threading.Thread(+ target=_abandon_reservation,+ name="codex-reserve-abandon",+ daemon=True,+ ).start()raiseexcept BaseException:self._profile_transport_reserved = Falseraise+ async def _release_after_failure() -> None:+ self._profile_transport_reserved = False+ await asyncio.shield(+ asyncio.to_thread(_release_subscription_transport, self)+ )+try:capability = await self.capability_status()except BaseException:- _release_subscription_transport(self)- self._profile_transport_reserved = False+ await _release_after_failure()raiseif not capability.available:- _release_subscription_transport(self)- self._profile_transport_reserved = False+ await _release_after_failure()raise CodexSubscriptionUnavailable(capability.reason)if not capability.binary_path:- _release_subscription_transport(self)- self._profile_transport_reserved = False+ await _release_after_failure()raise CodexSubscriptionUnavailable("Codex CLI binary is unavailable.")try:self._trusted_binary_path = capability.binary_path@@ -1619,6 +1726,9 @@ class CodexAppServerClient:self._workspace,)await self._ensure_sink_started()+ await asyncio.to_thread(+ _verify_spawn_binary, capability.binary_path+ )await self._spawn(capability.binary_path)await self._initialize_live_process()await self._verify_live_chatgpt_account()@@ -1639,11 +1749,13 @@ class CodexAppServerClient:# 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.+ # work by a probe thread. Shielded so a cancellation+ # cannot drop the job from the executor queue and leave+ # waiters running into their timeout.with _subscription_login_lock:_subscription_state_changed.notify_all()- await asyncio.to_thread(_announce_ready)+ await asyncio.shield(asyncio.to_thread(_announce_ready))except BaseException:await self._close_process(CodexAppServerDisconnected("Codex app-server initialization failed."),@@ -2780,11 +2892,14 @@ class CodexAppServerClient:self._ready = Falseself._close_lifeline()if self._profile_transport_reserved:- # 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.+ # Flag first, release off-loop and shielded: a cancellation+ # must neither skip the release nor drop the queued job (a+ # queued to_thread future CAN be cancelled before its thread+ # starts — shield keeps it alive).self._profile_transport_reserved = False- await asyncio.to_thread(_release_subscription_transport, self)+ await asyncio.shield(+ asyncio.to_thread(_release_subscription_transport, self)+ )returnself._process = Noneself._ready = False@@ -2842,9 +2957,12 @@ class CodexAppServerClient:tree.close()self._close_lifeline()if self._profile_transport_reserved:- # Flag first, release off-loop (see the early-return branch above).+ # Flag first, release off-loop and shielded (see the early-return+ # branch above for why both matter).self._profile_transport_reserved = False- await asyncio.to_thread(_release_subscription_transport, self)+ await asyncio.shield(+ asyncio.to_thread(_release_subscription_transport, self)+ )if not expected:log.warning("Codex app-server connection reset")@@ -3580,36 +3698,59 @@ async def disconnect_and_logout_codex_subscription("""Atomically block starts, close the transport, and delete its login."""del binary_path # Kept for the stable route/helper signature.- # ``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+ # Cleanup binds to OUR claim only: _begin... raising because a FOREIGN+ # owner is mutating must not clear that owner's state. The whole+ # decide-and-release lives in worker threads synchronized by a+ # threading.Event — never in a loop-side variable — because a SECOND+ # task cancellation interrupts even a shielded await, and a decision+ # read on the loop at that moment would miss a claim the worker is+ # about to complete (the permanent-wedge class).+ claim_settled = threading.Event()+ claim_failed: list[BaseException] = []def _claim() -> None:- nonlocal claimed- _begin_subscription_disconnect_mutation()- claimed = True+ try:+ _begin_subscription_disconnect_mutation()+ except BaseException as exc:+ claim_failed.append(exc)+ raise+ finally:+ claim_settled.set()++ def _settle() -> None:+ # Off-loop: waits for the claim thread to settle, then releases our+ # claim. Once this thread starts it always finishes, whatever happens+ # to the coroutine that spawned it.+ if not claim_settled.wait(timeout=60.0):+ log.error(+ "Subscription disconnect claim never settled; leaving state "+ "for the next disconnect to recover"+ )+ return+ if not claim_failed:+ _finish_subscription_disconnect_mutation()claim_future = asyncio.get_running_loop().run_in_executor(None, _claim)try:await asyncio.shield(claim_future)- await close_shared_codex_app_servers()+ await asyncio.shield(close_shared_codex_app_servers())return await asyncio.to_thread(_delete_codex_subscription_auth_locked)finally:- 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)- )+ # Shield keeps the settle job alive even if this await is interrupted+ # by another cancellation; the job itself cannot be skipped because+ # nothing can cancel an executor future the loop never cancels.+ await asyncio.shield(asyncio.to_thread(_settle))async def codex_subscription_login_ready(binary_path: str | None = None) -> bool:- """Return the lightweight dedicated-profile login snapshot."""+ """Return the lightweight dedicated-profile login snapshot.++ Transient ``busy`` fails OPEN, mirroring the realtime provider's+ ``external_login_ready``: a caller acting on this answer performs the+ authoritative live account verification anyway, while failing closed here+ turns a healthy install into "connect this provider first" for the busy+ window.+ """try:snapshot = await asyncio.to_thread(codex_subscription_auth_snapshot,@@ -3618,6 +3759,8 @@ async def codex_subscription_login_ready(binary_path: str | None = None) -> boolexcept (CodexAppServerError, OSError):# Readiness probes fail closed without starting transport.return False+ if snapshot.reason_code == "busy":+ return Truereturn bool(snapshot.available and snapshot.chatgpt_authenticated)diff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsxindex 066b0aac4a..c6cd3c13ee 100644--- a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx+++ b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx@@ -515,6 +515,35 @@ describe("ProviderCard: ChatGPT subscription Realtime", () => {);});+ it("shows the pinned install path for a wrong codex release", () => {+ installFetchMock();+ renderCard(+ codexRealtimeCard({+ configured: false,+ install_hint: "npm i -g @openai/[email protected]",+ codex_status: {+ installed: false,+ connected: false,+ mode: "not_connected",+ message: "Subscription voice requires Codex CLI 0.146.0.",+ reason_code: "not_installed",+ },+ }),+ );++ expect(+ screen.getByText(+ "Install the supported Codex version before connecting ChatGPT.",+ ),+ ).toBeTruthy();+ // The actionable fix — the pinned command — must render, and the precise+ // requirement appears as the diagnostic detail.+ expect(screen.getByText("npm i -g @openai/[email protected]")).toBeTruthy();+ expect(screen.getByTestId("codex-setup-detail").textContent).toContain(+ "Subscription voice requires Codex CLI 0.146.0.",+ );+ });+it("asks for a ChatGPT subscription login without suggesting an API key", () => {installFetchMock();renderCard(diff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsxindex 942ef1a830..23e576a67b 100644--- a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx+++ b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx@@ -20,6 +20,7 @@ import {type ProviderTestStatus,type ProviderTier,type SectionHealth,+ PROVIDER_BACKEND_UNREACHABLE,saveProviderBaseUrl,sectionHealthForSubject,startCodexLogin,@@ -604,7 +605,9 @@ export function ProviderCategory({<div className="flex items-start gap-2 rounded-md border border-destructive/30 bg-destructive/5 p-4 text-sm text-destructive"><AlertCircle className="mt-0.5 h-4 w-4" /><div>- {t("apikeys_view.load_error")} ({error}).+ {error === PROVIDER_BACKEND_UNREACHABLE+ ? t("apikeys_view.backend_unavailable")+ : `${t("apikeys_view.load_error")} (${error}).`}<button onClick={() => onChanged()} className="ml-2 underline">{t("apikeys_view.retry")}</button>@@ -1307,7 +1310,9 @@ export function ActiveControl({? disabledReason ?? "Provider cannot be activated": descriptor.configured? "Activate this provider"- : t("apikeys_view.needs_credentials");+ : descriptor.codex_status?.reason_code === "busy"+ ? t("apikeys_codex.status_busy")+ : t("apikeys_view.needs_credentials");return (<label@@ -1636,7 +1641,12 @@ function CodexAuthWidget({const subscriptionStatusKey = !status? "apikeys_codex.status_loading": status.reason_code && status.reason_code !== "login_required"- ? CODEX_STATUS_KEY_BY_REASON[status.reason_code]+ ? // Runtime fallback for a backend value the union does not know yet —+ // the Record enforces exhaustiveness at compile time, but a newer+ // backend must not render t(undefined).+ ((CODEX_STATUS_KEY_BY_REASON as Record<string, string>)[+ status.reason_code+ ] ?? "apikeys_codex.status_loading"): !status.installed? "apikeys_codex.status_not_installed": "apikeys_codex.status_login_required";@@ -1760,7 +1770,8 @@ function CodexAuthWidget({example the exact required Codex version). Hiding it behind thegeneric sentence left users guessing what to fix. */}{subscriptionOnly &&- status?.reason_code === "setup_invalid" &&+ (status?.reason_code === "setup_invalid" ||+ status?.reason_code === "not_installed") &&status.message && (<divdata-testid="codex-setup-detail"diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.pyindex 04b8ac2306..289b540d5c 100644--- a/jarvis/ui/web/provider_routes.py+++ b/jarvis/ui/web/provider_routes.py@@ -302,7 +302,10 @@ def _is_credential_present(spec: ProviderSpec, binary_path: str | None = None) -def _cli_installed(spec: ProviderSpec) -> bool | None:if spec.auth_mode == "codex":- return CodexAuthService().status().installed+ # Honor a configured custom binary path; the default-constructed+ # service would report the PATH install even when the user pinned a+ # different binary.+ return CodexAuthService(_codex_binary_path()).status().installedreturn None@@ -887,6 +890,7 @@ def _codex_subscription_status_payload(binary_path: str | None) -> dict[str, Anythe experimental provider or starts a call."""from jarvis.codex_app_server import (+ CODEX_SUBSCRIPTION_REASON_CODES,CodexAppServerCapability,codex_subscription_auth_snapshot,)@@ -910,6 +914,29 @@ def _codex_subscription_status_payload(binary_path: str | None) -> dict[str, Anyreason_code="busy",)installed = bool(snapshot.available or snapshot.version)+ if snapshot.reason_code == "not_installed":+ # The pinned release is absent. SOME codex may have answered the+ # version probe, but the actionable truth is "install the supported+ # release" — the card's install row keys off this flag.+ installed = False+ elif (+ not installed+ and snapshot.binary_path is None+ and snapshot.reason_code in {"busy", "login_required"}+ ):+ # Ownership windows (login in flight, busy probe) are silent about+ # the CLI itself. A pure PATH resolution answers "is it installed"+ # without touching the owned profile — the card must never tell a+ # user mid-login to reinstall the CLI that is running their login.+ try:+ installed = (+ CodexAuthService(binary_path)._resolve_binary() is not None+ )+ except Exception: # noqa: BLE001 — presence stays unknown, not fatal+ log.debug(+ "Codex CLI presence probe failed during an ownership window",+ exc_info=True,+ )connected = bool(snapshot.available and snapshot.chatgpt_authenticated)if connected:message = "Dedicated ChatGPT subscription voice login is ready."@@ -917,12 +944,18 @@ def _codex_subscription_status_payload(binary_path: str | None) -> dict[str, Anymessage = "Connect the dedicated ChatGPT subscription voice login."else:message = snapshot.reason+ reason_code = "ready" if connected else snapshot.reason_code+ if reason_code not in CODEX_SUBSCRIPTION_REASON_CODES:+ # Five-layer drift guard (BUG-008 class): an unknown vocabulary value+ # must degrade to a transient state, never reach the UI unmapped.+ log.warning("Unknown codex subscription reason_code %r", reason_code)+ reason_code = "busy"return {"installed": installed,"connected": connected,"mode": "chatgpt" if connected else "not_connected","message": message,- "reason_code": "ready" if connected else snapshot.reason_code,+ "reason_code": reason_code,"version": snapshot.version,"accountLabel": "ChatGPT subscription voice" if connected else None,"user_email": None,@@ -1092,6 +1125,17 @@ async def _run_tier_test(_codex_subscription_status_payload,getattr(getattr(cfg, "codex", None), "binary_path", "") or None,)+ if payload.get("reason_code") == "busy":+ # Transient — the same instant renders "checking" on the card and+ # unknown on the tab dot; a not_configured verdict here would be+ # the one dissenting surface. rate_limited is the existing+ # "transient, integration fine" status in the test vocabulary.+ return _provider_test.ProviderTestResult(+ spec.id,+ _provider_test.RATE_LIMITED,+ "The ChatGPT voice status is still being checked — try again "+ "in a moment.",+ )isolated_status = SimpleNamespace(connected=bool(payload.get("connected")),message=str(payload.get("message") or ""),diff --git a/tests/unit/codex_app_server/test_transport.py b/tests/unit/codex_app_server/test_transport.pyindex 419f599476..239e766409 100644--- a/tests/unit/codex_app_server/test_transport.py+++ b/tests/unit/codex_app_server/test_transport.py@@ -32,6 +32,11 @@ from jarvis.codex_app_server import ()+# Captured before the autouse fixture stubs it out, so the dedicated test can+# exercise the real pre-spawn verification.+_REAL_VERIFY_SPAWN_BINARY = transport._verify_spawn_binary++class FakeProcessTree:supports_containment = True@@ -77,6 +82,9 @@ def isolated_profile_lifecycle(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(transport, "_subscription_snapshot_cache_at", 0.0)monkeypatch.setattr(transport, "_subscription_status_probe_active", False)monkeypatch.setattr(transport, "_sha256_cache", {})+ # The pre-spawn re-hash needs a real approved file; the suite's fake+ # binaries have none. The dedicated test exercises the real check.+ monkeypatch.setattr(transport, "_verify_spawn_binary", lambda _path: None)class FakeStdin:@@ -1064,7 +1072,7 @@ def test_public_auth_snapshot_holds_profile_owner_for_entire_probe(assert transport._subscription_mutation_process_lock is process_lockassert process_lock.closed is Falsestarted.set()- assert release.wait(timeout=2.0)+ assert release.wait(timeout=10.0)return CodexAppServerCapability(available=True,chatgpt_authenticated=True,@@ -1339,7 +1347,7 @@ def test_logout_waits_for_a_running_status_probe(def slow_probe(_binary: str | None) -> CodexAppServerCapability:started.set()- assert release.wait(timeout=2.0)+ assert release.wait(timeout=10.0)return _ready_capability()monkeypatch.setattr(transport, "_read_codex_capability", slow_probe)@@ -1381,7 +1389,7 @@ def test_user_actions_report_a_probe_timeout_honestly(def slow_probe(_binary: str | None) -> CodexAppServerCapability:started.set()- assert release.wait(timeout=2.0)+ assert release.wait(timeout=10.0)return _ready_capability()monkeypatch.setattr(transport, "_read_codex_capability", slow_probe)@@ -1585,7 +1593,7 @@ async def test_capability_worker_keeps_profile_reserved_until_it_finishes(def slow_probe(_binary: str | None) -> CodexAppServerCapability:started.set()- assert release.wait(timeout=2.0)+ assert release.wait(timeout=10.0)return CodexAppServerCapability(available=False,chatgpt_authenticated=False,@@ -2154,6 +2162,157 @@ def test_native_codex_version_and_hash_are_both_required()+def test_wrong_release_maps_to_not_installed(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A real-but-different codex release is 'install the pinned one', not a+ profile defect — the card then shows the pinned npm command."""+ 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.150.0"++ def refuse(_binary: str, _version: str | None) -> str:+ raise transport.CodexSubscriptionBinaryUnsupported(+ "Subscription voice requires Codex CLI 0.146.0."+ )++ monkeypatch.setattr(auth_module, "CodexAuthService", FakeAuthService)+ monkeypatch.setattr(transport, "_trusted_native_codex_binary", refuse)++ capability = transport._read_codex_capability(None)++ assert capability.reason_code == "not_installed"+ assert capability.available is False+ assert "requires Codex CLI 0.146.0" in capability.reason+ assert capability.version == "codex-cli 0.150.0"+++async def test_cancelled_reserve_is_released_by_the_abandon_worker(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A cancel landing on the reserve await must not park the profile on+ 'voice is starting' forever (the permanent-wedge class)."""+ acquire_started = threading.Event()+ acquire_release = threading.Event()++ def blocking_acquire() -> FakeProfileProcessLock:+ acquire_started.set()+ assert acquire_release.wait(timeout=10.0)+ return FakeProfileProcessLock()++ monkeypatch.setattr(+ transport, "_acquire_subscription_process_lock", blocking_acquire+ )++ client = CodexAppServerClient("codex-test")+ task = asyncio.create_task(client.ensure_started())+ await asyncio.to_thread(acquire_started.wait, 5.0)+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task++ acquire_release.set()+ # The reserve worker completes AFTER the cancel; the abandon worker must+ # then release it. Poll briefly instead of assuming scheduling order.+ for _ in range(100):+ with transport._subscription_login_lock:+ if not transport._subscription_active_transports:+ break+ await asyncio.sleep(0.02)+ with transport._subscription_login_lock:+ assert transport._subscription_active_transports == set()+ assert transport._subscription_transport_process_lock is None+ assert client._profile_transport_reserved is False+++async def test_cancelled_disconnect_still_releases_the_mutation_claim(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Cancelling disconnect mid-flight (even twice) must not leave the+ profile permanently 'being checked or changed'."""+ close_entered = asyncio.Event()+ close_release = asyncio.Event()++ async def blocking_close() -> None:+ close_entered.set()+ await close_release.wait()++ monkeypatch.setattr(transport, "close_shared_codex_app_servers", blocking_close)+ monkeypatch.setattr(+ transport,+ "_delete_codex_subscription_auth_locked",+ lambda: (True, None),+ )++ task = asyncio.create_task(+ transport.disconnect_and_logout_codex_subscription()+ )+ await asyncio.wait_for(close_entered.wait(), timeout=5.0)+ with transport._subscription_login_lock:+ assert transport._subscription_profile_mutating is True++ task.cancel()+ await asyncio.sleep(0.02)+ task.cancel() # A second cancel interrupts even shielded awaits.+ with pytest.raises(asyncio.CancelledError):+ await task+ close_release.set()++ for _ in range(100):+ with transport._subscription_login_lock:+ if not transport._subscription_profile_mutating:+ break+ await asyncio.sleep(0.02)+ with transport._subscription_login_lock:+ assert transport._subscription_profile_mutating is False+ assert transport._subscription_mutation_process_lock is None+++def test_spawn_binary_is_rehashed_without_the_memo(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ """The copy that gets EXECUTED is verified fresh — a poisoned hash memo+ must never launder an in-place swap into execution."""+ binary = tmp_path / "codex.exe"+ binary.write_bytes(b"approved-content")+ approved = transport._sha256_file(binary)+ monkeypatch.setattr(transport.sys, "platform", "win32")+ monkeypatch.setattr(transport, "_normalized_machine", lambda: "x86_64")+ monkeypatch.setattr(+ transport,+ "_TRUSTED_CODEX_TARGETS",+ {+ ("win32", "x86_64"): (+ "win32-x64",+ "x86_64-pc-windows-msvc",+ "codex.exe",+ approved,+ )+ },+ )+ # A poisoned memo claiming the file is approved must be ignored here.+ monkeypatch.setattr(+ transport, "_sha256_file_cached", lambda _path: approved+ )++ _REAL_VERIFY_SPAWN_BINARY(str(binary))++ binary.write_bytes(b"swapped-content")+ with pytest.raises(CodexSubscriptionUnavailable, match="changed since"):+ _REAL_VERIFY_SPAWN_BINARY(str(binary))++def test_profile_allowlist_accepts_codex_own_runtime_markers() -> None:"""Codex 0.146 writes these into CODEX_HOME on a normal run; rejectingthem bricked the profile right after the CLI's first use."""diff --git a/tests/unit/ui/test_provider_spec_codex_subscription_realtime.py b/tests/unit/ui/test_provider_spec_codex_subscription_realtime.pyindex 5dfc866daf..9d3b9a1044 100644--- a/tests/unit/ui/test_provider_spec_codex_subscription_realtime.py+++ b/tests/unit/ui/test_provider_spec_codex_subscription_realtime.py@@ -277,6 +277,13 @@ def test_subscription_status_payload_maps_busy_without_claiming_missing_install() -> None:from jarvis import codex_app_server+ class _PresenceService:+ def __init__(self, *_args, **_kwargs) -> None:+ pass++ def _resolve_binary(self) -> str:+ return "codex"+snapshot = codex_app_server.CodexAppServerCapability(available=False,chatgpt_authenticated=False,@@ -290,11 +297,14 @@ def test_subscription_status_payload_maps_busy_without_claiming_missing_install("codex_subscription_auth_snapshot",lambda _binary_path: snapshot,)+ monkeypatch.setattr(routes, "CodexAuthService", _PresenceService)payload = routes._codex_subscription_status_payload(None)assert payload["reason_code"] == "busy"assert payload["connected"] is False+ # The name of this test is a promise: busy must not read as a missing CLI.+ assert payload["installed"] is Trueassert payload["message"] == ("Dedicated subscription voice status is being checked or changed.")@@ -416,6 +426,102 @@ async def test_tier_test_judges_the_isolated_voice_profile(assert "codex_status" in captured+def test_login_window_keeps_the_cli_reported_as_installed(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """During the minutes-long interactive login the snapshot is silent about+ the CLI; the card must not tell the user to reinstall mid-login."""+ from jarvis import codex_app_server++ class _PresenceService:+ def __init__(self, *_args, **_kwargs) -> None:+ pass++ def _resolve_binary(self) -> str:+ return "codex"++ snapshot = codex_app_server.CodexAppServerCapability(+ available=False,+ chatgpt_authenticated=False,+ binary_path=None,+ version=None,+ reason="Dedicated ChatGPT subscription login is in progress.",+ reason_code="login_required",+ )+ monkeypatch.setattr(+ codex_app_server,+ "codex_subscription_auth_snapshot",+ lambda _binary_path: snapshot,+ )+ monkeypatch.setattr(routes, "CodexAuthService", _PresenceService)++ payload = routes._codex_subscription_status_payload(None)++ assert payload["reason_code"] == "login_required"+ assert payload["installed"] is True+++def test_wrong_release_payload_shows_the_install_path(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A wrong codex release must surface the install flow, not a profile+ warning: installed=False drives the pinned npm command on the card."""+ from jarvis import codex_app_server++ snapshot = codex_app_server.CodexAppServerCapability(+ available=False,+ chatgpt_authenticated=False,+ binary_path="codex",+ version="codex-cli 0.150.0",+ reason="Subscription voice requires Codex CLI 0.146.0.",+ reason_code="not_installed",+ )+ monkeypatch.setattr(+ codex_app_server,+ "codex_subscription_auth_snapshot",+ lambda _binary_path: snapshot,+ )++ payload = routes._codex_subscription_status_payload(None)++ assert payload["reason_code"] == "not_installed"+ assert payload["installed"] is False+ assert "requires Codex CLI 0.146.0" in payload["message"]+++async def test_tier_test_reports_busy_as_transient_not_as_unconfigured(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The Test button must not issue a setup verdict for a transient window."""+ spec = get_spec("codex-subscription-realtime")+ assert spec is not None+ monkeypatch.setattr(+ routes,+ "_codex_subscription_status_payload",+ lambda _binary_path: {+ "installed": True,+ "connected": False,+ "mode": "not_connected",+ "message": "Dedicated subscription voice status is being checked or changed.",+ "reason_code": "busy",+ },+ )++ result = await routes._run_tier_test(spec, SimpleNamespace())++ assert result.status == "rate_limited"+ assert "being checked" in result.detail+++def test_install_hint_pins_the_supported_release() -> None:+ """The card's install command must name the pinned release — a silent+ unpin would send users to a version the trust gate rejects."""+ spec = get_spec("codex-subscription-realtime")+ assert spec is not None+ assert spec.install_hint == "npm i -g @openai/[email protected]"++def test_reason_code_vocabulary_is_pinned() -> None:"""The five-layer enum contract: this list mirrors the TS union inuseProviders.ts and the card mapping in ProviderTierSection.tsx — grow