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-4 review findings — ownership epochs, honest login and plan states
Ruben Lütke5f3f59f624d0
diff --git a/jarvis/codex_app_server.py b/jarvis/codex_app_server.pyindex 688677d29b..1a796074d4 100644--- a/jarvis/codex_app_server.py+++ b/jarvis/codex_app_server.py@@ -232,6 +232,14 @@ class CodexSubscriptionBinaryUnsupported(CodexSubscriptionUnavailable):"""+class CodexSubscriptionPlanUnsupported(CodexSubscriptionUnavailable):+ """The live account check refused this ChatGPT plan permanently.++ A transient startup failure must NOT carry this class: activation stores+ it as the sticky ``plan_unsupported`` diagnosis that outlives the toast.+ """++class CodexAppServerDisconnected(CodexAppServerError):"""The app-server process exited or its JSONL stream broke."""@@ -265,9 +273,15 @@ class CodexAppServerRPCError(CodexAppServerError):CodexSubscriptionReasonCode = Literal["ready","login_required",+ # An interactive login is running right now: the card must invite the+ # user to FINISH it in the browser, never to start a second one.+ "login_in_progress","lifecycle_unavailable","not_installed","setup_invalid",+ # The connected ChatGPT account can never activate this provider (for+ # example a business/enterprise plan) — sticky until login/logout.+ "plan_unsupported","busy",]CODEX_SUBSCRIPTION_REASON_CODES: Final = frozenset(@@ -861,9 +875,11 @@ def _sha256_file_cached(path: Path) -> str:probe, and probes run on each UI refresh. The signature (device, inode,size, mtime_ns, ctime_ns) is read fresh on every call and the entryexpires 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``).+ the timestamps could ride a stale digest. This memo authorizes STATUS+ reads — which do spawn the CLI for ``login status`` probes within the TTL+ window — while the app-server copy that runs with the user's ChatGPT+ identity is re-hashed without the memo right before spawn (see+ ``ensure_started``)."""try:identity = path.stat()@@ -901,7 +917,10 @@ def _verify_spawn_binary(binary_path: str) -> None:The memoized hash is fine for status polling; the copy that runs with theuser's ChatGPT identity gets one fresh verification right before spawn so- a stale memo can never launder an in-place swap into execution.+ a stale memo can never launder an in-place swap into execution. A+ microsecond rename-over between this check and exec remains possible on+ every platform (no portable fexecve); the guard binds the hash to the+ path at verification time, which is the strongest portable guarantee."""target = _TRUSTED_CODEX_TARGETS.get((sys.platform, _normalized_machine()))if target is None or _sha256_file(Path(binary_path)) != target[3]:@@ -1551,7 +1570,10 @@ class CodexAppServerClient:self._sink_server: asyncio.Server | None = Noneself._sink_base_url: str | None = Noneself._trusted_binary_path: str | None = None- self._profile_transport_reserved = False+ # Ownership epoch of this client's profile reservation; None when the+ # client holds none. Releases quote it so stale teardown can never+ # touch a newer reservation.+ self._profile_transport_epoch: int | None = Noneself._owner_loop: asyncio.AbstractEventLoop | None = Noneself._transport_provider_id = f"jarvis_voice_{secrets.token_hex(16)}"self._ready = False@@ -1610,6 +1632,7 @@ class CodexAppServerClient:log.warning("Codex subscription status failed (%s); app-server stays disabled",type(exc).__name__,+ exc_info=True,)return CodexAppServerCapability(available=False,@@ -1652,51 +1675,64 @@ class CodexAppServerClient:# 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()+ # Exactly-one-decider contract: the reserve worker and the+ # abandoner agree under a tiny lock who releases the epoch, so no+ # interleaving of cancellation, executor scheduling, or a second+ # ensure_started can leak the reservation OR release a newer one+ # (the epoch token makes stale releases no-ops). No timeouts: a+ # give-up path would turn executor saturation into a permanent+ # claim leak, because the worker would still claim later with+ # nobody left to release.+ decision_lock = threading.Lock()+ abandoned = threading.Event()reserve_failed: list[BaseException] = []+ published_epoch: list[int] = []def _reserve() -> None:try:- _reserve_subscription_transport(self)+ epoch = _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)+ with decision_lock:+ if not abandoned.is_set():+ self._profile_transport_epoch = epoch+ published_epoch.append(epoch)+ return+ # The caller was cancelled before we finished: nobody will+ # ever use this reservation, so this worker releases it.+ _release_subscription_transport(self, epoch)- self._profile_transport_reserved = Truereserve_future = asyncio.get_running_loop().run_in_executor(None, _reserve)try:await asyncio.shield(reserve_future)except asyncio.CancelledError:- threading.Thread(- target=_abandon_reservation,- name="codex-reserve-abandon",- daemon=True,- ).start()- raise- except BaseException:- self._profile_transport_reserved = False+ with decision_lock:+ abandoned.set()+ epoch = published_epoch[0] if published_epoch else None+ if epoch is not None and self._profile_transport_epoch == epoch:+ self._profile_transport_epoch = None+ if epoch is not None:+ # Already published before the cancel: release off-loop.+ threading.Thread(+ target=_release_subscription_transport,+ args=(self, epoch),+ name="codex-reserve-abandon",+ daemon=True,+ ).start()raiseasync def _release_after_failure() -> None:- self._profile_transport_reserved = False- await asyncio.shield(- asyncio.to_thread(_release_subscription_transport, self)- )+ epoch = self._profile_transport_epoch+ self._profile_transport_epoch = None+ if epoch is not None:+ await asyncio.shield(+ asyncio.to_thread(+ _release_subscription_transport, self, epoch+ )+ )try:capability = await self.capability_status()@@ -1799,7 +1835,7 @@ class CodexAppServerClient:)plan_type = account.get("planType") if isinstance(account, Mapping) else Noneif plan_type not in _PERSONAL_CHATGPT_PLANS:- raise CodexSubscriptionUnavailable(+ raise CodexSubscriptionPlanUnsupported("Subscription voice permits only personal ChatGPT accounts; workspace, ""enterprise, education, and unknown plans are refused.")@@ -2203,8 +2239,13 @@ class CodexAppServerClient:*command,]kwargs["start_new_session"] = True+ # Off-loop: the login mutex this helper takes can be held by a+ # probe thread across filesystem work; the audio loop must not+ # wait on it.kwargs["pass_fds"] = (- *_subscription_transport_pass_fds(self),+ *await asyncio.to_thread(+ _subscription_transport_pass_fds, self+ ),lifeline_read_fd,)except BaseException:@@ -2891,14 +2932,15 @@ class CodexAppServerClient:if process is None:self._ready = Falseself._close_lifeline()- if self._profile_transport_reserved:- # Flag first, release off-loop and shielded: a cancellation+ if self._profile_transport_epoch is not None:+ # Epoch 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+ epoch = self._profile_transport_epoch+ self._profile_transport_epoch = Noneawait asyncio.shield(- asyncio.to_thread(_release_subscription_transport, self)+ asyncio.to_thread(_release_subscription_transport, self, epoch))returnself._process = None@@ -2956,12 +2998,13 @@ class CodexAppServerClient:if tree is not None:tree.close()self._close_lifeline()- if self._profile_transport_reserved:- # Flag first, release off-loop and shielded (see the early-return+ if self._profile_transport_epoch is not None:+ # Epoch first, release off-loop and shielded (see the early-return# branch above for why both matter).- self._profile_transport_reserved = False+ epoch = self._profile_transport_epoch+ self._profile_transport_epoch = Noneawait asyncio.shield(- asyncio.to_thread(_release_subscription_transport, self)+ asyncio.to_thread(_release_subscription_transport, self, epoch))if not expected:log.warning("Codex app-server connection reset")@@ -2997,15 +3040,21 @@ _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.+# Invariant: WORKER threads may hold this lock across filesystem work (the+# cross-process profile lock is acquired under it: mkdir, resolve, ACL+# validation — its OS locking call itself is non-blocking). Event-loop code+# must therefore NEVER take this lock directly — always go through+# asyncio.to_thread (shielded where a cancellation must not drop the job)._subscription_login_lock = threading.Lock()_subscription_login_in_flight = False_subscription_login_process: Any | None = None_subscription_profile_mutating = False_subscription_active_transports: set[int] = set()_subscription_transport_process_lock: Any | None = None+# Monotonic ownership token for the transport reservation: bumped on every+# reserve (including same-client adoption), quoted by every release. A stale+# holder's release becomes a no-op instead of tearing down a live reservation.+_subscription_transport_epoch: int = 0_subscription_mutation_process_lock: Any | None = None# Status probes must never report a broken setup just because the profile is@@ -3097,11 +3146,35 @@ def _invalidate_subscription_snapshot_locked() -> None:global _subscription_snapshot_cache, _subscription_snapshot_cache_keyglobal _subscription_snapshot_cache_atglobal _subscription_snapshot_cache_is_failure+ global _subscription_activation_block_subscription_snapshot_cache = None_subscription_snapshot_cache_key = ""_subscription_snapshot_cache_at = 0.0_subscription_snapshot_cache_is_failure = False+ # A login/logout may change the account, so the sticky "this plan can+ # never activate" diagnosis must be re-earned by the next activation.+ _subscription_activation_block = None+++# Sticky reason the connected login cannot activate (for example a+# business/enterprise ChatGPT plan, refused by the live account check). The+# one honest 409 toast fades in seconds; without this, every surface keeps+# claiming "ready" for an account that can never work.+_subscription_activation_block: str | None = None+++def set_codex_subscription_activation_block(message: str | None) -> None:+ """Record (or clear with ``None``) why activation is impossible."""+ global _subscription_activation_block++ with _subscription_login_lock:+ _subscription_activation_block = (message or "").strip() or None+++def codex_subscription_activation_block() -> str | None:+ with _subscription_login_lock:+ return _subscription_activation_blockdef _await_status_probe_completion_locked() -> None:@@ -3150,8 +3223,16 @@ def _subscription_transport_pass_fds(return (descriptor,)-def _reserve_subscription_transport(client: CodexAppServerClient) -> None:- global _subscription_transport_process_lock+def _reserve_subscription_transport(client: CodexAppServerClient) -> int:+ """Reserve the profile for this client and return an ownership epoch.++ The epoch is the anti-stale-release token: every reservation (including a+ re-reservation by the same client after a crash or cancelled start) bumps+ it, and ``_release_subscription_transport`` only honors the CURRENT epoch.+ Without it, an abandon worker or a slow ``_close_process`` from a previous+ life could tear down a reservation a newer start legitimately owns.+ """+ global _subscription_transport_process_lock, _subscription_transport_epochwith _subscription_login_lock:_await_status_probe_completion_locked()@@ -3165,18 +3246,30 @@ def _reserve_subscription_transport(client: CodexAppServerClient) -> None:_subscription_active_transports == {client_id}and _subscription_transport_process_lock is not None):- return+ # Adoption: the new start supersedes any stale holder, whose+ # pending releases become no-ops via the epoch bump.+ _subscription_transport_epoch += 1+ return _subscription_transport_epochraise CodexSubscriptionUnavailable("Subscription voice is already owned by another client or event loop.")_subscription_transport_process_lock = _acquire_subscription_process_lock()_subscription_active_transports.add(client_id)+ _subscription_transport_epoch += 1+ return _subscription_transport_epoch-def _release_subscription_transport(client: CodexAppServerClient) -> None:+def _release_subscription_transport(+ client: CodexAppServerClient, epoch: int+) -> None:+ """Release the reservation, but only when ``epoch`` is still current."""global _subscription_transport_process_lockwith _subscription_login_lock:+ if epoch != _subscription_transport_epoch:+ # A newer reservation owns the profile now; this release belongs+ # to a superseded holder and must not touch the live state.+ return_subscription_active_transports.discard(id(client))if not _subscription_active_transports:process_lock = _subscription_transport_process_lock@@ -3257,7 +3350,10 @@ def _local_subscription_auth_snapshot_locked(binary_path=None,version=None,reason="Dedicated ChatGPT subscription login is in progress.",- reason_code="login_required",+ # Its own state, not login_required: the card must invite the+ # user to FINISH the running browser login, never to start a+ # second one.+ reason_code="login_in_progress",)if _subscription_profile_mutating:# Checked before the transport branch: during disconnect-and-logout@@ -3280,14 +3376,12 @@ def _local_subscription_auth_snapshot_locked()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+ # The bounded cache read applies the age ceiling and the+ # failure-memo exclusion — never read the raw cache here.+ cached = _cached_subscription_snapshot_locked(+ binary_path, allow_stale=True)+ cached_version = cached.version if cached is not None else Nonereturn CodexAppServerCapability(available=True,chatgpt_authenticated=True,@@ -3398,6 +3492,10 @@ def codex_subscription_auth_snapshot(),reason_code="busy",),+ # Flagged so the stale path never serves this memo as "what+ # was true before" — it exists only to keep coalesced waiters+ # off a broken CLI within the fresh TTL.+ is_failure=True,)raiseelse:@@ -3720,13 +3818,12 @@ async def disconnect_and_logout_codex_subscription(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+ # to the coroutine that spawned it. The wait is unbounded on purpose:+ # a give-up timeout would turn executor saturation into a permanent+ # claim leak (the claim thread still runs later, with nobody left to+ # release it), while the claim itself is bounded by construction+ # (probe wait <= 5s plus lock acquisition).+ claim_settled.wait()if not claim_failed:_finish_subscription_disconnect_mutation()diff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsxindex c6cd3c13ee..2b3c372d3f 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,107 @@ describe("ProviderCard: ChatGPT subscription Realtime", () => {);});+ it("keeps model and voice pickers mounted through a busy window", async () => {+ installFetchMock();+ renderCard(+ codexRealtimeCard({+ configured: false,+ codex_status: {+ installed: false,+ connected: false,+ mode: "not_connected",+ message: "Dedicated subscription voice status is being checked or changed.",+ reason_code: "busy",+ },+ }),+ );++ // The realtime options control mounts (it loads its options async) even+ // while the card is only transiently unsure about the login — the card+ // must not visibly flicker its pickers away during "one moment".+ expect(await screen.findByLabelText(/model/i)).toBeTruthy();+ });++ it("tells the user to finish a running login instead of restarting it", () => {+ installFetchMock();+ renderCard(+ codexRealtimeCard({+ configured: false,+ codex_status: {+ installed: true,+ connected: false,+ mode: "not_connected",+ message: "Dedicated ChatGPT subscription login is in progress.",+ reason_code: "login_in_progress",+ },+ }),+ );++ expect(+ screen.getByText(+ "The ChatGPT login is running — finish it in the browser window.",+ ),+ ).toBeTruthy();+ const connect = screen.getByRole("button", {+ name: "Connect with ChatGPT",+ }) as HTMLButtonElement;+ expect(connect.disabled).toBe(true);+ expect(screen.queryByText("npm i -g @openai/codex")).toBeNull();+ });++ it("treats an unsupported OS as terminal, not as a missing install", () => {+ installFetchMock();+ renderCard(+ codexRealtimeCard({+ configured: false,+ codex_status: {+ installed: false,+ connected: false,+ mode: "not_connected",+ message: "This operating-system architecture is not approved.",+ reason_code: "lifecycle_unavailable",+ },+ }),+ );++ expect(+ screen.getByText(+ "Subscription voice is not yet available on this operating system. API Realtime and standard voice still work.",+ ),+ ).toBeTruthy();+ // No install invitation for a CLI that would not help, and no active+ // Connect button that can only end in an error toast.+ expect(screen.queryByText("npm i -g @openai/codex")).toBeNull();+ const connect = screen.getByRole("button", {+ name: "Connect with ChatGPT",+ }) as HTMLButtonElement;+ expect(connect.disabled).toBe(true);+ });++ it("shows the sticky plan diagnosis after a refused activation", () => {+ installFetchMock();+ renderCard(+ codexRealtimeCard({+ configured: false,+ codex_status: {+ installed: true,+ connected: false,+ mode: "not_connected",+ message:+ "Subscription voice permits only personal ChatGPT accounts; workspace, enterprise, education, and unknown plans are refused.",+ reason_code: "plan_unsupported",+ },+ }),+ );++ expect(+ screen.getByText("This ChatGPT plan does not support subscription voice."),+ ).toBeTruthy();+ expect(screen.getByTestId("codex-setup-detail").textContent).toContain(+ "personal ChatGPT accounts",+ );+ });+it("shows the pinned install path for a wrong codex release", () => {installFetchMock();renderCard(diff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsxindex 23e576a67b..49c7db8f9b 100644--- a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx+++ b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx@@ -1615,12 +1615,23 @@ const CODEX_STATUS_KEY_BY_REASON: Record<> = {ready: "apikeys_codex.status_ready",login_required: "apikeys_codex.status_login_required",+ login_in_progress: "apikeys_codex.status_login_in_progress",lifecycle_unavailable: "apikeys_codex.status_lifecycle_unavailable",not_installed: "apikeys_codex.status_not_installed",setup_invalid: "apikeys_codex.status_setup_invalid",+ plan_unsupported: "apikeys_codex.status_plan_unsupported",busy: "apikeys_codex.status_busy",};+// States in which the install row and an active Connect button would be+// wrong: transient windows, a login the user must FINISH (not restart), and+// an OS the feature does not support at all.+const CODEX_NO_INSTALL_PROMPT_REASONS = new Set<string>([+ "busy",+ "login_in_progress",+ "lifecycle_unavailable",+]);+function CodexAuthWidget({descriptor,onChanged,@@ -1771,7 +1782,8 @@ function CodexAuthWidget({generic sentence left users guessing what to fix. */}{subscriptionOnly &&(status?.reason_code === "setup_invalid" ||- status?.reason_code === "not_installed") &&+ status?.reason_code === "not_installed" ||+ status?.reason_code === "plan_unsupported") &&status.message && (<divdata-testid="codex-setup-detail"@@ -1785,7 +1797,8 @@ function CodexAuthWidget({)}</div>- {!status?.installed && status?.reason_code !== "busy" && (+ {!status?.installed &&+ !CODEX_NO_INSTALL_PROMPT_REASONS.has(status?.reason_code ?? "") && (<div className="flex flex-wrap items-center gap-2"><code className="min-w-[220px] flex-1 rounded-md border border-border bg-muted/30 px-3 py-1.5 font-mono text-xs">{installCommand}@@ -1804,8 +1817,19 @@ function CodexAuthWidget({disabled={pending !== null ||loginPolling ||+ // Finish the RUNNING login instead of starting a second one; an+ // unsupported OS can never connect at all.+ status?.reason_code === "login_in_progress" ||+ status?.reason_code === "lifecycle_unavailable" ||(!status?.installed && status?.reason_code !== "busy")}+ title={+ status?.reason_code === "login_in_progress"+ ? t("apikeys_codex.status_login_in_progress")+ : status?.reason_code === "lifecycle_unavailable"+ ? t("apikeys_codex.status_lifecycle_unavailable")+ : undefined+ }><LogIn className="h-3.5 w-3.5" />{t("apikeys_codex.connect_chatgpt")}diff --git a/jarvis/ui/web/frontend/src/hooks/useProviders.ts b/jarvis/ui/web/frontend/src/hooks/useProviders.tsindex e7410d5ad7..930f5a19dc 100644--- a/jarvis/ui/web/frontend/src/hooks/useProviders.ts+++ b/jarvis/ui/web/frontend/src/hooks/useProviders.ts@@ -151,9 +151,14 @@ export interface CodexStatus {reason_code?:| "ready"| "login_required"+ // An interactive login is running: invite the user to FINISH it in the+ // browser, never to start a second one.+ | "login_in_progress"| "lifecycle_unavailable"| "not_installed"| "setup_invalid"+ // Sticky: the connected ChatGPT plan can never activate this provider.+ | "plan_unsupported"// Transient: the profile is briefly owned by another status probe, a// login/logout, or a starting voice session. Not a setup defect — the UI// shows a neutral "checking" line and never the reconnect warning.@@ -212,17 +217,27 @@ interface ProvidersResponse {providers: ProviderDescriptor[];}+export const PROVIDER_BACKEND_UNREACHABLE = "backend_unreachable";+const PROVIDER_RETRY_DELAYS_MS = [1_000, 2_000, 5_000, 10_000] as const;++interface UseProvidersOptions {+ retryDelaysMs?: readonly number[];+}+/*** Loads /api/providers and re-fetches on relevant WS events. The hook updates* the UI state live whenever a secret is set on the backend or a brain* provider was switched — without the component having to track that itself.*/-export function useProviders() {+export function useProviders(options: UseProvidersOptions = {}) {const [providers, setProviders] = useState<ProviderDescriptor[]>([]);const [loading, setLoading] = useState(true);const [error, setError] = useState<string | null>(null);const requestVersion = useRef(0);const requestController = useRef<AbortController | null>(null);+ const retryAttempt = useRef(0);+ const retryDelays = useRef<readonly number[]>(PROVIDER_RETRY_DELAYS_MS);+ retryDelays.current = options.retryDelaysMs ?? PROVIDER_RETRY_DELAYS_MS;const refetch = useCallback(async () => {const version = ++requestVersion.current;@@ -237,10 +252,17 @@ export function useProviders() {});if (!res.ok) throw new Error(`HTTP ${res.status}`);const data: ProvidersResponse = await res.json();- if (version === requestVersion.current) setProviders(data.providers);+ if (version === requestVersion.current) {+ retryAttempt.current = 0;+ setProviders(data.providers);+ }} catch (e) {if ((e as Error).name !== "AbortError" && version === requestVersion.current) {- setError((e as Error).message);+ setError(+ e instanceof TypeError+ ? PROVIDER_BACKEND_UNREACHABLE+ : (e as Error).message,+ );}} finally {if (version === requestVersion.current) setLoading(false);@@ -248,6 +270,17 @@ export function useProviders() {}}, []);+ useEffect(() => {+ if (error !== PROVIDER_BACKEND_UNREACHABLE || retryDelays.current.length === 0) {+ return;+ }+ const delays = retryDelays.current;+ const delay = delays[Math.min(retryAttempt.current, delays.length - 1)];+ retryAttempt.current += 1;+ const timer = window.setTimeout(() => void refetch(), delay);+ return () => window.clearTimeout(timer);+ }, [error, refetch]);+/*** Optimistically flip the active provider within a tier, in-memory, BEFORE* the backend switch resolves. The `/api/{brain,tts,stt}/switch` calls candiff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex a35583477f..4e09deff32 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -1135,6 +1135,7 @@"configured": "Konfiguriert","loading_providers": "Provider werden geladen…","load_error": "Konnte Provider-Liste nicht laden",+ "backend_unavailable": "Der lokale App-Dienst antwortet nicht. Das ist kein Internet- oder Cloud-Provider-Fehler. Automatischer Neuversuch läuft.","retry": "erneut versuchen","tier_brain": "Brain-Provider","tier_tts": "Voice-Output (TTS)",@@ -1910,6 +1911,8 @@"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.",+ "status_login_in_progress": "Der ChatGPT-Login läuft — schließ ihn im Browserfenster ab.",+ "status_plan_unsupported": "Dieser ChatGPT-Tarif unterstützt Subscription-Voice nicht.","setup_detail_label": "Details:","install_command_copied": "Installationsbefehl kopiert","connected_chatgpt": "Über dein ChatGPT-Abo verbunden.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex f0f3b51af0..05138c69cb 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -1135,6 +1135,7 @@"configured": "Configured","loading_providers": "Loading providers…","load_error": "Could not load provider list",+ "backend_unavailable": "The local app service is not responding. This is not an internet or cloud-provider error. Retrying automatically.","retry": "retry","tier_brain": "Brain Provider","tier_tts": "Voice Output (TTS)",@@ -1911,6 +1912,8 @@"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.",+ "status_login_in_progress": "The ChatGPT login is running — finish it in the browser window.",+ "status_plan_unsupported": "This ChatGPT plan does not support subscription voice.","setup_detail_label": "Details:","install_command_copied": "Install command copied","connected_chatgpt": "Connected through your ChatGPT subscription.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 42a84aef9c..ae4ce413ce 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -1135,6 +1135,7 @@"configured": "Configurada","loading_providers": "Cargando proveedores…","load_error": "No se pudo cargar la lista de proveedores",+ "backend_unavailable": "El servicio local de la aplicación no responde. No es un error de Internet ni del proveedor en la nube. Se volverá a intentar automáticamente.","retry": "reintentar","tier_brain": "Proveedor de IA","tier_tts": "Salida de voz (TTS)",@@ -1910,6 +1911,8 @@"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.",+ "status_login_in_progress": "El inicio de sesión de ChatGPT está en curso — termínalo en la ventana del navegador.",+ "status_plan_unsupported": "Este plan de ChatGPT no admite la voz por suscripción.","setup_detail_label": "Detalles:","install_command_copied": "Comando de instalación copiado","connected_chatgpt": "Conectado mediante tu suscripción de ChatGPT.",diff --git a/jarvis/ui/web/frontend/src/i18n/voice-i18n-parity.test.ts b/jarvis/ui/web/frontend/src/i18n/voice-i18n-parity.test.tsindex ca70085f07..adedac404c 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,8 @@ describe("subscription Realtime voice copy", () => {"apikeys_codex.status_lifecycle_unavailable","apikeys_codex.status_setup_invalid","apikeys_codex.status_busy",+ "apikeys_codex.status_login_in_progress",+ "apikeys_codex.status_plan_unsupported","apikeys_codex.setup_detail_label","apikeys_codex.install_command_copied","apikeys_codex.connected_chatgpt",diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.pyindex 289b540d5c..6ec36cdbd1 100644--- a/jarvis/ui/web/provider_routes.py+++ b/jarvis/ui/web/provider_routes.py@@ -892,6 +892,7 @@ def _codex_subscription_status_payload(binary_path: str | None) -> dict[str, Anyfrom jarvis.codex_app_server import (CODEX_SUBSCRIPTION_REASON_CODES,CodexAppServerCapability,+ codex_subscription_activation_block,codex_subscription_auth_snapshot,)@@ -922,7 +923,8 @@ def _codex_subscription_status_payload(binary_path: str | None) -> dict[str, Anyelif (not installedand snapshot.binary_path is None- and snapshot.reason_code in {"busy", "login_required"}+ and snapshot.reason_code+ in {"busy", "login_required", "login_in_progress", "lifecycle_unavailable"}):# Ownership windows (login in flight, busy probe) are silent about# the CLI itself. A pure PATH resolution answers "is it installed"@@ -938,13 +940,24 @@ def _codex_subscription_status_payload(binary_path: str | None) -> dict[str, Anyexc_info=True,)connected = bool(snapshot.available and snapshot.chatgpt_authenticated)- if connected:+ activation_block = codex_subscription_activation_block() if connected else None+ if activation_block:+ # The login works, but the live account check refused activation for+ # good (for example a business/enterprise plan). Without this sticky+ # diagnosis every surface would keep claiming "ready" after the one+ # honest activation toast has faded.+ connected = False+ message = activation_block+ reason_code = "plan_unsupported"+ elif connected:message = "Dedicated ChatGPT subscription voice login is ready."+ reason_code = "ready"elif snapshot.available:message = "Connect the dedicated ChatGPT subscription voice login."+ reason_code = snapshot.reason_codeelse:message = snapshot.reason- reason_code = "ready" if connected else snapshot.reason_code+ reason_code = snapshot.reason_codeif 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.@@ -1339,6 +1352,15 @@ async def _tier_section_health(detail=f"{spec.label}: status check in progress",subject_id=spec.id,)+ if codex_payload.get("reason_code") == "login_in_progress":+ # The user is mid-login; an amber "not connected" dot would+ # contradict the card telling them to finish that login.+ return SectionHealth(+ status=_section_health.UNKNOWN,+ reason="login_in_progress",+ detail=f"{spec.label}: login in progress",+ subject_id=spec.id,+ )configured = bool(codex_payload.get("connected"))else:configured = await _provider_credential_present_for_binary_async(@@ -3776,6 +3798,14 @@ async def realtime_switch(body: SwitchBody, request: Request) -> dict[str, Any]:"Try again in a moment."),)+ if codex_payload.get("reason_code") == "login_in_progress":+ raise HTTPException(+ status_code=409,+ detail=(+ "The ChatGPT subscription login is still running. Finish "+ "it in the browser window, then activate."+ ),+ )credential_present = bool(codex_payload.get("connected"))else:credential_present = await _provider_credential_present_async(spec, request)@@ -3813,7 +3843,23 @@ async def realtime_switch(body: SwitchBody, request: Request) -> dict[str, Any]:),) from excexcept Exception as exc: # noqa: BLE001 - provider gate returns a safe 409+ if spec.id == "codex-subscription-realtime":+ from jarvis.codex_app_server import (+ CodexSubscriptionPlanUnsupported,+ set_codex_subscription_activation_block,+ )++ if isinstance(exc, CodexSubscriptionPlanUnsupported):+ # Sticky: the one honest toast fades in seconds, but this+ # account can never activate — every surface must stop+ # claiming "ready" until a different login exists.+ set_codex_subscription_activation_block(str(exc))raise HTTPException(status_code=409, detail=str(exc)) from exc+ if spec.id == "codex-subscription-realtime":+ from jarvis.codex_app_server import set_codex_subscription_activation_block++ # A passed activation is the proof the account works again.+ set_codex_subscription_activation_block(None)if body.persist:try:diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.pyindex 036372ac88..4d1e5f969c 100644--- a/jarvis/ui/web/settings_routes.py+++ b/jarvis/ui/web/settings_routes.py@@ -281,13 +281,41 @@ async def put_voice_mode(body: VoiceModeBody, request: Request) -> dict[str, obj# A3: never pin the boot default to an unreachable engine. A provider may# use an API key or an external subscription login, so readiness — not a# particular credential shape — is the boundary.- if body.mode == "realtime" and await asyncio.to_thread(- _realtime_available_provider, cfg- ) is None:- raise HTTPException(- status_code=400,- detail="no realtime provider is configured and ready",- )+ if body.mode == "realtime":+ prov = await asyncio.to_thread(_realtime_available_provider, cfg)+ if prov is None:+ raise HTTPException(+ status_code=400,+ detail="no realtime provider is configured and ready",+ )+ if prov == "codex-subscription-realtime":+ # The availability bool fails OPEN on a transient busy window (by+ # design — the session opener verifies live). PERSISTING the mode+ # is a standing decision, so it gates on the actual payload: a+ # busy window answers "try again", a logged-out pinned provider+ # is refused instead of pinning a mode that cannot start.+ from jarvis.ui.web.provider_routes import (+ _codex_binary_path,+ _codex_subscription_status_payload,+ )++ payload = await asyncio.to_thread(+ _codex_subscription_status_payload,+ _codex_binary_path(request),+ )+ if payload.get("reason_code") in {"busy", "login_in_progress"}:+ raise HTTPException(+ status_code=409,+ detail=(+ "The ChatGPT subscription voice status is being "+ "checked. Try again in a moment."+ ),+ )+ if not payload.get("connected"):+ raise HTTPException(+ status_code=400,+ detail="no realtime provider is configured and ready",+ )if cfg is not None and getattr(cfg, "voice", None) is not None:try:diff --git a/tests/unit/codex_app_server/test_transport.py b/tests/unit/codex_app_server/test_transport.pyindex 239e766409..84fc703cce 100644--- a/tests/unit/codex_app_server/test_transport.py+++ b/tests/unit/codex_app_server/test_transport.py@@ -82,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", {})+ monkeypatch.setattr(transport, "_subscription_snapshot_cache_is_failure", False)+ monkeypatch.setattr(transport, "_subscription_transport_epoch", 0)+ monkeypatch.setattr(transport, "_subscription_activation_block", None)# 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)@@ -2231,7 +2234,7 @@ async def test_cancelled_reserve_is_released_by_the_abandon_worker(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+ assert client._profile_transport_epoch is None@pytest.mark.asyncio@@ -2253,6 +2256,19 @@ async def test_cancelled_disconnect_still_releases_the_mutation_claim("_delete_codex_subscription_auth_locked",lambda: (True, None),)+ # Gate the release so it provably happens AFTER both cancels — otherwise a+ # fast runner could finish cleanup before the second cancel and the test+ # would silently degrade to a single-cancel check.+ finish_gate = threading.Event()+ real_finish = transport._finish_subscription_disconnect_mutation++ def gated_finish() -> None:+ assert finish_gate.wait(timeout=10.0)+ real_finish()++ monkeypatch.setattr(+ transport, "_finish_subscription_disconnect_mutation", gated_finish+ )task = asyncio.create_task(transport.disconnect_and_logout_codex_subscription()@@ -2267,6 +2283,7 @@ async def test_cancelled_disconnect_still_releases_the_mutation_claim(with pytest.raises(asyncio.CancelledError):await taskclose_release.set()+ finish_gate.set()for _ in range(100):with transport._subscription_login_lock:@@ -2313,6 +2330,67 @@ def test_spawn_binary_is_rehashed_without_the_memo(_REAL_VERIFY_SPAWN_BINARY(str(binary))+def test_stale_epoch_release_is_ignored() -> None:+ """A superseded holder's release must never tear down a newer reservation."""+ client = CodexAppServerClient("codex-test")+ first = transport._reserve_subscription_transport(client)+ second = transport._reserve_subscription_transport(client) # adoption bump++ transport._release_subscription_transport(client, first)+ with transport._subscription_login_lock:+ # The stale release was a no-op: the newer reservation survives.+ assert transport._subscription_active_transports == {id(client)}+ assert transport._subscription_transport_process_lock is not None++ transport._release_subscription_transport(client, second)+ with transport._subscription_login_lock:+ assert transport._subscription_active_transports == set()+ assert transport._subscription_transport_process_lock is None+++def test_failure_memo_is_not_served_on_the_stale_path(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """One transient probe failure must not paint the card for the whole+ next busy window via the stale-cache path."""++ def probe(_binary: str | None) -> CodexAppServerCapability:+ raise OSError("cli exploded")++ monkeypatch.setattr(transport, "_read_codex_capability", probe)+ with pytest.raises(OSError):+ transport.codex_subscription_auth_snapshot("codex-test")++ def contended() -> FakeProfileProcessLock:+ raise CodexSubscriptionUnavailable("owned elsewhere")++ monkeypatch.setattr(transport, "_acquire_subscription_process_lock", contended)+ with transport._subscription_login_lock:+ # Age the memo past the fresh TTL: within it, serving the memo IS the+ # coalescing contract; the stale path is what must exclude it.+ transport._subscription_snapshot_cache_at = (+ time.monotonic() - transport._SUBSCRIPTION_SNAPSHOT_CACHE_TTL_S - 1.0+ )++ snapshot = transport.codex_subscription_auth_snapshot("codex-test")+ assert snapshot.reason_code == "busy"+ # The stale path answered with the live contention, not the failure memo.+ assert "owned elsewhere" in snapshot.reason+++def test_activation_block_sticks_until_invalidated() -> None:+ transport.set_codex_subscription_activation_block(+ "Subscription voice permits only personal ChatGPT accounts."+ )+ assert (+ transport.codex_subscription_activation_block()+ == "Subscription voice permits only personal ChatGPT accounts."+ )+ with transport._subscription_login_lock:+ transport._invalidate_subscription_snapshot_locked()+ assert transport.codex_subscription_activation_block() is None++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 9d3b9a1044..649fc1b118 100644--- a/tests/unit/ui/test_provider_spec_codex_subscription_realtime.py+++ b/tests/unit/ui/test_provider_spec_codex_subscription_realtime.py@@ -446,7 +446,7 @@ def test_login_window_keeps_the_cli_reported_as_installed(binary_path=None,version=None,reason="Dedicated ChatGPT subscription login is in progress.",- reason_code="login_required",+ reason_code="login_in_progress",)monkeypatch.setattr(codex_app_server,@@ -457,7 +457,74 @@ def test_login_window_keeps_the_cli_reported_as_installed(payload = routes._codex_subscription_status_payload(None)- assert payload["reason_code"] == "login_required"+ assert payload["reason_code"] == "login_in_progress"+ assert payload["installed"] is True+++def test_plan_block_turns_a_ready_login_into_plan_unsupported(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """After a refused activation, surfaces must stop claiming ready."""+ from jarvis import codex_app_server++ snapshot = codex_app_server.CodexAppServerCapability(+ available=True,+ chatgpt_authenticated=True,+ binary_path="codex",+ version="codex-cli 0.146.0",+ reason="Dedicated ChatGPT login is available.",+ reason_code="ready",+ )+ monkeypatch.setattr(+ codex_app_server,+ "codex_subscription_auth_snapshot",+ lambda _binary_path: snapshot,+ )+ monkeypatch.setattr(+ codex_app_server,+ "_subscription_activation_block",+ "Subscription voice permits only personal ChatGPT accounts.",+ )++ payload = routes._codex_subscription_status_payload(None)++ assert payload["reason_code"] == "plan_unsupported"+ assert payload["connected"] is False+ assert "personal ChatGPT accounts" in payload["message"]+++def test_lifecycle_unavailable_does_not_claim_missing_cli(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """An unsupported OS must not render the install prompt for a CLI that+ would not help anyway."""+ 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="This operating-system architecture is not approved.",+ reason_code="lifecycle_unavailable",+ )+ 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"] == "lifecycle_unavailable"assert payload["installed"] is True@@ -534,9 +601,11 @@ def test_reason_code_vocabulary_is_pinned() -> None:assert set(get_args(hints["reason_code"])) == {"ready","login_required",+ "login_in_progress","lifecycle_unavailable","not_installed","setup_invalid",+ "plan_unsupported","busy",}diff --git a/tests/unit/web/test_voice_mode_route.py b/tests/unit/web/test_voice_mode_route.pyindex 7564d904dd..768aba5861 100644--- a/tests/unit/web/test_voice_mode_route.py+++ b/tests/unit/web/test_voice_mode_route.py@@ -176,6 +176,66 @@ def test_get_voice_mode_no_realtime_key_anywhere(monkeypatch):assert body["active_model"] is None+def test_put_voice_mode_codex_busy_answers_409_and_persists_nothing(monkeypatch):+ """The availability bool fails open on busy; the standing mode decision+ must not — it asks the payload and answers 'try again' instead."""+ from jarvis.ui.web import provider_routes, settings_routes++ monkeypatch.setattr(+ settings_routes,+ "_realtime_available_provider",+ lambda _cfg: "codex-subscription-realtime",+ )+ monkeypatch.setattr(+ provider_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",+ },+ )+ client = TestClient(_app(mode="pipeline"))++ r = client.put(+ "/api/settings/voice-mode", json={"mode": "realtime", "persist": True}+ )++ assert r.status_code == 409+ assert "being checked" in r.json()["detail"]+++def test_put_voice_mode_codex_logged_out_is_400(monkeypatch):+ """A pinned but logged-out provider must not be persisted as the mode."""+ from jarvis.ui.web import provider_routes, settings_routes++ monkeypatch.setattr(+ settings_routes,+ "_realtime_available_provider",+ lambda _cfg: "codex-subscription-realtime",+ )+ monkeypatch.setattr(+ provider_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",+ },+ )+ client = TestClient(_app(mode="pipeline"))++ r = client.put(+ "/api/settings/voice-mode", json={"mode": "realtime", "persist": True}+ )++ assert r.status_code == 400++def test_put_voice_mode_invalid_is_400():client = TestClient(_app())r = client.put("/api/settings/voice-mode", json={"mode": "bogus", "persist": False})