Skip to content

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

refactor: reuse the Usage page's own parts in Subscriptions, and cut its refetches

[._.]/ Adam Eivy025ccb284e3d
diff --git a/client/src/components/models/SubscriptionsTab.jsx b/client/src/components/models/SubscriptionsTab.jsx
index 2090c0b1f7..49482a4253 100644
--- a/client/src/components/models/SubscriptionsTab.jsx
+++ b/client/src/components/models/SubscriptionsTab.jsx
@@ -1,15 +1,20 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
-import { useSearchParams } from 'react-router';
-import { AlertTriangle, CreditCard, RefreshCw, Save } from 'lucide-react';
+import { CreditCard, RefreshCw, Save } from 'lucide-react';
import * as api from '../../services/api';
import Banner from '../ui/Banner';
import BrailleSpinner from '../BrailleSpinner';
import PageSkeleton from '../ui/PageSkeleton';
import Pill from '../ui/Pill';
import ToggleSwitch from '../ToggleSwitch';
-import UsageMeter from '../usage/UsageMeter';
-import { parseCostInput } from '../usage/SubscriptionSavingsCard';
-import { formatUsd } from '../../utils/formatters';
+import ProviderQuotaBody from '../usage/ProviderQuotaBody';
+import {
+ CellValue,
+ CostInput,
+ parseCostInput,
+ rowCells,
+} from '../usage/SubscriptionSavingsCard';
+import useUrlParams from '../../hooks/useUrlParams';
+import { USAGE_PERIOD_OPTIONS, resolveUsagePeriod, DEFAULT_USAGE_PERIOD } from '../../lib/usagePeriods';
/**
* Subscriptions — which AI plans this install pays for, whether each is on, and
@@ -18,42 +23,28 @@ import { formatUsd } from '../../utils/formatters';
* The answer used to be spread across three places: enable/disable lived on the
* Providers page (per provider, not per plan), the price lived in an editor
* buried inside the Usage report, and the quota meters lived on a third card.
- * This tab is the one row per plan that joins them (#7403).
+ * This tab is the one row per plan that joins them (#7403). The money cells,
+ * the price widget and the quota ladder are the Usage page's own components, so
+ * the two surfaces cannot come to disagree about the same reading.
*
- * METADATA ONLY, and the page says so in its own copy: the toggle flips
- * PortOS-side enablement — the `enabled` flag on that family's provider records,
- * which is what `resolveEnabledFamilies` reads — and never reaches a vendor's
- * billing system. Nothing here purchases, cancels, upgrades or downgrades a
- * plan at Anthropic, OpenAI, Google or xAI.
+ * METADATA ONLY — the toggle flips PortOS-side enablement and never reaches a
+ * vendor's billing system. The contract lives with the write that implements it
+ * (`server/services/subscriptions.js`); the on-page Banner states it for the
+ * user.
*
- * Three reads, because they answer three different questions and each has its
- * own cost: `getSubscriptions` is the plan model (cheap, always), `getUsage` is
- * what the window spent (a report build), `getProviderUsage` is the live quota
- * (a multi-second CLI scrape per family, so it lands last and never blocks the
- * rows). The period lives in `?period` rather than local state, so a window is
- * shareable and survives a reload.
+ * Two reads on two different clocks: the plan rows and the quota scrape do not
+ * depend on the report window, so a period click refetches ONLY the spend
+ * figures — re-running `getProviderUsage` would respawn a multi-second CLI
+ * scrape per family for numbers that never moved.
*/
-const PERIOD_OPTIONS = [
- { id: '7d', label: '7 days' },
- { id: '30d', label: '30 days' },
- { id: '90d', label: '90 days' },
- { id: 'all', label: 'All time' },
-];
-
-const DEFAULT_PERIOD = '30d';
-
-// Empty-but-stable, so a payload that carries no rows can't re-run the memo
-// below on every render.
const NO_ROWS = [];
-const savingsTone = (savings) => (savings >= 0 ? 'text-port-success' : 'text-port-error');
-
/**
* Parse a tier input to the patch value the API expects: a trimmed label, or
* `null` to CLEAR it. Empty means "I'm not recording a tier", which must be
* SENT (as null) rather than omitted — omitting it would leave the old tier in
- * place, so a user who upgraded off a named plan could never remove the label.
+ * place, so a user who moved off a named plan could never remove the label.
*/
export function parseTierInput(raw) {
const trimmed = String(raw ?? '').trim();
@@ -61,7 +52,7 @@ export function parseTierInput(raw) {
}
/**
- * The per-family patches a row's drafts represent, or `null` when nothing
+ * The per-family patch a row's drafts represent, or `null` when nothing
* actually changed. Unchanged fields are omitted so one save never rewrites a
* value the user didn't touch, and an unparseable price is skipped rather than
* silently clearing a price that was merely fat-fingered.
@@ -83,68 +74,34 @@ export function buildRowPatch(row, draft) {
// The stored value a row's input shows while it is untouched. The draft map
// holds ONLY edited fields, so a period change (which refetches and hands down
-// fresh rows) can't clobber something the user is mid-way through typing.
+// fresh figures) can't clobber something the user is mid-way through typing.
const draftValue = (draft, key, stored) => (draft?.[key] !== undefined ? draft[key] : stored);
-/** The three derived money figures, defined once for every row. */
-const rowFigures = (savingsRow) => {
- if (!savingsRow) return [];
- return [
- { key: 'period', label: 'This period', value: savingsRow.configured ? formatUsd(savingsRow.periodCost) : null },
- { key: 'api', label: 'Est. API cost', value: formatUsd(savingsRow.apiCost) },
- {
- key: 'savings',
- label: 'Savings',
- value: savingsRow.configured ? formatUsd(savingsRow.savings, { signed: true }) : null,
- tone: savingsRow.configured ? savingsTone(savingsRow.savings) : undefined,
- },
- ];
+/**
+ * The tier to SHOW for a plan: what the user recorded, else what the install
+ * already scraped out of the CLI (`quota.plan`, the same value the Usage page
+ * pills). Without the fallback a user would type "Max 20x" for a plan PortOS
+ * already reports, and the two pages could pill different answers for one plan.
+ * The stored value stays the override — a scrape that reads `unknown` is
+ * exactly why the field exists.
+ */
+export const resolvePlanTier = (row, quota) => {
+ if (row.planTier) return row.planTier;
+ const scraped = quota?.plan;
+ return scraped && scraped !== 'unknown' ? scraped : null;
};
-function QuotaSummary({ quota }) {
- if (!quota) {
- return <p className="text-xs text-gray-500">No quota reading — the plan is off, or its CLI reports no usage surface.</p>;
- }
- if (quota.pending) {
- return (
- <div className="flex items-center gap-2 text-xs text-gray-400">
- <BrailleSpinner />
- <span>{quota.note || 'Reading quota…'}</span>
- </div>
- );
- }
- if (!quota.supported) {
- return <p className="text-xs text-gray-500">{quota.note || 'Usage reporting is not available for this provider.'}</p>;
- }
- if (quota.error) {
- return (
- <div role="status" className="flex items-start gap-1.5 text-xs text-gray-400">
- <AlertTriangle size={14} className="text-port-warning mt-0.5 shrink-0" />
- <span>{quota.error}</span>
- </div>
- );
- }
- if (!quota.limits?.length) {
- return <p className="text-xs text-gray-500">No rate-limit data reported</p>;
- }
- return (
- <div aria-label={`${quota.label} quota`}>
- {quota.limits.map((limit) => <UsageMeter key={limit.key} limit={limit} />)}
- </div>
- );
-}
-
function SubscriptionRow({ row, savingsRow, quota, draft, busy, onDraft, onSave, onToggle }) {
const patch = buildRowPatch(row, draft);
- const figures = rowFigures(savingsRow);
const toggleable = row.providers.length > 0;
+ const shownTier = resolvePlanTier(row, quota);
return (
<div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4 space-y-3">
<div className="flex items-start justify-between gap-2">
<div className="min-w-0">
<h3 className="text-sm sm:text-base font-semibold text-white truncate">
{row.label}
- {row.planTier && <Pill tone="context" size="xs" className="ml-2 align-middle">{row.planTier}</Pill>}
+ {shownTier && <Pill tone="context" size="xs" className="ml-2 align-middle">{shownTier}</Pill>}
</h3>
<p className="text-[10px] sm:text-xs text-gray-500 mt-0.5">
{toggleable
@@ -173,7 +130,9 @@ function SubscriptionRow({ row, savingsRow, quota, draft, busy, onDraft, onSave,
id={`subscription-tier-${row.family}`}
type="text"
maxLength={60}
- placeholder="e.g. Max 20x"
+ // The scraped plan name, when there is one, so the field shows what
+ // it would record rather than an invented example.
+ placeholder={quota?.plan && quota.plan !== 'unknown' ? quota.plan : 'e.g. Max 20x'}
aria-label={`Plan tier for ${row.label}`}
value={draftValue(draft, 'tier', row.planTier ?? '')}
onChange={(e) => onDraft(row.family, 'tier', e.target.value)}
@@ -181,25 +140,15 @@ function SubscriptionRow({ row, savingsRow, quota, draft, busy, onDraft, onSave,
/>
</div>
<div>
- <label htmlFor={`subscription-cost-${row.family}`} className="block text-[10px] sm:text-xs text-gray-400 mb-1">
+ <label htmlFor={`subscriptions-subscription-cost-${row.family}`} className="block text-[10px] sm:text-xs text-gray-400 mb-1">
Monthly cost
</label>
- <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"
- aria-label={`Monthly cost for ${row.label}`}
- value={draftValue(draft, 'cost', row.monthlyCost > 0 ? String(row.monthlyCost) : '')}
- onChange={(e) => onDraft(row.family, 'cost', 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"
- />
- <span className="text-gray-500 text-xs">/mo</span>
- </div>
+ <CostInput
+ row={row}
+ idPrefix="subscriptions"
+ value={draftValue(draft, 'cost', row.monthlyCost > 0 ? String(row.monthlyCost) : '')}
+ onChange={(family, value) => onDraft(family, 'cost', value)}
+ />
</div>
{patch && (
<button
@@ -214,41 +163,39 @@ function SubscriptionRow({ row, savingsRow, quota, draft, busy, onDraft, onSave,
)}
</div>
- {figures.length > 0 && (
+ {savingsRow && (
<div className="grid grid-cols-3 gap-2 text-[11px] sm:text-xs">
- {figures.map((figure) => (
- <div key={figure.key}>
- <span className="text-gray-500 block">{figure.label}</span>
- <span className={figure.tone || 'text-white'}>
- {figure.value ?? <span className="text-gray-600">not priced</span>}
- </span>
+ {rowCells(savingsRow).map((cell) => (
+ <div key={cell.key}>
+ <span className="text-gray-500 block">{cell.label}</span>
+ <CellValue cell={cell} />
</div>
))}
</div>
)}
<div className="border-t border-port-border pt-2">
- <QuotaSummary quota={quota} />
+ {quota
+ ? <ProviderQuotaBody quota={quota} showActivity={false} showNote={false} />
+ : <p className="text-xs text-gray-500">No quota reading — the plan is off, or its CLI reports no usage surface.</p>}
</div>
</div>
);
}
export default function SubscriptionsTab() {
- const [searchParams, setSearchParams] = useSearchParams();
- const period = searchParams.get('period') || DEFAULT_PERIOD;
+ const [searchParams, updateParams] = useUrlParams();
+ const period = resolveUsagePeriod(searchParams.get('period'));
- const [overview, setOverview] = useState(null);
+ const [rows, setRows] = useState(null);
const [savings, setSavings] = useState(null);
const [quotas, setQuotas] = useState(null);
- const [loading, setLoading] = useState(true);
const [drafts, setDrafts] = useState({});
- const [busyFamilies, setBusyFamilies] = useState(() => new Set());
+ const [busyFamily, setBusyFamily] = useState(null);
const loadPlans = useCallback(async () => {
const data = await api.getSubscriptions({ silent: true }).catch(() => null);
- if (data) setOverview(data);
- return data;
+ if (data?.families) setRows(data.families);
}, []);
const loadSavings = useCallback(async () => {
@@ -264,26 +211,21 @@ export default function SubscriptionsTab() {
if (data?.providers) setQuotas(data.providers);
}, []);
+ // Window-INDEPENDENT reads, once. `loadQuotas` is deliberately not awaited
+ // with the rows: it is a CLI scrape per family and must never gate the page.
useEffect(() => {
- let cancelled = false;
- setLoading(true);
- // Plans and figures gate the first paint; the quota scrape is fired
- // alongside them but never held for — it is seconds slower per family.
- Promise.all([loadPlans(), loadSavings()]).then(() => {
- if (!cancelled) setLoading(false);
- });
+ loadPlans();
loadQuotas();
- return () => { cancelled = true; };
- }, [loadPlans, loadSavings, loadQuotas]);
+ }, [loadPlans, loadQuotas]);
- const setPeriod = (id) => setSearchParams((prev) => {
- const next = new URLSearchParams(prev);
- if (id === DEFAULT_PERIOD) next.delete('period');
- else next.set('period', id);
- return next;
- }, { replace: true });
+ // Window-dependent read, re-run per period click — and only this one.
+ useEffect(() => { loadSavings(); }, [loadSavings]);
+
+ const setPeriod = (id) => updateParams(
+ { period: id === DEFAULT_USAGE_PERIOD ? null : id },
+ { replace: true },
+ );
- const rows = overview?.families ?? NO_ROWS;
const savingsByFamily = useMemo(
() => new Map((savings?.families ?? NO_ROWS).map((entry) => [entry.family, entry])),
[savings],
@@ -293,32 +235,30 @@ export default function SubscriptionsTab() {
[quotas],
);
- const withBusy = async (family, fn) => {
- setBusyFamilies((prev) => new Set(prev).add(family));
- await fn();
- setBusyFamilies((prev) => {
- const next = new Set(prev);
- next.delete(family);
- return next;
- });
- };
-
const onDraft = (family, key, value) => setDrafts((prev) => ({
...prev,
[family]: { ...prev[family], [key]: value },
}));
+ // One row saves at a time — each row's own controls are disabled while it is
+ // in flight, so a single slot says everything a set would.
+ const withBusy = async (family, fn) => {
+ setBusyFamily(family);
+ await fn();
+ setBusyFamily(null);
+ };
+
const onSave = (row, patch) => withBusy(row.family, async () => {
- // Two independent stored maps, so two calls — and both are awaited before
- // the refetch, or the rows would repaint from a half-applied save.
- if (patch.cost !== undefined) {
- await api.updateSubscriptionCosts({ [row.family]: patch.cost }, { silent: true }).catch(() => null);
- }
- if (patch.tier !== undefined) {
- await api.updateSubscriptionPlanTiers({ [row.family]: patch.tier }, { silent: true }).catch(() => null);
- }
- await Promise.all([loadPlans(), loadSavings()]);
- // Cleared only after the refetch lands: dropping the draft first would
+ // One request for both maps, and its response IS the refreshed row set —
+ // no follow-up GET. Only a PRICE moves the savings figures, so a tier-only
+ // edit must not trigger a full report + fleet rebuild.
+ const body = {};
+ if (patch.cost !== undefined) body.costs = { [row.family]: patch.cost };
+ if (patch.tier !== undefined) body.tiers = { [row.family]: patch.tier };
+ const result = await api.updateSubscriptions(body, { silent: true }).catch(() => null);
+ if (result?.families) setRows(result.families);
+ if (patch.cost !== undefined) await loadSavings();
+ // Cleared only after the new rows land: dropping the draft first would
// flash the pre-save value back onto the row in between.
setDrafts((prev) => {
const next = { ...prev };
@@ -332,11 +272,12 @@ export default function SubscriptionsTab() {
{ family: row.family, enabled: !row.enabled },
{ silent: true },
).catch(() => null);
- if (!result) return;
- // Re-read rather than patching state locally: enablement is derived from
+ if (!result?.families) return;
+ // The handler's own re-read, not a local patch: enablement is DERIVED from
// the provider records, so the server's answer is the only one that can't
// drift from what `resolveEnabledFamilies` will report next.
- await Promise.all([loadPlans(), loadSavings()]);
+ setRows(result.families);
+ await loadSavings();
// The quota card set follows enablement — a family that just went off has
// no reading to show, and one that came on needs its first scrape.
loadQuotas();
@@ -369,7 +310,7 @@ export default function SubscriptionsTab() {
</Banner>
<div className="flex flex-wrap gap-2">
- {PERIOD_OPTIONS.map((option) => (
+ {USAGE_PERIOD_OPTIONS.map((option) => (
<button
key={option.id}
type="button"
@@ -383,18 +324,18 @@ export default function SubscriptionsTab() {
))}
</div>
- {loading && (
+ {!rows && (
<PageSkeleton header="none" label="Loading subscriptions" layout="grid" gridColsClass="grid-cols-1 lg:grid-cols-2" cards={4} />
)}
- {!loading && rows.length === 0 && (
+ {rows?.length === 0 && (
<p className="text-sm text-gray-500">
No subscriptions to manage — configure a Claude, Codex, Antigravity or Grok provider, or record a plan price,
and it will appear here.
</p>
)}
- {!loading && rows.length > 0 && (
+ {rows?.length > 0 && (
<div className="grid grid-cols-1 lg:grid-cols-2 gap-3 items-start" aria-label="AI subscriptions">
{rows.map((row) => (
<SubscriptionRow
@@ -403,7 +344,7 @@ export default function SubscriptionsTab() {
savingsRow={savingsByFamily.get(row.family)}
quota={quotaByFamily.get(row.family)}
draft={drafts[row.family]}
- busy={busyFamilies.has(row.family)}
+ busy={busyFamily === row.family}
onDraft={onDraft}
onSave={onSave}
onToggle={onToggle}
diff --git a/client/src/components/models/SubscriptionsTab.test.jsx b/client/src/components/models/SubscriptionsTab.test.jsx
index f8f045a3e8..5401e8395c 100644
--- a/client/src/components/models/SubscriptionsTab.test.jsx
+++ b/client/src/components/models/SubscriptionsTab.test.jsx
@@ -6,13 +6,12 @@ const api = vi.hoisted(() => ({
getSubscriptions: vi.fn(),
getUsage: vi.fn(),
getProviderUsage: vi.fn(),
- updateSubscriptionCosts: vi.fn(),
- updateSubscriptionPlanTiers: vi.fn(),
+ updateSubscriptions: vi.fn(),
setSubscriptionEnabled: vi.fn(),
}));
vi.mock('../../services/api', () => api);
-const { default: SubscriptionsTab, buildRowPatch, parseTierInput } = await import('./SubscriptionsTab');
+const { default: SubscriptionsTab, buildRowPatch, resolvePlanTier } = await import('./SubscriptionsTab');
const claudeRow = {
family: 'claude',
@@ -47,22 +46,33 @@ beforeEach(() => {
});
api.getProviderUsage.mockResolvedValue({
providers: [{
- family: 'claude', label: 'Claude Code', supported: true, pending: false,
+ family: 'claude', label: 'Claude Code', supported: true, pending: false, plan: 'max_5x',
limits: [{ key: 'week', label: 'Weekly', percentUsed: 40, percentRemaining: 60 }],
}],
});
- api.updateSubscriptionCosts.mockResolvedValue({ costs: {} });
- api.updateSubscriptionPlanTiers.mockResolvedValue({ tiers: {} });
- api.setSubscriptionEnabled.mockResolvedValue({ family: 'codex', enabled: true, applied: true, changed: ['codex-cli'] });
+ api.updateSubscriptions.mockResolvedValue({ families: [claudeRow, codexRow] });
+ api.setSubscriptionEnabled.mockResolvedValue({
+ family: 'codex', enabled: true, applied: true, changed: ['codex-cli'],
+ families: [claudeRow, { ...codexRow, enabled: true }],
+ });
});
-describe('parseTierInput', () => {
- it('trims a label and maps an emptied field to an explicit clear', () => {
- expect(parseTierInput(' Max 20x ')).toBe('Max 20x');
- // Empty must be SENT as null, not omitted — omitting it would leave the
- // old tier on a plan the user is no longer on.
- expect(parseTierInput('')).toBeNull();
- expect(parseTierInput(' ')).toBeNull();
+describe('resolvePlanTier', () => {
+ it('prefers what the user recorded over what the CLI scraped', () => {
+ expect(resolvePlanTier(claudeRow, { plan: 'max_20x' })).toBe('Max 5x');
+ });
+
+ // Without this fallback the user would be asked to type a plan name PortOS
+ // already reports, and the two pages could pill different answers for it.
+ it('falls back to the scraped plan name when nothing was recorded', () => {
+ expect(resolvePlanTier(codexRow, { plan: 'pro' })).toBe('pro');
+ });
+
+ // 'unknown' is the scrape saying it could not read a plan — which is exactly
+ // the case the manual field exists for, so it must not be pilled as one.
+ it('shows nothing when neither side knows the plan', () => {
+ expect(resolvePlanTier(codexRow, { plan: 'unknown' })).toBeNull();
+ expect(resolvePlanTier(codexRow, undefined)).toBeNull();
});
});
@@ -113,9 +123,10 @@ describe('SubscriptionsTab', () => {
{ family: 'codex', enabled: true },
expect.anything(),
));
- // Enablement is derived from the provider records, so the server's answer
- // is re-read rather than patched into local state.
- await waitFor(() => expect(api.getSubscriptions).toHaveBeenCalledTimes(2));
+ // The handler's own rows are applied, so no follow-up GET is needed to
+ // learn the state it just computed.
+ await waitFor(() => expect(screen.getByLabelText('Disable the Codex subscription')).toBeInTheDocument());
+ expect(api.getSubscriptions).toHaveBeenCalledTimes(1);
});
// A disabled plan keeps its price: the row and its stored cost must survive a
@@ -132,17 +143,41 @@ describe('SubscriptionsTab', () => {
expect(screen.getByLabelText('Enable the Claude Code subscription')).toHaveAttribute('aria-checked', 'false');
});
- it('saves a changed tier and price through their own endpoints', async () => {
+ it('saves a changed tier and price in one request', async () => {
renderTab();
await screen.findByText('Claude Code');
fireEvent.change(screen.getByLabelText('Plan tier for Claude Code'), { target: { value: 'Max 20x' } });
fireEvent.change(screen.getByLabelText('Monthly cost for Claude Code'), { target: { value: '100' } });
fireEvent.click(screen.getByRole('button', { name: 'Save the Claude Code plan' }));
- await waitFor(() => expect(api.updateSubscriptionPlanTiers).toHaveBeenCalledWith(
- { claude: 'Max 20x' },
+ await waitFor(() => expect(api.updateSubscriptions).toHaveBeenCalledWith(
+ { costs: { claude: 100 }, tiers: { claude: 'Max 20x' } },
expect.anything(),
));
- expect(api.updateSubscriptionCosts).toHaveBeenCalledWith({ claude: 100 }, expect.anything());
+ expect(api.updateSubscriptions).toHaveBeenCalledTimes(1);
+ });
+
+ // Only a PRICE moves the savings figures, so a tier edit must not trigger a
+ // full cost-report + fleet rebuild.
+ it('does not rebuild the usage report for a tier-only edit', async () => {
+ renderTab();
+ await screen.findByText('Claude Code');
+ await waitFor(() => expect(api.getUsage).toHaveBeenCalledTimes(1));
+ fireEvent.change(screen.getByLabelText('Plan tier for Claude Code'), { target: { value: 'Max 20x' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Save the Claude Code plan' }));
+ await waitFor(() => expect(api.updateSubscriptions).toHaveBeenCalled());
+ expect(api.getUsage).toHaveBeenCalledTimes(1);
+ });
+
+ // A quota read is a multi-second CLI scrape per family; the window it is
+ // being compared against has nothing to do with it.
+ it('refetches only the spend figures when the period changes', async () => {
+ renderTab();
+ await screen.findByText('Claude Code');
+ await waitFor(() => expect(api.getProviderUsage).toHaveBeenCalledTimes(1));
+ fireEvent.click(screen.getByRole('button', { name: '90 days' }));
+ await waitFor(() => expect(api.getUsage).toHaveBeenCalledTimes(2));
+ expect(api.getProviderUsage).toHaveBeenCalledTimes(1);
+ expect(api.getSubscriptions).toHaveBeenCalledTimes(1);
});
it('offers no toggle for a priced plan with no provider configured', async () => {
diff --git a/client/src/components/usage/ProviderQuotaBody.jsx b/client/src/components/usage/ProviderQuotaBody.jsx
new file mode 100644
index 0000000000..e0cc9d2193
--- /dev/null
+++ b/client/src/components/usage/ProviderQuotaBody.jsx
@@ -0,0 +1,122 @@
+import { AlertTriangle } from 'lucide-react';
+import BrailleSpinner from '../BrailleSpinner';
+import UsageMeter from './UsageMeter';
+import { formatCompactCount } from '../../utils/formatters';
+
+/**
+ * The state ladder a subscription-quota reading renders through:
+ * unsupported → still reading → errored → nothing to meter → meters.
+ *
+ * Extracted from the Usage page's `ProviderQuotaCard` (#7403) when the
+ * Subscriptions page needed the same reading beside each plan. It had already
+ * started to drift in its first copy — an inverted branch order, different
+ * empty-state copy, and a dropped `metrics[]` branch, which is exactly the
+ * branch that exists for a backend whose quota cannot be queried at all. One
+ * ladder means a new provider shape is handled everywhere at once.
+ *
+ * Body only: the header, plan pill and per-card Refresh belong to each host,
+ * because the Usage card and a Subscriptions row frame the same reading very
+ * differently.
+ */
+
+// Small labelled stat, used for both the per-period activity counts and the
+// `metrics[]` a backend returns when its quota can't be queried at all.
+export function StatTile({ label, value, detail }) {
+ return (
+ <div className="bg-port-bg border border-port-border rounded-lg p-1.5 sm:p-2.5">
+ <div className="text-[10px] sm:text-xs text-gray-400 mb-0.5">{label}</div>
+ <div className="text-xs sm:text-sm text-white">{value}</div>
+ {detail && <div className="text-[9px] sm:text-xs text-gray-500 mt-0.5">{detail}</div>}
+ </div>
+ );
+}
+
+export default function ProviderQuotaBody({ quota, showActivity = true, showNote = true }) {
+ if (!quota) return null;
+ if (!quota.supported) {
+ return (
+ <p className="text-xs sm:text-sm text-gray-500">
+ {quota.note || 'Usage reporting is not available for this provider.'}
+ </p>
+ );
+ }
+
+ // The reading is still being taken. It comes BEFORE the error and empty
+ // branches because a pending card has no limits — rendering it through those
+ // says "No rate-limit data reported", which is a verdict about the provider
+ // rather than a statement about a scrape still in flight.
+ if (quota.pending) {
+ return (
+ <div className="flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm text-gray-400 py-1">
+ <BrailleSpinner />
+ <span>{quota.note || 'Reading quota…'}</span>
+ </div>
+ );
+ }
+
+ // `error` is also how a card that read fine says it has nothing to meter, so
+ // the note rides along — otherwise the one state where the reading's age
+ // matters most is the one state that hides it.
+ if (quota.error) {
+ return (
+ <div role="status" className="flex items-start gap-1.5 sm:gap-2 text-xs sm:text-sm text-gray-400 py-1">
+ <AlertTriangle size={15} className="text-port-warning mt-0.5 shrink-0" />
+ <span>
+ {quota.error}
+ {quota.note && <span className="block text-xs text-gray-500 mt-1">{quota.note}</span>}
+ </span>
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-1 sm:space-y-2">
+ {quota.limits?.length > 0 && (
+ <div>
+ {quota.limits.map((limit) => (
+ <UsageMeter key={limit.key} limit={limit} />
+ ))}
+ </div>
+ )}
+
+ {!quota.limits?.length && !quota.metrics?.length && (
+ <div className="text-xs sm:text-sm text-gray-500">No rate-limit data reported</div>
+ )}
+
+ {/* Backends with no queryable quota report observed counts instead of
+ a meter — a percentage we cannot measure must not be invented. */}
+ {quota.metrics?.length > 0 && (
+ // One tile per row on a phone: these cells sit inside an already
+ // half-width mobile card, and two columns of it wrapped a tile's
+ // label and detail onto four lines apiece.
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
+ {quota.metrics.map((m) => (
+ <StatTile key={m.key} label={m.label} value={m.value} detail={m.detail} />
+ ))}
+ </div>
+ )}
+
+ {showActivity && quota.activity?.length > 0 && (
+ <div className="hidden sm:grid sm:grid-cols-2 gap-2 pt-1">
+ {quota.activity.map((a) => (
+ <StatTile
+ key={a.period}
+ label={a.period}
+ value={(
+ <>
+ {formatCompactCount(a.requests)} requests
+ <span className="mx-2 text-gray-600">•</span>
+ {formatCompactCount(a.sessions)} sessions
+ </>
+ )}
+ />
+ ))}
+ </div>
+ )}
+
+ {showNote && quota.note && (
+ <p className="hidden sm:block text-xs text-gray-500">{quota.note}</p>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/usage/SubscriptionSavingsCard.jsx b/client/src/components/usage/SubscriptionSavingsCard.jsx
index fd469e80d1..ecace53d57 100644
--- a/client/src/components/usage/SubscriptionSavingsCard.jsx
+++ b/client/src/components/usage/SubscriptionSavingsCard.jsx
@@ -6,14 +6,14 @@ 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');
+export const savingsTone = (savings) => (savings >= 0 ? 'text-port-success' : 'text-port-error');
const NO_FAMILIES = [];
-// 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) => [
+// The three derived figures per plan, defined ONCE so the mobile cards, the
+// desktop table and the Subscriptions page can't drift into showing different
+// things (the first two already had: mobile was missing the totals row).
+export 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) },
{
@@ -74,7 +74,7 @@ export function buildCostPatch(drafts, families) {
return patch;
}
-function CostInput({ row, value, onChange, idPrefix }) {
+export function CostInput({ row, value, onChange, idPrefix }) {
return (
<div className="flex items-center gap-1">
<span className="text-gray-500 text-xs">$</span>
@@ -95,9 +95,9 @@ function CostInput({ row, value, onChange, idPrefix }) {
);
}
-const NotPriced = () => <span className="text-gray-600">not priced</span>;
+export const NotPriced = () => <span className="text-gray-600">not priced</span>;
-function CellValue({ cell }) {
+export function CellValue({ cell }) {
return (
<>
<span className={cell.tone}>{cell.value ?? <NotPriced />}</span>
diff --git a/client/src/components/usage/UsageMeter.jsx b/client/src/components/usage/UsageMeter.jsx
index e8956a789d..8d4e752a50 100644
--- a/client/src/components/usage/UsageMeter.jsx
+++ b/client/src/components/usage/UsageMeter.jsx
@@ -1,4 +1,5 @@
import { Clock } from 'lucide-react';
+import ProgressBar from '../ui/ProgressBar';
import { timeUntil } from '../../utils/formatters';
/**
@@ -9,6 +10,10 @@ import { timeUntil } from '../../utils/formatters';
* same meter beside each plan's price and toggle. Two copies would have drifted
* on the part that matters most: the colour thresholds that tell the user a
* plan is nearly spent.
+ *
+ * The bar itself is `ui/ProgressBar`, which owns the clamp and the
+ * `role="progressbar"` + `aria-valuenow` trio this markup was missing — the
+ * seventh hand-rolled track was not the place to re-learn that lesson.
*/
// Every provider adapter normalizes its reset to ISO before it reaches here, so
@@ -24,12 +29,16 @@ export const formatResetsAt = (resetsAt) => {
return relative ? `${local} (${relative})` : local;
};
-// Color a usage meter by how much is consumed: comfortable → warning → critical.
-export 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';
+/**
+ * Color a meter by how much of the window is consumed: comfortable → warning →
+ * critical, as ProgressBar's semantic tones. An unread percentage is `muted`,
+ * never `success` — "we didn't measure it" must not read as "plenty left".
+ */
+export function meterTone(percentUsed) {
+ if (percentUsed == null) return 'muted';
+ if (percentUsed >= 90) return 'error';
+ if (percentUsed >= 70) return 'warning';
+ return 'success';
}
export default function UsageMeter({ limit }) {
@@ -43,12 +52,7 @@ export default function UsageMeter({ limit }) {
{remaining == null ? '—' : `${remaining}% left`}
</span>
</div>
- <div className="h-1.5 sm: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>
+ <ProgressBar percent={used} tone={meterTone(limit.percentUsed)} label={`${limit.label} quota used`} />
<div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-0.5 sm:gap-1 mt-0.5 sm:mt-1">
<span className="text-[9px] sm:text-xs text-gray-500">{used}% used</span>
{limit.resetsAt && (
diff --git a/client/src/components/usage/UsageMeter.test.jsx b/client/src/components/usage/UsageMeter.test.jsx
index 7f5047b62e..4ded91b45e 100644
--- a/client/src/components/usage/UsageMeter.test.jsx
+++ b/client/src/components/usage/UsageMeter.test.jsx
@@ -1,23 +1,23 @@
import { describe, expect, it } from 'vitest';
import { render, screen } from '@testing-library/react';
-import UsageMeter, { meterColor, formatResetsAt } from './UsageMeter';
+import UsageMeter, { meterTone, formatResetsAt } from './UsageMeter';
-describe('meterColor', () => {
+describe('meterTone', () => {
// The thresholds are the whole reason this meter was extracted rather than
// copied: a plan that reads "comfortable" on one page and "critical" on
// another is worse than no meter at all.
it('escalates from comfortable to critical as a window is consumed', () => {
- expect(meterColor(10)).toBe('bg-port-success');
- expect(meterColor(69)).toBe('bg-port-success');
- expect(meterColor(70)).toBe('bg-port-warning');
- expect(meterColor(89)).toBe('bg-port-warning');
- expect(meterColor(90)).toBe('bg-port-error');
+ expect(meterTone(10)).toBe('success');
+ expect(meterTone(69)).toBe('success');
+ expect(meterTone(70)).toBe('warning');
+ expect(meterTone(89)).toBe('warning');
+ expect(meterTone(90)).toBe('error');
});
// An unread percentage must not render as "0% used, all clear".
it('renders an unknown percentage as neutral, not as comfortable', () => {
- expect(meterColor(null)).toBe('bg-gray-500');
- expect(meterColor(undefined)).toBe('bg-gray-500');
+ expect(meterTone(null)).toBe('muted');
+ expect(meterTone(undefined)).toBe('muted');
});
});
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 9a0c4050fa..5061c3ee08 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -258,6 +258,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `qrCode.js` | Deterministic SVG QR code generator for scoped mobile session join links (#5383). |
| `publicGuestRoutes.js` | `isPublicGuestRoute` identifies standalone guest pages that skip private app bootstrap. |
| `riggingReasons.js` | Client mirror of the character-rigging readiness reason labels in `server/services/rigging/readiness.js`: `RIGGING_UNAVAILABLE_REASONS` (reason code -> user-facing label), `RIGGING_REASON_FALLBACK`, and `riggingReasonLabel(code, fallback?)`. Render these anywhere a `GET /api/rigging/readiness` reason is shown; never re-declare the codes. Parity + code coverage enforced by `server/services/rigging/unavailableReasons.parity.test.js`. |
+| `usagePeriods.js` | The report windows every usage-cost surface offers — `USAGE_PERIOD_OPTIONS`, `DEFAULT_USAGE_PERIOD` (what a URL with no `?period` means) and `resolveUsagePeriod`. Shared because `?period` is a URL param the user carries between the Usage and Subscriptions pages; two copies had already disagreed on the default. |
| `usdzExport.js` | AR Quick Look (USDZ) export for the 3D viewer (#5756): `exportSceneToUsdz(scene, { maxTextureSize })` lazy-loads three's `USDZExporter` and serializes the already-decoded scene to bytes, `countSceneTriangles(object3d)` measures an object graph against `AR_TRIANGLE_BUDGET`, and `supportsArQuickLook()` feature-detects the `<a rel="ar">` handoff (Safari on iOS/iPadOS only — never sniff the user agent) so a desktop is offered a download instead of a button that does nothing. `AR_MAX_TEXTURE_SIZE` bounds the file: USDZ stores every texel raw, with no Draco/meshopt equivalent. |
| `installFailureTask.js` | Build the CoS task payload behind the installer-failure "Queue agent to investigate" button (#5981): `buildInstallFailureTask({ label, stage, error, logs, surface })` → `{ description, prompt }` carrying the installer name, failing stage, error text and a bounded log tail, and `installLogTail(logs)` (the `useInstallStream` `{ kind, text }` entries rendered as text, capped at `INSTALL_FAILURE_LOG_TAIL_LINES` / `INSTALL_FAILURE_LOG_TAIL_CHARS` so a 1000-line pip stream cannot push a huge body through `POST /api/cos/tasks`, cutting on a line boundary, redacting the home-directory paths pip/git echo, and neutralizing a log line that would close the prompt fence). Shared by both install modals and `LocalSetupPanel` so every surface queues the same reproducible context. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 98aa7d3ba6..9bdc151780 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -218,6 +218,7 @@ export * from './wrSceneCursor.js';
export * from './writingGuide.js';
export * from './qrCode.js';
export * from './riggingReasons.js';
+export * from './usagePeriods.js';
export * from './usdzExport.js';
export * from './eidoverseFrame.js';
export * from './songBookDraft.js';
diff --git a/client/src/lib/usagePeriods.js b/client/src/lib/usagePeriods.js
new file mode 100644
index 0000000000..de3d2fd54a
--- /dev/null
+++ b/client/src/lib/usagePeriods.js
@@ -0,0 +1,24 @@
+/**
+ * The report windows every usage-cost surface offers, and the one `?period`
+ * means when the URL carries none.
+ *
+ * Shared because the value is a URL param the user carries BETWEEN these pages.
+ * Two copies had already disagreed on the default, so the same `?period=`-less
+ * URL resolved to a different window depending on which page read it — and a
+ * link copied from one page silently changed meaning on the other.
+ */
+
+export const USAGE_PERIOD_OPTIONS = [
+ { id: '7d', label: '7 days' },
+ { id: '30d', label: '30 days' },
+ { id: '90d', label: '90 days' },
+ { id: 'all', label: 'All time' },
+];
+
+/** The window a URL with no `?period` means. Omitted from the URL, never set. */
+export const DEFAULT_USAGE_PERIOD = '7d';
+
+/** The period a URL's `?period` selects, falling back to the shared default. */
+export const resolveUsagePeriod = (value) => (
+ USAGE_PERIOD_OPTIONS.some((option) => option.id === value) ? value : DEFAULT_USAGE_PERIOD
+);
diff --git a/client/src/pages/UsagePage.jsx b/client/src/pages/UsagePage.jsx
index 12d476ce45..29b487886e 100644
--- a/client/src/pages/UsagePage.jsx
+++ b/client/src/pages/UsagePage.jsx
@@ -5,38 +5,20 @@ 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, formatCompactCountOrDash as formatNumber, formatUsd, timeAgo } from '../utils/formatters';
+import { formatCompactCountOrDash as formatNumber, formatUsd, timeAgo } from '../utils/formatters';
import { useAsyncAction } from '../hooks/useAsyncAction';
import { useAutoRefetch } from '../hooks/useAutoRefetch';
import SubscriptionSavingsCard from '../components/usage/SubscriptionSavingsCard';
import FleetUsageCard from '../components/usage/FleetUsageCard';
import FreeTierUsageCard from '../components/usage/FreeTierUsageCard';
-import UsageMeter from '../components/usage/UsageMeter';
+import ProviderQuotaBody from '../components/usage/ProviderQuotaBody';
import ModelsTabsHeader from '../components/models/ModelsTabsHeader';
+import { USAGE_PERIOD_OPTIONS, DEFAULT_USAGE_PERIOD } from '../lib/usagePeriods';
// 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.
const PENDING_POLL_MS = 4000;
-const PERIOD_OPTIONS = [
- { id: '7d', label: '7 days' },
- { id: '30d', label: '30 days' },
- { id: '90d', label: '90 days' },
- { id: 'all', label: 'All time' }
-];
-
-// Small labelled stat, used for both the per-period activity counts and the
-// `metrics[]` a backend returns when its quota can't be queried at all.
-function StatTile({ label, value, detail }) {
- return (
- <div className="bg-port-bg border border-port-border rounded-lg p-1.5 sm:p-2.5">
- <div className="text-[10px] sm:text-xs text-gray-400 mb-0.5">{label}</div>
- <div className="text-xs sm:text-sm text-white">{value}</div>
- {detail && <div className="text-[9px] sm:text-xs text-gray-500 mt-0.5">{detail}</div>}
- </div>
- );
-}
-
// A subscription is one account across every federated instance, but each
// instance can only read its own CLI's panel. When peers have contributed a
// reading, say so on the card and name them — the meters are the freshest
@@ -85,84 +67,7 @@ function ProviderQuotaCard({ quota, onRefresh, refreshing, disabled }) {
</div>
</div>
- {!quota.supported && (
- <p className="text-xs sm:text-sm text-gray-500">{quota.note || 'Usage reporting is not available for this provider.'}</p>
- )}
-
- {/* The reading is still being taken. It comes BEFORE the error and empty
- branches because a pending card has no limits — rendering it through
- those says "No rate-limit data reported", which is a verdict about the
- provider rather than a statement about a scrape still in flight. */}
- {quota.supported && quota.pending && (
- <div className="flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm text-gray-400 py-1">
- <BrailleSpinner />
- <span>{quota.note || 'Reading quota…'}</span>
- </div>
- )}
-
- {/* `error` is also how a card that read fine says it has nothing to
- meter, so the note rides along — otherwise the one state where the
- reading's age matters most is the one state that hides it. */}
- {quota.supported && !quota.pending && quota.error && (
- <div role="status" className="flex items-start gap-1.5 sm:gap-2 text-xs sm:text-sm text-gray-400 py-1">
- <AlertTriangle size={15} className="text-port-warning mt-0.5 shrink-0" />
- <span>
- {quota.error}
- {quota.note && <span className="block text-xs text-gray-500 mt-1">{quota.note}</span>}
- </span>
- </div>
- )}
-
- {quota.supported && !quota.pending && !quota.error && (
- <div className="space-y-1 sm:space-y-2">
- {quota.limits?.length > 0 && (
- <div>
- {quota.limits.map((limit) => (
- <UsageMeter key={limit.key} limit={limit} />
- ))}
- </div>
- )}
-
- {!quota.limits?.length && !quota.metrics?.length && (
- <div className="text-xs sm:text-sm text-gray-500">No rate-limit data reported</div>
- )}
-
- {/* Backends with no queryable quota report observed counts instead of
- a meter — a percentage we cannot measure must not be invented. */}
- {quota.metrics?.length > 0 && (
- // One tile per row on a phone: these cells sit inside an already
- // half-width mobile card, and two columns of it wrapped a tile's
- // label and detail onto four lines apiece.
- <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
- {quota.metrics.map((m) => (
- <StatTile key={m.key} label={m.label} value={m.value} detail={m.detail} />
- ))}
- </div>
- )}
-
- {quota.activity?.length > 0 && (
- <div className="hidden sm:grid sm:grid-cols-2 gap-2 pt-1">
- {quota.activity.map((a) => (
- <StatTile
- key={a.period}
- label={a.period}
- value={(
- <>
- {formatCompactCount(a.requests)} requests
- <span className="mx-2 text-gray-600">•</span>
- {formatCompactCount(a.sessions)} sessions
- </>
- )}
- />
- ))}
- </div>
- )}
-
- {quota.note && (
- <p className="hidden sm:block text-xs text-gray-500">{quota.note}</p>
- )}
- </div>
- )}
+ <ProviderQuotaBody quota={quota} />
</div>
);
}
@@ -501,7 +406,7 @@ function ProviderCostRows({ provider }) {
function CostReportFilters({ period, from, to, isCustom, onPeriod, onRange }) {
return (
<div className="flex flex-wrap items-center gap-2">
- {PERIOD_OPTIONS.map((opt) => (
+ {USAGE_PERIOD_OPTIONS.map((opt) => (
<button
key={opt.id}
onClick={() => onPeriod(opt.id)}
@@ -625,7 +530,7 @@ function getPeriodTopModels(usage) {
function InternalUsageMetrics() {
const [searchParams, setSearchParams] = useSearchParams();
- const period = searchParams.get('period') || '7d';
+ const period = searchParams.get('period') || DEFAULT_USAGE_PERIOD;
const from = searchParams.get('from') || '';
const to = searchParams.get('to') || '';
const isCustom = Boolean(from || to);
@@ -699,7 +604,7 @@ function InternalUsageMetrics() {
const next = new URLSearchParams(prev);
next.delete('from');
next.delete('to');
- if (id === '7d') next.delete('period'); else next.set('period', id);
+ if (id === DEFAULT_USAGE_PERIOD) next.delete('period'); else next.set('period', id);
return next;
}, { replace: true });
};
diff --git a/client/src/services/README.md b/client/src/services/README.md
index 4a52608168..89f8fb7838 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -65,7 +65,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `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`), plus `rearmQuotaBurn` to put spent `run once` steps back into the rotation. |
| `apiRapidReader.js` | Rapid Reader's optional author-hosted Accelerando loader and machine-local shelf API. |
-| `apiSystem.js` | System info (CPU/memory/ports/alerts/active processing and local hardware capabilities) + D&D-style character sheet getter, plus the usage cost report and explicit historical reconciliation (`getHourlyUsage` for dashboard hourly counters, `getUsage`, `getProviderUsage`, `getUsageBackfillStatus`/`startUsageBackfill`, `updateSubscriptionCosts` for the subscription-vs-API savings comparison, `getSubscriptions` / `updateSubscriptionPlanTiers` / `setSubscriptionEnabled` for the Subscriptions page's plan rows (PortOS-side enablement and plan-tier tracking only, never vendor billing), `updateUsageFleetBilling` to exclude an API-billed federated instance from Across Instances totals). Also `saveCredential` (write-only integration key save/clear) and `getCredentialInventory` (`GET /settings/credentials`) — presence and source of each PortOS credential, never a value. |
+| `apiSystem.js` | System info (CPU/memory/ports/alerts/active processing and local hardware capabilities) + D&D-style character sheet getter, plus the usage cost report and explicit historical reconciliation (`getHourlyUsage` for dashboard hourly counters, `getUsage`, `getProviderUsage`, `getUsageBackfillStatus`/`startUsageBackfill`, `updateSubscriptionCosts` for the subscription-vs-API savings comparison, `getSubscriptions` / `updateSubscriptions` / `setSubscriptionEnabled` for the Subscriptions page's plan rows (PortOS-side enablement and plan-tier tracking only, never vendor billing), `updateUsageFleetBilling` to exclude an API-billed federated instance from Across Instances totals). Also `saveCredential` (write-only integration key save/clear) and `getCredentialInventory` (`GET /settings/credentials`) — presence and source of each PortOS credential, never a value. |
| `apiAuth.js` | Optional login password — status, login, set/clear password. |
| `apiLoops.js` | Scheduled loops. |
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index 957f9a7696..8c81df764e 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -187,14 +187,20 @@ export const updateSubscriptionCosts = (costs, options = {}) =>
// Deliberately separate from `getUsage().subscriptionSavings`, which answers
// what those plans SPENT over a report window — this answers what they are.
export const getSubscriptions = (options = {}) => request('/usage/subscriptions', options);
-// Which tier of each plan the user is on ("Max 20x", "Pro"), same patch
-// semantics as the prices: an omitted family keeps its stored tier, `null` or
-// `''` clears it. Sent on its own key so a tier save never rewrites a price.
-export const updateSubscriptionPlanTiers = (tiers, options = {}) =>
- request('/usage/subscriptions', { method: 'PUT', body: JSON.stringify({ tiers }), ...options });
+// Save plan prices and/or plan tiers in ONE request, and get the refreshed rows
+// back — so an editor applies a save without a follow-up GET. Both maps are
+// patches: an omitted family keeps its stored value, `null` (or `0` / `''`)
+// clears it.
+export const updateSubscriptions = ({ costs, tiers } = {}, options = {}) =>
+ request('/usage/subscriptions', {
+ method: 'PUT',
+ body: JSON.stringify({ ...(costs ? { costs } : {}), ...(tiers ? { tiers } : {}) }),
+ ...options,
+ });
// Switch one subscription on or off — PortOS-side enablement only (it flips
// `enabled` across that family's provider records). Never touches vendor
-// billing. A priced family with no providers answers `applied: false`.
+// billing. A priced family with no providers answers `applied: false`. The
+// refreshed rows come back with the outcome.
export const setSubscriptionEnabled = ({ family, enabled }, options = {}) =>
request('/usage/subscriptions/enabled', {
method: 'PUT',
diff --git a/server/lib/README.md b/server/lib/README.md
index 02746137ee..2abc5b49ec 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -294,6 +294,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `downloadPreflight.js` | Free-disk preflight + resumable weight download. `assessDownloadPreflight({ destPath, expectedBytes })` → `{ freeBytes, requiredBytes, headroomBytes, verdict: ok\|tight\|insufficient }`; `assertDownloadFits` throws typed `DISK_INSUFFICIENT` (507) when the volume cannot hold the payload. `streamResumableDownload` Range-resumes a `.partial` on transport failure, discards it on user cancel, and verifies a published sha256 before rename. `sweepOrphanedPartials(dirs, { maxAgeMs })` unlinks leftover `.partial` (+ `.partial.etag`) files older than 7 days (default) and skips recent/in-flight dests; missing dirs are a no-op. `probeRemoteSize` / `siblingDownloadMeta` / `verifyDownloadHash` are the size+digest helpers the four weight-download entry points share. `createDownloadSlot({ codePrefix, idleStallEnvVar, exclusive, keepPartialOnCancel })` is the one transfer-slot registry a weight download claims before its first await — in-flight map, abort controller carrying a cancel/stall reason, typed `<PREFIX>_DOWNLOAD_IN_FLIGHT`/`_STALLED`/`_CANCELLED` errors, a per-chunk progress throttle, and an `isInFlight(path)` predicate covering the dest, its `.partial`, and shards under a claimed directory. Call it at module scope only. `isAnyDownloadInFlight` answers for every registered slot at once, which is how the orphaned-partial GC protects live transfers. |
| `agentInstructionsFile.js` | The `AGENTS.md` + bridge `CLAUDE.md` pair a repo carries (#4852). `writeAgentInstructions(repoPath, content)` writes the body to `AGENTS.md` and the one-line `@AGENTS.md` import beside it — use it in scaffolders instead of a bare `writeFile(join(repoPath, 'CLAUDE.md'), …)`, since a generated repo carrying only one name is unreadable to half the CLIs PortOS can point at it. Constants: `AGENT_INSTRUCTIONS_FILENAME`, `CLAUDE_BRIDGE_FILENAME`, `AGENT_INSTRUCTIONS_IMPORT`. |
| `fileCore.js` | Cross-cutting filesystem primitives (`atomicWrite`, `writeFileGuarded`, `appendFileGuarded`, `copyFileGuarded`, `rmGuarded`, `unlinkGuarded`, `createWriteStreamGuarded`, directory helpers, `parseFilesystemStats(stats)` → canonical/byte-alias metrics or `null`, bounded tail reads/watchers), time/format helpers, directory sizing, and SHA-256 helpers. |
+| `familySettingsMap.js` | The merge rule every per-provider-family map in `data/settings.json` shares (plan prices, plan tiers) — `normalizeFamilyMap(raw, normalizeValue)` and `mergeFamilyMap(stored, patch, normalizeValue)`, which hold the absent-vs-present-but-empty contract in ONE place: an omitted family keeps its stored value, one sent empty is an intentional clear and is deleted. Each store supplies only its value normalizer. Pure. |
| `fileUtils.js` | Backward-compatible facade re-exporting the focused file utility modules so existing deep imports need no caller changes. |
| `portosEnv.js` | Single server-side helper for PortOS's own `.env` (`PORTOS_ENV_PATH` anchored to `installRoot` per #1947, `parseEnvContents`, `readPortosEnvValue`, `upsertPortosEnvLine` + `upsertEnvLine`), with replacer-function guard for `$`-patterns and `process.env` wins precedence; `scripts/lib/envFile.js` stays as the zero-dependency boundary copy. |
| `portosRootPlaceholder.js` | Expand leftover `__PORTOS_ROOT__` tokens in apps registry fields (`repoPath`, `appIconPath`, etc.) so a partial/restored `data/` tree cannot leave Apps → Git looking for a non-existent checkout. `PORTOS_ROOT_TOKEN`, `expandPortosRootToken`, `expandPortosRootInApp`, `containsPortosRootToken`. Used by `services/apps.js` on load and by `scripts/setup-data.js` / `scripts/lib/rewriteAppsPortosRoot.js` when seeding or rewriting `data/apps.json`. |
diff --git a/server/lib/familySettingsMap.js b/server/lib/familySettingsMap.js
new file mode 100644
index 0000000000..d2e9ecd26b
--- /dev/null
+++ b/server/lib/familySettingsMap.js
@@ -0,0 +1,44 @@
+import { isPlainObject } from './objects.js';
+
+/**
+ * The merge rule shared by every per-provider-family map stored in
+ * `data/settings.json` — today the plan prices (`subscriptionCosts`) and the
+ * plan tiers (`subscriptionPlanTiers`).
+ *
+ * Both stores hold `{ [familyId]: value }` and both owe their editors the same
+ * ABSENT-vs-PRESENT-BUT-EMPTY contract AGENTS.md calls load-bearing: a family
+ * the patch omits keeps its stored value, while one sent as an empty value is
+ * an intentional CLEAR and is deleted. An editor that submits only the rows it
+ * changed depends on the first half; a user cancelling a plan depends on the
+ * second. Written twice, a fix to one would silently miss the other, so the
+ * loop lives here once and each store supplies only its value normalizer.
+ *
+ * Pure: the settings I/O stays in the services that own each key.
+ */
+
+/**
+ * Normalize a whole stored map, dropping every entry the value normalizer
+ * clears. `normalizeValue` returns `null` for "no value" — that is what makes a
+ * cleared entry disappear rather than persist as 0 / "".
+ */
+export function normalizeFamilyMap(raw, normalizeValue) {
+ if (!isPlainObject(raw)) return {};
+ const out = {};
+ for (const [family, value] of Object.entries(raw)) {
+ const normalized = normalizeValue(value);
+ if (normalized !== null) out[family] = normalized;
+ }
+ return out;
+}
+
+/** Apply a patch to a stored map: omitted keeps, cleared deletes. */
+export function mergeFamilyMap(stored, patch, normalizeValue) {
+ const merged = normalizeFamilyMap(stored, normalizeValue);
+ const incoming = isPlainObject(patch) ? patch : {};
+ for (const [family, value] of Object.entries(incoming)) {
+ const normalized = normalizeValue(value);
+ if (normalized === null) delete merged[family];
+ else merged[family] = normalized;
+ }
+ return merged;
+}
diff --git a/server/lib/index.js b/server/lib/index.js
index a3243bede1..26752cba2d 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -100,6 +100,7 @@ export * from './creativeLatitude.js';
// subdir with its own barrel — surface it under `editorial.*` so the root
// discovery surface reaches EDITORIAL_CHECKS + the lookup helpers.
export * as editorial from './editorial/index.js';
+export * from './familySettingsMap.js';
export * from './fableLoomGraph.js';
export * from './fableLoomCameraMovements.js';
export * from './fableLoomPlayback.js';
diff --git a/server/lib/subscriptionPlanTiers.js b/server/lib/subscriptionPlanTiers.js
index 975ad765f4..f4cad346ec 100644
--- a/server/lib/subscriptionPlanTiers.js
+++ b/server/lib/subscriptionPlanTiers.js
@@ -1,4 +1,4 @@
-import { isPlainObject } from './objects.js';
+import { trimTo } from './textUtils.js';
/**
* Which TIER of a subscription the user is on — "Max 5x" vs "Max 20x", "Pro"
@@ -38,21 +38,10 @@ export const MAX_PLAN_TIER_LENGTH = 60;
* mean different things depending on which side of the store you read it from
* (the same contract `normalizeCost` holds for prices). Empty, whitespace-only
* and non-string all collapse to null — a CLEARED tier, never an empty-string
- * tier that renders as a blank pill the user cannot remove.
+ * tier that renders as a blank pill the user cannot remove. `trimTo` is the
+ * tree's sole string bounder and already maps a non-string to `''`.
*/
export function normalizePlanTier(value) {
- if (typeof value !== 'string') return null;
- const tier = value.trim().slice(0, MAX_PLAN_TIER_LENGTH);
+ const tier = trimTo(value, MAX_PLAN_TIER_LENGTH);
return tier === '' ? null : tier;
}
-
-/** Pure: normalize a whole tier map, dropping every cleared/invalid entry. */
-export function normalizePlanTiers(raw) {
- if (!isPlainObject(raw)) return {};
- const out = {};
- for (const [family, value] of Object.entries(raw)) {
- const tier = normalizePlanTier(value);
- if (tier !== null) out[family] = tier;
- }
- return out;
-}
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 5261ff5118..a0521fbe6c 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1448,7 +1448,7 @@ export const subscriptionPlanTiersMapSchema = z.partialRecord(
* independent: the price editor sends only `costs`, the plan editor only
* `tiers`, and neither save may disturb the other's stored map.
*/
-export const subscriptionCostsSchema = z.object({
+export const subscriptionsUpdateSchema = z.object({
costs: subscriptionCostsMapSchema.optional(),
tiers: subscriptionPlanTiersMapSchema.optional(),
});
diff --git a/server/routes/usage.js b/server/routes/usage.js
index 0dbae210f4..4ba3225ed2 100644
--- a/server/routes/usage.js
+++ b/server/routes/usage.js
@@ -4,9 +4,9 @@ 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, subscriptionCostsSchema, subscriptionEnabledSchema, usageFleetBillingSchema } from '../lib/validation.js';
-import { saveSubscriptionCosts, getSubscriptionCosts, getSubscriptionSavings } from '../services/subscriptionCosts.js';
-import { getSubscriptionOverview, getPlanTiers, savePlanTiers, setSubscriptionEnabled } from '../services/subscriptions.js';
+import { validateRequest, usageQuerySchema, usageMessagesSchema, providerUsageQuerySchema, subscriptionsUpdateSchema, subscriptionEnabledSchema, usageFleetBillingSchema } from '../lib/validation.js';
+import { saveSubscriptionCosts, getSubscriptionSavings } from '../services/subscriptionCosts.js';
+import { getSubscriptionOverview, savePlanTiers, setSubscriptionEnabled } from '../services/subscriptions.js';
import { getFleetUsage } from '../services/peerUsage.js';
import { getApiBilledInstanceIds, setInstanceUsesSubscriptions } from '../services/usageFleetBilling.js';
import { resolveUsageRange } from '../lib/usageRange.js';
@@ -66,14 +66,16 @@ router.get('/subscriptions', asyncHandler(async (req, res) => {
// PUT /api/usage/subscriptions - Merge plan prices and/or plan tiers. Within
// each map an omitted family keeps its stored value; one sent as null (or 0 /
// "") is cleared. The two maps are independent, so a tier save never rewrites
-// a price and vice versa, and a body carrying neither is a no-op read-back.
+// a price and vice versa.
+//
+// Both slices land in ONE request, and the response is the refreshed row set —
+// so the editor applies a save without a follow-up GET, and a row where the
+// user changed both the price and the tier costs one round trip, not two.
router.put('/subscriptions', asyncHandler(async (req, res) => {
- const { costs, tiers } = validateRequest(subscriptionCostsSchema, req.body);
- const [nextCosts, nextTiers] = await Promise.all([
- costs === undefined ? getSubscriptionCosts() : saveSubscriptionCosts(costs, { actor: 'user' }),
- tiers === undefined ? getPlanTiers() : savePlanTiers(tiers, { actor: 'user' }),
- ]);
- res.json({ costs: nextCosts, tiers: nextTiers });
+ const { costs, tiers } = validateRequest(subscriptionsUpdateSchema, req.body);
+ if (costs !== undefined) await saveSubscriptionCosts(costs, { actor: 'user' });
+ if (tiers !== undefined) await savePlanTiers(tiers, { actor: 'user' });
+ res.json(await getSubscriptionOverview());
}));
// PUT /api/usage/subscriptions/enabled - Switch one subscription on or off by
@@ -83,10 +85,12 @@ router.put('/subscriptions', asyncHandler(async (req, res) => {
//
// A priced family with no providers configured answers `applied: false` rather
// than 404: the row legitimately exists so its price stays visible, there is
-// just nothing local to toggle.
+// just nothing local to toggle. The refreshed rows ride along for the same
+// reason as above.
router.put('/subscriptions/enabled', asyncHandler(async (req, res) => {
const { family, enabled } = validateRequest(subscriptionEnabledSchema, req.body);
- res.json(await setSubscriptionEnabled(family, enabled));
+ const outcome = await setSubscriptionEnabled(family, enabled);
+ res.json({ ...outcome, ...(await getSubscriptionOverview()) });
}));
// PUT /api/usage/fleet-billing - Mark one federated instance as paying API
diff --git a/server/routes/usage.test.js b/server/routes/usage.test.js
index eeff403fe9..53857441ce 100644
--- a/server/routes/usage.test.js
+++ b/server/routes/usage.test.js
@@ -24,13 +24,11 @@ vi.mock('../services/usageFleetBilling.js', () => ({
vi.mock('../services/subscriptionCosts.js', () => ({
saveSubscriptionCosts: vi.fn(async (costs) => costs),
- getSubscriptionCosts: vi.fn(async () => ({ claude: 100 })),
getSubscriptionSavings: vi.fn(async () => ({ configured: false, families: [] }))
}));
vi.mock('../services/subscriptions.js', () => ({
- getSubscriptionOverview: vi.fn(async () => ({ families: [], costs: {}, tiers: {} })),
- getPlanTiers: vi.fn(async () => ({})),
+ getSubscriptionOverview: vi.fn(async () => ({ families: [{ family: 'claude' }] })),
savePlanTiers: vi.fn(async (tiers) => tiers),
setSubscriptionEnabled: vi.fn(async (family, enabled) => ({ family, enabled, applied: true, changed: [] })),
}));
@@ -58,7 +56,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, getSubscriptionCosts } from '../services/subscriptionCosts.js';
+import { getSubscriptionSavings, saveSubscriptionCosts } from '../services/subscriptionCosts.js';
import { getSubscriptionOverview, savePlanTiers, setSubscriptionEnabled } from '../services/subscriptions.js';
import { getFleetUsage } from '../services/peerUsage.js';
import { getApiBilledInstanceIds, setInstanceUsesSubscriptions } from '../services/usageFleetBilling.js';
@@ -244,10 +242,11 @@ describe('usage routes', () => {
.send({ tiers: { claude: 'Max 20x' } });
expect(res.status).toBe(200);
expect(savePlanTiers).toHaveBeenCalledWith({ claude: 'Max 20x' }, { actor: 'user' });
- // The price map was only READ back — a tier save must never rewrite it.
+ // A tier save must never rewrite the price map beside it.
expect(saveSubscriptionCosts).not.toHaveBeenCalled();
- expect(getSubscriptionCosts).toHaveBeenCalled();
- expect(res.body).toEqual({ costs: { claude: 100 }, tiers: { claude: 'Max 20x' } });
+ // The refreshed rows come back with the write, so the editor needs no
+ // follow-up GET to apply what it just saved.
+ expect(res.body.families).toEqual([{ family: 'claude' }]);
});
it('PUT /api/usage/subscriptions saves both slices in one call', async () => {
@@ -276,7 +275,6 @@ describe('usage routes', () => {
});
it('GET /api/usage/subscriptions returns the plan rows', async () => {
- getSubscriptionOverview.mockResolvedValue({ families: [{ family: 'claude' }], costs: {}, tiers: {} });
const res = await request(buildApp()).get('/api/usage/subscriptions');
expect(res.status).toBe(200);
expect(res.body.families).toEqual([{ family: 'claude' }]);
@@ -289,7 +287,10 @@ describe('usage routes', () => {
.send({ family: 'codex', enabled: false });
expect(res.status).toBe(200);
expect(setSubscriptionEnabled).toHaveBeenCalledWith('codex', false);
- expect(res.body).toEqual({ family: 'codex', enabled: false, applied: true, changed: ['codex-cli'] });
+ expect(res.body).toEqual({
+ family: 'codex', enabled: false, applied: true, changed: ['codex-cli'],
+ families: [{ family: 'claude' }],
+ });
});
// The handler fans the flag across every provider record the family owns, so
@@ -302,14 +303,6 @@ describe('usage routes', () => {
expect(setSubscriptionEnabled).not.toHaveBeenCalled();
});
- it('PUT /api/usage/subscriptions/enabled rejects a non-boolean flag', async () => {
- const res = await request(buildApp())
- .put('/api/usage/subscriptions/enabled')
- .send({ family: 'codex', enabled: 'yes' });
- expect(res.status).toBe(400);
- expect(setSubscriptionEnabled).not.toHaveBeenCalled();
- });
-
it('PUT /api/usage/fleet-billing marks an instance as API-billed', async () => {
setInstanceUsesSubscriptions.mockResolvedValue(['inst-peer']);
const res = await request(buildApp())
diff --git a/server/services/providerUsage.js b/server/services/providerUsage.js
index ae2e9b7439..1629b6a508 100644
--- a/server/services/providerUsage.js
+++ b/server/services/providerUsage.js
@@ -4,7 +4,7 @@ import { join } from 'path';
import { getAllProviders } from './providers.js';
import { getClaudeCodeUsage, systemTimeZone } from './claudeCodeUsage.js';
import { commandBasename } from '../lib/providerModels.js';
-import { PROVIDER_FAMILIES } from '../lib/providerFamilies.js';
+import { PROVIDER_FAMILIES, familyForProvider } from '../lib/providerFamilies.js';
import { scrapeTuiUsage } from '../lib/tuiUsageScrape.js';
import { createStaleWhileRevalidate, PENDING, WAIT } from '../lib/staleWhileRevalidate.js';
import { parseHumanReset, normalizeResetAt } from '../lib/quotaReset.js';
@@ -765,14 +765,27 @@ const FAMILIES = PROVIDER_FAMILIES.map((family) => ({ ...family, fetch: FAMILY_F
/**
* Distinct quota families among the enabled providers, in registry order.
- * Local-runtime wrappers are excluded up front regardless of which CLI binary
- * they launch — a local model has no subscription quota, so e.g. an enabled
+ * Local-runtime wrappers are excluded regardless of which CLI binary they
+ * launch — a local model has no subscription quota, so e.g. an enabled
* `claude-ollama` must not surface a Claude Code card (nor a codex/agy/grok
* wrapper its family's card).
+ *
+ * Membership comes from `familyForProvider` rather than a second copy of the
+ * matcher + local-runtime exclusion list. That predicate is ALREADY what cost
+ * attribution and the Subscriptions page's enabled state use, and this function
+ * is what the savings card uses — one definition is what makes "the two can
+ * never disagree" structural instead of a promise two predicates have to keep.
+ * (It also settles a provider config that matched two families: it now belongs
+ * to the first, here as everywhere else, rather than lighting up both.)
*/
export function resolveEnabledFamilies(providers) {
- const enabled = (providers || []).filter((p) => p?.enabled && p.ollamaBacked !== true && p.lmstudioBacked !== true && p.mtplxBacked !== true && p.llamaBacked !== true && p.vllmBacked !== true && p.sglangBacked !== true);
- return FAMILIES.filter((family) => enabled.some((p) => family.matches(p)));
+ const enabledIds = new Set(
+ (providers || [])
+ .filter((p) => p?.enabled)
+ .map((p) => familyForProvider(p))
+ .filter(Boolean)
+ );
+ return FAMILIES.filter((family) => enabledIds.has(family.id));
}
const fetchFamilyQuota = (family, { wait, providers }) =>
diff --git a/server/services/subscriptionCosts.js b/server/services/subscriptionCosts.js
index 0bf0314e2f..4178efae9c 100644
--- a/server/services/subscriptionCosts.js
+++ b/server/services/subscriptionCosts.js
@@ -8,7 +8,7 @@ import {
roundCents,
MAX_MONTHLY_COST
} from '../lib/subscriptionSavings.js';
-import { isPlainObject } from '../lib/objects.js';
+import { mergeFamilyMap, normalizeFamilyMap } from '../lib/familySettingsMap.js';
/**
* What the user pays for each AI subscription, and what those plans saved
@@ -46,15 +46,7 @@ export function normalizeCost(value) {
}
/** 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;
-}
+export const normalizeSubscriptionCosts = (raw) => normalizeFamilyMap(raw, normalizeCost);
/** Stored monthly plan prices, `{ [family]: monthlyUsd }`. */
export async function getSubscriptionCosts() {
@@ -68,23 +60,17 @@ export async function getSubscriptionCosts() {
* Absent key vs. present-but-empty are DIFFERENT (the LLM/merge convention in
* AGENTS.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.
+ * is deleted. `mergeFamilyMap` owns that rule for every per-family settings
+ * map, so the plan tiers beside these prices cannot drift from it.
*/
// `options` is forwarded to `updateSettingsWith` so the operator-action actor
// (#5594) survives: both callers — the Settings PUT and the usage page's price
// editor — are a human, and would otherwise be logged as `system`.
export async function saveSubscriptionCosts(patch, options) {
- 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 };
- }, options);
+ const next = await updateSettingsWith((current) => ({
+ ...current,
+ [SETTINGS_KEY]: mergeFamilyMap(current?.[SETTINGS_KEY], patch, normalizeCost),
+ }), options);
return normalizeSubscriptionCosts(next?.[SETTINGS_KEY]);
}
diff --git a/server/services/subscriptions.js b/server/services/subscriptions.js
index 3b011814e6..7b6d0d348b 100644
--- a/server/services/subscriptions.js
+++ b/server/services/subscriptions.js
@@ -1,9 +1,9 @@
import { getSettings, updateSettingsWith } from './settings.js';
-import { getAllProviders, updateProvider } from './providers.js';
-import { getSubscriptionCosts } from './subscriptionCosts.js';
+import { listProviders, updateProvider } from './providers.js';
+import { normalizeSubscriptionCosts } from './subscriptionCosts.js';
import { PROVIDER_FAMILIES, familyForProvider, familyLabel } from '../lib/providerFamilies.js';
-import { normalizePlanTier, normalizePlanTiers } from '../lib/subscriptionPlanTiers.js';
-import { isPlainObject } from '../lib/objects.js';
+import { normalizePlanTier } from '../lib/subscriptionPlanTiers.js';
+import { mergeFamilyMap, normalizeFamilyMap } from '../lib/familySettingsMap.js';
/**
* The subscription plans this install pays for: which ones are switched on,
@@ -17,13 +17,15 @@ import { isPlainObject } from '../lib/objects.js';
*
* Prices live in `subscriptionCosts.js` (settings `subscriptionCosts`) because
* the savings math is their only consumer. Tiers live here (settings
- * `subscriptionPlanTiers`) with the same patch semantics, and this module is
- * what joins price + tier + enablement + provider membership into the one row
- * the Subscriptions page renders.
+ * `subscriptionPlanTiers`), both maps merging through `lib/familySettingsMap.js`
+ * so their absent-vs-cleared contract is one rule rather than two copies.
*/
const SETTINGS_KEY = 'subscriptionPlanTiers';
+/** Pure: normalize a whole tier map, dropping every cleared/invalid entry. */
+export const normalizePlanTiers = (raw) => normalizeFamilyMap(raw, normalizePlanTier);
+
/** Stored plan tiers, `{ [family]: label }`. */
export async function getPlanTiers() {
const settings = await getSettings();
@@ -32,23 +34,14 @@ export async function getPlanTiers() {
/**
* Merge a patch of plan tiers into settings and return the normalized map.
- *
- * Absent vs. present-but-empty are DIFFERENT, exactly as for prices: a family
- * the patch omits keeps its stored tier, while one sent as `null`/`""` is an
- * intentional clear and is deleted. Without that split an editor submitting
- * only changed rows could never remove a tier the user stopped being on.
+ * Omitted keeps, empty clears — see `mergeFamilyMap` for why that split is
+ * load-bearing. `options` carries the operator actor, as the price saver's does.
*/
export async function savePlanTiers(patch, options) {
- const incoming = isPlainObject(patch) ? patch : {};
- const next = await updateSettingsWith((current) => {
- const merged = { ...normalizePlanTiers(current?.[SETTINGS_KEY]) };
- for (const [family, value] of Object.entries(incoming)) {
- const tier = normalizePlanTier(value);
- if (tier === null) delete merged[family];
- else merged[family] = tier;
- }
- return { ...current, [SETTINGS_KEY]: merged };
- }, options);
+ const next = await updateSettingsWith((current) => ({
+ ...current,
+ [SETTINGS_KEY]: mergeFamilyMap(current?.[SETTINGS_KEY], patch, normalizePlanTier),
+ }), options);
return normalizePlanTiers(next?.[SETTINGS_KEY]);
}
@@ -79,42 +72,58 @@ const providerSummary = (provider) => ({
/**
* Pure: one row per manageable subscription — every family with at least one
- * provider configured, plus every family the user has priced or tiered.
+ * provider CONFIGURED (enabled or not), plus every family the user has priced
+ * or tiered.
*
- * That second half is the same rule `resolveSubscriptionFamilies` follows and
- * for the same reason: a priced family whose providers were all deleted must
- * keep a row, or its stored price becomes invisible and unclearable. A family
- * id that no longer exists in `PROVIDER_FAMILIES` (an older install's leftover)
- * still gets a row for exactly that reason, labelled by its raw id.
+ * Deliberately NOT `resolveSubscriptionFamilies` (subscriptionCosts.js), which
+ * answers a different question for the savings card: it starts from the
+ * ENABLED families, because a plan that did no work in the window has no
+ * figures to show. This page has to list a configured-but-switched-off plan —
+ * that row is the only way to switch it back on — so it starts from configured
+ * instead, and has no use for that function's spend-in-window extras.
+ *
+ * What the two DO share is the data-preservation rule: a priced or tiered
+ * family with no providers left still gets a row, or its stored value becomes
+ * invisible and unclearable. That covers a family id an older install stored
+ * and this registry no longer knows, which `familyLabel` renders by its raw id.
*
* `enabled` mirrors `resolveEnabledFamilies`: a plan is on when ANY of its
- * providers is enabled, so the toggle and the savings block's `enabled` flag
- * can never disagree.
+ * providers is enabled. Both now derive membership from `familyForProvider`,
+ * so the toggle and the savings block's `enabled` flag cannot disagree.
*/
export function buildSubscriptionFamilies({ providers = [], costs = {}, tiers = {} } = {}) {
const byFamily = groupProvidersByFamily(providers);
- const known = PROVIDER_FAMILIES
- .map((family) => ({ id: family.id, label: family.label, members: byFamily.get(family.id) || [] }))
- .filter((row) => row.members.length > 0 || costs[row.id] != null || tiers[row.id] != null);
- const knownIds = new Set(PROVIDER_FAMILIES.map((family) => family.id));
- const orphans = [...new Set([...Object.keys(costs), ...Object.keys(tiers)])]
- .filter((id) => !knownIds.has(id))
- .map((id) => ({ id, label: familyLabel(id), members: [] }));
- return [...known, ...orphans].map((row) => ({
- family: row.id,
- label: row.label,
- enabled: row.members.some((provider) => provider.enabled === true),
- monthlyCost: costs[row.id] ?? 0,
- planTier: tiers[row.id] ?? null,
- providers: row.members.map(providerSummary),
- }));
+ // Registry order first, then any stored-only id, so the rows are stable.
+ const ids = [...new Set([...PROVIDER_FAMILIES.map((f) => f.id), ...Object.keys(costs), ...Object.keys(tiers)])];
+ return ids
+ .map((id) => ({ id, members: byFamily.get(id) || [] }))
+ .filter(({ id, members }) => members.length > 0 || costs[id] != null || tiers[id] != null)
+ .map(({ id, members }) => ({
+ family: id,
+ label: familyLabel(id),
+ enabled: members.some((provider) => provider.enabled === true),
+ monthlyCost: costs[id] ?? 0,
+ planTier: tiers[id] ?? null,
+ providers: members.map(providerSummary),
+ }));
}
-/** The whole Subscriptions page model: rows plus the raw stored maps. */
+/**
+ * The Subscriptions page's row set.
+ *
+ * ONE `getSettings()` for both stored maps rather than `getSubscriptionCosts()`
+ * + `getPlanTiers()`: each of those deep-clones the whole settings tree, and
+ * the two keys sit in the same snapshot.
+ */
export async function getSubscriptionOverview() {
- const [result, costs, tiers] = await Promise.all([getAllProviders(), getSubscriptionCosts(), getPlanTiers()]);
- const providers = Array.isArray(result) ? result : (result?.providers || []);
- return { families: buildSubscriptionFamilies({ providers, costs, tiers }), costs, tiers };
+ const [providers, settings] = await Promise.all([listProviders(), getSettings()]);
+ return {
+ families: buildSubscriptionFamilies({
+ providers,
+ costs: normalizeSubscriptionCosts(settings?.subscriptionCosts),
+ tiers: normalizePlanTiers(settings?.[SETTINGS_KEY]),
+ }),
+ };
}
/**
@@ -130,9 +139,7 @@ export async function getSubscriptionOverview() {
* there is simply nothing local to toggle. Its price stays stored either way.
*/
export async function setSubscriptionEnabled(family, enabled) {
- const result = await getAllProviders();
- const providers = Array.isArray(result) ? result : (result?.providers || []);
- const members = groupProvidersByFamily(providers).get(family) || [];
+ const members = groupProvidersByFamily(await listProviders()).get(family) || [];
const changed = [];
for (const provider of members) {
if ((provider.enabled === true) === enabled) continue;
diff --git a/server/services/subscriptions.test.js b/server/services/subscriptions.test.js
index fba373773b..008897dbf6 100644
--- a/server/services/subscriptions.test.js
+++ b/server/services/subscriptions.test.js
@@ -20,14 +20,18 @@ const updateProvider = vi.fn(async (id, patch) => {
return providerRecords.find((p) => p.id === id);
});
vi.mock('./providers.js', () => ({
- getAllProviders: vi.fn(async () => ({ providers: structuredClone(providerRecords) })),
+ listProviders: vi.fn(async () => structuredClone(providerRecords)),
updateProvider: (...args) => updateProvider(...args),
}));
-// subscriptionCosts pulls providerUsage's PTY-scrape graph in transitively.
-// Only the stored-price read is needed here.
+// subscriptionCosts still imports providerUsage (for the savings card's own
+// family resolver), which drags the TUI-scrape/PTY graph in. Only the pure
+// price normalizer is needed here, and it is exercised for real by that
+// module's own suite.
vi.mock('./subscriptionCosts.js', () => ({
- getSubscriptionCosts: vi.fn(async () => structuredClone(stored.subscriptionCosts || {})),
+ normalizeSubscriptionCosts: (raw) => Object.fromEntries(
+ Object.entries(raw || {}).filter(([, value]) => Number(value) > 0),
+ ),
}));
import {
@@ -75,17 +79,6 @@ describe('plan tier persistence', () => {
});
});
-describe('groupProvidersByFamily', () => {
- it('maps each provider to its family and skips local-runtime wrappers', () => {
- const grouped = groupProvidersByFamily([claudeCli, claudeAlt, codexCli, claudeOnOllama]);
- expect(grouped.get('claude').map((p) => p.id)).toEqual(['claude-code', 'claude-code-alt']);
- expect(grouped.get('codex').map((p) => p.id)).toEqual(['codex-cli']);
- // An Ollama-backed `claude` wrapper runs a local model — no subscription to
- // manage, so it must not make the Claude plan look enabled.
- expect(grouped.get('claude')).not.toContainEqual(expect.objectContaining({ id: 'claude-ollama' }));
- });
-});
-
describe('buildSubscriptionFamilies', () => {
it('reports a plan as enabled when ANY of its providers is on', () => {
const [claude] = buildSubscriptionFamilies({ providers: [claudeCli, claudeAlt] });
@@ -125,8 +118,6 @@ describe('getSubscriptionOverview', () => {
providerRecords = [claudeCli, codexCli];
stored = { subscriptionCosts: { claude: 100 }, subscriptionPlanTiers: { claude: 'Max 5x' } };
const overview = await getSubscriptionOverview();
- expect(overview.costs).toEqual({ claude: 100 });
- expect(overview.tiers).toEqual({ claude: 'Max 5x' });
expect(overview.families).toEqual([
expect.objectContaining({ family: 'claude', enabled: true, monthlyCost: 100, planTier: 'Max 5x' }),
expect.objectContaining({ family: 'codex', enabled: false, monthlyCost: 0, planTier: null }),
@@ -165,7 +156,6 @@ describe('setSubscriptionEnabled', () => {
stored = { subscriptionCosts: { codex: 20 } };
await setSubscriptionEnabled('codex', false);
const overview = await getSubscriptionOverview();
- expect(overview.costs).toEqual({ codex: 20 });
expect(overview.families).toEqual([
expect.objectContaining({ family: 'codex', enabled: false, monthlyCost: 20 }),
]);