diff --git a/app/renderer/lib/types.ts b/app/renderer/lib/types.ts index 18d87805..f76807b7 100644 --- a/app/renderer/lib/types.ts +++ b/app/renderer/lib/types.ts @@ -174,8 +174,9 @@ export type MenubarPayload = { localModelSavings: LocalModelSavings providers: Record // Optional: older CLIs omit it. `id` is the internal provider name (round-trips - // as --provider), `label` the display name. Fall back to `providers` when absent. - providerDetails?: Array<{ id: string; label: string; cost: number }> + // as --provider), `label` the display name. `hasUsage` distinguishes active $0 + // providers from detected-but-idle providers when present. + providerDetails?: Array<{ id: string; label: string; cost: number; calls?: number; hasUsage?: boolean }> topProjects: Array<{ name: string cost: number diff --git a/app/renderer/sections/Settings.tsx b/app/renderer/sections/Settings.tsx index 073480ad..40025323 100644 --- a/app/renderer/sections/Settings.tsx +++ b/app/renderer/sections/Settings.tsx @@ -232,7 +232,7 @@ function ProvidersPane({ period, refreshToken }: { period: Period; refreshToken: // the internal id. Fall back to the providers map keys (lowercased display // names) for older CLIs that omit providerDetails. const providers = details - ? details.filter(entry => entry.cost > 0).map(entry => ({ id: entry.id, label: entry.label, cost: entry.cost })) + ? details.filter(entry => entry.hasUsage ?? entry.cost > 0).map(entry => ({ id: entry.id, label: entry.label, cost: entry.cost })) : Object.entries(overview.data?.current.providers ?? {}).map(([id, cost]) => ({ id, label: id.charAt(0).toUpperCase() + id.slice(1), cost })) return

Providers

codeburn auto-detects coding tools from local session files. No setup needed.

diff --git a/mac/Sources/CodeBurnMenubar/Data/MenubarPayload.swift b/mac/Sources/CodeBurnMenubar/Data/MenubarPayload.swift index 274c0865..c032ec45 100644 --- a/mac/Sources/CodeBurnMenubar/Data/MenubarPayload.swift +++ b/mac/Sources/CodeBurnMenubar/Data/MenubarPayload.swift @@ -219,6 +219,8 @@ struct CurrentBlock: Codable, Sendable { let topModels: [ModelEntry] let localModelSavings: LocalModelSavings let providers: [String: Double] + /// Stable provider identity plus period activity. Empty for older CLI payloads. + var providerDetails: [ProviderDetail] = [] let topProjects: [ProjectEntry] let modelEfficiency: [ModelEfficiencyEntry] let topSessions: [TopSessionEntry] @@ -255,7 +257,7 @@ struct PullRequestRow: Codable, Sendable { extension CurrentBlock { enum CodingKeys: String, CodingKey { case label, cost, calls, sessions, oneShotRate, inputTokens, outputTokens, - cacheHitPercent, codexCredits, topActivities, topModels, localModelSavings, providers, topProjects, + cacheHitPercent, codexCredits, topActivities, topModels, localModelSavings, providers, providerDetails, topProjects, modelEfficiency, topSessions, retryTax, routingWaste, tools, skills, subagents, mcpServers, workflow, topReworkedFiles, pullRequests @@ -275,6 +277,7 @@ extension CurrentBlock { topModels = try c.decodeIfPresent([ModelEntry].self, forKey: .topModels) ?? [] localModelSavings = try c.decodeIfPresent(LocalModelSavings.self, forKey: .localModelSavings) ?? LocalModelSavings(totalUSD: 0, calls: 0, byModel: [], byProvider: []) providers = try c.decodeIfPresent([String: Double].self, forKey: .providers) ?? [:] + providerDetails = try c.decodeIfPresent([ProviderDetail].self, forKey: .providerDetails) ?? [] topProjects = try c.decodeIfPresent([ProjectEntry].self, forKey: .topProjects) ?? [] modelEfficiency = try c.decodeIfPresent([ModelEfficiencyEntry].self, forKey: .modelEfficiency) ?? [] topSessions = try c.decodeIfPresent([TopSessionEntry].self, forKey: .topSessions) ?? [] @@ -290,6 +293,59 @@ extension CurrentBlock { } } +struct ProviderDetail: Codable, Sendable { + let id: String + let label: String + let cost: Double + let calls: Int + let hasUsage: Bool + + init(id: String, label: String, cost: Double, calls: Int, hasUsage: Bool) { + self.id = id + self.label = label + self.cost = cost + self.calls = calls + self.hasUsage = hasUsage + } + + private enum CodingKeys: String, CodingKey { + case id, label, cost, calls, hasUsage + } + + init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + id = try c.decode(String.self, forKey: .id) + label = try c.decode(String.self, forKey: .label) + cost = try c.decode(Double.self, forKey: .cost) + // Older CLIs emitted providerDetails without calls/hasUsage. When calls + // exists, derive activity from calls/cost; with neither signal, keep the + // detected provider visible rather than hiding valid $0 subscriptions. + let decodedCalls = try c.decodeIfPresent(Int.self, forKey: .calls) + calls = decodedCalls ?? 0 + if let decodedUsage = try c.decodeIfPresent(Bool.self, forKey: .hasUsage) { + hasUsage = decodedUsage + } else if decodedCalls != nil { + hasUsage = cost > 0 || calls > 0 + } else { + hasUsage = true + } + } +} + +enum ProviderVisibility { + static func activeKeys( + providerDetails: [ProviderDetail], + legacyProviders: [String: Double] + ) -> Set { + if !providerDetails.isEmpty { + return Set(providerDetails + .filter(\.hasUsage) + .flatMap { [$0.id.lowercased(), $0.label.lowercased()] }) + } + return Set(legacyProviders.keys.map { $0.lowercased() }) + } +} + struct LocalModelSavingsByModel: Codable, Sendable { let name: String let calls: Int diff --git a/mac/Sources/CodeBurnMenubar/Views/AgentTabStrip.swift b/mac/Sources/CodeBurnMenubar/Views/AgentTabStrip.swift index 022ae480..c7986cd3 100644 --- a/mac/Sources/CodeBurnMenubar/Views/AgentTabStrip.swift +++ b/mac/Sources/CodeBurnMenubar/Views/AgentTabStrip.swift @@ -113,13 +113,19 @@ struct AgentTabStrip: View { } private var visibleFilters: [ProviderFilter] { - // Tabs reflect the SELECTED range: every provider with usage (cost > 0) - // in the period, ordered by usage. Providers with no usage in the range - // are omitted. `.all` always leads. cost(for:) reads periodAll, so this - // updates as the user switches periods. + // Tabs reflect the selected range. The payload's activity signal keeps + // token-only and subscription/flat-rate providers visible while hiding + // providers merely discovered on disk. Older payloads lack the activity + // signal, so they preserve detected-provider visibility for compatibility. + let activeKeys = ProviderVisibility.activeKeys( + providerDetails: periodAll.current.providerDetails, + legacyProviders: periodAll.current.providers + ) let costs = Dictionary(uniqueKeysWithValues: ProviderFilter.allCases.map { ($0, cost(for: $0) ?? 0) }) let detected = ProviderFilter.allCases.filter { filter in - filter == .all || (costs[filter] ?? 0) > 0 + filter == .all + || activeKeys.contains(filter.cliArg) + || filter.providerKeys.contains(where: activeKeys.contains) } return detected.sorted { a, b in if a == .all { return true } diff --git a/mac/Sources/CodeBurnMenubar/Views/MenuBarContent.swift b/mac/Sources/CodeBurnMenubar/Views/MenuBarContent.swift index a9461be1..1ad37af7 100644 --- a/mac/Sources/CodeBurnMenubar/Views/MenuBarContent.swift +++ b/mac/Sources/CodeBurnMenubar/Views/MenuBarContent.swift @@ -97,19 +97,18 @@ struct MenuBarContent: View { // local usage — the quota endpoint doesn't depend on local sessions. if store.selectedProvider == .claude || store.selectedProvider == .codex || store.selectedProvider == .kimiCode || store.selectedProvider == .gemini { return false } if store.payload.current.cost > 0 || store.payload.current.calls > 0 { return false } - if providerHasCostInAllPayload { return false } + if providerHasUsageInAllPayload { return false } return true } - private var providerHasCostInAllPayload: Bool { + private var providerHasUsageInAllPayload: Bool { guard let allPayload = store.periodAllPayload else { return false } - let providers = Dictionary( - allPayload.current.providers.map { ($0.key.lowercased(), $0.value) }, - uniquingKeysWith: + + let activeKeys = ProviderVisibility.activeKeys( + providerDetails: allPayload.current.providerDetails, + legacyProviders: allPayload.current.providers ) - return store.selectedProvider.providerKeys.contains { key in - (providers[key] ?? 0) > 0 - } + return activeKeys.contains(store.selectedProvider.cliArg) + || store.selectedProvider.providerKeys.contains(where: activeKeys.contains) } /// Show the tab row whenever the CLI detected at least one AI coding tool installed diff --git a/mac/Tests/CodeBurnMenubarTests/AgentTabProviderVisibilityTests.swift b/mac/Tests/CodeBurnMenubarTests/AgentTabProviderVisibilityTests.swift new file mode 100644 index 00000000..71d356e5 --- /dev/null +++ b/mac/Tests/CodeBurnMenubarTests/AgentTabProviderVisibilityTests.swift @@ -0,0 +1,49 @@ +import Foundation +import Testing +@testable import CodeBurnMenubar + +@Suite("Agent tab provider visibility") +struct AgentTabProviderVisibilityTests { + @Test("zero-cost providers with usage remain active while idle providers stay hidden") + func zeroCostProvidersWithUsageRemainActive() { + let details = [ + ProviderDetail(id: "pi", label: "Pi", cost: 54.5, calls: 5, hasUsage: true), + ProviderDetail(id: "hermes", label: "Hermes Agent", cost: 0, calls: 0, hasUsage: true), + ProviderDetail(id: "claude", label: "Claude", cost: 0, calls: 0, hasUsage: false), + ] + + let keys = ProviderVisibility.activeKeys( + providerDetails: details, + legacyProviders: ["pi": 54.5, "hermes agent": 0, "claude": 0] + ) + + #expect(keys.contains("hermes")) + #expect(keys.contains("hermes agent")) + #expect(!keys.contains("claude")) + } + + @Test("legacy payloads keep detected providers visible when activity is unknowable") + func legacyDetectedProviderFallback() { + let keys = ProviderVisibility.activeKeys( + providerDetails: [], + legacyProviders: ["codex": 3.25, "hermes agent": 0] + ) + + #expect(keys == ["codex", "hermes agent"]) + } + + @Test("legacy provider details without activity fields fail open, while calls remain authoritative") + func legacyProviderDetailDecoding() throws { + let noSignal = try JSONDecoder().decode( + ProviderDetail.self, + from: Data(#"{"id":"hermes","label":"Hermes Agent","cost":0}"#.utf8) + ) + let explicitIdleCalls = try JSONDecoder().decode( + ProviderDetail.self, + from: Data(#"{"id":"hermes","label":"Hermes Agent","cost":0,"calls":0}"#.utf8) + ) + + #expect(noSignal.hasUsage) + #expect(!explicitIdleCalls.hasUsage) + } +} diff --git a/src/menubar-json.ts b/src/menubar-json.ts index 72b8c4be..df77dbed 100644 --- a/src/menubar-json.ts +++ b/src/menubar-json.ts @@ -80,6 +80,10 @@ export type ProviderCost = { name: string displayName: string cost: number + /** Behavioral calls in the selected period; token-only supplementary usage may be zero. */ + calls?: number + /** True when the selected period contains cost, calls, sessions, savings, or tokens. */ + hasUsage?: boolean } import type { OptimizeResult } from './optimize.js' import { getCurrency } from './currency.js' @@ -258,9 +262,10 @@ export type MenubarPayload = { localModelSavings: LocalModelSavings providers: Record /// Provider identity alongside the `providers` map: `id` is the internal - /// provider name (round-trips as `--provider`), `label` the display name. + /// provider name (round-trips as `--provider`), `label` the display name, + /// and `hasUsage` the period-activity signal used by provider pickers. /// The `providers` map keys stay lowercased display names for compatibility. - providerDetails: Array<{ id: string; label: string; cost: number }> + providerDetails: Array<{ id: string; label: string; cost: number; calls: number; hasUsage: boolean }> topProjects: Array<{ name: string cost: number @@ -462,7 +467,13 @@ function buildProviders(providers: ProviderCost[]): Record { function buildProviderDetails(providers: ProviderCost[]): MenubarPayload['current']['providerDetails'] { return providers .filter(p => p.cost >= 0) - .map(p => ({ id: p.name, label: p.displayName, cost: p.cost })) + .map(p => ({ + id: p.name, + label: p.displayName, + cost: p.cost, + calls: p.calls ?? 0, + hasUsage: p.hasUsage ?? (p.cost > 0 || (p.calls ?? 0) > 0), + })) } function buildHistory(daily: DailyHistoryEntry[] | undefined, timeline?: GranularHistory): MenubarPayload['history'] { diff --git a/src/usage-aggregator.ts b/src/usage-aggregator.ts index bf285d9b..babc9eb2 100644 --- a/src/usage-aggregator.ts +++ b/src/usage-aggregator.ts @@ -22,6 +22,17 @@ import { buildGranularHistory } from './granular-history.js' const TOP_BRANCHES = 15 type SubagentRow = NonNullable[number] +export function providerSliceHasUsage(slice: ProviderDaySlice): boolean { + return slice.cost > 0 + || slice.savingsUSD > 0 + || slice.calls > 0 + || (slice.sessions ?? 0) > 0 + || (slice.inputTokens ?? 0) > 0 + || (slice.outputTokens ?? 0) > 0 + || (slice.cacheReadTokens ?? 0) > 0 + || (slice.cacheWriteTokens ?? 0) > 0 +} + export function buildPeriodData(label: string, projects: ProjectSummary[]): PeriodData { const sessions = projects.flatMap(p => p.sessions) @@ -763,23 +774,29 @@ export async function buildMenubarPayloadForRange(periodInfo: PeriodInfo, opts: ) // PROVIDERS - // For .all: enumerate every provider with cost across the period (from cache) + installed-but-zero. - // For specific: just this single provider with its scoped cost. + // For .all: enumerate every provider with usage across the period (from cache) + installed-but-idle. + // `hasUsage` preserves token-only and subscription-backed activity while + // distinguishing a provider merely discovered on disk. + // For specific: just this single provider with its scoped totals. const allProviders = await getAllProviders() const displayNameByName = new Map(allProviders.map(p => [p.name, p.displayName])) const providers: ProviderCost[] = [] if (isClaudeConfigScoped) { - const providerTotals: Record = {} + const providerTotals: Record = {} for (const d of aggregateProjectsIntoDays(scanProjects)) { for (const [name, p] of Object.entries(d.providers)) { - providerTotals[name] = (providerTotals[name] ?? 0) + p.cost + const total = providerTotals[name] ?? { cost: 0, calls: 0, hasUsage: false } + total.cost += p.cost + total.calls += p.calls + total.hasUsage ||= providerSliceHasUsage(p) + providerTotals[name] = total } } - for (const [name, cost] of Object.entries(providerTotals)) { - providers.push({ name, displayName: displayNameByName.get(name) ?? name, cost }) + for (const [name, total] of Object.entries(providerTotals)) { + providers.push({ name, displayName: displayNameByName.get(name) ?? name, ...total }) } if (providers.length === 0 && claudeConfigs?.selectedId) { - providers.push({ name: 'claude', displayName: displayNameByName.get('claude') ?? 'Claude', cost: 0 }) + providers.push({ name: 'claude', displayName: displayNameByName.get('claude') ?? 'Claude', cost: 0, calls: 0, hasUsage: false }) } } else if (isAllProviders) { // Reuse the day set the headline was built from instead of rebuilding one @@ -794,22 +811,39 @@ export async function buildMenubarPayloadForRange(periodInfo: PeriodInfo, opts: // implies !isClaudeConfigScoped, which forces the !effectivelyScoped path that // assigns it. const allDaysForProviders = cacheDaysForPeriod ?? [] - const providerTotals: Record = {} + const providerTotals: Record = {} for (const d of allDaysForProviders) { for (const [name, p] of Object.entries(d.providers)) { - providerTotals[name] = (providerTotals[name] ?? 0) + p.cost + const total = providerTotals[name] ?? { cost: 0, calls: 0, hasUsage: false } + total.cost += p.cost + total.calls += p.calls + total.hasUsage ||= providerSliceHasUsage(p) + providerTotals[name] = total } } - for (const [name, cost] of Object.entries(providerTotals)) { - providers.push({ name, displayName: displayNameByName.get(name) ?? name, cost }) + for (const [name, total] of Object.entries(providerTotals)) { + providers.push({ name, displayName: displayNameByName.get(name) ?? name, ...total }) } for (const p of allProviders) { if (providers.some(pc => pc.name === p.name)) continue const sources = await safeDiscoverSessions(p) - if (sources.length > 0) providers.push({ name: p.name, displayName: p.displayName, cost: 0 }) + if (sources.length > 0) providers.push({ name: p.name, displayName: p.displayName, cost: 0, calls: 0, hasUsage: false }) } } else { - providers.push({ name: pf, displayName: displayNameByName.get(pf) ?? pf, cost: currentData.cost }) + providers.push({ + name: pf, + displayName: displayNameByName.get(pf) ?? pf, + cost: currentData.cost, + calls: currentData.calls, + hasUsage: currentData.cost > 0 + || currentData.savingsUSD > 0 + || currentData.calls > 0 + || currentData.sessions > 0 + || currentData.inputTokens > 0 + || currentData.outputTokens > 0 + || currentData.cacheReadTokens > 0 + || currentData.cacheWriteTokens > 0, + }) } // DAILY HISTORY (last 365 days) diff --git a/tests/cli-status-menubar.test.ts b/tests/cli-status-menubar.test.ts index 8cc19b1f..19ef9c0a 100644 --- a/tests/cli-status-menubar.test.ts +++ b/tests/cli-status-menubar.test.ts @@ -129,6 +129,49 @@ describe('codeburn status --format menubar-json', () => { } }) + it('reports calls for a zero-cost provider so the menubar can show its tab', async () => { + const home = await mkdtemp(join(tmpdir(), 'codeburn-menubar-zero-cost-provider-')) + + try { + const projectDir = join(home, '.claude', 'projects', 'myapp') + await mkdir(projectDir, { recursive: true }) + const now = new Date() + const todayUtcMidnight = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()) + const userAt = new Date(Math.max(todayUtcMidnight, now.getTime() - 60_000)) + const ts1 = userAt.toISOString().replace(/\.\d+Z$/, 'Z') + const ts2 = now.toISOString().replace(/\.\d+Z$/, 'Z') + await writeFile( + join(projectDir, 'session.jsonl'), + [ + userLine('zero-cost', ts1), + assistantLine('zero-cost', ts2, 'msg-zero-cost', 'definitely-unpriced-model'), + ].join('\n'), + ) + + const result = runCli([ + 'status', + '--format', 'menubar-json', + '--period', 'today', + '--provider', 'all', + '--no-optimize', + '--no-timeline', + ], home) + + expect(result.status, `stderr: ${result.stderr}`).toBe(0) + const payload = JSON.parse(result.stdout) as { + current: { providerDetails: Array<{ id: string; cost: number; calls: number; hasUsage: boolean }> } + } + expect(payload.current.providerDetails.find(p => p.id === 'claude')).toMatchObject({ + id: 'claude', + cost: 0, + calls: 1, + hasUsage: true, + }) + } finally { + await rm(home, { recursive: true, force: true }) + } + }) + it('omits history.timeline with --no-timeline, includes it by default', async () => { const home = await mkdtemp(join(tmpdir(), 'codeburn-menubar-tl-')) try { diff --git a/tests/menubar-json.test.ts b/tests/menubar-json.test.ts index c499bee3..b844bff1 100644 --- a/tests/menubar-json.test.ts +++ b/tests/menubar-json.test.ts @@ -262,14 +262,40 @@ describe('buildMenubarPayload', () => { const payload = buildMenubarPayload(emptyPeriod('Today'), providers, null) // providerDetails carries the internal id (round-trips as --provider) + label. expect(payload.current.providerDetails).toEqual([ - { id: 'grok', label: 'Grok Build', cost: 12.5 }, - { id: 'cursor-agent', label: 'Cursor Agent', cost: 3.4 }, + { id: 'grok', label: 'Grok Build', cost: 12.5, calls: 0, hasUsage: true }, + { id: 'cursor-agent', label: 'Cursor Agent', cost: 3.4, calls: 0, hasUsage: true }, ]) // ... while the existing providers map keys stay the lowercased display names. expect(payload.current.providers).toEqual({ 'grok build': 12.5, 'cursor agent': 3.4 }) }) - it('keeps zero-cost providers in the dict so installed-but-unused providers still render as tabs', () => { + it('preserves zero-cost provider usage counts for menubar provider visibility', () => { + const providers = [ + { name: 'hermes', displayName: 'Hermes Agent', cost: 0, calls: 7 }, + { name: 'claude', displayName: 'Claude', cost: 0, calls: 0 }, + ] satisfies Array + + const payload = buildMenubarPayload(emptyPeriod('Today'), providers, null) + + expect(payload.current.providerDetails).toEqual([ + { id: 'hermes', label: 'Hermes Agent', cost: 0, calls: 7, hasUsage: true }, + { id: 'claude', label: 'Claude', cost: 0, calls: 0, hasUsage: false }, + ]) + }) + + it('preserves token-only provider activity even when cost and behavioral calls are zero', () => { + const providers = [ + { name: 'hermes', displayName: 'Hermes Agent', cost: 0, calls: 0, hasUsage: true }, + ] satisfies Array + + const payload = buildMenubarPayload(emptyPeriod('Today'), providers, null) + + expect(payload.current.providerDetails).toEqual([ + { id: 'hermes', label: 'Hermes Agent', cost: 0, calls: 0, hasUsage: true }, + ]) + }) + + it('keeps zero-cost detected providers in the legacy dict for compatibility', () => { const providers: ProviderCost[] = [ { name: 'claude', displayName: 'Claude', cost: 76.45 }, { name: 'codex', displayName: 'Codex', cost: 0 }, @@ -349,7 +375,7 @@ describe('buildMenubarPayload', () => { ] const payload = buildMenubarPayload(emptyPeriod('Today'), providers, null) expect(payload.current.providers).toEqual({ claude: 76.45 }) - expect(payload.current.providerDetails).toEqual([{ id: 'claude', label: 'Claude', cost: 76.45 }]) + expect(payload.current.providerDetails).toEqual([{ id: 'claude', label: 'Claude', cost: 76.45, calls: 0, hasUsage: true }]) }) it('omits combined usage by default and accepts the documented combined shape when attached', () => { diff --git a/tests/usage-aggregator.test.ts b/tests/usage-aggregator.test.ts index 2e15a403..4c4ab729 100644 --- a/tests/usage-aggregator.test.ts +++ b/tests/usage-aggregator.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, beforeAll } from 'vitest' -import { buildMenubarPayloadForRange } from '../src/usage-aggregator.js' +import { buildMenubarPayloadForRange, providerSliceHasUsage } from '../src/usage-aggregator.js' import { getDateRange } from '../src/cli-date.js' import { loadPricing } from '../src/models.js' @@ -8,6 +8,16 @@ describe('buildMenubarPayloadForRange', () => { await loadPricing() }) + it('treats token-only provider slices as usage', () => { + expect(providerSliceHasUsage({ + calls: 0, + cost: 0, + savingsUSD: 0, + inputTokens: 1, + })).toBe(true) + expect(providerSliceHasUsage({ calls: 0, cost: 0, savingsUSD: 0 })).toBe(false) + }) + it('returns a valid payload and skips optimize findings when optimize:false', async () => { const payload = await buildMenubarPayloadForRange(getDateRange('today'), { provider: 'all', optimize: false }) expect(typeof payload.current.label).toBe('string') diff --git a/windows/src/lib/payload.ts b/windows/src/lib/payload.ts index e4d34755..944aaca9 100644 --- a/windows/src/lib/payload.ts +++ b/windows/src/lib/payload.ts @@ -15,6 +15,13 @@ export type MenubarPayload = { topActivities: Activity[] topModels: Model[] providers: Record + providerDetails?: Array<{ + id: string + label: string + cost: number + calls?: number + hasUsage?: boolean + }> } optimize: { findingCount: number