Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions docs/claude-code.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
4 changes: 2 additions & 2 deletions docs/writing-widgets.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:<connectionId>`,
`claude-account`, `claude-identity`, `codex`, `codex-live`, `dock`, `docker-local`,
`local-models`, plus one per connection: `azure-devops:<connectionId>`,
`bambu:<connectionId>`, `github:<connectionId>`, `synology:<connectionId>`,
and `calendar:<connectionId>` for an ICS connection.

Expand Down
2 changes: 2 additions & 0 deletions server/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -151,6 +152,7 @@ export async function buildApp(opts: AppOptions): Promise<FastifyInstance> {
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,
Expand Down
102 changes: 102 additions & 0 deletions server/src/claude/identity.ts
Original file line number Diff line number Diff line change
@@ -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<void> = (path) => access(path, constants.X_OK),
): Promise<string> {
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<string> {
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<string>
now?: () => number
} = {}): Provider<ClaudeIdentity> {
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<ClaudeIdentity> = {
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
}
84 changes: 84 additions & 0 deletions server/test/claude-identity.test.ts
Original file line number Diff line number Diff line change
@@ -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<string>((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()
}
})
})
27 changes: 23 additions & 4 deletions server/test/claude-usage-widget.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, StubNode>
markup: string
/** Hands the widget one answer from a channel, as the host delivers it. */
publish(channel: string, data: Record<string, unknown>): void
}
Expand Down Expand Up @@ -60,7 +61,7 @@ async function loadWidget(): Promise<Loaded> {
// 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)),
}
}
Expand All @@ -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 () => {
Expand All @@ -85,7 +86,7 @@ describe('the claude-usage widget', () => {
limits: [{ name: 'Opus', percent: 40, resetsAt: 0 }],
breakdown: [{ name: '<img src=x>', percent: 30 }],
})
expect(loaded.nodes.get('foot')?.innerHTML).toContain('&lt;img src=x&gt;')
expect(loaded.nodes.get('foot-text')?.innerHTML).toContain('&lt;img src=x&gt;')
})

it('draws the histogram that follows the footer', async () => {
Expand All @@ -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(/<div class=\"foot\"[^>]*><span class=\"plan\"[^>]*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('')
})
})
21 changes: 16 additions & 5 deletions widgets/claude-usage/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -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)}
</style>
<style>
.gauges{display:flex;gap:18px;flex-wrap:wrap}
Expand All @@ -27,6 +31,7 @@
.ok>i{background:var(--ok, #2fb36b)}.warn>i{background:#f0a020}.hot>i{background:var(--danger, #d9463f)}
.stale .g{opacity:.45}
.foot{font-size:calc(14px * var(--text-scale, 1));color:#c3c8d0}
.foot .plan{margin-right:8px}
.hist{display:flex;align-items:flex-end;gap:2px;height:40px;margin-top:6px}.hist>i{flex:1;background:var(--border-strong, #3a404a);border-radius:2px 2px 0 0;min-height:1px}.hist>i.now{background:var(--accent, #d9b36a)}.histrow{display:flex;gap:12px;align-items:flex-end}.histlbl{font-size:calc(12px * var(--text-scale, 1));color:var(--text-muted, #8b93a0);white-space:nowrap}
[hidden]{display:none!important}
/* Compact: the navigation bar shows the three limits on one line, sized from the bar height (--h). */
Expand All @@ -48,8 +53,8 @@
html.compact.slot-right .cwrap{justify-content:flex-end;text-align:right}
</style>
</head>
<body><div class="wrap" id="wrap"><div class="note" id="note"></div>
<div class="gauges" id="gauges"></div><div class="foot" id="foot"></div>
<body><div class="wrap" id="wrap"><div class="note-line"><div class="note" id="note"></div></div>
<div class="gauges" id="gauges"></div><div class="foot" id="foot"><span class="plan" id="plan" hidden></span><span id="foot-text"></span></div>
<div class="histrow" id="histrow" hidden><div class="hist" id="hist"></div><div class="histlbl" id="histlbl"></div></div></div>
<div class="cwrap" id="cwrap"></div>
<script>
Expand All @@ -73,7 +78,7 @@
millions: { fr: '{n} M', en: '{n}M' },
thousands: { fr: '{n} k', en: '{n}k' }
}
var data = null, account = null, accountOff = false
var data = null, account = null, accountOff = false, identity = null
function cls(p) { return p < 60 ? 'ok' : p < 85 ? 'warn' : 'hot' }
/** A decimal separator follows the language: a comma in French, a point in English. */
function dec(n, digits) { var text = n.toFixed(digits); return Fremkit.locale === 'fr' ? text.replace('.', ',') : text }
Expand Down Expand Up @@ -108,7 +113,12 @@
}).join('')
}
function render() {
var wrap = document.getElementById('wrap'), note = document.getElementById('note'), foot = document.getElementById('foot'), gauges = document.getElementById('gauges')
var knownPlan = identity && identity.loggedIn && identity.authMethod === 'claude.ai'
&& !identity.stale && identity.subscriptionType
var planBadge = document.getElementById('plan')
planBadge.hidden = !knownPlan
planBadge.textContent = knownPlan ? 'Claude ' + identity.subscriptionType.charAt(0).toUpperCase() + identity.subscriptionType.slice(1) : ''
var wrap = document.getElementById('wrap'), note = document.getElementById('note'), footText = document.getElementById('foot-text'), gauges = document.getElementById('gauges')
var useAccount = account && account.available && account.limits && account.limits.length
var stale = useAccount ? account.stale : !!(data && data.stale)
wrap.classList.toggle('stale', stale)
Expand All @@ -130,7 +140,7 @@
parts.push(Fremkit.t(L.today, { tokens: tokens(total), sessions: sessions })
+ (t.costUsd ? Fremkit.t(L.cost, { amount: dec(t.costUsd, 2) }) : ''))
}
foot.innerHTML = parts.map(Fremkit.esc).join('<br>')
footText.innerHTML = parts.map(Fremkit.esc).join('<br>')
var histrow = document.getElementById('histrow'), hist = document.getElementById('hist'), histlbl = document.getElementById('histlbl')
if (data && data.today && data.today.hourly && Fremkit.size.h >= 4) {
histrow.hidden = false
Expand All @@ -142,6 +152,7 @@
}
}
Fremkit.whenReady(function () {
Fremkit.subscribe('claude-identity', function (d) { identity = d; render() })
Fremkit.subscribe('claude-usage', function (d) { if (d.error) return; data = d; render() })
// A rate-limited poll still carries the last good gauges (flagged stale): keep showing them.
Fremkit.subscribe('claude-account', function (d) {
Expand Down
4 changes: 2 additions & 2 deletions widgets/claude-usage/manifest.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{ "id": "claude-usage",
"name": { "fr": "Quotas Claude", "en": "Claude limits" },
"version": "1.1.1",
"version": "1.1.2",
"description": { "fr": "Quotas 5 h / 7 jours et tokens du jour", "en": "5 h / 7 day limits and today’s tokens" },
"category": "ai",
"icon": "gauge", "minSize": [16, 4], "defaultSize": [16, 4], "compact": { "width": 9 },
"subscriptions": ["claude-usage", "claude-account"] }
"subscriptions": ["claude-usage", "claude-account", "claude-identity"] }
Loading