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.

chore: auto-save WIP via Claude stop-hook safety net (2026-07-06 20:58)

Ruben Lütke334b12ed2ece
diff --git a/jarvis/claude_auth.py b/jarvis/claude_auth.py
index 2330dc29c7..08e6a76cb4 100644
--- a/jarvis/claude_auth.py
+++ b/jarvis/claude_auth.py
@@ -39,6 +39,8 @@ import logging
import os
import subprocess
import sys
+import time
+from collections.abc import Callable
from dataclasses import dataclass
from pathlib import Path
from typing import Any
@@ -92,25 +94,44 @@ def _read_json(path: Path) -> dict[str, Any] | None:
return data if isinstance(data, dict) else None
-def _oauth_from_credentials(creds: dict[str, Any] | None) -> tuple[bool, str | None]:
- """Return ``(connected, subscription_type)`` from a parsed credentials dict.
+def _oauth_from_credentials(
+ creds: dict[str, Any] | None, *, now_fn: Callable[[], float] = time.time
+) -> tuple[bool, str | None, bool]:
+ """Return ``(connected, subscription_type, expired)`` from a credentials dict.
``claude`` writes ``{"claudeAiOauth": {"accessToken": "sk-ant-oat...",
- "subscriptionType": "max", ...}}``. A present ``sk-ant-oat`` bearer means the
- Claude Max / Pro subscription login is live; the tier comes from
+ "subscriptionType": "max", "expiresAt": <epoch ms>, ...}}``. A present
+ ``sk-ant-oat`` bearer whose ``expiresAt`` has NOT passed means the Claude
+ Max / Pro subscription login is live; the tier comes from
``subscriptionType``. Tolerant by design — any shape it does not recognize
- degrades to ``(False, None)`` rather than raising.
+ degrades to ``(False, None, False)`` rather than raising.
+
+ EXPIRY-aware since 2026-07-06: presence-only reporting said
+ "connected=True mode=subscription" for a token that had been dead since
+ 02:53, so the UI showed green while every subagent spawn died with
+ "401 Invalid authentication credentials". A present-but-expired bearer now
+ reports ``connected=False, expired=True`` so ``status()`` can tell the user
+ to run ``claude /login``. A missing ``expiresAt`` stays fail-open (older
+ credential shapes keep reporting connected).
"""
if not isinstance(creds, dict):
- return False, None
+ return False, None, False
oauth = creds.get("claudeAiOauth")
if not isinstance(oauth, dict):
- return False, None
+ return False, None, False
token = oauth.get("accessToken")
- connected = isinstance(token, str) and token.startswith("sk-ant-oat")
+ present = isinstance(token, str) and token.startswith("sk-ant-oat")
sub_type = oauth.get("subscriptionType")
sub_type = sub_type if isinstance(sub_type, str) and sub_type else None
- return connected, sub_type
+ if not present:
+ return False, None, False
+ expires_at = oauth.get("expiresAt")
+ expired = False
+ if isinstance(expires_at, (int, float)) and expires_at > 0:
+ # `claude` writes epoch milliseconds; tolerate seconds defensively.
+ expires_s = expires_at / 1000.0 if expires_at > 1e12 else float(expires_at)
+ expired = expires_s <= now_fn()
+ return (not expired), sub_type, expired
def _account_from_claude_json(
@@ -270,7 +291,7 @@ class ClaudeAuthService:
version = self._probe_version(binary)
creds = _read_json(self._credentials_path())
- oauth_connected, sub_type = _oauth_from_credentials(creds)
+ oauth_connected, sub_type, oauth_expired = _oauth_from_credentials(creds)
if oauth_connected:
email, _name = _account_from_claude_json(
@@ -309,6 +330,28 @@ class ClaudeAuthService:
api_key_present=True,
)
+ if oauth_expired:
+ # Honest expired-state (2026-07-06): the bearer exists but died in
+ # place — presence-only reporting showed a green "Connected via
+ # Claude Max" card while every subagent spawn 401'd.
+ log.info(
+ "claude status: installed=True connected=False (subscription "
+ "login expired)"
+ )
+ return ClaudeAuthStatus(
+ installed=True,
+ connected=False,
+ mode="unknown",
+ message=(
+ "Claude subscription login has expired — run 'claude /login' "
+ "to sign in again, or add an Anthropic API key."
+ ),
+ version=version,
+ subscription_type=sub_type,
+ binary_path=binary,
+ api_key_present=self._api_key_present,
+ )
+
log.info("claude status: installed=True connected=False")
return ClaudeAuthStatus(
installed=True,
diff --git a/jarvis/missions/init.py b/jarvis/missions/init.py
index cb4b0da435..ea84eb3bb8 100644
--- a/jarvis/missions/init.py
+++ b/jarvis/missions/init.py
@@ -449,6 +449,49 @@ def _live_subagent_provider(boot_snapshot: str | None) -> str | None:
return boot_snapshot
+def _claude_cli_auth_viable() -> bool:
+ """True when the ``claude`` CLI has a REACHABLE auth surface for a worker.
+
+ Binary presence alone is NOT viability (2026-07-06 incident): the worker
+ runs ``claude --print`` pinned to an isolated CLAUDE_CONFIG_DIR, so its
+ ONLY auth surface is the credential Jarvis injects — a live non-expired
+ OAuth bearer (``CLAUDE_CODE_OAUTH_TOKEN``) or a classic Anthropic API key.
+ An OAuth token that expired in place (nothing refreshes ``~/.claude`` on a
+ host whose interactive sessions use a different config dir) is a
+ deterministic 401 on every spawn, while ``claude status`` still says
+ connected (presence-only check).
+
+ Three gates, all cheap and offline:
+ 1. the process-local ``claude_auth_dead`` flag (a worker PROVED the current
+ credential dead this session — fingerprinted, so a fresh login/key
+ re-enables Claude instantly);
+ 2. a live, non-expired OAuth login in ``~/.claude/.credentials.json``;
+ 3. failing that, a CLASSIC (non-``sk-ant-oat``) stored Anthropic API key —
+ a stored ``sk-ant-oat`` is a stale OAuth copy that would be routed to
+ the OAuth slot and 401.
+ """
+ from jarvis.claude_auth_state import claude_auth_dead, credential_fingerprint
+ from jarvis.missions.isolation.env import (
+ live_claude_oauth_status,
+ read_live_claude_oauth_token,
+ )
+
+ if live_claude_oauth_status() == "valid":
+ token = read_live_claude_oauth_token()
+ return not claude_auth_dead(
+ current_fingerprint=credential_fingerprint(token)
+ )
+ try:
+ from jarvis.core.config import get_secret
+
+ key = get_secret("anthropic_api_key", env_fallback="ANTHROPIC_API_KEY")
+ except Exception: # noqa: BLE001 — unreadable secret store => not viable
+ return False
+ if not key or key.startswith("sk-ant-oat"):
+ return False
+ return not claude_auth_dead(current_fingerprint=credential_fingerprint(key))
+
+
def _cross_family_last_resort_worker(task_text: str) -> Any | None:
"""The key-aware, cross-family LAST-resort heavy worker (open-source AP-22/23).
@@ -477,11 +520,22 @@ def _cross_family_last_resort_worker(task_text: str) -> Any | None:
has no Claude at all (the §3 single-key downloader).
"""
# 1. Claude Max OAuth CLI — subscription, no metered key, preferred floor.
+ # Auth-aware since 2026-07-06: binary presence alone picked a claude CLI
+ # whose OAuth token had expired in place, and every mission 401'd while
+ # a healthy codex login + OpenRouter key sat unused (AP-22).
from jarvis.missions.workers.claude_direct_worker import _resolve_claude_binary
if _resolve_claude_binary() is not None:
- return ClaudeDirectWorker(
- mcp_servers=_assemble_worker_mcp_servers(task_text=task_text)
+ if _claude_cli_auth_viable():
+ return ClaudeDirectWorker(
+ mcp_servers=_assemble_worker_mcp_servers(task_text=task_text)
+ )
+ logger.warning(
+ "Mission worker: the `claude` CLI is installed but its auth is "
+ "dead/expired (no live OAuth login, no classic Anthropic key) — "
+ "skipping Claude and crossing provider families. Run "
+ "`claude /login` or save a fresh Anthropic key in the API-Keys "
+ "view to restore Claude."
)
# 2. ChatGPT subscription via the codex CLI OAuth login (no API key).
from jarvis.codex_auth_state import codex_needs_reauth
@@ -772,6 +826,15 @@ async def bootstrap_missions(
live_oat = read_live_claude_oauth_token()
if live_oat:
anthropic_key = live_oat
+ elif anthropic_key and anthropic_key.startswith("sk-ant-oat"):
+ # 2026-07-06: no live (non-expired) OAuth login, and the stored
+ # credential is itself an OAuth bearer — i.e. a STALE copy of a
+ # login that no longer exists. Injecting it is a guaranteed 401
+ # ("Failed to authenticate. API Error: 401 Invalid authentication
+ # credentials", missions 019f36e5 + 019f38b1). Drop it so the
+ # worker either runs on a different family (the factory's
+ # viability gate) or fails with the honest "Not logged in".
+ anthropic_key = None
return build_worker_env(
run_dir=mission_dir,
diff --git a/jarvis/missions/isolation/env.py b/jarvis/missions/isolation/env.py
index 736a228f7d..1a1b815742 100644
--- a/jarvis/missions/isolation/env.py
+++ b/jarvis/missions/isolation/env.py
@@ -21,8 +21,10 @@ import json
import logging
import os
import shutil
-from collections.abc import Mapping
+import time
+from collections.abc import Callable, Mapping
from pathlib import Path
+from typing import Literal
from jarvis.missions.workers.process_utils import resolve_node_executable
@@ -285,9 +287,54 @@ _WORKER_CLAUDE_SETTINGS: dict[str, object] = {
}
-def read_live_claude_oauth_token() -> str | None:
- """Return the current Claude Max OAuth access token from the user's
- ``~/.claude/.credentials.json``, or ``None`` if unavailable.
+# Minimum remaining lifetime for an injected OAuth token. A token that dies
+# seconds after the spawn would 401 mid-mission (the isolated worker holds no
+# refresh token), so anything expiring within this slack counts as expired.
+_OAUTH_EXPIRY_SLACK_S: float = 120.0
+
+
+def _claude_credentials_path() -> Path:
+ """Path of the user's live Claude CLI credentials file (test seam)."""
+ return Path(os.path.expanduser("~/.claude/.credentials.json"))
+
+
+def live_claude_oauth_status(
+ *, now_fn: Callable[[], float] = time.time
+) -> Literal["valid", "expired", "absent"]:
+ """Classify the Claude Max OAuth login in ``~/.claude/.credentials.json``.
+
+ - ``"valid"``: an ``sk-ant-oat`` bearer with ``expiresAt`` comfortably in
+ the future (or no ``expiresAt`` at all — older credential shapes stay
+ fail-open).
+ - ``"expired"``: the bearer exists but its ``expiresAt`` has passed (or is
+ within :data:`_OAUTH_EXPIRY_SLACK_S`). Injecting it guarantees a 401 —
+ the isolated worker cannot refresh (2026-07-06 incident, missions
+ 019f36e5 + 019f38b1: token expired 02:53, every spawn died
+ "401 Invalid authentication credentials").
+ - ``"absent"``: no readable ``sk-ant-oat`` bearer at all.
+ """
+ try:
+ data = json.loads(_claude_credentials_path().read_text(encoding="utf-8"))
+ oauth = data.get("claudeAiOauth", {})
+ token = oauth.get("accessToken")
+ expires_at = oauth.get("expiresAt")
+ except (OSError, ValueError, AttributeError, TypeError):
+ return "absent"
+ if not (isinstance(token, str) and token.startswith("sk-ant-oat")):
+ return "absent"
+ if isinstance(expires_at, (int, float)) and expires_at > 0:
+ # `claude` writes epoch milliseconds; tolerate seconds defensively.
+ expires_s = expires_at / 1000.0 if expires_at > 1e12 else float(expires_at)
+ if expires_s <= now_fn() + _OAUTH_EXPIRY_SLACK_S:
+ return "expired"
+ return "valid"
+
+
+def read_live_claude_oauth_token(
+ *, now_fn: Callable[[], float] = time.time
+) -> str | None:
+ """Return the current, NON-EXPIRED Claude Max OAuth access token from the
+ user's ``~/.claude/.credentials.json``, or ``None`` if unavailable.
Why this exists: ``claude`` refreshes its OAuth access token IN PLACE in
that file, but Jarvis' own secret store (Windows Credential Manager / ENV /
@@ -299,10 +346,19 @@ def read_live_claude_oauth_token() -> str | None:
fails with ``401 Invalid authentication`` (verified live 2026-05-29). So we
prefer the live file token. Only OAuth (``sk-ant-oat``) tokens are returned;
a classic API-key user keeps their own key.
+
+ EXPIRY-aware since 2026-07-06: the live file itself can hold a DEAD token —
+ when nothing on the host runs the ``claude`` CLI against that config dir
+ anymore, the access token expires in place and is never refreshed again.
+ Injecting it produced a deterministic 401 on every subagent spawn (missions
+ 019f36e5 + 019f38b1). An expired token is treated exactly like an absent
+ one; the caller's provider-viability gate then routes the worker to a
+ different family instead of a guaranteed-dead Claude spawn.
"""
+ if live_claude_oauth_status(now_fn=now_fn) != "valid":
+ return None
try:
- path = Path(os.path.expanduser("~/.claude/.credentials.json"))
- data = json.loads(path.read_text(encoding="utf-8"))
+ data = json.loads(_claude_credentials_path().read_text(encoding="utf-8"))
token = data.get("claudeAiOauth", {}).get("accessToken")
except (OSError, ValueError, AttributeError, TypeError):
return None
diff --git a/jarvis/missions/kontrollierer/orchestrator.py b/jarvis/missions/kontrollierer/orchestrator.py
index c80ac11b04..5ed6b59ab1 100644
--- a/jarvis/missions/kontrollierer/orchestrator.py
+++ b/jarvis/missions/kontrollierer/orchestrator.py
@@ -166,6 +166,49 @@ def _worker_error_is_transient(err: str) -> bool:
)
)
+
+def _worker_error_is_auth(err: str) -> bool:
+ """True when a worker's terminal error means its provider AUTH is dead.
+
+ Provider-agnostic by design (AP-21/AP-22): every worker kind surfaces its
+ credential failure through this one classifier — the claude CLI's
+ "Failed to authenticate. API Error: 401 Invalid authentication credentials"
+ (2026-07-06, expired Claude Max OAuth token), codex's "Failed to refresh
+ token. Please log in again." (2026-06-08), an API worker's
+ "invalid_api_key" / 401, a CLI's "Not logged in".
+
+ Why it matters: dead auth used to fall through to the fatal task_error
+ branch, killing the mission terminally even though the worker factory is
+ re-consulted on every iteration and — with the dead provider flagged by
+ the worker (claude_auth_dead / codex_needs_reauth) — would pick a HEALTHY
+ family on the retry. Classifying auth as retryable turns a one-provider
+ brick into a cross-family recovery for EVERY worker kind.
+ """
+ if not err:
+ return False
+ err_lower = err.lower()
+ return any(
+ m in err_lower
+ for m in (
+ "failed to authenticate",
+ "invalid authentication",
+ "authentication failed",
+ "authentication_error",
+ "unauthorized",
+ "401",
+ "invalid api key",
+ "invalid x-api-key",
+ "invalid_api_key",
+ "not logged in",
+ "please run /login",
+ "log in again",
+ "login again",
+ "token expired",
+ "expired token",
+ "oauth token has expired",
+ )
+ )
+
# Mission-level wall-clock safety net. Bounds TOTAL execution time across all
# critic iterations + the critic subprocess + decomposition — the per-iteration
# worker cap does not. Measured AFTER the concurrency semaphore is acquired
@@ -1240,6 +1283,14 @@ class Kontrollierer:
# subscription throttles under load (2026-06-09 codex verify:
# task_error rounds were throttle, not a code fault).
is_transient = _worker_error_is_transient(err_lower)
+ # Dead provider AUTH (401 / not logged in / expired token) is
+ # retryable too — not because the credential heals, but because
+ # the worker factory is re-consulted on every iteration and the
+ # failing worker flagged its provider dead (claude_auth_dead /
+ # codex_needs_reauth), so the retry runs on a DIFFERENT family
+ # (2026-07-06: expired Claude OAuth token killed every mission
+ # terminally while codex + OpenRouter were healthy — AP-22).
+ is_auth = _worker_error_is_auth(err_lower)
kill_reason: Literal[
"timeout", "user", "budget", "parent_cancelled",
"injection_detected", "path_guard", "worker_error",
@@ -1271,11 +1322,14 @@ class Kontrollierer:
# diff means nothing was produced (a genuine zero-output hang,
# e.g. Claude Max OAuth contention), so keep the transient-retry
# / hard-fail behaviour for that case.
- if (is_timeout or is_transient) and not _real_diff_is_empty(diff_text):
+ if (
+ is_timeout or is_transient or is_auth
+ ) and not _real_diff_is_empty(diff_text):
logger.warning(
- "Task %s iter %d: worker hit a timeout/transient error but "
- "left a non-empty diff (%d bytes) — grading the partial "
- "work with the critic instead of failing as task_error",
+ "Task %s iter %d: worker hit a timeout/transient/auth "
+ "error but left a non-empty diff (%d bytes) — grading "
+ "the partial work with the critic instead of failing "
+ "as task_error",
step.task_id, iteration, len(diff_text),
)
# Deliberately fall through (no continue / no return): the
@@ -1293,12 +1347,20 @@ class Kontrollierer:
# the whole mission — the heavy-phase semaphore (_mission_sem,
# default 1) serialises the retry so it no longer competes with
# the spawn that just timed out. Budget/auth errors stay fatal.
- elif (is_timeout or is_transient) and iteration < MAX_CRITIC_LOOPS - 1:
+ elif (
+ is_timeout or is_transient or is_auth
+ ) and iteration < MAX_CRITIC_LOOPS - 1:
logger.warning(
"Task %s iter %d: worker %s with no usable output — "
- "retrying on a fresh spawn",
+ "retrying on a fresh spawn%s",
step.task_id, iteration,
- "timed out" if is_timeout else "hit a transient/rate-limit error",
+ "timed out" if is_timeout
+ else "hit a transient/rate-limit error" if is_transient
+ else "hit a dead-auth error (401/not logged in)",
+ "" if not is_auth
+ else "; the worker factory will pick a different "
+ "provider family (the failing provider is flagged "
+ "auth-dead)",
)
continue
else:
diff --git a/jarvis/missions/workers/claude_direct_worker.py b/jarvis/missions/workers/claude_direct_worker.py
index 9cde6a8a92..7e67f818e0 100644
--- a/jarvis/missions/workers/claude_direct_worker.py
+++ b/jarvis/missions/workers/claude_direct_worker.py
@@ -136,6 +136,39 @@ def _claude_error_is_model_unavailable(text: str) -> bool:
return any(m in low for m in _MODEL_UNAVAILABLE_MARKERS)
+# Markers that mean the claude CLI's AUTH surface is dead — an expired/stale
+# OAuth bearer or an invalid API key. Distinct from the quota/usage markers
+# (the login is not exhausted, it is INVALID) and from model-unavailable.
+# Live shapes: "Failed to authenticate. API Error: 401 Invalid authentication
+# credentials" (2026-07-06, expired OAuth token injected into the isolated
+# worker), "Not logged in · Please run /login" (2026-05-29), "Invalid API key ·
+# Fix external API key" (2026-05-18).
+_CLAUDE_AUTH_FAILURE_MARKERS: tuple[str, ...] = (
+ "failed to authenticate",
+ "invalid authentication",
+ "authentication_error",
+ "invalid api key",
+ "invalid x-api-key",
+ "not logged in",
+ "please run /login",
+ "oauth token has expired",
+ "401",
+ "unauthorized",
+)
+
+
+def _claude_error_is_auth_failure(text: str) -> bool:
+ """True when a claude error string signals dead auth (401 / not logged in).
+
+ Dead auth does not reset on a clock (unlike a quota window) — retrying the
+ same credential is a guaranteed second 401. The caller marks
+ ``claude_auth_dead`` so the worker factory crosses provider families until
+ the user runs ``claude /login`` or saves a fresh key (AP-22).
+ """
+ low = (text or "").lower()
+ return any(m in low for m in _CLAUDE_AUTH_FAILURE_MARKERS)
+
+
def _resolve_claude_model(primary: Any) -> str:
"""Resolve the claude-cli ``--model`` this worker actually runs.
@@ -639,11 +672,14 @@ class ClaudeDirectWorker:
)
# A healthy Claude run means the Max window is available again — clear
- # any armed quota cooldown so the factory resumes routing to Claude.
+ # any armed quota cooldown AND any auth-dead flag so the factory
+ # resumes routing to Claude.
if not final_result.is_error and not timed_out:
+ from jarvis.claude_auth_state import clear_claude_auth_dead
from jarvis.claude_quota_state import clear_claude_quota_cooldown
clear_claude_quota_cooldown()
+ clear_claude_auth_dead()
# Model-unavailable recovery (live mission 019ec615, 2026-06-14): the
# configured --model (claude-fable-5) is approved-access-only and the
@@ -697,6 +733,80 @@ class ClaudeDirectWorker:
yield ev
return
+ # Auth-failure recovery (2026-07-06, missions 019f36e5 + 019f38b1 —
+ # the exact mirror of the codex-side 2026-06-08 incident): the Claude
+ # Max OAuth token expired in place (nothing refreshes ~/.claude on
+ # this host anymore) and every spawn died "Failed to authenticate.
+ # API Error: 401" while a healthy codex login + OpenRouter key were
+ # available. Dead auth is not a quota window — it never resets on a
+ # clock — so retrying the same credential is a guaranteed second 401:
+ # 1. ALWAYS mark claude_auth_dead (fingerprinting the credential that
+ # 401'd) so the worker factory routes the rest of the session
+ # cross-family until the user re-authenticates (AP-22).
+ # 2. When codex is reachable, complete THIS mission on the codex
+ # worker in place (subscription-first, same shape as the quota
+ # fallback below). `allow_backend_fallback=False` on the nested
+ # spawn prevents claude->codex->claude ping-pong.
+ if (
+ final_result.is_error
+ and not timed_out
+ and not any_tool_use
+ and _claude_error_is_auth_failure(
+ (final_result.result or "") + "\n" + stderr_text
+ )
+ ):
+ from jarvis.claude_auth_state import (
+ credential_fingerprint,
+ mark_claude_auth_dead,
+ )
+
+ mark_claude_auth_dead(
+ fingerprint=credential_fingerprint(
+ env.get("CLAUDE_CODE_OAUTH_TOKEN")
+ or env.get("ANTHROPIC_API_KEY")
+ )
+ )
+ if allow_backend_fallback:
+ from jarvis.codex_auth_state import codex_needs_reauth
+
+ from .codex_direct_worker import (
+ CodexDirectWorker,
+ _codex_oauth_available,
+ )
+
+ if _codex_oauth_available() and not codex_needs_reauth():
+ logger.warning(
+ "ClaudeDirectWorker[%s]: claude auth is dead (%r) with "
+ "no work delivered — falling back to the codex "
+ "(ChatGPT) worker so the mission completes. Run "
+ "`claude /login` (or save a fresh Anthropic key in the "
+ "API-Keys view) to use Claude again.",
+ worker_id, (final_result.result or "")[:160],
+ )
+ async for ev in CodexDirectWorker().spawn(
+ prompt,
+ worktree=worktree,
+ env=env,
+ job=job,
+ worker_id=worker_id,
+ log_dir=log_dir,
+ model="", # codex picks its ChatGPT default
+ allowed_tools=allowed_tools,
+ max_turns=max_turns,
+ timeout_s=timeout_s,
+ mission_id=mission_id,
+ allow_backend_fallback=False,
+ ):
+ yield ev
+ return
+ logger.error(
+ "ClaudeDirectWorker[%s]: claude auth is dead (%r) and no codex "
+ "login is reachable — surfacing the auth error honestly; the "
+ "worker factory will cross to another provider family on the "
+ "retry. Run `claude /login` to restore Claude.",
+ worker_id, (final_result.result or "")[:160],
+ )
+
# Claude Max quota fallback (mirror of the codex->claude direction).
# Live mission 019eb2fd (2026-06-10 21:23): with the Claude Max
# five-hour window exhausted ("You've hit your session limit · resets
diff --git a/tests/unit/test_claude_auth.py b/tests/unit/test_claude_auth.py
index 9a96ff1fe6..0fe0c5139d 100644
--- a/tests/unit/test_claude_auth.py
+++ b/tests/unit/test_claude_auth.py
@@ -56,22 +56,57 @@ def _service(
def test_oauth_from_credentials_detects_subscription() -> None:
creds = {"claudeAiOauth": {"accessToken": "sk-ant-oat01-abc", "subscriptionType": "max"}}
- connected, sub = _oauth_from_credentials(creds)
+ connected, sub, expired = _oauth_from_credentials(creds)
assert connected is True
assert sub == "max"
+ assert expired is False
def test_oauth_from_credentials_rejects_api_key_token() -> None:
# A classic API key in the bearer slot is NOT a subscription login.
creds = {"claudeAiOauth": {"accessToken": "sk-ant-api03-abc"}}
- connected, sub = _oauth_from_credentials(creds)
+ connected, sub, expired = _oauth_from_credentials(creds)
assert connected is False
assert sub is None
+ assert expired is False
+
+
+def test_oauth_from_credentials_flags_expired_token() -> None:
+ """2026-07-06 incident: the bearer is PRESENT but expiresAt has passed —
+ every API call 401s, so reporting connected=True is a lie that hid the
+ root cause of the all-subagents-fail incident."""
+ creds = {
+ "claudeAiOauth": {
+ "accessToken": "sk-ant-oat01-abc",
+ "subscriptionType": "max",
+ "expiresAt": 1_000.0 * 1000.0, # epoch ms, long past
+ }
+ }
+ connected, sub, expired = _oauth_from_credentials(
+ creds, now_fn=lambda: 2_000.0
+ )
+ assert connected is False
+ assert expired is True
+ assert sub == "max"
+
+
+def test_oauth_from_credentials_future_expiry_is_connected() -> None:
+ creds = {
+ "claudeAiOauth": {
+ "accessToken": "sk-ant-oat01-abc",
+ "expiresAt": 3_000.0 * 1000.0,
+ }
+ }
+ connected, _sub, expired = _oauth_from_credentials(
+ creds, now_fn=lambda: 2_000.0
+ )
+ assert connected is True
+ assert expired is False
@pytest.mark.parametrize("bad", [None, {}, {"claudeAiOauth": "nope"}, {"claudeAiOauth": {}}])
def test_oauth_from_credentials_tolerates_garbage(bad) -> None:
- assert _oauth_from_credentials(bad) == (False, None)
+ assert _oauth_from_credentials(bad) == (False, None, False)
def test_account_from_claude_json_reads_email() -> None:
@@ -134,6 +169,50 @@ def test_status_not_connected_without_creds_or_key(tmp_path, monkeypatch) -> Non
assert st.api_key_present is False
+def test_status_expired_subscription_is_not_connected(tmp_path, monkeypatch) -> None:
+ """The presence-only check reported 'Connected via Claude Max' for a token
+ that had been dead since 02:53 (2026-07-06) — the UI showed green while
+ every subagent spawn 401'd. An expired login must be honest and say how
+ to fix it."""
+ svc = _service(
+ tmp_path,
+ monkeypatch,
+ creds={
+ "claudeAiOauth": {
+ "accessToken": "sk-ant-oat01-x",
+ "subscriptionType": "max",
+ "expiresAt": 1.0, # epoch ms, long past
+ }
+ },
+ claude_json=None,
+ )
+ st = svc.status()
+ assert st.installed is True
+ assert st.connected is False
+ assert "expired" in st.message.lower()
+ assert "/login" in st.message
+
+
+def test_status_expired_oauth_falls_back_to_api_key(tmp_path, monkeypatch) -> None:
+ """Expired subscription login + a configured API key → the key is the
+ honest connected surface (it can still authenticate the CLI/API)."""
+ svc = _service(
+ tmp_path,
+ monkeypatch,
+ creds={
+ "claudeAiOauth": {
+ "accessToken": "sk-ant-oat01-x",
+ "expiresAt": 1.0,
+ }
+ },
+ claude_json=None,
+ api_key_present=True,
+ )
+ st = svc.status()
+ assert st.connected is True
+ assert st.mode == "api_key"
+
+
def test_status_surfaces_api_key_present_even_under_subscription(
tmp_path, monkeypatch
) -> None: