Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(accounts): per-account usage (scoped keychain service)
enes71beaa7606f7
diff --git a/src/main/claude-accounts-core.test.ts b/src/main/claude-accounts-core.test.tsindex 62ba5184c..c1b7d2368 100644--- a/src/main/claude-accounts-core.test.ts+++ b/src/main/claude-accounts-core.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'import {accountConfigDir,claudeKeychainService,+ usageCredsPaths,AUTH_ENV_STRIP,accountTmuxEnvArgs,parseLoginCapture,@@ -35,6 +36,27 @@ describe('claudeKeychainService', () => {})})+describe('usageCredsPaths', () => {+ it('without a config dir uses the legacy unscoped services + ~/.claude paths', () => {+ expect(usageCredsPaths('/Users/x')).toEqual({+ services: ['Claude Code-credentials', 'claudeAiOauth'],+ credsFile: '/Users/x/.claude/.credentials.json',+ identityFile: '/Users/x/.claude.json'+ })+ })+ it('with a config dir puts the scoped service first + reads that dir', () => {+ const configDir = '/ud/claude-accounts/a1'+ const p = usageCredsPaths('/Users/x', configDir)+ expect(p.services).toEqual([+ claudeKeychainService(configDir),+ 'Claude Code-credentials',+ 'claudeAiOauth'+ ])+ expect(p.credsFile).toBe('/ud/claude-accounts/a1/.credentials.json')+ expect(p.identityFile).toBe('/ud/claude-accounts/a1/.claude.json')+ })+})+describe('AUTH_ENV_STRIP', () => {it('covers the env vars that would shadow the account OAuth login', () => {expect(AUTH_ENV_STRIP).toEqual(diff --git a/src/main/claude-accounts-core.ts b/src/main/claude-accounts-core.tsindex 39369b0e5..a5df4a370 100644--- a/src/main/claude-accounts-core.ts+++ b/src/main/claude-accounts-core.ts@@ -37,6 +37,32 @@ export function claudeKeychainService(configDir: string): string {return `Claude Code-credentials-${suffix}`}+/**+ * Where the usage indicator looks for a Claude OAuth token + identity, per account. With a+ * `configDir` (managed account) the scoped Keychain service comes first — Claude Code ≥ 2.1+ * writes there — with the legacy unscoped services as fallback for older CLIs; the file ++ * identity live under that config dir. Without a `configDir` (system account) it's exactly the+ * legacy layout: unscoped services + `~/.claude`. Pure so it's unit-tested; the impure keychain+ * / fs reads live in claude-usage.ts.+ */+export function usageCredsPaths(+ homeDir: string,+ configDir?: string+): { services: string[]; credsFile: string; identityFile: string } {+ if (configDir) {+ return {+ services: [claudeKeychainService(configDir), 'Claude Code-credentials', 'claudeAiOauth'],+ credsFile: path.join(configDir, '.credentials.json'),+ identityFile: path.join(configDir, '.claude.json')+ }+ }+ return {+ services: ['Claude Code-credentials', 'claudeAiOauth'],+ credsFile: path.join(homeDir, '.claude', '.credentials.json'),+ identityFile: path.join(homeDir, '.claude.json')+ }+}+/** Env vars that would silently shadow the selected account's OAuth login. Stripped at spawn. */export const AUTH_ENV_STRIP = ['ANTHROPIC_API_KEY',diff --git a/src/main/claude-usage.ts b/src/main/claude-usage.tsindex 0b91675b3..f28a1119f 100644--- a/src/main/claude-usage.ts+++ b/src/main/claude-usage.ts@@ -9,6 +9,8 @@ import { promisify } from 'util'import { ipcMain, type BrowserWindow } from 'electron'import { IPC } from '../shared/ipc'import type { ClaudeUsage, ClaudeUsageWindow } from '../shared/types'+import { usageCredsPaths } from './claude-accounts-core'+import { claudeConfigDirFor } from './claude-accounts'const execFileP = promisify(execFile)@@ -44,12 +46,19 @@ export async function resolveClaudeAccessToken(): Promise<string | null> {return (await resolveCreds()).accessToken}-/** macOS Keychain → ~/.claude/.credentials.json → email backfill from ~/.claude.json. */-async function resolveCreds(): Promise<OAuthCreds> {+/**+ * macOS Keychain → {config}/.credentials.json → email backfill from {config}/.claude.json.+ * With an `accountId` the config dir is the managed account's isolated dir (scoped Keychain+ * service first); without, it's exactly the system default (`~/.claude`, unscoped services).+ */+async function resolveCreds(accountId?: string): Promise<OAuthCreds> {+ const configDir = accountId ? claudeConfigDirFor(accountId) : undefined+ const { services, credsFile, identityFile } = usageCredsPaths(os.homedir(), configDir)+let creds: OAuthCreds = { accessToken: null, email: null }if (process.platform === 'darwin') {- for (const service of ['Claude Code-credentials', 'claudeAiOauth']) {+ for (const service of services) {try {const { stdout } = await execFileP('security', ['find-generic-password',@@ -70,7 +79,7 @@ async function resolveCreds(): Promise<OAuthCreds> {if (!creds.accessToken) {try {- const raw = await fs.readFile(path.join(os.homedir(), '.claude', '.credentials.json'), 'utf-8')+ const raw = await fs.readFile(credsFile, 'utf-8')creds = parseCreds(raw)} catch {// no file — leave creds empty@@ -79,7 +88,7 @@ async function resolveCreds(): Promise<OAuthCreds> {if (creds.accessToken && !creds.email) {try {- const raw = await fs.readFile(path.join(os.homedir(), '.claude.json'), 'utf-8')+ const raw = await fs.readFile(identityFile, 'utf-8')const j = JSON.parse(raw) as Record<string, any>const acct = j.oauthAccount as Record<string, any> | undefinedconst email =@@ -102,9 +111,9 @@ function mapWindow(raw: any): ClaudeUsageWindow | null {return { leftPercent, resetsAt }}-async function fetchUsage(): Promise<ClaudeUsage> {+async function fetchUsage(accountId?: string): Promise<ClaudeUsage> {const now = Date.now()- const { accessToken, email } = await resolveCreds()+ const { accessToken, email } = await resolveCreds(accountId)if (!accessToken) {return { session: null, weekly: null, email, updatedAt: now, status: 'unavailable' }}@@ -135,33 +144,42 @@ async function fetchUsage(): Promise<ClaudeUsage> {}export function initClaudeUsage(win: BrowserWindow): void {- let last: ClaudeUsage | null = null- let lastFetchAt = 0- let inFlight: Promise<ClaudeUsage> | null = null-- const push = (u: ClaudeUsage): void => {- last = u- lastFetchAt = u.updatedAt- if (!win.isDestroyed()) win.webContents.send(IPC.usageUpdate, u)+ // Per-account caches keyed by `accountId ?? ''`. The empty key is the system account, the+ // only one that's proactively polled + pushed; managed-account rows fetch on demand from the+ // popover.+ const last = new Map<string, ClaudeUsage>()+ const lastFetchAt = new Map<string, number>()+ const inFlight = new Map<string, Promise<ClaudeUsage>>()++ const push = (key: string, u: ClaudeUsage): void => {+ last.set(key, u)+ lastFetchAt.set(key, u.updatedAt)+ // Only the system account feeds the push channel — the collapsed chip tracks it.+ if (key === '' && !win.isDestroyed()) win.webContents.send(IPC.usageUpdate, u)}- const run = async (): Promise<ClaudeUsage> => {- if (inFlight) return inFlight- inFlight = fetchUsage()+ const run = async (accountId?: string): Promise<ClaudeUsage> => {+ const key = accountId ?? ''+ const pending = inFlight.get(key)+ if (pending) return pending+ const p = fetchUsage(accountId)+ inFlight.set(key, p)try {- const u = await inFlight- push(u)+ const u = await p+ push(key, u)return u} finally {- inFlight = null+ inFlight.delete(key)}}- ipcMain.handle(IPC.usageFetch, async () => {- if (last && Date.now() - lastFetchAt < FOCUS_DEBOUNCE_MS) return last- return run()+ ipcMain.handle(IPC.usageFetch, async (_e, accountId?: string) => {+ const key = accountId ?? ''+ const cached = last.get(key)+ if (cached && Date.now() - (lastFetchAt.get(key) ?? 0) < FOCUS_DEBOUNCE_MS) return cached+ return run(accountId)})- ipcMain.handle(IPC.usageRefresh, () => run())+ ipcMain.handle(IPC.usageRefresh, (_e, accountId?: string) => run(accountId))void run()const interval = setInterval(() => {@@ -169,7 +187,7 @@ export function initClaudeUsage(win: BrowserWindow): void {}, POLL_MS)const onFocus = (): void => {- if (Date.now() - lastFetchAt >= FOCUS_DEBOUNCE_MS) void run()+ if (Date.now() - (lastFetchAt.get('') ?? 0) >= FOCUS_DEBOUNCE_MS) void run()}win.on('focus', onFocus)win.on('closed', () => clearInterval(interval))diff --git a/src/preload/index.ts b/src/preload/index.tsindex 6dfc13bfb..4d5f4f374 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -238,8 +238,8 @@ const api: NodeTerminalApi = {fetch: () => ipcRenderer.invoke(IPC.announcementsFetch)},usage: {- fetch: () => ipcRenderer.invoke(IPC.usageFetch),- refresh: () => ipcRenderer.invoke(IPC.usageRefresh),+ fetch: (accountId?: string) => ipcRenderer.invoke(IPC.usageFetch, accountId),+ refresh: (accountId?: string) => ipcRenderer.invoke(IPC.usageRefresh, accountId),onUpdate: (listener) => {const handler = (_e: unknown, payload: Parameters<typeof listener>[0]) => listener(payload)ipcRenderer.on(IPC.usageUpdate, handler)diff --git a/src/renderer/components/UsageIndicator.tsx b/src/renderer/components/UsageIndicator.tsxindex 5c9d1dde5..0f0fb3fe8 100644--- a/src/renderer/components/UsageIndicator.tsx+++ b/src/renderer/components/UsageIndicator.tsx@@ -1,5 +1,6 @@-import { useEffect, useRef, useState } from 'react'+import { useEffect, useMemo, useRef, useState } from 'react'import type { ClaudeUsage, ClaudeUsageWindow } from '@shared/types'+import { useSettings } from '../state/settings'import { barColor, formatResetCountdown, formatTimeAgo } from '../lib/usageFormat'const SESSION_LABEL = '5h'@@ -22,6 +23,23 @@ function WindowRow({ title, w }: { title: string; w: ClaudeUsageWindow }) {)}+/**+ * One account's session/weekly bars under a label, for the multi-account popover. Reuses+ * WindowRow's markup — `u` is null while its on-demand fetch is in flight.+ */+function AccountUsageBlock({ label, email, u }: { label: string; email?: string; u: ClaudeUsage | null }) {+ return (+ <div className="usage-account">+ <div className="usage-account__label">{label}</div>+ {(email ?? u?.email) && <div className="usage-account__email">{email ?? u?.email}</div>}+ {u?.session && <WindowRow title="Session" w={u.session} />}+ {u?.weekly && <WindowRow title="Weekly" w={u.weekly} />}+ {u && !u.session && !u.weekly && <div className="usage-popover__empty">No usage data.</div>}+ {!u && <div className="usage-popover__empty usage-pill__pulse">···</div>}+ </div>+ )+}+/*** Bottom-left Claude usage pill + popover. Renders to the right of the React Flow Controls.* States: hidden when 'unavailable'; '···' while first-fetching; '⚠' on error w/o data;@@ -31,13 +49,35 @@ export function UsageIndicator(): JSX.Element | null {const [usage, setUsage] = useState<ClaudeUsage | null>(null)const [open, setOpen] = useState(false)const [refreshing, setRefreshing] = useState(false)+ const [acctUsage, setAcctUsage] = useState<Record<string, ClaudeUsage | null>>({})const popRef = useRef<HTMLDivElement>(null)+ const claudeAccounts = useSettings((s) => s.settings.claudeAccounts)+ // Local logged-in accounts get their own popover row; skip pending logins + remote (host) ones.+ const accounts = useMemo(+ () => claudeAccounts.filter((a) => !a.pending && !a.host),+ [claudeAccounts]+ )+useEffect(() => {void window.nodeTerminal.usage.fetch().then(setUsage)return window.nodeTerminal.usage.onUpdate(setUsage)}, [])+ // Fetch each account's usage on demand when the popover opens (system row uses `usage`).+ useEffect(() => {+ if (!open || accounts.length === 0) return+ let cancelled = false+ for (const a of accounts) {+ void window.nodeTerminal.usage.fetch(a.id).then((u) => {+ if (!cancelled) setAcctUsage((m) => ({ ...m, [a.id]: u }))+ })+ }+ return () => {+ cancelled = true+ }+ }, [open, accounts])+// Close the popover on an outside click.useEffect(() => {if (!open) return@@ -106,14 +146,25 @@ export function UsageIndicator(): JSX.Element | null {<span className="usage-popover__title">✦ Claude</span><span className="usage-popover__ago">Updated {formatTimeAgo(usage.updatedAt)}</span></div>- {session && <WindowRow title="Session" w={session} />}- {weekly && <WindowRow title="Weekly" w={weekly} />}- {!hasData && <div className="usage-popover__empty">No usage data.</div>}- {usage.email && (- <div className="usage-account">- <div className="usage-account__label">Claude Account</div>- <div className="usage-account__email">{usage.email}</div>- </div>+ {accounts.length > 0 ? (+ <>+ <AccountUsageBlock label="System" u={usage} />+ {accounts.map((a) => (+ <AccountUsageBlock key={a.id} label={a.label} email={a.email} u={acctUsage[a.id] ?? null} />+ ))}+ </>+ ) : (+ <>+ {session && <WindowRow title="Session" w={session} />}+ {weekly && <WindowRow title="Weekly" w={weekly} />}+ {!hasData && <div className="usage-popover__empty">No usage data.</div>}+ {usage.email && (+ <div className="usage-account">+ <div className="usage-account__label">Claude Account</div>+ <div className="usage-account__email">{usage.email}</div>+ </div>+ )}+ </>)}</div>)}diff --git a/src/shared/types.ts b/src/shared/types.tsindex 8c7d501b1..a3acb5a7c 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -659,10 +659,11 @@ export interface ClaudeUsage {}export interface UsageApi {- /** Returns the latest snapshot (cached if fresh, else a fresh fetch). */- fetch(): Promise<ClaudeUsage>- /** Forces a fresh fetch, bypassing the focus debounce. */- refresh(): Promise<ClaudeUsage>+ /** Returns the latest snapshot (cached if fresh, else a fresh fetch). Optional account id+ * targets a managed account; omitted = the system account (also the pushed one). */+ fetch(accountId?: string): Promise<ClaudeUsage>+ /** Forces a fresh fetch, bypassing the focus debounce. Optional account id as `fetch`. */+ refresh(accountId?: string): Promise<ClaudeUsage>/** Fires whenever main pushes a new snapshot (poll/refresh). Returns unsubscribe. */onUpdate(listener: (usage: ClaudeUsage) => void): () => void}