fix(usage): keep failed usage visible in sidebar (#9594)
Retain the last successful percentages in the sidebar after a failed refresh, with a red warning that opens the existing error detail. Share snapshot selection between cards, default pins, and summary rendering so the surfaces no longer disagree about retained usage.
This commit is contained in:
1 parent
a30b784eb2
commit
ec52097924
6 files changed
+142
-32
No files matched your search
@@ -25,6 +25,7 @@ import {
|
||||
} from "../support/helpers/usage-login";
|
||||
import {
|
||||
claudeAndCodexReports,
|
||||
closeUsage,
|
||||
expectPinnedUsage,
|
||||
openCompactSidebar,
|
||||
openUsageFromIcon,
|
||||
@@ -79,12 +80,17 @@ function twoHoursAgo(): string {
|
||||
}
|
||||
|
||||
/** Set PASEO_QA_SCREENSHOT_DIR to keep a QA screenshot. */
|
||||
async function qaScreenshot(page: Page, name: string) {
|
||||
async function qaScreenshot(page: Page, name: string, target: "page" | "summary" = "page") {
|
||||
const directory = process.env.PASEO_QA_SCREENSHOT_DIR;
|
||||
if (!directory) return;
|
||||
await page.waitForTimeout(600);
|
||||
await page.addStyleTag({ content: ".__expo_fast_refresh { display: none !important; }" });
|
||||
await page.screenshot({ path: path.join(directory, `${name}.png`) });
|
||||
const file = path.join(directory, `${name}.png`);
|
||||
if (target === "summary") {
|
||||
await usageItem(page).screenshot({ path: file });
|
||||
return;
|
||||
}
|
||||
await page.screenshot({ path: file });
|
||||
}
|
||||
|
||||
function hostFilter(page: Page) {
|
||||
@@ -628,6 +634,15 @@ for (const compact of [false, true]) {
|
||||
await refreshLoginUsage(page);
|
||||
await expectRetainedLoginUsage(page, "Claude: Rate limited");
|
||||
await expectLoginUsageFreshness(page, "Last updated 1h ago", compact);
|
||||
await expectPinnedUsage(page, ["42% Weekly"]);
|
||||
await expect(usageItem(page).getByTestId("sidebar-usage-error")).toBeVisible();
|
||||
await expect(usageItem(page)).toHaveAccessibleName(/Unable to refresh usage/);
|
||||
await qaScreenshot(page, `usage-error-detail-${compact ? "compact" : "desktop"}`);
|
||||
await closeUsage(page);
|
||||
await qaScreenshot(page, `usage-error-summary-${compact ? "compact" : "desktop"}`, "summary");
|
||||
await openUsageFromItem(page);
|
||||
await expectRetainedLoginUsage(page, "Claude: Rate limited");
|
||||
|
||||
await refreshLoginUsage(page);
|
||||
await expectRetainedLoginUsage(page, "Claude: Rate limited");
|
||||
await expectLoginUsageFreshness(page, "Last updated 1h ago", compact);
|
||||
@@ -639,6 +654,8 @@ for (const compact of [false, true]) {
|
||||
await refreshLoginUsage(page);
|
||||
await expectRetainedLoginUsage(page, "Claude: No active quota");
|
||||
await expectLoginUsageFreshness(page, "Last updated 1h ago", compact);
|
||||
await expectPinnedUsage(page, ["42% Weekly"]);
|
||||
await expect(usageItem(page).getByTestId("sidebar-usage-error")).toHaveCount(0);
|
||||
|
||||
await fixture.setReport({
|
||||
status: "available",
|
||||
@@ -647,6 +664,9 @@ for (const compact of [false, true]) {
|
||||
await page.clock.setFixedTime(new Date(Date.now() + 150_000));
|
||||
await refreshLoginUsage(page);
|
||||
await expectLoginUsageOnly(page, "43% used");
|
||||
await expectPinnedUsage(page, ["43% Weekly"]);
|
||||
await expect(usageItem(page).getByTestId("sidebar-usage-error")).toHaveCount(0);
|
||||
await expect(usageItem(page)).not.toHaveAccessibleName(/Unable to refresh usage/);
|
||||
await advanceUsageClock(page, 60_000);
|
||||
await expect(page.getByText("42% used", { exact: true })).toHaveCount(0);
|
||||
await expectLoginUsageFreshness(page, "Updated 2m ago", compact);
|
||||
|
||||
@@ -2,7 +2,13 @@ import type { TFunction } from "i18next";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { usageCopy } from "./copy";
|
||||
import type { UsageDisplayAs } from "./preferences";
|
||||
import type { UsageReport, UsageReportEntry, UsageView, UsageWindow } from "./types";
|
||||
import type {
|
||||
AvailableUsageReport,
|
||||
UsageReport,
|
||||
UsageReportEntry,
|
||||
UsageView,
|
||||
UsageWindow,
|
||||
} from "./types";
|
||||
|
||||
export function usedPercent(window: UsageWindow): number | null {
|
||||
if (window.usedPct != null) return window.usedPct;
|
||||
@@ -205,13 +211,34 @@ export function resolveUsageModalHostId(choice: UsageHostChoice): string | null
|
||||
return picked?.serverId ?? resolveUsageHostId(choice) ?? connected[0]?.serverId ?? null;
|
||||
}
|
||||
|
||||
export interface UsageSnapshot {
|
||||
report: AvailableUsageReport;
|
||||
successfulAt: string;
|
||||
retained: boolean;
|
||||
}
|
||||
|
||||
/** The latest successful values and their freshness, independent of the latest attempt's outcome. */
|
||||
export function resolveUsageSnapshot(entry: UsageReportEntry): UsageSnapshot | null {
|
||||
if (entry.report.status === "available") {
|
||||
// COMPAT(usageSuccessfulAt): added in v0.12.0, remove after 2027-04-17 once daemon floor >= v0.12.0.
|
||||
// Old daemons expose only attempt time for available reports, never for failures.
|
||||
return {
|
||||
report: entry.report,
|
||||
successfulAt: entry.successfulAt ?? entry.fetchedAt,
|
||||
retained: false,
|
||||
};
|
||||
}
|
||||
// COMPAT(usageLastSuccessful): added in v0.12.0, remove after 2027-04-17 once daemon floor >= v0.12.0.
|
||||
// Older daemons cannot provide history; a failed attempt is never a successful update.
|
||||
const retained = entry.lastSuccessful;
|
||||
if (!retained) return null;
|
||||
return { report: retained.report, successfulAt: retained.fetchedAt, retained: true };
|
||||
}
|
||||
|
||||
/** Current outcome owns messages; only a successful poll owns values and freshness. */
|
||||
export function resolveUsageReport(entry: UsageReportEntry, t: TFunction) {
|
||||
const available = entry.report.status === "available";
|
||||
// COMPAT(usageLastSuccessful): added in v0.12.0, remove after 2027-04-17 once daemon floor >= v0.12.0.
|
||||
// Older daemons cannot provide history; a failed attempt is never a successful update.
|
||||
const snapshot = available ? null : (entry.lastSuccessful ?? null);
|
||||
const content = entry.report.status === "available" ? entry.report : (snapshot?.report ?? null);
|
||||
const snapshot = resolveUsageSnapshot(entry);
|
||||
const messages: string[] = [];
|
||||
if (!available) {
|
||||
if (entry.loginErrors)
|
||||
@@ -224,16 +251,12 @@ export function resolveUsageReport(entry: UsageReportEntry, t: TFunction) {
|
||||
else messages.push(usageProblemText(entry.report, t));
|
||||
}
|
||||
return {
|
||||
windows: content?.windows ?? [],
|
||||
balances: content?.balances ?? [],
|
||||
details: content?.details ?? [],
|
||||
planLabel: content?.planLabel ?? null,
|
||||
// COMPAT(usageSuccessfulAt): added in v0.12.0, remove after 2027-04-17 once daemon floor >= v0.12.0.
|
||||
// Old daemons expose only attempt time for available reports, never for failures.
|
||||
successfulAt: available
|
||||
? (entry.successfulAt ?? entry.fetchedAt)
|
||||
: (snapshot?.fetchedAt ?? null),
|
||||
retained: snapshot !== null,
|
||||
windows: snapshot?.report.windows ?? [],
|
||||
balances: snapshot?.report.balances ?? [],
|
||||
details: snapshot?.report.details ?? [],
|
||||
planLabel: snapshot?.report.planLabel ?? null,
|
||||
successfulAt: snapshot?.successfulAt ?? null,
|
||||
retained: snapshot?.retained ?? false,
|
||||
messages,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -139,6 +139,7 @@ describe("resolvePinnedUsage", () => {
|
||||
expect(sources[0]).toEqual({
|
||||
key: "claude:default",
|
||||
icon: "<svg/>",
|
||||
hasError: false,
|
||||
windows: [
|
||||
{
|
||||
key: "claude:default/five-hour",
|
||||
@@ -257,7 +258,7 @@ describe("resolvePinnedUsage", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps unavailable and error reports out of the sidebar summary even with retained data", () => {
|
||||
it("shows retained windows and marks errored sources in the sidebar summary", () => {
|
||||
if (claude.report.status !== "available" || codex.report.status !== "available")
|
||||
throw new Error("fixtures must be available");
|
||||
const expired: UsageReportEntry = {
|
||||
@@ -273,7 +274,30 @@ it("keeps unavailable and error reports out of the sidebar summary even with ret
|
||||
lastSuccessful: { fetchedAt: codex.fetchedAt, report: codex.report },
|
||||
report: { status: "error", error: "Store deleted" },
|
||||
};
|
||||
expect(resolvePinnedUsage([expired, failed], preferences(null))).toEqual([]);
|
||||
const expected = [
|
||||
{ key: "claude:default", hasError: false, windows: ["31%"] },
|
||||
{ key: "codex:default", hasError: true, windows: ["12%"] },
|
||||
];
|
||||
const summarize = (pins: UsagePreferences["pins"]) =>
|
||||
resolvePinnedUsage([expired, failed], preferences(pins)).map((source) => ({
|
||||
key: source.key,
|
||||
hasError: source.hasError,
|
||||
windows: source.windows.map((window) => window.percentText),
|
||||
}));
|
||||
|
||||
expect(summarize(null)).toEqual(expected);
|
||||
expect(
|
||||
summarize([
|
||||
{ sourceId: "claude", windowId: "five-hour" },
|
||||
{ sourceId: "codex", windowId: "weekly" },
|
||||
]),
|
||||
).toEqual(expected);
|
||||
expect(
|
||||
resolvePinnedUsage(
|
||||
[{ ...failed, lastSuccessful: undefined }],
|
||||
preferences([{ sourceId: "codex", windowId: "weekly" }]),
|
||||
),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("localizes pinned labels and meanings while preserving custom window names", async () => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { TFunction } from "i18next";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { formatPct, formatDisplayPct, formatProviderUsageLabel } from "./format";
|
||||
import { displayPercent } from "./model";
|
||||
import { displayPercent, resolveUsageSnapshot } from "./model";
|
||||
import { effectiveUsagePins, type UsagePreferences } from "./preferences";
|
||||
import { windowTone } from "./tone";
|
||||
import type { UsageReportEntry, UsageTone } from "./types";
|
||||
@@ -23,6 +23,8 @@ export interface PinnedUsageWindow {
|
||||
export interface PinnedUsageSource {
|
||||
key: string;
|
||||
icon: string | null;
|
||||
/** The displayed values are retained from before a failed refresh. */
|
||||
hasError: boolean;
|
||||
windows: PinnedUsageWindow[];
|
||||
}
|
||||
|
||||
@@ -74,8 +76,9 @@ export function resolvePinnedUsage(
|
||||
): PinnedUsageSource[] {
|
||||
const pins = effectiveUsagePins(preferences, reports);
|
||||
return groupBySource(reports).flatMap((entry) => {
|
||||
if (entry.report.status !== "available") return [];
|
||||
const windows = entry.report.windows
|
||||
const snapshot = resolveUsageSnapshot(entry);
|
||||
if (!snapshot) return [];
|
||||
const windows = snapshot.report.windows
|
||||
.filter(
|
||||
(window) =>
|
||||
displayPercent(window, preferences.displayAs) !== null &&
|
||||
@@ -94,6 +97,13 @@ export function resolvePinnedUsage(
|
||||
};
|
||||
});
|
||||
if (windows.length === 0) return [];
|
||||
return [{ key: entry.id, icon: entry.icon ?? null, windows }];
|
||||
return [
|
||||
{
|
||||
key: entry.id,
|
||||
icon: entry.icon ?? null,
|
||||
hasError: entry.report.status === "error",
|
||||
windows,
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { displayPercent } from "./model";
|
||||
import { displayPercent, resolveUsageSnapshot } from "./model";
|
||||
import type { UsageReportEntry } from "./types";
|
||||
|
||||
/** Whether percentages read as the share used or the share left. */
|
||||
@@ -55,8 +55,9 @@ export function effectiveUsagePins(
|
||||
if (preferences.pins !== null) return preferences.pins;
|
||||
const pins: UsagePin[] = [];
|
||||
for (const entry of reports) {
|
||||
if (entry.report.status !== "available") continue;
|
||||
const withPercent = entry.report.windows.filter(
|
||||
const snapshot = resolveUsageSnapshot(entry);
|
||||
if (!snapshot) continue;
|
||||
const withPercent = snapshot.report.windows.filter(
|
||||
(window) => displayPercent(window, preferences.displayAs) !== null,
|
||||
);
|
||||
const marked = withPercent.filter((window) => window.summary);
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { TriangleAlert } from "lucide-react-native";
|
||||
import {
|
||||
Pressable,
|
||||
Text,
|
||||
@@ -15,7 +16,8 @@ import {
|
||||
type LayoutChangeEvent,
|
||||
type PressableStateCallbackType,
|
||||
} from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { useRetainedPanelActive } from "@/components/retained-panel";
|
||||
import { useAppVisible } from "@/hooks/use-app-visible";
|
||||
import { builtinSidebarNavLabelKey } from "@/sidebar-nav/model";
|
||||
@@ -35,6 +37,9 @@ import {
|
||||
} from "./pinned";
|
||||
import { UsageModal } from "./usage-modal";
|
||||
|
||||
const ThemedTriangleAlert = withUnistyles(TriangleAlert);
|
||||
const errorIconColor = (theme: Theme) => ({ color: theme.colors.statusDanger });
|
||||
|
||||
/** Each summary window with data on the usage host, under its source; empty while none has. */
|
||||
export function useUsageSummary(): readonly PinnedUsageSource[] {
|
||||
const { t } = useTranslation();
|
||||
@@ -60,7 +65,14 @@ export function UsageSidebarItem({ sources }: { sources: readonly PinnedUsageSou
|
||||
const label = t(builtinSidebarNavLabelKey("usage"));
|
||||
const openUsage = useOpenSidebarUsage();
|
||||
if (sources.length === 0) return null;
|
||||
return <PinnedUsageTrigger label={label} sources={sources} onPress={openUsage} />;
|
||||
return (
|
||||
<PinnedUsageTrigger
|
||||
label={label}
|
||||
sources={sources}
|
||||
errorLabel={t("providerUsage.refreshFailed")}
|
||||
onPress={openUsage}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const OpenSidebarUsageContext = createContext<(() => void) | null>(null);
|
||||
@@ -95,9 +107,15 @@ export function useOpenSidebarUsage(): () => void {
|
||||
return openUsage;
|
||||
}
|
||||
|
||||
function pinnedUsageLabel(label: string, sources: readonly PinnedUsageSource[]): string {
|
||||
function pinnedUsageLabel(
|
||||
label: string,
|
||||
sources: readonly PinnedUsageSource[],
|
||||
errorLabel: string,
|
||||
): string {
|
||||
const windows = sources.flatMap((source) => source.windows);
|
||||
return `${label}: ${windows.map((window) => window.label).join(", ")}`;
|
||||
const summary = windows.map((window) => window.label).join(", ");
|
||||
const error = sources.some((source) => source.hasError) ? `, ${errorLabel}` : "";
|
||||
return `${label}: ${summary}${error}`;
|
||||
}
|
||||
|
||||
function triggerStyle({ hovered }: PressableStateCallbackType & { hovered?: boolean }) {
|
||||
@@ -116,10 +134,12 @@ function layoutWidth(event: LayoutChangeEvent): number {
|
||||
function PinnedUsageTrigger({
|
||||
label,
|
||||
sources,
|
||||
errorLabel,
|
||||
onPress,
|
||||
}: {
|
||||
label: string;
|
||||
sources: readonly PinnedUsageSource[];
|
||||
errorLabel: string;
|
||||
onPress: () => void;
|
||||
}) {
|
||||
const [available, setAvailable] = useState<number | null>(null);
|
||||
@@ -144,7 +164,7 @@ function PinnedUsageTrigger({
|
||||
<Pressable
|
||||
onPress={onPress}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={pinnedUsageLabel(label, sources)}
|
||||
accessibilityLabel={pinnedUsageLabel(label, sources, errorLabel)}
|
||||
style={triggerStyle}
|
||||
testID="sidebar-usage"
|
||||
>
|
||||
@@ -185,10 +205,17 @@ function PinnedUsageLine({
|
||||
return sources.map((source, sourceIndex) => (
|
||||
<Fragment key={source.key}>
|
||||
<View
|
||||
style={sourceIndex === 0 ? null : styles.sourceGap}
|
||||
style={[styles.source, sourceIndex === 0 ? null : styles.sourceGap]}
|
||||
testID={measuring ? undefined : "sidebar-usage-source"}
|
||||
>
|
||||
<UsageSourceIcon svg={source.icon} size={14} />
|
||||
{source.hasError ? (
|
||||
<ThemedTriangleAlert
|
||||
size={12}
|
||||
uniProps={errorIconColor}
|
||||
testID={measuring ? undefined : "sidebar-usage-error"}
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
{source.windows.map((window, windowIndex) => {
|
||||
const leadStyle = windowIndex === 0 ? styles.iconGap : styles.windowGap;
|
||||
@@ -251,6 +278,11 @@ const styles = StyleSheet.create((theme) => ({
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
},
|
||||
source: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[1],
|
||||
},
|
||||
sourceGap: {
|
||||
marginLeft: theme.spacing[3],
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user