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 subscriptions from Settings and per terminal
Ruben Lütke4439a7d748e0
diff --git a/jarvis/ui/web/frontend/src/components/AgentAccountsPanel.test.tsx b/jarvis/ui/web/frontend/src/components/AgentAccountsPanel.test.tsxnew file mode 100644index 0000000000..10093d4d71--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/AgentAccountsPanel.test.tsx@@ -0,0 +1,200 @@+/**+ * Component tests for the subscription switcher.+ *+ * The interesting cases are the ones where a wrong pixel means a wrong plan:+ * which row reads as the one new terminals will use, that a registered account+ * with no login is not dressed up as ready, and that the CLI's own default+ * login can be neither renamed nor removed from here.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";++import { AgentAccountsPanel } from "@/components/AgentAccountsPanel";+import {+ createAgentAccount,+ fetchAgentAccounts,+ loginAgentAccount,+ setActiveAgentAccount,+} from "@/lib/agentAccountsApi";++vi.mock("@/lib/agentAccountsApi", async () => {+ const actual = await vi.importActual<typeof import("@/lib/agentAccountsApi")>(+ "@/lib/agentAccountsApi",+ );+ return {+ ...actual,+ fetchAgentAccounts: vi.fn(),+ createAgentAccount: vi.fn(),+ setActiveAgentAccount: vi.fn(),+ loginAgentAccount: vi.fn(),+ deleteAgentAccount: vi.fn(),+ renameAgentAccount: vi.fn(),+ };+});++function account(over: Partial<Record<string, unknown>> = {}) {+ return {+ id: "claude:default",+ platform: "claude" as const,+ label: "Default Claude Code login",+ config_dir: "/home/u/.claude",+ builtin: true,+ connected: true,+ mode: "subscription",+ message: "Signed in via Claude Max ([email protected]).",+ email: "[email protected]",+ tier: "max",+ ...over,+ };+}++function response(claudeAccounts: unknown[], active = "claude:default") {+ return {+ platforms: [+ { platform: "claude" as const, active_account: active, accounts: claudeAccounts },+ {+ platform: "codex" as const,+ active_account: "codex:default",+ accounts: [+ account({+ id: "codex:default",+ platform: "codex",+ label: "Default Codex login",+ message: "Signed in via ChatGPT.",+ }),+ ],+ },+ ],+ };+}++const secondSeat = account({+ id: "claude:abc123",+ label: "Second seat",+ builtin: false,+ connected: true,+ message: "Signed in via Claude Max ([email protected]).",+ email: "[email protected]",+});++afterEach(cleanup);+beforeEach(() => {+ vi.mocked(fetchAgentAccounts).mockReset();+ vi.mocked(setActiveAgentAccount).mockReset();+ vi.mocked(createAgentAccount).mockReset();+ vi.mocked(loginAgentAccount).mockReset();+});++describe("AgentAccountsPanel", () => {+ it("lists every registered subscription of both CLIs", async () => {+ vi.mocked(fetchAgentAccounts).mockResolvedValue(+ response([account(), secondSeat]) as never,+ );+ render(<AgentAccountsPanel />);+ await waitFor(() => {+ expect(screen.getByText("Second seat")).toBeTruthy();+ });+ expect(screen.getByText("Default Claude Code login")).toBeTruthy();+ expect(screen.getByText("Default Codex login")).toBeTruthy();+ });++ it("marks exactly the account new terminals will use", async () => {+ vi.mocked(fetchAgentAccounts).mockResolvedValue(+ response([account(), secondSeat], "claude:abc123") as never,+ );+ render(<AgentAccountsPanel />);+ // One "in use" chip per platform — never two on one CLI, which would leave+ // the user unable to tell which plan the next terminal spends.+ await waitFor(() => {+ expect(screen.getAllByText("in use").length).toBe(2);+ });+ const active = screen+ .getByText("Second seat")+ .closest("li");+ expect(active?.textContent).toContain("in use");+ });++ it("switches the active account on click", async () => {+ vi.mocked(fetchAgentAccounts).mockResolvedValue(+ response([account(), secondSeat]) as never,+ );+ vi.mocked(setActiveAgentAccount).mockResolvedValue(+ response([account(), secondSeat], "claude:abc123") as never,+ );+ render(<AgentAccountsPanel />);+ await waitFor(() => expect(screen.getByText("Second seat")).toBeTruthy());++ const row = screen.getByText("Second seat").closest("li")!;+ fireEvent.click(row.querySelector("button")!);++ await waitFor(() => {+ expect(setActiveAgentAccount).toHaveBeenCalledWith("claude", "claude:abc123");+ });+ });++ it("shows a registered-but-unsigned account honestly, with a way in", async () => {+ const fresh = account({+ id: "claude:new1",+ label: "Fresh seat",+ builtin: false,+ connected: false,+ mode: "unknown",+ message: "Not signed in yet — use Sign in, and finish the flow in the window that opens.",+ email: null,+ tier: null,+ });+ vi.mocked(fetchAgentAccounts).mockResolvedValue(+ response([account(), fresh]) as never,+ );+ vi.mocked(loginAgentAccount).mockResolvedValue({ message: "Sign-in started" } as never);+ render(<AgentAccountsPanel />);+ await waitFor(() => expect(screen.getByText("Fresh seat")).toBeTruthy());++ const row = screen.getByText("Fresh seat").closest("li")!;+ expect(row.textContent).toContain("Not signed in yet");+ fireEvent.click(screen.getByText("Sign in"));+ await waitFor(() => {+ expect(loginAgentAccount).toHaveBeenCalledWith("claude:new1");+ });+ });++ it("offers no rename or remove on the CLI's own default login", async () => {+ vi.mocked(fetchAgentAccounts).mockResolvedValue(response([account()]) as never);+ render(<AgentAccountsPanel />);+ await waitFor(() =>+ expect(screen.getByText("Default Claude Code login")).toBeTruthy(),+ );+ const row = screen.getByText("Default Claude Code login").closest("li")!;+ expect(row.querySelector('[aria-label="Rename"]')).toBeNull();+ expect(row.querySelector('[aria-label="Remove"]')).toBeNull();+ });++ it("adds a subscription with the name the user typed", async () => {+ vi.mocked(fetchAgentAccounts).mockResolvedValue(response([account()]) as never);+ vi.mocked(createAgentAccount).mockResolvedValue(+ response([account(), secondSeat]) as never,+ );+ render(<AgentAccountsPanel />);+ await waitFor(() =>+ expect(screen.getByText("Default Claude Code login")).toBeTruthy(),+ );++ fireEvent.click(screen.getAllByText("Add account")[0]);+ fireEvent.change(screen.getByPlaceholderText(/Name, e\.g\./i), {+ target: { value: "Second seat" },+ });+ fireEvent.click(screen.getByText("Add"));++ await waitFor(() => {+ expect(createAgentAccount).toHaveBeenCalledWith("claude", "Second seat");+ });+ });++ it("reports a failed load instead of rendering an empty, confident list", async () => {+ vi.mocked(fetchAgentAccounts).mockRejectedValue(new Error("backend is warming up"));+ render(<AgentAccountsPanel />);+ await waitFor(() => {+ expect(screen.getByRole("alert").textContent).toContain("backend is warming up");+ });+ });+});diff --git a/jarvis/ui/web/frontend/src/components/AgentAccountsPanel.tsx b/jarvis/ui/web/frontend/src/components/AgentAccountsPanel.tsxnew file mode 100644index 0000000000..8cb58a99a2--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/AgentAccountsPanel.tsx@@ -0,0 +1,368 @@+/**+ * Several subscriptions per coding CLI, switchable without signing out.+ *+ * Someone holding two Claude Max seats (or two ChatGPT/Codex plans) could only+ * reach one of them: each CLI keeps a single login, so getting to the other+ * meant a logout that threw the first away. Here both are registered side by+ * side and the switch is a click — because an account is nothing but a config+ * directory, and switching decides which directory the next terminal opens+ * against.+ *+ * Two things this panel is careful about, both of which would otherwise mislead:+ *+ * 1. **"Active" means new terminals, not running ones.** A pane keeps the+ * account it was opened with, so switching never moves an agent+ * mid-conversation onto a plan whose history has never seen it. The+ * subtitle says so rather than leaving the user to find out.+ * 2. **A registered account is not a signed-in one.** Adding mints a folder;+ * the sign-in is a separate, deliberate step. An account with no login says+ * exactly that instead of showing a hopeful green row.+ */++import { useCallback, useEffect, useState } from "react";+import { Check, KeyRound, LogIn, Pencil, Plus, Trash2, Users } from "lucide-react";++import { useT } from "@/i18n";+import {+ type AccountPlatform,+ type AgentAccount,+ type AgentAccountsResponse,+ createAgentAccount,+ deleteAgentAccount,+ fetchAgentAccounts,+ groupFor,+ loginAgentAccount,+ renameAgentAccount,+ setActiveAgentAccount,+} from "@/lib/agentAccountsApi";+import { useEventStore } from "@/store/events";+import { cn } from "@/lib/utils";++const PLATFORM_LABEL: Record<AccountPlatform, string> = {+ claude: "Claude Code",+ codex: "Codex",+};++const PLATFORMS: AccountPlatform[] = ["claude", "codex"];++export function AgentAccountsPanel() {+ const t = useT();+ const pushToast = useEventStore((s) => s.pushToast);+ const [data, setData] = useState<AgentAccountsResponse | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [busy, setBusy] = useState<string | null>(null);++ const reload = useCallback(async () => {+ try {+ setData(await fetchAgentAccounts());+ setError(null);+ } catch (e) {+ setError((e as Error).message);+ }+ }, []);++ useEffect(() => {+ void reload();+ }, [reload]);++ /** Run one account action, keeping the list and any error message honest. */+ const run = useCallback(+ async (key: string, action: () => Promise<AgentAccountsResponse | void>) => {+ setBusy(key);+ try {+ const next = await action();+ if (next) setData(next);+ else await reload();+ setError(null);+ } catch (e) {+ pushToast("error", (e as Error).message);+ } finally {+ setBusy(null);+ }+ },+ [pushToast, reload],+ );++ return (+ <div className="space-y-3">+ <div className="flex items-center gap-2 px-1">+ <Users className="h-4 w-4 text-violet-400" />+ <span className="text-xs font-semibold uppercase tracking-wider text-violet-400">+ {t("agent_accounts.title")}+ </span>+ <span className="text-[11px] text-muted-foreground">+ · {t("agent_accounts.hint")}+ </span>+ </div>+ <p className="px-1 text-[11px] leading-relaxed text-muted-foreground">+ {t("agent_accounts.description")}+ </p>++ {error && (+ <p className="px-1 text-[11px] text-amber-600" role="alert">+ {error}+ </p>+ )}++ <div className="grid gap-4 md:grid-cols-2 md:items-start">+ {PLATFORMS.map((platform) => (+ <PlatformCard+ key={platform}+ platform={platform}+ group={groupFor(data, platform)}+ busy={busy}+ run={run}+ />+ ))}+ </div>+ </div>+ );+}++function PlatformCard({+ platform,+ group,+ busy,+ run,+}: {+ platform: AccountPlatform;+ group: ReturnType<typeof groupFor>;+ busy: string | null;+ run: (key: string, action: () => Promise<AgentAccountsResponse | void>) => Promise<void>;+}) {+ const t = useT();+ const [adding, setAdding] = useState(false);+ const [label, setLabel] = useState("");++ const accounts = group?.accounts ?? [];+ const activeId = group?.active_account ?? null;++ async function add() {+ const name = label.trim();+ if (!name) return;+ await run(`add:${platform}`, () => createAgentAccount(platform, name));+ setLabel("");+ setAdding(false);+ }++ return (+ <div className="relative flex flex-col gap-3 rounded-2xl border border-border bg-card/60 p-4 backdrop-blur">+ <span+ aria-hidden="true"+ className="absolute bottom-4 left-0 top-4 w-[3px] rounded-r-full bg-violet-400/60"+ />+ <div className="flex items-center justify-between gap-2">+ <h4 className="text-sm font-semibold">{PLATFORM_LABEL[platform]}</h4>+ <span className="text-[11px] text-muted-foreground">+ {accounts.length} {t("agent_accounts.accounts")}+ </span>+ </div>++ <ul className="space-y-1.5">+ {accounts.map((account) => (+ <AccountRow+ key={account.id}+ account={account}+ active={account.id === activeId}+ busy={busy}+ run={run}+ />+ ))}+ {accounts.length === 0 && (+ <li className="text-[11px] text-muted-foreground">+ {t("agent_accounts.loading")}+ </li>+ )}+ </ul>++ {adding ? (+ <div className="flex items-center gap-2">+ <input+ autoFocus+ value={label}+ onChange={(e) => setLabel(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") void add();+ if (e.key === "Escape") setAdding(false);+ }}+ placeholder={t("agent_accounts.name_placeholder")}+ aria-label={t("agent_accounts.name_placeholder")}+ className="min-w-0 flex-1 rounded-lg border border-border bg-background px-2 py-1.5 text-xs"+ />+ <button+ type="button"+ onClick={() => void add()}+ disabled={!label.trim() || busy === `add:${platform}`}+ className="shrink-0 rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground disabled:opacity-50"+ >+ {t("agent_accounts.add_confirm")}+ </button>+ <button+ type="button"+ onClick={() => setAdding(false)}+ className="shrink-0 rounded-lg border border-border px-3 py-1.5 text-xs"+ >+ {t("agent_accounts.cancel")}+ </button>+ </div>+ ) : (+ <button+ type="button"+ onClick={() => setAdding(true)}+ className="inline-flex w-fit items-center gap-1.5 rounded-lg border border-border px-3 py-1.5 text-xs hover:border-primary/40"+ >+ <Plus className="h-3.5 w-3.5" />+ {t("agent_accounts.add")}+ </button>+ )}+ </div>+ );+}++function AccountRow({+ account,+ active,+ busy,+ run,+}: {+ account: AgentAccount;+ active: boolean;+ busy: string | null;+ run: (key: string, action: () => Promise<AgentAccountsResponse | void>) => Promise<void>;+}) {+ const t = useT();+ const pushToast = useEventStore((s) => s.pushToast);+ const [renaming, setRenaming] = useState(false);+ const [draft, setDraft] = useState(account.label);+ const pending = busy?.endsWith(account.id) ?? false;++ async function activate() {+ if (active) return;+ await run(`active:${account.id}`, () =>+ setActiveAgentAccount(account.platform, account.id),+ );+ }++ async function signIn() {+ await run(`login:${account.id}`, async () => {+ const { message } = await loginAgentAccount(account.id);+ pushToast("info", message);+ });+ }++ async function rename() {+ const name = draft.trim();+ if (!name || name === account.label) {+ setRenaming(false);+ return;+ }+ await run(`rename:${account.id}`, () => renameAgentAccount(account.id, name));+ setRenaming(false);+ }++ return (+ <li+ className={cn(+ "flex flex-col gap-1.5 rounded-xl border px-3 py-2 transition-colors",+ active+ ? "border-primary/55 bg-primary/[0.06]"+ : "border-border/70 hover:border-primary/30",+ )}+ >+ <div className="flex items-center gap-2">+ <button+ type="button"+ onClick={() => void activate()}+ disabled={active || pending}+ aria-pressed={active}+ aria-label={`${t("agent_accounts.use_account")}: ${account.label}`}+ title={t("agent_accounts.use_account")}+ className={cn(+ "grid h-4 w-4 shrink-0 place-items-center rounded-full border",+ active+ ? "border-primary bg-primary text-primary-foreground"+ : "border-muted-foreground/50 hover:border-primary",+ )}+ >+ {active && <Check className="h-2.5 w-2.5" />}+ </button>++ {renaming ? (+ <input+ autoFocus+ value={draft}+ onChange={(e) => setDraft(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") void rename();+ if (e.key === "Escape") setRenaming(false);+ }}+ onBlur={() => void rename()}+ aria-label={t("agent_accounts.rename")}+ className="min-w-0 flex-1 rounded-md border border-border bg-background px-1.5 py-0.5 text-xs"+ />+ ) : (+ <span className="min-w-0 flex-1 truncate text-xs font-medium">+ {account.label}+ </span>+ )}++ {active && (+ <span className="chip-yellow shrink-0">{t("agent_accounts.in_use")}</span>+ )}++ {!account.connected && (+ <button+ type="button"+ onClick={() => void signIn()}+ disabled={pending}+ className="inline-flex shrink-0 items-center gap-1 rounded-lg bg-primary px-2 py-1 text-[11px] font-medium text-primary-foreground disabled:opacity-50"+ >+ <LogIn className="h-3 w-3" />+ {t("agent_accounts.sign_in")}+ </button>+ )}++ {!account.builtin && (+ <>+ <button+ type="button"+ onClick={() => {+ setDraft(account.label);+ setRenaming(true);+ }}+ aria-label={t("agent_accounts.rename")}+ title={t("agent_accounts.rename")}+ className="shrink-0 rounded-md p-1 text-muted-foreground hover:text-foreground"+ >+ <Pencil className="h-3 w-3" />+ </button>+ <button+ type="button"+ onClick={() =>+ void run(`delete:${account.id}`, () => deleteAgentAccount(account.id))+ }+ disabled={pending}+ aria-label={t("agent_accounts.remove")}+ title={t("agent_accounts.remove")}+ className="shrink-0 rounded-md p-1 text-muted-foreground hover:text-destructive"+ >+ <Trash2 className="h-3 w-3" />+ </button>+ </>+ )}+ </div>++ <p+ className={cn(+ "flex items-start gap-1.5 pl-6 text-[11px]",+ account.connected ? "text-muted-foreground" : "text-amber-600",+ )}+ >+ <KeyRound className="mt-0.5 h-3 w-3 shrink-0" />+ <span className="min-w-0 break-words">{account.message}</span>+ </p>+ </li>+ );+}++export default AgentAccountsPanel;diff --git a/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx b/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsxindex e0f3036375..37f53d23b9 100644--- a/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx+++ b/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx@@ -22,6 +22,7 @@ import {} from "@/hooks/useProviders";import { BrainModelSelector } from "@/components/BrainModelSelector";import { ApiKeyForm } from "@/components/ApiKeyForm";+import { AgentAccountsPanel } from "@/components/AgentAccountsPanel";/*** Subagent tier for the API-Keys view.@@ -304,6 +305,13 @@ export function JarvisAgentSection({))}</div></div>++ {/* Below the two columns rather than inside one: this is a second axis.+ The cards above answer "which provider powers the agent"; this answers+ "which of YOUR seats on that provider", and a card holding two Claude+ Max logins does not belong in a column of one-login-per-provider+ cards. */}+ <AgentAccountsPanel /></section>);}diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsxindex 7f44ef13a0..f52cd2b586 100644--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx@@ -36,7 +36,7 @@ import {type SplitDirection,} from "./AgenticTerminal";import type { TerminalAppearance } from "./terminalThemes";-import { paneGrid, workspaceBandCapacityFor } from "./layout";+import { bandCapacityFor, GRID_HORIZONTAL_PADDING_PX, paneGrid } from "./layout";import { PromptPreview } from "./PromptPreview";import {addTerminal,@@ -201,14 +201,33 @@ export function AgenticGrid({// How many panes may share one band is a question about WIDTH, not a constant:// eight side by side leave ~18 characters each and the agent's output becomes// unreadable. So the grid measures itself and wraps once panes would starve.+ /*+ * CONTENT width — the box the grid tracks actually occupy, padding excluded.+ *+ * Which of the two widths this is matters, and getting it wrong was a real+ * defect. `contentRect.width` already excludes this element's 12 px of padding+ * a side, but the value was then passed to `workspaceBandCapacityFor`, which+ * subtracts that same padding AGAIN — so the grid laid itself out 24 px+ * narrower than it is. The wizard preview measures an UNPADDED element, where+ * that helper is right, so the two flipped to a new column count at different+ * window widths and the preview appeared to lie. The seed value made it worse:+ * it came from `clientWidth`, which INCLUDES padding, so the grid could+ * silently re-column itself on the first resize after opening.+ *+ * Now both sides state which width they hold: this one is already content, so+ * it calls `bandCapacityFor` directly; the wizard subtracts the padding the+ * grid will have via `workspaceBandCapacityFor`.+ */const gridRef = useRef<HTMLDivElement | null>(null);const [gridWidth, setGridWidth] = useState(0);useEffect(() => {const node = gridRef.current;if (!node) return;- setGridWidth(node.clientWidth);+ setGridWidth(Math.max(0, node.clientWidth - GRID_HORIZONTAL_PADDING_PX));const observer = new ResizeObserver((entries) => {- const width = entries[0]?.contentRect.width ?? node.clientWidth;+ const width =+ entries[0]?.contentRect.width ??+ Math.max(0, node.clientWidth - GRID_HORIZONTAL_PADDING_PX);// Round to a step so a one-pixel drift cannot churn the layout (and with// it every pane's resize) on window animations.setGridWidth(Math.round(width / 16) * 16);@@ -261,7 +280,7 @@ export function AgenticGrid({? COMPOSER_COLLAPSED_PX: requestedComposer;- const perBand = useMemo(() => workspaceBandCapacityFor(gridWidth), [gridWidth]);+ const perBand = useMemo(() => bandCapacityFor(gridWidth), [gridWidth]);const grid = useMemo(() => paneGrid(session.terminals, perBand),[session.terminals, perBand],@@ -529,6 +548,15 @@ export function AgenticGrid({name={term.name}workspaceId={session.id}displayName={term.display_name}+ // Only the panes that are NOT on the default login carry a+ // badge. Labelling every pane "Default Claude Code login" would+ // be noise for the many; labelling the odd one out is the whole+ // signal for the few running two seats at once.+ accountLabel={+ term.account && !term.account.endsWith(":default")+ ? term.account_label+ : null+ }appearance={appearance}fontSize={fontSize}focused={target === term.name}diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsxindex 085f3f793a..cdae7b0eb7 100644--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx@@ -103,6 +103,12 @@ interface AgenticTerminalProps {workspaceId?: string;/** Agent label shown in the pane header ("Claude Code"). */displayName: string;+ /**+ * Which subscription this pane runs on ("Work seat"), when that is worth+ * saying. Undefined for everyone with a single login — the header must not+ * grow a badge that answers a question the user does not have.+ */+ accountLabel?: string | null;appearance: TerminalAppearance;fontSize: number;/** Highlight this pane as the prompt target. */@@ -148,6 +154,7 @@ export function AgenticTerminal({name,workspaceId,displayName,+ accountLabel,appearance,fontSize,focused = false,@@ -535,6 +542,7 @@ export function AgenticTerminal({onRestart={onRestart}name={name}displayName={displayName}+ accountLabel={accountLabel}appearance={appearance}focused={focused}maximized={maximized}@@ -571,6 +579,7 @@ export function AgenticTerminal({function PaneHeader({name,displayName,+ accountLabel,appearance,focused,maximized,@@ -584,6 +593,7 @@ function PaneHeader({}: {name: string;displayName: string;+ accountLabel?: string | null;appearance: TerminalAppearance;focused: boolean;maximized: boolean;@@ -638,6 +648,23 @@ function PaneHeader({>{displayName}</span>+ {/* Which of several subscriptions this pane is spending. Only rendered+ when the user actually has more than one, so the header stays quiet+ for everybody else — but with two seats open side by side, knowing+ which pane bills which plan is the whole point. */}+ {accountLabel && (+ <span+ className="truncate rounded-full px-1.5 text-[10px] tracking-wide"+ style={{+ color: light ? "#6b6b73" : "#9a9aa5",+ backgroundColor: light ? "#00000010" : "#ffffff12",+ }}+ title={`Running on ${accountLabel}`}+ data-testid={`pane-account-${name}`}+ >+ {accountLabel}+ </span>+ )}</div>{/* Pane actions. Kept quiet until the pane is hovered or focused, so adiff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 5c2df94e6d..5426512855 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -3206,6 +3206,22 @@"paste_unavailable": "Zwischenablage konnte nicht gelesen werden.","paste_failed": "Hier kann nicht eingefügt werden."},+ "agent_accounts": {+ "title": "Deine Abos",+ "hint": "mehrere Logins pro CLI",+ "description": "Du hast mehr als ein Abo für dasselbe Coding-CLI? Trag hier jedes ein und wechsle, ohne dich abzumelden — jeder Login bleibt parallel gültig. Der Haken markiert das Konto, mit dem NEUE Terminals starten; bereits laufende Terminals behalten das Konto, mit dem sie gestartet wurden.",+ "accounts": "eingetragen",+ "loading": "Wird geladen…",+ "add": "Konto hinzufügen",+ "add_confirm": "Hinzufügen",+ "cancel": "Abbrechen",+ "name_placeholder": "Name, z. B. Arbeitskonto",+ "use_account": "Für neue Terminals verwenden",+ "in_use": "aktiv",+ "sign_in": "Anmelden",+ "rename": "Umbenennen",+ "remove": "Entfernen"+ },"agent_accounts": {"title": "Deine Abos","hint": "mehrere Logins pro CLI",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 892a298a7e..d33b624c6d 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -3207,6 +3207,22 @@"paste_unavailable": "Could not read the clipboard.","paste_failed": "Cannot paste here."},+ "agent_accounts": {+ "title": "Your subscriptions",+ "hint": "several logins per CLI",+ "description": "Hold more than one plan for the same coding CLI? Register each one here and switch without signing out — every login stays valid side by side. The tick marks the account NEW terminals open on; terminals that are already running keep the account they were started with.",+ "accounts": "registered",+ "loading": "Loading…",+ "add": "Add account",+ "add_confirm": "Add",+ "cancel": "Cancel",+ "name_placeholder": "Name, e.g. Work seat",+ "use_account": "Use for new terminals",+ "in_use": "in use",+ "sign_in": "Sign in",+ "rename": "Rename",+ "remove": "Remove"+ },"agent_accounts": {"title": "Your subscriptions","hint": "several logins per CLI",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex b8831473ce..8ce5e5cd3a 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -3206,6 +3206,22 @@"paste_unavailable": "No se pudo leer el portapapeles.","paste_failed": "Aquí no se puede pegar."},+ "agent_accounts": {+ "title": "Tus suscripciones",+ "hint": "varios inicios de sesión por CLI",+ "description": "¿Tienes más de un plan para la misma CLI de programación? Registra cada uno aquí y cambia sin cerrar sesión: todos los accesos siguen siendo válidos a la vez. La marca indica la cuenta con la que se abren los terminales NUEVOS; los terminales en curso conservan la cuenta con la que se iniciaron.",+ "accounts": "registradas",+ "loading": "Cargando…",+ "add": "Añadir cuenta",+ "add_confirm": "Añadir",+ "cancel": "Cancelar",+ "name_placeholder": "Nombre, p. ej. Cuenta de trabajo",+ "use_account": "Usar para terminales nuevos",+ "in_use": "en uso",+ "sign_in": "Iniciar sesión",+ "rename": "Renombrar",+ "remove": "Eliminar"+ },"agent_accounts": {"title": "Tus suscripciones","hint": "varios inicios de sesión por CLI",diff --git a/jarvis/ui/web/frontend/src/lib/agentAccountsApi.ts b/jarvis/ui/web/frontend/src/lib/agentAccountsApi.tsnew file mode 100644index 0000000000..d1e3c25b3a--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/agentAccountsApi.ts@@ -0,0 +1,129 @@+// REST client for switching between several subscriptions of one coding CLI.+// Plain same-origin fetch (mirrors agenticIdeApi/workspaceApi), `no-store`+// everywhere because WebView2 will happily serve a stale account list — and a+// stale one here is worse than elsewhere: it would show the wrong plan as the+// active one right after the user switched.++/** Which coding CLI a subscription belongs to. */+export type AccountPlatform = "claude" | "codex";++/**+ * One registered subscription.+ *+ * `builtin` marks the CLI's own default login. It is always present, cannot be+ * renamed or removed, and is what a user who never opens this feature uses —+ * so the UI must never offer those actions on it.+ */+export interface AgentAccount {+ id: string;+ platform: AccountPlatform;+ label: string;+ config_dir: string;+ builtin: boolean;+ connected: boolean;+ /** "subscription" | "api_key" | "expired" | "unknown" */+ mode: string;+ message: string;+ email: string | null;+ tier: string | null;+}++export interface AccountPlatformGroup {+ platform: AccountPlatform;+ active_account: string;+ accounts: AgentAccount[];+}++export interface AgentAccountsResponse {+ platforms: AccountPlatformGroup[];+}++async function detail(res: Response): Promise<string> {+ try {+ const body = (await res.json()) as { detail?: string };+ if (body?.detail) return body.detail;+ } catch {+ /* fall through */+ }+ return `request failed: ${res.status}`;+}++async function send<T>(url: string, init: RequestInit): Promise<T> {+ const res = await fetch(url, init);+ if (!res.ok) throw new Error(await detail(res));+ return (await res.json()) as T;+}++export async function fetchAgentAccounts(): Promise<AgentAccountsResponse> {+ const res = await fetch("/api/agent-accounts", { cache: "no-store" });+ if (!res.ok) throw new Error(await detail(res));+ return (await res.json()) as AgentAccountsResponse;+}++export function createAgentAccount(+ platform: AccountPlatform,+ label: string,+): Promise<AgentAccountsResponse> {+ return send<AgentAccountsResponse>("/api/agent-accounts", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ platform, label }),+ });+}++/** Point NEW terminals of one CLI at another subscription. Running panes stay put. */+export function setActiveAgentAccount(+ platform: AccountPlatform,+ accountId: string,+): Promise<AgentAccountsResponse> {+ return send<AgentAccountsResponse>("/api/agent-accounts/active", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ platform, account_id: accountId }),+ });+}++/** Start the CLI's own sign-in, pointed at this account's own folder. */+export function loginAgentAccount(accountId: string): Promise<{ message: string }> {+ return send<{ message: string }>(+ `/api/agent-accounts/${encodeURIComponent(accountId)}/login`,+ { method: "POST" },+ );+}++export function renameAgentAccount(+ accountId: string,+ label: string,+): Promise<AgentAccountsResponse> {+ return send<AgentAccountsResponse>(+ `/api/agent-accounts/${encodeURIComponent(accountId)}`,+ {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ label }),+ },+ );+}++/**+ * Forget a subscription. `removeFiles` also erases its stored login, which is+ * why it defaults to false: forgetting is reversible, erasing is not.+ */+export function deleteAgentAccount(+ accountId: string,+ removeFiles = false,+): Promise<AgentAccountsResponse> {+ const qs = removeFiles ? "?remove_files=true" : "";+ return send<AgentAccountsResponse>(+ `/api/agent-accounts/${encodeURIComponent(accountId)}${qs}`,+ { method: "DELETE" },+ );+}++/** The group for one platform, or undefined while the list is still loading. */+export function groupFor(+ data: AgentAccountsResponse | null,+ platform: AccountPlatform,+): AccountPlatformGroup | undefined {+ return data?.platforms.find((group) => group.platform === platform);+}diff --git a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.tsindex af51e83855..0ea7966d70 100644--- a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts+++ b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts@@ -95,6 +95,10 @@ export interface TerminalState {prompts_sent: number;last_prompt: string;lines_captured: number;+ /** Which subscription this pane runs on (see agentAccountsApi). */+ account?: string | null;+ /** Its display name, so the pane header can show it without a second lookup. */+ account_label?: string | null;}export interface SessionState {@@ -182,6 +186,8 @@ export interface ResumeResult {export interface TerminalPlan {agent: string;name?: string;+ /** Which registered subscription to open on; omitted uses the active one. */+ account?: string;}async function detail(res: Response): Promise<string> {@@ -411,6 +417,8 @@ export async function addTerminal(payload: {direction?: "right" | "down";agent?: string;name?: string;+ /** Subscription for the new pane; omitted inherits the anchor's. */+ account?: string;}): Promise<SessionState> {const res = await fetch("/api/agentic-ide/terminals", {method: "POST",diff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsxindex 19485b6a63..4120b6c317 100644--- a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx@@ -26,21 +26,23 @@ import {FolderOpen,Loader2,Mic,- Minus,- Plus,Rocket,Sparkles,Terminal,+ Users,} from "lucide-react";import { ViewHeader } from "@/views/ChatsView";import { useEventStore } from "@/store/events";import { cn } from "@/lib/utils";import { useT } from "@/i18n";import { AgenticGrid } from "@/components/agentic/AgenticGrid";+import { TerminalCountStep } from "@/components/agentic/TerminalCountStep";import {- paneColumns,- workspaceBandCapacityFor,-} from "@/components/agentic/layout";+ type AgentAccount,+ type AgentAccountsResponse,+ fetchAgentAccounts,+ groupFor,+} from "@/lib/agentAccountsApi";import { FolderPicker } from "@/components/agentic/FolderPicker";import { ResumeCard } from "@/components/agentic/ResumeCard";import { WorkspaceBar } from "@/components/agentic/WorkspaceBar";@@ -68,12 +70,15 @@ type Step = 0 | 1 | 2 | 3;interface PlannedTerminal {agent: string;name: string;+ /**+ * Which subscription of `agent` this pane opens on, or undefined for the+ * active one. Per pane rather than per workspace on purpose: that is what+ * lets two seats of the same plan run side by side in one folder — which is+ * the entire reason for holding two.+ */+ account?: string;}-// Common layouts stay one click away. Less common counts belong in the custom-// selector instead of widening this row with a card for every possible value.-const COUNT_CHOICES = [1, 2, 3, 4, 6, 8] as const;-/*** Terminal plan for ``count`` panes, preserving whatever the user already chose* for the panes that still exist.@@ -129,8 +134,11 @@ export function AgenticIdeView() {const [step, setStep] = useState<Step>(0);const [folder, setFolder] = useState<string | null>(null);const [count, setCount] = useState(2);- const [customCountSelected, setCustomCountSelected] = useState(false);const [planned, setPlanned] = useState<PlannedTerminal[]>([]);+ // The registered subscriptions per CLI. Only ever used to OFFER a choice, so+ // a failed load costs the picker, never the wizard: with none loaded every+ // pane simply opens on the active account, exactly as before.+ const [accounts, setAccounts] = useState<AgentAccountsResponse | null>(null);// The workspace that was open when the window last closed, if it can come// back. Null both when there is nothing to offer and after the user has// answered the offer either way.@@ -181,6 +189,24 @@ export function AgenticIdeView() {void refresh();}, [refresh]);+ // Loaded once, and deliberately NOT part of `refresh`: the wizard must open+ // even when this fails. Without it every pane opens on the active account,+ // which is exactly what happened before the switcher existed.+ useEffect(() => {+ fetchAgentAccounts()+ .then(setAccounts)+ .catch(() => setAccounts(null));+ }, []);++ /** The registered subscriptions of one CLI, for the wizard's per-pane picker. */+ const accountsFor = useCallback(+ (platform: string): AgentAccount[] =>+ platform === "claude" || platform === "codex"+ ? groupFor(accounts, platform)?.accounts ?? []+ : [],+ [accounts],+ );+/** Panes can appear without this view asking for them.*@@ -216,7 +242,7 @@ export function AgenticIdeView() {/** How wide the workspace will be — measured here, in the wizard, because the- * preview dots must promise the arrangement the grid will actually produce.+ * preview must show the arrangement the grid will actually produce.** The grid decides its band width from its own width (a pane below* MIN_PANE_WIDTH_PX is unreadable), so a preview computing columns from the@@ -224,6 +250,10 @@ export function AgenticIdeView() {* "12 → 6 above, 6 below" while the grid, in the same window, produced three* columns and four rows. The wizard shell sits in the same slot the grid will* occupy, so measuring it here answers the same question.+ *+ * This is the width the preview then NAMES rather than silently assumes — see+ * TerminalCountStep. Measuring it right only makes the preview correct for the+ * window it was shown in; saying so is what makes it correct after a maximise.*/const shellRef = useRef<HTMLDivElement | null>(null);const [shellWidth, setShellWidth] = useState(0);@@ -240,13 +270,6 @@ export function AgenticIdeView() {return () => observer.disconnect();}, [session]);- // The grid pads itself by 12 px on each side; without that the preview would- // promise one column more than fits at the boundary.- const previewPerBand = useMemo(- () => workspaceBandCapacityFor(shellWidth),- [shellWidth],- );-useEffect(() => {if (!session || session.focus_mode || optedOutRef.current) return;let cancelled = false;@@ -287,9 +310,8 @@ export function AgenticIdeView() {[agents],);- const chooseCount = (n: number, custom = false) => {+ const chooseCount = (n: number) => {const next = Math.max(1, Math.min(maxTerminals, Math.trunc(n)));- setCustomCountSelected(custom);setCount(next);setPlanned((prev) => buildPlan(next, prev, defaultAgent, suggested));};@@ -301,7 +323,6 @@ export function AgenticIdeView() {}) => {const total = Math.max(1, Math.min(recent.terminals, maxTerminals));setCount(total);- setCustomCountSelected(!COUNT_CHOICES.some((choice) => choice === total));const entries = Object.entries(recent.agents ?? {}).filter(([, n]) => n > 0);if (entries.length === 0) {setPlanned(buildPlan(total, [], defaultAgent, suggested));@@ -630,109 +651,15 @@ export function AgenticIdeView() {{step === 1 && (<Sectiontitle="How many terminals?"- hint="Each terminal runs its own agent. The dots show how they will sit — side by side, wrapping onto a second line once there are too many to stay readable."+ hint="Each terminal runs its own agent. Below is the workspace you are about to open — the panes sit exactly like that.">- <div className="grid grid-cols-3 gap-3 sm:grid-cols-6">- {COUNT_CHOICES.filter((n) => n <= maxTerminals).map((n) => (- <button- key={n}- type="button"- aria-pressed={!customCountSelected && count === n}- onClick={() => chooseCount(n)}- className={cn(- "flex aspect-square flex-col items-center justify-center gap-2 rounded-xl border p-3 transition-colors",- !customCountSelected && count === n- ? "border-primary/50 bg-primary/5"- : "border-border bg-card/60 hover:border-primary/30",- )}- >- <DotGrid- n={n}- perBand={previewPerBand}- active={!customCountSelected && count === n}- />- <span- className={cn(- "text-sm font-semibold",- !customCountSelected && count === n- ? "text-primary"- : "text-foreground",- )}- >- {n}- </span>- </button>- ))}- </div>-- <div- className={cn(- "flex flex-wrap items-center gap-4 rounded-xl border bg-card/60 p-4 transition-colors",- customCountSelected- ? "border-primary/50 bg-primary/5"- : "border-border hover:border-primary/30",- )}- >- <button- type="button"- aria-pressed={customCountSelected}- onClick={() => chooseCount(count, true)}- className="flex min-w-0 flex-1 items-center gap-3 text-left"- >- <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg border border-border bg-background/60">- <DotGrid- n={count}- perBand={previewPerBand}- active={customCountSelected}- testId="custom-terminal-preview"- />- </span>- <span className="min-w-0">- <span className="block text-sm font-semibold">Custom Terminals</span>- <span className="block text-xs text-muted-foreground">- Choose any number from 1 to {maxTerminals}.- </span>- </span>- </button>-- <div className="flex shrink-0 items-center gap-1 rounded-lg border border-border bg-background/60 p-1">- <button- type="button"- aria-label="Use one fewer terminal"- disabled={count <= 1}- onClick={() => chooseCount(count - 1, true)}- className="flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-40"- >- <Minus className="h-4 w-4" />- </button>- <input- type="number"- min={1}- max={maxTerminals}- value={count}- aria-label="Custom terminal count"- onFocus={() => chooseCount(count, true)}- onChange={(event) =>- chooseCount(- Number.isFinite(event.currentTarget.valueAsNumber)- ? event.currentTarget.valueAsNumber- : 1,- true,- )- }- className="h-8 w-14 rounded-md border border-border bg-background text-center font-mono text-sm font-semibold outline-none focus:border-primary/60"- />- <button- type="button"- aria-label="Use one more terminal"- disabled={count >= maxTerminals}- onClick={() => chooseCount(count + 1, true)}- className="flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-40"- >- <Plus className="h-4 w-4" />- </button>- </div>- </div>+ <TerminalCountStep+ count={count}+ max={maxTerminals}+ names={suggested}+ workspaceWidthPx={shellWidth}+ onChange={chooseCount}+ /></Section>)}@@ -772,13 +699,27 @@ export function AgenticIdeView() {onSelect={() =>setPlanned((prev) =>prev.map((p, i) =>- i === index ? { ...p, agent: agent.name } : p,+ i === index+ ? // The account belongs to the OLD CLI — an id+ // from one CLI means nothing to the other.+ { ...p, agent: agent.name, account: undefined }+ : p,),)}/>))}</div>+ <AccountChoice+ platform={pane.agent}+ accounts={accountsFor(pane.agent)}+ value={pane.account}+ onSelect={(id) =>+ setPlanned((prev) =>+ prev.map((p, i) => (i === index ? { ...p, account: id } : p)),+ )+ }+ /></li>))}</ul>@@ -1050,46 +991,44 @@ function AgentChoice({}/**- * The arrangement ``n`` terminals will actually open in.+ * Which of several subscriptions of one CLI this pane opens on.*- * Both numbers behind this come from the grid itself: `perBand` is what fits in- * the measured width, and `paneColumns` is the function the grid lays itself out- * with. The preview used to have its own formula (three per line), so choosing 4- * previewed 3 above and 1 below and then opened 4 side by side; then it dropped- * the width and promised 6 + 6 where a narrow window gave three columns and four- * rows. A preview is only worth showing while it cannot disagree with the real- * thing, and that means sharing every input, not just the function.+ * Renders NOTHING when the user has only the one login, which is almost+ * everybody — the wizard must not grow a control that answers a question the+ * user does not have. It appears the moment a second seat is registered, and+ * then it is per pane, so one folder can hold panes on both plans at once.*/-function DotGrid({- n,- perBand,- active,- testId,+function AccountChoice({+ platform,+ accounts,+ value,+ onSelect,}: {- n: number;- perBand: number;- active: boolean;- testId?: string;+ platform: string;+ accounts: AgentAccount[];+ value: string | undefined;+ onSelect: (id: string | undefined) => void;}) {- const cols = Math.max(1, paneColumns(n, perBand));- const tight = cols > 6;+ if (accounts.length < 2) return null;return (- <div- data-testid={testId}- className={cn("grid", tight ? "gap-0.5" : "gap-1")}- style={{ gridTemplateColumns: `repeat(${cols}, minmax(0, 1fr))` }}- >- {Array.from({ length: n }).map((_, i) => (- <span- key={i}- className={cn(- "rounded-[3px]",- tight ? "h-1.5 w-1.5" : "h-2 w-2",- active ? "bg-primary" : "bg-muted-foreground/40",- )}- />- ))}- </div>+ <label className="flex items-center gap-1.5 text-xs text-muted-foreground">+ <Users className="h-3.5 w-3.5 shrink-0" />+ <span className="sr-only">Subscription for this terminal</span>+ <select+ value={value ?? ""}+ onChange={(e) => onSelect(e.target.value || undefined)}+ aria-label={`Subscription for the ${platform} terminal`}+ className="rounded-lg border border-border bg-background/60 px-2 py-1.5 text-xs outline-none focus:border-primary/50"+ >+ <option value="">Active account</option>+ {accounts.map((account) => (+ <option key={account.id} value={account.id}>+ {account.label}+ {account.connected ? "" : " (not signed in)"}+ </option>+ ))}+ </select>+ </label>);}diff --git a/tests/unit/agentic_ide/test_account_spawn.py b/tests/unit/agentic_ide/test_account_spawn.pyindex 56dff56d5c..8cd606800f 100644--- a/tests/unit/agentic_ide/test_account_spawn.py+++ b/tests/unit/agentic_ide/test_account_spawn.py@@ -209,25 +209,22 @@ async def test_a_pane_looks_for_its_conversation_in_its_own_account(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:+async def test_a_remembered_pane_carries_its_account_through_the_store() -> None:+ """Deliberately at the pane level, not the snapshot wrapper's.++ What has to survive is the pane's account: the wrapper around it has+ changed shape before and will again, while "this pane ran on that seat" is+ the fact the reopen depends on.+ """from jarvis.agentic_ide import resume_storesecond = 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- )- ],+ pane = resume_store.SnapshotTerminal(+ key="alex", name="Alex", agent="codex", account=second.id)- restored = resume_store.Snapshot.from_dict(snapshot.to_dict())+ restored = resume_store.SnapshotTerminal.from_dict(pane.to_dict())assert restored is not None- assert restored.terminals[0].account == second.id+ assert restored.account == second.idasync def test_an_older_snapshot_without_an_account_still_reopens() -> None: