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 the round-5 activation-path findings
Ruben Lütke31d92f82c312
diff --git a/jarvis/codex_app_server.py b/jarvis/codex_app_server.pyindex 05b10dfdc4..f3b6e0e355 100644--- a/jarvis/codex_app_server.py+++ b/jarvis/codex_app_server.py@@ -240,6 +240,15 @@ class CodexSubscriptionPlanUnsupported(CodexSubscriptionUnavailable):"""+class CodexSubscriptionInspectionFailed(CodexSubscriptionUnavailable):+ """An OS read error prevented judging the profile — transiently unknown.++ Distinct from a genuinely invalid profile: an antivirus-locked directory+ or a slow disk must surface as ``busy`` ("checking"), never as "create a+ fresh voice-only login".+ """++class CodexAppServerDisconnected(CodexAppServerError):"""The app-server process exited or its JSONL stream broke."""@@ -559,7 +568,7 @@ def _validate_arg0_runtime_dir(try:children = {entry.name: entry for entry in path.iterdir()}except OSError as exc:- raise CodexSubscriptionUnavailable(+ raise CodexSubscriptionInspectionFailed("The dedicated Codex voice profile runtime could not be inspected.") from excexpected = {".lock"}@@ -646,7 +655,7 @@ def _validate_codex_runtime_state(try:runtime_children = {entry.name: entry for entry in runtime_root.iterdir()}except OSError as exc:- raise CodexSubscriptionUnavailable(+ raise CodexSubscriptionInspectionFailed("The dedicated Codex voice runtime could not be inspected.") from excif set(runtime_children) != {"arg0"}:@@ -661,7 +670,7 @@ def _validate_codex_runtime_state(try:process_dirs = tuple(arg0_root.iterdir())except OSError as exc:- raise CodexSubscriptionUnavailable(+ raise CodexSubscriptionInspectionFailed("The dedicated Codex voice runtime could not be inspected.") from excif len(process_dirs) > _MAX_ARG0_RUNTIME_DIRS:@@ -709,7 +718,7 @@ def _validated_subscription_home(try:canonical_root = root.resolve(strict=True)except OSError as exc:- raise CodexSubscriptionUnavailable(+ raise CodexSubscriptionInspectionFailed("Jarvis's private data directory could not be verified.") from exccandidate = canonical_root / _SUBSCRIPTION_HOME_DIRNAME@@ -738,7 +747,7 @@ def _validated_subscription_home(try:entries = tuple(canonical_home.iterdir())except OSError as exc:- raise CodexSubscriptionUnavailable(+ raise CodexSubscriptionInspectionFailed("The dedicated Codex voice profile could not be inspected.") from excunexpected = [@@ -763,7 +772,7 @@ def _validated_subscription_home(try:oversized = entry.stat().st_size > 4096except OSError as exc:- raise CodexSubscriptionUnavailable(+ raise CodexSubscriptionInspectionFailed("The dedicated Codex voice profile could not be inspected.") from excif oversized:@@ -1143,6 +1152,17 @@ def _read_codex_capability(binary_path: str | None) -> CodexAppServerCapability:reason=str(exc),reason_code=_login_required_reason_code(),)+ except CodexSubscriptionInspectionFailed as exc:+ # An OS read hiccup is transiently unknown, never a proven-broken+ # profile that tells the user to recreate their login.+ return CodexAppServerCapability(+ available=False,+ chatgpt_authenticated=False,+ binary_path=resolved_binary,+ version=version,+ reason=f"{exc} Retrying shortly.",+ reason_code="busy",+ )except CodexSubscriptionUnavailable as exc: # Unsafe profile state becomes a status snapshot.return CodexAppServerCapability(available=False,@@ -1182,6 +1202,16 @@ def _read_codex_capability(binary_path: str | None) -> CodexAppServerCapability:reason=str(exc),reason_code=_login_required_reason_code(),)+ except CodexSubscriptionInspectionFailed as exc:+ # Transiently unreadable, not proven-broken (see the first block).+ return CodexAppServerCapability(+ available=False,+ chatgpt_authenticated=False,+ binary_path=resolved_binary,+ version=version,+ reason=f"{exc} Retrying shortly.",+ reason_code="busy",+ )except CodexSubscriptionUnavailable as exc: # Profile validation failure is returned to the UI.return CodexAppServerCapability(available=False,@@ -1723,6 +1753,11 @@ class CodexAppServerClient:reserve_future = asyncio.get_running_loop().run_in_executor(None, _reserve)+ # A cancelled awaiter leaves the worker's exception unretrieved;+ # consume it so asyncio does not log a spurious GC error.+ reserve_future.add_done_callback(+ lambda f: None if f.cancelled() else f.exception()+ )try:await asyncio.shield(reserve_future)except asyncio.CancelledError:@@ -1733,12 +1768,17 @@ class CodexAppServerClient:self._profile_transport_epoch = Noneif 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()+ try:+ threading.Thread(+ target=_release_subscription_transport,+ args=(self, epoch),+ name="codex-reserve-abandon",+ daemon=True,+ ).start()+ except RuntimeError:+ # Thread exhaustion: a brief inline release beats+ # leaking the reservation until restart.+ _release_subscription_transport(self, epoch)raiseasync def _release_after_failure() -> None:@@ -1868,7 +1908,11 @@ 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".- set_codex_subscription_activation_block(str(exc))+ # 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)+ )await self._close_process(CodexAppServerDisconnected("Codex app-server authentication is not ChatGPT."@@ -2989,48 +3033,57 @@ class CodexAppServerClient:with suppress(Exception):stdin.close()- current = asyncio.current_task()- tasks = [- task- for task in (reader_task, stderr_task)- if task is not None and task is not current and not task.done()- ]- for task in tasks:- task.cancel()- if tasks:- await asyncio.gather(*tasks, return_exceptions=True)-- if process.returncode is None:- # EOF is Codex's graceful app-server shutdown path. Give its- # Arg0PathEntryGuard time to remove the locked tmp/arg0 directory- # before terminating the contained tree.- with suppress(TimeoutError):- await asyncio.wait_for(- process.wait(), timeout=_SHUTDOWN_TIMEOUT_S- )- if process.returncode is None:- with suppress(ProcessLookupError, OSError):- process.terminate()- try:- await asyncio.wait_for(process.wait(), timeout=_SHUTDOWN_TIMEOUT_S)- except TimeoutError: # The grace expired, so hard-kill the contained tree.+ # Everything past stdin-close awaits repeatedly; a SECOND cancellation+ # landing on any of those awaits must still run the resource cleanup+ # (job-object handle, lifeline FD, reservation epoch) — hence the+ # try/finally around the whole reaping tail.+ try:+ current = asyncio.current_task()+ tasks = [+ task+ for task in (reader_task, stderr_task)+ if task is not None and task is not current and not task.done()+ ]+ for task in tasks:+ task.cancel()+ if tasks:+ await asyncio.gather(*tasks, return_exceptions=True)++ if process.returncode is None:+ # EOF is Codex's graceful app-server shutdown path. Give its+ # Arg0PathEntryGuard time to remove the locked tmp/arg0+ # directory before terminating the contained tree.+ with suppress(TimeoutError):+ await asyncio.wait_for(+ process.wait(), timeout=_SHUTDOWN_TIMEOUT_S+ )+ if process.returncode is None:with suppress(ProcessLookupError, OSError):- process.kill()+ process.terminate()+ try:+ await asyncio.wait_for(process.wait(), timeout=_SHUTDOWN_TIMEOUT_S)+ except TimeoutError: # The grace expired, so hard-kill the contained tree.+ with suppress(ProcessLookupError, OSError):+ process.kill()with suppress(Exception):await asyncio.wait_for(process.wait(), timeout=_SHUTDOWN_TIMEOUT_S)- if tree is not None:- tree.close()- self._close_lifeline()- 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).- epoch = self._profile_transport_epoch- self._profile_transport_epoch = None- await asyncio.shield(- asyncio.to_thread(_release_subscription_transport, self, epoch)- )- if not expected:- log.warning("Codex app-server connection reset")+ finally:+ # Sync resource cleanup first (safe under any cancellation), the+ # awaited release last: its shield keeps the queued job alive even+ # if this await is interrupted again.+ if tree is not None:+ tree.close()+ self._close_lifeline()+ 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).+ epoch = self._profile_transport_epoch+ self._profile_transport_epoch = None+ await asyncio.shield(+ asyncio.to_thread(_release_subscription_transport, self, epoch)+ )+ if not expected:+ log.warning("Codex app-server connection reset")async def close(self) -> None:"""Reap the app-server tree and release local temporary state."""@@ -3851,6 +3904,11 @@ async def disconnect_and_logout_codex_subscription(_finish_subscription_disconnect_mutation()claim_future = asyncio.get_running_loop().run_in_executor(None, _claim)+ # A cancelled awaiter leaves the worker's exception unretrieved; consume+ # it so asyncio does not log a spurious GC error.+ claim_future.add_done_callback(+ lambda f: None if f.cancelled() else f.exception()+ )try:await asyncio.shield(claim_future)await asyncio.shield(close_shared_codex_app_servers())@@ -3898,6 +3956,20 @@ async def close_shared_codex_app_servers() -> None:elif owner_loop.is_running():future = asyncio.run_coroutine_threadsafe(client.close(), owner_loop)await asyncio.wrap_future(future)+ elif owner_loop.is_closed():+ # The owner loop is gone for good; this entry can never be+ # closed properly again. Escalating forever would make every+ # later logout answer 409 for the process lifetime — drop the+ # entry and free its reservation best-effort instead.+ log.warning(+ "Dropping Codex app-server entry whose owner loop is closed"+ )+ epoch = client._profile_transport_epoch+ client._profile_transport_epoch = None+ if epoch is not None:+ await asyncio.to_thread(+ _release_subscription_transport, client, epoch+ )else:raise CodexSubscriptionUnavailable("A Codex app-server owner loop is unavailable for safe shutdown."@@ -3928,8 +4000,10 @@ __all__ = ["CodexSubscriptionProfileMissing","CodexSubscriptionContainmentUnavailable","CodexSubscriptionBinaryUnsupported",+ "CodexSubscriptionInspectionFailed","CodexSubscriptionPlanUnsupported","CodexSubscriptionUnavailable",+ "CODEX_SUBSCRIPTION_REASON_CODES","codex_subscription_activation_block","set_codex_subscription_activation_block","codex_subscription_auth_snapshot",diff --git a/jarvis/plugins/realtime/codex_subscription.py b/jarvis/plugins/realtime/codex_subscription.pyindex 972954a42e..2360e95ca6 100644--- a/jarvis/plugins/realtime/codex_subscription.py+++ b/jarvis/plugins/realtime/codex_subscription.py@@ -716,12 +716,22 @@ class CodexSubscriptionRealtimeProvider:@classmethodasync def verify_activation(cls, cfg: Any) -> None:- """Run the provider's authoritative account/config activation gate."""+ """Run the provider's authoritative account/config activation gate.++ The gate starts app-server just to judge the account, so it must also+ clean up after itself: leaving the transport reservation and an idle+ Codex child running would make the card's reconnect button answer+ "disconnect active subscription voice" after every activation. A call+ that starts later simply re-runs ``ensure_started``.+ """app_server_module = importlib.import_module("jarvis.codex_app_server")codex_cfg = getattr(cfg, "codex", None)binary_path = str(getattr(codex_cfg, "binary_path", "") or "").strip() or Noneclient = app_server_module.get_shared_codex_app_server(binary_path)- await client.require_chatgpt_login()+ try:+ await client.require_chatgpt_login()+ finally:+ await client.close()requires_webrtc_offer = Trueinput_sample_rate = _INPUT_RATEoutput_sample_rate = _OUTPUT_RATEdiff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.pyindex 337e50401e..9132c443ee 100644--- a/jarvis/ui/web/provider_routes.py+++ b/jarvis/ui/web/provider_routes.py@@ -3821,7 +3821,22 @@ async def realtime_switch(body: SwitchBody, request: Request) -> dict[str, Any]:"it in the browser window, then activate."),)- credential_present = bool(codex_payload.get("connected"))+ if codex_payload.get("reason_code") != "plan_unsupported" and not (+ codex_payload.get("connected")+ ):+ # Answer with the payload's precise diagnosis — the generic "no+ # configured credentials" would be wrong for most codex states.+ raise HTTPException(+ status_code=409,+ detail=str(+ codex_payload.get("message")+ or "Connect the dedicated ChatGPT subscription voice login."+ ),+ )+ # plan_unsupported deliberately passes through: verify_activation+ # re-judges the LIVE account, which is the only way the sticky block+ # can clear when the plan changed back.+ credential_present = Trueelse:credential_present = await _provider_credential_present_async(spec, request)if not credential_present:@@ -3864,8 +3879,10 @@ async def realtime_switch(body: SwitchBody, request: Request) -> dict[str, Any]: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)+ # A passed activation is the proof the account works again. 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, None)if body.persist:try:diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.pyindex 4d1e5f969c..352992eb42 100644--- a/jarvis/ui/web/settings_routes.py+++ b/jarvis/ui/web/settings_routes.py@@ -312,9 +312,14 @@ async def put_voice_mode(body: VoiceModeBody, request: Request) -> dict[str, obj),)if not payload.get("connected"):+ # The payload's precise diagnosis (plan refused, login+ # required, …) beats the generic sentence.raise HTTPException(status_code=400,- detail="no realtime provider is configured and ready",+ detail=str(+ payload.get("message")+ or "no realtime provider is configured and ready"+ ),)if cfg is not None and getattr(cfg, "voice", None) is not None:diff --git a/tests/unit/codex_app_server/test_transport.py b/tests/unit/codex_app_server/test_transport.pyindex e455f10b3b..5ab0223b7c 100644--- a/tests/unit/codex_app_server/test_transport.py+++ b/tests/unit/codex_app_server/test_transport.py@@ -2410,6 +2410,42 @@ async def test_live_account_gate_records_the_plan_block()+def test_unreadable_profile_reports_busy_not_setup_invalid(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """An antivirus-locked or slow-disk profile read is transiently unknown —+ never 'create a fresh voice-only login'."""+ import jarvis.codex_auth as auth_module++ class FakeAuthService:+ def __init__(self, *_args: object, **_kwargs: object) -> None:+ pass++ def _resolve_binary(self) -> str:+ return "codex-test"++ def _probe_version(self, _binary: str) -> str:+ return "codex-cli 0.146.0"++ def unreadable(**_kwargs: object) -> Path:+ raise transport.CodexSubscriptionInspectionFailed(+ "The dedicated Codex voice profile could not be inspected."+ )++ monkeypatch.setattr(auth_module, "CodexAuthService", FakeAuthService)+ monkeypatch.setattr(+ transport,+ "_trusted_native_codex_binary",+ lambda binary, _version: binary,+ )+ monkeypatch.setattr(transport, "_validated_subscription_home", unreadable)++ capability = transport._read_codex_capability(None)++ assert capability.reason_code == "busy"+ assert "could not be inspected" in capability.reason++def test_activation_block_sticks_until_invalidated() -> None:transport.set_codex_subscription_activation_block("Subscription voice permits only personal ChatGPT accounts."diff --git a/tests/unit/realtime/test_codex_subscription.py b/tests/unit/realtime/test_codex_subscription.pyindex c4bc1562cc..988ca2273f 100644--- a/tests/unit/realtime/test_codex_subscription.py+++ b/tests/unit/realtime/test_codex_subscription.py@@ -318,6 +318,35 @@ async def test_orchestrator_capability_check_does_not_repeat_cli_auth_probe(assert await provider.can_open_duplex_session() is True+async def test_verify_activation_cleans_up_its_own_transport(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The gate starts app-server only to judge the account; leaving the+ reservation and an idle child running would 409 the card's reconnect+ button after every activation."""+ from jarvis import codex_app_server++ events: list[str] = []++ class _Client:+ async def require_chatgpt_login(self) -> None:+ events.append("verified")++ async def close(self) -> None:+ events.append("closed")++ monkeypatch.setattr(+ codex_app_server,+ "get_shared_codex_app_server",+ lambda _binary: _Client(),+ )++ await CodexSubscriptionRealtimeProvider.verify_activation(SimpleNamespace())++ assert events == ["verified", "closed"]++@pytest.mark.parametrize(("reason_code", "available", "authenticated", "expected"),[diff --git a/tests/unit/ui/test_provider_spec_codex_subscription_realtime.py b/tests/unit/ui/test_provider_spec_codex_subscription_realtime.pyindex 8c2ed8d000..ec0038d84f 100644--- a/tests/unit/ui/test_provider_spec_codex_subscription_realtime.py+++ b/tests/unit/ui/test_provider_spec_codex_subscription_realtime.py@@ -204,7 +204,62 @@ async def test_realtime_activation_rejects_codex_api_key_mode()assert caught.value.status_code == 409- assert "Connect or configure this provider first" in str(caught.value.detail)+ # The precise payload diagnosis, never the generic credential sentence.+ assert "dedicated ChatGPT subscription voice login" in str(caught.value.detail)+++async def test_plan_unsupported_activation_retries_the_live_gate(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """plan_unsupported must reach verify_activation (the only path that can+ CLEAR the sticky block) and answer with the plan diagnosis on re-refusal."""+ import jarvis.core.registry as registry+ from jarvis.codex_app_server import CodexSubscriptionPlanUnsupported++ monkeypatch.setattr(routes, "_codex_binary_path", lambda *_args: "codex")+ monkeypatch.setattr(+ routes,+ "_codex_subscription_status_payload",+ lambda _binary_path: {+ "installed": True,+ "connected": False,+ "mode": "not_connected",+ "message": "Subscription voice permits only personal ChatGPT accounts.",+ "reason_code": "plan_unsupported",+ },+ )++ gate_calls: list[object] = []++ class _Provider:+ @classmethod+ async def verify_activation(cls, cfg: object) -> None:+ gate_calls.append(cfg)+ raise CodexSubscriptionPlanUnsupported(+ "Subscription voice permits only personal ChatGPT accounts."+ )++ monkeypatch.setattr(registry, "load", lambda *_args, **_kwargs: _Provider)++ request = SimpleNamespace(+ app=SimpleNamespace(state=SimpleNamespace(config=None, cfg=None))+ )+ with pytest.raises(HTTPException) as caught:+ await routes.realtime_switch(+ routes.SwitchBody(+ provider="codex-subscription-realtime",+ persist=False,+ accept_experimental=True,+ ),+ request,+ )++ assert gate_calls, "the live gate must re-judge a plan-blocked account"+ assert caught.value.status_code == 409+ detail = str(caught.value.detail)+ assert "personal ChatGPT accounts" in detail+ assert "no configured credentials" not in detail@pytest.mark.asyncio