Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions apps/mobile/src/features/usage/UsageLimitsPooled.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
formatResetsIn,
paceRemainingPercent,
remainingPercent,
splitLimitPresentations,
type LimitAccount,
type LimitPoolWindow,
} from "@t3tools/shared/usageLimits";
Expand Down Expand Up @@ -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 (
<View className="gap-6">
{pools.length === 0 &&
notices.length === 0 &&
failedLabels.length === 0 &&
externalLinks.length === 0 ? (
externalLinks.length === 0 &&
offline.length === 0 ? (
<Text className="py-12 text-center text-base text-foreground-muted">
{selected.size === 0
? "Select an environment to see limits."
Expand Down Expand Up @@ -508,6 +512,14 @@ export function UsageLimitsSection({
</View>
</View>
) : null}
{offline.map((environment) => (
<Text key={environment.environmentId} className="px-1 text-xs text-foreground-muted">
{environment.label}:{" "}
{environment.since
? `offline since ${new Date(environment.since).toLocaleString()}`
: "offline"}
</Text>
))}
</View>
);
}
Expand Down
7 changes: 6 additions & 1 deletion apps/mobile/src/features/usage/UsageLimitsSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 = () =>
Expand Down
92 changes: 92 additions & 0 deletions apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(
<UsageLimitsPooled presentations={presentations} now={Date.parse(checkedAt)} />,
);

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(
<UsageLimitsPooled presentations={presentations} now={Date.parse(checkedAt)} />,
);

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(
<UsageLimitsPooled presentations={presentations} now={Date.parse(checkedAt)} />,
);

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();
});
});
91 changes: 73 additions & 18 deletions apps/web/src/components/usage/UsageLimitsPooled.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ import {
collectLimitNotices,
collectLimitOwnerGroups,
collectNotApplicable,
groupNotApplicable,
type OfflineLimitEnvironment,
splitLimitPresentations,
UNASSIGNED_OWNER,
cursorUsageWindowDetails,
displayLimitWindows,
Expand All @@ -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,
Expand All @@ -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";
Expand Down Expand Up @@ -633,12 +643,13 @@ function PoolSection({
}

export function UsageLimitsPooled({
presentations,
presentations: selected,
now,
}: {
readonly presentations: Parameters<typeof collectLimitAccounts>[0];
readonly now: number;
}) {
const { live: presentations, offline } = splitLimitPresentations(selected);
const [segmentPopover] = useState(() => PopoverCreateHandle<SegmentPayload>());
const segmentPopoverActions = useRef<PopoverPrimitive.Root.Actions | null>(null);
const groups = collectLimitOwnerGroups(
Expand All @@ -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 ? (
<p className="text-sm text-muted-foreground">
No provider on the selected environments reports subscription limits.
</p>
Expand Down Expand Up @@ -729,33 +741,76 @@ export function UsageLimitsPooled({
</section>
))}
<LimitNotices notices={notices} />
<NotApplicableList entries={notApplicable} />
<OfflineEnvironments environments={offline} now={now} />
<NotApplicableSummary entries={notApplicable} machineCount={presentations.size} />
</div>
);
}

/** 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 (
<ul className="flex flex-col gap-1 text-xs text-muted-foreground">
{environments.map((environment) => (
<li key={environment.environmentId} className="flex items-center gap-1.5 break-words">
<CloudOffIcon className="size-3.5 shrink-0" aria-hidden />
<span>
<span className="font-medium text-foreground">{environment.label}</span>:{" "}
{environment.since
? `offline since ${formatDayAwareTimestamp(environment.since, timestampFormat, now)}`
: "offline"}
</span>
</li>
))}
</ul>
);
}

/**
* 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<typeof collectNotApplicable>;
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 (
<section className="flex flex-col gap-2 text-xs text-muted-foreground">
<h2 className="flex items-center gap-1.5 text-sm font-medium text-foreground">
<CircleSlashIcon className="size-4 text-muted-foreground" aria-hidden />
Not applicable
</h2>
<ul className="flex flex-col gap-1">
{entries.map((entry) => (
<li key={entry.subject} className="break-words">
<span className="font-medium text-foreground">{entry.subject}:</span>{" "}
{entry.reason.replace(/^Not applicable:\s*/, "")}
<details className="group text-xs text-muted-foreground">
<summary className="flex w-fit cursor-pointer list-none items-center gap-1.5 rounded-sm outline-none select-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset [&::-webkit-details-marker]:hidden">
<ChevronRightIcon
className="size-3.5 shrink-0 transition-transform group-open:rotate-90"
aria-hidden
/>
<CircleSlashIcon className="size-3.5 shrink-0" aria-hidden />
{entries.length === 1
? "1 instance has no quota to read"
: `${entries.length} instances have no quota to read`}
</summary>
<ul className="mt-2 flex flex-col gap-1 ps-5">
{groups.map((group) => (
<li key={`${group.subject}:${group.reason}`} className="break-words">
<span className="font-medium text-foreground">{group.subject}:</span> {group.reason}
{nameMachines ? <span> ({group.environments.join(", ")})</span> : null}
</li>
))}
</ul>
</section>
</details>
);
}

Expand Down
Loading
Loading