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.
This commit is contained in:
Mohamed Boudra
2026-11-22 09:02:07 +01:00
parent ede181d39a
commit 5dbf156b7e
44 changed files with 717 additions and 202 deletions
+104 -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,106 @@ 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`);
await openUsageSources(page);
await expect(page.getByTestId("usage-source-toggle-claude:default")).toHaveAttribute(
"aria-checked",
"true",
);
await expect(page.getByTestId("usage-source-toggle-copilot:default")).toHaveAttribute(
"aria-checked",
"false",
);
await expect(page.getByTestId("usage-source-toggle-copilot:default")).toContainText(
"Provider not installed",
);
await qaScreenshot(page, `usage-sources-${size}-list`);
// Opting into a default-off source brings its card and summary window in immediately.
await page.getByTestId("usage-source-toggle-cursor:default").click();
await expect(page.getByTestId("usage-source-toggle-cursor:default")).toHaveAttribute(
"aria-checked",
"true",
);
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") {
@@ -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}}",
providerNotInstalled: "المزود غير مثبت",
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}}",
providerNotInstalled: "Provider not installed",
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}}",
providerNotInstalled: "Proveedor no instalado",
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}}",
providerNotInstalled: "Fournisseur non installé",
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}}",
providerNotInstalled: "プロバイダー未インストール",
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}}",
providerNotInstalled: "제공업체가 설치되지 않음",
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}}",
providerNotInstalled: "Provedor não instalado",
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}}",
providerNotInstalled: "Провайдер не установлен",
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}}",
providerNotInstalled: "未安装提供商",
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
+114 -20
View File
@@ -2,10 +2,11 @@ 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,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSubTrigger,
type MenuPageDefinition,
} from "@/components/ui/dropdown-menu";
@@ -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,61 @@ function UsageHostPage({ hostSelection }: { hostSelection: UsageHostSelection })
</>
);
}
function UsageSourcesPage({
reports,
display,
}: {
reports: readonly UsageReportEntry[];
display: UsageDisplay;
}) {
const { t } = useTranslation();
const notInstalledLabel = t("providerUsage.providerNotInstalled");
return (
<>
{reports.map((entry) => (
<UsageSourceMenuItem
key={entry.id}
entry={entry}
on={display.isCardOn(entry)}
onToggle={display.setCardOn}
notInstalledLabel={notInstalledLabel}
/>
))}
</>
);
}
function UsageSourceMenuItem({
entry,
on,
onToggle,
notInstalledLabel,
}: {
entry: UsageReportEntry;
on: boolean;
onToggle: (reportId: string, on: boolean) => void;
notInstalledLabel: 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 ? notInstalledLabel : null]
.filter(Boolean)
.join(" · ") || undefined;
return (
<DropdownMenuItem
leading={leading}
description={description}
selected={on}
closeOnSelect={false}
onSelect={handleSelect}
testID={`usage-source-toggle-${entry.id}`}
>
{entry.sourceLabel}
</DropdownMenuItem>
);
}
+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
@@ -7082,6 +7082,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 });
@@ -529,6 +529,48 @@ 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): 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 homeTarget = this.targets.get(resolveProviderSnapshotTarget().snapshotCwd);
const unresolved: Array<{ id: AgentProvider; definition: ProviderDefinition }> = [];
for (const candidate of matching) {
const entry = homeTarget?.snapshot.records.find(
(record) => record.entry.provider === candidate.id,
)?.entry;
if (entry?.status === "ready") return true;
if (entry?.status === "unavailable") continue;
unresolved.push(candidate);
}
if (unresolved.length === 0) return false;
const results = await Promise.all(
unresolved.map(async ({ id, definition }) => {
try {
return await this.ensureClient(id, definition).isAvailable(AbortSignal.timeout(5_000), {
scope: "global",
force: false,
});
} catch {
return false;
}
}),
);
return results.some(Boolean);
}
async listProviders(input: ProviderSnapshotReadOptions = {}): Promise<ProviderSnapshotEntry[]> {
const target = resolveProviderSnapshotTarget(input.cwd);
if (input.wait) {
+1
View File
@@ -686,6 +686,7 @@ export async function createPaseoDaemon(
hasAgent: (id) => agentManager.getAgent(id) !== null,
usageSession: (id) => agentManager.usageSession(id),
resolveLaunch: (provider) => providerSnapshotManager.resolveUsageLaunch(provider),
isProviderActive: (provider) => providerSnapshotManager.isProviderActiveForUsage(provider),
},
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
@@ -42,6 +42,7 @@ export interface PluginUsageSourceMetadata {
id: string;
label: string;
provider?: string;
providers?: string[];
icon?: string;
}
@@ -197,6 +198,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();
@@ -226,7 +226,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}`);
}
@@ -486,6 +489,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,54 @@ 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,
});
});
@@ -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): Promise<boolean>;
}
export interface ListUsageReportsOptions {
@@ -104,20 +109,72 @@ export class UsageSourceRegistry {
this.mergeKnown();
ids = [...this.known.keys()];
}
const uniqueIds = [...new Set(ids)];
const activeProviders =
options.agentId === undefined
? await this.resolveProviderActivity(uniqueIds, reports)
: undefined;
return Promise.all(
[...new Set(ids)].flatMap((id) => {
uniqueIds.flatMap((id) => {
const known = reports.get(id);
if (!known) return [];
const defaultEnabled = activeProviders
? this.resolveDefaultEnabled(known, activeProviders)
: undefined;
return [
this.fetchId(id, known, options.forceRefresh).then((entry) => {
options.onReport?.(entry);
return entry;
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 async resolveProviderActivity(
ids: readonly string[],
reports: ReadonlyMap<string, KnownReport>,
): Promise<Map<string, boolean> | undefined> {
const isProviderActive = this.agents.isProviderActive;
if (!isProviderActive) return undefined;
const providerIds = new Set<string>();
for (const id of ids) {
const known = reports.get(id);
if (!known) continue;
for (const provider of this.hintedProviders(known)) providerIds.add(provider);
}
if (providerIds.size === 0) return undefined;
const results = await Promise.all(
[...providerIds].map(async (provider) => {
try {
return [provider, await isProviderActive(provider)] as const;
} catch (error) {
this.logger.warn({ provider, err: error }, "Usage provider availability hint failed");
return [provider, true] as const;
}
}),
);
return new Map(results);
}
private resolveDefaultEnabled(
known: KnownReport,
activeProviders: ReadonlyMap<string, boolean>,
): boolean | undefined {
const hinted = this.hintedProviders(known);
if (hinted.length === 0) return undefined;
return hinted.some((provider) => activeProviders.get(provider) !== false) ? undefined : false;
}
private pruneAgents(): void {
for (const id of this.byAgent.keys()) {
if (!this.agents.hasAgent(id)) this.byAgent.delete(id);
@@ -197,6 +254,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 +263,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);
@@ -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,
@@ -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,