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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(accounts): stop false logged-out rows and account-switch drift
Ruben Lütke47019b7304dc
diff --git a/jarvis/agent_accounts.py b/jarvis/agent_accounts.pyindex 4b875bf3ce..4c52ccb20a 100644--- a/jarvis/agent_accounts.py+++ b/jarvis/agent_accounts.py@@ -920,6 +920,24 @@ def _describe_claude(account: AgentAccount) -> AccountSnapshot:email=email,tier=tier,)+ if snapshot.status == "expired" and snapshot.refresh_token_present:+ # A stale ACCESS token beside a refresh token is a signed-in account+ # between sessions, not a signed-out one: the CLI renews the bearer the+ # moment a terminal runs on this directory. Reporting it disconnected+ # painted every idle account red for most of the day and pointed its+ # owner at a Sign-in button that only ever re-authorized the browser's+ # live session (the "permanently logged out" report, 2026-07-31).+ label = subscription_label(tier)+ return AccountSnapshot(+ account=account,+ connected=True,+ mode="subscription",+ message=(+ f"Signed in via {label} ({email})." if email else f"Signed in via {label}."+ ),+ email=email,+ tier=tier,+ )if snapshot.status == "expired":return AccountSnapshot(account=account,@@ -1090,13 +1108,23 @@ def start_login(account: AgentAccount) -> Any:env = env_overrides(account.platform, account.id)if account.platform == "claude":- from jarvis.claude_auth import ClaudeAuthService, claude_install_hint+ from jarvis.claude_auth import (+ ClaudeAuthService,+ claude_account_identity,+ claude_install_hint,+ )service = ClaudeAuthService()binary = service._resolve_binary() # noqa: SLF001 — the module's own seamif binary is None:raise FileNotFoundError(f"Claude CLI is not installed. {claude_install_hint()}")- argv = service._login_argv(binary) # noqa: SLF001 — capability-selected argv+ # Aim the sign-in at the identity this seat already holds (a re-login is+ # the common case). Without the hint, a browser with a live claude.com+ # session re-authorizes THAT account without ever asking — and a second+ # row silently lands on the first row's plan. A first-ever sign-in has+ # no recorded email yet, so there the hint is honestly absent.+ known_email, _name = claude_account_identity(account.config_dir)+ argv = service._login_argv(binary, email=known_email) # noqa: SLF001 — capability-selected argvtitle = f"Claude sign-in — {account.label}"elif account.platform == "codex":from jarvis.codex_auth import CodexAuthServicediff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.pyindex c75f426c94..e6483f8154 100644--- a/jarvis/agentic_ide/session.py+++ b/jarvis/agentic_ide/session.py@@ -1334,11 +1334,12 @@ class Registry:# changed.self._sessions: dict[str, Session] = {}self._active: str | None = None- # Which subscription NEW panes of each coding CLI open on, chosen in the- # workspace's own settings. Empty means "whatever the stored default- # says" — `active_account_id` is the only reader and owns that fallback,- # so an untouched install behaves exactly as it did before.- self._active_accounts: dict[str, str] = {}+ # Which subscription NEW panes open on is deliberately NOT cached here.+ # An in-memory copy was a second source of truth: once the workspace+ # switcher had written it, a later switch on the app's own Subscriptions+ # page (which only writes the store) never reached this registry, and+ # new panes kept opening on the seat the user had just moved away from.+ # `active_account_id` reads the one persisted store instead.# Injectable so tests can drive the registry against a fake PTY pool# without a real pseudo-terminal (and without a coding agent installed).self._pty: PtyManager | None = pty_manager@@ -1414,14 +1415,17 @@ class Registry:def active_account_id(self, agent: str) -> str | None:"""Which subscription of ``agent`` the next new pane opens on.- The workspace's own choice when one was made here, the stored default- otherwise — and an id that no longer resolves degrades to the built-in- login rather than to nothing (``resolve_account`` owns that fallback).- ``None`` only for something that is not a coding CLI with accounts.+ Always the ONE persisted default (`jarvis.agent_accounts`), never a+ registry-local copy — every surface that switches accounts writes that+ store, so reading anything else lets two surfaces disagree about which+ seat the next pane spends. An id that no longer resolves degrades to+ the built-in login rather than to nothing (``resolve_account`` owns+ that fallback). ``None`` only for something that is not a coding CLI+ with accounts."""if not has_accounts(agent):return None- return resolve_account(agent, self._active_accounts.get(agent))+ return resolve_account(agent, None)def active_accounts(self) -> list[dict[str, Any]]:"""The active subscription of every coding CLI, as the UI shows it.@@ -1468,13 +1472,13 @@ class Registry:raise SessionError(f"{AGENT_DISPLAY.get(agent, agent)} has no account with id {account_id!r}.")- self._active_accounts[agent] = account.id+ # The store is the ONE place the choice lives (see active_account_id),+ # so a failure to write it means the switch did not happen — surfacing+ # that honestly beats a success answer new panes then contradict.try:await asyncio.to_thread(agent_accounts.set_active, agent, account.id) # type: ignore[arg-type]except agent_accounts.AccountError as exc:- # The pin above already governs this session; only its survival past- # a restart is lost, and that is worth a log rather than a failure.- logger.warning("Agentic IDE: the active account was not persisted: {}", exc)+ raise SessionError(f"The account switch was not saved: {exc}") from exclogger.info("Agentic IDE: new {} terminals will use {!r}", agent, account.label)return accountdiff --git a/jarvis/claude_auth.py b/jarvis/claude_auth.pyindex 84b2165c4e..8434fe850d 100644--- a/jarvis/claude_auth.py+++ b/jarvis/claude_auth.py@@ -60,7 +60,12 @@ _BINARY_CANDIDATES: tuple[str, ...] = ("claude", "claude.cmd", "claude.exe")# TTL auth probe on later calls. A failed version probe is cached too, so an# absent/hanging Claude install never re-pays that timeout._VERSION_CACHE: dict[str, str | None] = {}-_AUTH_LOGIN_CACHE: dict[str, bool] = {}+#: ``auth login --help`` output per binary, or ``None`` where the subcommand+#: does not exist. The TEXT is cached rather than a boolean because it answers+#: two capability questions: whether ``auth login`` exists at all, and whether+#: it takes ``--email`` (older releases with the subcommand but not the flag+#: would abort on an unknown option).+_AUTH_LOGIN_CACHE: dict[str, str | None] = {}_AUTH_LOGOUT_CACHE: dict[str, bool] = {}_AUTH_STATUS_CACHE: dict[tuple[str, str, str, str, str], tuple[float, ClaudeCliAuthSnapshot | None]@@ -516,8 +521,8 @@ class ClaudeAuthService:_AUTH_STATUS_CACHE[cache_key] = (now, snapshot)return snapshot- def _supports_auth_login(self, binary: str) -> bool:- """Whether this installed CLI exposes the modern ``auth login`` command."""+ def _auth_login_help(self, binary: str) -> str | None:+ """``auth login --help`` output, or ``None`` where the command is absent."""if binary in _AUTH_LOGIN_CACHE:return _AUTH_LOGIN_CACHE[binary]try:@@ -530,11 +535,15 @@ class ClaudeAuthService:text=True,creationflags=NO_WINDOW_CREATIONFLAGS,)- supported = proc.returncode == 0+ help_text = (proc.stdout or "") if proc.returncode == 0 else Noneexcept (OSError, subprocess.SubprocessError):- supported = False- _AUTH_LOGIN_CACHE[binary] = supported- return supported+ help_text = None+ _AUTH_LOGIN_CACHE[binary] = help_text+ return help_text++ def _supports_auth_login(self, binary: str) -> bool:+ """Whether this installed CLI exposes the modern ``auth login`` command."""+ return self._auth_login_help(binary) is not Nonedef _supports_auth_logout(self, binary: str) -> bool:"""Whether the CLI can remove its own platform-native credentials."""@@ -556,11 +565,24 @@ class ClaudeAuthService:_AUTH_LOGOUT_CACHE[binary] = supportedreturn supported- def _login_argv(self, binary: str) -> list[str]:- """Capability-selected login argv, with a first-run fallback for old CLIs."""+ def _login_argv(self, binary: str, *, email: str | None = None) -> list[str]:+ """Capability-selected login argv, with a first-run fallback for old CLIs.++ ``email`` names the account this sign-in is FOR. Passed through only+ when the installed CLI advertises ``--email``: the OAuth page then+ targets that account instead of silently re-authorizing whichever one+ the browser is already signed in with at claude.com — which is how two+ subscription rows ended up on the same plan (2026-07-27).+ """prefix = self._cli_argv_prefix(binary)if self._supports_auth_login(binary):- return [*prefix, "auth", "login", "--claudeai"]+ argv = [*prefix, "auth", "login", "--claudeai"]+ # Gated on the flag being ADVERTISED: a release with the subcommand+ # but not the option would abort on it, and a failed login argv+ # reads to the user as a rejected account.+ if email and "--email" in (self._auth_login_help(binary) or ""):+ argv += ["--email", email]+ return argv# Older Claude Code releases have no auth subcommand. A bare interactive# start is their documented first-run login flow; passing ``/login`` as# a positional argv value incorrectly treats it as an initial prompt.diff --git a/jarvis/claude_credentials.py b/jarvis/claude_credentials.pyindex b05931846b..c95a5d442d 100644--- a/jarvis/claude_credentials.py+++ b/jarvis/claude_credentials.py@@ -92,16 +92,22 @@ class ClaudeOAuthSnapshot:subscription_type: str | None = Noneconfig_dir: Path | None = Noneexpires_s: float | None = None # epoch seconds; None == no expiry recorded+ #: A refresh token sits beside the bearer, so an ``"expired"`` login renews+ #: itself the next time the CLI runs — "expired" then means "stale between+ #: sessions", not "signed out". Status readers may report such a login as+ #: signed in; token INJECTORS must not, because the stale bearer itself is+ #: still a guaranteed 401 (only the CLI can redeem the refresh token).+ refresh_token_present: bool = Falsedef _parse_oauth_file(path: Path,-) -> tuple[str, str | None, float | None] | None:+) -> tuple[str, str | None, float | None, bool] | 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.+ Returns ``(access_token, subscription_type, expires_s, refresh_present)``+ 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"))@@ -120,7 +126,9 @@ def _parse_oauth_file(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+ refresh = oauth.get("refreshToken")+ refresh_present = isinstance(refresh, str) and bool(refresh.strip())+ return token, sub_type, expires_s, refresh_presentdef claude_login_in(@@ -140,13 +148,14 @@ def claude_login_in(parsed = _parse_oauth_file(config_dir / ".credentials.json")if parsed is None:return ClaudeOAuthSnapshot(status="absent", config_dir=config_dir)- token, sub_type, expires_s = parsed+ token, sub_type, expires_s, refresh_present = parsedif expires_s is not None and expires_s <= now_fn() + OAUTH_EXPIRY_SLACK_S:return ClaudeOAuthSnapshot(status="expired",subscription_type=sub_type,config_dir=config_dir,expires_s=expires_s,+ refresh_token_present=refresh_present,)return ClaudeOAuthSnapshot(status="valid",@@ -154,6 +163,7 @@ def claude_login_in(subscription_type=sub_type,config_dir=config_dir,expires_s=expires_s,+ refresh_token_present=refresh_present,)@@ -177,7 +187,7 @@ def freshest_claude_oauth(*, now_fn: Callable[[], float] = time.time) -> ClaudeOparsed = _parse_oauth_file(config_dir / ".credentials.json")if parsed is None:continue- token, sub_type, expires_s = parsed+ token, sub_type, expires_s, refresh_present = parsedif expires_s is None or expires_s > horizon:sort_key = float("inf") if expires_s is None else expires_sif best_valid is None or sort_key > best_valid[0]:@@ -189,6 +199,7 @@ def freshest_claude_oauth(*, now_fn: Callable[[], float] = time.time) -> ClaudeOsubscription_type=sub_type,config_dir=config_dir,expires_s=expires_s,+ refresh_token_present=refresh_present,),)elif best_expired is None or expires_s > best_expired[0]:@@ -199,6 +210,7 @@ def freshest_claude_oauth(*, now_fn: Callable[[], float] = time.time) -> ClaudeOsubscription_type=sub_type,config_dir=config_dir,expires_s=expires_s,+ refresh_token_present=refresh_present,),)if best_valid is not None:diff --git a/tests/unit/agentic_ide/test_account_spawn.py b/tests/unit/agentic_ide/test_account_spawn.pyindex f89d56460f..cd7420d951 100644--- a/tests/unit/agentic_ide/test_account_spawn.py+++ b/tests/unit/agentic_ide/test_account_spawn.py@@ -118,8 +118,27 @@ async def test_a_new_pane_after_the_switch_gets_the_new_account(agent_accounts.set_active("claude", second.id)added = await registry.add_terminal(agent="claude", anchor=None)assert added.account == second.id- # ...and the pane that was already open is untouched by it.- assert registry.session.terminals[0].account == agent_accounts.builtin_id("claude")+++async def test_a_switch_on_the_subscriptions_page_reaches_the_workspace(+ registry: Registry, tmp_path: Path+) -> None:+ """The store is the ONE source of the active account — no registry shadow.++ The app has two switch surfaces: the workspace's own settings (which go+ through the registry) and the Subscriptions page (which writes the store+ directly). An in-memory copy inside the registry made the first switch+ permanent: once used, a later switch on the Subscriptions page never+ reached new panes, which kept opening on the seat the user had just left.+ """+ first = agent_accounts.create_account("claude", "First seat")+ second = agent_accounts.create_account("claude", "Second seat")+ await registry.set_active_account("claude", first.id)+ # The Subscriptions page writes the store directly, not via the registry.+ agent_accounts.set_active("claude", second.id)+ assert registry.active_account_id("claude") == second.id+ await registry.start(str(tmp_path), [{"agent": "claude"}])+ assert registry.session.terminals[0].account == second.idasync def test_a_split_stays_on_the_account_its_anchor_runs_on(diff --git a/tests/unit/test_agent_accounts.py b/tests/unit/test_agent_accounts.pyindex 9c349caeff..4b9000b2b7 100644--- a/tests/unit/test_agent_accounts.py+++ b/tests/unit/test_agent_accounts.py@@ -507,6 +507,36 @@ def test_a_described_account_never_carries_a_token() -> None:assert "supersecret" not in serialized+def test_an_expired_access_token_beside_a_refresh_token_is_still_signed_in() -> None:+ """A stale bearer between sessions is not a signed-out account.++ Claude Code renews the access token the moment a terminal runs on the+ directory, so for most of an idle day every healthy account holds an+ expired bearer AND a live refresh token. Reporting that as disconnected+ painted the whole switcher red and sent the user through pointless+ re-logins (the "permanently logged out" report, 2026-07-31).+ """+ account = agent_accounts.create_account("claude", "Idle seat")+ (account.config_dir / ".credentials.json").write_text(+ json.dumps(+ {+ "claudeAiOauth": {+ "accessToken": "sk-ant-oat-old",+ "refreshToken": "sk-ant-ort-live",+ "subscriptionType": "max",+ "expiresAt": 1_000, # long dead+ }+ }+ ),+ encoding="utf-8",+ )+ snapshot = agent_accounts.describe(account)+ assert snapshot.connected is True+ assert snapshot.mode == "subscription"+ serialized = json.dumps(snapshot.to_dict())+ assert "sk-ant-ort-live" not in serialized++def test_an_expired_claude_login_is_not_reported_as_connected() -> None:account = agent_accounts.create_account("claude", "Stale seat")(account.config_dir / ".credentials.json").write_text(diff --git a/tests/unit/test_claude_auth.py b/tests/unit/test_claude_auth.pyindex d42393c615..2b61b66fc7 100644--- a/tests/unit/test_claude_auth.py+++ b/tests/unit/test_claude_auth.py@@ -413,6 +413,42 @@ def test_start_login_uses_modern_auth_command(monkeypatch) -> None:assert captured["kwargs"] == {"title": "Claude sign-in"}+def test_login_argv_targets_the_accounts_email_when_the_cli_can(monkeypatch) -> None:+ """`--email` aims the browser flow at the seat being signed in.++ Without it, a browser holding a live claude.com session silently+ re-authorizes THAT account — two subscription rows on one plan.+ """+ svc = ClaudeAuthService()+ monkeypatch.setattr(+ svc,+ "_auth_login_help",+ lambda _binary: "Options:\n --claudeai\n --email <email> Pre-populate",+ )+ assert svc._login_argv("/opt/claude", email="[email protected]") == [+ "/opt/claude",+ "auth",+ "login",+ "--claudeai",+ "--email",+ "[email protected]",+ ]+++def test_login_argv_omits_email_when_the_cli_does_not_advertise_it(monkeypatch) -> None:+ """A release with `auth login` but no `--email` must not be handed the flag."""+ svc = ClaudeAuthService()+ monkeypatch.setattr(+ svc, "_auth_login_help", lambda _binary: "Options:\n --claudeai"+ )+ assert svc._login_argv("/opt/claude", email="[email protected]") == [+ "/opt/claude",+ "auth",+ "login",+ "--claudeai",+ ]++def test_start_login_old_cli_uses_bare_first_run(monkeypatch) -> None:captured: dict[str, object] = {}svc = ClaudeAuthService()