Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: add a Subscriptions page under Models to manage AI plans (#7403)
[._.]/ Adam Eivy326612e33400
diff --git a/client/src/components/models/SubscriptionsTab.jsx b/client/src/components/models/SubscriptionsTab.jsxnew file mode 100644index 0000000000..2090c0b1f7--- /dev/null+++ b/client/src/components/models/SubscriptionsTab.jsx@@ -0,0 +1,416 @@+import { useCallback, useEffect, useMemo, useState } from 'react';+import { useSearchParams } from 'react-router';+import { AlertTriangle, 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';++/**+ * Subscriptions — which AI plans this install pays for, whether each is on, and+ * what each is costing against what it did.+ *+ * 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).+ *+ * 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.+ *+ * 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.+ */++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.+ */+export function parseTierInput(raw) {+ const trimmed = String(raw ?? '').trim();+ return trimmed === '' ? null : trimmed;+}++/**+ * The per-family patches 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.+ */+export function buildRowPatch(row, draft) {+ if (!draft) return null;+ const patch = {};+ if (draft.cost !== undefined) {+ const nextCost = parseCostInput(draft.cost);+ const storedCost = row.monthlyCost > 0 ? row.monthlyCost : null;+ if (nextCost !== undefined && nextCost !== storedCost) patch.cost = nextCost;+ }+ if (draft.tier !== undefined) {+ const nextTier = parseTierInput(draft.tier);+ if (nextTier !== (row.planTier ?? null)) patch.tier = nextTier;+ }+ return Object.keys(patch).length ? patch : null;+}++// 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.+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,+ },+ ];+};++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;+ 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>}+ </h3>+ <p className="text-[10px] sm:text-xs text-gray-500 mt-0.5">+ {toggleable+ ? `${row.providers.length} provider${row.providers.length === 1 ? '' : 's'} · ${row.enabled ? 'on' : 'off'}`+ : 'No provider configured — price kept for the record'}+ </p>+ </div>+ <div className="flex items-center gap-2 shrink-0">+ {busy && <BrailleSpinner />}+ <ToggleSwitch+ size="sm"+ enabled={row.enabled}+ disabled={busy || !toggleable}+ onChange={() => onToggle(row)}+ ariaLabel={`${row.enabled ? 'Disable' : 'Enable'} the ${row.label} subscription`}+ />+ </div>+ </div>++ <div className="flex flex-wrap items-end gap-3">+ <div>+ <label htmlFor={`subscription-tier-${row.family}`} className="block text-[10px] sm:text-xs text-gray-400 mb-1">+ Plan+ </label>+ <input+ id={`subscription-tier-${row.family}`}+ type="text"+ maxLength={60}+ placeholder="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)}+ className="w-36 sm:w-44 bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-white outline-none focus:border-port-accent"+ />+ </div>+ <div>+ <label htmlFor={`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>+ </div>+ {patch && (+ <button+ type="button"+ onClick={() => onSave(row, patch)}+ disabled={busy}+ aria-label={`Save the ${row.label} plan`}+ 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"+ >+ <Save size={14} /> Save+ </button>+ )}+ </div>++ {figures.length > 0 && (+ <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>+ </div>+ ))}+ </div>+ )}++ <div className="border-t border-port-border pt-2">+ <QuotaSummary quota={quota} />+ </div>+ </div>+ );+}++export default function SubscriptionsTab() {+ const [searchParams, setSearchParams] = useSearchParams();+ const period = searchParams.get('period') || DEFAULT_PERIOD;++ const [overview, setOverview] = 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 loadPlans = useCallback(async () => {+ const data = await api.getSubscriptions({ silent: true }).catch(() => null);+ if (data) setOverview(data);+ return data;+ }, []);++ const loadSavings = useCallback(async () => {+ const data = await api.getUsage({ period }).catch(() => null);+ setSavings(data?.subscriptionSavings ?? null);+ }, [period]);++ const loadQuotas = useCallback(async (refresh = false) => {+ const data = await api.getProviderUsage({ refresh }).catch(() => null);+ // A failed read keeps whatever was already on screen: the meters are+ // supporting detail here, and blanking them would look like "the plan has+ // no quota" rather than "the scrape didn't answer".+ if (data?.providers) setQuotas(data.providers);+ }, []);++ 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);+ });+ loadQuotas();+ return () => { cancelled = true; };+ }, [loadPlans, loadSavings, 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 });++ const rows = overview?.families ?? NO_ROWS;+ const savingsByFamily = useMemo(+ () => new Map((savings?.families ?? NO_ROWS).map((entry) => [entry.family, entry])),+ [savings],+ );+ const quotaByFamily = useMemo(+ () => new Map((quotas ?? NO_ROWS).map((entry) => [entry.family, entry])),+ [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 },+ }));++ 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+ // flash the pre-save value back onto the row in between.+ setDrafts((prev) => {+ const next = { ...prev };+ delete next[row.family];+ return next;+ });+ });++ const onToggle = (row) => withBusy(row.family, async () => {+ const result = await api.setSubscriptionEnabled(+ { family: row.family, enabled: !row.enabled },+ { silent: true },+ ).catch(() => null);+ if (!result) return;+ // Re-read rather than patching state locally: 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()]);+ // 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();+ });++ return (+ <div className="space-y-4">+ <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2">+ <div>+ <h1 className="text-xl sm:text-2xl font-bold text-white flex items-center gap-2">+ <CreditCard size={20} className="text-port-accent" /> Subscriptions+ </h1>+ <p className="text-xs text-gray-500 mt-0.5">+ Which AI plans this install pays for, whether each is switched on, and what each costs against what it did.+ </p>+ </div>+ <button+ type="button"+ onClick={() => loadQuotas(true)}+ className="flex items-center gap-1.5 self-start px-2 sm:px-3 py-1.5 text-xs sm:text-sm text-gray-400 hover:text-white"+ title="Re-read every plan's quota"+ >+ <RefreshCw size={15} className="will-change-transform" /> Refresh quota+ </button>+ </div>++ <Banner tone="info">+ PortOS tracking only. Switching a subscription off here stops this install dispatching work to that plan — it+ does not change, pause or cancel anything with the provider. Manage real billing on the provider’s own site.+ </Banner>++ <div className="flex flex-wrap gap-2">+ {PERIOD_OPTIONS.map((option) => (+ <button+ key={option.id}+ type="button"+ onClick={() => setPeriod(option.id)}+ className={`px-3 py-1 rounded-full text-xs sm:text-sm border ${period === option.id+ ? 'border-port-accent text-white bg-port-accent/20'+ : 'border-port-border text-gray-400 hover:text-white'}`}+ >+ {option.label}+ </button>+ ))}+ </div>++ {loading && (+ <PageSkeleton header="none" label="Loading subscriptions" layout="grid" gridColsClass="grid-cols-1 lg:grid-cols-2" cards={4} />+ )}++ {!loading && 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 && (+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-3 items-start" aria-label="AI subscriptions">+ {rows.map((row) => (+ <SubscriptionRow+ key={row.family}+ row={row}+ savingsRow={savingsByFamily.get(row.family)}+ quota={quotaByFamily.get(row.family)}+ draft={drafts[row.family]}+ busy={busyFamilies.has(row.family)}+ onDraft={onDraft}+ onSave={onSave}+ onToggle={onToggle}+ />+ ))}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/models/SubscriptionsTab.test.jsx b/client/src/components/models/SubscriptionsTab.test.jsxnew file mode 100644index 0000000000..f8f045a3e8--- /dev/null+++ b/client/src/components/models/SubscriptionsTab.test.jsx@@ -0,0 +1,164 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { MemoryRouter } from 'react-router';++const api = vi.hoisted(() => ({+ getSubscriptions: vi.fn(),+ getUsage: vi.fn(),+ getProviderUsage: vi.fn(),+ updateSubscriptionCosts: vi.fn(),+ updateSubscriptionPlanTiers: vi.fn(),+ setSubscriptionEnabled: vi.fn(),+}));+vi.mock('../../services/api', () => api);++const { default: SubscriptionsTab, buildRowPatch, parseTierInput } = await import('./SubscriptionsTab');++const claudeRow = {+ family: 'claude',+ label: 'Claude Code',+ enabled: true,+ monthlyCost: 200,+ planTier: 'Max 5x',+ providers: [{ id: 'claude-code', name: 'Claude Code', enabled: true }],+};++const codexRow = {+ family: 'codex',+ label: 'Codex',+ enabled: false,+ monthlyCost: 20,+ planTier: null,+ providers: [{ id: 'codex-cli', name: 'Codex', enabled: false }],+};++const renderTab = () => render(<MemoryRouter><SubscriptionsTab /></MemoryRouter>);++beforeEach(() => {+ vi.clearAllMocks();+ api.getSubscriptions.mockResolvedValue({ families: [claudeRow, codexRow], costs: {}, tiers: {} });+ api.getUsage.mockResolvedValue({+ subscriptionSavings: {+ families: [+ { family: 'claude', configured: true, periodCost: 46, apiCost: 812.44, savings: 766.44 },+ { family: 'codex', configured: true, periodCost: 4.6, apiCost: 2, savings: -2.6 },+ ],+ },+ });+ api.getProviderUsage.mockResolvedValue({+ providers: [{+ family: 'claude', label: 'Claude Code', supported: true, pending: false,+ 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'] });+});++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('buildRowPatch', () => {+ it('returns null when nothing the user typed differs from what is stored', () => {+ expect(buildRowPatch(claudeRow, undefined)).toBeNull();+ expect(buildRowPatch(claudeRow, { cost: '200', tier: 'Max 5x' })).toBeNull();+ });++ it('patches only the field that changed', () => {+ expect(buildRowPatch(claudeRow, { cost: '200', tier: 'Max 20x' })).toEqual({ tier: 'Max 20x' });+ expect(buildRowPatch(claudeRow, { cost: '100' })).toEqual({ cost: 100 });+ });++ it('carries an emptied field through as a clear', () => {+ expect(buildRowPatch(claudeRow, { cost: '', tier: '' })).toEqual({ cost: null, tier: null });+ });++ it('skips an unparseable price rather than clearing a fat-fingered one', () => {+ expect(buildRowPatch(claudeRow, { cost: 'abc' })).toBeNull();+ });+});++describe('SubscriptionsTab', () => {+ it('renders one row per plan with its tier, price, spend and quota', async () => {+ renderTab();+ expect(await screen.findByText('Claude Code')).toBeInTheDocument();+ expect(screen.getByText('Codex')).toBeInTheDocument();+ expect(screen.getByDisplayValue('Max 5x')).toBeInTheDocument();+ expect(screen.getByDisplayValue('200')).toBeInTheDocument();+ // Spend figures come from the savings block, quota meters from the scrape.+ expect(screen.getByText('$812.44')).toBeInTheDocument();+ await waitFor(() => expect(screen.getByText('Weekly')).toBeInTheDocument());+ });++ // The whole point of the page: it manages PortOS-side tracking, not billing.+ it('states that it never touches provider billing', async () => {+ renderTab();+ await screen.findByText('Claude Code');+ expect(screen.getByText(/does not change, pause or cancel anything with the provider/i)).toBeInTheDocument();+ });++ it('toggles a subscription through the family endpoint and re-reads the rows', async () => {+ renderTab();+ await screen.findByText('Codex');+ fireEvent.click(screen.getByLabelText('Enable the Codex subscription'));+ await waitFor(() => expect(api.setSubscriptionEnabled).toHaveBeenCalledWith(+ { 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));+ });++ // A disabled plan keeps its price: the row and its stored cost must survive a+ // toggle, or cancelling a plan for a week would silently lose what it costs.+ it('keeps a disabled plan listed with its price intact', async () => {+ api.getSubscriptions.mockResolvedValue({+ families: [{ ...claudeRow, enabled: false, providers: [{ id: 'claude-code', name: 'Claude Code', enabled: false }] }],+ costs: { claude: 200 },+ tiers: { claude: 'Max 5x' },+ });+ renderTab();+ expect(await screen.findByText('Claude Code')).toBeInTheDocument();+ expect(screen.getByDisplayValue('200')).toBeInTheDocument();+ expect(screen.getByLabelText('Enable the Claude Code subscription')).toHaveAttribute('aria-checked', 'false');+ });++ it('saves a changed tier and price through their own endpoints', 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' },+ expect.anything(),+ ));+ expect(api.updateSubscriptionCosts).toHaveBeenCalledWith({ claude: 100 }, expect.anything());+ });++ it('offers no toggle for a priced plan with no provider configured', async () => {+ api.getSubscriptions.mockResolvedValue({+ families: [{ family: 'grok', label: 'Grok', enabled: false, monthlyCost: 30, planTier: null, providers: [] }],+ costs: { grok: 30 },+ tiers: {},+ });+ renderTab();+ expect(await screen.findByText(/No provider configured/i)).toBeInTheDocument();+ expect(screen.getByLabelText('Enable the Grok subscription')).toBeDisabled();+ });++ it('says so when there is nothing to manage', async () => {+ api.getSubscriptions.mockResolvedValue({ families: [], costs: {}, tiers: {} });+ renderTab();+ expect(await screen.findByText(/No subscriptions to manage/i)).toBeInTheDocument();+ });+});diff --git a/client/src/components/usage/UsageMeter.jsx b/client/src/components/usage/UsageMeter.jsxnew file mode 100644index 0000000000..e8956a789d--- /dev/null+++ b/client/src/components/usage/UsageMeter.jsx@@ -0,0 +1,62 @@+import { Clock } from 'lucide-react';+import { timeUntil } from '../../utils/formatters';++/**+ * One quota window's meter — the shared rendering for a `limits[]` entry from+ * `GET /api/usage/providers`.+ *+ * Extracted from the Usage page (#7403) when the Subscriptions page needed the+ * 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.+ */++// 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+// a glance. The raw-text fallback stays for a reading off an older peer that+// still emits its CLI's own wording.+export const formatResetsAt = (resetsAt) => {+ if (!resetsAt || !/^\d{4}-\d{2}-\d{2}T/.test(resetsAt)) return resetsAt;+ const d = new Date(resetsAt);+ if (Number.isNaN(d.getTime())) return resetsAt;+ const local = d.toLocaleString(undefined, { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });+ const relative = timeUntil(d, '');+ 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';+}++export default function UsageMeter({ limit }) {+ const used = limit.percentUsed ?? 0;+ const remaining = limit.percentRemaining;+ return (+ <div className="py-1 sm:py-2 border-b border-port-border last:border-0">+ <div className="flex items-baseline justify-between gap-2 mb-0.5 sm:mb-1">+ <span className="text-white text-xs sm:text-base truncate" title={limit.label}>{limit.label}</span>+ <span className="shrink-0 text-gray-400 text-[10px] sm:text-sm">+ {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>+ <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 && (+ <span className="flex min-w-0 text-[9px] sm:text-xs text-gray-500 items-start sm:justify-end gap-1 sm:text-right leading-tight">+ <Clock size={11} className="shrink-0" /> resets {formatResetsAt(limit.resetsAt)}+ </span>+ )}+ </div>+ </div>+ );+}diff --git a/client/src/components/usage/UsageMeter.test.jsx b/client/src/components/usage/UsageMeter.test.jsxnew file mode 100644index 0000000000..7f5047b62e--- /dev/null+++ b/client/src/components/usage/UsageMeter.test.jsx@@ -0,0 +1,49 @@+import { describe, expect, it } from 'vitest';+import { render, screen } from '@testing-library/react';+import UsageMeter, { meterColor, formatResetsAt } from './UsageMeter';++describe('meterColor', () => {+ // 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');+ });++ // 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');+ });+});++describe('formatResetsAt', () => {+ it('passes through a non-ISO reading from an older peer unchanged', () => {+ expect(formatResetsAt('in about 3 hours')).toBe('in about 3 hours');+ expect(formatResetsAt(null)).toBeNull();+ });++ it('localizes an ISO reset', () => {+ expect(formatResetsAt('2026-03-01T12:00:00.000Z')).toMatch(/\d/);+ });+});++describe('UsageMeter', () => {+ it('shows the window, the remaining share and the used share', () => {+ render(<UsageMeter limit={{ key: 'week', label: 'Weekly', percentUsed: 40, percentRemaining: 60 }} />);+ expect(screen.getByText('Weekly')).toBeInTheDocument();+ expect(screen.getByText('60% left')).toBeInTheDocument();+ expect(screen.getByText('40% used')).toBeInTheDocument();+ });++ // A provider that reports usage but not a remainder must show an em dash,+ // never a fabricated 100%.+ it('renders a missing remainder as unknown', () => {+ render(<UsageMeter limit={{ key: 'week', label: 'Weekly', percentUsed: 40, percentRemaining: null }} />);+ expect(screen.getByText('—')).toBeInTheDocument();+ });+});diff --git a/client/src/lib/navPresentation.js b/client/src/lib/navPresentation.jsindex c7d8bc8e3d..db35a7b9d0 100644--- a/client/src/lib/navPresentation.js+++ b/client/src/lib/navPresentation.js@@ -9,6 +9,7 @@ import {Activity,BarChart3,Cpu,+ CreditCard,Gauge,FlaskConical,Braces,@@ -233,6 +234,7 @@ export const NAV_PRESENTATION = {'/models/performance': { icon: Gauge },'/local-llm/playground': { icon: FlaskConical },'/models/status': { icon: Activity },+ '/models/subscriptions': { icon: CreditCard },'/models/training': { icon: GraduationCap },'/settings/ai-assignments': { icon: Bot },'/settings/api-access': { icon: Globe },diff --git a/client/src/pages/Models.jsx b/client/src/pages/Models.jsxindex 54009f5173..1c5d538f66 100644--- a/client/src/pages/Models.jsx+++ b/client/src/pages/Models.jsx@@ -6,6 +6,7 @@ import PageSkeleton from '../components/ui/PageSkeleton';import ModelsTabsHeader from '../components/models/ModelsTabsHeader';import Image3dRuntimes from '../components/models/Image3dRuntimes';import ModelStatusTab from '../components/models/ModelStatusTab';+import SubscriptionsTab from '../components/models/SubscriptionsTab';import CodeReviewersTab from '../components/settings/CodeReviewersTab';import HarnessesTab from '../components/models/HarnessesTab';import EmbeddingsTab from '../components/settings/EmbeddingsTab';@@ -38,6 +39,7 @@ const MediaModels = lazyWithReload(() => import('./MediaModels'));* - **Performance** — measured assessments and launch-tuning comparison.* - **Providers** — configured AI provider connections and model catalogs.* - **Status** — residency plus the downloaded-model inventory.+ * - **Subscriptions** — which paid plans are on, their tier, price and spend.* - **Training** — LoRA fine-tuning datasets and runs.* - **Usage** — provider quota and PortOS AI usage accounting.*@@ -61,6 +63,7 @@ const TAB_CONTENT = {media: MediaModels,performance: LocalModelAssessments,status: ModelStatusTab,+ subscriptions: SubscriptionsTab,training: LoraTraining,};diff --git a/client/src/pages/Models.test.jsx b/client/src/pages/Models.test.jsxindex b54c036453..dae4ca5270 100644--- a/client/src/pages/Models.test.jsx+++ b/client/src/pages/Models.test.jsx@@ -19,6 +19,7 @@ vi.mock('../components/settings/LocalLlmTab', () => ({vi.mock('../components/settings/EmbeddingsTab', () => ({ default: () => <div>embeddings panel</div> }));vi.mock('../components/models/Image3dRuntimes', () => ({ default: () => <div>3d runtimes panel</div> }));vi.mock('../components/models/ModelStatusTab', () => ({ default: () => <div>status panel</div> }));+vi.mock('../components/models/SubscriptionsTab', () => ({ default: () => <div>subscriptions panel</div> }));vi.mock('../components/settings/CodeReviewersTab', () => ({ default: () => <div>code reviewers panel</div> }));vi.mock('../components/models/HarnessesTab', () => ({ default: () => <div>harnesses panel</div> }));vi.mock('../components/models/ModelComparison', () => ({ default: () => <div>comparison panel</div> }));@@ -44,6 +45,7 @@ const PANEL_MARKER = {media: 'media models panel',performance: 'assessments panel',status: 'status panel',+ subscriptions: 'subscriptions panel',training: 'training panel',};diff --git a/client/src/pages/UsagePage.jsx b/client/src/pages/UsagePage.jsxindex 5f2a41c72c..12d476ce45 100644--- a/client/src/pages/UsagePage.jsx+++ b/client/src/pages/UsagePage.jsx@@ -1,16 +1,17 @@import { useCallback, useState, useEffect, useRef } from 'react';import { useSearchParams } from 'react-router';-import { RefreshCw, Clock, AlertTriangle, DatabaseZap, Network } from 'lucide-react';+import { RefreshCw, AlertTriangle, DatabaseZap, Network } 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, formatCompactCountOrDash as formatNumber, formatUsd, timeAgo, timeUntil } from '../utils/formatters';+import { formatCompactCount, 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 ModelsTabsHeader from '../components/models/ModelsTabsHeader';// How often to re-ask while a provider's quota reading is still being taken. A@@ -24,56 +25,6 @@ const PERIOD_OPTIONS = [{ id: 'all', label: 'All time' }];-// 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-// a glance. The raw-text fallback stays for a reading off an older peer that-// still emits its CLI's own wording.-const formatResetsAt = (resetsAt) => {- if (!resetsAt || !/^\d{4}-\d{2}-\d{2}T/.test(resetsAt)) return resetsAt;- const d = new Date(resetsAt);- if (Number.isNaN(d.getTime())) return resetsAt;- const local = d.toLocaleString(undefined, { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });- const relative = timeUntil(d, '');- return relative ? `${local} (${relative})` : local;-};--// Color a usage meter by how much is consumed: comfortable → warning → critical.-function meterColor(percentUsed) {- if (percentUsed == null) return 'bg-gray-500';- if (percentUsed >= 90) return 'bg-port-error';- if (percentUsed >= 70) return 'bg-port-warning';- return 'bg-port-success';-}--function UsageMeter({ limit }) {- const used = limit.percentUsed ?? 0;- const remaining = limit.percentRemaining;- return (- <div className="py-1 sm:py-2 border-b border-port-border last:border-0">- <div className="flex items-baseline justify-between gap-2 mb-0.5 sm:mb-1">- <span className="text-white text-xs sm:text-base truncate" title={limit.label}>{limit.label}</span>- <span className="shrink-0 text-gray-400 text-[10px] sm:text-sm">- {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>- <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 && (- <span className="flex min-w-0 text-[9px] sm:text-xs text-gray-500 items-start sm:justify-end gap-1 sm:text-right leading-tight">- <Clock size={11} className="shrink-0" /> resets {formatResetsAt(limit.resetsAt)}- </span>- )}- </div>- </div>- );-}-// 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 }) {diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 761786d060..4a52608168 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, `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` / `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. || `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.jsindex 0f03bcaa5f..957f9a7696 100644--- a/client/src/services/apiSystem.js+++ b/client/src/services/apiSystem.js@@ -182,6 +182,25 @@ export const getUsageBackfillStatus = (options = {}) => request('/usage/backfill// 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 });+// The Subscriptions page's own model: one row per manageable plan (enabled+// state, plan tier, monthly price, the provider records a toggle fans out to).+// 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 });+// 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`.+export const setSubscriptionEnabled = ({ family, enabled }, options = {}) =>+ request('/usage/subscriptions/enabled', {+ method: 'PUT',+ body: JSON.stringify({ family, enabled }),+ ...options,+ });// Mark one federated instance as paying API rates (`usesSubscriptions: false`)// or riding this install's subscriptions (`true`). The Across Instances// combined total skips API-billed rows; the row itself stays listed.diff --git a/server/lib/README.md b/server/lib/README.mdindex e277c1b566..02746137ee 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -215,6 +215,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `reviewerProviderMatchers.js` | Which PROVIDER RECORDS front each model-taking reviewer's binary — `REVIEWER_PROVIDER_MATCHERS` (slug → record predicates, in preference order), `providersForReviewer(reviewer, providers)` (every match, de-duped, preference-ordered so `[0]` is the record whose default a picker shows) and `reviewerProviderIds`. A reviewer slug names a BINARY and PortOS ships more than one record per binary (`claude` spans `claude-code` + `claude-code-tui`, `grok` spans `grok-cli` + its TUI), so both the picker's option list and the retired-pin audit union every match: sourcing from one record makes the answer hostage to that record's staleness, and judging a pin against one produces a false retirement for a model the other still lists. Deliberately excludes Bedrock/Vertex and the `opencode-<backend>` presets (ids that resolve only under another record's environment). Imported directly by `client/src/hooks/useReviewerModelOptions.js` — one table, no mirror to drift (#7339). || `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). |+| `subscriptionPlanTiers.js` | Which TIER of a subscription plan the user is on ("Max 20x", "Pro"), as a short free-text label per provider family — `MAX_PLAN_TIER_LENGTH` (the cap the Zod schema enforces), `normalizePlanTier` / `normalizePlanTiers` (trim, cap, and collapse empty/non-string to `null` = not recorded). Deliberately free text: tiers are vendor marketing names that change off the PortOS release cycle. Pure; persistence lives in `services/subscriptions.js`. || `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. || `credentialRegistry.js` | Pure catalog of PortOS credentials (`CREDENTIALS`, `CREDENTIAL_IDS`, `CREDENTIAL_TIERS`) — one entry per key/token an install can use (`id`, `label`, `unlocks`, `tier`, `getUrl`, `envVars`, `settingsPath`, `configurePath`, optional `feature`). Sits beside `instanceFeatureRegistry.js` so the two lists stay greppable together. Runtime resolution (settings / repo `.env` / inherited `process.env` / CLI / instance config) lives in `services/credentialInventory.js`. The Settings > Credentials page never receives a value or masked prefix. || `instanceFeatureRegistry.js` | The registry of optional per-install features (`INSTANCE_FEATURES`, `INSTANCE_FEATURE_IDS`, `APP_FEATURE_IDS`) — pure data, so `validation.js` derives its feature schemas from it and `navManifest.js` can be checked against it without a service→lib inversion. Runtime resolution (stored override → auto-detection → `defaultEnabled`) lives in `services/instanceFeatures.js`. A feature id tagged on a nav entry hides that page from ⌘K and the sidebar when the feature is off. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 7ed00a9f5b..a3243bede1 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -462,6 +462,7 @@ export * from './noReplaceMove.js';export * from './instanceFeatureRegistry.js';export * from './credentialRegistry.js';export * from './usageRange.js';+export * from './subscriptionPlanTiers.js';export * from './subscriptionSavings.js';export * from './providerFamilies.js';export * from './fleetQuotas.js';diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex e0774fd850..cb5606ae50 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -325,6 +325,7 @@ const RAW_NAV_COMMANDS = [// keywords live here — 'model resources' and 'downloaded models' must keep// resolving after the fold.{ id: 'nav.models.status', path: '/models/status', label: 'Status', section: 'Models', tabId: 'status', previousPaths: ['/system-resources/models'], aliases: ['model-status', 'models-status', 'memory-management', 'resident-models', 'model-resources', 'loaded-models', 'downloaded-models', 'model-memory'], keywords: ['memory', 'resident', 'loaded', 'unload', 'ram', 'vram', 'free memory', 'what is loaded', 'ollama', 'lm studio', 'hugging face', 'lora', 'delete model', 'disk'] },+ { id: 'nav.models.subscriptions', path: '/models/subscriptions', label: 'Subscriptions', section: 'Models', tabId: 'subscriptions', aliases: ['subscriptions', 'subscription', 'plans', 'ai-subscriptions', 'my-plans'], keywords: ['plan', 'price', 'spend', 'cost', 'billing', 'enable', 'disable', 'claude max', 'chatgpt plus', 'pro', 'tier', 'savings', 'quota'] },{ id: 'nav.settings.local-llm-playground', path: '/local-llm/playground', label: 'Playground', section: 'Models', tabId: 'playground', aliases: ['llm-playground', 'playground', 'model-playground', 'compare-models'], keywords: ['ollama', 'lm studio', 'compare', 'benchmark', 'chat', 'test model', 'ttft', 'tokens per second', 'local llm'] },{ id: 'nav.settings.mortalloom', path: '/settings/mortalloom', label: 'MortalLoom', section: 'Settings', tabId: 'mortalloom', feature: 'health', aliases: ['settings-mortalloom', 'mortalloom'] },{ id: 'nav.settings.openclaw', path: '/openclaw', label: 'OpenClaw', section: 'Settings', tabId: 'openclaw', feature: 'openclaw', aliases: ['openclaw', 'settings-openclaw'], keywords: ['operator', 'chat', 'agent', 'runtime', 'sessions', 'streaming'] },diff --git a/server/lib/subscriptionPlanTiers.js b/server/lib/subscriptionPlanTiers.jsnew file mode 100644index 0000000000..975ad765f4--- /dev/null+++ b/server/lib/subscriptionPlanTiers.js@@ -0,0 +1,58 @@+import { isPlainObject } from './objects.js';++/**+ * Which TIER of a subscription the user is on — "Max 5x" vs "Max 20x", "Pro"+ * vs "Plus" — as a short free-text label per provider family.+ *+ * The price in `services/subscriptionCosts.js` already answers "what does this+ * plan cost", and that number is what every savings figure is computed from.+ * What it cannot answer is WHICH plan produced it: two installs both paying+ * $100/mo may be on different Claude tiers with different quota ceilings, and+ * the quota scrape reports a window's percentage, not a plan name. Recording+ * the tier keeps that identity next to the price without overloading it — a+ * numeric field can never hold "Max 20x", and a price that silently doubled+ * would be the only trace of an upgrade.+ *+ * Deliberately free text, not an enum: the tiers are each vendor's marketing+ * names and they change on the vendor's schedule, not on PortOS releases. A+ * stale enum would reject the plan the user is actually paying for.+ *+ * Pure by design, like `lib/subscriptionSavings.js` beside it: the Zod schema+ * that guards the persisted write needs the cap, and a schema cannot import a+ * service. Persistence and the merge semantics live in+ * `services/subscriptions.js`.+ */++/**+ * Longest stored tier label. Generous enough for every real plan name+ * ("Claude Max 20x", "ChatGPT Pro"), short enough that the value stays a LABEL+ * — settings.json must not become a notes field, and the row renders inline+ * beside a price input.+ */+export const MAX_PLAN_TIER_LENGTH = 60;++/**+ * Pure: a stored/incoming tier as a trimmed label, or null for "not recorded".+ *+ * ONE definition of the rule, used on both read and write, so a tier can never+ * 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.+ */+export function normalizePlanTier(value) {+ if (typeof value !== 'string') return null;+ const tier = value.trim().slice(0, 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.jsindex b9a34566cc..5261ff5118 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -7,6 +7,7 @@ import { WORK_TRACKERS } from './workTracker.js';import { PROVIDER_FAMILY_IDS } from './providerFamilies.js';import { APP_FEATURE_IDS, INSTANCE_FEATURE_IDS, INSTANCE_FEATURE_GROUP_IDS } from './instanceFeatureRegistry.js';import { MAX_MONTHLY_COST } from './subscriptionSavings.js';+import { MAX_PLAN_TIER_LENGTH } from './subscriptionPlanTiers.js';import { QUEUEABLE_IMAGE_MODES, VIDEO_GEN_MODES } from './generationModes.js';import { RENDER_TARGETS, RENDER_TARGET_BACKEND_AUTO } from './renderTargets.js';import {@@ -1425,8 +1426,42 @@ export const subscriptionCostsMapSchema = z.partialRecord(z.number().min(0).max(MAX_MONTHLY_COST).nullable());-/** Body for PUT /api/usage/subscriptions. */-export const subscriptionCostsSchema = z.object({ costs: subscriptionCostsMapSchema });+/**+ * Which TIER of each family's plan the user is on, keyed by family id. Same+ * key rule and same patch semantics as the price map above — an omitted family+ * keeps its stored tier, `null` (or an empty string, which normalizes to null)+ * CLEARS it. Free text rather than an enum because these are vendor marketing+ * names ("Max 20x", "Pro") that change on the vendor's schedule, not on the+ * PortOS release cycle; the length cap is what keeps settings.json from+ * collecting notes.+ *+ * Used by BOTH write paths — `PUT /api/usage/subscriptions` and the+ * `subscriptionPlanTiers` slice of `PUT /api/settings`.+ */+export const subscriptionPlanTiersMapSchema = z.partialRecord(+ z.enum(PROVIDER_FAMILY_IDS),+ z.string().max(MAX_PLAN_TIER_LENGTH).nullable()+);++/**+ * Body for PUT /api/usage/subscriptions. Both slices are OPTIONAL and+ * 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({+ costs: subscriptionCostsMapSchema.optional(),+ tiers: subscriptionPlanTiersMapSchema.optional(),+});++/**+ * Body for PUT /api/usage/subscriptions/enabled — switch one subscription on or+ * off. `family` is enumerated, not free text, because the handler fans the flag+ * out across every provider record that family owns.+ */+export const subscriptionEnabledSchema = z.object({+ family: z.enum(PROVIDER_FAMILY_IDS),+ enabled: z.boolean(),+});/*** Instances that pay API rates rather than the viewer's subscriptions, so thediff --git a/server/routes/settings.js b/server/routes/settings.jsindex ee2540934e..4632f0f41e 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -4,6 +4,7 @@ import { z } from 'zod';import { getSettings, updateSettingsWith } from '../services/settings.js';import { getAiAssignments, updateAiAssignment } from '../services/aiAssignments.js';import { saveSubscriptionCosts } from '../services/subscriptionCosts.js';+import { savePlanTiers } from '../services/subscriptions.js';import { saveApiBilledInstanceIds } from '../services/usageFleetBilling.js';import {setCodexParallelLimit,@@ -23,7 +24,7 @@ import { resolveBackupConfig } from '../lib/backupConfig.js';import { DEFAULT_UNTRUSTED_CONTENT_POLICY, untrustedContentSettingsSchema } from '../lib/untrustedContent.js';import { agentContextSettingsSchema } from '../lib/agentContextValidation.js';import { EFFORT_LEVELS } from '../lib/providerModels.js';-import { privateCredentialParamsSchema, privateCredentialInputSchema, backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, hideFirstRunCardSchema, networkSetupPreferenceSchema, settingsEmbeddingsSchema, localLlmSettingsSchema, imessageConfigSchema, signalConfigSchema, beeperSettingsSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, instanceFeatureSettingsSchema, instanceFeatureIdSchema, instanceFeatureUpdateSchema, instanceFeatureGroupSettingsSchema, instanceFeatureGroupIdSchema, instanceFeatureGroupUpdateSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, musicSettingsSchema, federationSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, layeredIntelligenceSettingsSchema, imageGenGrokSettingsSchema, imageGenAgySettingsSchema, renderDefaultsSettingsSchema, videoGenSettingsSchema, subscriptionCostsMapSchema, usageApiBilledInstanceIdsSchema, namedOrchestrationProfileSchema, orchestrationProfilesSettingsSchema, validateRequest } from '../lib/validation.js';+import { privateCredentialParamsSchema, privateCredentialInputSchema, backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, hideFirstRunCardSchema, networkSetupPreferenceSchema, settingsEmbeddingsSchema, localLlmSettingsSchema, imessageConfigSchema, signalConfigSchema, beeperSettingsSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, instanceFeatureSettingsSchema, instanceFeatureIdSchema, instanceFeatureUpdateSchema, instanceFeatureGroupSettingsSchema, instanceFeatureGroupIdSchema, instanceFeatureGroupUpdateSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, musicSettingsSchema, federationSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, layeredIntelligenceSettingsSchema, imageGenGrokSettingsSchema, imageGenAgySettingsSchema, renderDefaultsSettingsSchema, videoGenSettingsSchema, subscriptionCostsMapSchema, subscriptionPlanTiersMapSchema, usageApiBilledInstanceIdsSchema, namedOrchestrationProfileSchema, orchestrationProfilesSettingsSchema, validateRequest } from '../lib/validation.js';const router = Router();@@ -538,6 +539,12 @@ router.put('/', asyncHandler(async (req, res) => {if (req.body?.subscriptionCosts !== undefined) {validateRequest(subscriptionCostsMapSchema, req.body.subscriptionCosts);}+ // Plan tiers ride the same rails as the prices beside them, for the same+ // reason: an unvalidated key here would persist, read back as "no tier", and+ // be dropped by the next save from the Subscriptions page.+ if (req.body?.subscriptionPlanTiers !== undefined) {+ validateRequest(subscriptionPlanTiersMapSchema, req.body.subscriptionPlanTiers);+ }// Same schema PUT /api/usage/fleet-billing's store uses, so a restore dump// can't write an unbounded or non-string list through the generic endpoint.if (req.body?.usageApiBilledInstanceIds !== undefined) {@@ -555,16 +562,17 @@ router.put('/', asyncHandler(async (req, res) => {// would bypass the current-password proof the /api/auth/password routes// require. Secrets are write-only through their dedicated routes// (/api/auth/password, /api/github/secrets, etc.).- // subscriptionCosts and usageApiBilledInstanceIds are excluded from the- // generic shallow spread below and routed through their dedicated savers —- // the same merge PUT /api/usage/subscriptions and PUT /api/usage/fleet-billing- // use — so a restore dump can't persist an unvalidated slice, and a shallow- // `{ ...current, ...settingsPatch }` can't replace a map by dropping keys- // the incoming patch didn't mention.+ // subscriptionCosts, subscriptionPlanTiers and usageApiBilledInstanceIds are+ // excluded from the generic shallow spread below and routed through their+ // dedicated savers — the same merge PUT /api/usage/subscriptions and PUT+ // /api/usage/fleet-billing use — so a restore dump cannot persist an+ // unvalidated slice, and a shallow `{ ...current, ...settingsPatch }` cannot+ // replace a map by dropping keys the incoming patch did not mention.const {secrets: _ignoredSecrets,catalogUserTypes: _ignoredTypes,subscriptionCosts: subscriptionCostsPatch,+ subscriptionPlanTiers: subscriptionPlanTiersPatch,usageApiBilledInstanceIds: apiBilledPatch,...settingsPatch} = req.body || {};@@ -636,6 +644,10 @@ router.put('/', asyncHandler(async (req, res) => {const costs = await saveSubscriptionCosts(subscriptionCostsPatch, { actor: 'user' });merged = { ...merged, subscriptionCosts: costs };}+ if (subscriptionPlanTiersPatch !== undefined) {+ const tiers = await savePlanTiers(subscriptionPlanTiersPatch, { actor: 'user' });+ merged = { ...merged, subscriptionPlanTiers: tiers };+ }if (apiBilledPatch !== undefined) {const ids = await saveApiBilledInstanceIds(apiBilledPatch, { actor: 'user' });merged = { ...merged, usageApiBilledInstanceIds: ids };diff --git a/server/routes/usage.js b/server/routes/usage.jsindex 04138446fd..0dbae210f4 100644--- a/server/routes/usage.js+++ b/server/routes/usage.js@@ -4,8 +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, usageFleetBillingSchema } from '../lib/validation.js';-import { saveSubscriptionCosts, getSubscriptionSavings } from '../services/subscriptionCosts.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 { getFleetUsage } from '../services/peerUsage.js';import { getApiBilledInstanceIds, setInstanceUsesSubscriptions } from '../services/usageFleetBilling.js';import { resolveUsageRange } from '../lib/usageRange.js';@@ -54,11 +55,38 @@ router.get('/', asyncHandler(async (req, res) => {res.json({ ...summary, subscriptionSavings, fleet });}));-// PUT /api/usage/subscriptions - Merge plan prices. An omitted family keeps its-// stored price; one sent as null (or 0) is cleared.+// GET /api/usage/subscriptions - The Subscriptions page's own model: one row+// per manageable plan (enabled state, plan tier, monthly price, the provider+// records the toggle fans out to). The savings/spend figures for those rows+// come from GET /api/usage; the quota meters from GET /api/usage/providers.+router.get('/subscriptions', asyncHandler(async (req, res) => {+ res.json(await getSubscriptionOverview());+}));++// 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.router.put('/subscriptions', asyncHandler(async (req, res) => {- const { costs } = validateRequest(subscriptionCostsSchema, req.body);- res.json({ costs: await saveSubscriptionCosts(costs, { actor: 'user' }) });+ 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 });+}));++// PUT /api/usage/subscriptions/enabled - Switch one subscription on or off by+// flipping `enabled` across every provider record in that family — PortOS-side+// enablement only. It never reaches the vendor's billing system: nothing here+// purchases, cancels or changes a plan at Anthropic, OpenAI, Google or xAI.+//+// 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.+router.put('/subscriptions/enabled', asyncHandler(async (req, res) => {+ const { family, enabled } = validateRequest(subscriptionEnabledSchema, req.body);+ res.json(await setSubscriptionEnabled(family, enabled));}));// PUT /api/usage/fleet-billing - Mark one federated instance as paying APIdiff --git a/server/routes/usage.test.js b/server/routes/usage.test.jsindex 1bf4060d4f..eeff403fe9 100644--- a/server/routes/usage.test.js+++ b/server/routes/usage.test.js@@ -24,9 +24,17 @@ 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 () => ({})),+ savePlanTiers: vi.fn(async (tiers) => tiers),+ setSubscriptionEnabled: vi.fn(async (family, enabled) => ({ family, enabled, applied: true, changed: [] })),+}));+vi.mock('../services/providers.js', () => ({// getAllProviders returns the wrapped { activeProvider, providers } shape —// the route must unwrap `.providers` before passing to getUsageSummary.@@ -50,7 +58,8 @@ 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 { getSubscriptionSavings, saveSubscriptionCosts, getSubscriptionCosts } 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 usageRoutes from './usage.js';@@ -229,6 +238,78 @@ describe('usage routes', () => {expect(res.status).toBe(400);});+ it('PUT /api/usage/subscriptions saves a tier patch without disturbing the stored prices', async () => {+ const res = await request(buildApp())+ .put('/api/usage/subscriptions')+ .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.+ expect(saveSubscriptionCosts).not.toHaveBeenCalled();+ expect(getSubscriptionCosts).toHaveBeenCalled();+ expect(res.body).toEqual({ costs: { claude: 100 }, tiers: { claude: 'Max 20x' } });+ });++ it('PUT /api/usage/subscriptions saves both slices in one call', async () => {+ const res = await request(buildApp())+ .put('/api/usage/subscriptions')+ .send({ costs: { claude: 200 }, tiers: { claude: null } });+ expect(res.status).toBe(200);+ expect(saveSubscriptionCosts).toHaveBeenCalledWith({ claude: 200 }, { actor: 'user' });+ expect(savePlanTiers).toHaveBeenCalledWith({ claude: null }, { actor: 'user' });+ });++ it('PUT /api/usage/subscriptions rejects an over-long plan tier', async () => {+ const res = await request(buildApp())+ .put('/api/usage/subscriptions')+ .send({ tiers: { claude: 'x'.repeat(61) } });+ expect(res.status).toBe(400);+ expect(savePlanTiers).not.toHaveBeenCalled();+ });++ it('PUT /api/usage/subscriptions rejects an unknown family key in the tier map', async () => {+ const res = await request(buildApp())+ .put('/api/usage/subscriptions')+ .send({ tiers: { 'not-a-family': 'Pro' } });+ expect(res.status).toBe(400);+ expect(savePlanTiers).not.toHaveBeenCalled();+ });++ 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' }]);+ });++ it('PUT /api/usage/subscriptions/enabled toggles one subscription', async () => {+ setSubscriptionEnabled.mockResolvedValue({ family: 'codex', enabled: false, applied: true, changed: ['codex-cli'] });+ const res = await request(buildApp())+ .put('/api/usage/subscriptions/enabled')+ .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'] });+ });++ // The handler fans the flag across every provider record the family owns, so+ // an unrecognized id must be refused at the edge rather than silently no-op.+ it('PUT /api/usage/subscriptions/enabled rejects an unknown family', async () => {+ const res = await request(buildApp())+ .put('/api/usage/subscriptions/enabled')+ .send({ family: 'not-a-family', enabled: true });+ expect(res.status).toBe(400);+ 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/subscriptions.js b/server/services/subscriptions.jsnew file mode 100644index 0000000000..3b011814e6--- /dev/null+++ b/server/services/subscriptions.js@@ -0,0 +1,148 @@+import { getSettings, updateSettingsWith } from './settings.js';+import { getAllProviders, updateProvider } from './providers.js';+import { getSubscriptionCosts } 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';++/**+ * The subscription plans this install pays for: which ones are switched on,+ * which tier each is, and what each costs.+ *+ * PortOS-side METADATA and tracking only. Toggling a plan here flips the+ * `enabled` flag on that family's provider records — the same flag+ * `resolveEnabledFamilies` reads — so the install stops dispatching work to it.+ * It never reaches a vendor's billing system: nothing here purchases, cancels,+ * upgrades or downgrades anything at Anthropic, OpenAI, Google or xAI.+ *+ * 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.+ */++const SETTINGS_KEY = 'subscriptionPlanTiers';++/** Stored plan tiers, `{ [family]: label }`. */+export async function getPlanTiers() {+ const settings = await getSettings();+ return normalizePlanTiers(settings?.[SETTINGS_KEY]);+}++/**+ * 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.+ */+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);+ return normalizePlanTiers(next?.[SETTINGS_KEY]);+}++/**+ * Pure: the provider records that belong to each family, keyed by family id.+ *+ * `familyForProvider` already excludes local-runtime wrappers (an Ollama-backed+ * `claude-*` provider has no subscription to meter), so a row here only ever+ * holds providers whose enablement really is the plan's enablement.+ */+export function groupProvidersByFamily(providers) {+ const byFamily = new Map();+ for (const provider of providers || []) {+ const family = familyForProvider(provider);+ if (!family) continue;+ if (!byFamily.has(family)) byFamily.set(family, []);+ byFamily.get(family).push(provider);+ }+ return byFamily;+}++/** The trimmed provider projection a row carries — never the full config. */+const providerSummary = (provider) => ({+ id: provider.id,+ name: provider.name || provider.id,+ enabled: provider.enabled === true,+});++/**+ * Pure: one row per manageable subscription — every family with at least one+ * provider configured, 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.+ *+ * `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.+ */+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),+ }));+}++/** The whole Subscriptions page model: rows plus the raw stored maps. */+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 };+}++/**+ * Switch a whole subscription on or off by flipping `enabled` on every provider+ * record in that family.+ *+ * Writes are SEQUENTIAL, not `Promise.all`: every `updateProvider` is a+ * read-merge-write of the same providers.json, so firing them concurrently+ * would let the last write win and silently drop its siblings' changes.+ *+ * A family with no providers configured is reported as `applied: false` rather+ * than treated as an error — the row exists because the plan is priced, and+ * 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 changed = [];+ for (const provider of members) {+ if ((provider.enabled === true) === enabled) continue;+ await updateProvider(provider.id, { enabled });+ changed.push(provider.id);+ }+ return {+ family,+ enabled: members.length ? enabled : false,+ applied: members.length > 0,+ changed,+ };+}diff --git a/server/services/subscriptions.test.js b/server/services/subscriptions.test.jsnew file mode 100644index 0000000000..fba373773b--- /dev/null+++ b/server/services/subscriptions.test.js@@ -0,0 +1,180 @@+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);+ }),+}));++// The provider store is the thing the enable toggle writes through. Standing it+// in keeps providers.json (and the toolkit graph behind it) out of the suite+// while still proving the fan-out lands on the right records.+let providerRecords = [];+const updateProvider = vi.fn(async (id, patch) => {+ providerRecords = providerRecords.map((p) => (p.id === id ? { ...p, ...patch } : p));+ return providerRecords.find((p) => p.id === id);+});+vi.mock('./providers.js', () => ({+ getAllProviders: vi.fn(async () => ({ providers: structuredClone(providerRecords) })),+ updateProvider: (...args) => updateProvider(...args),+}));++// subscriptionCosts pulls providerUsage's PTY-scrape graph in transitively.+// Only the stored-price read is needed here.+vi.mock('./subscriptionCosts.js', () => ({+ getSubscriptionCosts: vi.fn(async () => structuredClone(stored.subscriptionCosts || {})),+}));++import {+ getPlanTiers,+ savePlanTiers,+ groupProvidersByFamily,+ buildSubscriptionFamilies,+ getSubscriptionOverview,+ setSubscriptionEnabled,+} from './subscriptions.js';++// Real provider-config shapes, so the matchers in lib/providerFamilies.js are+// what these tests exercise rather than a stand-in that can drift from them.+const claudeCli = { id: 'claude-code', name: 'Claude Code', enabled: true, type: 'cli', command: 'claude' };+const claudeAlt = { id: 'claude-code-alt', name: 'Claude (alt)', enabled: false, type: 'cli', command: 'claude' };+const codexCli = { id: 'codex-cli', name: 'Codex', enabled: false, type: 'cli', command: 'codex' };+const claudeOnOllama = { id: 'claude-ollama', name: 'Local', enabled: true, type: 'cli', command: 'claude', ollamaBacked: true };++beforeEach(() => {+ stored = {};+ providerRecords = [];+ updateProvider.mockClear();+});++describe('plan tier persistence', () => {+ it('merges a patch, keeping omitted families and clearing the ones sent empty', async () => {+ await savePlanTiers({ claude: 'Max 20x', codex: 'Pro' });+ expect(await getPlanTiers()).toEqual({ claude: 'Max 20x', codex: 'Pro' });++ // Omitted keeps, '' clears — the same absent-vs-intentionally-empty split+ // the price map holds, so an editor submitting one row can still remove it.+ await savePlanTiers({ codex: '' });+ expect(await getPlanTiers()).toEqual({ claude: 'Max 20x' });++ await savePlanTiers({ claude: null });+ expect(await getPlanTiers()).toEqual({});+ });++ it('trims and caps a stored tier, and never stores a whitespace-only label', async () => {+ await savePlanTiers({ claude: ' Max 5x ', codex: ' ', agy: 'x'.repeat(200) });+ const tiers = await getPlanTiers();+ expect(tiers.claude).toBe('Max 5x');+ expect(tiers).not.toHaveProperty('codex');+ expect(tiers.agy).toHaveLength(60);+ });+});++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] });+ expect(claude).toMatchObject({ family: 'claude', enabled: true });+ expect(claude.providers).toEqual([+ { id: 'claude-code', name: 'Claude Code', enabled: true },+ { id: 'claude-code-alt', name: 'Claude (alt)', enabled: false },+ ]);+ });++ it('keeps a priced family with every provider disabled — its price must stay visible', () => {+ const rows = buildSubscriptionFamilies({ providers: [codexCli], costs: { codex: 20 } });+ expect(rows).toHaveLength(1);+ expect(rows[0]).toMatchObject({ family: 'codex', enabled: false, monthlyCost: 20 });+ });++ it('keeps a priced or tiered family that has no providers at all', () => {+ const rows = buildSubscriptionFamilies({ providers: [], costs: { grok: 30 }, tiers: { agy: 'Pro' } });+ expect(rows.map((r) => r.family).sort()).toEqual(['agy', 'grok']);+ expect(rows.find((r) => r.family === 'grok')).toMatchObject({ monthlyCost: 30, providers: [] });+ expect(rows.find((r) => r.family === 'agy')).toMatchObject({ planTier: 'Pro', providers: [] });+ });++ it('omits a family that is neither configured nor priced', () => {+ const rows = buildSubscriptionFamilies({ providers: [claudeCli] });+ expect(rows.map((r) => r.family)).toEqual(['claude']);+ });++ it('still rows a stored family id the registry no longer knows, so its price is clearable', () => {+ const rows = buildSubscriptionFamilies({ providers: [], costs: { retired: 12 } });+ expect(rows).toEqual([expect.objectContaining({ family: 'retired', label: 'retired', monthlyCost: 12 })]);+ });+});++describe('getSubscriptionOverview', () => {+ it('joins provider membership, stored prices and stored tiers into one row set', async () => {+ 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 }),+ ]);+ });+});++describe('setSubscriptionEnabled', () => {+ it('flips every provider in the family and leaves the others alone', async () => {+ providerRecords = [claudeCli, claudeAlt, codexCli];+ const result = await setSubscriptionEnabled('claude', false);+ expect(result).toMatchObject({ family: 'claude', enabled: false, applied: true });+ // Only the one that actually had to change was written.+ expect(result.changed).toEqual(['claude-code']);+ expect(updateProvider).toHaveBeenCalledTimes(1);+ expect(updateProvider).toHaveBeenCalledWith('claude-code', { enabled: false });+ expect(providerRecords.find((p) => p.id === 'codex-cli').enabled).toBe(false);+ });++ it('enables every disabled provider in the family', async () => {+ providerRecords = [claudeCli, claudeAlt];+ const result = await setSubscriptionEnabled('claude', true);+ expect(result.changed).toEqual(['claude-code-alt']);+ expect(providerRecords.every((p) => p.enabled)).toBe(true);+ });++ it('never touches a local-runtime wrapper that happens to launch the same binary', async () => {+ providerRecords = [claudeCli, claudeOnOllama];+ await setSubscriptionEnabled('claude', false);+ expect(updateProvider).toHaveBeenCalledTimes(1);+ expect(updateProvider).toHaveBeenCalledWith('claude-code', { enabled: false });+ });++ it('keeps a stored price when the plan is switched off', async () => {+ providerRecords = [codexCli, { ...codexCli, id: 'codex-2', enabled: true }];+ 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 }),+ ]);+ });++ it('reports applied:false for a priced family with nothing local to toggle', async () => {+ providerRecords = [];+ const result = await setSubscriptionEnabled('grok', true);+ expect(result).toEqual({ family: 'grok', enabled: false, applied: false, changed: [] });+ expect(updateProvider).not.toHaveBeenCalled();+ });+});