Skip to content

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.

feat(usage): scope the indicator to the project you are looking at

enes4282f1821619
diff --git a/src/core/usage/usage-service.remote.test.ts b/src/core/usage/usage-service.remote.test.ts
index f8181fd4d..94e671165 100644
--- a/src/core/usage/usage-service.remote.test.ts
+++ b/src/core/usage/usage-service.remote.test.ts
@@ -49,8 +49,8 @@ function start(remote?: RemoteUsageDeps): void {
service = startUsageService({ shouldPoll: () => false, remote })
}
-const callRemote = (force?: boolean): Promise<RemoteAccountUsage[]> =>
- platform.handlers[IPC.usageRemote](force) as Promise<RemoteAccountUsage[]>
+const callRemote = (query?: { hostKey?: string; force?: boolean }): Promise<RemoteAccountUsage[]> =>
+ platform.handlers[IPC.usageRemote](query) as Promise<RemoteAccountUsage[]>
describe('usage:remote', () => {
it('answers empty — never rejects — on a shell with no SSH deps', async () => {
@@ -75,7 +75,7 @@ describe('usage:remote', () => {
await callRemote()
await callRemote()
expect(run).toHaveBeenCalledTimes(1)
- await callRemote(true)
+ await callRemote({ force: true })
expect(run).toHaveBeenCalledTimes(2)
})
@@ -114,6 +114,26 @@ describe('usage:remote', () => {
expect(rows.map((r) => r.usage.status)).toEqual(['ok', 'error'])
})
+ it('reads only the named host — the scoped indicator shows one machine', async () => {
+ const run = vi.fn(async () => OK_REPLY)
+ start({ targets: () => [target('root@alpha'), target('root@beta')], run })
+ const rows = await callRemote({ hostKey: 'root@beta' })
+ expect(rows.map((r) => r.hostKey)).toEqual(['root@beta'])
+ // The other host is not read at all: an ssh exec per connected project, every time the
+ // popover opened, is the cost this scoping exists to avoid.
+ expect(run).toHaveBeenCalledTimes(1)
+ })
+
+ it('keeps the other host’s cache while you look at this one', async () => {
+ const run = vi.fn(async () => OK_REPLY)
+ start({ targets: () => [target('root@alpha'), target('root@beta')], run })
+ await callRemote({ hostKey: 'root@alpha' })
+ await callRemote({ hostKey: 'root@beta' })
+ // Switching back must not re-read: eviction is against the FULL target list, not the query.
+ await callRemote({ hostKey: 'root@alpha' })
+ expect(run).toHaveBeenCalledTimes(2)
+ })
+
it('survives a throwing target provider', async () => {
start({
targets: () => {
diff --git a/src/core/usage/usage-service.ts b/src/core/usage/usage-service.ts
index 1535cfbad..969e2e6f5 100644
--- a/src/core/usage/usage-service.ts
+++ b/src/core/usage/usage-service.ts
@@ -14,7 +14,8 @@ import { IPC } from '../../shared/ipc'
import type {
ClaudeUsage,
ProviderUsage,
- RemoteAccountUsage
+ RemoteAccountUsage,
+ RemoteUsageQuery
} from '../../shared/types'
import { emptyUsage, usageFromPayload } from './claude-usage-map'
import {
@@ -364,19 +365,25 @@ export function startUsageService(opts: UsageServiceOptions = {}): UsageService
}
}
- platform().handle(IPC.usageRemote, async (force?: boolean): Promise<RemoteAccountUsage[]> => {
+ platform().handle(IPC.usageRemote, async (query?: RemoteUsageQuery): Promise<RemoteAccountUsage[]> => {
const deps = opts.remote
if (!deps) return []
- let targets: RemoteUsageTarget[] = []
+ let all: RemoteUsageTarget[] = []
try {
- targets = deps.targets()
+ all = deps.targets()
} catch {
return [] // a throwing provider must never break the popover
}
// Rows for hosts that have since disconnected would otherwise sit in the cache forever,
- // reporting numbers from a connection that no longer exists.
- const live = new Set(targets.map((t) => t.key))
+ // reporting numbers from a connection that no longer exists. Evicted against the FULL target
+ // list rather than the caller's filtered one: switching between two SSH projects would
+ // otherwise throw away each host's cache on the way to the other.
+ const live = new Set(all.map((t) => t.key))
for (const key of [...remoteCache.keys()]) if (!live.has(key)) remoteCache.delete(key)
+ // The scoped indicator asks for ONE host — the machine the active project runs on — so the
+ // other connections cost nothing while you are not looking at them.
+ const targets = query?.hostKey ? all.filter((t) => t.hostKey === query.hostKey) : all
+ const force = query?.force
// One slow / unreachable host must not withhold the others.
const rows = await Promise.all(
targets.map(async (t): Promise<RemoteAccountUsage> => {
diff --git a/src/preload/index.ts b/src/preload/index.ts
index ea3f7c7d0..513f9e6ae 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -8,6 +8,7 @@ import type {
PtyCreateOptions,
RecycledInfo,
RelayPeerPending,
+ RemoteUsageQuery,
UpdateInfo,
UpdateProgress,
Workspace,
@@ -333,7 +334,7 @@ const api: NodeTerminalApi = {
fetch: (accountId?: string) => ipcRenderer.invoke(IPC.usageFetch, accountId),
refresh: (accountId?: string) => ipcRenderer.invoke(IPC.usageRefresh, accountId),
providers: (force?: boolean) => ipcRenderer.invoke(IPC.usageProviders, force),
- remote: (force?: boolean) => ipcRenderer.invoke(IPC.usageRemote, force),
+ remote: (query?: RemoteUsageQuery) => ipcRenderer.invoke(IPC.usageRemote, query),
setProviderCookie: (provider: string, cookie: string) =>
ipcRenderer.invoke(IPC.usageSetProviderCookie, provider, cookie),
cookieProviders: () => ipcRenderer.invoke(IPC.usageCookieProviders),
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index 5c24c8359..2b10095a9 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -33,6 +33,7 @@ import {
type ClaudeUsage,
type ProviderUsage,
type RemoteAccountUsage,
+ type RemoteUsageQuery,
type Settings,
type SpeechApi,
type SpeechModelInfo,
@@ -535,8 +536,8 @@ function buildUsageApi(client: RpcClient): Pick<NodeTerminalApi, 'usage'> {
// Real, but structurally empty on the server: `usage:remote` is registered by the same core
// service, and the server shell injects no SSH deps (it has no SSH projects), so it answers
// `[]` rather than rejecting.
- remote: (force?: boolean) =>
- client.request(IPC.usageRemote, force) as Promise<RemoteAccountUsage[]>,
+ remote: (query?: RemoteUsageQuery) =>
+ client.request(IPC.usageRemote, query) as Promise<RemoteAccountUsage[]>,
setProviderCookie: (provider: string, cookie: string) =>
client.request(IPC.usageSetProviderCookie, provider, cookie) as Promise<boolean>,
cookieProviders: () =>
diff --git a/src/renderer/components/UsageIndicator.tsx b/src/renderer/components/UsageIndicator.tsx
index 7dfae2a75..7862bbd4e 100644
--- a/src/renderer/components/UsageIndicator.tsx
+++ b/src/renderer/components/UsageIndicator.tsx
@@ -2,7 +2,9 @@ import { useEffect, useMemo, useRef, useState } from 'react'
import type { ClaudeUsage, ProviderUsage, RemoteAccountUsage, UsageLimit } from '@shared/types'
import { AGENT_CONFIG } from '@shared/agents/config'
import { useSettings } from '../state/settings'
+import { useProjects } from '../state/projects'
import { useSshConn } from '../state/sshConn'
+import { scopeFromKey, scopeUsage, usageScopeKey } from '../lib/usageScope'
import { formatResetCountdown, formatTimeAgo, percentNumber, percentText, severityColor } from '../lib/usageFormat'
import {
enabledProviders,
@@ -11,8 +13,7 @@ import {
limitLabel,
limitShortLabel,
primaryLimit,
- providerLabel,
- remotePillSegments
+ providerLabel
} from '@shared/usage-limits'
import { systemAccountDisplay } from '../state/workspace'
@@ -160,6 +161,15 @@ export function UsageIndicator({ overBoard = false }: { overBoard?: boolean }):
[claudeAccounts]
)
+ // The indicator follows the ACTIVE project: on a local project it is this machine, on an SSH
+ // project it is that host and nothing else. Showing every source at once is what made the panel
+ // unreadable once remote hosts joined it.
+ const activeProjectId = useProjects((s) => s.activeProjectId)
+ const scopeHostKey = useProjects((s) =>
+ usageScopeKey(s.projects.find((p) => p.id === s.activeProjectId))
+ )
+ const scope = useMemo(() => scopeFromKey(scopeHostKey), [scopeHostKey])
+
useEffect(() => {
void window.nodeTerminal.usage.fetch().then(setUsage)
return window.nodeTerminal.usage.onUpdate(setUsage)
@@ -180,29 +190,32 @@ export function UsageIndicator({ overBoard = false }: { overBoard?: boolean }):
}
}, [open])
- // Which SSH projects are connected right now, as a stable primitive. It is the dependency that
- // matters for remote usage: a project connecting AFTER mount adds rows nobody would otherwise
- // see until the popover was opened, and a disconnect must retire them. (Zustand compares with
- // Object.is, so a joined string re-renders only when the set actually changes.)
- const sshProjectKey = useSshConn((s) => Object.keys(s.byProject).sort().join(','))
-
- // Remote (SSH host) Claude accounts. Same cadence as `providers` — mount, popover open, and
- // now a change in connected projects — never a poll: each row is an ssh exec plus an HTTPS
+ // Remote (SSH host) Claude accounts, for THIS project's host only. Same cadence as
+ // `providers` — mount, popover open — plus the moment the project's connection comes up
+ // (`sshUp`: an SSH project is usually opened before its master is ready, and without this the
+ // pill stays empty until you click it). Never polled: each row is an ssh exec plus an HTTPS
// request made on the host, which is not a price to pay every 15 minutes for a pill nobody may
- // be looking at. Answers `[]` with nothing connected, and on shells without SSH projects.
+ // be looking at.
+ const sshUp = useSshConn((s) => !!s.byProject[activeProjectId])
useEffect(() => {
+ if (!scopeHostKey || !sshUp) {
+ // Leaving the rows up after a switch would attribute one machine's numbers to another.
+ setRemote((prev) => (prev.length ? [] : prev))
+ return
+ }
let cancelled = false
- void window.nodeTerminal.usage.remote().then((rows) => {
+ void window.nodeTerminal.usage.remote({ hostKey: scopeHostKey }).then((rows) => {
if (!cancelled) setRemote(rows)
})
return () => {
cancelled = true
}
- }, [open, sshProjectKey])
+ }, [open, scopeHostKey, sshUp])
// Fetch each account's usage on demand when the popover opens (system row uses `usage`).
+ // Skipped entirely on an SSH project: those identities are not what this project spends.
useEffect(() => {
- if (!open || accounts.length === 0) return
+ if (scope.kind !== 'local' || !open || accounts.length === 0) return
let cancelled = false
for (const a of accounts) {
void window.nodeTerminal.usage.fetch(a.id).then((u) => {
@@ -212,7 +225,7 @@ export function UsageIndicator({ overBoard = false }: { overBoard?: boolean }):
return () => {
cancelled = true
}
- }, [open, accounts])
+ }, [open, accounts, scope.kind])
// Close the popover on an outside click.
useEffect(() => {
@@ -225,50 +238,57 @@ export function UsageIndicator({ overBoard = false }: { overBoard?: boolean }):
}, [open])
// Settings → Usage toggles are a display choice, applied before any other rule — a hidden
- // provider is invisible here even when signed in and mid-limit.
+ // provider is invisible here even when signed in and mid-limit. Scoping runs after them: the
+ // toggles say what you never want to see, the scope says what belongs to where you are.
const hidden = new Set(hiddenProviders)
- const visibleProviders = providers.filter((p) => !hidden.has(p.provider))
- const claudeUsage = hidden.has('claude') ? null : usage
- // Its own switch, not Claude's: hiding the local rows must not silently take the SSH hosts
- // down with them, and vice versa.
- const visibleRemote = hidden.has('claude-remote') ? [] : remote
+ const scoped = scopeUsage({
+ scope,
+ claude: hidden.has('claude') ? null : usage,
+ accounts,
+ providers: providers.filter((p) => !hidden.has(p.provider)),
+ // Its own switch, not Claude's: hiding the local rows must not silently take the SSH hosts
+ // down with them, and vice versa.
+ remote: hidden.has('claude-remote') ? [] : remote
+ })
+ const claudeUsage = scoped.claude
+ const visibleProviders = scoped.providers
+ const visibleRemote = scoped.remote
// Only providers the user has actually enabled reach the pill; render whenever ANY of them
// (Claude included) has something to say. Both rules are pure and pinned by tests — gating on
// Claude alone, which is what this did, left a Codex-only user with no pill at all.
const enabled = enabledProviders(visibleProviders)
- const remoteSegments = remotePillSegments(visibleRemote)
if (!hasAnyUsage(claudeUsage, visibleProviders, visibleRemote)) return null
- const limits = claudeUsage?.limits ?? []
- const status = claudeUsage?.status ?? 'unavailable'
- const hasData = limits.length > 0 || enabled.length > 0 || remoteSegments.length > 0
+ // On an SSH project these are the HOST's limits — same shape, same labels, read somewhere else.
+ const limits = scoped.pillLimits
+ const status = claudeUsage?.status ?? visibleRemote[0]?.usage.status ?? 'unavailable'
+ const hasData = limits.length > 0 || enabled.length > 0
const fetching = refreshing
const isError = status === 'error'
// The pill leads with whatever is closest to biting, so a scoped model cap that is nearly
// exhausted can't hide behind a comfortable 5h window. Considers every enabled provider, not
- // just Claude, so an exhausted Codex window drives the bar too — and every connected host, so
- // an agent fleet burning a server's quota surfaces without opening the popover.
- const primary = primaryLimit([
- ...limits,
- ...enabled.flatMap((p) => p.limits),
- ...remoteSegments.map((s) => s.limit)
- ])
+ // just Claude, so an exhausted Codex window drives the bar too.
+ const primary = primaryLimit([...limits, ...enabled.flatMap((p) => p.limits)])
+ const updatedAt = claudeUsage?.updatedAt ?? visibleRemote[0]?.usage.updatedAt ?? null
const refresh = async (e: React.MouseEvent): Promise<void> => {
e.stopPropagation()
if (refreshing) return
setRefreshing(true)
try {
- // The remote rows are forced past their debounce too — ⟳ is the only way to make a host
- // re-read before the cache expires, and "refresh" that skipped half the panel would be a
- // lie. Settled independently: a host that has gone away must not withhold the local answer.
- const [local, rows] = await Promise.all([
- window.nodeTerminal.usage.refresh(),
- window.nodeTerminal.usage.remote(true).catch((): RemoteAccountUsage[] => [])
- ])
- setUsage(local)
- setRemote(rows)
+ // ⟳ refreshes what is actually on screen. On an SSH project that is the host — forced past
+ // its debounce, since this is the only way to make it re-read before the cache expires —
+ // and the local snapshot is left alone rather than spending a request on rows nobody can see.
+ if (scope.kind === 'ssh') {
+ setRemote(
+ await window.nodeTerminal.usage
+ .remote({ hostKey: scope.hostKey, force: true })
+ .catch((): RemoteAccountUsage[] => [])
+ )
+ } else {
+ setUsage(await window.nodeTerminal.usage.refresh())
+ }
} finally {
setRefreshing(false)
}
@@ -315,18 +335,6 @@ export function UsageIndicator({ overBoard = false }: { overBoard?: boolean }):
</span>
)
})}
- {/* One segment per connected HOST, labelled by its short hostname — the pill's whole job
- for a user whose Claude runs on a server, where every number above is empty. */}
- {remoteSegments.map((s, i) => (
- <span key={s.hostKey} className="usage-pill__provider">
- {(limits.length > 0 || enabled.length > 0 || i > 0) && (
- <span className="usage-pill__sep">·</span>
- )}
- <span className="usage-pill__num" title={s.hostKey}>
- {percentNumber(s.limit.usedPercent, percentMode)}% {s.label}
- </span>
- </span>
- ))}
{isError && hasData && <span className="usage-pill__dim">⚠</span>}
</>
)
@@ -338,55 +346,70 @@ export function UsageIndicator({ overBoard = false }: { overBoard?: boolean }):
<div className="usage-popover">
<div className="usage-popover__head">
<span className="usage-popover__title">✦ Usage</span>
- {/* Timestamp tracks the Claude snapshot, the only one that is polled. Absent when
- Claude is not signed in and the panel is showing other providers only. */}
- {usage && (
- <span className="usage-popover__ago">Updated {formatTimeAgo(usage.updatedAt)}</span>
+ {/* Tracks whichever snapshot the panel is actually showing — the local poll's, or
+ the host read's on an SSH project. Absent when neither has answered yet. */}
+ {updatedAt !== null && (
+ <span className="usage-popover__ago">Updated {formatTimeAgo(updatedAt)}</span>
)}
</div>
- {accounts.length > 0 && usage ? (
- <>
- <AccountUsageBlock
- mode={percentMode}
- label={systemAccountDisplay(systemLabelSetting, usage.email)}
- // Avoid printing the email twice when it's already the display label.
- email={systemLabelSetting.trim() ? (usage.email ?? undefined) : undefined}
- u={usage}
- />
- {accounts.map((a) => (
- <AccountUsageBlock key={a.id} mode={percentMode} label={a.label} email={a.email} u={acctUsage[a.id] ?? null} />
- ))}
- </>
- ) : (
- <>
- {/* Claude's rows are bare when it is the only provider; once others share the
- panel they need a heading of their own to stay attributable. */}
- {enabled.length > 0 && limits.length > 0 && (
- <div className="usage-account__label">Claude</div>
- )}
- {limits.map((l) => (
- <LimitRow key={limitKey(l)} limit={l} mode={percentMode} />
- ))}
- {!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>
- )}
- </>
- )}
- {/* Remote hosts sit between the local Claude rows and the other providers: they are
- still Claude, just read somewhere else. */}
+ {/* The local Claude section belongs to a LOCAL project only. On an SSH project the
+ remote blocks below carry the same limits, and rendering both would print the
+ host's numbers twice under two different headings. */}
+ {scope.kind === 'local' &&
+ (scoped.accounts.length > 0 && claudeUsage ? (
+ <>
+ <AccountUsageBlock
+ mode={percentMode}
+ label={systemAccountDisplay(systemLabelSetting, claudeUsage.email)}
+ // Avoid printing the email twice when it's already the display label.
+ email={systemLabelSetting.trim() ? (claudeUsage.email ?? undefined) : undefined}
+ u={claudeUsage}
+ />
+ {scoped.accounts.map((a) => (
+ <AccountUsageBlock key={a.id} mode={percentMode} label={a.label} email={a.email} u={acctUsage[a.id] ?? null} />
+ ))}
+ </>
+ ) : (
+ <>
+ {/* Claude's rows are bare when it is the only provider; once others share the
+ panel they need a heading of their own to stay attributable. */}
+ {enabled.length > 0 && limits.length > 0 && (
+ <div className="usage-account__label">Claude</div>
+ )}
+ {limits.map((l) => (
+ <LimitRow key={limitKey(l)} limit={l} mode={percentMode} />
+ ))}
+ {!hasData && <div className="usage-popover__empty">No usage data.</div>}
+ {claudeUsage?.email && (
+ <div className="usage-account">
+ <div className="usage-account__label">Claude Account</div>
+ <div className="usage-account__email">{claudeUsage.email}</div>
+ </div>
+ )}
+ </>
+ ))}
+ {/* On an SSH project these are the whole panel; the host badge is what says the numbers
+ were read somewhere other than this machine. */}
{visibleRemote.map((r) => (
<RemoteUsageBlock key={`${r.hostKey}#${r.accountId ?? ''}`} row={r} mode={percentMode} />
))}
+ {scope.kind === 'ssh' && visibleRemote.length === 0 && (
+ <div className="usage-popover__empty">
+ No usage from this host yet — it is read once the project connects.
+ </div>
+ )}
{visibleProviders.map((p) => (
<ProviderBlock key={p.provider} u={p} mode={percentMode} />
))}
</div>
)}
- <button className="usage-pill" onClick={() => setOpen((v) => !v)} title="Agent usage">
+ {/* The SSH pill is visually identical to the local one — same labels, same bar — so the
+ title is what answers "whose numbers are these?" without opening the popover. */}
+ <button
+ className="usage-pill"
+ onClick={() => setOpen((v) => !v)}
+ title={scope.kind === 'ssh' ? `Agent usage on ${scope.hostKey}` : 'Agent usage'}
+ >
<span className="usage-pill__icon">✦</span>
{pillBody}
</button>
diff --git a/src/renderer/lib/usageScope.test.ts b/src/renderer/lib/usageScope.test.ts
new file mode 100644
index 000000000..9076c744a
--- /dev/null
+++ b/src/renderer/lib/usageScope.test.ts
@@ -0,0 +1,172 @@
+import { describe, it, expect } from 'vitest'
+import {
+ scopeFromKey,
+ scopeUsage,
+ usageScopeFor,
+ usageScopeKey,
+ type UsageScope
+} from './usageScope'
+import type {
+ ClaudeAccount,
+ ClaudeUsage,
+ Project,
+ ProviderUsage,
+ RemoteAccountUsage,
+ UsageLimit
+} from '@shared/types'
+
+function limit(over: Partial<UsageLimit> = {}): UsageLimit {
+ return {
+ kind: 'session',
+ group: 'session',
+ usedPercent: 10,
+ severity: null,
+ resetsAt: null,
+ windowMinutes: null,
+ scopeLabel: null,
+ isActive: false,
+ ...over
+ }
+}
+
+function usage(limits: UsageLimit[], status: ClaudeUsage['status'] = 'ok'): ClaudeUsage {
+ return { limits, session: null, weekly: null, email: null, updatedAt: 0, status }
+}
+
+function project(over: Partial<Project> = {}): Project {
+ return {
+ id: 'p1',
+ name: 'p',
+ color: '#fff',
+ viewport: { x: 0, y: 0, zoom: 1 },
+ nodes: [],
+ ...over
+ }
+}
+
+const sshProject = (user: string, host: string): Project =>
+ project({
+ ssh: { server: { host, user, port: 22 } as never, remoteCwd: '/srv' }
+ })
+
+const remoteRow = (
+ hostKey: string,
+ accountId: string | null,
+ limits: UsageLimit[],
+ status: ClaudeUsage['status'] = 'ok'
+): RemoteAccountUsage => ({
+ hostKey,
+ accountId,
+ label: accountId ?? hostKey,
+ usage: usage(limits, status)
+})
+
+const LOCAL: UsageScope = { kind: 'local' }
+const ACCOUNTS: ClaudeAccount[] = [{ id: 'a1', label: 'Work', createdAt: 0 }]
+const PROVIDERS: ProviderUsage[] = [
+ { provider: 'codex', limits: [limit()], account: null, updatedAt: 0, status: 'ok' }
+]
+
+describe('usageScopeFor', () => {
+ it('is local for a folder project, a missing one, and a relay tab', () => {
+ expect(usageScopeFor(project())).toEqual(LOCAL)
+ expect(usageScopeFor(undefined)).toEqual(LOCAL)
+ // A relay tab's terminals run on a peer's desktop, but `usage` is app-global and stays local —
+ // showing someone else's quota under your own pill would be a lie about their account.
+ expect(usageScopeFor(project({ remote: true }))).toEqual(LOCAL)
+ })
+
+ it('is the host for an SSH project', () => {
+ expect(usageScopeFor(sshProject('root', 'niova.example.com'))).toEqual({
+ kind: 'ssh',
+ hostKey: '[email protected]'
+ })
+ })
+})
+
+describe('usageScopeKey / scopeFromKey', () => {
+ it('round-trips the scope through the one primitive a store selector can compare', () => {
+ expect(usageScopeKey(project())).toBe('')
+ expect(scopeFromKey('')).toEqual(LOCAL)
+ const key = usageScopeKey(sshProject('root', 'alpha'))
+ expect(key).toBe('root@alpha')
+ expect(scopeFromKey(key)).toEqual({ kind: 'ssh', hostKey: 'root@alpha' })
+ })
+})
+
+describe('scopeUsage — local project', () => {
+ it('keeps this machine’s accounts and providers, and drops every host', () => {
+ const out = scopeUsage({
+ scope: LOCAL,
+ claude: usage([limit({ usedPercent: 13 })]),
+ accounts: ACCOUNTS,
+ providers: PROVIDERS,
+ remote: [remoteRow('root@alpha', null, [limit({ usedPercent: 90 })])]
+ })
+ expect(out.claude?.limits[0].usedPercent).toBe(13)
+ expect(out.accounts).toHaveLength(1)
+ expect(out.providers).toHaveLength(1)
+ expect(out.remote).toEqual([])
+ // A busy server must not drive the pill of a project that does not run there.
+ expect(out.pillLimits.map((l) => l.usedPercent)).toEqual([13])
+ })
+})
+
+describe('scopeUsage — SSH project', () => {
+ const scope: UsageScope = { kind: 'ssh', hostKey: 'root@alpha' }
+
+ it('shows only that host — no local Claude, no local providers', () => {
+ const out = scopeUsage({
+ scope,
+ claude: usage([limit({ usedPercent: 13 })]),
+ accounts: ACCOUNTS,
+ providers: PROVIDERS,
+ remote: [
+ remoteRow('root@alpha', null, [limit({ usedPercent: 23 })]),
+ remoteRow('root@beta', null, [limit({ usedPercent: 99 })])
+ ]
+ })
+ expect(out.claude).toBeNull()
+ expect(out.accounts).toEqual([])
+ expect(out.providers).toEqual([])
+ expect(out.remote.map((r) => r.hostKey)).toEqual(['root@alpha'])
+ expect(out.pillLimits.map((l) => l.usedPercent)).toEqual([23])
+ })
+
+ it('leads the pill with the host’s SYSTEM account, not a managed one', () => {
+ const out = scopeUsage({
+ scope,
+ claude: null,
+ accounts: [],
+ providers: [],
+ remote: [
+ remoteRow('root@alpha', 'a1', [limit({ usedPercent: 88 })]),
+ remoteRow('root@alpha', null, [limit({ usedPercent: 23 })])
+ ]
+ })
+ expect(out.pillLimits.map((l) => l.usedPercent)).toEqual([23])
+ expect(out.remote).toHaveLength(2) // both still listed in the popover
+ })
+
+ it('falls back to a managed account when the system one has nothing', () => {
+ // A host used only through a managed login would otherwise show an empty pill over a full
+ // popover.
+ const out = scopeUsage({
+ scope,
+ claude: null,
+ accounts: [],
+ providers: [],
+ remote: [
+ remoteRow('root@alpha', null, [], 'unavailable'),
+ remoteRow('root@alpha', 'a1', [limit({ usedPercent: 88 })])
+ ]
+ })
+ expect(out.pillLimits.map((l) => l.usedPercent)).toEqual([88])
+ })
+
+ it('has nothing to say before the host has answered', () => {
+ const out = scopeUsage({ scope, claude: usage([limit()]), accounts: ACCOUNTS, providers: PROVIDERS, remote: [] })
+ expect(out.pillLimits).toEqual([])
+ expect(out.remote).toEqual([])
+ })
+})
diff --git a/src/renderer/lib/usageScope.ts b/src/renderer/lib/usageScope.ts
new file mode 100644
index 000000000..06153ae22
--- /dev/null
+++ b/src/renderer/lib/usageScope.ts
@@ -0,0 +1,115 @@
+// What the usage indicator is allowed to talk about, given the project you are looking at.
+//
+// One rule: **the pill describes the machine the ACTIVE project runs on.** On a local project
+// that is this machine (local Claude accounts + the other providers, whose credentials are all
+// local); on an SSH project it is the host (that host's Claude accounts, and nothing else).
+//
+// Before this, every source was shown at once — local Claude, local managed accounts, six
+// billing providers, and every connected SSH host. Each addition was individually reasonable and
+// the sum was unreadable: numbers from three machines sharing one line, with nothing saying which
+// was which. Scoping is what makes the panel answerable ("what am I burning HERE?") instead of a
+// list of everything the app can read.
+//
+// Deliberately NOT filtered down to the project's own `defaultAccountId`: the local side lists
+// every local identity rather than just the project default, and an SSH project listing only one
+// of its host's accounts would break that symmetry — the machine is the scope, the account is a
+// row within it.
+import type {
+ ClaudeAccount,
+ ClaudeUsage,
+ Project,
+ ProviderUsage,
+ RemoteAccountUsage
+} from '@shared/types'
+import { sshHostKey } from '@shared/ssh'
+
+/** Local = this machine. SSH = the host of the active project, by `user@host`. */
+export type UsageScope = { kind: 'local' } | { kind: 'ssh'; hostKey: string }
+
+/**
+ * The scope of the project you are looking at. No project, an unavailable tab, or a local folder
+ * all mean "this machine". A **relay** tab (`project.remote`) is local too: its terminals live on a peer's desktop,
+ * but the usage namespace is app-global and deliberately stays local (see relay-api) — a relay
+ * tab shows YOUR numbers, and claiming otherwise would be a lie about someone else's quota.
+ */
+export function usageScopeFor(project: Project | undefined): UsageScope {
+ if (!project?.ssh) return { kind: 'local' }
+ const hostKey = sshHostKey(project.ssh.server)
+ return hostKey ? { kind: 'ssh', hostKey } : { kind: 'local' }
+}
+
+/**
+ * The scope as ONE primitive — '' for local, else the host key. Zustand compares a selector's
+ * result with Object.is, and the active project object is rebuilt whenever its nodes are
+ * serialized back into the store; selecting the project itself would re-render the indicator on
+ * every canvas edit. Selecting this string re-renders it only when the answer actually changes.
+ */
+export function usageScopeKey(project: Project | undefined): string {
+ const scope = usageScopeFor(project)
+ return scope.kind === 'ssh' ? scope.hostKey : ''
+}
+
+/** Inverse of `usageScopeKey`. */
+export function scopeFromKey(hostKey: string): UsageScope {
+ return hostKey ? { kind: 'ssh', hostKey } : { kind: 'local' }
+}
+
+export interface ScopeInput {
+ scope: UsageScope
+ /** This machine's system-account snapshot (null while unknown / hidden by settings). */
+ claude: ClaudeUsage | null
+ /** Local managed accounts configured in settings (already filtered of pending ones). */
+ accounts: readonly ClaudeAccount[]
+ /** Non-Claude providers — all local credentials. */
+ providers: readonly ProviderUsage[]
+ /** Every remote row the service answered with. */
+ remote: readonly RemoteAccountUsage[]
+}
+
+export interface ScopedUsage {
+ /** The system-account snapshot to render as the leading Claude block, or null. */
+ claude: ClaudeUsage | null
+ accounts: ClaudeAccount[]
+ providers: ProviderUsage[]
+ remote: RemoteAccountUsage[]
+ /**
+ * The limits the collapsed pill spells out. On a local project that is the system account's;
+ * on an SSH project the host's system account, falling back to the first identity that has
+ * anything to say — a host used only through a managed account would otherwise show an empty
+ * pill while its popover was full.
+ *
+ * Managed accounts (local OR remote) never get their own pill segment: the pill has one line
+ * beside the canvas, and the popover is where per-account detail belongs. This is the rule the
+ * local side has always followed; the SSH side now matches it.
+ */
+ pillLimits: ClaudeUsage['limits']
+}
+
+export function scopeUsage(input: ScopeInput): ScopedUsage {
+ const { scope, claude, accounts, providers, remote } = input
+ if (scope.kind === 'local') {
+ return {
+ claude,
+ accounts: [...accounts],
+ providers: [...providers],
+ // Remote hosts are another machine's story — not this project's.
+ remote: [],
+ pillLimits: claude?.limits ?? []
+ }
+ }
+ const rows = remote.filter((r) => r.hostKey === scope.hostKey)
+ const system = rows.find((r) => r.accountId === null)
+ const leading =
+ system && system.usage.limits.length > 0
+ ? system
+ : (rows.find((r) => r.usage.limits.length > 0) ?? system)
+ return {
+ // The local machine's Claude, its managed accounts and the local billing providers are all
+ // credentials you are NOT spending while you work on the host.
+ claude: null,
+ accounts: [],
+ providers: [],
+ remote: rows,
+ pillLimits: leading?.usage.limits ?? []
+ }
+}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index b627087a3..bbfc04c54 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -1269,6 +1269,15 @@ export interface RemoteAccountUsage {
usage: ClaudeUsage
}
+/** What the usage indicator wants from the remote hosts right now. */
+export interface RemoteUsageQuery {
+ /** Read only this `user@host` — the machine the active project runs on. Omitted = every
+ * connected host, which no scoped UI asks for but keeps the channel general. */
+ hostKey?: string
+ /** Bypass the cache debounce (the ⟳ button). */
+ force?: boolean
+}
+
export interface UsageApi {
/** 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). */
@@ -1279,11 +1288,12 @@ export interface UsageApi {
* `force` to bypass the cache debounce. Providers that aren't signed in come back
* 'unavailable' rather than being omitted, so the caller can tell "off" from "broken". */
providers(force?: boolean): Promise<ProviderUsage[]>
- /** Usage for every Claude identity on the hosts of the CONNECTED SSH projects, read on those
- * hosts (the credential never crosses back). On-demand like `providers`, not polled — each row
- * costs an ssh round-trip. Empty when nothing is connected, or on a shell with no SSH projects
- * (Server Edition), so callers need no capability check. */
- remote(force?: boolean): Promise<RemoteAccountUsage[]>
+ /** Usage for the Claude identities on connected SSH hosts, read on those hosts (the credential
+ * never crosses back). On-demand like `providers`, not polled — each row costs an ssh
+ * round-trip, which is also why the caller should name the ONE host it is showing. Empty when
+ * nothing is connected, or on a shell with no SSH projects (Server Edition), so callers need
+ * no capability check. */
+ remote(query?: RemoteUsageQuery): Promise<RemoteAccountUsage[]>
/** Store (or, with an empty string, clear) a provider's browser cookie. Resolves to whether one
* is now stored. Write-only by design — nothing reads the value back across this boundary. */
setProviderCookie(provider: string, cookie: string): Promise<boolean>
diff --git a/src/shared/usage-limits.test.ts b/src/shared/usage-limits.test.ts
index 736b42804..54f00c790 100644
--- a/src/shared/usage-limits.test.ts
+++ b/src/shared/usage-limits.test.ts
@@ -7,9 +7,7 @@ import {
limitKey,
enabledProviders,
hasAnyUsage,
- providerLabel,
- remotePillSegments,
- shortHostLabel
+ providerLabel
} from './usage-limits'
import type { ProviderUsage, RemoteAccountUsage, UsageLimit } from './types'
@@ -158,40 +156,6 @@ function remoteRow(over: Partial<RemoteAccountUsage> & { limits?: UsageLimit[] }
}
}
-describe('shortHostLabel', () => {
- it('takes the hostname, without the user or the domain', () => {
- expect(shortHostLabel('[email protected]')).toBe('build-01')
- expect(shortHostLabel('niova')).toBe('niova')
- })
-
- it('keeps a bare IP whole — chopping at the dot would print "10"', () => {
- expect(shortHostLabel('[email protected]')).toBe('10.0.0.4')
- expect(shortHostLabel('root@fe80::1')).toBe('fe80::1')
- })
-})
-
-describe('remotePillSegments', () => {
- it('gives one segment per host, carrying its worst limit', () => {
- const segs = remotePillSegments([
- remoteRow({ limits: [limit({ usedPercent: 60 })] }),
- remoteRow({
- hostKey: '[email protected]',
- accountId: 'a1',
- label: 'Work',
- limits: [limit({ kind: 'weekly_all', usedPercent: 91 })]
- }),
- remoteRow({ hostKey: 'root@beta', label: 'root@beta', limits: [limit({ usedPercent: 5 })] })
- ])
- // Two accounts on one host collapse into ONE segment — the pill shares a line with the canvas.
- expect(segs.map((s) => s.label)).toEqual(['alpha', 'beta'])
- expect(segs[0].limit.usedPercent).toBe(91)
- })
-
- it('skips hosts with nothing to report', () => {
- expect(remotePillSegments([remoteRow(), remoteRow({ hostKey: 'root@beta' })])).toEqual([])
- })
-})
-
describe('hasAnyUsage with remote rows', () => {
it('shows the pill for a user whose Claude only runs on a server', () => {
expect(hasAnyUsage({ status: 'unavailable' }, [], [remoteRow({ limits: [limit({})] })])).toBe(true)
diff --git a/src/shared/usage-limits.ts b/src/shared/usage-limits.ts
index 16244fc1e..fe3041bec 100644
--- a/src/shared/usage-limits.ts
+++ b/src/shared/usage-limits.ts
@@ -82,43 +82,10 @@ export function hasAnyUsage(
return remote.some((r) => r.usage.status === 'ok' || r.usage.status === 'error')
}
-/**
- * Short, human name for an ssh `user@host` — what the collapsed pill labels a remote segment
- * with, since `[email protected]` cannot share a row with three other
- * numbers. Bare IPs are kept whole: chopping at the first dot would turn 10.0.0.4 into "10".
- */
-export function shortHostLabel(hostKey: string): string {
- const host = hostKey.includes('@') ? hostKey.slice(hostKey.indexOf('@') + 1) : hostKey
- if (!host) return hostKey
- if (/^[\d.]+$/.test(host) || host.includes(':')) return host // IPv4 / IPv6
- const first = host.split('.')[0]
- return first || host
-}
-
-/**
- * One pill segment per remote HOST, carrying that host's worst limit.
- *
- * Per host, not per account: a host with three managed accounts would otherwise push three more
- * numbers into a pill that already shares a line with the canvas. The full per-account breakdown
- * is what the popover is for.
- */
-export function remotePillSegments(
- remote: readonly RemoteAccountUsage[]
-): { hostKey: string; label: string; limit: UsageLimit }[] {
- const byHost = new Map<string, UsageLimit[]>()
- for (const r of remote) {
- if (r.usage.status !== 'ok' || r.usage.limits.length === 0) continue
- const acc = byHost.get(r.hostKey)
- if (acc) acc.push(...r.usage.limits)
- else byHost.set(r.hostKey, [...r.usage.limits])
- }
- const out: { hostKey: string; label: string; limit: UsageLimit }[] = []
- for (const [hostKey, limits] of byHost) {
- const worst = primaryLimit(limits)
- if (worst) out.push({ hostKey, label: shortHostLabel(hostKey), limit: worst })
- }
- return out
-}
+// (A per-host pill segment lived here while the pill showed every connected host at once. The
+// indicator is scoped to the active project now — at most ONE machine is ever in view — so the
+// host's limits take the pill's ordinary Claude slot and the segment has nothing left to say.
+// See renderer/lib/usageScope.ts.)
/**
* Every usage source the app can read, in display order — Claude first (the primary agent) with