Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(realtime): keep login verification honest and gate startup history

rubenluetke10-beep461cae11229a
diff --git a/jarvis/codex_app_server.py b/jarvis/codex_app_server.py
index 2842e24862..985fd7ca3f 100644
--- a/jarvis/codex_app_server.py
+++ b/jarvis/codex_app_server.py
@@ -2702,9 +2702,26 @@ class CodexAppServerClient:
# The verify pass just proved the account; completing the FULL startup
# audit here (off the wake critical path) lets one wake word inside
# the ride TTL skip the byte-identical re-audit in ``thread_start``.
- await self.prime_startup_audit()
+ # Priming is a pure wake-latency optimization on top of a login that
+ # was JUST proven, so it is best-effort: any failure short of the
+ # unambiguous entitlement loss below is logged and dropped — it never
+ # fails the login result or closes the just-verified process, and the
+ # next wake word simply pays the full audit in ``thread_start``.
+ try:
+ await self.prime_startup_audit(best_effort=True)
+ except CodexSubscriptionPlanUnsupported:
+ # The audit's own live account re-read refused the plan — a real
+ # entitlement loss, recorded sticky where it was discovered. The
+ # login result must report it, exactly like the gate above.
+ raise
+ except Exception:
+ log.warning(
+ "Codex warm-audit priming failed after a proven login; "
+ "skipping the wake ride (the next wake word re-audits in full)",
+ exc_info=True,
+ )
- async def prime_startup_audit(self) -> None:
+ async def prime_startup_audit(self, *, best_effort: bool = False) -> None:
"""Complete the full startup audit now and mint the one-shot wake ride.
Runs the byte-identical audit ``thread_start`` performs (profile walk,
@@ -2717,6 +2734,12 @@ class CodexAppServerClient:
ever minted from an audit that actually completed — this method never
skips or weakens any check, it only moves the identical work off the
wake critical path.
+
+ With ``best_effort=True`` (the ``require_chatgpt_login`` warm path) a
+ refusal other than the permanently-recorded plan loss leaves the live
+ process untouched and re-raises for the caller to log-and-drop: the
+ account was proven moments earlier, so an ambiguous refusal must not
+ tear down a just-verified process over a wake-latency optimization.
"""
await self.ensure_started()
async with self._thread_start_lock:
@@ -2752,6 +2775,14 @@ class CodexAppServerClient:
await asyncio.shield(
asyncio.to_thread(set_codex_subscription_activation_block, str(exc))
)
+ elif best_effort:
+ # Ambiguous between a transient hiccup (an antivirus-locked
+ # profile directory, a config read racing a restart) and a
+ # real state change — and the account was proven moments
+ # ago. Keep the just-verified process alive and re-raise
+ # for the caller to log-and-drop; the next wake word
+ # re-audits in full.
+ raise
error = type(exc)(str(exc))
await self._close_process(
CodexAppServerDisconnected("Codex app-server safety state changed."),
@@ -3842,6 +3873,20 @@ class CodexAppServerClient:
"thread/unsubscribe", {"threadId": thread_id}
)
+ def realtime_start_instructions_supported(self) -> bool:
+ """Whether ``realtimeStartInstructions`` will actually be transmitted.
+
+ Cheap, synchronous capability probe for the adapter layer, derived
+ from the same trusted-binary gate ``realtime_start`` applies before
+ sending any 0.147-audited field: ``True`` only when this client is
+ bound to the audited 0.147.0 binary, whose schema accepts the field
+ (per call, ``realtime_start`` additionally requires the audited v3
+ protocol). This is the adapter's basis for deciding whether to blank
+ its fallback prompt — when the field would be withheld, the fallback
+ must stay in place instead.
+ """
+ return self._trusted_binary_version == _SUPPORTED_CODEX_VERSION
+
async def realtime_start(
self,
thread_id: str,
@@ -3900,15 +3945,28 @@ class CodexAppServerClient:
"prompt": start_prompt,
"threadId": thread_id,
}
- if startup_items:
- params["initialItems"] = startup_items
# Added in audited 0.147.0. Older approved binaries must not receive an
# unknown field, while 0.147 explicitly suppresses the automatic
# delegation acknowledgement that otherwise speaks over Jarvis.
- if (
+ trusted_current_binary = (
version == "v3"
and self._trusted_binary_version == _SUPPORTED_CODEX_VERSION
- ):
+ )
+ if startup_items:
+ if trusted_current_binary:
+ params["initialItems"] = startup_items
+ else:
+ # Same rule as the audited fields below: an older approved
+ # binary must never receive an unknown field. A thread rebuild
+ # on 0.146 restores the call without its history instead of
+ # failing the whole start on serde.
+ log.warning(
+ "Codex realtime start dropped initialItems (%d startup-history "
+ "items) for this binary: the field exists only in the audited "
+ "0.147.0 release.",
+ len(startup_items),
+ )
+ if trusted_current_binary:
params["delegationAckFiller"] = False
# Same 0.147/v3 gate for the caller-provided audited fields: the
# start/end instruction slots and the codexResponse* handoff
diff --git a/tests/unit/test_codex_app_server_warm_ride.py b/tests/unit/test_codex_app_server_warm_ride.py
index aecd31c306..e71c445aa2 100644
--- a/tests/unit/test_codex_app_server_warm_ride.py
+++ b/tests/unit/test_codex_app_server_warm_ride.py
@@ -11,6 +11,7 @@ from __future__ import annotations
import asyncio
import json
+import logging
import time
from collections.abc import Callable
from pathlib import Path
@@ -523,6 +524,175 @@ async def test_realtime_start_never_sends_audited_fields_to_an_untrusted_binary(
await client.close()
+# --- (d) best-effort warm-audit priming inside the login gate ---------------
+
+
+def _fail_config_requirements_after(first_ok: int) -> Callable[[FakeProcess, dict[str, Any]], None]:
+ """Responder whose ``configRequirements/read`` errors after ``first_ok`` calls."""
+ seen = {"count": 0}
+
+ def responder(process: FakeProcess, message: dict[str, Any]) -> None:
+ request_id = message.get("id")
+ if not isinstance(request_id, int):
+ return
+ if message.get("method") == "configRequirements/read":
+ seen["count"] += 1
+ if seen["count"] > first_ok:
+ asyncio.get_running_loop().call_soon(
+ process.emit,
+ {
+ "id": request_id,
+ "error": {"code": -32000, "message": "transient hiccup"},
+ },
+ )
+ return
+ _default_responder(process, message)
+
+ return responder
+
+
+async def test_login_survives_a_transient_rpc_failure_in_warm_audit_priming(
+ monkeypatch: pytest.MonkeyPatch,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ """A transient RPC error inside the priming audit must not fail the login
+ result or touch the just-verified live process — only a WARNING is left."""
+ harness = SpawnHarness(monkeypatch, _fail_config_requirements_after(first_ok=1))
+ client = CodexAppServerClient()
+
+ # Cold start audits in full (its configRequirements/read succeeds).
+ await client.ensure_started()
+ _age_stamp(client)
+ client._warm_audit_process = None
+ client._warm_audit_at = 0.0
+
+ with caplog.at_level(logging.WARNING, logger="jarvis.codex_app_server"):
+ await client.require_chatgpt_login()
+
+ assert client.running is True
+ assert harness.processes[0].returncode is None
+ assert any(
+ "warm-audit priming failed" in record.getMessage()
+ for record in caplog.records
+ if record.levelno == logging.WARNING and record.exc_info is not None
+ )
+ # No ride was minted from an audit that never completed.
+ assert client._warm_audit_process is None
+ await client.close()
+
+
+async def test_login_survives_a_subscription_refusal_in_warm_audit_priming(
+ monkeypatch: pytest.MonkeyPatch,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ """A non-plan ``CodexSubscriptionUnavailable`` from the priming audit is
+ ambiguous right after a proven account: log-and-continue, never close."""
+ seen = {"count": 0}
+
+ def responder(process: FakeProcess, message: dict[str, Any]) -> None:
+ request_id = message.get("id")
+ if not isinstance(request_id, int):
+ return
+ if message.get("method") == "configRequirements/read":
+ seen["count"] += 1
+ if seen["count"] > 1:
+ # A managed-requirements payload makes the audit refuse.
+ _respond(process, request_id, {"requirements": {"managed": True}})
+ return
+ _default_responder(process, message)
+
+ harness = SpawnHarness(monkeypatch, responder)
+ client = CodexAppServerClient()
+
+ await client.ensure_started()
+ _age_stamp(client)
+ client._warm_audit_process = None
+ client._warm_audit_at = 0.0
+
+ with caplog.at_level(logging.WARNING, logger="jarvis.codex_app_server"):
+ await client.require_chatgpt_login()
+
+ assert client.running is True
+ assert harness.processes[0].returncode is None
+ assert any(
+ "warm-audit priming failed" in record.getMessage()
+ for record in caplog.records
+ if record.levelno == logging.WARNING
+ )
+ assert client._warm_audit_process is None
+ await client.close()
+
+
+# --- (e) initialItems trusted-binary gate ------------------------------------
+
+
+async def test_realtime_start_sends_initial_items_to_the_trusted_binary(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ harness = SpawnHarness(monkeypatch)
+ client = CodexAppServerClient()
+ await client.ensure_started()
+ client._trusted_binary_version = transport._SUPPORTED_CODEX_VERSION
+
+ await client.realtime_start(
+ "thread-1",
+ version="v3",
+ trusted_prompt="Contract",
+ initial_items=({"role": "user", "text": "hello"},),
+ )
+
+ params = _realtime_start_params(harness)
+ assert params["initialItems"] == [{"role": "user", "text": "hello"}]
+ await client.close()
+
+
+async def test_realtime_start_drops_initial_items_for_an_untrusted_binary(
+ monkeypatch: pytest.MonkeyPatch,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ """An older approved binary never receives the unknown ``initialItems``
+ field: a rebuild restores the call without history, with one warning."""
+ harness = SpawnHarness(monkeypatch)
+ client = CodexAppServerClient()
+ await client.ensure_started()
+ client._trusted_binary_version = transport._LEGACY_CODEX_VERSION
+
+ with caplog.at_level(logging.WARNING, logger="jarvis.codex_app_server"):
+ await client.realtime_start(
+ "thread-1",
+ version="v3",
+ trusted_prompt="Contract",
+ initial_items=({"role": "user", "text": "hello"},),
+ )
+
+ params = _realtime_start_params(harness)
+ assert "initialItems" not in params
+ dropped = [
+ record
+ for record in caplog.records
+ if record.levelno == logging.WARNING and "initialItems" in record.getMessage()
+ ]
+ assert len(dropped) == 1
+ await client.close()
+
+
+# --- (f) realtimeStartInstructions capability probe --------------------------
+
+
+def test_realtime_start_instructions_supported_tracks_the_trusted_binary() -> None:
+ client = CodexAppServerClient()
+
+ assert client.realtime_start_instructions_supported() is False
+ client._trusted_binary_version = transport._LEGACY_CODEX_VERSION
+ assert client.realtime_start_instructions_supported() is False
+ client._trusted_binary_version = transport._SUPPORTED_CODEX_VERSION
+ assert client.realtime_start_instructions_supported() is True
+
+
@pytest.mark.asyncio
async def test_realtime_start_rejects_invalid_audited_field_values() -> None:
client = CodexAppServerClient()