diff --git a/CHANGELOG.md b/CHANGELOG.md index 03727f47..77e2e376 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,9 @@ tagged `vX.Y.Z`. - **cmux session navigation.** A Claude card selects its cmux panel through the bundled CLI when the running process identifies both workspace and surface and socket access allows it. Otherwise it brings cmux forward. - **Local Docker and AI models.** Registry widgets can show up to 200 local containers and observed Ollama or MLX models. Fremkit refuses remote Docker contexts, distinguishes a missing CLI from a stopped daemon, and keeps the container list when stats fail. - **The Uptime tile shows time since boot.** The reading comes from macOS and remains unavailable when the system cannot provide it. +- **The Claude limits tile shows your plan.** When the local Claude CLI reports a known + subscription, the tile shows a compact badge beside the footer, visible even when the hourly + histogram is displayed, without publishing the account email. - **Borrow the Edge display.** Hide or show the dashboard from the helper menu without quitting it. Hidden state survives display rearrangements, and the mouse fence pauses while the Edge is borrowed. Touch and data collection continue; the dashboard reappears after a helper restart. - **Account e-mail stays private.** A new box in **/admin → Screen → Privacy**, *Show the account e-mail address*, off by default. Until you tick it, a widget that shows an account gets its plan diff --git a/docs/claude-code.md b/docs/claude-code.md index d7c3c604..236a2f11 100644 --- a/docs/claude-code.md +++ b/docs/claude-code.md @@ -98,3 +98,8 @@ Nothing the Claude providers publish carries the account's e-mail address. Shoul it is held to the rule every account provider is: the address is left out unless **/admin → Screen → Privacy → Show the account e-mail address** is ticked (see [connections.md](connections.md#the-accounts-e-mail-address)). + +The usage tile also shows a plan badge when the local Claude CLI reports a known subscription. +Fremkit reads `claude auth status --json` from a fixed local binary path. It publishes only login +state, authentication method and the known plan, never the account email or authentication data. +The plan badge is independent of the optional account-usage read. diff --git a/docs/writing-widgets.md b/docs/writing-widgets.md index 675eb26c..1984c52c 100644 --- a/docs/writing-widgets.md +++ b/docs/writing-widgets.md @@ -298,8 +298,8 @@ document.documentElement.style.setProperty('--h', Fremkit.size.px.height + 'px') `system`, `processes`, `volume`, `spotify`, `mutedeck`, `clipboard`, `shortcuts`, `cleanshot`, `network`, `battery`, `service-status`, `config`, `claude-sessions`, `claude-usage`, -`claude-account`, `codex`, `codex-live`, `dock`, `docker-local`, `local-models`, -plus one per connection: `azure-devops:`, +`claude-account`, `claude-identity`, `codex`, `codex-live`, `dock`, `docker-local`, +`local-models`, plus one per connection: `azure-devops:`, `bambu:`, `github:`, `synology:`, and `calendar:` for an ICS connection. diff --git a/server/src/app.ts b/server/src/app.ts index 817f472a..f090efd7 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -39,6 +39,7 @@ import { claudeRoutes } from './claude/routes.js' import { createClaudeSessionsProvider, createClaudeUsageProvider, createClaudeAccountProvider } from './claude/providers.js' import { createCodexProvider } from './providers/codex.js' import { createLocalChatValidator } from './codex/local-chats.js' +import { createClaudeIdentityProvider } from './claude/identity.js' import { createAttention } from './claude/attention.js' import { DockState } from './dock/state.js' import { dockRoutes } from './dock/routes.js' @@ -151,6 +152,7 @@ export async function buildApp(opts: AppOptions): Promise { for (const p of opts.providers ?? []) registry.register(p) registry.register(createClaudeSessionsProvider(tracker)) registry.register(createClaudeUsageProvider(usage)) + registry.register(createClaudeIdentityProvider()) registry.register(createClaudeAccountProvider({ filePath: join(opts.dataDir, 'claude-account.json'), enabled: () => store.get().privacy.claudeAccountUsage, diff --git a/server/src/claude/identity.ts b/server/src/claude/identity.ts new file mode 100644 index 00000000..44a6633a --- /dev/null +++ b/server/src/claude/identity.ts @@ -0,0 +1,102 @@ +import { execFile } from 'node:child_process' +import { access, constants } from 'node:fs/promises' +import { homedir, userInfo } from 'node:os' +import { join } from 'node:path' +import { z } from 'zod' +import type { Provider } from '../providers/types.js' + +const Status = z.object({ + loggedIn: z.boolean(), + authMethod: z.string().max(100).nullish(), + subscriptionType: z.string().max(100).nullish(), +}) + +export interface ClaudeIdentity { + loggedIn: boolean | null + subscriptionType: string | null + authMethod: string | null + updatedAt: number | null + stale: boolean + error: 'offline' | 'invalid' | null +} + +export function identityEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv { + const safe: NodeJS.ProcessEnv = {} + for (const key of ['HOME', 'PATH', 'TMPDIR', 'LANG', 'LC_ALL', 'USER', 'LOGNAME', 'SHELL', 'CLAUDE_CONFIG_DIR']) { + if (env[key] !== undefined) safe[key] = env[key] + } + return safe +} + +/** Resolve only known local installs; the helper's PATH need not contain the CLI. */ +export async function resolveClaudeBinary( + canExecute: (path: string) => Promise = (path) => access(path, constants.X_OK), +): Promise { + const candidates = [join(homedir(), '.local/bin/claude'), '/opt/homebrew/bin/claude', '/usr/local/bin/claude'] + for (const path of candidates) { + try { + await canExecute(path) + return path + } catch { /* Try the next fixed location. */ } + } + throw new Error('offline') +} + +function readStatus(): Promise { + const env = identityEnv(process.env) + env.USER ??= userInfo().username + env.LOGNAME ??= env.USER + return resolveClaudeBinary().then((binary) => new Promise((resolve, reject) => { + execFile(binary, ['auth', 'status', '--json'], { + env, cwd: homedir(), timeout: 10000, maxBuffer: 16384, shell: false, + }, (error, stdout) => { + if (!error || (error.code === 1 && stdout.trim().startsWith('{'))) resolve(stdout) + else reject(new Error('offline')) + }) + })) +} + +function plan(type: string | null | undefined): string | null { + return type === 'max' || type === 'pro' || type === 'team' || type === 'enterprise' ? type : null +} + +export function createClaudeIdentityProvider(opts: { + read?: () => Promise + now?: () => number +} = {}): Provider { + const read = opts.read ?? readStatus + const now = opts.now ?? Date.now + let last: ClaudeIdentity = { + loggedIn: null, subscriptionType: null, authMethod: null, + updatedAt: null, stale: false, error: null, + } + let generation = 0 + const provider: Provider = { + channel: 'claude-identity', + intervalMs: 300000, + stop() { generation++ }, + async poll() { + const epoch = generation + try { + const status = Status.parse(JSON.parse(await read())) + const next: ClaudeIdentity = { + loggedIn: status.loggedIn, + subscriptionType: status.loggedIn && status.authMethod === 'claude.ai' ? plan(status.subscriptionType) : null, + authMethod: status.authMethod === 'claude.ai' || status.authMethod === 'api-key' ? status.authMethod : null, + updatedAt: now(), stale: false, error: null, + } + if (epoch === generation) last = next + } catch (error) { + if (epoch === generation) last = { + ...last, stale: true, + error: error instanceof z.ZodError || error instanceof SyntaxError ? 'invalid' : 'offline', + } + } + // The registry may reuse this provider after its last listener briefly leaves. + // Its old in-flight read was discarded, so retry promptly on reactivation. + provider.intervalMs = epoch !== generation ? 1 : last.error ? 30000 : 300000 + return last + }, + } + return provider +} diff --git a/server/test/claude-identity.test.ts b/server/test/claude-identity.test.ts new file mode 100644 index 00000000..0b14c0e3 --- /dev/null +++ b/server/test/claude-identity.test.ts @@ -0,0 +1,84 @@ +import { describe, it, expect } from 'vitest' +import { createClaudeIdentityProvider, identityEnv, resolveClaudeBinary } from '../src/claude/identity.js' +import { ProviderRegistry } from '../src/providers/registry.js' + +const status = JSON.stringify({ loggedIn: true, authMethod: 'claude.ai', subscriptionType: 'max', email: 'PRIVATE', accessToken: 'PRIVATE' }) + +describe('Claude identity', () => { + it('projects only login and plan from CLI status', async () => { + const provider = createClaudeIdentityProvider({ read: async () => status, now: () => 100 }) + const result = await provider.poll!() + expect(result).toEqual({ loggedIn: true, subscriptionType: 'max', authMethod: 'claude.ai', updatedAt: 100, stale: false, error: null }) + expect(JSON.stringify(result)).not.toContain('PRIVATE') + }) + it('keeps login status without inventing an unrecognized plan', async () => { + const provider = createClaudeIdentityProvider({ read: async () => JSON.stringify({ loggedIn: true, authMethod: 'claude.ai', subscriptionType: 'unknown-plan' }) }) + expect(await provider.poll!()).toMatchObject({ loggedIn: true, subscriptionType: null, stale: false }) + }) + it('does not publish an unrecognized authentication method', async () => { + const provider = createClaudeIdentityProvider({ + read: async () => JSON.stringify({ loggedIn: true, authMethod: 'unexpected', subscriptionType: 'max' }), + }) + expect(await provider.poll!()).toMatchObject({ authMethod: null, subscriptionType: null }) + }) + it('clears account on logout and marks a later status failure stale', async () => { + let raw = status + const provider = createClaudeIdentityProvider({ + read: async () => { + if (raw === 'fail') throw new Error('secret stderr') + return raw + }, + }) + await provider.poll!() + raw = JSON.stringify({ loggedIn: false, authMethod: 'none' }) + expect(await provider.poll!()).toMatchObject({ loggedIn: false, subscriptionType: null, authMethod: null }) + raw = 'fail' + expect(await provider.poll!()).toMatchObject({ loggedIn: false, stale: true, error: 'offline' }) + expect(provider.intervalMs).toBe(30000) + }) + it('rejects malformed status without exposing its content', async () => { + const provider = createClaudeIdentityProvider({ + read: async () => JSON.stringify({ loggedIn: 'yes', token: 'PRIVATE' }), + }) + expect(await provider.poll!()).toMatchObject({ subscriptionType: null, stale: true, error: 'invalid' }) + expect(provider.intervalMs).toBe(30000) + }) + it('uses only the first executable absolute path from the closed list', async () => { + const seen: string[] = [] + const path = await resolveClaudeBinary(async (candidate) => { + seen.push(candidate) + if (candidate !== '/opt/homebrew/bin/claude') throw new Error('missing') + }) + expect(path).toBe('/opt/homebrew/bin/claude') + expect(seen[0]).toMatch(/\/\.local\/bin\/claude$/) + expect(seen).toHaveLength(2) + }) + it('strips token and loader environment variables', () => { + const env = identityEnv({ + HOME: '/path/to/home', PATH: '/usr/bin', USER: 'example', LOGNAME: 'example', + ANTHROPIC_API_KEY: 'PRIVATE', NODE_OPTIONS: 'PRIVATE', + }) + expect(env).toEqual({ HOME: '/path/to/home', PATH: '/usr/bin', USER: 'example', LOGNAME: 'example' }) + }) + it('rereads promptly if a widget returns while the first CLI read is pending', async () => { + let resolveFirst!: (value: string) => void + const first = new Promise((resolve) => { resolveFirst = resolve }) + let reads = 0 + const provider = createClaudeIdentityProvider({ read: () => ++reads === 1 ? first : Promise.resolve(status) }) + const published: unknown[] = [] + const registry = new ProviderRegistry((_channel, value) => published.push(value)) + try { + registry.register(provider) + registry.addSubscriber('claude-identity') + await new Promise((resolve) => setTimeout(resolve, 10)) + registry.removeSubscriber('claude-identity') + registry.addSubscriber('claude-identity') + resolveFirst(status) + await new Promise((resolve) => setTimeout(resolve, 20)) + expect(reads).toBe(2) + expect(published).toContainEqual(expect.objectContaining({ subscriptionType: 'max' })) + } finally { + registry.stop() + } + }) +}) diff --git a/server/test/claude-usage-widget.test.ts b/server/test/claude-usage-widget.test.ts index 27e5a56e..fd9efa28 100644 --- a/server/test/claude-usage-widget.test.ts +++ b/server/test/claude-usage-widget.test.ts @@ -15,6 +15,7 @@ interface StubNode { innerHTML: string; textContent: string; hidden: boolean } interface Loaded { /** The elements the widget asked for by id, so a test can read what it put in them. */ nodes: Map + markup: string /** Hands the widget one answer from a channel, as the host delivers it. */ publish(channel: string, data: Record): void } @@ -60,7 +61,7 @@ async function loadWidget(): Promise { // The widget redraws itself every second for the countdowns; a test wants the renders it asks for. new Function('document', 'Fremkit', 'setInterval', script)(document, Fremkit, () => 0) return { - nodes, + nodes, markup: html, publish: (channel, data) => (subscribers.get(channel) ?? []).forEach((cb) => cb(data)), } } @@ -74,8 +75,8 @@ describe('the claude-usage widget', () => { it('puts the day in its footer', async () => { const loaded = await loadWidget() loaded.publish('claude-usage', { fiveHour: { pct: 10, resetsAt: 0 }, sevenDay: { pct: 20, resetsAt: 0 }, today, updatedAt: Date.now() }) - expect(loaded.nodes.get('foot')?.innerHTML).toContain('aujourd’hui') - expect(loaded.nodes.get('foot')?.innerHTML).toContain('4 k tokens') + expect(loaded.nodes.get('foot-text')?.innerHTML).toContain('aujourd’hui') + expect(loaded.nodes.get('foot-text')?.innerHTML).toContain('4 k tokens') }) it('escapes what the account names, since a limit name is not ours', async () => { @@ -85,7 +86,7 @@ describe('the claude-usage widget', () => { limits: [{ name: 'Opus', percent: 40, resetsAt: 0 }], breakdown: [{ name: '', percent: 30 }], }) - expect(loaded.nodes.get('foot')?.innerHTML).toContain('<img src=x>') + expect(loaded.nodes.get('foot-text')?.innerHTML).toContain('<img src=x>') }) it('draws the histogram that follows the footer', async () => { @@ -95,3 +96,21 @@ describe('the claude-usage widget', () => { expect(loaded.nodes.get('hist')?.innerHTML).toContain('height:100%') }) }) + +describe('Claude plan in its usage widget', () => { + it('shows a known plan independently of account usage being disabled', async () => { + const widget = await loadWidget() + widget.publish('claude-account', { error: 'disabled' }) + widget.publish('claude-identity', { loggedIn: true, subscriptionType: 'max', authMethod: 'claude.ai', stale: false }) + expect(widget.nodes.get('plan')?.textContent).toBe('Claude Max') + expect(widget.nodes.get('plan')?.hidden).toBe(false) + expect(widget.markup).toMatch(/
]*>]*id=\"plan\"/) + }) + it('hides the badge when the plan is stale or the user signs out', async () => { + const widget = await loadWidget() + widget.publish('claude-identity', { loggedIn: true, subscriptionType: 'pro', authMethod: 'claude.ai', stale: true }) + expect(widget.nodes.get('plan')?.hidden).toBe(true) + widget.publish('claude-identity', { loggedIn: false, subscriptionType: null, stale: false }) + expect(widget.nodes.get('plan')?.textContent).toBe('') + }) +}) diff --git a/widgets/claude-usage/index.html b/widgets/claude-usage/index.html index ccff4f56..d6e1a30b 100644 --- a/widgets/claude-usage/index.html +++ b/widgets/claude-usage/index.html @@ -17,6 +17,10 @@ /* A bar painted in the accent vanishes when the body *is* the accent, so it flips to the text colour. */ html.on-light .bar,html.accent-fill .bar{background:rgba(128,128,128,.35)} html.accent-fill .bar>i{background:var(--on-surface,#0b0d10)} + .note-line{display:flex;align-items:center;gap:8px;min-width:0;line-height:1;overflow:hidden} + .note-line .note{min-width:0} + .plan{font-size:calc(12px * var(--text-scale, 1));font-weight:600;color:var(--accent, #d9b36a);white-space:nowrap} + html.on-light .plan,html.accent-fill .plan{color:var(--on-surface,#0b0d10)} -
-
+
+