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
show what quota subscriptions save versus paying API rates on the usage page
[._.]/ Adam Eivyc44e0da0db7b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex fff7ec129a..5fa848779e 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,6 +1,7 @@## Added- CoS now notices when a scheduled task (the overnight branch-reconcile loop) finishes the same work over and over in short-lived agent runs. It parks a looping coordinator so it stops burning quota, files one GitHub issue to fix the drain, and records per-run duration so the burst is visible as a metric.+- The Usage page can now record what you pay each month for your AI subscriptions (Claude, Codex, Antigravity, Grok) and shows what those plans saved against the estimated API cost. Each plan's price is prorated across whatever report window is selected, so both sides of the comparison cover the same days, and every plan gets its own row: monthly price, cost for this window, the API-rate cost its usage ran up, and the difference. Usage no subscription covers — pay-as-you-go API providers and pre-breakdown legacy rows — is reported separately instead of being credited to a plan.## Fixeddiff --git a/client/src/components/usage/SubscriptionSavingsCard.jsx b/client/src/components/usage/SubscriptionSavingsCard.jsxnew file mode 100644index 0000000000..28f4f46d10--- /dev/null+++ b/client/src/components/usage/SubscriptionSavingsCard.jsx@@ -0,0 +1,289 @@+import { useState, useMemo } from 'react';+import { PiggyBank, Save } from 'lucide-react';+import * as api from '../../services/api';+import Pill from '../ui/Pill';+import BrailleSpinner from '../BrailleSpinner';+import { formatUsd } from '../../utils/formatters';+import { useAsyncAction } from '../../hooks/useAsyncAction';++const savingsTone = (savings) => (savings >= 0 ? 'text-port-success' : 'text-port-error');++// The three derived figures per plan, defined ONCE so the mobile cards and the+// desktop table can't drift into showing different things (they already had:+// mobile was missing the totals row entirely).+const rowCells = (row) => [+ { key: 'period', label: 'This period', value: row.configured ? formatUsd(row.periodCost) : null },+ { key: 'api', label: 'Est. API cost', value: formatUsd(row.apiCost) },+ {+ key: 'savings',+ label: 'Savings',+ value: row.configured ? formatUsd(row.savings, { signed: true }) : null,+ tone: row.configured ? savingsTone(row.savings) : undefined,+ suffix: row.configured && row.multiplier != null ? `${row.multiplier}×` : null+ }+];++const totalCells = (totals) => [+ { key: 'period', label: 'This period', value: formatUsd(totals.periodCost) },+ { key: 'api', label: 'Est. API cost', value: formatUsd(totals.apiCost) },+ {+ key: 'savings',+ label: 'Savings',+ value: formatUsd(totals.savings, { signed: true }),+ tone: savingsTone(totals.savings),+ suffix: totals.savingsPercent != null ? `${totals.savingsPercent}%` : null+ }+];++// The draft map holds ONLY edited rows, so a period change (which refetches and+// hands down fresh `savings`) can't clobber a price the user is mid-way through+// typing, and an unedited row always renders the persisted value.+const displayValue = (drafts, row) =>+ (row.family in drafts ? drafts[row.family] : (row.monthlyCost > 0 ? String(row.monthlyCost) : ''));++/**+ * Parse an input string to the patch value the API expects: a positive number,+ * or `null` to CLEAR the plan. Empty and 0 both mean "I don't pay for this",+ * which must be sent (as null) rather than omitted — omitting it would leave+ * the old price in place. Returns `undefined` for unparseable input so the row+ * is skipped instead of silently clearing a price the user fat-fingered.+ */+export function parseCostInput(raw) {+ const trimmed = String(raw ?? '').trim();+ if (trimmed === '') return null;+ const value = Number(trimmed.replace(/^\$/, ''));+ if (!Number.isFinite(value) || value < 0) return undefined;+ return value > 0 ? Math.round(value * 100) / 100 : null;+}++/**+ * The rows whose price actually changed, as an API patch. Unchanged rows are+ * omitted so a save never rewrites a price the user didn't touch.+ */+export function buildCostPatch(drafts, families) {+ const stored = new Map(families.map((f) => [f.family, f.monthlyCost > 0 ? f.monthlyCost : null]));+ const patch = {};+ for (const [family, raw] of Object.entries(drafts)) {+ if (!stored.has(family)) continue;+ const next = parseCostInput(raw);+ if (next === undefined) continue;+ if (next !== stored.get(family)) patch[family] = next;+ }+ return patch;+}++function CostInput({ row, value, onChange }) {+ return (+ <div className="flex items-center gap-1">+ <span className="text-gray-500 text-xs">$</span>+ <input+ id={`subscription-cost-${row.family}`}+ type="number"+ inputMode="decimal"+ min="0"+ step="1"+ placeholder="0"+ value={value}+ onChange={(e) => onChange(row.family, e.target.value)}+ className="w-20 bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-white outline-none focus:border-port-accent"+ aria-label={`Monthly cost for ${row.label}`}+ />+ <span className="text-gray-500 text-xs">/mo</span>+ </div>+ );+}++const NotPriced = () => <span className="text-gray-600">not priced</span>;++function CellValue({ cell }) {+ return (+ <>+ <span className={cell.tone}>{cell.value ?? <NotPriced />}</span>+ {cell.suffix && <span className="text-[10px] text-gray-500 ml-1">{cell.suffix}</span>}+ </>+ );+}++/**+ * Per-family subscription pricing plus the savings those plans produced against+ * the cost report's API-rate estimate for the same window.+ *+ * `savings` is the `subscriptionSavings` block from GET /api/usage — it already+ * carries every family the editor should offer (including unpriced ones), so+ * this component never fetches the family list separately. `onSaved` refetches+ * the report and resolves once the new figures are in hand, so the button stays+ * busy until the rows on screen reflect the price that was just saved.+ */+export default function SubscriptionSavingsCard({ savings, onSaved }) {+ const [drafts, setDrafts] = useState({});+ const families = savings?.families;++ const patch = useMemo(() => buildCostPatch(drafts, families || []), [drafts, families]);+ const dirty = Object.keys(patch).length > 0;++ const [save, saving] = useAsyncAction(async () => {+ await api.updateSubscriptionCosts(patch, { silent: true });+ await onSaved?.();+ // Cleared only after the refetch lands: dropping the drafts first would+ // flash the pre-save prices back onto the rows in between.+ setDrafts({});+ }, { errorMessage: 'Failed to save subscription costs' });++ if (!savings) return null;++ const onChange = (family, value) => setDrafts((prev) => ({ ...prev, [family]: value }));+ const { totals, range } = savings;+ const windowLabel = range?.start+ ? `${range.start} → ${range.end} (${range.days} day${range.days === 1 ? '' : 's'})`+ : 'no usage recorded yet';++ return (+ <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">+ <div>+ <h3 className="text-sm font-medium text-gray-400 flex items-center gap-2">+ <PiggyBank size={16} className="text-port-accent" />+ Subscription vs. API Cost+ </h3>+ <p className="text-[10px] sm:text-xs text-gray-500 mt-0.5">+ What your quota plans cost over {windowLabel}, against what the same usage would have cost at API rates.+ </p>+ </div>+ <div className="flex items-center gap-2 shrink-0">+ {dirty && (+ <button+ type="button"+ onClick={save}+ disabled={saving}+ className="inline-flex items-center gap-1.5 rounded-lg border border-port-accent px-3 py-1.5 text-sm text-white hover:bg-port-accent/20 disabled:opacity-50"+ >+ {saving ? <BrailleSpinner /> : <Save size={14} />} Save costs+ </button>+ )}+ {savings.configured && (+ <div className="text-right">+ <div className={`text-xl font-bold ${savingsTone(totals.savings)}`}>+ {formatUsd(totals.savings, { signed: true })}+ </div>+ <div className="text-[10px] text-gray-500">+ {totals.savings >= 0 ? 'saved' : 'over API cost'}+ {totals.multiplier != null && ` · ${totals.multiplier}×`}+ </div>+ </div>+ )}+ </div>+ </div>++ {families.length === 0 && (+ <p className="text-sm text-gray-500">+ No provider families to price — enable a Claude/Codex/Antigravity/Grok provider to record its plan cost.+ </p>+ )}++ {families.length > 0 && (+ <>+ {/* Mobile: one card per plan, so the numbers never need a sideways scroll. */}+ <div className="block sm:hidden space-y-2">+ {families.map((row) => (+ <div key={row.family} className="bg-port-bg border border-port-border rounded-lg p-3 space-y-2">+ <div className="flex items-center justify-between gap-2">+ <label htmlFor={`subscription-cost-${row.family}`} className="text-sm font-medium text-white truncate">+ {row.label}+ {!row.enabled && <Pill tone="context" size="xs" className="ml-2">disabled</Pill>}+ </label>+ <CostInput row={row} value={displayValue(drafts, row)} onChange={onChange} />+ </div>+ <div className="grid grid-cols-3 gap-2 text-[11px] text-white">+ {rowCells(row).map((cell) => (+ <div key={cell.key}>+ <span className="text-gray-500 block">{cell.label}</span>+ <CellValue cell={cell} />+ </div>+ ))}+ </div>+ </div>+ ))}+ {savings.configured && (+ <div className="bg-port-bg border border-port-border rounded-lg p-3 space-y-2">+ <div className="flex items-center justify-between text-sm font-semibold text-white">+ <span>Total</span>+ <span className="text-gray-400 font-normal text-xs">{formatUsd(totals.monthlyCost, { trimWhole: true })}/mo</span>+ </div>+ <div className="grid grid-cols-3 gap-2 text-[11px] text-white">+ {totalCells(totals).map((cell) => (+ <div key={cell.key}>+ <span className="text-gray-500 block">{cell.label}</span>+ <CellValue cell={cell} />+ </div>+ ))}+ </div>+ </div>+ )}+ </div>++ {/* Desktop: table */}+ <div className="hidden sm:block overflow-x-auto">+ <table className="w-full text-sm">+ <thead>+ <tr className="text-left text-xs text-gray-500 border-b border-port-border">+ <th className="py-2 pr-2 font-medium">Subscription</th>+ <th className="py-2 px-2 font-medium">Cost</th>+ {rowCells(families[0]).map((cell) => (+ <th key={cell.key} className="py-2 px-2 font-medium text-right">{cell.label}</th>+ ))}+ </tr>+ </thead>+ <tbody>+ {families.map((row) => (+ <tr key={row.family} className="border-t border-port-border text-white">+ <td className="py-2 pr-2">+ <label htmlFor={`subscription-cost-${row.family}`} className="font-medium cursor-pointer">+ {row.label}+ </label>+ {!row.enabled && <Pill tone="context" size="xs" className="ml-2">disabled</Pill>}+ </td>+ <td className="py-2 px-2">+ <CostInput row={row} value={displayValue(drafts, row)} onChange={onChange} />+ </td>+ {rowCells(row).map((cell) => (+ <td key={cell.key} className="py-2 px-2 text-right text-gray-300">+ <CellValue cell={cell} />+ </td>+ ))}+ </tr>+ ))}+ </tbody>+ {savings.configured && (+ <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-gray-400 font-normal">+ {formatUsd(totals.monthlyCost, { trimWhole: true })}/mo+ </td>+ {totalCells(totals).map((cell) => (+ <td key={cell.key} className="py-2 px-2 text-right">+ <CellValue cell={cell} />+ </td>+ ))}+ </tr>+ </tfoot>+ )}+ </table>+ </div>+ </>+ )}++ <p className="text-[10px] sm:text-xs text-gray-500">+ Enter what each plan costs you per month (annual plans: divide by 12). A plan’s cost is prorated across the+ selected report window, so both sides of the comparison cover the same days.+ {savings.unmatchedApiCost > 0 && (+ <>+ {' '}<span className="text-gray-400">{formatUsd(savings.unmatchedApiCost)}</span> of estimated API cost came from+ usage no subscription covers (pay-as-you-go API providers or pre-breakdown legacy rows) and is excluded from savings.+ </>+ )}+ {' '}Savings inherit the estimate’s accuracy — rows marked Estimated above understate real usage.+ </p>+ </div>+ );+}diff --git a/client/src/components/usage/SubscriptionSavingsCard.test.jsx b/client/src/components/usage/SubscriptionSavingsCard.test.jsxnew file mode 100644index 0000000000..7610819c97--- /dev/null+++ b/client/src/components/usage/SubscriptionSavingsCard.test.jsx@@ -0,0 +1,112 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';++const api = vi.hoisted(() => ({ updateSubscriptionCosts: vi.fn() }));+vi.mock('../../services/api', () => api);++const { default: SubscriptionSavingsCard, buildCostPatch, parseCostInput } =+ await import('./SubscriptionSavingsCard');++const savings = {+ range: { start: '2026-02-01', end: '2026-02-07', days: 7 },+ configured: true,+ unmatchedApiCost: 12.5,+ families: [+ {+ family: 'claude', label: 'Claude Code', enabled: true, monthlyCost: 200, configured: true,+ periodCost: 46.0, apiCost: 812.44, savings: 766.44, multiplier: 17.7+ },+ {+ family: 'codex', label: 'Codex', enabled: true, monthlyCost: 0, configured: false,+ periodCost: 0, apiCost: 40, savings: 0, multiplier: null+ }+ ],+ totals: { monthlyCost: 200, periodCost: 46.0, apiCost: 812.44, savings: 766.44, savingsPercent: 94, multiplier: 17.7 }+};++beforeEach(() => {+ vi.clearAllMocks();+ api.updateSubscriptionCosts.mockResolvedValue({ costs: { claude: 200 } });+});++describe('parseCostInput', () => {+ it('reads a price, tolerating a typed dollar sign', () => {+ expect(parseCostInput('200')).toBe(200);+ expect(parseCostInput('$19.99')).toBe(19.99);+ });++ // Empty and 0 must be SENT as a clear, not omitted — omitting them would+ // leave the cancelled plan's old price in place.+ it('maps an emptied or zeroed field to an explicit clear', () => {+ expect(parseCostInput('')).toBeNull();+ expect(parseCostInput('0')).toBeNull();+ });++ it('skips unparseable input rather than clearing a fat-fingered price', () => {+ expect(parseCostInput('abc')).toBeUndefined();+ expect(parseCostInput('-5')).toBeUndefined();+ });+});++describe('buildCostPatch', () => {+ it('sends only the rows whose price actually changed', () => {+ expect(buildCostPatch({ claude: '200', codex: '20' }, savings.families)).toEqual({ codex: 20 });+ });++ it('sends a null for a cleared plan', () => {+ expect(buildCostPatch({ claude: '' }, savings.families)).toEqual({ claude: null });+ });++ it('ignores an unknown family', () => {+ expect(buildCostPatch({ nope: '5' }, savings.families)).toEqual({});+ });+});++describe('SubscriptionSavingsCard', () => {+ it('renders nothing until the server sends a savings block', () => {+ const { container } = render(<SubscriptionSavingsCard savings={null} />);+ expect(container).toBeEmptyDOMElement();+ });++ it('shows the total saved and each plan row', () => {+ render(<SubscriptionSavingsCard savings={savings} />);+ expect(screen.getAllByText('$766.44').length).toBeGreaterThan(0);+ expect(screen.getAllByLabelText('Monthly cost for Claude Code')[0]).toHaveValue(200);+ expect(screen.getAllByText('not priced').length).toBeGreaterThan(0);+ });++ // The mobile layout used to omit the totals entirely, so a phone user could+ // price their plans and never see what they saved.+ it('renders the totals in both the mobile and desktop layouts', () => {+ render(<SubscriptionSavingsCard savings={savings} />);+ expect(screen.getAllByText('Total')).toHaveLength(2);+ expect(screen.getAllByText('$200/mo')).toHaveLength(2);+ });++ it('reports API cost no subscription covers', () => {+ render(<SubscriptionSavingsCard savings={savings} />);+ expect(screen.getByText(/of estimated API cost came from/)).toBeInTheDocument();+ });++ it('saves only the edited price and asks the parent to refetch', async () => {+ const onSaved = vi.fn();+ render(<SubscriptionSavingsCard savings={savings} onSaved={onSaved} />);++ expect(screen.queryByRole('button', { name: /Save costs/ })).toBeNull();+ fireEvent.change(screen.getAllByLabelText('Monthly cost for Codex')[0], { target: { value: '20' } });+ fireEvent.click(screen.getByRole('button', { name: /Save costs/ }));++ await waitFor(() => expect(api.updateSubscriptionCosts).toHaveBeenCalledWith({ codex: 20 }, { silent: true }));+ await waitFor(() => expect(onSaved).toHaveBeenCalled());+ });++ it('offers a price field for a plan whose provider is disabled', () => {+ const withDisabled = {+ ...savings,+ families: [{ ...savings.families[0], family: 'grok', label: 'Grok', enabled: false }]+ };+ render(<SubscriptionSavingsCard savings={withDisabled} />);+ expect(screen.getAllByLabelText('Monthly cost for Grok').length).toBeGreaterThan(0);+ expect(screen.getAllByText('disabled').length).toBeGreaterThan(0);+ });+});diff --git a/client/src/pages/UsagePage.jsx b/client/src/pages/UsagePage.jsxindex f835b3c31c..3b660fa007 100644--- a/client/src/pages/UsagePage.jsx+++ b/client/src/pages/UsagePage.jsx@@ -1,13 +1,14 @@-import { useCallback, useState, useEffect } from 'react';+import { useCallback, useState, useEffect, useRef } from 'react';import { useSearchParams } from 'react-router';import { RefreshCw, Clock, AlertTriangle, DatabaseZap } from 'lucide-react';import * as api from '../services/api';import BrailleSpinner from '../components/BrailleSpinner';import PageSkeleton from '../components/ui/PageSkeleton';import Pill from '../components/ui/Pill';-import { formatCompactCount, timeUntil } from '../utils/formatters';+import { formatCompactCount, formatUsd, timeUntil } from '../utils/formatters';import { useAsyncAction } from '../hooks/useAsyncAction';import { useAutoRefetch } from '../hooks/useAutoRefetch';+import SubscriptionSavingsCard from '../components/usage/SubscriptionSavingsCard';// How often to re-ask while a provider's quota reading is still being taken. A// CLI/TUI scrape is a 10-20s spawn, so this is a handful of polls, not a loop.@@ -23,7 +24,6 @@ const PERIOD_OPTIONS = [// 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)}`;// Every provider adapter normalizes its reset to ISO before it reaches here, so// this localizes and adds the relative "in 3h" that makes a reset time useful at@@ -372,7 +372,7 @@ function CostReportTable({ report }) {{!provider.free && <SourcePill source={provider.source} className="shrink-0" />}</div><span className="text-sm font-semibold text-port-success shrink-0" title={approxMark(provider.rateMatch) ? 'Approximate pricing' : undefined}>- {approxMark(provider.rateMatch)}{formatCost(provider.estimatedCost)}+ {approxMark(provider.rateMatch)}{formatUsd(provider.estimatedCost)}</span></div>@@ -402,7 +402,7 @@ function CostReportTable({ report }) {<div key={m.model} className="bg-port-card/30 p-2 rounded text-xs space-y-1"><div className="flex items-center justify-between font-mono text-gray-300 text-[11px]"><span className="truncate pr-2" title={m.model}>{m.model}</span>- <span className="text-gray-400 shrink-0 font-sans font-medium">{approxMark(m.rateMatch)}{formatCost(m.estimatedCost)}</span>+ <span className="text-gray-400 shrink-0 font-sans font-medium">{approxMark(m.rateMatch)}{formatUsd(m.estimatedCost)}</span></div><div className="flex items-center justify-between text-[10px] text-gray-400"><span>{formatNumber(m.sessions)} sess</span>@@ -418,7 +418,7 @@ function CostReportTable({ report }) {<div className="bg-port-bg border border-port-border rounded-lg p-3 flex items-center justify-between text-xs font-semibold text-white"><span>Total ({formatNumber(report.totals.sessions)} sessions)</span>- <span className="text-port-success text-sm">{formatCost(report.totals.estimatedCost)}</span>+ <span className="text-port-success text-sm">{formatUsd(report.totals.estimatedCost)}</span></div></div>@@ -449,7 +449,7 @@ function CostReportTable({ report }) {<td className="py-2 px-2 text-right hidden md:table-cell">{formatNumber(report.totals.cacheReadTokens)}</td><td className="py-2 px-2 text-right hidden md:table-cell">{formatNumber(report.totals.cacheWriteTokens)}</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>+ <td className="py-2 pl-2 text-right text-port-success">{formatUsd(report.totals.estimatedCost)}</td></tr></tfoot></table>@@ -483,7 +483,7 @@ function ProviderCostRows({ provider }) {className="py-2 pl-2 text-right"title={approxMark(provider.rateMatch) ? 'Approximate — provider or legacy usage uses fallback pricing' : undefined}>- {approxMark(provider.rateMatch)}{formatCost(provider.estimatedCost)}+ {approxMark(provider.rateMatch)}{formatUsd(provider.estimatedCost)}</td></tr>{provider.models.map((m) => (@@ -502,7 +502,7 @@ function ProviderCostRows({ provider }) {<td className="py-1.5 px-2 text-right text-xs hidden md:table-cell">{formatNumber(m.cacheWriteTokens)}</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)}{formatCost(m.estimatedCost)}+ {approxMark(m.rateMatch)}{formatUsd(m.estimatedCost)}</td></tr>))}@@ -648,23 +648,28 @@ function InternalUsageMetrics() {const [loading, setLoading] = useState(true);const [backfill, setBackfill] = useState(null);- useEffect(() => {- let cancelled = false;- setLoading(true);+ // One fetch for every trigger — the range effect, the backfill-complete+ // refetch, and a subscription-price save (which re-derives the savings block+ // server-side). It resolves once the new payload is applied, so a caller can+ // keep its button busy until the screen actually reflects the change.+ const requestRef = useRef(0);+ const fetchUsage = useCallback(async () => {+ const token = ++requestRef.current;const params = isCustom ? { from, to } : { period };- api.getUsage(params)- .catch(() => null)- .then((data) => {- if (cancelled) return;- // Keep the previously-loaded metrics on a failed fetch (e.g. an- // in-progress custom range where from > to briefly 400s) so the- // filter controls stay on screen for the user to correct the range.- if (data) setUsage(data);- setLoading(false);- });- return () => { cancelled = true; };+ const data = await api.getUsage(params).catch(() => null);+ // Keep the previously-loaded metrics on a failed fetch (e.g. an in-progress+ // custom range where from > to briefly 400s) so the filter controls stay on+ // screen for the user to correct the range — and drop a response a newer+ // request has already superseded.+ if (data && token === requestRef.current) setUsage(data);+ return data;}, [period, from, to, isCustom]);+ useEffect(() => {+ setLoading(true);+ fetchUsage().finally(() => setLoading(false));+ }, [fetchUsage]);+useEffect(() => {let cancelled = false;api.getUsageBackfillStatus({ silent: true })@@ -688,9 +693,7 @@ function InternalUsageMetrics() {if (cancelled) return;setBackfill(status);if (status?.status === 'complete') {- const params = isCustom ? { from, to } : { period };- const refreshed = await api.getUsage(params);- if (!cancelled) setUsage(refreshed);+ await fetchUsage();} else if (status?.status === 'running') {timer = setTimeout(poll, 1000);}@@ -702,7 +705,7 @@ function InternalUsageMetrics() {cancelled = true;clearTimeout(timer);};- }, [backfill?.status, isCustom, from, to, period]);+ }, [backfill?.status, fetchUsage]);const setPeriod = (id) => {@@ -815,7 +818,7 @@ function InternalUsageMetrics() {</div><div className="flex items-center gap-2">{report?.totals?.source && <SourcePill source={report.totals.source} />}- <span className="text-xl font-bold text-port-success">{formatCost(report?.totals?.estimatedCost)}</span>+ <span className="text-xl font-bold text-port-success">{formatUsd(report?.totals?.estimatedCost)}</span></div></div><CostReportFilters period={period} from={from} to={to} isCustom={isCustom} onPeriod={setPeriod} onRange={setRange} />@@ -832,6 +835,10 @@ function InternalUsageMetrics() {</p></div>+ {/* Directly under the API estimate it is derived from: the estimate is the+ opportunity cost, this is what the quota plans actually cost to avoid it. */}+ <SubscriptionSavingsCard savings={usage.subscriptionSavings} onSaved={fetchUsage} />+<div className="grid grid-cols-1 md:grid-cols-2 gap-4 sm:gap-6">{/* 7-Day Activity */}<div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4">@@ -899,7 +906,7 @@ function InternalUsageMetrics() {</div><div className="flex items-center gap-2 shrink-0 text-xs">{provider.estimatedCost != null && provider.estimatedCost > 0 && (- <span className="text-port-success font-semibold">{formatCost(provider.estimatedCost)}</span>+ <span className="text-port-success font-semibold">{formatUsd(provider.estimatedCost)}</span>)}<span className="text-gray-400 bg-port-bg border border-port-border px-1.5 py-0.5 rounded text-[10px] sm:text-xs font-mono">{provider.percent}%@@ -953,7 +960,7 @@ function InternalUsageMetrics() {</div><div className="flex items-center gap-2 shrink-0 text-xs">{model.estimatedCost != null && model.estimatedCost > 0 && (- <span className="text-port-success font-semibold">{formatCost(model.estimatedCost)}</span>+ <span className="text-port-success font-semibold">{formatUsd(model.estimatedCost)}</span>)}<span className="text-gray-400 bg-port-bg border border-port-border px-1.5 py-0.5 rounded text-[10px] sm:text-xs font-mono">{model.percent}%diff --git a/client/src/pages/UsagePage.test.jsx b/client/src/pages/UsagePage.test.jsxindex 8383f67ee1..0aa4464de8 100644--- a/client/src/pages/UsagePage.test.jsx+++ b/client/src/pages/UsagePage.test.jsx@@ -6,7 +6,8 @@ const api = vi.hoisted(() => ({getProviderUsage: vi.fn(),getUsage: vi.fn(),getUsageBackfillStatus: vi.fn(),- startUsageBackfill: vi.fn()+ startUsageBackfill: vi.fn(),+ updateSubscriptionCosts: vi.fn()}));vi.mock('../services/api', () => api);@@ -36,6 +37,41 @@ beforeEach(() => {api.getUsage.mockResolvedValue(usage);api.getUsageBackfillStatus.mockResolvedValue({ status: 'idle' });api.startUsageBackfill.mockResolvedValue({ status: 'complete', corrected: 2 });+ api.updateSubscriptionCosts.mockResolvedValue({ costs: { claude: 200 } });+});++describe('UsagePage subscription savings', () => {+ const savings = {+ range: { start: '2026-02-01', end: '2026-02-07', days: 7 },+ configured: false,+ unmatchedApiCost: 0,+ families: [{+ family: 'claude', label: 'Claude Code', enabled: true, monthlyCost: 0, configured: false,+ periodCost: 0, apiCost: 30, savings: 0, multiplier: null+ }],+ totals: { monthlyCost: 0, periodCost: 0, apiCost: 0, savings: 0, savingsPercent: null, multiplier: null }+ };++ it('renders the savings editor from the report payload', async () => {+ api.getUsage.mockResolvedValue({ ...usage, subscriptionSavings: savings });+ render(<MemoryRouter><UsagePage /></MemoryRouter>);+ expect(await screen.findByText('Subscription vs. API Cost')).toBeInTheDocument();+ });++ // A new plan price changes every derived figure in the report, so saving one+ // has to pull the whole report back down — not just the prices.+ it('refetches the report after a price is saved', async () => {+ api.getUsage.mockResolvedValue({ ...usage, subscriptionSavings: savings });+ render(<MemoryRouter><UsagePage /></MemoryRouter>);++ const inputs = await screen.findAllByLabelText('Monthly cost for Claude Code');+ fireEvent.change(inputs[0], { target: { value: '200' } });+ const calls = api.getUsage.mock.calls.length;+ fireEvent.click(screen.getByRole('button', { name: /Save costs/ }));++ await waitFor(() => expect(api.updateSubscriptionCosts).toHaveBeenCalledWith({ claude: 200 }, { silent: true }));+ await waitFor(() => expect(api.getUsage.mock.calls.length).toBeGreaterThan(calls));+ });});describe('UsagePage historical reconciliation', () => {diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 54a94119f0..caf8276dfb 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -59,7 +59,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiScaffold.js` | App scaffolding templates. || `apiSchedules.js` | Automation schedules. || `apiQuotaBurn.js` | Quota Burn plan + live status, the job-type catalog its config form renders, and manual runs (`getQuotaBurn`/`getQuotaBurnCatalog`/`saveQuotaBurn`/`runQuotaBurn`). |-| `apiSystem.js` | System info (CPU/memory/ports/alerts) + D&D-style character sheet getter, plus the usage cost report and explicit historical reconciliation (`getUsage`/`getUsageRaw`/`resetUsage`, `getProviderUsage`, `getUsageBackfillStatus`/`startUsageBackfill`). |+| `apiSystem.js` | System info (CPU/memory/ports/alerts) + D&D-style character sheet getter, plus the usage cost report and explicit historical reconciliation (`getUsage`/`getUsageRaw`/`resetUsage`, `getProviderUsage`, `getUsageBackfillStatus`/`startUsageBackfill`, `updateSubscriptionCosts` for the subscription-vs-API savings comparison). || `apiAuth.js` | Optional login password — status, login/logout, set/clear password. || `apiLoops.js` | Scheduled loops. |diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.jsindex ad2a8470a1..3f750a1f67 100644--- a/client/src/services/apiSystem.js+++ b/client/src/services/apiSystem.js@@ -115,6 +115,12 @@ export const getUsage = (params = {}) => {export const getUsageRaw = () => request('/usage/raw');export const resetUsage = () => request('/usage', { method: 'DELETE' });export const getUsageBackfillStatus = (options = {}) => request('/usage/backfill', options);+// Monthly plan prices per provider family, used to compare subscription spend+// against the report's estimated API cost. `costs` is a partial patch: an+// omitted family keeps its stored price, `null` clears it. Reads come back with+// the report (`getUsage().subscriptionSavings`), so there is no getter here.+export const updateSubscriptionCosts = (costs, options = {}) =>+ request('/usage/subscriptions', { method: 'PUT', body: JSON.stringify({ costs }), ...options });export const startUsageBackfill = (options = {}) => request('/usage/backfill', { method: 'POST', ...options });diff --git a/client/src/utils/README.md b/client/src/utils/README.mdindex e7d9e406e3..0975e3575f 100644--- a/client/src/utils/README.md+++ b/client/src/utils/README.md@@ -22,7 +22,7 @@ grep -i "what you want to do" client/src/utils/README.md| Module | Purpose ||---|---|-| `formatters` | Date/time/duration/byte/word formatters (`formatBytes`, `formatCompactCount`, `timeAgo`, `formatTimecode`, `formatDurationMs`, `formatDateShort`, `parseTimeoutMs`, `formatCooldown`, `parseSizeGb`, `recommendedRamGb`, `nameFromImageFilename`, `formatWeight` / `formatPercent` — round unit-converted floats (`170.35000000000002` → `170.4 lbs`) so raw binary precision never reaches a tile — `middleTruncate` — clip a long string from the MIDDLE so its distinguishing tail survives, where CSS `line-clamp`/`text-overflow` always eats the end — …) plus timeout-input bounds and `getAppName`. Do not re-define formatters inside components. |+| `formatters` | Date/time/duration/byte/word formatters (`formatBytes`, `formatCompactCount`, `timeAgo`, `formatTimecode`, `formatDurationMs`, `formatDateShort`, `parseTimeoutMs`, `formatCooldown`, `parseSizeGb`, `recommendedRamGb`, `nameFromImageFilename`, `formatUsd` — one USD renderer (`signed` puts the minus outside the `$`; `trimWhole` drops `.00` on a typed round price) — `formatWeight` / `formatPercent` — round unit-converted floats (`170.35000000000002` → `170.4 lbs`) so raw binary precision never reaches a tile — `middleTruncate` — clip a long string from the MIDDLE so its distinguishing tail survives, where CSS `line-clamp`/`text-overflow` always eats the end — …) plus timeout-input bounds and `getAppName`. Do not re-define formatters inside components. || `cronHelpers` | Cron preset list, `isCronExpression` detection, and `describeCron` human-readable rendering. || `markdownText` | `markdownToPlainText(md)` — flatten markdown source to one plain-text string for a clamped preview: strips heading/list/blockquote/fence markers, unwraps emphasis, inline code and links, images → `[alt]`, collapses blank-line runs. Use whenever a card previews arbitrary agent-authored markdown — `line-clamp-N` does not clamp a subtree of block elements, and foreign `##` headings would otherwise join the page's heading outline. Underscore emphasis is word-boundary gated and `__…__` needs interior whitespace, so stack frames and user-agent strings (`10_15_7`, `__init__`) are never silently rewritten. `dropsMarkupWhenFlattened(md)` — did the flatten lose actual markup, as opposed to only normalizing whitespace? Gates a "Show more" disclosure so a short-but-lossy body stays reachable without putting a toggle on every body that merely lost a trailing newline. || `timeWindow` | Time-of-day window math (`isInTimeWindow`, `timeStringToMinutes`) and morning-layout auto-switch helpers (`pickActiveLayoutId`, `recordManualLayoutPick`). |diff --git a/client/src/utils/formatters.js b/client/src/utils/formatters.jsindex 5820ab38b2..313e413fec 100644--- a/client/src/utils/formatters.js+++ b/client/src/utils/formatters.js@@ -187,6 +187,25 @@ export function formatPercent(value, { decimals = 1, fallback = '—' } = {}) {return `${n}%`;}+/**+ * Format a USD amount for display: `$12.34`.+ *+ * `signed` keeps the minus sign OUTSIDE the dollar sign (`-$5.00`), so a+ * negative saving reads as a loss rather than as a strange currency string.+ * `trimWhole` drops the `.00` on a round figure — for a price the user typed+ * ($200/mo), not for a computed total, where aligned cents are the point.+ *+ * @param {number} value - Dollar amount (nullish renders as $0.00)+ * @param {{ signed?: boolean, trimWhole?: boolean }} [options]+ * @returns {string} e.g. "$12.34", "-$5.00", "$200"+ */+export function formatUsd(value, { signed = false, trimWhole = false } = {}) {+ const n = Number(value) || 0;+ const magnitude = signed ? Math.abs(n) : n;+ const body = trimWhole && Number.isInteger(magnitude) ? String(magnitude) : magnitude.toFixed(2);+ return `${signed && n < 0 ? '-' : ''}$${body}`;+}+/*** Format bytes as a human-readable string* @param {number} bytes - Size in bytesdiff --git a/client/src/utils/formatters.test.js b/client/src/utils/formatters.test.jsindex 3fcba0798f..4c3c3a03d7 100644--- a/client/src/utils/formatters.test.js+++ b/client/src/utils/formatters.test.js@@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest';import {formatContextLength, formatDurationMin, formatDurationMs, formatEventDateTime, timeAgo,formatCooldown, parseSizeGb, recommendedRamGb, parseTimeoutMs, formatDurationSec, middleTruncate,- formatWeight, formatPercent,+ formatWeight, formatPercent, formatUsd,} from './formatters.js';describe('formatWeight', () => {@@ -45,6 +45,26 @@ describe('formatWeight', () => {});});+describe('formatUsd', () => {+ it('renders cents by default and treats a missing amount as zero', () => {+ expect(formatUsd(12.3)).toBe('$12.30');+ expect(formatUsd(null)).toBe('$0.00');+ });++ // The minus belongs OUTSIDE the dollar sign, so a negative saving reads as a+ // loss instead of as a malformed currency string.+ it('puts the sign before the dollar sign when signed', () => {+ expect(formatUsd(-5, { signed: true })).toBe('-$5.00');+ expect(formatUsd(5, { signed: true })).toBe('$5.00');+ });++ it('trims .00 only when asked', () => {+ expect(formatUsd(200, { trimWhole: true })).toBe('$200');+ expect(formatUsd(19.99, { trimWhole: true })).toBe('$19.99');+ expect(formatUsd(200)).toBe('$200.00');+ });+});+describe('formatPercent', () => {it('rounds float noise and suffixes a percent sign', () => {expect(formatPercent(18.400000000000002)).toBe('18.4%');diff --git a/server/lib/README.md b/server/lib/README.mdindex b22d8b0ca4..1b1cae822a 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -117,6 +117,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `providerVendors.js` | `PROVIDER_VENDORS` — one row per coding-agent CLI/TUI vendor (claude/codex/antigravity/opencode/grok/kimi/cursor, plus a deliberately-incomplete legacy `gemini-cli` row), consumed by every dispatch site that used to hand-roll its own vendor if-chain across ~8 branches in 5 files (#3618): `applyCommandDefaults`/`prepareCliPrompt` (re-exported from `tuiHandshake.js`/`cliProviderArgs.js`), `buildVendorCliArgs`/`buildVendorSpawnConfig` (consumed by `cliProviderArgs.js#buildCliArgs` / `agentCliSpawning.js#buildCliSpawnConfig`), `inferTuiCommand` (re-exported from `tuiHandshake.js`), and `injectTuiModelAndEffort` — the shared antigravity-validates-the-pair-vs-everyone-else `--model`/`--effort` injection used by both `tuiHandshake.js#buildTuiInvocation` and `agentTuiSpawning.js#buildTuiSpawnConfig`, replacing a second copy of that split that had already drifted once before this file existed. Doesn't rewrite any vendor's argv-building logic — that stays in `antigravity.js`/`grok.js`/`kimi.js`/`cursor.js`/`codex.js`. Dependency-light on purpose, mirroring those files. || `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; also derives `cacheReadPer1M`/`cacheWritePer1M` from the input rate via per-family multipliers), `isFreeProvider` (ollama/lmstudio/`ollamaBacked`/localhost = free), `estimateCostUsd(tokensIn, tokensOut, rates, cache?)` — `tokensIn` is UNCACHED input; cache tiers are priced separately via the optional 4th arg — and `PRICING_AS_OF`. Informational only (PortOS runs on subscriptions); still excludes batch/long-context tiers. || `usageRange.js` | `resolveUsageRange({ period, from, to })` — pure period→inclusive-YYYY-MM-DD range resolution for the usage cost report (explicit dates win; `all` unbounded; default 7d). |+| `subscriptionSavings.js` | Subscription-vs-API savings math for the usage page — `resolveSavingsWindow` (clamps an open-ended report range to today / first activity day), `prorateMonthlyCost` (monthly plan price → this window's share, `DAYS_PER_MONTH`, capped by `MAX_MONTHLY_COST`), `savingsPercent` / `costMultiplier` (null, never 0, when the comparison is undefined), `attributeReportCostToFamilies` (groups report rows by their stamped `family`), `roundCents` (the one money rounder), and `buildSubscriptionSavings({ entries, range, unmatchedApiCost })` → per-family rows + totals. Pure. |+| `providerFamilies.js` | Subscription-quota FAMILY identity — `PROVIDER_FAMILIES` (`{ id, label, matches }` for claude/codex/agy/grok), `PROVIDER_FAMILY_IDS`, `familyLabel`, `familyForProvider(config)` → family id or null (Ollama-backed wrappers and API-only providers belong to none). The pure half of the registry `services/providerUsage.js` attaches quota `fetch`ers to, so cost attribution and route validation can ask "which plan is this provider on?" without importing the PTY-scrape graph. Distinct from `providerVendors.js`, which is argv-shaped and includes vendors with no subscription quota. || `providerTranscriptUsage.js` | Parsers for the real per-message token counts the coding CLIs write to disk (0 tokens to read) — `parseClaudeTranscript` (`~/.claude/projects/<cwd-slug>/*.jsonl`), `parseCodexRollout` (`~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`), `claudeProjectSlug`, `totalTranscriptTokens`. Both de-duplicate a format hazard that otherwise inflates counts badly: Claude repeats one response across several lines sharing a `message.id`, and Codex's `total_token_usage` is cumulative and repeated. Each parser returns per-model buckets (`byModel`) plus the message keys it counted (`countedKeys`), and accepts an `exclude` set — that is what stops two overlapping PortOS runs from both billing the same messages. Tolerant of truncated (mid-write) files; consumed by `services/usageReconciler.js`. || `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. || `cliChildEnv.js` | The one place the AI-CLI child environment is composed, replacing the hand-rolled copy every spawn site carried — which made each env-level fix an N-file sweep (#3194). `buildCliChildEnv({ baseEnv, before, provider, model, cwd, extra, guard })` returns a COMPLETE env for `spawn`: layers `baseEnv → before → provider.envVars → buildOpencodeEnvVars → extra`, pins `PWD` to `cwd`, strips `CLAUDECODE`, and (with `guard: true`) prepends the pm2 guard shim onto the final `PATH`. `composeProviderEnv({ before, provider, model, extra })` returns just the ordered provider layers, for sites that build a DELTA someone else bases and spawns (the CoS runner payload, a shell-session overlay). The two slots are not interchangeable: `before` sits UNDER `provider.envVars` (forgeTokenEnv/claudeSettingsEnv, so a provider override still wins), `extra` sits OVER it (TERM/COLORTERM for a PTY). `cliChildEnv.test.js` asserts the composed order per call site and **discovers** any new site that hand-rolls the tuple instead of calling these — so the call-site list stays in the test, not in prose here. |diff --git a/server/lib/index.js b/server/lib/index.jsindex edb219afb5..0a9bbfc46f 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -256,6 +256,8 @@ export * from './migrationMarker.js';export * from './modelPricing.js';export * from './navManifest.js';export * from './usageRange.js';+export * from './subscriptionSavings.js';+export * from './providerFamilies.js';export * from './personaTraitBlend.js';export * from './pipelineIssueOrder.js';export * from './postAdaptive.js';diff --git a/server/lib/providerFamilies.js b/server/lib/providerFamilies.jsnew file mode 100644index 0000000000..9b2be3f7e8--- /dev/null+++ b/server/lib/providerFamilies.js@@ -0,0 +1,62 @@+import { commandBasename, isClaudeCommand } from './providerModels.js';+import { isGrokCommand } from './grok.js';++/**+ * Subscription-quota FAMILY identity: which provider configs belong to the same+ * paid plan (`claude`, `codex`, `agy`, `grok`).+ *+ * This is the pure half of the registry `server/services/providerUsage.js`+ * drives — that service attaches a `fetch` per family, and those fetches spawn+ * PTYs to scrape a CLI's `/usage` panel. Identity has no business dragging that+ * graph in: pricing, cost attribution, and route validation all need to answer+ * "which plan is this provider on?" without being able to start a subprocess.+ *+ * Distinct from `lib/providerVendors.js`, which is argv-shaped and includes+ * vendors with no subscription quota to meter (opencode, kimi, cursor).+ */++/**+ * 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 (see `familyForProvider`).+ */+export const PROVIDER_FAMILIES = [+ {+ id: 'claude',+ label: 'Claude Code',+ matches: (p) => (p.type === 'cli' || p.type === 'tui') && isClaudeCommand(p.command)+ },+ {+ id: 'codex',+ label: 'Codex',+ matches: (p) => commandBasename(p.command) === 'codex'+ },+ {+ id: 'agy',+ label: 'Antigravity',+ matches: (p) => commandBasename(p.command) === 'agy' || /antigravity/i.test(p.id || '')+ },+ {+ id: 'grok',+ label: 'Grok',+ matches: (p) => isGrokCommand(p.command) || /grok/i.test(p.id || '')+ }+];++/** Every family id, for schemas that must accept only a real family. */+export const PROVIDER_FAMILY_IDS = PROVIDER_FAMILIES.map((f) => f.id);++/** The human label for a family id, falling back to the id itself. Pure. */+export const familyLabel = (id) => PROVIDER_FAMILIES.find((f) => f.id === id)?.label || id;++/**+ * The family id a single provider config belongs to, or null for one that+ * belongs to none (an Ollama-backed wrapper, a pay-as-you-go API provider).+ * The inverse of `resolveEnabledFamilies`, so cost reporting can attribute a+ * provider's spend to the subscription that actually covered it.+ */+export function familyForProvider(provider) {+ if (!provider || provider.ollamaBacked === true) return null;+ return PROVIDER_FAMILIES.find((f) => f.matches(provider))?.id ?? null;+}diff --git a/server/lib/subscriptionSavings.js b/server/lib/subscriptionSavings.jsnew file mode 100644index 0000000000..14fa7aaf70--- /dev/null+++ b/server/lib/subscriptionSavings.js@@ -0,0 +1,161 @@+import { ymdToUTC } from './postStreak.js';++/**+ * Subscription-vs-API savings math for the /devtools/usage cost report — pure,+ * so the shape can be unit-tested without a settings file or a provider config.+ *+ * PortOS runs on flat-rate subscriptions (Claude Max, ChatGPT Pro, …) while the+ * cost report prices the same traffic at published API rates. The interesting+ * number is the difference: what the quota plans saved over paying per token.+ * That comparison only means anything if BOTH sides cover the same window, so a+ * monthly plan price is prorated across the report range rather than compared+ * whole against a 7-day API estimate.+ */++// Average Gregorian month. A plan is billed per calendar month, so proration+// uses the average month length rather than 30 — over a year the two differ by+// five days of subscription cost, which is real money on a $200/mo plan.+export const DAYS_PER_MONTH = 365.25 / 12;++// A plan price is a monthly USD figure. The ceiling is a typo guard (a fat-+// fingered "20000" for $200/mo would otherwise silently swamp every savings+// figure on the page), not a product limit. Defined here so the route schema+// and the settings normalizer enforce ONE number.+export const MAX_MONTHLY_COST = 100000;++/** Round a dollar amount to whole cents. Shared by every money figure PortOS derives. */+export const roundCents = (n) => Math.round(n * 100) / 100;++const isDay = (value) => typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value);++/** Pure: inclusive day count between two YYYY-MM-DD days (UTC calendar days). */+const inclusiveDays = (start, end) => Math.floor((ymdToUTC(end) - ymdToUTC(start)) / 86400000) + 1;++/**+ * Resolve the window the subscription cost is prorated over, as+ * `{ start, end, days }` (days is 0 when the window is empty).+ *+ * The report's range is open-ended on both sides, and each open end has a+ * different correct answer:+ * - No `to` (or a `to` in the future) → today. A window that runs to the end of+ * next month must not bill next month's subscription today.+ * - No `from` ("All time") → the first day usage was actually recorded. Falling+ * back to today instead would price all-time savings over a single day, and+ * falling back to epoch would invent years of subscription spend.+ *+ * @param {{ from?: string|null, to?: string|null, firstActivityDay?: string|null, today: string }} args+ */+export function resolveSavingsWindow({ from = null, to = null, firstActivityDay = null, today }) {+ if (!isDay(today)) throw new TypeError('resolveSavingsWindow: today must be a YYYY-MM-DD day');+ const end = isDay(to) && to < today ? to : today;+ const start = isDay(from) ? from : (isDay(firstActivityDay) ? firstActivityDay : null);+ if (!start || start > end) return { start: start || null, end, days: 0 };+ return { start, end, days: inclusiveDays(start, end) };+}++/** Pure: what a monthly plan price costs over `days` days, in whole cents. */+export function prorateMonthlyCost(monthlyCost, days) {+ if (!(monthlyCost > 0) || !(days > 0)) return 0;+ return roundCents((monthlyCost * days) / DAYS_PER_MONTH);+}++/**+ * Percent of the API bill a subscription avoided, or null when there is no API+ * bill to compare against. Null rather than 0 or 100 on purpose: "we cannot+ * express this as a percentage" is not "you saved nothing" (see the+ * sentinel-vs-empty convention in CLAUDE.md), and a UI that prints 0% for an+ * unused-but-paid-for plan is stating a falsehood about the plan.+ */+export function savingsPercent(apiCost, savings) {+ if (!(apiCost > 0)) return null;+ return Math.round((savings / apiCost) * 100);+}++/**+ * Value returned per dollar of subscription spend (API cost ÷ prorated plan+ * cost), rounded to one decimal. Null when nothing is being paid — an infinite+ * multiplier is not a number a card can render.+ */+export function costMultiplier(apiCost, periodCost) {+ if (!(periodCost > 0)) return null;+ return Math.round((apiCost / periodCost) * 10) / 10;+}++/**+ * Pure: group a cost report's provider rows by the subscription family that+ * covered them, as `{ byFamily: Map<familyId, usd>, unmatched: usd }`.+ *+ * `buildUsageReport` stamps each row's `family` from the live provider config+ * it already had in hand, so this is a plain groupBy — a row with no family+ * (uninstalled provider, `legacy`, `unknown`, a pay-as-you-go API provider)+ * lands in `unmatched` and is reported on its own rather than being credited to+ * a plan no one was paying.+ */+export function attributeReportCostToFamilies(report) {+ const byFamily = new Map();+ let unmatched = 0;+ for (const row of report?.providers || []) {+ const cost = Number(row?.estimatedCost) || 0;+ if (cost <= 0) continue;+ if (!row.family) { unmatched += cost; continue; }+ byFamily.set(row.family, (byFamily.get(row.family) || 0) + cost);+ }+ return { byFamily, unmatched };+}++/**+ * Build the savings block from per-family `{ family, label, monthlyCost,+ * apiCost }` entries and a resolved window (prices already normalized by the+ * settings layer — this is arithmetic, not validation).+ *+ * Every entry is returned, including plans priced at 0 — that is the editor's+ * row list, and a family the user has not priced yet must still be visible and+ * editable. Only priced plans (`configured`) contribute to the totals, so an+ * unpriced plan reads as "not counted", never as "free".+ *+ * `unmatchedApiCost` is API-billed usage that belongs to no subscription family.+ * It is reported separately instead of being folded into savings: no plan+ * covered it, so counting it as saved would overstate the plans' value.+ *+ * @param {{ entries: Array, range: { start: string|null, end: string, days: number }, unmatchedApiCost?: number }} args+ */+export function buildSubscriptionSavings({ entries = [], range, unmatchedApiCost = 0 }) {+ const days = range?.days || 0;+ const families = entries.map((entry) => {+ const monthlyCost = entry.monthlyCost > 0 ? entry.monthlyCost : 0;+ const apiCost = roundCents(Number(entry.apiCost) || 0);+ const configured = monthlyCost > 0;+ const periodCost = prorateMonthlyCost(monthlyCost, days);+ return {+ family: entry.family,+ label: entry.label,+ enabled: entry.enabled !== false,+ monthlyCost,+ configured,+ periodCost,+ apiCost,+ savings: configured ? roundCents(apiCost - periodCost) : 0,+ multiplier: configured ? costMultiplier(apiCost, periodCost) : null+ };+ });++ const priced = families.filter((f) => f.configured);+ const periodCost = roundCents(priced.reduce((sum, f) => sum + f.periodCost, 0));+ const apiCost = roundCents(priced.reduce((sum, f) => sum + f.apiCost, 0));+ const savings = roundCents(apiCost - periodCost);++ return {+ range,+ configured: priced.length > 0,+ families,+ unmatchedApiCost: roundCents(Number(unmatchedApiCost) || 0),+ totals: {+ monthlyCost: roundCents(priced.reduce((sum, f) => sum + f.monthlyCost, 0)),+ periodCost,+ apiCost,+ savings,+ savingsPercent: savingsPercent(apiCost, savings),+ multiplier: costMultiplier(apiCost, periodCost)+ }+ };+}diff --git a/server/lib/subscriptionSavings.test.js b/server/lib/subscriptionSavings.test.jsnew file mode 100644index 0000000000..488f0aecc8--- /dev/null+++ b/server/lib/subscriptionSavings.test.js@@ -0,0 +1,160 @@+import { describe, it, expect } from 'vitest';+import {+ DAYS_PER_MONTH,+ resolveSavingsWindow,+ prorateMonthlyCost,+ savingsPercent,+ costMultiplier,+ attributeReportCostToFamilies,+ buildSubscriptionSavings+} from './subscriptionSavings.js';++const window7 = { start: '2026-02-01', end: '2026-02-07', days: 7 };+const window30 = { start: '2026-02-01', end: '2026-03-02', days: 30 };++describe('resolveSavingsWindow', () => {+ it('counts an explicit range inclusively', () => {+ expect(resolveSavingsWindow({ from: '2026-02-01', to: '2026-02-07', today: '2026-03-01' }))+ .toEqual(window7);+ });++ it('clamps an open end to today rather than billing the future', () => {+ expect(resolveSavingsWindow({ from: '2026-02-25', to: null, today: '2026-03-01' }))+ .toEqual({ start: '2026-02-25', end: '2026-03-01', days: 5 });+ });++ it('clamps a future `to` to today', () => {+ expect(resolveSavingsWindow({ from: '2026-02-25', to: '2026-12-31', today: '2026-03-01' }).end)+ .toBe('2026-03-01');+ });++ it('starts an unbounded range at the first recorded activity', () => {+ expect(resolveSavingsWindow({ firstActivityDay: '2026-01-30', today: '2026-02-01' }))+ .toEqual({ start: '2026-01-30', end: '2026-02-01', days: 3 });+ });++ it('is empty when nothing has been recorded yet', () => {+ expect(resolveSavingsWindow({ today: '2026-02-01' })).toEqual({ start: null, end: '2026-02-01', days: 0 });+ });++ it('is empty when the window starts after it ends', () => {+ expect(resolveSavingsWindow({ from: '2026-05-01', to: null, today: '2026-02-01' }).days).toBe(0);+ });++ it('crosses a leap day correctly', () => {+ expect(resolveSavingsWindow({ from: '2028-02-27', to: '2028-03-01', today: '2028-06-01' }).days).toBe(4);+ });++ it('rejects a caller that forgot to pass today', () => {+ expect(() => resolveSavingsWindow({ from: '2026-01-01' })).toThrow(TypeError);+ });+});++describe('prorateMonthlyCost', () => {+ it('charges a full average month for a month-long window', () => {+ expect(prorateMonthlyCost(200, DAYS_PER_MONTH)).toBe(200);+ });++ it('charges a week of a $200 plan', () => {+ expect(prorateMonthlyCost(200, 7)).toBeCloseTo(46.0, 1);+ });++ it('treats an unpriced, negative, or zero-day plan as costing nothing', () => {+ expect(prorateMonthlyCost(0, 30)).toBe(0);+ expect(prorateMonthlyCost(-5, 30)).toBe(0);+ expect(prorateMonthlyCost(200, 0)).toBe(0);+ });+});++describe('savingsPercent / costMultiplier', () => {+ it('reports the share of the API bill avoided', () => {+ expect(savingsPercent(1000, 800)).toBe(80);+ });++ // The distinction the sentinel convention exists for: an unused plan has no+ // percentage, which is NOT the same statement as "you saved 0%".+ it('returns null, not 0, when there is nothing to divide by', () => {+ expect(savingsPercent(0, -50)).toBeNull();+ expect(costMultiplier(500, 0)).toBeNull();+ });++ it('reports API value per dollar of plan spend', () => {+ expect(costMultiplier(500, 50)).toBe(10);+ expect(costMultiplier(0, 50)).toBe(0);+ });+});++describe('attributeReportCostToFamilies', () => {+ const report = {+ providers: [+ { id: 'claude-code', family: 'claude', estimatedCost: 100 },+ { id: 'claude-tui', family: 'claude', estimatedCost: 20 },+ { id: 'codex-cli', family: 'codex', estimatedCost: 25 },+ { id: 'legacy', family: null, estimatedCost: 12.5 },+ { id: 'ollama-local', family: null, estimatedCost: 0 }+ ]+ };++ it('sums each family and leaves unattributed rows out of it', () => {+ const { byFamily, unmatched } = attributeReportCostToFamilies(report);+ expect(byFamily.get('claude')).toBe(120);+ expect(byFamily.get('codex')).toBe(25);+ expect(unmatched).toBe(12.5);+ });++ it('is empty-safe on a missing report', () => {+ expect(attributeReportCostToFamilies(null)).toEqual({ byFamily: new Map(), unmatched: 0 });+ });+});++describe('buildSubscriptionSavings', () => {+ const entries = [+ { family: 'claude', label: 'Claude Code', monthlyCost: 200, apiCost: 812.44 },+ { family: 'codex', label: 'Codex', monthlyCost: 0, apiCost: 40 }+ ];++ it('prices each plan over the window and totals only the priced ones', () => {+ const result = buildSubscriptionSavings({ entries, range: window30 });+ const claude = result.families.find((f) => f.family === 'claude');+ expect(claude.configured).toBe(true);+ expect(claude.periodCost).toBeCloseTo(197.12, 1);+ expect(claude.savings).toBeCloseTo(615.32, 1);+ expect(result.totals.apiCost).toBe(812.44); // codex is unpriced → excluded+ expect(result.totals.monthlyCost).toBe(200);+ expect(result.configured).toBe(true);+ expect(result.range).toBe(window30);+ });++ it('keeps unpriced plans visible but out of the totals', () => {+ const codex = buildSubscriptionSavings({ entries, range: window30 }).families.find((f) => f.family === 'codex');+ expect(codex).toMatchObject({ configured: false, periodCost: 0, savings: 0, multiplier: null });+ expect(codex.apiCost).toBe(40);+ });++ it('reports a plan that cost more than it did as a negative saving', () => {+ const result = buildSubscriptionSavings({+ entries: [{ family: 'grok', label: 'Grok', monthlyCost: 300, apiCost: 1 }],+ range: window30+ });+ expect(result.totals.savings).toBeLessThan(0);+ expect(result.totals.multiplier).toBeCloseTo(0, 1);+ });++ it('reports uncovered API spend separately from savings', () => {+ const result = buildSubscriptionSavings({ entries, range: window30, unmatchedApiCost: 12.5 });+ expect(result.unmatchedApiCost).toBe(12.5);+ expect(result.totals.savings).toBeCloseTo(615.32, 1); // unaffected+ });++ it('is empty-but-valid with no families', () => {+ const result = buildSubscriptionSavings({ entries: [], range: window7 });+ expect(result).toMatchObject({ configured: false, families: [], unmatchedApiCost: 0 });+ expect(result.totals).toMatchObject({ periodCost: 0, apiCost: 0, savings: 0, savingsPercent: null, multiplier: null });+ });++ it('charges nothing for a zero-day window', () => {+ const result = buildSubscriptionSavings({ entries, range: { start: null, end: '2026-02-01', days: 0 } });+ expect(result.totals.periodCost).toBe(0);+ expect(result.families[0].configured).toBe(true); // still priced, just not billed+ });+});diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 59433aa97d..f3b693118d 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -2,6 +2,8 @@ import { z } from 'zod';import { ServerError } from './errorHandler.js';import { partialWithoutDefaults, emptyToUndefined, emptyToNull, optionalBooleanMap } from './zodCompat.js';import { WORK_TRACKERS } from './workTracker.js';+import { PROVIDER_FAMILY_IDS } from './providerFamilies.js';+import { MAX_MONTHLY_COST } from './subscriptionSavings.js';import { SPRITE_ID_PATTERN, SPRITE_RECORD_KINDS } from '../services/sprites/recordsLogic.js';import { ANCHOR_DIRECTIONS, SPRITE_DIRECTIONS, TURNAROUND_ID } from '../services/sprites/prompts.js';import { CHROMA_KEY_HEXES } from '../services/sprites/chromaKey.js';@@ -822,6 +824,31 @@ export const usageMessagesSchema = z.object({inputTokenCount: z.number().int().nonnegative().optional().default(0)});+/**+ * What the user pays monthly for each provider family's quota plan, keyed by+ * family id. Used by BOTH write paths — `PUT /api/usage/subscriptions` (wrapped+ * below) and the `subscriptionCosts` slice of `PUT /api/settings` — so a price+ * can't be written past validation through the generic settings endpoint.+ *+ * Keys are the real family ids, not a loose id pattern: this gates a PERSISTED+ * write, and an arbitrary key would accumulate in settings.json with no editor+ * row that could ever clear it. `null` is accepted and meaningful — it CLEARS a+ * plan's price (the user cancelled it), which an omitted key must not do, since+ * the editor submits only the rows it knows about. Prices are plain USD dollars+ * (cents allowed), capped at `MAX_MONTHLY_COST` so a mistyped extra digit can't+ * swamp every savings figure on the page.+ */+// `partialRecord`, not `record`: with an enum key schema Zod 4's `record` is+// EXHAUSTIVE — it would demand a price for every family on every save, which is+// the opposite of the patch semantics the editor relies on.+export const subscriptionCostsMapSchema = z.partialRecord(+ z.enum(PROVIDER_FAMILY_IDS),+ z.number().min(0).max(MAX_MONTHLY_COST).nullable()+);++/** Body for PUT /api/usage/subscriptions. */+export const subscriptionCostsSchema = z.object({ costs: subscriptionCostsMapSchema });+// =============================================================================// PORTSdiff --git a/server/routes/settings.js b/server/routes/settings.jsindex 6c63bd80df..a525c5355a 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -10,7 +10,7 @@ import {} from '../services/mediaJobQueue/index.js';import { asyncHandler } from '../lib/errorHandler.js';import { isPlainObject } from '../lib/objects.js';-import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, imessageConfigSchema, signalConfigSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, musicSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, layeredIntelligenceSettingsSchema, imageGenGrokSettingsSchema, imageGenAgySettingsSchema, renderDefaultsSettingsSchema, videoGenSettingsSchema, validateRequest } from '../lib/validation.js';+import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, imessageConfigSchema, signalConfigSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, musicSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, layeredIntelligenceSettingsSchema, imageGenGrokSettingsSchema, imageGenAgySettingsSchema, renderDefaultsSettingsSchema, videoGenSettingsSchema, subscriptionCostsMapSchema, validateRequest } from '../lib/validation.js';const router = Router();@@ -252,6 +252,14 @@ router.put('/', asyncHandler(async (req, res) => {if (req.body.layeredIntelligence) {validateRequest(layeredIntelligenceSettingsSchema.partial(), req.body.layeredIntelligence);}+ // Subscription plan prices — the same schema PUT /api/usage/subscriptions+ // enforces, so a legacy client or restore bundle can't write a junk family+ // key or an over-cap price through the generic settings endpoint. Without it+ // the value persists, reads back as "not priced", and is silently deleted by+ // the next save from the usage page.+ if (req.body?.subscriptionCosts !== undefined) {+ validateRequest(subscriptionCostsMapSchema, req.body.subscriptionCosts);+ }// User-defined catalog types moved out of settings.json into PostgreSQL// (`catalog_user_types`, #1001). The `/api/catalog/types` routes are the only// write path; a `catalogUserTypes` key in a PUT /api/settings body (legacydiff --git a/server/routes/usage.js b/server/routes/usage.jsindex 48c6616d7f..1077690a88 100644--- a/server/routes/usage.js+++ b/server/routes/usage.js@@ -4,7 +4,8 @@ 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, usageMessagesSchema, providerUsageQuerySchema } from '../lib/validation.js';+import { validateRequest, usageQuerySchema, usageMessagesSchema, providerUsageQuerySchema, subscriptionCostsSchema } from '../lib/validation.js';+import { saveSubscriptionCosts, getSubscriptionSavings } from '../services/subscriptionCosts.js';import { resolveUsageRange } from '../lib/usageRange.js';import { WAIT } from '../lib/staleWhileRevalidate.js';import {@@ -22,7 +23,26 @@ router.get('/', asyncHandler(async (req, res) => {const result = await getAllProviders();const providers = Array.isArray(result) ? result : (result?.providers || []);const summary = usage.getUsageSummary({ from, to, providers });- res.json(summary);+ // The report prices this window's usage at published API rates; the savings+ // block says what the user's flat-rate plans cost over the SAME window, so+ // the headline figure has something to be compared against.+ const subscriptionSavings = await getSubscriptionSavings({+ report: summary.report,+ providers,+ from,+ to,+ // Only an unbounded ("All time") window needs a start day inferred from+ // history; every other range already has one, so don't pay the scan.+ firstActivityDay: from ? null : usage.getFirstActivityDay()+ });+ res.json({ ...summary, subscriptionSavings });+}));++// PUT /api/usage/subscriptions - Merge plan prices. An omitted family keeps its+// stored price; one sent as null (or 0) is cleared.+router.put('/subscriptions', asyncHandler(async (req, res) => {+ const { costs } = validateRequest(subscriptionCostsSchema, req.body);+ res.json({ costs: await saveSubscriptionCosts(costs) });}));// GET /api/usage/providers - Subscription-quota status for every enableddiff --git a/server/routes/usage.test.js b/server/routes/usage.test.jsindex bbd50b6b7f..6b270ced12 100644--- a/server/routes/usage.test.js+++ b/server/routes/usage.test.js@@ -6,12 +6,18 @@ import { errorMiddleware } from '../lib/errorHandler.js';vi.mock('../services/usage.js', () => ({getUsageSummary: vi.fn(),getUsage: vi.fn(),+ getFirstActivityDay: vi.fn(() => '2026-01-01'),recordSession: vi.fn(),recordMessages: vi.fn(),recordTokens: vi.fn(),resetUsage: vi.fn()}));+vi.mock('../services/subscriptionCosts.js', () => ({+ saveSubscriptionCosts: vi.fn(async (costs) => costs),+ getSubscriptionSavings: vi.fn(async () => ({ configured: false, families: [] }))+}));+vi.mock('../services/providers.js', () => ({// getAllProviders returns the wrapped { activeProvider, providers } shape —// the route must unwrap `.providers` before passing to getUsageSummary.@@ -35,6 +41,7 @@ import * as usage from '../services/usage.js';import { getAllProviders } from '../services/providers.js';import { getProviderQuotas } from '../services/providerUsage.js';import { getHistoricalUsageBackfillStatus, startHistoricalUsageBackfill } from '../services/usageBackfill.js';+import { getSubscriptionSavings, saveSubscriptionCosts } from '../services/subscriptionCosts.js';import usageRoutes from './usage.js';const buildApp = () => {@@ -54,7 +61,11 @@ describe('usage routes', () => {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'] });+ expect(res.body).toEqual({+ totalSessions: 4,+ providers: ['anthropic'],+ subscriptionSavings: { configured: false, families: [] }+ });const arg = usage.getUsageSummary.mock.calls[0][0];expect(arg.from).toMatch(/^\d{4}-\d{2}-\d{2}$/);expect(arg.to).toBeNull();@@ -102,6 +113,64 @@ describe('usage routes', () => {expect(res.status).toBe(400);});+ it('GET /api/usage prorates the savings block over the same window as the report', async () => {+ usage.getUsageSummary.mockReturnValue({ report: { totals: { estimatedCost: 12 } } });+ getAllProviders.mockResolvedValue({ activeProvider: null, providers: [{ id: 'claude-code' }] });+ const res = await request(buildApp()).get('/api/usage?from=2026-02-01&to=2026-02-07');+ expect(res.status).toBe(200);+ expect(getSubscriptionSavings).toHaveBeenCalledWith({+ report: { totals: { estimatedCost: 12 } },+ providers: [{ id: 'claude-code' }],+ from: '2026-02-01',+ to: '2026-02-07',+ firstActivityDay: null+ });+ });++ // Only an unbounded window needs a start day inferred from history; paying+ // for the scan on every 7d/30d request would throw the result away.+ it('GET /api/usage only reads the first activity day for an unbounded range', async () => {+ usage.getUsageSummary.mockReturnValue({});+ await request(buildApp()).get('/api/usage?period=7d');+ expect(usage.getFirstActivityDay).not.toHaveBeenCalled();++ await request(buildApp()).get('/api/usage?period=all');+ expect(usage.getFirstActivityDay).toHaveBeenCalled();+ });++ it('PUT /api/usage/subscriptions saves a price patch, including a null clear', async () => {+ const res = await request(buildApp())+ .put('/api/usage/subscriptions')+ .send({ costs: { claude: 200, codex: null } });+ expect(res.status).toBe(200);+ expect(saveSubscriptionCosts).toHaveBeenCalledWith({ claude: 200, codex: null });+ });++ it('PUT /api/usage/subscriptions rejects a non-numeric price', async () => {+ const res = await request(buildApp())+ .put('/api/usage/subscriptions')+ .send({ costs: { claude: '200' } });+ expect(res.status).toBe(400);+ expect(saveSubscriptionCosts).not.toHaveBeenCalled();+ });++ // A key that isn't a real family would persist forever with no editor row to+ // clear it, so it is rejected at the edge rather than normalized away later.+ it('PUT /api/usage/subscriptions rejects an unknown family key', async () => {+ const res = await request(buildApp())+ .put('/api/usage/subscriptions')+ .send({ costs: { 'not-a-family': 10 } });+ expect(res.status).toBe(400);+ expect(saveSubscriptionCosts).not.toHaveBeenCalled();+ });++ it('PUT /api/usage/subscriptions rejects an over-cap price', async () => {+ const res = await request(buildApp())+ .put('/api/usage/subscriptions')+ .send({ costs: { claude: 100001 } });+ expect(res.status).toBe(400);+ });+it('GET /api/usage/providers returns quota entries and honors refresh', async () => {getProviderQuotas.mockResolvedValue([{ family: 'claude', supported: true, limits: [] },diff --git a/server/services/providerUsage.js b/server/services/providerUsage.jsindex c191196711..9327a5c4f4 100644--- a/server/services/providerUsage.js+++ b/server/services/providerUsage.js@@ -3,8 +3,8 @@ import { homedir } from 'os';import { join } from 'path';import { getAllProviders } from './providers.js';import { getClaudeCodeUsage, systemTimeZone } from './claudeCodeUsage.js';-import { commandBasename, isClaudeCommand } from '../lib/providerModels.js';-import { isGrokCommand } from '../lib/grok.js';+import { commandBasename } from '../lib/providerModels.js';+import { PROVIDER_FAMILIES } from '../lib/providerFamilies.js';import { scrapeTuiUsage } from '../lib/tuiUsageScrape.js';import { createStaleWhileRevalidate, PENDING, WAIT } from '../lib/staleWhileRevalidate.js';import { parseHumanReset } from '../lib/quotaReset.js';@@ -566,37 +566,20 @@ async function fetchClaudeQuota({ wait = WAIT.CACHED } = {}) {// --- 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.+ * The quota reader for each family, keyed by the family id that+ * `lib/providerFamilies.js` defines. Identity (which provider is on which plan)+ * lives in that pure lib so cost attribution and route validation can ask+ * without importing this module's PTY-scraping graph; only the readers — which+ * genuinely spawn subprocesses — live here.*/-const FAMILIES = [- {- id: 'claude',- label: 'Claude Code',- matches: (p) => (p.type === 'cli' || p.type === 'tui') && 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: makeTuiUsageFetcher({ id: 'agy', binary: 'agy', slashCommand: '/usage', label: 'Antigravity', parse: parseAgyUsage, name: 'Antigravity CLI', readyMarker: /Weekly Limit(?:\s+Remaining)?|Five Hour Limit(?:\s+Remaining)?|Models & Quota/i })- },- {- id: 'grok',- label: 'Grok',- matches: (p) => isGrokCommand(p.command) || /grok/i.test(p.id || ''),- fetch: makeTuiUsageFetcher({ id: 'grok', binary: 'grok', slashCommand: '/usage show', label: 'Grok', parse: parseGrokUsage, name: 'Grok Build CLI', readyMarker: /(Weekly|Monthly) limit:/i })- }-];+const FAMILY_FETCHERS = {+ claude: fetchClaudeQuota,+ codex: () => fetchCodexQuota(),+ agy: makeTuiUsageFetcher({ id: 'agy', binary: 'agy', slashCommand: '/usage', label: 'Antigravity', parse: parseAgyUsage, name: 'Antigravity CLI', readyMarker: /Weekly Limit(?:\s+Remaining)?|Five Hour Limit(?:\s+Remaining)?|Models & Quota/i }),+ grok: makeTuiUsageFetcher({ id: 'grok', binary: 'grok', slashCommand: '/usage show', label: 'Grok', parse: parseGrokUsage, name: 'Grok Build CLI', readyMarker: /(Weekly|Monthly) limit:/i })+};++const FAMILIES = PROVIDER_FAMILIES.map((family) => ({ ...family, fetch: FAMILY_FETCHERS[family.id] }));/*** Distinct quota families among the enabled providers, in registry order.diff --git a/server/services/subscriptionCosts.js b/server/services/subscriptionCosts.jsnew file mode 100644index 0000000000..9ab5ac1525--- /dev/null+++ b/server/services/subscriptionCosts.js@@ -0,0 +1,129 @@+import { getSettings, updateSettingsWith } from './settings.js';+import { resolveEnabledFamilies } from './providerUsage.js';+import { familyLabel } from '../lib/providerFamilies.js';+import {+ attributeReportCostToFamilies,+ buildSubscriptionSavings,+ resolveSavingsWindow,+ roundCents,+ MAX_MONTHLY_COST+} from '../lib/subscriptionSavings.js';+import { isPlainObject } from '../lib/objects.js';++/**+ * What the user pays for each AI subscription, and what those plans saved+ * against the usage page's estimated API cost.+ *+ * The cost report already prices every recorded token at published API rates.+ * PortOS does not actually pay those rates — it runs on flat-rate quota plans —+ * so the report's headline is an opportunity cost with nothing to compare it+ * against. Recording the monthly price of each plan turns it into the number+ * the user actually wants: "my subscriptions cost $X this week and did $Y of+ * API-rate work."+ *+ * Prices are per-install configuration, stored in `data/settings.json` under+ * `subscriptionCosts` as `{ [familyId]: monthlyUsd }` — a plan price is local+ * to the person paying it and never rides the federation layer.+ */++const SETTINGS_KEY = 'subscriptionCosts';++/**+ * Pure: a stored/incoming plan price as a number, or null for "no plan".+ *+ * ONE definition of the rule, used on both read and write, so a price can never+ * mean different things depending on which side of the store you read it from.+ * 0, negative, unparseable, and above-the-cap all collapse to null — a CLEARED+ * plan, not a $0 plan — so `configured` downstream means "the user told us what+ * this costs", never "we assumed it was free". The route schema rejects an+ * over-cap price outright (400); this is the backstop for a value that reached+ * settings.json some other way.+ */+export function normalizeCost(value) {+ const cost = Number(value);+ if (!Number.isFinite(cost) || cost <= 0 || cost > MAX_MONTHLY_COST) return null;+ return roundCents(cost);+}++/** Pure: normalize a whole cost map, dropping every cleared/invalid entry. */+export function normalizeSubscriptionCosts(raw) {+ if (!isPlainObject(raw)) return {};+ const out = {};+ for (const [family, value] of Object.entries(raw)) {+ const cost = normalizeCost(value);+ if (cost !== null) out[family] = cost;+ }+ return out;+}++/** Stored monthly plan prices, `{ [family]: monthlyUsd }`. */+export async function getSubscriptionCosts() {+ const settings = await getSettings();+ return normalizeSubscriptionCosts(settings?.[SETTINGS_KEY]);+}++/**+ * Merge a patch of plan prices into settings and return the normalized map.+ *+ * Absent key vs. present-but-empty are DIFFERENT (the LLM/merge convention in+ * CLAUDE.md applies to user edits too): a family the patch omits keeps its+ * stored price, while a family sent as `null`/`0` is an intentional clear and+ * is deleted. Without that split, an editor that only submits changed rows+ * could never remove a plan the user cancelled.+ */+export async function saveSubscriptionCosts(patch) {+ const incoming = isPlainObject(patch) ? patch : {};+ const next = await updateSettingsWith((current) => {+ const merged = { ...normalizeSubscriptionCosts(current?.[SETTINGS_KEY]) };+ for (const [family, value] of Object.entries(incoming)) {+ const cost = normalizeCost(value);+ if (cost === null) delete merged[family];+ else merged[family] = cost;+ }+ return { ...current, [SETTINGS_KEY]: merged };+ });+ return normalizeSubscriptionCosts(next?.[SETTINGS_KEY]);+}++/**+ * The families the editor offers, as `{ family, label, enabled }`: every+ * enabled provider family, plus any family that is priced or that ran up API+ * cost inside the report window even though its provider is no longer enabled.+ *+ * Those extras matter. Dropping a priced-but-disabled family would hide — and+ * on the next save, silently discard — the price of a plan whose provider the+ * user merely toggled off. Dropping one with spend in-window would strand that+ * spend in "usage no subscription covers" with no row to price it, so the user+ * could never account for it at all.+ */+export function resolveSubscriptionFamilies(providers, costs = {}, spentFamilyIds = []) {+ const enabled = resolveEnabledFamilies(providers).map((f) => ({ family: f.id, label: f.label, enabled: true }));+ const seen = new Set(enabled.map((f) => f.family));+ const extras = [...new Set([...Object.keys(costs), ...spentFamilyIds])]+ .filter((family) => !seen.has(family))+ .map((family) => ({ family, label: familyLabel(family), enabled: false }));+ return [...enabled, ...extras];+}++/** Today as a UTC `YYYY-MM-DD` — the calendar usage.js keys its day buckets by. */+const utcToday = () => new Date().toISOString().split('T')[0];++/**+ * The savings block served alongside the cost report: per-family plan price,+ * prorated cost for the report window, the API-rate cost that window's usage+ * would have run to, and the difference.+ */+export async function getSubscriptionSavings({ report, providers = [], from = null, to = null, firstActivityDay = null, today = utcToday() }) {+ const costs = await getSubscriptionCosts();+ const { byFamily, unmatched } = attributeReportCostToFamilies(report);+ const entries = resolveSubscriptionFamilies(providers, costs, [...byFamily.keys()]).map((f) => ({+ ...f,+ monthlyCost: costs[f.family] ?? 0,+ apiCost: byFamily.get(f.family) || 0+ }));+ return buildSubscriptionSavings({+ entries,+ range: resolveSavingsWindow({ from, to, firstActivityDay, today }),+ unmatchedApiCost: unmatched+ });+}diff --git a/server/services/subscriptionCosts.test.js b/server/services/subscriptionCosts.test.jsnew file mode 100644index 0000000000..9bbd887dc4--- /dev/null+++ b/server/services/subscriptionCosts.test.js@@ -0,0 +1,186 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// The real settings store writes data/settings.json; this suite only cares+// about the merge semantics on top of it, so it stands in an in-memory one.+let stored = {};+vi.mock('./settings.js', () => ({+ getSettings: vi.fn(async () => structuredClone(stored)),+ updateSettingsWith: vi.fn(async (mutate) => {+ stored = await mutate(structuredClone(stored));+ return structuredClone(stored);+ })+}));++// providerUsage drags in the TUI-scrape/PTY graph. Only `resolveEnabledFamilies`+// is needed here, and it is the one piece that must know about spawnable+// providers — the pure identity half (familyForProvider/familyLabel) is+// imported for real from lib/providerFamilies.js and exercised by these tests.+vi.mock('./providerUsage.js', () => ({+ resolveEnabledFamilies: vi.fn((providers) =>+ (providers || []).filter((p) => p.enabled).map((p) => ({ id: p.expectFamily, label: p.expectLabel })))+}));++import {+ normalizeCost,+ normalizeSubscriptionCosts,+ getSubscriptionCosts,+ saveSubscriptionCosts,+ resolveSubscriptionFamilies,+ getSubscriptionSavings+} from './subscriptionCosts.js';++// Real provider-config shapes, so the family matchers in lib/providerFamilies.js+// are the thing under test rather than a stand-in that can't drift with them.+const providers = [+ { id: 'claude-code', enabled: true, type: 'cli', command: 'claude', expectFamily: 'claude', expectLabel: 'Claude Code' },+ { id: 'codex-cli', enabled: true, type: 'cli', command: 'codex', expectFamily: 'codex', expectLabel: 'Codex' }+];++beforeEach(() => {+ stored = {};+ vi.clearAllMocks();+});++describe('normalizeCost', () => {+ it('keeps a positive price, rounded to cents', () => {+ expect(normalizeCost(200)).toBe(200);+ expect(normalizeCost(20.005)).toBe(20.01);+ });++ // ONE rule for read and write: an over-cap price is cleared on both sides, so+ // it can never read as "not priced" while still sitting in settings.json.+ it('clears zero, negative, over-cap, and unparseable prices', () => {+ for (const value of [0, -1, 1e9, 'x', null, undefined, NaN]) {+ expect(normalizeCost(value)).toBeNull();+ }+ });+});++describe('normalizeSubscriptionCosts', () => {+ it('keeps positive prices and drops cleared ones', () => {+ expect(normalizeSubscriptionCosts({ claude: 200, codex: 0, agy: 1e9 })).toEqual({ claude: 200 });+ });++ it('tolerates a non-object stored value', () => {+ expect(normalizeSubscriptionCosts(null)).toEqual({});+ expect(normalizeSubscriptionCosts('nope')).toEqual({});+ });+});++describe('saveSubscriptionCosts', () => {+ it('persists a price and reads it back', async () => {+ expect(await saveSubscriptionCosts({ claude: 200 })).toEqual({ claude: 200 });+ expect(await getSubscriptionCosts()).toEqual({ claude: 200 });+ });++ it('leaves an omitted family alone but clears one sent as null', async () => {+ await saveSubscriptionCosts({ claude: 200, codex: 20 });+ expect(await saveSubscriptionCosts({ codex: null })).toEqual({ claude: 200 });+ });++ it('treats 0 as a clear, not a $0 plan', async () => {+ await saveSubscriptionCosts({ claude: 200 });+ expect(await saveSubscriptionCosts({ claude: 0 })).toEqual({});+ });++ it('preserves unrelated settings keys', async () => {+ stored = { timezone: 'UTC' };+ await saveSubscriptionCosts({ claude: 200 });+ expect(stored.timezone).toBe('UTC');+ });+});++describe('resolveSubscriptionFamilies', () => {+ it('offers every enabled family', () => {+ expect(resolveSubscriptionFamilies(providers, {})).toEqual([+ { family: 'claude', label: 'Claude Code', enabled: true },+ { family: 'codex', label: 'Codex', enabled: true }+ ]);+ });++ // Otherwise toggling a provider off would hide — and on the next save,+ // silently discard — the price of a plan the user still pays for.+ it('keeps a priced family whose provider is no longer enabled', () => {+ const rows = resolveSubscriptionFamilies(providers, { grok: 30 });+ expect(rows).toContainEqual({ family: 'grok', label: 'Grok', enabled: false });+ });++ // Without this the spend has no editor row, so it is stranded in "usage no+ // subscription covers" and the user can never account for it.+ it('offers a row for a disabled family that still has spend in the window', () => {+ const rows = resolveSubscriptionFamilies(providers, {}, ['agy']);+ expect(rows).toContainEqual({ family: 'agy', label: 'Antigravity', enabled: false });+ });++ it('does not duplicate a family that is both priced and spent', () => {+ const rows = resolveSubscriptionFamilies(providers, { grok: 30 }, ['grok']);+ expect(rows.filter((r) => r.family === 'grok')).toHaveLength(1);+ });+});++describe('getSubscriptionSavings', () => {+ it('compares a plan price against the API cost its family ran up', async () => {+ await saveSubscriptionCosts({ claude: 200 });+ const savings = await getSubscriptionSavings({+ report: { providers: [{ id: 'claude-code', family: 'claude', estimatedCost: 500 }] },+ providers,+ from: '2026-02-01',+ to: '2026-02-28',+ today: '2026-03-05'+ });+ const claude = savings.families.find((f) => f.family === 'claude');+ expect(savings.range.days).toBe(28);+ expect(claude.periodCost).toBeCloseTo(184, 0);+ expect(claude.savings).toBeCloseTo(316, 0);+ expect(savings.totals.savings).toBeCloseTo(316, 0);+ });++ it('reports API cost from a family the user has not priced as uncovered', async () => {+ const savings = await getSubscriptionSavings({+ report: { providers: [{ id: 'codex-cli', family: 'codex', estimatedCost: 25 }] },+ providers,+ from: '2026-02-01',+ to: '2026-02-07',+ today: '2026-03-05'+ });+ expect(savings.configured).toBe(false);+ expect(savings.totals.apiCost).toBe(0);+ expect(savings.families.find((f) => f.family === 'codex').apiCost).toBe(25);+ });++ it('gives spend from a no-longer-enabled family its own priceable row', async () => {+ const savings = await getSubscriptionSavings({+ report: { providers: [{ id: 'agy-cli', family: 'agy', estimatedCost: 60 }] },+ providers,+ from: '2026-02-01',+ to: '2026-02-07',+ today: '2026-03-05'+ });+ expect(savings.families.find((f) => f.family === 'agy')).toMatchObject({ apiCost: 60, enabled: false });+ expect(savings.unmatchedApiCost).toBe(0);+ });++ it('reports cost no family covers as uncovered, not as savings', async () => {+ const savings = await getSubscriptionSavings({+ report: { providers: [{ id: 'legacy', family: null, estimatedCost: 12.5 }] },+ providers,+ from: '2026-02-01',+ to: '2026-02-07',+ today: '2026-03-05'+ });+ expect(savings.unmatchedApiCost).toBe(12.5);+ expect(savings.totals.savings).toBe(0);+ });++ it('prorates an unbounded range from the first recorded activity', async () => {+ await saveSubscriptionCosts({ claude: 200 });+ const savings = await getSubscriptionSavings({+ report: { providers: [] },+ providers,+ firstActivityDay: '2026-02-01',+ today: '2026-02-10'+ });+ expect(savings.range.days).toBe(10);+ expect(savings.totals.periodCost).toBeCloseTo(65.7, 1);+ });+});diff --git a/server/services/usage.js b/server/services/usage.jsindex d454470e89..2bd84fde45 100644--- a/server/services/usage.js+++ b/server/services/usage.js@@ -1,6 +1,8 @@import { join } from 'path';import { atomicWrite, ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';import { resolveModelRates, isFreeProvider, isFreeModelId, estimateCostUsd, PRICING_AS_OF } from '../lib/modelPricing.js';+import { familyForProvider } from '../lib/providerFamilies.js';+import { roundCents } from '../lib/subscriptionSavings.js';const DATA_DIR = PATHS.data;const USAGE_FILE = join(DATA_DIR, 'usage.json');@@ -170,6 +172,32 @@ export function getUsage() {return usageData || getEmptyUsage();}+/**+ * The earliest day usage was recorded (`YYYY-MM-DD`), or null on an install+ * with no history yet. Rolled-up months only know their month, so they+ * contribute their first day — a whole-month bucket's activity cannot have+ * started earlier than that.+ *+ * Consumers: the subscription-savings window, which prorates a monthly plan+ * price over an "All time" report and needs a real start day rather than an+ * unbounded one (see lib/subscriptionSavings.js).+ */+export function getFirstActivityDay() {+ const data = getUsage();+ // Min over the keys rather than sort-then-head: on a full 400-day retention+ // window that is one linear pass instead of three intermediate arrays and an+ // O(n log n) string sort. YYYY-MM-DD compares correctly as a string.+ let earliest = null;+ const consider = (day) => { if (!earliest || day < earliest) earliest = day; };+ for (const key of Object.keys(data.dailyActivity || {})) {+ if (DAY_KEY_RE.test(key)) consider(key);+ }+ for (const key of Object.keys(data.monthlyActivity || {})) {+ if (/^\d{4}-\d{2}$/.test(key)) consider(`${key}-01`);+ }+ return earliest;+}+/*** Per-day per-provider per-model bucket inside dailyActivity — the additive* shape that makes arbitrary-period cost breakdowns possible. Missing provider@@ -643,7 +671,6 @@ 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@@ -875,6 +902,11 @@ export function buildUsageReport(dailyActivity, { from = null, to = null, providid: pid,name: p.name,free,+ // The subscription family this row's spend belongs to, stamped from the+ // config already in hand — so a consumer comparing plan cost against API+ // cost (lib/subscriptionSavings.js) groups rows without rebuilding this+ // provider-id → config map. Null for a row no plan covers.+ family: familyForProvider(config),sessions: p.sessions,messages: p.messages,tokensIn: p.tokensIn,diff --git a/server/services/usage.test.js b/server/services/usage.test.jsindex 22db129d86..a740c9f065 100644--- a/server/services/usage.test.js+++ b/server/services/usage.test.js@@ -23,6 +23,7 @@ import { atomicWrite, readJSONFile } from '../lib/fileUtils.js';import {applyHistoricalUsageCorrections,buildUsageReport,+ getFirstActivityDay,getUsage,getUsageSummary,loadUsage,@@ -287,6 +288,31 @@ describe('usage.js — streak calculations', () => {});});+ describe('getFirstActivityDay', () => {+ it('returns the earliest recorded day', async () => {+ readJSONFile.mockResolvedValueOnce(makeUsage({ [daysAgo(2)]: { sessions: 1 }, [daysAgo(9)]: { sessions: 1 } }));+ await loadUsage();+ expect(getFirstActivityDay()).toBe(daysAgo(9));+ });++ // A rolled-up month only knows its month, so it contributes its first day —+ // the subscription-savings window would otherwise start after usage that+ // predates the daily retention boundary.+ it('falls back to a rolled-up month when it predates every day bucket', async () => {+ readJSONFile.mockResolvedValueOnce(+ makeUsage({ [daysAgo(1)]: { sessions: 1 } }, { monthlyActivity: { '2024-03': { sessions: 5 } } })+ );+ await loadUsage();+ expect(getFirstActivityDay()).toBe('2024-03-01');+ });++ it('is null with no recorded history', async () => {+ readJSONFile.mockResolvedValueOnce(makeUsage({}));+ await loadUsage();+ expect(getFirstActivityDay()).toBeNull();+ });+ });+describe('time-dimensioned capture', () => {it('recordSession creates per-provider/per-model day buckets', async () => {readJSONFile.mockResolvedValueOnce(makeUsage({}));