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): take the round-8 approvals' recommended hardening
Ruben Lütke262b760baf24
diff --git a/jarvis/codex_app_server.py b/jarvis/codex_app_server.pyindex 1b05660b94..7518058575 100644--- a/jarvis/codex_app_server.py+++ b/jarvis/codex_app_server.py@@ -554,7 +554,13 @@ def _validate_unix_arg0_alias(*,trusted_binary_path: str | None = None,) -> None:- metadata = path.lstat()+ try:+ metadata = path.lstat()+ except OSError as exc:+ # Transiently unreadable, not proven-broken (see the sibling wraps).+ raise CodexSubscriptionInspectionFailed(+ "The dedicated Codex voice profile runtime could not be inspected."+ ) from excif not stat.S_ISLNK(metadata.st_mode):raise CodexSubscriptionUnavailable("The dedicated Codex voice profile contains an invalid runtime alias."@@ -841,11 +847,13 @@ def _rebuild_invalid_subscription_home() -> None:) from exccandidate = root / _SUBSCRIPTION_HOME_DIRNAMEtry:- if candidate.is_symlink():+ if not candidate.exists() and not candidate.is_symlink():+ return+ if _is_link_or_reparse(candidate):+ # Detach the link/junction itself; never follow it.candidate.unlink()return- if candidate.exists():- shutil.rmtree(candidate)+ shutil.rmtree(candidate)except OSError as exc:raise CodexSubscriptionUnavailable("The invalid Codex voice profile could not be removed. Delete the "@@ -862,9 +870,25 @@ def _prepare_subscription_login_home() -> Path:raiseexcept CodexSubscriptionUnavailable:# The profile is invalid and the user explicitly asked for a fresh- # login — rebuild the Jarvis-owned directory from scratch.+ # login — rebuild the Jarvis-owned directory from scratch. The short+ # retry rides out Windows' delete-pending window (an indexer or AV+ # briefly holding the freshly removed directory open)._rebuild_invalid_subscription_home()- home = _validated_subscription_home(create=True, require_marker=False)+ last_error: CodexSubscriptionUnavailable | None = None+ for _attempt in range(3):+ try:+ home = _validated_subscription_home(+ create=True, require_marker=False+ )+ break+ except CodexSubscriptionUnavailable as exc: # Retried: Windows delete-pending briefly blocks the recreate.+ last_error = exc+ time.sleep(0.2)+ else:+ raise CodexSubscriptionUnavailable(+ "The Codex voice profile could not be rebuilt. "+ "Try Connect again in a moment."+ ) from last_errormarker = home / _SUBSCRIPTION_PROFILE_MARKERauth_file = home / "auth.json"if not marker.exists() and auth_file.exists():@@ -2003,10 +2027,13 @@ class CodexAppServerClient:# the LIVE call path, so a plan that turns unsupported after# activation still flips every status surface to the sticky# diagnosis instead of leaving them all claiming "ready".- # Off-loop: the helper takes the login mutex, which worker- # threads may hold across filesystem work.- await asyncio.to_thread(- set_codex_subscription_activation_block, str(exc)+ # Off-loop and shielded like its cold-start and warm-path+ # siblings: an activation timeout must not drop the queued+ # recording job.+ await asyncio.shield(+ asyncio.to_thread(+ set_codex_subscription_activation_block, str(exc)+ ))await self._close_process(CodexAppServerDisconnected(@@ -3468,6 +3495,26 @@ def _reserve_subscription_transport(client: CodexAppServerClient) -> int:return _subscription_transport_epoch+def _force_drop_subscription_transport(client: CodexAppServerClient) -> None:+ """Unconditionally drop a dead client's reservation (no epoch check).++ Safe ONLY for a client whose owner loop is closed: it can never reserve+ again, and no other client can hold the reservation while its id is in+ the set. Without this, a close that nulled the epoch before its loop died+ left the profile permanently "starting" with login/logout refused.+ """+ global _subscription_transport_process_lock++ with _subscription_login_lock:+ _subscription_active_transports.discard(id(client))+ if not _subscription_active_transports:+ process_lock = _subscription_transport_process_lock+ _subscription_transport_process_lock = None+ if process_lock is not None:+ process_lock.close()+ _subscription_state_changed.notify_all()++def _release_subscription_transport(client: CodexAppServerClient, epoch: int) -> None:@@ -3915,7 +3962,12 @@ def _delete_codex_subscription_auth_locked() -> tuple[bool, str | None]:auth_file = home / "auth.json"if not auth_file.exists() and not auth_file.is_symlink():return True, None- _validate_regular_private_file(auth_file)+ try:+ _validate_regular_private_file(auth_file)+ except CodexSubscriptionInspectionFailed as exc:+ # Same contract as the profile-level branch above: transiently+ # unreadable refuses honestly instead of escaping as a raw error.+ return False, f"{exc} Try again in a moment."try:auth_file.unlink()except OSError as exc: # Return a path-free deletion error to the authenticated caller.@@ -3924,7 +3976,15 @@ def _delete_codex_subscription_auth_locked() -> tuple[bool, str | None]:"Dedicated subscription credentials could not be removed "f"({type(exc).__name__}).",)- _validated_subscription_home(create=False, require_marker=True)+ try:+ _validated_subscription_home(create=False, require_marker=True)+ except CodexSubscriptionUnavailable: # noqa: S110 - the logout already succeeded; this recheck is advisory.+ # The credential IS deleted — reporting failure here would show a+ # 409 for a logout that actually happened.+ log.warning(+ "Post-logout profile revalidation failed; the login file is gone",+ exc_info=True,+ )return True, None@@ -4140,17 +4200,14 @@ async def close_shared_codex_app_servers() -> None:orphan_tree.close()with suppress(Exception):client._close_lifeline()- epoch = client._profile_transport_epoch+ # Unconditional: a close that nulled the epoch before its+ # loop died would otherwise leave the reservation forever.client._profile_transport_epoch = None- if epoch is not None:- # Shielded like every other epoch release: a cancellation- # after the attribute was nulled must not strand the- # reservation.- await asyncio.shield(- asyncio.to_thread(- _release_subscription_transport, client, epoch- )+ await asyncio.shield(+ asyncio.to_thread(+ _force_drop_subscription_transport, client)+ )else:raise CodexSubscriptionUnavailable("A Codex app-server owner loop is unavailable for safe shutdown."diff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsxindex 42c1150aff..2674f0969e 100644--- a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx+++ b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx@@ -125,12 +125,16 @@ function codexRealtimeCard(};}-function renderCard(descriptor: ProviderDescriptor, onChanged: () => void = () => {}) {+function renderCard(+ descriptor: ProviderDescriptor,+ onChanged: () => void = () => {},+ onActivateOptimistic: (tier: string, id: string) => void = () => {},+) {return render(<ProviderCarddescriptor={descriptor}onChanged={onChanged}- onActivateOptimistic={() => {}}+ onActivateOptimistic={onActivateOptimistic}autoActivateOnSave={false}/>,);@@ -465,7 +469,7 @@ describe("ProviderCard: ChatGPT subscription Realtime", () => {expect(screen.queryByText("npm i -g @openai/codex")).toBeNull();expect(screen.queryByText(- "The protected Codex voice profile needs attention. Review the setup guide, then reconnect.",+ "The protected Codex voice profile is no longer valid. Connect with ChatGPT rebuilds it fresh.",),).toBeNull();// The state chip next to the provider name must not shout "missing" (red)@@ -505,7 +509,7 @@ describe("ProviderCard: ChatGPT subscription Realtime", () => {expect(screen.getByText(- "The protected Codex voice profile needs attention. Review the setup guide, then reconnect.",+ "The protected Codex voice profile is no longer valid. Connect with ChatGPT rebuilds it fresh.",),).toBeTruthy();const detail = screen.getByTestId("codex-setup-detail").textContent ?? "";@@ -756,7 +760,8 @@ describe("ProviderCard: ChatGPT subscription Realtime", () => {it("does not activate until the user accepts the experimental boundary", async () => {const calls = installFetchMock();vi.spyOn(window, "confirm").mockReturnValue(false);- renderCard(codexRealtimeCard());+ const optimistic = vi.fn();+ renderCard(codexRealtimeCard(), () => {}, optimistic);fireEvent.click(screen.getByText("ChatGPT subscription (Codex)"));@@ -767,5 +772,25 @@ describe("ProviderCard: ChatGPT subscription Realtime", () => {candidate.method === "POST" && candidate.url === "/api/realtime/switch",),).toBe(false);+ // The consent dialog comes BEFORE the optimistic radio flip: a declined+ // dialog used to leave the highlight stuck on the new card with no+ // refetch to roll it back.+ expect(optimistic).not.toHaveBeenCalled();+ });++ it("flips the radio optimistically only after the consent is accepted", async () => {+ installFetchMock();+ vi.spyOn(window, "confirm").mockReturnValue(true);+ const optimistic = vi.fn();+ renderCard(codexRealtimeCard(), () => {}, optimistic);++ fireEvent.click(screen.getByText("ChatGPT subscription (Codex)"));++ await waitFor(() =>+ expect(optimistic).toHaveBeenCalledWith(+ "realtime",+ "codex-subscription-realtime",+ ),+ );});});diff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsxindex c6b404f80a..d12b588e76 100644--- a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx+++ b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx@@ -1872,9 +1872,11 @@ function CodexAuthWidget({{t("apikeys_codex.install_codex")}</a></Button>- {/* A plan-refused login is stored but unusable — offer the exit even- though the connected panel (with its Disconnect) never renders. */}- {status?.reason_code === "plan_unsupported" && (+ {/* A plan-refused or invalid profile is stored but unusable — offer+ the in-app exit the backend implements, even though the connected+ panel (with its Disconnect) never renders in these states. */}+ {(status?.reason_code === "plan_unsupported" ||+ status?.reason_code === "setup_invalid") && (<Buttonsize="sm"variant="ghost"diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 4e09deff32..2c7d75921d 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -1909,7 +1909,7 @@"status_login_required": "Verbinde dein ChatGPT-Abo, um diesen Sprachanbieter zu nutzen.","status_not_installed": "Installiere zuerst die unterstützte Codex-Version und verbinde danach ChatGPT.","status_lifecycle_unavailable": "Subscription Voice ist auf diesem Betriebssystem noch nicht verfügbar. API Realtime und Standard-Voice funktionieren weiterhin.",- "status_setup_invalid": "Das geschützte Codex-Sprachprofil braucht Aufmerksamkeit. Prüfe die Anleitung und verbinde es danach neu.",+ "status_setup_invalid": "Das geschützte Codex-Sprachprofil ist nicht mehr gültig. \"Mit ChatGPT verbinden\" baut es neu auf.","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.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 05138c69cb..a7530608fb 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -1910,7 +1910,7 @@"status_login_required": "Connect your ChatGPT subscription to use this voice provider.","status_not_installed": "Install the supported Codex version before connecting ChatGPT.","status_lifecycle_unavailable": "Subscription voice is not yet available on this operating system. API Realtime and standard voice still work.",- "status_setup_invalid": "The protected Codex voice profile needs attention. Review the setup guide, then reconnect.",+ "status_setup_invalid": "The protected Codex voice profile is no longer valid. Connect with ChatGPT rebuilds it fresh.","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.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex ae4ce413ce..b758885d9a 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -1909,7 +1909,7 @@"status_login_required": "Conecta tu suscripción de ChatGPT para usar este proveedor de voz.","status_not_installed": "Instala la versión compatible de Codex antes de conectar ChatGPT.","status_lifecycle_unavailable": "La voz por suscripción aún no está disponible en este sistema operativo. API Realtime y la voz estándar siguen funcionando.",- "status_setup_invalid": "El perfil protegido de voz de Codex necesita atención. Revisa la guía de configuración y vuelve a conectarlo.",+ "status_setup_invalid": "El perfil protegido de voz de Codex ya no es válido. \"Conectar con ChatGPT\" lo reconstruye desde cero.","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.",diff --git a/tests/unit/ui/test_provider_spec_codex_subscription_realtime.py b/tests/unit/ui/test_provider_spec_codex_subscription_realtime.pyindex ec0038d84f..3ec3c8741b 100644--- a/tests/unit/ui/test_provider_spec_codex_subscription_realtime.py+++ b/tests/unit/ui/test_provider_spec_codex_subscription_realtime.py@@ -687,10 +687,35 @@ async def test_section_health_reports_login_in_progress_as_unknown(assert health.reason == "login_in_progress"+ ("reason_code", "message", "expected_fragment"),+ [+ (+ "plan_unsupported",+ "Subscription voice permits only personal ChatGPT accounts.",+ "personal ChatGPT accounts",+ ),+ (+ "lifecycle_unavailable",+ "Interactive subscription-voice login is unavailable on headless Linux.",+ "headless Linux",+ ),+ (+ "not_installed",+ "Subscription voice requires Codex CLI 0.146.0.",+ "requires Codex CLI 0.146.0",+ ),+ ],+)@pytest.mark.asyncio-async def test_section_health_names_the_plan_as_the_blocker(+async def test_section_health_hover_names_the_real_remedy(monkeypatch: pytest.MonkeyPatch,+ reason_code: str,+ message: str,+ expected_fragment: str,) -> None:+ """The amber dot's hover must never say "not connected or configured"+ when the actual remedy is a plan change, another host, or an install."""spec = get_spec("codex-subscription-realtime")assert spec is not Nonemonkeypatch.setattr(@@ -700,8 +725,8 @@ async def test_section_health_names_the_plan_as_the_blocker("installed": True,"connected": False,"mode": "not_connected",- "message": "Subscription voice permits only personal ChatGPT accounts.",- "reason_code": "plan_unsupported",+ "message": message,+ "reason_code": reason_code,},)@@ -710,9 +735,9 @@ async def test_section_health_names_the_plan_as_the_blocker()assert health.status == "needs_setup"- assert health.reason == "plan_unsupported"- # The hover detail names the actual blocker, not "not connected".- assert "personal ChatGPT accounts" in health.detail+ assert health.reason == reason_code+ assert expected_fragment in health.detail+ assert "not connected or configured" not in health.detail@pytest.mark.asyncio