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
fix(usage): show the active Claude organization per account
review1e7b42cf24fe
diff --git a/CLAUDE.md b/CLAUDE.mdindex f108819c7..6a3c3515c 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -2891,7 +2891,7 @@ else, and its context links must keep classifying across restarts).picks the account dir's `projects/`, composite cache key includes `accountId`); the samethreading runs through the session-name poll, restart handoff, and `ChatPanel` (the ⌘Mtranscript view, `chat.readTranscript`). The **usage indicator** is per account (`claude-usage.ts`: scoped Keychain- service first, legacy unscoped fallback; popover lists a row per account with **System**+ service only for managed accounts, then their credentials file; popover lists a row per account with **System**first). **Remote (SSH host) accounts are included** — see **Remote usage** below.- **Pickers** — New Claude exposes an account **submenu** (pane menu; flat entries inthe dock; palette commands; TabBar sets the **per-project default**). A **local** project@@ -2947,6 +2947,17 @@ else, and its context links must keep classifying across restarts).tooltip pointing at Settings → Accounts, where **Detected config dirs** lists it for one-clicklinking. Mobile: N/A (additive mirror fields).+- **Active Claude organization** (#552) — local Desktop and Server usage snapshots carry optional+ `organization` metadata from the SAME account's `.claude.json` (system, managed or linked).+ Read it even if Keychain/file credentials already have an email; unreadable/missing metadata+ preserves the email and usage. A known email mismatch drops metadata. Managed usage cannot use+ an unscoped Keychain token: a matching email alone does not prove it belongs to the same org.+ The popover names the org beneath the email; internal type/tier/id remain tooltip details.+ Refresh re-reads metadata together with usage; normal cache/poll intervals still apply.+ SSH's existing shell reader does not supply organization metadata and keeps its email-only+ fallback. Mobile's usage mirror currently omits it; displaying orgs there needs a follow-up+ mirror/iOS protocol change. No organization picker, credential writes or switching are added.+- **The usage indicator is scoped to the ACTIVE project** (`renderer/lib/usageScope.ts`, pure +unit-tested) — it describes **the machine that project runs on**, and nothing else. A localproject shows this machine (system + managed local accounts + the billing providers, whosediff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 0223794bd..dfe8dbfc8 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -56,6 +56,11 @@ handler needs something only Electron has (an SSH ControlMaster, a native dialog**injected dep** whose absence is a documented degrade — see `registerTranscriptIpc` /`registerContextEnsureIpc` — rather than a reason to keep the whole handler in `src/main`.+Claude usage identity is scoped to the same config directory as its credentials. Read organization+metadata even when credentials already include an email, and degrade to the email-only row when+metadata cannot be read. Managed usage must never fall back to an unscoped system Keychain token:+that would label one account's limits with another account's organization.+## Three surfacesA feature is not done until you have decided how it behaves on each — even if the decision is "notdiff --git a/src/core/usage/usage-service.identity.test.ts b/src/core/usage/usage-service.identity.test.tsnew file mode 100644index 000000000..c8e41feca--- /dev/null+++ b/src/core/usage/usage-service.identity.test.ts@@ -0,0 +1,115 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { promises as fs } from 'fs'+import { fetchUsage } from './usage-service'+import { initPlatform, resetPlatformForTests } from '../platform'+import { fakePlatform } from '../platform-fake'+import { registerClaudeAccountsSource, resetClaudeAccountsSourceForTests } from '../claude-config-dir'++const { keychain } = vi.hoisted(() => ({ keychain: vi.fn() }))+vi.mock('child_process', () => ({ execFile: keychain }))+vi.mock('fs', async (original) => {+ const actual = await original<typeof import('fs')>()+ return { ...actual, promises: { ...actual.promises, readFile: vi.fn() } }+})+vi.mock('os', async (original) => {+ const actual = await original<typeof import('os')>()+ return { ...actual, default: { ...actual, homedir: () => '/fixture-home' } }+})++const token = JSON.stringify({ claudeAiOauth: { accessToken: 'fixture-token', email: '[email protected]' } })+const identity = (name: string) => JSON.stringify({ oauthAccount: {+ emailAddress: '[email protected]', organizationName: name,+ organizationUuid: `id-${name}`, organizationType: 'claude_team',+ organizationRateLimitTier: 'default_raven'+} })+let files: Record<string, string>++beforeEach(() => {+ initPlatform(fakePlatform({ userDataDir: '/fixture-data' }))+ vi.spyOn(process, 'platform', 'get').mockReturnValue('linux')+ files = { '/fixture-home/.claude/.credentials.json': token, '/fixture-home/.claude.json': identity('Personal') }+ vi.mocked(fs.readFile).mockImplementation(async (file) => {+ const raw = files[String(file)]+ if (raw === undefined) throw new Error('fixture missing')+ return raw+ })+ keychain.mockReset()+ keychain.mockImplementation((_cmd, _args, cb) => cb(new Error('fixture missing')))+ vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ five_hour: { utilization: 12 } }))))+})+afterEach(() => {+ vi.restoreAllMocks()+ vi.unstubAllGlobals()+ resetClaudeAccountsSourceForTests()+ resetPlatformForTests()+})++describe('active Claude organization', () => {+ it('reads the identity even when credentials already supply email; refresh follows a same-email org switch', async () => {+ expect(await fetchUsage()).toMatchObject({ email: '[email protected]', organization: { name: 'Personal', rateLimitTier: 'default_raven' } })+ files['/fixture-home/.claude.json'] = identity('Team')+ expect(await fetchUsage()).toMatchObject({ organization: { name: 'Team' }, status: 'ok' })+ })+ it.each(['missing', '{broken', 'null', '{}', '{"oauthAccount":{"organizationName":42}}'])('fails softly for identity %s', async (raw) => {+ if (raw === 'missing') delete files['/fixture-home/.claude.json']+ else files['/fixture-home/.claude.json'] = raw+ const u = await fetchUsage()+ expect(u).toMatchObject({ email: '[email protected]', status: 'ok', session: { leftPercent: 88 } })+ expect(u.organization).toBeUndefined()+ })+ it('does not attribute a different email’s metadata to the token', async () => {+ files['/fixture-home/.claude.json'] = identity('Wrong').replace('[email protected]', '[email protected]')+ expect((await fetchUsage()).organization).toBeUndefined()+ })+ it('uses each managed or linked account’s identity without falling back to the system file', async () => {+ registerClaudeAccountsSource(() => [{ id: 'linked', label: 'Linked', createdAt: 0, configDir: '/fixture-linked' }])+ for (const [id, dir] of [['managed', '/fixture-data/claude-accounts/managed'], ['linked', '/fixture-linked']]) {+ files[`${dir}/.credentials.json`] = token+ files[`${dir}/.claude.json`] = identity(id)+ expect((await fetchUsage(id)).organization?.name).toBe(id)+ delete files[`${dir}/.claude.json`]+ expect((await fetchUsage(id)).organization).toBeUndefined()+ }+ })+ it('reads org metadata with a Keychain email on macOS', async () => {+ vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin')+ keychain.mockImplementation((_cmd, _args, cb) => cb(null, { stdout: token, stderr: '' }))+ expect((await fetchUsage()).organization?.name).toBe('Personal')+ })+ it('never combines managed identity with an unscoped system Keychain token', async () => {+ vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin')+ keychain.mockImplementation((_cmd, args, cb) => args.includes('Claude Code-credentials') ? cb(null, { stdout: token, stderr: '' }) : cb(new Error('no scoped entry')))+ files['/fixture-data/claude-accounts/team/.claude.json'] = identity('Team')+ expect(await fetchUsage('team')).toMatchObject({ status: 'unavailable' })+ expect(fetch).not.toHaveBeenCalled()+ expect(keychain).toHaveBeenCalledTimes(1)+ })+})++it('falls back to the managed credentials FILE after a scoped Keychain miss', async () => {+ vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin')+ files['/fixture-data/claude-accounts/team/.credentials.json'] = token+ files['/fixture-data/claude-accounts/team/.claude.json'] = identity('Team')+ expect(await fetchUsage('team')).toMatchObject({ status: 'ok', organization: { name: 'Team' } })+ expect(keychain).toHaveBeenCalledTimes(1)+})+it('preserves email backfill and drops malformed optional fields', async () => {+ files['/fixture-home/.claude/.credentials.json'] = '{"accessToken":"fixture-token"}'+ files['/fixture-home/.claude.json'] = JSON.stringify({ oauthAccount: {+ emailAddress: '[email protected]', organizationName: ' Team ',+ organizationUuid: 1, organizationType: [], organizationRateLimitTier: ' '+ } })+ const u = await fetchUsage()+ expect(u.email).toBe('[email protected]')+ expect(u.organization).toEqual({ name: 'Team', uuid: undefined, type: undefined, rateLimitTier: undefined })+})+it('does not advertise stale organization metadata without credentials', async () => {+ delete files['/fixture-home/.claude/.credentials.json']+ expect(await fetchUsage()).toMatchObject({ status: 'unavailable' })+ expect((await fetchUsage()).organization).toBeUndefined()+ expect(fetch).not.toHaveBeenCalled()+})+it('preserves resolved identity when usage fetch fails', async () => {+ vi.mocked(fetch).mockRejectedValue(new Error('fixture offline'))+ expect(await fetchUsage()).toMatchObject({ status: 'error', email: '[email protected]', organization: { name: 'Personal' } })+})diff --git a/src/core/usage/usage-service.ts b/src/core/usage/usage-service.tsindex 989175c70..b42266c18 100644--- a/src/core/usage/usage-service.ts+++ b/src/core/usage/usage-service.ts@@ -52,6 +52,7 @@ const REFETCH_DEBOUNCE_MS = 5 * 60 * 1000interface OAuthCreds {accessToken: string | nullemail: string | null+ organization?: ClaudeUsage['organization']}/**@@ -88,7 +89,7 @@ export function parseCreds(raw: string): OAuthCreds {}/**- * macOS Keychain → {config}/.credentials.json → email backfill from {config}/.claude.json.+ * macOS Keychain → {config}/.credentials.json; identity metadata 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).*@@ -102,7 +103,9 @@ async function resolveCreds(accountId?: string): Promise<OAuthCreds> {let creds: OAuthCreds = { accessToken: null, email: null }if (process.platform === 'darwin') {- for (const service of services) {+ // An unscoped Keychain entry belongs to the system account. Using it here would+ // label the system token's limits with the managed account's organization.+ for (const service of configDir ? services.slice(0, 1) : services) {try {const { stdout } = await execFileP('security', ['find-generic-password',@@ -130,7 +133,7 @@ async function resolveCreds(accountId?: string): Promise<OAuthCreds> {}}- if (creds.accessToken && !creds.email) {+ if (creds.accessToken) {try {const raw = await fs.readFile(identityFile, 'utf-8')const j = JSON.parse(raw) as Record<string, any>@@ -139,7 +142,25 @@ async function resolveCreds(accountId?: string): Promise<OAuthCreds> {(acct && typeof acct.emailAddress === 'string' && acct.emailAddress) ||(acct && typeof acct.email === 'string' && acct.email) ||null- if (email) creds = { ...creds, email }+ // Identity may lag a login. A known email mismatch must not label this token+ // with another user's organization; missing metadata still leaves usage intact.+ if (!creds.email || !email || creds.email === email) {+ const text = (value: unknown): string | undefined =>+ typeof value === 'string' ? value.trim() || undefined : undefined+ const name = text(acct?.organizationName)+ creds = {+ ...creds,+ email: creds.email || email,+ ...(name+ ? { organization: {+ name,+ uuid: text(acct?.organizationUuid),+ type: text(acct?.organizationType),+ rateLimitTier: text(acct?.organizationRateLimitTier)+ } }+ : {})+ }+ }} catch {// best-effort only}@@ -155,8 +176,10 @@ export async function resolveClaudeAccessToken(accountId?: string): Promise<striexport async function fetchUsage(accountId?: string): Promise<ClaudeUsage> {const now = Date.now()- const { accessToken, email } = await resolveCreds(accountId)- if (!accessToken) return emptyUsage(email, now, 'unavailable')+ const { accessToken, email, organization } = await resolveCreds(accountId)+ const identify = (usage: ClaudeUsage): ClaudeUsage =>+ organization ? { ...usage, organization } : usage+ if (!accessToken) return identify(emptyUsage(email, now, 'unavailable'))try {const ctrl = new AbortController()const t = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS)@@ -168,12 +191,12 @@ export async function fetchUsage(accountId?: string): Promise<ClaudeUsage> {if (!res.ok) {// 401/403 → token is an API key or expired: no subscription windows to show.const status = res.status === 401 || res.status === 403 ? 'unavailable' : 'error'- return emptyUsage(email, now, status)+ return identify(emptyUsage(email, now, status))}const data = (await res.json()) as Record<string, any>- return usageFromPayload(data, email, now)+ return identify(usageFromPayload(data, email, now))} catch {- return emptyUsage(email, now, 'error')+ return identify(emptyUsage(email, now, 'error'))}}diff --git a/src/renderer/components/UsageIndicator.organization.test.tsx b/src/renderer/components/UsageIndicator.organization.test.tsxnew file mode 100644index 000000000..4cfed9d17--- /dev/null+++ b/src/renderer/components/UsageIndicator.organization.test.tsx@@ -0,0 +1,68 @@+// @vitest-environment jsdom+import { act } from 'react'+import { createRoot, type Root } from 'react-dom/client'+import { beforeEach, afterEach, expect, it, vi } from 'vitest'+import { DEFAULT_SETTINGS, type ClaudeUsage } from '@shared/types'+import { useSettings } from '../state/settings'+import { UsageIndicator } from './UsageIndicator'++;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true+let host: HTMLDivElement+let root: Root+let system: ClaudeUsage+let managed: ClaudeUsage+const snapshot = (name?: string): ClaudeUsage => ({+ limits: [], session: null, weekly: null, email: '[email protected]', updatedAt: Date.now(), status: 'ok',+ ...(name ? { organization: { name, rateLimitTier: 'default_raven' } } : {})+})+beforeEach(() => {+ system = snapshot('Personal')+ managed = snapshot('Team')+ useSettings.setState({ settings: { ...DEFAULT_SETTINGS, claudeAccounts: [] } })+ window.nodeTerminal = { usage: {+ fetch: vi.fn(async (id?: string) => id ? managed : system),+ refresh: vi.fn(async () => system),+ providers: vi.fn(async () => []), onUpdate: vi.fn(() => () => {})+ } } as unknown as typeof window.nodeTerminal+ host = document.createElement('div')+ document.body.append(host)+ root = createRoot(host)+})+afterEach(async () => {+ await act(async () => root.unmount())+ host.remove()+})+async function open() {+ await act(async () => root.render(<UsageIndicator />))+ await act(async () => host.querySelector<HTMLButtonElement>('.usage-pill')!.click())+}+it('shows the active organization beside the system email and keeps the raw tier in the tooltip', async () => {+ await open()+ const row = host.querySelector('.usage-account')!+ expect(row.textContent).toContain('[email protected]')+ expect(row.textContent).toContain('Organization: Personal')+ expect(row.textContent).not.toContain('default_raven')+ expect(row.querySelector('.usage-account__organization')?.getAttribute('title')).toContain('Rate limit tier: default_raven')+})+it('keeps same-email organizations in separate account rows and prefers the fetched identity email', async () => {+ useSettings.setState({ settings: { ...DEFAULT_SETTINGS, claudeAccounts: [{ id: 'team', label: 'Work', email: '[email protected]', createdAt: 0 }] } })+ await open()+ const rows = [...host.querySelectorAll('.usage-account')]+ expect(rows).toHaveLength(2)+ expect(rows[0].textContent).toContain('Organization: Personal')+ expect(rows[0].textContent).not.toContain('Organization: Team')+ expect(rows[1].textContent).toContain('Organization: Team')+ expect(rows[1].textContent).toContain('[email protected]')+ expect(rows[1].textContent).not.toContain('[email protected]')+})+it('keeps the email-only block when organization metadata is unavailable', async () => {+ system = snapshot()+ await open()+ expect(host.querySelector('.usage-account')?.textContent).toBe('Claude [email protected]')+ expect(host.querySelector('.usage-account__organization')).toBeNull()+})+it('shows an available organization even when no email was found', async () => {+ system.email = null+ await open()+ expect(host.querySelector('.usage-account')?.textContent).toContain('Organization: Personal')+})diff --git a/src/renderer/components/UsageIndicator.tsx b/src/renderer/components/UsageIndicator.tsxindex 7599233e9..95abedac0 100644--- a/src/renderer/components/UsageIndicator.tsx+++ b/src/renderer/components/UsageIndicator.tsx@@ -1,4 +1,5 @@import { useEffect, useMemo, useRef, useState } from 'react'+import { UsageOrganization } from './UsageOrganization'import { IconReload } from './icons'import type { ClaudeUsage, ProviderUsage, RemoteAccountUsage, UsageLimit } from '@shared/types'import { AGENT_CONFIG } from '@shared/agents/config'@@ -128,7 +129,8 @@ function AccountUsageBlock({{label}<DefaultAccountMark isDefault={isDefault} onUse={onUse} /></div>- {(email ?? u?.email) && <div className="usage-account__email">{email ?? u?.email}</div>}+ {(u?.email ?? email) && <div className="usage-account__email">{u?.email ?? email}</div>}+ <UsageOrganization organization={u?.organization} />{u?.limits.map((l) => (<LimitRow key={limitKey(l)} limit={l} mode={mode} />))}@@ -532,10 +534,11 @@ export function UsageIndicator({<LimitRow key={limitKey(l)} limit={l} mode={percentMode} />))}{!hasData && <div className="usage-popover__empty">No usage data.</div>}- {claudeUsage?.email && (+ {(claudeUsage?.email || claudeUsage?.organization) && (<div className="usage-account"><div className="usage-account__label">Claude Account</div><div className="usage-account__email">{claudeUsage.email}</div>+ <UsageOrganization organization={claudeUsage.organization} /></div>)}</>diff --git a/src/renderer/components/UsageOrganization.tsx b/src/renderer/components/UsageOrganization.tsxnew file mode 100644index 000000000..fc2081d93--- /dev/null+++ b/src/renderer/components/UsageOrganization.tsx@@ -0,0 +1,16 @@+import type { ClaudeUsageOrganization } from '@shared/types'++/** Optional identity detail: old snapshots and unreadable metadata keep the email-only view. */+export function UsageOrganization({ organization }: { organization?: ClaudeUsageOrganization }) {+ if (!organization?.name) return null+ const detail = [+ organization.type && `Type: ${organization.type}`,+ organization.rateLimitTier && `Rate limit tier: ${organization.rateLimitTier}`,+ organization.uuid && `Organization ID: ${organization.uuid}`+ ].filter(Boolean).join('\n')+ return (+ <div className="usage-account__organization" title={detail || undefined}>+ Organization: {organization.name}+ </div>+ )+}diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex caec75eb2..60ddcd6f0 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -7587,6 +7587,11 @@ button.group-node__setup:disabled {.ctx-popover__meta { margin-top: 8px; font-size: 12px; }.ctx-popover__sub { margin-top: 4px; font-size: 11px; color: rgba(var(--tint-rgb), 0.5); }.usage-account__email { font-size: 13px; }+.usage-account__organization {+ font-size: 12px;+ color: rgba(var(--tint-rgb), 0.65);+ overflow-wrap: anywhere;+}.seg-pill {display: inline-flex;diff --git a/src/shared/types.ts b/src/shared/types.tsindex d05cad046..830b0100b 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -2536,6 +2536,14 @@ export interface SessionMemoryApi {host(q?: SessionMemoryQuery): Promise<MemInfo | null>}+/** Best-effort active organization from this account's Claude identity file. */+export interface ClaudeUsageOrganization {+ name: string+ uuid?: string+ type?: string+ rateLimitTier?: string+}+/** Claude Code subscription usage snapshot for the bottom-left indicator. */export interface ClaudeUsage {/**@@ -2547,6 +2555,8 @@ export interface ClaudeUsage {weekly: ClaudeUsageWindow | null/** Signed-in account email, read-only and best-effort (null if unknown). */email: string | null+ /** Active organization, absent when its metadata is unavailable. */+ organization?: ClaudeUsageOrganization/** Unix ms when this snapshot was produced. */updatedAt: number/**