mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-11-29 02:39:13 +00:00
Add a new `localModelSavings` config and `codeburn model-savings` CLI that maps a local-model name (e.g. llama3.1:8b) to a paid baseline (e.g. gpt-4o). The local call still costs $0; the new `savingsUSD` field tracks the counterfactual spend avoided by running locally and is reported separately from `costUSD` everywhere a number is shown. * Parser normalization (`applyLocalModelSavings`) runs on Claude parse, direct provider calls, and the cached-call path. It forces `costUSD` to 0 and attaches `savingsUSD` + `savingsBaselineModel` + `isLocalSavings` on the `ParsedApiCall`. Local-savings wins for actual cost even when the same model is also in `modelAliases`. * Session, project, day, model, category, activity, skill, and subagent rollups all carry `savingsUSD` alongside `costUSD`. * `status --format json` adds `today.savings` and `month.savings`. * `status --format menubar-json` adds a `current.localModelSavings` block (totalUSD, calls, byModel, byProvider) plus savings on topModels, topProjects, topSessions, topActivities, and history daily entries. Schema fields default-decode for backward compat. * `report --format json` adds savings across overview/daily/ projects/models/activities/skills/subagents/topSessions, with the active paid baseline name on each model row. * `models` command gains a `Saved` column on table/markdown/CSV and a `savingsUSD`/`savingsBaselineModel` pair in JSON. Default `--min-cost 0.01` filter now ORs in `savingsUSD >= minCost` so local models with $0 actual cost but >0 savings still surface. * CSV/JSON exports add a `Saved (CODE)` column on summary/daily/ models/projects/sessions. * Dashboard TUI shows a green 'saved $X by local models' footer line in the overview when any savings are present. * macOS Swift payload gains a `LocalModelSavings` Codable block and savings fields on every model/activity/session/daily struct. Hero shows a green leaf 'Saved $X' caption, models section gets a green `Saved` column. `swift build` clean. * GNOME indicator adds 'saved $X' to the hero meta line and a `codeburn-model-saved` column to the model row. * Daily cache schema bumped to v8 (`savingsUSD` on day/model/ category/provider). `savingsConfigHash` invalidates the cache when the user changes their baseline mapping so historical saved-spend numbers never lie about a stale baseline. * Defensive `Object.hasOwn` lookup in `getLocalSavingsBaseline` blocks the prototype-pollution test that previously surfaced via the savings path with a hostile `__proto__` model name. * New tests (5 files, 25 tests, 549 lines) cover pricing helpers, end-to-end parser normalization, day aggregator savings, menubar payload savings, CLI set/list/remove, and daily-cache hash invalidation. Existing tests for daily-cache / day-aggregator / models-report updated for the new fields. Full vitest suite: 1028/1028 passing across 73 test files. `tsc --noEmit` clean. `npm run build` clean. (Note: `mac/Tests` has a pre-existing `no such module 'Testing'` environment error on the installed Swift toolchain, confirmed on `main` before this PR; not caused by these changes.)
138 lines
4.8 KiB
TypeScript
138 lines
4.8 KiB
TypeScript
import { mkdtemp, mkdir, rm, writeFile } from 'fs/promises'
|
|
import { tmpdir } from 'os'
|
|
import { join } from 'path'
|
|
import { afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'
|
|
|
|
import {
|
|
setLocalModelSavings,
|
|
setModelAliases,
|
|
loadPricing,
|
|
} from '../src/models.js'
|
|
import { parseAllSessions, clearSessionCache } from '../src/parser.js'
|
|
import type { DateRange } from '../src/types.js'
|
|
|
|
const FIXTURE_DAY = Date.UTC(2026, 3, 16)
|
|
const RANGE_START = new Date(FIXTURE_DAY - 24 * 60 * 60 * 1000)
|
|
const RANGE_END = new Date(FIXTURE_DAY + 24 * 60 * 60 * 1000)
|
|
|
|
function makeRange(): DateRange {
|
|
return { start: RANGE_START, end: RANGE_END }
|
|
}
|
|
|
|
let tmpDirs: string[] = []
|
|
let originalConfigDir: string | undefined
|
|
|
|
beforeAll(async () => {
|
|
await loadPricing()
|
|
})
|
|
|
|
beforeEach(() => {
|
|
originalConfigDir = process.env['CLAUDE_CONFIG_DIR']
|
|
setLocalModelSavings({})
|
|
setModelAliases({})
|
|
})
|
|
|
|
afterEach(async () => {
|
|
delete (Object.prototype as Record<string, unknown>).calls
|
|
if (originalConfigDir === undefined) {
|
|
delete process.env['CLAUDE_CONFIG_DIR']
|
|
} else {
|
|
process.env['CLAUDE_CONFIG_DIR'] = originalConfigDir
|
|
}
|
|
clearSessionCache()
|
|
while (tmpDirs.length > 0) {
|
|
const d = tmpDirs.pop()
|
|
if (d) await rm(d, { recursive: true, force: true })
|
|
}
|
|
})
|
|
|
|
async function setupLocalModelSession(modelName: string): Promise<string> {
|
|
const base = await mkdtemp(join(tmpdir(), 'codeburn-savings-'))
|
|
tmpDirs.push(base)
|
|
const projectDir = join(base, 'projects', 'p')
|
|
await mkdir(projectDir, { recursive: true })
|
|
// Use a synthetic local-style model name and a small known token count.
|
|
const file = join(projectDir, 's1.jsonl')
|
|
const ts = '2026-04-16T10:00:00.000Z'
|
|
const line = JSON.stringify({
|
|
type: 'assistant',
|
|
timestamp: ts,
|
|
sessionId: 's1',
|
|
message: {
|
|
type: 'message',
|
|
role: 'assistant',
|
|
model: modelName,
|
|
id: 'msg-1',
|
|
content: [],
|
|
usage: {
|
|
input_tokens: 1000,
|
|
output_tokens: 200,
|
|
cache_creation_input_tokens: 0,
|
|
cache_read_input_tokens: 0,
|
|
},
|
|
},
|
|
})
|
|
await writeFile(file, line + '\n', 'utf-8')
|
|
process.env['CLAUDE_CONFIG_DIR'] = base
|
|
return base
|
|
}
|
|
|
|
describe('local-model savings: end-to-end', () => {
|
|
it('keeps an unconfigured local model at $0 with no savings recorded', async () => {
|
|
await setupLocalModelSession('llama3.1:8b')
|
|
const projects = await parseAllSessions(makeRange(), 'all')
|
|
const allCalls = projects.flatMap(p => p.sessions.flatMap(s => s.turns.flatMap(t => t.assistantCalls)))
|
|
expect(allCalls.length).toBeGreaterThan(0)
|
|
for (const c of allCalls) {
|
|
expect(c.costUSD).toBe(0)
|
|
expect(c.savingsUSD ?? 0).toBe(0)
|
|
expect(c.isLocalSavings).toBeFalsy()
|
|
}
|
|
})
|
|
|
|
it('records savings and forces cost to 0 when a local model has a savings mapping', async () => {
|
|
await setupLocalModelSession('llama3.1:8b')
|
|
setLocalModelSavings({ 'llama3.1:8b': 'gpt-4o' })
|
|
clearSessionCache()
|
|
const projects = await parseAllSessions(makeRange(), 'all')
|
|
const allCalls = projects.flatMap(p => p.sessions.flatMap(s => s.turns.flatMap(t => t.assistantCalls)))
|
|
expect(allCalls.length).toBeGreaterThan(0)
|
|
for (const c of allCalls) {
|
|
expect(c.costUSD).toBe(0)
|
|
expect(c.savingsUSD).toBeGreaterThan(0)
|
|
expect(c.savingsBaselineModel).toBe('gpt-4o')
|
|
expect(c.isLocalSavings).toBe(true)
|
|
}
|
|
// Session and project rollups surface the savings total.
|
|
const totalSavings = projects.reduce((s, p) => s + p.totalSavingsUSD, 0)
|
|
expect(totalSavings).toBeGreaterThan(0)
|
|
})
|
|
|
|
it('does not apply savings for a model that has no mapping', async () => {
|
|
await setupLocalModelSession('qwen2.5:32b')
|
|
setLocalModelSavings({ 'unrelated:1b': 'gpt-4o' })
|
|
clearSessionCache()
|
|
const projects = await parseAllSessions(makeRange(), 'all')
|
|
const allCalls = projects.flatMap(p => p.sessions.flatMap(s => s.turns.flatMap(t => t.assistantCalls)))
|
|
for (const c of allCalls) {
|
|
expect(c.savingsUSD ?? 0).toBe(0)
|
|
}
|
|
})
|
|
|
|
it('forces a $0 cost even when the same model is also in modelAliases', async () => {
|
|
// The local-savings path is meant to win for actual cost: spending
|
|
// config semantics say "this is local, track counterfactual", so
|
|
// even a stale modelAliases entry must not cause us to charge real
|
|
// dollars for a local call.
|
|
await setupLocalModelSession('llama3.1:8b')
|
|
setModelAliases({ 'llama3.1:8b': 'gpt-4o' })
|
|
setLocalModelSavings({ 'llama3.1:8b': 'gpt-4o' })
|
|
clearSessionCache()
|
|
const projects = await parseAllSessions(makeRange(), 'all')
|
|
const allCalls = projects.flatMap(p => p.sessions.flatMap(s => s.turns.flatMap(t => t.assistantCalls)))
|
|
for (const c of allCalls) {
|
|
expect(c.costUSD).toBe(0)
|
|
expect(c.savingsUSD).toBeGreaterThan(0)
|
|
}
|
|
})
|
|
})
|