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(voice): stop paying a cold Codex start for a client that was already killed

rubenluetke10-beep8ba0ff1b225d
diff --git a/jarvis/codex_app_server.py b/jarvis/codex_app_server.py
index d2685b1e85..60d47700ce 100644
--- a/jarvis/codex_app_server.py
+++ b/jarvis/codex_app_server.py
@@ -117,6 +117,33 @@ _ALLOWED_SUBSCRIPTION_HOME_ENTRIES: Final = frozenset(
_SUBSCRIPTION_PROFILE_MARKER,
}
)
+# Desktop-shell droppings, not Codex state: Finder writes ``.DS_Store`` the
+# moment anyone LOOKS at the folder, Explorer writes ``Thumbs.db`` /
+# ``desktop.ini``, and copying the profile across a network share leaves
+# AppleDouble ``._`` siblings. These are ignored rather than allowlisted —
+# they carry nothing to validate, and treating one as "the profile contains
+# configuration" used to delete a working ChatGPT login on the next Connect.
+_OS_METADATA_ENTRY_NAMES: Final = frozenset(
+ {
+ ".ds_store",
+ ".localized",
+ ".spotlight-v100",
+ ".trashes",
+ ".fseventsd",
+ "desktop.ini",
+ "thumbs.db",
+ "ehthumbs.db",
+ "$recycle.bin",
+ "system volume information",
+ }
+)
+
+
+def _is_os_metadata_entry(name: str) -> bool:
+ lowered = name.lower()
+ return lowered in _OS_METADATA_ENTRY_NAMES or lowered.startswith("._")
+
+
_ARG0_RUNTIME_DIR_RE: Final = re.compile(r"^codex-arg0[A-Za-z0-9]{6}$")
_MAX_ARG0_RUNTIME_DIRS: Final = 32
_PERSONAL_CHATGPT_PLANS: Final = frozenset(
@@ -144,8 +171,42 @@ _SUBSCRIPTION_ENV_ALLOWLIST: Final = frozenset(
"APPDATA",
"LOCALAPPDATA",
"CODEX_HOME",
+ # Locale and terminal shape. These say how text is ENCODED and drawn,
+ # never who anyone is: without them the child falls back to the C
+ # locale and mangles every non-ASCII byte it handles. The interactive
+ # login child already inherits exactly these
+ # (``jarvis/codex_auth.py::_ISOLATED_CODEX_ENV_ALLOWLIST``); the
+ # transport dropping them was an undocumented divergence.
+ "LANG",
+ "TERM",
+ "NO_COLOR",
+ # TLS trust roots. Not credentials — they name WHICH certificate
+ # authorities to believe, and on hosts that carry their roots in the
+ # environment (corporate images, Nix, conda, many container bases)
+ # dropping them left the child with no trust store at all: `codex
+ # login status` reads a local file and succeeds, so the card said
+ # "connected" while every call died in the TLS handshake.
+ "SSL_CERT_FILE",
+ "SSL_CERT_DIR",
+ "REQUESTS_CA_BUNDLE",
}
)
+# ``LC_*`` is an open family (LC_ALL, LC_CTYPE, LC_MESSAGES, ...), so it is
+# matched by prefix. Same reasoning as LANG above: encoding, not identity.
+_SUBSCRIPTION_ENV_ALLOWED_PREFIXES: Final = ("LC_",)
+
+
+def _subscription_env_allowed(name: str) -> bool:
+ """Whether one inherited environment variable may reach the child."""
+ upper = name.upper()
+ if upper in _OPENAI_BILLING_ENV_NAMES:
+ # Belt and braces: the allowlist already excludes every billing token,
+ # but a future entry added there must not silently re-open the
+ # usage-billed path this transport exists to avoid.
+ return False
+ return upper in _SUBSCRIPTION_ENV_ALLOWLIST or upper.startswith(
+ _SUBSCRIPTION_ENV_ALLOWED_PREFIXES
+ )
_DISABLED_APP_SERVER_FEATURES: Final = (
"shell_tool",
@@ -243,6 +304,16 @@ class CodexSubscriptionPlanUnsupported(CodexSubscriptionUnavailable):
"""
+class CodexSubscriptionRuntimeStateInvalid(CodexSubscriptionUnavailable):
+ """Codex's own ephemeral scratch under ``tmp/`` is not a shape we accept.
+
+ Separate from a bad PROFILE because the recovery differs: this state is
+ regenerated by the CLI on every run and contains no credential, so the
+ honest repair is to clear ``tmp/`` — never to delete the profile, which
+ would take a working ChatGPT login with it over a leftover scratch file.
+ """
+
+
class CodexSubscriptionInspectionFailed(CodexSubscriptionUnavailable):
"""An OS read error prevented judging the profile — transiently unknown.
@@ -264,13 +335,88 @@ class CodexNotificationOverflow(CodexAppServerError):
"""A subscriber stopped consuming realtime notifications fast enough."""
+#: A machine token is safe to forward; free text is not. Anything that is not
+#: a short, lowercase, punctuation-free identifier stays redacted.
+_RPC_ERROR_TOKEN_RE: Final = re.compile(r"^[a-z0-9_]{1,64}$")
+_RPC_ERROR_STATUS_KEYS: Final = (
+ "httpStatus",
+ "http_status",
+ "statusCode",
+ "status_code",
+ "status",
+)
+_RPC_ERROR_TYPE_KEYS: Final = ("type", "errorType", "error_type", "reason")
+
+
+def _rpc_error_detail(error: Any) -> tuple[int | None, str | None]:
+ """Extract ONLY an HTTP status and a bounded error-type token.
+
+ Everything else in an app-server error — the message, the account label,
+ the upstream request detail — stays redacted, which is why this transport
+ used to surface a plan/quota refusal and a broken transport as the same
+ opaque "rejected (code -32000)". Those two need opposite reactions from
+ the user, so the two machine-readable fields that tell them apart are
+ forwarded and nothing more.
+ """
+ if not isinstance(error, Mapping):
+ return None, None
+ scopes: list[Mapping[str, Any]] = [error]
+ for key in ("data", "error"):
+ nested = error.get(key)
+ if isinstance(nested, Mapping):
+ scopes.append(nested)
+ deeper = nested.get("error")
+ if isinstance(deeper, Mapping):
+ scopes.append(deeper)
+ status: int | None = None
+ token: str | None = None
+ for scope in scopes:
+ if status is None:
+ for key in _RPC_ERROR_STATUS_KEYS:
+ candidate = scope.get(key)
+ if isinstance(candidate, bool):
+ continue
+ if isinstance(candidate, int) and 100 <= candidate <= 599:
+ status = candidate
+ break
+ if token is None:
+ for key in _RPC_ERROR_TYPE_KEYS:
+ candidate = scope.get(key)
+ if not isinstance(candidate, str):
+ continue
+ normalized = candidate.strip().lower()
+ if _RPC_ERROR_TOKEN_RE.fullmatch(normalized):
+ token = normalized
+ break
+ return status, token
+
+
class CodexAppServerRPCError(CodexAppServerError):
"""A redacted JSON-RPC error returned by app-server."""
- def __init__(self, method: str, code: int | None) -> None:
+ def __init__(
+ self,
+ method: str,
+ code: int | None,
+ *,
+ http_status: int | None = None,
+ error_type: str | None = None,
+ ) -> None:
self.method = method
self.code = code
- suffix = f" (code {code})" if code is not None else ""
+ self.http_status = http_status
+ self.error_type = error_type
+ details = []
+ if code is not None:
+ details.append(f"code {code}")
+ if http_status is not None:
+ # Spelled as a bare status so the shared classifier
+ # (jarvis/brain/provider_test.py::classify_provider_error) reads
+ # 402/429 as an account state instead of "possible integration bug".
+ details.append(f"http {http_status}")
+ if error_type is not None:
+ details.append(f"type {error_type}")
+ suffix = f" ({'; '.join(details)})" if details else ""
super().__init__(f"Codex app-server rejected {method}{suffix}.")
@@ -536,7 +682,7 @@ def _validate_windows_arg0_wrapper(
raise ValueError("wrapper is too large")
body = path.read_text(encoding="utf-8")
except (OSError, UnicodeError, ValueError) as exc:
- raise CodexSubscriptionUnavailable(
+ raise CodexSubscriptionRuntimeStateInvalid(
"The dedicated Codex voice profile contains an invalid runtime wrapper."
) from exc
match = re.fullmatch(
@@ -547,7 +693,7 @@ def _validate_windows_arg0_wrapper(
Path(match.group(1)),
trusted_binary_path=trusted_binary_path,
):
- raise CodexSubscriptionUnavailable(
+ raise CodexSubscriptionRuntimeStateInvalid(
"The dedicated Codex voice profile contains an untrusted runtime wrapper."
)
@@ -565,7 +711,7 @@ def _validate_unix_arg0_alias(
"The dedicated Codex voice profile runtime could not be inspected."
) from exc
if not stat.S_ISLNK(metadata.st_mode):
- raise CodexSubscriptionUnavailable(
+ raise CodexSubscriptionRuntimeStateInvalid(
"The dedicated Codex voice profile contains an invalid runtime alias."
)
_validate_current_owner(metadata)
@@ -573,14 +719,14 @@ def _validate_unix_arg0_alias(
raw_target = Path(os.readlink(path))
target = raw_target if raw_target.is_absolute() else path.parent / raw_target
except OSError as exc:
- raise CodexSubscriptionUnavailable(
+ raise CodexSubscriptionRuntimeStateInvalid(
"The dedicated Codex voice profile contains an unreadable runtime alias."
) from exc
if not _is_trusted_codex_runtime_binary(
target,
trusted_binary_path=trusted_binary_path,
):
- raise CodexSubscriptionUnavailable(
+ raise CodexSubscriptionRuntimeStateInvalid(
"The dedicated Codex voice profile contains an untrusted runtime alias."
)
@@ -590,39 +736,55 @@ def _validate_arg0_runtime_dir(
*,
trusted_binary_path: str | None = None,
) -> None:
+ """Judge one ``tmp/arg0/codex-arg0XXXXXX`` scratch directory.
+
+ Membership is a NAME ALLOWLIST over a required ``.lock``, not set
+ equality. The exact file set was only ever measured on Windows; the macOS
+ and Linux sets were assumptions, and one file more or fewer (a Codex point
+ release, a platform that ships no sandbox helper) turned a healthy install
+ into ``setup_invalid``. The real security boundary is per entry and
+ unchanged: every non-lock child must still resolve to the approved binary
+ (``_validate_unix_arg0_alias`` / ``_validate_windows_arg0_wrapper``), so a
+ name that merely went missing proves nothing and an extra name still has
+ to survive that check.
+ """
_validate_private_directory(path)
try:
- children = {entry.name: entry for entry in path.iterdir()}
+ children = {
+ entry.name: entry
+ for entry in path.iterdir()
+ if not _is_os_metadata_entry(entry.name)
+ }
except OSError as exc:
raise CodexSubscriptionInspectionFailed(
"The dedicated Codex voice profile runtime could not be inspected."
) from exc
- expected = {".lock"}
if sys.platform == "win32":
- expected.update({"apply_patch.bat", "applypatch.bat"})
- elif sys.platform == "darwin":
- expected.update({"apply_patch", "applypatch", "codex-execve-wrapper"})
- elif sys.platform.startswith("linux"):
- expected.update(
- {
- "apply_patch",
- "applypatch",
- "codex-execve-wrapper",
- "codex-linux-sandbox",
- }
- )
+ allowed = {"apply_patch.bat", "applypatch.bat"}
+ elif sys.platform == "darwin" or sys.platform.startswith("linux"):
+ allowed = {
+ "apply_patch",
+ "applypatch",
+ "codex-execve-wrapper",
+ "codex-linux-sandbox",
+ }
else:
raise CodexSubscriptionUnavailable(
"This platform's Codex runtime layout is not approved."
)
- if set(children) != expected:
- raise CodexSubscriptionUnavailable(
+ lock_file = children.get(".lock")
+ if lock_file is None:
+ raise CodexSubscriptionRuntimeStateInvalid(
+ "The dedicated Codex voice profile runtime is missing its lock."
+ )
+ unknown = sorted(set(children) - allowed - {".lock"})
+ if unknown:
+ raise CodexSubscriptionRuntimeStateInvalid(
"The dedicated Codex voice profile contains unexpected runtime files."
)
- lock_file = children[".lock"]
_validate_regular_private_file(lock_file)
if lock_file.stat().st_size != 0:
- raise CodexSubscriptionUnavailable(
+ raise CodexSubscriptionRuntimeStateInvalid(
"The dedicated Codex voice profile contains an invalid runtime lock."
)
for name, child in children.items():
@@ -679,13 +841,17 @@ def _validate_codex_runtime_state(
) from exc
_validate_private_directory(runtime_root)
try:
- runtime_children = {entry.name: entry for entry in runtime_root.iterdir()}
+ runtime_children = {
+ entry.name: entry
+ for entry in runtime_root.iterdir()
+ if not _is_os_metadata_entry(entry.name)
+ }
except OSError as exc:
raise CodexSubscriptionInspectionFailed(
"The dedicated Codex voice runtime could not be inspected."
) from exc
if set(runtime_children) != {"arg0"}:
- raise CodexSubscriptionUnavailable(
+ raise CodexSubscriptionRuntimeStateInvalid(
"The dedicated Codex voice profile contains unexpected runtime state."
)
arg0_root = runtime_children["arg0"]
@@ -694,18 +860,22 @@ def _validate_codex_runtime_state(
exact_posix_mode=0o700 if os.name == "posix" else None,
)
try:
- process_dirs = tuple(arg0_root.iterdir())
+ process_dirs = tuple(
+ entry
+ for entry in arg0_root.iterdir()
+ if not _is_os_metadata_entry(entry.name)
+ )
except OSError as exc:
raise CodexSubscriptionInspectionFailed(
"The dedicated Codex voice runtime could not be inspected."
) from exc
if len(process_dirs) > _MAX_ARG0_RUNTIME_DIRS:
- raise CodexSubscriptionUnavailable(
+ raise CodexSubscriptionRuntimeStateInvalid(
"The dedicated Codex voice profile contains excessive runtime state."
)
for process_dir in process_dirs:
if _ARG0_RUNTIME_DIR_RE.fullmatch(process_dir.name) is None:
- raise CodexSubscriptionUnavailable(
+ raise CodexSubscriptionRuntimeStateInvalid(
"The dedicated Codex voice profile contains an unknown runtime directory."
)
_validate_arg0_runtime_dir(
@@ -719,7 +889,7 @@ def _validate_codex_runtime_state(
if trusted_runtime_binary is not None and not _is_trusted_codex_runtime_binary(
trusted_runtime_binary
):
- raise CodexSubscriptionUnavailable(
+ raise CodexSubscriptionRuntimeStateInvalid(
"The dedicated Codex voice profile references an untrusted runtime binary."
)
@@ -776,6 +946,12 @@ def _validated_subscription_home(
raise CodexSubscriptionInspectionFailed(
"The dedicated Codex voice profile could not be inspected."
) from exc
+ # Desktop-shell sidecars are skipped entirely: they are not Codex state,
+ # and judging one as "the profile contains configuration" made merely
+ # opening the folder in Finder or Explorer cost the user their login.
+ entries = tuple(
+ entry for entry in entries if not _is_os_metadata_entry(entry.name)
+ )
unexpected = [
entry.name
for entry in entries
@@ -865,12 +1041,49 @@ def _rebuild_invalid_subscription_home() -> None:
) from exc
+def _clear_subscription_runtime_state() -> None:
+ """Delete only Codex's ephemeral ``tmp/`` scratch inside the profile.
+
+ The scratch is regenerated on the CLI's next run and holds no credential,
+ so an unrecognised file in there must cost the user a directory Codex
+ rebuilds by itself — never the ChatGPT login sitting next to it.
+ """
+ from jarvis.core.paths import user_data_dir
+
+ try:
+ root = user_data_dir().resolve(strict=True)
+ except OSError as exc:
+ raise CodexSubscriptionUnavailable(
+ "Jarvis's private data directory could not be verified."
+ ) from exc
+ runtime_root = root / _SUBSCRIPTION_HOME_DIRNAME / "tmp"
+ try:
+ if not runtime_root.exists() and not runtime_root.is_symlink():
+ return
+ if _is_link_or_reparse(runtime_root):
+ # Detach the link itself; never follow it out of the profile.
+ runtime_root.unlink()
+ return
+ shutil.rmtree(runtime_root)
+ except OSError as exc:
+ raise CodexSubscriptionRuntimeStateInvalid(
+ "The Codex voice runtime state could not be cleared. Close any "
+ "running Codex process and try again."
+ ) from exc
+
+
def _prepare_subscription_login_home() -> Path:
try:
home = _validated_subscription_home(create=True, require_marker=False)
except CodexSubscriptionInspectionFailed:
# Transiently unreadable is NOT license to delete anything.
raise
+ except CodexSubscriptionRuntimeStateInvalid:
+ # Codex's own scratch, not the login. Clear ONLY that and re-validate;
+ # the profile — and the ChatGPT login inside it — survives. If it still
+ # fails, the honest error reaches the user instead of a silent wipe.
+ _clear_subscription_runtime_state()
+ home = _validated_subscription_home(create=True, require_marker=False)
except CodexSubscriptionUnavailable:
# The profile is invalid and the user explicitly asked for a fresh
# login — rebuild the Jarvis-owned directory from scratch. The short
@@ -959,52 +1172,64 @@ def _sha256_file(path: Path) -> str:
_SHA256_CACHE_MAX_ENTRIES: Final = 16
-_SHA256_CACHE_TTL_S: Final = 60.0
-_sha256_cache: dict[str, tuple[tuple[int, int, int, int, int], float, str]] = {}
+_SHA256_IDENTITY = tuple[int, int, int, int, int]
+_sha256_cache: dict[str, tuple[_SHA256_IDENTITY, str]] = {}
_sha256_cache_lock = threading.Lock()
+def _file_identity_signature(identity: os.stat_result) -> _SHA256_IDENTITY:
+ """Everything about a file that must be equal for its digest to be reused."""
+ return (
+ identity.st_dev,
+ identity.st_ino,
+ identity.st_size,
+ identity.st_mtime_ns,
+ # POSIX ctime changes on every write regardless of utimes-forgery; on
+ # Windows this is creation time and merely harmless extra identity.
+ identity.st_ctime_ns,
+ )
+
+
+def _forget_cached_digest(path: Path) -> None:
+ """Drop a memoized digest so the next reader hashes the file again."""
+ key = os.path.normcase(str(path))
+ with _sha256_cache_lock:
+ _sha256_cache.pop(key, None)
+
+
def _sha256_file_cached(path: Path) -> str:
"""Memoized ``_sha256_file`` keyed on the file's identity signature.
- Hashing the ~100 MB native Codex binary dominates the cost of every status
- 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 entry
- expires after a short TTL, bounding how long an in-place swap that forges
- 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``).
+ Hashing the ~100 MB native Codex binary dominated the cost of every status
+ probe, profile validation, and call start — and each of those runs several
+ times per voice call. The signature (device, inode, size, mtime_ns,
+ ctime_ns) is read fresh on EVERY call, so any ordinary change to the file
+ re-hashes it; the digest is then kept for the process lifetime instead of
+ expiring on a wall-clock timer, because a timer bounded nothing an
+ attacker could not simply wait out while costing a full re-hash on every
+ tick.
+
+ The memo authorizes STATUS and profile-validation reads only. The copy
+ that actually RUNS with the user's ChatGPT identity is hashed without the
+ memo immediately before spawn (``_verify_spawn_binary``), and that
+ un-memoized verdict overwrites — or purges — the memo, so the executing
+ path can never be laundered by a cached digest.
"""
try:
identity = path.stat()
except OSError: # An unreadable identity cannot be memoized — hash fresh.
return _sha256_file(path)
key = os.path.normcase(str(path))
- signature = (
- identity.st_dev,
- identity.st_ino,
- identity.st_size,
- identity.st_mtime_ns,
- # POSIX ctime changes on every write regardless of utimes-forgery; on
- # Windows this is creation time and merely harmless extra identity.
- identity.st_ctime_ns,
- )
- now = time.monotonic()
+ signature = _file_identity_signature(identity)
with _sha256_cache_lock:
entry = _sha256_cache.get(key)
- if (
- entry is not None
- and entry[0] == signature
- and now - entry[1] <= _SHA256_CACHE_TTL_S
- ):
- return entry[2]
+ if entry is not None and entry[0] == signature:
+ return entry[1]
digest = _sha256_file(path)
with _sha256_cache_lock:
if len(_sha256_cache) >= _SHA256_CACHE_MAX_ENTRIES:
_sha256_cache.clear()
- _sha256_cache[key] = (signature, now, digest)
+ _sha256_cache[key] = (signature, digest)
return digest
@@ -1017,12 +1242,35 @@ def _verify_spawn_binary(binary_path: str) -> None:
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.
+
+ This un-memoized verdict is also the memo's corrector: a match refreshes
+ the entry, a mismatch purges it, so a digest the memo believes can never
+ outlive the evidence that it is wrong.
"""
+ path = Path(binary_path)
target = _TRUSTED_CODEX_TARGETS.get((sys.platform, _normalized_machine()))
- if target is None or _sha256_file(Path(binary_path)) != target[3]:
+ try:
+ identity: os.stat_result | None = path.stat()
+ except OSError: # Unreadable identity: verify anyway, just do not memoize.
+ identity = None
+ try:
+ digest = _sha256_file(path)
+ except OSError:
+ # The file could not be hashed at all — a memo that still claims this
+ # path is approved would outlive the only evidence we have.
+ _forget_cached_digest(path)
+ raise
+ if target is None or digest != target[3]:
+ _forget_cached_digest(path)
raise CodexSubscriptionUnavailable(
"The Codex executable changed since it was verified."
)
+ if identity is not None:
+ with _sha256_cache_lock:
+ _sha256_cache[os.path.normcase(str(path))] = (
+ _file_identity_signature(identity),
+ digest,
+ )
def _codex_package_roots(launcher: Path) -> list[Path]:
@@ -1413,7 +1661,7 @@ def _subscription_environment(
environment = {
name: value
for name, value in os.environ.items()
- if name.upper() in _SUBSCRIPTION_ENV_ALLOWLIST
+ if _subscription_env_allowed(name)
}
environment.update(
{
@@ -1775,6 +2023,16 @@ class CodexAppServerClient:
self._owner_loop: asyncio.AbstractEventLoop | None = None
self._transport_provider_id = f"jarvis_voice_{secrets.token_hex(16)}"
self._ready = False
+ # Set once ``close()`` ran. A closed client has released its profile
+ # reservation and deleted its workspace, so restarting it would fight
+ # the successor for the single-owner profile; callers acquire a fresh
+ # one from ``get_shared_codex_app_server`` instead.
+ self._closed = False
+ # The live process whose FULL startup audit (profile, live account,
+ # config requirements, effective config) just passed. ``thread_start``
+ # consumes this to skip repeating that identical audit microseconds
+ # later; every WARM thread start still re-audits.
+ self._startup_audit_process: asyncio.subprocess.Process | None = None
def _assert_owner_loop(self) -> asyncio.AbstractEventLoop:
loop = asyncio.get_running_loop()
@@ -1856,9 +2114,22 @@ class CodexAppServerClient:
self._assert_owner_loop()
if self.ready:
return
+ if self._closed:
+ # Restarting a closed client would race the successor for the
+ # single-owner profile and wedge it behind an unactionable
+ # "already owned" error. Name the recovery instead.
+ raise CodexSubscriptionUnavailable(
+ "This subscription-voice transport was closed. Start voice "
+ "again to open a new one."
+ )
async with self._start_lock:
if self.ready:
return
+ if self._closed:
+ raise CodexSubscriptionUnavailable(
+ "This subscription-voice transport was closed. Start voice "
+ "again to open a new one."
+ )
if self._process is not None:
await self._close_process(
CodexAppServerDisconnected("Codex app-server exited."),
@@ -1985,6 +2256,12 @@ class CodexAppServerClient:
trusted_binary_path=self._trusted_binary_path,
)
self._ready = True
+ # The audit that just passed is byte-for-byte the one
+ # ``thread_start`` performs. Record which process it covers so
+ # the very next thread start rides it instead of repeating
+ # three RPC round trips and a profile walk on the SAME process
+ # microseconds later.
+ self._startup_audit_process = self._process
def _announce_ready() -> None:
# Status callers waiting out the "voice is starting"
@@ -2454,27 +2731,34 @@ class CodexAppServerClient:
)
try:
if sys.platform != "win32":
+ # 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.
+ profile_lock_fds = await asyncio.to_thread(
+ _subscription_transport_pass_fds, self
+ )
lifeline_read_fd, lifeline_write_fd = os.pipe()
os.set_inheritable(lifeline_read_fd, True)
os.set_inheritable(lifeline_write_fd, False)
+ keep_fd_args: list[str] = []
+ for descriptor in profile_lock_fds:
+ # The lifeline supervisor spawns the REAL child with
+ # close_fds, so every descriptor above stdio stopped here
+ # unless it is re-declared. Without these pairs the profile
+ # lock was held by the supervisor, not by the app-server
+ # the docstring promises holds it.
+ keep_fd_args.extend(("--keep-fd", str(descriptor)))
command = [
sys.executable,
"-I",
_CHILD_LIFELINE_SCRIPT,
str(lifeline_read_fd),
+ *keep_fd_args,
"--",
*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"] = (
- *await asyncio.to_thread(
- _subscription_transport_pass_fds, self
- ),
- lifeline_read_fd,
- )
+ kwargs["pass_fds"] = (*profile_lock_fds, lifeline_read_fd)
except BaseException:
tree.close()
for descriptor in (lifeline_read_fd, lifeline_write_fd):
@@ -2715,8 +2999,14 @@ class CodexAppServerClient:
if "error" in message:
error = message.get("error")
code = error.get("code") if isinstance(error, Mapping) else None
+ http_status, error_type = _rpc_error_detail(error)
future.set_exception(
- CodexAppServerRPCError(pending_method, code if isinstance(code, int) else None)
+ CodexAppServerRPCError(
+ pending_method,
+ code if isinstance(code, int) else None,
+ http_status=http_status,
+ error_type=error_type,
+ )
)
else:
future.set_result(message.get("result"))
@@ -2967,18 +3257,35 @@ class CodexAppServerClient:
# this check with its thread/start frame.
async with self._thread_start_lock:
await self.ensure_started()
+ # ...with ONE exception: a cold start that finished inside this
+ # very call already ran the identical audit against the identical
+ # process, and nothing but this coroutine has touched it since.
+ # Repeating it cost three RPC round trips plus a profile walk (and
+ # a ~100 MB re-hash on a cold memo) on every first call. The token
+ # is consumed here, under the same lock that serializes the
+ # thread/start frame, so exactly one thread start can ride it and
+ # every WARM start still re-audits.
+ live_process = self._process
+ audit_is_fresh = (
+ live_process is not None
+ and self._startup_audit_process is live_process
+ )
+ self._startup_audit_process = None
try:
- await asyncio.to_thread(
- _validated_subscription_home,
- create=False,
- require_marker=True,
- trusted_binary_path=self._trusted_binary_path,
- )
- await self._verify_live_chatgpt_account()
- self._audit_config_requirements(
- await self._read_config_requirements()
- )
- self._audit_effective_config(await self._read_effective_config())
+ if not audit_is_fresh:
+ await asyncio.to_thread(
+ _validated_subscription_home,
+ create=False,
+ require_marker=True,
+ trusted_binary_path=self._trusted_binary_path,
+ )
+ await self._verify_live_chatgpt_account()
+ self._audit_config_requirements(
+ await self._read_config_requirements()
+ )
+ self._audit_effective_config(
+ await self._read_effective_config()
+ )
except CodexSubscriptionUnavailable as exc:
if isinstance(exc, CodexSubscriptionPlanUnsupported):
# The WARM call path re-judges the live account before
@@ -3041,21 +3348,39 @@ class CodexAppServerClient:
)
return _result_dict("turn/start", await self.request("turn/start", params))
+ async def _teardown_request(
+ self, method: str, params: Mapping[str, Any]
+ ) -> dict[str, Any]:
+ """Send a teardown RPC, but never START a process just to send it.
+
+ ``request`` lazily starts app-server, which is right for real work and
+ wrong for cleanup: when the process is already gone, so is the
+ ephemeral thread this call would tidy up, and the plain ``request``
+ path paid a 15-25 s cold start only to have the caller's short cleanup
+ budget expire and poison the client. Nothing is hidden — the skip is
+ logged, and a LIVE process still gets the real RPC and its real error.
+ """
+ if not self.running:
+ log.debug(
+ "Skipping Codex %s: the app-server process is already gone",
+ method,
+ )
+ return {}
+ return _result_dict(
+ method, await self._request_live(method, params, timeout_s=None)
+ )
+
async def turn_interrupt(self, thread_id: str, turn_id: str) -> dict[str, Any]:
"""Interrupt one exact app-server turn by its schema-defined ids."""
- return _result_dict(
+ return await self._teardown_request(
"turn/interrupt",
- await self.request(
- "turn/interrupt",
- {"threadId": thread_id, "turnId": turn_id},
- ),
+ {"threadId": thread_id, "turnId": turn_id},
)
async def thread_unsubscribe(self, thread_id: str) -> dict[str, Any]:
"""Unload a completed ephemeral voice thread from app-server."""
- return _result_dict(
- "thread/unsubscribe",
- await self.request("thread/unsubscribe", {"threadId": thread_id}),
+ return await self._teardown_request(
+ "thread/unsubscribe", {"threadId": thread_id}
)
async def realtime_start(
@@ -3199,15 +3524,15 @@ class CodexAppServerClient:
)
async def realtime_stop(self, thread_id: str) -> dict[str, Any]:
- return _result_dict(
- "thread/realtime/stop",
- await self.request("thread/realtime/stop", {"threadId": thread_id}),
+ return await self._teardown_request(
+ "thread/realtime/stop", {"threadId": thread_id}
)
async def _close_process(self, error: CodexAppServerDisconnected, *, expected: bool) -> None:
process = self._process
if process is None:
self._ready = False
+ self._startup_audit_process = None
self._close_lifeline()
if self._profile_transport_epoch is not None:
# Epoch first, release off-loop and shielded: a cancellation
@@ -3222,6 +3547,7 @@ class CodexAppServerClient:
return
self._process = None
self._ready = False
+ self._startup_audit_process = None
tree = self._process_tree
self._process_tree = None
reader_task = self._reader_task
@@ -3308,35 +3634,50 @@ class CodexAppServerClient:
log.warning("Codex app-server connection reset")
async def close(self) -> None:
- """Reap the app-server tree and release local temporary state."""
+ """Reap the app-server tree and release local temporary state.
+
+ Closing also RETIRES this client from the shared registry. Without
+ that, ``get_shared_codex_app_server`` kept handing the same corpse to
+ the next caller — whose ``ensure_started`` then paid a full cold start
+ against a client whose workspace had already been deleted. Eviction is
+ idempotent and runs even when the teardown itself fails, because a
+ client nobody can use must never be reachable.
+ """
self._assert_owner_loop()
- async with self._start_lock:
- await self._close_process(
- CodexAppServerDisconnected("Codex app-server client closed."),
- expected=True,
- )
- workspace = self._workspace
- self._workspace = None
- self._child_environment = {}
- sink_server = self._sink_server
- self._sink_server = None
- self._sink_base_url = None
- if sink_server is not None:
- sink_server.close()
- with suppress(Exception):
- await sink_server.wait_closed()
- if workspace is not None:
- with suppress(OSError):
- await asyncio.to_thread(shutil.rmtree, workspace.root)
+ try:
+ async with self._start_lock:
+ await self._close_process(
+ CodexAppServerDisconnected("Codex app-server client closed."),
+ expected=True,
+ )
+ workspace = self._workspace
+ self._workspace = None
+ self._child_environment = {}
+ sink_server = self._sink_server
+ self._sink_server = None
+ self._sink_base_url = None
+ if sink_server is not None:
+ sink_server.close()
+ with suppress(Exception):
+ await sink_server.wait_closed()
+ if workspace is not None:
+ with suppress(OSError):
+ await asyncio.to_thread(shutil.rmtree, workspace.root)
+ finally:
+ self._closed = True
+ _evict_shared_codex_app_server(self)
async def poison(self) -> None:
"""Fail closed after an uncertain remote cleanup."""
await self.close()
-_shared_clients: dict[
- tuple[str, asyncio.AbstractEventLoop], CodexAppServerClient
-] = {}
+# Keyed on the binary path ALONE, never on the acquiring event loop. The
+# resource behind a client is process-global (one OS profile lock, one
+# app-server child bound to it), so a per-loop client could only ever be a
+# client that can never reserve the profile — the second loop got one and
+# every call from it failed with "already owned by another client".
+_shared_clients: dict[str, CodexAppServerClient] = {}
_shared_clients_lock = threading.Lock()
# Invariant: WORKER threads may hold this lock across filesystem work (the
# cross-process profile lock is acquired under it: mkdir, resolve, ACL
@@ -3348,6 +3689,11 @@ _subscription_login_in_flight = False
_subscription_login_process: Any | None = None
_subscription_profile_mutating = False
_subscription_active_transports: set[int] = set()
+# The one client currently holding the reservation. Kept as an object (not
+# just its id) so an off-loop reserve can tell a live owner from one whose
+# event loop died, and so status reads do not depend on the client still
+# being registered.
+_subscription_transport_owner: CodexAppServerClient | None = None
_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
@@ -3530,6 +3876,36 @@ def _subscription_transport_pass_fds(
return (descriptor,)
+def _owner_loop_is_dead(client: CodexAppServerClient) -> bool:
+ """True when this client's owning event loop can never run it again."""
+ loop = client._owner_loop
+ return loop is not None and loop.is_closed()
+
+
+def _reap_dead_loop_transport_locked(client: CodexAppServerClient) -> None:
+ """Kill an orphan whose owning loop died; caller holds the login lock.
+
+ Mirrors the shutdown sweep's dead-loop branch: the loop that owns the
+ child can never reap it, so the tree is killed and the lifeline closed
+ BEFORE the reservation is handed on — an orphan must never keep running
+ against ``CODEX_HOME`` while the profile reads as free.
+ """
+ orphan_process = client._process
+ client._process = None
+ orphan_tree = client._process_tree
+ client._process_tree = None
+ client._ready = False
+ if orphan_process is not None and orphan_process.returncode is None:
+ with suppress(ProcessLookupError, OSError):
+ orphan_process.kill()
+ if orphan_tree is not None:
+ with suppress(Exception):
+ orphan_tree.close()
+ with suppress(Exception):
+ client._close_lifeline()
+ client._profile_transport_epoch = None
+
+
def _reserve_subscription_transport(client: CodexAppServerClient) -> int:
"""Reserve the profile for this client and return an ownership epoch.
@@ -3540,6 +3916,7 @@ def _reserve_subscription_transport(client: CodexAppServerClient) -> int:
life could tear down a reservation a newer start legitimately owns.
"""
global _subscription_transport_process_lock, _subscription_transport_epoch
+ global _subscription_transport_owner
with _subscription_login_lock:
_await_status_probe_completion_locked()
@@ -3555,13 +3932,38 @@ def _reserve_subscription_transport(client: CodexAppServerClient) -> int:
):
# Adoption: the new start supersedes any stale holder, whose
# pending releases become no-ops via the epoch bump.
+ _subscription_transport_owner = client
+ _subscription_transport_epoch += 1
+ return _subscription_transport_epoch
+ owner = _subscription_transport_owner
+ if (
+ owner is not None
+ and owner is not client
+ and _subscription_active_transports == {id(owner)}
+ and _subscription_transport_process_lock is not None
+ and _owner_loop_is_dead(owner)
+ ):
+ # The holder's event loop is gone for good: it can never
+ # release the reservation itself, and refusing forever would
+ # make subscription voice unusable until a restart. Reap its
+ # orphan and hand the SAME process lock to the new owner.
+ log.warning(
+ "Reclaiming the subscription-voice reservation from a "
+ "client whose event loop is closed"
+ )
+ _reap_dead_loop_transport_locked(owner)
+ _subscription_active_transports.discard(id(owner))
+ _subscription_active_transports.add(client_id)
+ _subscription_transport_owner = client
_subscription_transport_epoch += 1
return _subscription_transport_epoch
raise CodexSubscriptionUnavailable(
- "Subscription voice is already owned by another client or event loop."
+ "Subscription voice is already running elsewhere in Jarvis. "
+ "End the active voice session before starting another one."
)
_subscription_transport_process_lock = _acquire_subscription_process_lock()
_subscription_active_transports.add(client_id)
+ _subscription_transport_owner = client
_subscription_transport_epoch += 1
return _subscription_transport_epoch
@@ -3574,10 +3976,12 @@ def _force_drop_subscription_transport(client: CodexAppServerClient) -> None:
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
+ global _subscription_transport_process_lock, _subscription_transport_owner
with _subscription_login_lock:
_subscription_active_transports.discard(id(client))
+ if _subscription_transport_owner is client:
+ _subscription_transport_owner = None
if not _subscription_active_transports:
process_lock = _subscription_transport_process_lock
_subscription_transport_process_lock = None
@@ -3590,7 +3994,7 @@ def _release_subscription_transport(
client: CodexAppServerClient, epoch: int
) -> None:
"""Release the reservation, but only when ``epoch`` is still current."""
- global _subscription_transport_process_lock
+ global _subscription_transport_process_lock, _subscription_transport_owner
with _subscription_login_lock:
if epoch != _subscription_transport_epoch:
@@ -3598,6 +4002,8 @@ def _release_subscription_transport(
# to a superseded holder and must not touch the live state.
return
_subscription_active_transports.discard(id(client))
+ if _subscription_transport_owner is client:
+ _subscription_transport_owner = None
if not _subscription_active_transports:
process_lock = _subscription_transport_process_lock
_subscription_transport_process_lock = None
@@ -3638,24 +4044,54 @@ def _launch_subscription_login_reaper(target: Any) -> None:
).start()
+def _evict_shared_codex_app_server(client: CodexAppServerClient) -> None:
+ """Retire a client from the shared registry. Safe to call repeatedly."""
+ with _shared_clients_lock:
+ for key in [
+ key for key, entry in _shared_clients.items() if entry is client
+ ]:
+ _shared_clients.pop(key, None)
+
+
def get_shared_codex_app_server(
binary_path: str | None = None,
) -> CodexAppServerClient:
- """Return the shared client for Jarvis's fixed subscription-voice identity."""
+ """Return the shared client for Jarvis's fixed subscription-voice identity.
+
+ One client per binary, process-wide. A caller on a different event loop is
+ refused HERE with an actionable message rather than being handed a client
+ that cannot reserve the single-owner profile and fails deep inside a call.
+ """
try:
loop = asyncio.get_running_loop()
except RuntimeError as exc:
raise CodexSubscriptionUnavailable(
"The shared Codex app-server must be acquired from its owning event loop."
) from exc
- binary_key = (binary_path or "").strip() or "<default>"
- key = (binary_key, loop)
+ key = (binary_path or "").strip() or "<default>"
with _shared_clients_lock:
client = _shared_clients.get(key)
- if client is None:
- client = CodexAppServerClient(binary_path=binary_path)
- client._owner_loop = loop
- _shared_clients[key] = client
+ if client is not None:
+ owner = client._owner_loop
+ if owner is loop:
+ return client
+ if owner is not None and not owner.is_closed():
+ raise CodexSubscriptionUnavailable(
+ "Subscription voice is already running elsewhere in "
+ "Jarvis. End the active voice session before starting "
+ "another one."
+ )
+ # The owning loop is gone for good; this entry can never be used
+ # or closed again. Retire it here — the reservation it may still
+ # hold is reclaimed off-loop by the next reserve, which can kill
+ # the orphan safely.
+ log.warning(
+ "Replacing a Codex app-server client whose owner loop is closed"
+ )
+ _shared_clients.pop(key, None)
+ client = CodexAppServerClient(binary_path=binary_path)
+ client._owner_loop = loop
+ _shared_clients[key] = client
return client
@@ -3695,13 +4131,18 @@ def _local_subscription_auth_snapshot_locked(
reason_code="busy",
)
if _subscription_active_transports:
- with _shared_clients_lock:
- active_clients = tuple(
- client
- for client in _shared_clients.values()
- if id(client) in _subscription_active_transports
- )
- ready_client = next((client for client in active_clients if client.ready), None)
+ # The reservation holder is tracked directly: it stays authoritative
+ # even after the client was retired from the shared registry (a closed
+ # owner loop), where a registry scan would have found nothing and
+ # reported a live call as "starting".
+ owner = _subscription_transport_owner
+ ready_client = (
+ owner
+ if owner is not None
+ and id(owner) in _subscription_active_transports
+ and owner.ready
+ else None
+ )
if ready_client is not None:
# The bounded cache read applies the age ceiling and the
# failure-memo exclusion — never read the raw cache here.
@@ -4238,7 +4679,7 @@ async def close_shared_codex_app_servers() -> None:
entries = tuple(_shared_clients.items())
failures: list[BaseException] = []
for key, client in entries:
- owner_loop = key[1]
+ owner_loop = client._owner_loop or current_loop
try:
if owner_loop is current_loop:
await client.close()
@@ -4309,6 +4750,7 @@ __all__ = [
"CodexSubscriptionBinaryUnsupported",
"CodexSubscriptionInspectionFailed",
"CodexSubscriptionPlanUnsupported",
+ "CodexSubscriptionRuntimeStateInvalid",
"CodexSubscriptionUnavailable",
"CODEX_SUBSCRIPTION_REASON_CODES",
"codex_subscription_activation_block",
diff --git a/tests/unit/codex_app_server/test_transport.py b/tests/unit/codex_app_server/test_transport.py
index 8baf722483..f481d1df0f 100644
--- a/tests/unit/codex_app_server/test_transport.py
+++ b/tests/unit/codex_app_server/test_transport.py
@@ -76,6 +76,7 @@ def isolated_profile_lifecycle(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(transport, "_subscription_login_process", None)
monkeypatch.setattr(transport, "_subscription_profile_mutating", False)
monkeypatch.setattr(transport, "_subscription_active_transports", set())
+ monkeypatch.setattr(transport, "_subscription_transport_owner", None)
monkeypatch.setattr(transport, "_subscription_transport_process_lock", None)
monkeypatch.setattr(transport, "_subscription_mutation_process_lock", None)
monkeypatch.setattr(transport, "_subscription_snapshot_cache", None)
@@ -369,7 +370,12 @@ async def test_lazy_start_handshake_scrubs_api_billing_environment_and_reaps_tre
assert child_env["RUST_LOG"] == "warn"
assert child_env["RUST_BACKTRACE"] == "0"
assert child_env["CODEX_INTERNAL_APP_SERVER_REMOTE_CONTROL_DISABLED"] == "1"
- assert kwargs["creationflags"] & transport.NO_WINDOW_CREATIONFLAGS
+ # Windows-only by construction: NO_WINDOW_CREATIONFLAGS is 0 elsewhere, so
+ # asserting the bit off Windows only ever asserted 0 and failed there.
+ if sys.platform == "win32":
+ assert kwargs["creationflags"] & transport.NO_WINDOW_CREATIONFLAGS
+ else:
+ assert kwargs["creationflags"] == 0
process = harness.processes[0]
assert process.stdin.messages[0]["method"] == "initialize"
@@ -416,6 +422,10 @@ async def test_posix_child_runs_behind_parent_lifeline_and_inherits_profile_lock
assert kwargs["start_new_session"] is True
assert kwargs["pass_fds"][0] == 91
assert len(kwargs["pass_fds"]) == 2
+ # The supervisor spawns the real child with close_fds, so the profile lock
+ # only reaches app-server when it is re-declared in the lifeline argv.
+ assert argv[4:6] == ("--keep-fd", "91")
+ assert argv[separator - 1] == "91"
assert client._lifeline_write_fd is not None
await client.close()
assert client._lifeline_write_fd is None
@@ -429,9 +439,39 @@ async def test_posix_lifeline_setup_failure_closes_both_pipe_descriptors(
harness = SpawnHarness(monkeypatch)
closed: list[int] = []
monkeypatch.setattr(transport.os, "pipe", lambda: (80, 81))
- monkeypatch.setattr(transport.os, "set_inheritable", lambda *_args: None)
monkeypatch.setattr(transport.os, "close", closed.append)
+ def refuse_inheritable(*_args: object) -> None:
+ raise OSError("inheritable flag refused")
+
+ monkeypatch.setattr(transport.os, "set_inheritable", refuse_inheritable)
+ client = CodexAppServerClient()
+
+ with pytest.raises(OSError, match="inheritable flag refused"):
+ await client.ensure_started()
+
+ assert closed == [80, 81]
+ assert harness.calls == []
+ assert harness.all_trees[0].closed is True
+
+
+async def test_posix_profile_lock_failure_creates_no_pipe_at_all(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The lock is resolved BEFORE the pipe, because its descriptors have to
+ reach the lifeline argv — so a lock failure has nothing to leak."""
+ monkeypatch.setattr(transport.sys, "platform", "linux")
+ harness = SpawnHarness(monkeypatch)
+ pipes = 0
+
+ def count_pipe() -> tuple[int, int]:
+ nonlocal pipes
+ pipes += 1
+ return (80, 81)
+
+ monkeypatch.setattr(transport.os, "pipe", count_pipe)
+
def unavailable_lock(_client: CodexAppServerClient) -> tuple[int, ...]:
raise CodexSubscriptionUnavailable("profile lock unavailable")
@@ -441,7 +481,7 @@ async def test_posix_lifeline_setup_failure_closes_both_pipe_descriptors(
with pytest.raises(CodexSubscriptionUnavailable, match="profile lock unavailable"):
await client.ensure_started()
- assert closed == [80, 81]
+ assert pipes == 0
assert harness.calls == []
assert harness.all_trees[0].closed is True
@@ -1036,12 +1076,10 @@ def test_public_auth_snapshot_uses_live_state_without_cli_probe(
client._ready = True
client._trusted_binary_path = "trusted-codex-test"
owner_loop = asyncio.new_event_loop()
- monkeypatch.setattr(
- transport,
- "_shared_clients",
- {("codex-test", owner_loop): client},
- )
+ client._owner_loop = owner_loop
+ monkeypatch.setattr(transport, "_shared_clients", {"codex-test": client})
monkeypatch.setattr(transport, "_subscription_active_transports", {id(client)})
+ monkeypatch.setattr(transport, "_subscription_transport_owner", client)
monkeypatch.setattr(
transport,
"_read_codex_capability",
@@ -1684,27 +1722,35 @@ async def test_shared_client_ignores_active_codex_account_profiles(
@pytest.mark.asyncio
-async def test_shared_clients_are_scoped_to_their_event_loop(
+async def test_shared_client_is_process_wide_and_refuses_a_second_loop(
monkeypatch: pytest.MonkeyPatch,
) -> None:
+ """One client per binary, process-wide.
+
+ A per-loop client could only ever be one that can never reserve the
+ single-owner profile, so a second loop is refused at ACQUISITION with a
+ message naming what to do — not handed a client that fails deep inside a
+ call with "already owned by another client".
+ """
SpawnHarness(monkeypatch)
await transport.close_shared_codex_app_servers()
current = transport.get_shared_codex_app_server("codex-test")
+ assert transport.get_shared_codex_app_server("codex-test") is current
- async def acquire_on_foreign_loop() -> int:
- loop = asyncio.get_running_loop()
- client = transport.get_shared_codex_app_server("codex-test")
- identifier = id(client)
- await client.close()
- with transport._shared_clients_lock:
- transport._shared_clients.pop(("codex-test", loop), None)
- return identifier
+ def acquire_on_foreign_loop() -> BaseException | None:
+ async def acquire() -> BaseException | None:
+ try:
+ transport.get_shared_codex_app_server("codex-test")
+ except BaseException as exc: # noqa: BLE001 - returned for assertion
+ return exc
+ return None
- foreign_identifier = await asyncio.to_thread(
- lambda: asyncio.run(acquire_on_foreign_loop())
- )
+ return asyncio.run(acquire())
- assert foreign_identifier != id(current)
+ error = await asyncio.to_thread(acquire_on_foreign_loop)
+
+ assert isinstance(error, CodexSubscriptionUnavailable)
+ assert "already running elsewhere" in str(error)
await transport.close_shared_codex_app_servers()
@@ -1736,7 +1782,7 @@ async def test_second_client_cannot_share_the_subscription_profile(
second = CodexAppServerClient()
await first.ensure_started()
- with pytest.raises(CodexSubscriptionUnavailable, match="another client"):
+ with pytest.raises(CodexSubscriptionUnavailable, match="already running elsewhere"):
await second.ensure_started()
assert len(harness.processes) == 1
@@ -1938,9 +1984,11 @@ def test_effective_config_audit_requires_empty_host_layers_and_session_origins()
@pytest.mark.asyncio
-async def test_dedicated_home_is_revalidated_before_thread_start(
+async def test_dedicated_home_is_revalidated_before_a_warm_thread_start(
monkeypatch: pytest.MonkeyPatch,
) -> None:
+ """The first thread start rides the startup audit; every later one
+ revalidates the profile before it may send a thread/start frame."""
harness = SpawnHarness(monkeypatch)
validations = 0
@@ -1956,20 +2004,30 @@ async def test_dedicated_home_is_revalidated_before_thread_start(
monkeypatch.setattr(transport, "_validated_subscription_home", validate_home)
client = CodexAppServerClient()
+ # Startup validates the profile twice (before spawn and after the audit);
+ # the first thread start rides that, the warm one hits the poisoned third.
+ await client.thread_start()
with pytest.raises(CodexSubscriptionUnavailable, match="configuration"):
await client.thread_start()
- assert not any(
- message.get("method") == "thread/start"
+ assert [
+ message.get("method")
for message in harness.processes[0].stdin.messages
- )
+ ].count("thread/start") == 1
await client.close()
@pytest.mark.asyncio
-async def test_account_is_rechecked_immediately_before_every_thread_start(
+async def test_account_is_rechecked_before_every_warm_thread_start(
monkeypatch: pytest.MonkeyPatch,
) -> None:
+ """A live account switch between calls still stops the next thread.
+
+ The cold start's own account/read covers the thread start that triggered
+ it; every WARM thread start re-reads the live account, because
+ ``codex login --with-api-key`` can switch the shared process while it
+ stays alive.
+ """
account_reads = 0
def responder(process: FakeProcess, message: dict[str, Any]) -> None:
@@ -1982,7 +2040,7 @@ async def test_account_is_rechecked_immediately_before_every_thread_start(
_respond(process, request_id, {})
elif method == "account/read":
account_reads += 1
- account_type = "chatgpt" if account_reads <= 2 else "apiKey"
+ account_type = "chatgpt" if account_reads <= 1 else "apiKey"
_respond(
process,
request_id,
@@ -2005,7 +2063,9 @@ async def test_account_is_rechecked_immediately_before_every_thread_start(
await client.thread_start()
methods = [item.get("method") for item in harness.processes[0].stdin.messages]
- assert methods.count("account/read") == 3
+ # One at startup (which the first thread start rides) plus one for the
+ # warm second start — not one per start on top of the startup read.
+ assert methods.count("account/read") == 2
assert methods.count("thread/start") == 1