The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(usage): make the Usage page show the spend it recorded
[email protected]dde2d5287dfc
diff --git a/app/src/components/dashboard/CostBarChart.tsx b/app/src/components/dashboard/CostBarChart.tsxindex d1058b3c98..13b943fae1 100644--- a/app/src/components/dashboard/CostBarChart.tsx+++ b/app/src/components/dashboard/CostBarChart.tsx@@ -38,11 +38,13 @@ const CostBarChart = ({ days, currency }: CostBarChartProps) => {date: day.date,label: shortDayLabel(day.date),dayNumber: dayOfMonth(day.date),- cost: Number(day.cost_usd.toFixed(4)),+ cost: day.cost_usd || 0,requestCount: day.request_count,isToday: day.date === todayDate,}));+ const hasSpend = chartData.some(point => point.cost > 0);+return (<div data-testid="cost-bar-chart" className="w-full"><div className="w-full h-56">@@ -73,7 +75,8 @@ const CostBarChart = ({ days, currency }: CostBarChartProps) => {axisLine={false}width={52}tick={{ fill: 'currentColor', opacity: 0.7 }}- tickFormatter={(v: number) => formatCurrency(v, currency)}+ domain={[0, hasSpend ? 'auto' : 1]}+ tickFormatter={(v: number) => formatCurrency(v, currency, { precise: true })}/><Tooltipcursor={{ fill: 'rgba(150,150,150,0.10)' }}diff --git a/app/src/components/dashboard/ModelCostTable.test.tsx b/app/src/components/dashboard/ModelCostTable.test.tsxindex def991fa82..96a423ea5f 100644--- a/app/src/components/dashboard/ModelCostTable.test.tsx+++ b/app/src/components/dashboard/ModelCostTable.test.tsx@@ -58,4 +58,24 @@ describe('<ModelCostTable />', () => {);expect(screen.getByText('None')).toBeInTheDocument();});++ it('shows a share under 0.1% as "<0.1%" and sub-cent cost as "<$0.01"', () => {+ render(+ <ModelCostTable+ models={[+ {+ model: 'tiny-model',+ cost_usd: 0.0004,+ total_tokens: 90,+ request_count: 1,+ provider: 'openrouter',+ percent_of_total: 0.03,+ },+ ]}+ currency="USD"+ />+ );+ expect(screen.getByText('<0.1%')).toBeInTheDocument();+ expect(screen.getByText('<$0.01')).toBeInTheDocument();+ });});diff --git a/app/src/components/dashboard/ModelCostTable.tsx b/app/src/components/dashboard/ModelCostTable.tsxindex 380753385b..139a2aa57e 100644--- a/app/src/components/dashboard/ModelCostTable.tsx+++ b/app/src/components/dashboard/ModelCostTable.tsx@@ -12,7 +12,7 @@ import {TableCell,TableRow,} from '../ui';-import { formatCurrency, formatTokens } from './formatCurrency';+import { formatCurrency, formatPercent, formatTokens } from './formatCurrency';interface ModelCostTableProps {models: CostDashboardModelStats[];@@ -81,7 +81,7 @@ const ModelCostTable = ({ models, currency, title, description }: ModelCostTable<div className="flex items-center justify-end gap-2"><Progress value={sharePct} className="h-1 w-14" /><span className="w-11 text-right tabular-nums text-content-secondary">- {`${sharePct.toFixed(1)}%`}+ {formatPercent(sharePct)}</span></div>);diff --git a/app/src/components/dashboard/TokenUsageChart.tsx b/app/src/components/dashboard/TokenUsageChart.tsxindex 5531f93f1f..a9d47d5523 100644--- a/app/src/components/dashboard/TokenUsageChart.tsx+++ b/app/src/components/dashboard/TokenUsageChart.tsx@@ -32,6 +32,8 @@ const TokenUsageChart = ({ days }: TokenUsageChartProps) => {total: d.total_tokens,}));+ const hasTokens = data.some(point => point.total > 0);+return (<div data-testid="token-usage-chart" className="w-full h-56"><ResponsiveContainer width="100%" height="100%">@@ -61,6 +63,8 @@ const TokenUsageChart = ({ days }: TokenUsageChartProps) => {axisLine={false}width={52}tick={{ fill: 'currentColor', opacity: 0.7 }}+ allowDecimals={false}+ domain={[0, hasTokens ? 'auto' : 1000]}tickFormatter={(v: number) => formatTokens(v)}/><Tooltipdiff --git a/app/src/components/dashboard/formatCurrency.test.ts b/app/src/components/dashboard/formatCurrency.test.tsindex 5de95ba567..b04db6f972 100644--- a/app/src/components/dashboard/formatCurrency.test.ts+++ b/app/src/components/dashboard/formatCurrency.test.ts@@ -1,6 +1,12 @@import { describe, expect, it } from 'vitest';-import { formatCurrency, formatTokens, relativeTime, shortDayLabel } from './formatCurrency';+import {+ formatCurrency,+ formatPercent,+ formatTokens,+ relativeTime,+ shortDayLabel,+} from './formatCurrency';describe('formatCurrency', () => {it('formats positive USD amounts with two decimals under 100', () => {@@ -23,6 +29,37 @@ describe('formatCurrency', () => {it('honours empty currency string by falling back to USD', () => {expect(formatCurrency(7, '')).toMatch(/\$7\.00/);});++ it('shows real spend under one cent as "<$0.01", not "$0.00"', () => {+ expect(formatCurrency(0.0001, 'USD')).toBe('<$0.01');+ expect(formatCurrency(0.004, 'USD')).toBe('<$0.01');+ expect(formatCurrency(0.009999, 'USD')).toBe('<$0.01');+ expect(formatCurrency(3.6e-7, 'USD')).toBe('<$0.01');+ });++ it('switches to plain two-decimal output at exactly one cent', () => {+ expect(formatCurrency(0.01, 'USD')).toBe('$0.01');+ expect(formatCurrency(0.0149, 'USD')).toBe('$0.01');+ });++ it('renders zero and negative zero as plain zero', () => {+ expect(formatCurrency(0, 'USD')).toBe('$0.00');+ expect(formatCurrency(-0, 'USD')).toBe('$0.00');+ });++ it('keeps the sign on a tiny negative amount', () => {+ expect(formatCurrency(-0.001, 'USD')).toBe('-<$0.01');+ });++ it('applies the sub-cent rule in other currencies', () => {+ expect(formatCurrency(0.0001, 'EUR')).toMatch(/^<.*0\.01/);+ });++ it('can show sub-cent amounts to four decimals for chart axes', () => {+ expect(formatCurrency(0.0004, 'USD', { precise: true })).toBe('$0.0004');+ expect(formatCurrency(0.0025, 'USD', { precise: true })).toBe('$0.0025');+ expect(formatCurrency(0.5, 'USD', { precise: true })).toBe('$0.50');+ });});describe('formatTokens', () => {@@ -39,6 +76,30 @@ describe('formatTokens', () => {expect(formatTokens(1_500)).toBe('1.5K');expect(formatTokens(2_500_000)).toBe('2.5M');});++ it('rolls over to M instead of showing "1000.0K"', () => {+ expect(formatTokens(999_949)).toBe('999.9K');+ expect(formatTokens(999_960)).toBe('1.0M');+ expect(formatTokens(1_000_000)).toBe('1.0M');+ });+});++describe('formatPercent', () => {+ it('rounds to one decimal', () => {+ expect(formatPercent(12.34)).toBe('12.3%');+ expect(formatPercent(100)).toBe('100.0%');+ });++ it('shows a non-zero share under 0.1% as "<0.1%", not "0.0%"', () => {+ expect(formatPercent(0.04)).toBe('<0.1%');+ expect(formatPercent(0.1)).toBe('0.1%');+ });++ it('treats zero, negative and non-finite input as 0.0%', () => {+ expect(formatPercent(0)).toBe('0.0%');+ expect(formatPercent(-3)).toBe('0.0%');+ expect(formatPercent(Number.NaN)).toBe('0.0%');+ });});describe('shortDayLabel', () => {diff --git a/app/src/components/dashboard/formatCurrency.ts b/app/src/components/dashboard/formatCurrency.tsindex 3aa711d0e4..a0698d596e 100644--- a/app/src/components/dashboard/formatCurrency.ts+++ b/app/src/components/dashboard/formatCurrency.ts@@ -1,34 +1,73 @@-/**- * Format a USD-denominated amount with the requested display currency label.- * Falls back to the locale "USD" formatter when the configured currency- * code is not a valid ISO-4217 currency Intl supports — this keeps- * arbitrary display labels (e.g. "USD ($)") from throwing.- */-export function formatCurrency(amountUsd: number, currency: string): string {- const safe = Number.isFinite(amountUsd) ? amountUsd : 0;+const ONE_CENT = 0.01;++function currencyFormatter(currency: string, maximumFractionDigits: number): Intl.NumberFormat {const normalized = currency?.trim() ? currency.trim().toUpperCase() : 'USD';try {return new Intl.NumberFormat(undefined, {style: 'currency',currency: normalized,- maximumFractionDigits: safe >= 100 ? 0 : 2,- }).format(safe);+ maximumFractionDigits,+ });} catch {return new Intl.NumberFormat(undefined, {style: 'currency',currency: 'USD',- maximumFractionDigits: safe >= 100 ? 0 : 2,- }).format(safe);+ maximumFractionDigits,+ });+ }+}++interface FormatCurrencyOptions {+ /**+ * Show sub-cent amounts to four decimals instead of collapsing them to+ * "<$0.01". For chart axes, where several ticks below one cent would+ * otherwise all read the same.+ */+ precise?: boolean;+}++/**+ * Format a USD-denominated amount with the requested display currency label.+ * Falls back to the locale "USD" formatter when the configured currency+ * code is not a valid ISO-4217 currency Intl supports — this keeps+ * arbitrary display labels (e.g. "USD ($)") from throwing.+ *+ * A non-zero amount below one cent renders as "<$0.01" rather than "$0.00",+ * so real spend never reads as none. Negative zero (an empty Rust sum+ * serialises as `-0.0`) renders as plain zero.+ */+export function formatCurrency(+ amountUsd: number,+ currency: string,+ options: FormatCurrencyOptions = {}+): string {+ const finite = Number.isFinite(amountUsd) ? amountUsd : 0;+ const safe = Object.is(finite, -0) ? 0 : finite;+ if (safe !== 0 && Math.abs(safe) < ONE_CENT) {+ if (options.precise) {+ return currencyFormatter(currency, 4).format(safe);+ }+ return `${safe < 0 ? '-' : ''}<${currencyFormatter(currency, 2).format(ONE_CENT)}`;}+ return currencyFormatter(currency, Math.abs(safe) >= 100 ? 0 : 2).format(safe);}export function formatTokens(n: number): string {if (!Number.isFinite(n) || n <= 0) return '0';- if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;- if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`;+ // Round to one decimal in thousands first: 999_960 is "1000.0K" otherwise.+ const thousands = Math.round(n / 100) / 10;+ if (n >= 1_000_000 || thousands >= 1_000) return `${(n / 1_000_000).toFixed(1)}M`;+ if (n >= 1_000) return `${thousands.toFixed(1)}K`;return Math.round(n).toString();}+/** Percentage to one decimal; a non-zero share below 0.1% reads "<0.1%", not "0.0%". */+export function formatPercent(percent: number): string {+ const safe = Number.isFinite(percent) ? Math.max(0, percent) : 0;+ if (safe > 0 && safe < 0.1) return '<0.1%';+ return `${safe.toFixed(1)}%`;+}+export function shortDayLabel(isoDate: string): string {try {const date = new Date(`${isoDate}T00:00:00Z`);diff --git a/app/src/components/settings/panels/TokenUsagePanel.tsx b/app/src/components/settings/panels/TokenUsagePanel.tsxindex a5bd12a6f1..ace86f7a07 100644--- a/app/src/components/settings/panels/TokenUsagePanel.tsx+++ b/app/src/components/settings/panels/TokenUsagePanel.tsx@@ -11,6 +11,7 @@ import {type TokenjuiceSettingsPatch,updateTokenjuiceSettings,} from '../../../utils/tauriCommands/tokenjuice';+import { formatCurrency } from '../../dashboard/formatCurrency';import { Button, Card, Field, NumberField, StatusLine, Switch } from '../../ui';import SettingsPanel from '../layout/SettingsPanel';@@ -18,11 +19,6 @@ function formatInt(n: number): string {return Math.round(n).toLocaleString();}-function formatUsd(n: number): string {- if (n > 0 && n < 0.01) return '<$0.01';- return `$${n.toFixed(2)}`;-}-function formatBytes(n: number): string {if (n < 1024) return `${n} B`;if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;@@ -207,7 +203,7 @@ const TokenUsagePanel = ({ embedded = false }: TokenUsagePanelProps = {}) => {/><StatTilelabel={t('settings.tokenUsage.costSaved')}- value={total ? formatUsd(total.costSavedUsd) : '—'}+ value={total ? formatCurrency(total.costSavedUsd, 'USD') : '—'}/><StatTilelabel={t('settings.tokenUsage.cacheOccupancy')}@@ -234,7 +230,7 @@ const TokenUsagePanel = ({ embedded = false }: TokenUsagePanelProps = {}) => {<span className="tabular-nums text-content-muted">{t('settings.tokenUsage.tokensAndCost', '{tokens} tok · {cost}').replace('{tokens}', formatInt(b.tokensSaved))- .replace('{cost}', formatUsd(b.costSavedUsd))}+ .replace('{cost}', formatCurrency(b.costSavedUsd, 'USD'))}</span></div>))}diff --git a/app/src/components/settings/panels/ai/backgroundLoopPrimitives.test.ts b/app/src/components/settings/panels/ai/backgroundLoopPrimitives.test.tsnew file mode 100644index 0000000000..fa40b9a1b0--- /dev/null+++ b/app/src/components/settings/panels/ai/backgroundLoopPrimitives.test.ts@@ -0,0 +1,20 @@+import { describe, expect, it } from 'vitest';++import { formatUsd } from './backgroundLoopPrimitives';++describe('formatUsd', () => {+ it('keeps four to six decimals for small real charges', () => {+ expect(formatUsd(0.0004)).toBe('$0.0004');+ expect(formatUsd(1.7831)).toBe('$1.7831');+ });++ it('never renders a non-zero charge as zero', () => {+ expect(formatUsd(3.6e-7)).toBe('<$0.000001');+ expect(formatUsd(6e-8)).toBe('<$0.000001');+ });++ it('renders zero and non-finite input as zero', () => {+ expect(formatUsd(0)).toBe('$0.0000');+ expect(formatUsd(Number.NaN)).toBe('$0.0000');+ });+});diff --git a/app/src/components/settings/panels/ai/backgroundLoopPrimitives.tsx b/app/src/components/settings/panels/ai/backgroundLoopPrimitives.tsxindex 81f8f0be30..bc73ae4c6d 100644--- a/app/src/components/settings/panels/ai/backgroundLoopPrimitives.tsx+++ b/app/src/components/settings/panels/ai/backgroundLoopPrimitives.tsx@@ -19,7 +19,11 @@ export const LEARNING_REBUILD_MINUTES = 30;export const MEMORY_WORKERS = 4;export const MEMORY_POLL_SECONDS = 5;-export const formatUsd = (value: number): string => USD.format(Number.isFinite(value) ? value : 0);+export const formatUsd = (value: number): string => {+ const safe = Number.isFinite(value) ? value : 0;+ if (safe > 0 && safe < 0.000001) return `<${USD.format(0.000001)}`;+ return USD.format(safe);+};export const spendAmount = (tx: CreditTransaction): number => {const amount = Number(tx.amountUsd);diff --git a/app/src/components/settings/settingsRouteRegistry.ts b/app/src/components/settings/settingsRouteRegistry.tsindex 615c025c62..727386a598 100644--- a/app/src/components/settings/settingsRouteRegistry.ts+++ b/app/src/components/settings/settingsRouteRegistry.ts@@ -527,7 +527,7 @@ export const SETTINGS_ROUTE_REGISTRY: SettingsRegistryEntry[] = [// About page, so dev builds listed two sidebar entries for one page. About's// search keywords already cover "build" and "version".- // Token & Cost (TokenJuice compression settings + savings) is now the+ // Token savings (TokenJuice compression settings + savings) is now the// "Token savings" tab of the merged Usage & limits surface on Connections —// the standalone token-usage entry was retired (route redirects there).diff --git a/app/src/lib/i18n/ar.ts b/app/src/lib/i18n/ar.tsindex 9c649d9e69..0c26927845 100644--- a/app/src/lib/i18n/ar.ts+++ b/app/src/lib/i18n/ar.ts@@ -451,7 +451,7 @@ const messages: TranslationMap = {'settings.analysisViews.title': 'طرق العرض التحليلية','settings.analysisViews.menuDesc':'تحليل رسم الذاكرة البياني: المخطط، والمركزية، والتماسك، والارتباطات، والحداثة، والجدول الزمني، والمسارات، والمساحات',- 'settings.tokenUsage.title': 'الرموز والتكلفة',+ 'settings.tokenUsage.title': 'توفير الرموز','settings.tokenUsage.menuDesc': 'إعدادات الضغط ومقدار ما وفّرته من رموز ودولارات','settings.tokenUsage.saving': 'جارٍ الحفظ…','settings.tokenUsage.saved': 'تم الحفظ',diff --git a/app/src/lib/i18n/bn.ts b/app/src/lib/i18n/bn.tsindex 7c1260fdfb..d3640dc0dd 100644--- a/app/src/lib/i18n/bn.ts+++ b/app/src/lib/i18n/bn.ts@@ -468,7 +468,7 @@ const messages: TranslationMap = {'settings.analysisViews.title': 'বিশ্লেষণ ভিউ','settings.analysisViews.menuDesc':'মেমরি গ্রাফ বিশ্লেষণ: ডায়াগ্রাম, কেন্দ্রীয়তা, সংহতি, সংযোগ, সতেজতা, টাইমলাইন, পাথ এবং নেমস্পেস',- 'settings.tokenUsage.title': 'টোকেন ও খরচ',+ 'settings.tokenUsage.title': 'টোকেন সাশ্রয়','settings.tokenUsage.menuDesc': 'সংকোচন সেটিংস এবং সেগুলি কত টোকেন ও ডলার সাশ্রয় করেছে','settings.tokenUsage.saving': 'সংরক্ষণ করা হচ্ছে…','settings.tokenUsage.saved': 'সংরক্ষিত হয়েছে',diff --git a/app/src/lib/i18n/de.ts b/app/src/lib/i18n/de.tsindex 513e4223e5..73f253b15c 100644--- a/app/src/lib/i18n/de.ts+++ b/app/src/lib/i18n/de.ts@@ -489,7 +489,7 @@ const messages: TranslationMap = {'settings.analysisViews.title': 'Analyseansichten','settings.analysisViews.menuDesc':'Speichergraph-Analyse: Diagramm, Zentralität, Kohäsion, Verknüpfungen, Aktualität, Zeitachse, Pfade und Namensräume',- 'settings.tokenUsage.title': 'Tokens & Kosten',+ 'settings.tokenUsage.title': 'Token-Einsparungen','settings.tokenUsage.menuDesc':'Komprimierungseinstellungen und wie viele Tokens und Dollar sie eingespart haben','settings.tokenUsage.saving': 'Wird gespeichert…',diff --git a/app/src/lib/i18n/en.ts b/app/src/lib/i18n/en.tsindex dcf5970dbc..acce6113e3 100644--- a/app/src/lib/i18n/en.ts+++ b/app/src/lib/i18n/en.ts@@ -277,7 +277,7 @@ const en: TranslationMap = {'settings.analysisViews.title': 'Analysis views','settings.analysisViews.menuDesc':'Memory graph analysis: diagram, centrality, cohesion, associations, freshness, timeline, paths, and namespaces',- 'settings.tokenUsage.title': 'Token & Cost',+ 'settings.tokenUsage.title': 'Token savings','settings.tokenUsage.menuDesc':'Compression settings and how many tokens and dollars they have saved','settings.tokenUsage.saving': 'Saving…',diff --git a/app/src/lib/i18n/es.ts b/app/src/lib/i18n/es.tsindex 029ac27725..2fd72dc5e5 100644--- a/app/src/lib/i18n/es.ts+++ b/app/src/lib/i18n/es.ts@@ -479,7 +479,7 @@ const messages: TranslationMap = {'settings.analysisViews.title': 'Vistas de análisis','settings.analysisViews.menuDesc':'Análisis del grafo de memoria: diagrama, centralidad, cohesión, asociaciones, frescura, línea de tiempo, rutas y espacios de nombres',- 'settings.tokenUsage.title': 'Tokens y coste',+ 'settings.tokenUsage.title': 'Ahorro de tokens','settings.tokenUsage.menuDesc': 'Ajustes de compresión y cuántos tokens y dólares han ahorrado','settings.tokenUsage.saving': 'Guardando…','settings.tokenUsage.saved': 'Guardado',diff --git a/app/src/lib/i18n/fr.ts b/app/src/lib/i18n/fr.tsindex 8b3c2fb7bc..b61c6f8ff9 100644--- a/app/src/lib/i18n/fr.ts+++ b/app/src/lib/i18n/fr.ts@@ -487,7 +487,7 @@ const messages: TranslationMap = {'settings.analysisViews.title': 'Vues d’analyse','settings.analysisViews.menuDesc':'Analyse du graphe mémoire: diagramme, centralité, cohésion, associations, fraîcheur, chronologie, chemins et espaces de noms',- 'settings.tokenUsage.title': 'Tokens et coût',+ 'settings.tokenUsage.title': 'Économies de tokens','settings.tokenUsage.menuDesc':'Paramètres de compression et combien de tokens et de dollars ils ont économisés','settings.tokenUsage.saving': 'Enregistrement…',diff --git a/app/src/lib/i18n/hi.ts b/app/src/lib/i18n/hi.tsindex 87af726863..44533abb83 100644--- a/app/src/lib/i18n/hi.ts+++ b/app/src/lib/i18n/hi.ts@@ -469,7 +469,7 @@ const messages: TranslationMap = {'settings.analysisViews.title': 'विश्लेषण दृश्य','settings.analysisViews.menuDesc':'मेमोरी ग्राफ़ विश्लेषण: डायग्राम, केंद्रीयता, संसक्ति, संबंध, ताज़गी, टाइमलाइन, पथ और नेमस्पेस',- 'settings.tokenUsage.title': 'टोकन और लागत',+ 'settings.tokenUsage.title': 'टोकन बचत','settings.tokenUsage.menuDesc': 'संपीड़न सेटिंग्स और उन्होंने कितने टोकन और डॉलर बचाए हैं','settings.tokenUsage.saving': 'सहेजा जा रहा है…','settings.tokenUsage.saved': 'सहेजा गया',diff --git a/app/src/lib/i18n/id.ts b/app/src/lib/i18n/id.tsindex 86bb49b140..18412d5c78 100644--- a/app/src/lib/i18n/id.ts+++ b/app/src/lib/i18n/id.ts@@ -474,7 +474,7 @@ const messages: TranslationMap = {'settings.analysisViews.title': 'Tampilan analisis','settings.analysisViews.menuDesc':'Analisis grafik memori: diagram, sentralitas, kohesi, asosiasi, kesegaran, lini masa, jalur, dan namespace',- 'settings.tokenUsage.title': 'Token & Biaya',+ 'settings.tokenUsage.title': 'Penghematan token','settings.tokenUsage.menuDesc':'Pengaturan kompresi dan berapa banyak token dan dolar yang telah dihemat','settings.tokenUsage.saving': 'Menyimpan…',diff --git a/app/src/lib/i18n/it.ts b/app/src/lib/i18n/it.tsindex bace3682ac..29e522ea42 100644--- a/app/src/lib/i18n/it.ts+++ b/app/src/lib/i18n/it.ts@@ -480,7 +480,7 @@ const messages: TranslationMap = {'settings.analysisViews.title': 'Viste di analisi','settings.analysisViews.menuDesc':'Analisi del grafo di memoria: diagramma, centralità, coesione, associazioni, freschezza, cronologia, percorsi e namespace',- 'settings.tokenUsage.title': 'Token e costo',+ 'settings.tokenUsage.title': 'Risparmio di token','settings.tokenUsage.menuDesc':'Impostazioni di compressione e quanti token e dollari hanno fatto risparmiare','settings.tokenUsage.saving': 'Salvataggio…',diff --git a/app/src/lib/i18n/ko.ts b/app/src/lib/i18n/ko.tsindex f6b03d3084..71e21c604f 100644--- a/app/src/lib/i18n/ko.ts+++ b/app/src/lib/i18n/ko.ts@@ -464,7 +464,7 @@ const messages: TranslationMap = {'settings.analysisViews.title': '분석 보기','settings.analysisViews.menuDesc':'메모리 그래프 분석: 다이어그램, 중심성, 응집도, 연관, 최신성, 타임라인, 경로 및 네임스페이스',- 'settings.tokenUsage.title': '토큰 및 비용',+ 'settings.tokenUsage.title': '토큰 절감','settings.tokenUsage.menuDesc': '압축 설정과 그것이 절약한 토큰 및 달러의 양','settings.tokenUsage.saving': '저장 중…','settings.tokenUsage.saved': '저장됨',diff --git a/app/src/lib/i18n/pl.ts b/app/src/lib/i18n/pl.tsindex 84739f587a..8c7cd6906a 100644--- a/app/src/lib/i18n/pl.ts+++ b/app/src/lib/i18n/pl.ts@@ -478,7 +478,7 @@ const messages: TranslationMap = {'settings.analysisViews.title': 'Widoki analizy','settings.analysisViews.menuDesc':'Analiza grafu pamięci: diagram, centralność, spójność, powiązania, świeżość, oś czasu, ścieżki i przestrzenie nazw',- 'settings.tokenUsage.title': 'Tokeny i koszt',+ 'settings.tokenUsage.title': 'Oszczędność tokenów','settings.tokenUsage.menuDesc': 'Ustawienia kompresji oraz ile tokenów i dolarów zaoszczędziły','settings.tokenUsage.saving': 'Zapisywanie…','settings.tokenUsage.saved': 'Zapisano',diff --git a/app/src/lib/i18n/pt.ts b/app/src/lib/i18n/pt.tsindex a805c5530d..e0503a16c7 100644--- a/app/src/lib/i18n/pt.ts+++ b/app/src/lib/i18n/pt.ts@@ -477,7 +477,7 @@ const messages: TranslationMap = {'settings.analysisViews.title': 'Visões de análise','settings.analysisViews.menuDesc':'Análise do grafo de memória: diagrama, centralidade, coesão, associações, atualidade, linha do tempo, caminhos e namespaces',- 'settings.tokenUsage.title': 'Tokens e custo',+ 'settings.tokenUsage.title': 'Economia de tokens','settings.tokenUsage.menuDesc':'Configurações de compressão e quantos tokens e dólares elas economizaram','settings.tokenUsage.saving': 'Salvando…',diff --git a/app/src/lib/i18n/ru.ts b/app/src/lib/i18n/ru.tsindex c531c5258c..5a87e75fd7 100644--- a/app/src/lib/i18n/ru.ts+++ b/app/src/lib/i18n/ru.ts@@ -475,7 +475,7 @@ const messages: TranslationMap = {'settings.analysisViews.title': 'Аналитические виды','settings.analysisViews.menuDesc':'Анализ графа памяти: диаграмма, центральность, связность, ассоциации, свежесть, временная шкала, пути и пространства имён',- 'settings.tokenUsage.title': 'Токены и стоимость',+ 'settings.tokenUsage.title': 'Экономия токенов','settings.tokenUsage.menuDesc': 'Настройки сжатия и сколько токенов и долларов они сэкономили','settings.tokenUsage.saving': 'Сохранение…','settings.tokenUsage.saved': 'Сохранено',diff --git a/app/src/lib/i18n/zh-CN.ts b/app/src/lib/i18n/zh-CN.tsindex babe2a227d..fb5f00e9af 100644--- a/app/src/lib/i18n/zh-CN.ts+++ b/app/src/lib/i18n/zh-CN.ts@@ -434,7 +434,7 @@ const messages: TranslationMap = {'settings.analysisViews.title': '分析视图','settings.analysisViews.menuDesc':'内存图分析:关系图、中心性、内聚性、关联、新鲜度、时间线、路径和命名空间',- 'settings.tokenUsage.title': '令牌与成本',+ 'settings.tokenUsage.title': '令牌节省','settings.tokenUsage.menuDesc': '压缩设置以及它们已节省的令牌和美元数量','settings.tokenUsage.saving': '正在保存…','settings.tokenUsage.saved': '已保存',diff --git a/app/test/playwright/specs/token-usage-load-failure.spec.ts b/app/test/playwright/specs/token-usage-load-failure.spec.tsindex 0a304506dc..a2241a367b 100644--- a/app/test/playwright/specs/token-usage-load-failure.spec.ts+++ b/app/test/playwright/specs/token-usage-load-failure.spec.ts@@ -7,7 +7,7 @@ import {} from '../helpers/core-rpc';/**- * Token & Cost panel — what the compression switches do when their settings+ * Token savings panel — what the compression switches do when their settings* never arrive (#5925).** Two separate properties, and before #5925 the panel got both wrong:@@ -57,7 +57,7 @@ async function openUsageTab(page: Page) {await dismissWalkthroughIfPresent(page);}-test.describe('Token & Cost — settings that fail to load', () => {+test.describe('Token savings — settings that fail to load', () => {test('a settings failure disables every compression switch', async ({ page }) => {await bootAuthenticatedPage(page, 'pw-w6-tokenusage-settings-fail', '/connections?tab=usage');await failMethod(diff --git a/crates/openhuman-core/src/agent/tinyagents/host/budget_gate.rs b/crates/openhuman-core/src/agent/tinyagents/host/budget_gate.rsindex 19fd30a8d4..92ec64f3b2 100644--- a/crates/openhuman-core/src/agent/tinyagents/host/budget_gate.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/budget_gate.rs@@ -10,9 +10,10 @@//! * **admission / back-pressure** — [`scheduler_gate::wait_for_capacity`],//! which owns the single-slot global LLM semaphore and the//! AC-power / CPU / signed-out policy backoff;-//! * **budget refusal + accounting** — [`cost::CostTracker::check_budget`] and-//! [`cost::record_provider_usage`], priced through-//! [`cost::catalog::estimate_cost_usd`];+//! * **pricing hints** — [`cost::catalog::estimate_cost_usd`] on the way in.+//! Nothing here refuses a call on cost, and nothing here writes the cost+//! ledger: the event bridge records each model call under its real model, and+//! a second write from this gate double-counted tokens and requests;//! * **compression advice** — the agent's//! [`AgentTokenjuiceCompression`] profile, which decides how much lossy//! compaction that agent tolerates.@@ -32,10 +33,8 @@//! in flight on one gate the attribution can transpose. The alternative —//! dropping the record entirely — loses the spend, which is strictly worse//! for a budget guard.-//! * *Pricing* — with no provider-reported charge available, the cost is-//! estimated from the catalog. See the `TODO(phase4)` on [`Self::record`]:-//! OpenHuman will label that record `CostSource::ProviderCharged` even though-//! it is an estimate.+//! * *Pricing* — with no provider-reported charge available, the pre-call+//! estimate comes from the catalog and is only logged.//!//! **2. `compression_hint` must be cheap and synchronous**, but every budget//! read in OpenHuman goes through a mutex and may touch the JSONL store. The@@ -51,9 +50,8 @@//! profile is `Off` yields `None` rather than anything stronger — `Off` opts//! that agent out of *TokenJuice*, not out of summarization.//!-//! Nothing here bypasses an OpenHuman guard: budget refusal still goes through-//! `check_budget` (which honours `cost.enabled`), and the scheduler-gate permit-//! is held for exactly the lifetime of the crate permit.+//! Nothing here bypasses an OpenHuman guard: the scheduler-gate permit is held+//! for exactly the lifetime of the crate permit.use std::sync::Arc;@@ -68,7 +66,6 @@ use tinyinference_llm::usage::Usage;use crate::config::{Config, DEFAULT_MODEL};use crate::cron::scheduler_gate;-use crate::inference::provider::types::UsageInfo;use crate::inference::tokenjuice::AgentTokenjuiceCompression;use crate::platform::cost;@@ -262,58 +259,24 @@ impl BudgetGate for OpenHumanBudgetGate {.with_reserved_tokens(est.estimated_total_tokens()))}- /// Persists realised usage to OpenHuman's cost tracker and refreshes the- /// cached budget pressure.+ /// Observes realised usage. Additive and non-fatal, as the trait requires:+ /// it is also called for failed calls that burned tokens.///- /// Additive and non-fatal, as the trait requires: it is also called for- /// failed calls that burned tokens, and `record_provider_usage` swallows- /// its own write errors so cost tracking can never break a turn. An- /// all-zero `Usage` is skipped by that helper rather than inflating the- /// request count with a non-event.- ///- /// TODO(phase4): the record's `CostSource` will read `ProviderCharged`- /// even though the amount is a catalog estimate — `build_token_usage` in- /// `crates/openhuman-core/src/cost/global.rs` infers provenance from- /// `charged_amount_usd > 0.0`, and the crate's `Usage` carries neither a- /// charged amount nor a cost field to distinguish them. The fix is an- /// explicit estimated-usage entry point in `cost::global` (or a- /// `cost_source` argument on `record_provider_usage`); pricing here is- /// deliberately not skipped, because a zero-cost ledger would silently- /// disable `check_budget` enforcement altogether.+ /// Deliberately does not write the cost ledger. The event bridge+ /// (`observability::event_bridge`) records every model call under its real+ /// model with the provider-charged amount; this gate would add a second row+ /// under `host:<agent_id>` with an estimated cost, doubling the tokens and+ /// request counts on the dashboard. Nothing reads spend from here to refuse+ /// a call, so there is no enforcement to feed.async fn record(&self, usage: &Usage) -> Result<()> {- let model = self.attributed_model();- let charged_amount_usd = cost::catalog::estimate_cost_usd(- &model,- usage.input_tokens,- usage.output_tokens,- usage.cache_read_tokens,- );-- cost::record_provider_usage(- &model,- &UsageInfo {- input_tokens: usage.input_tokens,- output_tokens: usage.output_tokens,- // The crate's `Usage` does not carry the model's context- // window; `UsageInfo::context_window` documents 0 as unknown.- context_window: 0,- cached_input_tokens: usage.cache_read_tokens,- cache_creation_tokens: usage.cache_creation_tokens,- reasoning_tokens: usage.reasoning_tokens,- charged_amount_usd,- },- );-log::debug!(- "[tinyagents][budget] recorded usage model={model} in={} out={} cached={} \- est_usd={charged_amount_usd:.6}",+ "[tinyagents][budget] observed usage model={} in={} out={} cached={} (ledger is \+ written by the event bridge)",+ self.attributed_model(),usage.input_tokens,usage.output_tokens,usage.cache_read_tokens,);-- // Reconcile after the spend: this is the I/O-bearing refresh that- // `compression_hint` then reads for free.Ok(())}diff --git a/crates/openhuman-core/src/agent/tinyagents/host/budget_gate_tests.rs b/crates/openhuman-core/src/agent/tinyagents/host/budget_gate_tests.rsindex 1cb44a6f59..0607fec4f3 100644--- a/crates/openhuman-core/src/agent/tinyagents/host/budget_gate_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/budget_gate_tests.rs@@ -125,6 +125,33 @@ async fn explicit_release_returns_capacity_before_end_of_scope() {.expect("grants");}+#[tokio::test]+async fn recording_usage_does_not_write_a_second_ledger_row() {+ // The event bridge already records every model call under its real model.+ // A `host:<agent>` row from this gate doubled tokens and request counts.+ const MODEL: &str = "budget-gate-probe/no-duplicate-row";+ let tmp = tempfile::TempDir::new().unwrap();+ let mut cost_config = crate::config::CostConfig::default();+ cost_config.enabled = true;+ crate::platform::cost::rebind_global(cost_config, tmp.path());++ let gate = gate(AgentTokenjuiceCompression::Auto);+ let _permit = gate+ .acquire(&CallEstimate::new(MODEL, 1_000, 250))+ .await+ .expect("grants");+ gate.record(&Usage::new(1_000, 250))+ .await+ .expect("recording never fails the turn");++ let ledger =+ std::fs::read_to_string(tmp.path().join("state").join("costs.jsonl")).unwrap_or_default();+ assert!(+ !ledger.contains(MODEL) && !ledger.contains("host:"),+ "the gate must not write to the cost ledger, got: {ledger}"+ );+}+#[tokio::test]async fn recording_usage_is_a_soft_no_op_without_a_tracker() {// `cost::try_global()` is `None` in unit tests. Recording must stilldiff --git a/crates/openhuman-core/src/agent/tinyagents/turn_outcome.rs b/crates/openhuman-core/src/agent/tinyagents/turn_outcome.rsindex da12297003..a2a2a85685 100644--- a/crates/openhuman-core/src/agent/tinyagents/turn_outcome.rs+++ b/crates/openhuman-core/src/agent/tinyagents/turn_outcome.rs@@ -108,8 +108,8 @@ pub(crate) type HaltSummarySlot = std::sync::Arc<std::sync::Mutex<Option<String>/// which only exists on observed runs (`on_progress` set). Without this/// aggregate record a fire-and-forget turn's spend never reaches the cost/// dashboard / wallet surfaces (issue #4249, Phase 5 rollup gap). The bridge-/// and this fallback are mutually exclusive, so spend is recorded exactly once-/// either way.+/// and this fallback are mutually exclusive, and the host budget gate does not+/// write the ledger, so spend is recorded exactly once either way.////// Returns `true` when a record was attempted (any tokens observed); all-zero/// usage is skipped so providers that echo no usage don't inflate the requestdiff --git a/crates/openhuman-core/src/platform/cost/README.md b/crates/openhuman-core/src/platform/cost/README.mdindex 0abc4defd6..cc9d63ad25 100644--- a/crates/openhuman-core/src/platform/cost/README.md+++ b/crates/openhuman-core/src/platform/cost/README.md@@ -19,7 +19,7 @@ Local API-usage cost tracking for the agent. Records per-call token usage and co| `crates/openhuman-core/src/platform/cost/mod.rs` | Export-focused module root; re-exports tracker, types, global helpers, and the `all_cost_*` controller schema/registry pair. || `crates/openhuman-core/src/platform/cost/types.rs` | Serde domain types: `TokenUsage`, `CostSource`, `CostRecord`, `UsagePeriod`, `CostSummary`, `ModelStats`, `DailyCostEntry`, `BudgetStatus`, `CostDashboard`. Cost-calc logic lives in `TokenUsage::new`. || `crates/openhuman-core/src/platform/cost/tracker.rs` | `CostTracker` (recording, summaries, daily history, dashboard build) plus the private `CostStorage` JSONL persistence + aggregate-cache layer. Functions as both `ops` and `store`. |-| `crates/openhuman-core/src/platform/cost/global.rs` | Process-global `OnceCell<Arc<CostTracker>>` singleton: `init_global`, `try_global`, `record_provider_usage`, and `build_token_usage` (provider `UsageInfo` → `TokenUsage`). |+| `crates/openhuman-core/src/platform/cost/global.rs` | Process-global `RwLock<Option<Arc<CostTracker>>>` singleton: `init_global`, `rebind_global` (follows the active workspace on sign-in/out), `try_global`, `record_provider_usage`, and `build_token_usage` (provider `UsageInfo` → `TokenUsage`). || `crates/openhuman-core/src/platform/cost/rpc.rs` | RPC-facing handlers (`dashboard`, `daily_history`, `summary`) returning `RpcOutcome<Value>`; DTO types; `resolve_tracker` with a cached fallback tracker + error-replay TTL. || `crates/openhuman-core/src/platform/cost/schemas.rs` | Controller schemas + `handle_*` JSON-RPC dispatchers; `all_controller_schemas` / `all_registered_controllers`. || `crates/openhuman-core/src/platform/cost/tracker_tests.rs` | Sibling test suite for `tracker.rs` (`#[path]`-included). |@@ -32,7 +32,7 @@ Local API-usage cost tracking for the agent. Records per-call token usage and coFrom `mod.rs` re-exports:- `CostTracker`: the tracker (`tracker`).-- `init_global`, `try_global`, `record_provider_usage` (`global`).+- `init_global`, `rebind_global`, `try_global`, `record_provider_usage` (`global`).- `all_cost_controller_schemas`, `all_cost_registered_controllers` (`schemas`).- Types: `BudgetStatus`, `CostDashboard`, `CostRecord`, `CostSource`, `CostSummary`, `DailyCostEntry`, `ModelStats`, `TokenUsage`, `UsagePeriod`.diff --git a/crates/openhuman-core/src/platform/cost/global.rs b/crates/openhuman-core/src/platform/cost/global.rsindex 6aa76e2f86..54978712fd 100644--- a/crates/openhuman-core/src/platform/cost/global.rs+++ b/crates/openhuman-core/src/platform/cost/global.rs@@ -8,11 +8,16 @@//! `bootstrap_core_runtime` path calls [`init_global`] at startup, and any//! later call is a no-op. Callers that run before bootstrap (e.g. unit//! tests) see `None` from [`try_global`] and skip recording — never a panic.+//!+//! The tracker is bound to one workspace. Signing in or out switches the+//! active workspace (`users/local` <-> `users/<id>`), so the credential path+//! calls [`rebind_global`] to move it; otherwise usage recorded after login+//! would keep landing in the pre-login ledger.use std::path::Path;use std::sync::Arc;-use once_cell::sync::OnceCell;+use parking_lot::RwLock;use crate::config::CostConfig;use crate::inference::provider::types::UsageInfo;@@ -20,7 +25,7 @@ use crate::inference::provider::types::UsageInfo;use super::tracker::CostTracker;use super::types::{CostSource, TokenUsage};-static GLOBAL_TRACKER: OnceCell<Arc<CostTracker>> = OnceCell::new();+static GLOBAL_TRACKER: RwLock<Option<Arc<CostTracker>>> = RwLock::new(None);/// Initialise the global cost tracker. Idempotent — subsequent calls are/// no-ops and the original tracker is preserved. Logs (but does not panic)@@ -35,29 +40,14 @@ static GLOBAL_TRACKER: OnceCell<Arc<CostTracker>> = OnceCell::new();/// workspace so the default-on behaviour shows up in startup logs for/// existing deployments that omit the `[cost]` block.pub fn init_global(config: CostConfig, workspace_dir: &Path) {- if GLOBAL_TRACKER.get().is_some() {+ if GLOBAL_TRACKER.read().is_some() {return;}let cost_enabled = config.enabled;match CostTracker::new(config, workspace_dir) {- Ok(tracker) => match GLOBAL_TRACKER.set(Arc::new(tracker)) {- Ok(()) => {- log::info!(- "[cost] global CostTracker initialised at workspace {} (cost.enabled={}, \- dashboard telemetry always-on). Set cost.dashboard.enabled=false in \- config.toml to hide the panel.",- workspace_dir.display(),- cost_enabled- );- if !cost_enabled {- log::warn!(- "[cost] cost.enabled=false: dashboard telemetry will still append to \- costs.jsonl. Set cost.dashboard.enabled=false to disable the panel; \- the JSONL is local and never leaves the workspace."- );- }- }- Err(_) => {+ Ok(tracker) => {+ let mut slot = GLOBAL_TRACKER.write();+ if slot.is_some() {// Another caller won a concurrent init race; the original// tracker is kept. Avoid logging a misleading "initialised"// line — the winner already did so.@@ -65,8 +55,25 @@ pub fn init_global(config: CostConfig, workspace_dir: &Path) {"[cost] global CostTracker already initialised by another caller; \discarding duplicate instance");+ return;}- },+ *slot = Some(Arc::new(tracker));+ drop(slot);+ log::info!(+ "[cost] global CostTracker initialised at workspace {} (cost.enabled={}, \+ dashboard telemetry always-on). Set cost.dashboard.enabled=false in \+ config.toml to hide the panel.",+ workspace_dir.display(),+ cost_enabled+ );+ if !cost_enabled {+ log::warn!(+ "[cost] cost.enabled=false: dashboard telemetry will still append to \+ costs.jsonl. Set cost.dashboard.enabled=false to disable the panel; \+ the JSONL is local and never leaves the workspace."+ );+ }+ }Err(err) => {log::warn!("[cost] failed to initialise global CostTracker at {}: {err} \@@ -77,11 +84,50 @@ pub fn init_global(config: CostConfig, workspace_dir: &Path) {}}+/// Point the global tracker at `workspace_dir` when it is bound elsewhere.+///+/// Called when the active workspace changes (sign-in, sign-out). A no-op when+/// the tracker already serves `workspace_dir`. Old ledgers are not migrated:+/// each workspace keeps its own `costs.jsonl`. The session-scoped in-memory+/// figures start over with the new tracker. A failed construction keeps the+/// previous tracker rather than leaving the process with none.+pub fn rebind_global(config: CostConfig, workspace_dir: &Path) {+ if let Some(current) = try_global() {+ if current.workspace_dir() == workspace_dir {+ log::debug!(+ "[cost] rebind_global: tracker already bound to workspace {}",+ workspace_dir.display()+ );+ return;+ }+ }+ match CostTracker::new(config, workspace_dir) {+ Ok(tracker) => {+ let previous = GLOBAL_TRACKER.write().replace(Arc::new(tracker));+ log::info!(+ "[cost] global CostTracker rebound from workspace {} to {}",+ previous+ .as_ref()+ .map(|t| t.workspace_dir().display().to_string())+ .unwrap_or_else(|| "<unbound>".to_string()),+ workspace_dir.display()+ );+ }+ Err(err) => {+ log::warn!(+ "[cost] failed to rebind global CostTracker to {}: {err}; keeping the \+ previous tracker",+ workspace_dir.display()+ );+ }+ }+}+/// Fetch the global tracker if it has been initialised. Returns `None`/// before bootstrap or after an init failure — callers must treat the/// absence as a soft no-op.pub fn try_global() -> Option<Arc<CostTracker>> {- GLOBAL_TRACKER.get().cloned()+ GLOBAL_TRACKER.read().clone()}/// Convenience hook used by the agent turn loop: translates a providerdiff --git a/crates/openhuman-core/src/platform/cost/global_tests.rs b/crates/openhuman-core/src/platform/cost/global_tests.rsindex 591252865f..20701dac7d 100644--- a/crates/openhuman-core/src/platform/cost/global_tests.rs+++ b/crates/openhuman-core/src/platform/cost/global_tests.rs@@ -140,9 +140,9 @@ fn init_global_is_idempotent() {// A second `init_global` must be a no-op and must preserve the tracker the// first caller installed (`global.rs` early-returns when the cell is set).//- // Asserting that through `try_global()` alone would be vacuous: the cell is- // a `OnceCell`, so `set` refuses the replacement even with the early return- // deleted, and the *pointer* stays equal either way. The observable that+ // Asserting that through `try_global()` alone would be vacuous: the slot is+ // only filled when empty, so it refuses the replacement even with the early+ // return deleted, and the *pointer* stays equal either way. The observable that// actually distinguishes the two is one level down — `CostTracker::new`// eagerly creates `<workspace>/state/` (`CostStorage::new` ->// `fs::create_dir_all`). So if the guard is removed, the second call@@ -182,3 +182,42 @@ fn init_global_is_idempotent() {"second init_global replaced the installed tracker instance");}++#[test]+fn rebind_global_moves_recording_to_the_new_workspace() {+ let _lock = tracker_test_lock();+ const MODEL_A: &str = "test-model/rebind-before-login";+ const MODEL_B: &str = "test-model/rebind-after-login";+ let previous = try_global();+ let before_login = TempDir::new().unwrap();+ let after_login = TempDir::new().unwrap();+ let mut cfg = CostConfig::default();+ cfg.enabled = true;++ rebind_global(cfg.clone(), before_login.path());+ record_provider_usage(MODEL_A, &make_usage(10, 5, 0.1));++ rebind_global(cfg.clone(), after_login.path());+ let bound = try_global().expect("rebind leaves a tracker installed");+ assert_eq!(bound.workspace_dir(), after_login.path());+ record_provider_usage(MODEL_B, &make_usage(20, 10, 0.2));++ let ledger = |dir: &TempDir| {+ std::fs::read_to_string(dir.path().join("state").join("costs.jsonl")).unwrap_or_default()+ };+ assert!(ledger(&before_login).contains(MODEL_A));+ assert!(!ledger(&before_login).contains(MODEL_B));+ assert!(ledger(&after_login).contains(MODEL_B));+ assert!(!ledger(&after_login).contains(MODEL_A));+ assert_eq!(records_for_model(&bound, MODEL_B).len(), 1);+ assert!(records_for_model(&bound, MODEL_A).is_empty());++ rebind_global(cfg, after_login.path());+ let unchanged = try_global().unwrap();+ assert!(+ std::sync::Arc::ptr_eq(&bound, &unchanged),+ "rebinding to the workspace already served must keep the tracker"+ );++ *GLOBAL_TRACKER.write() = previous;+}diff --git a/crates/openhuman-core/src/platform/cost/mod.rs b/crates/openhuman-core/src/platform/cost/mod.rsindex e601fa3e87..f09bd8ebd9 100644--- a/crates/openhuman-core/src/platform/cost/mod.rs+++ b/crates/openhuman-core/src/platform/cost/mod.rs@@ -7,7 +7,9 @@ pub mod tools;pub mod tracker;pub mod types;-pub use global::{init_global, record_embedding_usage, record_provider_usage, try_global};+pub use global::{+ init_global, rebind_global, record_embedding_usage, record_provider_usage, try_global,+};pub use route::{route_for_model, CostRoute};pub use schemas::{all_controller_schemas as all_cost_controller_schemas,@@ -21,8 +23,9 @@ pub use types::{/// Serialises tests that touch the process-global [`CostTracker`].///-/// The tracker is a one-shot `OnceCell` shared by every test in this binary,-/// so a test that reads it and a test that installs it must not interleave:+/// The tracker is one process-wide slot shared by every test in this binary,+/// so a test that reads it and a test that installs or rebinds it must not+/// interleave:/// `rpc_tests::dashboard_query_includes_persisted_record` guards itself with/// `try_global().is_some()`, and that check-then-use is only sound while no/// other test can call `init_global` between the two. Every test in thisdiff --git a/crates/openhuman-core/src/platform/cost/rpc.rs b/crates/openhuman-core/src/platform/cost/rpc.rsindex 318791674c..d8251211d3 100644--- a/crates/openhuman-core/src/platform/cost/rpc.rs+++ b/crates/openhuman-core/src/platform/cost/rpc.rs@@ -21,7 +21,7 @@ use crate::config::{Config, CostConfig};use crate::rpc::RpcOutcome;use super::global::try_global;-use super::tracker::CostTracker;+use super::tracker::{non_negative_zero, CostTracker};use super::types::{BudgetStatus, CostDashboard, CostRecord, CostSource, CostSummary, DailyCostEntry, ModelStats,};@@ -183,7 +183,8 @@ fn usage_log_to_dto(days: u32,limit: usize,) -> UsageLogDto {- let total_cost_usd: f64 = records.iter().map(|record| record.usage.cost_usd).sum();+ let total_cost_usd: f64 =+ non_negative_zero(records.iter().map(|record| record.usage.cost_usd).sum());let total_tokens: u64 = records.iter().map(|record| record.usage.total_tokens).sum();let request_count = records.len();let mut by_category: HashMap<String, CategoryStatsDto> = HashMap::new();diff --git a/crates/openhuman-core/src/platform/cost/rpc_tests.rs b/crates/openhuman-core/src/platform/cost/rpc_tests.rsindex df4f52ddac..2c4a1fe59e 100644--- a/crates/openhuman-core/src/platform/cost/rpc_tests.rs+++ b/crates/openhuman-core/src/platform/cost/rpc_tests.rs@@ -276,3 +276,10 @@ fn dashboard_query_includes_persisted_record() {.unwrap();assert!((1.24..=1.26).contains(&total), "got total {total}");}++#[test]+fn usage_log_total_of_no_records_is_not_negative_zero() {+ let dto = usage_log_to_dto(Vec::new(), "USD".to_string(), 30, 100);+ assert!(dto.total_cost_usd.is_sign_positive());+ assert!(!serde_json::to_string(&dto).unwrap().contains("-0.0"));+}diff --git a/crates/openhuman-core/src/platform/cost/tracker.rs b/crates/openhuman-core/src/platform/cost/tracker.rsindex aea84c4e69..61bdf40ff0 100644--- a/crates/openhuman-core/src/platform/cost/tracker.rs+++ b/crates/openhuman-core/src/platform/cost/tracker.rs@@ -1,6 +1,7 @@use super::route::route_for_model;use super::types::{- BudgetStatus, CostDashboard, CostRecord, CostSummary, DailyCostEntry, ModelStats, TokenUsage,+ BudgetStatus, CostDashboard, CostRecord, CostSource, CostSummary, DailyCostEntry, ModelStats,+ TokenUsage,};use crate::config::CostConfig;use anyhow::{anyhow, Context, Result};@@ -15,6 +16,7 @@ use std::sync::Arc;/// Cost tracker for API usage monitoring and budget enforcement.pub struct CostTracker {config: CostConfig,+ workspace_dir: PathBuf,storage: Arc<Mutex<CostStorage>>,session_id: String,session_costs: Arc<Mutex<Vec<CostRecord>>>,@@ -31,6 +33,7 @@ impl CostTracker {Ok(Self {config,+ workspace_dir: workspace_dir.to_path_buf(),storage: Arc::new(Mutex::new(storage)),session_id: uuid::Uuid::new_v4().to_string(),session_costs: Arc::new(Mutex::new(Vec::new())),@@ -42,6 +45,11 @@ impl CostTracker {&self.session_id}+ /// Workspace this tracker persists into.+ pub fn workspace_dir(&self) -> &Path {+ &self.workspace_dir+ }+fn lock_storage(&self) -> MutexGuard<'_, CostStorage> {self.storage.lock()}@@ -103,10 +111,12 @@ impl CostTracker {};let session_costs = self.lock_session_costs();- let session_cost: f64 = session_costs- .iter()- .map(|record| record.usage.cost_usd)- .sum();+ let session_cost: f64 = non_negative_zero(+ session_costs+ .iter()+ .map(|record| record.usage.cost_usd)+ .sum(),+ );let total_tokens: u64 = session_costs.iter().map(|record| record.usage.total_tokens)@@ -262,7 +272,7 @@ impl CostTracker {alert_threshold: f64,) -> Result<CostDashboard> {let days = self.get_daily_history(7)?;- let period_total_usd: f64 = days.iter().map(|d| d.cost_usd).sum();+ let period_total_usd: f64 = non_negative_zero(days.iter().map(|d| d.cost_usd).sum());let daily_average = period_total_usd / days.len().max(1) as f64;let monthly_pace_usd = daily_average * 30.0;let budget_limit_monthly_usd = self.config.monthly_limit_usd.max(0.0);@@ -335,6 +345,24 @@ impl CostTracker {}}+/// An empty `f64` sum is `-0.0`, which serialises as `-0.0` and renders as+/// "-$0.00". Every derived total goes through this.+pub(super) fn non_negative_zero(value: f64) -> f64 {+ if value == 0.0 {+ 0.0+ } else {+ value+ }+}++/// Rows the budget gate once wrote as `host:<agent_id>` with an estimated cost+/// of zero. The event bridge already recorded the same model call under its+/// real model, so these only double the token and request counts. Ledgers+/// written before that stopped still hold them; every read skips them.+fn is_legacy_host_duplicate(record: &CostRecord) -> bool {+ record.usage.model.starts_with("host:") && record.usage.cost_source == CostSource::Estimated+}+fn resolve_storage_path(workspace_dir: &Path) -> Result<PathBuf> {let storage_path = workspace_dir.join("state").join("costs.jsonl");let legacy_path = workspace_dir.join(".openhuman").join("costs.db");@@ -457,6 +485,7 @@ impl CostStorage {}match serde_json::from_str::<CostRecord>(trimmed) {+ Ok(record) if is_legacy_host_duplicate(&record) => {}Ok(record) => on_record(record),Err(error) => {tracing::warn!(diff --git a/crates/openhuman-core/src/platform/cost/tracker_tests.rs b/crates/openhuman-core/src/platform/cost/tracker_tests.rsindex b0e21fa646..6c4dfac6ff 100644--- a/crates/openhuman-core/src/platform/cost/tracker_tests.rs+++ b/crates/openhuman-core/src/platform/cost/tracker_tests.rs@@ -513,3 +513,55 @@ fn daily_history_still_counts_calendar_days_inclusive_of_today() {);assert_eq!(history[0].request_count, 1);}++#[test]+fn legacy_host_estimated_rows_are_ignored_by_every_read() {+ let tmp = TempDir::new().unwrap();+ let mut real = TokenUsage::new("openrouter/vendor/real-model", 1000, 500, 0.0, 0.0);+ real.cost_usd = 0.25;+ real.cost_source = CostSource::ProviderCharged;+ let duplicate = TokenUsage::new("host:orchestrator", 1000, 500, 0.0, 0.0);+ assert_eq!(duplicate.cost_source, CostSource::Estimated);+ let mut kept_host = TokenUsage::new("host:kept", 40, 10, 0.0, 0.0);+ kept_host.cost_usd = 0.5;+ kept_host.cost_source = CostSource::ProviderCharged;+ for usage in [real, duplicate, kept_host] {+ write_raw_record(tmp.path(), &CostRecord::new("s", usage));+ }++ let tracker = CostTracker::new(enabled_config(), tmp.path()).unwrap();++ let today = Utc::now().date_naive();+ let day = tracker+ .get_daily_history(1)+ .unwrap()+ .into_iter()+ .find(|entry| entry.date == today)+ .unwrap();+ assert_eq!(+ day.request_count, 2,+ "the estimated host: row is a duplicate"+ );+ assert_eq!(day.total_tokens, 1500 + 50);+ assert!(!day.by_model.contains_key("host:orchestrator"));+ assert!(day.by_model.contains_key("host:kept"));++ let recent = tracker.get_recent_records(1, 100).unwrap();+ assert_eq!(recent.len(), 2);+ assert!(recent.iter().all(|r| r.usage.model != "host:orchestrator"));+}++#[test]+fn empty_ledger_sums_are_not_negative_zero() {+ let tmp = TempDir::new().unwrap();+ let tracker = CostTracker::new(enabled_config(), tmp.path()).unwrap();++ let summary = tracker.get_summary().unwrap();+ assert!(summary.session_cost_usd.is_sign_positive());+ assert!(!serde_json::to_string(&summary).unwrap().contains("-0.0"));++ let dashboard = tracker.get_dashboard("USD", 0.8, 0.95).unwrap();+ assert!(dashboard.period_total_usd.is_sign_positive());+ assert!(dashboard.monthly_pace_usd.is_sign_positive());+ assert!(!serde_json::to_string(&dashboard).unwrap().contains("-0.0"));+}diff --git a/crates/openhuman-core/src/security/credentials/ops/user_scope.rs b/crates/openhuman-core/src/security/credentials/ops/user_scope.rsindex 5a98310ddb..abaf617ace 100644--- a/crates/openhuman-core/src/security/credentials/ops/user_scope.rs+++ b/crates/openhuman-core/src/security/credentials/ops/user_scope.rs@@ -117,8 +117,9 @@ pub(super) async fn reload_config_or(_fallback: &Config) -> Result<Config, Strin/// Point every process-global store at `config`'s workspace after a/// credential change: cron seeds, the core context (which carries the memory-/// binding — see `CoreContext::memory_binding`, #5560), and conversation-/// persistence. Returns log lines for the RPC outcome.+/// binding — see `CoreContext::memory_binding`, #5560), conversation+/// persistence, and the process-global cost tracker. Returns log lines for+/// the RPC outcome.pub(super) fn rebind_after_credential_change(config: &Config,_reason: &str,@@ -136,5 +137,7 @@ pub(super) fn rebind_after_credential_change());conversations::register_conversation_persistence_subscriber(config.workspace_dir.clone());logs.push("conversation persistence bound to active workspace".to_string());+ crate::platform::cost::rebind_global(config.cost.clone(), &config.workspace_dir);+ logs.push("cost tracker bound to active workspace".to_string());Ok(logs)}