diff --git a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx index 218a7f21feb1..f0aee5101902 100644 --- a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx +++ b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx @@ -13,6 +13,7 @@ import { formatResetsIn, paceRemainingPercent, remainingPercent, + splitLimitPresentations, type LimitAccount, type LimitPoolWindow, } from "@t3tools/shared/usageLimits"; @@ -417,16 +418,19 @@ export function UsageLimitsSection({ selectedEnvironmentIds === null ? presentations : new Map([...presentations].filter(([id]) => selectedEnvironmentIds.has(id))); - const pools = collectLimitPools(collectLimitAccounts(selected), now); - const notices = collectLimitNotices(selected); - const externalLinks = collectExternalUsageLinks(selected); + // A disconnected machine's last config would repeat its last errors; it is one offline line. + const { live, offline } = splitLimitPresentations(selected); + const pools = collectLimitPools(collectLimitAccounts(live), now); + const notices = collectLimitNotices(live); + const externalLinks = collectExternalUsageLinks(live); const colors = useProviderColors(); return ( {pools.length === 0 && notices.length === 0 && failedLabels.length === 0 && - externalLinks.length === 0 ? ( + externalLinks.length === 0 && + offline.length === 0 ? ( {selected.size === 0 ? "Select an environment to see limits." @@ -508,6 +512,14 @@ export function UsageLimitsSection({ ) : null} + {offline.map((environment) => ( + + {environment.label}:{" "} + {environment.since + ? `offline since ${new Date(environment.since).toLocaleString()}` + : "offline"} + + ))} ); } diff --git a/apps/mobile/src/features/usage/UsageLimitsSection.tsx b/apps/mobile/src/features/usage/UsageLimitsSection.tsx index be4bf0c929d1..b79127c96da4 100644 --- a/apps/mobile/src/features/usage/UsageLimitsSection.tsx +++ b/apps/mobile/src/features/usage/UsageLimitsSection.tsx @@ -332,8 +332,13 @@ export function useRefreshLimits( const failedIds = new Set( useAtomValue(limitsRefreshFailuresAtom(environmentIdsKey(selected.map(([id]) => id)))), ); + // A failure is only reset by a later refresh, which runs only while connected; + // a dropped machine shows its offline line instead. const failedLabels = selected - .filter(([environmentId]) => failedIds.has(environmentId)) + .filter( + ([environmentId, presentation]) => + failedIds.has(environmentId) && presentation.connection.phase === "connected", + ) .map(([, presentation]) => presentation.entry.target.label); const refresh = () => diff --git a/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx b/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx index ab114fbbd6f2..3c2cfcc40ed8 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx @@ -63,3 +63,95 @@ describe("UsageLimitsPooled ChatGPT usage card", () => { .toBeVisible(); }); }); + +function routedCodex(): ServerProvider { + return { + ...managedChatGpt("magpie_codex", "Magpie Codex"), + usageLimits: { + checkedAt, + windows: [], + unavailable: { + reason: "unsupported", + message: "Not applicable: this instance routes through a custom model provider.", + }, + }, + }; +} + +describe("UsageLimitsPooled quiet states", () => { + it("shows a stopped machine as one offline line, not its last errors", async () => { + const failing: ServerProvider = { + ...managedChatGpt("codex", "Codex"), + usageLimits: { + checkedAt, + windows: [], + unavailable: { reason: "probeFailed", message: "Codex could not read usage." }, + }, + }; + const presentations = new Map([ + [ + EnvironmentId.make("crown"), + { + entry: { target: { label: "Crown Rain Gutters" } }, + connection: { phase: "reconnecting" }, + serverConfig: { providers: [failing] }, + }, + ], + ]); + await using screen = await render( + , + ); + + await expect.element(screen.getByText(/offline since/)).toBeVisible(); + expect(screen.container.textContent).not.toContain("could not read usage"); + }); + + it("folds not-applicable instances into one closed summary across machines", async () => { + const presentations = new Map( + ["primary-r720", "primary-asus", "primary-mac-laptop"].map((label) => [ + EnvironmentId.make(label), + { entry: { target: { label } }, serverConfig: { providers: [routedCodex()] } }, + ]), + ); + await using screen = await render( + , + ); + + const summary = screen.getByText("3 instances have no quota to read"); + await expect.element(summary).toBeVisible(); + const details = screen.container.querySelector("details"); + expect(details?.open).toBe(false); + await summary.click(); + await expect + .element(screen.getByText("(primary-r720, primary-asus, primary-mac-laptop)")) + .toBeVisible(); + expect(screen.container.querySelectorAll("details li")).toHaveLength(1); + }); + + it("names the machine when only one of several in view has the instance", async () => { + const presentations = new Map([ + [ + EnvironmentId.make("primary-r720"), + { + entry: { target: { label: "primary-r720" } }, + serverConfig: { providers: [routedCodex()] }, + }, + ], + [ + EnvironmentId.make("primary-asus"), + { + entry: { target: { label: "primary-asus" } }, + serverConfig: { providers: [managedChatGpt("codex", "Codex")] }, + }, + ], + ]); + await using screen = await render( + , + ); + + const summary = screen.getByText("1 instance has no quota to read"); + await expect.element(summary).toBeVisible(); + await summary.click(); + await expect.element(screen.getByText("(primary-r720)")).toBeVisible(); + }); +}); diff --git a/apps/web/src/components/usage/UsageLimitsPooled.tsx b/apps/web/src/components/usage/UsageLimitsPooled.tsx index 33cb123307cf..a436eedf1cda 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.tsx @@ -6,6 +6,9 @@ import { collectLimitNotices, collectLimitOwnerGroups, collectNotApplicable, + groupNotApplicable, + type OfflineLimitEnvironment, + splitLimitPresentations, UNASSIGNED_OWNER, cursorUsageWindowDetails, displayLimitWindows, @@ -21,7 +24,14 @@ import { } from "@t3tools/shared/usageLimits"; import type { Popover as PopoverPrimitive } from "@base-ui/react/popover"; import { normalizeProviderAccentColor } from "@t3tools/client-runtime/state/provider-instance-display"; -import { AlertTriangleIcon, CircleSlashIcon, ExternalLinkIcon, TicketIcon } from "lucide-react"; +import { + AlertTriangleIcon, + ChevronRightIcon, + CircleSlashIcon, + CloudOffIcon, + ExternalLinkIcon, + TicketIcon, +} from "lucide-react"; import { createContext, Fragment, @@ -36,7 +46,7 @@ import { import { ensureLocalApi } from "../../localApi"; import { usePrimarySettings } from "../../hooks/useSettings"; import { cn } from "../../lib/utils"; -import { formatUpcomingTimestamp } from "../../timestampFormat"; +import { formatDayAwareTimestamp, formatUpcomingTimestamp } from "../../timestampFormat"; import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon"; import { providerClients } from "../settings/providerDriverMeta"; import { RedactedSensitiveText } from "../settings/RedactedSensitiveText"; @@ -633,12 +643,13 @@ function PoolSection({ } export function UsageLimitsPooled({ - presentations, + presentations: selected, now, }: { readonly presentations: Parameters[0]; readonly now: number; }) { + const { live: presentations, offline } = splitLimitPresentations(selected); const [segmentPopover] = useState(() => PopoverCreateHandle()); const segmentPopoverActions = useRef(null); const groups = collectLimitOwnerGroups( @@ -657,7 +668,8 @@ export function UsageLimitsPooled({ {pools.length === 0 && notices.length === 0 && externalLinks.length === 0 && - notApplicable.length === 0 ? ( + notApplicable.length === 0 && + offline.length === 0 ? (

No provider on the selected environments reports subscription limits.

@@ -729,33 +741,76 @@ export function UsageLimitsPooled({ ))} - + + ); } -/** Usage that cannot be read on this setup, with why; informational, not a warning. */ -function NotApplicableList({ +/** A machine that stopped answering: one quiet line, not its last errors. */ +function OfflineEnvironments({ + environments, + now, +}: { + readonly environments: readonly OfflineLimitEnvironment[]; + readonly now: number; +}) { + const timestampFormat = usePrimarySettings((settings) => settings.timestampFormat); + if (environments.length === 0) return null; + return ( +
    + {environments.map((environment) => ( +
  • + + + {environment.label}:{" "} + {environment.since + ? `offline since ${formatDayAwareTimestamp(environment.since, timestampFormat, now)}` + : "offline"} + +
  • + ))} +
+ ); +} + +/** + * Usage that cannot be read on this setup, with why; informational, not a + * warning, so it stays closed. Each instance and reason is one row naming its + * machines. + */ +function NotApplicableSummary({ entries, + machineCount, }: { readonly entries: ReturnType; + readonly machineCount: number; }) { if (entries.length === 0) return null; + const groups = groupNotApplicable(entries); + // With one machine in view, naming it on every row is noise. + const nameMachines = machineCount > 1; return ( -
-

- - Not applicable -

-
    - {entries.map((entry) => ( -
  • - {entry.subject}:{" "} - {entry.reason.replace(/^Not applicable:\s*/, "")} +
    + + + + {entries.length === 1 + ? "1 instance has no quota to read" + : `${entries.length} instances have no quota to read`} + +
      + {groups.map((group) => ( +
    • + {group.subject}: {group.reason} + {nameMachines ? ({group.environments.join(", ")}) : null}
    • ))}
    -
+ ); } diff --git a/packages/shared/src/usageLimits.test.ts b/packages/shared/src/usageLimits.test.ts index e94d4c33911a..6e21b53ff83e 100644 --- a/packages/shared/src/usageLimits.test.ts +++ b/packages/shared/src/usageLimits.test.ts @@ -21,6 +21,8 @@ import { collectLimitNotices, collectLimitOwnerGroups, collectNotApplicable, + groupNotApplicable, + splitLimitPresentations, collectLimitPools, elapsedShare, exhaustedUsageWindow, @@ -1946,12 +1948,108 @@ describe("owners and not-applicable usage", () => { expect(groups.map((group) => group.owner)).toEqual(["Unassigned"]); }); - it("lists not-applicable usage apart from failures", () => { + it("lists not-applicable usage apart from failures, and a billing refusal as a notice", () => { const view = presentations(); expect(collectNotApplicable(view)).toEqual([ - { subject: "Magpie Codex", reason: "Not applicable: gateway reports it." }, - { subject: "Magpie · owner.a@example.com · Team", reason: "Payment Required." }, + { environment: "Crown", subject: "Magpie Codex", reason: "gateway reports it." }, ]); - expect(collectLimitNotices(view)).toEqual(["Magpie · k: Upstream timed out."]); + expect(collectLimitNotices(view)).toEqual([ + "Magpie · owner.a@example.com · Team: the vendor says payment is required, so this subscription's billing needs attention.", + "Magpie · k: Upstream timed out.", + ]); + }); + + it("names a billing refusal once however many machines see it", () => { + const view = new Map([ + [EnvironmentId.make("env-a"), presentations().get(EnvironmentId.make("env-a"))!], + [ + EnvironmentId.make("env-b"), + { + ...presentations().get(EnvironmentId.make("env-a"))!, + entry: { target: { label: "Desk" } }, + }, + ], + ]); + const billing = collectLimitNotices(view).filter((notice) => notice.includes("payment")); + expect(billing).toHaveLength(1); + }); + + it("groups one instance and reason across machines into one row", () => { + const base = presentations().get(EnvironmentId.make("env-a"))!; + const view = new Map( + ["r720", "asus", "laptop"].map((label) => [ + EnvironmentId.make(label), + { ...base, entry: { target: { label } } }, + ]), + ); + const entries = collectNotApplicable(view); + expect(entries).toHaveLength(3); + expect(groupNotApplicable(entries)).toEqual([ + { + subject: "Magpie Codex", + reason: "gateway reports it.", + environments: ["r720", "asus", "laptop"], + }, + ]); + }); +}); + +describe("splitLimitPresentations", () => { + const checkedAt = "2026-11-18T22:00:00.000Z"; + const later = "2026-11-18T22:05:00.000Z"; + const failing = provider({ + checkedAt, + usageLimits: { + checkedAt: later, + windows: [], + unavailable: { reason: "probeFailed", message: "Codex could not read usage." }, + }, + }); + const config = { providers: [failing] }; + const view = new Map([ + [ + EnvironmentId.make("live"), + { + entry: { target: { label: "Desk" } }, + connection: { phase: "connected" }, + serverConfig: config, + }, + ], + [ + EnvironmentId.make("stopped"), + { + entry: { target: { label: "Crown Rain Gutters" } }, + connection: { phase: "reconnecting" }, + serverConfig: config, + }, + ], + [ + EnvironmentId.make("starting"), + { + entry: { target: { label: "Laptop" } }, + connection: { phase: "connecting" }, + serverConfig: null, + }, + ], + [ + EnvironmentId.make("never"), + { entry: { target: { label: "Air" } }, connection: { phase: "error" }, serverConfig: null }, + ], + [EnvironmentId.make("implicit"), { entry: { target: { label: "Box" } }, serverConfig: config }], + ]); + + it("keeps only connected environments and turns the rest into offline lines", () => { + const { live, offline } = splitLimitPresentations(view); + expect([...live.keys()]).toEqual(["live", "implicit"]); + expect(offline).toEqual([ + { environmentId: "stopped", label: "Crown Rain Gutters", since: later }, + { environmentId: "never", label: "Air", since: null }, + ]); + }); + + it("drops a stopped machine's last errors from the notices", () => { + const { live } = splitLimitPresentations(view); + expect(collectLimitNotices(live).some((notice) => notice.includes("Crown"))).toBe(false); + expect(collectLimitNotices(view).some((notice) => notice.includes("Crown"))).toBe(true); }); }); diff --git a/packages/shared/src/usageLimits.ts b/packages/shared/src/usageLimits.ts index 0c8ddf78ff40..07121759317d 100644 --- a/packages/shared/src/usageLimits.ts +++ b/packages/shared/src/usageLimits.ts @@ -171,19 +171,73 @@ function providersWithLimits(providers: readonly ServerProvider[]): readonly Ser ); } -export type LimitPresentations = ReadonlyMap< - EnvironmentId, - { - readonly entry: { readonly target: { readonly label: string } }; - readonly serverConfig: { - readonly providers: readonly ServerProvider[]; - readonly usageLimitSources?: UsageLimitSourceSnapshots | undefined; - readonly settings?: - | { readonly usageAccountOwners?: Readonly> | undefined } - | undefined; - } | null; +export interface LimitServerConfig { + readonly providers: readonly ServerProvider[]; + readonly usageLimitSources?: UsageLimitSourceSnapshots | undefined; + readonly settings?: + | { readonly usageAccountOwners?: Readonly> | undefined } + | undefined; +} + +export interface LimitPresentation { + readonly entry: { readonly target: { readonly label: string } }; + /** Absent means connected: callers that only hold live configs need not say so. */ + readonly connection?: { readonly phase: string } | undefined; + readonly serverConfig: LimitServerConfig | null; +} + +export type LimitPresentations = ReadonlyMap; + +export interface OfflineLimitEnvironment { + readonly environmentId: EnvironmentId; + readonly label: string; + /** The newest check in its last config: about when it stopped answering. */ + readonly since: string | null; +} + +function latestCheck(config: LimitServerConfig): string | null { + const checks = [ + ...config.providers.flatMap((provider) => [ + provider.checkedAt, + provider.usageLimits?.checkedAt, + ]), + ...(config.usageLimitSources ?? []).map((source) => source.checkedAt), + ]; + let latest: string | null = null; + for (const checkedAt of checks) { + if (!checkedAt || !Number.isFinite(Date.parse(checkedAt))) continue; + if (latest === null || Date.parse(checkedAt) > Date.parse(latest)) latest = checkedAt; } ->; + return latest; +} + +/** + * Only connected environments count. A disconnected one keeps its last config, + * and with it the errors it last reported; a stopped machine would repeat them + * forever. It becomes one offline line instead. One still on its first connect + * has nothing to say yet, so it is left out. + */ +export function splitLimitPresentations(presentations: LimitPresentations): { + readonly live: LimitPresentations; + readonly offline: readonly OfflineLimitEnvironment[]; +} { + const live = new Map(); + const offline: OfflineLimitEnvironment[] = []; + for (const [environmentId, presentation] of presentations) { + const phase = presentation.connection?.phase ?? "connected"; + if (phase === "connected") { + live.set(environmentId, presentation); + continue; + } + if (phase === "connecting") continue; + offline.push({ + environmentId, + label: presentation.entry.target.label, + since: presentation.serverConfig ? latestCheck(presentation.serverConfig) : null, + }); + } + return { live, offline }; +} export function collectExternalUsageLinks(presentations: LimitPresentations) { const links = new Map< @@ -448,7 +502,15 @@ export function collectLimitNotices(presentations: LimitPresentations): readonly notices.add(`${label(environmentLabel, source.label)}: No accounts reported.`); } for (const account of source.accounts) { - if (account.usageLimits.unavailable?.reason !== "probeFailed") continue; + const unavailable = account.usageLimits.unavailable; + if (source.kind === "magpie" && isBillingRefusal(unavailable)) { + // A real billing state, not "no quota here"; every machine sees the same account, so once. + notices.add( + `${source.label} · ${sourceAccountName(account)}: the vendor says payment is required, so this subscription's billing needs attention.`, + ); + continue; + } + if (unavailable?.reason !== "probeFailed") continue; const subject = `${source.label} · ${sourceAccountName(account)}`; notices.add( `${label(environmentLabel, subject)}: ${limitsNotice(account.usageLimits) ?? ""}`, @@ -464,19 +526,40 @@ function sourceAccountName(account: { readonly id: string; readonly email?: stri return account.email ?? account.id.replace(/^[\w-]+:/, ""); } +/** "Payment Required" from a vendor: a lapsed or unpaid subscription, which needs a person. */ +function isBillingRefusal( + unavailable: ServerProviderUsageLimits["unavailable"] | undefined, +): boolean { + return ( + unavailable?.reason === "unsupported" && /payment required/i.test(unavailable.message ?? "") + ); +} + +export interface NotApplicableEntry { + readonly environment: string; + readonly subject: string; + /** Why, without the "Not applicable:" lead-in. */ + readonly reason: string; +} + /** * Usage that cannot be read on its current setup (a key with no subscription, * an instance whose gateway reports for it), so a missing bar reads as "not - * applicable". Only entries that say why are listed. + * applicable". Only entries that say why are listed, one per environment. */ export function collectNotApplicable( presentations: LimitPresentations, -): ReadonlyArray<{ readonly subject: string; readonly reason: string }> { - const label = (environmentLabel: string, subject: string) => - presentations.size > 1 ? `${environmentLabel} · ${subject}` : subject; - const entries = new Map(); +): readonly NotApplicableEntry[] { + const entries = new Map(); + const add = (environment: string, subject: string, reason: string) => { + entries.set(`${environment}\u0000${subject}`, { + environment, + subject, + reason: reason.replace(/^Not applicable:\s*/, ""), + }); + }; for (const presentation of presentations.values()) { - const environmentLabel = presentation.entry.target.label; + const environment = presentation.entry.target.label; for (const provider of providersWithLimits(presentation.serverConfig?.providers ?? [])) { // Only an explicit "Not applicable:" reason: other unsupported messages // (a sign-in prompt, a sharing notice shown as a link) ask for action. @@ -488,23 +571,54 @@ export function collectNotApplicable( ) { continue; } - const name = provider.displayName?.trim() || String(provider.driver); - entries.set(label(environmentLabel, name), unavailable.message); + add( + environment, + provider.displayName?.trim() || String(provider.driver), + unavailable.message, + ); } for (const source of presentation.serverConfig?.usageLimitSources ?? []) { // Magpie maps only standing vendor refusals to unsupported. if (source.kind !== "magpie") continue; for (const account of source.accounts) { const unavailable = account.usageLimits.unavailable; - if (unavailable?.reason !== "unsupported") continue; - entries.set( - label(environmentLabel, `${source.label} · ${sourceAccountName(account)}`), + if (unavailable?.reason !== "unsupported" || isBillingRefusal(unavailable)) continue; + add( + environment, + `${source.label} · ${sourceAccountName(account)}`, unavailable.message ?? "This account has no subscription limits.", ); } } } - return [...entries].map(([subject, reason]) => ({ subject, reason })); + return [...entries.values()]; +} + +/** + * The same instance and reason on several machines is one row naming the + * machines, so the list grows with setups, not with the fleet. + */ +export function groupNotApplicable(entries: readonly NotApplicableEntry[]): ReadonlyArray<{ + readonly subject: string; + readonly reason: string; + readonly environments: readonly string[]; +}> { + const groups = new Map(); + for (const entry of entries) { + const key = `${entry.subject}\u0000${entry.reason}`; + const group = groups.get(key); + if (group) { + if (!group.environments.includes(entry.environment)) + group.environments.push(entry.environment); + } else { + groups.set(key, { + subject: entry.subject, + reason: entry.reason, + environments: [entry.environment], + }); + } + } + return [...groups.values()]; } export const UNASSIGNED_OWNER = "Unassigned";