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(agent-accounts): stop the switcher naming the wrong subscription

Ruben Lütke132af82f00f3
diff --git a/docs/BUGS.md b/docs/BUGS.md
index acbf6d7b5e..c5bc507ace 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -7733,3 +7733,97 @@ scheduling turns a slow consumer into a compounding delay, and the first thing
that delay eats is the user's own keystrokes. The same rule governs the far end
— never render for a surface nobody is looking at, because that thread is
usually the one holding the keyboard.
+
+## BUG-112: the subscription switcher names the wrong account — panes run on a plan the user never selected (HIGH, FIXED 2026-07-27)
+
+**Symptom (desktop field report, with screenshots).** In *Workspace settings →
+Your subscriptions*, two Claude rows showed the SAME email, and the row marked
+"in use" named a subscription the user was not actually on. The only visible
+evidence was arithmetic: the account named in the switcher had ~9 % of its
+weekly limit left, while the plan the terminals were really spending had ~1 %.
+Nothing in the UI was red — both rows were green, both said "Signed in via
+Claude Max", and the user could only tell something was wrong by comparing the
+usage page against what the switcher claimed.
+
+**Root cause A — a fixed preference over two identity files.** Claude Code can
+keep its signed-in identity in either `~/.claude.json` or
+`~/.claude/.claude.json`, depending on release. `claude_account_identity()`
+built a candidate list and returned the FIRST one that parsed:
+
+```python
+candidates = [config_dir / ".claude.json"] # ← always won
+if config_dir == Path(os.path.expanduser("~/.claude")):
+ candidates.append(Path(os.path.expanduser("~/.claude.json")))
+for candidate in candidates:
+ ...
+ if email or name:
+ return email, name
+```
+
+On the reporting machine `~/.claude/.claude.json` was an abandoned copy from an
+earlier release, last written **ten days** before the report; the live
+`~/.claude.json` next to it was minutes old and named a different account. The
+list order alone decided, so the switcher confidently displayed the previous
+occupant of that directory and the default login appeared to be someone it had
+not been for a week and a half.
+
+The same ordering bug sat in `ClaudeAuthService._identity_path()`, which
+additionally fell back to `~/.claude.json` for a CUSTOM config dir — so an
+added account with no identity file of its own borrowed the DEFAULT login's
+email and displayed it as its own. That fallback existed to make sure the card
+"still shows an email"; showing the wrong one is worse than showing none.
+
+**Root cause B — a second sign-in silently reuses the first account.** The
+CLI's OAuth flow is a browser redirect. With a live claude.com session, the
+browser approves the new authorization against the account it is already signed
+in with, without an account chooser and without ever reaching the "paste this
+code" step — the sign-in terminal sits at `Paste code here if prompted >`
+while the browser page just says the user is signed in. The result is two
+registered accounts holding ONE subscription. Both rows go green, both name a
+valid plan, and the only symptom is one plan's usage draining twice as fast:
+precisely the feature's whole purpose, inverted, with no signal anywhere.
+
+**Fix.**
+- `jarvis/claude_auth.py` — `claude_account_identity()` now picks the
+ **freshest readable** candidate by mtime instead of the first in a list: the
+ file the installed CLI actually keeps current is the truth, the same
+ "most recently refreshed wins" rule `freshest_claude_oauth()` already applies
+ to credentials. `_identity_path()` follows the same rule, and a custom config
+ dir no longer falls back to the home identity — no email beats a wrong one.
+- `_is_default_config_dir()` builds the comparison from `Path.home()` and
+ compares through `os.path.normcase`, replacing a hand-written `"~/.claude"`
+ string, so the home-level candidate is considered on macOS and Linux too and
+ survives a differently-cased Windows path (CLAUDE.md §3).
+- `jarvis/agent_accounts.py` — `snapshots()` groups connected accounts by email
+ and flags every row after the first as a duplicate of the account it collides
+ with, naming it and saying how to avoid it (sign out at claude.com, or use a
+ private window). Accounts with no readable email are never grouped: "both
+ unknown" is absence of evidence, not evidence of sameness. New display-safe
+ `AccountSnapshot.warning`, carried through `to_dict()` and rendered by
+ `AgentAccountsPanel`.
+- `jarvis/ui/web/agent_accounts_routes.py` — the sign-in response now states
+ the browser-session trap up front, at the moment the user is about to hit it.
+
+**Deliberately NOT done.** An "identity older than its credentials is stale"
+guard reads like the obvious extra safeguard and is wrong: the CLI refreshes
+the bearer in place indefinitely while never rewriting the identity, so on any
+long-lived account the identity is legitimately the older file. That rule would
+blank the email on exactly the accounts that work. It is written into the
+docstring so it does not get "fixed" back in.
+
+**Regression guard.** `tests/unit/test_claude_auth.py` — freshest-wins in both
+directions, a custom dir never borrowing the default's email, a custom dir
+reporting its own, and `_is_default_config_dir` built without a hardcoded
+separator. `tests/unit/test_agent_accounts.py` — two accounts on one
+subscription flagged (naming the collision partner), two genuine subscriptions
+never flagged, no grouping without an email, and the warning surviving
+`to_dict()` while no token does.
+`AgentAccountsPanel.test.tsx` — the warning renders on the colliding row and
+not on the one it duplicates.
+
+**Class rule.** When two files on disk can answer the same question, never let
+declaration order decide — take the freshest, because which one an external
+tool keeps current is that tool's choice and changes between its releases. And
+an identity read for account A must never be satisfied from account B's file:
+a confident wrong name sends work to the wrong plan, where the only feedback is
+a number on a billing page nobody is watching.
diff --git a/jarvis/agent_accounts.py b/jarvis/agent_accounts.py
index 97429fecb3..f9b355d3d8 100644
--- a/jarvis/agent_accounts.py
+++ b/jarvis/agent_accounts.py
@@ -135,6 +135,9 @@ class AccountSnapshot:
message: str
email: str | None = None
tier: str | None = None
+ #: Set when this account is signed in as the SAME identity as another one.
+ #: Two rows, one subscription — see :func:`snapshots`.
+ warning: str | None = None
def to_dict(self) -> dict[str, Any]:
return {
@@ -144,6 +147,7 @@ class AccountSnapshot:
"message": self.message,
"email": self.email,
"tier": self.tier,
+ "warning": self.warning,
}
@@ -612,9 +616,55 @@ def _not_signed_in_message(account: AgentAccount) -> str:
)
+def _duplicate_warning(label: str) -> str:
+ return (
+ f"This is the same subscription as {label!r} — both are signed in as the "
+ "same account, so they share one plan's usage. To connect a second "
+ "subscription, sign out at claude.com (or use a private window) before "
+ "signing in here, otherwise the browser silently reuses the account you "
+ "are already signed in with."
+ )
+
+
def snapshots(platform: Platform) -> list[AccountSnapshot]:
- """Every account of *platform*, described."""
- return [describe(account) for account in list_accounts(platform)]
+ """Every account of *platform*, described, with same-identity rows flagged.
+
+ Two accounts holding the SAME login is the failure this feature exists to
+ prevent, and nothing about it looks wrong: both rows go green, both name a
+ valid subscription, and the only visible symptom is a usage figure that
+ drops twice as fast as it should — which is how the 2026-07-27 report
+ surfaced, after the browser's live session auto-approved the second sign-in
+ against the first account without ever showing a code to paste.
+
+ So it is stated on the row rather than left to be inferred. Detection is by
+ email, the one identity the CLI writes down; accounts with no readable email
+ are never grouped, since "both unknown" is not evidence of sameness.
+ """
+ described = [describe(account) for account in list_accounts(platform)]
+ first_seen: dict[str, str] = {}
+ result: list[AccountSnapshot] = []
+ for snapshot in described:
+ email = (snapshot.email or "").strip().lower()
+ if not (snapshot.connected and email):
+ result.append(snapshot)
+ continue
+ owner = first_seen.get(email)
+ if owner is None:
+ first_seen[email] = snapshot.account.label
+ result.append(snapshot)
+ continue
+ result.append(
+ AccountSnapshot(
+ account=snapshot.account,
+ connected=snapshot.connected,
+ mode=snapshot.mode,
+ message=snapshot.message,
+ email=snapshot.email,
+ tier=snapshot.tier,
+ warning=_duplicate_warning(owner),
+ )
+ )
+ return result
# ------------------------------------------------------------------- login
diff --git a/jarvis/claude_auth.py b/jarvis/claude_auth.py
index 5e08a5e3a4..84b2165c4e 100644
--- a/jarvis/claude_auth.py
+++ b/jarvis/claude_auth.py
@@ -149,28 +149,87 @@ def subscription_label(sub_type: str | None) -> str:
return _subscription_label(sub_type)
+def _is_default_config_dir(config_dir: Path) -> bool:
+ """Whether *config_dir* is the CLI's own ``~/.claude`` default location.
+
+ Built with ``Path.home()`` rather than a hand-written ``"~/.claude"`` string
+ so the comparison holds on every OS, and compared through ``os.path.normcase``
+ so a differently-cased Windows path still recognises its own default.
+ """
+ try:
+ default = Path.home() / ".claude"
+ except (OSError, ValueError, RuntimeError): # pragma: no cover - exotic home
+ return False
+ if config_dir == default:
+ return True
+ try:
+ return os.path.normcase(str(config_dir)) == os.path.normcase(str(default))
+ except (OSError, ValueError): # pragma: no cover - unrepresentable path
+ return False
+
+
+def _identity_candidates(config_dir: Path) -> list[Path]:
+ """Every ``.claude.json`` that may legitimately describe *config_dir*'s login.
+
+ For a CUSTOM config dir that is exactly one file — the one inside it. The
+ home-level ``~/.claude.json`` belongs to the default login and must never be
+ consulted for an added account, or every account borrows the default's email
+ and the switcher shows the same person on every row.
+ """
+ candidates = [config_dir / ".claude.json"]
+ if _is_default_config_dir(config_dir):
+ try:
+ candidates.append(Path.home() / ".claude.json")
+ except (OSError, ValueError, RuntimeError): # pragma: no cover
+ pass
+ return candidates
+
+
+def _mtime_or_none(path: Path) -> float | None:
+ try:
+ return path.stat().st_mtime
+ except OSError:
+ return None
+
+
def claude_account_identity(config_dir: Path) -> tuple[str | None, str | None]:
"""``(email, display name)`` of the login kept in *config_dir* — display only.
- The CLI files the identity next to the credentials, but WHERE depends on the
- directory: with the default ``~/.claude`` it is the SIBLING ``~/.claude.json``;
- with a custom ``CLAUDE_CONFIG_DIR`` it lives inside that directory. Both are
- tried so a switched account shows its own email instead of borrowing the
- default account's.
+ Two files can carry an identity for the default config dir: ``~/.claude.json``
+ (where the CLI actually keeps it) and ``~/.claude/.claude.json`` (written by
+ some releases). Which one is live is a property of the installed CLI, not
+ something this module can assume — so the FRESHEST readable one wins, the
+ same "most recently refreshed file is the truth" rule
+ :func:`~jarvis.claude_credentials.freshest_claude_oauth` already applies to
+ the credentials themselves.
+
+ Preferring a fixed order instead is the 2026-07-27 defect: an abandoned
+ ``~/.claude/.claude.json`` from an earlier release kept naming the account
+ that had signed in ten days before, so the switcher confidently showed one
+ subscription's email while every pane actually ran on another — visible only
+ as an unexplained usage figure.
+
+ Note there is deliberately no "identity older than its credentials is stale"
+ rule. It reads as an obvious extra safeguard and is wrong: the CLI refreshes
+ the bearer in place indefinitely while never rewriting the identity, so on
+ any long-lived account the identity is legitimately the older file, and such
+ a rule would blank the email on exactly the accounts that are working.
Never raises and never returns a secret.
"""
- candidates = [config_dir / ".claude.json"]
- try:
- if config_dir == Path(os.path.expanduser("~/.claude")):
- candidates.append(Path(os.path.expanduser("~/.claude.json")))
- except (OSError, ValueError): # pragma: no cover - exotic home resolution
- pass
- for candidate in candidates:
+ best: tuple[float, str | None, str | None] | None = None
+ for candidate in _identity_candidates(config_dir):
email, name = _account_from_claude_json(_read_json(candidate))
- if email or name:
- return email, name
- return None, None
+ if not (email or name):
+ continue
+ mtime = _mtime_or_none(candidate)
+ if mtime is None: # pragma: no cover - readable file that cannot be stat'd
+ mtime = 0.0
+ if best is None or mtime > best[0]:
+ best = (mtime, email, name)
+ if best is None:
+ return None, None
+ return best[1], best[2]
@dataclass(frozen=True)
@@ -526,21 +585,32 @@ class ClaudeAuthService:
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.
+ Two files can hold it for the default config dir — ``~/.claude.json``
+ and ``~/.claude/.claude.json`` — and which one the installed CLI keeps
+ current is not knowable here, so the FRESHEST readable one wins rather
+ than a fixed preference (2026-07-27: an abandoned in-dir copy named the
+ previous occupant of the directory for ten days).
+
+ A CUSTOM config dir never falls back to ``~/.claude.json``. That
+ fallback existed so the card "still shows an email", but the email it
+ shows then belongs to the DEFAULT login, not to the directory being
+ described — naming the wrong subscription with full confidence. No
+ email is the honest answer there.
"""
- 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()
+ home_identity = self._claude_json_path()
+ if config_dir is None:
+ return home_identity
+ candidates = [config_dir / ".claude.json"]
+ if _is_default_config_dir(config_dir):
+ candidates.append(home_identity)
+ freshest = max(
+ (c for c in candidates if _mtime_or_none(c) is not None),
+ key=lambda c: _mtime_or_none(c) or 0.0,
+ default=None,
+ )
+ # No readable candidate: hand back the in-dir path so the caller's read
+ # simply comes up empty, rather than borrowing a neighbour's identity.
+ return freshest if freshest is not None else candidates[0]
# -- public API ------------------------------------------------------
diff --git a/jarvis/ui/web/agent_accounts_routes.py b/jarvis/ui/web/agent_accounts_routes.py
index 8ff6483ab0..66e775efec 100644
--- a/jarvis/ui/web/agent_accounts_routes.py
+++ b/jarvis/ui/web/agent_accounts_routes.py
@@ -152,7 +152,13 @@ async def login(account_id: str) -> dict[str, Any]:
) from exc
return {
"ok": True,
- "message": f"Sign-in started for {account.label} — finish it in the window that opened.",
+ "message": (
+ f"Sign-in started for {account.label} — finish it in the window that "
+ "opened. If the browser signs you straight in without ever showing a "
+ "code, it reused the account you are already signed in with at "
+ "claude.com: sign out there (or use a private window) and start this "
+ "sign-in again, or both entries end up on the same subscription."
+ ),
}
diff --git a/jarvis/ui/web/frontend/src/components/AgentAccountsPanel.test.tsx b/jarvis/ui/web/frontend/src/components/AgentAccountsPanel.test.tsx
index 10093d4d71..f70caa5222 100644
--- a/jarvis/ui/web/frontend/src/components/AgentAccountsPanel.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/AgentAccountsPanel.test.tsx
@@ -190,6 +190,32 @@ describe("AgentAccountsPanel", () => {
});
});
+ it("shows the duplicate-subscription warning on the row that collides", async () => {
+ // 2026-07-27: a browser with a live claude.com session approved the second
+ // sign-in against the FIRST account without ever showing a code, so two
+ // rows named one plan. Both looked perfectly healthy; the only symptom was
+ // usage draining twice as fast. The backend flags it — the row must show it.
+ const twin = account({
+ id: "claude:abc123",
+ label: "Second seat",
+ builtin: false,
+ warning:
+ "This is the same subscription as 'Default Claude Code login' — both are " +
+ "signed in as the same account, so they share one plan's usage.",
+ });
+ vi.mocked(fetchAgentAccounts).mockResolvedValue(
+ response([account(), twin]) as never,
+ );
+ render(<AgentAccountsPanel />);
+ await waitFor(() => expect(screen.getByText("Second seat")).toBeTruthy());
+
+ const row = screen.getByText("Second seat").closest("li")!;
+ expect(row.textContent).toContain("same subscription");
+ // and the account it duplicates stays clean, or every row cries wolf
+ const original = screen.getByText("Default Claude Code login").closest("li")!;
+ expect(original.textContent).not.toContain("same subscription");
+ });
+
it("reports a failed load instead of rendering an empty, confident list", async () => {
vi.mocked(fetchAgentAccounts).mockRejectedValue(new Error("backend is warming up"));
render(<AgentAccountsPanel />);
diff --git a/jarvis/ui/web/frontend/src/components/AgentAccountsPanel.tsx b/jarvis/ui/web/frontend/src/components/AgentAccountsPanel.tsx
index 8cb58a99a2..a94ac843a1 100644
--- a/jarvis/ui/web/frontend/src/components/AgentAccountsPanel.tsx
+++ b/jarvis/ui/web/frontend/src/components/AgentAccountsPanel.tsx
@@ -20,7 +20,16 @@
*/
import { useCallback, useEffect, useState } from "react";
-import { Check, KeyRound, LogIn, Pencil, Plus, Trash2, Users } from "lucide-react";
+import {
+ AlertTriangle,
+ Check,
+ KeyRound,
+ LogIn,
+ Pencil,
+ Plus,
+ Trash2,
+ Users,
+} from "lucide-react";
import { useT } from "@/i18n";
import {
@@ -361,6 +370,17 @@ function AccountRow({
<KeyRound className="mt-0.5 h-3 w-3 shrink-0" />
<span className="min-w-0 break-words">{account.message}</span>
</p>
+
+ {/* Two accounts on ONE subscription look completely healthy — both rows
+ green, both naming a valid plan — and the only symptom is usage
+ draining twice as fast. So it is said out loud, next to the row that
+ duplicates another, rather than left to be deduced from a usage page. */}
+ {account.warning && (
+ <p className="flex items-start gap-1.5 pl-6 text-[11px] text-amber-600">
+ <AlertTriangle className="mt-0.5 h-3 w-3 shrink-0" />
+ <span className="min-w-0 break-words">{account.warning}</span>
+ </p>
+ )}
</li>
);
}
diff --git a/jarvis/ui/web/frontend/src/lib/agentAccountsApi.ts b/jarvis/ui/web/frontend/src/lib/agentAccountsApi.ts
index d1e3c25b3a..824473725c 100644
--- a/jarvis/ui/web/frontend/src/lib/agentAccountsApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/agentAccountsApi.ts
@@ -26,6 +26,11 @@ export interface AgentAccount {
message: string;
email: string | null;
tier: string | null;
+ /**
+ * Set when this account is signed in as the SAME identity as another one —
+ * two rows, one plan's usage. Absent on older backends, hence optional.
+ */
+ warning?: string | null;
}
export interface AccountPlatformGroup {
diff --git a/tests/unit/test_agent_accounts.py b/tests/unit/test_agent_accounts.py
index 38abf438ed..6c8f63f391 100644
--- a/tests/unit/test_agent_accounts.py
+++ b/tests/unit/test_agent_accounts.py
@@ -365,3 +365,94 @@ def test_a_codex_account_holding_only_an_api_key_says_so() -> None:
snapshot = agent_accounts.describe(account)
assert snapshot.connected is True
assert snapshot.mode == "api_key"
+
+
+# ------------------------------------------------- same subscription twice
+
+
+def _sign_in(directory: Path, email: str, *, expires_at: int = 4_102_444_800_000) -> None:
+ """Give *directory* a live Claude login belonging to *email*."""
+ directory.mkdir(parents=True, exist_ok=True)
+ (directory / ".credentials.json").write_text(
+ json.dumps(
+ {
+ "claudeAiOauth": {
+ "accessToken": "sk-ant-oat01-test",
+ "subscriptionType": "max",
+ "expiresAt": expires_at,
+ }
+ }
+ ),
+ encoding="utf-8",
+ )
+ (directory / ".claude.json").write_text(
+ json.dumps({"oauthAccount": {"emailAddress": email}}), encoding="utf-8"
+ )
+
+
+def test_two_accounts_on_one_subscription_are_flagged_not_shown_as_two_plans() -> None:
+ """The 2026-07-27 report: both rows green, one plan's usage draining twice.
+
+ A browser with a live claude.com session approves the second sign-in against
+ the account already signed in, without ever showing a code — so the user
+ ends up with two entries naming one subscription and no way to tell.
+ """
+ first = agent_accounts.create_account("claude", "Seat A")
+ second = agent_accounts.create_account("claude", "Seat B")
+ _sign_in(first.config_dir, "[email protected]")
+ _sign_in(second.config_dir, "[email protected]")
+
+ by_label = {s.account.label: s for s in agent_accounts.snapshots("claude")}
+ assert by_label["Seat A"].connected and by_label["Seat B"].connected
+ # The first occurrence stays clean; the duplicate names who it collides with.
+ assert by_label["Seat A"].warning is None
+ assert by_label["Seat B"].warning is not None
+ assert "Seat A" in by_label["Seat B"].warning
+ assert "sign out" in by_label["Seat B"].warning.lower()
+
+
+def test_two_genuinely_different_subscriptions_are_never_flagged() -> None:
+ """The whole point of the feature must not trip its own warning."""
+ first = agent_accounts.create_account("claude", "Personal")
+ second = agent_accounts.create_account("claude", "Work")
+ _sign_in(first.config_dir, "[email protected]")
+ _sign_in(second.config_dir, "[email protected]")
+
+ assert all(s.warning is None for s in agent_accounts.snapshots("claude"))
+
+
+def test_accounts_without_a_readable_email_are_never_grouped() -> None:
+ """"Both unknown" is not evidence of sameness — it is absence of evidence."""
+ first = agent_accounts.create_account("claude", "Seat A")
+ second = agent_accounts.create_account("claude", "Seat B")
+ for account in (first, second):
+ (account.config_dir / ".credentials.json").write_text(
+ json.dumps(
+ {
+ "claudeAiOauth": {
+ "accessToken": "sk-ant-oat01-test",
+ "subscriptionType": "max",
+ "expiresAt": 4_102_444_800_000,
+ }
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ snaps = agent_accounts.snapshots("claude")
+ assert all(s.connected for s in snaps if not s.account.builtin)
+ assert all(s.warning is None for s in snaps)
+
+
+def test_the_warning_survives_the_wire_format() -> None:
+ """It has to reach the row that renders it, not stop at the dataclass."""
+ first = agent_accounts.create_account("claude", "Seat A")
+ second = agent_accounts.create_account("claude", "Seat B")
+ _sign_in(first.config_dir, "[email protected]")
+ _sign_in(second.config_dir, "[email protected]")
+
+ payload = [s.to_dict() for s in agent_accounts.snapshots("claude")]
+ duplicate = next(p for p in payload if p["label"] == "Seat B")
+ assert "warning" in duplicate and duplicate["warning"]
+ # And it must never carry the thing it was reading next to.
+ assert not any("sk-ant-oat" in json.dumps(p) for p in payload)
diff --git a/tests/unit/test_claude_auth.py b/tests/unit/test_claude_auth.py
index fc701f658f..d42393c615 100644
--- a/tests/unit/test_claude_auth.py
+++ b/tests/unit/test_claude_auth.py
@@ -8,6 +8,7 @@ depends on a real ``claude`` install or the user's real credentials.
from __future__ import annotations
import json
+import os
import subprocess
from pathlib import Path
@@ -18,8 +19,10 @@ from jarvis.claude_auth import (
ClaudeAuthService,
ClaudeCliAuthSnapshot,
_account_from_claude_json,
+ _is_default_config_dir,
_parse_cli_auth_status,
_subscription_label,
+ claude_account_identity,
)
@@ -551,3 +554,96 @@ def test_logout_uses_cli_native_credential_store(
assert svc.logout_blocking() == (True, None)
assert calls == [["/opt/claude", "auth", "logout"]]
+
+
+# -- identity resolution: the freshest file wins -------------------------
+# 2026-07-27: the switcher showed one subscription's email while every pane
+# actually ran on another. Two files can name the account for the default
+# config dir, and the abandoned one was preferred purely because it came first
+# in a hand-written list — it had not been touched in ten days.
+
+
+def _write_identity(path: Path, email: str, *, mtime: float) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(
+ json.dumps({"oauthAccount": {"emailAddress": email}}), encoding="utf-8"
+ )
+ os.utime(path, (mtime, mtime))
+
+
+def test_identity_prefers_the_freshest_file_not_the_first_one(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A dead in-dir copy must not outrank the file the CLI keeps current."""
+ home = tmp_path / "home"
+ config_dir = home / ".claude"
+ monkeypatch.setattr(Path, "home", classmethod(lambda _cls: home))
+
+ _write_identity(config_dir / ".claude.json", "[email protected]", mtime=1_000_000)
+ _write_identity(home / ".claude.json", "[email protected]", mtime=2_000_000)
+
+ email, _name = claude_account_identity(config_dir)
+ assert email == "[email protected]"
+
+
+def test_identity_still_reads_an_in_dir_file_when_it_is_the_fresh_one(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The rule is "freshest", not "always the home file" — it works both ways."""
+ home = tmp_path / "home"
+ config_dir = home / ".claude"
+ monkeypatch.setattr(Path, "home", classmethod(lambda _cls: home))
+
+ _write_identity(config_dir / ".claude.json", "[email protected]", mtime=2_000_000)
+ _write_identity(home / ".claude.json", "[email protected]", mtime=1_000_000)
+
+ email, _name = claude_account_identity(config_dir)
+ assert email == "[email protected]"
+
+
+def test_a_custom_config_dir_never_borrows_the_default_accounts_email(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """An added account showing the default login's email is the core defect.
+
+ Every row would name the same person, which is exactly how a user ends up
+ switching to a subscription they are not actually on.
+ """
+ home = tmp_path / "home"
+ monkeypatch.setattr(Path, "home", classmethod(lambda _cls: home))
+ _write_identity(home / ".claude.json", "[email protected]", mtime=9_000_000)
+
+ custom = tmp_path / "accounts" / "second-seat"
+ custom.mkdir(parents=True)
+
+ email, name = claude_account_identity(custom)
+ assert email is None and name is None
+
+
+def test_a_custom_config_dir_reports_its_own_email(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ home = tmp_path / "home"
+ monkeypatch.setattr(Path, "home", classmethod(lambda _cls: home))
+ _write_identity(home / ".claude.json", "[email protected]", mtime=9_000_000)
+
+ custom = tmp_path / "accounts" / "second-seat"
+ _write_identity(custom / ".claude.json", "[email protected]", mtime=1_000)
+
+ email, _name = claude_account_identity(custom)
+ assert email == "[email protected]"
+
+
+def test_the_default_dir_is_recognised_without_a_hardcoded_separator(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Built from Path.home(), so the home fallback is not Windows-only.
+
+ A hand-written "~/.claude" string is a per-OS guess about the separator;
+ this repo ships the same behaviour on macOS and Linux (CLAUDE.md §3).
+ """
+ home = tmp_path / "home"
+ monkeypatch.setattr(Path, "home", classmethod(lambda _cls: home))
+
+ assert _is_default_config_dir(home / ".claude") is True
+ assert _is_default_config_dir(tmp_path / "elsewhere") is False