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): read Claude usage on SSH hosts, without pulling their tokens

enesbba0bcfa56f3
diff --git a/src/core/agent-status-mirror.ts b/src/core/agent-status-mirror.ts
index 36b6102c0..99f9c41a3 100644
--- a/src/core/agent-status-mirror.ts
+++ b/src/core/agent-status-mirror.ts
@@ -322,9 +322,12 @@ export function reduceEntry(
* Deliberately drops the local `settings` block: a slice carries per-host settings that the SSH
* push injects itself (Task 2 of mobile-agent-launch-parity), never this host's local block.
*
- * `usage` is likewise DROPPED (spec: mobile-usage-inbox): a remote host's account credentials
- * live on that host, so the desktop cannot answer for them — a host running nodeterm itself
- * writes its own mirror with its own usage. `server` (install metadata) is DROPPED for the same
+ * `usage` is likewise DROPPED (spec: mobile-usage-inbox): the block describes THIS machine's
+ * local accounts, and a host running nodeterm itself writes its own mirror with its own usage.
+ * (The desktop CAN now read a host's Claude usage — see core/usage/remote-claude-usage — but
+ * pushing those numbers back to the very host they were read on would be a round trip to
+ * nowhere. Surfacing remote usage on the phone means teaching the phone to ask, not padding
+ * this slice.) `server` (install metadata) is DROPPED for the same
* reason (it describes THIS host's install, not the remote's — a remote nodeterm writes its own).
* `inbox` is KEPT but filtered to the slice's node ids (both the `events` feed and the per-node
* `nodes` map).
diff --git a/src/core/usage/claude-usage-map.ts b/src/core/usage/claude-usage-map.ts
index 7bb4a0365..96d34275a 100644
--- a/src/core/usage/claude-usage-map.ts
+++ b/src/core/usage/claude-usage-map.ts
@@ -10,7 +10,8 @@
// contract: when the next model ships, its limit arrives as another array entry and this file
// does not change. Binding a `fableWeekly` slot (or a `seven_day_fable` field) would recreate
// the exact rigidity Anthropic just moved away from.
-import type { UsageLimit } from '../../shared/types'
+import type { ClaudeUsage, ClaudeUsageWindow, UsageLimit } from '../../shared/types'
+import { findLimit } from '../../shared/usage-limits'
/** `percent`/`utilization` are portions USED, 0–100. Clamp — the server is not our validator. */
function clampPercent(v: unknown): number | null {
@@ -103,3 +104,35 @@ export function mapUsageLimits(data: unknown): UsageLimit[] {
}
return legacyLimits(body)
}
+
+/** Back-compat view of one limit as the old remaining-percent window. */
+function asWindow(limit: UsageLimit | null): ClaudeUsageWindow | null {
+ if (!limit) return null
+ return { leftPercent: 100 - limit.usedPercent, resetsAt: limit.resetsAt }
+}
+
+/**
+ * A full `ClaudeUsage` snapshot from a raw `/api/oauth/usage` body. Shared by the LOCAL fetch
+ * (usage-service) and the REMOTE one (remote-claude-usage), which differ only in who performs
+ * the request — the payload, and therefore its normalization, is identical.
+ */
+export function usageFromPayload(data: unknown, email: string | null, now: number): ClaudeUsage {
+ const limits = mapUsageLimits(data)
+ return {
+ limits,
+ session: asWindow(findLimit(limits, 'session')),
+ weekly: asWindow(findLimit(limits, 'weekly_all')),
+ email,
+ updatedAt: now,
+ status: 'ok'
+ }
+}
+
+/** An empty snapshot carrying only the identity we managed to resolve. */
+export function emptyUsage(
+ email: string | null,
+ now: number,
+ status: ClaudeUsage['status']
+): ClaudeUsage {
+ return { limits: [], session: null, weekly: null, email, updatedAt: now, status }
+}
diff --git a/src/core/usage/remote-claude-usage.test.ts b/src/core/usage/remote-claude-usage.test.ts
new file mode 100644
index 000000000..c8d61092e
--- /dev/null
+++ b/src/core/usage/remote-claude-usage.test.ts
@@ -0,0 +1,313 @@
+// The remote-usage command is generated shell that no compiler checks, running on a machine we
+// cannot inspect — the same class of code as the canvas-control shim, and tested the same way:
+// the real script, run by the real /bin/sh, against a fake `curl` on PATH and a fake $HOME. A
+// quoting slip here does not fail loudly; it returns an empty pill and looks like "the host has
+// no usage", which is precisely the bug this feature exists to fix.
+import { describe, it, expect, beforeAll, afterAll } from 'vitest'
+import { execFile } from 'node:child_process'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { promisify } from 'node:util'
+import type { ClaudeAccount } from '../../shared/types'
+import {
+ fetchRemoteUsage,
+ parseRemoteUsageOutput,
+ remoteUsageCommand,
+ remoteUsageTargets,
+ type RemoteUsageTarget
+} from './remote-claude-usage'
+
+const run = promisify(execFile)
+
+let dir = ''
+let home = ''
+let bin = ''
+
+/** Where the fake curl records what it was handed, so the token's path can be asserted. */
+const argvLog = (): string => path.join(dir, 'curl-argv.txt')
+const stdinLog = (): string => path.join(dir, 'curl-stdin.txt')
+
+const USAGE_BODY = JSON.stringify({
+ limits: [
+ { kind: 'session', group: 'session', percent: 60, severity: 'normal' },
+ { kind: 'weekly_all', group: 'weekly', percent: 12, severity: 'normal' }
+ ]
+})
+
+beforeAll(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-rusage-'))
+ home = path.join(dir, 'home')
+ bin = path.join(dir, 'bin')
+ fs.mkdirSync(home, { recursive: true })
+ fs.mkdirSync(bin, { recursive: true })
+ // Stands in for curl: records argv + stdin, then emits a body plus the `-w` marker the real
+ // curl would append. Everything the command does around it (reading the files, piping the
+ // config, the markers) is the real thing.
+ fs.writeFileSync(
+ path.join(bin, 'curl'),
+ [
+ '#!/bin/sh',
+ `printf '%s\\n' "$*" > ${JSON.stringify(argvLog())}`,
+ `cat > ${JSON.stringify(stdinLog())}`,
+ `printf '%s' ${JSON.stringify(USAGE_BODY)}`,
+ "printf '\\n__NTU_HTTP__200\\n'",
+ ''
+ ].join('\n'),
+ { mode: 0o755 }
+ )
+ // A host with the ordinary text tools but no curl. Emptying PATH instead would break the
+ // credential read too and report `nocreds` — a different, misleading answer.
+ const noCurl = path.join(dir, 'nocurl-bin')
+ fs.mkdirSync(noCurl, { recursive: true })
+ for (const tool of ['tr', 'grep', 'sed', 'head', 'cat']) {
+ const real = ['/usr/bin', '/bin'].map((p) => path.join(p, tool)).find((p) => fs.existsSync(p))
+ if (real) fs.symlinkSync(real, path.join(noCurl, tool))
+ }
+})
+
+afterAll(() => {
+ fs.rmSync(dir, { recursive: true, force: true })
+})
+
+/** Run the generated command in a sandboxed $HOME, with the fake curl first on PATH. */
+async function runCommand(
+ accountId: string | null,
+ opts: { curl?: boolean } = {}
+): Promise<string> {
+ const { stdout } = await run('/bin/sh', ['-c', remoteUsageCommand(accountId)], {
+ env: {
+ HOME: home,
+ // `command -v curl` genuinely fails on the no-curl PATH — the real branch, not a mock of it.
+ PATH: opts.curl === false ? path.join(dir, 'nocurl-bin') : `${bin}:${process.env.PATH ?? ''}`
+ }
+ })
+ return stdout
+}
+
+function writeCreds(dirPath: string, token: string, pretty = false): void {
+ fs.mkdirSync(dirPath, { recursive: true })
+ const body = { claudeAiOauth: { accessToken: token } }
+ fs.writeFileSync(
+ path.join(dirPath, '.credentials.json'),
+ pretty ? JSON.stringify(body, null, 2) : JSON.stringify(body)
+ )
+}
+
+describe('remoteUsageTargets', () => {
+ const accounts: ClaudeAccount[] = [
+ { id: 'acc-1', label: 'Work', host: 'root@alpha', createdAt: 0 },
+ { id: 'acc-2', label: 'Half-done', host: 'root@alpha', pending: true, createdAt: 0 },
+ { id: 'acc-3', label: 'Elsewhere', host: 'root@beta', createdAt: 0 },
+ { id: 'acc-4', label: 'Local', createdAt: 0 }
+ ]
+
+ it('offers the system account plus the host-matched managed ones', () => {
+ const t = remoteUsageTargets([{ projectId: 'p1', hostKey: 'root@alpha' }], accounts)
+ expect(t.map((x) => x.accountId)).toEqual([null, 'acc-1'])
+ expect(t[0].label).toBe('root@alpha')
+ expect(t[1].label).toBe('Work')
+ expect(t.every((x) => x.projectId === 'p1')).toBe(true)
+ })
+
+ it('reads a shared host once, through its first connected project', () => {
+ const t = remoteUsageTargets(
+ [
+ { projectId: 'p1', hostKey: 'root@alpha' },
+ { projectId: 'p2', hostKey: 'root@alpha' },
+ { projectId: 'p3', hostKey: 'root@beta' }
+ ],
+ accounts
+ )
+ expect(t.map((x) => x.key)).toEqual(['root@alpha#', 'root@alpha#acc-1', 'root@beta#', 'root@beta#acc-3'])
+ expect(t.find((x) => x.hostKey === 'root@alpha')?.projectId).toBe('p1')
+ })
+
+ it('has nothing to offer with no connections', () => {
+ expect(remoteUsageTargets([], accounts)).toEqual([])
+ })
+
+ it('refuses an account id that could escape the accounts root', () => {
+ const t = remoteUsageTargets(
+ [{ projectId: 'p1', hostKey: 'root@alpha' }],
+ [{ id: '../../.ssh', label: 'evil', host: 'root@alpha', createdAt: 0 }]
+ )
+ expect(t.map((x) => x.accountId)).toEqual([null])
+ })
+})
+
+describe('remoteUsageCommand', () => {
+ it('refuses a hostile account id at the interpolation site', () => {
+ expect(() => remoteUsageCommand('a"; rm -rf ~; #')).toThrow()
+ expect(() => remoteUsageCommand('../other')).toThrow()
+ })
+
+ it('reads the system account from ~/.claude and a managed one from its config dir', () => {
+ expect(remoteUsageCommand(null)).toContain('"$HOME/.claude/.credentials.json"')
+ expect(remoteUsageCommand('acc-1')).toContain(
+ '"$HOME/.nodeterm/claude-accounts/acc-1/.credentials.json"'
+ )
+ })
+
+ it('never puts the token on curl’s command line', () => {
+ // `-H "authorization: …"` would be visible in `ps` to every other user on the host.
+ expect(remoteUsageCommand(null)).toContain('--config -')
+ expect(remoteUsageCommand(null)).not.toMatch(/-H\s+["']?authorization/i)
+ })
+})
+
+describe('the generated command, run by /bin/sh', () => {
+ it('reads the system account and returns the usage payload', async () => {
+ writeCreds(path.join(home, '.claude'), 'tok-system')
+ fs.writeFileSync(
+ path.join(home, '.claude.json'),
+ JSON.stringify({ oauthAccount: { emailAddress: '[email protected]' } })
+ )
+ const out = parseRemoteUsageOutput(await runCommand(null))
+ expect(out.complete).toBe(true)
+ expect(out.reason).toBeNull()
+ expect(out.httpCode).toBe(200)
+ expect(out.email).toBe('[email protected]')
+ expect(JSON.parse(out.body).limits).toHaveLength(2)
+ // The token reached curl on STDIN and never through argv.
+ expect(fs.readFileSync(stdinLog(), 'utf-8')).toContain('Bearer tok-system')
+ expect(fs.readFileSync(argvLog(), 'utf-8')).not.toContain('tok-system')
+ })
+
+ it('takes the subscription token, not an MCP server’s', async () => {
+ // Found against a real credentials file: every MCP server the CLI has authorized keeps its
+ // own "accessToken" under `mcpOAuth`. Grabbing the first match in the file sends an MCP token
+ // to the usage endpoint, which answers 401 — so a perfectly signed-in host reported "not
+ // signed in". Both key orders, since the writer does not promise one.
+ for (const body of [
+ { mcpOAuth: { 'srv-a': { accessToken: 'tok-mcp' } }, claudeAiOauth: { accessToken: 'tok-real' } },
+ { claudeAiOauth: { accessToken: 'tok-real', scopes: ['user:inference'] }, mcpOAuth: { 'srv-a': { accessToken: 'tok-mcp' } } }
+ ]) {
+ fs.writeFileSync(path.join(home, '.claude', '.credentials.json'), JSON.stringify(body))
+ await runCommand(null)
+ const sent = fs.readFileSync(stdinLog(), 'utf-8')
+ expect(sent).toContain('Bearer tok-real')
+ expect(sent).not.toContain('tok-mcp')
+ }
+ })
+
+ it('still reads a flat top-level credentials shape', async () => {
+ // What `parseCreds` accepts as its fallback (`j.claudeAiOauth ?? j`) must work here too.
+ fs.writeFileSync(
+ path.join(home, '.claude', '.credentials.json'),
+ JSON.stringify({ accessToken: 'tok-flat', expiresAt: 1 })
+ )
+ await runCommand(null)
+ expect(fs.readFileSync(stdinLog(), 'utf-8')).toContain('Bearer tok-flat')
+ })
+
+ it('parses a pretty-printed credentials file', async () => {
+ writeCreds(path.join(home, '.claude'), 'tok-pretty', true)
+ await runCommand(null)
+ expect(fs.readFileSync(stdinLog(), 'utf-8')).toContain('Bearer tok-pretty')
+ })
+
+ it('reads a managed account from its own config dir', async () => {
+ const accDir = path.join(home, '.nodeterm', 'claude-accounts', 'acc-1')
+ writeCreds(accDir, 'tok-managed')
+ fs.writeFileSync(
+ path.join(accDir, '.claude.json'),
+ JSON.stringify({ oauthAccount: { emailAddress: '[email protected]' } })
+ )
+ const out = parseRemoteUsageOutput(await runCommand('acc-1'))
+ expect(out.email).toBe('[email protected]')
+ expect(fs.readFileSync(stdinLog(), 'utf-8')).toContain('Bearer tok-managed')
+ })
+
+ it('reports nocreds — without calling curl — when the account has never logged in', async () => {
+ const out = parseRemoteUsageOutput(await runCommand('acc-never'))
+ expect(out.complete).toBe(true)
+ expect(out.reason).toBe('nocreds')
+ expect(out.email).toBeNull()
+ })
+
+ it('reports nocurl on a host without curl', async () => {
+ writeCreds(path.join(home, '.claude'), 'tok-system')
+ const out = parseRemoteUsageOutput(await runCommand(null, { curl: false }))
+ expect(out.reason).toBe('nocurl')
+ })
+})
+
+describe('parseRemoteUsageOutput', () => {
+ it('discards everything outside the marker block', () => {
+ const out = parseRemoteUsageOutput(
+ ['Welcome to Ubuntu 22.04!', 'Last login: today', '__NTU_BEGIN__', '[email protected]', '{"limits":[]}', '__NTU_HTTP__200', '__NTU_END__', 'logout'].join('\n')
+ )
+ expect(out.complete).toBe(true)
+ expect(out.body).toBe('{"limits":[]}')
+ expect(out.email).toBe('[email protected]')
+ })
+
+ it('reports an incomplete run when the command never finished', () => {
+ const out = parseRemoteUsageOutput('__NTU_BEGIN__\[email protected]\n')
+ expect(out.complete).toBe(false)
+ })
+
+ it('is not fooled by empty output', () => {
+ expect(parseRemoteUsageOutput('').complete).toBe(false)
+ })
+})
+
+describe('fetchRemoteUsage', () => {
+ const target: RemoteUsageTarget = {
+ key: 'root@alpha#',
+ hostKey: 'root@alpha',
+ projectId: 'p1',
+ accountId: null,
+ label: 'root@alpha'
+ }
+ const reply = (...lines: string[]): string =>
+ ['__NTU_BEGIN__', ...lines, '__NTU_END__'].join('\n')
+
+ it('maps a 200 into limits', async () => {
+ const u = await fetchRemoteUsage(
+ target,
+ async () => reply('[email protected]', USAGE_BODY, '__NTU_HTTP__200'),
+ 1000
+ )
+ expect(u.status).toBe('ok')
+ expect(u.email).toBe('[email protected]')
+ expect(u.limits.map((l) => l.usedPercent)).toEqual([60, 12])
+ expect(u.session?.leftPercent).toBe(40)
+ })
+
+ it('treats a logged-out account as unavailable (hidden), not an error', async () => {
+ const u = await fetchRemoteUsage(target, async () => reply('__NTU_EMAIL__', '__NTU_STATUS__nocreds'), 1)
+ expect(u.status).toBe('unavailable')
+ })
+
+ it('treats an API-key / expired token (401) as unavailable', async () => {
+ const u = await fetchRemoteUsage(target, async () => reply('__NTU_EMAIL__', '{}', '__NTU_HTTP__401'), 1)
+ expect(u.status).toBe('unavailable')
+ })
+
+ it('keeps a broken read visible as an error', async () => {
+ const missingCurl = await fetchRemoteUsage(target, async () => reply('__NTU_STATUS__nocurl'), 1)
+ expect(missingCurl.status).toBe('error')
+ const http500 = await fetchRemoteUsage(target, async () => reply('oops', '__NTU_HTTP__500'), 1)
+ expect(http500.status).toBe('error')
+ const garbage = await fetchRemoteUsage(target, async () => reply('not json', '__NTU_HTTP__200'), 1)
+ expect(garbage.status).toBe('error')
+ })
+
+ it('never reports unavailable when the command could not run at all', async () => {
+ // A dead master / disconnected project says nothing about whether the account has a
+ // subscription — reporting 'unavailable' would silently drop the row from the popover.
+ expect((await fetchRemoteUsage(target, async () => null, 1)).status).toBe('error')
+ expect((await fetchRemoteUsage(target, async () => 'ssh: connect failed', 1)).status).toBe('error')
+ expect(
+ (
+ await fetchRemoteUsage(
+ target,
+ () => Promise.reject(new Error('master gone')),
+ 1
+ )
+ ).status
+ ).toBe('error')
+ })
+})
diff --git a/src/core/usage/remote-claude-usage.ts b/src/core/usage/remote-claude-usage.ts
new file mode 100644
index 000000000..adfcda2f2
--- /dev/null
+++ b/src/core/usage/remote-claude-usage.ts
@@ -0,0 +1,218 @@
+// Claude subscription usage for a REMOTE (SSH project) account, read over that project's
+// ControlMaster. v1 deliberately had none of this ("remote accounts are excluded"), so a user
+// whose Claude runs on a server saw an empty pill while the host had perfectly good numbers.
+//
+// **The token never leaves the host.** The desktop could `cat` the remote `.credentials.json`
+// and call the API itself — it already reads remote transcripts over the same master — but a
+// bearer token pulled off a (possibly shared) server into another machine's memory is a bigger
+// surface than any transcript read, and it buys nothing: the host can make the request itself.
+// So the remote shell reads its own credential file and curls the endpoint; we only ever see
+// the JSON answer. Two consequences the command below is built around:
+// - the token must not appear in the remote **argv** (`ps` is readable by other users on a
+// shared host), which is why it is piped into `curl --config -` instead of `-H`;
+// - the reply is marker-delimited, so shell/profile noise can never be parsed as usage
+// (same lesson as `claude-version-probe`).
+//
+// curl is a hard requirement, not a fallback-to-wget: the canvas-control and context-link shims
+// already require it on every host, and wget would put the token back on the command line.
+import type { ClaudeAccount, ClaudeUsage } from '../../shared/types'
+import { emptyUsage, usageFromPayload } from './claude-usage-map'
+
+/** Same shape of id every remote path builder validates against (see claude-accounts-core). */
+const ACCOUNT_ID_RE = /^[A-Za-z0-9_-]+$/
+
+const BEGIN = '__NTU_BEGIN__'
+const END = '__NTU_END__'
+const EMAIL = '__NTU_EMAIL__'
+const STATUS = '__NTU_STATUS__'
+const HTTP = '__NTU_HTTP__'
+
+/** How long the REMOTE curl may take. Below the ssh runner's own 15 s child timeout. */
+const REMOTE_CURL_TIMEOUT_S = 10
+
+/** One remote Claude identity the usage popover can show a row for. */
+export interface RemoteUsageTarget {
+ /** Stable row identity: `<hostKey>#<accountId ?? ''>`. Also the service's cache key. */
+ key: string
+ /** `user@host` of the connection — matches `ClaudeAccount.host`. */
+ hostKey: string
+ /** A connected SSH project on that host, whose ControlMaster carries the read. */
+ projectId: string
+ /** Managed remote account, or null for the host's system `~/.claude`. */
+ accountId: string | null
+ /** Display label: the account's own label, else the host key. */
+ label: string
+}
+
+/** Runs a POSIX sh command on the target's host; resolves its stdout, or null if it could not run. */
+export type RemoteUsageRunner = (
+ target: RemoteUsageTarget,
+ command: string
+) => Promise<string | null>
+
+/**
+ * The rows to offer, given every connected SSH project and the configured accounts.
+ *
+ * One host answers once: several projects can share a host (and share its `$HOME`), so the hosts
+ * are deduped and the first connected project is elected reader — a second read over a second
+ * master would return the same numbers at twice the cost. Each host contributes its system
+ * account (`~/.claude`, the common case: someone SSHes in and runs plain `claude`) plus every
+ * managed account pinned to that host. `pending` accounts have no credentials yet, so they are
+ * skipped exactly as the local popover skips them.
+ */
+export function remoteUsageTargets(
+ connected: readonly { projectId: string; hostKey: string }[],
+ accounts: readonly ClaudeAccount[]
+): RemoteUsageTarget[] {
+ const out: RemoteUsageTarget[] = []
+ const seen = new Set<string>()
+ for (const { projectId, hostKey } of connected) {
+ if (!hostKey || seen.has(hostKey)) continue
+ seen.add(hostKey)
+ out.push({ key: `${hostKey}#`, hostKey, projectId, accountId: null, label: hostKey })
+ for (const a of accounts) {
+ if (a.host !== hostKey || a.pending || !ACCOUNT_ID_RE.test(a.id)) continue
+ out.push({
+ key: `${hostKey}#${a.id}`,
+ hostKey,
+ projectId,
+ accountId: a.id,
+ label: a.label || a.id
+ })
+ }
+ }
+ return out
+}
+
+/**
+ * The remote sh command for one account's usage. `accountId` null = the host's system account.
+ *
+ * The two file paths mirror `usageCredsPaths`' file leg, rooted at the REMOTE `$HOME`: a managed
+ * account keeps both under its config dir (`remoteAccountConfigDir`), the system account splits
+ * them (`~/.claude/.credentials.json` + `~/.claude.json`). There is no keychain leg — a remote
+ * host is a Linux server in practice, and prompting a headless macOS host's Keychain over ssh
+ * would hang rather than answer.
+ *
+ * The account id is re-validated here even though the caller already filtered on it: this is an
+ * interpolation into a remote shell command, and the type system is compile-time only.
+ */
+export function remoteUsageCommand(accountId: string | null): string {
+ if (accountId !== null && !ACCOUNT_ID_RE.test(accountId)) {
+ throw new Error(`invalid account id: ${JSON.stringify(accountId)}`)
+ }
+ const credsFile = accountId
+ ? `"$HOME/.nodeterm/claude-accounts/${accountId}/.credentials.json"`
+ : '"$HOME/.claude/.credentials.json"'
+ const identityFile = accountId
+ ? `"$HOME/.nodeterm/claude-accounts/${accountId}/.claude.json"`
+ : '"$HOME/.claude.json"'
+ // `tr -d` first so a pretty-printed file parses too (grep is line-based, and the CLI's writer
+ // is not contractually single-line). `head -n 1` takes the first match: in `.claude.json` —
+ // large and full of unrelated history — the identity block is the one we want, and a later
+ // stray "emailAddress" must not win.
+ const firstString = (key: string): string =>
+ `grep -o '"${key}"[[:space:]]*:[[:space:]]*"[^"]*"' | head -n 1 | sed 's/.*"\\([^"]*\\)"$/\\1/'`
+ const flatten = (file: string): string => `tr -d '\\n\\r' < ${file} 2>/dev/null`
+ return [
+ `printf '%s\\n' '${BEGIN}'`,
+ // `.credentials.json` holds MORE than one "accessToken": every MCP server the CLI has
+ // authorized keeps its own under `mcpOAuth`. Taking the first match in the file hands the
+ // endpoint an MCP token, which answers 401 — i.e. the row reports "not signed in" on a host
+ // that is perfectly signed in. So narrow to the `claudeAiOauth` object first, exactly as the
+ // local `parseCreds` does (`j.claudeAiOauth ?? j`); a file without that key falls back to the
+ // whole text, which is the flat top-level shape parseCreds also accepts.
+ `c=$(${flatten(credsFile)})`,
+ `case "$c" in *claudeAiOauth*) c=\${c#*claudeAiOauth}; c=\${c%%\\}*};; esac`,
+ `t=$(printf '%s' "$c" | ${firstString('accessToken')})`,
+ `e=$(${flatten(identityFile)} | ${firstString('emailAddress')})`,
+ `printf '${EMAIL}%s\\n' "$e"`,
+ `if [ -z "$t" ]; then printf '${STATUS}nocreds\\n%s\\n' '${END}'; exit 0; fi`,
+ `if ! command -v curl >/dev/null 2>&1; then printf '${STATUS}nocurl\\n%s\\n' '${END}'; exit 0; fi`,
+ // The token goes in on stdin as a curl config directive — never in argv, where `ps` would
+ // hand it to every other user on the host.
+ `printf 'header = "authorization: Bearer %s"\\n' "$t" | ` +
+ `curl -sS -m ${REMOTE_CURL_TIMEOUT_S} --config - ` +
+ `-H 'anthropic-beta: oauth-2025-04-20' ` +
+ `-w '\\n${HTTP}%{http_code}\\n' ` +
+ `'https://api.anthropic.com/api/oauth/usage' 2>/dev/null`,
+ `printf '%s\\n' '${END}'`
+ ].join('; ')
+}
+
+export interface RemoteUsageOutput {
+ /** 'nocreds' | 'nocurl' when the remote short-circuited, else null. */
+ reason: string | null
+ email: string | null
+ /** HTTP status curl reported, or null when it never got that far. */
+ httpCode: number | null
+ /** The response body, with every marker line stripped. */
+ body: string
+ /** Did the command actually run to completion (both markers present)? */
+ complete: boolean
+}
+
+/**
+ * Split the marker-delimited reply. Anything outside BEGIN/END is discarded — an ssh banner, a
+ * host's MOTD or an rc-file warning is noise, and parsing it as JSON is how a "usage" row ends
+ * up reporting nonsense.
+ */
+export function parseRemoteUsageOutput(stdout: string): RemoteUsageOutput {
+ const start = stdout.indexOf(BEGIN)
+ const end = stdout.indexOf(END, start + 1)
+ const complete = start >= 0 && end > start
+ const inner = complete ? stdout.slice(start + BEGIN.length, end) : ''
+ let reason: string | null = null
+ let email: string | null = null
+ let httpCode: number | null = null
+ const bodyLines: string[] = []
+ for (const line of inner.split('\n')) {
+ if (line.startsWith(EMAIL)) {
+ const v = line.slice(EMAIL.length).trim()
+ email = v || null
+ } else if (line.startsWith(STATUS)) {
+ reason = line.slice(STATUS.length).trim() || null
+ } else if (line.startsWith(HTTP)) {
+ const n = Number(line.slice(HTTP.length).trim())
+ httpCode = Number.isFinite(n) && n > 0 ? n : null
+ } else {
+ bodyLines.push(line)
+ }
+ }
+ return { reason, email, httpCode, body: bodyLines.join('\n').trim(), complete }
+}
+
+/**
+ * One target's snapshot. Fails soft in every direction — this is an informational pill, and a
+ * host that is mid-reconnect, missing curl, or logged out must degrade to a quiet row rather
+ * than an error the user has to dismiss.
+ *
+ * Status mapping mirrors the local fetch: no credentials or a 401/403 means "nothing to show
+ * for this identity" ('unavailable', which the UI hides), while a reachable-but-broken read
+ * ('error') stays visible — a configured account whose numbers stopped arriving is information.
+ */
+export async function fetchRemoteUsage(
+ target: RemoteUsageTarget,
+ run: RemoteUsageRunner,
+ now: number
+): Promise<ClaudeUsage> {
+ let stdout: string | null = null
+ try {
+ stdout = await run(target, remoteUsageCommand(target.accountId))
+ } catch {
+ return emptyUsage(null, now, 'error')
+ }
+ if (stdout === null) return emptyUsage(null, now, 'error')
+ const out = parseRemoteUsageOutput(stdout)
+ // The command never ran (master down, project disconnected mid-read): not evidence that this
+ // account has no subscription, so it must not report 'unavailable' and vanish from the popover.
+ if (!out.complete) return emptyUsage(out.email, now, 'error')
+ if (out.reason === 'nocreds') return emptyUsage(out.email, now, 'unavailable')
+ if (out.reason) return emptyUsage(out.email, now, 'error')
+ if (out.httpCode === 401 || out.httpCode === 403) return emptyUsage(out.email, now, 'unavailable')
+ if (out.httpCode !== 200 || !out.body) return emptyUsage(out.email, now, 'error')
+ try {
+ return usageFromPayload(JSON.parse(out.body), out.email, now)
+ } catch {
+ return emptyUsage(out.email, now, 'error')
+ }
+}
diff --git a/src/core/usage/usage-service.remote.test.ts b/src/core/usage/usage-service.remote.test.ts
new file mode 100644
index 000000000..f8181fd4d
--- /dev/null
+++ b/src/core/usage/usage-service.remote.test.ts
@@ -0,0 +1,126 @@
+// The `usage:remote` RPC surface: caching, invalidation and failure containment. The command
+// itself is covered in remote-claude-usage.test.ts; this is about what the service does with it,
+// because a popover row is only as good as the cache behind it — a stale row from a host that
+// disconnected an hour ago is worse than no row at all.
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { IPC } from '../../shared/ipc'
+import { initPlatform, resetPlatformForTests } from '../platform'
+import { fakePlatform, type FakePlatform } from '../platform-fake'
+import { startUsageService, type RemoteUsageDeps, type UsageService } from './usage-service'
+import type { RemoteAccountUsage } from '../../shared/types'
+import type { RemoteUsageTarget } from './remote-claude-usage'
+
+const OK_REPLY = [
+ '__NTU_BEGIN__',
+ JSON.stringify({ limits: [{ kind: 'session', group: 'session', percent: 60 }] }),
+ '__NTU_HTTP__200',
+ '__NTU_END__'
+].join('\n')
+
+function target(hostKey: string, accountId: string | null = null): RemoteUsageTarget {
+ return {
+ key: `${hostKey}#${accountId ?? ''}`,
+ hostKey,
+ projectId: 'p1',
+ accountId,
+ label: accountId ?? hostKey
+ }
+}
+
+let platform: FakePlatform
+let service: UsageService | undefined
+
+beforeEach(() => {
+ resetPlatformForTests()
+ platform = fakePlatform()
+ initPlatform(platform)
+})
+
+afterEach(() => {
+ service?.dispose()
+ service = undefined
+ resetPlatformForTests()
+ vi.useRealTimers()
+})
+
+/** Start the service with the poll gate shut, so nothing but the remote path is exercised. */
+function start(remote?: RemoteUsageDeps): void {
+ service = startUsageService({ shouldPoll: () => false, remote })
+}
+
+const callRemote = (force?: boolean): Promise<RemoteAccountUsage[]> =>
+ platform.handlers[IPC.usageRemote](force) as Promise<RemoteAccountUsage[]>
+
+describe('usage:remote', () => {
+ it('answers empty — never rejects — on a shell with no SSH deps', async () => {
+ start()
+ // This is the Server Edition's permanent answer, so the UI needs no capability check.
+ await expect(callRemote()).resolves.toEqual([])
+ })
+
+ it('reads each target and labels the rows by host', async () => {
+ const run = vi.fn(async () => OK_REPLY)
+ start({ targets: () => [target('root@alpha'), target('root@alpha', 'acc-1')], run })
+ const rows = await callRemote()
+ expect(rows.map((r) => r.accountId)).toEqual([null, 'acc-1'])
+ expect(rows[0].hostKey).toBe('root@alpha')
+ expect(rows[0].usage.limits[0].usedPercent).toBe(60)
+ expect(run).toHaveBeenCalledTimes(2)
+ })
+
+ it('serves a repeat call from cache, and re-reads on force', async () => {
+ const run = vi.fn(async () => OK_REPLY)
+ start({ targets: () => [target('root@alpha')], run })
+ await callRemote()
+ await callRemote()
+ expect(run).toHaveBeenCalledTimes(1)
+ await callRemote(true)
+ expect(run).toHaveBeenCalledTimes(2)
+ })
+
+ it('retires a host that has disconnected instead of serving its last numbers', async () => {
+ const run = vi.fn(async () => OK_REPLY)
+ let connected = [target('root@alpha')]
+ start({ targets: () => connected, run })
+ expect(await callRemote()).toHaveLength(1)
+ connected = []
+ expect(await callRemote()).toEqual([])
+ // Reconnecting must produce a FRESH read — the evicted entry cannot come back from the cache.
+ connected = [target('root@alpha')]
+ await callRemote()
+ expect(run).toHaveBeenCalledTimes(2)
+ })
+
+ it('coalesces concurrent reads of the same target into one ssh round-trip', async () => {
+ let resolveRun: ((v: string) => void) | undefined
+ const run = vi.fn(() => new Promise<string>((res) => (resolveRun = res)))
+ start({ targets: () => [target('root@alpha')], run })
+ const both = Promise.all([callRemote(), callRemote()])
+ resolveRun?.(OK_REPLY)
+ const [a, b] = await both
+ expect(run).toHaveBeenCalledTimes(1)
+ expect(a[0].usage.status).toBe('ok')
+ expect(b[0].usage.status).toBe('ok')
+ })
+
+ it('does not let one unreachable host withhold the others', async () => {
+ const run = vi.fn(async (t: RemoteUsageTarget) => {
+ if (t.hostKey === 'root@beta') throw new Error('master gone')
+ return OK_REPLY
+ })
+ start({ targets: () => [target('root@alpha'), target('root@beta')], run })
+ const rows = await callRemote()
+ expect(rows.map((r) => r.usage.status)).toEqual(['ok', 'error'])
+ })
+
+ it('survives a throwing target provider', async () => {
+ start({
+ targets: () => {
+ throw new Error('settings blew up')
+ },
+ run: async () => OK_REPLY
+ })
+ await expect(callRemote()).resolves.toEqual([])
+ })
+})
diff --git a/src/core/usage/usage-service.ts b/src/core/usage/usage-service.ts
index eb6956bdf..1535cfbad 100644
--- a/src/core/usage/usage-service.ts
+++ b/src/core/usage/usage-service.ts
@@ -13,12 +13,15 @@ import { promisify } from 'util'
import { IPC } from '../../shared/ipc'
import type {
ClaudeUsage,
- ClaudeUsageWindow,
ProviderUsage,
- UsageLimit
+ RemoteAccountUsage
} from '../../shared/types'
-import { findLimit } from '../../shared/usage-limits'
-import { mapUsageLimits } from './claude-usage-map'
+import { emptyUsage, usageFromPayload } from './claude-usage-map'
+import {
+ fetchRemoteUsage,
+ type RemoteUsageRunner,
+ type RemoteUsageTarget
+} from './remote-claude-usage'
import { fetchCodexUsage } from './codex-usage'
import { fetchGeminiUsage } from './gemini-usage'
import { fetchGrokUsage } from './grok-usage'
@@ -147,16 +150,6 @@ export async function resolveClaudeAccessToken(accountId?: string): Promise<stri
return (await resolveCreds(accountId)).accessToken
}
-/** Back-compat view of one limit as the old remaining-percent window. */
-function asWindow(limit: UsageLimit | null): ClaudeUsageWindow | null {
- if (!limit) return null
- return { leftPercent: 100 - limit.usedPercent, resetsAt: limit.resetsAt }
-}
-
-function emptyUsage(email: string | null, now: number, status: ClaudeUsage['status']): ClaudeUsage {
- return { limits: [], session: null, weekly: null, email, updatedAt: now, status }
-}
-
export async function fetchUsage(accountId?: string): Promise<ClaudeUsage> {
const now = Date.now()
const { accessToken, email } = await resolveCreds(accountId)
@@ -175,15 +168,7 @@ export async function fetchUsage(accountId?: string): Promise<ClaudeUsage> {
return emptyUsage(email, now, status)
}
const data = (await res.json()) as Record<string, any>
- const limits = mapUsageLimits(data)
- return {
- limits,
- session: asWindow(findLimit(limits, 'session')),
- weekly: asWindow(findLimit(limits, 'weekly_all')),
- email,
- updatedAt: now,
- status: 'ok'
- }
+ return usageFromPayload(data, email, now)
} catch {
return emptyUsage(email, now, 'error')
}
@@ -210,6 +195,21 @@ export interface UsageServiceOptions {
* phone-facing `usage` block refreshes when a poll lands. Best-effort; must never throw.
*/
onCacheUpdate?: () => void
+ /**
+ * Claude accounts living on the hosts of connected SSH projects. Injected the same way Context
+ * Link takes its remote deps: core owns the command + the parsing, the shell owns the
+ * ControlMaster. Absent ⇒ `usage:remote` answers `[]` — which is exactly right for the Server
+ * Edition (no SSH projects there) and needs no capability check in the UI.
+ */
+ remote?: RemoteUsageDeps
+}
+
+export interface RemoteUsageDeps {
+ /** The rows to offer right now (see `remoteUsageTargets`). Re-read per request — projects
+ * connect and disconnect under us. Must never throw. */
+ targets: () => RemoteUsageTarget[]
+ /** Run a POSIX sh command on that target's host; null when it could not run. */
+ run: RemoteUsageRunner
}
export interface UsageService {
@@ -340,6 +340,58 @@ export function startUsageService(opts: UsageServiceOptions = {}): UsageService
return runProviders()
})
+ // Remote (SSH host) Claude accounts. Cached per target under the same debounce and, like the
+ // providers above, fetched ON DEMAND rather than polled: each row costs an ssh exec plus an
+ // HTTPS request made on someone else's machine, and the pill is informational. The renderer
+ // asks on mount, when the popover opens, and whenever the set of connected projects changes.
+ const remoteCache = new Map<string, { at: number; usage: ClaudeUsage }>()
+ const remoteInFlight = new Map<string, Promise<ClaudeUsage>>()
+
+ const runRemote = async (
+ deps: RemoteUsageDeps,
+ target: RemoteUsageTarget
+ ): Promise<ClaudeUsage> => {
+ const pending = remoteInFlight.get(target.key)
+ if (pending) return pending
+ const p = fetchRemoteUsage(target, deps.run, Date.now())
+ remoteInFlight.set(target.key, p)
+ try {
+ const u = await p
+ remoteCache.set(target.key, { at: Date.now(), usage: u })
+ return u
+ } finally {
+ remoteInFlight.delete(target.key)
+ }
+ }
+
+ platform().handle(IPC.usageRemote, async (force?: boolean): Promise<RemoteAccountUsage[]> => {
+ const deps = opts.remote
+ if (!deps) return []
+ let targets: RemoteUsageTarget[] = []
+ try {
+ targets = 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))
+ for (const key of [...remoteCache.keys()]) if (!live.has(key)) remoteCache.delete(key)
+ // One slow / unreachable host must not withhold the others.
+ const rows = await Promise.all(
+ targets.map(async (t): Promise<RemoteAccountUsage> => {
+ const cached = remoteCache.get(t.key)
+ const fresh = cached && Date.now() - cached.at < REFETCH_DEBOUNCE_MS
+ const usage =
+ !force && fresh
+ ? cached.usage
+ : await runRemote(deps, t).catch(() => emptyUsage(null, Date.now(), 'error'))
+ return { hostKey: t.hostKey, accountId: t.accountId, label: t.label, usage }
+ })
+ )
+ return rows
+ })
+
// Poll the system account AND every local managed account (spec: mobile-usage-inbox), so the
// agent-status mirror can advertise per-account usage to the phone — not just the collapsed chip's
// system row. Each account is one request per cadence; the request-budget gate (`shouldPoll`)
diff --git a/src/main/claude-usage.ts b/src/main/claude-usage.ts
index 9bed18b67..559a44851 100644
--- a/src/main/claude-usage.ts
+++ b/src/main/claude-usage.ts
@@ -3,15 +3,22 @@
// the Server Edition boots the same code. All that is left here is the one thing core cannot
// know: whether a desktop window is focused.
import type { BrowserWindow } from 'electron'
-import { startUsageService, type UsageService } from '../core/usage/usage-service'
+import {
+ startUsageService,
+ type RemoteUsageDeps,
+ type UsageService
+} from '../core/usage/usage-service'
export { resolveClaudeAccessToken } from '../core/usage/usage-service'
/** Extra usage-service wiring the shell owns: the local managed accounts to poll for the mobile
- * `usage` mirror block, and the mirror-flush callback fired on every cache update. */
+ * `usage` mirror block, the mirror-flush callback fired on every cache update, and the SSH
+ * ControlMaster access remote-host usage is read over (desktop-only — the Server Edition has no
+ * SSH projects, so it passes none and `usage:remote` answers empty). */
export interface InitClaudeUsageOpts {
localAccounts?: () => string[]
onCacheUpdate?: () => void
+ remote?: RemoteUsageDeps
}
/** Start the usage service on the focused-window poll gate and return it, so the caller can wire
@@ -22,7 +29,8 @@ export function initClaudeUsage(win: BrowserWindow, opts: InitClaudeUsageOpts =
const service = startUsageService({
shouldPoll: () => win.isFocused(),
localAccounts: opts.localAccounts,
- onCacheUpdate: opts.onCacheUpdate
+ onCacheUpdate: opts.onCacheUpdate,
+ remote: opts.remote
})
const onFocus = (): void => service.refreshIfStale()
diff --git a/src/main/index.ts b/src/main/index.ts
index d9bec6aab..7b99554d6 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -88,6 +88,7 @@ import { initCanvasControl, installCanvasSkillInto } from './canvas-control'
import { initTranscriptIndex, searchTranscripts } from '../core/transcript-index'
import { initTelemetry } from './telemetry'
import { initClaudeUsage } from './claude-usage'
+import { remoteUsageTargets } from '../core/usage/remote-claude-usage'
import { initLicense, isPremium, getStoredEntitlement } from '../core/license'
import { WhisperModelStore } from '../core/speech/whisper-models'
import { SpeechService } from '../core/speech/speech-service'
@@ -1499,6 +1500,30 @@ app.whenReady().then(async () => {
localAccounts: localClaudeAccountIds,
onCacheUpdate: () => {
void flushAgentStatusMirror()
+ },
+ // Remote (SSH host) Claude usage. Same shape as the Context Link remote deps: core owns the
+ // command and the parsing, main owns the ControlMaster. `sshProjectManager` is assigned just
+ // below, so both closures read it lazily — they only ever run after a project has connected.
+ remote: {
+ targets: () =>
+ remoteUsageTargets(
+ sshProjectManager?.connectedHosts() ?? [],
+ settingsStore.get().claudeAccounts ?? []
+ ),
+ run: async (target, command) => {
+ const mgr = sshProjectManager
+ const ref = mgr?.refForProject(target.projectId)
+ if (!mgr || !ref) return null
+ try {
+ const { stdout } = await mgr.sshRun(childArgs(ref.conn, ref.controlPath, command))
+ // Deliberately not gated on the exit code: the remote script exits 0 on its own
+ // short-circuits but curl's exit status rides through on a network failure, and the
+ // marker block is what says whether the read completed.
+ return stdout
+ } catch {
+ return null
+ }
+ }
}
})
setMirrorUsageProvider(() =>
diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.ts
index b2eabf55e..f2af9848e 100644
--- a/src/main/remote-ssh/ssh-project.ts
+++ b/src/main/remote-ssh/ssh-project.ts
@@ -596,6 +596,19 @@ export class SshProjectManager {
return this.conns.get(projectId)?.claudeAutoPermissionMode
}
+ /**
+ * Every LIVE connection as `{ projectId, hostKey }`. Feeds the remote-usage target list, which
+ * needs both halves: the host key to match accounts against, and a project whose ControlMaster
+ * can carry the read. Hosts shared by several projects are deduped by the caller
+ * (`remoteUsageTargets`), not here — this is the raw map.
+ */
+ connectedHosts(): { projectId: string; hostKey: string }[] {
+ return [...this.conns.entries()].map(([projectId, c]) => ({
+ projectId,
+ hostKey: sshHostKey(c.conn)
+ }))
+ }
+
/** `user@host` key of a connected project (matches ClaudeAccount.host). */
hostKeyFor(projectId: string): string | undefined {
const c = this.conns.get(projectId)
diff --git a/src/preload/index.ts b/src/preload/index.ts
index b4d1c2a4a..ea3f7c7d0 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -333,6 +333,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),
setProviderCookie: (provider: string, cookie: string) =>
ipcRenderer.invoke(IPC.usageSetProviderCookie, provider, cookie),
cookieProviders: () => ipcRenderer.invoke(IPC.usageCookieProviders),
diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.ts
index 4f44c1591..4448c4ff7 100644
--- a/src/renderer/bridge/stubs.ts
+++ b/src/renderer/bridge/stubs.ts
@@ -232,6 +232,9 @@ export function buildStubApi(): Omit<
// Empty, not a reject: "no providers configured" is a real answer and the popover
// renders it as nothing. This one needs no cast — the honest type already fits.
providers: () => Promise.resolve([]),
+ // Same reasoning as `providers`: "no connected SSH hosts" is a real answer, and it is the
+ // permanently correct one on a shell with no SSH projects.
+ remote: () => Promise.resolve([]),
setProviderCookie: U('usage.setProviderCookie'),
cookieProviders: () => Promise.resolve({}),
onUpdate: noopUnsub
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index 335f28d0e..5c24c8359 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -32,6 +32,7 @@ import {
type SettingsApi,
type ClaudeUsage,
type ProviderUsage,
+ type RemoteAccountUsage,
type Settings,
type SpeechApi,
type SpeechModelInfo,
@@ -531,6 +532,11 @@ function buildUsageApi(client: RpcClient): Pick<NodeTerminalApi, 'usage'> {
client.request(IPC.usageRefresh, accountId) as Promise<ClaudeUsage>,
providers: (force?: boolean) =>
client.request(IPC.usageProviders, force) as Promise<ProviderUsage[]>,
+ // 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[]>,
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 c8445f35e..7dfae2a75 100644
--- a/src/renderer/components/UsageIndicator.tsx
+++ b/src/renderer/components/UsageIndicator.tsx
@@ -1,7 +1,8 @@
import { useEffect, useMemo, useRef, useState } from 'react'
-import type { ClaudeUsage, ProviderUsage, UsageLimit } from '@shared/types'
+import type { ClaudeUsage, ProviderUsage, RemoteAccountUsage, UsageLimit } from '@shared/types'
import { AGENT_CONFIG } from '@shared/agents/config'
import { useSettings } from '../state/settings'
+import { useSshConn } from '../state/sshConn'
import { formatResetCountdown, formatTimeAgo, percentNumber, percentText, severityColor } from '../lib/usageFormat'
import {
enabledProviders,
@@ -10,7 +11,8 @@ import {
limitLabel,
limitShortLabel,
primaryLimit,
- providerLabel
+ providerLabel,
+ remotePillSegments
} from '@shared/usage-limits'
import { systemAccountDisplay } from '../state/workspace'
@@ -69,6 +71,39 @@ function AccountUsageBlock({
)
}
+/**
+ * One SSH host's Claude identity. Carries the host explicitly: the same subscription can be
+ * logged in on the desktop and on two servers, and a row that only said "Claude" would be
+ * indistinguishable from the local one sitting right above it.
+ *
+ * An 'unavailable' row is dropped exactly like an unused provider — a host where nobody has run
+ * `claude` has nothing to report, and listing it would turn "connect an SSH project" into "grow
+ * a permanent empty section".
+ */
+function RemoteUsageBlock({ row, mode }: { row: RemoteAccountUsage; mode: 'used' | 'remaining' }) {
+ if (row.usage.status === 'unavailable') return null
+ const showHost = row.label !== row.hostKey
+ return (
+ <div className="usage-account">
+ <div className="usage-account__label">
+ {row.label}
+ <span className="usage-account__host" title={`Read on ${row.hostKey} over SSH`}>
+ {showHost ? row.hostKey : 'SSH'}
+ </span>
+ </div>
+ {row.usage.email && <div className="usage-account__email">{row.usage.email}</div>}
+ {row.usage.limits.map((l) => (
+ <LimitRow key={limitKey(l)} limit={l} mode={mode} />
+ ))}
+ {row.usage.limits.length === 0 && (
+ <div className="usage-popover__empty">
+ {row.usage.status === 'error' ? 'Could not read usage on this host.' : 'No usage data.'}
+ </div>
+ )}
+ </div>
+ )
+}
+
/**
* One non-Claude provider's section in the popover. Providers that aren't signed in report
* 'unavailable' and are skipped entirely — showing an empty Codex row to someone who has never
@@ -112,6 +147,7 @@ export function UsageIndicator({ overBoard = false }: { overBoard?: boolean }):
const [refreshing, setRefreshing] = useState(false)
const [acctUsage, setAcctUsage] = useState<Record<string, ClaudeUsage | null>>({})
const [providers, setProviders] = useState<ProviderUsage[]>([])
+ const [remote, setRemote] = useState<RemoteAccountUsage[]>([])
const popRef = useRef<HTMLDivElement>(null)
const claudeAccounts = useSettings((s) => s.settings.claudeAccounts)
@@ -144,6 +180,26 @@ 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
+ // 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.
+ useEffect(() => {
+ let cancelled = false
+ void window.nodeTerminal.usage.remote().then((rows) => {
+ if (!cancelled) setRemote(rows)
+ })
+ return () => {
+ cancelled = true
+ }
+ }, [open, sshProjectKey])
+
// Fetch each account's usage on demand when the popover opens (system row uses `usage`).
useEffect(() => {
if (!open || accounts.length === 0) return
@@ -173,29 +229,46 @@ export function UsageIndicator({ overBoard = false }: { overBoard?: boolean }):
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
// 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)
- if (!hasAnyUsage(claudeUsage, visibleProviders)) return null
+ 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
+ const hasData = limits.length > 0 || enabled.length > 0 || remoteSegments.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.
- const primary = primaryLimit([...limits, ...enabled.flatMap((p) => p.limits)])
+ // 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)
+ ])
const refresh = async (e: React.MouseEvent): Promise<void> => {
e.stopPropagation()
if (refreshing) return
setRefreshing(true)
try {
- setUsage(await window.nodeTerminal.usage.refresh())
+ // 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)
} finally {
setRefreshing(false)
}
@@ -242,6 +315,18 @@ 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>}
</>
)
@@ -291,6 +376,11 @@ export function UsageIndicator({ overBoard = false }: { overBoard?: boolean }):
)}
</>
)}
+ {/* Remote hosts sit between the local Claude rows and the other providers: they are
+ still Claude, just read somewhere else. */}
+ {visibleRemote.map((r) => (
+ <RemoteUsageBlock key={`${r.hostKey}#${r.accountId ?? ''}`} row={r} mode={percentMode} />
+ ))}
{visibleProviders.map((p) => (
<ProviderBlock key={p.provider} u={p} mode={percentMode} />
))}
diff --git a/src/renderer/components/settings/sections/UsageSection.tsx b/src/renderer/components/settings/sections/UsageSection.tsx
index 5f3456150..c36b9b704 100644
--- a/src/renderer/components/settings/sections/UsageSection.tsx
+++ b/src/renderer/components/settings/sections/UsageSection.tsx
@@ -23,6 +23,9 @@ const ROWS = {
'hide',
'toggle',
'claude',
+ 'remote',
+ 'ssh',
+ 'host',
'codex',
'gemini',
'grok',
@@ -48,6 +51,8 @@ function labelFor(provider: string): string {
const PROVIDER_BLURBS: Record<string, string> = {
claude: 'Session, weekly and per-model limits from your Claude subscription.',
+ 'claude-remote':
+ "Limits for the Claude accounts on your connected SSH projects' hosts. Each read runs on the host itself over the existing connection — the credential never leaves it.",
codex: 'Session and weekly limits from your ChatGPT (Codex) subscription.',
gemini: 'Per-model hourly quota from the Gemini CLI sign-in.',
grok: 'Weekly credits and monthly budget from the Grok CLI sign-in.',
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index 4cb94532d..13b108932 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -5097,6 +5097,18 @@ body,
color: rgba(255, 255, 255, 0.45);
margin-bottom: 4px;
}
+/* Host chip on a remote (SSH) account row — the same email can be signed in on several
+ machines, so the row has to say WHERE these numbers came from. */
+.usage-account__host {
+ margin-left: 6px;
+ padding: 1px 5px;
+ border-radius: 4px;
+ font-size: 10px;
+ letter-spacing: 0.02em;
+ color: rgba(255, 255, 255, 0.55);
+ background: rgba(255, 255, 255, 0.08);
+ vertical-align: middle;
+}
/* ---- Claude context-window meter (per-node header pill + popover) ---- */
.ctx-meter {
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index dcecb8e6c..0ff49d857 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -105,6 +105,9 @@ export const IPC = {
usageUpdate: 'usage:update',
/** Non-Claude providers (codex, …) as one list; Claude keeps its own account-aware channels. */
usageProviders: 'usage:providers',
+ /** Claude usage for the connected SSH hosts' accounts, read ON those hosts over their
+ * ControlMasters. Empty on a shell without SSH projects. */
+ usageRemote: 'usage:remote',
/** Store/clear a provider's browser cookie (minimax, opencode). Write-only: no channel reads
* it back. */
usageSetProviderCookie: 'usage:set-provider-cookie',
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 9dbd58376..b627087a3 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -1253,6 +1253,22 @@ export interface ClaudeUsage {
status: 'unavailable' | 'fetching' | 'ok' | 'error'
}
+/**
+ * One REMOTE (SSH host) Claude identity's usage, read on that host over the project's
+ * ControlMaster. Separate from the local per-account rows because the identity is only
+ * meaningful together with the host it lives on — the same email can be logged in on two
+ * machines with two different quotas in flight.
+ */
+export interface RemoteAccountUsage {
+ /** `user@host` of the connection the numbers came from. */
+ hostKey: string
+ /** Managed remote account id, or null for that host's system `~/.claude`. */
+ accountId: string | null
+ /** Display label: the managed account's label, else the host key. */
+ label: string
+ usage: ClaudeUsage
+}
+
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). */
@@ -1263,6 +1279,11 @@ 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[]>
/** 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 e304fddef..736b42804 100644
--- a/src/shared/usage-limits.test.ts
+++ b/src/shared/usage-limits.test.ts
@@ -7,9 +7,11 @@ import {
limitKey,
enabledProviders,
hasAnyUsage,
- providerLabel
+ providerLabel,
+ remotePillSegments,
+ shortHostLabel
} from './usage-limits'
-import type { ProviderUsage, UsageLimit } from './types'
+import type { ProviderUsage, RemoteAccountUsage, UsageLimit } from './types'
function limit(over: Partial<UsageLimit>): UsageLimit {
return {
@@ -138,6 +140,74 @@ describe('hasAnyUsage', () => {
})
})
+function remoteRow(over: Partial<RemoteAccountUsage> & { limits?: UsageLimit[] } = {}): RemoteAccountUsage {
+ const { limits = [], ...rest } = over
+ return {
+ hostKey: '[email protected]',
+ accountId: null,
+ label: '[email protected]',
+ usage: {
+ limits,
+ session: null,
+ weekly: null,
+ email: null,
+ updatedAt: 0,
+ status: limits.length ? 'ok' : 'unavailable'
+ },
+ ...rest
+ }
+}
+
+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)
+ })
+
+ it('keeps a failing host visible rather than flapping', () => {
+ const broken = remoteRow()
+ broken.usage.status = 'error'
+ expect(hasAnyUsage(null, [], [broken])).toBe(true)
+ })
+
+ it('stays hidden when no host has anything to say', () => {
+ expect(hasAnyUsage({ status: 'unavailable' }, [], [remoteRow()])).toBe(false)
+ })
+})
+
describe('providerLabel', () => {
it('prefers a builtin agent label', () => {
expect(providerLabel('codex', 'Codex')).toBe('Codex')
diff --git a/src/shared/usage-limits.ts b/src/shared/usage-limits.ts
index d9754fc87..16244fc1e 100644
--- a/src/shared/usage-limits.ts
+++ b/src/shared/usage-limits.ts
@@ -3,7 +3,7 @@
//
// The parsing that produces `UsageLimit[]` from a raw provider payload is service-side and
// lives in core/usage — only the vocabulary lives here.
-import type { ProviderUsage, UsageLimit } from './types'
+import type { ProviderUsage, RemoteAccountUsage, UsageLimit } from './types'
/**
* Human label for a limit. A scoped limit is named by its model ("Fable"); everything else
@@ -72,19 +72,67 @@ export function enabledProviders(providers: ProviderUsage[]): ProviderUsage[] {
*/
export function hasAnyUsage(
claude: { status: string } | null | undefined,
- providers: ProviderUsage[]
+ providers: ProviderUsage[],
+ remote: readonly RemoteAccountUsage[] = []
): boolean {
if (claude && (claude.status === 'ok' || claude.status === 'error')) return true
- return enabledProviders(providers).length > 0
+ if (enabledProviders(providers).length > 0) return true
+ // A remote row counts for the same reason a local Claude one does — and it is the whole point
+ // of remote usage: someone whose Claude only ever runs on a server had no indicator at all.
+ return remote.some((r) => r.usage.status === 'ok' || r.usage.status === 'error')
}
/**
- * Every usage provider the app can read, in display order — Claude first (the primary agent),
- * then the rest alphabetically. The Settings toggles iterate this, so a new provider gets its
- * on/off switch by being added here.
+ * 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
+}
+
+/**
+ * Every usage source the app can read, in display order — Claude first (the primary agent) with
+ * its SSH-host variant beside it, then the rest alphabetically. The Settings toggles iterate
+ * this, so a new provider gets its on/off switch by being added here.
+ *
+ * `claude-remote` is not a provider but a SOURCE of Claude usage (the accounts on connected SSH
+ * hosts). It gets its own switch because the cost profile differs: those rows are read over an
+ * ssh round-trip on someone else's machine, so wanting Claude usage without them is a reasonable
+ * position — and the local toggle must not silently take remote hosts down with it.
*/
export const USAGE_PROVIDER_IDS = [
'claude',
+ 'claude-remote',
'codex',
'gemini',
'grok',
@@ -99,6 +147,7 @@ export const USAGE_PROVIDER_IDS = [
* entry to borrow a label from.
*/
const PROVIDER_LABELS: Record<string, string> = {
+ 'claude-remote': 'Claude on SSH hosts',
grok: 'Grok',
kimi: 'Kimi',
minimax: 'MiniMax',