diff --git a/apps/mobile/src/features/usage/UsageRouteScreen.tsx b/apps/mobile/src/features/usage/UsageRouteScreen.tsx index 48215804ee2dc..2c9f6046d0afe 100644 --- a/apps/mobile/src/features/usage/UsageRouteScreen.tsx +++ b/apps/mobile/src/features/usage/UsageRouteScreen.tsx @@ -4,6 +4,7 @@ import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScroll import { EnvironmentId, USAGE_CONTRACT_VERSION, type UsageProviderKind } from "@t3tools/contracts"; import { type RouteProp, useIsFocused, useRoute } from "@react-navigation/native"; import { + emptyUsageReason, updatingProvidersLabel, usageEnvironmentProgress, usageProgress, @@ -146,6 +147,7 @@ function UsageScreen(props: { const canReadDiagnostics = selectedEnvironments.some( (environment) => environment.canReadDiagnostics, ); + const emptyReason = merged.models.length === 0 ? emptyUsageReason(selectedEnvironments) : null; const days = enumerateDays(window.sinceDay, window.untilDay); const chartDays = @@ -328,7 +330,7 @@ function UsageScreen(props: { ) : null} - {isPending ? ( + {isPending || emptyReason === "pending" ? ( Scanning provider transcripts… @@ -338,7 +340,7 @@ function UsageScreen(props: { ? gt("Connect an environment to see usage.") : gt("Select an environment to see usage.")} - ) : !canReadDiagnostics ? ( + ) : !canReadDiagnostics || emptyReason === "failed" ? ( {selectedEnvironments.map((environment) => ( ({ useUsage: vi.fn() })); +vi.mock(import("../../state/usage"), async (original) => ({ + ...(await original()), + useUsage: fixture.useUsage, +})); +vi.mock(import("./usagePagePreferences"), () => ({ + readUsagePagePreferences: () => ({ metric: "cost" as const, windowDays: 30 as const }), + saveUsagePagePreferences: () => {}, +})); +vi.mock(import("../AppRouteModal"), () => ({ + AppRouteModal: ({ children }: { children: ReactNode }) => <>{children}, + AppRouteModalClose: () => <>, +})); + +import { UsagePage } from "./UsagePage"; + +it("keeps the Day breakdown when an empty read becomes pending and settles", async () => { + fixture.useUsage.mockReset(); + const merged = mergeUsage([], USAGE_CONTRACT_VERSION); + const answered = { + environmentId: EnvironmentId.make("workstation"), + label: "Workstation", + canReadDiagnostics: true, + isConnected: true, + isPending: false, + error: null, + summary: { + contractVersion: USAGE_CONTRACT_VERSION, + readAt: "2026-11-16T00:00:00Z", + timeZone: "UTC", + sinceDay: UsageDay.make("2026-11-16"), + untilDay: UsageDay.make("2026-11-16"), + buckets: [], + sources: [], + pricing: { status: "fresh" as const, source: "test", fetchedAt: null, knownModels: 0 }, + scanDurationMs: 0, + }, + }; + const useView = ( + window: Parameters[0], + ): UsageView => ({ + merged, + environments: [answered], + selectedEnvironments: [answered], + isPending: false, + isPartial: false, + shown: { merged, window }, + refresh: async () => {}, + }); + fixture.useUsage.mockImplementation(useView); + await using screen = await render(); + await userEvent.click(screen.getByRole("button", { name: "Day", exact: true })); + await expect + .element(screen.getByRole("button", { name: "Day", exact: true })) + .toHaveAttribute("aria-pressed", "true"); + + fixture.useUsage.mockImplementation((window) => ({ + ...useView(window), + selectedEnvironments: [ + answered, + { ...answered, environmentId: EnvironmentId.make("waiting"), summary: null, isPending: true }, + ], + })); + await screen.rerender(); + await expect + .element(screen.getByRole("button", { name: "Day", exact: true })) + .not.toBeInTheDocument(); + + fixture.useUsage.mockImplementation(useView); + await screen.rerender(); + await expect + .element(screen.getByRole("button", { name: "Day", exact: true })) + .toHaveAttribute("aria-pressed", "true"); +}); diff --git a/apps/web/src/components/usage/UsagePage.tsx b/apps/web/src/components/usage/UsagePage.tsx index adb05afb92ebb..7003d7de1709d 100644 --- a/apps/web/src/components/usage/UsagePage.tsx +++ b/apps/web/src/components/usage/UsagePage.tsx @@ -17,6 +17,7 @@ import * as AsyncResult from "effect/reactivity/AsyncResult"; import * as Cause from "effect/Cause"; import { refreshUsageLimits } from "@t3tools/client-runtime/state/usage"; import { + emptyUsageReason, updatingProvidersLabel, usageEnvironmentProgress, usageLoadingState, @@ -176,6 +177,7 @@ function UsageModelDialogHost({ export function UsagePage() { const [preferences, setPreferences] = useState(readUsagePagePreferences); + const [breakdown, setBreakdown] = useState<"model" | "time">("model"); const keybindings = useAtomValue(primaryServerKeybindingsAtom); const hour12 = usePrimarySettings((settings) => resolveHour12(settings.timestampFormat)); const gt = useGT(); @@ -234,6 +236,7 @@ export function UsagePage() { const canReadDiagnostics = selectedEnvironments.some( (environment) => environment.canReadDiagnostics, ); + const emptyReason = merged.models.length === 0 ? emptyUsageReason(selectedEnvironments) : null; const updatePreferences = (patch: Partial) => { const nextPreferences = { ...preferences, ...patch }; @@ -537,9 +540,9 @@ export function UsagePage() { hiddenProviders={hiddenProviders} now={limitsNow} /> - ) : shown === null ? ( + ) : shown === null || emptyReason === "pending" ? ( - ) : !canReadDiagnostics ? ( + ) : !canReadDiagnostics || emptyReason === "failed" ? (
{selectedEnvironments.map((environment) => (

@@ -554,6 +557,8 @@ export function UsagePage() {

) : ( void; readonly merged: MergedUsage; readonly shownWindow: UsageSummaryInput; readonly hour12: boolean; @@ -631,7 +640,6 @@ function UsageOverview({ const gt = useGT(); const locale = useLocale(); const m = useMessages(); - const [breakdown, setBreakdown] = useState<"model" | "time">("model"); const shownHourly = shownWindow.resolution === "hour"; const loading = usageLoading(showingKept, selectedEnvironments, refreshingUsage, hiddenProviders); // Copy the primitive; JSX reads of loading.partial would merge all derivations into one compiler cache @@ -900,7 +908,7 @@ function UsageOverview({ value={[breakdown]} onValueChange={(next) => { const value = next[0]; - if (value === "model" || value === "time") setBreakdown(value); + if (value === "model" || value === "time") onBreakdownChange(value); }} > {( diff --git a/packages/client-runtime/src/state/usageProgress.test.ts b/packages/client-runtime/src/state/usageProgress.test.ts index ce720b0bc0289..90a7d4de58b8b 100644 --- a/packages/client-runtime/src/state/usageProgress.test.ts +++ b/packages/client-runtime/src/state/usageProgress.test.ts @@ -6,7 +6,12 @@ import { } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { usageEnvironmentProgress, usageLoadingState, usageProgress } from "./usageProgress.ts"; +import { + emptyUsageReason, + usageEnvironmentProgress, + usageLoadingState, + usageProgress, +} from "./usageProgress.ts"; function summary(refreshing: readonly UsageProviderKind[] = []): UsageSummary { return { @@ -118,3 +123,13 @@ describe("usageLoadingState", () => { expect(state).toEqual({ partial: false, everyProvider: false, providers: new Set() }); }); }); + +it("does not call an unfinished or failed read empty", () => { + const answered = { summary: summary(), error: null }; + const reconnecting = { summary: null, error: null }; + const failed = { summary: null, error: "This environment could not report usage." }; + + expect(emptyUsageReason([answered, reconnecting])).toBe("pending"); + expect(emptyUsageReason([failed, failed])).toBe("failed"); + expect(emptyUsageReason([answered, failed])).toBeNull(); +}); diff --git a/packages/client-runtime/src/state/usageProgress.ts b/packages/client-runtime/src/state/usageProgress.ts index 9398ec73647d2..8148d116b875e 100644 --- a/packages/client-runtime/src/state/usageProgress.ts +++ b/packages/client-runtime/src/state/usageProgress.ts @@ -29,6 +29,22 @@ export function usageEnvironmentProgress( : ({ phase: "stale" } as const); } +/** + * Why a merge with no usage is not yet a finished read: an environment has + * still to answer, or every read failed. Null means the window really is empty. + */ +export function emptyUsageReason( + environments: readonly Pick[], +): "pending" | "failed" | null { + if ( + environments.some((environment) => environment.summary === null && environment.error === null) + ) + return "pending"; + return environments.length > 0 && environments.every((environment) => environment.error !== null) + ? "failed" + : null; +} + export function updatingProvidersLabel( providers: readonly UsageProviderKind[], providerLabel: (provider: UsageProviderKind) => string,