Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
refactor(usage): move the usage service into core so Server Edition serves it (#7)
eneskirca06b4f1af9db2
diff --git a/src/core/usage/usage-service.ts b/src/core/usage/usage-service.tsnew file mode 100644index 000000000..30e3afaad--- /dev/null+++ b/src/core/usage/usage-service.ts@@ -0,0 +1,243 @@+// Claude Code subscription usage: credential resolution, the OAuth fetch, the per-account cache,+// and the RPC surface. Lives in core so BOTH shells serve it — the Server Edition previously had+// no usage at all (the browser bridge answered `null`), because every line of this was welded to+// Electron's ipcMain + BrowserWindow.+//+// Display-only: we read credentials, never write or refresh them. Rotating a refresh token here+// would log out whatever CLI session owns it.+import { promises as fs } from 'fs'+import os from 'os'+import path from 'path'+import { execFile } from 'child_process'+import { promisify } from 'util'+import { IPC } from '../../shared/ipc'+import type { ClaudeUsage, ClaudeUsageWindow, UsageLimit } from '../../shared/types'+import { findLimit } from '../../shared/usage-limits'+import { mapUsageLimits } from './claude-usage-map'+import { usageCredsPaths } from '../claude-accounts-core'+import { claudeConfigDirFor } from '../claude-config-dir'+import { platform } from '../platform'++const execFileP = promisify(execFile)++const USAGE_URL = 'https://api.anthropic.com/api/oauth/usage'+const OAUTH_BETA = 'oauth-2025-04-20'+const FETCH_TIMEOUT_MS = 8000+const POLL_MS = 15 * 60 * 1000+/** Also the cache TTL for `usage.fetch` — a repeat call inside this window is served from cache. */+const REFETCH_DEBOUNCE_MS = 5 * 60 * 1000++interface OAuthCreds {+ accessToken: string | null+ email: string | null+}++/** Parse a credentials JSON blob; tokens may sit at top level or under `claudeAiOauth`. */+export function parseCreds(raw: string): OAuthCreds {+ try {+ const j = JSON.parse(raw) as Record<string, any>+ const o = (j.claudeAiOauth ?? j) as Record<string, any>+ const accessToken = typeof o.accessToken === 'string' ? o.accessToken : null+ const email =+ (typeof o.email === 'string' && o.email) ||+ (typeof o.emailAddress === 'string' && o.emailAddress) ||+ null+ return { accessToken, email }+ } catch {+ return { accessToken: null, email: null }+ }+}++/**+ * macOS Keychain → {config}/.credentials.json → email backfill from {config}/.claude.json.+ * With an `accountId` the config dir is the managed account's isolated dir (scoped Keychain+ * service first); without, it's exactly the system default (`~/.claude`, unscoped services).+ *+ * The Keychain leg is darwin-only by construction — on the Server Edition's Linux host the+ * `security` binary does not exist, so the file leg is the whole story there.+ */+async function resolveCreds(accountId?: string): Promise<OAuthCreds> {+ const configDir = accountId ? claudeConfigDirFor(accountId) : undefined+ const { services, credsFile, identityFile } = usageCredsPaths(os.homedir(), configDir)++ let creds: OAuthCreds = { accessToken: null, email: null }++ if (process.platform === 'darwin') {+ for (const service of services) {+ try {+ const { stdout } = await execFileP('security', [+ 'find-generic-password',+ '-s',+ service,+ '-w'+ ])+ const parsed = parseCreds(stdout.trim())+ if (parsed.accessToken) {+ creds = parsed+ break+ }+ } catch {+ // not in keychain under this service — try the next / the file+ }+ }+ }++ if (!creds.accessToken) {+ try {+ const raw = await fs.readFile(credsFile, 'utf-8')+ creds = parseCreds(raw)+ } catch {+ // no file — leave creds empty+ }+ }++ if (creds.accessToken && !creds.email) {+ try {+ const raw = await fs.readFile(identityFile, 'utf-8')+ const j = JSON.parse(raw) as Record<string, any>+ const acct = j.oauthAccount as Record<string, any> | undefined+ const email =+ (acct && typeof acct.emailAddress === 'string' && acct.emailAddress) ||+ (acct && typeof acct.email === 'string' && acct.email) ||+ null+ if (email) creds = { ...creds, email }+ } catch {+ // best-effort only+ }+ }++ return creds+}++/** The OAuth access token alone (keychain → {config}/.credentials.json), or null. */+export async function resolveClaudeAccessToken(accountId?: string): Promise<string | null> {+ 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)+ if (!accessToken) return emptyUsage(email, now, 'unavailable')+ try {+ const ctrl = new AbortController()+ const t = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS)+ const res = await fetch(USAGE_URL, {+ signal: ctrl.signal,+ cache: 'no-cache',+ headers: { authorization: `Bearer ${accessToken}`, 'anthropic-beta': OAUTH_BETA }+ }).finally(() => clearTimeout(t))+ if (!res.ok) {+ // 401/403 → token is an API key or expired: no subscription windows to show.+ const status = res.status === 401 || res.status === 403 ? 'unavailable' : 'error'+ return emptyUsage(email, now, status)+ }+ 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'+ }+ } catch {+ return emptyUsage(email, now, 'error')+ }+}++export interface UsageServiceOptions {+ /**+ * Whether a background poll should actually fire. The shell owns this because "is anyone+ * looking?" is shell-specific: Electron asks the window whether it is focused, the server asks+ * whether any browser is connected. Core must not learn about either. Default: always poll.+ *+ * Why gate at all: the usage endpoint has a tight request budget and this data is purely+ * informational, so a stale snapshot beats polling an idle app into 429s.+ */+ shouldPoll?: () => boolean+}++export interface UsageService {+ /** Cached if fresh, else a fresh fetch. */+ fetch(accountId?: string): Promise<ClaudeUsage>+ /** Always a fresh fetch, bypassing the debounce. */+ refresh(accountId?: string): Promise<ClaudeUsage>+ /** Refresh the system account if the debounce has elapsed — for shell focus/attach events. */+ refreshIfStale(): void+ /** Stop the poll timer. */+ dispose(): void+}++/**+ * Start the usage service and register its RPC handlers. Safe to call once per shell boot.+ */+export function startUsageService(opts: UsageServiceOptions = {}): UsageService {+ const shouldPoll = opts.shouldPoll ?? ((): boolean => true)++ // Per-account caches keyed by `accountId ?? ''`. The empty key is the system account, the only+ // one that's proactively polled + pushed; managed-account rows fetch on demand from the popover.+ const last = new Map<string, ClaudeUsage>()+ const lastFetchAt = new Map<string, number>()+ const inFlight = new Map<string, Promise<ClaudeUsage>>()++ const push = (key: string, u: ClaudeUsage): void => {+ last.set(key, u)+ lastFetchAt.set(key, u.updatedAt)+ // Only the system account feeds the push channel — the collapsed chip tracks it.+ if (key === '') platform().broadcast(IPC.usageUpdate, u)+ }++ const run = async (accountId?: string): Promise<ClaudeUsage> => {+ const key = accountId ?? ''+ const pending = inFlight.get(key)+ if (pending) return pending+ const p = fetchUsage(accountId)+ inFlight.set(key, p)+ try {+ const u = await p+ push(key, u)+ return u+ } finally {+ inFlight.delete(key)+ }+ }++ platform().handle(IPC.usageFetch, async (accountId?: string) => {+ const key = accountId ?? ''+ const cached = last.get(key)+ if (cached && Date.now() - (lastFetchAt.get(key) ?? 0) < REFETCH_DEBOUNCE_MS) return cached+ return run(accountId)+ })+ platform().handle(IPC.usageRefresh, (accountId?: string) => run(accountId))++ // The warm-up fetch goes through the same gate as the poll: it IS a poll, just the first one.+ // On desktop a focused window warms the cache before the pill mounts; on the server, boot+ // happens with no browser attached, so this correctly does nothing until someone connects+ // (and UsageIndicator fetches on mount regardless, so nothing is lost either way).+ if (shouldPoll()) void run()+ const interval = setInterval(() => {+ if (shouldPoll()) void run()+ }, POLL_MS)+ // Node keeps the process alive for pending timers; the server shell should exit on its own terms.+ interval.unref?.()++ return {+ fetch: (accountId?: string) => run(accountId),+ refresh: (accountId?: string) => run(accountId),+ refreshIfStale: () => {+ if (Date.now() - (lastFetchAt.get('') ?? 0) >= REFETCH_DEBOUNCE_MS) void run()+ },+ dispose: () => clearInterval(interval)+ }+}diff --git a/src/main/claude-usage.ts b/src/main/claude-usage.tsindex 71915b4a2..f8e634153 100644--- a/src/main/claude-usage.ts+++ b/src/main/claude-usage.ts@@ -1,207 +1,23 @@-// Fetches Claude Code subscription usage from Anthropic's OAuth usage endpoint — every limit-// the plan exposes, including per-model scoped caps (Fable's weekly cap and whatever ships-// next), which arrive as generic `limits[]` entries rather than fixed fields.-// Runs in the main process (Node) so the renderer CSP stays 'self' — the renderer asks for the-// data over IPC. Display-only: we never write credentials or refresh tokens.-import { promises as fs } from 'fs'-import os from 'os'-import path from 'path'-import { execFile } from 'child_process'-import { promisify } from 'util'-import { ipcMain, type BrowserWindow } from 'electron'-import { IPC } from '../shared/ipc'-import type { ClaudeUsage, ClaudeUsageWindow, UsageLimit } from '../shared/types'-import { mapUsageLimits } from '../core/usage/claude-usage-map'-import { findLimit } from '../shared/usage-limits'-import { usageCredsPaths } from '../core/claude-accounts-core'-import { claudeConfigDirFor } from './claude-accounts'+// Electron shell for the usage service. Everything real — credential resolution, the OAuth+// fetch, the per-account cache, the RPC handlers — lives in src/core/usage/usage-service.ts so+// 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 } from '../core/usage/usage-service'-const execFileP = promisify(execFile)--const USAGE_URL = 'https://api.anthropic.com/api/oauth/usage'-const OAUTH_BETA = 'oauth-2025-04-20'-const FETCH_TIMEOUT_MS = 8000-const POLL_MS = 15 * 60 * 1000-const FOCUS_DEBOUNCE_MS = 5 * 60 * 1000--interface OAuthCreds {- accessToken: string | null- email: string | null-}--/** Parse a credentials JSON blob; tokens may sit at top level or under `claudeAiOauth`. */-function parseCreds(raw: string): OAuthCreds {- try {- const j = JSON.parse(raw) as Record<string, any>- const o = (j.claudeAiOauth ?? j) as Record<string, any>- const accessToken = typeof o.accessToken === 'string' ? o.accessToken : null- const email =- (typeof o.email === 'string' && o.email) ||- (typeof o.emailAddress === 'string' && o.emailAddress) ||- null- return { accessToken, email }- } catch {- return { accessToken: null, email: null }- }-}--/** The OAuth access token alone (keychain → ~/.claude/.credentials.json), or null. */-export async function resolveClaudeAccessToken(): Promise<string | null> {- return (await resolveCreds()).accessToken-}--/**- * macOS Keychain → {config}/.credentials.json → email backfill from {config}/.claude.json.- * With an `accountId` the config dir is the managed account's isolated dir (scoped Keychain- * service first); without, it's exactly the system default (`~/.claude`, unscoped services).- */-async function resolveCreds(accountId?: string): Promise<OAuthCreds> {- const configDir = accountId ? claudeConfigDirFor(accountId) : undefined- const { services, credsFile, identityFile } = usageCredsPaths(os.homedir(), configDir)-- let creds: OAuthCreds = { accessToken: null, email: null }-- if (process.platform === 'darwin') {- for (const service of services) {- try {- const { stdout } = await execFileP('security', [- 'find-generic-password',- '-s',- service,- '-w'- ])- const parsed = parseCreds(stdout.trim())- if (parsed.accessToken) {- creds = parsed- break- }- } catch {- // not in keychain under this service — try the next / the file- }- }- }-- if (!creds.accessToken) {- try {- const raw = await fs.readFile(credsFile, 'utf-8')- creds = parseCreds(raw)- } catch {- // no file — leave creds empty- }- }-- if (creds.accessToken && !creds.email) {- try {- const raw = await fs.readFile(identityFile, 'utf-8')- const j = JSON.parse(raw) as Record<string, any>- const acct = j.oauthAccount as Record<string, any> | undefined- const email =- (acct && typeof acct.emailAddress === 'string' && acct.emailAddress) ||- (acct && typeof acct.email === 'string' && acct.email) ||- null- if (email) creds = { ...creds, email }- } catch {- // best-effort only- }- }-- return creds-}--/** 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 }-}--async function fetchUsage(accountId?: string): Promise<ClaudeUsage> {- const now = Date.now()- const { accessToken, email } = await resolveCreds(accountId)- if (!accessToken) {- return emptyUsage(email, now, 'unavailable')- }- try {- const ctrl = new AbortController()- const t = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS)- const res = await fetch(USAGE_URL, {- signal: ctrl.signal,- cache: 'no-cache',- headers: { authorization: `Bearer ${accessToken}`, 'anthropic-beta': OAUTH_BETA }- }).finally(() => clearTimeout(t))- if (!res.ok) {- // 401/403 → token is an API key or expired: no subscription windows to show.- const status = res.status === 401 || res.status === 403 ? 'unavailable' : 'error'- return emptyUsage(email, now, status)- }- 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'- }- } catch {- return emptyUsage(email, now, 'error')- }-}+export { resolveClaudeAccessToken } from '../core/usage/usage-service'export function initClaudeUsage(win: BrowserWindow): void {- // Per-account caches keyed by `accountId ?? ''`. The empty key is the system account, the- // only one that's proactively polled + pushed; managed-account rows fetch on demand from the- // popover.- const last = new Map<string, ClaudeUsage>()- const lastFetchAt = new Map<string, number>()- const inFlight = new Map<string, Promise<ClaudeUsage>>()+ // Poll only while the window is focused, and re-check on focus — the usage endpoint has a+ // tight request budget and this data is informational, so an unattended app should not spend it.+ const service = startUsageService({ shouldPoll: () => win.isFocused() })- const push = (key: string, u: ClaudeUsage): void => {- last.set(key, u)- lastFetchAt.set(key, u.updatedAt)- // Only the system account feeds the push channel — the collapsed chip tracks it.- if (key === '' && !win.isDestroyed()) win.webContents.send(IPC.usageUpdate, u)- }-- const run = async (accountId?: string): Promise<ClaudeUsage> => {- const key = accountId ?? ''- const pending = inFlight.get(key)- if (pending) return pending- const p = fetchUsage(accountId)- inFlight.set(key, p)- try {- const u = await p- push(key, u)- return u- } finally {- inFlight.delete(key)- }- }-- ipcMain.handle(IPC.usageFetch, async (_e, accountId?: string) => {- const key = accountId ?? ''- const cached = last.get(key)- if (cached && Date.now() - (lastFetchAt.get(key) ?? 0) < FOCUS_DEBOUNCE_MS) return cached- return run(accountId)- })- ipcMain.handle(IPC.usageRefresh, (_e, accountId?: string) => run(accountId))-- void run()- const interval = setInterval(() => {- if (win.isFocused()) void run()- }, POLL_MS)-- const onFocus = (): void => {- if (Date.now() - (lastFetchAt.get('') ?? 0) >= FOCUS_DEBOUNCE_MS) void run()- }+ const onFocus = (): void => service.refreshIfStale()win.on('focus', onFocus)- win.on('closed', () => clearInterval(interval))+ win.on('closed', () => {+ // Both matter: the timer keeps firing otherwise, and the listener kept a dead window+ // referenced (the pre-core version cleared the interval but never removed this handler).+ win.off('focus', onFocus)+ service.dispose()+ })}diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex 995a76a9a..1836f6970 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -214,11 +214,14 @@ export function buildStubApi(): Omit<info: U('contextLink.info')},usage: {- // Boot path awaits this; null = "no usage snapshot" so the indicator hides. The consumer- // (UsageIndicator) does guard for it, but the value still lies about its type: the- // `null as unknown as ClaudeUsage` cast is exactly the pattern that hid the getPolicy- // TypeError above. Fixing it properly means widening `UsageApi.fetch` to- // `Promise<ClaudeUsage | null>` (a public-API change) — tracked separately.+ // Superseded by the real WS-backed namespace in ws-bridge (the core usage service runs in+ // the server shell too), so nothing reaches these in a live browser session. Kept only to+ // satisfy `satisfies NodeTerminalApi`.+ //+ // The `null as unknown as ClaudeUsage` cast is retained on purpose: the boot path awaits+ // `fetch`, and UsageIndicator treats a null snapshot as "nothing to show" and renders+ // nothing. It still lies about its type — the honest fix is widening `UsageApi.fetch` to+ // `Promise<ClaudeUsage | null>`, a public-API change tracked separately.fetch: (): Promise<ClaudeUsage> => Promise.resolve(null as unknown as ClaudeUsage),refresh: U('usage.refresh'),onUpdate: noopUnsubdiff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex 4eccab6e0..c22891fdf 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -27,6 +27,7 @@ import {type PtyApi,type PtyCreateOptions,type SettingsApi,+ type ClaudeUsage,type Settings,type SpeechApi,type SpeechModelInfo,@@ -464,6 +465,28 @@ export function buildSpeechApi(client: RpcClient): Pick<NodeTerminalApi, 'speechreturn { speech }}+/**+ * Build the `usage` namespace over an RpcClient. The server shell runs the same core usage+ * service the desktop does, so this is real end to end — including `onUpdate`, which subscribes+ * to the poll's broadcast rather than the stub's no-op.+ *+ * `fetch` deliberately does NOT catch: `UsageApi.fetch` is typed as `Promise<ClaudeUsage>`, so+ * swallowing a transport failure would mean inventing a snapshot. The one consumer+ * (UsageIndicator) leaves `usage` null until a real one arrives and renders nothing meanwhile,+ * which is the correct outcome for "we don't know".+ */+function buildUsageApi(client: RpcClient): Pick<NodeTerminalApi, 'usage'> {+ return {+ usage: {+ fetch: (accountId?: string) =>+ client.request(IPC.usageFetch, accountId) as Promise<ClaudeUsage>,+ refresh: (accountId?: string) =>+ client.request(IPC.usageRefresh, accountId) as Promise<ClaudeUsage>,+ onUpdate: (listener) => client.subscribe(IPC.usageUpdate, listener as Listener)+ }+ }+}+/*** Build the `claude` namespace over an RpcClient. `cliCaps` is a REAL handler on the server* (`registerClaudeCliIpc` runs in the server shell too), so the browser resolves the very same@@ -595,6 +618,7 @@ export async function installWsBridge(): Promise<boolean> {...buildCanvasApi(client),...buildPresenceApi(client),...buildSpeechApi(client),+ ...buildUsageApi(client),// Only `cliCaps` is real here — the rest of the namespace stays stubbed (see buildClaudeApi).claude: buildClaudeApi(client, stubApi.claude),// Web replacement for the Electron native dialog: an in-app server-directory browser overdiff --git a/src/server/handlers/index.ts b/src/server/handlers/index.tsindex f8bb99307..aaff8030e 100644--- a/src/server/handlers/index.ts+++ b/src/server/handlers/index.ts@@ -4,6 +4,7 @@ import { GitService } from '../../core/git-service'import { generateCommitMessage } from '../../core/commit-message'import { registerFsHandlers } from '../../core/fs-handlers'import { claudeCliCaps, registerClaudeCliIpc } from '../../core/claude-cli'+import { startUsageService } from '../../core/usage/usage-service'import { IPC } from '../../shared/ipc'/** Register the Phase-3a handler surface (fs + git + commit) on the server platform.@@ -36,5 +37,10 @@ export function registerCoreHandlers(registerClaudeCliIpc()void claudeCliCaps()+ // Claude subscription usage. Previously desktop-only — the browser bridge answered `null`, so+ // the pill never rendered in the Server Edition. Poll only while a browser is attached: with+ // no client there is nobody to show it to, and the usage endpoint's request budget is tight.+ startUsageService({ shouldPoll: () => platform.clientIds().length > 0 })+return { gitService }}diff --git a/test/server/usage-e2e.test.ts b/test/server/usage-e2e.test.tsnew file mode 100644index 000000000..c12ac2e12--- /dev/null+++ b/test/server/usage-e2e.test.ts@@ -0,0 +1,88 @@+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import fs from 'fs'+import os from 'os'+import path from 'path'+import WebSocket from 'ws'+import { startServer } from '../../src/server/index'+import { SESSION_COOKIE } from '../../src/server/http'+import { IPC } from '../../src/shared/ipc'+import type { ClaudeUsage } from '../../src/shared/types'++/**+ * Server Edition usage: the browser bridge used to answer a hardcoded `null`, so the pill never+ * rendered outside Electron. The usage service now lives in core and the server shell registers+ * it, so `usage:fetch` must be a REAL handler over the WS-RPC transport.+ *+ * Asserts the SHAPE, not the numbers: whether this machine has Claude credentials decides+ * between `ok` and `unavailable`, and both are correct answers. What must hold either way is+ * that a handler exists at all (an unregistered channel rejects) and that it returns a+ * well-formed ClaudeUsage — which is exactly what the old `null` failed to do.+ */+describe('server e2e: usage over WS-RPC', () => {+ let dataDir: string, close: () => Promise<void>, port: number, cookie: string++ beforeAll(async () => {+ dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-usage-e2e-'))+ const srv = await startServer({+ port: 0,+ host: '127.0.0.1',+ dataDir,+ rendererDir: path.join(dataDir, 'no-renderer'),+ insecureHttp: false,+ passwordSeed: 'e2e-password-123',+ // Never touch the developer's real ~/.claude — see server-e2e.test.ts.+ installHooks: false+ })+ port = srv.port+ close = srv.close+ const res = await fetch(`http://127.0.0.1:${port}/auth/login`, {+ method: 'POST',+ headers: { 'content-type': 'application/x-www-form-urlencoded' },+ body: 'password=e2e-password-123',+ redirect: 'manual'+ })+ expect(res.status).toBe(303)+ cookie = res.headers.get('set-cookie')!.split(';')[0]+ }, 30_000)++ afterAll(async () => {+ await close?.()+ fs.rmSync(dataDir, { recursive: true, force: true })+ })++ it('serves usage:fetch as a real handler returning a well-formed snapshot', async () => {+ const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`, { headers: { cookie } })+ await new Promise<void>((res, rej) => {+ ws.on('open', () => res())+ ws.on('error', rej)+ })++ const result = await new Promise<ClaudeUsage>((resolve, reject) => {+ ws.on('message', (d, isBinary) => {+ if (isBinary) return+ const m = JSON.parse(d.toString())+ if (m.t !== 'res' || m.id !== 1) return+ if (!m.ok) reject(new Error(`usage:fetch rejected: ${m.error}`))+ else resolve(m.result as ClaudeUsage)+ })+ ws.send(JSON.stringify({ t: 'req', id: 1, method: IPC.usageFetch, args: [] }))+ setTimeout(() => reject(new Error('usage:fetch timed out')), 20_000)+ })++ expect(Array.isArray(result.limits)).toBe(true)+ expect(['ok', 'unavailable', 'error', 'fetching']).toContain(result.status)+ expect(typeof result.updatedAt).toBe('number')++ // Whatever limits came back must be renderable — the pill reads exactly these fields, and a+ // NaN percentage or a missing kind would paint a broken bar rather than fail loudly.+ for (const l of result.limits) {+ expect(typeof l.kind).toBe('string')+ expect(l.kind.length).toBeGreaterThan(0)+ expect(Number.isFinite(l.usedPercent)).toBe(true)+ expect(l.usedPercent).toBeGreaterThanOrEqual(0)+ expect(l.usedPercent).toBeLessThanOrEqual(100)+ }++ ws.close()+ }, 30_000)+})