Compare commits

...
Author SHA1 Message Date
Mohamed Boudra b888bd29bc fix(usage): keep refresh errors visible alongside quota
Store request feedback with its refresh control. A newer report can restore the forecast while an overlapping failed request still needs to surface its error.
2026-11-20 11:07:10 +01:00
Mohamed Boudra 232fef63a0 test(usage): timestamp the expired-login refresh fixture
The expired-login result represents a new attempt. Give it a fresh timestamp so the UI can accept it without relaxing the guard against older reports.
2026-11-20 10:54:43 +01:00
Mohamed Boudra 5ce5a9b5e2 test(usage): cover a timed-out Refresh all and retry 2026-11-20 10:31:55 +01:00
Mohamed Boudra 961cc3ae48 fix(usage): hide stale forecasts after Refresh all fails
Store refresh failures with the cached readings they affect so card and list requests use the same forecast rule. Reports that arrive during a refresh retain their forecasts.
2026-11-20 10:22:50 +01:00
Mohamed Boudra c2808d5d96 fix(usage): keep quota forecasts tied to their readings
A cached provider observation must keep its own timestamp across refreshes. Hide forecasts after a failed request until a newer reading takes its place, and keep reset text within its column on narrow screens.
2026-11-20 10:14:47 +01:00
Mohamed Boudra af20ec20eb feat(usage): forecast quota remaining at reset
Show whether current usage will last until reset and how much quota is likely to remain. Anchor estimates to the last successful reading so the countdown does not move the projected runout between refreshes.
2026-11-20 10:02:28 +01:00
30 changed files with 551 additions and 96 deletions
+103 -1
View File
@@ -2,13 +2,14 @@ import { tmpdir } from "node:os";
import { randomUUID } from "node:crypto";
import path from "node:path";
import type { Page } from "@playwright/test";
import type { UsageReportEntry } from "@getpaseo/protocol/messages";
import type { UsageReport, UsageReportEntry } from "@getpaseo/protocol/messages";
import { expect, test } from "../support/fixtures";
import { gotoAppShell, openSettings } from "../support/helpers/app";
import { addConnectedHostAndReload } from "../support/helpers/hosts";
import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon";
import { openSettingsSection } from "../support/helpers/settings";
import { gate } from "../support/helpers/context-window";
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
import { getServerId } from "../support/helpers/server-id";
import { seedSidebarFooterPreferences } from "../support/helpers/sidebar-nav-settings";
import {
@@ -45,6 +46,7 @@ import {
refreshAllUsage,
togglePin,
usageItem,
usageModal,
} from "../support/helpers/usage-sidebar-item";
const emptyHome = path.join(tmpdir(), `paseo-usage-empty-${randomUUID()}`);
@@ -865,6 +867,106 @@ test("open usage clocks advance without refreshing or reopening", async ({ page
}
});
test("Refresh all keeps quota visible and restores the forecast after a timeout", async ({
page,
}) => {
const reading = new Date();
const login = await installLoginUsage(usageReading(reading, 40));
try {
const transport = await installDaemonWebSocketGate(page);
await openCompactUsageWithClock(page, reading);
await expectQuota(page, "40% used", /runs out in /);
await timeOutUsageRefresh(page, transport);
await expectQuota(page, "40% used", null);
await expectUsageRefreshError(page).toBeVisible();
await login.setReport(usageReading(reading, 10));
transport.releaseHeldClientRequest();
await refreshAllUsage(page);
await expectQuota(page, "10% used", "~50% left at reset");
await expectUsageRefreshError(page).toBeHidden();
} finally {
await login.cleanup();
}
});
test("a card refresh timeout is visible alongside a newer quota forecast", async ({ page }) => {
const reading = new Date();
const login = await installLoginUsage(usageReading(reading, 40));
try {
const transport = await installDaemonWebSocketGate(page);
await openCompactUsageWithClock(page, reading);
await expectQuota(page, "40% used", /runs out in /);
await delayCardRefreshResponse(page, transport);
await login.setReport(usageReading(reading, 10));
await refreshAllUsage(page);
await expectQuota(page, "10% used", "~50% left at reset");
await advanceUsageClock(page, 61_000);
await expectUsageRefreshError(page).toBeVisible();
await expectQuota(page, "10% used", "~50% left at reset");
} finally {
await login.cleanup();
}
});
function expectUsageRefreshError(page: Page) {
return expect(usageModal(page).getByText("Unable to refresh usage", { exact: true }));
}
async function delayCardRefreshResponse(
page: Page,
transport: Awaited<ReturnType<typeof installDaemonWebSocketGate>>,
) {
await expect(page.getByRole("button", { name: "Refresh all", exact: true })).toBeEnabled();
transport.holdNextServerMessage("usage.list_reports.response");
await refreshLoginUsage(page);
await transport.waitForHeldServerMessage("usage.list_reports.response");
}
function usageReading(observed: Date, usedPct: number): UsageReport {
return {
status: "available",
observedAt: observed.toISOString(),
windows: [
{
id: "session",
label: "Session",
usedPct,
durationSeconds: 18_000,
resetsAt: new Date(observed.getTime() + 4 * 3_600_000).toISOString(),
},
],
};
}
async function expectQuota(page: Page, amount: string, forecast: string | RegExp | null) {
const usage = usageModal(page);
await expect(usage.getByText(amount, { exact: true })).toBeVisible();
await expect(usage.getByText(/^resets in /)).toBeVisible();
if (forecast === null) {
await expect(usage.getByText(/^runs out in /)).toBeHidden();
return;
}
await expect(usage.getByText(forecast)).toBeVisible();
}
async function timeOutUsageRefresh(
page: Page,
transport: Awaited<ReturnType<typeof installDaemonWebSocketGate>>,
) {
const refresh = page.getByRole("button", { name: "Refresh all", exact: true });
await expect(refresh).toBeEnabled();
transport.holdNextClientRequest("usage.list_reports.request");
await refreshAllUsage(page);
await transport.waitForHeldClientRequest();
await expect(refresh).toBeDisabled();
await advanceUsageClock(page, 61_000);
await expect(refresh).toBeEnabled();
}
async function openCompactUsageWithClock(page: Page, now: Date) {
await page.setViewportSize({ width: 390, height: 844 });
await page.clock.install({ time: now });
@@ -185,13 +185,15 @@ function onLogin(report: UsageReportEntry, login: string): UsageReportEntry {
}
export function expiredLogin(report: UsageReportEntry): UsageReportEntry {
const fetchedAt = Date.now();
return {
...report,
fetchedAt: new Date(fetchedAt).toISOString(),
report: {
status: "unavailable",
problem: {
kind: "expired",
expiresAt: new Date(Date.now() - 2 * 60 * 60_000).toISOString(),
expiresAt: new Date(fetchedAt - 2 * 60 * 60_000).toISOString(),
refreshedBy: "claude",
},
},
+3
View File
@@ -2323,6 +2323,9 @@ export const ar: TranslationResources = {
resetsIn: "تتم إعادة التعيين خلال {{duration}}",
resetsAtWeekday: "{{weekday}} {{time}}",
resetsAtDate: "{{date}}، {{time}}",
projectedLeftAtReset: "نحو {{percentage}} متبقية عند إعادة التعيين",
limitReached: "تم بلوغ الحد",
mayHaveRunOut: "ربما نفدت الحصة",
runsOutNow: "ينفد الآن",
runsOutIn: "ينفد خلال {{duration}}",
justNow: "الآن",
+3
View File
@@ -2333,6 +2333,9 @@ export const en = {
resetsIn: "resets in {{duration}}",
resetsAtWeekday: "{{weekday}} {{time}}",
resetsAtDate: "{{date}}, {{time}}",
projectedLeftAtReset: "~{{percentage}} left at reset",
limitReached: "Limit reached",
mayHaveRunOut: "May have run out",
runsOutNow: "runs out now",
runsOutIn: "runs out in {{duration}}",
justNow: "just now",
+3
View File
@@ -2354,6 +2354,9 @@ export const es: TranslationResources = {
resetsIn: "se restablece en {{duration}}",
resetsAtWeekday: "{{weekday}} {{time}}",
resetsAtDate: "{{date}}, {{time}}",
projectedLeftAtReset: "~{{percentage}} restante al restablecerse",
limitReached: "Límite alcanzado",
mayHaveRunOut: "Puede que ya se haya agotado",
runsOutNow: "se agota ahora",
runsOutIn: "se agota en {{duration}}",
justNow: "ahora mismo",
+3
View File
@@ -2355,6 +2355,9 @@ export const fr: TranslationResources = {
resetsIn: "se réinitialise dans {{duration}}",
resetsAtWeekday: "{{weekday}} {{time}}",
resetsAtDate: "{{date}}, {{time}}",
projectedLeftAtReset: "~{{percentage}} restant à la réinitialisation",
limitReached: "Limite atteinte",
mayHaveRunOut: "Le quota est peut-être épuisé",
runsOutNow: "s’épuise maintenant",
runsOutIn: "s’épuise dans {{duration}}",
justNow: "à l’instant",
+3
View File
@@ -2328,6 +2328,9 @@ export const ja: TranslationResources = {
resetsIn: "{{duration}}後にリセット",
resetsAtWeekday: "{{weekday}} {{time}}",
resetsAtDate: "{{date}} {{time}}",
projectedLeftAtReset: "リセット時に約{{percentage}}残る見込み",
limitReached: "上限に達しました",
mayHaveRunOut: "上限に達した可能性があります",
runsOutNow: "まもなく上限に到達",
runsOutIn: "{{duration}}後に上限に到達",
justNow: "たった今",
+3
View File
@@ -2316,6 +2316,9 @@ export const ko: TranslationResources = {
resetsIn: "{{duration}} 후 재설정",
resetsAtWeekday: "{{weekday}} {{time}}",
resetsAtDate: "{{date}} {{time}}",
projectedLeftAtReset: "초기화 시 약 {{percentage}} 남을 예정",
limitReached: "한도에 도달함",
mayHaveRunOut: "한도를 소진했을 수 있음",
runsOutNow: "지금 한도에 도달",
runsOutIn: "{{duration}} 후 한도에 도달",
justNow: "방금",
+3
View File
@@ -2339,6 +2339,9 @@ export const ptBR: TranslationResources = {
resetsIn: "redefine em {{duration}}",
resetsAtWeekday: "{{weekday}} {{time}}",
resetsAtDate: "{{date}}, {{time}}",
projectedLeftAtReset: "~{{percentage}} restará na renovação",
limitReached: "Limite atingido",
mayHaveRunOut: "A cota pode ter se esgotado",
runsOutNow: "esgota agora",
runsOutIn: "esgota em {{duration}}",
justNow: "agora mesmo",
+3
View File
@@ -2341,6 +2341,9 @@ export const ru: TranslationResources = {
resetsIn: "сброс через {{duration}}",
resetsAtWeekday: "{{weekday}} {{time}}",
resetsAtDate: "{{date}}, {{time}}",
projectedLeftAtReset: "К сбросу останется ~{{percentage}}",
limitReached: "Лимит исчерпан",
mayHaveRunOut: "Лимит мог уже исчерпаться",
runsOutNow: "закончится сейчас",
runsOutIn: "закончится через {{duration}}",
justNow: "только что",
+3
View File
@@ -2282,6 +2282,9 @@ export const zhCN: TranslationResources = {
resetsIn: "将在 {{duration}}后重置",
resetsAtWeekday: "{{weekday}} {{time}}",
resetsAtDate: "{{date}} {{time}}",
projectedLeftAtReset: "重置时约剩余 {{percentage}}",
limitReached: "已达到上限",
mayHaveRunOut: "额度可能已用完",
runsOutNow: "即将用尽",
runsOutIn: "将在 {{duration}}后用尽",
justNow: "刚刚",
@@ -32,6 +32,7 @@ it("translates mounted usage rows when the language changes", async () => {
<>
<UsageWindowBar
window={window}
forecastAt={null}
displayAs="used"
pinnable={false}
pinned={false}
@@ -51,3 +52,44 @@ it("translates mounted usage rows when the language changes", async () => {
expect(container.textContent).toContain("セッション70% 使用済み");
expect(container.textContent).toContain("クレジット");
});
const narrowReadingMs = Date.now();
const narrowForecastAt = new Date(narrowReadingMs).toISOString();
const narrowWindow: UsageWindow = {
id: "weekly",
label: "Weekly",
usedPct: 0.2,
durationSeconds: 604_800,
resetsAt: new Date(narrowReadingMs + 165.5 * 3_600_000).toISOString(),
};
it("keeps the French reset countdown and forecast apart in a narrow card", async () => {
await i18n.changeLanguage("fr");
container.style.width = "272px";
act(() =>
root.render(
<UsageWindowBar
window={narrowWindow}
forecastAt={narrowForecastAt}
displayAs="used"
pinnable={false}
pinned={false}
onTogglePin={ignorePin}
pinLabel=""
pinTestID=""
/>,
),
);
function textBounds(prefix: string) {
const element = Array.from(container.querySelectorAll("*")).find(
(node) => node.childElementCount === 0 && node.textContent.startsWith(prefix),
);
expect(element).toBeDefined();
const range = document.createRange();
range.selectNodeContents(element!);
return range.getBoundingClientRect();
}
expect(textBounds("se réinitialise").right).toBeLessThan(textBounds("~").left);
});
+6 -2
View File
@@ -70,7 +70,7 @@ export function UsageCard({
}) {
const { t } = useTranslation();
const isCompact = useIsCompactFormFactor();
const { refresh, refreshState } = useReportRefresh(serverId, entry.id, agentId);
const { refresh, refreshState } = useReportRefresh(serverId, entry, agentId);
// Where there is no hover the freshness is printed on the card; elsewhere the Refresh tooltip.
const showsFreshnessInline = isNative || isCompact || !refreshable;
const usage = entry.report;
@@ -176,7 +176,7 @@ function UsageCardBody({
refreshState: UsageRefresh;
}) {
const { t } = useTranslation();
const { windows, balances, details, retained, successfulAt, messages } = report;
const { windows, balances, details, retained, successfulAt, forecastAt, messages } = report;
const footer = entry.account.label ?? null;
return (
<>
@@ -194,6 +194,7 @@ function UsageCardBody({
entry={entry}
window={window}
retained={retained}
forecastAt={forecastAt}
display={display}
pinnable={pinnable}
/>
@@ -267,8 +268,10 @@ function CardWindowBar({
display,
pinnable,
retained,
forecastAt,
}: {
retained: boolean;
forecastAt: string | null;
entry: UsageReportEntry;
window: UsageWindow;
display: UsageDisplay;
@@ -285,6 +288,7 @@ function CardWindowBar({
<UsageWindowBar
window={window}
retained={retained}
forecastAt={forecastAt}
displayAs={display.displayAs}
pinnable={pinnable}
pinned={display.isPinned(pin)}
+58 -8
View File
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it } from "vitest";
import { i18n } from "@/i18n/i18next";
import {
resolveUsageReport,
markUsageRefreshFailure,
displayPercent,
resolveAgentUsageView,
replaceReport,
@@ -82,7 +83,7 @@ describe("resolveUsageView", () => {
expect(resolveUsageView({ ...base, query: undefined })).toEqual({ kind: "loading" });
expect(
resolveUsageView({ ...base, query: { data: [], error: null, isFetching: true } }),
).toEqual({ kind: "ready", reports: [], isRefreshing: true });
).toEqual({ kind: "ready", reports: [], isRefreshing: true, refreshFailed: false });
expect(
resolveUsageView({
...base,
@@ -90,6 +91,19 @@ describe("resolveUsageView", () => {
}),
).toEqual({ kind: "error", message: "boom" });
});
it("shows a failed Refresh all alongside the reports still on screen", () => {
const reports = [entry({})];
expect(
resolveUsageView({
hostLabel: "Laptop",
isConnected: true,
supportsUsage: true,
query: ready(reports),
refreshState: "failed",
}),
).toEqual({ kind: "ready", reports, isRefreshing: false, refreshFailed: true });
});
});
afterEach(async () => {
@@ -203,15 +217,12 @@ describe("displayPercent", () => {
describe("resolveUsageRefresh", () => {
it("is pending while a refresh runs, even after an earlier failure", () => {
expect(resolveUsageRefresh({ isPending: true, error: new Error("boom") })).toBe("pending");
expect(resolveUsageRefresh({ isPending: true, isError: true })).toBe("pending");
});
it("is failed after a refresh errors", () => {
expect(resolveUsageRefresh({ isPending: false, error: new Error("boom") })).toBe("failed");
});
it("is idle before and after a successful refresh", () => {
expect(resolveUsageRefresh({ isPending: false, error: null })).toBe("idle");
it("reports the request outcome independently of the reading", () => {
expect(resolveUsageRefresh({ isPending: false, isError: true })).toBe("failed");
expect(resolveUsageRefresh({ isPending: false, isError: false })).toBe("idle");
});
});
@@ -352,6 +363,7 @@ it("resolves retained usage and successful time without inventing old-daemon his
details: [],
planLabel: null,
successfulAt: success.fetchedAt,
forecastAt: null,
retained: true,
messages: ["Rate limited"],
});
@@ -361,6 +373,7 @@ it("resolves retained usage and successful time without inventing old-daemon his
details: [],
planLabel: null,
successfulAt: null,
forecastAt: null,
retained: false,
messages: ["Rate limited"],
});
@@ -370,11 +383,48 @@ it("resolves retained usage and successful time without inventing old-daemon his
details: [],
planLabel: null,
successfulAt: success.fetchedAt,
forecastAt: success.fetchedAt,
retained: false,
messages: [],
});
});
it("uses the quota observation time for pace and keeps the reading after a failed request", () => {
const success = entry({ windows: [{ id: "weekly", label: "Weekly", usedPct: 42 }] });
if (success.report.status !== "available") throw new Error("fixture must be available");
const observedAt = success.fetchedAt;
const successfulAt = "2026-01-01T00:15:00.000Z";
const report = { ...success, successfulAt, report: { ...success.report, observedAt } };
expect(resolveUsageReport(report, i18n.t)).toMatchObject({
successfulAt,
forecastAt: observedAt,
});
expect(resolveUsageReport({ ...report, forecastStale: true }, i18n.t)).toMatchObject({
windows: success.report.windows,
successfulAt,
forecastAt: null,
});
});
it("keeps cached quota and hides its forecast when Refresh all fails before a new report arrives", () => {
const before = entry({ windows: [{ id: "weekly", label: "Weekly", usedPct: 42 }] });
const other = entry({ sourceId: "other" });
const refreshedAt = "2026-01-01T00:06:00.000Z";
const streamed = { ...other, fetchedAt: refreshedAt };
const attempted = [before, other];
const failed = markUsageRefreshFailure([before, streamed], attempted)!;
expect(resolveUsageReport(failed[0]!, i18n.t)).toMatchObject({
forecastAt: null,
windows: before.report.status === "available" ? before.report.windows : [],
});
expect(resolveUsageReport(failed[1]!, i18n.t).forecastAt).toBe(refreshedAt);
expect(resolveUsageReport(upsertReport(failed, before)[0]!, i18n.t).forecastAt).toBeNull();
const retried = settleReports(failed, [{ ...before, fetchedAt: refreshedAt }, streamed]);
expect(resolveUsageReport(retried[0]!, i18n.t).forecastAt).toBe(refreshedAt);
});
it("orders failed polls by attempt time even when successful data is older", () => {
const success = entry({});
if (success.report.status !== "available") throw new Error("fixture must be available");
+35 -7
View File
@@ -38,18 +38,31 @@ export function usageWindowRowLabel(input: {
return `${input.pinLabel}, ${summary}`;
}
/** A user-requested refresh of one report. The previous report stays on screen throughout. */
/** The outcome of a user-requested usage refresh. */
export type UsageRefresh = "idle" | "pending" | "failed";
export function resolveUsageRefresh(mutation: {
isPending: boolean;
error: unknown;
isError: boolean;
}): UsageRefresh {
if (mutation.isPending) return "pending";
if (mutation.error) return "failed";
if (mutation.isError) return "failed";
return "idle";
}
/** Keep quota readings after a failed refresh and attach the outcome to the readings it targeted. */
export function markUsageRefreshFailure(
current: UsageReportEntry[] | undefined,
attempted: readonly UsageReportEntry[],
): UsageReportEntry[] | undefined {
const attemptedAt = new Map(attempted.map((entry) => [entry.id, entry.fetchedAt]));
return current?.map((entry) =>
attemptedAt.get(entry.id) === entry.fetchedAt && !entry.forecastStale
? { ...entry, forecastStale: true }
: entry,
);
}
/**
* A host's report list with one report swapped for its refreshed copy, in place.
* `null` means the daemon no longer knows the ID, so the report leaves the list.
@@ -60,7 +73,9 @@ export function replaceReport(
refreshed: UsageReportEntry | null,
): UsageReportEntry[] {
if (!refreshed) return reports.filter((report) => report.id !== reportId);
return reports.map((report) => (report.id === reportId ? refreshed : report));
return reports.map((report) =>
report.id === reportId ? laterFetched(report, refreshed) : report,
);
}
/**
@@ -68,7 +83,9 @@ export function replaceReport(
* started, so a Refresh that lands while it streams is newer than what the request still delivers.
*/
function laterFetched(shown: UsageReportEntry, arriving: UsageReportEntry): UsageReportEntry {
return Date.parse(shown.fetchedAt) > Date.parse(arriving.fetchedAt) ? shown : arriving;
const shownAt = Date.parse(shown.fetchedAt);
const arrivingAt = Date.parse(arriving.fetchedAt);
return shownAt > arrivingAt || (shownAt === arrivingAt && shown.forecastStale) ? shown : arriving;
}
/**
@@ -117,10 +134,11 @@ export function resolveUsageView(
isConnected: boolean;
supportsUsage: boolean;
query: UsageQueryState | undefined;
refreshState?: UsageRefresh;
},
t: TFunction = i18n.t,
): UsageView {
const { hostLabel, isConnected, supportsUsage, query } = input;
const { hostLabel, isConnected, supportsUsage, query, refreshState } = input;
if (!isConnected)
return {
kind: "unavailable",
@@ -135,7 +153,12 @@ export function resolveUsageView(
if (input.enabled === false)
return { kind: "off", message: t("providerUsage.off", { host: hostLabel }) };
if (query?.data) {
return { kind: "ready", reports: query.data, isRefreshing: query.isFetching };
return {
kind: "ready",
reports: query.data,
isRefreshing: query.isFetching || refreshState === "pending",
refreshFailed: refreshState === "failed",
};
}
if (query?.error) {
return {
@@ -250,7 +273,12 @@ export function resolveUsageReport(entry: UsageReportEntry, t: TFunction) {
// COMPAT(usageLoginErrors): added in v0.11.0, remove after 2027-04-05 once daemon floor >= v0.11.0.
else messages.push(usageProblemText(entry.report, t));
}
const forecastAt =
snapshot && !snapshot.retained && !entry.forecastStale
? (snapshot.report.observedAt ?? snapshot.successfulAt)
: null;
return {
forecastAt,
windows: snapshot?.report.windows ?? [],
balances: snapshot?.report.balances ?? [],
details: snapshot?.report.details ?? [],
+45
View File
@@ -0,0 +1,45 @@
import { describe, expect, it } from "vitest";
import { usagePace } from "./pace";
import type { UsageWindow } from "./types";
const day = "2026-11-20T";
const reading = (time: string) => `${day}${time}:00.000Z`;
const window: UsageWindow = {
id: "five_hour",
label: "Session",
durationSeconds: 18_000,
usedPct: 65,
resetsAt: reading("15:00"),
};
describe("usage pace", () => {
it("projects the limit from the sample time and keeps it fixed between readings", () => {
const sampledAt = reading("12:00");
const estimate = { kind: "runsOut", at: `${day}13:04:36.923Z` };
expect(usagePace(window, sampledAt, Date.parse(sampledAt))).toEqual(estimate);
expect(usagePace(window, sampledAt, Date.parse(reading("12:30")))).toEqual(estimate);
});
it("updates after a later reading and works with a remaining percentage", () => {
const close = reading("13:30");
const safe = reading("14:00");
const forecast = usagePace(window, close, Date.parse(close));
expect(forecast.kind).toBe("remaining");
if (forecast.kind === "remaining") expect(forecast.remainingAtResetPct).toBeCloseTo(7.14);
expect(
usagePace({ ...window, usedPct: undefined, remainingPct: 35 }, safe, Date.parse(safe)),
).toEqual({ kind: "remaining", remainingAtResetPct: 18.75 });
});
it("only forecasts with timing and an active, usable reading", () => {
const sampledAt = reading("12:00");
const now = Date.parse(sampledAt);
expect(usagePace({ ...window, durationSeconds: undefined }, sampledAt, now)).toEqual({
kind: "unknown",
});
expect(usagePace(window, null, now)).toEqual({ kind: "unknown" });
expect(usagePace(window, reading("10:01"), now)).toEqual({ kind: "unknown" });
expect(usagePace(window, sampledAt, Date.parse(window.resetsAt!))).toEqual({ kind: "unknown" });
expect(usagePace({ ...window, usedPct: 100 }, sampledAt, now)).toEqual({ kind: "reached" });
});
});
+45
View File
@@ -0,0 +1,45 @@
import { usedPercent } from "./model";
import type { UsageWindow } from "./types";
type UsagePace =
| { kind: "unknown" }
| { kind: "reached" }
| { kind: "runsOut"; at: string }
| { kind: "remaining"; remainingAtResetPct: number };
/** Estimate from the window's average pace as of the reading. The clock only expires the estimate. */
export function usagePace(window: UsageWindow, observedAt: string | null, now: number): UsagePace {
if (observedAt === null) return { kind: "unknown" };
const reset = Date.parse(window.resetsAt ?? "");
if (reset <= now) return { kind: "unknown" };
const used = usedPercent(window);
if (used != null && used >= 100) return { kind: "reached" };
const supplied = window.runsOutAt;
const suppliedAt = Date.parse(supplied ?? "");
if (supplied && Number.isFinite(suppliedAt) && (!Number.isFinite(reset) || suppliedAt < reset)) {
return { kind: "runsOut", at: supplied };
}
const duration = (window.durationSeconds ?? 0) * 1_000;
const sampled = Date.parse(observedAt);
const elapsed = sampled - (reset - duration);
if (
used == null ||
!Number.isFinite(used) ||
used < 0 ||
!Number.isFinite(elapsed) ||
sampled >= reset ||
elapsed < Math.max(60_000, duration * 0.01)
) {
return { kind: "unknown" };
}
const projectedAtReset = (used / elapsed) * duration;
if (projectedAtReset > 100) {
const runsOut = sampled + ((100 - used) / used) * elapsed;
return { kind: "runsOut", at: new Date(runsOut).toISOString() };
}
return { kind: "remaining", remainingAtResetPct: 100 - projectedAtReset };
}
+42 -19
View File
@@ -20,6 +20,7 @@ import { useSessionStore, type SessionState } from "@/stores/session-store";
import { useUsageSetting } from "./setting";
import { usageCopy } from "./copy";
import {
markUsageRefreshFailure,
replaceReport,
resolveAgentUsageView,
resolveUsageRefresh,
@@ -97,17 +98,32 @@ async function streamReports(input: {
return settleReports(queryClient.getQueryData<UsageReportEntry[]>(queryKey), reports);
}
function listReports(
async function listReports(
queryClient: QueryClient,
serverId: string,
forceRefresh = false,
): Promise<UsageReportEntry[]> {
return streamReports({
queryClient,
queryKey: usageReportsQueryKey(serverId),
serverId,
forceRefresh,
});
const queryKey = usageReportsQueryKey(serverId);
const attempted = queryClient.getQueryData<UsageReportEntry[]>(queryKey) ?? [];
try {
return await streamReports({ queryClient, queryKey, serverId, forceRefresh });
} catch (error) {
recordUsageRefreshFailure(queryClient, queryKey, attempted);
throw error;
}
}
function recordUsageRefreshFailure(
queryClient: QueryClient,
queryKey: QueryKey,
attempted: readonly UsageReportEntry[],
): void {
const { dataUpdatedAt } = queryClient.getQueryState(queryKey) ?? {};
queryClient.setQueryData<UsageReportEntry[]>(
queryKey,
(current) => markUsageRefreshFailure(current, attempted),
{ updatedAt: dataUpdatedAt },
);
}
async function getReport(
@@ -158,9 +174,12 @@ export function useHostUsage(serverId: string): { view: UsageView; refresh: () =
dataShape: "value",
staleTimeMs: REPORTS_STALE_TIME_MS,
});
const refresh = useCallback(() => {
void refreshReports(queryClient, serverId).catch(() => undefined);
}, [queryClient, serverId]);
const mutation = useMutation({
mutationKey: [...usageReportsQueryKey(serverId), "refresh"],
mutationFn: (hostId: string) => refreshReports(queryClient, hostId),
});
const { mutate, variables } = mutation;
const refresh = useCallback(() => mutate(serverId), [mutate, serverId]);
const { t } = useTranslation();
const hostLabel = useHosts().find((host) => host.serverId === serverId)?.label ?? serverId;
const view = resolveUsageView(
@@ -170,6 +189,7 @@ export function useHostUsage(serverId: string): { view: UsageView; refresh: () =
isConnected,
supportsUsage: isSupported,
query: toQueryState(query),
refreshState: variables === serverId ? resolveUsageRefresh(mutation) : "idle",
},
t,
);
@@ -265,23 +285,26 @@ export function useUsageHosts(): UsageHost[] {
*/
export function useReportRefresh(
serverId: string,
reportId: string,
entry: UsageReportEntry,
agentId?: string,
): { refresh: () => void; refreshState: UsageRefresh } {
const queryClient = useQueryClient();
const usageScopeKey = useAgentUsageScopeKey(serverId, agentId);
const queryKey =
agentId === undefined
? usageReportsQueryKey(serverId)
: agentUsageQueryKey(serverId, agentId, usageScopeKey);
const mutation = useMutation({
mutationFn: () => getReport(serverId, reportId, true, agentId),
onSuccess: (report) => {
queryClient.setQueryData<UsageReportEntry[]>(
agentId === undefined
? usageReportsQueryKey(serverId)
: agentUsageQueryKey(serverId, agentId, usageScopeKey),
(reports) => (reports ? replaceReport(reports, reportId, report) : reports),
mutationKey: [...queryKey, "refresh", entry.id],
mutationFn: (attempted: UsageReportEntry) => getReport(serverId, attempted.id, true, agentId),
onSuccess: (report, attempted) => {
queryClient.setQueryData<UsageReportEntry[]>(queryKey, (reports) =>
reports ? replaceReport(reports, attempted.id, report) : reports,
);
},
onError: (_error, attempted) => recordUsageRefreshFailure(queryClient, queryKey, [attempted]),
});
const { mutate } = mutation;
const refresh = useCallback(() => mutate(), [mutate]);
const refresh = useCallback(() => mutate(entry), [mutate, entry]);
return { refresh, refreshState: resolveUsageRefresh(mutation) };
}
+5 -13
View File
@@ -3,24 +3,21 @@ import { StyleSheet } from "react-native-unistyles";
/**
* The reset data of a window or balance: the countdown first, then the exact time. When the line
* is too narrow the exact time gives way (truncates) and the countdown stays whole.
* is too narrow the exact time truncates and the countdown wraps within its column.
*/
export function UsageResetLine({
countdown,
exactTime,
atRisk = false,
testID,
}: {
countdown: string | null;
exactTime: string | null;
/** The countdown is a runs-out warning rather than a reset. */
atRisk?: boolean;
testID?: string;
}) {
if (!countdown) return null;
return (
<View style={styles.line} testID={testID}>
<Text style={atRisk ? styles.atRisk : styles.text}>{countdown}</Text>
<Text style={[styles.text, styles.countdown]}>{countdown}</Text>
{exactTime ? (
<Text style={[styles.text, styles.exactTime]} numberOfLines={1} ellipsizeMode="tail">
{`\u00a0·\u00a0${exactTime}`}
@@ -31,18 +28,13 @@ export function UsageResetLine({
}
const styles = StyleSheet.create((theme) => ({
line: { flexDirection: "row", alignItems: "center" },
line: { flexDirection: "row", alignItems: "baseline" },
text: {
flexShrink: 0,
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
fontWeight: theme.fontWeight.normal,
},
atRisk: {
flexShrink: 0,
color: theme.colors.statusDanger,
fontSize: theme.fontSize.sm,
fontWeight: theme.fontWeight.normal,
},
exactTime: { flexShrink: 1 },
countdown: { maxWidth: "100%" },
exactTime: { flexShrink: 1, minWidth: 0 },
}));
+9 -3
View File
@@ -1,6 +1,12 @@
import type { ProviderUsageTone, UsageReportEntry } from "@getpaseo/protocol/messages";
import type {
ProviderUsageTone,
UsageReportEntry as WireUsageReportEntry,
} from "@getpaseo/protocol/messages";
export type { UsageReportEntry };
export interface UsageReportEntry extends WireUsageReportEntry {
/** A refresh failed while this reading was cached. */
forecastStale?: true;
}
export type UsageReport = UsageReportEntry["report"];
export type UsageTone = ProviderUsageTone;
export type AvailableUsageReport = Extract<UsageReport, { status: "available" }>;
@@ -14,4 +20,4 @@ export type UsageView =
| { kind: "unavailable"; message: string }
| { kind: "loading" }
| { kind: "error"; message: string }
| { kind: "ready"; reports: UsageReportEntry[]; isRefreshing: boolean };
| { kind: "ready"; reports: UsageReportEntry[]; isRefreshing: boolean; refreshFailed: boolean };
+13 -5
View File
@@ -84,11 +84,18 @@ export function UsageBody({
);
}
if (view.reports.length === 0) {
return <UsageMessage text={t("providerUsage.empty")} />;
}
return <UsageList serverId={serverId} reports={view.reports} 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} />
)}
</View>
);
}
export function UsageMessage({ text }: { text: string }) {
@@ -100,6 +107,7 @@ export function UsageMessage({ text }: { text: string }) {
}
const styles = StyleSheet.create((theme) => ({
reports: { gap: theme.spacing[3] },
emptyCard: {
padding: theme.spacing[4],
alignItems: "center",
+71 -22
View File
@@ -1,3 +1,4 @@
import type { TFunction } from "i18next";
import { Pin } from "lucide-react-native";
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
@@ -6,6 +7,7 @@ import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import {
formatDisplayPct,
formatPct,
formatProviderUsageLabel,
formatResetLabel,
formatResetTime,
@@ -13,9 +15,9 @@ import {
} from "./format";
import { UsageMeter } from "./meter";
import { displayPercent, usageWindowRowLabel } from "./model";
import { usagePace } from "./pace";
import { UsageResetLine } from "./reset-line";
import type { UsageDisplayAs } from "./preferences";
import { windowTone } from "./tone";
import type { UsageTone, UsageWindow } from "./types";
import { useRelativeTimeTick } from "./use-relative-time-tick";
@@ -28,8 +30,10 @@ export function UsageWindowBar({
pinLabel,
pinTestID,
retained = false,
forecastAt,
}: {
retained?: boolean;
forecastAt: string | null;
window: UsageWindow;
displayAs: UsageDisplayAs;
/** Whether the row pins the window to the sidebar. When false the row is a plain bar. */
@@ -42,19 +46,11 @@ export function UsageWindowBar({
}) {
const { t, i18n } = useTranslation();
const shownPct = displayPercent(window, displayAs);
const tone = windowTone(window);
const now = useRelativeTimeTick({ enabled: window.runsOutAt != null || window.resetsAt != null });
const isAtRisk =
window.runsOutAt != null &&
window.shortfallPct != null &&
(!retained || Date.parse(window.runsOutAt) > now);
const countdown = isAtRisk
? formatRunsOutLabel(window.runsOutAt, now, t)
: formatResetLabel(window.resetsAt, retained, now, t);
// The exact time belongs to the reset; beside a runs-out warning it would read as the moment
// the quota runs out.
const exactTime = isAtRisk ? null : formatResetTime(window.resetsAt, now, t);
const pace = usagePace(window, forecastAt, now);
const forecast = formatPace(pace, now, t);
const countdown = formatResetLabel(window.resetsAt, retained, now, t);
const exactTime = formatResetTime(window.resetsAt, now, t);
const value =
shownPct != null ? formatDisplayPct(shownPct, displayAs, i18n.resolvedLanguage, t) : "—";
@@ -64,9 +60,8 @@ export function UsageWindowBar({
value,
countdown,
exactTime,
isAtRisk,
forecast,
percent: shownPct ?? 0,
tone,
pinned,
};
@@ -86,7 +81,7 @@ export function UsageWindowBar({
accessibilityLabel={usageWindowRowLabel({
pinLabel,
value,
trailing: [countdown, exactTime].filter(Boolean).join(" · "),
trailing: [countdown, exactTime, forecast?.label].filter(Boolean).join(" · "),
})}
accessibilityState={accessibilityState}
aria-checked={pinned}
@@ -103,9 +98,8 @@ function WindowRowContent({
value,
countdown,
exactTime,
isAtRisk,
forecast,
percent,
tone,
pinnable,
pinned,
}: {
@@ -113,9 +107,8 @@ function WindowRowContent({
value: string;
countdown: string | null;
exactTime: string | null;
isAtRisk: boolean;
forecast: PaceLabel | null;
percent: number;
tone: UsageTone;
pinnable: boolean;
pinned: boolean;
}) {
@@ -130,12 +123,51 @@ function WindowRowContent({
</Text>
{pinnable ? <UsagePinGlyph pinned={pinned} /> : null}
</View>
<UsageMeter percent={percent} tone={tone} />
<UsageResetLine countdown={countdown} exactTime={exactTime} atRisk={isAtRisk} />
<UsageMeter percent={percent} tone={forecast?.tone ?? "default"} />
{countdown || forecast ? (
<View style={styles.timingRow}>
<View style={styles.resetTiming}>
<UsageResetLine countdown={countdown} exactTime={exactTime} />
</View>
{forecast ? <Text style={styles.forecast(forecast.tone)}>{forecast.label}</Text> : null}
</View>
) : null}
</>
);
}
interface PaceLabel {
label: string;
tone: UsageTone;
}
function formatPace(
pace: ReturnType<typeof usagePace>,
now: number,
t: TFunction,
): PaceLabel | null {
switch (pace.kind) {
case "reached":
return { label: t("providerUsage.timing.limitReached"), tone: "danger" };
case "runsOut": {
const label =
Date.parse(pace.at) <= now
? t("providerUsage.timing.mayHaveRunOut")
: formatRunsOutLabel(pace.at, now, t);
return label ? { label, tone: "danger" } : null;
}
case "remaining":
return {
label: t("providerUsage.timing.projectedLeftAtReset", {
percentage: formatPct(pace.remainingAtResetPct),
}),
tone: pace.remainingAtResetPct <= 10 ? "warning" : "default",
};
case "unknown":
return null;
}
}
const ThemedPin = withUnistyles(Pin);
function UsagePinGlyph({ pinned }: { pinned: boolean }) {
@@ -167,6 +199,23 @@ function UsagePinGlyph({ pinned }: { pinned: boolean }) {
}
const styles = StyleSheet.create((theme) => ({
timingRow: {
flexDirection: "row",
alignItems: "flex-start",
gap: theme.spacing[2],
},
resetTiming: { flex: 1, minWidth: 0 },
forecast: (tone: UsageTone) => ({
color: {
danger: theme.colors.statusDanger,
warning: theme.colors.statusWarning,
default: theme.colors.foregroundMuted,
ok: theme.colors.statusSuccess,
}[tone],
fontSize: theme.fontSize.sm,
maxWidth: "50%",
textAlign: "right",
}),
row: { gap: 3, paddingVertical: theme.spacing[1.5] },
pin: { width: 12, alignItems: "center" },
tooltipText: { color: theme.colors.popoverForeground, fontSize: theme.fontSize.sm },
+7 -7
View File
@@ -96,12 +96,12 @@ test.each([
])(
"duration %s owns the window's identity and both names",
(durationSeconds, id, label, shortLabel) => {
expect(
windowFromReportedDuration({
durationSeconds: durationSeconds as number | null,
unknown: { id: "primary", label: "Primary limit", shortLabel: "" },
utilizationPct: 11,
}),
).toMatchObject({ id, label, shortLabel, usedPct: 11 });
const window = windowFromReportedDuration({
durationSeconds: durationSeconds as number | null,
unknown: { id: "primary", label: "Primary limit", shortLabel: "" },
utilizationPct: 11,
});
expect(window).toMatchObject({ id, label, shortLabel, usedPct: 11 });
expect(window.durationSeconds).toBe(durationSeconds ?? undefined);
},
);
+11 -5
View File
@@ -16,6 +16,8 @@ export interface UsageWindow {
usedPct?: number | null;
remainingPct?: number | null;
resetsAt?: string | null;
/** Full length of the quota window when known. */
durationSeconds?: number;
runsOutAt?: string | null;
shortfallPct?: number | null;
tone?: "default" | "ok" | "warning" | "danger";
@@ -48,6 +50,8 @@ export type UsageReport =
| {
status: "available";
planLabel?: string;
/** When the provider measured the quota, if the report returns a previous reading. */
observedAt?: string;
windows: UsageWindow[];
balances?: UsageBalance[];
details?: UsageDetail[];
@@ -96,6 +100,7 @@ export function windowFromUsedPct(input: {
shortLabel?: string;
summary?: boolean;
utilizationPct: number | null | undefined;
durationSeconds?: number;
resetsAt?: string | null;
tone?: UsageWindow["tone"];
}): UsageWindow {
@@ -107,6 +112,7 @@ export function windowFromUsedPct(input: {
remainingPct: usedPct === null ? null : Math.max(0, 100 - usedPct),
resetsAt: input.resetsAt ?? null,
};
if (input.durationSeconds !== undefined) window.durationSeconds = input.durationSeconds;
if (input.shortLabel !== undefined) window.shortLabel = input.shortLabel;
if (input.summary) window.summary = true;
if (input.tone) window.tone = input.tone;
@@ -129,11 +135,10 @@ export function windowFromReportedDuration(input: {
summary?: boolean;
tone?: UsageWindow["tone"];
}): UsageWindow {
const duration = input.durationSeconds;
const name =
duration !== null && Number.isFinite(duration) && duration > 0
? durationWindowName(duration)
: input.unknown;
const reported = input.durationSeconds;
const duration =
reported !== null && Number.isFinite(reported) && reported > 0 ? reported : undefined;
const name = duration === undefined ? input.unknown : durationWindowName(duration);
const scope = input.scope;
return windowFromUsedPct({
id: scope ? `${scope.id}:${name.id}` : name.id,
@@ -142,6 +147,7 @@ export function windowFromReportedDuration(input: {
? `${scope.label}${name.shortLabel ? ` ${name.shortLabel}` : ""}`
: name.shortLabel,
utilizationPct: input.utilizationPct,
durationSeconds: duration,
resetsAt: input.resetsAt,
summary: input.summary,
tone: input.tone,
+2
View File
@@ -6992,6 +6992,7 @@ export const ProviderUsageWindowSchema = z.object({
usedPct: z.number().nullable().optional(),
remainingPct: z.number().nullable().optional(),
resetsAt: z.string().nullable().optional(),
durationSeconds: z.number().optional(),
runsOutAt: z.string().nullable().optional(),
shortfallPct: z.number().nullable().optional(),
tone: ProviderUsageToneSchema.optional(),
@@ -7054,6 +7055,7 @@ export const UsageProblemSchema = z.discriminatedUnion("kind", [
const AvailableUsageReportSchema = z.object({
status: z.literal("available"),
planLabel: z.string().optional(),
observedAt: z.string().optional(),
windows: z.array(ProviderUsageWindowSchema),
balances: z.array(ProviderUsageBalanceSchema).optional(),
details: z.array(ProviderUsageDetailSchema).optional(),
@@ -56,6 +56,17 @@ function shortWindow(window: string): string {
return trimmed;
}
function windowDurationSeconds(window: string): number | undefined {
switch (window.trim().toLowerCase()) {
case "5h":
return 5 * 3600;
case "weekly":
return 7 * 86400;
default:
return undefined;
}
}
function shortGroupName(name: string): string {
return name
.trim()
@@ -129,6 +140,7 @@ export class Usage {
shortLabel: formatShortLabel(group.name, bucket.window, includeGroup),
summary: !bucket.disabled && bucket.window === "weekly",
utilizationPct: used,
durationSeconds: windowDurationSeconds(bucket.window),
resetsAt: bucket.disabled ? null : bucket.reset_time,
tone: used === null ? "default" : toneFromUsedPct(used),
}),
@@ -263,6 +263,7 @@ function unscopedWindows(resp: ClaudeUsageResponse): UsageWindow[] {
shortLabel: spec.shortLabel,
summary: spec.summary,
utilizationPct: window.utilization,
durationSeconds: spec.field === "five_hour" ? 5 * 3600 : 7 * 86400,
resetsAt: window.resets_at ?? null,
tone: toneFromUsedPct(window.utilization),
}),
@@ -283,6 +284,7 @@ function scopedWindows(limits: ScopedLimit[]): UsageWindow[] {
label: `Weekly \u00b7 ${limit.name}`,
shortLabel: `wk ${limit.name}`,
utilizationPct: limit.usedPct,
durationSeconds: 7 * 86400,
resetsAt: limit.resetsAt,
tone: toneFromUsedPct(limit.usedPct),
});
+3 -1
View File
@@ -86,8 +86,10 @@ export class Usage {
try {
const { usage } = await this.read(account, launch);
if (!usage) return unavailable({ kind: "no_quota", detail: "No usage quota reported" });
const observedAt = new Date(usage.observedAtMs).toISOString();
return {
status: "available",
observedAt,
planLabel: usage.tier,
windows: [
windowFromReportedDuration({
@@ -112,7 +114,7 @@ export class Usage {
{
id: "observed",
label: "Observed",
value: new Date(usage.observedAtMs).toISOString(),
value: observedAt,
},
],
};
+5 -1
View File
@@ -1505,6 +1505,7 @@ for (const usage of [
expect(report).toMatchObject({
status: "available",
planLabel: "Pro",
observedAt: new Date(usage.usage.observedAtMs).toISOString(),
windows: [
{
id: "five_hour",
@@ -1800,7 +1801,10 @@ test("Muse reports belong only to the session's account and remain available glo
for (const [index, agentId] of ["muse-home", "muse-work"].entries()) {
const reports = await registry.listReports({ agentId });
expect(reports.map((report) => report.id)).toEqual([accountIds[index]]);
expect(reports[0]!.report.status).toBe("available");
expect(reports[0]!.report).toMatchObject({
status: "available",
observedAt: "2023-11-14T22:13:20.000Z",
});
}
expect(await registry.listReports({ agentId: "muse-unknown" })).toEqual([]);
expect((await registry.listReports()).map((report) => report.id)).toEqual(accountIds);
+5 -1
View File
@@ -616,7 +616,11 @@ For numeric durations, use `windowFromReportedDuration()` from
`@getpaseo/plugin/server/usage` (Paseo 0.11+). Pass the reported seconds or `null`, a neutral
`unknown` identity and name, and an optional stable quota `scope`. The helper derives the ID,
label, and short label together; it accepts no duration-label override. For named API periods,
use `windowFromUsedPct()` with names justified by that field.
use `windowFromUsedPct()` with names justified by that field. Set `durationSeconds` when
the period has a known fixed length. Usage Details uses it with the reset time and the
latest reading to estimate whether the quota will last until reset. If the source returns
a previous reading, include its measurement time as an ISO timestamp in the report’s
`observedAt` field.
A window ID identifies a quota scope and period, never its response position, utilization, or
reset instant. Scope model-specific quotas by the provider's stable feature ID, falling back to