mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-11-29 10:43:47 +00:00
fix menubar provider usage contracts
This commit is contained in:
parent
41f44edc7f
commit
7106db2c0e
22 changed files with 519 additions and 118 deletions
|
|
@ -498,14 +498,13 @@ describe('App shortcuts', () => {
|
|||
await waitFor(() => expect(mocks.getOverview).toHaveBeenCalledWith('30days', 'grok'))
|
||||
})
|
||||
|
||||
it('lists a detected provider with no spend this period and sorts it last', async () => {
|
||||
// Hermes has usage only outside the current period: the CLI still emits it
|
||||
// as a detected provider (cost 0), so the picker must show it, at the bottom.
|
||||
it('hides idle providers while preserving explicit zero-cost activity', async () => {
|
||||
const payload = overviewPayload()
|
||||
payload.current.providers = { claude: 10, hermes: 0 }
|
||||
payload.current.providers = { claude: 10, hermes: 0, cursor: 0 }
|
||||
payload.current.providerDetails = [
|
||||
{ id: 'claude', label: 'Claude', cost: 10 },
|
||||
{ id: 'hermes', label: 'Hermes', cost: 0 },
|
||||
{ id: 'claude', label: 'Claude', cost: 10, hasUsage: true },
|
||||
{ id: 'hermes', label: 'Hermes', cost: 0, hasUsage: false },
|
||||
{ id: 'cursor', label: 'Cursor', cost: 0, hasUsage: true },
|
||||
]
|
||||
mocks.getOverview.mockResolvedValue(payload)
|
||||
|
||||
|
|
@ -513,14 +512,9 @@ describe('App shortcuts', () => {
|
|||
expect(await screen.findByText('Most expensive sessions')).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByText('All providers'))
|
||||
const claudeOption = await screen.findByRole('option', { name: 'Claude' })
|
||||
const hermesOption = screen.getByRole('option', { name: 'Hermes' })
|
||||
const options = screen.getAllByRole('option')
|
||||
// Zero-cost Hermes appears, and sorts after the provider that has spend.
|
||||
expect(options.indexOf(hermesOption)).toBeGreaterThan(options.indexOf(claudeOption))
|
||||
|
||||
fireEvent.click(hermesOption)
|
||||
await waitFor(() => expect(mocks.getOverview).toHaveBeenCalledWith('30days', 'hermes'))
|
||||
expect(await screen.findByRole('option', { name: 'Claude' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('option', { name: 'Cursor' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('option', { name: 'Hermes' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('hides the Claude config picker when the payload carries no claudeConfigs', async () => {
|
||||
|
|
|
|||
|
|
@ -388,30 +388,29 @@ function AppMain() {
|
|||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!overview.data) return
|
||||
// Only the all-provider payload is authoritative for the picker. A scoped
|
||||
// payload contains just the selected provider; merging it forever also
|
||||
// leaked idle providers across period changes.
|
||||
if (!overview.data || provider !== 'all') return
|
||||
const details = overview.data.current.providerDetails
|
||||
// Prefer providerDetails (internal id + display label); fall back to the
|
||||
// providers map keys (lowercased display names) for older CLIs. The CLI
|
||||
// only emits detected providers, so keep every entry (including ones with
|
||||
// no spend this period) and sort by cost so zero-cost ones sit at the
|
||||
// bottom of the picker.
|
||||
// providers map keys (lowercased display names) for older CLIs. Explicit
|
||||
// `hasUsage` preserves subscription-backed zero-cost activity while idle
|
||||
// discovery rows stay out of the selected-period picker.
|
||||
const found = details
|
||||
? [...details]
|
||||
.filter(entry => entry.hasUsage ?? entry.cost > 0)
|
||||
.sort((a, b) => b.cost - a.cost)
|
||||
.map(entry => ({ id: entry.id, label: entry.label }))
|
||||
: Object.entries(overview.data.current.providers)
|
||||
// Fallback map keys are lowercased display names; ones with spaces
|
||||
// ("grok build") cannot round-trip as --provider, so exclude them
|
||||
// rather than offer a filter that is guaranteed to error.
|
||||
.filter(([key]) => /^[a-z0-9-]+$/.test(key))
|
||||
.filter(([key, cost]) => cost > 0 && /^[a-z0-9-]+$/.test(key))
|
||||
.sort(([, a], [, b]) => b - a)
|
||||
.map(([key]) => ({ id: key, label: providerName(key) }))
|
||||
setDetectedProviders(current => {
|
||||
const next = [...current]
|
||||
for (const item of found) if (!next.some(entry => entry.id === item.id)) next.push(item)
|
||||
return next.length === current.length ? current : next
|
||||
})
|
||||
}, [overview.data])
|
||||
setDetectedProviders(found)
|
||||
}, [overview.data, provider])
|
||||
|
||||
useEffect(() => {
|
||||
const currency = overview.data?.currency
|
||||
|
|
|
|||
|
|
@ -209,6 +209,7 @@ final class AppStore {
|
|||
private var antigravityRefreshGen: Int = 0
|
||||
|
||||
private var cache: [PayloadCacheKey: CachedPayload] = [:]
|
||||
private var selectionFallbackPayload: MenubarPayload?
|
||||
private var cacheDate: String = ""
|
||||
private var switchTask: Task<Void, Never>?
|
||||
private var payloadRefreshGeneration: UInt64 = 0
|
||||
|
|
@ -301,7 +302,7 @@ final class AppStore {
|
|||
return combinedPayload
|
||||
}
|
||||
}
|
||||
return cache[currentKey]?.payload ?? .empty
|
||||
return cache[currentKey]?.payload ?? selectionFallbackPayload ?? .empty
|
||||
}
|
||||
|
||||
/// Today (across all providers) backs day-specific views in the popover.
|
||||
|
|
@ -580,6 +581,9 @@ final class AppStore {
|
|||
/// Existing content stays mounted while the background fetch runs, so a tab
|
||||
/// click never becomes a loading gate or resets unrelated in-flight work.
|
||||
func switchTo(provider: ProviderFilter) {
|
||||
if provider != selectedProvider, hasCachedData {
|
||||
selectionFallbackPayload = payload
|
||||
}
|
||||
selectedProvider = provider
|
||||
// A Claude config scope only applies to All/Claude views; picking any
|
||||
// other provider tab clears it (the CLI rejects the contradictory combo).
|
||||
|
|
@ -664,6 +668,7 @@ final class AppStore {
|
|||
lastErrorByKey.removeAll()
|
||||
if clearCache {
|
||||
cache.removeAll()
|
||||
selectionFallbackPayload = nil
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -727,6 +732,7 @@ final class AppStore {
|
|||
if cacheDate != today {
|
||||
payloadRefreshGeneration &+= 1
|
||||
cache.removeAll()
|
||||
selectionFallbackPayload = nil
|
||||
loadingCountsByKey.removeAll()
|
||||
loadingStartedAtByKey.removeAll()
|
||||
inFlightKeys.removeAll()
|
||||
|
|
@ -739,6 +745,7 @@ final class AppStore {
|
|||
|
||||
func invalidateCache() {
|
||||
cache.removeAll()
|
||||
selectionFallbackPayload = nil
|
||||
}
|
||||
|
||||
private func reconcileClaudeConfigSelection(from payload: MenubarPayload, for key: PayloadCacheKey) {
|
||||
|
|
@ -906,6 +913,9 @@ final class AppStore {
|
|||
return false
|
||||
}
|
||||
cache[key] = CachedPayload(payload: fresh, fetchedAt: Date())
|
||||
if key == currentKey || (effectiveSelectedScope == .combined && key == localCurrentKey) {
|
||||
selectionFallbackPayload = nil
|
||||
}
|
||||
reconcileClaudeConfigSelection(from: fresh, for: key)
|
||||
lastSuccessByKey[key] = Date()
|
||||
lastErrorByKey[key] = nil
|
||||
|
|
@ -2242,7 +2252,7 @@ enum ProviderFilter: String, CaseIterable, Identifiable {
|
|||
switch self {
|
||||
case .cursor: ["cursor"]
|
||||
case .cursorAgent: ["cursor-agent", "cursor agent"]
|
||||
case .cline: ["cline"]
|
||||
case .cline: ["cline", "cline-cli"]
|
||||
case .codewhale: ["codewhale"]
|
||||
case .rooCode: ["roo-code", "roo code"]
|
||||
case .kiloCode: ["kilo-code", "kilocode"]
|
||||
|
|
|
|||
|
|
@ -317,9 +317,9 @@ struct ProviderDetail: Codable, Sendable {
|
|||
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.
|
||||
// Older CLIs emitted providerDetails without calls/hasUsage. Those
|
||||
// payloads cannot distinguish period activity from a provider merely
|
||||
// discovered on disk, so cost is the only safe activity signal.
|
||||
let decodedCalls = try c.decodeIfPresent(Int.self, forKey: .calls)
|
||||
calls = decodedCalls ?? 0
|
||||
if let decodedUsage = try c.decodeIfPresent(Bool.self, forKey: .hasUsage) {
|
||||
|
|
@ -327,7 +327,7 @@ struct ProviderDetail: Codable, Sendable {
|
|||
} else if decodedCalls != nil {
|
||||
hasUsage = cost > 0 || calls > 0
|
||||
} else {
|
||||
hasUsage = true
|
||||
hasUsage = cost > 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -342,7 +342,9 @@ enum ProviderVisibility {
|
|||
.filter(\.hasUsage)
|
||||
.flatMap { [$0.id.lowercased(), $0.label.lowercased()] })
|
||||
}
|
||||
return Set(legacyProviders.keys.map { $0.lowercased() })
|
||||
return Set(legacyProviders.compactMap { key, cost in
|
||||
cost > 0 ? key.lowercased() : nil
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,34 @@
|
|||
import Foundation
|
||||
|
||||
struct ProviderReconnectPresentation: Sendable, Equatable {
|
||||
let title: String
|
||||
let defaultReason: String
|
||||
let instruction: String
|
||||
|
||||
init(provider: ProviderFilter) {
|
||||
title = "Reconnect \(provider.rawValue)"
|
||||
switch provider {
|
||||
case .claude:
|
||||
defaultReason = "Claude Code credentials need to be refreshed."
|
||||
instruction = "Open Claude Code in your terminal and type `/login`, then click Reconnect."
|
||||
case .codex:
|
||||
defaultReason = "Codex credentials need to be refreshed."
|
||||
instruction = "Run `codex login` in your terminal, then click Reconnect."
|
||||
case .kimiCode:
|
||||
defaultReason = "Kimi Code credentials need to be refreshed."
|
||||
instruction = "Run the Kimi CLI once to refresh your login, then click Reconnect."
|
||||
case .gemini:
|
||||
defaultReason = "Gemini credentials need to be refreshed."
|
||||
instruction = "Run the Gemini CLI once to refresh your login, then click Reconnect."
|
||||
case .copilot:
|
||||
defaultReason = "Copilot credentials need to be refreshed."
|
||||
instruction = "Sign in with the Copilot CLI, an editor plugin, or `gh auth login`, then click Reconnect."
|
||||
case .antigravity:
|
||||
defaultReason = "The local Antigravity service is unavailable."
|
||||
instruction = "Start the Antigravity app, then click Reconnect."
|
||||
default:
|
||||
defaultReason = "\(provider.rawValue) credentials need to be refreshed."
|
||||
instruction = "Sign in to \(provider.rawValue) again, then retry."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
import Foundation
|
||||
|
||||
struct ProviderStripPagingState: Sendable, Equatable {
|
||||
let filters: [ProviderFilter]
|
||||
let selectedProvider: ProviderFilter
|
||||
private(set) var viewportAnchor: ProviderFilter?
|
||||
|
||||
init(
|
||||
filters: [ProviderFilter],
|
||||
selectedProvider: ProviderFilter,
|
||||
viewportAnchor: ProviderFilter?
|
||||
) {
|
||||
self.filters = filters
|
||||
self.selectedProvider = selectedProvider
|
||||
if let viewportAnchor, filters.contains(viewportAnchor) {
|
||||
self.viewportAnchor = viewportAnchor
|
||||
} else if filters.contains(selectedProvider) {
|
||||
self.viewportAnchor = selectedProvider
|
||||
} else {
|
||||
self.viewportAnchor = filters.first
|
||||
}
|
||||
}
|
||||
|
||||
var canMoveBackward: Bool { anchorIndex > 0 }
|
||||
var canMoveForward: Bool { anchorIndex >= 0 && anchorIndex < filters.count - 1 }
|
||||
|
||||
@discardableResult
|
||||
mutating func move(direction: Int) -> ProviderFilter? {
|
||||
guard !filters.isEmpty, direction != 0 else { return viewportAnchor }
|
||||
let targetIndex = min(max(anchorIndex + (direction < 0 ? -1 : 1), 0), filters.count - 1)
|
||||
viewportAnchor = filters[targetIndex]
|
||||
return viewportAnchor
|
||||
}
|
||||
|
||||
private var anchorIndex: Int {
|
||||
guard let viewportAnchor else { return -1 }
|
||||
return filters.firstIndex(of: viewportAnchor) ?? -1
|
||||
}
|
||||
}
|
||||
|
|
@ -16,6 +16,7 @@ struct AgentTabStrip: View {
|
|||
@State private var stripViewportWidth: CGFloat = 0
|
||||
@State private var stripContentWidth: CGFloat = 0
|
||||
@State private var scrollWheelMonitor: Any?
|
||||
@State private var viewportAnchor: ProviderFilter?
|
||||
|
||||
var body: some View {
|
||||
GeometryReader { viewportGeo in
|
||||
|
|
@ -23,7 +24,7 @@ struct AgentTabStrip: View {
|
|||
HStack(spacing: 4) {
|
||||
if isOverflowing {
|
||||
Button {
|
||||
selectAdjacentProvider(direction: -1, proxy: proxy)
|
||||
pageProviderStrip(direction: -1, proxy: proxy)
|
||||
} label: {
|
||||
Image(systemName: "chevron.left")
|
||||
.font(.system(size: 10, weight: .semibold))
|
||||
|
|
@ -44,6 +45,7 @@ struct AgentTabStrip: View {
|
|||
isActive: store.selectedProvider == filter,
|
||||
quota: store.quotaSummary(for: filter)
|
||||
) {
|
||||
viewportAnchor = filter
|
||||
store.switchTo(provider: filter)
|
||||
withAnimation(.easeInOut(duration: 0.18)) {
|
||||
proxy.scrollTo(filter.id, anchor: .center)
|
||||
|
|
@ -73,7 +75,7 @@ struct AgentTabStrip: View {
|
|||
|
||||
if isOverflowing {
|
||||
Button {
|
||||
selectAdjacentProvider(direction: 1, proxy: proxy)
|
||||
pageProviderStrip(direction: 1, proxy: proxy)
|
||||
} label: {
|
||||
Image(systemName: "chevron.right")
|
||||
.font(.system(size: 10, weight: .semibold))
|
||||
|
|
@ -88,16 +90,30 @@ struct AgentTabStrip: View {
|
|||
.onAppear {
|
||||
stripViewportWidth = viewportGeo.size.width
|
||||
installScrollWheelMonitorIfNeeded()
|
||||
viewportAnchor = pagingState.viewportAnchor
|
||||
withAnimation(.easeInOut(duration: 0.18)) {
|
||||
proxy.scrollTo(store.selectedProvider.id, anchor: .center)
|
||||
if let viewportAnchor {
|
||||
proxy.scrollTo(viewportAnchor.id, anchor: .center)
|
||||
}
|
||||
}
|
||||
}
|
||||
.onChange(of: viewportGeo.size.width) { _, newWidth in
|
||||
stripViewportWidth = newWidth
|
||||
}
|
||||
.onChange(of: store.selectedProvider) { _, newProvider in
|
||||
viewportAnchor = visibleFilters.contains(newProvider) ? newProvider : pagingState.viewportAnchor
|
||||
withAnimation(.easeInOut(duration: 0.18)) {
|
||||
proxy.scrollTo(newProvider.id, anchor: .center)
|
||||
if let viewportAnchor {
|
||||
proxy.scrollTo(viewportAnchor.id, anchor: .center)
|
||||
}
|
||||
}
|
||||
}
|
||||
.onChange(of: visibleFilters) { _, _ in
|
||||
viewportAnchor = pagingState.viewportAnchor
|
||||
withAnimation(.easeInOut(duration: 0.18)) {
|
||||
if let viewportAnchor {
|
||||
proxy.scrollTo(viewportAnchor.id, anchor: .center)
|
||||
}
|
||||
}
|
||||
}
|
||||
.onDisappear {
|
||||
|
|
@ -149,19 +165,22 @@ struct AgentTabStrip: View {
|
|||
}
|
||||
}
|
||||
|
||||
private var currentFilterIndex: Int {
|
||||
visibleFilters.firstIndex(of: store.selectedProvider) ?? 0
|
||||
private var pagingState: ProviderStripPagingState {
|
||||
ProviderStripPagingState(
|
||||
filters: visibleFilters,
|
||||
selectedProvider: store.selectedProvider,
|
||||
viewportAnchor: viewportAnchor
|
||||
)
|
||||
}
|
||||
|
||||
private var canMoveBackward: Bool { currentFilterIndex > 0 }
|
||||
private var canMoveForward: Bool { currentFilterIndex < visibleFilters.count - 1 }
|
||||
private var canMoveBackward: Bool { pagingState.canMoveBackward }
|
||||
private var canMoveForward: Bool { pagingState.canMoveForward }
|
||||
private var isOverflowing: Bool { stripContentWidth > (stripViewportWidth - 30) }
|
||||
|
||||
private func selectAdjacentProvider(direction: Int, proxy: ScrollViewProxy) {
|
||||
guard !visibleFilters.isEmpty else { return }
|
||||
let targetIndex = min(max(currentFilterIndex + direction, 0), visibleFilters.count - 1)
|
||||
let target = visibleFilters[targetIndex]
|
||||
store.switchTo(provider: target)
|
||||
private func pageProviderStrip(direction: Int, proxy: ScrollViewProxy) {
|
||||
var state = pagingState
|
||||
guard let target = state.move(direction: direction) else { return }
|
||||
viewportAnchor = target
|
||||
withAnimation(.easeInOut(duration: 0.18)) {
|
||||
proxy.scrollTo(target.id, anchor: .center)
|
||||
}
|
||||
|
|
@ -410,38 +429,21 @@ private struct QuotaDetailPopover: View {
|
|||
|
||||
private func terminalFailureCard(reason: String?) -> some View {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
Text(reconnectTitle)
|
||||
Text(reconnectPresentation.title)
|
||||
.font(.system(size: 11.5, weight: .semibold))
|
||||
.foregroundStyle(.red)
|
||||
Text(reason ?? defaultReconnectReason)
|
||||
Text(reason ?? reconnectPresentation.defaultReason)
|
||||
.font(.system(size: 11))
|
||||
.foregroundStyle(.secondary)
|
||||
.lineLimit(2)
|
||||
Text(reconnectInstruction)
|
||||
Text(reconnectPresentation.instruction)
|
||||
.font(.system(size: 10.5))
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
|
||||
private var reconnectTitle: String {
|
||||
switch quota.providerFilter {
|
||||
case .codex: return "Reconnect Codex"
|
||||
default: return "Reconnect Claude"
|
||||
}
|
||||
}
|
||||
|
||||
private var defaultReconnectReason: String {
|
||||
switch quota.providerFilter {
|
||||
case .codex: return "Refresh token rejected by OpenAI."
|
||||
default: return "Refresh token rejected by Anthropic."
|
||||
}
|
||||
}
|
||||
|
||||
private var reconnectInstruction: String {
|
||||
switch quota.providerFilter {
|
||||
case .codex: return "Run `codex login` in your terminal, then click Reconnect."
|
||||
default: return "Open Claude Code in your terminal and type `/login`, then click Reconnect."
|
||||
}
|
||||
private var reconnectPresentation: ProviderReconnectPresentation {
|
||||
ProviderReconnectPresentation(provider: quota.providerFilter)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -4,6 +4,11 @@ import Testing
|
|||
|
||||
@Suite("Agent tab provider visibility")
|
||||
struct AgentTabProviderVisibilityTests {
|
||||
@Test func clineFilterRecognizesBothNativeAndCLIProviderIds() {
|
||||
#expect(ProviderFilter.cline.providerKeys.contains("cline"))
|
||||
#expect(ProviderFilter.cline.providerKeys.contains("cline-cli"))
|
||||
}
|
||||
|
||||
@Test("zero-cost providers with usage remain active while idle providers stay hidden")
|
||||
func zeroCostProvidersWithUsageRemainActive() {
|
||||
let details = [
|
||||
|
|
@ -22,28 +27,33 @@ struct AgentTabProviderVisibilityTests {
|
|||
#expect(!keys.contains("claude"))
|
||||
}
|
||||
|
||||
@Test("legacy payloads keep detected providers visible when activity is unknowable")
|
||||
func legacyDetectedProviderFallback() {
|
||||
@Test("legacy payloads show only providers with period spend")
|
||||
func legacyProviderCostFallback() {
|
||||
let keys = ProviderVisibility.activeKeys(
|
||||
providerDetails: [],
|
||||
legacyProviders: ["codex": 3.25, "hermes agent": 0]
|
||||
)
|
||||
|
||||
#expect(keys == ["codex", "hermes agent"])
|
||||
#expect(keys == ["codex"])
|
||||
}
|
||||
|
||||
@Test("legacy provider details without activity fields fail open, while calls remain authoritative")
|
||||
@Test("legacy provider details require a positive cost or call signal")
|
||||
func legacyProviderDetailDecoding() throws {
|
||||
let noSignal = try JSONDecoder().decode(
|
||||
ProviderDetail.self,
|
||||
from: Data(#"{"id":"hermes","label":"Hermes Agent","cost":0}"#.utf8)
|
||||
)
|
||||
let positiveLegacyCost = try JSONDecoder().decode(
|
||||
ProviderDetail.self,
|
||||
from: Data(#"{"id":"codex","label":"Codex","cost":1.25}"#.utf8)
|
||||
)
|
||||
let explicitIdleCalls = try JSONDecoder().decode(
|
||||
ProviderDetail.self,
|
||||
from: Data(#"{"id":"hermes","label":"Hermes Agent","cost":0,"calls":0}"#.utf8)
|
||||
)
|
||||
|
||||
#expect(noSignal.hasUsage)
|
||||
#expect(!noSignal.hasUsage)
|
||||
#expect(positiveLegacyCost.hasUsage)
|
||||
#expect(!explicitIdleCalls.hasUsage)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -84,6 +84,23 @@ private func menubarPayload(cost: Double,
|
|||
@Suite("AppStore refresh recovery")
|
||||
@MainActor
|
||||
struct AppStoreRefreshRecoveryTests {
|
||||
@Test("provider switches retain the last rendered payload until the target loads")
|
||||
func providerSwitchRetainsLastRenderedPayload() {
|
||||
let store = AppStore()
|
||||
store.suppressRefreshesForTesting()
|
||||
store.setCachedPayloadForTesting(
|
||||
menubarPayload(cost: 12.34),
|
||||
period: .today,
|
||||
provider: .all,
|
||||
fetchedAt: Date()
|
||||
)
|
||||
|
||||
store.switchTo(provider: .cursor)
|
||||
|
||||
#expect(store.selectedProvider == .cursor)
|
||||
#expect(store.payload.current.cost == 12.34)
|
||||
}
|
||||
|
||||
@Test("stale visible payload triggers hard recovery without clearing cache")
|
||||
func stalePayloadTriggersHardRecoveryWithoutClearingCache() {
|
||||
let store = AppStore()
|
||||
|
|
|
|||
|
|
@ -0,0 +1,36 @@
|
|||
import Testing
|
||||
@testable import CodeBurnMenubar
|
||||
|
||||
@Suite("Provider reconnect presentation")
|
||||
struct ProviderReconnectPresentationTests {
|
||||
@Test("every quota provider gets provider-specific recovery copy", arguments: [
|
||||
ProviderFilter.claude,
|
||||
.codex,
|
||||
.kimiCode,
|
||||
.gemini,
|
||||
.copilot,
|
||||
.antigravity,
|
||||
])
|
||||
func providerSpecificRecoveryCopy(_ provider: ProviderFilter) {
|
||||
let presentation = ProviderReconnectPresentation(provider: provider)
|
||||
|
||||
#expect(presentation.title == "Reconnect \(provider.rawValue)")
|
||||
#expect(!presentation.defaultReason.isEmpty)
|
||||
#expect(!presentation.instruction.isEmpty)
|
||||
|
||||
for other in ["Claude", "Codex", "Kimi", "Gemini", "Copilot", "Antigravity"]
|
||||
where other != provider.rawValue && !(provider == .kimiCode && other == "Kimi") {
|
||||
#expect(!presentation.title.contains(other))
|
||||
#expect(!presentation.instruction.contains(other))
|
||||
}
|
||||
}
|
||||
|
||||
@Test("unsupported providers receive neutral recovery copy")
|
||||
func genericRecoveryCopy() {
|
||||
let presentation = ProviderReconnectPresentation(provider: .cursor)
|
||||
|
||||
#expect(presentation.title == "Reconnect Cursor")
|
||||
#expect(presentation.defaultReason == "Cursor credentials need to be refreshed.")
|
||||
#expect(presentation.instruction == "Sign in to Cursor again, then retry.")
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
import Testing
|
||||
@testable import CodeBurnMenubar
|
||||
|
||||
@Suite("Provider strip paging")
|
||||
struct ProviderStripPagingStateTests {
|
||||
@Test("paging changes the viewport without selecting a provider")
|
||||
func pagingDoesNotSelect() {
|
||||
var state = ProviderStripPagingState(
|
||||
filters: [.all, .claude, .cursor],
|
||||
selectedProvider: .all,
|
||||
viewportAnchor: .all
|
||||
)
|
||||
|
||||
#expect(state.move(direction: 1) == .claude)
|
||||
#expect(state.viewportAnchor == .claude)
|
||||
#expect(state.selectedProvider == .all)
|
||||
|
||||
#expect(state.move(direction: 1) == .cursor)
|
||||
#expect(state.viewportAnchor == .cursor)
|
||||
#expect(state.selectedProvider == .all)
|
||||
#expect(!state.canMoveForward)
|
||||
}
|
||||
|
||||
@Test("paging clamps a missing anchor to the selected provider")
|
||||
func missingAnchorUsesSelection() {
|
||||
var state = ProviderStripPagingState(
|
||||
filters: [.all, .claude, .cursor],
|
||||
selectedProvider: .claude,
|
||||
viewportAnchor: .grok
|
||||
)
|
||||
|
||||
#expect(state.viewportAnchor == .claude)
|
||||
#expect(state.move(direction: -1) == .all)
|
||||
#expect(state.selectedProvider == .claude)
|
||||
}
|
||||
|
||||
@Test("an empty strip cannot page")
|
||||
func emptyStrip() {
|
||||
var state = ProviderStripPagingState(
|
||||
filters: [],
|
||||
selectedProvider: .all,
|
||||
viewportAnchor: nil
|
||||
)
|
||||
|
||||
#expect(state.move(direction: 1) == nil)
|
||||
#expect(!state.canMoveBackward)
|
||||
#expect(!state.canMoveForward)
|
||||
}
|
||||
}
|
||||
|
|
@ -27,7 +27,7 @@ import type { DateRange, ProjectSummary } from './types.js'
|
|||
// again here. 26 is the first free number on main's ladder — and it is load
|
||||
// bearing beyond the collision: the branch's own validators already hold
|
||||
// daily-cache.v21.json files whose copilot slices were carried stale by the
|
||||
// bug PENDING_REDERIVE_PROVIDERS fixes below, and only a number those files
|
||||
// bug PENDING_REDERIVE_PROVIDER_VERSIONS fixes below, and only a number those files
|
||||
// cannot claim gets them re-derived. isMigratableCache/adoptOlderDailyCaches
|
||||
// carry a same-or-newer version forward as FINALIZED without re-deriving it,
|
||||
// so a number can never mean two accountings. (feat/core-extraction also sits
|
||||
|
|
@ -174,7 +174,10 @@ import type { DateRange, ProjectSummary } from './types.js'
|
|||
// but optimize added reasoning again. Re-derive so report matches the live parse.
|
||||
// v29: #1118 OrcaRouter route pricing (fusion aliases + peel; auto stays unpriced).
|
||||
// v28 on main already shipped #1115.
|
||||
export const DAILY_CACHE_VERSION = 29
|
||||
// v30: Hermes cost provenance. Subscription-included sessions stay $0,
|
||||
// explicit estimates retain their status, and surviving Hermes sources replace
|
||||
// v29 slices produced by the old API-equivalent fallback.
|
||||
export const DAILY_CACHE_VERSION = 30
|
||||
const MIN_SUPPORTED_VERSION = 28
|
||||
|
||||
/// Providers whose per-day CALL COUNT means something different at
|
||||
|
|
@ -197,7 +200,16 @@ const MIN_SUPPORTED_VERSION = 28
|
|||
/// for the (day, provider). A day whose copilot sources are gone yields no
|
||||
/// fresh slice at all, so it still carries forward whole — the #1033 bar is
|
||||
/// untouched, in both directions, and every other provider keeps the guard.
|
||||
const PENDING_REDERIVE_PROVIDERS: readonly string[] = ['copilot']
|
||||
const PENDING_REDERIVE_PROVIDER_VERSIONS: Readonly<Record<string, number>> = {
|
||||
copilot: 26,
|
||||
hermes: 30,
|
||||
}
|
||||
|
||||
function providersPendingRederiveFrom(fromVersion: number): string[] {
|
||||
return Object.entries(PENDING_REDERIVE_PROVIDER_VERSIONS)
|
||||
.filter(([, contractVersion]) => fromVersion < contractVersion)
|
||||
.map(([provider]) => provider)
|
||||
}
|
||||
// Version-suffixed so different binaries each own a distinct file and never
|
||||
// clobber an incompatible schema. Bumping the version mints a fresh filename;
|
||||
// adoptOlderDailyCaches then unions days out of every previous file (including
|
||||
|
|
@ -299,7 +311,7 @@ export type DailyCache = {
|
|||
watermarkTrusted?: boolean
|
||||
/// Providers still owed the one re-derivation that a migration from a
|
||||
/// pre-`DAILY_CACHE_VERSION` cache entitles them to, despite a shrinking
|
||||
/// call count (see PENDING_REDERIVE_PROVIDERS). Set by the migration,
|
||||
/// call count (see PENDING_REDERIVE_PROVIDER_VERSIONS). Set by the migration,
|
||||
/// cleared by the first COMPLETE re-derive — persisted rather than computed
|
||||
/// so a partial parse in between does not silently spend the entitlement.
|
||||
pendingRederive?: string[]
|
||||
|
|
@ -453,7 +465,10 @@ function migrateDays(days: Record<string, unknown>[]): DailyEntry[] {
|
|||
/// an unspent entitlement out of the parsed file so a same-version reload does
|
||||
/// not drop it.
|
||||
function pendingRederiveFor(fromVersion: number, parsed: unknown): string[] | undefined {
|
||||
if (fromVersion < DAILY_CACHE_VERSION) return [...PENDING_REDERIVE_PROVIDERS]
|
||||
if (fromVersion < DAILY_CACHE_VERSION) {
|
||||
const pending = providersPendingRederiveFrom(fromVersion)
|
||||
return pending.length > 0 ? pending : undefined
|
||||
}
|
||||
const raw = (parsed as { pendingRederive?: unknown } | null)?.pendingRederive
|
||||
if (!Array.isArray(raw)) return undefined
|
||||
const kept = raw.filter((p): p is string => typeof p === 'string')
|
||||
|
|
@ -578,9 +593,17 @@ async function adoptOlderDailyCaches(): Promise<DailyCache> {
|
|||
days,
|
||||
// Anything adopted out of an OLDER file was derived under an older
|
||||
// accounting, so the providers whose call counts changed meaning get their
|
||||
// one guarded-shrink-exempt re-derivation (see PENDING_REDERIVE_PROVIDERS).
|
||||
pendingRederive: base.pendingRederive
|
||||
?? (rest.some(c => c.parsed.version < DAILY_CACHE_VERSION) ? [...PENDING_REDERIVE_PROVIDERS] : undefined),
|
||||
// one guarded-shrink-exempt re-derivation (see
|
||||
// PENDING_REDERIVE_PROVIDER_VERSIONS).
|
||||
pendingRederive: (() => {
|
||||
const pending = new Set(base.pendingRederive ?? [])
|
||||
for (const candidate of rest) {
|
||||
for (const provider of providersPendingRederiveFrom(candidate.parsed.version)) {
|
||||
pending.add(provider)
|
||||
}
|
||||
}
|
||||
return pending.size > 0 ? [...pending] : undefined
|
||||
})(),
|
||||
// An untrusted base means nothing here was derived under the current
|
||||
// accounting: leave complete unset so the next hydration re-derives every
|
||||
// day whose sources survive (the merge keeps the rest).
|
||||
|
|
@ -1091,7 +1114,7 @@ export function mergeDayEntries(
|
|||
guardPartialSurvival = false,
|
||||
/// Providers whose baseline slices were recorded under an accounting where a
|
||||
/// call meant something else, so a shrink is not evidence of source loss for
|
||||
/// this one re-derivation (see PENDING_REDERIVE_PROVIDERS). Only consulted
|
||||
/// this one re-derivation (see PENDING_REDERIVE_PROVIDER_VERSIONS). Only consulted
|
||||
/// where the fresh parse actually produced a slice for the (date, provider);
|
||||
/// a slice it could not produce at all is carried by the branch above,
|
||||
/// exactly as before.
|
||||
|
|
|
|||
|
|
@ -22,10 +22,10 @@ import type { CachedCall, ProviderSection } from './session-cache.js'
|
|||
// dropped: sealed days are not re-read. This slice does not bump
|
||||
// DAILY_CACHE_VERSION (one cold re-parse for every user) to recover history.
|
||||
|
||||
export const HERMES_SESSION_LEDGER_FILENAME = 'hermes-session-ledger.v1.json'
|
||||
export const HERMES_SESSION_LEDGER_VERSION = 1 as const
|
||||
export const HERMES_SESSION_LEDGER_FILENAME = 'hermes-session-ledger.v2.json'
|
||||
export const HERMES_SESSION_LEDGER_VERSION = 2 as const
|
||||
|
||||
export type HermesCostBasis = 'actual' | 'estimated' | 'calculated'
|
||||
export type HermesCostBasis = 'actual' | 'estimated' | 'calculated' | 'included'
|
||||
|
||||
export type HermesTokenTotals = {
|
||||
inputTokens: number
|
||||
|
|
@ -299,7 +299,7 @@ function isNum(v: unknown): v is number {
|
|||
}
|
||||
|
||||
function isCostBasis(v: unknown): v is HermesCostBasis {
|
||||
return v === 'actual' || v === 'estimated' || v === 'calculated'
|
||||
return v === 'actual' || v === 'estimated' || v === 'calculated' || v === 'included'
|
||||
}
|
||||
|
||||
function validateTokens(o: Record<string, unknown>): o is Record<string, unknown> & HermesTokenTotals {
|
||||
|
|
|
|||
|
|
@ -55,7 +55,7 @@ const { version } = require('../package.json')
|
|||
// Bump when the menubar payload's rendering semantics change without a package
|
||||
// release or daily-cache version change. The envelope version in session-cache
|
||||
// protects record shape; this protects the meaning of an otherwise valid one.
|
||||
const STATUS_SNAPSHOT_RENDER_VERSION = 2
|
||||
const STATUS_SNAPSHOT_RENDER_VERSION = 3
|
||||
const STATUS_SNAPSHOT_SEMANTIC_KEY = `${version}:render-${STATUS_SNAPSHOT_RENDER_VERSION}:daily-${DAILY_CACHE_VERSION}`
|
||||
import { loadCurrency, getCurrency, isValidCurrencyCode } from './currency.js'
|
||||
import { CodexThroughputReader, newestCodexSession, renderCodexThroughput } from './codex-throughput.js'
|
||||
|
|
|
|||
|
|
@ -37,6 +37,8 @@ type HermesSessionRow = {
|
|||
reasoning_tokens: number | null
|
||||
estimated_cost_usd: number | null
|
||||
actual_cost_usd: number | null
|
||||
cost_status: string | null
|
||||
cost_source: string | null
|
||||
api_call_count: number | null
|
||||
tool_call_count: number | null
|
||||
started_at: number | null
|
||||
|
|
@ -467,13 +469,20 @@ function resolveHermesCost(
|
|||
if (row && row.actual_cost_usd != null) {
|
||||
return { costUSD: row.actual_cost_usd, costIsEstimated: false, costBasis: 'actual' }
|
||||
}
|
||||
// estimated_cost_usd = 0.0 is not a measurement: Hermes writes it when cost_status
|
||||
// is 'unknown' (no pricing data) or 'included' (flat subscription), so trusting it
|
||||
// would zero out every subscription session. Only positive estimates are trusted;
|
||||
// anything else falls through to the token-based calculation. A genuinely free
|
||||
// model still lands on $0 either way, since litellm prices it at 0.
|
||||
const costStatus = row?.cost_status?.trim().toLowerCase()
|
||||
// Included subscription usage is real activity but not metered API spend.
|
||||
// Its recorded zero must win over API-equivalent token pricing.
|
||||
if (costStatus === 'included') {
|
||||
return { costUSD: 0, costIsEstimated: false, costBasis: 'included' }
|
||||
}
|
||||
// An explicit Hermes estimate is authoritative even when it is zero (for
|
||||
// example, a provider's free tier). Preserve that provenance in the UI.
|
||||
if (costStatus === 'estimated' && row?.estimated_cost_usd != null) {
|
||||
return { costUSD: row.estimated_cost_usd, costIsEstimated: true, costBasis: 'estimated' }
|
||||
}
|
||||
// Older Hermes schemas may have a positive estimate without cost_status.
|
||||
if (row && row.estimated_cost_usd != null && row.estimated_cost_usd > 0) {
|
||||
return { costUSD: row.estimated_cost_usd, costIsEstimated: false, costBasis: 'estimated' }
|
||||
return { costUSD: row.estimated_cost_usd, costIsEstimated: true, costBasis: 'estimated' }
|
||||
}
|
||||
return { costUSD: calculatedCost, costIsEstimated: true, costBasis: 'calculated' }
|
||||
}
|
||||
|
|
@ -507,9 +516,11 @@ function observationToCall(
|
|||
reasoningTokens: observation.reasoningTokens,
|
||||
webSearchRequests: 0,
|
||||
costUSD: observation.costUSD,
|
||||
// Later observations keep the stored basis: calculated stays estimated;
|
||||
// provider-recorded actual/estimated keep main's measured behavior.
|
||||
costIsEstimated: later ? observation.costBasis === 'calculated' : args.costIsEstimated,
|
||||
// Later observations keep the stored basis. Included and actual are
|
||||
// recorded facts; estimated and calculated remain estimates.
|
||||
costIsEstimated: later
|
||||
? observation.costBasis === 'calculated' || observation.costBasis === 'estimated'
|
||||
: args.costIsEstimated,
|
||||
tools: later ? [] : args.tools,
|
||||
bashCommands: later ? [] : args.bashCommands,
|
||||
timestamp: observation.timestamp,
|
||||
|
|
@ -637,6 +648,8 @@ function createParser(source: SessionSource, seenKeys: Set<string>, hermesHome:
|
|||
${numberColumn(columns, 'reasoning_tokens')},
|
||||
${nullableColumn(columns, 'estimated_cost_usd')},
|
||||
${nullableColumn(columns, 'actual_cost_usd')},
|
||||
${nullableColumn(columns, 'cost_status')},
|
||||
${nullableColumn(columns, 'cost_source')},
|
||||
${numberColumn(columns, 'api_call_count')},
|
||||
${numberColumn(columns, 'tool_call_count')},
|
||||
${nullableColumn(columns, 'started_at')},
|
||||
|
|
|
|||
|
|
@ -373,7 +373,9 @@ export const PROVIDER_PARSE_VERSIONS: Record<string, string> = {
|
|||
// replays (double-counted before), takes the model from the reporting
|
||||
// assistant/message, and keeps agent-injected context out of the preview.
|
||||
dsh: 'seed-aware-v1',
|
||||
hermes: 'reasoning-output-accounting-v1-est-cost-routed-ids-workspace-pr-v5-zero-estimate-fallback-v1',
|
||||
// cost-provenance-v2: preserve Hermes included/estimated/actual status and
|
||||
// rebuild the provider section alongside the v2 lifetime ledger.
|
||||
hermes: 'reasoning-output-accounting-v1-est-cost-routed-ids-workspace-pr-v5-cost-provenance-v2',
|
||||
'lingtai-tui': 'token-ledger-registry-activity-v3',
|
||||
'ibm-bob': 'worktree-project-grouping-v1',
|
||||
// project-path-v1: the parser now records the session's full working
|
||||
|
|
|
|||
|
|
@ -585,10 +585,14 @@ export async function buildDurablePeriod(periodInfo: PeriodInfo, opts: Aggregate
|
|||
: aggregateProjectsIntoDays(fp(await parseAllSessions(todayRange, 'all'))).filter(d => d.date === todayStr)
|
||||
}
|
||||
} else {
|
||||
// Provider-filtered: today's all-provider parse feeds the union (sliced
|
||||
// below); the provider-scoped parse feeds the detail/enrichment fields.
|
||||
todayAllDays = aggregateProjectsIntoDays(fp(await parseAllSessions(todayRange, 'all'))).filter(d => d.date === todayStr)
|
||||
// Provider-filtered: one provider-scoped parse feeds both today's union
|
||||
// slice and the detail/enrichment fields. Scanning every unrelated provider
|
||||
// here made a first hover deserialize the entire multi-gigabyte cache even
|
||||
// though the returned payload contains only `pf`.
|
||||
const rawProv = fp(await parseAllSessions(isTodayOnly ? todayRange : periodInfo.range, pf))
|
||||
todayAllDays = rangeEndStr >= todayStr
|
||||
? aggregateProjectsIntoDays(filterProjectsByDays(rawProv, new Set([todayStr]))).filter(d => d.date === todayStr)
|
||||
: []
|
||||
liveProjects = daysSelection && !isTodayOnly ? filterProjectsByDays(rawProv, daysSelection.days) : rawProv
|
||||
scanRange = isTodayOnly ? todayRange : periodInfo.range
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
|
||||
import { existsSync, readdirSync, statSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { delimiter as pathDelimiter, join } from 'node:path'
|
||||
|
|
@ -827,6 +827,52 @@ describe('codeburn status --format menubar-json', () => {
|
|||
}
|
||||
})
|
||||
|
||||
it('rejects a provider payload cached under the previous render contract', async () => {
|
||||
const home = await mkdtemp(join(tmpdir(), 'codeburn-menubar-provider-render-'))
|
||||
|
||||
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 base = new Date(Math.max(todayUtcMidnight, now.getTime() - 2 * 3600_000))
|
||||
const ts = (offset: number) => new Date(base.getTime() + offset).toISOString().replace(/\.\d+Z$/, 'Z')
|
||||
await writeFile(
|
||||
join(projectDir, 'session.jsonl'),
|
||||
[userLine('s1', ts(0)), assistantLine('s1', ts(60_000), 'msg-1')].join('\n'),
|
||||
)
|
||||
|
||||
const args = ['status', '--format', 'menubar-json', '--period', 'today', '--provider', 'all', '--no-optimize']
|
||||
const first = runCli(args, home)
|
||||
expect(first.status, `stderr: ${first.stderr}`).toBe(0)
|
||||
|
||||
const snapshotFiles = findSnapshotFiles(join(home, '.cache', 'codeburn'))
|
||||
expect(snapshotFiles).toHaveLength(1)
|
||||
const record = JSON.parse(await readFile(snapshotFiles[0]!, 'utf-8')) as {
|
||||
semanticKey: string
|
||||
payload: { current: { providerDetails: unknown[] } }
|
||||
}
|
||||
record.semanticKey = record.semanticKey.replace(/:render-\d+:/, ':render-2:')
|
||||
record.payload.current.providerDetails = [
|
||||
{ id: 'legacy-idle', label: 'Legacy Idle', cost: 0 },
|
||||
]
|
||||
await writeFile(snapshotFiles[0]!, JSON.stringify(record))
|
||||
|
||||
const second = runCli(args, home)
|
||||
expect(second.status, `stderr: ${second.stderr}`).toBe(0)
|
||||
const payload = JSON.parse(second.stdout) as {
|
||||
current: { providerDetails: Array<{ id: string; calls: number; hasUsage: boolean }> }
|
||||
}
|
||||
expect(payload.current.providerDetails.map(provider => provider.id)).not.toContain('legacy-idle')
|
||||
expect(payload.current.providerDetails.find(provider => provider.id === 'claude')).toMatchObject({
|
||||
calls: 1,
|
||||
hasUsage: true,
|
||||
})
|
||||
} finally {
|
||||
await rm(home, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('reprices from an updated live LiteLLM cache instead of serving a stale snapshot', async () => {
|
||||
const home = await mkdtemp(join(tmpdir(), 'codeburn-menubar-pricing-gen-'))
|
||||
|
||||
|
|
|
|||
|
|
@ -738,9 +738,9 @@ describe('#946: a migration re-derives copilot instead of carrying it', () => {
|
|||
/// so `loadDailyCache` takes the adoption path.
|
||||
const seedOlderCache = async (days: DailyEntry[]) => {
|
||||
await writeFile(
|
||||
join(TMP_CACHE_ROOT, `daily-cache.v${DAILY_CACHE_VERSION - 4}.json`),
|
||||
join(TMP_CACHE_ROOT, `daily-cache.v${DAILY_CACHE_VERSION - 5}.json`),
|
||||
JSON.stringify({
|
||||
version: DAILY_CACHE_VERSION - 4,
|
||||
version: DAILY_CACHE_VERSION - 5,
|
||||
savingsConfigHash: 'cfg-A',
|
||||
tzKey: currentTzKey(),
|
||||
lastComputedDate: daysAgoStr(1),
|
||||
|
|
@ -763,6 +763,41 @@ describe('#946: a migration re-derives copilot instead of carrying it', () => {
|
|||
expect(out.pendingRederive).toBeUndefined()
|
||||
})
|
||||
|
||||
it('re-derives a Hermes slice after the cost-provenance contract changes', async () => {
|
||||
const corrupt = slice(4603, 6764, { sessions: 6764 })
|
||||
const corrected = slice(0.438, 6, { sessions: 6 })
|
||||
await seedOlderCache([day(settled, { hermes: corrupt })])
|
||||
|
||||
const out = await ensureCacheHydrated(
|
||||
noSessions,
|
||||
() => [day(settled, { hermes: corrected })],
|
||||
'cfg-A',
|
||||
)
|
||||
|
||||
expect(out.days.find(d => d.date === settled)!.providers['hermes'])
|
||||
.toMatchObject({ cost: 0.438, calls: 6, sessions: 6 })
|
||||
expect(out.pendingRederive).toBeUndefined()
|
||||
})
|
||||
|
||||
it('does not re-open Copilot re-derivation for a cache already past its contract change', async () => {
|
||||
await writeFile(
|
||||
join(TMP_CACHE_ROOT, `daily-cache.v${DAILY_CACHE_VERSION - 1}.json`),
|
||||
JSON.stringify({
|
||||
version: DAILY_CACHE_VERSION - 1,
|
||||
savingsConfigHash: 'cfg-A',
|
||||
tzKey: currentTzKey(),
|
||||
lastComputedDate: daysAgoStr(1),
|
||||
days: [day(settled, { copilot: PRE_STORE, hermes: slice(4603, 6764) })],
|
||||
complete: true,
|
||||
watermarkTrusted: true,
|
||||
}),
|
||||
'utf-8',
|
||||
)
|
||||
|
||||
const loaded = await loadDailyCache()
|
||||
expect(loaded.pendingRederive).toEqual(['hermes'])
|
||||
})
|
||||
|
||||
it('still carries the slice whole when the sources are gone (never-lose, #1033)', async () => {
|
||||
await seedOlderCache([day(settled, { copilot: PRE_STORE })])
|
||||
// The re-derive finds nothing at all for that day: the store and the
|
||||
|
|
@ -794,7 +829,7 @@ describe('#946: a migration re-derives copilot instead of carrying it', () => {
|
|||
it('a PARTIAL parse does not spend the entitlement', async () => {
|
||||
await seedOlderCache([day(settled, { copilot: PRE_STORE })])
|
||||
const partial = await ensureCacheHydrated(noSessions, () => [], 'cfg-A', () => false)
|
||||
expect(partial.pendingRederive).toEqual(['copilot'])
|
||||
expect(partial.pendingRederive).toEqual(['copilot', 'hermes'])
|
||||
// The next COMPLETE run still gets to re-derive.
|
||||
const out = await ensureCacheHydrated(noSessions, () => [day(settled, { copilot: STORE_BACKED })], 'cfg-A')
|
||||
expect(out.days.find(d => d.date === settled)!.providers['copilot'])
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ function seedDb(): void {
|
|||
input_tokens INTEGER DEFAULT 0, output_tokens INTEGER DEFAULT 0,
|
||||
cache_read_tokens INTEGER DEFAULT 0, cache_write_tokens INTEGER DEFAULT 0,
|
||||
reasoning_tokens INTEGER DEFAULT 0, estimated_cost_usd REAL, actual_cost_usd REAL,
|
||||
cost_status TEXT, cost_source TEXT,
|
||||
api_call_count INTEGER DEFAULT 0, tool_call_count INTEGER DEFAULT 0,
|
||||
started_at REAL, title TEXT
|
||||
)
|
||||
|
|
@ -41,18 +42,21 @@ function seedDb(): void {
|
|||
const startedAt = Date.now() / 1000 - 3600
|
||||
const insert = db.prepare(
|
||||
`INSERT INTO sessions (id, source, model, input_tokens, output_tokens,
|
||||
estimated_cost_usd, actual_cost_usd, api_call_count, started_at)
|
||||
VALUES (?, 'cli', ?, ?, ?, ?, ?, 1, ?)`,
|
||||
estimated_cost_usd, actual_cost_usd, cost_status, cost_source, api_call_count, started_at)
|
||||
VALUES (?, 'cli', ?, ?, ?, ?, ?, ?, ?, 1, ?)`,
|
||||
)
|
||||
// Hermes writes estimated 0.0 when cost_status is 'unknown' or 'included'
|
||||
// (subscription). CodeBurn must not trust that $0: the tokens are real, so
|
||||
// cost falls through to the token-based calculation.
|
||||
insert.run('zero-estimate', 'claude-opus-4-6', 100000, 10000, 0.0, null, startedAt)
|
||||
// Subscription-included usage is recorded $0 spend even though it carries
|
||||
// real tokens. API-equivalent pricing must not overwrite that provenance.
|
||||
insert.run('included-zero', 'gpt-5.6-sol', 100000, 10000, 0.0, null, 'included', 'none', startedAt)
|
||||
// Unknown cost with no usable estimate falls back to token pricing.
|
||||
insert.run('unknown-zero', 'claude-opus-4-6', 100000, 10000, 0.0, null, 'unknown', 'none', startedAt)
|
||||
// A positive recorded estimate stays authoritative.
|
||||
insert.run('positive-estimate', 'claude-opus-4-6', 100000, 10000, 0.5, null, startedAt)
|
||||
insert.run('positive-estimate', 'claude-opus-4-6', 100000, 10000, 0.5, null, 'estimated', 'official_docs_snapshot', startedAt)
|
||||
// An explicitly estimated free value remains zero.
|
||||
insert.run('estimated-zero', 'free-model', 100000, 10000, 0.0, null, 'estimated', 'provider_models_api', startedAt)
|
||||
// An explicit $0 *actual* invoice amount is recorded fact and stays $0.
|
||||
insert.run('zero-actual', 'claude-opus-4-6', 100000, 10000, null, 0.0, startedAt)
|
||||
for (const id of ['zero-estimate', 'positive-estimate', 'zero-actual']) {
|
||||
insert.run('zero-actual', 'claude-opus-4-6', 100000, 10000, null, 0.0, 'actual', 'invoice', startedAt)
|
||||
for (const id of ['included-zero', 'unknown-zero', 'positive-estimate', 'estimated-zero', 'zero-actual']) {
|
||||
db.prepare('INSERT INTO messages (session_id, role, content, timestamp) VALUES (?, ?, ?, ?)')
|
||||
.run(id, 'user', `session ${id}`, startedAt)
|
||||
db.prepare('INSERT INTO messages (session_id, role, content, timestamp) VALUES (?, ?, ?, ?)')
|
||||
|
|
@ -77,18 +81,24 @@ afterEach(async () => {
|
|||
const skipUnlessSqlite = isSqliteAvailable() ? describe : describe.skip
|
||||
|
||||
skipUnlessSqlite('hermes recorded-cost fallback', () => {
|
||||
it('ignores a $0 estimated cost and calculates from tokens', async () => {
|
||||
it('preserves included and recorded zeroes while estimating unknown cost', async () => {
|
||||
seedDb()
|
||||
const projects = await parseAllSessions(undefined, 'hermes')
|
||||
const sessions = projects.flatMap(project => project.sessions)
|
||||
const byId = new Map(sessions.map(s => [s.sessionId, s]))
|
||||
|
||||
const zeroEstimate = byId.get('zero-estimate')!
|
||||
expect(zeroEstimate.totalCostUSD).toBeGreaterThan(0)
|
||||
const included = byId.get('included-zero')!
|
||||
expect(included.totalCostUSD).toBe(0)
|
||||
|
||||
const unknown = byId.get('unknown-zero')!
|
||||
expect(unknown.totalCostUSD).toBeGreaterThan(0)
|
||||
|
||||
const positive = byId.get('positive-estimate')!
|
||||
expect(positive.totalCostUSD).toBe(0.5)
|
||||
|
||||
const estimatedZero = byId.get('estimated-zero')!
|
||||
expect(estimatedZero.totalCostUSD).toBe(0)
|
||||
|
||||
const zeroActual = byId.get('zero-actual')!
|
||||
expect(zeroActual.totalCostUSD).toBe(0)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,10 +1,11 @@
|
|||
import { mkdir, mkdtemp, rm } from 'fs/promises'
|
||||
import { mkdir, mkdtemp, rm, writeFile } from 'fs/promises'
|
||||
import { join } from 'path'
|
||||
import { tmpdir } from 'os'
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
applyHermesSnapshot,
|
||||
HERMES_SESSION_LEDGER_VERSION,
|
||||
hermesBaselineKey,
|
||||
hermesObservationKey,
|
||||
hermesSessionLedgerPath,
|
||||
|
|
@ -237,10 +238,36 @@ describe('hermes session ledger unit', () => {
|
|||
await mkdir(hermesSessionLedgerPath())
|
||||
let caught: unknown
|
||||
try {
|
||||
await persistHermesSessionLedger({ version: 1, cursors: {} })
|
||||
await persistHermesSessionLedger({ version: HERMES_SESSION_LEDGER_VERSION, cursors: {} })
|
||||
} catch (err) {
|
||||
caught = err
|
||||
}
|
||||
expect(isHermesLedgerPublicationError(caught)).toBe(true)
|
||||
})
|
||||
|
||||
it('does not adopt a v1 ledger after the cost-provenance contract changes', async () => {
|
||||
await writeFile(join(cacheDir, 'hermes-session-ledger.v1.json'), JSON.stringify({
|
||||
version: 1,
|
||||
cursors: {
|
||||
default: {
|
||||
corrupt: {
|
||||
profile: 'default',
|
||||
sessionId: 'corrupt',
|
||||
lastSeen: {
|
||||
inputTokens: 1,
|
||||
outputTokens: 0,
|
||||
cacheReadTokens: 0,
|
||||
cacheWriteTokens: 0,
|
||||
reasoningTokens: 0,
|
||||
costUSD: 4603,
|
||||
costBasis: 'calculated',
|
||||
},
|
||||
observations: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
expect(loadHermesSessionLedger().cursors).toEqual({})
|
||||
})
|
||||
})
|
||||
|
|
|
|||
49
tests/usage-aggregator-provider-scope.test.ts
Normal file
49
tests/usage-aggregator-provider-scope.test.ts
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
import { beforeAll, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { buildMenubarPayloadForRange } from '../src/usage-aggregator.js'
|
||||
import { getDateRange } from '../src/cli-date.js'
|
||||
import { loadPricing } from '../src/models.js'
|
||||
|
||||
const parseAllSessions = vi.hoisted(() => vi.fn(async () => []))
|
||||
|
||||
vi.mock('../src/parser.js', async (importOriginal) => {
|
||||
const mod = await importOriginal<typeof import('../src/parser.js')>()
|
||||
return {
|
||||
...mod,
|
||||
parseAllSessions,
|
||||
isSessionHydrationComplete: vi.fn(() => true),
|
||||
sessionHydrationSnapshot: vi.fn(() => ({
|
||||
complete: true,
|
||||
deferredForFirstPaint: false,
|
||||
indexedFiles: 0,
|
||||
pendingFiles: 0,
|
||||
})),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../src/daily-cache.js', async (importOriginal) => {
|
||||
const mod = await importOriginal<typeof import('../src/daily-cache.js')>()
|
||||
return {
|
||||
...mod,
|
||||
ensureCacheHydrated: vi.fn(async () => mod.emptyCache()),
|
||||
}
|
||||
})
|
||||
|
||||
describe('provider-scoped menubar aggregation', () => {
|
||||
beforeAll(async () => {
|
||||
await loadPricing()
|
||||
})
|
||||
|
||||
it('never scans unrelated providers to render one selected provider', async () => {
|
||||
parseAllSessions.mockClear()
|
||||
|
||||
await buildMenubarPayloadForRange(getDateRange('today'), {
|
||||
provider: 'hermes',
|
||||
optimize: false,
|
||||
timeline: false,
|
||||
})
|
||||
|
||||
expect(parseAllSessions.mock.calls.map(([, provider]) => provider))
|
||||
.toEqual(['hermes'])
|
||||
})
|
||||
})
|
||||
Loading…
Add table
Add a link
Reference in a new issue