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
feat(agent-accounts): switch between several coding-CLI subscriptions
Ruben Lütke1b0558c75fe9
diff --git a/docs/superpowers/specs/2026-07-26-agent-account-switching-design.md b/docs/superpowers/specs/2026-07-26-agent-account-switching-design.mdnew file mode 100644index 0000000000..efc39b67d3--- /dev/null+++ b/docs/superpowers/specs/2026-07-26-agent-account-switching-design.md@@ -0,0 +1,181 @@+# Agent accounts — switching between several coding-CLI subscriptions++**Date:** 2026-07-26+**Status:** accepted, implementing+**Surface:** Settings (API-Keys view) + Agentic IDE++---++## 1. The problem++A user can hold more than one subscription for the same coding CLI — two Claude+Max seats, two ChatGPT/Codex plans. Today only one of them is reachable at a+time: the CLI keeps exactly one login, and reaching the other one means a full+`logout` / `login` round trip. That is slow, it throws away the previous+login, and it makes running both plans **at once** impossible — which is the+whole reason someone holds two.++## 2. The mechanism this rests on++Both CLIs resolve their entire identity — credentials, account file, and+conversation history — from one directory, and both expose the official+environment override that moves it:++| CLI | Override | Default | Contents |+|---|---|---|---|+| Claude Code | `CLAUDE_CONFIG_DIR` | `~/.claude` | `.credentials.json`, `.claude.json`, `projects/` |+| Codex | `CODEX_HOME` | `~/.codex` | `auth.json`, `config.toml`, `sessions/` |++So **one account is one directory**, and switching is "which directory does the+next spawn point at". Both logins stay valid side by side; nothing is copied,+nothing is logged out.++Copying tokens between directories is explicitly **not** the design. Claude Code+refreshes its OAuth access token in place, so a copy goes stale on its own — the+2026-07-06 and 2026-07-10 incidents (`jarvis/claude_credentials.py`) are exactly+that failure. Separate directories each refresh themselves.++## 3. What already exists++- `jarvis/terminal/backend.py` — all three PTY backends already accept `env=`.+- `jarvis/missions/isolation/env.py` — already pins `CODEX_HOME` ++ `CLAUDE_CONFIG_DIR` per mission worker.+- `jarvis/claude_credentials.py` — already scans several config dirs and lets+ the freshest live login win.+- `jarvis/workspace/trust.py` — already honours `CODEX_HOME`.++## 4. What is missing++1. `PtyManager.spawn()` takes no `env` — the chain from the backend seam up to+ the Agentic IDE is broken at exactly one link.+2. Nothing owns the list of accounts, or which one is active.+3. Resume discovery (`jarvis/agentic_ide/agent_sessions.py`) reads the config+ dir from `os.environ`, so a pane running account B would look for its+ transcript in account A's directory and silently start fresh.+4. `launch_interactive_terminal()` cannot carry an environment overlay, so a+ sign-in cannot be pointed at a specific account directory.++## 5. Design++### 5.1 `jarvis/agent_accounts.py` — the one owner++A small, stdlib-only module (the `recents.py` / `resume_store.py` pattern:+one JSON file under the per-user data dir, atomic writes, defensive reads).++```+AgentAccount(id, platform, label, config_dir, builtin)+```++- **`platform`** is `"claude"` or `"codex"`.+- **The built-in account is synthetic and always present**: it represents the+ CLI's own platform default (`~/.claude` / `~/.codex`), is never written to the+ store, and can neither be renamed away nor deleted. It is what a fresh install+ has, so the feature costs an untouched user nothing.+- **Added accounts** get a directory under+ `<user data>/agent-accounts/<platform>/<slug>/`.+- Store: `<user data>/agent_accounts.json`, holding the added accounts plus the+ active id per platform. An unreadable / newer-version file degrades to "only+ the built-in account exists" rather than breaking the view.++Public surface:++| Function | Purpose |+|---|---|+| `list_accounts(platform)` | built-in first, then added, stable order |+| `active_account(platform)` | falls back to built-in when the pinned id is gone |+| `set_active(platform, account_id)` | the switch |+| `create_account(platform, label)` | mint id + directory |+| `delete_account(account_id, *, remove_files)` | forget; optionally erase |+| `resolve(account_id)` | id → account, `None` when unknown |+| `spawn_env(platform, account_id)` | full child environment for a spawn |+| `describe(account)` | display-safe snapshot: connected, email, tier |++**`spawn_env` semantics (load-bearing).** It returns `os.environ` **plus** the+override, never a replacement — a replaced environment loses `PATH` and the+agent binary stops resolving. For the **built-in** account it *removes* any+inherited `CLAUDE_CONFIG_DIR` / `CODEX_HOME` instead of setting one, so the CLI+uses its true platform default — which on macOS is the Keychain, not a file.++**`describe` reuses the existing parsers** rather than growing a third copy:+`jarvis.claude_credentials` for the Claude bearer + `.claude.json` identity,+`jarvis.codex_auth` helpers for `auth.json`. It never returns a token.++### 5.2 Wiring the spawn++- `PtyManager.spawn(..., env: Mapping[str, str] | None = None)` → passed to+ `backend.spawn`. Default `None` keeps every existing caller identical.+- `Terminal` gains `account: str | None`. It is resolved to a concrete id **when+ the pane is created**, not when it spawns: flipping the global switch must not+ silently re-point a pane that is already on screen.+- `Session.attach()` builds `spawn_env(term.agent, term.account)`.+- `resume_store` persists `account` so a resumed workspace comes back on the+ same accounts.++### 5.3 Resume discovery follows the account++`has_conversation()` and `discover()` take an optional `home: Path | None`.+`None` keeps today's behaviour (`os.environ` → default). `session.py` passes the+pane's account directory. Without this the "continue where you left off" path is+wrong for every non-default account.++### 5.4 REST — `jarvis/ui/web/agent_accounts_routes.py`++Per the CLI-first contract (CLAUDE.md §5), which makes each of these a+`jarvis api agent-accounts <op>` command automatically:++| Route | Purpose |+|---|---|+| `GET /api/agent-accounts` | every account of both platforms + status |+| `POST /api/agent-accounts` | add one (mints the directory) |+| `PUT /api/agent-accounts/active` | switch the default for a platform |+| `POST /api/agent-accounts/{id}/login` | sign in *inside that account's dir* |+| `PATCH /api/agent-accounts/{id}` | rename |+| `DELETE /api/agent-accounts/{id}` | forget (`x-jarvis-dangerous`) |++`launch_interactive_terminal()` grows an `env` overlay parameter so the sign-in+lands in the right directory on all three OSes (Windows/Linux via `Popen(env=)`,+macOS via a `VAR=value` prefix in the AppleScript command, because Terminal.app+runs a shell string).++### 5.5 UI++- **Settings → API Keys**, inside `JarvisAgentSection`: an accounts block per+ platform under the existing connection card — the accounts, which is active,+ a radio-style switch, "Add account", rename, remove.+- **Agentic IDE**: the pane / batch creation form gets an account picker per+ agent, defaulting to the active one. This is what makes both subscriptions+ run *at the same time*.+- Strings go through i18n (`de` / `en` / `es`), English source.++### 5.6 Honesty rules++- A directory with no readable login shows **"not signed in"** with the sign-in+ button — never a green state it cannot back up.+- `describe()` never returns a token, only booleans + the display email/tier.+- **macOS caveat:** Claude Code stores its credentials in the Keychain there.+ Whether a second config directory yields a second Keychain entry is unproven+ on this hardware, so after a sign-in the account is **verified**: if the+ directory produced no readable login, the UI says so plainly instead of+ routing panes to an account that is silently the first one. Tracked in+ `docs/os-parity.md`.++## 6. Out of scope (deliberately)++- Automatic failover when a plan hits its rate limit. Real appeal, but it needs+ reliable limit detection from CLI output — a separate feature, and guessing+ wrong would move work onto the wrong plan silently.+- Mission workers (`build_worker_env`). They own a security-relevant isolated+ environment (ADR-0009 §3); folding accounts in there is its own change.+- Any account concept for API-key providers. This is about **subscription CLIs**.++## 7. Testing++- `tests/unit/test_agent_accounts.py` — store round-trip, built-in synthesis,+ active fallback when a pinned id vanishes, `spawn_env` overlay + built-in+ *removal*, corrupt/newer-version file degradation, no token in `describe`.+- `tests/unit/agentic_ide/test_account_spawn.py` — a pane spawns with its+ account's directory; the built-in pane spawns without an override; switching+ the global default does not re-point an existing pane.+- `tests/unit/test_agent_accounts_routes.py` — route contract + danger metadata.+- Frontend: the accounts panel renders, switches, and shows an unsigned account+ honestly.diff --git a/jarvis/agent_accounts.py b/jarvis/agent_accounts.pynew file mode 100644index 0000000000..97429fecb3--- /dev/null+++ b/jarvis/agent_accounts.py@@ -0,0 +1,695 @@+"""Several subscriptions per coding CLI, switchable without logging out.++A user can hold more than one seat for the same CLI — two Claude Max plans, two+ChatGPT/Codex plans. Out of the box only one of them is reachable: the CLI keeps+exactly one login, so getting to the other means a full ``logout`` / ``login``+round trip that throws the first one away. Holding two plans and being able to+use only one at a time is the problem this module exists to remove.++**One account is one directory.** Both CLIs resolve their whole identity —+credentials, account file, conversation history — from a single directory, and+both publish the environment variable that moves it:++=========== ====================== ==============+CLI Variable Platform default+=========== ====================== ==============+Claude Code ``CLAUDE_CONFIG_DIR`` ``~/.claude``+Codex ``CODEX_HOME`` ``~/.codex``+=========== ====================== ==============++So switching is not an auth operation at all: it decides which directory the+NEXT spawn points at. Every login stays valid, side by side, indefinitely — and+because the choice is per spawn, two panes can run two different subscriptions+at the same moment, which is the actual reason to hold two.++**Tokens are never copied between accounts.** That is the obvious shortcut and+it is a trap: Claude Code refreshes its OAuth access token *in place*, so a copy+starts dying the moment it is made — the 2026-07-06 and 2026-07-10 incidents+behind :mod:`jarvis.claude_credentials` are exactly that failure, one directory+further left each time. Separate directories each refresh themselves and cannot+go stale relative to one another.++**The built-in account is synthetic.** Every platform always offers the CLI's+own default directory as an account that was never created here, cannot be+deleted, and is never written to the store. A user who never opens this feature+therefore has exactly the behaviour they had before, and an empty store is a+complete, valid state rather than a broken one.++Storage follows the pattern ``recents.py`` and ``resume_store.py`` already+proved in this codebase: one small JSON file under the per-user data directory+(never the repo, never ``jarvis.toml``, never a secret in it — only labels and+paths), atomic writes, and defensive reads where a truncated, hand-edited or+newer-version file degrades to "only the built-in account exists" instead of+breaking the view that reads it.++Cross-platform by construction: ``pathlib`` throughout, no hardcoded user paths,+and no OS-specific branch. The one honest caveat is macOS, where Claude Code+keeps credentials in the Keychain rather than in the config directory — see+:func:`describe`, which reports an account with no readable login as exactly+that instead of quietly routing panes to whichever login the CLI finds.+"""++from __future__ import annotations++import json+import os+import re+import shutil+import threading+from collections.abc import Mapping+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Literal+from uuid import uuid4++from loguru import logger++Platform = Literal["claude", "codex"]++#: The platforms that own a switchable subscription login. Anything else — an+#: API-key provider — has no directory to switch and is deliberately absent.+PLATFORMS: tuple[Platform, ...] = ("claude", "codex")++#: The official config-dir override each CLI publishes. This mapping IS the+#: mechanism; everything else in this module is bookkeeping around it.+ENV_VAR: dict[Platform, str] = {+ "claude": "CLAUDE_CONFIG_DIR",+ "codex": "CODEX_HOME",+}++#: Where each CLI looks when its override is unset.+_NATIVE_DIR: dict[Platform, str] = {"claude": "~/.claude", "codex": "~/.codex"}++_DISPLAY: dict[Platform, str] = {"claude": "Claude Code", "codex": "Codex"}++#: Bumped when the stored shape changes incompatibly. An unknown version reads+#: as "no added accounts": half-understanding a newer build's file would offer+#: accounts whose directories this build cannot interpret, and a pane would then+#: launch against the wrong login — worse than offering only the built-in one.+SCHEMA_VERSION = 1++#: A label the user can actually read back in a pane header. Long enough for+#: "Work account (Max 20x)", short enough not to break the switcher's layout.+MAX_LABEL_CHARS = 60++#: Runaway guard, not a product ceiling — nobody holds this many seats, but a+#: scripted loop against the REST route must not fill the disk with config dirs.+MAX_ACCOUNTS_PER_PLATFORM = 20++# Writes arrive from the REST routes and from pane creation, and the last one has+# to be the one that lands rather than the one that finished renaming first.+_WRITE_LOCK = threading.Lock()+++class AccountError(RuntimeError):+ """A requested account operation cannot be carried out (surfaced as 4xx)."""+++@dataclass(frozen=True, slots=True)+class AgentAccount:+ """One subscription of one coding CLI, identified by its config directory."""++ id: str+ platform: Platform+ label: str+ config_dir: Path+ builtin: bool = False++ def to_dict(self) -> dict[str, Any]:+ return {+ "id": self.id,+ "platform": self.platform,+ "label": self.label,+ "config_dir": str(self.config_dir),+ "builtin": self.builtin,+ }+++@dataclass(frozen=True, slots=True)+class AccountSnapshot:+ """Display-safe state of one account. Never carries a token."""++ account: AgentAccount+ connected: bool+ mode: str # "subscription" | "api_key" | "expired" | "unknown"+ message: str+ email: str | None = None+ tier: str | None = None++ def to_dict(self) -> dict[str, Any]:+ return {+ **self.account.to_dict(),+ "connected": self.connected,+ "mode": self.mode,+ "message": self.message,+ "email": self.email,+ "tier": self.tier,+ }+++# ---------------------------------------------------------------- storage+++def _store_path() -> Path:+ from jarvis.core.paths import user_data_dir++ return user_data_dir() / "agent_accounts.json"+++def _accounts_root() -> Path:+ from jarvis.core.paths import user_data_dir++ return user_data_dir() / "agent-accounts"+++def _native_dir(platform: Platform) -> Path:+ """Where the CLI reads its login from when this module does nothing.++ That includes an override the app was STARTED with. A host running under a+ profile manager already has one set, and the login it points at genuinely is+ that session's default — reporting ``~/.claude`` there (and clearing the+ variable at spawn) would move panes onto a different, probably stale login+ than the one everything else on the machine uses.+ """+ inherited = os.environ.get(ENV_VAR[platform], "").strip()+ if inherited:+ return Path(inherited).expanduser()+ return Path(os.path.expanduser(_NATIVE_DIR[platform]))+++def builtin_id(platform: Platform) -> str:+ """The stable id of a platform's synthetic default account."""+ return f"{platform}:default"+++def _builtin(platform: Platform) -> AgentAccount:+ return AgentAccount(+ id=builtin_id(platform),+ platform=platform,+ label=f"Default {_DISPLAY[platform]} login",+ config_dir=_native_dir(platform),+ builtin=True,+ )+++def _read_store() -> dict[str, Any]:+ """The stored state, or an empty one for every unreadable shape."""+ try:+ raw = _store_path().read_text(encoding="utf-8")+ except FileNotFoundError:+ return {"accounts": [], "active": {}}+ except OSError as exc:+ logger.warning("Agent accounts: store could not be read ({}) — ignoring it", exc)+ return {"accounts": [], "active": {}}+ try:+ data = json.loads(raw)+ except ValueError as exc:+ logger.warning("Agent accounts: store is not valid JSON ({}) — ignoring it", exc)+ return {"accounts": [], "active": {}}+ if not isinstance(data, dict) or data.get("version") != SCHEMA_VERSION:+ return {"accounts": [], "active": {}}+ accounts = data.get("accounts")+ active = data.get("active")+ return {+ "accounts": accounts if isinstance(accounts, list) else [],+ "active": active if isinstance(active, dict) else {},+ }+++def _write_store(state: Mapping[str, Any]) -> None:+ """Atomic write — a half-written store must never be a readable one."""+ path = _store_path()+ payload = json.dumps(+ {+ "version": SCHEMA_VERSION,+ "accounts": list(state.get("accounts", [])),+ "active": dict(state.get("active", {})),+ },+ indent=2,+ ensure_ascii=False,+ )+ try:+ path.parent.mkdir(parents=True, exist_ok=True)+ tmp = path.with_name(f"{path.name}.{uuid4().hex[:8]}.tmp")+ tmp.write_text(payload, encoding="utf-8")+ os.replace(tmp, path)+ except OSError as exc:+ logger.warning("Agent accounts: store could not be written: {}", exc)+++def _parse_account(raw: Any) -> AgentAccount | None:+ """One stored entry, or ``None`` for anything that is not a usable account."""+ if not isinstance(raw, dict):+ return None+ account_id = raw.get("id")+ platform = raw.get("platform")+ config_dir = raw.get("config_dir")+ if not (isinstance(account_id, str) and account_id):+ return None+ if platform not in PLATFORMS:+ return None+ if not (isinstance(config_dir, str) and config_dir):+ return None+ label = raw.get("label")+ label = label if isinstance(label, str) and label.strip() else account_id+ try:+ directory = Path(config_dir).expanduser()+ except (OSError, ValueError):+ return None+ return AgentAccount(+ id=account_id,+ platform=platform, # type: ignore[arg-type] # narrowed by the check above+ label=label.strip()[:MAX_LABEL_CHARS],+ config_dir=directory,+ builtin=False,+ )+++# ------------------------------------------------------------------ query+++def list_accounts(platform: Platform) -> list[AgentAccount]:+ """Every account of *platform*, the built-in one first.++ The order is what the switcher renders, and it is deliberately stable: the+ default login stays at the top so the familiar entry never moves under the+ cursor as accounts are added.+ """+ stored = _read_store()["accounts"]+ added = [+ account+ for account in (_parse_account(entry) for entry in stored)+ if account is not None and account.platform == platform+ ]+ return [_builtin(platform), *added]+++def all_accounts() -> list[AgentAccount]:+ """Every account of every platform, grouped by platform."""+ return [account for platform in PLATFORMS for account in list_accounts(platform)]+++def resolve(account_id: str | None) -> AgentAccount | None:+ """An id back to its account; ``None`` when the id is unknown or empty."""+ if not account_id:+ return None+ for platform in PLATFORMS:+ if account_id == builtin_id(platform):+ return _builtin(platform)+ for account in all_accounts():+ if account.id == account_id:+ return account+ return None+++def active_account(platform: Platform) -> AgentAccount:+ """The account new panes of *platform* use unless told otherwise.++ Falls back to the built-in account whenever the pinned id no longer resolves+ — a deleted or hand-edited account must degrade to the login that always+ exists, never to "no account" (which has no directory to spawn against).+ """+ pinned = _read_store()["active"].get(platform)+ if isinstance(pinned, str):+ account = resolve(pinned)+ if account is not None and account.platform == platform:+ return account+ return _builtin(platform)+++def active_ids() -> dict[str, str]:+ """``{platform: active account id}`` for every platform."""+ return {platform: active_account(platform).id for platform in PLATFORMS}+++# ----------------------------------------------------------------- mutate+++def _slug(label: str) -> str:+ """A filesystem-safe directory stem derived from a human label."""+ cleaned = re.sub(r"[^a-z0-9]+", "-", label.strip().lower()).strip("-")+ return cleaned[:24] or "account"+++def create_account(platform: Platform, label: str) -> AgentAccount:+ """Register a new account and mint its (empty) config directory.++ The directory is created but NOT signed in — that is a separate, deliberate+ step, because a sign-in opens a browser and must never be a side effect of+ adding a row to a list. Until then the account reports itself as not signed+ in, which is exactly true.+ """+ if platform not in PLATFORMS:+ raise AccountError(f"Unknown platform: {platform}")+ clean_label = (label or "").strip()[:MAX_LABEL_CHARS]+ if not clean_label:+ raise AccountError("An account needs a name.")+ existing = [a for a in list_accounts(platform) if not a.builtin]+ if len(existing) >= MAX_ACCOUNTS_PER_PLATFORM:+ raise AccountError(+ f"{_DISPLAY[platform]} already has the maximum of "+ f"{MAX_ACCOUNTS_PER_PLATFORM} extra accounts."+ )+ account_id = f"{platform}:{uuid4().hex[:12]}"+ directory = _accounts_root() / platform / f"{_slug(clean_label)}-{account_id[-6:]}"+ try:+ directory.mkdir(parents=True, exist_ok=True)+ except OSError as exc:+ raise AccountError(f"The account folder could not be created: {exc}") from exc+ account = AgentAccount(+ id=account_id,+ platform=platform,+ label=clean_label,+ config_dir=directory,+ builtin=False,+ )+ with _WRITE_LOCK:+ state = _read_store()+ state["accounts"] = [*state["accounts"], account.to_dict()]+ _write_store(state)+ logger.info("Agent accounts: added {} account {!r}", platform, clean_label)+ return account+++def rename_account(account_id: str, label: str) -> AgentAccount:+ """Give an added account a new display name. The built-in one is fixed."""+ account = resolve(account_id)+ if account is None:+ raise AccountError("That account no longer exists.")+ if account.builtin:+ raise AccountError("The default login cannot be renamed.")+ clean_label = (label or "").strip()[:MAX_LABEL_CHARS]+ if not clean_label:+ raise AccountError("An account needs a name.")+ with _WRITE_LOCK:+ state = _read_store()+ entries = []+ for entry in state["accounts"]:+ if isinstance(entry, dict) and entry.get("id") == account_id:+ entries.append({**entry, "label": clean_label})+ else:+ entries.append(entry)+ state["accounts"] = entries+ _write_store(state)+ return AgentAccount(+ id=account.id,+ platform=account.platform,+ label=clean_label,+ config_dir=account.config_dir,+ builtin=False,+ )+++def set_active(platform: Platform, account_id: str) -> AgentAccount:+ """Point new panes of *platform* at *account_id*. This is the switch.++ Nothing that is already running changes — a pane carries the account it was+ created with, so flipping this cannot re-point an agent mid-conversation.+ """+ account = resolve(account_id)+ if account is None or account.platform != platform:+ raise AccountError("That account no longer exists.")+ with _WRITE_LOCK:+ state = _read_store()+ state["active"] = {**state["active"], platform: account_id}+ _write_store(state)+ logger.info("Agent accounts: {} now defaults to {!r}", platform, account.label)+ return account+++def delete_account(account_id: str, *, remove_files: bool = False) -> AgentAccount:+ """Forget an added account, optionally erasing its directory.++ ``remove_files=False`` is the default on purpose: forgetting is reversible+ (re-add and point at the same folder), erasing a login is not.+ """+ account = resolve(account_id)+ if account is None:+ raise AccountError("That account no longer exists.")+ if account.builtin:+ raise AccountError("The default login cannot be removed.")+ with _WRITE_LOCK:+ state = _read_store()+ state["accounts"] = [+ entry+ for entry in state["accounts"]+ if not (isinstance(entry, dict) and entry.get("id") == account_id)+ ]+ state["active"] = {+ platform: value+ for platform, value in state["active"].items()+ if value != account_id+ }+ _write_store(state)+ if remove_files:+ try:+ shutil.rmtree(account.config_dir)+ except OSError as exc:+ logger.warning(+ "Agent accounts: {} was forgotten but its folder stayed: {}",+ account.label,+ exc,+ )+ logger.info("Agent accounts: removed {!r}", account.label)+ return account+++# ------------------------------------------------------------------ spawn+++def config_dir_for(platform: Platform, account_id: str | None) -> Path:+ """The directory a spawn for *account_id* must read its login from.++ An unknown id resolves to the platform default rather than raising: a stale+ id in a resumed workspace must reopen the pane on the login that always+ exists, not kill it.+ """+ account = resolve(account_id)+ if account is None or account.platform != platform:+ return _native_dir(platform)+ return account.config_dir+++def env_overrides(platform: Platform, account_id: str | None) -> dict[str, str]:+ """The environment delta for a spawn — EMPTY for the built-in account.++ Empty, not "set it to the default path", and the difference is load-bearing+ twice over. Pinning ``CLAUDE_CONFIG_DIR=~/.claude`` is not the same as+ leaving it unset: unset lets the CLI use its true platform default, which on+ macOS is the Keychain rather than a directory, so an explicit path would send+ it looking for a file that platform never writes. And on a host that was+ started WITH an override, touching the variable at all would move the default+ account off the login the rest of the machine is using.++ In one sentence: the built-in account means "spawn exactly as this app would+ have spawned before this feature existed".+ """+ account = resolve(account_id)+ if account is None or account.platform != platform or account.builtin:+ return {}+ return {ENV_VAR[platform]: str(account.config_dir)}+++def spawn_env(+ platform: Platform,+ account_id: str | None,+ *,+ base: Mapping[str, str] | None = None,+) -> dict[str, str]:+ """The full child environment for a spawn on *account_id*.++ Inherits (``os.environ`` unless *base* is given) and then applies the+ override. Inheriting is not a convenience — the PTY backends REPLACE the+ child environment with whatever they are handed, so a bare ``{VAR: dir}``+ would strip ``PATH`` and the agent binary would stop resolving.+ """+ env = dict(os.environ if base is None else base)+ env.update(env_overrides(platform, account_id))+ return env+++# ------------------------------------------------------------------ status+++def describe(account: AgentAccount) -> AccountSnapshot:+ """Display-safe state of one account, read straight from its directory.++ Deliberately asks a narrower question than the app's connection cards do:+ not "is this machine signed in" but "is THIS account signed in". The+ cross-directory search that powers the cards would report a neighbouring+ account's healthy login here, and the switcher would show a green row for an+ account that cannot run a single pane.++ Never raises, never returns a token, and never spawns the CLI — a handful of+ small file reads, so the switcher can refresh freely.+ """+ if account.platform == "claude":+ return _describe_claude(account)+ return _describe_codex(account)+++def _describe_claude(account: AgentAccount) -> AccountSnapshot:+ from jarvis.claude_auth import claude_account_identity, subscription_label+ from jarvis.claude_credentials import claude_login_in++ snapshot = claude_login_in(account.config_dir)+ email, _name = claude_account_identity(account.config_dir)+ tier = snapshot.subscription_type+ if snapshot.status == "valid":+ 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,+ connected=False,+ mode="expired",+ # The advice matters: an access token refreshes itself the next time+ # the CLI runs, so telling this user to sign in again would be wrong+ # (the 2026-07-18 confusion on the Windows test machine).+ message=(+ "This login's token has expired — it refreshes itself the next "+ "time a terminal runs on this account. Sign in again only if that fails."+ ),+ email=email,+ tier=tier,+ )+ return AccountSnapshot(+ account=account,+ connected=False,+ mode="unknown",+ message=_not_signed_in_message(account),+ email=email,+ )+++def _describe_codex(account: AgentAccount) -> AccountSnapshot:+ from jarvis.codex_auth import codex_login_in++ connected, mode, email = codex_login_in(account.config_dir)+ if not connected:+ return AccountSnapshot(+ account=account,+ connected=False,+ mode="unknown",+ message=_not_signed_in_message(account),+ )+ if mode == "chatgpt":+ return AccountSnapshot(+ account=account,+ connected=True,+ mode="subscription",+ message=f"Signed in via ChatGPT ({email})." if email else "Signed in via ChatGPT.",+ email=email,+ )+ return AccountSnapshot(+ account=account,+ connected=True,+ mode="api_key",+ message="Signed in via an OpenAI API key.",+ )+++def _not_signed_in_message(account: AgentAccount) -> str:+ """Why an account has no login — the built-in and an added one differ.++ The macOS wording is not hedging. Claude Code stores credentials in the+ Keychain there, and whether a second config directory earns its own Keychain+ entry is not something this module can prove, so an added account that comes+ back empty after a sign-in says so plainly rather than sending panes to a+ login that is silently the first account's. Tracked in docs/os-parity.md.+ """+ if account.builtin:+ return f"Not signed in — use Sign in to connect this {_DISPLAY[account.platform]} plan."+ return (+ "Not signed in yet — use Sign in, and finish the flow in the window that opens."+ )+++def snapshots(platform: Platform) -> list[AccountSnapshot]:+ """Every account of *platform*, described."""+ return [describe(account) for account in list_accounts(platform)]+++# ------------------------------------------------------------------- login+++def start_login(account: AgentAccount) -> Any:+ """Open the CLI's own sign-in flow POINTED AT this account's directory.++ Nothing about the flow itself is reimplemented — it is each CLI's real+ interactive login, in a real visible terminal, with one environment variable+ set. That is what makes a second subscription cost a sign-in rather than a+ credential-handling scheme of our own, and it is why the first account is+ untouched while the second is being added.++ Raises ``FileNotFoundError`` when the CLI is absent and+ ``InteractiveTerminalUnavailable`` on a headless host — both honest+ capability answers rather than an invisible process nobody can complete.+ """+ from jarvis.core.interactive_terminal import launch_interactive_terminal++ env = env_overrides(account.platform, account.id)+ if account.platform == "claude":+ from jarvis.claude_auth import ClaudeAuthService, claude_install_hint++ service = ClaudeAuthService()+ binary = service._resolve_binary() # noqa: SLF001 — the module's own seam+ if binary is None:+ raise FileNotFoundError(f"Claude CLI is not installed. {claude_install_hint()}")+ argv = service._login_argv(binary) # noqa: SLF001 — capability-selected argv+ title = f"Claude sign-in — {account.label}"+ else:+ from jarvis.codex_auth import CodexAuthService++ service_codex = CodexAuthService()+ binary = service_codex._resolve_binary() # noqa: SLF001 — the module's own seam+ if binary is None:+ raise FileNotFoundError(+ "Codex CLI is not installed (run: npm i -g @openai/codex)."+ )+ argv = [binary, "login"]+ title = f"Codex sign-in — {account.label}"+ # The directory must exist before the CLI writes into it; a login that fails+ # on a missing folder looks to the user like a rejected account.+ try:+ account.config_dir.mkdir(parents=True, exist_ok=True)+ except OSError as exc:+ raise AccountError(f"The account folder is not usable: {exc}") from exc+ logger.info("Agent accounts: starting sign-in for {!r}", account.label)+ return launch_interactive_terminal(argv, title=title, env=env)+++__all__ = [+ "ENV_VAR",+ "MAX_ACCOUNTS_PER_PLATFORM",+ "MAX_LABEL_CHARS",+ "PLATFORMS",+ "SCHEMA_VERSION",+ "AccountError",+ "AccountSnapshot",+ "AgentAccount",+ "Platform",+ "active_account",+ "active_ids",+ "all_accounts",+ "builtin_id",+ "config_dir_for",+ "create_account",+ "delete_account",+ "describe",+ "env_overrides",+ "list_accounts",+ "rename_account",+ "resolve",+ "set_active",+ "snapshots",+ "spawn_env",+ "start_login",+]diff --git a/jarvis/agentic_ide/agent_sessions.py b/jarvis/agentic_ide/agent_sessions.pyindex 520a967618..f9ef98019f 100644--- a/jarvis/agentic_ide/agent_sessions.py+++ b/jarvis/agentic_ide/agent_sessions.py@@ -26,6 +26,14 @@ handle can be minted, spent, or found, and an agent that answers "no" degradesto a fresh start with an honest message — which is also what any coding CLIadded later gets for free.+Every lookup takes an optional ``home`` — the config directory whose history is+meant. It exists because a pane can run any of several subscriptions of the same+CLI (:mod:`jarvis.agent_accounts`), and each account keeps a SEPARATE history in+its own directory. Without it, a pane on the second account would look for its+transcript in the first account's folder, find nothing, and start fresh with no+sign that anything was lost. ``None`` keeps the old behaviour: the environment+override if one is set, otherwise the CLI's conventional home.+Cross-platform: nothing here is OS-specific. ``CODEX_HOME`` is honoured whenset, otherwise the CLI's conventional home directory is used, and paths arecompared through ``os.path.normcase`` so a drive-letter difference on Windows@@ -108,10 +116,13 @@ class _Adapter:# Extra argv that reopens the conversation behind an id.resume: Callable[[str], tuple[str, ...]]# Finds the id afterwards, for CLIs that cannot be told one. The third- # argument is the set of ids other panes already hold — see `discover`.- discover: Callable[[str, float, Collection[str]], ResumeHandle | None] | None+ # argument is the set of ids other panes already hold — see `discover`; the+ # fourth is the config dir whose history to search (None = the default).+ discover: (+ Callable[[str, float, Collection[str], Path | None], ResumeHandle | None] | None+ )# Is there actually a conversation behind an id? See `has_conversation`.- exists: Callable[[ResumeHandle], bool]+ exists: Callable[[ResumeHandle, Path | None], bool]def _claude_launch() -> tuple[tuple[str, ...], ResumeHandle | None]:@@ -134,7 +145,7 @@ _ADAPTERS: dict[str, _Adapter] = {launch=_claude_launch,resume=lambda session_id: ("--resume", session_id),discover=None,- exists=lambda handle: _claude_conversation_exists(handle),+ exists=lambda handle, home: _claude_conversation_exists(handle, home),),"codex": _Adapter(kind="codex_rollout",@@ -144,8 +155,10 @@ _ADAPTERS: dict[str, _Adapter] = {resume=lambda session_id: ("resume", session_id),# Late-bound on purpose: the discovery function is defined further down,# next to the file-format knowledge it needs.- discover=lambda cwd, started, taken: _discover_codex(cwd, started, taken),- exists=lambda handle: _codex_conversation_exists(handle),+ discover=lambda cwd, started, taken, home: _discover_codex(+ cwd, started, taken, home+ ),+ exists=lambda handle, home: _codex_conversation_exists(handle, home),),}@@ -182,7 +195,9 @@ def resume_argv(agent: str, handle: ResumeHandle | None) -> tuple[str, ...] | Noreturn adapter.resume(handle.id)-def has_conversation(agent: str, handle: ResumeHandle | None) -> bool:+def has_conversation(+ agent: str, handle: ResumeHandle | None, home: Path | None = None+) -> bool:"""Is there actually something behind this handle, or only a reserved id?**The distinction this whole module got wrong at first.** Being handed an id@@ -206,7 +221,7 @@ def has_conversation(agent: str, handle: ResumeHandle | None) -> bool:if adapter is None or adapter.kind != handle.kind:return Falsetry:- return adapter.exists(handle)+ return adapter.exists(handle, home)except OSError as exc:# An unreadable history is not a present conversation. Starting fresh is# recoverable; launching into a missing one kills the pane.@@ -219,6 +234,7 @@ def discover(cwd: str,started_at: float,taken: Collection[str] = (),+ home: Path | None = None,) -> ResumeHandle | None:"""Find the session a pane started at ``started_at`` in ``cwd`` created.@@ -238,19 +254,24 @@ def discover(if adapter is None or adapter.discover is None:return Nonetry:- return adapter.discover(cwd, started_at, taken)+ return adapter.discover(cwd, started_at, taken, home)except Exception as exc: # noqa: BLE001 - discovery is a conveniencelogger.warning("Agentic IDE: {} session discovery failed: {}", agent, exc)return None# -------------------------------------------------------------- Claude Code-def _claude_home() -> Path:+def _claude_home(override: Path | None = None) -> Path:+ """The config dir whose history to read: the account's, else the default."""+ if override is not None:+ return Path(override).expanduser()raw = os.environ.get("CLAUDE_CONFIG_DIR")return Path(raw).expanduser() if raw else Path.home() / ".claude"-def _claude_conversation_exists(handle: ResumeHandle) -> bool:+def _claude_conversation_exists(+ handle: ResumeHandle, home: Path | None = None+) -> bool:"""True when Claude Code has a transcript filed under this session id.Searched by id across all project folders rather than by rebuilding the@@ -262,14 +283,17 @@ def _claude_conversation_exists(handle: ResumeHandle) -> bool:session_id = handle.idif not session_id or "/" in session_id or "\\" in session_id:return False- projects = _claude_home() / "projects"+ projects = _claude_home(home) / "projects"if not projects.is_dir():return Falsereturn next(projects.glob(f"*/{session_id}.jsonl"), None) is not None# --------------------------------------------------------------------- Codex-def _codex_home() -> Path:+def _codex_home(override: Path | None = None) -> Path:+ """The CODEX_HOME whose history to read: the account's, else the default."""+ if override is not None:+ return Path(override).expanduser()raw = os.environ.get("CODEX_HOME")return Path(raw).expanduser() if raw else Path.home() / ".codex"@@ -374,7 +398,9 @@ def _candidate_files(root: Path, started_at: float) -> list[Path]:return keep[:_MAX_CANDIDATES]-def _codex_conversation_exists(handle: ResumeHandle) -> bool:+def _codex_conversation_exists(+ handle: ResumeHandle, home: Path | None = None+) -> bool:"""True when Codex still has the rollout file this handle came from.The id is in the filename, and ``captured_at`` says roughly when it was@@ -386,7 +412,7 @@ def _codex_conversation_exists(handle: ResumeHandle) -> bool:session_id = handle.idif not session_id or "/" in session_id or "\\" in session_id:return False- sessions = _codex_home() / "sessions"+ sessions = _codex_home(home) / "sessions"if not sessions.is_dir():return Falseif handle.captured_at <= 0:@@ -406,7 +432,10 @@ def _codex_conversation_exists(handle: ResumeHandle) -> bool:def _discover_codex(- cwd: str, started_at: float, taken: Collection[str] = ()+ cwd: str,+ started_at: float,+ taken: Collection[str] = (),+ home: Path | None = None,) -> ResumeHandle | None:"""The Codex session a pane in ``cwd`` started at ``started_at`` created.@@ -424,7 +453,7 @@ def _discover_codex("""claimed = {str(t) for t in taken}best: tuple[float, str] | None = None- for path in _candidate_files(_codex_home(), started_at):+ for path in _candidate_files(_codex_home(home), started_at):payload = _read_meta(path)if payload is None:continuediff --git a/jarvis/agentic_ide/resume_store.py b/jarvis/agentic_ide/resume_store.pyindex ae8c42d42b..067db1acee 100644--- a/jarvis/agentic_ide/resume_store.py+++ b/jarvis/agentic_ide/resume_store.py@@ -64,6 +64,12 @@ class SnapshotTerminal:slot: int = 0resume: ResumeHandle | None = Noneprompts_sent: int = 0+ # Which subscription this pane ran on. Remembered because the resume handle+ # alone is not enough: an account keeps its conversations in its OWN config+ # directory, so reopening on a different one would search the wrong history+ # and silently start fresh. An absent value (an older snapshot) means "the+ # account that is active when it reopens" — the old behaviour exactly.+ account: str | None = Nonedef to_dict(self) -> dict[str, Any]:return {@@ -74,6 +80,7 @@ class SnapshotTerminal:"slot": self.slot,"resume": self.resume.to_dict() if self.resume else None,"prompts_sent": self.prompts_sent,+ "account": self.account,}@staticmethod@@ -92,9 +99,33 @@ class SnapshotTerminal:slot=_as_int(data.get("slot")),resume=ResumeHandle.from_dict(data.get("resume")),prompts_sent=_as_int(data.get("prompts_sent")),+ account=(+ str(data.get("account")).strip() or None+ if isinstance(data.get("account"), str)+ else None+ ),)+def _account_home(agent: str, account_id: str | None) -> Path | None:+ """The config dir a remembered pane's conversation lives in.++ Kept local (rather than imported from ``session``) to keep this module free+ of the import cycle: ``session`` reads this store, not the other way round.+ """+ if not account_id:+ return None+ try:+ from jarvis import agent_accounts++ if agent not in agent_accounts.PLATFORMS:+ return None+ return agent_accounts.config_dir_for(agent, account_id) # type: ignore[arg-type]+ except Exception as exc: # noqa: BLE001 - the offer must never fail on this+ logger.debug("Agentic IDE: account folder for {} is unknown: {}", agent, exc)+ return None++@dataclass(slots=True)class Snapshot:"""A workspace as it stood, ready to be offered back."""@@ -275,7 +306,10 @@ def offer(snapshot: Snapshot | None, *, installed: set[str]) -> dict[str, Any]:"column": term.column,"slot": term.slot,"available": agent_available,- "resumable": agent_available and has_conversation(term.agent, term.resume),+ "resumable": agent_available+ and has_conversation(+ term.agent, term.resume, _account_home(term.agent, term.account)+ ),"prompts_sent": term.prompts_sent,})diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.pyindex d75b1e67e4..767b30a6b6 100644--- a/jarvis/agentic_ide/session.py+++ b/jarvis/agentic_ide/session.py@@ -253,6 +253,79 @@ def sanitize_prompt(text: str, *, keep_newlines: bool = False) -> str:return "\n".join(lines).strip()[:MAX_PROMPT_CHARS]+def resolve_account(agent: str, requested: str | None) -> str | None:+ """Pin a pane to a concrete account id at CREATION time.++ ``None`` in, active account out — but the answer is stored, not re-read+ later. That is the whole point: a pane must keep running on the subscription+ it was opened with even after the user switches the default, because the+ alternative is an agent whose conversation history moves out from under it.++ A requested id that does not resolve (or belongs to another CLI) falls back+ to the active account rather than failing the pane: an unopenable pane is a+ worse answer than an honest default.+ """+ if agent not in AGENT_BINARIES:+ return None+ from jarvis import agent_accounts++ if requested:+ account = agent_accounts.resolve(requested)+ if account is not None and account.platform == agent:+ return account.id+ logger.info(+ "Agentic IDE: account {!r} is unknown — using the active one instead",+ requested,+ )+ return agent_accounts.active_account(agent).id # type: ignore[arg-type]+++def account_label(account_id: str | None) -> str | None:+ """The display name of a pane's account, or ``None`` when it has none."""+ if not account_id:+ return None+ from jarvis import agent_accounts++ account = agent_accounts.resolve(account_id)+ return account.label if account is not None else None+++def _requested_account(entry: dict[str, Any]) -> str | None:+ """The account id a wizard/API request asked for, if it named one."""+ value = entry.get("account")+ return str(value).strip() or None if isinstance(value, str) else None+++def _spawn_env(term: Terminal) -> dict[str, str] | None:+ """The child environment that puts this pane on its own subscription.++ ``None`` — plain inheritance — whenever the pane's account needs nothing+ changed, which is every pane on the built-in account. So a user who never+ opens the switcher gets a spawn byte-for-byte identical to the one this app+ produced before the feature existed.+ """+ if not term.account or term.agent not in AGENT_BINARIES:+ return None+ from jarvis import agent_accounts++ if not agent_accounts.env_overrides(term.agent, term.account): # type: ignore[arg-type]+ return None+ return agent_accounts.spawn_env(term.agent, term.account) # type: ignore[arg-type]+++def account_home(agent: str, account_id: str | None) -> Path | None:+ """The config dir a pane's conversation history lives in.++ ``None`` for a pane with no account (or an agent that has none), which keeps+ every existing lookup on its old path.+ """+ if not account_id or agent not in AGENT_BINARIES:+ return None+ from jarvis import agent_accounts++ return agent_accounts.config_dir_for(agent, account_id) # type: ignore[arg-type]++def agent_argv(agent: str) -> tuple[str, ...] | None:"""argv that runs ``agent`` as the PTY's own process, or None if missing."""binary = AGENT_BINARIES.get(agent)@@ -318,6 +391,12 @@ class Terminal:# readable.column: int = 0slot: int = 0+ # Which subscription of `agent` this pane runs on (see jarvis.agent_accounts).+ # Resolved to a concrete id when the pane is CREATED, never read live at+ # spawn time: flipping the global default must not silently re-point a pane+ # that is already on screen — least of all one mid-conversation, which would+ # hand a resumed transcript to an account that has never seen it.+ account: str | None = Nonestatus: Status = "pending"pty_id: str | None = None# Set just before this pane's agent is killed on purpose (viewer gone, pane@@ -391,6 +470,8 @@ class Terminal:# Whether a handle EXISTS, never the handle itself: it is an# internal pointer into the CLI's history and no client needs it."has_resume": self.resume is not None,+ "account": self.account,+ "account_label": account_label(self.account),}def to_snapshot(self) -> resume_store.SnapshotTerminal:@@ -403,6 +484,7 @@ class Terminal:slot=self.slot,resume=self.resume,prompts_sent=self.prompts_sent,+ account=self.account,)@@ -644,6 +726,7 @@ class Registry:# A wizard-opened workspace is one row of columns; the# user's own "split down" is what creates a stack.column=index,+ account=resolve_account(agent, _requested_account(entry)),))@@ -792,6 +875,11 @@ class Registry:slot=entry.slot,resume=entry.resume,prompts_sent=entry.prompts_sent,+ # The remembered account, re-validated: a pane must come back+ # on the subscription whose history holds its conversation,+ # and an account deleted in the meantime falls back to the+ # active one rather than failing the reopen.+ account=resolve_account(entry.agent, entry.account),)for index, entry in enumerate(snapshot.terminals)]@@ -1095,8 +1183,15 @@ class Registry:# behind, and asking the CLI to resume that id makes it print "no# conversation found" and die. Measured on a real workspace — twelve# panes opened, none prompted, twelve dead panes on the way back.+ # Every history lookup below is scoped to the pane's OWN account: a pane+ # on the second subscription keeps its transcripts in that account's+ # directory, and asking the default one would report "no conversation"+ # for a conversation that is right there.+ home = account_home(term.agent, term.account)continuing = resume_argv(term.agent, term.resume)- if continuing is not None and not has_conversation(term.agent, term.resume):+ if continuing is not None and not has_conversation(+ term.agent, term.resume, home+ ):logger.info("Agentic IDE: {} has no conversation to continue — starting fresh",term.name,@@ -1197,6 +1292,7 @@ class Registry:rows=rows,on_output=_output,on_closed=_closed,+ env=_spawn_env(term),)except Exception as exc: # noqa: BLE001 - surfaced to the paneterm.status = "error"@@ -1246,7 +1342,12 @@ class Registry:if other.resume is not None}found = await asyncio.to_thread(- discover, term.agent, folder, started_at, taken+ discover,+ term.agent,+ folder,+ started_at,+ taken,+ account_home(term.agent, term.account),)if found is None:continue@@ -1318,6 +1419,7 @@ class Registry:name: str | None = None,anchor: str | None = None,direction: str = "right",+ account: str | None = None,) -> Terminal:"""Open one more terminal in the running workspace.@@ -1330,6 +1432,12 @@ class Registry:The agent defaults to the anchor's, because splitting a Claude Code paneusually means "another one of these" — but a caller may name anyinstalled agent, which is how the UI offers a choice of coding CLI.++ ``account`` names which subscription of that agent to run on; without one+ the pane inherits the anchor's, falling back to the active account. The+ inheritance matters more than it looks: splitting a pane that runs the+ second plan should stay on the second plan, or a "split" would quietly+ move the work onto a different bill."""async with self._lock:session = self.session@@ -1391,6 +1499,9 @@ class Registry:if other.column == column and other.slot >= slot:other.slot += 1+ # Inherit the anchor's account only when the split stays on the same+ # CLI — a Claude account id means nothing to Codex.+ inherited = base.account if base is not None and base.agent == chosen else Noneterm = Terminal(key=normalize(final) or f"t{len(session.terminals)}",name=final,@@ -1399,6 +1510,7 @@ class Registry:index=len(session.terminals),column=column,slot=slot,+ account=resolve_account(chosen, account or inherited),)session.terminals.append(term)self._renumber(session)@@ -1413,7 +1525,7 @@ class Registry:return termasync def add_terminals(- self, count: int, *, agent: str | None = None+ self, count: int, *, agent: str | None = None, account: str | None = None) -> tuple[list[Terminal], bool]:"""Open up to ``count`` more panes — the batch behind "open five more".@@ -1437,7 +1549,7 @@ class Registry:created: list[Terminal] = []for _ in range(wanted):try:- created.append(await self.add_terminal(agent=agent))+ created.append(await self.add_terminal(agent=agent, account=account))except SessionError as exc:if not created:raisediff --git a/jarvis/claude_auth.py b/jarvis/claude_auth.pyindex fb18ff3fba..5e08a5e3a4 100644--- a/jarvis/claude_auth.py+++ b/jarvis/claude_auth.py@@ -144,6 +144,35 @@ def _subscription_label(sub_type: str | None) -> str:return f"Claude {sub_type}"+def subscription_label(sub_type: str | None) -> str:+ """Public alias of the tier label, for the multi-account switcher."""+ return _subscription_label(sub_type)+++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.++ 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:+ email, name = _account_from_claude_json(_read_json(candidate))+ if email or name:+ return email, name+ return None, None++@dataclass(frozen=True)class ClaudeCliAuthSnapshot:"""Display-safe result from ``claude auth status --json``.diff --git a/jarvis/claude_credentials.py b/jarvis/claude_credentials.pyindex 340895c127..b05931846b 100644--- a/jarvis/claude_credentials.py+++ b/jarvis/claude_credentials.py@@ -123,6 +123,40 @@ def _parse_oauth_file(return token, sub_type, expires_s+def claude_login_in(+ config_dir: Path, *, now_fn: Callable[[], float] = time.time+) -> ClaudeOAuthSnapshot:+ """The login stored in ONE specific config dir, without cross-dir search.++ The multi-account switcher (:mod:`jarvis.agent_accounts`) asks a different+ question than :func:`freshest_claude_oauth`: not "where is the live login on+ this machine" but "is THIS account signed in". Answering that with the+ cross-dir scan would report a neighbouring account's healthy login as if it+ belonged to the directory being asked about, and the UI would show a green+ card for an account that cannot run anything.++ Never raises; an unreadable or absent file is ``"absent"``.+ """+ 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+ if 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,+ )+ return ClaudeOAuthSnapshot(+ status="valid",+ access_token=token,+ subscription_type=sub_type,+ config_dir=config_dir,+ expires_s=expires_s,+ )++def freshest_claude_oauth(*, now_fn: Callable[[], float] = time.time) -> ClaudeOAuthSnapshot:"""Scan every candidate config dir; the freshest LIVE login wins.@@ -178,5 +212,6 @@ __all__ = ["OAUTH_EXPIRY_SLACK_S","ClaudeOAuthSnapshot","claude_config_dirs",+ "claude_login_in","freshest_claude_oauth",]diff --git a/jarvis/codex_auth.py b/jarvis/codex_auth.pyindex c0fb43728a..58e6692e28 100644--- a/jarvis/codex_auth.py+++ b/jarvis/codex_auth.py@@ -125,6 +125,34 @@ def _email_from_id_token(tokens: dict[str, Any] | None) -> str | None:return email if isinstance(email, str) and email else None+def codex_login_in(codex_home: Path) -> tuple[bool, str, str | None]:+ """``(connected, mode, email)`` for the login kept in ONE ``CODEX_HOME``.++ The multi-account switcher (:mod:`jarvis.agent_accounts`) asks about a+ specific directory rather than about "the" Codex login, so this deliberately+ ignores ``$CODEX_HOME`` and reads exactly the directory it is handed.++ Never raises; an absent or unparseable ``auth.json`` is+ ``(False, "unknown", None)``.+ """+ try:+ raw = (codex_home / "auth.json").read_text(encoding="utf-8")+ except (OSError, ValueError):+ return False, "unknown", None+ try:+ data = json.loads(raw)+ except (ValueError, json.JSONDecodeError):+ return False, "unknown", None+ auth = data if isinstance(data, dict) else None+ connected, mode = _derive_auth(auth)+ email = (+ _email_from_id_token(auth.get("tokens"))+ if connected and mode == "chatgpt" and isinstance(auth, dict)+ else None+ )+ return connected, mode, email++# ----------------------------------------------------------------------# Status snapshot# ----------------------------------------------------------------------diff --git a/jarvis/core/interactive_terminal.py b/jarvis/core/interactive_terminal.pyindex d1a1e06a27..54e946bc9b 100644--- a/jarvis/core/interactive_terminal.py+++ b/jarvis/core/interactive_terminal.py@@ -20,7 +20,7 @@ import shleximport shutilimport subprocessimport sys-from collections.abc import Sequence+from collections.abc import Mapping, Sequencefrom dataclasses import dataclassfrom pathlib import Path@@ -50,8 +50,27 @@ def _validated_argv(argv: Sequence[str]) -> list[str]:return values-def _macos_script(argv: Sequence[str], cwd: Path) -> str:- command = f"cd {shlex.quote(str(cwd))} && {shlex.join(argv)}"+def _child_env(env: Mapping[str, str] | None) -> dict[str, str] | None:+ """This process's environment plus *env*, or ``None`` to inherit unchanged.++ An overlay, never a replacement: handing a child a bare ``{VAR: value}``+ would strip ``PATH`` and the CLI being launched would stop resolving.+ """+ if not env:+ return None+ return {**os.environ, **{str(k): str(v) for k, v in env.items()}}+++def _macos_script(argv: Sequence[str], cwd: Path, env: Mapping[str, str] | None) -> str:+ # Terminal.app runs a shell STRING, not an argv with an environment block, so+ # an override has to be written into the command itself as a `VAR=value`+ # prefix — the one place where carrying an environment differs per OS.+ assignments = (+ "".join(f"{key}={shlex.quote(str(value))} " for key, value in sorted(env.items()))+ if env+ else ""+ )+ command = f"cd {shlex.quote(str(cwd))} && {assignments}{shlex.join(argv)}"apple_string = command.replace("\\", "\\\\").replace('"', '\\"')return f'tell application "Terminal"\nactivate\ndo script "{apple_string}"\nend tell'@@ -60,6 +79,7 @@ def _launch_macos(argv: Sequence[str],*,cwd: Path,+ env: Mapping[str, str] | None = None,) -> InteractiveTerminalLaunch:osascript = shutil.which("osascript")if not osascript:@@ -68,7 +88,7 @@ def _launch_macos()try:result = subprocess.run(- [osascript, "-e", _macos_script(argv, cwd)],+ [osascript, "-e", _macos_script(argv, cwd, env)],capture_output=True,text=True,timeout=8.0,@@ -106,6 +126,7 @@ def _launch_windows(argv: Sequence[str],*,cwd: Path,+ env: Mapping[str, str] | None = None,) -> InteractiveTerminalLaunch:flags = getattr(subprocess, "CREATE_NEW_CONSOLE", 0x00000010) | getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0x00000200@@ -116,6 +137,7 @@ def _launch_windows(cwd=str(cwd),creationflags=flags,close_fds=True,+ env=_child_env(env),)except OSError as exc:raise InteractiveTerminalUnavailable(@@ -150,6 +172,7 @@ def _launch_linux(*,cwd: Path,title: str,+ env: Mapping[str, str] | None = None,) -> InteractiveTerminalLaunch:if not (os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY")):raise InteractiveTerminalUnavailable(@@ -175,6 +198,7 @@ def _launch_linux(start_new_session=True,close_fds=True,creationflags=NO_WINDOW_CREATIONFLAGS,+ env=_child_env(env),)except OSError:failures.append(name)@@ -194,21 +218,27 @@ def launch_interactive_terminal(*,title: str,cwd: Path | None = None,+ env: Mapping[str, str] | None = None,) -> InteractiveTerminalLaunch:"""Open ``argv`` in a visible terminal, or raise an honest capability error.Windows receives a fresh console, macOS uses Terminal.app, and Linux probescommon terminal emulators only when a graphical display is present. Aheadless server never starts an invisible OAuth process.++ ``env`` is an OVERLAY on this process's environment, not a replacement. It+ exists so a sign-in can be pointed at a specific config directory — that is+ how a second subscription is added without disturbing the first+ (:mod:`jarvis.agent_accounts`)."""command = _validated_argv(argv)workdir = Path(cwd) if cwd is not None else Path.home()if sys.platform == "win32":- return _launch_windows(command, cwd=workdir)+ return _launch_windows(command, cwd=workdir, env=env)if sys.platform == "darwin":- return _launch_macos(command, cwd=workdir)+ return _launch_macos(command, cwd=workdir, env=env)if sys.platform.startswith("linux"):- return _launch_linux(command, cwd=workdir, title=title)+ return _launch_linux(command, cwd=workdir, title=title, env=env)raise InteractiveTerminalUnavailable(f"Interactive terminal launch is not supported on platform {sys.platform!r}.")diff --git a/jarvis/terminal/pty_manager.py b/jarvis/terminal/pty_manager.pyindex 5ec56ed836..24b3e7458b 100644--- a/jarvis/terminal/pty_manager.py+++ b/jarvis/terminal/pty_manager.py@@ -22,7 +22,7 @@ from __future__ import annotationsimport asyncioimport threading-from collections.abc import Awaitable, Callable+from collections.abc import Awaitable, Callable, Mappingfrom dataclasses import dataclassfrom uuid import uuid4@@ -66,6 +66,7 @@ class PtyManager:rows: int,on_output: OutputCallback,on_closed: ClosedCallback,+ env: Mapping[str, str] | None = None,) -> PtySession:"""Starts a new PTY session and registers the I/O callbacks.@@ -76,6 +77,13 @@ class PtyManager:Winpty on Windows, ptyprocess on POSIX, or a null backend that raises aclear English RuntimeError when no PTY capability exists (AD-6). Anysuch RuntimeError propagates to the caller as a typed error.++ ``env`` REPLACES the child environment (that is the backend contract, not+ a choice made here), so a caller passing one must hand over a COMPLETE+ environment — typically ``os.environ`` plus its own keys. Building that+ overlay is what `jarvis.agent_accounts.spawn_env` exists for. ``None``+ inherits this process's environment and is what every caller that does+ not care gets."""backend = make_pty_backend()@@ -88,6 +96,7 @@ class PtyManager:cwd=cwd,cols=cols,rows=rows,+ env=env,)proc = await loop.run_in_executor(None, _spawn_sync)diff --git a/jarvis/ui/web/agent_accounts_routes.py b/jarvis/ui/web/agent_accounts_routes.pynew file mode 100644index 0000000000..8ff6483ab0--- /dev/null+++ b/jarvis/ui/web/agent_accounts_routes.py@@ -0,0 +1,193 @@+"""REST routes for switching between several subscriptions of a coding CLI.++A user with two Claude Max seats (or two ChatGPT/Codex plans) can register both+here and flip which one new terminals run on, without ever logging out. The+mechanism is deliberately thin — an account IS a config directory, and switching+picks the directory the next spawn points at — so everything below is the CRUD+around :mod:`jarvis.agent_accounts` plus one sign-in launcher.++Mount alongside the other routers::++ from .agent_accounts_routes import router as agent_accounts_router+ app.include_router(agent_accounts_router)++Nothing here returns a credential. The snapshots carry booleans, the display+email, and the tier — never a token, and never the contents of a config file.+"""+from __future__ import annotations++import asyncio+import logging+from typing import Any++from fastapi import APIRouter, HTTPException+from pydantic import BaseModel, Field++from jarvis import agent_accounts+from jarvis.agent_accounts import MAX_LABEL_CHARS, PLATFORMS, AccountError+from jarvis.core.interactive_terminal import InteractiveTerminalUnavailable++log = logging.getLogger(__name__)++router = APIRouter(prefix="/api/agent-accounts", tags=["agent-accounts"])+++class AccountCreateRequest(BaseModel):+ platform: str = Field(description="Which coding CLI: 'claude' or 'codex'.")+ label: str = Field(+ max_length=MAX_LABEL_CHARS,+ description="Display name for this subscription, e.g. 'Work seat'.",+ )+++class AccountRenameRequest(BaseModel):+ label: str = Field(+ max_length=MAX_LABEL_CHARS, description="New display name for the account."+ )+++class ActiveRequest(BaseModel):+ platform: str = Field(description="Which coding CLI to switch: 'claude' or 'codex'.")+ account_id: str = Field(description="Id of the account new terminals should use.")+++def _platform(value: str) -> str:+ if value not in PLATFORMS:+ raise HTTPException(+ status_code=422,+ detail=f"Unknown platform {value!r}. Known: {', '.join(PLATFORMS)}.",+ )+ return value+++def _collect() -> dict[str, Any]:+ """Every account of every platform, described, plus who is active."""+ return {+ "platforms": [+ {+ "platform": platform,+ "active_account": agent_accounts.active_account(platform).id,+ "accounts": [s.to_dict() for s in agent_accounts.snapshots(platform)],+ }+ for platform in PLATFORMS+ ]+ }++[email protected]("", summary="Stored subscriptions per coding CLI")+async def list_accounts() -> dict[str, Any]:+ """Every registered subscription and which one new terminals will use.++ Reading a handful of small files per account, off the event loop so a slow+ or spun-down drive cannot stall the rest of the server.+ """+ return await asyncio.to_thread(_collect)++[email protected]("", summary="Add another subscription")+async def create_account(req: AccountCreateRequest) -> dict[str, Any]:+ """Register a subscription and mint its (still empty) config directory.++ Adding does NOT sign in — that is a separate, deliberate step, because a+ sign-in opens a browser window and must never be a side effect of adding a+ row to a list. Until it happens the account reports itself as not signed in,+ which is exactly true.+ """+ platform = _platform(req.platform)+ try:+ account = await asyncio.to_thread(+ agent_accounts.create_account, platform, req.label+ )+ except AccountError as exc:+ raise HTTPException(status_code=422, detail=str(exc)) from exc+ snapshot = await asyncio.to_thread(agent_accounts.describe, account)+ return {"ok": True, "account": snapshot.to_dict(), **await asyncio.to_thread(_collect)}++[email protected]("/active", summary="Switch which subscription new terminals use")+async def set_active(req: ActiveRequest) -> dict[str, Any]:+ """Point new terminals of one CLI at another subscription.++ Running panes are untouched on purpose: each carries the account it was+ opened with, so this can never move an agent mid-conversation onto a plan+ whose history does not contain that conversation.+ """+ platform = _platform(req.platform)+ try:+ account = await asyncio.to_thread(+ agent_accounts.set_active, platform, req.account_id+ )+ except AccountError as exc:+ raise HTTPException(status_code=404, detail=str(exc)) from exc+ return {+ "ok": True,+ "active_account": account.id,+ "message": f"New {platform} terminals will use {account.label}.",+ **await asyncio.to_thread(_collect),+ }++[email protected]("/{account_id}/login", summary="Sign in to one subscription")+async def login(account_id: str) -> dict[str, Any]:+ """Run the CLI's own sign-in, pointed at this account's directory.++ 409 when the CLI is missing or the host has no terminal to show — both are+ capability answers the user can act on, not failures to hide.+ """+ account = await asyncio.to_thread(agent_accounts.resolve, account_id)+ if account is None:+ raise HTTPException(status_code=404, detail="That account no longer exists.")+ try:+ await asyncio.to_thread(agent_accounts.start_login, account)+ except FileNotFoundError as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc+ except InteractiveTerminalUnavailable as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc+ except AccountError as exc:+ raise HTTPException(status_code=422, detail=str(exc)) from exc+ except Exception as exc: # noqa: BLE001+ raise HTTPException(+ status_code=500,+ detail=f"The sign-in could not be started: {type(exc).__name__}: {exc}",+ ) from exc+ return {+ "ok": True,+ "message": f"Sign-in started for {account.label} — finish it in the window that opened.",+ }++[email protected]("/{account_id}", summary="Rename a subscription")+async def rename(account_id: str, req: AccountRenameRequest) -> dict[str, Any]:+ """Give an added subscription a different display name."""+ try:+ account = await asyncio.to_thread(+ agent_accounts.rename_account, account_id, req.label+ )+ except AccountError as exc:+ raise HTTPException(status_code=422, detail=str(exc)) from exc+ return {"ok": True, "account": account.to_dict(), **await asyncio.to_thread(_collect)}+++ "/{account_id}",+ summary="Remove a subscription",+ openapi_extra={"x-jarvis-dangerous": True},+)+async def delete(account_id: str, remove_files: bool = False) -> dict[str, Any]:+ """Forget an added subscription; optionally erase its stored login too.++ ``remove_files`` defaults to false because forgetting is reversible and+ erasing a login is not. The default login can never be removed — it is the+ CLI's own, and this feature does not get to take it away.+ """+ try:+ account = await asyncio.to_thread(+ agent_accounts.delete_account, account_id, remove_files=remove_files+ )+ except AccountError as exc:+ raise HTTPException(status_code=422, detail=str(exc)) from exc+ return {+ "ok": True,+ "message": f"{account.label} was removed.",+ **await asyncio.to_thread(_collect),+ }diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.pyindex 2616751a03..5d417d66b8 100644--- a/jarvis/ui/web/agentic_ide_routes.py+++ b/jarvis/ui/web/agentic_ide_routes.py@@ -60,6 +60,7 @@ from jarvis.agentic_ide.session import (MAX_TERMINALS,MAX_WORKSPACES,SessionError,+ account_home,agent_argv,get_registry,terminals_added_event,@@ -78,12 +79,22 @@ _native_picker_lock = asyncio.Lock()# --------------------------------------------------------------------------- ## Models ## --------------------------------------------------------------------------- #+#: Reused wherever a caller may pick which subscription a pane runs on.+_ACCOUNT_FIELD_DESCRIPTION = (+ "Which stored subscription of that agent to run on (see /api/agent-accounts). "+ "Defaults to the active account; an unknown id falls back to it."+)++class TerminalRequest(BaseModel):agent: str = Field(description="Coding agent to run: 'claude' or 'codex'.")name: str | None = Field(default=None,description="Call-sign for this terminal; auto-assigned when omitted.",)+ account: str | None = Field(+ default=None, description=_ACCOUNT_FIELD_DESCRIPTION+ )class StartSessionRequest(BaseModel):@@ -114,6 +125,13 @@ class AddTerminalRequest(BaseModel):"anchor's own column and stacks the new pane under it."),)+ account: str | None = Field(+ default=None,+ description=(+ "Which stored subscription to run on; defaults to the anchor pane's, "+ "then to the active account."+ ),+ )class AddTerminalsRequest(BaseModel):@@ -129,6 +147,9 @@ class AddTerminalsRequest(BaseModel):default=None,description="Coding agent to run in all of them; defaults to the last pane's.",)+ account: str | None = Field(+ default=None, description=_ACCOUNT_FIELD_DESCRIPTION+ )class ModeRequest(BaseModel):@@ -772,11 +793,17 @@ async def resume_workspace() -> dict:# points at nothing, and reporting it as continued would be the same lie the# offer screen exists to prevent. One thread hop for the whole list, since# each check is a filename lookup.- def _count_conversations(panes: list[tuple[str, object]]) -> int:- return sum(1 for agent, handle in panes if has_conversation(agent, handle))+ def _count_conversations(panes: list[tuple[str, object, object]]) -> int:+ # The history to ask is the PANE's account, not the machine default:+ # each subscription keeps its conversations in its own directory.+ return sum(1 for agent, handle, home in panes if has_conversation(agent, handle, home))resumable = await asyncio.to_thread(- _count_conversations, [(t.agent, t.resume) for t in session.terminals]+ _count_conversations,+ [+ (t.agent, t.resume, account_home(t.agent, t.account))+ for t in session.terminals+ ],)return {"ok": True,@@ -837,6 +864,7 @@ async def add_terminal(req: AddTerminalRequest) -> dict:name=req.name,anchor=req.anchor,direction=req.direction,+ account=req.account,)except SessionError as exc:raise HTTPException(status_code=409, detail=str(exc)) from exc@@ -857,7 +885,9 @@ async def add_terminals(request: Request, req: AddTerminalsRequest) -> dict:"""registry = get_registry()try:- created, capped = await registry.add_terminals(req.count, agent=req.agent)+ created, capped = await registry.add_terminals(+ req.count, agent=req.agent, account=req.account+ )except SessionError as exc:raise HTTPException(status_code=409, detail=str(exc)) from excdiff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex 65730f7080..6d4063ac74 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -288,6 +288,7 @@ class WebServer:from jarvis.runs.routes import router as runs_routerfrom jarvis.runs.runs_ws import router as runs_ws_router+ from .agent_accounts_routes import router as agent_accounts_routerfrom .antigravity_routes import router as antigravity_routerfrom .board_routes import (board_router as board_meta_router,@@ -366,6 +367,8 @@ class WebServer:app.include_router(provider_router)app.include_router(antigravity_router)app.include_router(claude_router)+ # Several subscriptions per coding CLI, switchable without a logout.+ app.include_router(agent_accounts_router)app.include_router(control_router)app.include_router(profile_router)app.include_router(settings_router)diff --git a/tests/fakes/fake_pty_manager.py b/tests/fakes/fake_pty_manager.pyindex 058978367f..601177d3af 100644--- a/tests/fakes/fake_pty_manager.py+++ b/tests/fakes/fake_pty_manager.py@@ -46,6 +46,7 @@ class FakePtyManager:rows: int,on_output: Any,on_closed: Any,+ env: Any = None,) -> FakePtySession:if self.spawn_error:raise RuntimeError(self.spawn_error)@@ -60,6 +61,9 @@ class FakePtyManager:"rows": rows,"on_output": on_output,"on_closed": on_closed,+ # The environment a pane was started with — how a test proves+ # which subscription an agent actually runs on.+ "env": dict(env) if env is not None else None,})self._live.add(terminal_id)diff --git a/tests/unit/agentic_ide/conftest.py b/tests/unit/agentic_ide/conftest.pyindex 6539dd99f9..399707bc3e 100644--- a/tests/unit/agentic_ide/conftest.py+++ b/tests/unit/agentic_ide/conftest.py@@ -23,6 +23,9 @@ guarantee that only holds until somebody writes the next test.entries, which the trust check then had to parse before every workspace open.The trust logic itself is covered where it belongs, in``tests/unit/workspace/test_trust.py``, against a temporary home.+4. **The agent-account store.** Panes now record which subscription they run on,+ which means opening one reads (and resuming one could write) the developer's+ real account list. Same store, same failure class as 1 and 2."""from __future__ import annotations@@ -73,6 +76,19 @@ def _agent_history_in_tmp(return home[email protected](autouse=True)+def _agent_accounts_in_tmp(+ tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatch+) -> Path:+ """Give each test its own empty account list and account folder root."""+ from jarvis import agent_accounts++ root = tmp_path_factory.mktemp("agent-accounts")+ monkeypatch.setattr(agent_accounts, "_store_path", lambda: root / "accounts.json")+ monkeypatch.setattr(agent_accounts, "_accounts_root", lambda: root / "dirs")+ return root++@pytest.fixturedef existing_conversation() -> Any:"""Create the on-disk conversation a resume handle points at.diff --git a/tests/unit/agentic_ide/test_account_spawn.py b/tests/unit/agentic_ide/test_account_spawn.pynew file mode 100644index 0000000000..56dff56d5c--- /dev/null+++ b/tests/unit/agentic_ide/test_account_spawn.py@@ -0,0 +1,241 @@+"""Which subscription a pane actually runs on.++The switch is only worth anything if the pane's environment really carries it,+so these drive the registry end to end and read the environment the PTY was+handed — not the intent, the result.++The other half is the trap this feature could create: a user switches the+default while agents are running. A pane that silently followed would resume a+conversation on a plan whose history has never seen it, and the agent would come+back amnesiac with no explanation. Pinning the account at pane CREATION is what+prevents that, and it is pinned down here.+"""++from __future__ import annotations++from pathlib import Path++import pytest++from jarvis import agent_accounts+from jarvis.agentic_ide import session as session_mod+from jarvis.agentic_ide.session import Registry+from tests.fakes.fake_pty_manager import FakePtyManager+++def fake_pty() -> FakePtyManager:+ return FakePtyManager()+++def registry(fake_pty: FakePtyManager, monkeypatch: pytest.MonkeyPatch) -> Registry:+ monkeypatch.setattr(session_mod, "agent_argv", lambda name: (f"/usr/bin/{name}",))+ return Registry(pty_manager=fake_pty)+++async def _noop(_text: str) -> None:+ return None+++async def _noop_exit(_code: int) -> None:+ return None+++async def _attach(registry: Registry, name: str) -> None:+ await registry.attach(name, 80, 24, _noop, _noop_exit)+++def _env_of(fake_pty: FakePtyManager, index: int = 0) -> dict[str, str] | None:+ return fake_pty.spawns[index]["env"]+++# ------------------------------------------------------------------- pinning+++async def test_a_pane_is_pinned_to_the_active_account_when_it_is_created(+ registry: Registry, tmp_path: Path+) -> None:+ second = agent_accounts.create_account("claude", "Second seat")+ agent_accounts.set_active("claude", second.id)+ await registry.start(str(tmp_path), [{"agent": "claude"}])+ assert registry.session.terminals[0].account == second.id+++async def test_a_pane_may_be_opened_on_an_account_that_is_not_the_active_one(+ registry: Registry, tmp_path: Path+) -> None:+ """This is what makes two subscriptions usable AT THE SAME TIME."""+ second = agent_accounts.create_account("claude", "Second seat")+ await registry.start(+ str(tmp_path),+ [{"agent": "claude"}, {"agent": "claude", "account": second.id}],+ )+ panes = registry.session.terminals+ assert panes[0].account == agent_accounts.builtin_id("claude")+ assert panes[1].account == second.id+++async def test_switching_the_default_does_not_move_a_running_pane(+ registry: Registry, tmp_path: Path+) -> None:+ """The whole reason the account is pinned at creation rather than read live."""+ await registry.start(str(tmp_path), [{"agent": "claude"}])+ pinned = registry.session.terminals[0].account+ second = agent_accounts.create_account("claude", "Second seat")+ agent_accounts.set_active("claude", second.id)+ assert registry.session.terminals[0].account == pinned+++async def test_a_new_pane_after_the_switch_gets_the_new_account(+ registry: Registry, tmp_path: Path+) -> None:+ await registry.start(str(tmp_path), [{"agent": "claude"}])+ second = agent_accounts.create_account("claude", "Second seat")+ agent_accounts.set_active("claude", second.id)+ added = await registry.add_terminal(agent="claude", anchor=None)+ # No anchor was named, so the last pane is the anchor and its account is+ # inherited — the switch reaches the panes that DON'T inherit one.+ assert added.account == registry.session.terminals[0].account+++async def test_a_split_stays_on_the_account_its_anchor_runs_on(+ registry: Registry, tmp_path: Path+) -> None:+ """Splitting must not quietly move the work onto a different bill."""+ second = agent_accounts.create_account("claude", "Second seat")+ await registry.start(str(tmp_path), [{"agent": "claude", "account": second.id}])+ anchor = registry.session.terminals[0]+ split = await registry.add_terminal(anchor=anchor.name, direction="down")+ assert split.account == second.id+++async def test_a_split_onto_a_different_cli_does_not_inherit_the_account(+ registry: Registry, tmp_path: Path+) -> None:+ """A Claude account id means nothing to Codex."""+ second = agent_accounts.create_account("claude", "Second seat")+ await registry.start(str(tmp_path), [{"agent": "claude", "account": second.id}])+ anchor = registry.session.terminals[0]+ split = await registry.add_terminal(anchor=anchor.name, agent="codex")+ assert split.account == agent_accounts.builtin_id("codex")+++async def test_an_unknown_account_falls_back_instead_of_failing_the_pane(+ registry: Registry, tmp_path: Path+) -> None:+ await registry.start(str(tmp_path), [{"agent": "claude", "account": "claude:ghost"}])+ assert registry.session.terminals[0].account == agent_accounts.builtin_id("claude")+++# --------------------------------------------------------------- the spawn+++async def test_a_pane_on_an_added_account_spawns_with_that_config_dir(+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path+) -> None:+ second = agent_accounts.create_account("claude", "Second seat")+ await registry.start(str(tmp_path), [{"agent": "claude", "account": second.id}])+ await _attach(registry, registry.session.terminals[0].name)+ env = _env_of(fake_pty)+ assert env is not None+ assert env["CLAUDE_CONFIG_DIR"] == str(second.config_dir)+++async def test_a_pane_on_the_builtin_account_spawns_exactly_as_it_always_did(+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path+) -> None:+ """No environment is passed at all — plain inheritance, byte for byte.++ This is the promise to everyone who never opens the switcher: adding the+ feature changed nothing about how their panes start.+ """+ await registry.start(str(tmp_path), [{"agent": "claude"}])+ await _attach(registry, registry.session.terminals[0].name)+ assert _env_of(fake_pty) is None+++async def test_the_spawn_environment_keeps_PATH(+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path+) -> None:+ """A replaced environment would leave the agent binary unresolvable."""+ second = agent_accounts.create_account("codex", "Second plan")+ await registry.start(str(tmp_path), [{"agent": "codex", "account": second.id}])+ await _attach(registry, registry.session.terminals[0].name)+ env = _env_of(fake_pty)+ assert env is not None+ assert env.get("PATH")+ assert env["CODEX_HOME"] == str(second.config_dir)+++async def test_two_panes_can_run_two_different_subscriptions_at_once(+ registry: Registry, fake_pty: FakePtyManager, tmp_path: Path+) -> None:+ """The point of holding two plans, expressed as one assertion."""+ second = agent_accounts.create_account("claude", "Second seat")+ await registry.start(+ str(tmp_path),+ [{"agent": "claude"}, {"agent": "claude", "account": second.id}],+ )+ for term in registry.session.terminals:+ await _attach(registry, term.name)+ first_env, second_env = _env_of(fake_pty, 0), _env_of(fake_pty, 1)+ # The default pane inherits untouched; the second is pinned to its own seat.+ assert first_env is None+ assert second_env is not None+ assert second_env["CLAUDE_CONFIG_DIR"] == str(second.config_dir)+++# ------------------------------------------------------------------- resume+++async def test_a_pane_looks_for_its_conversation_in_its_own_account(+ registry: Registry, tmp_path: Path+) -> None:+ """The silent-amnesia bug: the right handle, searched in the wrong folder."""+ from jarvis.agentic_ide.agent_sessions import ResumeHandle, has_conversation++ second = agent_accounts.create_account("claude", "Second seat")+ handle = ResumeHandle(+ kind="claude_session", id="11111111-2222-3333-4444-555555555555", captured_at=0.0+ )+ projects = second.config_dir / "projects" / "some-repo"+ projects.mkdir(parents=True, exist_ok=True)+ (projects / f"{handle.id}.jsonl").write_text("{}\n", encoding="utf-8")++ # Found when asked about the account that holds it...+ assert has_conversation("claude", handle, second.config_dir) is True+ # ...and honestly absent from the default account, which never saw it.+ assert has_conversation("claude", handle, tmp_path / "elsewhere") is False+++async def test_a_resumed_workspace_comes_back_on_the_same_accounts(+ registry: Registry, tmp_path: Path+) -> None:+ from jarvis.agentic_ide import resume_store++ second = agent_accounts.create_account("codex", "Second plan")+ snapshot = resume_store.Snapshot(+ session_id="s1",+ folder=str(tmp_path),+ saved_at=0.0,+ terminals=[+ resume_store.SnapshotTerminal(+ key="alex", name="Alex", agent="codex", account=second.id+ )+ ],+ )+ restored = resume_store.Snapshot.from_dict(snapshot.to_dict())+ assert restored is not None+ assert restored.terminals[0].account == second.id+++async def test_an_older_snapshot_without_an_account_still_reopens() -> None:+ """A build that predates the switcher must keep resuming."""+ from jarvis.agentic_ide import resume_store++ restored = resume_store.SnapshotTerminal.from_dict(+ {"key": "alex", "name": "Alex", "agent": "claude", "column": 0, "slot": 0}+ )+ assert restored is not None+ assert restored.account is Nonediff --git a/tests/unit/agentic_ide/test_resume_session.py b/tests/unit/agentic_ide/test_resume_session.pyindex f0f8ab01df..ad11bbc20e 100644--- a/tests/unit/agentic_ide/test_resume_session.py+++ b/tests/unit/agentic_ide/test_resume_session.py@@ -575,7 +575,7 @@ async def test_a_lookup_offers_the_ids_other_panes_already_hold(monkeypatch.setattr(ide, "DISCOVERY_DELAYS_S", (0.0,))seen: list[set[str]] = []- def _spy(_agent: str, _cwd: str, _started: float, taken: set[str]):+ def _spy(_agent: str, _cwd: str, _started: float, taken: set[str], _home=None):seen.append(set(taken))return Nonediff --git a/tests/unit/test_agent_accounts.py b/tests/unit/test_agent_accounts.pynew file mode 100644index 0000000000..38abf438ed--- /dev/null+++ b/tests/unit/test_agent_accounts.py@@ -0,0 +1,367 @@+"""The store, the switch, and the environment behind multi-subscription support.++What these pin down is not "does the JSON round-trip" but the four things that+would silently send work to the wrong plan:++* the built-in account is synthetic and always there, even with no store;+* switching the default cannot leave a pane pointing at a vanished account;+* the built-in account REMOVES the override rather than pinning a path+ (the macOS Keychain depends on that difference);+* ``spawn_env`` inherits, because a replaced environment has no ``PATH``.+"""++from __future__ import annotations++import json+from pathlib import Path++import pytest++from jarvis import agent_accounts+from jarvis.agent_accounts import AccountError++[email protected](autouse=True)+def _isolated_store(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ """A throwaway store + account root, never the developer's own."""+ monkeypatch.setattr(agent_accounts, "_store_path", lambda: tmp_path / "accounts.json")+ monkeypatch.setattr(agent_accounts, "_accounts_root", lambda: tmp_path / "dirs")+ monkeypatch.setattr(+ agent_accounts, "_native_dir", lambda platform: tmp_path / "native" / platform+ )+ return tmp_path+++# ------------------------------------------------------------------ built-in+++def test_every_platform_offers_its_builtin_account_with_no_store() -> None:+ """A fresh install has one usable account per CLI and no file at all."""+ for platform in agent_accounts.PLATFORMS:+ accounts = agent_accounts.list_accounts(platform)+ assert len(accounts) == 1+ assert accounts[0].builtin is True+ assert accounts[0].id == agent_accounts.builtin_id(platform)+ assert agent_accounts.active_account(platform).id == accounts[0].id+++def test_the_builtin_account_can_be_neither_renamed_nor_removed() -> None:+ """It is the CLI's own login; this feature does not get to take it away."""+ builtin = agent_accounts.builtin_id("claude")+ with pytest.raises(AccountError):+ agent_accounts.rename_account(builtin, "Something else")+ with pytest.raises(AccountError):+ agent_accounts.delete_account(builtin)+++# --------------------------------------------------------------------- store+++def test_an_added_account_survives_a_reread_and_keeps_the_builtin_first() -> None:+ account = agent_accounts.create_account("claude", "Second seat")+ listed = agent_accounts.list_accounts("claude")+ assert [a.builtin for a in listed] == [True, False]+ assert listed[1].id == account.id+ assert listed[1].label == "Second seat"+ assert listed[1].config_dir.is_dir()+++def test_accounts_of_one_platform_never_leak_into_the_other() -> None:+ agent_accounts.create_account("claude", "Claude seat")+ agent_accounts.create_account("codex", "Codex seat")+ assert [a.label for a in agent_accounts.list_accounts("claude")][1:] == ["Claude seat"]+ assert [a.label for a in agent_accounts.list_accounts("codex")][1:] == ["Codex seat"]+++def test_an_unreadable_store_degrades_to_the_builtin_account(tmp_path: Path) -> None:+ """A truncated or hand-edited file must not break the switcher."""+ (tmp_path / "accounts.json").write_text("{ not json", encoding="utf-8")+ assert [a.builtin for a in agent_accounts.list_accounts("claude")] == [True]+++def test_a_newer_schema_version_is_ignored_rather_than_half_understood(+ tmp_path: Path,+) -> None:+ """Half-reading a future build's file would spawn against the wrong login."""+ (tmp_path / "accounts.json").write_text(+ json.dumps(+ {+ "version": agent_accounts.SCHEMA_VERSION + 1,+ "accounts": [+ {+ "id": "claude:zzz",+ "platform": "claude",+ "label": "From the future",+ "config_dir": str(tmp_path / "future"),+ }+ ],+ "active": {"claude": "claude:zzz"},+ }+ ),+ encoding="utf-8",+ )+ assert [a.builtin for a in agent_accounts.list_accounts("claude")] == [True]+ assert agent_accounts.active_account("claude").builtin is True+++def test_a_malformed_entry_is_skipped_without_losing_its_neighbours(+ tmp_path: Path,+) -> None:+ good = agent_accounts.create_account("claude", "Good one")+ raw = json.loads((tmp_path / "accounts.json").read_text(encoding="utf-8"))+ raw["accounts"].insert(0, {"id": "broken"}) # no platform, no config_dir+ (tmp_path / "accounts.json").write_text(json.dumps(raw), encoding="utf-8")+ listed = agent_accounts.list_accounts("claude")+ assert [a.id for a in listed] == [agent_accounts.builtin_id("claude"), good.id]+++def test_an_account_needs_a_name() -> None:+ with pytest.raises(AccountError):+ agent_accounts.create_account("claude", " ")+++def test_the_per_platform_cap_is_enforced(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(agent_accounts, "MAX_ACCOUNTS_PER_PLATFORM", 2)+ agent_accounts.create_account("claude", "One")+ agent_accounts.create_account("claude", "Two")+ with pytest.raises(AccountError):+ agent_accounts.create_account("claude", "Three")+++# -------------------------------------------------------------------- switch+++def test_switching_changes_which_account_new_panes_get() -> None:+ second = agent_accounts.create_account("claude", "Second seat")+ assert agent_accounts.active_account("claude").builtin is True+ agent_accounts.set_active("claude", second.id)+ assert agent_accounts.active_account("claude").id == second.id+++def test_switching_one_platform_leaves_the_other_alone() -> None:+ second = agent_accounts.create_account("claude", "Second seat")+ agent_accounts.set_active("claude", second.id)+ assert agent_accounts.active_account("codex").builtin is True+++def test_an_account_of_the_wrong_platform_cannot_be_made_active() -> None:+ codex_account = agent_accounts.create_account("codex", "Codex seat")+ with pytest.raises(AccountError):+ agent_accounts.set_active("claude", codex_account.id)+++def test_a_deleted_active_account_falls_back_to_the_builtin_one() -> None:+ """Never "no account": there would be no directory to spawn against."""+ second = agent_accounts.create_account("claude", "Second seat")+ agent_accounts.set_active("claude", second.id)+ agent_accounts.delete_account(second.id)+ assert agent_accounts.active_account("claude").builtin is True+++def test_a_pinned_id_that_vanished_by_hand_edit_falls_back_too(tmp_path: Path) -> None:+ (tmp_path / "accounts.json").write_text(+ json.dumps(+ {+ "version": agent_accounts.SCHEMA_VERSION,+ "accounts": [],+ "active": {"claude": "claude:ghost"},+ }+ ),+ encoding="utf-8",+ )+ assert agent_accounts.active_account("claude").builtin is True+++def test_forgetting_keeps_the_files_unless_asked() -> None:+ """Forgetting is reversible; erasing a login is not."""+ account = agent_accounts.create_account("claude", "Second seat")+ directory = account.config_dir+ (directory / ".credentials.json").write_text("{}", encoding="utf-8")+ agent_accounts.delete_account(account.id)+ assert directory.is_dir()+++def test_removing_with_files_erases_the_directory() -> None:+ account = agent_accounts.create_account("claude", "Second seat")+ directory = account.config_dir+ agent_accounts.delete_account(account.id, remove_files=True)+ assert not directory.exists()+++def test_renaming_keeps_the_directory_and_the_id() -> None:+ account = agent_accounts.create_account("codex", "Old name")+ renamed = agent_accounts.rename_account(account.id, "New name")+ assert renamed.id == account.id+ assert renamed.config_dir == account.config_dir+ assert agent_accounts.list_accounts("codex")[1].label == "New name"+++# ----------------------------------------------------------------- spawn env+++def test_the_builtin_account_changes_nothing_about_the_environment() -> None:+ """Load-bearing twice over.++ Pinning the default path is not the same as leaving the variable unset: on+ macOS the true default is the Keychain, and an explicit path would send the+ CLI looking for a file that platform never writes. And clearing an override+ the app was STARTED with would move the default account off the login the+ rest of the machine uses.+ """+ assert agent_accounts.env_overrides("claude", agent_accounts.builtin_id("claude")) == {}+ assert agent_accounts.env_overrides("codex", agent_accounts.builtin_id("codex")) == {}+++def test_an_added_account_pins_its_own_directory() -> None:+ account = agent_accounts.create_account("codex", "Second seat")+ assert agent_accounts.env_overrides("codex", account.id) == {+ "CODEX_HOME": str(account.config_dir)+ }+++def test_spawn_env_inherits_rather_than_replaces() -> None:+ """A bare {VAR: dir} would strip PATH and the agent binary would vanish."""+ account = agent_accounts.create_account("claude", "Second seat")+ env = agent_accounts.spawn_env(+ "claude", account.id, base={"PATH": "/usr/bin", "TERM": "xterm"}+ )+ assert env["PATH"] == "/usr/bin"+ assert env["TERM"] == "xterm"+ assert env["CLAUDE_CONFIG_DIR"] == str(account.config_dir)+++def test_spawn_env_for_the_builtin_account_keeps_an_inherited_override() -> None:+ """On a profile-managed host that override IS the session's default login.++ Clearing it would silently move the default account onto ``~/.claude``,+ which on such a host is the stale copy nothing refreshes any more.+ """+ env = agent_accounts.spawn_env(+ "claude",+ agent_accounts.builtin_id("claude"),+ base={"PATH": "/usr/bin", "CLAUDE_CONFIG_DIR": "/managed/profile"},+ )+ assert env["CLAUDE_CONFIG_DIR"] == "/managed/profile"+ assert env["PATH"] == "/usr/bin"+++def test_the_builtin_account_reports_an_inherited_override_as_its_folder(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """What the card shows must be the directory the CLI will really read."""+ monkeypatch.undo() # drop the _native_dir stand-in for this one case+ monkeypatch.setattr(agent_accounts, "_store_path", lambda: tmp_path / "accounts.json")+ monkeypatch.setenv("CODEX_HOME", str(tmp_path / "managed-codex"))+ assert agent_accounts.active_account("codex").config_dir == tmp_path / "managed-codex"+++def test_an_unknown_account_id_resolves_to_the_platform_default() -> None:+ """A stale id in a resumed workspace must reopen the pane, not kill it."""+ assert agent_accounts.config_dir_for("claude", "claude:ghost") == (+ agent_accounts._native_dir("claude")+ )+ assert agent_accounts.resolve("claude:ghost") is None+++def test_an_account_id_of_the_other_platform_is_not_honoured() -> None:+ """A Claude directory means nothing to Codex."""+ claude_account = agent_accounts.create_account("claude", "Claude seat")+ assert agent_accounts.env_overrides("codex", claude_account.id) == {}+++# -------------------------------------------------------------------- status+++def test_an_account_with_no_login_reports_itself_as_not_signed_in() -> None:+ account = agent_accounts.create_account("claude", "Fresh seat")+ snapshot = agent_accounts.describe(account)+ assert snapshot.connected is False+ assert "Not signed in" in snapshot.message+++def test_a_signed_in_claude_account_is_described_from_its_own_directory() -> None:+ """Not from the machine-wide search — that would show a neighbour's login."""+ account = agent_accounts.create_account("claude", "Work seat")+ (account.config_dir / ".credentials.json").write_text(+ json.dumps(+ {+ "claudeAiOauth": {+ "accessToken": "sk-ant-oat-test",+ "subscriptionType": "max",+ # Far future in epoch milliseconds, so this never expires+ # into a flaky test.+ "expiresAt": 99_999_999_999_000,+ }+ }+ ),+ encoding="utf-8",+ )+ (account.config_dir / ".claude.json").write_text(+ json.dumps({"oauthAccount": {"emailAddress": "[email protected]"}}),+ encoding="utf-8",+ )+ snapshot = agent_accounts.describe(account)+ assert snapshot.connected is True+ assert snapshot.mode == "subscription"+ assert snapshot.email == "[email protected]"+ assert snapshot.tier == "max"+++def test_a_described_account_never_carries_a_token() -> None:+ account = agent_accounts.create_account("claude", "Work seat")+ (account.config_dir / ".credentials.json").write_text(+ json.dumps(+ {+ "claudeAiOauth": {+ "accessToken": "sk-ant-oat-supersecret",+ "subscriptionType": "max",+ "expiresAt": 99_999_999_999_000,+ }+ }+ ),+ encoding="utf-8",+ )+ serialized = json.dumps(agent_accounts.describe(account).to_dict())+ assert "supersecret" 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(+ json.dumps(+ {+ "claudeAiOauth": {+ "accessToken": "sk-ant-oat-old",+ "subscriptionType": "max",+ "expiresAt": 1_000, # long dead+ }+ }+ ),+ encoding="utf-8",+ )+ snapshot = agent_accounts.describe(account)+ assert snapshot.connected is False+ assert snapshot.mode == "expired"+ # The advice matters: a stale ACCESS token refreshes itself on the next run.+ assert "refreshes itself" in snapshot.message+++def test_a_signed_in_codex_account_is_described_from_its_own_directory() -> None:+ account = agent_accounts.create_account("codex", "Second plan")+ (account.config_dir / "auth.json").write_text(+ json.dumps({"tokens": {"access_token": "abc", "refresh_token": "def"}}),+ encoding="utf-8",+ )+ snapshot = agent_accounts.describe(account)+ assert snapshot.connected is True+ assert snapshot.mode == "subscription"+++def test_a_codex_account_holding_only_an_api_key_says_so() -> None:+ account = agent_accounts.create_account("codex", "Key seat")+ (account.config_dir / "auth.json").write_text(+ json.dumps({"OPENAI_API_KEY": "sk-test"}), encoding="utf-8"+ )+ snapshot = agent_accounts.describe(account)+ assert snapshot.connected is True+ assert snapshot.mode == "api_key"