Enable sidebar usage summary by default and move source toggles to a dedicated Sources list (#10491)

* feat(usage): enable sidebar usage summary by default and add dedicated Sources list

Show the sidebar Usage summary by default instead of requiring opt-in in
Appearance settings, while honoring explicit off preferences and continuing
to hide the row when no enabled source has pinned windows.

Let usage sources declare optional provider hints (`providers` on the
registration and `provider` on discovered accounts) so the daemon can mark
reports `defaultEnabled: false` when their hinted providers are neither
enabled nor installed, keeping usage sources decoupled from agent providers
while avoiding clutter from leftover credentials.

Move per-source show/hide controls out of individual card headers into a
dedicated `Sources` submenu inside Usage Settings (with tri-state
`cardVisibility` preferences migrating legacy `cardsOff`) so disabled
sources stay out of the main card list.

* fix(usage): resolve provider hints per report, refresh on forceRefresh, and clarify inactive copy

Resolve each usage report's provider activity hint in parallel with its
fetch and enforce a real timeout deadline in `isProviderActiveForUsage` so
a slow provider probe never holds back unrelated reports or hangs past the
deadline on non-abortable plugin RPCs.

Give the availability hint a 5-minute freshness TTL and re-probe when
`forceRefresh` is requested, retaining the fresher probe result across
subsequent normal reads until a newer snapshot or TTL expiry supersedes it.

Rename the default-off Sources sublabel from "Provider not installed" to
"Provider inactive" across all locales so it accurately covers both
disabled and unavailable providers.

* fix(usage): share provider availability reading across snapshot publishes and usage probes

Record both `ready` and `unavailable` global snapshot publications into
`usageActivityCache` so `isProviderActiveForUsage` reads one timestamped
availability cache instead of relying on `fetchedAt` (which unavailable
snapshot entries do not carry).

* fix(app): add MenuCheckboxItem so Usage Sources toggles expose checked state to screen readers

Introduce `MenuCheckboxItem` / `DropdownMenuCheckboxItem` backed by
`accessibilityRole="checkbox"` so toggleable menu rows expose their checked
state in Chromium's accessibility tree and native screen readers while
leaving existing `MenuItem` roles unchanged.

* fix(app): keep compact menu sheet rows in Tab order and activate on Space

Use `tabIndex={0}` for `MenuRow` in `sheet` presentation (leaving
popover roving arrow-key navigation at `tabIndex={-1}`) and handle Space
in web sheet rows since React Native Web only activates Space for
`role="button"`, not `menuitem` or `checkbox`.

* test(usage): include provider hint in claude-usage-source keychain and stores assertions
This commit is contained in:
Mohamed Boudra authored and GitHub committed 2026-11-22 16:43:11 +07:00
1 parent 9cb521dda2
commit 52377f595a
50 files changed
+1026 -215

No files matched your search

+112 -8
View File
@@ -34,6 +34,7 @@ import {
openUsageFromItem,
pinRow,
openUsageOptions,
openUsageSources,
closeUsageOptions,
pickUsageHost,
usageModalHost,
@@ -250,16 +251,15 @@ test.describe("usage modal", () => {
await expect(alphaHandle).toHaveCSS("opacity", "1");
await alphaHandle.blur();
// The off card collapses to its header, which still names the account.
await setUsageCardOn(page, "beta plan (work)", false);
const work = page.getByTestId("usage-report-beta:work");
await expect(work.getByText("12% used")).toHaveCount(0);
await expect(work.getByText("work", { exact: true })).toBeVisible();
// Turning a source off in the dedicated Sources list removes its card and sidebar summary.
await setUsageCardOn(page, "beta:work", false);
await expectUsageCardOrder(page, ["alpha:a", "beta:home"]);
await expect(page.getByTestId("usage-report-beta:work")).toHaveCount(0);
await expectPinnedUsage(page, ["31% Weekly", "20% Weekly"]);
const stopRecording = await recordUsageCardPositionsAfterRelease(page);
await dragUsageCardAbove(page, "beta:home", "alpha:a");
await expectUsageCardOrder(page, ["beta:home", "alpha:a", "beta:work"]);
await expectUsageCardOrder(page, ["beta:home", "alpha:a"]);
await expectPinnedUsage(page, ["20% Weekly", "31% Weekly"]);
// The cards are in their new slots from the first frame after the drop.
const framesAfterDrop = await stopRecording();
@@ -270,10 +270,114 @@ test.describe("usage modal", () => {
await page.reload();
await expectPinnedUsage(page, ["20% Weekly", "31% Weekly"]);
await openUsageFromItem(page);
await expectUsageCardOrder(page, ["beta:home", "alpha:a", "beta:work"]);
await expect(page.getByTestId("usage-report-beta:work").getByText("12% used")).toHaveCount(0);
await expectUsageCardOrder(page, ["beta:home", "alpha:a"]);
await expect(page.getByTestId("usage-report-beta:work")).toHaveCount(0);
});
for (const [size, viewport] of Object.entries({
desktop: { width: 1440, height: 900 },
compact: { width: 390, height: 844 },
})) {
test(`dedicated Sources list manages default-off sources without clutter (${size})`, async ({
page,
}) => {
test.setTimeout(120_000);
const [claude, codex] = claudeAndCodexReports();
const fetchedAt = twoHoursAgo();
await installUsageReportsFixture(page, {
lists: [
() => [
claude!,
codex!,
{
id: "copilot:default",
account: {},
fetchedAt,
sourceId: "copilot",
sourceLabel: "GitHub Copilot",
defaultEnabled: false,
report: {
status: "unavailable",
problem: { kind: "rejected", status: 403 },
},
},
{
id: "cursor:default",
account: { label: "dev@example.com" },
fetchedAt,
sourceId: "cursor",
sourceLabel: "Cursor",
defaultEnabled: false,
report: {
status: "available",
windows: [
{ id: "monthly", label: "Monthly", shortLabel: "mo", summary: true, usedPct: 18 },
],
},
},
],
],
});
await page.setViewportSize(viewport);
await gotoAppShell(page);
if (size === "compact") await openCompactSidebar(page);
// Only active sources appear in the sidebar summary and modal cards.
await expectPinnedUsage(page, ["31% 5h", "54% wk", "7% 5h", "12% wk"]);
await openUsageFromItem(page);
await expectUsageCardOrder(page, ["claude:default", "codex:default"]);
await expect(page.getByTestId("usage-report-copilot:default")).toHaveCount(0);
await expect(page.getByTestId("usage-report-cursor:default")).toHaveCount(0);
await qaScreenshot(page, `usage-sources-${size}-cards`);
await openUsageOptions(page);
await expect(page.getByTestId("usage-options-sources")).toContainText("2 of 4");
await qaScreenshot(page, `usage-sources-${size}-settings`);
if (size === "compact") {
// Compact sheets expose menu rows in the browser Tab order so keyboard users can open
// Sources and toggle checkboxes without a pointer.
await page.getByTestId("usage-options-sources").focus();
await expect(page.getByTestId("usage-options-sources")).toBeFocused();
await expect(page.getByTestId("usage-options-sources")).toHaveAttribute("tabindex", "0");
await page.keyboard.press("Enter");
} else {
await openUsageSources(page);
}
const claudeToggle = page.getByRole("checkbox", { name: /^Claude/ });
const copilotToggle = page.getByRole("checkbox", { name: /^GitHub Copilot/ });
const cursorToggle = page.getByRole("checkbox", { name: /^Cursor/ });
await expect(claudeToggle).toBeChecked();
await expect(copilotToggle).not.toBeChecked();
await expect(copilotToggle).toContainText("Provider inactive");
await qaScreenshot(page, `usage-sources-${size}-list`);
// Opting into a default-off source brings its card and summary window in immediately.
if (size === "compact") {
await cursorToggle.focus();
await expect(cursorToggle).toBeFocused();
await expect(cursorToggle).toHaveAttribute("tabindex", "0");
await page.keyboard.press("Space");
} else {
await cursorToggle.click();
}
await expect(cursorToggle).toBeChecked();
await closeUsageOptions(page);
await expectUsageCardOrder(page, ["claude:default", "codex:default", "cursor:default"]);
// Hiding every source shows a quiet empty state with a shortcut back to Settings.
await openUsageSources(page);
await page.getByTestId("usage-source-toggle-claude:default").click();
await page.getByTestId("usage-source-toggle-codex:default").click();
await page.getByTestId("usage-source-toggle-cursor:default").click();
await closeUsageOptions(page);
await expect(page.getByTestId("usage-all-hidden")).toBeVisible();
await expect(page.getByTestId("usage-choose-sources")).toBeVisible();
await qaScreenshot(page, `usage-sources-${size}-empty`);
await page.getByTestId("usage-choose-sources").click();
await expect(page.getByTestId("usage-options-sources")).toContainText("0 of 4");
});
}
test("refreshes one report from its card", async ({ page }) => {
test.setTimeout(120_000);
const serverId = getServerId();
@@ -291,12 +291,12 @@ test.describe("Usage item", () => {
await gotoAppShell(page);
const screen = page.getByTestId(`usage-host-${serverId}`);
await test.step("a fresh device shows default windows once the Usage item is on", async () => {
// The Usage item starts off on every layout; turning it on stores the choice.
await expectNoUsageItem(page);
await test.step("a fresh device shows default windows in the sidebar automatically", async () => {
// The Usage item starts on by default on every layout.
await expectPinnedUsage(page, ["31% 5h", "54% wk", "7% 5h", "12% wk"]);
await qaScreenshot(page, "desktop-footer-defaults", { kind: "footer" });
await openSidebarNavSettings(page);
await expectFooterItemSetting(page, "usage", false);
await setFooterItemVisible(page, "usage", true);
await expectFooterItemSetting(page, "usage", true);
await qaScreenshot(page, "desktop-settings-sidebar-footer");
await page.setViewportSize(COMPACT);
await expectFooterItemSetting(page, "usage", true);
@@ -308,7 +308,6 @@ test.describe("Usage item", () => {
await page.setViewportSize(WIDE);
await gotoAppShell(page);
await expectPinnedUsage(page, ["31% 5h", "54% wk", "7% 5h", "12% wk"]);
await qaScreenshot(page, "desktop-footer-defaults", { kind: "footer" });
await openUsageFromItem(page);
await qaScreenshot(page, "default-pins-card");
await expect(pinRow(screen, "Claude", "Session")).toBeChecked();
@@ -478,7 +477,7 @@ test("without summary data the footer drops the Usage item and keeps the Usage i
await openUsageFromIcon(page);
});
test("the Usage Settings switch turns on the sidebar summary and the pins with it", async ({
test("the Usage Settings switch turns the sidebar summary and pins off and back on", async ({
page,
}) => {
const serverId = getServerId();
@@ -488,8 +487,17 @@ test("the Usage Settings switch turns on the sidebar summary and the pins with i
const screen = page.getByTestId(`usage-host-${serverId}`);
const claude = screen.getByTestId("usage-report-claude:default");
await test.step("off by default: no Usage item, and rows that do not pin", async () => {
await openUsageFromIcon(page);
await test.step("on by default: the Usage item and pins appear", async () => {
await expectPinnedUsage(page, ["31% 5h", "54% wk", "7% 5h", "12% wk"]);
await openUsageFromItem(page);
await expect(pinRow(screen, "Claude", "Weekly")).toBeChecked();
await togglePin(screen, "Claude", "Weekly");
await expectPinnedUsage(page, ["31% 5h", "7% 5h", "12% wk"]);
await qaScreenshot(page, "usage-summary-on");
});
await test.step("off: no Usage item, and rows that do not pin", async () => {
await setSummaryInSidebar(page, false);
await expectNoUsageItem(page);
await expect(claude.getByText("Session", { exact: true })).toBeVisible({ timeout: 10_000 });
await expectUnpinnableRows(claude);
@@ -498,19 +506,7 @@ test("the Usage Settings switch turns on the sidebar summary and the pins with i
await qaScreenshot(page, "usage-summary-off");
});
await test.step("on: the Usage item and the pins appear", async () => {
await setSummaryInSidebar(page, true);
await expectPinnedUsage(page, ["31% 5h", "54% wk", "7% 5h", "12% wk"]);
await expect(pinRow(screen, "Claude", "Weekly")).toBeChecked();
await togglePin(screen, "Claude", "Weekly");
await expectPinnedUsage(page, ["31% 5h", "7% 5h", "12% wk"]);
await qaScreenshot(page, "usage-summary-on");
});
await test.step("off then on again, after a reload, brings back the saved pins", async () => {
await setSummaryInSidebar(page, false);
await expectNoUsageItem(page);
await expectUnpinnableRows(claude);
await test.step("after a reload, turning it back on brings back the saved pins", async () => {
await page.reload();
await openUsageFromIcon(page);
await expectSummaryInSidebar(page, false);
@@ -554,6 +550,7 @@ test("released hosts supply source logos through the client conversion", async (
test("hidden usage sends no requests until opened", async ({ page }) => {
test.setTimeout(180_000);
const usage = await installUsageReportsFixture(page, { lists: [() => claudeAndCodexReports()] });
await seedSidebarFooterPreferences(page, [{ key: "usage", visible: false }]);
await page.setViewportSize(WIDE);
await gotoAppShell(page);
await expectNoUsageItem(page);
@@ -569,10 +566,9 @@ test("hidden usage sends no requests until opened", async ({ page }) => {
expect(usage.listRequests()).toHaveLength(1);
});
test("visible usage summary requests reports on load", async ({ page }) => {
test("visible usage summary requests reports on load by default", async ({ page }) => {
test.setTimeout(180_000);
const usage = await installUsageReportsFixture(page, { lists: [() => claudeAndCodexReports()] });
await seedSidebarFooterPreferences(page, [{ key: "usage", visible: true }]);
await page.setViewportSize(WIDE);
await gotoAppShell(page);
await expectPinnedUsage(page, ["31% 5h", "54% wk", "7% 5h", "12% wk"]);
@@ -160,11 +160,23 @@ export async function expectUsageCardOrder(page: Page, reportIds: string[]): Pro
.toEqual(reportIds);
}
/** Turns a card on or off from its header switch, named by its source and account. */
export async function setUsageCardOn(page: Page, name: string, on: boolean): Promise<void> {
const cardSwitch = usageModal(page).getByRole("switch", { name: `Show ${name}`, exact: true });
await cardSwitch.click();
await expect(cardSwitch).toBeChecked({ checked: on });
/** Turns a source on or off from the Sources page in Usage Settings, by report id. */
export async function setUsageCardOn(page: Page, reportId: string, on: boolean): Promise<void> {
await openUsageSources(page);
const item = visible(page, `usage-source-toggle-${reportId}`);
const checked = (await item.getAttribute("aria-checked")) === "true";
if (checked !== on) {
await item.click();
await expect(item).toHaveAttribute("aria-checked", String(on));
}
await closeUsageOptions(page);
}
/** Opens the Sources submenu inside Usage Settings (flyout on wide, in-place page on compact). */
export async function openUsageSources(page: Page): Promise<void> {
await openUsageOptions(page);
await visible(page, "usage-options-sources").click();
await expect(page.locator('[data-testid^="usage-source-toggle-"]:visible').first()).toBeVisible();
}
/** Drags a card by its handle until it sits above another card, with the mouse. */
@@ -245,18 +257,14 @@ export function pinRow(scope: Locator, source: string, window: string): Locator
/**
* A report card whose window rows do not pin: no pin toggle, no pin glyph, and nothing focusable
* but the header's buttons and on/off switch, so no row presses or highlights on hover.
* but the header's buttons, so no row presses or highlights on hover.
*/
export async function expectUnpinnableRows(card: Locator): Promise<void> {
await expect(card.getByRole("checkbox")).toHaveCount(0);
await expect(card.locator('[data-testid^="usage-pin-"]')).toHaveCount(0);
const focusable = await card
.locator("[tabindex]")
.evaluateAll(
(nodes) =>
nodes.filter((node) => !["button", "switch"].includes(node.getAttribute("role") ?? ""))
.length,
);
.evaluateAll((nodes) => nodes.filter((node) => node.getAttribute("role") !== "button").length);
expect(focusable).toBe(0);
}
@@ -388,6 +396,7 @@ export async function closeUsageOptions(page: Page): Promise<void> {
await waitForSettledPosition(usageOptionsSurface(page));
await page.mouse.click(0, 0);
await expect(page.getByTestId("usage-display-used")).toHaveCount(0);
await expect(page.locator('[data-testid^="usage-source-toggle-"]:visible')).toHaveCount(0);
}
export async function showUsageAs(page: Page, displayAs: "used" | "remaining") {
@@ -1,5 +1,6 @@
import { useCallback, type ReactElement } from "react";
import {
MenuCheckboxItem,
MenuHint,
MenuItem,
MenuLabel,
@@ -23,11 +24,16 @@ import {
export { MenuRoot as DropdownMenu };
export { MenuTrigger as DropdownMenuTrigger };
export { MenuItem as DropdownMenuItem };
export { MenuCheckboxItem as DropdownMenuCheckboxItem };
export { MenuLabel as DropdownMenuLabel };
export { MenuSeparator as DropdownMenuSeparator };
export { MenuHint as DropdownMenuHint };
export type { MenuTriggerProps as DropdownMenuTriggerProps };
export type { ActionStatus, MenuItemProps as DropdownMenuItemProps } from "@/components/ui/menu";
export type {
ActionStatus,
MenuCheckboxItemProps as DropdownMenuCheckboxItemProps,
MenuItemProps as DropdownMenuItemProps,
} from "@/components/ui/menu";
export type { MenuPageDefinition } from "@/components/ui/menu";
export { MenuSubTrigger as DropdownMenuSubTrigger } from "@/components/ui/menu";
@@ -19,6 +19,7 @@ export {
} from "./menu-surface";
export { MenuSubTrigger } from "./menu-sub";
export {
MenuCheckboxItem,
MenuHint,
MenuItem,
MenuLabel,
@@ -26,6 +27,7 @@ export {
MenuTextField,
menuRowContentInset,
type ActionStatus,
type MenuCheckboxItemProps,
type MenuItemProps,
} from "./menu-item";
export { MENU_ITEM_HEIGHT } from "./menu-geometry";
@@ -18,6 +18,7 @@ import { Check, CheckCircle } from "lucide-react-native";
import { AdaptiveTextInput } from "@/components/adaptive-modal-sheet";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { isWeb } from "@/constants/platform";
import type { Theme } from "@/styles/theme";
import { MenuDepthProvider, useMenuContext } from "./menu-context";
import { MENU_ITEM_HEIGHT } from "./menu-geometry";
@@ -221,6 +222,36 @@ function resolveItemLabel(input: {
return children;
}
function resolveTrailingContent(input: {
trailing: ReactElement | null | undefined;
showSelectedCheck: boolean;
selected: boolean | undefined;
}): ReactElement | null {
if (input.trailing !== undefined) return input.trailing;
if (!input.showSelectedCheck && input.selected) {
return <ThemedCheck size={16} uniProps={mutedMapping} />;
}
return null;
}
function useSheetSpaceKeyProps(
enabled: boolean,
onPress: () => void,
): { onKeyDown?: (event: { key?: string; preventDefault?: () => void }) => void } {
return useMemo(() => {
if (!isWeb || !enabled) return {};
return {
// React Native Web's Pressable activates Space only for role="button", not menuitem/checkbox.
onKeyDown: (event: { key?: string; preventDefault?: () => void }) => {
if (event.key === " " || event.key === "Spacebar") {
event.preventDefault?.();
onPress();
}
},
};
}, [enabled, onPress]);
}
export interface MenuItemProps {
description?: string;
onSelect?: () => void;
@@ -253,7 +284,37 @@ export interface MenuItemProps {
tooltip?: string;
}
export function MenuItem({
export function MenuItem(props: PropsWithChildren<MenuItemProps>): ReactElement {
return <MenuRow {...props} accessibilityRole="menuitem" />;
}
export interface MenuCheckboxItemProps extends Omit<MenuItemProps, "selected" | "onSelect"> {
checked: boolean;
onToggle: () => void;
}
/**
* A toggleable menu row that stays open on press by default and exposes `checkbox` semantics so
* screen readers announce its checked state.
*/
export function MenuCheckboxItem({
checked,
onToggle,
closeOnSelect = false,
...rest
}: PropsWithChildren<MenuCheckboxItemProps>): ReactElement {
return (
<MenuRow
{...rest}
selected={checked}
onSelect={onToggle}
closeOnSelect={closeOnSelect}
accessibilityRole="checkbox"
/>
);
}
function MenuRow({
children,
description,
onSelect,
@@ -272,8 +333,11 @@ export function MenuItem({
closeOnSelect = true,
testID,
tooltip,
}: PropsWithChildren<MenuItemProps>): ReactElement {
const { selectItem } = useMenuContext("MenuItem");
accessibilityRole,
}: PropsWithChildren<
MenuItemProps & { accessibilityRole: "menuitem" | "checkbox" }
>): ReactElement {
const { selectItem, presentation } = useMenuContext("MenuItem");
const isPending = status === "pending" || loading;
const isSuccess = status === "success";
const isDisabled = disabled || isPending || isSuccess;
@@ -286,14 +350,14 @@ export function MenuItem({
const label = resolveItemLabel({ children, isPending, isSuccess, pendingLabel, successLabel });
const trailingContent =
trailing ??
(!showSelectedCheck && selected ? <ThemedCheck size={16} uniProps={mutedMapping} /> : null);
const trailingContent = resolveTrailingContent({ trailing, showSelectedCheck, selected });
const handleItemPress = useCallback(() => {
if (isDisabled) return;
selectItem(onSelect, closeOnSelect);
}, [isDisabled, selectItem, onSelect, closeOnSelect]);
const isSheet = presentation === "sheet";
const sheetKeyProps = useSheetSpaceKeyProps(isSheet, handleItemPress);
// A row that draws a check has to say so as well: a multi-select page is a list of things that
// are on or off, and the check is the only thing telling a sighted user which. Rows that answer
@@ -336,11 +400,13 @@ export function MenuItem({
const content = (
<Pressable
{...sheetKeyProps}
testID={testID}
accessibilityRole="menuitem"
accessibilityRole={accessibilityRole}
accessibilityState={accessibilityState}
aria-checked={selected}
tabIndex={-1}
// Popovers manage focus via arrow keys; compact sheets rely on the browser's Tab order.
tabIndex={isSheet ? 0 : -1}
dataSet={itemDataSet}
disabled={isDisabled}
onPress={handleItemPress}
@@ -331,7 +331,7 @@ describe("loadAppSettingsFromStorage", () => {
pins: null,
serverId: null,
cardOrder: [],
cardsOff: [],
cardVisibility: {},
});
const deps = makeDeps({
@@ -357,7 +357,7 @@ describe("loadAppSettingsFromStorage", () => {
],
serverId: "server",
cardOrder: [],
cardsOff: [],
cardVisibility: {},
});
});
@@ -374,7 +374,7 @@ describe("loadAppSettingsFromStorage", () => {
pins: [],
serverId: "server",
cardOrder: [],
cardsOff: [],
cardVisibility: {},
});
});
@@ -396,7 +396,7 @@ describe("loadAppSettingsFromStorage", () => {
pins: [{ sourceId: "claude", windowId: "weekly" }],
serverId: null,
cardOrder: [],
cardsOff: [],
cardVisibility: {},
});
});
+5 -1
View File
@@ -2264,7 +2264,11 @@ export const ar: TranslationResources = {
title: "استخدام الخطة",
refresh: "تحديث",
reorderCard: "إعادة ترتيب {{source}}",
showCard: "إظهار {{source}}",
sources: "المصادر",
sourcesCount: "{{shown}} من {{total}}",
providerInactive: "المزود غير نشط",
allSourcesHidden: "لا توجد مصادر استخدام معروضة",
chooseSources: "اختيار المصادر",
refreshAll: "تحديث الكل",
refreshing: "جارٍ التحديث...",
loading: "جارٍ تحميل بيانات الاستخدام...",
+5 -1
View File
@@ -2292,7 +2292,11 @@ export const en = {
title: "Plan usage",
refresh: "Refresh",
reorderCard: "Reorder {{source}}",
showCard: "Show {{source}}",
sources: "Sources",
sourcesCount: "{{shown}} of {{total}}",
providerInactive: "Provider inactive",
allSourcesHidden: "No usage sources shown",
chooseSources: "Choose sources",
refreshAll: "Refresh all",
refreshing: "Refreshing...",
loading: "Loading usage...",
+5 -1
View File
@@ -2313,7 +2313,11 @@ export const es: TranslationResources = {
title: "Uso del plan",
refresh: "Actualizar",
reorderCard: "Reordenar {{source}}",
showCard: "Mostrar {{source}}",
sources: "Fuentes",
sourcesCount: "{{shown}} de {{total}}",
providerInactive: "Proveedor inactivo",
allSourcesHidden: "No hay fuentes de uso visibles",
chooseSources: "Elegir fuentes",
refreshAll: "Actualizar todo",
refreshing: "Actualizando...",
loading: "Cargando uso...",
+5 -1
View File
@@ -2314,7 +2314,11 @@ export const fr: TranslationResources = {
title: "Utilisation du forfait",
refresh: "Actualiser",
reorderCard: "Réorganiser {{source}}",
showCard: "Afficher {{source}}",
sources: "Sources",
sourcesCount: "{{shown}} sur {{total}}",
providerInactive: "Fournisseur inactif",
allSourcesHidden: "Aucune source d'utilisation affichée",
chooseSources: "Choisir les sources",
refreshAll: "Tout actualiser",
refreshing: "Actualisation...",
loading: "Chargement de l’utilisation...",
+5 -1
View File
@@ -2287,7 +2287,11 @@ export const ja: TranslationResources = {
title: "プラン使用量",
refresh: "更新",
reorderCard: "{{source}} を並べ替え",
showCard: "{{source}} を表示",
sources: "ソース",
sourcesCount: "{{shown}} / {{total}}",
providerInactive: "プロバイダー無効",
allSourcesHidden: "表示中の使用量ソースはありません",
chooseSources: "ソースを選択",
refreshAll: "すべて更新",
refreshing: "更新中...",
loading: "使用状況を読み込み中...",
+5 -1
View File
@@ -2275,7 +2275,11 @@ export const ko: TranslationResources = {
title: "플랜 사용량",
refresh: "새로 고침",
reorderCard: "{{source}} 순서 변경",
showCard: "{{source}} 표시",
sources: "소스",
sourcesCount: "{{shown}} / {{total}}",
providerInactive: "제공업체 비활성",
allSourcesHidden: "표시된 사용량 소스가 없습니다",
chooseSources: "소스 선택",
refreshAll: "모두 새로 고침",
refreshing: "새로 고치는 중...",
loading: "사용량 불러오는 중...",
+5 -1
View File
@@ -2298,7 +2298,11 @@ export const ptBR: TranslationResources = {
title: "Uso do plano",
refresh: "Atualizar",
reorderCard: "Reordenar {{source}}",
showCard: "Mostrar {{source}}",
sources: "Fontes",
sourcesCount: "{{shown}} de {{total}}",
providerInactive: "Provedor inativo",
allSourcesHidden: "Nenhuma fonte de uso exibida",
chooseSources: "Escolher fontes",
refreshAll: "Atualizar tudo",
refreshing: "Atualizando...",
loading: "Carregando uso...",
+5 -1
View File
@@ -2300,7 +2300,11 @@ export const ru: TranslationResources = {
title: "Использование плана",
refresh: "Обновить",
reorderCard: "Переместить {{source}}",
showCard: "Показывать {{source}}",
sources: "Источники",
sourcesCount: "{{shown}} из {{total}}",
providerInactive: "Провайдер неактивен",
allSourcesHidden: "Источники использования скрыты",
chooseSources: "Выбрать источники",
refreshAll: "Обновить всё",
refreshing: "Обновление...",
loading: "Загрузка данных об использовании...",
+5 -1
View File
@@ -2241,7 +2241,11 @@ export const zhCN: TranslationResources = {
title: "套餐用量",
refresh: "刷新",
reorderCard: "重新排序 {{source}}",
showCard: "显示 {{source}}",
sources: "来源",
sourcesCount: "{{shown}} / {{total}}",
providerInactive: "提供商未启用",
allSourcesHidden: "未显示任何用量来源",
chooseSources: "选择来源",
refreshAll: "全部刷新",
refreshing: "刷新中...",
loading: "正在加载用量...",
+5 -5
View File
@@ -115,12 +115,12 @@ describe("resolveSidebarNavItems", () => {
});
describe("resolveSidebarNavItems for the Usage item", () => {
it("hides the Usage item until it is turned on", () => {
it("shows the Usage item by default and honors an explicit off choice", () => {
const resolve = (preferences: SidebarNavPreference[]) =>
summarize(resolveSidebarNavItems({ section: "footer", pluginGroups: [], preferences }));
expect(resolve([])).toEqual([{ key: "usage", visible: false }]);
expect(resolve([{ key: "usage", visible: true }])).toEqual([{ key: "usage", visible: true }]);
expect(resolve([])).toEqual([{ key: "usage", visible: true }]);
expect(resolve([{ key: "usage", visible: false }])).toEqual([{ key: "usage", visible: false }]);
});
});
@@ -297,7 +297,7 @@ describe("footer section", () => {
});
expect(summarize(items)).toEqual([
{ key: "usage", visible: false },
{ key: "usage", visible: true },
{ key: syncKey, visible: true },
]);
});
@@ -309,7 +309,7 @@ describe("footer section", () => {
preferences: [{ key: "history", visible: false }],
});
expect(summarize(items)).toEqual([{ key: "usage", visible: false }]);
expect(summarize(items)).toEqual([{ key: "usage", visible: true }]);
});
it("ignores the footer icon buttons, which are fixed and not items", () => {
+2 -5
View File
@@ -69,11 +69,8 @@ export function builtinSidebarNavShortcutAction(id: BuiltinSidebarItemId): strin
return BUILTIN_SHORTCUT_ACTIONS[id];
}
/** Builtins that start hidden until the user turns them on: the Usage summary is opt-in. */
const HIDDEN_BY_DEFAULT: ReadonlySet<BuiltinSidebarItemId> = new Set(["usage"]);
function builtinVisibleByDefault(id: BuiltinSidebarItemId): boolean {
return !HIDDEN_BY_DEFAULT.has(id);
function builtinVisibleByDefault(_id: BuiltinSidebarItemId): boolean {
return true;
}
export function pluginSidebarNavKey(
+15 -51
View File
@@ -1,5 +1,5 @@
import { GripVertical, RotateCw } from "lucide-react-native";
import { useCallback, useMemo } from "react";
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { Text, View, type StyleProp, type TextStyle } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
@@ -9,14 +9,13 @@ import {
smallIconButtonChromeFrameSize,
} from "@/components/ui/icon-button-chrome";
import { DraggableListHandle } from "@/components/draggable-list";
import { ControlSizeProvider } from "@/components/ui/control-size";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { ToolbarButton, paneContentToolbarIconSize } from "@/components/ui/pane-content-toolbar";
import { StatusBadge } from "@/components/ui/status-badge";
import { Switch } from "@/components/ui/switch";
import { useIsCompactFormFactor } from "@/constants/layout";
import { isNative } from "@/constants/platform";
import type { TFunction } from "i18next";
import { useCallback } from "react";
import { UsageBalanceBar } from "./balance-bar";
import type { UsageDisplay } from "./display";
import { formatAgo, formatProviderUsageLabel, formatUsageAccountName } from "./format";
@@ -37,10 +36,8 @@ function statusText(report: UsageReport, t: TFunction): string | null {
const ThemedRotateCw = withUnistyles(RotateCw);
const ThemedGripVertical = withUnistyles(GripVertical);
/** A card in the user's arrangement: dragged by its handle, turned off from its switch. */
/** A card in the user's arrangement: dragged by its handle. */
export interface UsageCardArrangement {
on: boolean;
onSetOn: (on: boolean) => void;
/** The handle is always there; it shows while the card is hovered or where there is no hover. */
handleVisible: boolean;
}
@@ -64,7 +61,7 @@ export function UsageCard({
pinnable: boolean;
/** Whether the header has a Refresh button. Without one the freshness shows on the card. */
refreshable: boolean;
/** Present where the user arranges cards. An off card collapses to its header. */
/** Present where the user arranges cards. */
arrangement?: UsageCardArrangement;
compact?: boolean;
}) {
@@ -75,7 +72,6 @@ export function UsageCard({
const showsFreshnessInline = isNative || isCompact || !refreshable;
const usage = entry.report;
const status = statusText(usage, t);
const collapsed = arrangement?.on === false;
const report = resolveUsageReport(entry, t);
const { planLabel, successfulAt, retained } = report;
@@ -105,23 +101,15 @@ export function UsageCard({
<Text style={styles.name} numberOfLines={1}>
{entry.sourceLabel}
</Text>
{collapsed && entry.account.label ? (
// The body that names the account is gone, and two off cards of one source must differ.
<Text style={styles.collapsedAccount} numberOfLines={1}>
{entry.account.label}
</Text>
) : null}
{planLabel && !collapsed ? (
<StatusBadge label={planLabel} variant="muted" size="xs" />
) : null}
{planLabel ? <StatusBadge label={planLabel} variant="muted" size="xs" /> : null}
<View style={styles.headerSpacer} />
{status && !collapsed ? (
{status ? (
<View style={styles.statusRow}>
<View style={dotStyle} />
<Text style={styles.statusLabel}>{status}</Text>
</View>
) : null}
{refreshable && !collapsed ? (
{refreshable ? (
<UsageRefreshButton
sourceLabel={entry.sourceLabel}
successfulAt={successfulAt}
@@ -131,31 +119,16 @@ export function UsageCard({
compact={isCompact}
/>
) : null}
{arrangement ? (
<ControlSizeProvider size="sm">
<Switch
value={arrangement.on}
onValueChange={arrangement.onSetOn}
accessibilityLabel={t("providerUsage.showCard", {
source: formatUsageAccountName(entry),
})}
style={styles.cardSwitch}
testID={`usage-card-switch-${entry.id}`}
/>
</ControlSizeProvider>
) : null}
</View>
{collapsed ? null : (
<UsageCardBody
entry={entry}
display={display}
pinnable={pinnable}
report={report}
showsFreshnessInline={showsFreshnessInline}
refreshState={refreshState}
/>
)}
<UsageCardBody
entry={entry}
display={display}
pinnable={pinnable}
report={report}
showsFreshnessInline={showsFreshnessInline}
refreshState={refreshState}
/>
</View>
);
}
@@ -434,11 +407,6 @@ const styles = StyleSheet.create((theme) => ({
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
},
collapsedAccount: {
flexShrink: 1,
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
},
headerSpacer: {
flex: 1,
},
@@ -510,10 +478,6 @@ const styles = StyleSheet.create((theme) => ({
},
dragHandle: dragHandleSlot(theme.spacing),
dragHandleHidden: { ...dragHandleSlot(theme.spacing), opacity: 0 },
// The switch's reserved control height overhangs the header like the Refresh button's hitbox.
cardSwitch: {
marginVertical: -theme.spacing[2],
},
refreshButton: iconHitboxOverhang(false),
refreshButtonCompact: iconHitboxOverhang(true),
}));
+47 -4
View File
@@ -3,6 +3,7 @@ import {
arrangeUsageCards,
arrangeUsageReports,
DEFAULT_USAGE_PREFERENCES,
isUsageCardOn,
setUsageCardOn,
UsagePreferencesSchema,
usageReportsOn,
@@ -11,13 +12,19 @@ import {
import { resolvePinnedUsage } from "./pinned";
import type { UsageReportEntry } from "./types";
function report(sourceId: string, sourceLabel: string, account?: string): UsageReportEntry {
function report(
sourceId: string,
sourceLabel: string,
account?: string,
defaultEnabled?: boolean,
): UsageReportEntry {
return {
id: `${sourceId}:${account ?? "default"}`,
sourceId,
sourceLabel,
account: account ? { label: account } : {},
fetchedAt: "2026-01-01T00:00:00.000Z",
...(defaultEnabled === undefined ? {} : { defaultEnabled }),
report: {
status: "available",
windows: [{ id: "weekly", label: "Weekly", summary: true, usedPct: 40 }],
@@ -114,8 +121,31 @@ describe("usage card order", () => {
describe("usage cards turned off", () => {
it("turns a card off and back on", () => {
const off = setUsageCardOn(DEFAULT_USAGE_PREFERENCES, "codex:default", false);
expect(off.cardsOff).toEqual(["codex:default"]);
expect(setUsageCardOn(off, "codex:default", true).cardsOff).toEqual([]);
expect(off.cardVisibility).toEqual({ "codex:default": false });
expect(isUsageCardOn(off, codex)).toBe(false);
const on = setUsageCardOn(off, "codex:default", true);
expect(on.cardVisibility).toEqual({ "codex:default": true });
expect(isUsageCardOn(on, codex)).toBe(true);
});
it("hides sources hinted off by default until the user explicitly turns them on", () => {
const uninstalledCopilot = report("copilot", "GitHub Copilot", undefined, false);
expect(isUsageCardOn(DEFAULT_USAGE_PREFERENCES, uninstalledCopilot)).toBe(false);
expect(ids(usageReportsOn([codex, uninstalledCopilot], DEFAULT_USAGE_PREFERENCES))).toEqual([
"codex:default",
]);
expect(
resolvePinnedUsage([codex, uninstalledCopilot], DEFAULT_USAGE_PREFERENCES).map(
(source) => source.key,
),
).toEqual(["codex:default"]);
const optedIn = setUsageCardOn(DEFAULT_USAGE_PREFERENCES, uninstalledCopilot.id, true);
expect(isUsageCardOn(optedIn, uninstalledCopilot)).toBe(true);
expect(ids(usageReportsOn([codex, uninstalledCopilot], optedIn))).toEqual([
"codex:default",
"copilot:default",
]);
});
it("leaves off cards out of the sidebar summary", () => {
@@ -143,11 +173,24 @@ describe("stored card preferences", () => {
);
});
it("migrates legacy cardsOff into cardVisibility", () => {
expect(
UsagePreferencesSchema.parse({
displayAs: "used",
serverId: null,
cardsOff: ["codex:default"],
}),
).toEqual({
...DEFAULT_USAGE_PREFERENCES,
cardVisibility: { "codex:default": false },
});
});
it("survives a save and reload, and ignores a malformed arrangement", () => {
const saved = setUsageCardOn(arranged(["codex:default"]), "claude:work", false);
expect(UsagePreferencesSchema.parse(JSON.parse(JSON.stringify(saved)))).toEqual(saved);
expect(
UsagePreferencesSchema.parse({ displayAs: "used", cardOrder: "bad", cardsOff: [1] }),
UsagePreferencesSchema.parse({ displayAs: "used", cardOrder: "bad", cardVisibility: [1] }),
).toEqual(DEFAULT_USAGE_PREFERENCES);
});
});
+26 -4
View File
@@ -1,8 +1,9 @@
import { View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { useMemo, type ReactElement } from "react";
import { useCallback, useMemo, useState, type ReactElement } from "react";
import { UsageRefreshButton } from "./refresh-button";
import { UsageOptions } from "./options";
import { useUsageDisplay, type UsageDisplay } from "./display";
import { hasHostChoice, type UsageHostSelection } from "./hosts";
import { useHostUsage } from "./queries";
import type { UsageView } from "./types";
@@ -15,13 +16,19 @@ import type { UsageView } from "./types";
export function UsageControls({
view,
serverId,
display,
onRefresh,
hostSelection,
optionsOpen,
onOptionsOpenChange,
}: {
view: UsageView;
serverId: string;
display?: UsageDisplay;
onRefresh: () => void;
hostSelection?: UsageHostSelection;
optionsOpen?: boolean;
onOptionsOpenChange?: (open: boolean) => void;
}) {
const busy = view.kind === "loading" || (view.kind === "ready" && view.isRefreshing);
if (!hasUsageControls(view, hostSelection)) return null;
@@ -30,7 +37,14 @@ export function UsageControls({
{view.kind === "off" || view.kind === "unavailable" ? null : (
<UsageRefreshButton busy={busy} onRefresh={onRefresh} />
)}
<UsageOptions serverId={serverId} hostSelection={hostSelection} />
<UsageOptions
serverId={serverId}
hostSelection={hostSelection}
reports={view.kind === "ready" ? view.reports : []}
display={display}
open={optionsOpen}
onOpenChange={onOptionsOpenChange}
/>
</View>
);
}
@@ -54,10 +68,15 @@ const styles = StyleSheet.create((theme) => ({
*/
export function useHostUsageWithControls(hostSelection: UsageHostSelection): {
view: UsageView;
display: UsageDisplay;
refresh: () => void;
controls: ReactElement | null;
openOptions: () => void;
} {
const { view, refresh } = useHostUsage(hostSelection.serverId);
const { display } = useUsageDisplay(view.kind === "ready" ? view.reports : []);
const [optionsOpen, setOptionsOpen] = useState(false);
const openOptions = useCallback(() => setOptionsOpen(true), []);
const controls = useMemo(
() =>
hasUsageControls(view, hostSelection) ? (
@@ -67,11 +86,14 @@ export function useHostUsageWithControls(hostSelection: UsageHostSelection): {
key={hostSelection.serverId}
serverId={hostSelection.serverId}
view={view}
display={display}
onRefresh={refresh}
hostSelection={hostSelection}
optionsOpen={optionsOpen}
onOptionsOpenChange={setOptionsOpen}
/>
) : null,
[hostSelection, refresh, view],
[display, hostSelection, optionsOpen, refresh, view],
);
return { view, refresh, controls };
return { view, display, refresh, controls, openOptions };
}
+3 -3
View File
@@ -3,7 +3,7 @@ import { useAppSettings } from "@/hooks/use-settings";
import {
arrangeUsageCards,
arrangeUsageReports,
isUsageCardOff,
isUsageCardOn,
isUsagePinned,
setUsageCardOn,
setUsageDisplayAs,
@@ -25,7 +25,7 @@ export interface UsageDisplay {
arrange: (reports: readonly UsageReportEntry[]) => UsageReportEntry[];
/** Saves the order of the shown cards after the user drops one. */
arrangeCards: (drop: UsageCardDrop) => void;
isCardOn: (reportId: string) => boolean;
isCardOn: (entry: Pick<UsageReportEntry, "id" | "defaultEnabled">) => boolean;
setCardOn: (reportId: string, on: boolean) => void;
}
@@ -72,7 +72,7 @@ export function useUsageDisplay(reports: readonly UsageReportEntry[]): UsagePref
togglePin,
arrange: (shown) => arrangeUsageReports(shown, preferences),
arrangeCards,
isCardOn: (reportId) => !isUsageCardOff(preferences, reportId),
isCardOn: (entry) => isUsageCardOn(preferences, entry),
setCardOn,
}),
[arrangeCards, preferences, reports, setCardOn, setDisplayAs, togglePin],
+5 -14
View File
@@ -16,8 +16,8 @@ function reportKey(entry: UsageReportEntry): string {
}
/**
* One card per report (source + account), in the user's order. Each card drags by its handle and
* turns off from its switch. Window rows pin while the sidebar summary is on.
* One card per shown report (source + account), in the user's order. Each card drags by its handle.
* Window rows pin while the sidebar summary is on.
*/
export function UsageList({
serverId,
@@ -29,8 +29,7 @@ export function UsageList({
display: UsageDisplay;
}) {
const { inSidebar } = useUsageInSidebar();
const { arrange, arrangeCards } = display;
const arranged = useMemo(() => arrange(reports), [arrange, reports]);
const { arrangeCards } = display;
const handleDragEnd = useCallback(
(next: UsageReportEntry[], moved: string) =>
arrangeCards({ moved, after: next.map(reportKey) }),
@@ -52,7 +51,7 @@ export function UsageList({
);
return (
<DraggableList
data={arranged}
data={reports}
keyExtractor={reportKey}
renderItem={renderItem}
onDragEnd={handleDragEnd}
@@ -90,19 +89,11 @@ function UsageListCard({
const [hasFocus, setHasFocus] = useState(false);
const handleFocus = useCallback(() => setHasFocus(true), []);
const handleBlur = useCallback(() => setHasFocus(false), []);
const { isCardOn, setCardOn } = display;
const on = isCardOn(entry.id);
const handleSetOn = useCallback(
(next: boolean) => setCardOn(entry.id, next),
[entry.id, setCardOn],
);
const arrangement = useMemo(
() => ({
on,
onSetOn: handleSetOn,
handleVisible: isHovered || hasFocus || dragging || isNative || isCompact,
}),
[dragging, handleSetOn, hasFocus, isCompact, isHovered, on],
[dragging, hasFocus, isCompact, isHovered],
);
return (
<View
+113 -20
View File
@@ -2,9 +2,10 @@ import { useTranslation } from "react-i18next";
import { View } from "react-native";
import { Settings } from "lucide-react-native";
import { withUnistyles } from "react-native-unistyles";
import { useMemo } from "react";
import { useCallback, useMemo } from "react";
import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuSubTrigger,
type MenuPageDefinition,
@@ -23,26 +24,36 @@ import { Alert } from "@/components/ui/alert";
import { useHosts } from "@/runtime/host-runtime";
import { settingsStyles } from "@/styles/settings";
import { useUsageSetting } from "./setting";
import { useUsageDisplay } from "./display";
import { useUsageDisplay, type UsageDisplay } from "./display";
import { useUsageInSidebar } from "./in-sidebar";
import { hasHostChoice, type UsageHostSelection } from "./hosts";
import type { UsageDisplayAs } from "./preferences";
import { UsageSourceIcon } from "./source-icon";
import type { UsageReportEntry } from "./types";
const ThemedSettings = withUnistyles(Settings);
const HOST_PAGE = "host";
const SOURCES_PAGE = "sources";
/**
* The shared usage preferences, opened from a cog as a popover or compact sheet. With more than
* one host, it leads with the host whose usage shows: the row reads as the current host, and the
* hosts are a page of the same surface, so a compact sheet never opens a second sheet over it.
* The shared usage preferences, opened from a cog as a popover or compact sheet. Host and Sources
* open as pages of the same surface, so a compact sheet never opens a second sheet over it.
*/
export function UsageOptions({
serverId,
hostSelection,
reports = [],
display: providedDisplay,
open,
onOpenChange,
}: {
serverId: string | null;
hostSelection?: UsageHostSelection;
reports?: readonly UsageReportEntry[];
display?: UsageDisplay;
open?: boolean;
onOpenChange?: (open: boolean) => void;
}) {
const setting = useUsageSetting(serverId);
const hostLabel = useHosts().find((host) => host.serverId === serverId)?.label ?? serverId;
@@ -57,24 +68,37 @@ export function UsageOptions({
];
const compact = useIsCompactFormFactor();
const glyphSize = useIconButtonChromeGlyphSize("small", compact);
const { display } = useUsageDisplay([]);
const fallbackDisplay = useUsageDisplay(providedDisplay ? [] : reports).display;
const display = providedDisplay ?? fallbackDisplay;
const { inSidebar, setInSidebar } = useUsageInSidebar();
const hostChoice = hasHostChoice(hostSelection) ? hostSelection : null;
const pages = useMemo<MenuPageDefinition[] | undefined>(
() =>
hostChoice
? [
{
id: HOST_PAGE,
title: t("providerUsage.host"),
content: <UsageHostPage hostSelection={hostChoice} />,
},
]
: undefined,
[hostChoice, t],
const arrangedReports = useMemo(() => display.arrange(reports), [display, reports]);
const hasSources = arrangedReports.length > 0;
const shownCount = useMemo(
() => arrangedReports.filter((entry) => display.isCardOn(entry)).length,
[arrangedReports, display],
);
const pages = useMemo<MenuPageDefinition[] | undefined>(() => {
const definitions: MenuPageDefinition[] = [];
if (hostChoice) {
definitions.push({
id: HOST_PAGE,
title: t("providerUsage.host"),
content: <UsageHostPage hostSelection={hostChoice} />,
});
}
if (hasSources) {
definitions.push({
id: SOURCES_PAGE,
title: t("providerUsage.sources"),
content: <UsageSourcesPage reports={arrangedReports} display={display} />,
});
}
return definitions.length > 0 ? definitions : undefined;
}, [arrangedReports, display, hasSources, hostChoice, t]);
const hasSubTriggers = Boolean(hostChoice || hasSources);
return (
<DropdownMenu compactMode="sheet">
<DropdownMenu compactMode="sheet" open={open} onOpenChange={onOpenChange}>
<ToolbarButton
kind="menu"
label={t("providerUsage.options")}
@@ -99,8 +123,20 @@ export function UsageOptions({
{t("providerUsage.host")}
</DropdownMenuSubTrigger>
) : null}
{hasSources ? (
<DropdownMenuSubTrigger
id={SOURCES_PAGE}
value={t("providerUsage.sourcesCount", {
shown: shownCount,
total: arrangedReports.length,
})}
testID="usage-options-sources"
>
{t("providerUsage.sources")}
</DropdownMenuSubTrigger>
) : null}
<View
style={hostChoice ? settingsStyles.rowBorder : undefined}
style={hasSubTriggers ? settingsStyles.rowBorder : undefined}
testID="usage-options-fields"
>
<MenuSettingsRows>
@@ -156,3 +192,60 @@ function UsageHostPage({ hostSelection }: { hostSelection: UsageHostSelection })
</>
);
}
function UsageSourcesPage({
reports,
display,
}: {
reports: readonly UsageReportEntry[];
display: UsageDisplay;
}) {
const { t } = useTranslation();
const inactiveLabel = t("providerUsage.providerInactive");
return (
<>
{reports.map((entry) => (
<UsageSourceMenuItem
key={entry.id}
entry={entry}
on={display.isCardOn(entry)}
onToggle={display.setCardOn}
inactiveLabel={inactiveLabel}
/>
))}
</>
);
}
function UsageSourceMenuItem({
entry,
on,
onToggle,
inactiveLabel,
}: {
entry: UsageReportEntry;
on: boolean;
onToggle: (reportId: string, on: boolean) => void;
inactiveLabel: string;
}) {
const handleSelect = useCallback(() => onToggle(entry.id, !on), [entry.id, on, onToggle]);
const leading = useMemo(
() => <UsageSourceIcon svg={entry.icon ?? null} size={14} />,
[entry.icon],
);
const description =
[entry.account.label, !on && entry.defaultEnabled === false ? inactiveLabel : null]
.filter(Boolean)
.join(" · ") || undefined;
return (
<DropdownMenuCheckboxItem
leading={leading}
description={description}
checked={on}
onToggle={handleSelect}
testID={`usage-source-toggle-${entry.id}`}
>
{entry.sourceLabel}
</DropdownMenuCheckboxItem>
);
}
+42 -17
View File
@@ -20,8 +20,8 @@ export interface UsagePreferences {
serverId: string | null;
/** Report IDs the user arranged, in their order. Shared by every host. */
cardOrder: string[];
/** Report IDs the user turned off. Their cards collapse and leave the sidebar summary. */
cardsOff: string[];
/** Explicit per-report visibility overrides; absent IDs follow the host's `defaultEnabled` hint. */
cardVisibility: Record<string, boolean>;
}
export const DEFAULT_USAGE_PREFERENCES: UsagePreferences = {
@@ -29,11 +29,12 @@ export const DEFAULT_USAGE_PREFERENCES: UsagePreferences = {
pins: null,
serverId: null,
cardOrder: [],
cardsOff: [],
cardVisibility: {},
};
const pinsSchema = z.array(z.object({ sourceId: z.string(), windowId: z.string() }));
const reportIdsSchema = z.array(z.string()).optional().catch(undefined);
const cardVisibilitySchema = z.record(z.string(), z.boolean()).optional().catch(undefined);
export const UsagePreferencesSchema = z
.object({
@@ -44,18 +45,34 @@ export const UsagePreferencesSchema = z
pinned: pinsSchema.optional().catch([]),
serverId: z.string().nullable().catch(null),
cardOrder: reportIdsSchema,
cardVisibility: cardVisibilitySchema,
// COMPAT(usageCardsOff): replaced by cardVisibility in v0.18, remove after 2027-05-22.
cardsOff: reportIdsSchema,
})
.transform(({ displayAs, pins, pinned, serverId, cardOrder, cardsOff }): UsagePreferences => {
const legacyPins = pinned && pinned.length > 0 ? pinned : null;
return {
.transform(
({
displayAs,
pins: pins === undefined ? legacyPins : pins,
pins,
pinned,
serverId,
cardOrder: cardOrder ?? [],
cardsOff: cardsOff ?? [],
};
})
cardOrder,
cardVisibility,
cardsOff,
}): UsagePreferences => {
const legacyPins = pinned && pinned.length > 0 ? pinned : null;
const legacyVisibility =
cardsOff && cardsOff.length > 0
? Object.fromEntries(cardsOff.map((id) => [id, false] as const))
: {};
return {
displayAs,
pins: pins === undefined ? legacyPins : pins,
serverId,
cardOrder: cardOrder ?? [],
cardVisibility: cardVisibility ?? legacyVisibility,
};
},
)
.catch(DEFAULT_USAGE_PREFERENCES);
function samePin(a: UsagePin, b: UsagePin): boolean {
@@ -154,8 +171,8 @@ export function usageReportsOn(
reports: readonly UsageReportEntry[],
preferences: UsagePreferences,
): UsageReportEntry[] {
return arrangeUsageReports(reports, preferences).filter(
(entry) => !isUsageCardOff(preferences, entry.id),
return arrangeUsageReports(reports, preferences).filter((entry) =>
isUsageCardOn(preferences, entry),
);
}
@@ -188,8 +205,14 @@ export function arrangeUsageCards(
return { ...preferences, cardOrder: rest };
}
export function isUsageCardOff(preferences: UsagePreferences, reportId: string): boolean {
return preferences.cardsOff.includes(reportId);
/** Whether a report card is shown, honoring an explicit user override before the host's default hint. */
export function isUsageCardOn(
preferences: UsagePreferences,
entry: Pick<UsageReportEntry, "id" | "defaultEnabled">,
): boolean {
const explicit = preferences.cardVisibility[entry.id];
if (explicit !== undefined) return explicit;
return entry.defaultEnabled !== false;
}
export function setUsageCardOn(
@@ -197,6 +220,8 @@ export function setUsageCardOn(
reportId: string,
on: boolean,
): UsagePreferences {
const others = preferences.cardsOff.filter((id) => id !== reportId);
return { ...preferences, cardsOff: on ? others : [...others, reportId] };
return {
...preferences,
cardVisibility: { ...preferences.cardVisibility, [reportId]: on },
};
}
+8 -4
View File
@@ -4,7 +4,6 @@ import { View } from "react-native";
import { AdaptiveModalSheet, SheetHeaderSubtitle } from "@/components/adaptive-modal-sheet";
import { builtinSidebarNavLabelKey } from "@/sidebar-nav/model";
import { useHostUsageWithControls } from "./controls";
import { useUsageDisplay } from "./display";
import { getHostPickerLabel } from "@/components/hosts/host-picker";
import { hasHostChoice, useUsageHostSelection } from "./hosts";
import type { UsageHost } from "./model";
@@ -50,8 +49,7 @@ function HostUsageModal({
() => ({ hosts, serverId, onSelect: onSelectHost }),
[hosts, onSelectHost, serverId],
);
const { view, refresh, controls } = useHostUsageWithControls(hostSelection);
const { display } = useUsageDisplay(view.kind === "ready" ? view.reports : []);
const { view, display, refresh, controls, openOptions } = useHostUsageWithControls(hostSelection);
const hostLabel = hasHostChoice(hostSelection)
? getHostPickerLabel(hostSelection.hosts, hostSelection.serverId)
: undefined;
@@ -61,7 +59,13 @@ function HostUsageModal({
host's cards. The frame is not keyed: remounting it would dismiss a compact sheet, and Usage
with it. */}
<View key={serverId} testID={`usage-host-${serverId}`}>
<UsageBody serverId={serverId} view={view} display={display} onRefresh={refresh} />
<UsageBody
serverId={serverId}
view={view}
display={display}
onRefresh={refresh}
onOpenSources={openOptions}
/>
</View>
</UsageModalFrame>
);
+50 -9
View File
@@ -1,5 +1,5 @@
import { useTranslation } from "react-i18next";
import { useMemo } from "react";
import { useCallback, useMemo, useState } from "react";
import { Text, View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { Alert } from "@/components/ui/alert";
@@ -27,14 +27,31 @@ export function UsageSection({
onRefresh: () => void;
testID?: string;
}) {
const [optionsOpen, setOptionsOpen] = useState(false);
const openOptions = useCallback(() => setOptionsOpen(true), []);
const trailing = useMemo(
() => <UsageControls serverId={serverId} view={view} onRefresh={onRefresh} />,
[onRefresh, view, serverId],
() => (
<UsageControls
serverId={serverId}
view={view}
display={display}
onRefresh={onRefresh}
optionsOpen={optionsOpen}
onOptionsOpenChange={setOptionsOpen}
/>
),
[display, onRefresh, optionsOpen, serverId, view],
);
return (
<SettingsSection title={title} testID={testID} trailing={trailing}>
<UsageBody serverId={serverId} view={view} display={display} onRefresh={onRefresh} />
<UsageBody
serverId={serverId}
view={view}
display={display}
onRefresh={onRefresh}
onOpenSources={openOptions}
/>
</SettingsSection>
);
}
@@ -45,14 +62,23 @@ export function UsageBody({
view,
display,
onRefresh,
onOpenSources,
}: {
serverId: string;
view: UsageView;
display: UsageDisplay;
onRefresh: () => void;
onOpenSources?: () => void;
}) {
const { t } = useTranslation();
const setting = useUsageSetting(serverId);
const visibleReports = useMemo(
() =>
view.kind === "ready"
? display.arrange(view.reports).filter((entry) => display.isCardOn(entry))
: [],
[display, view],
);
if (view.kind === "off")
return (
<View>
@@ -84,16 +110,30 @@ export function UsageBody({
);
}
let content: React.ReactNode;
if (view.reports.length === 0) {
content = <UsageMessage text={t("providerUsage.empty")} />;
} else if (visibleReports.length === 0) {
content = (
<View style={[settingsStyles.card, styles.emptyCard]} testID="usage-all-hidden">
<Text style={styles.emptyText}>{t("providerUsage.allSourcesHidden")}</Text>
{onOpenSources ? (
<Button variant="outline" onPress={onOpenSources} testID="usage-choose-sources">
{t("providerUsage.chooseSources")}
</Button>
) : null}
</View>
);
} else {
content = <UsageList serverId={serverId} reports={visibleReports} display={display} />;
}
return (
<View style={styles.reports}>
{view.refreshFailed ? (
<Alert size="sm" variant="error" title={t("providerUsage.refreshFailed")} />
) : null}
{view.reports.length === 0 ? (
<UsageMessage text={t("providerUsage.empty")} />
) : (
<UsageList serverId={serverId} reports={view.reports} display={display} />
)}
{content}
</View>
);
}
@@ -110,6 +150,7 @@ const styles = StyleSheet.create((theme) => ({
reports: { gap: theme.spacing[3] },
emptyCard: {
padding: theme.spacing[4],
gap: theme.spacing[3],
alignItems: "center",
},
emptyText: {
+4
View File
@@ -65,6 +65,8 @@ export interface UsageAccount {
label?: string;
/** Harness owning this login, e.g. Codex, OpenCode, Pi or OMP. */
harness?: string;
/** Provider ID associated with this login, used as a hint for default visibility. */
provider?: string;
/** Store locator, opaque to the daemon. */
input: JsonValue;
}
@@ -87,6 +89,8 @@ export interface UsageSourceRegistration {
icon?: string;
/** Provider whose resolved launch is needed for discovery. */
provider?: string;
/** Provider IDs associated with this source, used as a hint for default visibility. */
providers?: readonly string[];
input: ZodType;
/** Accounts for this scope only. The same key in any scope identifies the same account. */
discover(scope: UsageScope): Promise<UsageAccount[]>;
+2
View File
@@ -7083,6 +7083,8 @@ export const UsageReportEntrySchema = z.object({
sourceId: z.string(),
sourceLabel: z.string(),
icon: z.string().optional(),
/** Host hint for whether this report starts shown until the user overrides it. Absent means true. */
defaultEnabled: z.boolean().optional(),
report: UsageReportSchema,
// Successful completion time; fetchedAt remains the attempt timestamp for ordering.
successfulAt: z.string().optional(),
@@ -535,6 +535,9 @@ test("usage entries accept older failures and additive successful snapshots", ()
successfulAt: "2026-10-17T10:00:15Z",
};
expect(UsageReportEntrySchema.parse(available)).toEqual(available);
const hintedOff = { ...available, defaultEnabled: false };
expect(UsageReportEntrySchema.parse(hintedOff)).toEqual(hintedOff);
expect(UsageReportEntrySchema.omit({ defaultEnabled: true }).parse(hintedOff)).toEqual(available);
expect(
UsageReportEntrySchema.omit({ lastSuccessful: true, successfulAt: true }).parse(available),
).toEqual({ ...oldEntry, report: available.report });
@@ -3856,3 +3856,68 @@ test("model overrides preserve negotiated plugin capabilities and connection shu
manager.destroy();
}
});
test("isProviderActiveForUsage rechecks on forceRefresh and enforces a real timeout deadline", async () => {
let codexAvailable = false;
let codexChecks = 0;
let copilotSignalAborted = false;
const manager = new ProviderSnapshotManager({
logger: createTestLogger(),
extraClients: {
codex: createExtraClient("codex", {
async isAvailable() {
codexChecks += 1;
return codexAvailable;
},
}),
copilot: createExtraClient("copilot", {
isAvailable(signal) {
signal?.addEventListener("abort", () => {
copilotSignalAborted = true;
});
// Simulate a plugin provider RPC that ignores AbortSignal and hangs indefinitely.
return new Promise<boolean>(() => {});
},
}),
},
});
try {
// Prime the global snapshot while codex is unavailable.
await manager.getProvider({ provider: "codex", wait: true });
expect(await manager.isProviderActiveForUsage("codex")).toBe(false);
const checksAfterSnapshot = codexChecks;
// Install codex externally; a forced Usage refresh re-probes and persists the fresh result.
codexAvailable = true;
expect(await manager.isProviderActiveForUsage("codex", { forceRefresh: true })).toBe(true);
expect(codexChecks).toBeGreaterThan(checksAfterSnapshot);
// Subsequent non-forced reads keep the fresher probe result instead of falling back to the
// older unavailable snapshot.
const checksAfterForce = codexChecks;
expect(await manager.isProviderActiveForUsage("codex")).toBe(true);
expect(codexChecks).toBe(checksAfterForce);
// Refreshing Providers after uninstalling codex updates the shared availability reading even
// though an unavailable snapshot entry carries no fetchedAt.
codexAvailable = false;
await manager.refreshSettingsSnapshot({ providers: ["codex"] });
const checksAfterSettingsRefresh = codexChecks;
expect(await manager.isProviderActiveForUsage("codex")).toBe(false);
expect(codexChecks).toBe(checksAfterSettingsRefresh);
// Once the TTL elapses, a normal read re-probes automatically.
codexAvailable = true;
expect(await manager.isProviderActiveForUsage("codex", { ttlMs: 0 })).toBe(true);
expect(codexChecks).toBeGreaterThan(checksAfterSettingsRefresh);
// A hung non-abortable provider check resolves at the deadline instead of blocking callers.
const started = Date.now();
expect(await manager.isProviderActiveForUsage("copilot", { timeoutMs: 30 })).toBe(true);
expect(Date.now() - started).toBeLessThan(1_000);
expect(copilotSignalAborted).toBe(true);
} finally {
await manager.shutdown();
manager.destroy();
}
});
@@ -62,6 +62,8 @@ import {
const DEFAULT_REFRESH_TIMEOUT_MS = 120_000;
const MAX_REFRESH_TIMEOUT_MS = 2_147_483_647;
const DEFAULT_DIAGNOSTIC_TIMEOUT_MS = 120_000;
const USAGE_PROVIDER_ACTIVITY_TIMEOUT_MS = 5_000;
const USAGE_PROVIDER_ACTIVITY_TTL_MS = 300_000;
const PROVIDER_REFRESH_DEADLINE_ENV = "PASEO_PROVIDER_REFRESH_TIMEOUT_MS";
/** How long shutdown waits for aborted probes; a provider ignoring the abort must not hang it. */
const PROBE_SHUTDOWN_GRACE_MS = 10_000;
@@ -266,6 +268,7 @@ interface ProviderSnapshotTarget {
export class ProviderSnapshotManager {
private readonly catalogs = new Map<string, Map<AgentProvider, ProviderCatalog>>();
private readonly targets = new Map<string, Target>();
private readonly usageActivityCache = new Map<AgentProvider, { at: number; active: boolean }>();
private readonly events = new EventEmitter();
private destroyed = false;
/** Aborts provider work in flight when the manager stops. */
@@ -529,6 +532,87 @@ export class ProviderSnapshotManager {
return this.ensureClient(provider, definition).resolveUsageLaunch?.();
}
/**
* Whether `provider` (or a custom provider derived from it) is enabled and installed on this
* host. Used as a hint for whether discovered usage accounts start shown.
*/
async isProviderActiveForUsage(
provider: string,
options: { forceRefresh?: boolean; timeoutMs?: number; ttlMs?: number } = {},
): Promise<boolean> {
const matching = this.generation.order
.map((id) => ({ id, definition: this.generation.definitions[id] }))
.filter(
(candidate): candidate is { id: AgentProvider; definition: ProviderDefinition } =>
candidate.definition !== undefined &&
candidate.definition.enabled &&
(candidate.id === provider || candidate.definition.derivedFromProviderId === provider),
);
if (matching.length === 0) return false;
const forceRefresh = options.forceRefresh === true;
const ttlMs = options.ttlMs ?? USAGE_PROVIDER_ACTIVITY_TTL_MS;
const timeoutMs = options.timeoutMs ?? USAGE_PROVIDER_ACTIVITY_TIMEOUT_MS;
const now = Date.now();
const unresolved: Array<{ id: AgentProvider; definition: ProviderDefinition }> = [];
if (forceRefresh) {
unresolved.push(...matching);
} else {
for (const candidate of matching) {
const cached = this.usageActivityCache.get(candidate.id);
if (cached && now - cached.at < ttlMs) {
if (cached.active) return true;
continue;
}
unresolved.push(candidate);
}
if (unresolved.length === 0) return false;
}
const results = await Promise.all(
unresolved.map(({ id, definition }) => this.probeUsageActivity(id, definition, timeoutMs)),
);
return results.some(Boolean);
}
private async probeUsageActivity(
provider: AgentProvider,
definition: ProviderDefinition,
timeoutMs: number,
): Promise<boolean> {
const generation = this.generation;
const controller = new AbortController();
const timedOut = Symbol("usage-provider-activity-timeout");
let timer: ReturnType<typeof setTimeout> | undefined;
const deadline = new Promise<typeof timedOut>((finish) => {
timer = setTimeout(() => {
controller.abort();
finish(timedOut);
}, timeoutMs);
});
const probe = this.ensureClient(provider, definition)
.isAvailable(controller.signal, { scope: "global", force: true })
.then(
(active) => ({ ok: true as const, active }),
() => ({ ok: false as const, active: false }),
);
try {
const outcome = await Promise.race([probe, deadline]);
if (outcome === timedOut) {
// Fail open without caching when a slow probe misses the deadline; a subsequent read
// picks up the real status once the provider snapshot finishes loading.
return true;
}
if (outcome.ok && this.generation === generation) {
this.usageActivityCache.set(provider, { at: Date.now(), active: outcome.active });
}
return outcome.active;
} finally {
if (timer) clearTimeout(timer);
}
}
async listProviders(input: ProviderSnapshotReadOptions = {}): Promise<ProviderSnapshotEntry[]> {
const target = resolveProviderSnapshotTarget(input.cwd);
if (input.wait) {
@@ -723,6 +807,7 @@ export class ProviderSnapshotManager {
): void {
for (const provider of changed) {
this.generation.providerStates.get(provider)?.discoveryLimit.clearQueue();
this.usageActivityCache.delete(provider);
}
this.generation = generation;
this.providerClients = clients;
@@ -1089,6 +1174,12 @@ export class ProviderSnapshotManager {
publish: (entry, { incomplete }) => {
if (!isCurrent()) return false;
const result = identifyEntry(structuredClone(entry));
const boundTargets = [...this.targets].flatMap(([cwd, target]) =>
target.bindings.get(provider)?.key === key ? [cwd] : [],
);
const isGlobal =
catalogOptions.scope === "global" ||
boundTargets.includes(resolveProviderSnapshotTarget().snapshotCwd);
if (
background &&
current.result &&
@@ -1106,12 +1197,25 @@ export class ProviderSnapshotManager {
"Background provider refresh failed; keeping the last catalogue",
);
}
if (
isGlobal &&
(entry.status === "ready" ||
(entry.status === "unavailable" && current.result.entry.status !== "ready"))
) {
this.usageActivityCache.set(provider, {
at: Date.now(),
active: entry.status === "ready",
});
}
return false;
}
current.result = result;
const boundTargets = [...this.targets].flatMap(([cwd, target]) =>
target.bindings.get(provider)?.key === key ? [cwd] : [],
);
if (isGlobal && (entry.status === "ready" || entry.status === "unavailable")) {
this.usageActivityCache.set(provider, {
at: Date.now(),
active: entry.status === "ready",
});
}
this.publishTargets(boundTargets);
return true;
},
+2
View File
@@ -687,6 +687,8 @@ export async function createPaseoDaemon(
hasAgent: (id) => agentManager.getAgent(id) !== null,
usageSession: (id) => agentManager.usageSession(id),
resolveLaunch: (provider) => providerSnapshotManager.resolveUsageLaunch(provider),
isProviderActive: (provider, options) =>
providerSnapshotManager.isProviderActiveForUsage(provider, options),
},
managedSources: new ManagedPluginSources(config.paseoHome, {
registries: config.pluginRegistries,
@@ -712,6 +712,7 @@ export class PluginService {
id: source.id,
label: source.label,
icon: source.icon,
providers: source.providers ?? (source.provider ? [source.provider] : undefined),
discover: async (scope) => {
const launch =
scope.kind === "global" && source.provider
@@ -43,6 +43,7 @@ export interface PluginUsageSourceMetadata {
id: string;
label: string;
provider?: string;
providers?: string[];
icon?: string;
}
@@ -199,6 +200,7 @@ const usageSourceMetadataSchema = z
id: z.string().min(1),
label: z.string().min(1),
provider: z.string().min(1).optional(),
providers: z.array(z.string().min(1)).optional(),
icon: z.string().optional(),
})
.strict();
@@ -231,7 +231,10 @@ export function createPluginWorker(options: {
typeof source.fetch !== "function" ||
typeof source.discover !== "function" ||
!source.input ||
typeof source.input.parseAsync !== "function"
typeof source.input.parseAsync !== "function" ||
(source.providers !== undefined &&
(!Array.isArray(source.providers) ||
source.providers.some((provider) => typeof provider !== "string" || !provider.trim())))
) {
throw new Error(`Invalid usage source: ${source.id}`);
}
@@ -492,6 +495,7 @@ export function createPluginWorker(options: {
id: source.id,
label: source.label,
provider: source.provider,
providers: source.providers ? [...source.providers] : undefined,
icon: source.icon
? await readPluginProviderIcon(message.pluginDirectory, source.icon)
: undefined,
@@ -179,12 +179,16 @@ test("#7142: host usage retains distinct Cursor accounts after their individual
function source(input: {
id: string;
discover?: () => Promise<Array<{ key: string; label?: string; input: unknown }>>;
providers?: readonly string[];
discover?: () => Promise<
Array<{ key: string; label?: string; harness?: string; provider?: string; input: unknown }>
>;
fetch?: (value: unknown) => Promise<unknown>;
}) {
return {
id: input.id,
label: input.id,
...(input.providers ? { providers: input.providers } : {}),
discover: input.discover ?? (async () => []),
fetch: input.fetch ?? (async () => ({ status: "available", windows: [] })),
};
@@ -937,3 +941,119 @@ test("failed discovery preserves history until discovery confirms account remova
present = true;
expect((await registry.listReports())[0]?.lastSuccessful).toBeUndefined();
});
test("uses provider activity as a defaultEnabled hint without blocking discovery", async () => {
const activeProviders = new Set(["claude"]);
const registry = new UsageSourceRegistry(Date.now, 300_000, undefined, {
hasAgent: () => false,
usageSession: () => null,
isProviderActive: async (provider) => activeProviders.has(provider),
});
registry.register(
source({
id: "claude",
providers: ["claude", "pi"],
discover: async () => [
{ key: "cli", provider: "claude", input: "cli" },
{ key: "pi-only", provider: "pi", input: "pi" },
],
}),
);
registry.register(
source({
id: "copilot",
providers: ["copilot"],
discover: async () => [{ key: "default", input: {} }],
}),
);
registry.register(
source({
id: "openrouter",
discover: async () => [{ key: "default", input: {} }],
}),
);
const byId = (reports: Awaited<ReturnType<typeof registry.listReports>>) =>
Object.fromEntries(reports.map((entry) => [entry.id, entry.defaultEnabled]));
expect(byId(await registry.listReports())).toEqual({
"claude:cli": undefined,
"claude:pi-only": false,
"copilot:default": false,
"openrouter:default": undefined,
});
// Enabling a provider updates defaultEnabled on the next read without waiting for fetch cache expiry.
activeProviders.add("copilot");
expect(byId(await registry.listReports())).toEqual({
"claude:cli": undefined,
"claude:pi-only": false,
"copilot:default": undefined,
"openrouter:default": undefined,
});
});
test("streams unrelated usage reports without waiting on a slow provider check and forwards forceRefresh", async () => {
let resolveSlowCheck: ((active: boolean) => void) | undefined;
const forceRefreshSeen: Array<{ provider: string; forceRefresh?: boolean }> = [];
const registry = new UsageSourceRegistry(Date.now, 300_000, undefined, {
hasAgent: () => false,
usageSession: () => null,
isProviderActive: (provider, options) => {
forceRefreshSeen.push({ provider, forceRefresh: options?.forceRefresh });
if (provider === "slow") {
return new Promise<boolean>((resolve) => {
resolveSlowCheck = resolve;
});
}
return Promise.resolve(true);
},
});
registry.register(
source({
id: "slow-source",
providers: ["slow"],
discover: async () => [{ key: "default", input: {} }],
}),
);
registry.register(
source({
id: "fast-source",
providers: ["fast"],
discover: async () => [{ key: "default", input: {} }],
}),
);
registry.register(
source({
id: "unhinted",
discover: async () => [{ key: "default", input: {} }],
}),
);
const streamed: string[] = [];
let fastStreamed!: () => void;
const bothFastStreamed = new Promise<void>((resolve) => {
fastStreamed = resolve;
});
const pending = registry.listReports({
forceRefresh: true,
onReport: (report) => {
streamed.push(report.id);
if (streamed.includes("fast-source:default") && streamed.includes("unhinted:default")) {
fastStreamed();
}
},
});
await bothFastStreamed;
expect(streamed).not.toContain("slow-source:default");
expect(forceRefreshSeen).toContainEqual({ provider: "slow", forceRefresh: true });
expect(forceRefreshSeen).toContainEqual({ provider: "fast", forceRefresh: true });
resolveSlowCheck?.(false);
const reports = await pending;
expect(reports.find((entry) => entry.id === "slow-source:default")?.defaultEnabled).toBe(false);
expect(
reports.find((entry) => entry.id === "fast-source:default")?.defaultEnabled,
).toBeUndefined();
});
@@ -15,6 +15,8 @@ export interface UsageSource {
id: string;
label: string;
icon?: string;
/** Provider IDs associated with this source, used as a hint for default visibility. */
providers?: readonly string[];
discover(scope: UsageScope): Promise<unknown>;
fetch(input: unknown): Promise<unknown>;
}
@@ -22,6 +24,7 @@ export interface UsageSource {
interface Login {
input: unknown;
harness: string;
provider?: string;
}
interface KnownReport {
@@ -36,6 +39,8 @@ export interface AgentUsageLookup {
resolveLaunch?(
provider: string,
): Promise<import("@getpaseo/plugin/server/provider").ProviderLaunch | undefined>;
/** Whether the provider (or a custom provider derived from it) is installed and enabled. */
isProviderActive?(provider: string, options?: { forceRefresh?: boolean }): Promise<boolean>;
}
export interface ListUsageReportsOptions {
@@ -104,20 +109,67 @@ export class UsageSourceRegistry {
this.mergeKnown();
ids = [...this.known.keys()];
}
const uniqueIds = [...new Set(ids)];
const checkProvider =
options.agentId === undefined
? this.createProviderActivityChecker(options.forceRefresh)
: undefined;
return Promise.all(
[...new Set(ids)].flatMap((id) => {
uniqueIds.flatMap((id) => {
const known = reports.get(id);
if (!known) return [];
// Resolve each report's provider hint alongside its fetch so a slow provider probe
// never blocks unrelated reports from fetching or streaming.
return [
this.fetchId(id, known, options.forceRefresh).then((entry) => {
options.onReport?.(entry);
return entry;
Promise.all([
this.fetchId(id, known, options.forceRefresh),
this.resolveDefaultEnabled(known, checkProvider),
]).then(([entry, defaultEnabled]) => {
const stamped = defaultEnabled === false ? { ...entry, defaultEnabled: false } : entry;
options.onReport?.(stamped);
return stamped;
}),
];
}),
);
}
private hintedProviders(known: KnownReport): string[] {
const fromLogins = [
...new Set(known.logins.flatMap((login) => (login.provider ? [login.provider] : []))),
];
if (fromLogins.length > 0) return fromLogins;
return known.source.providers ? [...new Set(known.source.providers)] : [];
}
private createProviderActivityChecker(
forceRefresh?: boolean,
): ((provider: string) => Promise<boolean>) | undefined {
const isProviderActive = this.agents.isProviderActive;
if (!isProviderActive) return undefined;
const checks = new Map<string, Promise<boolean>>();
return (provider: string) => {
const existing = checks.get(provider);
if (existing) return existing;
const check = isProviderActive(provider, { forceRefresh }).catch((error) => {
this.logger.warn({ provider, err: error }, "Usage provider availability hint failed");
return true;
});
checks.set(provider, check);
return check;
};
}
private async resolveDefaultEnabled(
known: KnownReport,
checkProvider: ((provider: string) => Promise<boolean>) | undefined,
): Promise<boolean | undefined> {
if (!checkProvider) return undefined;
const hinted = this.hintedProviders(known);
if (hinted.length === 0) return undefined;
return (await anyTrue(hinted.map(checkProvider))) ? undefined : false;
}
private pruneAgents(): void {
for (const id of this.byAgent.keys()) {
if (!this.agents.hasAgent(id)) this.byAgent.delete(id);
@@ -197,6 +249,7 @@ export class UsageSourceRegistry {
key: z.string().regex(/^[A-Za-z0-9._-]{1,128}$/),
label: z.string().optional(),
harness: z.string().min(1).optional(),
provider: z.string().min(1).optional(),
input: z.json(),
}),
)
@@ -205,7 +258,11 @@ export class UsageSourceRegistry {
const id = `${source.id}:${account.key}`;
const known = reports.get(id);
// COMPAT(usageLoginHarness): added in v0.11.0, remove after 2027-04-05 once plugin floor >= v0.11.0.
const login = { input: account.input, harness: account.harness ?? source.label };
const login: Login = {
input: account.input,
harness: account.harness ?? source.label,
...(account.provider ? { provider: account.provider } : {}),
};
if (known) {
if (!known.logins.some((existing) => loginKey(existing) === loginKey(login)))
known.logins.push(login);
@@ -390,3 +447,28 @@ function cacheIdentity(id: string, known: KnownReport): string {
.update(JSON.stringify([known.label, known.logins.map(loginKey)]))
.digest("hex")}`;
}
/** Resolves true as soon as any check resolves true, or false once every check resolves false. */
function anyTrue(checks: readonly Promise<boolean>[]): Promise<boolean> {
if (checks.length === 0) return Promise.resolve(false);
return new Promise((resolve) => {
let remaining = checks.length;
let settled = false;
for (const check of checks) {
void (async () => {
const value = await check;
if (settled) return;
if (value) {
settled = true;
resolve(true);
return;
}
remaining -= 1;
if (remaining === 0) {
settled = true;
resolve(false);
}
})();
}
});
}
@@ -7,6 +7,7 @@ export default function contribute(server: PluginServerContext) {
id: "claude",
label: "Claude",
icon: "icon.svg",
providers: ["claude", "pi", "omp"],
input: inputSchema,
discover: (scope) => discover(scope),
fetch: fetchUsage,
@@ -142,6 +142,7 @@ describe("Claude credential routes", () => {
{
key: "fixture-account.fixture-org",
harness: "Claude",
provider: "claude",
input: {
route: { store: "claude", path: join(dir, ".credentials.json") },
accountKey: "fixture-account.fixture-org",
@@ -252,6 +252,7 @@ test("keychain identity belongs to its token even when Claude Code metadata name
expect(identity).toEqual({
key: "pi-account.pi-org",
harness: "Claude",
provider: "claude",
input: {
route: { store: "keychain", service: "Claude Code-credentials", account: "fixture-user" },
accountKey: "pi-account.pi-org",
@@ -916,6 +916,7 @@ it("keeps an expired Keychain login without calling the network and prefers Keyc
{
key: expect.stringMatching(/^[a-f0-9]{64}$/),
harness: "Claude",
provider: "claude",
input: {
route: { store: "keychain", service: "Claude Code-credentials", account: "fixture" },
},
@@ -966,6 +967,7 @@ it.each([401, 403])("a rejected profile HTTP %i keeps a locator-keyed account",
{
key: expect.stringMatching(/^[a-f0-9]{64}$/),
harness: "Claude",
provider: "claude",
input: credentialInput(lookup.claudeHome),
},
]);
@@ -1000,7 +1002,12 @@ it.each([
};
const accounts = await discover({ kind: "global" }, lookup, api);
expect(accounts).toEqual([
{ key: hashAccountKey(JSON.stringify(input.route)), harness: "Claude", input },
{
key: hashAccountKey(JSON.stringify(input.route)),
harness: "Claude",
provider: "claude",
input,
},
]);
await expect(fetchUsage(accounts[0]!.input as UsageInput, api, lookup)).rejects.toThrow(error);
},
@@ -1084,6 +1091,7 @@ it("session discovery reads only its Claude home and excludes foreign sessions",
key: "session-account.org",
label: "session@example.test",
harness: "Claude",
provider: "claude",
input: { ...credentialInput(home), accountKey: "session-account.org" },
},
]);
+3 -2
View File
@@ -385,7 +385,8 @@ export async function discover(
const harness = { pi: "Pi", omp: "OMP", claude: "Claude", keychain: "Claude" }[
input.route.store
];
const fallback = { key: hashAccountKey(JSON.stringify(input.route)), harness, input };
const provider = input.route.store === "keychain" ? "claude" : input.route.store;
const fallback = { key: hashAccountKey(JSON.stringify(input.route)), harness, provider, input };
if (credentials.expires !== undefined && credentials.expires <= (lookup.now ?? Date.now)()) {
accounts.push(fallback);
continue;
@@ -399,7 +400,7 @@ export async function discover(
accounts.push(
"status" in profile
? fallback
: { ...profile, harness, input: { ...input, accountKey: profile.key } },
: { ...profile, harness, provider, input: { ...input, accountKey: profile.key } },
);
} catch {
// Keep the login visible; fetching usage reports the vendor failure.
@@ -7,6 +7,7 @@ export default function contribute(server: PluginServerContext) {
id: "codex",
label: "Codex",
icon: "icon.svg",
providers: ["codex", "opencode", "pi", "omp"],
input: inputSchema,
discover: (scope) => discover(scope),
fetch: fetchUsage,
+6 -1
View File
@@ -73,7 +73,12 @@ export async function discover(
for (const input of candidates) {
const auth = await readAuth(input, lookup);
if (auth)
present.push({ ...accountIdentity(auth, input), harness: harnessLabel(input), input });
present.push({
...accountIdentity(auth, input),
harness: harnessLabel(input),
provider: input.route.store,
input,
});
}
return present;
}
@@ -7,6 +7,7 @@ export default function contribute(server: PluginServerContext) {
id: "copilot",
label: "GitHub Copilot",
icon: "icon.svg",
providers: ["copilot"],
input: inputSchema,
discover: (scope) => (scope.kind === "global" ? discover() : Promise.resolve([])),
fetch: fetchUsage,
@@ -7,6 +7,7 @@ export default function contribute(server: PluginServerContext) {
id: "cursor",
label: "Cursor",
icon: "icon.svg",
providers: ["cursor"],
input: inputSchema,
discover: (scope) => (scope.kind === "global" ? discover() : discoverSession(scope)),
fetch: fetchUsage,
@@ -7,6 +7,7 @@ export default function contribute(server: PluginServerContext) {
id: "kimi",
label: "Kimi",
icon: "icon.svg",
providers: ["kimi"],
input: inputSchema,
discover: (scope) => (scope.kind === "global" ? discover() : Promise.resolve([])),
fetch: fetchUsage,
+1
View File
@@ -63,6 +63,7 @@ export class Usage {
id: "muse",
label: "Muse Code",
icon: "icon.svg",
providers: ["muse"],
input: inputSchema,
discover: async (scope) => {
let accounts: string[];
@@ -7,6 +7,7 @@ export default function contribute(server: PluginServerContext) {
id: "opencode-go",
label: "OpenCode Go",
icon: "icon.svg",
providers: ["opencode"],
input: inputSchema,
discover: (scope) => (scope.kind === "global" ? discover() : Promise.resolve([])),
fetch: fetchUsage,