diff --git a/packages/app/e2e/browser/usage-modal.spec.ts b/packages/app/e2e/browser/usage-modal.spec.ts index 26b77b10ff..f6a314535c 100644 --- a/packages/app/e2e/browser/usage-modal.spec.ts +++ b/packages/app/e2e/browser/usage-modal.spec.ts @@ -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(); diff --git a/packages/app/e2e/browser/usage-sidebar-item.spec.ts b/packages/app/e2e/browser/usage-sidebar-item.spec.ts index 1d232e8b4d..f065b66107 100644 --- a/packages/app/e2e/browser/usage-sidebar-item.spec.ts +++ b/packages/app/e2e/browser/usage-sidebar-item.spec.ts @@ -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"]); diff --git a/packages/app/e2e/support/helpers/usage-sidebar-item.ts b/packages/app/e2e/support/helpers/usage-sidebar-item.ts index f6faf3be65..0f9a9935f6 100644 --- a/packages/app/e2e/support/helpers/usage-sidebar-item.ts +++ b/packages/app/e2e/support/helpers/usage-sidebar-item.ts @@ -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 { - 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 { + 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 { + 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 { 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 { 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") { diff --git a/packages/app/src/hooks/use-settings/storage.test.ts b/packages/app/src/hooks/use-settings/storage.test.ts index 55e2d2085b..6400e15fc6 100644 --- a/packages/app/src/hooks/use-settings/storage.test.ts +++ b/packages/app/src/hooks/use-settings/storage.test.ts @@ -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: {}, }); }); diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index 1826f63bac..a31ec3207f 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -2264,7 +2264,11 @@ export const ar: TranslationResources = { title: "استخدام الخطة", refresh: "تحديث", reorderCard: "إعادة ترتيب {{source}}", - showCard: "إظهار {{source}}", + sources: "المصادر", + sourcesCount: "{{shown}} من {{total}}", + providerNotInstalled: "المزود غير مثبت", + allSourcesHidden: "لا توجد مصادر استخدام معروضة", + chooseSources: "اختيار المصادر", refreshAll: "تحديث الكل", refreshing: "جارٍ التحديث...", loading: "جارٍ تحميل بيانات الاستخدام...", diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index 951e36271c..e6cff764f8 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -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...", diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index e99bdfb172..9bf92fa29d 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -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...", diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index 981cfa72ed..9d00bb263e 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -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...", diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index 76d95f0942..0e99df4503 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -2287,7 +2287,11 @@ export const ja: TranslationResources = { title: "プラン使用量", refresh: "更新", reorderCard: "{{source}} を並べ替え", - showCard: "{{source}} を表示", + sources: "ソース", + sourcesCount: "{{shown}} / {{total}}", + providerNotInstalled: "プロバイダー未インストール", + allSourcesHidden: "表示中の使用量ソースはありません", + chooseSources: "ソースを選択", refreshAll: "すべて更新", refreshing: "更新中...", loading: "使用状況を読み込み中...", diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index b7bad0f679..30be0bcbda 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -2275,7 +2275,11 @@ export const ko: TranslationResources = { title: "플랜 사용량", refresh: "새로 고침", reorderCard: "{{source}} 순서 변경", - showCard: "{{source}} 표시", + sources: "소스", + sourcesCount: "{{shown}} / {{total}}", + providerNotInstalled: "제공업체가 설치되지 않음", + allSourcesHidden: "표시된 사용량 소스가 없습니다", + chooseSources: "소스 선택", refreshAll: "모두 새로 고침", refreshing: "새로 고치는 중...", loading: "사용량 불러오는 중...", diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index 62d408baf7..86031f6774 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -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...", diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index 4185c2d481..52919cd958 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -2300,7 +2300,11 @@ export const ru: TranslationResources = { title: "Использование плана", refresh: "Обновить", reorderCard: "Переместить {{source}}", - showCard: "Показывать {{source}}", + sources: "Источники", + sourcesCount: "{{shown}} из {{total}}", + providerNotInstalled: "Провайдер не установлен", + allSourcesHidden: "Источники использования скрыты", + chooseSources: "Выбрать источники", refreshAll: "Обновить всё", refreshing: "Обновление...", loading: "Загрузка данных об использовании...", diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index e1ba06b09e..1813ed3b8f 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -2241,7 +2241,11 @@ export const zhCN: TranslationResources = { title: "套餐用量", refresh: "刷新", reorderCard: "重新排序 {{source}}", - showCard: "显示 {{source}}", + sources: "来源", + sourcesCount: "{{shown}} / {{total}}", + providerNotInstalled: "未安装提供商", + allSourcesHidden: "未显示任何用量来源", + chooseSources: "选择来源", refreshAll: "全部刷新", refreshing: "刷新中...", loading: "正在加载用量...", diff --git a/packages/app/src/sidebar-nav/model.test.ts b/packages/app/src/sidebar-nav/model.test.ts index f7e7ba0933..c294cd2a3b 100644 --- a/packages/app/src/sidebar-nav/model.test.ts +++ b/packages/app/src/sidebar-nav/model.test.ts @@ -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", () => { diff --git a/packages/app/src/sidebar-nav/model.ts b/packages/app/src/sidebar-nav/model.ts index 6b98821e93..838571b222 100644 --- a/packages/app/src/sidebar-nav/model.ts +++ b/packages/app/src/sidebar-nav/model.ts @@ -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 = new Set(["usage"]); - -function builtinVisibleByDefault(id: BuiltinSidebarItemId): boolean { - return !HIDDEN_BY_DEFAULT.has(id); +function builtinVisibleByDefault(_id: BuiltinSidebarItemId): boolean { + return true; } export function pluginSidebarNavKey( diff --git a/packages/app/src/usage/card.tsx b/packages/app/src/usage/card.tsx index d106a806fc..d381519bc1 100644 --- a/packages/app/src/usage/card.tsx +++ b/packages/app/src/usage/card.tsx @@ -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({ {entry.sourceLabel} - {collapsed && entry.account.label ? ( - // The body that names the account is gone, and two off cards of one source must differ. - - {entry.account.label} - - ) : null} - {planLabel && !collapsed ? ( - - ) : null} + {planLabel ? : null} - {status && !collapsed ? ( + {status ? ( {status} ) : null} - {refreshable && !collapsed ? ( + {refreshable ? ( ) : null} - {arrangement ? ( - - - - ) : null} - {collapsed ? null : ( - - )} + ); } @@ -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), })); diff --git a/packages/app/src/usage/cards.test.ts b/packages/app/src/usage/cards.test.ts index 86e62b3d21..6614ae0454 100644 --- a/packages/app/src/usage/cards.test.ts +++ b/packages/app/src/usage/cards.test.ts @@ -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); }); }); diff --git a/packages/app/src/usage/controls.tsx b/packages/app/src/usage/controls.tsx index b4637778c7..994c07a33e 100644 --- a/packages/app/src/usage/controls.tsx +++ b/packages/app/src/usage/controls.tsx @@ -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 : ( )} - + ); } @@ -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 }; } diff --git a/packages/app/src/usage/display.ts b/packages/app/src/usage/display.ts index f54c168834..1efb0ac111 100644 --- a/packages/app/src/usage/display.ts +++ b/packages/app/src/usage/display.ts @@ -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) => 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], diff --git a/packages/app/src/usage/list.tsx b/packages/app/src/usage/list.tsx index e9218ae326..6052466c8b 100644 --- a/packages/app/src/usage/list.tsx +++ b/packages/app/src/usage/list.tsx @@ -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 ( 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 ( 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( - () => - hostChoice - ? [ - { - id: HOST_PAGE, - title: t("providerUsage.host"), - content: , - }, - ] - : 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(() => { + const definitions: MenuPageDefinition[] = []; + if (hostChoice) { + definitions.push({ + id: HOST_PAGE, + title: t("providerUsage.host"), + content: , + }); + } + if (hasSources) { + definitions.push({ + id: SOURCES_PAGE, + title: t("providerUsage.sources"), + content: , + }); + } + return definitions.length > 0 ? definitions : undefined; + }, [arrangedReports, display, hasSources, hostChoice, t]); + const hasSubTriggers = Boolean(hostChoice || hasSources); return ( - + ) : null} + {hasSources ? ( + + {t("providerUsage.sources")} + + ) : null} @@ -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) => ( + + ))} + + ); +} + +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( + () => , + [entry.icon], + ); + const description = + [entry.account.label, !on && entry.defaultEnabled === false ? notInstalledLabel : null] + .filter(Boolean) + .join(" · ") || undefined; + return ( + + {entry.sourceLabel} + + ); +} diff --git a/packages/app/src/usage/preferences.ts b/packages/app/src/usage/preferences.ts index 7ad7d5a3e8..6ee91680c5 100644 --- a/packages/app/src/usage/preferences.ts +++ b/packages/app/src/usage/preferences.ts @@ -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; } 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, +): 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 }, + }; } diff --git a/packages/app/src/usage/usage-modal.tsx b/packages/app/src/usage/usage-modal.tsx index d93bea8b1b..15970870b7 100644 --- a/packages/app/src/usage/usage-modal.tsx +++ b/packages/app/src/usage/usage-modal.tsx @@ -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. */} - + ); diff --git a/packages/app/src/usage/usage-section.tsx b/packages/app/src/usage/usage-section.tsx index d96e3f9104..9e6d788f2c 100644 --- a/packages/app/src/usage/usage-section.tsx +++ b/packages/app/src/usage/usage-section.tsx @@ -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( - () => , - [onRefresh, view, serverId], + () => ( + + ), + [display, onRefresh, optionsOpen, serverId, view], ); return ( - + ); } @@ -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 ( @@ -84,16 +110,30 @@ export function UsageBody({ ); } + let content: React.ReactNode; + if (view.reports.length === 0) { + content = ; + } else if (visibleReports.length === 0) { + content = ( + + {t("providerUsage.allSourcesHidden")} + {onOpenSources ? ( + + ) : null} + + ); + } else { + content = ; + } + return ( {view.refreshFailed ? ( ) : null} - {view.reports.length === 0 ? ( - - ) : ( - - )} + {content} ); } @@ -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: { diff --git a/packages/plugin/src/server/usage.ts b/packages/plugin/src/server/usage.ts index 91cb24d584..67b0cb5071 100644 --- a/packages/plugin/src/server/usage.ts +++ b/packages/plugin/src/server/usage.ts @@ -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; diff --git a/packages/protocol/src/messages.ts b/packages/protocol/src/messages.ts index e8b9142c41..e6c0dca562 100644 --- a/packages/protocol/src/messages.ts +++ b/packages/protocol/src/messages.ts @@ -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(), diff --git a/packages/protocol/src/messages.wire-compat.test.ts b/packages/protocol/src/messages.wire-compat.test.ts index a15c1ae1be..f7098649ee 100644 --- a/packages/protocol/src/messages.wire-compat.test.ts +++ b/packages/protocol/src/messages.wire-compat.test.ts @@ -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 }); diff --git a/packages/server/src/server/agent/provider-snapshot-manager.ts b/packages/server/src/server/agent/provider-snapshot-manager.ts index bc9600ab6c..f8d45fa264 100644 --- a/packages/server/src/server/agent/provider-snapshot-manager.ts +++ b/packages/server/src/server/agent/provider-snapshot-manager.ts @@ -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 { + 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 { const target = resolveProviderSnapshotTarget(input.cwd); if (input.wait) { diff --git a/packages/server/src/server/bootstrap.ts b/packages/server/src/server/bootstrap.ts index 28abdb858f..59f5213347 100644 --- a/packages/server/src/server/bootstrap.ts +++ b/packages/server/src/server/bootstrap.ts @@ -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, diff --git a/packages/server/src/server/plugins/index.ts b/packages/server/src/server/plugins/index.ts index 373e0c29e8..336a85a233 100644 --- a/packages/server/src/server/plugins/index.ts +++ b/packages/server/src/server/plugins/index.ts @@ -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 diff --git a/packages/server/src/server/plugins/plugin-process-protocol.ts b/packages/server/src/server/plugins/plugin-process-protocol.ts index ccbdf5d1c5..20b1547b05 100644 --- a/packages/server/src/server/plugins/plugin-process-protocol.ts +++ b/packages/server/src/server/plugins/plugin-process-protocol.ts @@ -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(); diff --git a/packages/server/src/server/plugins/plugin-process.ts b/packages/server/src/server/plugins/plugin-process.ts index 17d7ff40ba..a4bd76c728 100644 --- a/packages/server/src/server/plugins/plugin-process.ts +++ b/packages/server/src/server/plugins/plugin-process.ts @@ -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, diff --git a/packages/server/src/server/plugins/usage-sources/index.test.ts b/packages/server/src/server/plugins/usage-sources/index.test.ts index 7851e20184..58cda02ce2 100644 --- a/packages/server/src/server/plugins/usage-sources/index.test.ts +++ b/packages/server/src/server/plugins/usage-sources/index.test.ts @@ -179,12 +179,16 @@ test("#7142: host usage retains distinct Cursor accounts after their individual function source(input: { id: string; - discover?: () => Promise>; + providers?: readonly string[]; + discover?: () => Promise< + Array<{ key: string; label?: string; harness?: string; provider?: string; input: unknown }> + >; fetch?: (value: unknown) => Promise; }) { 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>) => + 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, + }); +}); diff --git a/packages/server/src/server/plugins/usage-sources/index.ts b/packages/server/src/server/plugins/usage-sources/index.ts index 55b865416f..319e6019a4 100644 --- a/packages/server/src/server/plugins/usage-sources/index.ts +++ b/packages/server/src/server/plugins/usage-sources/index.ts @@ -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; fetch(input: unknown): Promise; } @@ -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; + /** Whether the provider (or a custom provider derived from it) is installed and enabled. */ + isProviderActive?(provider: string): Promise; } 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, + ): Promise | undefined> { + const isProviderActive = this.agents.isProviderActive; + if (!isProviderActive) return undefined; + const providerIds = new Set(); + 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, + ): 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); diff --git a/plugins/claude-usage-source/index.server.ts b/plugins/claude-usage-source/index.server.ts index 4c97771bfa..0c81cb3839 100644 --- a/plugins/claude-usage-source/index.server.ts +++ b/plugins/claude-usage-source/index.server.ts @@ -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, diff --git a/plugins/claude-usage-source/server/usage.test.ts b/plugins/claude-usage-source/server/usage.test.ts index d38266c42c..626dc2abca 100644 --- a/plugins/claude-usage-source/server/usage.test.ts +++ b/plugins/claude-usage-source/server/usage.test.ts @@ -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" }, }, ]); diff --git a/plugins/claude-usage-source/server/usage.ts b/plugins/claude-usage-source/server/usage.ts index d902ea8318..fa6141f40b 100644 --- a/plugins/claude-usage-source/server/usage.ts +++ b/plugins/claude-usage-source/server/usage.ts @@ -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. diff --git a/plugins/codex-usage-source/index.server.ts b/plugins/codex-usage-source/index.server.ts index 8d38c15ebf..8c5943c1f6 100644 --- a/plugins/codex-usage-source/index.server.ts +++ b/plugins/codex-usage-source/index.server.ts @@ -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, diff --git a/plugins/codex-usage-source/server/usage.ts b/plugins/codex-usage-source/server/usage.ts index 0b211726c6..cce3335624 100644 --- a/plugins/codex-usage-source/server/usage.ts +++ b/plugins/codex-usage-source/server/usage.ts @@ -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; } diff --git a/plugins/copilot-usage-source/index.server.ts b/plugins/copilot-usage-source/index.server.ts index d5e965d759..f341a03630 100644 --- a/plugins/copilot-usage-source/index.server.ts +++ b/plugins/copilot-usage-source/index.server.ts @@ -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, diff --git a/plugins/cursor-usage-source/index.server.ts b/plugins/cursor-usage-source/index.server.ts index a357b3d1bb..78bdef8a7b 100644 --- a/plugins/cursor-usage-source/index.server.ts +++ b/plugins/cursor-usage-source/index.server.ts @@ -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, diff --git a/plugins/kimi-usage-source/index.server.ts b/plugins/kimi-usage-source/index.server.ts index a18da096a3..c9ce9e2f65 100644 --- a/plugins/kimi-usage-source/index.server.ts +++ b/plugins/kimi-usage-source/index.server.ts @@ -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, diff --git a/plugins/muse-provider/server/usage.ts b/plugins/muse-provider/server/usage.ts index 4db5a9bdcb..99dde3dd41 100644 --- a/plugins/muse-provider/server/usage.ts +++ b/plugins/muse-provider/server/usage.ts @@ -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[]; diff --git a/plugins/opencode-go-usage-source/index.server.ts b/plugins/opencode-go-usage-source/index.server.ts index b707c26858..5b3af5df23 100644 --- a/plugins/opencode-go-usage-source/index.server.ts +++ b/plugins/opencode-go-usage-source/index.server.ts @@ -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,