Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-2484]): multi-provider usage page — per-model cost report with time filters + quota adapters
[._.]/ Adam Eivy06dfd28621ba
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex ac814ceed0..85b239ce7b 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Changes+- **The DevTools Usage page now covers every enabled AI provider — subscription meters plus a "what would this have cost" report with time filters (#2484).** The old Claude-only subscription panel becomes a per-provider grid: Claude Code keeps its live `/usage` meters, Codex gains real session/weekly meters read zero-cost from its local session telemetry (with plan type and reset times), and Antigravity/Grok show an honest "usage reporting not available" note instead of nothing. Below it, a new Est. API Cost Report answers "what would my subscription usage have cost under API billing" for any window — 7/30/90 days, all time, or a custom date range (URL-driven, so views are shareable) — broken down per provider and per model with input/output token counts and an aggregate total. Local providers (Ollama, LM Studio, and Ollama-backed CLI wrappers) are tagged "Local — free" and priced at $0. The flat legacy $3/$15 blended estimate is replaced by a real per-model rate table verified against the Anthropic/OpenAI/xAI/Google pricing pages (2026-07-12), with family fallbacks for shorthand model ids and a `~` marker on approximated rows; caching/batch discounts are deliberately excluded and disclosed. Usage capture now also records input tokens (estimated from prompt size) and attributes tokens per provider per model per day — the breakdown is forward-only from this upgrade, and the report says so.+- **Code reviewers can now be marked non-blocking, so a flaky local reviewer no longer strands your PRs.** Each reviewer chip in the Code Review Defaults panel, the task form, and the per-task-type schedule config gains a `~opt` toggle. A reviewer marked non-blocking still runs and still has its findings fixed, but its *inconclusive* verdict (timeout / no result / partial review) is excluded from the merge gate — it no longer flips the aggregate to `inconclusive`, so a saved `--merge` proceeds. A hard failure (broken build / failed tests) from it still blocks. This is the answer to a valuable-but-flaky reviewer like a local Ollama model that frequently returns no verdict and would otherwise block every auto-merge. Under the hood the setting is a new `optionalReviewers` list (additive, no migration) threaded through the CoS reviewer config into slashdo's new `--review-with …~opt` suffix (requires the bundled slashdo submodule bump in this release). GitHub `@username` reviewers can be marked non-blocking too.- **The Claude reviewer now takes an optional model, including an Ollama-backed Claude for local-only setups (#2377).** Code Review Defaults gains a **Claude model** field alongside the existing Codex one: pick a Claude tier, or — if you run `claude` pointed at a local Ollama daemon — type or pick one of your installed Ollama models, and the Review Loop invokes the reviewer as `claude --model <id>`. Under the hood the codex-only model threading is generalized into a reviewer-keyed model map, so any CLI reviewer that supports `--model` (today: Codex and Claude) threads its configured model through the review-loop follow-up with a single code path instead of a per-reviewer special case. Older in-flight review tasks that stored only the legacy Codex tier still work unchanged.diff --git a/client/src/pages/UsagePage.jsx b/client/src/pages/UsagePage.jsxindex ec446a0587..b54bf16a2f 100644--- a/client/src/pages/UsagePage.jsx+++ b/client/src/pages/UsagePage.jsx@@ -1,28 +1,346 @@import { useState, useEffect } from 'react';+import { useSearchParams } from 'react-router-dom';import { RefreshCw, Clock, AlertTriangle } from 'lucide-react';import * as api from '../services/api';import BrailleSpinner from '../components/BrailleSpinner';import { formatCompactCount } from '../utils/formatters';+const PERIOD_OPTIONS = [+ { id: '7d', label: '7 days' },+ { id: '30d', label: '30 days' },+ { id: '90d', label: '90 days' },+ { id: 'all', label: 'All time' }+];++// Preserve the em-dash empty-state; delegate K/M abbreviation to the shared helper.+const formatNumber = (num) => (num == null ? '—' : formatCompactCount(num));++const formatCost = (cost) => `$${(cost ?? 0).toFixed(2)}`;++// Reset times arrive either as human text from the Claude CLI ("Jul 15, 3am")+// or as an ISO timestamp from telemetry-based adapters — localize the latter.+const formatResetsAt = (resetsAt) => {+ if (!resetsAt || !/^\d{4}-\d{2}-\d{2}T/.test(resetsAt)) return resetsAt;+ const d = new Date(resetsAt);+ return Number.isNaN(d.getTime()) ? resetsAt : d.toLocaleString(undefined, { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });+};++// Color a usage meter by how much is consumed: comfortable → warning → critical.+function meterColor(percentUsed) {+ if (percentUsed == null) return 'bg-gray-500';+ if (percentUsed >= 90) return 'bg-port-error';+ if (percentUsed >= 70) return 'bg-port-warning';+ return 'bg-port-success';+}++function UsageMeter({ limit }) {+ const used = limit.percentUsed ?? 0;+ const remaining = limit.percentRemaining;+ return (+ <div className="py-2 border-b border-port-border last:border-0">+ <div className="flex items-baseline justify-between gap-2 mb-1">+ <span className="text-white text-sm sm:text-base">{limit.label}</span>+ <span className="text-xs sm:text-sm text-gray-400">+ {remaining == null ? '—' : `${remaining}% left`}+ </span>+ </div>+ <div className="h-2 rounded-full bg-port-bg overflow-hidden">+ <div+ className={`h-full rounded-full ${meterColor(limit.percentUsed)}`}+ style={{ width: `${Math.min(100, Math.max(0, used))}%` }}+ />+ </div>+ <div className="flex items-center justify-between mt-1">+ <span className="text-[10px] sm:text-xs text-gray-500">{used}% used</span>+ {limit.resetsAt && (+ <span className="text-[10px] sm:text-xs text-gray-500 flex items-center gap-1">+ <Clock size={11} /> resets {formatResetsAt(limit.resetsAt)}+ </span>+ )}+ </div>+ </div>+ );+}++// One subscription-quota card per enabled provider family. Providers with no+// queryable usage surface (supported: false) render a muted note, never an+// error; a supported adapter that failed transiently shows a soft warning.+function ProviderQuotaCard({ quota }) {+ return (+ <div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4">+ <div className="flex items-center justify-between mb-2">+ <h3 className="text-base font-semibold text-white">{quota.label}</h3>+ {quota.plan && quota.plan !== 'unknown' && (+ <span className="text-[10px] sm:text-xs uppercase tracking-wide text-gray-400 border border-port-border rounded-full px-2 py-0.5">+ {quota.plan}+ </span>+ )}+ </div>++ {!quota.supported && (+ <p className="text-sm text-gray-500">{quota.note || 'Usage reporting is not available for this provider.'}</p>+ )}++ {quota.supported && quota.error && (+ <div className="flex items-start gap-2 text-sm text-gray-400 py-1">+ <AlertTriangle size={15} className="text-port-warning mt-0.5 shrink-0" />+ <span>{quota.error}</span>+ </div>+ )}++ {quota.supported && !quota.error && (+ <div className="space-y-2">+ {quota.limits?.length > 0 ? (+ <div>+ {quota.limits.map((limit) => (+ <UsageMeter key={limit.key} limit={limit} />+ ))}+ </div>+ ) : (+ <div className="text-gray-500 text-sm">No rate-limit data reported</div>+ )}++ {quota.activity?.length > 0 && (+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 pt-1">+ {quota.activity.map((a) => (+ <div key={a.period} className="bg-port-bg border border-port-border rounded-lg p-2.5">+ <div className="text-xs text-gray-400 mb-0.5">{a.period}</div>+ <div className="text-sm text-white">+ {formatCompactCount(a.requests)} requests+ <span className="mx-2 text-gray-600">•</span>+ {formatCompactCount(a.sessions)} sessions+ </div>+ </div>+ ))}+ </div>+ )}++ {quota.note && (+ <p className="text-[10px] sm:text-xs text-gray-500">{quota.note}</p>+ )}+ </div>+ )}+ </div>+ );+}++// Subscription usage for every enabled provider family (claude, codex, agy,+// grok). Self-contained fetch/loading/error state so it always renders above+// the PortOS-internal metrics.+function ProviderQuotaSection() {+ const [quotas, setQuotas] = useState(null);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState(false);++ const load = async (refresh = false) => {+ setLoading(true);+ setError(false);+ const result = await api.getProviderUsage({ refresh }).catch(() => null);+ if (result?.providers) {+ setQuotas(result.providers);+ } else {+ // Keep previously-loaded cards on a transient refresh failure.+ setError(true);+ }+ setLoading(false);+ };++ useEffect(() => { load(); }, []);++ return (+ <div className="space-y-3">+ <div className="flex items-center justify-between">+ <h2 className="text-lg font-semibold text-white">Subscription Usage</h2>+ <button+ onClick={() => load(true)}+ disabled={loading}+ className="flex items-center gap-2 px-3 py-1.5 text-sm text-gray-400 hover:text-white disabled:opacity-50"+ title="Refresh provider usage"+ >+ <RefreshCw size={15} className={loading ? 'animate-spin' : ''} /> Refresh+ </button>+ </div>++ {loading && !quotas && (+ <div className="py-6"><BrailleSpinner text="Reading provider usage" /></div>+ )}++ {!loading && error && !quotas && (+ <div className="flex items-start gap-2 text-sm text-gray-400 py-2">+ <AlertTriangle size={16} className="text-port-warning mt-0.5 shrink-0" />+ <span>Couldn’t read provider usage.</span>+ </div>+ )}++ {quotas && (+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-3 sm:gap-4">+ {quotas.map((quota) => (+ <ProviderQuotaCard key={quota.family} quota={quota} />+ ))}+ {quotas.length === 0 && (+ <div className="text-gray-500 text-sm">No enabled providers report subscription usage.</div>+ )}+ </div>+ )}+ </div>+ );+}++// Approximate-rate marker: anything other than an exact model-id rate match.+const approxMark = (rateMatch) => (rateMatch === 'exact' || rateMatch === 'free' ? '' : '~');++function CostReportTable({ report }) {+ if (!report?.providers?.length) {+ return <div className="text-gray-500 text-sm py-4">No per-provider usage recorded in this period.</div>;+ }+ return (+ <div className="overflow-x-auto">+ <table className="w-full text-sm min-w-[560px]">+ <thead>+ <tr className="text-left text-xs text-gray-500 border-b border-port-border">+ <th className="py-2 pr-2 font-medium">Provider / Model</th>+ <th className="py-2 px-2 font-medium text-right">Sessions</th>+ <th className="py-2 px-2 font-medium text-right">Tokens In</th>+ <th className="py-2 px-2 font-medium text-right">Tokens Out</th>+ <th className="py-2 pl-2 font-medium text-right">Est. API Cost</th>+ </tr>+ </thead>+ <tbody>+ {report.providers.map((provider) => (+ <ProviderCostRows key={provider.id} provider={provider} />+ ))}+ </tbody>+ <tfoot>+ <tr className="border-t border-port-border font-semibold text-white">+ <td className="py-2 pr-2">Total</td>+ <td className="py-2 px-2 text-right">{formatNumber(report.totals.sessions)}</td>+ <td className="py-2 px-2 text-right">{formatNumber(report.totals.tokensIn)}</td>+ <td className="py-2 px-2 text-right">{formatNumber(report.totals.tokensOut)}</td>+ <td className="py-2 pl-2 text-right text-port-success">{formatCost(report.totals.estimatedCost)}</td>+ </tr>+ </tfoot>+ </table>+ </div>+ );+}++function ProviderCostRows({ provider }) {+ return (+ <>+ <tr className="border-t border-port-border text-white">+ <td className="py-2 pr-2">+ <span className="font-medium">{provider.name}</span>+ {provider.free && (+ <span className="ml-2 text-[10px] uppercase tracking-wide text-port-success border border-port-success/40 rounded-full px-1.5 py-0.5">+ Local — free+ </span>+ )}+ </td>+ <td className="py-2 px-2 text-right">{formatNumber(provider.sessions)}</td>+ <td className="py-2 px-2 text-right">{formatNumber(provider.tokensIn)}</td>+ <td className="py-2 px-2 text-right">{formatNumber(provider.tokensOut)}</td>+ <td className="py-2 pl-2 text-right">{provider.free ? formatCost(0) : formatCost(provider.estimatedCost)}</td>+ </tr>+ {provider.models.map((m) => (+ <tr key={m.model} className="text-gray-400">+ <td className="py-1.5 pr-2 pl-4 sm:pl-6 font-mono text-xs truncate max-w-[220px]" title={m.rateModel ? `Priced as ${m.rateModel} ($${m.inputPer1M}/$${m.outputPer1M} per 1M)` : undefined}>+ {m.model}+ </td>+ <td className="py-1.5 px-2 text-right text-xs">{formatNumber(m.sessions)}</td>+ <td className="py-1.5 px-2 text-right text-xs">{formatNumber(m.tokensIn)}</td>+ <td className="py-1.5 px-2 text-right text-xs">{formatNumber(m.tokensOut)}</td>+ <td className="py-1.5 pl-2 text-right text-xs" title={approxMark(m.rateMatch) ? 'Approximate — no exact published rate for this model id' : undefined}>+ {approxMark(m.rateMatch)}{m.rateMatch === 'free' ? formatCost(0) : formatCost(m.estimatedCost)}+ </td>+ </tr>+ ))}+ </>+ );+}++// Time-filter pills + custom range, driven by URL search params so every+// report view is shareable/bookmarkable (linkable-routes convention).+function CostReportFilters({ period, from, to, isCustom, onPeriod, onRange }) {+ return (+ <div className="flex flex-wrap items-center gap-2">+ {PERIOD_OPTIONS.map((opt) => (+ <button+ key={opt.id}+ onClick={() => onPeriod(opt.id)}+ className={`px-3 py-1 rounded-full text-xs sm:text-sm border ${!isCustom && period === opt.id+ ? 'bg-port-accent/20 border-port-accent text-white'+ : 'border-port-border text-gray-400 hover:text-white'}`}+ >+ {opt.label}+ </button>+ ))}+ <div className={`flex items-center gap-1.5 rounded-full border px-2 py-0.5 ${isCustom ? 'border-port-accent bg-port-accent/10' : 'border-port-border'}`}>+ <label htmlFor="usage-from" className="text-xs text-gray-400">From</label>+ <input+ id="usage-from"+ type="date"+ value={from}+ onChange={(e) => onRange(e.target.value, to)}+ className="bg-transparent text-xs text-white outline-none [color-scheme:dark]"+ />+ <label htmlFor="usage-to" className="text-xs text-gray-400">To</label>+ <input+ id="usage-to"+ type="date"+ value={to}+ onChange={(e) => onRange(from, e.target.value)}+ className="bg-transparent text-xs text-white outline-none [color-scheme:dark]"+ />+ </div>+ </div>+ );+}+function InternalUsageMetrics() {+ const [searchParams, setSearchParams] = useSearchParams();+ const period = searchParams.get('period') || '7d';+ const from = searchParams.get('from') || '';+ const to = searchParams.get('to') || '';+ const isCustom = Boolean(from || to);+const [usage, setUsage] = useState(null);const [loading, setLoading] = useState(true);useEffect(() => {- loadUsage();- }, []);-- const loadUsage = async () => {+ let cancelled = false;setLoading(true);- const data = await api.getUsage().catch(() => null);- setUsage(data);- setLoading(false);+ const params = isCustom ? { from, to } : { period };+ api.getUsage(params)+ .catch(() => null)+ .then((data) => {+ if (cancelled) return;+ setUsage(data);+ setLoading(false);+ });+ return () => { cancelled = true; };+ }, [period, from, to, isCustom]);++ const setPeriod = (id) => {+ setSearchParams((prev) => {+ const next = new URLSearchParams(prev);+ next.delete('from');+ next.delete('to');+ if (id === '7d') next.delete('period'); else next.set('period', id);+ return next;+ }, { replace: true });};- // Preserve the em-dash empty-state; delegate K/M abbreviation to the shared helper.- const formatNumber = (num) => (num == null ? '—' : formatCompactCount(num));+ const setRange = (nextFrom, nextTo) => {+ setSearchParams((prev) => {+ const next = new URLSearchParams(prev);+ next.delete('period');+ if (nextFrom) next.set('from', nextFrom); else next.delete('from');+ if (nextTo) next.set('to', nextTo); else next.delete('to');+ return next;+ }, { replace: true });+ };- if (loading) {+ if (loading && !usage) {return <div className="text-center py-8"><BrailleSpinner text="Loading usage data" /></div>;}@@ -31,13 +349,14 @@ function InternalUsageMetrics() {}const maxActivity = Math.max(1, ...(usage.last7Days?.map(d => d.sessions) || []));+ const report = usage.report;return (<div className="space-y-6"><h2 className="text-lg font-semibold text-white">PortOS AI Usage</h2>- {/* Summary Stats */}- <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3 sm:gap-4">+ {/* Summary Stats (all-time) */}+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 sm:gap-4"><div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4 text-center"><div className="text-xl sm:text-2xl font-bold text-white">{formatNumber(usage.totalSessions)}</div><div className="text-xs sm:text-sm text-gray-400">Sessions</div>@@ -54,10 +373,22 @@ function InternalUsageMetrics() {<div className="text-xl sm:text-2xl font-bold text-white">{formatNumber((usage.totalTokens?.input ?? 0) + (usage.totalTokens?.output ?? 0))}</div><div className="text-xs sm:text-sm text-gray-400">Tokens</div></div>- <div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4 text-center col-span-2 sm:col-span-1">- <div className="text-xl sm:text-2xl font-bold text-port-success">${(usage.estimatedCost ?? 0).toFixed(2)}</div>- <div className="text-xs sm:text-sm text-gray-400">Est. Cost</div>+ </div>++ {/* Cost report — range-filtered per-provider/per-model breakdown */}+ <div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4 space-y-3">+ <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2">+ <h3 className="text-sm font-medium text-gray-400">Est. API Cost Report</h3>+ <span className="text-xl font-bold text-port-success">{formatCost(report?.totals?.estimatedCost)}</span></div>+ <CostReportFilters period={period} from={from} to={to} isCustom={isCustom} onPeriod={setPeriod} onRange={setRange} />+ <CostReportTable report={report} />+ <p className="text-[10px] sm:text-xs text-gray-500">+ Informational estimate of what this usage would have cost under API billing (PortOS runs on subscriptions).+ Token counts are partially estimated; rates as of {report?.pricingAsOf || 'the last update'}, excluding prompt-caching and batch discounts.+ {report?.breakdownSince && <> Per-provider breakdown available from {report.breakdownSince}.</>}+ {' '}Rows marked ~ use an approximated rate.+ </p></div><div className="grid grid-cols-1 md:grid-cols-2 gap-4 sm:gap-6">@@ -146,144 +477,6 @@ function InternalUsageMetrics() {</div></div></div>-- {/* Refresh button */}- <div className="flex justify-end">- <button- onClick={loadUsage}- className="flex items-center gap-2 px-4 py-2 text-gray-400 hover:text-white"- >- <RefreshCw size={16} /> Refresh- </button>- </div>- </div>- );-}--// Color a usage meter by how much is consumed: comfortable → warning → critical.-function meterColor(percentUsed) {- if (percentUsed == null) return 'bg-gray-500';- if (percentUsed >= 90) return 'bg-port-error';- if (percentUsed >= 70) return 'bg-port-warning';- return 'bg-port-success';-}--function UsageMeter({ limit }) {- const used = limit.percentUsed ?? 0;- const remaining = limit.percentRemaining;- return (- <div className="py-2 border-b border-port-border last:border-0">- <div className="flex items-baseline justify-between gap-2 mb-1">- <span className="text-white text-sm sm:text-base">{limit.label}</span>- <span className="text-xs sm:text-sm text-gray-400">- {remaining == null ? '—' : `${remaining}% left`}- </span>- </div>- <div className="h-2 rounded-full bg-port-bg overflow-hidden">- <div- className={`h-full rounded-full ${meterColor(limit.percentUsed)}`}- style={{ width: `${Math.min(100, Math.max(0, used))}%` }}- />- </div>- <div className="flex items-center justify-between mt-1">- <span className="text-[10px] sm:text-xs text-gray-500">{used}% used</span>- {limit.resetsAt && (- <span className="text-[10px] sm:text-xs text-gray-500 flex items-center gap-1">- <Clock size={11} /> resets {limit.resetsAt}- </span>- )}- </div>- </div>- );-}--// Claude Code SUBSCRIPTION rate-limit usage, parsed server-side from the CLI-// `/usage` output. Self-contained: owns its own fetch/loading/error state so it-// always renders (above the PortOS-internal token metrics below).-function ClaudeCodeUsagePanel() {- const [data, setData] = useState(null);- const [loading, setLoading] = useState(true);- const [error, setError] = useState(false);-- const load = async (refresh = false) => {- setLoading(true);- setError(false);- const result = await api.getClaudeCodeUsage({ refresh }).catch(() => null);- if (result) {- setData(result);- } else {- // Keep previously-loaded meters on a transient refresh failure instead of- // replacing them with the generic error state.- setError(true);- }- setLoading(false);- };-- useEffect(() => { load(); }, []);-- return (- <div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4">- <div className="flex items-center justify-between mb-3">- <h2 className="text-lg font-semibold text-white">Claude Code Subscription</h2>- <button- onClick={() => load(true)}- disabled={loading}- className="flex items-center gap-2 px-3 py-1.5 text-sm text-gray-400 hover:text-white disabled:opacity-50"- title="Refresh from the Claude Code CLI"- >- <RefreshCw size={15} className={loading ? 'animate-spin' : ''} /> Refresh- </button>- </div>-- {loading && !data && (- <div className="py-6"><BrailleSpinner text="Reading Claude Code usage" /></div>- )}-- {!loading && error && (- <div className="flex items-start gap-2 text-sm text-gray-400 py-2">- <AlertTriangle size={16} className="text-port-warning mt-0.5 shrink-0" />- <span>- {data- ? 'Couldn’t refresh Claude Code usage — showing the last successful reading.'- : <>Couldn’t read Claude Code usage. The <code className="text-gray-300">claude</code> CLI must be installed and signed in on this machine.</>}- </span>- </div>- )}-- {data && (- <div className="space-y-3">- {data.limits?.length > 0 ? (- <div>- {data.limits.map((limit) => (- <UsageMeter key={limit.key} limit={limit} />- ))}- </div>- ) : (- <div className="text-gray-500 text-sm">No rate-limit data reported</div>- )}-- {data.activity?.length > 0 && (- <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 pt-1">- {data.activity.map((a) => (- <div key={a.period} className="bg-port-bg border border-port-border rounded-lg p-3">- <div className="text-xs text-gray-400 mb-1">{a.period}</div>- <div className="text-sm text-white">- {formatCompactCount(a.requests)} requests- <span className="mx-2 text-gray-600">•</span>- {formatCompactCount(a.sessions)} sessions- </div>- </div>- ))}- </div>- )}-- {data.approximate && (- <p className="text-[10px] sm:text-xs text-gray-500">- Approximate — based on local sessions on this machine only; does not include other devices or claude.ai.- </p>- )}- </div>- )}</div>);}@@ -292,7 +485,7 @@ export function UsagePage() {return (<div className="space-y-6"><h1 className="text-2xl font-bold text-white">Usage</h1>- <ClaudeCodeUsagePanel />+ <ProviderQuotaSection /><InternalUsageMetrics /></div>);diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.jsindex 34a63e5446..2293dbc9e6 100644--- a/client/src/services/apiSystem.js+++ b/client/src/services/apiSystem.js@@ -89,11 +89,22 @@ export const patchSettingsSlice = async (slicePath, partial, options = {}) => {return updateSettings({ [segments[0]]: updated }, options);};-// Usage-export const getUsage = () => request('/usage');+// Usage. `params` selects the cost-report window: { period } (7d|30d|90d|all)+// or { from, to } (YYYY-MM-DD).+export const getUsage = (params = {}) => {+ const qs = new URLSearchParams(+ Object.entries(params).filter(([, v]) => v != null && v !== '')+ ).toString();+ return request(`/usage${qs ? `?${qs}` : ''}`);+};export const getUsageRaw = () => request('/usage/raw');export const resetUsage = () => request('/usage', { method: 'DELETE' });+// Subscription-quota status for every enabled provider family (claude, codex,+// agy, grok). Callers own their inline error UI — silent by default.+export const getProviderUsage = ({ refresh = false, ...options } = {}) =>+ request(`/usage/providers${refresh ? '?refresh=1' : ''}`, { silent: true, ...options });+// Claude Code subscription rate-limit usage (parsed from the CLI `/usage` output).// Callers own their own inline error UI, so default to silent to avoid a toast// on machines without the `claude` CLI.diff --git a/server/index.js b/server/index.jsindex 85b3fb5e58..1816f91e03 100644--- a/server/index.js+++ b/server/index.js@@ -5,7 +5,7 @@ import { dirname, join } from 'path';import { PATHS } from './lib/fileUtils.js';import { resolveInstallRoot } from './lib/dataRoot.js';import { PORTS } from './lib/ports.js';-import { estimateTokens } from './lib/contextBudget.js';+import { estimateTokens, CHARS_PER_TOKEN } from './lib/contextBudget.js';import { existsSync } from 'fs';import { createTailscaleServers } from '../lib/tailscale-https.js';import { certPaths } from '../lib/certPaths.js';@@ -292,7 +292,8 @@ const aiToolkitHooks = {},onRunCompleted: (metadata, output) => {const estimatedTokens = estimateTokens(output);- recordMessages(metadata.providerId, metadata.model, 1, estimatedTokens).catch(err => {+ const inputTokens = Math.ceil((metadata.promptLength || 0) / CHARS_PER_TOKEN);+ recordMessages(metadata.providerId, metadata.model, 1, estimatedTokens, inputTokens).catch(err => {console.error(`❌ Failed to record usage: ${err.message}`);});},diff --git a/server/lib/README.md b/server/lib/README.mdindex 49b45c5e3a..7df07e4785 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -96,6 +96,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `promptPartials.js` | Mustache-style partial expansion. || `mediaModels.js` | Single source of truth for image/video model metadata. || `providerModels.js` | Provider model resolution sentinels + helpers (`CODEX_CONFIGURED_DEFAULT` / `ANTIGRAVITY_CONFIGURED_DEFAULT` / `GROK_CONFIGURED_DEFAULT`, `resolveCliModel`, `filterSelectableModels`, Bedrock/OpenCode model mappers, model-flag scan helpers). |+| `modelPricing.js` | Per-model API billing rates for the /devtools/usage cost estimates — `resolveModelRates(providerId, model)` (exact → family regex → provider default → blended fallback, with a `matched` tier), `isFreeProvider` (ollama/lmstudio/`ollamaBacked`/localhost = free), `estimateCostUsd`, `PRICING_AS_OF`. Informational only (PortOS runs on subscriptions); excludes cache/batch/tier discounts. || `opencodeConfig.js` | OpenCode config builder — `buildOpencodeEnvVars(provider, model)` builds dynamic `OPENCODE_CONFIG_CONTENT` declaring the models map under `provider.ollama.models` (bare ids) for Ollama-backed OpenCode providers. Fixes --model rejection. || `cliProviderArgs.js` | Per-CLI argv conventions (`buildCliArgs`) for stdin prompt delivery — dependency-light extraction from runner.js so out-of-process callers (autofixer) can import it. || `cliProviderRun.js` | One-shot CLI provider invocation (`pickCliProvider` + `runCliProviderPrompt`) — lightweight path for the autofixer + calendar MCP sync to honor the configured provider/model. |diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.jsindex ba61f198b6..91b2c95e60 100644--- a/server/lib/aiToolkit/runner.js+++ b/server/lib/aiToolkit/runner.js@@ -350,6 +350,9 @@ export function createRunnerService(config = {}) {workspaceName,source,prompt: prompt.substring(0, 500),+ // Full prompt size (chars) — `prompt` above is truncated for display.+ // Hosts use this to estimate input-token usage on completion.+ promptLength: prompt.length,startTime: new Date().toISOString(),endTime: null,duration: null,diff --git a/server/lib/index.js b/server/lib/index.jsindex 80bba12390..5750b0cc60 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -194,6 +194,7 @@ export * from './localModelHeuristics.js';export * from './loraDataset.js';export * from './issueLength.js';export * from './mediaItemKey.js';+export * from './modelPricing.js';export * from './navManifest.js';export * from './personaTraitBlend.js';export * from './pipelineIssueOrder.js';diff --git a/server/lib/modelPricing.js b/server/lib/modelPricing.jsnew file mode 100644index 0000000000..c80a40165c--- /dev/null+++ b/server/lib/modelPricing.js@@ -0,0 +1,170 @@+/**+ * Per-model API billing rates for the "what would this have cost" estimates on+ * /devtools/usage. PortOS runs on provider subscriptions, so these numbers are+ * informational only — they answer "what would the recorded usage have cost+ * under API billing," never an actual bill.+ *+ * Rates are USD per 1M tokens (standard input/output only — prompt-caching,+ * batch, and long-context tier discounts are deliberately ignored; PortOS does+ * not capture cache hits, and the UI discloses the approximation). Verified+ * against the official pricing pages on PRICING_AS_OF:+ * - https://platform.claude.com/docs/en/about-claude/pricing+ * - https://developers.openai.com/api/docs/pricing+ * - https://docs.x.ai/docs/pricing+ * - https://ai.google.dev/gemini-api/docs/pricing+ *+ * Model ids arrive in many shapes (full ids, CLI sentinels like `opus`, the+ * `*-configured-default` sentinels from providerModels.js, Bedrock-prefixed+ * ids), so resolution is exact-id first, then ordered family regexes, then a+ * per-provider default, then a generic fallback — `matched` reports which tier+ * answered so the UI can flag approximate rows.+ */++export const PRICING_AS_OF = '2026-07-12';++/** USD per 1M tokens: [input, output]. Exact model-id matches. */+const EXACT_RATES = {+ // Anthropic+ 'claude-fable-5': [10.0, 50.0],+ 'claude-mythos-5': [10.0, 50.0],+ 'claude-opus-4-8': [5.0, 25.0],+ 'claude-opus-4-7': [5.0, 25.0],+ 'claude-opus-4-6': [5.0, 25.0],+ 'claude-opus-4-5': [5.0, 25.0],+ 'claude-sonnet-5': [2.0, 10.0], // intro pricing through 2026-08-31 ($3/$15 after)+ 'claude-sonnet-4-6': [3.0, 15.0],+ 'claude-sonnet-4-5': [3.0, 15.0],+ 'claude-haiku-4-5': [1.0, 5.0],+ // OpenAI (Codex CLI)+ 'gpt-5.6-sol': [5.0, 30.0],+ 'gpt-5.6-terra': [2.5, 15.0],+ 'gpt-5.6-luna': [1.0, 6.0],+ 'gpt-5.5': [5.0, 30.0],+ 'gpt-5.5-pro': [30.0, 180.0],+ 'gpt-5.4': [2.5, 15.0],+ 'gpt-5.4-mini': [0.75, 4.5],+ 'gpt-5.4-nano': [0.2, 1.25],+ 'gpt-5.3-codex': [1.75, 14.0],+ // xAI+ 'grok-4.5': [2.0, 6.0],+ 'grok-4.3': [1.25, 2.5],+ 'grok-build-0.1': [1.0, 2.0],+ // Google (Antigravity)+ 'gemini-3.1-pro-preview': [2.0, 12.0], // ≤200k-token tier+ 'gemini-3.5-flash': [1.5, 9.0],+ 'gemini-3.1-flash-lite': [0.25, 1.5],+ 'gemini-2.5-pro': [1.25, 10.0],+ 'gemini-2.5-flash': [0.3, 2.5],+ 'gemini-2.5-flash-lite': [0.1, 0.4],+};++/**+ * Ordered family rules — first regex that matches the model id wins. Covers+ * CLI shorthand (`opus`, `sonnet`), versioned ids the exact table doesn't+ * list, Bedrock-prefixed ids, and the `*-configured-default` sentinels (the+ * sentinel strings contain their provider family name).+ */+const FAMILY_RULES = [+ { test: /fable|mythos/i, rateModel: 'claude-fable-5' },+ { test: /opus/i, rateModel: 'claude-opus-4-8' },+ { test: /sonnet[-.]?5/i, rateModel: 'claude-sonnet-5' },+ { test: /sonnet/i, rateModel: 'claude-sonnet-4-5' },+ { test: /haiku/i, rateModel: 'claude-haiku-4-5' },+ { test: /gpt-5\.6-sol/i, rateModel: 'gpt-5.6-sol' },+ { test: /gpt-5\.6-terra/i, rateModel: 'gpt-5.6-terra' },+ { test: /gpt-5\.6-luna/i, rateModel: 'gpt-5.6-luna' },+ { test: /codex/i, rateModel: 'gpt-5.3-codex' },+ { test: /gpt-5\.5-pro/i, rateModel: 'gpt-5.5-pro' },+ { test: /gpt-5\.4-mini/i, rateModel: 'gpt-5.4-mini' },+ { test: /gpt-5\.4-nano/i, rateModel: 'gpt-5.4-nano' },+ { test: /gpt/i, rateModel: 'gpt-5.4' },+ { test: /grok-build/i, rateModel: 'grok-build-0.1' },+ { test: /grok-4\.(3|20)/i, rateModel: 'grok-4.3' },+ { test: /grok/i, rateModel: 'grok-4.5' },+ { test: /gemini-3\.5-flash/i, rateModel: 'gemini-3.5-flash' },+ { test: /gemini-2\.5-pro/i, rateModel: 'gemini-2.5-pro' },+ { test: /gemini-2\.5-flash-lite/i, rateModel: 'gemini-2.5-flash-lite' },+ { test: /gemini-2\.5-flash/i, rateModel: 'gemini-2.5-flash' },+ { test: /gemini|antigravity/i, rateModel: 'gemini-3.1-pro-preview' },+];++/** Per-provider default when the model id resolves to no known family. */+const PROVIDER_DEFAULT_RULES = [+ { test: /claude/i, rateModel: 'claude-sonnet-4-5' },+ { test: /codex|openai/i, rateModel: 'gpt-5.3-codex' },+ { test: /grok|xai/i, rateModel: 'grok-4.5' },+ { test: /antigravity|agy|gemini|google/i, rateModel: 'gemini-3.1-pro-preview' },+];++// Legacy blended estimate (the old flat usage.js rate) — the last resort for a+// provider/model pair nothing above recognizes.+const FALLBACK_RATES = { rateModel: null, inputPer1M: 3.0, outputPer1M: 15.0 };++const toRates = (rateModel) => ({+ rateModel,+ inputPer1M: EXACT_RATES[rateModel][0],+ outputPer1M: EXACT_RATES[rateModel][1],+});++/**+ * Resolve billing rates for a (providerId, model) pair.+ * @param {string|null|undefined} providerId+ * @param {string|null|undefined} model+ * @returns {{ rateModel: string|null, inputPer1M: number, outputPer1M: number,+ * matched: 'exact'|'family'|'providerDefault'|'fallback' }}+ */+export function resolveModelRates(providerId, model) {+ const id = typeof model === 'string' ? model.trim() : '';+ if (id && EXACT_RATES[id]) {+ return { ...toRates(id), matched: 'exact' };+ }+ if (id) {+ for (const rule of FAMILY_RULES) {+ if (rule.test.test(id)) {+ return { ...toRates(rule.rateModel), matched: 'family' };+ }+ }+ }+ const pid = typeof providerId === 'string' ? providerId : '';+ for (const rule of PROVIDER_DEFAULT_RULES) {+ if (rule.test.test(pid)) {+ return { ...toRates(rule.rateModel), matched: 'providerDefault' };+ }+ }+ return { ...FALLBACK_RATES, matched: 'fallback' };+}++const LOCALHOST_ENDPOINT = /^https?:\/\/(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(:|\/|$)/i;+const FREE_ID = /ollama|lmstudio|lm-studio/i;++/**+ * True when a provider's usage is free — local inference (Ollama, LM Studio,+ * any `ollamaBacked` CLI wrapper, or an API provider pointed at localhost).+ * Accepts a provider config object or a bare provider-id string (usage records+ * can outlive their provider config).+ * @param {object|string|null|undefined} providerOrId+ * @returns {boolean}+ */+export function isFreeProvider(providerOrId) {+ if (providerOrId == null) return false;+ if (typeof providerOrId === 'string') return FREE_ID.test(providerOrId);+ const p = providerOrId;+ if (p.ollamaBacked === true) return true;+ if (FREE_ID.test(p.id || '') || FREE_ID.test(p.command || '')) return true;+ if (typeof p.endpoint === 'string' && LOCALHOST_ENDPOINT.test(p.endpoint)) return true;+ return false;+}++/**+ * Estimated USD cost for a token count under the given rates. Returns the raw+ * float — callers round for display.+ * @param {number} tokensIn+ * @param {number} tokensOut+ * @param {{inputPer1M: number, outputPer1M: number}} rates+ * @returns {number}+ */+export function estimateCostUsd(tokensIn, tokensOut, rates) {+ const input = ((tokensIn || 0) / 1_000_000) * (rates?.inputPer1M || 0);+ const output = ((tokensOut || 0) / 1_000_000) * (rates?.outputPer1M || 0);+ return input + output;+}diff --git a/server/lib/modelPricing.test.js b/server/lib/modelPricing.test.jsnew file mode 100644index 0000000000..dfc8d21778--- /dev/null+++ b/server/lib/modelPricing.test.js@@ -0,0 +1,91 @@+import { describe, it, expect } from 'vitest';+import { resolveModelRates, isFreeProvider, estimateCostUsd, PRICING_AS_OF } from './modelPricing.js';++describe('resolveModelRates', () => {+ it('matches exact model ids', () => {+ const r = resolveModelRates('claude-code', 'claude-opus-4-8');+ expect(r).toMatchObject({ rateModel: 'claude-opus-4-8', inputPer1M: 5, outputPer1M: 25, matched: 'exact' });+ });++ it('resolves CLI shorthand model names via family rules', () => {+ expect(resolveModelRates('claude-code', 'opus')).toMatchObject({ rateModel: 'claude-opus-4-8', matched: 'family' });+ expect(resolveModelRates('claude-code', 'sonnet')).toMatchObject({ rateModel: 'claude-sonnet-4-5', matched: 'family' });+ expect(resolveModelRates('claude-code', 'haiku')).toMatchObject({ rateModel: 'claude-haiku-4-5', matched: 'family' });+ });++ it('resolves fable/mythos to the Claude 5 flagship rates', () => {+ expect(resolveModelRates('claude-code', 'claude-fable-5')).toMatchObject({ inputPer1M: 10, outputPer1M: 50 });+ expect(resolveModelRates('claude-code', 'fable')).toMatchObject({ rateModel: 'claude-fable-5', matched: 'family' });+ });++ it('resolves Bedrock-prefixed ids through family rules', () => {+ const r = resolveModelRates('claude-code-bedrock', 'global.anthropic.claude-opus-4-8');+ expect(r).toMatchObject({ rateModel: 'claude-opus-4-8', matched: 'family' });+ });++ it('resolves configured-default sentinels to their provider family', () => {+ expect(resolveModelRates('codex', 'codex-configured-default')).toMatchObject({ rateModel: 'gpt-5.3-codex', matched: 'family' });+ expect(resolveModelRates('grok', 'grok-configured-default')).toMatchObject({ rateModel: 'grok-4.5', matched: 'family' });+ expect(resolveModelRates('antigravity-cli', 'antigravity-configured-default')).toMatchObject({ rateModel: 'gemini-3.1-pro-preview', matched: 'family' });+ });++ it('resolves suffixed gpt-5.6 ids to their base rates', () => {+ expect(resolveModelRates('codex', 'gpt-5.6-terra-2026-06-01')).toMatchObject({ rateModel: 'gpt-5.6-terra', matched: 'family' });+ });++ it('falls back to a provider default when the model is unknown', () => {+ const r = resolveModelRates('claude-code', 'my-custom-alias');+ expect(r).toMatchObject({ rateModel: 'claude-sonnet-4-5', matched: 'providerDefault' });+ });++ it('falls back to the generic blended rate when nothing matches', () => {+ const r = resolveModelRates('mystery-provider', 'mystery-model');+ expect(r).toMatchObject({ rateModel: null, inputPer1M: 3, outputPer1M: 15, matched: 'fallback' });+ });++ it('handles null/undefined inputs without throwing', () => {+ expect(resolveModelRates(null, null).matched).toBe('fallback');+ expect(resolveModelRates(undefined, undefined).matched).toBe('fallback');+ });++ it('exposes the verification date', () => {+ expect(PRICING_AS_OF).toMatch(/^\d{4}-\d{2}-\d{2}$/);+ });+});++describe('isFreeProvider', () => {+ it('classifies ollama and lmstudio ids as free (object and string forms)', () => {+ expect(isFreeProvider('ollama')).toBe(true);+ expect(isFreeProvider('lmstudio')).toBe(true);+ expect(isFreeProvider({ id: 'ollama', type: 'api' })).toBe(true);+ });++ it('classifies ollamaBacked CLI wrappers as free', () => {+ expect(isFreeProvider({ id: 'claude-ollama', ollamaBacked: true, command: 'claude' })).toBe(true);+ });++ it('classifies localhost API endpoints as free', () => {+ expect(isFreeProvider({ id: 'my-local', type: 'api', endpoint: 'http://localhost:1234/v1' })).toBe(true);+ expect(isFreeProvider({ id: 'my-local', type: 'api', endpoint: 'http://127.0.0.1:11434/v1' })).toBe(true);+ });++ it('does not classify paid providers as free', () => {+ expect(isFreeProvider({ id: 'claude-code', type: 'cli', command: 'claude' })).toBe(false);+ expect(isFreeProvider({ id: 'grok', type: 'api', endpoint: 'https://api.x.ai/v1' })).toBe(false);+ expect(isFreeProvider('codex')).toBe(false);+ expect(isFreeProvider(null)).toBe(false);+ });+});++describe('estimateCostUsd', () => {+ it('computes input + output cost per 1M tokens', () => {+ const rates = { inputPer1M: 3, outputPer1M: 15 };+ expect(estimateCostUsd(1_000_000, 1_000_000, rates)).toBeCloseTo(18);+ expect(estimateCostUsd(500_000, 0, rates)).toBeCloseTo(1.5);+ });++ it('treats missing counts and rates as zero', () => {+ expect(estimateCostUsd(null, undefined, { inputPer1M: 3, outputPer1M: 15 })).toBe(0);+ expect(estimateCostUsd(1000, 1000, null)).toBe(0);+ });+});diff --git a/server/lib/validation.js b/server/lib/validation.jsindex bab2bfd557..ad3bf46143 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -615,6 +615,22 @@ export const scaffoldSchema = z.object({githubOrg: z.preprocess(emptyToNull, z.string().min(1).nullable().optional())});+// =============================================================================+// USAGE (devtools usage reports)+// =============================================================================++const isoDay = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Expected YYYY-MM-DD');++/**+ * Query params for GET /api/usage — either a preset period or an explicit+ * from/to date range (inclusive, YYYY-MM-DD). Explicit dates win over period.+ */+export const usageQuerySchema = z.object({+ period: z.enum(['7d', '30d', '90d', 'all']).optional(),+ from: isoDay.optional(),+ to: isoDay.optional()+}).refine((q) => !(q.from && q.to) || q.from <= q.to, { message: 'from must be on or before to' });+/*** Validate data against a Zod schema, throwing on failure.* Returns parsed data on success, throws ServerError on failure.diff --git a/server/routes/usage.js b/server/routes/usage.jsindex f9e4663705..5375572067 100644--- a/server/routes/usage.js+++ b/server/routes/usage.js@@ -1,19 +1,51 @@import { Router } from 'express';import * as usage from '../services/usage.js';import { getClaudeCodeUsage } from '../services/claudeCodeUsage.js';+import { getProviderQuotas } from '../services/providerUsage.js';+import { getAllProviders } from '../services/providers.js';import { asyncHandler } from '../lib/errorHandler.js';+import { validateRequest, usageQuerySchema } from '../lib/validation.js';const router = Router();-// GET /api/usage - Get usage summary+const PERIOD_DAYS = { '7d': 7, '30d': 30, '90d': 90 };++/**+ * Resolve validated query params to an inclusive { from, to } date range+ * (YYYY-MM-DD, null = unbounded). Explicit from/to win; otherwise a preset+ * period counting back from today (default 7d, matching the page's charts).+ */+export function resolveUsageRange({ period, from, to } = {}) {+ if (from || to) return { from: from || null, to: to || null };+ if (period === 'all') return { from: null, to: null };+ const days = PERIOD_DAYS[period] || PERIOD_DAYS['7d'];+ const start = new Date();+ start.setDate(start.getDate() - (days - 1));+ return { from: start.toISOString().split('T')[0], to: null };+}++// GET /api/usage - Usage summary + cost report. Accepts ?period=7d|30d|90d|all+// or an explicit ?from/?to (YYYY-MM-DD, inclusive) for the report window.router.get('/', asyncHandler(async (req, res) => {- const summary = usage.getUsageSummary();+ const query = validateRequest(usageQuerySchema, req.query);+ const { from, to } = resolveUsageRange(query);+ const providers = await getAllProviders();+ const summary = usage.getUsageSummary({ from, to, providers });res.json(summary);}));+// GET /api/usage/providers - Subscription-quota status for every enabled+// provider family (claude, codex, agy, grok). Providers without a queryable+// usage surface report `supported: false`. `?refresh=1` bypasses the cache.+router.get('/providers', asyncHandler(async (req, res) => {+ const refresh = req.query.refresh === '1' || req.query.refresh === 'true';+ const providers = await getProviderQuotas({ refresh });+ res.json({ providers });+}));+// GET /api/usage/claude-code - Claude Code SUBSCRIPTION rate-limit usage,-// parsed from the CLI's `/usage` output. Distinct from the PortOS-internal-// token accounting above. `?refresh=1` bypasses the 60s cache.+// parsed from the CLI's `/usage` output. Kept for back-compat — the usage page+// now reads the generalized /providers endpoint. `?refresh=1` bypasses cache.router.get('/claude-code', asyncHandler(async (req, res) => {const refresh = req.query.refresh === '1' || req.query.refresh === 'true';const data = await getClaudeCodeUsage({ refresh });@@ -35,8 +67,8 @@ router.post('/session', asyncHandler(async (req, res) => {// POST /api/usage/messages - Record messagesrouter.post('/messages', asyncHandler(async (req, res) => {- const { providerId, model, messageCount, tokenCount } = req.body;- await usage.recordMessages(providerId, model, messageCount, tokenCount);+ const { providerId, model, messageCount, tokenCount, inputTokenCount } = req.body;+ await usage.recordMessages(providerId, model, messageCount, tokenCount, inputTokenCount || 0);res.json({ success: true });}));diff --git a/server/routes/usage.test.js b/server/routes/usage.test.jsindex 44913aecbb..4b95116193 100644--- a/server/routes/usage.test.js+++ b/server/routes/usage.test.js@@ -12,8 +12,22 @@ vi.mock('../services/usage.js', () => ({resetUsage: vi.fn()}));+vi.mock('../services/providers.js', () => ({+ getAllProviders: vi.fn().mockResolvedValue([])+}));++vi.mock('../services/providerUsage.js', () => ({+ getProviderQuotas: vi.fn()+}));++vi.mock('../services/claudeCodeUsage.js', () => ({+ getClaudeCodeUsage: vi.fn()+}));+import * as usage from '../services/usage.js';-import usageRoutes from './usage.js';+import { getAllProviders } from '../services/providers.js';+import { getProviderQuotas } from '../services/providerUsage.js';+import usageRoutes, { resolveUsageRange } from './usage.js';const buildApp = () => {const app = express();@@ -28,11 +42,75 @@ describe('usage routes', () => {vi.clearAllMocks();});- it('GET /api/usage returns the usage summary', async () => {+ it('GET /api/usage returns the usage summary with the default 7d range', async () => {usage.getUsageSummary.mockReturnValue({ totalSessions: 4, providers: ['anthropic'] });const res = await request(buildApp()).get('/api/usage');expect(res.status).toBe(200);expect(res.body).toEqual({ totalSessions: 4, providers: ['anthropic'] });+ const arg = usage.getUsageSummary.mock.calls[0][0];+ expect(arg.from).toMatch(/^\d{4}-\d{2}-\d{2}$/);+ expect(arg.to).toBeNull();+ expect(arg.providers).toEqual([]);+ });++ it('GET /api/usage passes an explicit from/to range through', async () => {+ usage.getUsageSummary.mockReturnValue({});+ getAllProviders.mockResolvedValue([{ id: 'ollama' }]);+ const res = await request(buildApp()).get('/api/usage?from=2026-01-01&to=2026-02-01');+ expect(res.status).toBe(200);+ expect(usage.getUsageSummary).toHaveBeenCalledWith({+ from: '2026-01-01',+ to: '2026-02-01',+ providers: [{ id: 'ollama' }]+ });+ });++ it('GET /api/usage resolves period=all to an unbounded range', async () => {+ usage.getUsageSummary.mockReturnValue({});+ const res = await request(buildApp()).get('/api/usage?period=all');+ expect(res.status).toBe(200);+ expect(usage.getUsageSummary.mock.calls[0][0]).toMatchObject({ from: null, to: null });+ });++ it('GET /api/usage rejects a malformed date', async () => {+ const res = await request(buildApp()).get('/api/usage?from=01-01-2026');+ expect(res.status).toBe(400);+ expect(usage.getUsageSummary).not.toHaveBeenCalled();+ });++ it('GET /api/usage rejects from after to', async () => {+ const res = await request(buildApp()).get('/api/usage?from=2026-03-01&to=2026-01-01');+ expect(res.status).toBe(400);+ });++ it('GET /api/usage rejects an unknown period', async () => {+ const res = await request(buildApp()).get('/api/usage?period=14d');+ expect(res.status).toBe(400);+ });++ it('GET /api/usage/providers returns quota entries and honors refresh', async () => {+ getProviderQuotas.mockResolvedValue([+ { family: 'claude', supported: true, limits: [] },+ { family: 'grok', supported: false, limits: [] }+ ]);+ const res = await request(buildApp()).get('/api/usage/providers?refresh=1');+ expect(res.status).toBe(200);+ expect(res.body.providers).toHaveLength(2);+ expect(getProviderQuotas).toHaveBeenCalledWith({ refresh: true });+ });++ describe('resolveUsageRange', () => {+ it('counts period days back from today inclusive', () => {+ const { from, to } = resolveUsageRange({ period: '30d' });+ const expected = new Date();+ expected.setDate(expected.getDate() - 29);+ expect(from).toBe(expected.toISOString().split('T')[0]);+ expect(to).toBeNull();+ });++ it('lets explicit dates win over period', () => {+ expect(resolveUsageRange({ period: '90d', from: '2026-01-01' })).toEqual({ from: '2026-01-01', to: null });+ });});it('GET /api/usage/raw returns the raw usage data', async () => {@@ -59,7 +137,15 @@ describe('usage routes', () => {.send({ providerId: 'p1', model: 'm', messageCount: 3, tokenCount: 1000 });expect(res.status).toBe(200);expect(res.body).toEqual({ success: true });- expect(usage.recordMessages).toHaveBeenCalledWith('p1', 'm', 3, 1000);+ expect(usage.recordMessages).toHaveBeenCalledWith('p1', 'm', 3, 1000, 0);+ });++ it('POST /api/usage/messages passes an input token count through', async () => {+ usage.recordMessages.mockResolvedValue();+ await request(buildApp())+ .post('/api/usage/messages')+ .send({ providerId: 'p1', model: 'm', messageCount: 1, tokenCount: 100, inputTokenCount: 400 });+ expect(usage.recordMessages).toHaveBeenCalledWith('p1', 'm', 1, 100, 400);});it('POST /api/usage/tokens defaults missing token counts to 0', async () => {diff --git a/server/services/agentRunTracking.js b/server/services/agentRunTracking.jsindex a512ff5021..45560f9ab3 100644--- a/server/services/agentRunTracking.js+++ b/server/services/agentRunTracking.js@@ -10,7 +10,7 @@ import { v4 as uuidv4 } from '../lib/uuid.js';import { recordSession, recordMessages } from './usage.js';import { bufferedSpawn } from '../lib/bufferedSpawn.js';import { atomicWrite, ensureDir, pathExists, readJSONFile, PATHS } from '../lib/fileUtils.js';-import { estimateTokens } from '../lib/contextBudget.js';+import { estimateTokens, CHARS_PER_TOKEN } from '../lib/contextBudget.js';const RUNS_DIR = PATHS.runs;@@ -37,6 +37,9 @@ export async function createAgentRun(agentId, task, model, provider, workspacePaworkspacePath,workspaceName: appName || 'portos',prompt: (task.description || '').substring(0, 500),+ // Full prompt size (chars) for input-token estimation on completion —+ // `prompt` above is truncated for display.+ promptLength: (task.description || '').length,startTime: new Date().toISOString(),endTime: null,duration: null,@@ -131,10 +134,11 @@ export async function completeAgentRun(runId, output, exitCode, duration, errorAawait atomicWrite(metaPath, metadata);await writeFile(join(runDir, 'output.txt'), output || '');- // Record usage for successful CoS agent runs (token count is estimated)+ // Record usage for successful CoS agent runs (token counts are estimated)if (exitCode === 0 && metadata.providerId && metadata.model) {const estimatedTokens = estimateTokens(output);- recordMessages(metadata.providerId, metadata.model, 1, estimatedTokens).catch(err => {+ const inputTokens = Math.ceil((metadata.promptLength || 0) / CHARS_PER_TOKEN);+ recordMessages(metadata.providerId, metadata.model, 1, estimatedTokens, inputTokens).catch(err => {console.error(`❌ Failed to record usage: ${err.message}`);});}diff --git a/server/services/providerUsage.js b/server/services/providerUsage.jsnew file mode 100644index 0000000000..52885a9e29--- /dev/null+++ b/server/services/providerUsage.js@@ -0,0 +1,277 @@+import { open, readdir, readFile, stat } from 'fs/promises';+import { homedir } from 'os';+import { join } from 'path';+import { getAllProviders } from './providers.js';+import { getClaudeCodeUsage } from './claudeCodeUsage.js';+import { commandBasename, isClaudeCommand } from '../lib/providerModels.js';++/**+ * Provider subscription-quota adapters for /devtools/usage — one card per+ * enabled provider *family* (claude, codex, agy, grok), each answering "how+ * much usage do I have left." Every adapter returns the common shape:+ *+ * { family, label, supported, plan?, limits[], activity[], approximate,+ * fetchedAt, note?, error? }+ *+ * `supported: false` means the provider has no queryable usage surface at all+ * (the UI renders a muted "not available" note, never an error). A supported+ * adapter that fails transiently returns `error` instead of throwing so one+ * broken CLI can't 500 the whole endpoint.+ *+ * AI Provider Usage Policy: these fetches run only on user request from the+ * usage page — never at server boot — and none of them consume tokens (the+ * Claude `/usage` print-mode call is 0-token; the Codex adapter only reads+ * local session logs).+ */++const CACHE_TTL_MS = 60_000;++// family -> { data, at }+const cache = new Map();+// family -> Promise (single-flight)+const inflight = new Map();++// --- Codex: parse rate-limit telemetry out of local session logs -----------+//+// The Codex CLI has no queryable usage command, but every session appends+// `token_count` events carrying `rate_limits` (used %, window minutes, reset+// epoch, plan type) to its rollout log. Reading the newest event costs zero+// tokens; the numbers are "as of the last Codex session activity."++const CODEX_SCAN_FILE_LIMIT = 15;+const CODEX_TAIL_BYTES = 256 * 1024;++const codexHomeDir = () => process.env.CODEX_HOME || join(homedir(), '.codex');++function humanizeWindowMinutes(minutes) {+ if (!Number.isFinite(minutes)) return 'window';+ if (minutes % 10080 === 0) return minutes === 10080 ? 'week' : `${minutes / 10080} weeks`;+ if (minutes % 1440 === 0) return minutes === 1440 ? 'day' : `${minutes / 1440} days`;+ if (minutes % 60 === 0) return `${minutes / 60}h window`;+ return `${minutes}m window`;+}++/**+ * Pure: extract the newest `rate_limits` payload from rollout-JSONL content.+ * Scans lines from the end. Returns `{ rateLimits, timestamp }` or null.+ * Exported for tests.+ */+export function parseCodexRateLimits(jsonlText) {+ const lines = String(jsonlText || '').split('\n');+ for (let i = lines.length - 1; i >= 0; i--) {+ const line = lines[i];+ if (!line.includes('"rate_limits"')) continue;+ let parsed;+ try {+ parsed = JSON.parse(line);+ } catch {+ continue; // tail-read can clip the oldest line in the chunk mid-JSON+ }+ const rateLimits = parsed?.payload?.rate_limits ?? parsed?.rate_limits;+ if (rateLimits && typeof rateLimits === 'object') {+ return { rateLimits, timestamp: parsed.timestamp || null };+ }+ }+ return null;+}++function codexLimitEntry(scopeKey, window) {+ if (!window || typeof window.used_percent !== 'number') return null;+ const windowLabel = humanizeWindowMinutes(window.window_minutes);+ const percentUsed = Math.round(window.used_percent);+ return {+ key: scopeKey,+ label: `Current ${windowLabel}`,+ scope: scopeKey,+ model: null,+ percentUsed,+ percentRemaining: Math.max(0, 100 - percentUsed),+ resetsAt: Number.isFinite(window.resets_at) ? new Date(window.resets_at * 1000).toISOString() : null,+ timezone: null+ };+}++/**+ * Pure: map a codex `rate_limits` payload + event timestamp to the common+ * quota shape. Exported for tests.+ */+export function mapCodexQuota(rateLimits, timestamp) {+ const limits = [+ codexLimitEntry('session', rateLimits.primary),+ codexLimitEntry('week', rateLimits.secondary)+ ].filter(Boolean);+ return {+ family: 'codex',+ label: 'Codex',+ supported: true,+ plan: rateLimits.plan_type || 'unknown',+ limits,+ activity: [],+ approximate: true,+ note: timestamp+ ? `As of the last Codex session activity (${timestamp}). Local telemetry only.`+ : 'As of the last Codex session activity. Local telemetry only.',+ fetchedAt: new Date().toISOString()+ };+}++/** Newest-first rollout log paths under <codexHome>/sessions (bounded scan). */+async function listCodexRolloutFiles(codexHome) {+ const sessionsDir = join(codexHome, 'sessions');+ const files = [];+ const walk = async (dir) => {+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);+ for (const entry of entries) {+ const p = join(dir, entry.name);+ if (entry.isDirectory()) await walk(p);+ else if (entry.name.startsWith('rollout-') && entry.name.endsWith('.jsonl')) files.push(p);+ }+ };+ await walk(sessionsDir);+ const withTimes = await Promise.all(+ files.map(async (f) => ({ f, mtime: (await stat(f).catch(() => null))?.mtimeMs || 0 }))+ );+ return withTimes.sort((a, b) => b.mtime - a.mtime).slice(0, CODEX_SCAN_FILE_LIMIT).map((e) => e.f);+}++async function readFileTail(file, bytes) {+ const info = await stat(file);+ if (info.size <= bytes) return readFile(file, 'utf-8');+ const handle = await open(file, 'r');+ const buffer = Buffer.alloc(bytes);+ await handle.read(buffer, 0, bytes, info.size - bytes);+ await handle.close();+ return buffer.toString('utf-8');+}++async function fetchCodexQuota({ codexHome = codexHomeDir() } = {}) {+ const files = await listCodexRolloutFiles(codexHome);+ for (const file of files) {+ const tail = await readFileTail(file, CODEX_TAIL_BYTES).catch(() => null);+ if (!tail) continue;+ const found = parseCodexRateLimits(tail);+ if (found) return mapCodexQuota(found.rateLimits, found.timestamp);+ }+ return {+ family: 'codex',+ label: 'Codex',+ supported: true,+ plan: 'unknown',+ limits: [],+ activity: [],+ approximate: true,+ fetchedAt: new Date().toISOString(),+ error: files.length+ ? 'No rate-limit telemetry found in recent Codex session logs.'+ : 'No Codex session logs found — run Codex once to populate usage telemetry.'+ };+}++// --- Claude: wrap the existing /usage CLI parser ---------------------------++async function fetchClaudeQuota({ refresh = false } = {}) {+ const data = await getClaudeCodeUsage({ refresh });+ return {+ family: 'claude',+ label: 'Claude Code',+ supported: true,+ plan: data.plan,+ limits: data.limits,+ activity: data.activity,+ approximate: data.approximate,+ note: data.approximate ? 'Local sessions only — does not include other devices or claude.ai.' : null,+ fetchedAt: data.fetchedAt+ };+}++// --- Unsupported families ---------------------------------------------------++const unsupported = (family, label, reason) => async () => ({+ family,+ label,+ supported: false,+ limits: [],+ activity: [],+ approximate: false,+ note: reason,+ fetchedAt: new Date().toISOString()+});++// --- Family registry --------------------------------------------------------++/**+ * A provider config belongs to at most one family. CLI/TUI commands are+ * matched by binary basename; the Grok/Kimi-style API providers by id or+ * endpoint. Ollama-backed CLI wrappers are local/free and have no+ * subscription quota, so they map to no family.+ */+const FAMILIES = [+ {+ id: 'claude',+ label: 'Claude Code',+ matches: (p) => (p.type === 'cli' || p.type === 'tui') && !p.ollamaBacked && isClaudeCommand(p.command),+ fetch: fetchClaudeQuota+ },+ {+ id: 'codex',+ label: 'Codex',+ matches: (p) => commandBasename(p.command) === 'codex',+ fetch: () => fetchCodexQuota()+ },+ {+ id: 'agy',+ label: 'Antigravity',+ matches: (p) => commandBasename(p.command) === 'agy' || /antigravity/i.test(p.id || ''),+ fetch: unsupported('agy', 'Antigravity', 'The Antigravity CLI does not expose usage or quota telemetry.')+ },+ {+ id: 'grok',+ label: 'Grok',+ matches: (p) => commandBasename(p.command) === 'grok' || /grok/i.test(p.id || ''),+ fetch: unsupported('grok', 'Grok', 'The Grok CLI and xAI API do not expose remaining-quota telemetry.')+ }+];++/** Distinct quota families among the enabled providers, in registry order. */+export function resolveEnabledFamilies(providers) {+ const enabled = (providers || []).filter((p) => p?.enabled);+ return FAMILIES.filter((family) => enabled.some((p) => family.matches(p)));+}++async function fetchFamilyQuota(family, { refresh }) {+ if (!refresh && cache.has(family.id) && Date.now() - cache.get(family.id).at < CACHE_TTL_MS) {+ return cache.get(family.id).data;+ }+ if (inflight.has(family.id)) return inflight.get(family.id);++ const run = Promise.resolve(family.fetch({ refresh }))+ .then((data) => {+ cache.set(family.id, { data, at: Date.now() });+ return data;+ })+ .catch((err) => ({+ family: family.id,+ label: family.label,+ supported: true,+ limits: [],+ activity: [],+ approximate: false,+ fetchedAt: new Date().toISOString(),+ error: err?.message || String(err)+ }))+ .finally(() => inflight.delete(family.id));++ inflight.set(family.id, run);+ return run;+}++/**+ * Quota status for every enabled provider family. `refresh: true` bypasses+ * the per-family 60s cache. Never rejects — per-family failures surface as+ * `error` entries.+ */+export async function getProviderQuotas({ refresh = false } = {}) {+ const providers = await getAllProviders();+ const families = resolveEnabledFamilies(providers);+ return Promise.all(families.map((family) => fetchFamilyQuota(family, { refresh })));+}diff --git a/server/services/providerUsage.test.js b/server/services/providerUsage.test.jsnew file mode 100644index 0000000000..ac1e86ffb7--- /dev/null+++ b/server/services/providerUsage.test.js@@ -0,0 +1,99 @@+import { describe, it, expect, vi } from 'vitest';++// providerUsage imports the provider config service (toolkit-backed) and the+// claude CLI wrapper — mock both so this suite stays hermetic.+vi.mock('./providers.js', () => ({+ getAllProviders: vi.fn().mockResolvedValue([])+}));+vi.mock('./claudeCodeUsage.js', () => ({+ getClaudeCodeUsage: vi.fn()+}));++import { parseCodexRateLimits, mapCodexQuota, resolveEnabledFamilies } from './providerUsage.js';++// Synthetic rollout line matching the codex event_msg/token_count shape —+// invented values only, never a transcript from a real session.+const codexLine = (rateLimits, timestamp = '2026-01-01T00:00:00.000Z') =>+ JSON.stringify({ timestamp, type: 'event_msg', payload: { type: 'token_count', info: {}, rate_limits: rateLimits } });++const SAMPLE_RATE_LIMITS = {+ limit_id: 'codex',+ primary: { used_percent: 7.0, window_minutes: 300, resets_at: 1767225600 },+ secondary: { used_percent: 26.0, window_minutes: 10080, resets_at: 1767830400 },+ plan_type: 'pro'+};++describe('parseCodexRateLimits', () => {+ it('returns the newest rate_limits event in the log', () => {+ const older = codexLine({ ...SAMPLE_RATE_LIMITS, primary: { ...SAMPLE_RATE_LIMITS.primary, used_percent: 3 } }, '2026-01-01T00:00:00Z');+ const newer = codexLine(SAMPLE_RATE_LIMITS, '2026-01-02T00:00:00Z');+ const text = [older, '{"type":"other"}', newer, '{"type":"trailing"}'].join('\n');+ const found = parseCodexRateLimits(text);+ expect(found.timestamp).toBe('2026-01-02T00:00:00Z');+ expect(found.rateLimits.primary.used_percent).toBe(7);+ });++ it('skips a clipped (unparseable) line and keeps scanning', () => {+ const clipped = codexLine(SAMPLE_RATE_LIMITS).slice(20); // broken head from a tail-read+ const good = codexLine(SAMPLE_RATE_LIMITS);+ // clipped line is NEWER (later in file) — parser must fall back to the good one+ expect(parseCodexRateLimits([good, clipped].join('\n'))).not.toBeNull();+ });++ it('returns null when no rate_limits event exists', () => {+ expect(parseCodexRateLimits('{"type":"event_msg","payload":{"type":"agent_message"}}')).toBeNull();+ expect(parseCodexRateLimits('')).toBeNull();+ });+});++describe('mapCodexQuota', () => {+ it('maps primary/secondary windows to the common limit shape', () => {+ const quota = mapCodexQuota(SAMPLE_RATE_LIMITS, '2026-01-02T00:00:00Z');+ expect(quota).toMatchObject({ family: 'codex', supported: true, plan: 'pro', approximate: true });+ expect(quota.limits).toHaveLength(2);+ expect(quota.limits[0]).toMatchObject({ key: 'session', label: 'Current 5h window', percentUsed: 7, percentRemaining: 93 });+ expect(quota.limits[1]).toMatchObject({ key: 'week', label: 'Current week', percentUsed: 26, percentRemaining: 74 });+ expect(quota.limits[0].resetsAt).toBe(new Date(1767225600 * 1000).toISOString());+ expect(quota.note).toContain('2026-01-02T00:00:00Z');+ });++ it('omits windows with no usable used_percent', () => {+ const quota = mapCodexQuota({ primary: { used_percent: 50, window_minutes: 300 }, secondary: null, plan_type: null }, null);+ expect(quota.limits).toHaveLength(1);+ expect(quota.plan).toBe('unknown');+ });+});++describe('resolveEnabledFamilies', () => {+ const providers = [+ { id: 'claude-code', enabled: true, type: 'cli', command: 'claude' },+ { id: 'claude-code-tui', enabled: true, type: 'tui', command: 'claude' },+ { id: 'claude-ollama', enabled: true, type: 'cli', command: 'claude', ollamaBacked: true },+ { id: 'codex', enabled: true, type: 'cli', command: 'codex' },+ { id: 'antigravity-cli', enabled: false, type: 'cli', command: 'agy' },+ { id: 'grok', enabled: true, type: 'api', endpoint: 'https://api.x.ai/v1' },+ { id: 'ollama', enabled: true, type: 'api', endpoint: 'http://localhost:11434/v1' }+ ];++ it('dedupes CLI+TUI variants into one family and skips disabled providers', () => {+ const families = resolveEnabledFamilies(providers).map((f) => f.id);+ expect(families).toEqual(['claude', 'codex', 'grok']); // agy disabled; ollama maps to no family+ });++ it('does not map ollama-backed claude wrappers to the claude family', () => {+ const families = resolveEnabledFamilies([+ { id: 'claude-ollama', enabled: true, type: 'cli', command: 'claude', ollamaBacked: true }+ ]);+ expect(families).toEqual([]);+ });++ it('matches the agy family when enabled', () => {+ const families = resolveEnabledFamilies([{ id: 'antigravity-cli', enabled: true, type: 'cli', command: 'agy' }]);+ expect(families.map((f) => f.id)).toEqual(['agy']);+ });++ it('returns empty for empty/undefined provider lists', () => {+ expect(resolveEnabledFamilies([])).toEqual([]);+ expect(resolveEnabledFamilies(undefined)).toEqual([]);+ });+});diff --git a/server/services/usage.js b/server/services/usage.jsindex 49f0bb1f18..e848ec081f 100644--- a/server/services/usage.js+++ b/server/services/usage.js@@ -1,5 +1,6 @@import { join } from 'path';import { atomicWrite, ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';+import { resolveModelRates, isFreeProvider, estimateCostUsd, PRICING_AS_OF } from '../lib/modelPricing.js';const DATA_DIR = PATHS.data;const USAGE_FILE = join(DATA_DIR, 'usage.json');@@ -57,6 +58,42 @@ export function getUsage() {return usageData || getEmptyUsage();}+/**+ * Per-day per-provider per-model bucket inside dailyActivity — the additive+ * shape that makes arbitrary-period cost breakdowns possible. Legacy day+ * buckets (pre-upgrade) lack `byProvider`; breakdown reports are forward-only+ * from the first day that has it (see `breakdownSince`).+ */+function providerDayBucket(day, providerId, providerName) {+ if (!day.byProvider) day.byProvider = {};+ if (!day.byProvider[providerId]) {+ day.byProvider[providerId] = {+ name: providerName || providerId,+ sessions: 0,+ messages: 0,+ tokensIn: 0,+ tokensOut: 0,+ byModel: {}+ };+ }+ return day.byProvider[providerId];+}++function modelDayBucket(providerDay, model) {+ if (!providerDay.byModel[model]) {+ providerDay.byModel[model] = { sessions: 0, messages: 0, tokensIn: 0, tokensOut: 0 };+ }+ return providerDay.byModel[model];+}++function todayBucket() {+ const today = new Date().toISOString().split('T')[0];+ if (!usageData.dailyActivity[today]) {+ usageData.dailyActivity[today] = { sessions: 0, messages: 0, tokens: 0 };+ }+ return usageData.dailyActivity[today];+}+/*** Record a new session*/@@ -67,24 +104,24 @@ export async function recordSession(providerId, providerName, model) {// Track by providerif (!usageData.byProvider[providerId]) {- usageData.byProvider[providerId] = { name: providerName, sessions: 0, messages: 0, tokens: 0 };+ usageData.byProvider[providerId] = { name: providerName, sessions: 0, messages: 0, tokens: 0, tokensIn: 0, tokensOut: 0 };}usageData.byProvider[providerId].sessions++;// Track by modelif (model) {if (!usageData.byModel[model]) {- usageData.byModel[model] = { sessions: 0, messages: 0, tokens: 0 };+ usageData.byModel[model] = { sessions: 0, messages: 0, tokens: 0, tokensIn: 0, tokensOut: 0 };}usageData.byModel[model].sessions++;}- // Track daily activity- const today = new Date().toISOString().split('T')[0];- if (!usageData.dailyActivity[today]) {- usageData.dailyActivity[today] = { sessions: 0, messages: 0, tokens: 0 };- }- usageData.dailyActivity[today].sessions++;+ // Track daily activity (with the per-provider/per-model split)+ const day = todayBucket();+ day.sessions++;+ const providerDay = providerDayBucket(day, providerId, providerName);+ providerDay.sessions++;+ if (model) modelDayBucket(providerDay, model).sessions++;// Track hourly activityconst hour = new Date().getHours();@@ -95,34 +132,55 @@ export async function recordSession(providerId, providerName, model) {}/**- * Record messages in a session+ * Record messages in a session. `outputTokens`/`inputTokens` are estimates+ * (or real counts when the runner reports them) attributed to the provider,+ * model, and current day.*/-export async function recordMessages(providerId, model, messageCount, tokenCount = 0) {+export async function recordMessages(providerId, model, messageCount, outputTokens = 0, inputTokens = 0) {if (!usageData) await loadUsage();usageData.totalMessages += messageCount;- if (tokenCount > 0) {- usageData.totalTokens.output += tokenCount;+ if (outputTokens > 0) {+ usageData.totalTokens.output += outputTokens;+ }+ if (inputTokens > 0) {+ usageData.totalTokens.input += inputTokens;}- // Track by provider+ // Track by provider (legacy `tokens` stays output-only for old readers)if (usageData.byProvider[providerId]) {- usageData.byProvider[providerId].messages += messageCount;- usageData.byProvider[providerId].tokens += tokenCount;+ const p = usageData.byProvider[providerId];+ p.messages += messageCount;+ p.tokens = (p.tokens || 0) + outputTokens;+ p.tokensIn = (p.tokensIn || 0) + inputTokens;+ p.tokensOut = (p.tokensOut || 0) + outputTokens;}// Track by modelif (model && usageData.byModel[model]) {- usageData.byModel[model].messages += messageCount;- usageData.byModel[model].tokens += tokenCount;+ const m = usageData.byModel[model];+ m.messages += messageCount;+ m.tokens = (m.tokens || 0) + outputTokens;+ m.tokensIn = (m.tokensIn || 0) + inputTokens;+ m.tokensOut = (m.tokensOut || 0) + outputTokens;}- // Track daily- const today = new Date().toISOString().split('T')[0];- if (usageData.dailyActivity[today]) {- usageData.dailyActivity[today].messages += messageCount;- usageData.dailyActivity[today].tokens += tokenCount;+ // Track daily (a run can finish on a different day than it started — create+ // the day/provider buckets if missing rather than gating on existence)+ const day = todayBucket();+ day.messages = (day.messages || 0) + messageCount;+ day.tokens = (day.tokens || 0) + outputTokens;+ const providerName = usageData.byProvider[providerId]?.name;+ const providerDay = providerDayBucket(day, providerId, providerName);+ providerDay.messages += messageCount;+ providerDay.tokensIn += inputTokens;+ providerDay.tokensOut += outputTokens;+ if (model) {+ const modelDay = modelDayBucket(providerDay, model);+ modelDay.messages += messageCount;+ modelDay.tokensIn += inputTokens;+ modelDay.tokensOut += outputTokens;}await saveUsage();@@ -216,10 +274,124 @@ function findLongestStreak(dailyActivity) {return maxStreak;}+const roundCents = (n) => Math.round(n * 100) / 100;++/**+ * Aggregate the per-day per-provider per-model buckets over a date range into+ * a cost report. `from`/`to` are inclusive `YYYY-MM-DD` strings (null = open+ * end). `providers` is the live provider config list (from+ * `services/providers.getAllProviders()`), used for free-classification and+ * display names — records whose provider config no longer exists fall back to+ * an id-based heuristic.+ */+export function buildUsageReport(dailyActivity, { from = null, to = null, providers = [] } = {}) {+ const configById = new Map((providers || []).map((p) => [p.id, p]));+ const agg = new Map(); // providerId -> { name, sessions, messages, tokensIn, tokensOut, byModel: Map }+ let breakdownSince = null;++ for (const [date, day] of Object.entries(dailyActivity || {})) {+ if (!day?.byProvider) continue;+ if (!breakdownSince || date < breakdownSince) breakdownSince = date;+ if (from && date < from) continue;+ if (to && date > to) continue;++ for (const [pid, pDay] of Object.entries(day.byProvider)) {+ if (!agg.has(pid)) {+ agg.set(pid, { name: pDay.name || pid, sessions: 0, messages: 0, tokensIn: 0, tokensOut: 0, byModel: new Map() });+ }+ const p = agg.get(pid);+ p.sessions += pDay.sessions || 0;+ p.messages += pDay.messages || 0;+ p.tokensIn += pDay.tokensIn || 0;+ p.tokensOut += pDay.tokensOut || 0;+ for (const [model, mDay] of Object.entries(pDay.byModel || {})) {+ if (!p.byModel.has(model)) {+ p.byModel.set(model, { sessions: 0, messages: 0, tokensIn: 0, tokensOut: 0 });+ }+ const m = p.byModel.get(model);+ m.sessions += mDay.sessions || 0;+ m.messages += mDay.messages || 0;+ m.tokensIn += mDay.tokensIn || 0;+ m.tokensOut += mDay.tokensOut || 0;+ }+ }+ }++ const totals = { sessions: 0, messages: 0, tokensIn: 0, tokensOut: 0, estimatedCost: 0 };+ const providerRows = [];++ for (const [pid, p] of agg.entries()) {+ const config = configById.get(pid);+ const free = isFreeProvider(config || pid);+ const models = [];+ let providerCost = 0;++ for (const [model, m] of p.byModel.entries()) {+ const rates = free ? null : resolveModelRates(pid, model);+ const cost = free ? 0 : estimateCostUsd(m.tokensIn, m.tokensOut, rates);+ providerCost += cost;+ models.push({+ model,+ sessions: m.sessions,+ messages: m.messages,+ tokensIn: m.tokensIn,+ tokensOut: m.tokensOut,+ estimatedCost: roundCents(cost),+ rateModel: rates?.rateModel ?? null,+ rateMatch: free ? 'free' : rates.matched,+ inputPer1M: rates?.inputPer1M ?? 0,+ outputPer1M: rates?.outputPer1M ?? 0+ });+ }+ models.sort((a, b) => b.estimatedCost - a.estimatedCost || b.tokensOut - a.tokensOut);++ // Tokens recorded without a model id (older capture paths) still count+ // toward the provider row; price them at the provider-default rate.+ const modelTokensIn = models.reduce((s, m) => s + m.tokensIn, 0);+ const modelTokensOut = models.reduce((s, m) => s + m.tokensOut, 0);+ const unattributedIn = Math.max(0, p.tokensIn - modelTokensIn);+ const unattributedOut = Math.max(0, p.tokensOut - modelTokensOut);+ if (!free && (unattributedIn > 0 || unattributedOut > 0)) {+ providerCost += estimateCostUsd(unattributedIn, unattributedOut, resolveModelRates(pid, null));+ }++ totals.sessions += p.sessions;+ totals.messages += p.messages;+ totals.tokensIn += p.tokensIn;+ totals.tokensOut += p.tokensOut;+ totals.estimatedCost += providerCost;++ providerRows.push({+ id: pid,+ name: p.name,+ free,+ sessions: p.sessions,+ messages: p.messages,+ tokensIn: p.tokensIn,+ tokensOut: p.tokensOut,+ estimatedCost: roundCents(providerCost),+ models+ });+ }++ providerRows.sort((a, b) => b.estimatedCost - a.estimatedCost || b.tokensOut - a.tokensOut);+ totals.estimatedCost = roundCents(totals.estimatedCost);++ return {+ range: { from, to },+ breakdownSince,+ pricingAsOf: PRICING_AS_OF,+ providers: providerRows,+ totals+ };+}+/**- * Get usage summary+ * Get usage summary. Optional `range` selects the cost-report window:+ * `{ from, to }` as inclusive YYYY-MM-DD strings (null = unbounded), plus the+ * live `providers` config list for free-classification.*/-export function getUsageSummary() {+export function getUsageSummary({ from = null, to = null, providers = [] } = {}) {if (!usageData) {const empty = getEmptyUsage();// Generate empty last7Days@@ -242,7 +414,8 @@ export function getUsageSummary() {last7Days,estimatedCost: 0,topProviders: [],- topModels: []+ topModels: [],+ report: buildUsageReport({}, { from, to, providers })};}@@ -252,26 +425,22 @@ export function getUsageSummary() {const date = new Date();date.setDate(date.getDate() - i);const dateStr = date.toISOString().split('T')[0];- last7Days.push({- date: dateStr,- label: date.toLocaleDateString('en-US', { weekday: 'short' }),- ...(usageData.dailyActivity[dateStr] || { sessions: 0, messages: 0, tokens: 0 })- });+ const { sessions = 0, messages = 0, tokens = 0 } = usageData.dailyActivity[dateStr] || {};+ last7Days.push({ date: dateStr, label: date.toLocaleDateString('en-US', { weekday: 'short' }), sessions, messages, tokens });}// Calculate streaksconst currentStreak = calculateStreak(usageData.dailyActivity);const longestStreak = findLongestStreak(usageData.dailyActivity);- // Calculate totals- const totalCost = estimateCost(usageData.totalTokens.input, usageData.totalTokens.output);+ const report = buildUsageReport(usageData.dailyActivity, { from, to, providers });return {totalSessions: usageData.totalSessions,totalMessages: usageData.totalMessages,totalToolCalls: usageData.totalToolCalls,totalTokens: usageData.totalTokens,- estimatedCost: totalCost,+ estimatedCost: report.totals.estimatedCost,currentStreak,longestStreak,last7Days,@@ -284,24 +453,11 @@ export function getUsageSummary() {.map(([model, data]) => ({ model, ...data })).sort((a, b) => b.sessions - a.sessions).slice(0, 5),+ report,lastUpdated: usageData.lastUpdated};}-/**- * Estimate cost based on token usage- */-function estimateCost(inputTokens, outputTokens) {- // Average costs per 1M tokens (rough estimates)- const inputCostPer1M = 3.00;- const outputCostPer1M = 15.00;-- const inputCost = (inputTokens / 1_000_000) * inputCostPer1M;- const outputCost = (outputTokens / 1_000_000) * outputCostPer1M;-- return Math.round((inputCost + outputCost) * 100) / 100;-}-/*** Reset usage data*/diff --git a/server/services/usage.test.js b/server/services/usage.test.jsindex 4f685d2d1e..7b7ad40ad4 100644--- a/server/services/usage.test.js+++ b/server/services/usage.test.js@@ -14,12 +14,13 @@ vi.mock('fs/promises', () => ({vi.mock('../lib/fileUtils.js', () => ({tryReadFile: vi.fn().mockResolvedValue(null),ensureDir: vi.fn().mockResolvedValue(undefined),+ atomicWrite: vi.fn().mockResolvedValue(undefined),PATHS: { data: '/fake/data' },readJSONFile: vi.fn()}));import { readJSONFile } from '../lib/fileUtils.js';-import { loadUsage, getUsageSummary, getUsage } from './usage.js';+import { loadUsage, getUsageSummary, getUsage, recordSession, recordMessages, buildUsageReport } from './usage.js';// Helper: produce a date string N days ago (relative to today)function daysAgo(n) {@@ -226,4 +227,137 @@ describe('usage.js — streak calculations', () => {expect(usage.totalSessions).toBe(99);});});++ describe('time-dimensioned capture', () => {+ it('recordSession creates per-provider/per-model day buckets', async () => {+ readJSONFile.mockResolvedValueOnce(makeUsage({}));+ await loadUsage();+ await recordSession('claude-code', 'Claude Code', 'opus');++ const day = getUsage().dailyActivity[daysAgo(0)];+ expect(day.sessions).toBe(1);+ expect(day.byProvider['claude-code']).toMatchObject({ name: 'Claude Code', sessions: 1 });+ expect(day.byProvider['claude-code'].byModel.opus.sessions).toBe(1);+ });++ it('recordMessages attributes input and output tokens to provider, model, and day', async () => {+ readJSONFile.mockResolvedValueOnce(makeUsage({}));+ await loadUsage();+ await recordSession('claude-code', 'Claude Code', 'opus');+ await recordMessages('claude-code', 'opus', 1, 400, 1200);++ const usage = getUsage();+ expect(usage.totalTokens).toEqual({ input: 1200, output: 400 });+ expect(usage.byProvider['claude-code']).toMatchObject({ tokensIn: 1200, tokensOut: 400, tokens: 400 });+ expect(usage.byModel.opus).toMatchObject({ tokensIn: 1200, tokensOut: 400 });+ const modelDay = usage.dailyActivity[daysAgo(0)].byProvider['claude-code'].byModel.opus;+ expect(modelDay).toMatchObject({ messages: 1, tokensIn: 1200, tokensOut: 400 });+ });++ it('recordMessages tolerates legacy all-time entries without tokensIn/tokensOut', async () => {+ readJSONFile.mockResolvedValueOnce(makeUsage({}, {+ byProvider: { codex: { name: 'Codex', sessions: 5, messages: 5, tokens: 100 } },+ byModel: { 'gpt-5.3-codex': { sessions: 5, messages: 5, tokens: 100 } }+ }));+ await loadUsage();+ await recordMessages('codex', 'gpt-5.3-codex', 1, 50, 200);++ const usage = getUsage();+ expect(usage.byProvider.codex).toMatchObject({ tokens: 150, tokensIn: 200, tokensOut: 50 });+ expect(usage.byModel['gpt-5.3-codex']).toMatchObject({ tokens: 150, tokensIn: 200, tokensOut: 50 });+ });+ });++ describe('buildUsageReport', () => {+ const nestedDay = (pid, name, model, { sessions = 1, messages = 1, tokensIn = 0, tokensOut = 0 } = {}) => ({+ sessions,+ messages,+ tokens: tokensOut,+ byProvider: {+ [pid]: {+ name, sessions, messages, tokensIn, tokensOut,+ byModel: { [model]: { sessions, messages, tokensIn, tokensOut } }+ }+ }+ });++ it('aggregates per-provider and per-model over the range with per-model costs', () => {+ const daily = {+ [daysAgo(1)]: nestedDay('claude-code', 'Claude Code', 'claude-opus-4-8', { tokensIn: 1_000_000, tokensOut: 1_000_000 }),+ [daysAgo(0)]: nestedDay('claude-code', 'Claude Code', 'claude-opus-4-8', { tokensIn: 1_000_000, tokensOut: 0 })+ };+ const report = buildUsageReport(daily, {});+ expect(report.providers).toHaveLength(1);+ const row = report.providers[0];+ expect(row).toMatchObject({ id: 'claude-code', free: false, tokensIn: 2_000_000, tokensOut: 1_000_000 });+ // opus 4.8: $5/1M in, $25/1M out → 2*5 + 1*25 = $35+ expect(row.estimatedCost).toBeCloseTo(35);+ expect(row.models[0]).toMatchObject({ model: 'claude-opus-4-8', rateMatch: 'exact', estimatedCost: 35 });+ expect(report.totals.estimatedCost).toBeCloseTo(35);+ });++ it('filters by from/to (inclusive)', () => {+ const daily = {+ '2025-06-01': nestedDay('codex', 'Codex', 'gpt-5.3-codex', { tokensOut: 100 }),+ '2025-06-05': nestedDay('codex', 'Codex', 'gpt-5.3-codex', { tokensOut: 200 }),+ '2025-06-10': nestedDay('codex', 'Codex', 'gpt-5.3-codex', { tokensOut: 400 })+ };+ const report = buildUsageReport(daily, { from: '2025-06-02', to: '2025-06-09' });+ expect(report.providers[0].tokensOut).toBe(200);+ expect(report.range).toEqual({ from: '2025-06-02', to: '2025-06-09' });+ });++ it('marks free providers with zero cost (config and id-heuristic paths)', () => {+ const daily = {+ [daysAgo(0)]: {+ sessions: 2, messages: 2, tokens: 500,+ byProvider: {+ ollama: { name: 'Ollama', sessions: 1, messages: 1, tokensIn: 1_000_000, tokensOut: 1_000_000, byModel: { 'qwen3:32b': { sessions: 1, messages: 1, tokensIn: 1_000_000, tokensOut: 1_000_000 } } },+ 'my-local': { name: 'My Local', sessions: 1, messages: 1, tokensIn: 1_000_000, tokensOut: 1_000_000, byModel: { llm: { sessions: 1, messages: 1, tokensIn: 1_000_000, tokensOut: 1_000_000 } } }+ }+ }+ };+ const providers = [{ id: 'my-local', type: 'api', endpoint: 'http://localhost:1234/v1' }];+ const report = buildUsageReport(daily, { providers });+ const ollama = report.providers.find(p => p.id === 'ollama');+ const local = report.providers.find(p => p.id === 'my-local');+ expect(ollama).toMatchObject({ free: true, estimatedCost: 0 });+ expect(ollama.models[0].rateMatch).toBe('free');+ expect(local).toMatchObject({ free: true, estimatedCost: 0 });+ expect(report.totals.estimatedCost).toBe(0);+ });++ it('reports breakdownSince as the earliest day with a provider split, ignoring legacy days', () => {+ const daily = {+ '2025-05-01': { sessions: 3, messages: 3, tokens: 100 }, // legacy — no byProvider+ '2025-06-03': nestedDay('codex', 'Codex', 'gpt-5.3-codex', { tokensOut: 10 }),+ '2025-06-01': nestedDay('codex', 'Codex', 'gpt-5.3-codex', { tokensOut: 10 })+ };+ const report = buildUsageReport(daily, {});+ expect(report.breakdownSince).toBe('2025-06-01');+ // legacy day contributes nothing to the breakdown+ expect(report.totals.sessions).toBe(2);+ });++ it('prices provider-level tokens missing a model split at the provider default', () => {+ const daily = {+ [daysAgo(0)]: {+ sessions: 1, messages: 1, tokens: 0,+ byProvider: {+ 'claude-code': { name: 'Claude Code', sessions: 1, messages: 1, tokensIn: 1_000_000, tokensOut: 0, byModel: {} }+ }+ }+ };+ const report = buildUsageReport(daily, {});+ // provider default for claude-* is sonnet-4.5 ($3/1M in)+ expect(report.providers[0].estimatedCost).toBeCloseTo(3);+ });++ it('returns an empty report for empty activity', () => {+ const report = buildUsageReport({}, { from: null, to: null });+ expect(report.providers).toEqual([]);+ expect(report.totals).toMatchObject({ sessions: 0, estimatedCost: 0 });+ expect(report.breakdownSince).toBeNull();+ });+ });});