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(providers): resolve the Claude subscription login across all config dirs

Ruben Lütked3d908b878c9
diff --git a/jarvis/claude_auth.py b/jarvis/claude_auth.py
index 08e6a76cb4..b3e4b5c928 100644
--- a/jarvis/claude_auth.py
+++ b/jarvis/claude_auth.py
@@ -4,8 +4,9 @@ Personal Jarvis talks to Anthropic's ``claude`` (Claude Code) CLI in two roles:
* **Subagent** (heavy-task worker) via the ``claude`` binary using the **Claude
Max subscription** (``claude`` stores an OAuth bearer in
- ``~/.claude/.credentials.json``; no per-call billing — it runs against the
- plan's included usage).
+ ``<config dir>/.credentials.json``, resolved across all candidate config
+ dirs by :mod:`jarvis.claude_credentials`; no per-call billing — it runs
+ against the plan's included usage).
* **Brain provider** via the Anthropic Messages API using an **Anthropic API key**
(separate, billed per token on the Anthropic account).
@@ -15,11 +16,13 @@ the UI can render "Connected as <email>" exactly like the Codex / Antigravity
subscription cards. It is the Anthropic sibling of :mod:`jarvis.codex_auth` and
:mod:`jarvis.google_cli.auth_service`.
-Email source: ``claude`` keeps the access bearer (no identity) in
-``~/.claude/.credentials.json``, but the signed-in account identity lives in a
-SEPARATE file, ``~/.claude.json`` under ``oauthAccount`` (``emailAddress``,
-``displayName``, ``organizationName``). The subscription tier (``max`` / ``pro``)
-is in the credentials file under ``claudeAiOauth.subscriptionType``.
+Email source: ``claude`` keeps the access bearer (no identity) in the
+credentials file, but the signed-in account identity lives in a SEPARATE
+file, ``.claude.json`` under ``oauthAccount`` (``emailAddress``,
+``displayName``, ``organizationName``) — the sibling ``~/.claude.json`` for
+the default config dir, or inside a custom ``CLAUDE_CONFIG_DIR``. The
+subscription tier (``max`` / ``pro``) is in the credentials file under
+``claudeAiOauth.subscriptionType``.
Cross-platform (CLOUD.md Rule #1): pure stdlib, ``pathlib``-only, degrades to a
clean "not installed" / "not connected" snapshot on any host where the ``claude``
@@ -39,12 +42,11 @@ 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
+from jarvis.claude_credentials import ClaudeOAuthSnapshot, freshest_claude_oauth
from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
log = logging.getLogger(__name__)
@@ -94,46 +96,6 @@ 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, *, 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", "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, 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, False
- oauth = creds.get("claudeAiOauth")
- if not isinstance(oauth, dict):
- return False, None, False
- token = oauth.get("accessToken")
- 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
- 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(
data: dict[str, Any] | None,
) -> tuple[str | None, str | None]:
@@ -271,6 +233,35 @@ class ClaudeAuthService:
def _claude_json_path(self) -> Path:
return Path(os.path.expanduser("~/.claude.json"))
+ def _oauth_snapshot(self) -> ClaudeOAuthSnapshot:
+ """The freshest OAuth login across all known config dirs (test seam).
+
+ Multi-config-dir aware since 2026-07-10: reading only ``~/.claude``
+ reported "subscription login expired" on a host whose interactive
+ sessions pin ``CLAUDE_CONFIG_DIR`` to a profile-manager dir — the
+ live, freshly-refreshed login next door was never considered.
+ """
+ return freshest_claude_oauth()
+
+ def _identity_path(self, config_dir: Path | None) -> Path:
+ """The ``.claude.json`` identity file that belongs to *config_dir*.
+
+ With the default ``~/.claude`` config dir the CLI keeps the identity
+ as the SIBLING ``~/.claude.json``; with a custom ``CLAUDE_CONFIG_DIR``
+ it lives INSIDE that dir. Falls back to the default-location seam so
+ the card still shows an email when the custom dir has no identity file.
+ """
+ if config_dir is not None and config_dir != Path(
+ os.path.expanduser("~/.claude")
+ ):
+ candidate = config_dir / ".claude.json"
+ try:
+ if candidate.is_file():
+ return candidate
+ except OSError:
+ pass
+ return self._claude_json_path()
+
# -- public API ------------------------------------------------------
def status(self) -> ClaudeAuthStatus:
@@ -290,12 +281,13 @@ class ClaudeAuthService:
)
version = self._probe_version(binary)
- creds = _read_json(self._credentials_path())
- oauth_connected, sub_type, oauth_expired = _oauth_from_credentials(creds)
+ snapshot = self._oauth_snapshot()
+ sub_type = snapshot.subscription_type
+ oauth_expired = snapshot.status == "expired"
- if oauth_connected:
+ if snapshot.status == "valid":
email, _name = _account_from_claude_json(
- _read_json(self._claude_json_path())
+ _read_json(self._identity_path(snapshot.config_dir))
)
label = _subscription_label(sub_type)
message = f"Connected via {label} ({email})." if email else (
@@ -397,7 +389,11 @@ class ClaudeAuthService:
Returns ``(ok, error)``. Removes ONLY ``~/.claude/.credentials.json`` (the
bearer file) — never ``~/.claude.json``, which holds the user's whole
Claude Code config + project history. A missing file counts as success
- (already logged out).
+ (already logged out). Deliberately DEFAULT-DIR only: a login owned by
+ an external profile manager (custom ``CLAUDE_CONFIG_DIR``) also feeds
+ that manager's own live sessions — deleting it here would log those
+ out behind the user's back, so the card may keep reporting connected
+ after a disconnect on such a host.
"""
creds = self._credentials_path()
try:
diff --git a/jarvis/claude_credentials.py b/jarvis/claude_credentials.py
new file mode 100644
index 0000000000..340895c127
--- /dev/null
+++ b/jarvis/claude_credentials.py
@@ -0,0 +1,182 @@
+"""Locate the freshest live Claude CLI OAuth login across config dirs.
+
+The ``claude`` CLI stores its subscription OAuth bearer in
+``<config dir>/.credentials.json`` and refreshes it in place — but only in
+the config dir its sessions actually run with. The default is ``~/.claude``;
+``CLAUDE_CONFIG_DIR`` (the CLI's official override) and multi-profile
+managers pin sessions elsewhere, so the default file silently expires in
+place while the real, freshly-refreshed login lives in another directory.
+
+Reading ONLY ``~/.claude`` then reports "subscription login expired", the
+Jarvis-Agents health banner declares the worker unavailable, and every heavy
+mission diverts to another family — although a perfectly live login sits on
+disk (2026-07-10 incident on a profile-manager-driven host; the same class as
+the 2026-07-06 expired-in-place incident, one directory further left).
+
+One shared rule fixes every reader: enumerate the known candidate config
+dirs and let the FRESHEST live login win. Consumers:
+
+* ``jarvis.missions.isolation.env`` — the token injected into isolated
+ mission workers and the worker-viability gate;
+* ``jarvis.claude_auth.ClaudeAuthService`` — the subscription card in the
+ API-Keys view.
+
+Pure stdlib + pathlib, cross-platform, never raises (CLOUD.md Rule #1): a
+missing directory, file, or profile manager is simply not a candidate.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import time
+from collections.abc import Callable
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Literal
+
+# Minimum remaining lifetime for a login to count as live. An isolated
+# mission worker holds no refresh token, so a bearer dying seconds after the
+# spawn would 401 mid-mission; the status card shares the same rule so the UI
+# and the worker never disagree about "connected".
+OAUTH_EXPIRY_SLACK_S: float = 120.0
+
+# Multi-profile managers keep one Claude config dir per profile and launch
+# every session with CLAUDE_CONFIG_DIR pointing at it — on such a host
+# nothing ever refreshes ~/.claude again, so these profiles are where the
+# live login actually is. Globbed relative to the home dir, best-effort;
+# empty wherever the manager is not installed.
+_PROFILE_MANAGER_GLOBS: tuple[str, ...] = (".bridgespace/ai-profiles/claude/*",)
+
+
+def claude_config_dirs() -> list[Path]:
+ """Candidate Claude CLI config dirs, most authoritative first (test seam).
+
+ Order: ``$CLAUDE_CONFIG_DIR`` (the CLI's official override, when set) →
+ the ``~/.claude`` default → per-profile dirs of known profile managers.
+ Existence is NOT required; readers treat unreadable files as absent.
+ """
+ dirs: list[Path] = []
+ env_dir = os.environ.get("CLAUDE_CONFIG_DIR", "").strip()
+ if env_dir:
+ dirs.append(Path(env_dir).expanduser())
+ home = Path.home()
+ dirs.append(home / ".claude")
+ for pattern in _PROFILE_MANAGER_GLOBS:
+ try:
+ dirs.extend(sorted(p for p in home.glob(pattern) if p.is_dir()))
+ except OSError:
+ continue
+ # Path.__eq__ is already case-insensitive on Windows; dedupe keeps the
+ # first (most authoritative) occurrence.
+ unique: list[Path] = []
+ for d in dirs:
+ if d not in unique:
+ unique.append(d)
+ return unique
+
+
+@dataclass(frozen=True)
+class ClaudeOAuthSnapshot:
+ """The winning Claude OAuth login across all candidate config dirs.
+
+ ``access_token`` is only set while ``status == "valid"`` — an expired
+ bearer is never handed out (injecting it is a guaranteed 401).
+ ``config_dir`` names the directory whose credentials file won, so
+ callers can read sibling files (e.g. the ``.claude.json`` identity)
+ from the SAME login, not a different profile's.
+ """
+
+ status: Literal["valid", "expired", "absent"]
+ access_token: str | None = None
+ subscription_type: str | None = None
+ config_dir: Path | None = None
+ expires_s: float | None = None # epoch seconds; None == no expiry recorded
+
+
+def _parse_oauth_file(
+ path: Path,
+) -> tuple[str, str | None, float | None] | None:
+ """Tolerant parse of one ``.credentials.json``.
+
+ Returns ``(access_token, subscription_type, expires_s)`` for a present
+ ``sk-ant-oat`` bearer, else ``None``. Only OAuth bearers count — a classic
+ API key in the bearer slot is not a subscription login.
+ """
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return None
+ oauth = data.get("claudeAiOauth") if isinstance(data, dict) else None
+ if not isinstance(oauth, dict):
+ return None
+ token = oauth.get("accessToken")
+ if not (isinstance(token, str) and token.startswith("sk-ant-oat")):
+ return None
+ sub_type = oauth.get("subscriptionType")
+ sub_type = sub_type if isinstance(sub_type, str) and sub_type else None
+ expires_at = oauth.get("expiresAt")
+ expires_s: float | None = None
+ 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)
+ return token, sub_type, expires_s
+
+
+def freshest_claude_oauth(*, now_fn: Callable[[], float] = time.time) -> ClaudeOAuthSnapshot:
+ """Scan every candidate config dir; the freshest LIVE login wins.
+
+ - ``"valid"``: at least one non-expired bearer exists; the one with the
+ farthest ``expiresAt`` is returned (no ``expiresAt`` at all stays
+ fail-open for older credential shapes and sorts as farthest).
+ - ``"expired"``: bearers exist but every one has died in place; the
+ least-stale one is the reference (its tier feeds the UI message).
+ - ``"absent"``: no readable ``sk-ant-oat`` bearer anywhere.
+
+ Cheap and offline — a handful of small file reads, never a subprocess or
+ network probe, so health checks may call it freely.
+ """
+ horizon = now_fn() + OAUTH_EXPIRY_SLACK_S
+ best_valid: tuple[float, ClaudeOAuthSnapshot] | None = None
+ best_expired: tuple[float, ClaudeOAuthSnapshot] | None = None
+ for config_dir in claude_config_dirs():
+ parsed = _parse_oauth_file(config_dir / ".credentials.json")
+ if parsed is None:
+ continue
+ token, sub_type, expires_s = parsed
+ if expires_s is None or expires_s > horizon:
+ sort_key = float("inf") if expires_s is None else expires_s
+ if best_valid is None or sort_key > best_valid[0]:
+ best_valid = (
+ sort_key,
+ ClaudeOAuthSnapshot(
+ status="valid",
+ access_token=token,
+ subscription_type=sub_type,
+ config_dir=config_dir,
+ expires_s=expires_s,
+ ),
+ )
+ elif best_expired is None or expires_s > best_expired[0]:
+ best_expired = (
+ expires_s,
+ ClaudeOAuthSnapshot(
+ status="expired",
+ subscription_type=sub_type,
+ config_dir=config_dir,
+ expires_s=expires_s,
+ ),
+ )
+ if best_valid is not None:
+ return best_valid[1]
+ if best_expired is not None:
+ return best_expired[1]
+ return ClaudeOAuthSnapshot(status="absent")
+
+
+__all__ = [
+ "OAUTH_EXPIRY_SLACK_S",
+ "ClaudeOAuthSnapshot",
+ "claude_config_dirs",
+ "freshest_claude_oauth",
+]
diff --git a/jarvis/missions/isolation/env.py b/jarvis/missions/isolation/env.py
index 1a1b815742..e9a816f492 100644
--- a/jarvis/missions/isolation/env.py
+++ b/jarvis/missions/isolation/env.py
@@ -287,84 +287,57 @@ _WORKER_CLAUDE_SETTINGS: dict[str, object] = {
}
-# 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``.
+ """Classify the user's Claude Max OAuth login (freshest config dir wins).
- ``"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").
+ - ``"expired"``: bearers exist but every one has died in place. Injecting
+ one 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.
+
+ Multi-config-dir aware since 2026-07-10: the login is looked up across
+ ALL candidate config dirs (``CLAUDE_CONFIG_DIR``, ``~/.claude``, profile
+ managers) via :func:`jarvis.claude_credentials.freshest_claude_oauth` —
+ a host whose interactive sessions pin a different config dir keeps a
+ stale ``~/.claude`` copy that must not shadow the live login next door.
"""
- 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"
+ from jarvis.claude_credentials import freshest_claude_oauth
+
+ return freshest_claude_oauth(now_fn=now_fn).status
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.
+ freshest of the user's Claude config dirs, 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 /
- ``.env``) can hold a STALE copy from an earlier login. Pre-fix, that didn't
- matter — the worker ran with the *user's* config dir and ``claude`` read
- the live file itself. Once the worker is pinned to an isolated
- CLAUDE_CONFIG_DIR (see ``build_worker_env``), the injected
+ its credentials file, but Jarvis' own secret store (Windows Credential
+ Manager / ENV / ``.env``) can hold a STALE copy from an earlier login.
+ Pre-fix, that didn't matter — the worker ran with the *user's* config dir
+ and ``claude`` read the live file itself. Once the worker is pinned to an
+ isolated CLAUDE_CONFIG_DIR (see ``build_worker_env``), the injected
``CLAUDE_CODE_OAUTH_TOKEN`` becomes the only auth surface, and a stale token
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.
+ EXPIRY-aware since 2026-07-06 and multi-config-dir aware since 2026-07-10
+ (see :func:`live_claude_oauth_status`): 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 —
+ and a live login in a non-default config dir wins over the stale default.
"""
- if live_claude_oauth_status(now_fn=now_fn) != "valid":
- return None
- try:
- data = json.loads(_claude_credentials_path().read_text(encoding="utf-8"))
- token = data.get("claudeAiOauth", {}).get("accessToken")
- except (OSError, ValueError, AttributeError, TypeError):
- return None
- if isinstance(token, str) and token.startswith("sk-ant-oat"):
- return token
- return None
+ from jarvis.claude_credentials import freshest_claude_oauth
+
+ return freshest_claude_oauth(now_fn=now_fn).access_token
def _seed_worker_claude_config(run_dir: Path) -> Path:
diff --git a/tests/missions/test_env_oauth_expiry.py b/tests/missions/test_env_oauth_expiry.py
index 8a700f9c3b..a1feeca65a 100644
--- a/tests/missions/test_env_oauth_expiry.py
+++ b/tests/missions/test_env_oauth_expiry.py
@@ -1,4 +1,4 @@
-"""The live Claude OAuth token reader must be EXPIRY-aware.
+"""The live Claude OAuth token reader must be EXPIRY- and multi-dir-aware.
Forensic ground truth (2026-07-06, missions 019f36e5 + 019f38b1): the Claude
Max OAuth access token in ``~/.claude/.credentials.json`` expired at 02:53 and
@@ -9,9 +9,14 @@ injected it as ``CLAUDE_CODE_OAUTH_TOKEN``, and the worker — pinned to an
isolated CLAUDE_CONFIG_DIR with no refresh token — failed every spawn with
"Failed to authenticate. API Error: 401 Invalid authentication credentials".
+Second half of the same class (2026-07-10): the freshly-refreshed login that
+DID exist sat in the profile-manager config dir the readers never looked at,
+so the app declared the Claude worker dead while a live login was on disk.
+
Contract under test: a token whose ``expiresAt`` lies in the past is treated
as ABSENT (never injected); a missing ``expiresAt`` stays fail-open so older
-CLI credential shapes keep working.
+CLI credential shapes keep working; and the freshest live login across ALL
+candidate config dirs wins over a stale default-dir copy.
"""
from __future__ import annotations
@@ -20,21 +25,24 @@ from pathlib import Path
import pytest
+from jarvis import claude_credentials
from jarvis.missions.isolation import env as env_mod
# Test fixtures, not real credentials.
_TEST_OAT = "sk-ant-oat01-test-token" # noqa: S105 — test fixture, not a real token
+_TEST_OAT_FRESH = "sk-ant-oat01-fresh-token" # noqa: S105 — test fixture
_TEST_CLASSIC_KEY = "sk-ant-api03-classic-key" # noqa: S105 — test fixture
def _write_credentials(
- tmp_path: Path,
+ config_dir: Path,
*,
token: str = _TEST_OAT,
expires_at_ms: float | None = None,
omit_expiry: bool = False,
) -> Path:
- creds = tmp_path / ".credentials.json"
+ config_dir.mkdir(parents=True, exist_ok=True)
+ creds = config_dir / ".credentials.json"
oauth: dict[str, object] = {"accessToken": token}
if not omit_expiry and expires_at_ms is not None:
oauth["expiresAt"] = expires_at_ms
@@ -44,8 +52,9 @@ def _write_credentials(
return creds
-def _pin_credentials_path(monkeypatch: pytest.MonkeyPatch, path: Path) -> None:
- monkeypatch.setattr(env_mod, "_claude_credentials_path", lambda: path)
+def _pin_config_dirs(monkeypatch: pytest.MonkeyPatch, dirs: list[Path]) -> None:
+ """Pin the candidate config dirs the readers scan (hermetic tests)."""
+ monkeypatch.setattr(claude_credentials, "claude_config_dirs", lambda: dirs)
NOW_S = 1_783_300_000.0 # arbitrary fixed wall clock for the tests
@@ -54,10 +63,8 @@ NOW_S = 1_783_300_000.0 # arbitrary fixed wall clock for the tests
def test_valid_token_is_returned(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
- creds = _write_credentials(
- tmp_path, expires_at_ms=(NOW_S + 3600.0) * 1000.0
- )
- _pin_credentials_path(monkeypatch, creds)
+ _write_credentials(tmp_path, expires_at_ms=(NOW_S + 3600.0) * 1000.0)
+ _pin_config_dirs(monkeypatch, [tmp_path])
token = env_mod.read_live_claude_oauth_token(now_fn=lambda: NOW_S)
assert token == _TEST_OAT
assert env_mod.live_claude_oauth_status(now_fn=lambda: NOW_S) == "valid"
@@ -67,10 +74,8 @@ def test_expired_token_is_never_returned(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""The 2026-07-06 shape: expiresAt hours in the past → treat as absent."""
- creds = _write_credentials(
- tmp_path, expires_at_ms=(NOW_S - 18 * 3600.0) * 1000.0
- )
- _pin_credentials_path(monkeypatch, creds)
+ _write_credentials(tmp_path, expires_at_ms=(NOW_S - 18 * 3600.0) * 1000.0)
+ _pin_config_dirs(monkeypatch, [tmp_path])
assert env_mod.read_live_claude_oauth_token(now_fn=lambda: NOW_S) is None
assert env_mod.live_claude_oauth_status(now_fn=lambda: NOW_S) == "expired"
@@ -79,10 +84,8 @@ def test_token_expiring_within_slack_is_treated_as_expired(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A token that dies seconds from now would 401 mid-mission — skip it."""
- creds = _write_credentials(
- tmp_path, expires_at_ms=(NOW_S + 10.0) * 1000.0
- )
- _pin_credentials_path(monkeypatch, creds)
+ _write_credentials(tmp_path, expires_at_ms=(NOW_S + 10.0) * 1000.0)
+ _pin_config_dirs(monkeypatch, [tmp_path])
assert env_mod.read_live_claude_oauth_token(now_fn=lambda: NOW_S) is None
@@ -90,8 +93,8 @@ def test_missing_expiry_field_stays_fail_open(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Older credential shapes without expiresAt keep working (back-compat)."""
- creds = _write_credentials(tmp_path, omit_expiry=True)
- _pin_credentials_path(monkeypatch, creds)
+ _write_credentials(tmp_path, omit_expiry=True)
+ _pin_config_dirs(monkeypatch, [tmp_path])
token = env_mod.read_live_claude_oauth_token(now_fn=lambda: NOW_S)
assert token == _TEST_OAT
assert env_mod.live_claude_oauth_status(now_fn=lambda: NOW_S) == "valid"
@@ -100,7 +103,7 @@ def test_missing_expiry_field_stays_fail_open(
def test_absent_file_reports_absent(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
- _pin_credentials_path(monkeypatch, tmp_path / "nope" / ".credentials.json")
+ _pin_config_dirs(monkeypatch, [tmp_path / "nope"])
assert env_mod.read_live_claude_oauth_token(now_fn=lambda: NOW_S) is None
assert env_mod.live_claude_oauth_status(now_fn=lambda: NOW_S) == "absent"
@@ -109,10 +112,30 @@ def test_non_oat_token_reports_absent(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Only sk-ant-oat bearers count — anything else is not a live OAuth login."""
- creds = _write_credentials(
+ _write_credentials(
tmp_path, token=_TEST_CLASSIC_KEY,
expires_at_ms=(NOW_S + 3600.0) * 1000.0,
)
- _pin_credentials_path(monkeypatch, creds)
+ _pin_config_dirs(monkeypatch, [tmp_path])
assert env_mod.read_live_claude_oauth_token(now_fn=lambda: NOW_S) is None
assert env_mod.live_claude_oauth_status(now_fn=lambda: NOW_S) == "absent"
+
+
+def test_fresh_profile_login_wins_over_stale_default(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The 2026-07-10 shape: ~/.claude expired in place while the profile
+ manager's config dir holds the real, freshly-refreshed login — the live
+ token must be injected instead of declaring the Claude worker dead."""
+ default_dir = tmp_path / "dot-claude"
+ profile_dir = tmp_path / "profile"
+ _write_credentials(default_dir, expires_at_ms=(NOW_S - 48 * 3600.0) * 1000.0)
+ _write_credentials(
+ profile_dir,
+ token=_TEST_OAT_FRESH,
+ expires_at_ms=(NOW_S + 4 * 3600.0) * 1000.0,
+ )
+ _pin_config_dirs(monkeypatch, [default_dir, profile_dir])
+ token = env_mod.read_live_claude_oauth_token(now_fn=lambda: NOW_S)
+ assert token == _TEST_OAT_FRESH
+ assert env_mod.live_claude_oauth_status(now_fn=lambda: NOW_S) == "valid"
diff --git a/tests/unit/brain/test_section_health.py b/tests/unit/brain/test_section_health.py
index 33a64109a6..a7b36f4a43 100644
--- a/tests/unit/brain/test_section_health.py
+++ b/tests/unit/brain/test_section_health.py
@@ -144,3 +144,55 @@ class TestSubagentSectionHealth:
health = pr._jarvis_agent_section_health(self._cfg())
assert health.status == sh.ERROR
assert health.reason == "no_provider"
+
+ def test_degraded_label_says_subscription_for_oauth_user(
+ self, monkeypatch, tmp_path
+ ) -> None:
+ """2026-07-10 report: the banner blamed 'Claude (API-Key)' although the
+ user runs the worker on the Claude subscription login — the degraded
+ message must name the auth mode actually in play."""
+ import json
+
+ from jarvis import claude_credentials
+ from jarvis.ui.web import provider_routes as pr
+
+ (tmp_path / ".credentials.json").write_text(
+ json.dumps(
+ {
+ "claudeAiOauth": {
+ "accessToken": "sk-ant-oat01-x",
+ "expiresAt": 1.0, # expired-in-place — still an OAuth user
+ }
+ }
+ ),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(
+ claude_credentials, "claude_config_dirs", lambda: [tmp_path]
+ )
+ monkeypatch.setattr(pr, "_worker_usable", lambda p: False)
+ monkeypatch.setattr(pr, "_worker_flagged_dead", lambda p: True)
+ monkeypatch.setattr(
+ "jarvis.missions.init.reachable_worker_families", lambda: ["codex"]
+ )
+ health = pr._jarvis_agent_section_health(self._cfg())
+ assert "Claude (subscription)" in health.detail
+ assert "API-Key" not in health.detail
+
+ def test_degraded_label_keeps_api_key_for_keyed_user(
+ self, monkeypatch, tmp_path
+ ) -> None:
+ from jarvis import claude_credentials
+ from jarvis.ui.web import provider_routes as pr
+
+ # No OAuth bearer anywhere → the user really is on the API-key path.
+ monkeypatch.setattr(
+ claude_credentials, "claude_config_dirs", lambda: [tmp_path]
+ )
+ monkeypatch.setattr(pr, "_worker_usable", lambda p: False)
+ monkeypatch.setattr(pr, "_worker_flagged_dead", lambda p: True)
+ monkeypatch.setattr(
+ "jarvis.missions.init.reachable_worker_families", lambda: ["codex"]
+ )
+ health = pr._jarvis_agent_section_health(self._cfg())
+ assert "Claude (API-Key)" in health.detail
diff --git a/tests/unit/test_claude_auth.py b/tests/unit/test_claude_auth.py
index e23f86f7a4..2dbdc572b7 100644
--- a/tests/unit/test_claude_auth.py
+++ b/tests/unit/test_claude_auth.py
@@ -12,11 +12,10 @@ from pathlib import Path
import pytest
-from jarvis import claude_auth
+from jarvis import claude_auth, claude_credentials
from jarvis.claude_auth import (
ClaudeAuthService,
_account_from_claude_json,
- _oauth_from_credentials,
_subscription_label,
)
@@ -35,7 +34,12 @@ def _service(
binary: str | None = "/usr/bin/claude",
api_key_present: bool = False,
) -> ClaudeAuthService:
- """Build a service whose seams point at temp files / a stubbed binary."""
+ """Build a service whose seams point at temp files / a stubbed binary.
+
+ ``tmp_path`` acts as the single candidate Claude config dir (pinned via
+ ``claude_credentials.claude_config_dirs``), so the OAuth snapshot reads
+ the temp credentials file — hermetic against the host's real logins.
+ """
creds_path = tmp_path / ".credentials.json"
claude_json_path = tmp_path / ".claude.json"
if creds is not None:
@@ -44,6 +48,9 @@ def _service(
claude_json_path.write_text(json.dumps(claude_json), encoding="utf-8")
svc = ClaudeAuthService(api_key_present=api_key_present)
+ monkeypatch.setattr(
+ claude_credentials, "claude_config_dirs", lambda: [tmp_path]
+ )
monkeypatch.setattr(svc, "_resolve_binary", lambda: binary)
monkeypatch.setattr(svc, "_probe_version", lambda _b: "claude 1.2.3")
monkeypatch.setattr(svc, "_credentials_path", lambda: creds_path)
@@ -52,65 +59,8 @@ def _service(
# -- pure helpers -------------------------------------------------------
-
-
-def test_oauth_from_credentials_detects_subscription() -> None:
- creds = {"claudeAiOauth": {"accessToken": "sk-ant-oat01-abc", "subscriptionType": "max"}}
- 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, 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. Uses the incident's real
- epoch-ms shape: token expired 02:53, status probed 20:30 the same day."""
- expired_at_ms = 1_783_299_232_815 # 2026-07-06T02:53:52 (epoch ms)
- probed_at_s = 1_783_362_600.0 # 2026-07-06T20:30:00 (epoch s)
- creds = {
- "claudeAiOauth": {
- "accessToken": "sk-ant-oat01-abc",
- "subscriptionType": "max",
- "expiresAt": expired_at_ms,
- }
- }
- connected, sub, expired = _oauth_from_credentials(
- creds, now_fn=lambda: probed_at_s
- )
- assert connected is False
- assert expired is True
- assert sub == "max"
-
-
-def test_oauth_from_credentials_future_expiry_is_connected() -> None:
- now_s = 1_783_362_600.0
- creds = {
- "claudeAiOauth": {
- "accessToken": "sk-ant-oat01-abc",
- "expiresAt": (now_s + 4 * 3600.0) * 1000.0, # epoch ms, hours ahead
- }
- }
- connected, _sub, expired = _oauth_from_credentials(
- creds, now_fn=lambda: now_s
- )
- assert connected is True
- assert expired is False
-
-
[email protected]("bad", [None, {}, {"claudeAiOauth": "nope"}, {"claudeAiOauth": {}}])
-def test_oauth_from_credentials_tolerates_garbage(bad) -> None:
- assert _oauth_from_credentials(bad) == (False, None, False)
+# (credential parsing/expiry/multi-dir selection is covered by
+# tests/unit/test_claude_credentials.py — the shared locator owns it now)
def test_account_from_claude_json_reads_email() -> None:
@@ -235,6 +185,62 @@ def test_status_surfaces_api_key_present_even_under_subscription(
assert st.api_key_present is True
+def test_status_connected_via_fresh_profile_when_default_is_stale(
+ tmp_path, monkeypatch
+) -> None:
+ """2026-07-10 incident: ~/.claude held a login that expired in place while
+ the profile manager's config dir (where every interactive session actually
+ runs) held a freshly-refreshed one. The card said "subscription login has
+ expired" and the Jarvis-Agents banner diverted missions to codex although
+ a live login sat on disk. The freshest login must win — including reading
+ the account identity from the WINNING dir, not the stale default's."""
+ default_dir = tmp_path / "dot-claude"
+ profile_dir = tmp_path / "profile"
+ for d in (default_dir, profile_dir):
+ d.mkdir()
+ (default_dir / ".credentials.json").write_text(
+ json.dumps(
+ {
+ "claudeAiOauth": {
+ "accessToken": "sk-ant-oat01-stale",
+ "subscriptionType": "max",
+ "expiresAt": 1.0, # epoch ms, long past
+ }
+ }
+ ),
+ encoding="utf-8",
+ )
+ (profile_dir / ".credentials.json").write_text(
+ json.dumps(
+ {
+ "claudeAiOauth": {
+ "accessToken": "sk-ant-oat01-fresh",
+ "subscriptionType": "max",
+ "expiresAt": 4_102_444_800_000.0, # epoch ms, far future
+ }
+ }
+ ),
+ encoding="utf-8",
+ )
+ (profile_dir / ".claude.json").write_text(
+ json.dumps({"oauthAccount": {"emailAddress": "[email protected]"}}),
+ encoding="utf-8",
+ )
+
+ svc = ClaudeAuthService()
+ monkeypatch.setattr(
+ claude_credentials,
+ "claude_config_dirs",
+ lambda: [default_dir, profile_dir],
+ )
+ monkeypatch.setattr(svc, "_resolve_binary", lambda: "/usr/bin/claude")
+ monkeypatch.setattr(svc, "_probe_version", lambda _b: "claude 1.2.3")
+ st = svc.status()
+ assert st.connected is True
+ assert st.mode == "subscription"
+ assert st.user_email == "[email protected]"
+
+
def test_status_api_key_present_when_not_installed(tmp_path, monkeypatch) -> None:
# The key field stays "configured" even if the CLI binary is absent — the
# stored key is independent of the local install.
diff --git a/tests/unit/test_claude_credentials.py b/tests/unit/test_claude_credentials.py
new file mode 100644
index 0000000000..03a84c9b3d
--- /dev/null
+++ b/tests/unit/test_claude_credentials.py
@@ -0,0 +1,214 @@
+"""The shared Claude credentials locator must let the FRESHEST login win.
+
+Forensic ground truth (2026-07-10): every interactive Claude session on the
+maintainer host runs through a profile manager that pins ``CLAUDE_CONFIG_DIR``
+to a per-profile directory, so ``~/.claude/.credentials.json`` expired in
+place on 07-08 while a freshly-refreshed login sat in the profile dir. Both
+hardcoded ``~/.claude`` readers (mission-worker token injection and the
+subscription card) reported "expired", the Jarvis-Agents banner declared the
+worker unavailable, and every mission diverted to codex — although a live
+login existed on disk the whole time.
+
+Contract under test: ``freshest_claude_oauth`` scans every candidate config
+dir and returns the live login with the farthest expiry; only when NO
+candidate is live does it report expired/absent.
+"""
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from jarvis import claude_credentials as cc
+
+# Test fixtures, not real credentials.
+_TEST_OAT = "sk-ant-oat01-test-token" # noqa: S105 — test fixture, not a real token
+_TEST_OAT_2 = "sk-ant-oat01-second-token" # noqa: S105 — test fixture
+_TEST_CLASSIC_KEY = "sk-ant-api03-classic-key" # noqa: S105 — test fixture
+
+NOW_S = 1_783_300_000.0 # arbitrary fixed wall clock for the tests
+
+
+def _write_credentials(
+ config_dir: Path,
+ *,
+ token: str = _TEST_OAT,
+ expires_at_ms: float | None = None,
+ subscription_type: str | None = None,
+) -> Path:
+ config_dir.mkdir(parents=True, exist_ok=True)
+ oauth: dict[str, object] = {"accessToken": token}
+ if expires_at_ms is not None:
+ oauth["expiresAt"] = expires_at_ms
+ if subscription_type is not None:
+ oauth["subscriptionType"] = subscription_type
+ creds = config_dir / ".credentials.json"
+ creds.write_text(json.dumps({"claudeAiOauth": oauth}), encoding="utf-8")
+ return creds
+
+
+def _pin_dirs(monkeypatch: pytest.MonkeyPatch, dirs: list[Path]) -> None:
+ monkeypatch.setattr(cc, "claude_config_dirs", lambda: dirs)
+
+
+# -- freshest_claude_oauth ----------------------------------------------
+
+
+def test_single_valid_login_is_returned(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ d = tmp_path / "default"
+ _write_credentials(
+ d, expires_at_ms=(NOW_S + 3600.0) * 1000.0, subscription_type="max"
+ )
+ _pin_dirs(monkeypatch, [d])
+ snap = cc.freshest_claude_oauth(now_fn=lambda: NOW_S)
+ assert snap.status == "valid"
+ assert snap.access_token == _TEST_OAT
+ assert snap.subscription_type == "max"
+ assert snap.config_dir == d
+
+
+def test_valid_profile_login_beats_expired_default(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """THE 2026-07-10 shape: ~/.claude expired in place, the profile-manager
+ dir holds the real, freshly-refreshed login — the login must win."""
+ default = tmp_path / "dot-claude"
+ profile = tmp_path / "profile"
+ _write_credentials(default, expires_at_ms=(NOW_S - 48 * 3600.0) * 1000.0)
+ _write_credentials(
+ profile, token=_TEST_OAT_2, expires_at_ms=(NOW_S + 4 * 3600.0) * 1000.0
+ )
+ _pin_dirs(monkeypatch, [default, profile])
+ snap = cc.freshest_claude_oauth(now_fn=lambda: NOW_S)
+ assert snap.status == "valid"
+ assert snap.access_token == _TEST_OAT_2
+ assert snap.config_dir == profile
+
+
+def test_freshest_of_two_valid_logins_wins(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ older = tmp_path / "older"
+ fresher = tmp_path / "fresher"
+ _write_credentials(older, expires_at_ms=(NOW_S + 600.0) * 1000.0)
+ _write_credentials(
+ fresher, token=_TEST_OAT_2, expires_at_ms=(NOW_S + 7200.0) * 1000.0
+ )
+ _pin_dirs(monkeypatch, [older, fresher])
+ snap = cc.freshest_claude_oauth(now_fn=lambda: NOW_S)
+ assert snap.access_token == _TEST_OAT_2
+ assert snap.config_dir == fresher
+
+
+def test_all_expired_reports_expired(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ a = tmp_path / "a"
+ b = tmp_path / "b"
+ _write_credentials(
+ a, expires_at_ms=(NOW_S - 3600.0) * 1000.0, subscription_type="max"
+ )
+ _write_credentials(b, expires_at_ms=(NOW_S - 7200.0) * 1000.0)
+ _pin_dirs(monkeypatch, [a, b])
+ snap = cc.freshest_claude_oauth(now_fn=lambda: NOW_S)
+ assert snap.status == "expired"
+ assert snap.access_token is None
+ # The least-stale candidate is the reference (its tier feeds the UI).
+ assert snap.config_dir == a
+ assert snap.subscription_type == "max"
+
+
+def test_no_readable_bearer_reports_absent(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _pin_dirs(monkeypatch, [tmp_path / "missing"])
+ snap = cc.freshest_claude_oauth(now_fn=lambda: NOW_S)
+ assert snap.status == "absent"
+ assert snap.access_token is None
+ assert snap.config_dir is None
+
+
+def test_classic_api_key_in_bearer_slot_is_absent(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ d = tmp_path / "d"
+ _write_credentials(
+ d, token=_TEST_CLASSIC_KEY, expires_at_ms=(NOW_S + 3600.0) * 1000.0
+ )
+ _pin_dirs(monkeypatch, [d])
+ assert cc.freshest_claude_oauth(now_fn=lambda: NOW_S).status == "absent"
+
+
+def test_missing_expiry_stays_fail_open_valid(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Older credential shapes without expiresAt keep working (back-compat)."""
+ d = tmp_path / "d"
+ _write_credentials(d)
+ _pin_dirs(monkeypatch, [d])
+ snap = cc.freshest_claude_oauth(now_fn=lambda: NOW_S)
+ assert snap.status == "valid"
+ assert snap.access_token == _TEST_OAT
+
+
+def test_token_expiring_within_slack_is_expired(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A bearer dying seconds from now would 401 mid-mission — never live."""
+ d = tmp_path / "d"
+ _write_credentials(d, expires_at_ms=(NOW_S + 10.0) * 1000.0)
+ _pin_dirs(monkeypatch, [d])
+ assert cc.freshest_claude_oauth(now_fn=lambda: NOW_S).status == "expired"
+
+
+def test_garbage_file_is_tolerated_as_absent(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ d = tmp_path / "d"
+ d.mkdir()
+ (d / ".credentials.json").write_text("{not json", encoding="utf-8")
+ _pin_dirs(monkeypatch, [d])
+ assert cc.freshest_claude_oauth(now_fn=lambda: NOW_S).status == "absent"
+
+
+# -- claude_config_dirs --------------------------------------------------
+
+
+def test_config_dirs_env_override_comes_first(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ home = tmp_path / "home"
+ home.mkdir()
+ env_dir = tmp_path / "pinned-profile"
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(env_dir))
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: home))
+ dirs = cc.claude_config_dirs()
+ assert dirs[0] == env_dir
+ assert home / ".claude" in dirs
+
+
+def test_config_dirs_include_profile_manager_profiles(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ home = tmp_path / "home"
+ profile = home / ".bridgespace" / "ai-profiles" / "claude" / "prof_x"
+ profile.mkdir(parents=True)
+ monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False)
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: home))
+ dirs = cc.claude_config_dirs()
+ assert dirs[0] == home / ".claude"
+ assert profile in dirs
+
+
+def test_config_dirs_deduplicate_env_and_default(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ home = tmp_path / "home"
+ home.mkdir()
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(home / ".claude"))
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: home))
+ dirs = cc.claude_config_dirs()
+ assert dirs.count(home / ".claude") == 1