Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix: align usage dashboard with recorded costs and move billing to account

Steven Enamakel15a66b00b49e
diff --git a/app/src/components/dashboard/BudgetSummary.test.tsx b/app/src/components/dashboard/BudgetSummary.test.tsx
deleted file mode 100644
index a80905dd50..0000000000
--- a/app/src/components/dashboard/BudgetSummary.test.tsx
+++ /dev/null
@@ -1,71 +0,0 @@
-import { render, screen } from '@testing-library/react';
-import { describe, expect, it } from 'vitest';
-
-import BudgetSummary from './BudgetSummary';
-
-describe('<BudgetSummary />', () => {
- it('renders all four metric tiles and the status badge', () => {
- render(
- <BudgetSummary
- currency="USD"
- periodTotalUsd={42.5}
- monthlyPaceUsd={181.25}
- budgetLimitMonthlyUsd={200}
- monthToDateUsd={50}
- utilization={0.25}
- status="normal"
- />
- );
- expect(screen.getByTestId('metric-total-spend')).toBeInTheDocument();
- expect(screen.getByTestId('metric-monthly-pace')).toBeInTheDocument();
- expect(screen.getByTestId('metric-budget-limit')).toBeInTheDocument();
- expect(screen.getByTestId('utilization-fill')).toBeInTheDocument();
- expect(screen.getByTestId('budget-status-badge')).toHaveTextContent(/on track/i);
- });
-
- it('reflects "warning" status on the badge', () => {
- render(
- <BudgetSummary
- currency="USD"
- periodTotalUsd={1}
- monthlyPaceUsd={1}
- budgetLimitMonthlyUsd={10}
- monthToDateUsd={8}
- utilization={0.85}
- status="warning"
- />
- );
- expect(screen.getByTestId('budget-status-badge')).toHaveTextContent(/warning/i);
- });
-
- it('reflects "exceeded" status and clamps utilisation bar to 100%', () => {
- render(
- <BudgetSummary
- currency="USD"
- periodTotalUsd={1}
- monthlyPaceUsd={1}
- budgetLimitMonthlyUsd={10}
- monthToDateUsd={15}
- utilization={1}
- status="exceeded"
- />
- );
- expect(screen.getByTestId('budget-status-badge')).toHaveTextContent(/over budget/i);
- expect(screen.getByTestId('utilization-fill')).toHaveStyle({ width: '100%' });
- });
-
- it('falls back to "No limit set" when budget is zero', () => {
- render(
- <BudgetSummary
- currency="USD"
- periodTotalUsd={5}
- monthlyPaceUsd={5}
- budgetLimitMonthlyUsd={0}
- monthToDateUsd={0}
- utilization={0}
- status="normal"
- />
- );
- expect(screen.getByTestId('metric-budget-limit')).toHaveTextContent(/no limit set/i);
- });
-});
diff --git a/app/src/components/dashboard/BudgetSummary.tsx b/app/src/components/dashboard/BudgetSummary.tsx
deleted file mode 100644
index da439ce452..0000000000
--- a/app/src/components/dashboard/BudgetSummary.tsx
+++ /dev/null
@@ -1,197 +0,0 @@
-import type { ReactNode } from 'react';
-
-import type { BudgetStatus } from '../../hooks/useCostDashboard';
-import { useT } from '../../lib/i18n/I18nContext';
-import { formatCurrency } from './formatCurrency';
-
-interface BudgetSummaryProps {
- currency: string;
- periodTotalUsd: number;
- monthlyPaceUsd: number;
- budgetLimitMonthlyUsd: number;
- monthToDateUsd: number;
- utilization: number;
- status: BudgetStatus;
-}
-
-const STATUS_BG: Record<BudgetStatus, string> = {
- normal: 'bg-sage-500',
- warning: 'bg-amber-500',
- exceeded: 'bg-coral-500',
-};
-
-const STATUS_TEXT: Record<BudgetStatus, string> = {
- normal: 'text-sage-600 dark:text-sage-300',
- warning: 'text-amber-600 dark:text-amber-300',
- exceeded: 'text-coral-600 dark:text-coral-300',
-};
-
-const STATUS_LABEL_KEY: Record<BudgetStatus, string> = {
- normal: 'settings.costDashboard.budgetNormal',
- warning: 'settings.costDashboard.budgetWarning',
- exceeded: 'settings.costDashboard.budgetExceeded',
-};
-
-const BudgetSummary = ({
- currency,
- periodTotalUsd,
- monthlyPaceUsd,
- budgetLimitMonthlyUsd,
- monthToDateUsd,
- utilization,
- status,
-}: BudgetSummaryProps) => {
- const { t } = useT();
- const utilizationPct = Math.round(utilization * 100);
- const utilizationClamped = Math.min(100, Math.max(0, utilizationPct));
-
- return (
- <section
- data-testid="cost-dashboard-summary"
- className="grid grid-cols-1 md:grid-cols-3 gap-3"
- aria-label={t('settings.costDashboard.summaryAriaLabel')}>
- {/* Hero tile: 7-day total + status badge + progress bar */}
- <div
- data-testid="metric-total-spend"
- className="md:col-span-2 rounded-2xl border border-line bg-linear-to-br from-primary-50 to-surface dark:from-neutral-900 dark:to-neutral-950 p-5 flex flex-col gap-3 shadow-soft">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2 text-xs uppercase tracking-wide text-content-muted">
- <WalletIcon className="h-4 w-4" />
- <span>{t('settings.costDashboard.totalSpend')}</span>
- </div>
- <span
- data-testid="budget-status-badge"
- className={`inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-[11px] font-medium text-content-inverted ${STATUS_BG[status]}`}>
- <span
- aria-hidden
- className="inline-block h-1.5 w-1.5 rounded-full bg-surface/80 animate-pulse"
- />
- {t(STATUS_LABEL_KEY[status])}
- </span>
- </div>
- <div className="flex items-baseline gap-3">
- <span className="text-3xl md:text-4xl font-semibold tabular-nums text-content">
- {formatCurrency(periodTotalUsd, currency)}
- </span>
- <span className="text-xs text-content-muted">
- {t('settings.costDashboard.lastSevenDays')}
- </span>
- </div>
- <div className="flex flex-col gap-1">
- <div className="flex items-center justify-between text-[11px] text-content-muted">
- <span>
- {budgetLimitMonthlyUsd > 0
- ? `${formatCurrency(monthToDateUsd, currency)} ${t('settings.costDashboard.utilizationOf')} ${formatCurrency(budgetLimitMonthlyUsd, currency)} ${t('settings.costDashboard.thisMonth')}`
- : `${formatCurrency(monthToDateUsd, currency)} ${t('settings.costDashboard.thisMonth')}`}
- </span>
- <span className={`font-medium tabular-nums ${STATUS_TEXT[status]}`}>
- {`${utilizationPct}%`}
- </span>
- </div>
- <div aria-hidden className="h-2 w-full rounded-full bg-surface-strong overflow-hidden">
- <div
- data-testid="utilization-fill"
- className={`h-full rounded-full transition-all duration-300 ${STATUS_BG[status]}`}
- style={{ width: `${utilizationClamped}%` }}
- />
- </div>
- </div>
- </div>
-
- <div className="grid grid-cols-2 md:grid-cols-1 gap-3">
- <SmallMetric
- icon={<TrendingUpIcon className="h-4 w-4" />}
- label={t('settings.costDashboard.monthlyPace')}
- value={formatCurrency(monthlyPaceUsd, currency)}
- hint={t('settings.costDashboard.monthlyPaceHint')}
- testId="metric-monthly-pace"
- />
- <SmallMetric
- icon={<TargetIcon className="h-4 w-4" />}
- label={t('settings.costDashboard.budgetLimit')}
- value={
- budgetLimitMonthlyUsd > 0
- ? formatCurrency(budgetLimitMonthlyUsd, currency)
- : t('settings.costDashboard.noBudget')
- }
- hint={t('settings.costDashboard.budgetLimitHint')}
- testId="metric-budget-limit"
- />
- </div>
- </section>
- );
-};
-
-interface SmallMetricProps {
- icon: ReactNode;
- label: string;
- value: string;
- hint: string;
- testId: string;
-}
-
-const SmallMetric = ({ icon, label, value, hint, testId }: SmallMetricProps) => (
- <div
- data-testid={testId}
- title={hint}
- className="rounded-2xl border border-line p-3 flex flex-col gap-1 hover:border-primary-300 dark:hover:border-primary-700 transition-colors">
- <div className="flex items-center gap-2 text-[11px] uppercase tracking-wide text-content-muted">
- {icon}
- <span>{label}</span>
- </div>
- <span className="text-lg font-semibold tabular-nums text-content">{value}</span>
- </div>
-);
-
-interface IconProps {
- className?: string;
-}
-
-const WalletIcon = ({ className }: IconProps) => (
- <svg
- className={className}
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- strokeWidth="2"
- strokeLinecap="round"
- strokeLinejoin="round"
- aria-hidden>
- <path d="M21 12V7H5a2 2 0 0 1 0-4h14v4" />
- <path d="M3 5v14a2 2 0 0 0 2 2h16v-5" />
- <circle cx="17" cy="14" r="1.5" />
- </svg>
-);
-
-const TrendingUpIcon = ({ className }: IconProps) => (
- <svg
- className={className}
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- strokeWidth="2"
- strokeLinecap="round"
- strokeLinejoin="round"
- aria-hidden>
- <polyline points="23 6 13.5 15.5 8.5 10.5 1 18" />
- <polyline points="17 6 23 6 23 12" />
- </svg>
-);
-
-const TargetIcon = ({ className }: IconProps) => (
- <svg
- className={className}
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- strokeWidth="2"
- strokeLinecap="round"
- strokeLinejoin="round"
- aria-hidden>
- <circle cx="12" cy="12" r="10" />
- <circle cx="12" cy="12" r="6" />
- <circle cx="12" cy="12" r="2" />
- </svg>
-);
-
-export default BudgetSummary;
diff --git a/app/src/components/dashboard/CostBarChart.test.tsx b/app/src/components/dashboard/CostBarChart.test.tsx
deleted file mode 100644
index 8c992d2938..0000000000
--- a/app/src/components/dashboard/CostBarChart.test.tsx
+++ /dev/null
@@ -1,25 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import { colorForCost } from './CostBarChart';
-
-describe('colorForCost', () => {
- const warn = 0.8;
- const alert = 0.95;
-
- it('returns the normal hue when the daily target is zero (no budget set)', () => {
- expect(colorForCost(10, 0, warn, alert)).toBe('#4A83DD');
- });
-
- it('flips to amber once spend crosses the warn threshold', () => {
- // daily target $1.00, warn @ 80% → 0.85 triggers amber
- expect(colorForCost(0.85, 1, warn, alert)).toBe('#F5A524');
- });
-
- it('flips to red once spend reaches the alert threshold', () => {
- expect(colorForCost(0.95, 1, warn, alert)).toBe('#E5484D');
- });
-
- it('stays blue when well under warn', () => {
- expect(colorForCost(0.1, 1, warn, alert)).toBe('#4A83DD');
- });
-});
diff --git a/app/src/components/dashboard/CostBarChart.tsx b/app/src/components/dashboard/CostBarChart.tsx
index 7151f9182d..c89c110e73 100644
--- a/app/src/components/dashboard/CostBarChart.tsx
+++ b/app/src/components/dashboard/CostBarChart.tsx
@@ -3,7 +3,6 @@ import {
BarChart,
Cell,
LabelList,
- ReferenceLine,
ResponsiveContainer,
Tooltip,
XAxis,
@@ -18,31 +17,9 @@ import { dayOfMonth, formatCurrency, longDateLabel, shortDayLabel } from './form
interface CostBarChartProps {
days: CostDashboardDay[];
currency: string;
- /** Monthly budget in USD; used to derive a daily target. */
- budgetLimitMonthlyUsd: number;
- /** Fraction of daily target that flips bar colour to amber. */
- warnThreshold: number;
- /** Fraction of daily target that flips bar colour to red. */
- alertThreshold: number;
}
const NORMAL_FILL = '#4A83DD';
-const WARN_FILL = '#F5A524';
-const ALERT_FILL = '#E5484D';
-const TARGET_STROKE = '#94A3B8';
-
-export function colorForCost(
- cost: number,
- dailyTarget: number,
- warnThreshold: number,
- alertThreshold: number
-): string {
- if (dailyTarget <= 0) return NORMAL_FILL;
- const ratio = cost / dailyTarget;
- if (ratio >= alertThreshold) return ALERT_FILL;
- if (ratio >= warnThreshold) return WARN_FILL;
- return NORMAL_FILL;
-}
interface ChartPoint {
date: string;
@@ -50,19 +27,11 @@ interface ChartPoint {
dayNumber: string;
cost: number;
requestCount: number;
- fill: string;
isToday: boolean;
}
-const CostBarChart = ({
- days,
- currency,
- budgetLimitMonthlyUsd,
- warnThreshold,
- alertThreshold,
-}: CostBarChartProps) => {
+const CostBarChart = ({ days, currency }: CostBarChartProps) => {
const { t } = useT();
- const dailyTarget = budgetLimitMonthlyUsd > 0 ? budgetLimitMonthlyUsd / 30 : 0;
const todayDate = days.length > 0 ? days[days.length - 1].date : null;
const chartData: ChartPoint[] = days.map(day => ({
@@ -71,23 +40,11 @@ const CostBarChart = ({
dayNumber: dayOfMonth(day.date),
cost: Number(day.cost_usd.toFixed(4)),
requestCount: day.request_count,
- fill: colorForCost(day.cost_usd, dailyTarget, warnThreshold, alertThreshold),
isToday: day.date === todayDate,
}));
return (
<div data-testid="cost-bar-chart" className="w-full">
- {dailyTarget > 0 && (
- <div className="text-[11px] text-content-muted mb-1 flex items-center gap-1.5">
- <span
- aria-hidden
- className="inline-block h-px w-3 border-t border-dashed border-content-faint"
- />
- <span>
- {`${t('settings.costDashboard.dailyTarget')}: ${formatCurrency(dailyTarget, currency)}`}
- </span>
- </div>
- )}
<div className="w-full h-56">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={chartData} margin={{ top: 16, right: 8, left: 0, bottom: 0 }}>
@@ -130,36 +87,22 @@ const CostBarChart = ({
{
label: t('settings.costDashboard.cost'),
value: formatCurrency(item.cost, currency),
- color: item.fill,
+ color: NORMAL_FILL,
},
{
label: t('settings.costDashboard.requests'),
value: String(item.requestCount),
},
]}
- footer={
- dailyTarget > 0
- ? `${t('settings.costDashboard.dailyTarget')}: ${formatCurrency(dailyTarget, currency)}`
- : undefined
- }
/>
);
}}
/>
- {dailyTarget > 0 && (
- <ReferenceLine
- y={dailyTarget}
- stroke={TARGET_STROKE}
- strokeDasharray="4 4"
- strokeWidth={1}
- ifOverflow="extendDomain"
- />
- )}
<Bar dataKey="cost" radius={[6, 6, 0, 0]} isAnimationActive={false} maxBarSize={56}>
{chartData.map(entry => (
<Cell
key={entry.date}
- fill={entry.fill}
+ fill={NORMAL_FILL}
stroke={entry.isToday ? '#0F172A' : 'transparent'}
strokeOpacity={entry.isToday ? 0.15 : 0}
/>
diff --git a/app/src/components/dashboard/CostDashboardPanel.test.tsx b/app/src/components/dashboard/CostDashboardPanel.test.tsx
index 0e967ec7e5..b46569bbea 100644
--- a/app/src/components/dashboard/CostDashboardPanel.test.tsx
+++ b/app/src/components/dashboard/CostDashboardPanel.test.tsx
@@ -48,38 +48,6 @@ function renderPanel() {
);
}
-const usageLogPayload = {
- records: [
- {
- id: 'record-1',
- timestamp: '2026-05-27T12:00:00Z',
- session_id: 'session-abcdef',
- model: 'anthropic/claude-sonnet-4',
- provider: 'anthropic',
- category: 'AI chat and reasoning',
- input_tokens: 1000,
- output_tokens: 500,
- total_tokens: 1500,
- cost_usd: 1.25,
- },
- ],
- by_category: [
- {
- category: 'AI chat and reasoning',
- cost_usd: 1.25,
- total_tokens: 1500,
- request_count: 1,
- percent_of_total: 100,
- },
- ],
- total_cost_usd: 1.25,
- total_tokens: 1500,
- request_count: 1,
- currency: 'USD',
- days: 30,
- limit: 250,
-};
-
describe('<CostDashboardPanel />', () => {
beforeEach(() => {
mockedCall.mockReset();
@@ -90,49 +58,46 @@ describe('<CostDashboardPanel />', () => {
});
it('shows the loading state and then renders all sections', async () => {
- mockedCall
- .mockResolvedValueOnce({
- days: Array.from({ length: 7 }, (_, i) => ({
- date: `2026-05-${21 + i}`,
- cost_usd: i === 6 ? 1.25 : 0,
- input_tokens: i === 6 ? 1000 : 0,
- output_tokens: i === 6 ? 500 : 0,
- total_tokens: i === 6 ? 1500 : 0,
- request_count: i === 6 ? 1 : 0,
- by_model: [],
- })),
- period_total_usd: 1.25,
- monthly_pace_usd: 5.36,
- budget_limit_monthly_usd: 100,
- month_to_date_usd: 1.25,
- budget_utilization: 0.0125,
- budget_status: 'normal',
- currency: 'USD',
- warn_threshold: 0.8,
- alert_threshold: 0.95,
- enabled: true,
- by_model: [
- {
- model: 'anthropic/claude-sonnet-4',
- cost_usd: 1.25,
- total_tokens: 1500,
- request_count: 1,
- provider: 'anthropic',
- percent_of_total: 100,
- },
- ],
- })
- .mockResolvedValueOnce(usageLogPayload);
+ mockedCall.mockResolvedValueOnce({
+ days: Array.from({ length: 7 }, (_, i) => ({
+ date: `2026-05-${21 + i}`,
+ cost_usd: i === 6 ? 1.25 : 0,
+ input_tokens: i === 6 ? 1000 : 0,
+ output_tokens: i === 6 ? 500 : 0,
+ total_tokens: i === 6 ? 1500 : 0,
+ request_count: i === 6 ? 1 : 0,
+ by_model: [],
+ })),
+ period_total_usd: 1.25,
+ monthly_pace_usd: 5.36,
+ budget_limit_monthly_usd: 100,
+ month_to_date_usd: 1.25,
+ budget_utilization: 0.0125,
+ budget_status: 'normal',
+ currency: 'USD',
+ warn_threshold: 0.8,
+ alert_threshold: 0.95,
+ enabled: true,
+ by_model: [
+ {
+ model: 'anthropic/claude-sonnet-4',
+ cost_usd: 1.25,
+ total_tokens: 1500,
+ request_count: 1,
+ provider: 'anthropic',
+ percent_of_total: 100,
+ },
+ ],
+ });
renderPanel();
await waitFor(() => expect(screen.getByTestId('cost-dashboard-summary')).toBeInTheDocument());
expect(screen.getByTestId('cost-dashboard-cost-chart')).toBeInTheDocument();
expect(screen.getByTestId('cost-dashboard-token-chart')).toBeInTheDocument();
expect(screen.getByTestId('cost-dashboard-model-table')).toBeInTheDocument();
- expect(screen.getByTestId('cost-dashboard-category-distribution')).toBeInTheDocument();
- expect(screen.getByTestId('cost-dashboard-usage-log')).toHaveTextContent(
- 'AI chat and reasoning'
- );
- expect(mockedCall).toHaveBeenCalledWith(
+ expect(screen.queryByTestId('metric-budget-limit')).not.toBeInTheDocument();
+ expect(screen.queryByTestId('budget-status-badge')).not.toBeInTheDocument();
+ expect(screen.queryByTestId('cost-dashboard-usage-log')).not.toBeInTheDocument();
+ expect(mockedCall).not.toHaveBeenCalledWith(
expect.objectContaining({ method: 'openhuman.cost_get_usage_log' })
);
});
diff --git a/app/src/components/dashboard/CostDashboardPanel.tsx b/app/src/components/dashboard/CostDashboardPanel.tsx
index a6b2dcd8ef..2db90fb72c 100644
--- a/app/src/components/dashboard/CostDashboardPanel.tsx
+++ b/app/src/components/dashboard/CostDashboardPanel.tsx
@@ -1,42 +1,29 @@
-import { type ReactNode, useEffect, useMemo, useState } from 'react';
+import { useEffect, useMemo, useState } from 'react';
-import {
- type CostUsageCategoryStats,
- type CostUsageRecord,
- useCostDashboard,
- useCostUsageLog,
-} from '../../hooks/useCostDashboard';
+import { useCostDashboard } from '../../hooks/useCostDashboard';
import { useT } from '../../lib/i18n/I18nContext';
import { SettingsStatusLine } from '../settings/controls';
import SettingsPanel from '../settings/layout/SettingsPanel';
import { Alert, AlertDescription, Button, Card } from '../ui';
-import BudgetSummary from './BudgetSummary';
import CostBarChart from './CostBarChart';
+import CostSummary from './CostSummary';
import DashboardSkeleton from './DashboardSkeleton';
-import { formatCurrency, formatTokens, relativeTime } from './formatCurrency';
+import { relativeTime } from './formatCurrency';
import ModelCostTable from './ModelCostTable';
import TokenUsageChart from './TokenUsageChart';
interface CostDashboardPanelProps {
/** When true the panel is hosted inside another settings page (e.g. the
- * Usage & Limits tabs) — skip the standalone SettingsHeader chrome. */
+ * Usage tabs) — skip the standalone SettingsHeader chrome. */
embedded?: boolean;
}
const CostDashboardPanel = ({ embedded = false }: CostDashboardPanelProps) => {
const { t } = useT();
const { data, isLoading, isFetching, error, lastUpdated, refetch } = useCostDashboard();
- const {
- data: usageLog,
- isLoading: usageLogLoading,
- isFetching: usageLogFetching,
- error: usageLogError,
- lastUpdated: usageLogUpdated,
- refetch: refetchUsageLog,
- } = useCostUsageLog({ days: 30, limit: 250 });
- const hasAnyCost = useMemo(
- () => (data ? data.days.some(day => day.cost_usd > 0) : false),
+ const hasAnyUsage = useMemo(
+ () => (data ? data.days.some(day => day.request_count > 0 || day.total_tokens > 0) : false),
[data]
);
@@ -55,15 +42,15 @@ const CostDashboardPanel = ({ embedded = false }: CostDashboardPanelProps) => {
{t('settings.costDashboard.subtitle')}
</p>
<div className="flex items-center gap-2 shrink-0">
- {(lastUpdated !== null || usageLogUpdated !== null) && (
+ {lastUpdated !== null && (
<span
data-testid="cost-dashboard-updated"
className="inline-flex items-center gap-1.5 text-[11px] text-content-muted">
<span
aria-hidden
- className={`inline-block h-1.5 w-1.5 rounded-full ${isFetching || usageLogFetching ? 'bg-primary-500 animate-pulse' : 'bg-sage-500'}`}
+ className={`inline-block h-1.5 w-1.5 rounded-full ${isFetching ? 'bg-primary-500 animate-pulse' : 'bg-sage-500'}`}
/>
- {`${t('settings.costDashboard.updated')} ${relativeTime(Math.max(lastUpdated ?? 0, usageLogUpdated ?? 0), t)}`}
+ {`${t('settings.costDashboard.updated')} ${relativeTime(lastUpdated ?? 0, t)}`}
</span>
)}
<Button
@@ -71,13 +58,11 @@ const CostDashboardPanel = ({ embedded = false }: CostDashboardPanelProps) => {
variant="secondary"
size="xs"
data-testid="cost-dashboard-refresh"
- onClick={() => void Promise.all([refetch(), refetchUsageLog()])}
- disabled={isFetching || usageLogFetching}
+ onClick={() => void refetch()}
+ disabled={isFetching}
aria-label={t('settings.costDashboard.refresh')}
leadingIcon={
- <RefreshIcon
- className={`h-3.5 w-3.5 ${isFetching || usageLogFetching ? 'animate-spin' : ''}`}
- />
+ <RefreshIcon className={`h-3.5 w-3.5 ${isFetching ? 'animate-spin' : ''}`} />
}>
{t('settings.costDashboard.refresh')}
</Button>
@@ -89,11 +74,6 @@ const CostDashboardPanel = ({ embedded = false }: CostDashboardPanelProps) => {
<SettingsStatusLine saving={false} error={error} savingLabel="" />
</div>
)}
- {usageLogError && (
- <div role="alert" data-testid="cost-dashboard-usage-error">
- <SettingsStatusLine saving={false} error={usageLogError} savingLabel="" />
- </div>
- )}
{data && !data.enabled && (
// A resolved config state, not a response to a user action — opt out
// of the assertive default so it doesn't talk over the page it's on.
@@ -110,14 +90,11 @@ const CostDashboardPanel = ({ embedded = false }: CostDashboardPanelProps) => {
{data && (
<>
- <BudgetSummary
+ <CostSummary
currency={data.currency}
periodTotalUsd={data.period_total_usd}
monthlyPaceUsd={data.monthly_pace_usd}
- budgetLimitMonthlyUsd={data.budget_limit_monthly_usd}
monthToDateUsd={data.month_to_date_usd}
- utilization={data.budget_utilization}
- status={data.budget_status}
/>
<Card
data-testid="cost-dashboard-cost-chart"
@@ -130,13 +107,7 @@ const CostDashboardPanel = ({ embedded = false }: CostDashboardPanelProps) => {
{t('settings.costDashboard.utcNote')}
</span>
}>
- <CostBarChart
- days={data.days}
- currency={data.currency}
- budgetLimitMonthlyUsd={data.budget_limit_monthly_usd}
- warnThreshold={data.warn_threshold}
- alertThreshold={data.alert_threshold}
- />
+ <CostBarChart days={data.days} currency={data.currency} />
</Card>
<Card
data-testid="cost-dashboard-token-chart"
@@ -160,57 +131,7 @@ const CostDashboardPanel = ({ embedded = false }: CostDashboardPanelProps) => {
description={t('settings.costDashboard.modelBreakdownHint')}>
<ModelCostTable models={data.by_model} currency={data.currency} />
</Card>
- <Card
- data-testid="cost-dashboard-category-distribution"
- padded
- divided={false}
- className="bg-surface/40"
- title={t('settings.costDashboard.categoryDistribution')}
- description={t('settings.costDashboard.categoryDistributionHint')}>
- {usageLog ? (
- <CategoryDistribution
- categories={usageLog.by_category}
- currency={usageLog.currency}
- />
- ) : usageLogLoading ? (
- <div className="text-xs text-content-muted">
- {t('settings.costDashboard.loading')}
- </div>
- ) : null}
- </Card>
- <Card
- data-testid="cost-dashboard-usage-log"
- padded
- divided={false}
- className="bg-surface/40"
- title={t('settings.costDashboard.usageLog')}
- description={
- usageLog
- ? t('settings.costDashboard.usageLogHint')
- .replace('{days}', String(usageLog.days))
- .replace('{limit}', String(usageLog.limit))
- : t('settings.costDashboard.usageLogHint')
- .replace('{days}', '30')
- .replace('{limit}', '250')
- }
- headerRight={
- usageLog && (
- <span className="shrink-0 text-[11px] text-content-muted">
- {t('settings.costDashboard.logTotal')
- .replace('{requests}', String(usageLog.request_count))
- .replace('{cost}', formatCurrency(usageLog.total_cost_usd, usageLog.currency))}
- </span>
- )
- }>
- {usageLog ? (
- <UsageLogTable records={usageLog.records} currency={usageLog.currency} />
- ) : usageLogLoading ? (
- <div className="text-xs text-content-muted">
- {t('settings.costDashboard.loading')}
- </div>
- ) : null}
- </Card>
- {!hasAnyCost && (
+ {!hasAnyUsage && (
<div
data-testid="cost-dashboard-empty"
className="rounded-xl border border-dashed border-line-strong px-4 py-6 text-center">
@@ -227,7 +148,7 @@ const CostDashboardPanel = ({ embedded = false }: CostDashboardPanelProps) => {
</>
);
- // Embedded inside the tabbed Usage & Limits page: the parent owns the header,
+ // Embedded inside the tabbed Usage page: the parent owns the header,
// so render just the padded body.
if (embedded)
return (
@@ -239,172 +160,6 @@ const CostDashboardPanel = ({ embedded = false }: CostDashboardPanelProps) => {
return <SettingsPanel testId="cost-dashboard-panel">{body}</SettingsPanel>;
};
-const CATEGORY_COLORS = [
- 'bg-primary-500',
- 'bg-sage-500',
- 'bg-amber-500',
- 'bg-coral-500',
- 'bg-content-faint',
-];
-
-const CategoryDistribution = ({
- categories,
- currency,
-}: {
- categories: CostUsageCategoryStats[];
- currency: string;
-}) => {
- const { t } = useT();
- if (categories.length === 0) {
- return (
- <div className="text-xs text-content-muted italic py-2">
- {t('settings.costDashboard.noCategories')}
- </div>
- );
- }
-
- return (
- <div className="space-y-3">
- <div aria-hidden className="flex h-3 w-full overflow-hidden rounded-full bg-surface-strong">
- {categories.map((category, index) => (
- <div
- key={category.category}
- className={CATEGORY_COLORS[index % CATEGORY_COLORS.length]}
- style={{ width: `${Math.max(0, Math.min(100, category.percent_of_total))}%` }}
- />
- ))}
- </div>
- <div className="grid gap-2 sm:grid-cols-2">
- {categories.map((category, index) => (
- <div key={category.category} className="rounded-lg border border-line px-3 py-2">
- <div className="flex items-center justify-between gap-3">
- <div className="flex min-w-0 items-center gap-2">
- <span
- aria-hidden
- className={`h-2 w-2 rounded-full ${CATEGORY_COLORS[index % CATEGORY_COLORS.length]}`}
- />
- <span className="truncate text-xs font-medium text-content">
- {category.category}
- </span>
- </div>
- <span className="shrink-0 text-xs font-semibold tabular-nums text-content">
- {formatCurrency(category.cost_usd, currency)}
- </span>
- </div>
- <div className="mt-1 flex items-center justify-between gap-2 text-[11px] text-content-muted">
- <span>{`${category.percent_of_total.toFixed(1)}%`}</span>
- <span>
- {t('settings.costDashboard.categoryMeta')
- .replace('{requests}', String(category.request_count))
- .replace('{tokens}', formatTokens(category.total_tokens))}
- </span>
- </div>
- </div>
- ))}
- </div>
- </div>
- );
-};
-
-const UsageLogTable = ({ records, currency }: { records: CostUsageRecord[]; currency: string }) => {
- const { t } = useT();
- if (records.length === 0) {
- return (
- <div className="text-xs text-content-muted italic py-2">
- {t('settings.costDashboard.noUsageLog')}
- </div>
- );
- }
-
- return (
- <div className="overflow-x-auto -mx-1">
- <table className="w-full min-w-[760px] text-xs">
- <thead>
- <tr className="border-b border-line text-left text-[10px] uppercase tracking-wide text-content-muted">
- <Th>{t('settings.costDashboard.when')}</Th>
- <Th>{t('settings.costDashboard.category')}</Th>
- <Th>{t('settings.costDashboard.model')}</Th>
- <Th align="right">{t('settings.costDashboard.inputTokens')}</Th>
- <Th align="right">{t('settings.costDashboard.outputTokens')}</Th>
- <Th align="right">{t('settings.costDashboard.cost')}</Th>
- <Th>{t('settings.costDashboard.session')}</Th>
- </tr>
- </thead>
- <tbody>
- {records.map(record => (
- <tr
- key={record.id}
- className="border-b border-line-subtle transition-colors last:border-0 hover:bg-surface-muted/60 dark:border-line/60 dark:hover:bg-surface-muted/40">
- <Td>
- <div className="tabular-nums text-content-secondary">
- {formatDateTime(record.timestamp)}
- </div>
- </Td>
- <Td>
- <span className="inline-flex rounded-full bg-surface-subtle px-2 py-0.5 text-[10px] font-medium text-content-secondary ring-1 ring-inset ring-line-strong">
- {record.category}
- </span>
- </Td>
- <Td>
- <div className="max-w-[16rem] truncate font-medium text-content">
- {record.model}
- </div>
- <div className="text-[10px] text-content-muted">
- {record.provider ?? t('settings.costDashboard.unknownProvider')}
- </div>
- </Td>
- <Td align="right">{formatTokens(record.input_tokens)}</Td>
- <Td align="right">{formatTokens(record.output_tokens)}</Td>
- <Td align="right">
- <span className="font-semibold tabular-nums text-content">
- {formatCurrency(record.cost_usd, currency)}
- </span>
- </Td>
- <Td>
- <span className="font-mono text-[10px] text-content-muted">
- {shortId(record.session_id)}
- </span>
- </Td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- );
-};
-
-interface CellProps {
- children: ReactNode;
- align?: 'left' | 'right';
-}
-
-const Th = ({ children, align = 'left' }: CellProps) => (
- <th className={`px-2 py-2 font-medium ${align === 'right' ? 'text-right' : 'text-left'}`}>
- {children}
- </th>
-);
-
-const Td = ({ children, align = 'left' }: CellProps) => (
- <td className={`px-2 py-2 align-middle ${align === 'right' ? 'text-right' : 'text-left'}`}>
- {children}
- </td>
-);
-
-function formatDateTime(value: string): string {
- const date = new Date(value);
- if (Number.isNaN(date.getTime())) return value;
- return new Intl.DateTimeFormat(undefined, {
- month: 'short',
- day: 'numeric',
- hour: 'numeric',
- minute: '2-digit',
- }).format(date);
-}
-
-function shortId(value: string): string {
- return value.length > 8 ? value.slice(0, 8) : value;
-}
-
interface IconProps {
className?: string;
}
diff --git a/app/src/components/dashboard/CostSummary.test.tsx b/app/src/components/dashboard/CostSummary.test.tsx
new file mode 100644
index 0000000000..f196394f72
--- /dev/null
+++ b/app/src/components/dashboard/CostSummary.test.tsx
@@ -0,0 +1,22 @@
+import { render, screen } from '@testing-library/react';
+import { describe, expect, it } from 'vitest';
+
+import CostSummary from './CostSummary';
+
+describe('<CostSummary />', () => {
+ it('shows recorded costs without implying an enforced budget', () => {
+ render(
+ <CostSummary
+ currency="USD"
+ periodTotalUsd={42.5}
+ monthlyPaceUsd={181.25}
+ monthToDateUsd={50}
+ />
+ );
+ expect(screen.getByTestId('metric-total-spend')).toHaveTextContent('$42.50');
+ expect(screen.getByTestId('metric-total-spend')).toHaveTextContent('$50.00');
+ expect(screen.getByTestId('metric-monthly-pace')).toHaveTextContent('$181');
+ expect(screen.queryByTestId('metric-budget-limit')).not.toBeInTheDocument();
+ expect(screen.queryByTestId('budget-status-badge')).not.toBeInTheDocument();
+ });
+});
diff --git a/app/src/components/dashboard/CostSummary.tsx b/app/src/components/dashboard/CostSummary.tsx
new file mode 100644
index 0000000000..b1a963910b
--- /dev/null
+++ b/app/src/components/dashboard/CostSummary.tsx
@@ -0,0 +1,117 @@
+import type { ReactNode } from 'react';
+
+import { useT } from '../../lib/i18n/I18nContext';
+import { formatCurrency } from './formatCurrency';
+
+interface CostSummaryProps {
+ currency: string;
+ periodTotalUsd: number;
+ monthlyPaceUsd: number;
+ monthToDateUsd: number;
+}
+
+const CostSummary = ({
+ currency,
+ periodTotalUsd,
+ monthlyPaceUsd,
+ monthToDateUsd,
+}: CostSummaryProps) => {
+ const { t } = useT();
+
+ return (
+ <section
+ data-testid="cost-dashboard-summary"
+ className="grid grid-cols-1 md:grid-cols-2 gap-3"
+ aria-label={t('settings.costDashboard.summaryAriaLabel')}>
+ <div
+ data-testid="metric-total-spend"
+ className="rounded-2xl border border-line bg-linear-to-br from-primary-50 to-surface dark:from-neutral-900 dark:to-neutral-950 p-5 flex flex-col gap-3 shadow-soft">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2 text-xs uppercase tracking-wide text-content-muted">
+ <WalletIcon className="h-4 w-4" />
+ <span>{t('settings.costDashboard.totalSpend')}</span>
+ </div>
+ </div>
+ <div className="flex items-baseline gap-3">
+ <span className="text-3xl md:text-4xl font-semibold tabular-nums text-content">
+ {formatCurrency(periodTotalUsd, currency)}
+ </span>
+ <span className="text-xs text-content-muted">
+ {t('settings.costDashboard.lastSevenDays')}
+ </span>
+ </div>
+ <div className="text-xs text-content-muted">
+ {`${t('settings.costDashboard.monthToDate')}: ${formatCurrency(monthToDateUsd, currency)}`}
+ </div>
+ </div>
+
+ <div className="grid grid-cols-1 gap-3">
+ <SmallMetric
+ icon={<TrendingUpIcon className="h-4 w-4" />}
+ label={t('settings.costDashboard.monthlyPace')}
+ value={formatCurrency(monthlyPaceUsd, currency)}
+ hint={t('settings.costDashboard.monthlyPaceHint')}
+ testId="metric-monthly-pace"
+ />
+ </div>
+ </section>
+ );
+};
+
+interface SmallMetricProps {
+ icon: ReactNode;
+ label: string;
+ value: string;
+ hint: string;
+ testId: string;
+}
+
+const SmallMetric = ({ icon, label, value, hint, testId }: SmallMetricProps) => (
+ <div
+ data-testid={testId}
+ title={hint}
+ className="rounded-2xl border border-line p-3 flex flex-col gap-1 hover:border-primary-300 dark:hover:border-primary-700 transition-colors">
+ <div className="flex items-center gap-2 text-[11px] uppercase tracking-wide text-content-muted">
+ {icon}
+ <span>{label}</span>
+ </div>
+ <span className="text-lg font-semibold tabular-nums text-content">{value}</span>
+ </div>
+);
+
+interface IconProps {
+ className?: string;
+}
+
+const WalletIcon = ({ className }: IconProps) => (
+ <svg
+ className={className}
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ aria-hidden>
+ <path d="M21 12V7H5a2 2 0 0 1 0-4h14v4" />
+ <path d="M3 5v14a2 2 0 0 0 2 2h16v-5" />
+ <circle cx="17" cy="14" r="1.5" />
+ </svg>
+);
+
+const TrendingUpIcon = ({ className }: IconProps) => (
+ <svg
+ className={className}
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ aria-hidden>
+ <polyline points="23 6 13.5 15.5 8.5 10.5 1 18" />
+ <polyline points="17 6 23 6 23 12" />
+ </svg>
+);
+
+export default CostSummary;
diff --git a/app/src/components/dashboard/UsageLogPanel.test.tsx b/app/src/components/dashboard/UsageLogPanel.test.tsx
new file mode 100644
index 0000000000..c011f977b6
--- /dev/null
+++ b/app/src/components/dashboard/UsageLogPanel.test.tsx
@@ -0,0 +1,114 @@
+import { configureStore } from '@reduxjs/toolkit';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { Provider } from 'react-redux';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { callCoreRpc } from '../../services/coreRpcClient';
+import UsageLogPanel from './UsageLogPanel';
+
+vi.mock('../../services/coreRpcClient', () => ({ callCoreRpc: vi.fn() }));
+const mockedCall = vi.mocked(callCoreRpc);
+
+const records = [
+ {
+ id: 'one',
+ timestamp: '2026-09-24T12:00:00Z',
+ session_id: 'session-one',
+ model: 'alpha',
+ provider: 'openrouter',
+ category: 'Chat',
+ input_tokens: 100,
+ output_tokens: 50,
+ total_tokens: 150,
+ cached_input_tokens: 0,
+ cache_creation_tokens: 0,
+ reasoning_tokens: 0,
+ cost_usd: 1,
+ cost_source: 'estimated',
+ },
+ {
+ id: 'two',
+ timestamp: '2026-09-24T11:00:00Z',
+ session_id: 'session-two',
+ model: 'beta',
+ provider: 'anthropic',
+ category: 'Voice',
+ input_tokens: 200,
+ output_tokens: 20,
+ total_tokens: 220,
+ cached_input_tokens: 0,
+ cache_creation_tokens: 0,
+ reasoning_tokens: 0,
+ cost_usd: 2,
+ cost_source: 'provider_charged',
+ },
+];
+
+function renderPanel() {
+ const store = configureStore({ reducer: { locale: (state = { current: 'en' }) => state } });
+ return render(
+ <Provider store={store}>
+ <UsageLogPanel />
+ </Provider>
+ );
+}
+
+describe('<UsageLogPanel />', () => {
+ beforeEach(() => {
+ mockedCall.mockReset();
+ mockedCall.mockResolvedValue({
+ records,
+ by_category: [],
+ total_cost_usd: 3,
+ total_tokens: 370,
+ request_count: 2,
+ currency: 'USD',
+ days: 30,
+ limit: 1000,
+ } as never);
+ });
+
+ it('filters loaded rows and labels the bounded result', async () => {
+ renderPanel();
+ await screen.findByText('alpha');
+ expect(screen.getByText('2 of 2 loaded records • $3.00')).toBeInTheDocument();
+
+ fireEvent.change(screen.getByLabelText('Category'), { target: { value: 'Voice' } });
+ expect(screen.queryByText('alpha')).not.toBeInTheDocument();
+ expect(screen.getByText('beta')).toBeInTheDocument();
+ expect(screen.getByText('1 of 2 loaded records • $2.00')).toBeInTheDocument();
+
+ fireEvent.change(screen.getByLabelText('Model or session'), { target: { value: 'missing' } });
+ expect(screen.getByText('No usage records found for this period.')).toBeInTheDocument();
+ });
+
+ it('requests the chosen period from the core', async () => {
+ renderPanel();
+ await screen.findByText('alpha');
+ fireEvent.change(screen.getByLabelText('Period'), { target: { value: '7' } });
+ await waitFor(() =>
+ expect(mockedCall).toHaveBeenCalledWith(
+ expect.objectContaining({
+ method: 'openhuman.cost_get_usage_log',
+ params: { days: 7, limit: 1000 },
+ })
+ )
+ );
+ });
+
+ it('filters by provider and whether cost was reported by the provider', async () => {
+ renderPanel();
+ await screen.findByText('alpha');
+
+ fireEvent.change(screen.getByLabelText('Provider'), { target: { value: 'anthropic' } });
+ expect(screen.queryByText('alpha')).not.toBeInTheDocument();
+ expect(screen.getByText('beta')).toBeInTheDocument();
+
+ fireEvent.change(screen.getByLabelText('Cost source'), { target: { value: 'estimated' } });
+ expect(screen.getByText('No usage records found for this period.')).toBeInTheDocument();
+ fireEvent.change(screen.getByLabelText('Cost source'), {
+ target: { value: 'provider_charged' },
+ });
+ expect(screen.getByText('beta')).toBeInTheDocument();
+ });
+});
diff --git a/app/src/components/dashboard/UsageLogPanel.tsx b/app/src/components/dashboard/UsageLogPanel.tsx
new file mode 100644
index 0000000000..337a86d2ae
--- /dev/null
+++ b/app/src/components/dashboard/UsageLogPanel.tsx
@@ -0,0 +1,222 @@
+import { useMemo, useState } from 'react';
+
+import { type CostUsageRecord, useCostUsageLog } from '../../hooks/useCostDashboard';
+import { useT } from '../../lib/i18n/I18nContext';
+import { SettingsStatusLine } from '../settings/controls';
+import { Button, Card } from '../ui';
+import { formatCurrency, formatTokens } from './formatCurrency';
+
+const ALL = '';
+
+/** Detailed local usage records. Filters apply to the fetched, bounded window. */
+const UsageLogPanel = () => {
+ const { t } = useT();
+ const [days, setDays] = useState(30);
+ const [category, setCategory] = useState(ALL);
+ const [provider, setProvider] = useState(ALL);
+ const [query, setQuery] = useState('');
+ const [source, setSource] = useState(ALL);
+ const { data, isLoading, isFetching, error, refetch } = useCostUsageLog({ days, limit: 1000 });
+
+ const categories = useMemo(
+ () => [...new Set(data?.records.map(record => record.category) ?? [])].sort(),
+ [data]
+ );
+ const providers = useMemo(
+ () => [...new Set(data?.records.map(record => record.provider ?? '') ?? [])].sort(),
+ [data]
+ );
+ const records = useMemo(() => {
+ const needle = query.trim().toLocaleLowerCase();
+ return (data?.records ?? []).filter(
+ record =>
+ (category === ALL || record.category === category) &&
+ (provider === ALL || (record.provider ?? '') === provider) &&
+ (source === ALL || record.cost_source === source) &&
+ (!needle ||
+ record.model.toLocaleLowerCase().includes(needle) ||
+ record.session_id.toLocaleLowerCase().includes(needle))
+ );
+ }, [data, category, provider, source, query]);
+ const filteredCost = records.reduce((sum, record) => sum + record.cost_usd, 0);
+
+ return (
+ <div className="p-4 space-y-4" data-testid="usage-log-panel">
+ <div className="flex items-start justify-between gap-3">
+ <p className="text-xs text-content-muted max-w-prose">
+ {t('settings.costDashboard.usageLogHint')
+ .replace('{days}', String(days))
+ .replace('{limit}', '1000')}
+ </p>
+ <Button
+ type="button"
+ variant="secondary"
+ size="xs"
+ onClick={() => void refetch()}
+ disabled={isFetching}>
+ {t('settings.costDashboard.refresh')}
+ </Button>
+ </div>
+ {error && <SettingsStatusLine saving={false} error={error} savingLabel="" />}
+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-5">
+ <Filter label={t('settings.costDashboard.period')}>
+ <select
+ value={days}
+ onChange={event => setDays(Number(event.target.value))}
+ className="w-full rounded-lg border border-line bg-surface px-2 py-1.5 text-xs">
+ {[1, 7, 30, 90, 365].map(value => (
+ <option key={value} value={value}>
+ {t('settings.costDashboard.periodDays').replace('{days}', String(value))}
+ </option>
+ ))}
+ </select>
+ </Filter>
+ <Filter label={t('settings.costDashboard.category')}>
+ <select
+ value={category}
+ onChange={event => setCategory(event.target.value)}
+ className="w-full rounded-lg border border-line bg-surface px-2 py-1.5 text-xs">
+ <option value="">{t('settings.costDashboard.all')}</option>
+ {categories.map(value => (
+ <option key={value} value={value}>
+ {value}
+ </option>
+ ))}
+ </select>
+ </Filter>
+ <Filter label={t('settings.costDashboard.provider')}>
+ <select
+ value={provider}
+ onChange={event => setProvider(event.target.value)}
+ className="w-full rounded-lg border border-line bg-surface px-2 py-1.5 text-xs">
+ <option value="">{t('settings.costDashboard.all')}</option>
+ {providers.filter(Boolean).map(value => (
+ <option key={value} value={value}>
+ {value}
+ </option>
+ ))}
+ </select>
+ </Filter>
+ <Filter label={t('settings.costDashboard.costSource')}>
+ <select
+ value={source}
+ onChange={event => setSource(event.target.value)}
+ className="w-full rounded-lg border border-line bg-surface px-2 py-1.5 text-xs">
+ <option value="">{t('settings.costDashboard.all')}</option>
+ <option value="estimated">{t('settings.costDashboard.estimated')}</option>
+ <option value="provider_charged">{t('settings.costDashboard.providerCharged')}</option>
+ </select>
+ </Filter>
+ <Filter label={t('settings.costDashboard.searchModelSession')}>
+ <input
+ value={query}
+ onChange={event => setQuery(event.target.value)}
+ className="w-full rounded-lg border border-line bg-surface px-2 py-1.5 text-xs"
+ />
+ </Filter>
+ </div>
+ <Card
+ padded
+ divided={false}
+ className="bg-surface/40"
+ title={t('settings.costDashboard.usageLog')}
+ headerRight={
+ data && (
+ <span className="text-[11px] text-content-muted">
+ {t('settings.costDashboard.filteredTotal')
+ .replace('{shown}', String(records.length))
+ .replace('{loaded}', String(data.records.length))
+ .replace('{cost}', formatCurrency(filteredCost, data.currency))}
+ </span>
+ )
+ }>
+ {data ? (
+ <UsageLogTable records={records} currency={data.currency} />
+ ) : isLoading ? (
+ <div className="text-xs text-content-muted">{t('settings.costDashboard.loading')}</div>
+ ) : null}
+ </Card>
+ </div>
+ );
+};
+
+const Filter = ({ label, children }: { label: string; children: React.ReactNode }) => (
+ <label className="space-y-1 text-xs text-content-secondary">
+ <span>{label}</span>
+ {children}
+ </label>
+);
+
+const UsageLogTable = ({ records, currency }: { records: CostUsageRecord[]; currency: string }) => {
+ const { t } = useT();
+ if (records.length === 0)
+ return (
+ <div className="text-xs text-content-muted italic py-2">
+ {t('settings.costDashboard.noUsageLog')}
+ </div>
+ );
+ return (
+ <div className="overflow-x-auto -mx-1">
+ <table className="w-full min-w-[850px] text-xs">
+ <thead>
+ <tr className="border-b border-line text-left text-[10px] uppercase tracking-wide text-content-muted">
+ <th className="px-2 py-2">{t('settings.costDashboard.when')}</th>
+ <th className="px-2 py-2">{t('settings.costDashboard.category')}</th>
+ <th className="px-2 py-2">{t('settings.costDashboard.model')}</th>
+ <th className="px-2 py-2 text-right">{t('settings.costDashboard.inputTokens')}</th>
+ <th className="px-2 py-2 text-right">{t('settings.costDashboard.outputTokens')}</th>
+ <th className="px-2 py-2 text-right">{t('settings.costDashboard.cost')}</th>
+ <th className="px-2 py-2">{t('settings.costDashboard.costSource')}</th>
+ <th className="px-2 py-2">{t('settings.costDashboard.session')}</th>
+ </tr>
+ </thead>
+ <tbody>
+ {records.map(record => (
+ <tr
+ key={record.id}
+ className="border-b border-line-subtle last:border-0 hover:bg-surface-muted/60">
+ <td className="px-2 py-2 whitespace-nowrap">{formatDateTime(record.timestamp)}</td>
+ <td className="px-2 py-2">{record.category}</td>
+ <td className="px-2 py-2">
+ <div
+ className="max-w-[16rem] truncate font-medium text-content"
+ title={record.model}>
+ {record.model}
+ </div>
+ <div className="text-content-muted">
+ {record.provider ?? t('settings.costDashboard.unknownProvider')}
+ </div>
+ </td>
+ <td className="px-2 py-2 text-right">{formatTokens(record.input_tokens)}</td>
+ <td className="px-2 py-2 text-right">{formatTokens(record.output_tokens)}</td>
+ <td className="px-2 py-2 text-right font-semibold">
+ {formatCurrency(record.cost_usd, currency)}
+ </td>
+ <td className="px-2 py-2">
+ {record.cost_source === 'provider_charged'
+ ? t('settings.costDashboard.providerCharged')
+ : t('settings.costDashboard.estimated')}
+ </td>
+ <td className="px-2 py-2 font-mono text-content-muted" title={record.session_id}>
+ {record.session_id.slice(0, 8)}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ );
+};
+
+function formatDateTime(value: string): string {
+ const date = new Date(value);
+ if (Number.isNaN(date.getTime())) return value;
+ return new Intl.DateTimeFormat(undefined, {
+ month: 'short',
+ day: 'numeric',
+ hour: 'numeric',
+ minute: '2-digit',
+ }).format(date);
+}
+
+export default UsageLogPanel;
diff --git a/app/src/components/notices/useAppNotices.ts b/app/src/components/notices/useAppNotices.ts
index 94b0e99333..c2056275d6 100644
--- a/app/src/components/notices/useAppNotices.ts
+++ b/app/src/components/notices/useAppNotices.ts
@@ -63,7 +63,7 @@ export interface AppNotice {
/** Deep-link target for each classified-error action. `dismiss` has no route. */
const ACTION_ROUTE: Record<Exclude<UserErrorAction, 'dismiss'>, string> = {
- open_billing: '/settings/billing',
+ open_billing: '/settings/account',
open_provider_settings: '/settings/llm',
// #5324: both memory-embedding remediations (local Ollama, BYO key) live on
// this one screen, so a single CTA covers them without the user needing to
diff --git a/app/src/components/settings/__tests__/settingsRouteRegistry.test.ts b/app/src/components/settings/__tests__/settingsRouteRegistry.test.ts
index a0cf0e063c..fe1019121d 100644
--- a/app/src/components/settings/__tests__/settingsRouteRegistry.test.ts
+++ b/app/src/components/settings/__tests__/settingsRouteRegistry.test.ts
@@ -194,7 +194,6 @@ describe('SETTINGS_ROUTE_REGISTRY integrity', () => {
it('surfaces the restructured home hub entries', () => {
const homeIds = entriesForSection('home').map(e => e.id);
expect(homeIds).toContain('personality');
- // billing is surfaced in the General group now (no longer a hidden deep-link).
- expect(homeIds).toContain('billing');
+ expect(homeIds).not.toContain('billing');
});
});
diff --git a/app/src/components/settings/panels/AccountPanel.test.tsx b/app/src/components/settings/panels/AccountPanel.test.tsx
index 4fe36aa6ac..3198589efa 100644
--- a/app/src/components/settings/panels/AccountPanel.test.tsx
+++ b/app/src/components/settings/panels/AccountPanel.test.tsx
@@ -1,9 +1,14 @@
-import { screen } from '@testing-library/react';
+import { fireEvent, screen } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { renderWithProviders } from '../../../test/test-utils';
import AccountPanel from './AccountPanel';
+const openUrlMock = vi.fn();
+vi.mock('../../../utils/openUrl', () => ({
+ openUrl: (...args: unknown[]) => openUrlMock(...args),
+}));
+
const useCoreStateMock = vi.fn();
vi.mock('../../../providers/CoreStateProvider', () => ({ useCoreState: () => useCoreStateMock() }));
@@ -36,6 +41,8 @@ describe('AccountPanel', () => {
expect(screen.getByText('@ada')).toBeInTheDocument();
// Avatar fallback renders the first letter of the display name.
expect(screen.getByText('A')).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Billing' }));
+ expect(openUrlMock).toHaveBeenCalledWith('https://tinyhumans.ai/dashboard?tab=billing');
});
it('falls back to the username initial when no name is set', () => {
@@ -49,5 +56,6 @@ describe('AccountPanel', () => {
renderPanel(null);
expect(screen.queryByText('@')).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Billing' })).not.toBeInTheDocument();
});
});
diff --git a/app/src/components/settings/panels/AccountPanel.tsx b/app/src/components/settings/panels/AccountPanel.tsx
index 9ef831a7e1..1956fad676 100644
--- a/app/src/components/settings/panels/AccountPanel.tsx
+++ b/app/src/components/settings/panels/AccountPanel.tsx
@@ -1,6 +1,9 @@
import { useT } from '../../../lib/i18n/I18nContext';
import { useCoreState } from '../../../providers/CoreStateProvider';
+import { BILLING_DASHBOARD_URL } from '../../../utils/links';
+import { openUrl } from '../../../utils/openUrl';
import { AvatarFallback, AvatarRoot } from '../../ui/Avatar';
+import Button from '../../ui/Button';
import { SettingsSection } from '../controls';
import SettingsPanel from '../layout/SettingsPanel';
import LogoutAndClearActions from '../LogoutAndClearActions';
@@ -40,6 +43,17 @@ const AccountPanel = () => {
)}
<SettingsSection>
+ {user && (
+ <div className="px-4 py-3">
+ <Button
+ type="button"
+ variant="secondary"
+ size="md"
+ onClick={() => void openUrl(`${BILLING_DASHBOARD_URL}?tab=billing`)}>
+ {t('nav.avatarMenu.billing')}
+ </Button>
+ </div>
+ )}
<LogoutAndClearActions />
</SettingsSection>
</SettingsPanel>
diff --git a/app/src/components/settings/panels/BillingPanel.test.tsx b/app/src/components/settings/panels/BillingPanel.test.tsx
deleted file mode 100644
index 457948652a..0000000000
--- a/app/src/components/settings/panels/BillingPanel.test.tsx
+++ /dev/null
@@ -1,185 +0,0 @@
-import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import BillingPanel from './BillingPanel';
-
-const navigateBack = vi.fn();
-const openUrlMock = vi.fn();
-const getSummaryMock = vi.fn();
-const getTeamUsageMock = vi.fn();
-
-vi.mock('../hooks/useSettingsNavigation', () => ({
- useSettingsNavigation: () => ({
- navigateBack,
- navigateToSettings: vi.fn(),
- navigateToTeamManagement: vi.fn(),
- breadcrumbs: [],
- }),
-}));
-
-vi.mock('../../../utils/openUrl', () => ({ openUrl: (url: string) => openUrlMock(url) }));
-vi.mock('../../../services/api/billingApi', () => ({
- billingApi: { getSummary: (...args: unknown[]) => getSummaryMock(...args) },
-}));
-vi.mock('../../../services/api/creditsApi', () => ({
- creditsApi: { getTeamUsage: (...args: unknown[]) => getTeamUsageMock(...args) },
-}));
-
-const summary = {
- credits: { promotionBalanceUsd: 4.5, teamTopupUsd: 10, totalUsd: 14.5 },
- plan: {
- plan: 'PRO',
- hasActiveSubscription: true,
- planExpiry: '2026-12-01T00:00:00.000Z',
- subscription: null,
- monthlyBudgetUsd: 100,
- weeklyBudgetUsd: 25,
- },
- links: {
- topUpUrl: 'https://staging.tinyhumans.ai/dashboard?tab=billing',
- manageUrl: 'https://staging.tinyhumans.ai/dashboard?tab=plans',
- apiKeysUrl: 'https://staging.tinyhumans.ai/dashboard?tab=api-keys',
- },
-};
-
-const usage = {
- remainingUsd: 39.5,
- cycleBudgetUsd: 25,
- cycleSpentUsd: 6,
- cycleStartDate: '2026-09-07T00:00:00.000Z',
- cycleEndsAt: '2026-09-14T00:00:00.000Z',
- plan: {
- plan: 'PRO',
- name: 'Pro',
- marginPercent: 10,
- payAsYouGoMarginPercent: 100,
- discountVsPayAsYouGoPercent: 90,
- },
- insights: {
- period: { startDate: '2026-09-07', endDate: '2026-09-14' },
- totals: {
- inferenceUsd: 5,
- integrationsUsd: 1,
- totalUsd: 6,
- inferenceCalls: 20,
- integrationCalls: 2,
- },
- dailySeries: [],
- topModels: [],
- topIntegrations: [],
- },
-};
-
-describe('<BillingPanel />', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- openUrlMock.mockResolvedValue(undefined);
- getSummaryMock.mockResolvedValue(summary);
- getTeamUsageMock.mockResolvedValue(usage);
- });
-
- it('shows plan, balances, cycle spend, and total funds remaining', async () => {
- render(<BillingPanel />);
-
- await waitFor(() => expect(getSummaryMock).toHaveBeenCalledTimes(1));
- expect(getTeamUsageMock).toHaveBeenCalledTimes(1);
- expect(screen.getByText('PRO')).toBeInTheDocument();
- expect(screen.getByText('$39.50')).toBeInTheDocument();
- expect(screen.getByText('$4.50')).toBeInTheDocument();
- expect(screen.getByText('$10.00')).toBeInTheDocument();
- expect(screen.getByText(/Spent \$6\.00 this cycle/i)).toBeInTheDocument();
- });
-
- it('shows each response without waiting for the other request to settle', async () => {
- let resolveUsage: (value: typeof usage) => void = () => undefined;
- getTeamUsageMock.mockReturnValue(
- new Promise<typeof usage>(resolve => {
- resolveUsage = resolve;
- })
- );
- render(<BillingPanel />);
-
- expect(await screen.findByText('$4.50')).toBeInTheDocument();
- expect(screen.getByText('$10.00')).toBeInTheDocument();
- expect(screen.queryByText('$39.50')).not.toBeInTheDocument();
-
- await act(async () => resolveUsage(usage));
- expect(await screen.findByText('$39.50')).toBeInTheDocument();
- });
-
- it('uses backend-provided dashboard URLs for billing actions', async () => {
- render(<BillingPanel />);
- await screen.findByText('$39.50');
-
- fireEvent.click(screen.getByRole('button', { name: 'Top Up Credits' }));
- fireEvent.click(screen.getByRole('button', { name: 'Open billing dashboard' }));
-
- expect(openUrlMock).toHaveBeenNthCalledWith(1, summary.links.topUpUrl);
- expect(openUrlMock).toHaveBeenNthCalledWith(2, summary.links.manageUrl);
- });
-
- it('keeps usable cycle details visible when the aggregate summary fails', async () => {
- getSummaryMock.mockRejectedValue(new Error('Summary unavailable'));
- render(<BillingPanel />);
-
- expect(await screen.findByText('Summary unavailable')).toBeInTheDocument();
- expect(screen.getByText('PRO')).toBeInTheDocument();
- expect(screen.getByText('$39.50')).toBeInTheDocument();
- expect(screen.getByText(/Spent \$6\.00 this cycle/i)).toBeInTheDocument();
- });
-
- it('renders malformed balances as unavailable and falls back from unusable links', async () => {
- getSummaryMock.mockResolvedValue({
- ...summary,
- credits: {
- promotionBalanceUsd: Number.NaN,
- teamTopupUsd: -1,
- totalUsd: Number.POSITIVE_INFINITY,
- },
- links: null,
- });
- render(<BillingPanel />);
-
- await screen.findByText('$39.50');
- expect(screen.getAllByText('n/a')).toHaveLength(2);
-
- fireEvent.click(screen.getByRole('button', { name: 'Top Up Credits' }));
- fireEvent.click(screen.getByRole('button', { name: 'Open billing dashboard' }));
- expect(openUrlMock).toHaveBeenNthCalledWith(1, 'https://tinyhumans.ai/dashboard?tab=billing');
- expect(openUrlMock).toHaveBeenNthCalledWith(2, 'https://tinyhumans.ai/dashboard');
- });
-
- it('falls back when the backend returns empty billing links', async () => {
- getSummaryMock.mockResolvedValue({
- ...summary,
- links: { ...summary.links, topUpUrl: '', manageUrl: '' },
- });
- render(<BillingPanel />);
-
- await screen.findByText('$39.50');
- fireEvent.click(screen.getByRole('button', { name: 'Top Up Credits' }));
- fireEvent.click(screen.getByRole('button', { name: 'Open billing dashboard' }));
- expect(openUrlMock).toHaveBeenNthCalledWith(1, 'https://tinyhumans.ai/dashboard?tab=billing');
- expect(openUrlMock).toHaveBeenNthCalledWith(2, 'https://tinyhumans.ai/dashboard');
- });
-
- it('keeps plan and balances visible when cycle usage fails', async () => {
- getTeamUsageMock.mockRejectedValue(new Error('Usage unavailable'));
- render(<BillingPanel />);
-
- expect(await screen.findByText('Usage unavailable')).toBeInTheDocument();
- expect(screen.getByText('PRO')).toBeInTheDocument();
- expect(screen.queryByText('$14.50')).not.toBeInTheDocument();
- expect(screen.getAllByText('n/a').length).toBeGreaterThanOrEqual(1);
- expect(screen.getByText(/Unable to load usage data/i)).toBeInTheDocument();
- });
-
- it('invokes the navigation back handler from both back buttons', async () => {
- render(<BillingPanel />);
- await screen.findByText('$39.50');
-
- fireEvent.click(screen.getByRole('button', { name: 'Back' }));
- fireEvent.click(screen.getByRole('button', { name: 'Back to settings' }));
- expect(navigateBack).toHaveBeenCalledTimes(2);
- });
-});
diff --git a/app/src/components/settings/panels/BillingPanel.tsx b/app/src/components/settings/panels/BillingPanel.tsx
deleted file mode 100644
index e144725352..0000000000
--- a/app/src/components/settings/panels/BillingPanel.tsx
+++ /dev/null
@@ -1,160 +0,0 @@
-import createDebug from 'debug';
-import { useEffect, useState } from 'react';
-
-import { useT } from '../../../lib/i18n/I18nContext';
-import { billingApi } from '../../../services/api/billingApi';
-import { creditsApi, type TeamUsage } from '../../../services/api/creditsApi';
-import type { BillingSummaryData } from '../../../types/api';
-import { BILLING_DASHBOARD_URL } from '../../../utils/links';
-import { openUrl } from '../../../utils/openUrl';
-import Button from '../../ui/Button';
-import { SettingsStatusLine } from '../controls';
-import { useSettingsNavigation } from '../hooks/useSettingsNavigation';
-import SettingsPanel from '../layout/SettingsPanel';
-import InferenceBudget from './billing/InferenceBudget';
-
-const log = createDebug('openhuman:billing:panel');
-const formatUsd = (amount: unknown, unavailable: string): string =>
- typeof amount === 'number' && Number.isFinite(amount) && amount >= 0
- ? `$${amount.toFixed(2)}`
- : unavailable;
-
-const BillingPanel = () => {
- const { t } = useT();
- const { navigateBack } = useSettingsNavigation();
- const [summary, setSummary] = useState<BillingSummaryData | null>(null);
- const [teamUsage, setTeamUsage] = useState<TeamUsage | null>(null);
- const [summaryLoading, setSummaryLoading] = useState(true);
- const [usageLoading, setUsageLoading] = useState(true);
- const [error, setError] = useState<string | null>(null);
-
- useEffect(() => {
- let cancelled = false;
-
- const recordError = (failure: unknown) => {
- const message = failure instanceof Error ? failure.message : String(failure);
- setError(current => current ?? message);
- };
-
- log('loading billing summary and cycle usage');
- void billingApi
- .getSummary()
- .then(value => {
- if (!cancelled) setSummary(value);
- })
- .catch(failure => {
- log('summary load failed error=%s', String(failure));
- if (!cancelled) recordError(failure);
- })
- .finally(() => {
- if (!cancelled) setSummaryLoading(false);
- });
- void creditsApi
- .getTeamUsage()
- .then(value => {
- if (!cancelled) setTeamUsage(value);
- })
- .catch(failure => {
- log('usage load failed error=%s', String(failure));
- if (!cancelled) recordError(failure);
- })
- .finally(() => {
- if (!cancelled) setUsageLoading(false);
- });
-
- return () => {
- cancelled = true;
- };
- }, []);
-
- // Only /teams/me/usage includes the remaining subscription-cycle allowance.
- // The summary's totalUsd is wallet-only (promotion + top-up), so it is not a
- // safe fallback for the account's true available balance.
- const availableUsd = teamUsage?.remainingUsd;
- const unavailable = t('settings.billing.inferenceBudget.notAvailable');
- const topUpUrl = summary?.links?.topUpUrl || `${BILLING_DASHBOARD_URL}?tab=billing`;
- const manageUrl = summary?.links?.manageUrl || BILLING_DASHBOARD_URL;
-
- return (
- <SettingsPanel>
- <SettingsStatusLine
- saving={summaryLoading || usageLoading}
- error={error}
- savingLabel={t('common.loading')}
- />
-
- <section className="rounded-2xl border border-line bg-surface p-4 space-y-4">
- <div className="space-y-1">
- <h2 className="text-base font-semibold text-content">
- {t('settings.billing.movedToWeb')}
- </h2>
- <p className="text-sm text-content-muted">{t('settings.billing.movedToWebDesc')}</p>
- </div>
-
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
- <SummaryTile
- label={t('settings.billing.subscription.currentPlan')}
- value={
- summary?.plan?.plan ??
- teamUsage?.plan?.plan ??
- (summaryLoading || usageLoading ? '...' : unavailable)
- }
- />
- <SummaryTile
- label={t('settings.billing.payAsYouGo.available')}
- value={
- availableUsd === undefined
- ? usageLoading
- ? '...'
- : unavailable
- : formatUsd(availableUsd, unavailable)
- }
- />
- <SummaryTile
- label={t('settings.billing.payAsYouGo.promotionalCredits')}
- value={
- summary
- ? formatUsd(summary.credits?.promotionBalanceUsd, unavailable)
- : summaryLoading
- ? '...'
- : unavailable
- }
- />
- <SummaryTile
- label={t('settings.billing.payAsYouGo.topUpBalance')}
- value={
- summary
- ? formatUsd(summary.credits?.teamTopupUsd, unavailable)
- : summaryLoading
- ? '...'
- : unavailable
- }
- />
- </div>
- </section>
-
- <InferenceBudget teamUsage={teamUsage} isLoadingCredits={usageLoading} />
-
- <div className="flex flex-wrap gap-3">
- <Button type="button" variant="primary" size="md" onClick={() => void openUrl(topUpUrl)}>
- {t('settings.billing.payAsYouGo.topUpCredits')}
- </Button>
- <Button type="button" variant="secondary" size="md" onClick={() => void openUrl(manageUrl)}>
- {t('settings.billing.openDashboard')}
- </Button>
- <Button type="button" variant="tertiary" size="md" onClick={navigateBack}>
- {t('settings.billing.backToSettings')}
- </Button>
- </div>
- </SettingsPanel>
- );
-};
-
-const SummaryTile = ({ label, value }: { label: string; value: string }) => (
- <div className="rounded-xl border border-line bg-surface-muted px-3 py-3">
- <div className="text-[11px] text-content-muted">{label}</div>
- <div className="mt-1 text-lg font-semibold text-content">{value}</div>
- </div>
-);
-
-export default BillingPanel;
diff --git a/app/src/components/settings/panels/UsagePanel.tsx b/app/src/components/settings/panels/UsagePanel.tsx
index 01d0310349..2723b27e71 100644
--- a/app/src/components/settings/panels/UsagePanel.tsx
+++ b/app/src/components/settings/panels/UsagePanel.tsx
@@ -4,24 +4,31 @@ import { useLocation, useNavigate } from 'react-router-dom';
import { useT } from '../../../lib/i18n/I18nContext';
import { type AISettings, loadAISettings } from '../../../services/api/aiSettingsApi';
import CostDashboardPanel from '../../dashboard/CostDashboardPanel';
+import UsageLogPanel from '../../dashboard/UsageLogPanel';
import { SettingsStatusLine } from '../controls';
import SettingsPanel from '../layout/SettingsPanel';
import { BackgroundLoopControls } from './AIPanel';
import TokenUsagePanel from './TokenUsagePanel';
-type TabId = 'costs' | 'tokens' | 'background';
+type TabId = 'costs' | 'log' | 'tokens' | 'background';
-const TAB_HASH: Record<TabId, string> = { costs: '', tokens: '#tokens', background: '#background' };
+const TAB_HASH: Record<TabId, string> = {
+ costs: '',
+ log: '#log',
+ tokens: '#tokens',
+ background: '#background',
+};
const hashToTab = (hash: string): TabId => {
if (hash === '#background') return 'background';
if (hash === '#tokens') return 'tokens';
+ if (hash === '#log') return 'log';
return 'costs';
};
/**
- * Single Settings entry for usage & limits. Combines the cost dashboard
- * (charts, budgets, usage log), the Tokenjuice token-savings surface, and the
+ * Single Settings entry for usage. Combines the cost dashboard, usage log,
+ * Tokenjuice token-savings surface, and the
* background-activity controls (heartbeat cadences + usage ledger, previously
* the separate Heartbeat and Usage-ledger pages) as tabs under one header. The
* active tab is reflected in the URL hash (`#tokens` / `#background`) so deep
@@ -52,6 +59,7 @@ const UsagePanel = () => {
label: t('settings.costDashboard.title'),
content: <CostDashboardPanel embedded />,
},
+ { id: 'log', label: t('settings.costDashboard.usageLog'), content: <UsageLogPanel /> },
{
id: 'tokens',
label: t('settings.tokenUsage.title'),
diff --git a/app/src/components/settings/panels/__tests__/InferenceBudget.test.tsx b/app/src/components/settings/panels/__tests__/InferenceBudget.test.tsx
deleted file mode 100644
index 481574a8f2..0000000000
--- a/app/src/components/settings/panels/__tests__/InferenceBudget.test.tsx
+++ /dev/null
@@ -1,252 +0,0 @@
-import { render, screen } from '@testing-library/react';
-import { describe, expect, it } from 'vitest';
-
-import type { TeamUsage, TeamUsageInsights } from '../../../../services/api/creditsApi';
-import InferenceBudget from '../billing/InferenceBudget';
-
-function buildInsights(overrides: Partial<TeamUsageInsights> = {}): TeamUsageInsights {
- return {
- period: { startDate: '2026-05-01', endDate: '2026-05-31' },
- totals: {
- inferenceUsd: 3,
- integrationsUsd: 2,
- totalUsd: 5,
- inferenceCalls: 100,
- integrationCalls: 10,
- },
- dailySeries: [
- { date: '2026-05-01', inferenceUsd: 1, integrationsUsd: 0.5, totalUsd: 1.5 },
- { date: '2026-05-02', inferenceUsd: 2, integrationsUsd: 1.5, totalUsd: 3.5 },
- ],
- topModels: [{ model: 'claude-sonnet', provider: 'anthropic', spentUsd: 3, calls: 100 }],
- topIntegrations: [{ provider: 'gmail', action: 'send', spentUsd: 2, calls: 10 }],
- ...overrides,
- };
-}
-
-function buildTeamUsage(overrides: Partial<TeamUsage> = {}): TeamUsage {
- return {
- remainingUsd: 5,
- cycleBudgetUsd: 10,
- cycleSpentUsd: 5,
- cycleStartDate: '2026-05-01T00:00:00.000Z',
- cycleEndsAt: '2026-05-31T00:00:00.000Z',
- plan: {
- plan: 'PRO',
- name: 'Pro',
- marginPercent: 90,
- payAsYouGoMarginPercent: 0,
- discountVsPayAsYouGoPercent: 50,
- },
- insights: buildInsights(),
- ...overrides,
- };
-}
-
-describe('InferenceBudget', () => {
- describe('loading state', () => {
- it('shows Loading… text when isLoadingCredits=true and teamUsage=null', () => {
- render(<InferenceBudget teamUsage={null} isLoadingCredits={true} />);
- expect(screen.getByText('Loading…')).toBeInTheDocument();
- });
-
- it('shows pulse skeleton bar when isLoadingCredits=true and teamUsage=null', () => {
- const { container } = render(<InferenceBudget teamUsage={null} isLoadingCredits={true} />);
- expect(container.querySelector('.animate-pulse')).toBeInTheDocument();
- });
- });
-
- describe('null teamUsage (not loading)', () => {
- it('shows unable-to-load message', () => {
- render(<InferenceBudget teamUsage={null} isLoadingCredits={false} />);
- expect(screen.getByText(/Unable to load usage data/i)).toBeInTheDocument();
- });
- });
-
- describe('with cycleBudgetUsd > 0', () => {
- it('renders remaining / budget text in the header', () => {
- const usage = buildTeamUsage({ remainingUsd: 20, cycleBudgetUsd: 10, cycleSpentUsd: 5 });
- render(<InferenceBudget teamUsage={usage} isLoadingCredits={false} />);
- expect(screen.getByText(/\$5\.00 \/ \$10\.00 remaining/i)).toBeInTheDocument();
- });
-
- it('does not count promotional and top-up balances as recurring cycle budget', () => {
- const usage = buildTeamUsage({ remainingUsd: 30, cycleBudgetUsd: 10, cycleSpentUsd: 8.5 });
- const { container } = render(<InferenceBudget teamUsage={usage} isLoadingCredits={false} />);
-
- expect(screen.getByText(/\$1\.50 \/ \$10\.00 remaining/i)).toBeInTheDocument();
- expect(container.querySelector<HTMLElement>('.bg-amber-500')).toHaveStyle({ width: '15%' });
- });
-
- it('renders cycle-spent and cycle-ends date', () => {
- const usage = buildTeamUsage({ cycleSpentUsd: 5, cycleEndsAt: '2026-05-31T00:00:00.000Z' });
- render(<InferenceBudget teamUsage={usage} isLoadingCredits={false} />);
- expect(screen.getByText(/Spent \$5\.00 this cycle/i)).toBeInTheDocument();
- expect(screen.getByText(/Cycle ends/i)).toBeInTheDocument();
- });
-
- it('renders formatCycleEnds as n/a for an invalid date string', () => {
- const usage = buildTeamUsage({ cycleEndsAt: 'not-a-valid-date' });
- render(<InferenceBudget teamUsage={usage} isLoadingCredits={false} />);
- expect(screen.getByText(/Cycle ends n\/a/i)).toBeInTheDocument();
- });
-
- it('shows coral exhausted warning when remainingUsd <= 0', () => {
- const usage = buildTeamUsage({ remainingUsd: 0, cycleSpentUsd: 10 });
- render(<InferenceBudget teamUsage={usage} isLoadingCredits={false} />);
- expect(screen.getByText(/Included subscription usage is exhausted/i)).toBeInTheDocument();
- });
-
- it('does not tell users to top up when non-cycle credits remain', () => {
- const usage = buildTeamUsage({ remainingUsd: 5, cycleSpentUsd: 10 });
- render(<InferenceBudget teamUsage={usage} isLoadingCredits={false} />);
- expect(screen.queryByText(/Top up credits to keep using AI/i)).not.toBeInTheDocument();
- });
- });
-
- describe('with cycleBudgetUsd === 0', () => {
- it('renders "No recurring plan budget" in the header', () => {
- const usage = buildTeamUsage({ cycleBudgetUsd: 0, remainingUsd: 0 });
- render(<InferenceBudget teamUsage={usage} isLoadingCredits={false} />);
- expect(screen.getByText(/No recurring plan budget/i)).toBeInTheDocument();
- });
-
- it('renders the pay-as-you-go notice card', () => {
- const usage = buildTeamUsage({ cycleBudgetUsd: 0 });
- render(<InferenceBudget teamUsage={usage} isLoadingCredits={false} />);
- expect(
- screen.getByText(/does not include a recurring weekly inference budget/i)
- ).toBeInTheDocument();
- });
- });
-
- describe('plan discount banner', () => {
- it('shows discount text when discountVsPayAsYouGoPercent > 0', () => {
- const usage = buildTeamUsage();
- render(<InferenceBudget teamUsage={usage} isLoadingCredits={false} />);
- expect(screen.getByText(/50% cheaper per call/i)).toBeInTheDocument();
- expect(screen.getByText(/Pro:/i)).toBeInTheDocument();
- });
-
- it('does not render discount banner when discountVsPayAsYouGoPercent === 0', () => {
- const usage = buildTeamUsage({
- plan: {
- plan: 'FREE',
- name: 'Free',
- marginPercent: 0,
- payAsYouGoMarginPercent: 0,
- discountVsPayAsYouGoPercent: 0,
- },
- });
- render(<InferenceBudget teamUsage={usage} isLoadingCredits={false} />);
- expect(screen.queryByText(/cheaper per call/i)).not.toBeInTheDocument();
- });
- });
-
- describe('UsageBreakdown', () => {
- it('renders inference and integrations totals', () => {
- const usage = buildTeamUsage();
- render(<InferenceBudget teamUsage={usage} isLoadingCredits={false} />);
- expect(screen.getByText(/Cycle spend/i)).toBeInTheDocument();
- // "Inference" and "Integrations" each appear once in UsageBreakdown and once in the DailyChart legend
- expect(screen.getAllByText('Inference').length).toBeGreaterThanOrEqual(1);
- expect(screen.getAllByText('Integrations').length).toBeGreaterThanOrEqual(1);
- expect(screen.getByText(/\$5\.00 total/i)).toBeInTheDocument();
- });
-
- it('renders call counts formatted with toLocaleString', () => {
- const usage = buildTeamUsage({
- insights: buildInsights({
- totals: {
- inferenceUsd: 3,
- integrationsUsd: 2,
- totalUsd: 5,
- inferenceCalls: 1000,
- integrationCalls: 200,
- },
- }),
- });
- render(<InferenceBudget teamUsage={usage} isLoadingCredits={false} />);
- expect(screen.getByText(/1,000 calls/i)).toBeInTheDocument();
- });
- });
-
- describe('DailyChart', () => {
- it('renders daily spend section when points are present', () => {
- render(<InferenceBudget teamUsage={buildTeamUsage()} isLoadingCredits={false} />);
- expect(screen.getByText(/Daily spend/i)).toBeInTheDocument();
- });
-
- it('renders legend items for inference and integrations (2 instances each with chart)', () => {
- render(<InferenceBudget teamUsage={buildTeamUsage()} isLoadingCredits={false} />);
- // DailyChart renders legend labels + UsageBreakdown renders column headers = 2 each
- expect(screen.getAllByText('Inference').length).toBeGreaterThanOrEqual(2);
- expect(screen.getAllByText('Integrations').length).toBeGreaterThanOrEqual(2);
- });
-
- it('does not render chart section when dailySeries is empty', () => {
- const usage = buildTeamUsage({ insights: buildInsights({ dailySeries: [] }) });
- const { container } = render(<InferenceBudget teamUsage={usage} isLoadingCredits={false} />);
- // The bar container is only rendered when there are points
- expect(container.querySelector('.h-16')).not.toBeInTheDocument();
- });
- });
-
- describe('TopModels', () => {
- it('renders top models heading', () => {
- render(<InferenceBudget teamUsage={buildTeamUsage()} isLoadingCredits={false} />);
- expect(screen.getByText('Top models')).toBeInTheDocument();
- });
-
- it('renders model name and spend', () => {
- render(<InferenceBudget teamUsage={buildTeamUsage()} isLoadingCredits={false} />);
- expect(screen.getByText('claude-sonnet')).toBeInTheDocument();
- expect(screen.getByText(/\$3\.00 · 100/i)).toBeInTheDocument();
- });
-
- it('falls back to provider name when model is empty string', () => {
- const usage = buildTeamUsage({
- insights: buildInsights({
- topModels: [{ model: '', provider: 'anthropic', spentUsd: 1, calls: 5 }],
- }),
- });
- render(<InferenceBudget teamUsage={usage} isLoadingCredits={false} />);
- expect(screen.getByText('anthropic')).toBeInTheDocument();
- });
-
- it('shows empty-state message when topModels is empty', () => {
- const usage = buildTeamUsage({ insights: buildInsights({ topModels: [] }) });
- render(<InferenceBudget teamUsage={usage} isLoadingCredits={false} />);
- expect(screen.getByText(/No inference usage this cycle/i)).toBeInTheDocument();
- });
- });
-
- describe('TopIntegrations', () => {
- it('renders top integrations heading', () => {
- render(<InferenceBudget teamUsage={buildTeamUsage()} isLoadingCredits={false} />);
- expect(screen.getByText('Top integrations')).toBeInTheDocument();
- });
-
- it('renders provider and action together', () => {
- render(<InferenceBudget teamUsage={buildTeamUsage()} isLoadingCredits={false} />);
- expect(screen.getByText(/gmail · send/i)).toBeInTheDocument();
- });
-
- it('renders provider alone when action is empty', () => {
- const usage = buildTeamUsage({
- insights: buildInsights({
- topIntegrations: [{ provider: 'slack', action: '', spentUsd: 1, calls: 3 }],
- }),
- });
- render(<InferenceBudget teamUsage={usage} isLoadingCredits={false} />);
- expect(screen.getByText('slack')).toBeInTheDocument();
- expect(screen.queryByText(/slack ·/i)).not.toBeInTheDocument();
- });
-
- it('shows empty-state message when topIntegrations is empty', () => {
- const usage = buildTeamUsage({ insights: buildInsights({ topIntegrations: [] }) });
- render(<InferenceBudget teamUsage={usage} isLoadingCredits={false} />);
- expect(screen.getByText(/No integration usage this cycle/i)).toBeInTheDocument();
- });
- });
-});
diff --git a/app/src/components/settings/panels/__tests__/UsagePanel.test.tsx b/app/src/components/settings/panels/__tests__/UsagePanel.test.tsx
index 462a2c7853..24d9d3f9ad 100644
--- a/app/src/components/settings/panels/__tests__/UsagePanel.test.tsx
+++ b/app/src/components/settings/panels/__tests__/UsagePanel.test.tsx
@@ -30,6 +30,10 @@ vi.mock('../TokenUsagePanel', () => ({
),
}));
+vi.mock('../../../dashboard/UsageLogPanel', () => ({
+ default: () => <div data-testid="stub-usage-log" />,
+}));
+
vi.mock('../../../../services/api/aiSettingsApi', async () => {
const actual = await vi.importActual<typeof import('../../../../services/api/aiSettingsApi')>(
'../../../../services/api/aiSettingsApi'
@@ -80,6 +84,14 @@ describe('UsagePanel', () => {
expect(screen.queryByTestId('stub-cost-dashboard')).not.toBeInTheDocument();
});
+ test('#log hash selects the usage log without mounting the cost dashboard', () => {
+ renderWithProviders(<UsagePanel />, { initialEntries: ['/settings/usage#log'] });
+
+ expect(screen.getByTestId('usage-tab-log')).toHaveAttribute('aria-selected', 'true');
+ expect(screen.getByTestId('stub-usage-log')).toBeInTheDocument();
+ expect(screen.queryByTestId('stub-cost-dashboard')).not.toBeInTheDocument();
+ });
+
test('#background hash selects the Background tab and renders the loop controls', async () => {
renderWithProviders(<UsagePanel />, { initialEntries: ['/settings/usage#background'] });
diff --git a/app/src/components/settings/panels/billing/InferenceBudget.tsx b/app/src/components/settings/panels/billing/InferenceBudget.tsx
deleted file mode 100644
index c00a5cea37..0000000000
--- a/app/src/components/settings/panels/billing/InferenceBudget.tsx
+++ /dev/null
@@ -1,303 +0,0 @@
-import { useT } from '../../../../lib/i18n/I18nContext';
-import type {
- TeamUsage,
- TeamUsageDailyPoint,
- TeamUsageIntegrationRow,
- TeamUsageModelRow,
-} from '../../../../services/api/creditsApi';
-
-interface InferenceBudgetProps {
- teamUsage: TeamUsage | null;
- isLoadingCredits: boolean;
-}
-
-const fmtUsd = (n: number): string => `$${(n ?? 0).toFixed(2)}`;
-
-const formatCycleEnds = (iso: string, notAvailable: string): string => {
- const date = new Date(iso);
- if (Number.isNaN(date.getTime())) return notAvailable;
- // Use UTC so a UTC-midnight cycle end doesn't shift a day in the user's TZ.
- return date.toLocaleDateString(undefined, {
- month: 'short',
- day: 'numeric',
- year: 'numeric',
- timeZone: 'UTC',
- });
-};
-
-const InferenceBudget = ({ teamUsage, isLoadingCredits }: InferenceBudgetProps) => {
- const { t } = useT();
- const cycleRemainingUsd = teamUsage
- ? Math.max(0, teamUsage.cycleBudgetUsd - teamUsage.cycleSpentUsd)
- : 0;
-
- return (
- <div className="rounded-2xl border border-line bg-surface p-3 space-y-3">
- <div className="flex items-center justify-between">
- <h3 className="text-sm font-semibold text-content">
- {t('settings.billing.inferenceBudget.title')}
- </h3>
- {isLoadingCredits && (
- <span className="text-[10px] text-content-muted">{t('common.loading')}</span>
- )}
- {teamUsage && !isLoadingCredits && (
- <span className="text-xs text-content-faint">
- {teamUsage.cycleBudgetUsd > 0
- ? t('settings.billing.inferenceBudget.remainingSummary')
- .replace('{remaining}', fmtUsd(cycleRemainingUsd))
- .replace('{budget}', fmtUsd(teamUsage.cycleBudgetUsd))
- : t('settings.billing.inferenceBudget.noRecurringPlanBudget')}
- </span>
- )}
- </div>
-
- {teamUsage ? (
- <>
- {teamUsage.cycleBudgetUsd > 0 ? (
- <>
- <div className="h-1.5 bg-surface-strong rounded-full overflow-hidden">
- <div
- className={`h-full rounded-full transition-all duration-300 ${
- cycleRemainingUsd <= 0
- ? 'bg-coral-500'
- : cycleRemainingUsd / teamUsage.cycleBudgetUsd < 0.2
- ? 'bg-amber-500'
- : 'bg-primary-500'
- }`}
- style={{
- width: `${Math.max(
- 0,
- Math.min(100, (cycleRemainingUsd / teamUsage.cycleBudgetUsd) * 100)
- )}%`,
- }}
- />
- </div>
- <div className="flex items-center justify-between">
- <span className="text-[11px] text-content-muted">
- {t('settings.billing.inferenceBudget.spentThisCycle').replace(
- '{amount}',
- fmtUsd(teamUsage.cycleSpentUsd)
- )}
- </span>
- <span className="text-[11px] text-content-muted">
- {t('settings.billing.inferenceBudget.cycleEndsOn').replace(
- '{date}',
- formatCycleEnds(
- teamUsage.cycleEndsAt,
- t('settings.billing.inferenceBudget.notAvailable')
- )
- )}
- </span>
- </div>
- {cycleRemainingUsd <= 0 && teamUsage.remainingUsd <= 0 && (
- <p className="text-[11px] text-coral-400">
- {t('settings.billing.inferenceBudget.exhaustedDesc')}
- </p>
- )}
- </>
- ) : (
- <div className="rounded-xl border border-line bg-surface-muted px-3 py-2.5">
- <p className="text-[11px] text-content-secondary">
- {t('settings.billing.inferenceBudget.noRecurringWeeklyDesc')}
- </p>
- </div>
- )}
-
- {teamUsage.plan.discountVsPayAsYouGoPercent > 0 && (
- <div className="rounded-xl border border-primary-100 bg-primary-50 px-3 py-2 text-[11px] text-primary-700">
- <span className="font-semibold">{teamUsage.plan.name}:</span>{' '}
- {t('settings.billing.inferenceBudget.discountVsPayg').replace(
- '{pct}',
- String(teamUsage.plan.discountVsPayAsYouGoPercent)
- )}
- </div>
- )}
-
- <UsageBreakdown
- totalUsd={teamUsage.insights.totals.totalUsd}
- inferenceUsd={teamUsage.insights.totals.inferenceUsd}
- integrationsUsd={teamUsage.insights.totals.integrationsUsd}
- inferenceCalls={teamUsage.insights.totals.inferenceCalls}
- integrationCalls={teamUsage.insights.totals.integrationCalls}
- />
-
- <DailyChart points={teamUsage.insights.dailySeries} />
-
- <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
- <TopModels rows={teamUsage.insights.topModels} />
- <TopIntegrations rows={teamUsage.insights.topIntegrations} />
- </div>
- </>
- ) : isLoadingCredits ? (
- <div className="h-1.5 w-full rounded-full bg-surface-strong animate-pulse" />
- ) : (
- <p className="text-xs text-content-muted">
- {t('settings.billing.inferenceBudget.unableToLoad')}
- </p>
- )}
- </div>
- );
-};
-
-const UsageBreakdown = ({
- totalUsd,
- inferenceUsd,
- integrationsUsd,
- inferenceCalls,
- integrationCalls,
-}: {
- totalUsd: number;
- inferenceUsd: number;
- integrationsUsd: number;
- inferenceCalls: number;
- integrationCalls: number;
-}) => {
- const { t } = useT();
-
- return (
- <div className="rounded-xl border border-line bg-surface-muted px-3 py-2">
- <div className="flex items-center justify-between mb-1.5">
- <span className="text-[10px] font-semibold uppercase tracking-wide text-content-faint">
- {t('settings.billing.inferenceBudget.cycleSpend')}
- </span>
- <span className="text-[11px] text-content-secondary">
- {t('settings.billing.inferenceBudget.totalAmount').replace('{amount}', fmtUsd(totalUsd))}
- </span>
- </div>
- <div className="grid grid-cols-2 gap-2 text-[11px]">
- <div>
- <div className="text-content-muted">
- {t('settings.billing.inferenceBudget.inference')}
- </div>
- <div className="text-content font-medium">{fmtUsd(inferenceUsd)}</div>
- <div className="text-content-faint">
- {t('settings.billing.inferenceBudget.calls').replace(
- '{count}',
- inferenceCalls.toLocaleString()
- )}
- </div>
- </div>
- <div>
- <div className="text-content-muted">
- {t('settings.billing.inferenceBudget.integrations')}
- </div>
- <div className="text-content font-medium">{fmtUsd(integrationsUsd)}</div>
- <div className="text-content-faint">
- {t('settings.billing.inferenceBudget.calls').replace(
- '{count}',
- integrationCalls.toLocaleString()
- )}
- </div>
- </div>
- </div>
- </div>
- );
-};
-
-const DailyChart = ({ points }: { points: TeamUsageDailyPoint[] }) => {
- const { t } = useT();
-
- if (points.length === 0) {
- return null;
- }
- const max = points.reduce((m, p) => Math.max(m, p.totalUsd), 0) || 1;
- return (
- <div className="rounded-xl border border-line bg-surface px-3 py-2">
- <div className="text-[10px] font-semibold uppercase tracking-wide text-content-faint mb-2">
- {t('settings.billing.inferenceBudget.dailySpend')}
- </div>
- <div className="flex items-end gap-1 h-16">
- {points.map(p => {
- const inferenceHeight = (p.inferenceUsd / max) * 100;
- const integrationsHeight = (p.integrationsUsd / max) * 100;
- return (
- <div
- key={p.date}
- className="flex-1 h-full flex flex-col-reverse"
- title={t('settings.billing.inferenceBudget.dailySpendPoint')
- .replace('{date}', p.date)
- .replace('{amount}', fmtUsd(p.totalUsd))}>
- <div className="bg-primary-400" style={{ height: `${inferenceHeight}%` }} />
- <div className="bg-amber-400" style={{ height: `${integrationsHeight}%` }} />
- </div>
- );
- })}
- </div>
- <div className="flex items-center gap-3 mt-1.5 text-[10px] text-content-muted">
- <span className="flex items-center gap-1">
- <span className="w-2 h-2 bg-primary-400 inline-block" />{' '}
- {t('settings.billing.inferenceBudget.inference')}
- </span>
- <span className="flex items-center gap-1">
- <span className="w-2 h-2 bg-amber-400 inline-block" />{' '}
- {t('settings.billing.inferenceBudget.integrations')}
- </span>
- </div>
- </div>
- );
-};
-
-const TopModels = ({ rows }: { rows: TeamUsageModelRow[] }) => {
- const { t } = useT();
-
- return (
- <div className="rounded-xl border border-line bg-surface px-3 py-2">
- <div className="text-[10px] font-semibold uppercase tracking-wide text-content-faint mb-1.5">
- {t('settings.billing.inferenceBudget.topModels')}
- </div>
- {rows.length === 0 ? (
- <p className="text-[11px] text-content-muted">
- {t('settings.billing.inferenceBudget.noInferenceUsage')}
- </p>
- ) : (
- <ul className="space-y-0.5">
- {rows.map((r, i) => (
- <li
- key={`${r.provider}::${r.model}::${i}`}
- className="flex items-center justify-between text-[11px]">
- <span className="text-content-secondary truncate mr-2">{r.model || r.provider}</span>
- <span className="text-content-muted shrink-0">
- {fmtUsd(r.spentUsd)} · {r.calls.toLocaleString()}
- </span>
- </li>
- ))}
- </ul>
- )}
- </div>
- );
-};
-
-const TopIntegrations = ({ rows }: { rows: TeamUsageIntegrationRow[] }) => {
- const { t } = useT();
-
- return (
- <div className="rounded-xl border border-line bg-surface px-3 py-2">
- <div className="text-[10px] font-semibold uppercase tracking-wide text-content-faint mb-1.5">
- {t('settings.billing.inferenceBudget.topIntegrations')}
- </div>
- {rows.length === 0 ? (
- <p className="text-[11px] text-content-muted">
- {t('settings.billing.inferenceBudget.noIntegrationUsage')}
- </p>
- ) : (
- <ul className="space-y-0.5">
- {rows.map((r, i) => (
- <li
- key={`${r.provider}::${r.action}::${i}`}
- className="flex items-center justify-between text-[11px]">
- <span className="text-content-secondary truncate mr-2">
- {r.provider}
- {r.action ? ` · ${r.action}` : ''}
- </span>
- <span className="text-content-muted shrink-0">
- {fmtUsd(r.spentUsd)} · {r.calls.toLocaleString()}
- </span>
- </li>
- ))}
- </ul>
- )}
- </div>
- );
-};
-
-export default InferenceBudget;
diff --git a/app/src/components/settings/settingsRouteElements.tsx b/app/src/components/settings/settingsRouteElements.tsx
index 5202e44550..0514aa02b9 100644
--- a/app/src/components/settings/settingsRouteElements.tsx
+++ b/app/src/components/settings/settingsRouteElements.tsx
@@ -11,7 +11,6 @@ import AgentEditorPage from './panels/AgentEditorPage';
import AgentsPanel from './panels/AgentsPanel';
import AppearancePanel from './panels/AppearancePanel';
import ApprovalHistoryPanel from './panels/ApprovalHistoryPanel';
-import BillingPanel from './panels/BillingPanel';
import CoreConnectionPanel from './panels/CoreConnectionPanel';
import DeveloperOptionsPanel from './panels/DeveloperOptionsPanel';
import DevicesPanel from './panels/DevicesPanel';
@@ -78,7 +77,7 @@ export function settingsRouteElements(): ReactNode {
index via the catch-all. */}
<Route path="team" element={<SettingsRedirect to="/settings/account" />} />
<Route path="team/*" element={<SettingsRedirect to="/settings/account" />} />
- <Route path="billing" element={wrapSettingsPage(<BillingPanel />)} />
+ <Route path="billing" element={<SettingsRedirect to="/settings/account" />} />
<Route path="privacy" element={wrapSettingsPage(<PrivacyPanel />)} />
<Route path="security" element={wrapSettingsPage(<SecurityPanel />)} />
<Route path="migration" element={wrapSettingsPage(<MigrationPanel />)} />
diff --git a/app/src/components/settings/settingsRouteRegistry.ts b/app/src/components/settings/settingsRouteRegistry.ts
index 36a5a84260..2821032d9e 100644
--- a/app/src/components/settings/settingsRouteRegistry.ts
+++ b/app/src/components/settings/settingsRouteRegistry.ts
@@ -143,7 +143,16 @@ export const SETTINGS_ROUTE_REGISTRY: SettingsRegistryEntry[] = [
titleKey: 'pages.settings.accountSection.title',
descriptionKey: 'pages.settings.accountSection.description',
section: 'home',
- searchKeywords: ['profile', 'sign out', 'logout'],
+ searchKeywords: [
+ 'profile',
+ 'sign out',
+ 'logout',
+ 'billing',
+ 'subscription',
+ 'payment',
+ 'plan',
+ 'invoice',
+ ],
navGroup: 'general',
navOrder: 0,
},
@@ -352,8 +361,6 @@ export const SETTINGS_ROUTE_REGISTRY: SettingsRegistryEntry[] = [
'ledger',
'cost',
'spend',
- 'billing',
- 'budget',
'heartbeat',
'loops',
'background',
@@ -563,16 +570,6 @@ export const SETTINGS_ROUTE_REGISTRY: SettingsRegistryEntry[] = [
// =========================================================================
// INTENTIONALLY HIDDEN / DEEP-LINK ONLY (not surfaced in any menu)
// =========================================================================
- {
- // billing: surfaced in the General group (also opened from the avatar menu).
- id: 'billing',
- titleKey: 'nav.avatarMenu.billing',
- section: 'home',
- searchKeywords: ['billing', 'subscription', 'payment', 'plan', 'invoice'],
- navGroup: 'general',
- navOrder: 4,
- highlight: true,
- },
{
// search: web search engine settings (Brave / Google / Tavily provider).
// Surfaced on the Connections page (Intelligence group); route kept for
diff --git a/app/src/config/__tests__/navConfig.test.ts b/app/src/config/__tests__/navConfig.test.ts
index cd507ddddc..e8efdaf8b5 100644
--- a/app/src/config/__tests__/navConfig.test.ts
+++ b/app/src/config/__tests__/navConfig.test.ts
@@ -67,29 +67,25 @@ describe('NAV_TABS', () => {
});
describe('AVATAR_MENU_ITEMS', () => {
- it('has exactly 4 entries', () => {
- expect(AVATAR_MENU_ITEMS).toHaveLength(4);
+ it('has exactly 3 entries', () => {
+ expect(AVATAR_MENU_ITEMS).toHaveLength(3);
});
it('has the correct ids in order', () => {
- expect(AVATAR_MENU_ITEMS.map(i => i.id)).toEqual(['account', 'billing', 'invites', 'wallet']);
+ expect(AVATAR_MENU_ITEMS.map(i => i.id)).toEqual(['account', 'invites', 'wallet']);
});
it('no longer offers rewards (it is a primary nav destination now)', () => {
expect(AVATAR_MENU_ITEMS.find(i => i.id === 'rewards')).toBeUndefined();
});
- it('billing and invites are cloudOnly; account and wallet are not', () => {
+ it('invites is cloudOnly; account and wallet are not', () => {
const cloudOnly = AVATAR_MENU_ITEMS.filter(i => i.cloudOnly).map(i => i.id);
- expect(cloudOnly).toEqual(['billing', 'invites']);
+ expect(cloudOnly).toEqual(['invites']);
});
it('keeps every account-menu destination inside the app', () => {
const openUrlItems = AVATAR_MENU_ITEMS.filter(i => i.kind === 'openUrl').map(i => i.id);
expect(openUrlItems).toEqual([]);
});
-
- it('opens the billing summary before the user chooses a web action', () => {
- expect(AVATAR_MENU_ITEMS.find(i => i.id === 'billing')?.target).toBe('/settings/billing');
- });
});
diff --git a/app/src/config/navConfig.ts b/app/src/config/navConfig.ts
index 8c58ce632d..fce0d8308a 100644
--- a/app/src/config/navConfig.ts
+++ b/app/src/config/navConfig.ts
@@ -87,7 +87,7 @@ interface AvatarMenuItem {
/**
* Avatar dropdown menu items.
- * Order: Account → Billing → Invites → Wallet.
+ * Order: Account → Invites → Wallet.
*
* Rewards is not here: it is a primary `NAV_TABS` destination now, and one
* door per surface is the point of moving it.
@@ -99,13 +99,6 @@ export const AVATAR_MENU_ITEMS: AvatarMenuItem[] = [
target: '/settings/account',
kind: 'navigate',
},
- {
- id: 'billing',
- labelKey: 'nav.avatarMenu.billing',
- target: '/settings/billing',
- kind: 'navigate',
- cloudOnly: true,
- },
{
id: 'invites',
labelKey: 'nav.avatarMenu.invites',
diff --git a/app/src/hooks/useCostDashboard.ts b/app/src/hooks/useCostDashboard.ts
index 3ff4773846..1ba68a40cd 100644
--- a/app/src/hooks/useCostDashboard.ts
+++ b/app/src/hooks/useCostDashboard.ts
@@ -200,23 +200,25 @@ export function useCostUsageLog(options: UseCostUsageLogOptions = {}): UseCostUs
const [isFetching, setIsFetching] = useState<boolean>(true);
const [lastUpdated, setLastUpdated] = useState<number | null>(null);
const cancelledRef = useRef<boolean>(false);
+ const requestRef = useRef(0);
const fetchOnce = useCallback(async () => {
+ const request = ++requestRef.current;
setIsFetching(true);
try {
const response = await callCoreRpc<RpcEnvelope<CostUsageLogPayload> | CostUsageLogPayload>({
method: 'openhuman.cost_get_usage_log',
params: { days, limit },
});
- if (cancelledRef.current) return;
+ if (cancelledRef.current || request !== requestRef.current) return;
setData(unwrapRpcPayload(response));
setError(null);
setLastUpdated(Date.now());
} catch (err) {
- if (cancelledRef.current) return;
+ if (cancelledRef.current || request !== requestRef.current) return;
setError(err instanceof Error ? err.message : String(err));
} finally {
- if (!cancelledRef.current) {
+ if (!cancelledRef.current && request === requestRef.current) {
setIsLoading(false);
setIsFetching(false);
}
@@ -229,10 +231,13 @@ export function useCostUsageLog(options: UseCostUsageLogOptions = {}): UseCostUs
useEffect(() => {
cancelledRef.current = false;
+ setData(null);
+ setIsLoading(true);
void fetchOnce();
if (paused) {
return () => {
cancelledRef.current = true;
+ requestRef.current++;
};
}
const interval = window.setInterval(
@@ -243,6 +248,7 @@ export function useCostUsageLog(options: UseCostUsageLogOptions = {}): UseCostUs
);
return () => {
cancelledRef.current = true;
+ requestRef.current++;
window.clearInterval(interval);
};
}, [fetchOnce, refreshMs, paused]);
diff --git a/app/src/lib/i18n/ar.ts b/app/src/lib/i18n/ar.ts
index 80e6c09675..66e90bad37 100644
--- a/app/src/lib/i18n/ar.ts
+++ b/app/src/lib/i18n/ar.ts
@@ -1399,8 +1399,17 @@ const messages: TranslationMap = {
'settings.about.connectionHelperCloud':
'متصلة بقاعدة نائية غيّر هذا في (بوتشيك) أو مُخلّق السحابة.',
'settings.heartbeat.title': 'نبضات القلب والحلقات',
- 'settings.usage.title': 'الاستخدام والحدود',
- 'settings.usage.menuDesc': 'التكاليف واستخدام الرموز والميزانيات والنشاط في الخلفية',
+ 'settings.usage.title': 'الاستخدام',
+ 'settings.usage.menuDesc': 'التكاليف وتوفير الرموز وسجل الاستخدام والنشاط في الخلفية',
+ 'settings.costDashboard.monthToDate': 'من بداية الشهر',
+ 'settings.costDashboard.period': 'الفترة',
+ 'settings.costDashboard.periodDays': 'آخر {days} يومًا',
+ 'settings.costDashboard.all': 'الكل',
+ 'settings.costDashboard.costSource': 'مصدر التكلفة',
+ 'settings.costDashboard.estimated': 'تقديري',
+ 'settings.costDashboard.providerCharged': 'محصّل من المزوّد',
+ 'settings.costDashboard.searchModelSession': 'النموذج أو الجلسة',
+ 'settings.costDashboard.filteredTotal': '{shown} من {loaded} سجل محمّل • {cost}',
'settings.costDashboard.title': 'لوحة بيانات التكاليف',
'settings.costDashboard.sevenDayCost': 'التكلفة اليومية',
'settings.costDashboard.sevenDayTokens': '7 أيام',
@@ -1427,7 +1436,7 @@ const messages: TranslationMap = {
'settings.costDashboard.disabledHint':
'خزانة التكاليف معطلة في الدير مجموعة [xx0xx] مُمَكَّنَة = حقيقي في Xqx1x إلى re-enable.',
'settings.costDashboard.subtitle':
- 'نقضي حياتنا ونحترق عبر الحزام ولا حاجة إلى إعادة تحميل الصفحات.',
+ 'استخدام محلي لكل استدعاء للمزوّد. قد تكون التكاليف تقديرية؛ وتتم الفوترة المستضافة بشكل منفصل.',
'settings.costDashboard.summaryAriaLabel': 'القياسات الموجزة للتكاليف',
'settings.costDashboard.lastSevenDays': '7 أيام',
'settings.costDashboard.utilizationOf': 'من',
diff --git a/app/src/lib/i18n/bn.ts b/app/src/lib/i18n/bn.ts
index 84278ccce5..d4d0a647ba 100644
--- a/app/src/lib/i18n/bn.ts
+++ b/app/src/lib/i18n/bn.ts
@@ -1432,8 +1432,17 @@ const messages: TranslationMap = {
'settings.about.connectionHelperCloud':
'রিমোটের সাথে সংযুক্ত। এটি বুট করা অথবা মেঘের মোড দ্বারা পরিবর্তন করা হবে।',
'settings.heartbeat.title': 'হার্টবিট এবং লুপস',
- 'settings.usage.title': 'ব্যবহার ও সীমা',
- 'settings.usage.menuDesc': 'খরচ, টোকেন ব্যবহার, বাজেট এবং পটভূমির কার্যকলাপ',
+ 'settings.usage.title': 'ব্যবহার',
+ 'settings.usage.menuDesc': 'খরচ, টোকেন সাশ্রয়, ব্যবহারের রেকর্ড ও পটভূমির কার্যকলাপ',
+ 'settings.costDashboard.monthToDate': 'এই মাসে এখন পর্যন্ত',
+ 'settings.costDashboard.period': 'সময়কাল',
+ 'settings.costDashboard.periodDays': 'শেষ {days} দিন',
+ 'settings.costDashboard.all': 'সব',
+ 'settings.costDashboard.costSource': 'খরচের উৎস',
+ 'settings.costDashboard.estimated': 'আনুমানিক',
+ 'settings.costDashboard.providerCharged': 'প্রদানকারীর চার্জ',
+ 'settings.costDashboard.searchModelSession': 'মডেল বা সেশন',
+ 'settings.costDashboard.filteredTotal': 'লোড হওয়া {loaded}টির মধ্যে {shown}টি • {cost}',
'settings.costDashboard.title': 'বিভাজনের স্থান',
'settings.costDashboard.sevenDayCost': '৭ দিনের মূল্য',
'settings.costDashboard.sevenDayTokens': '৭ দিনের ব্যবহার',
@@ -1460,7 +1469,7 @@ const messages: TranslationMap = {
'settings.costDashboard.disabledHint':
'কনফিগ- এর ড্যাশবোর্ড নিষ্ক্রিয় করা হয়েছে। এক্স- অক্ষের সাথে ( xxxqx) সক্রিয় করুন = xx1xqxXqx সক্রিয় করুন।',
'settings.costDashboard.subtitle':
- 'লাইভ সময় কাটান আর গোছগাছে পুড়ে যায়। কয়েক সেকেন্ডের মধ্যে বার নতুন করে নতুন করে তৈরি করা হয়: কোনো পৃষ্ঠা পুনরায় লোড করার প্রয়োজন নেই ।',
+ 'স্থানীয় প্রদানকারী কলের ব্যবহার। খরচ আনুমানিক হতে পারে; হোস্ট করা বিলিং আলাদা।',
'settings.costDashboard.summaryAriaLabel': 'অবস্থানের সংক্ষিপ্ত তথ্য',
'settings.costDashboard.lastSevenDays': 'গত ৭ দিন',
'settings.costDashboard.utilizationOf': 'এর',
diff --git a/app/src/lib/i18n/de.ts b/app/src/lib/i18n/de.ts
index 6bf811013b..94b620fe3f 100644
--- a/app/src/lib/i18n/de.ts
+++ b/app/src/lib/i18n/de.ts
@@ -1482,8 +1482,18 @@ const messages: TranslationMap = {
'settings.about.connectionHelperCloud':
'Verbunden mit einem Remote-Core. Ändern Sie dies in BootCheck oder in der Cloud-Modus-Auswahl.',
'settings.heartbeat.title': 'Heartbeat und Schleifen',
- 'settings.usage.title': 'Nutzung & Limits',
- 'settings.usage.menuDesc': 'Kosten, Token-Verbrauch, Budgets und Hintergrundaktivität',
+ 'settings.usage.title': 'Nutzung',
+ 'settings.usage.menuDesc':
+ 'Kosten, Token-Einsparungen, Nutzungsprotokoll und Hintergrundaktivität',
+ 'settings.costDashboard.monthToDate': 'Seit Monatsbeginn',
+ 'settings.costDashboard.period': 'Zeitraum',
+ 'settings.costDashboard.periodDays': 'Letzte {days} Tage',
+ 'settings.costDashboard.all': 'Alle',
+ 'settings.costDashboard.costSource': 'Kostenquelle',
+ 'settings.costDashboard.estimated': 'Geschätzt',
+ 'settings.costDashboard.providerCharged': 'Vom Anbieter berechnet',
+ 'settings.costDashboard.searchModelSession': 'Modell oder Sitzung',
+ 'settings.costDashboard.filteredTotal': '{shown} von {loaded} geladenen Einträgen • {cost}',
'settings.costDashboard.title': 'Kosten-Dashboard',
'settings.costDashboard.sevenDayCost': '7-Tage-Tageskosten',
'settings.costDashboard.sevenDayTokens': '7-Tage-Token-Nutzung',
@@ -1510,7 +1520,7 @@ const messages: TranslationMap = {
'settings.costDashboard.disabledHint':
'Das Kosten-Dashboard ist in der Konfiguration deaktiviert. [cost.dashboard] enabled = true in config.toml auf re-enable setzen.',
'settings.costDashboard.subtitle':
- 'Lebendige Ausgaben und Token brennen über den Schwarm. Leisten werden alle paar Sekunden automatisch aktualisiert: kein Neuladen der Seite erforderlich.',
+ 'Lokale Nutzung pro Anbieteraufruf. Kosten können geschätzt sein; die Abrechnung erfolgt separat.',
'settings.costDashboard.summaryAriaLabel': 'Kostenübersicht Metriken',
'settings.costDashboard.lastSevenDays': 'letzten 7 Tage',
'settings.costDashboard.utilizationOf': 'der',
diff --git a/app/src/lib/i18n/en.ts b/app/src/lib/i18n/en.ts
index 134ee30abd..12c3a89dd8 100644
--- a/app/src/lib/i18n/en.ts
+++ b/app/src/lib/i18n/en.ts
@@ -1608,8 +1608,17 @@ const en: TranslationMap = {
'settings.gateway.binaryRequired': 'Enter the path to openhuman-core on that machine.',
'settings.gateway.portInvalid': 'The SSH port must be a number.',
'settings.heartbeat.title': 'Heartbeat & loops',
- 'settings.usage.title': 'Usage & Limits',
- 'settings.usage.menuDesc': 'Costs, token usage, budgets, and background activity',
+ 'settings.usage.title': 'Usage',
+ 'settings.usage.menuDesc': 'Costs, token savings, usage records, and background activity',
+ 'settings.costDashboard.monthToDate': 'Month to date',
+ 'settings.costDashboard.period': 'Period',
+ 'settings.costDashboard.periodDays': 'Last {days} days',
+ 'settings.costDashboard.all': 'All',
+ 'settings.costDashboard.costSource': 'Cost source',
+ 'settings.costDashboard.estimated': 'Estimated',
+ 'settings.costDashboard.providerCharged': 'Provider charged',
+ 'settings.costDashboard.searchModelSession': 'Model or session',
+ 'settings.costDashboard.filteredTotal': '{shown} of {loaded} loaded records • {cost}',
'settings.costDashboard.title': 'Cost dashboard',
'settings.costDashboard.sevenDayCost': '7-day daily cost',
'settings.costDashboard.sevenDayTokens': '7-day token usage',
@@ -1636,7 +1645,7 @@ const en: TranslationMap = {
'settings.costDashboard.disabledHint':
'Cost dashboard is disabled in config. Set [cost.dashboard] enabled = true in config.toml to re-enable.',
'settings.costDashboard.subtitle':
- 'Live spend and token burn across the swarm. Bars auto-refresh every few seconds: no page reload needed.',
+ 'Local provider-call usage. Costs may be estimated; hosted billing is separate.',
'settings.costDashboard.summaryAriaLabel': 'Cost summary metrics',
'settings.costDashboard.lastSevenDays': 'last 7 days',
'settings.costDashboard.utilizationOf': 'of',
diff --git a/app/src/lib/i18n/es.ts b/app/src/lib/i18n/es.ts
index 2f3d476e4f..b2d713eb01 100644
--- a/app/src/lib/i18n/es.ts
+++ b/app/src/lib/i18n/es.ts
@@ -1471,8 +1471,18 @@ const messages: TranslationMap = {
'settings.about.connectionHelperCloud':
'Conectado a un núcleo remoto. Cambia esto en BootCheck o en el selector de modo en la nube.',
'settings.heartbeat.title': 'Latidos y bucles',
- 'settings.usage.title': 'Uso y límites',
- 'settings.usage.menuDesc': 'Costos, uso de tokens, presupuestos y actividad en segundo plano',
+ 'settings.usage.title': 'Uso',
+ 'settings.usage.menuDesc':
+ 'Costos, ahorro de tokens, registros de uso y actividad en segundo plano',
+ 'settings.costDashboard.monthToDate': 'Mes hasta la fecha',
+ 'settings.costDashboard.period': 'Período',
+ 'settings.costDashboard.periodDays': 'Últimos {days} días',
+ 'settings.costDashboard.all': 'Todos',
+ 'settings.costDashboard.costSource': 'Origen del costo',
+ 'settings.costDashboard.estimated': 'Estimado',
+ 'settings.costDashboard.providerCharged': 'Cobrado por el proveedor',
+ 'settings.costDashboard.searchModelSession': 'Modelo o sesión',
+ 'settings.costDashboard.filteredTotal': '{shown} de {loaded} registros cargados • {cost}',
'settings.costDashboard.title': 'Panel de costos',
'settings.costDashboard.sevenDayCost': 'Costo diario de 7 días',
'settings.costDashboard.sevenDayTokens': 'Uso de token de 7 días',
@@ -1499,7 +1509,7 @@ const messages: TranslationMap = {
'settings.costDashboard.disabledHint':
'El panel de costos está deshabilitado en la configuración. Configure [cost.dashboard] enabled = true en config.toml para volver a habilitarlo.',
'settings.costDashboard.subtitle':
- 'Gasto en vivo y quema de tokens en todo el enjambre. Las barras se actualizan automáticamente cada pocos segundos: no se necesita recargar la página.',
+ 'Uso local por llamada al proveedor. Los costos pueden ser estimados; la facturación es independiente.',
'settings.costDashboard.summaryAriaLabel': 'Métricas de resumen de costos',
'settings.costDashboard.lastSevenDays': 'últimos 7 días',
'settings.costDashboard.utilizationOf': 'de',
diff --git a/app/src/lib/i18n/fr.ts b/app/src/lib/i18n/fr.ts
index e27662e053..b62ce839e6 100644
--- a/app/src/lib/i18n/fr.ts
+++ b/app/src/lib/i18n/fr.ts
@@ -1483,8 +1483,18 @@ const messages: TranslationMap = {
'settings.about.connectionHelperCloud':
'Connecté à un noyau distant. Modifiez cela dans BootCheck ou le sélecteur de mode cloud.',
'settings.heartbeat.title': 'Battement de coeur et boucles',
- 'settings.usage.title': 'Utilisation et limites',
- 'settings.usage.menuDesc': 'Coûts, utilisation des tokens, budgets et activité en arrière-plan',
+ 'settings.usage.title': 'Utilisation',
+ 'settings.usage.menuDesc':
+ 'Coûts, économies de jetons, journal d’utilisation et activité en arrière-plan',
+ 'settings.costDashboard.monthToDate': 'Depuis le début du mois',
+ 'settings.costDashboard.period': 'Période',
+ 'settings.costDashboard.periodDays': '{days} derniers jours',
+ 'settings.costDashboard.all': 'Tous',
+ 'settings.costDashboard.costSource': 'Source du coût',
+ 'settings.costDashboard.estimated': 'Estimé',
+ 'settings.costDashboard.providerCharged': 'Facturé par le fournisseur',
+ 'settings.costDashboard.searchModelSession': 'Modèle ou session',
+ 'settings.costDashboard.filteredTotal': '{shown} entrées sur {loaded} chargées • {cost}',
'settings.costDashboard.title': 'Tableau de bord des coûts',
'settings.costDashboard.sevenDayCost': 'Coût quotidien sur 7 jours',
'settings.costDashboard.sevenDayTokens': 'Utilisation du jeton sur 7 jours',
@@ -1511,7 +1521,7 @@ const messages: TranslationMap = {
'settings.costDashboard.disabledHint':
'Le tableau de bord des coûts est désactivé dans la configuration. Définissez [cost.dashboard] enabled = true dans config.toml pour le réactiver.',
'settings.costDashboard.subtitle':
- "Dépenses en direct et combustion de jetons à travers l'essaim. Les barres se rafraîchissent automatiquement toutes les quelques secondes: aucun rechargement de page nécessaire.",
+ 'Utilisation locale par appel au fournisseur. Les coûts peuvent être estimés ; la facturation est distincte.',
'settings.costDashboard.summaryAriaLabel': 'Résumé des métriques de coût',
'settings.costDashboard.lastSevenDays': 'les 7 derniers jours',
'settings.costDashboard.utilizationOf': 'de',
diff --git a/app/src/lib/i18n/hi.ts b/app/src/lib/i18n/hi.ts
index f57ff73633..57e8b016e3 100644
--- a/app/src/lib/i18n/hi.ts
+++ b/app/src/lib/i18n/hi.ts
@@ -1430,8 +1430,17 @@ const messages: TranslationMap = {
'settings.about.connectionHelperCloud':
'एक दूरस्थ कोर से जुड़ा हुआ है। इसे बूट चेक या क्लाउड मोड पिकर में बदलें।',
'settings.heartbeat.title': 'दिल की धड़कन और लूप',
- 'settings.usage.title': 'उपयोग और सीमाएँ',
- 'settings.usage.menuDesc': 'लागत, टोकन उपयोग, बजट और पृष्ठभूमि गतिविधि',
+ 'settings.usage.title': 'उपयोग',
+ 'settings.usage.menuDesc': 'लागत, टोकन बचत, उपयोग रिकॉर्ड और पृष्ठभूमि गतिविधि',
+ 'settings.costDashboard.monthToDate': 'इस महीने अब तक',
+ 'settings.costDashboard.period': 'अवधि',
+ 'settings.costDashboard.periodDays': 'पिछले {days} दिन',
+ 'settings.costDashboard.all': 'सभी',
+ 'settings.costDashboard.costSource': 'लागत स्रोत',
+ 'settings.costDashboard.estimated': 'अनुमानित',
+ 'settings.costDashboard.providerCharged': 'प्रदाता द्वारा शुल्क',
+ 'settings.costDashboard.searchModelSession': 'मॉडल या सत्र',
+ 'settings.costDashboard.filteredTotal': '{loaded} में से {shown} रिकॉर्ड • {cost}',
'settings.costDashboard.title': 'कॉस्ट डैशबोर्ड',
'settings.costDashboard.sevenDayCost': '7 दिन दैनिक लागत',
'settings.costDashboard.sevenDayTokens': '7 दिन टोकन उपयोग',
@@ -1458,7 +1467,7 @@ const messages: TranslationMap = {
'settings.costDashboard.disabledHint':
'लागत डैशबोर्ड विन्यास में अक्षम है। सेट [cost.dashboard] सक्षम = config.toml में फिर से सक्षम करने के लिए सही।',
'settings.costDashboard.subtitle':
- 'लाइव खर्च और टोकन पूरे झुंड में जलाते हैं। बार्स ऑटो रिफ्रेश हर कुछ सेकंड - कोई पेज पुनः लोड की जरूरत है।',
+ 'स्थानीय प्रदाता कॉल का उपयोग। लागत अनुमानित हो सकती है; होस्ट की गई बिलिंग अलग है।',
'settings.costDashboard.summaryAriaLabel': 'लागत सारांश मीट्रिक',
'settings.costDashboard.lastSevenDays': 'पिछले 7 दिनों',
'settings.costDashboard.utilizationOf': 'of',
diff --git a/app/src/lib/i18n/id.ts b/app/src/lib/i18n/id.ts
index 9cdcd382ad..1fa3586195 100644
--- a/app/src/lib/i18n/id.ts
+++ b/app/src/lib/i18n/id.ts
@@ -1446,8 +1446,18 @@ const messages: TranslationMap = {
'settings.about.connectionHelperCloud':
'Terhubung ke inti remote. Ubah ini dalam BootCheck atau mode awan picker.',
'settings.heartbeat.title': 'Detak jantung & loop',
- 'settings.usage.title': 'Penggunaan & batas',
- 'settings.usage.menuDesc': 'Biaya, penggunaan token, anggaran, dan aktivitas latar belakang',
+ 'settings.usage.title': 'Penggunaan',
+ 'settings.usage.menuDesc':
+ 'Biaya, penghematan token, catatan penggunaan, dan aktivitas latar belakang',
+ 'settings.costDashboard.monthToDate': 'Bulan ini',
+ 'settings.costDashboard.period': 'Periode',
+ 'settings.costDashboard.periodDays': '{days} hari terakhir',
+ 'settings.costDashboard.all': 'Semua',
+ 'settings.costDashboard.costSource': 'Sumber biaya',
+ 'settings.costDashboard.estimated': 'Perkiraan',
+ 'settings.costDashboard.providerCharged': 'Ditagih penyedia',
+ 'settings.costDashboard.searchModelSession': 'Model atau sesi',
+ 'settings.costDashboard.filteredTotal': '{shown} dari {loaded} catatan dimuat • {cost}',
'settings.costDashboard.title': 'Papan dashboard Biaya',
'settings.costDashboard.sevenDayCost': '7 hari biaya harian',
'settings.costDashboard.sevenDayTokens': 'Penggunaan token 7 hari',
@@ -1474,7 +1484,7 @@ const messages: TranslationMap = {
'settings.costDashboard.disabledHint':
'Papan dashboard biaya dinonaktifkan dalam konfigurasi. Set [cost.dashboard] diaktifkan = true dalam config.toml untuk mengaktifkan kembali.',
'settings.costDashboard.subtitle':
- 'Hidup menghabiskan dan token membakar seluruh kawanan. Bars auto- refresh setiap beberapa detik - tidak ada halaman reload yang dibutuhkan.',
+ 'Penggunaan panggilan penyedia lokal. Biaya dapat berupa perkiraan; penagihan terpisah.',
'settings.costDashboard.summaryAriaLabel': 'Metric ringkasan biaya',
'settings.costDashboard.lastSevenDays': '7 hari terakhir',
'settings.costDashboard.utilizationOf': 'of',
diff --git a/app/src/lib/i18n/it.ts b/app/src/lib/i18n/it.ts
index b7631e5694..69d1fcb0e8 100644
--- a/app/src/lib/i18n/it.ts
+++ b/app/src/lib/i18n/it.ts
@@ -1467,8 +1467,18 @@ const messages: TranslationMap = {
'settings.about.connectionHelperCloud':
'Connesso a un core remoto. Cambia questo in BootCheck o nel selettore della modalità cloud.',
'settings.heartbeat.title': 'Heartbeat e loop',
- 'settings.usage.title': 'Utilizzo e limiti',
- 'settings.usage.menuDesc': 'Costi, utilizzo dei token, budget e attività in background',
+ 'settings.usage.title': 'Utilizzo',
+ 'settings.usage.menuDesc':
+ 'Costi, risparmio di token, registro utilizzo e attività in background',
+ 'settings.costDashboard.monthToDate': 'Da inizio mese',
+ 'settings.costDashboard.period': 'Periodo',
+ 'settings.costDashboard.periodDays': 'Ultimi {days} giorni',
+ 'settings.costDashboard.all': 'Tutti',
+ 'settings.costDashboard.costSource': 'Origine del costo',
+ 'settings.costDashboard.estimated': 'Stimato',
+ 'settings.costDashboard.providerCharged': 'Addebitato dal fornitore',
+ 'settings.costDashboard.searchModelSession': 'Modello o sessione',
+ 'settings.costDashboard.filteredTotal': '{shown} di {loaded} record caricati • {cost}',
'settings.costDashboard.title': 'Cruscotto dei costi',
'settings.costDashboard.sevenDayCost': 'Costo giornaliero di 7 giorni',
'settings.costDashboard.sevenDayTokens': 'Utilizzo del token di 7 giorni',
@@ -1495,7 +1505,7 @@ const messages: TranslationMap = {
'settings.costDashboard.disabledHint':
'La dashboard dei costi è disabilitata nella configurazione. Imposta [cost.dashboard] enabled = true in config.toml per riattivarla.',
'settings.costDashboard.subtitle':
- 'Spese live e distruzione di token attraverso lo sciame. Le barre si aggiornano automaticamente ogni pochi secondi: nessun bisogno di ricaricare la pagina.',
+ 'Utilizzo locale per chiamata al fornitore. I costi possono essere stimati; la fatturazione è separata.',
'settings.costDashboard.summaryAriaLabel': 'Metriche riepilogative dei costi',
'settings.costDashboard.lastSevenDays': 'ultimi 7 giorni',
'settings.costDashboard.utilizationOf': 'di',
diff --git a/app/src/lib/i18n/ko.ts b/app/src/lib/i18n/ko.ts
index a1e3326416..0a1e64e9ff 100644
--- a/app/src/lib/i18n/ko.ts
+++ b/app/src/lib/i18n/ko.ts
@@ -1420,8 +1420,17 @@ const messages: TranslationMap = {
'settings.about.connectionHelperCloud':
'원격 코어에 연결되었습니다. BootCheck 또는 클라우드 모드 선택기에서 변경하세요.',
'settings.heartbeat.title': '하트비트 및 루프',
- 'settings.usage.title': '사용량 및 한도',
- 'settings.usage.menuDesc': '비용, 토큰 사용량, 예산 및 백그라운드 활동',
+ 'settings.usage.title': '사용량',
+ 'settings.usage.menuDesc': '비용, 토큰 절약, 사용 기록 및 백그라운드 활동',
+ 'settings.costDashboard.monthToDate': '이번 달 누계',
+ 'settings.costDashboard.period': '기간',
+ 'settings.costDashboard.periodDays': '최근 {days}일',
+ 'settings.costDashboard.all': '전체',
+ 'settings.costDashboard.costSource': '비용 출처',
+ 'settings.costDashboard.estimated': '추정',
+ 'settings.costDashboard.providerCharged': '제공업체 청구',
+ 'settings.costDashboard.searchModelSession': '모델 또는 세션',
+ 'settings.costDashboard.filteredTotal': '불러온 {loaded}개 중 {shown}개 • {cost}',
'settings.costDashboard.title': '비용 대시보드',
'settings.costDashboard.sevenDayCost': '7일 일별 비용',
'settings.costDashboard.sevenDayTokens': '7일 토큰 사용량',
@@ -1448,7 +1457,7 @@ const messages: TranslationMap = {
'settings.costDashboard.disabledHint':
'비용 대시보드가 config에서 비활성화되어 있습니다. 다시 활성화하려면 config.toml에서 [cost.dashboard] enabled = true로 설정하세요.',
'settings.costDashboard.subtitle':
- '전체 스웜의 실시간 지출과 토큰 사용량입니다. 막대는 몇 초마다 자동으로 새로고침되며 페이지를 다시 로드할 필요가 없습니다.',
+ '로컬 제공업체 호출 사용량입니다. 비용은 추정치일 수 있으며 청구는 별도로 처리됩니다.',
'settings.costDashboard.summaryAriaLabel': '비용 요약 지표',
'settings.costDashboard.lastSevenDays': '지난 7일',
'settings.costDashboard.utilizationOf': '/',
diff --git a/app/src/lib/i18n/pl.ts b/app/src/lib/i18n/pl.ts
index 12f2700075..2b00711d3f 100644
--- a/app/src/lib/i18n/pl.ts
+++ b/app/src/lib/i18n/pl.ts
@@ -1460,8 +1460,17 @@ const messages: TranslationMap = {
'settings.about.connectionHelperCloud':
'Połączono ze zdalnym rdzeniem. Zmień to w BootCheck lub w wyborze trybu chmury.',
'settings.heartbeat.title': 'Heartbeat i pętle',
- 'settings.usage.title': 'Zużycie i limity',
- 'settings.usage.menuDesc': 'Koszty, zużycie tokenów, budżety i aktywność w tle',
+ 'settings.usage.title': 'Użycie',
+ 'settings.usage.menuDesc': 'Koszty, oszczędność tokenów, dziennik użycia i aktywność w tle',
+ 'settings.costDashboard.monthToDate': 'Od początku miesiąca',
+ 'settings.costDashboard.period': 'Okres',
+ 'settings.costDashboard.periodDays': 'Ostatnie {days} dni',
+ 'settings.costDashboard.all': 'Wszystkie',
+ 'settings.costDashboard.costSource': 'Źródło kosztu',
+ 'settings.costDashboard.estimated': 'Szacowany',
+ 'settings.costDashboard.providerCharged': 'Naliczony przez dostawcę',
+ 'settings.costDashboard.searchModelSession': 'Model lub sesja',
+ 'settings.costDashboard.filteredTotal': '{shown} z {loaded} wczytanych wpisów • {cost}',
'settings.costDashboard.title': 'Panel kosztów',
'settings.costDashboard.sevenDayCost': 'Dzienny koszt z 7 dni',
'settings.costDashboard.sevenDayTokens': 'Zużycie tokenów z 7 dni',
@@ -1488,7 +1497,7 @@ const messages: TranslationMap = {
'settings.costDashboard.disabledHint':
'Panel kosztów jest wyłączony w konfiguracji. Ustaw [cost.dashboard] enabled = true w config.toml, aby włączyć go ponownie.',
'settings.costDashboard.subtitle':
- 'Bieżące wydatki i zużycie tokenów w całym roju. Słupki odświeżają się automatycznie co kilka sekund: bez przeładowywania strony.',
+ 'Lokalne użycie według wywołań dostawcy. Koszty mogą być szacowane; rozliczenia są osobne.',
'settings.costDashboard.summaryAriaLabel': 'Metryki podsumowania kosztów',
'settings.costDashboard.lastSevenDays': 'ostatnie 7 dni',
'settings.costDashboard.utilizationOf': 'z',
diff --git a/app/src/lib/i18n/pt.ts b/app/src/lib/i18n/pt.ts
index a21720e31f..017614cb6c 100644
--- a/app/src/lib/i18n/pt.ts
+++ b/app/src/lib/i18n/pt.ts
@@ -1469,8 +1469,18 @@ const messages: TranslationMap = {
'settings.about.connectionHelperCloud':
'Conectado a um núcleo remoto. Altere isso no BootCheck ou no seletor de modo de nuvem.',
'settings.heartbeat.title': 'Heartbeat e loops',
- 'settings.usage.title': 'Uso e limites',
- 'settings.usage.menuDesc': 'Custos, uso de tokens, orçamentos e atividade em segundo plano',
+ 'settings.usage.title': 'Uso',
+ 'settings.usage.menuDesc':
+ 'Custos, economia de tokens, registros de uso e atividade em segundo plano',
+ 'settings.costDashboard.monthToDate': 'Acumulado no mês',
+ 'settings.costDashboard.period': 'Período',
+ 'settings.costDashboard.periodDays': 'Últimos {days} dias',
+ 'settings.costDashboard.all': 'Todos',
+ 'settings.costDashboard.costSource': 'Origem do custo',
+ 'settings.costDashboard.estimated': 'Estimado',
+ 'settings.costDashboard.providerCharged': 'Cobrado pelo provedor',
+ 'settings.costDashboard.searchModelSession': 'Modelo ou sessão',
+ 'settings.costDashboard.filteredTotal': '{shown} de {loaded} registros carregados • {cost}',
'settings.costDashboard.title': 'Painel de custos',
'settings.costDashboard.sevenDayCost': 'Custo diário de 7 dias',
'settings.costDashboard.sevenDayTokens': 'Uso de token de 7 dias',
@@ -1497,7 +1507,7 @@ const messages: TranslationMap = {
'settings.costDashboard.disabledHint':
'O painel de custos está desativado na configuração. Defina [cost.dashboard] enabled = true no config.toml para reativar.',
'settings.costDashboard.subtitle':
- 'Gastos ao vivo e queima de tokens em todo o enxame. As barras atualizam automaticamente a cada poucos segundos: sem necessidade de recarregar a página.',
+ 'Uso local por chamada ao provedor. Os custos podem ser estimados; a cobrança é separada.',
'settings.costDashboard.summaryAriaLabel': 'Métricas de resumo de custos',
'settings.costDashboard.lastSevenDays': 'últimos 7 dias',
'settings.costDashboard.utilizationOf': 'de',
diff --git a/app/src/lib/i18n/ru.ts b/app/src/lib/i18n/ru.ts
index 5953fa4715..4bc8586e27 100644
--- a/app/src/lib/i18n/ru.ts
+++ b/app/src/lib/i18n/ru.ts
@@ -1449,8 +1449,17 @@ const messages: TranslationMap = {
'settings.about.connectionHelperCloud':
'Подключен к удаленному ядру. Измените это в BootCheck или в средстве выбора облачного режима.',
'settings.heartbeat.title': 'Heartbeat и циклы',
- 'settings.usage.title': 'Использование и лимиты',
- 'settings.usage.menuDesc': 'Расходы, использование токенов, бюджеты и фоновая активность',
+ 'settings.usage.title': 'Использование',
+ 'settings.usage.menuDesc': 'Расходы, экономия токенов, журнал использования и фоновая активность',
+ 'settings.costDashboard.monthToDate': 'С начала месяца',
+ 'settings.costDashboard.period': 'Период',
+ 'settings.costDashboard.periodDays': 'Последние {days} дней',
+ 'settings.costDashboard.all': 'Все',
+ 'settings.costDashboard.costSource': 'Источник стоимости',
+ 'settings.costDashboard.estimated': 'Оценка',
+ 'settings.costDashboard.providerCharged': 'Списано поставщиком',
+ 'settings.costDashboard.searchModelSession': 'Модель или сеанс',
+ 'settings.costDashboard.filteredTotal': '{shown} из {loaded} загруженных записей • {cost}',
'settings.costDashboard.title': 'Панель затрат',
'settings.costDashboard.sevenDayCost': '7-дневная ежедневная стоимость',
'settings.costDashboard.sevenDayTokens': '7-дневное использование токена',
@@ -1477,7 +1486,7 @@ const messages: TranslationMap = {
'settings.costDashboard.disabledHint':
'Панель затрат отключена в конфигурации. Установите [cost.dashboard] Enabled = True в config.toml, чтобы повторно включить.',
'settings.costDashboard.subtitle':
- 'Расходы в реальном времени и сжигание токенов по всему множеству. Бары автоматически обновляются каждые несколько секунд: перезагрузка страницы не требуется.',
+ 'Локальные данные по вызовам поставщика. Стоимость может быть оценочной; оплата учитывается отдельно.',
'settings.costDashboard.summaryAriaLabel': 'Сводные показатели затрат',
'settings.costDashboard.lastSevenDays': 'последние 7 дней',
'settings.costDashboard.utilizationOf': 'из',
diff --git a/app/src/lib/i18n/zh-CN.ts b/app/src/lib/i18n/zh-CN.ts
index 5b1ce136a2..3a8c3447c7 100644
--- a/app/src/lib/i18n/zh-CN.ts
+++ b/app/src/lib/i18n/zh-CN.ts
@@ -1340,8 +1340,17 @@ const messages: TranslationMap = {
'应用启动时由 Tauri shell 在进程内启动。端口会在启动时选择,因此此 URL 每次启动都可能变化。',
'settings.about.connectionHelperCloud': '已连接到远程核心。可在 BootCheck 或云模式选择器中更改。',
'settings.heartbeat.title': '心跳和循环',
- 'settings.usage.title': '用量与限制',
- 'settings.usage.menuDesc': '费用、token 使用量、预算和后台活动',
+ 'settings.usage.title': '用量',
+ 'settings.usage.menuDesc': '费用、Token 节省、使用记录和后台活动',
+ 'settings.costDashboard.monthToDate': '本月至今',
+ 'settings.costDashboard.period': '时间范围',
+ 'settings.costDashboard.periodDays': '最近 {days} 天',
+ 'settings.costDashboard.all': '全部',
+ 'settings.costDashboard.costSource': '费用来源',
+ 'settings.costDashboard.estimated': '估算',
+ 'settings.costDashboard.providerCharged': '服务商计费',
+ 'settings.costDashboard.searchModelSession': '模型或会话',
+ 'settings.costDashboard.filteredTotal': '已加载 {loaded} 条,显示 {shown} 条 • {cost}',
'settings.costDashboard.title': '成本看板',
'settings.costDashboard.sevenDayCost': '7 天每日成本',
'settings.costDashboard.sevenDayTokens': '7 天 token 用量',
@@ -1367,8 +1376,7 @@ const messages: TranslationMap = {
'settings.costDashboard.loading': '正在加载成本看板…',
'settings.costDashboard.disabledHint':
'成本看板已在配置中禁用。请在 config.toml 中设置 [cost.dashboard] enabled = true 以重新启用。',
- 'settings.costDashboard.subtitle':
- '集群实时支出和 token 消耗。条形图每隔几秒自动刷新,无需重新加载页面。',
+ 'settings.costDashboard.subtitle': '本地服务商调用用量。费用可能是估算值;托管计费单独计算。',
'settings.costDashboard.summaryAriaLabel': '成本汇总指标',
'settings.costDashboard.lastSevenDays': '过去 7 天',
'settings.costDashboard.utilizationOf': '/',
diff --git a/crates/openhuman-core/src/config/schema/identity_cost.rs b/crates/openhuman-core/src/config/schema/identity_cost.rs
index f75bb3569d..e753e38d5e 100644
--- a/crates/openhuman-core/src/config/schema/identity_cost.rs
+++ b/crates/openhuman-core/src/config/schema/identity_cost.rs
@@ -10,31 +10,28 @@ use std::collections::HashMap;
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct CostConfig {
- /// Enable budget enforcement (default: true).
- ///
/// Retained for **recording**, not enforcement: nothing refuses a request
/// on cost any more. `CostTracker::record_usage` is a no-op when this is
/// `false`; `record_usage_unconditional` (the dashboard/telemetry path)
/// ignores it.
///
- /// **Important:** as of the cost-dashboard PR this flag controls
- /// **enforcement only**, not telemetry capture. The dashboard
+ /// Dashboard telemetry uses `record_usage_unconditional`, so this flag
+ /// does not disable telemetry capture. The dashboard
/// JSONL store at `{workspace}/state/costs.jsonl` is populated by
/// [`crate::platform::cost::record_provider_usage`] regardless of
- /// this flag, so users can review historical spend before opting
- /// into hard caps. Set `dashboard.enabled = false` to hide the
+ /// this flag, so users can review historical usage. Set
+ /// `dashboard.enabled = false` to hide the
/// Settings panel; delete the JSONL file to clear collected
/// history. The file is local and never leaves the workspace.
#[serde(default = "default_cost_enabled")]
pub enabled: bool,
- /// Monthly budget in USD, for the dashboard only (default: 100.00).
+ /// Legacy monthly display target in USD (default: 100.00).
///
/// **This is a display target, not a cap.** Nothing in the core refuses a
/// request when it is exceeded — the enforcement path was removed with the
- /// spend cap. It is the denominator behind the dashboard's budget gauge
- /// and status (`CostTracker::get_dashboard`), which is why it survives and
- /// why the settings copy still points at `cost.monthly_limit_usd`.
+ /// spend cap. It remains in the dashboard RPC payload for compatibility,
+ /// but the UI no longer presents it as a limit.
///
/// Counts **managed (OpenHuman-credit) spend only** — see
/// [`crate::platform::cost::route`]. Bring-your-own-key and local
@@ -61,9 +58,8 @@ pub struct CostConfig {
/// Configuration for the 7-day cost & token usage dashboard panel.
///
-/// The monthly budget itself is read from [`CostConfig::monthly_limit_usd`]
-/// — `warn_threshold` and `alert_threshold` are fractions of that budget
-/// that drive bar colour-coding and status badges on the chart.
+/// Legacy thresholds are retained in the dashboard RPC payload for
+/// compatibility; the UI does not display budget warnings.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct CostDashboardConfig {
diff --git a/crates/openhuman-core/src/platform/cost/README.md b/crates/openhuman-core/src/platform/cost/README.md
index e61c7fecb7..d830972697 100644
--- a/crates/openhuman-core/src/platform/cost/README.md
+++ b/crates/openhuman-core/src/platform/cost/README.md
@@ -1,6 +1,6 @@
# cost
-API-usage cost tracking and budget enforcement for the agent. Records per-call token usage and computed USD cost to an append-only JSONL file, maintains in-memory daily/monthly aggregates, exposes a budget gate (`check_budget`) and a 7-day dashboard surface over JSON-RPC. A process-global singleton tracker is shared by the agent turn loop (telemetry) and the dashboard RPC handlers so each provider call is persisted exactly once.
+Local API-usage cost tracking for the agent. Records per-call token usage and computed USD cost to an append-only JSONL file, maintains in-memory daily/monthly aggregates, exposes a 7-day dashboard and a bounded usage log over JSON-RPC. A process-global singleton tracker is shared by the agent turn loop (telemetry) and the dashboard RPC handlers so each provider call is persisted exactly once.
## Responsibilities
@@ -8,9 +8,8 @@ API-usage cost tracking and budget enforcement for the agent. Records per-call t
- Preserve provider-reported usage provenance on persisted records: cached input tokens, cache-creation tokens, reasoning tokens, and whether `cost_usd` is `estimated` or `provider_charged`.
- Persist each usage event as a `CostRecord` line in `costs.jsonl` (durable: write + `sync_all`).
- Maintain cached current-day / current-month spend aggregates, rebuilt on day/month rollover.
-- Enforce daily and monthly budget limits with warn-threshold signalling (`check_budget` → `BudgetCheck::{Allowed, Warning, Exceeded}`) — only when `cost.enabled`.
-- Capture dashboard telemetry **unconditionally** (independent of `cost.enabled`) via `record_usage_unconditional`, so history exists before a user opts into enforcement.
-- Aggregate a 7-day daily history (zero-filling gap days), monthly pace projection, budget utilisation/status, and per-model breakdown for the dashboard.
+- Capture dashboard telemetry **unconditionally** (independent of `cost.enabled`) via `record_usage_unconditional`, so history remains available to the usage view.
+- Aggregate a 7-day daily history (zero-filling gap days), monthly pace projection, and per-model breakdown for the dashboard. Legacy budget fields remain on the RPC payload for compatibility, but the UI does not present them as limits.
- Serve the dashboard / daily-history / summary over JSON-RPC, with a cached read-only fallback tracker when the global is uninitialised.
## Key files
@@ -18,8 +17,8 @@ API-usage cost tracking and budget enforcement for the agent. Records per-call t
| File | Role |
| ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `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`, `BudgetCheck`, `CostSummary`, `ModelStats`, `DailyCostEntry`, `BudgetStatus`, `CostDashboard`. Cost-calc logic lives in `TokenUsage::new`. |
-| `crates/openhuman-core/src/platform/cost/tracker.rs` | `CostTracker` (budget checks, 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/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/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`. |
@@ -35,9 +34,9 @@ From `mod.rs` re-exports:
- `CostTracker` — the tracker (`tracker`).
- `init_global`, `try_global`, `record_provider_usage` (`global`).
- `all_cost_controller_schemas`, `all_cost_registered_controllers` (`schemas`).
-- Types: `BudgetCheck`, `BudgetStatus`, `CostDashboard`, `CostRecord`, `CostSource`, `CostSummary`, `DailyCostEntry`, `ModelStats`, `TokenUsage`, `UsagePeriod`.
+- Types: `BudgetStatus`, `CostDashboard`, `CostRecord`, `CostSource`, `CostSummary`, `DailyCostEntry`, `ModelStats`, `TokenUsage`, `UsagePeriod`.
-Notable `CostTracker` methods: `new`, `session_id`, `check_budget`, `record_usage`, `record_usage_unconditional`, `get_summary`, `get_daily_cost`, `get_monthly_cost`, `get_daily_history`, `get_dashboard`.
+Notable `CostTracker` methods: `new`, `session_id`, `record_usage`, `record_usage_unconditional`, `get_summary`, `get_daily_cost`, `get_monthly_cost`, `get_daily_history`, `get_dashboard`.
## RPC / controllers
@@ -45,11 +44,12 @@ Namespace `cost` (methods `openhuman.cost_*` via the registry):
| Method | Inputs | Output |
| ------------------------ | -------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
-| `cost_get_dashboard` | none | 7-day dashboard payload: per-day buckets, summary metrics, budget utilisation/status, per-model breakdown. |
+| `cost_get_dashboard` | none | 7-day dashboard payload: per-day buckets, summary metrics, legacy budget fields, per-model breakdown. |
| `cost_get_daily_history` | `days?` (u32, default 7, clamped `[1, 366]`) | Ordered daily entries, oldest first, gaps zero-filled. |
| `cost_get_summary` | none | Live session / daily / monthly cost summary. |
+| `cost_get_usage_log` | `days?`, `limit?` | Recent local records, newest first, bounded to 1,000 rows. |
-Handlers load config via `config_rpc::load_config_with_timeout`, then delegate to `rpc.rs`. RPC DTOs (`CostDashboardDto`, `DailyCostEntryDto`, `ModelStatsDto`, `CostSummaryDto`, `UsageLogRecordDto`) add presentation fields not on the domain types — `provider` (derived from the `provider/model` prefix), `percent_of_total`, and dashboard threshold/`enabled` flags from `cost.dashboard`. Usage-log records preserve the persisted token provenance fields (`cached_input_tokens`, `cache_creation_tokens`, `reasoning_tokens`, `cost_source`) for migration audit callers even when the dashboard table does not render them yet.
+Handlers load config via `config_rpc::load_config_with_timeout`, then delegate to `rpc.rs`. RPC DTOs (`CostDashboardDto`, `DailyCostEntryDto`, `ModelStatsDto`, `CostSummaryDto`, `UsageLogRecordDto`) add presentation fields not on the domain types — `provider` (derived from the `provider/model` prefix), `percent_of_total`, and dashboard threshold/`enabled` flags from `cost.dashboard`. Usage-log records preserve the persisted token provenance fields (`cached_input_tokens`, `cache_creation_tokens`, `reasoning_tokens`, `cost_source`) for migration audit callers for the dedicated usage-log tab.
## Events
@@ -64,7 +64,7 @@ None. The module has no `bus.rs` and no `DomainEvent` publishers/subscribers.
## Dependencies
-- `crate::config` — `CostConfig` / `Config` (limits, warn percent, `dashboard` thresholds/currency/enabled, `workspace_dir`); `config::rpc::load_config_with_timeout` in schemas.
+- `crate::config` — `CostConfig` / `Config` (legacy display target, dashboard currency/enabled, `workspace_dir`); `config::rpc::load_config_with_timeout` in schemas.
- `crate::inference::provider::types::UsageInfo` (re-exported as `crate::inference::provider::UsageInfo`) — provider usage payload translated into `TokenUsage` in `global.rs`.
- `crate::core::all` — `ControllerFuture`, `RegisteredController` for controller registration.
- `crate::core` — `ControllerSchema`, `FieldSchema`, `TypeSchema`.
@@ -77,15 +77,15 @@ None. The module has no `bus.rs` and no `DomainEvent` publishers/subscribers.
- `crates/openhuman-core/src/core/jsonrpc.rs` — calls `cost::init_global(cfg.cost.clone(), &workspace_dir)` at bootstrap.
- `crates/openhuman-core/src/agent/tinyagents/observability/event_bridge.rs`, `agent/tinyagents/turn_outcome.rs`, `agent/tinyagents/host/budget_gate.rs`, and `agent/subagent_host/` — call `cost::record_provider_usage` after provider calls to log per-turn (and subagent) usage.
- `crates/openhuman-core/src/tools/mod.rs` — re-exports `platform::cost::tools::*`.
-- `crates/openhuman-core/src/config/schema/identity_cost.rs` — `CostConfig` definition references `check_budget` / `record_provider_usage` semantics in docs.
+- `crates/openhuman-core/src/config/schema/identity_cost.rs` — `CostConfig` retains legacy budget-display fields for wire compatibility.
## Notes / gotchas
-- **`cost.enabled` gates enforcement only, not telemetry.** When `false`, `check_budget` returns `Allowed` and `record_usage` is a no-op, but the agent path uses `record_usage_unconditional`, so `costs.jsonl` still grows. This is a deliberate behavioural change (logged with a `warn` on init for upgraders) so spend history exists before turning on hard caps.
+- **`cost.enabled` gates `record_usage`, not telemetry.** The agent path uses `record_usage_unconditional`, so the local usage ledger continues to grow when this flag is false. The core no longer enforces a cost cap; hosted-credit exhaustion is enforced by the backend.
- The global tracker is a one-shot `OnceCell`; `init_global` is idempotent and never panics on construction failure (it logs and leaves `try_global() == None`). Callers before bootstrap (e.g. unit tests) must treat the absence as a soft no-op.
- `record_provider_usage` skips all-zero `UsageInfo` payloads (`input==0 && output==0 && charged==0.0`) so providers that don't echo usage don't inflate the request count.
- Provider-charged USD is persisted directly with `cost_source = provider_charged`; otherwise usage remains `estimated`. Cached input tokens are clamped to `input_tokens` during provider usage translation.
- The RPC fallback tracker (`resolve_tracker`) shares the same JSONL file as the real tracker and is read-effective only; it caches by workspace path and replays a construction error for `FALLBACK_ERROR_TTL` (30s) to avoid hammering a bad workspace on the UI's ~10s poll.
-- `budget_utilization` is clamped to `1.0` for display; `budget_status` is computed from the raw (unclamped) utilisation against `warn`/`alert` thresholds. A non-positive monthly limit forces `BudgetStatus::Normal` and `0.0` utilisation.
+- Legacy `budget_utilization` is clamped to `1.0` in the RPC payload; `budget_status` is computed from the raw (unclamped) utilisation against `warn`/`alert` thresholds. A non-positive monthly limit forces `BudgetStatus::Normal` and `0.0` utilisation.
- All amounts are stored/computed in USD; `currency` is a presentation hint only.
- Time bucketing is UTC throughout (`naive_utc().date()`); model is the bucket key for per-model stats, and `provider` is derived from the `provider/model` slash prefix in DTO mapping.
diff --git a/crates/openhuman-core/src/platform/cost/global.rs b/crates/openhuman-core/src/platform/cost/global.rs
index 93a7ffac05..6aa76e2f86 100644
--- a/crates/openhuman-core/src/platform/cost/global.rs
+++ b/crates/openhuman-core/src/platform/cost/global.rs
@@ -26,18 +26,10 @@ static GLOBAL_TRACKER: OnceCell<Arc<CostTracker>> = OnceCell::new();
/// no-ops and the original tracker is preserved. Logs (but does not panic)
/// when construction fails so a bad workspace path never blocks core boot.
///
-/// **Semantics note (changed in the cost-dashboard PR):**
-///
-/// - `cost.enabled = true` (the new default) — budget enforcement and
-/// dashboard telemetry are both active.
-/// - `cost.enabled = false` — budget enforcement is **off**, but the
-/// dashboard telemetry path still appends to `costs.jsonl` (see
-/// [`record_provider_usage`]). The flag now gates enforcement only;
-/// observability is independent. This is a deliberate trade-off so
-/// operators can review historical spend before opting into hard
-/// budget caps. A `warn` is emitted below so the change is visible
-/// in logs for anyone upgrading from a prior build where
-/// `cost.enabled = false` blocked recording too.
+/// The agent telemetry path appends to `costs.jsonl` through
+/// [`record_provider_usage`] regardless of `cost.enabled`. That flag only
+/// affects direct calls to `CostTracker::record_usage`; it does not enforce a
+/// spend cap. The local ledger remains available when the flag is false.
///
/// The first-boot `info` log records `enabled` and the resolved
/// workspace so the default-on behaviour shows up in startup logs for
@@ -59,10 +51,8 @@ pub fn init_global(config: CostConfig, workspace_dir: &Path) {
);
if !cost_enabled {
log::warn!(
- "[cost] cost.enabled=false: budget enforcement is OFF, but dashboard \
- telemetry will still append to costs.jsonl. This is a behavioural \
- change from prior builds where cost.enabled=false also blocked \
- recording. Set cost.dashboard.enabled=false to disable the panel; \
+ "[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."
);
}
@@ -102,10 +92,7 @@ pub fn try_global() -> Option<Arc<CostTracker>> {
///
/// Note: this path uses
/// [`crate::platform::cost::tracker::CostTracker::record_usage_unconditional`],
-/// so dashboard telemetry is captured even when `cost.enabled = false` —
-/// the `cost.enabled` flag gates budget enforcement (refusing requests),
-/// not observability. This lets users see history first and decide
-/// whether to switch on enforcement.
+/// so dashboard telemetry is captured even when `cost.enabled = false`.
///
/// `model` is the model identifier the request was routed to (e.g.
/// `"anthropic/claude-sonnet-4-20250514"`) and is used as the bucket key
diff --git a/gitbooks/features/billing-and-usage.md b/gitbooks/features/billing-and-usage.md
index 7a44adf32f..7826c2c124 100644
--- a/gitbooks/features/billing-and-usage.md
+++ b/gitbooks/features/billing-and-usage.md
@@ -1,13 +1,13 @@
---
description: >-
Plans, credits and saved cards over Stripe and Coinbase, plus a local
- real-time dashboard for token usage, cost and budget enforcement.
+ local dashboard for token usage and cost estimates.
icon: credit-card
---
# Billing, Cost & Usage
-OpenHuman keeps two related but separate ledgers. **Billing** is what you pay the hosted backend: plans, credit top-ups, saved cards and coupons, all settled through Stripe or Coinbase. **Cost & Usage** is what the agent spends on your behalf, tracked locally per provider call so you can see (and cap) real token spend before the bill ever lands.
+OpenHuman keeps two related but separate ledgers. **Billing** is what you pay the hosted backend: plans, credit top-ups, saved cards and coupons, all settled through Stripe or Coinbase. **Cost & Usage** is what the agent spends on your behalf, tracked locally per provider call so you can inspect estimated token costs.
The first lives in the cloud; the second never leaves your workspace.
@@ -50,7 +50,7 @@ Coupon codes are redeemed against the backend (`POST /coupons/redeem`), and you
### Where billing lives in the app
-The desktop **Settings → Billing** panel is read-only. It shows the current plan, promotional and top-up balances, total remaining funds, current-cycle spend, and usage breakdowns. Buttons link to the hosted web **billing dashboard**, which is the single place to manage plans, top-ups, coupons, cards, and invoices. Other clients can reach the same hosted billing operations through the authenticated RPC controllers described below; they are not exposed as agent tools.
+The **Billing** button on the desktop Accounts page opens the hosted web billing dashboard, where you can manage plans, top-ups, coupons, cards, and invoices. The former desktop Billing summary page has been removed. Other clients can reach the same hosted billing operations through the authenticated RPC controllers described below; they are not exposed as agent tools.
### RPC surface
@@ -60,38 +60,30 @@ Namespace `billing`, exposed as `openhuman.billing_*` (16 methods), e.g. `billin
## Part 2: Cost & Usage Dashboard
-The `cost` domain is entirely local. It records every provider call's token usage and computed USD cost to an append-only JSONL file (`<workspace>/state/costs.jsonl`), keeps in-memory daily/monthly aggregates, enforces budgets, and serves a 7-day dashboard over JSON-RPC. A process-global singleton tracker is shared by the agent turn loop (which logs telemetry after each provider call) and the dashboard handlers, so each call is persisted exactly once.
+The `cost` domain is entirely local. It records every provider call's token usage and computed USD cost to an append-only JSONL file (`<workspace>/state/costs.jsonl`), keeps in-memory daily/monthly aggregates and serves a 7-day dashboard over JSON-RPC. A process-global singleton tracker is shared by the agent turn loop (which logs telemetry after each provider call) and the dashboard handlers, so each call is persisted exactly once.
### Real-time token & cost tracking
For each call, per-call cost is computed from token counts and per-million-token prices (clamping non-finite or negative prices to `0.0`). When the provider echoes an authoritative `charged_amount_usd` that value wins; otherwise OpenHuman falls back to a static pricing catalog of known models. Usage is bucketed in UTC, keyed by model, with the **provider** derived from the `provider/model` prefix. All-zero usage payloads are skipped so providers that don't report usage don't inflate the request count.
-### Budgets & enforcement
+### Local tracking and usage view
-Budget enforcement is configured under the `[cost]` config block:
+The local `[cost] monthly_limit_usd` setting is a legacy display target, not an enforced cap. The core no longer refuses requests when estimated cost passes it. Hosted credit exhaustion is enforced by the backend and is separate from the local usage ledger. The Usage view therefore does not show a budget gauge, limit status, or daily threshold colors.
-| Setting | Default | Role |
-| ------------------- | -------- | ----------------------------------------- |
-| `enabled` | `true` | Gates **enforcement only**, not telemetry |
-| `daily_limit_usd` | `10.00` | Hard daily cap |
-| `monthly_limit_usd` | `100.00` | Hard monthly cap |
-| `warn_at_percent` | `80` | Warn threshold for `check_budget` |
+Settings → **Usage** shows the last seven UTC calendar days of recorded cost and token activity, a monthly pace projection, and a per-model breakdown. Costs can be estimates when the provider did not return a charged amount. The dashboard refreshes about every 10 seconds.
-`check_budget` returns `Allowed`, `Warning` (warn threshold reached) or `Exceeded` (over the daily or monthly cap). A crucial detail: **`enabled` controls enforcement, not capture.** When it is `false`, `check_budget` always returns `Allowed` and hard caps are off. The agent still records usage unconditionally, so your spend history accumulates and you can review it _before_ opting into hard caps. To hide the panel set `dashboard.enabled = false`; to clear history delete the JSONL file (it is local and never leaves the workspace).
-
-### The 7-day dashboard
-
-Settings → **Usage & Limits** hosts the cost dashboard (alongside background-activity controls). It renders a 7-day daily history (gap days zero-filled, oldest first), a token-usage chart, a monthly-pace projection, budget utilisation and a per-model cost breakdown. Dashboard colour-coding uses fractions of the monthly budget: bars flip to amber at the `warn_threshold` (default `0.8`) and red at the `alert_threshold` (default `0.95`). `budget_utilization` is clamped to `1.0` for display, while status is computed from the raw value. The panel polls roughly every 10 seconds and shows an "Updated Ns ago" freshness pill. A read-only fallback tracker (sharing the same JSONL file) serves the UI when the global tracker isn't yet initialised.
+The **Usage log** tab shows local provider-call records in a selected rolling period. It fetches at most 1,000 newest rows and supports category, provider, cost-source, and model/session filters over those loaded rows. The displayed row count and cost are for the filtered loaded set, not a complete billing total.
### RPC surface
Namespace `cost`, exposed as `openhuman.cost_*`:
-| Method | Inputs | Output |
-| ------------------------ | ------------------------------------- | ------------------------------------------------------------------------------ |
-| `cost_get_dashboard` | none | 7-day buckets, summary metrics, budget utilisation/status, per-model breakdown |
-| `cost_get_daily_history` | `days?` (default 7, clamped 1 to 366) | Ordered daily entries, oldest first, gaps zero-filled |
-| `cost_get_summary` | none | Live session / daily / monthly cost summary |
+| Method | Inputs | Output |
+| ------------------------ | ------------------------------------- | ----------------------------------------------------------------------------- |
+| `cost_get_dashboard` | none | 7-day buckets, summary metrics, legacy budget fields, per-model breakdown |
+| `cost_get_daily_history` | `days?` (default 7, clamped 1 to 366) | Ordered daily entries, oldest first, gaps zero-filled |
+| `cost_get_summary` | none | Live session / daily / monthly cost summary |
+| `cost_get_usage_log` | `days?`, `limit?` | Newest local provider-call records and category totals, bounded to 1,000 rows |
These are also exposed as read-only, default-ON agent tools so the agent can inspect its own spend.
@@ -99,7 +91,7 @@ These are also exposed as read-only, default-ON agent tools so the agent can ins
## Cost & token compression
-Because cost tracks **real token counts**, anything that shrinks the prompt directly lowers spend. OpenHuman's [TokenJuice token compression](token-compression.md) reduces the tokens sent on each call, and [model routing](model-routing/README.md) sends work to the cheapest model that can handle it. Both show up as lower bars in the dashboard and slower budget burn.
+Because cost tracks **real token counts**, anything that shrinks the prompt directly lowers spend. OpenHuman's [TokenJuice token compression](token-compression.md) reduces the tokens sent on each call, and [model routing](model-routing/README.md) sends work to the cheapest model that can handle it. Both can show up as lower recorded costs in the dashboard.
---