From 1e30f9e04679e6a47d4f265fa179d7675187f3e1 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sat, 21 Nov 2026 20:08:09 +0700 Subject: [PATCH] Polish Usage quota bars, labels, and forecasts (#10397) * fix(usage): clarify quota labels and show weekly forecasts sooner * fix(usage): show the exhaustion time and keep exhausted bars red * fix(usage): hide forecast text for quotas on track * fix(usage): label quota times by local calendar date * test(usage): keep the exhaustion clock test stable at midnight --- packages/app/e2e/browser/usage-modal.spec.ts | 37 +++++--- packages/app/src/i18n/resources/ar.ts | 4 +- packages/app/src/i18n/resources/en.ts | 4 +- packages/app/src/i18n/resources/es.ts | 4 +- packages/app/src/i18n/resources/fr.ts | 4 +- packages/app/src/i18n/resources/ja.ts | 4 +- packages/app/src/i18n/resources/ko.ts | 4 +- packages/app/src/i18n/resources/pt-BR.ts | 4 +- packages/app/src/i18n/resources/ru.ts | 4 +- packages/app/src/i18n/resources/zh-CN.ts | 4 +- packages/app/src/usage/bars.browser.test.tsx | 89 ++++++++++++++++++- packages/app/src/usage/format.test.ts | 65 ++++++++++---- packages/app/src/usage/format.ts | 21 +++-- packages/app/src/usage/meter.tsx | 7 +- packages/app/src/usage/pace.test.ts | 21 ++++- packages/app/src/usage/pace.ts | 8 +- packages/app/src/usage/window-bar.tsx | 41 ++++----- packages/app/src/utils/time.ts | 12 +-- .../antigravity-provider/server/usage.test.ts | 21 ++++- plugins/antigravity-provider/server/usage.ts | 34 ++++--- 20 files changed, 262 insertions(+), 130 deletions(-) diff --git a/packages/app/e2e/browser/usage-modal.spec.ts b/packages/app/e2e/browser/usage-modal.spec.ts index 4418ff24f..26b77b10f 100644 --- a/packages/app/e2e/browser/usage-modal.spec.ts +++ b/packages/app/e2e/browser/usage-modal.spec.ts @@ -836,6 +836,8 @@ test("usage percentages state their meaning and follow the selected language", a } }); +const exhaustionClock = /^runs out (?:[A-Z][a-z]{2} )?\d{1,2}:\d{2}(?: [AP]M)?$/; + test("open usage clocks advance without refreshing or reopening", async ({ page }) => { test.setTimeout(120_000); const now = new Date(); @@ -853,12 +855,16 @@ test("open usage clocks advance without refreshing or reopening", async ({ page const card = page.getByTestId("usage-report-login-journey:account"); await expect(card.getByTestId("usage-freshness")).toHaveText("Updated just now"); await expect(card.getByText("resets in 30m", { exact: false }).first()).toBeVisible(); + const forecast = card.getByText(exhaustionClock); + await expect(forecast).toBeVisible(); + const forecastTime = (await forecast.innerText()).replace(/^[^0-9]+/, ""); // The shared minute clock is wall-aligned, and the daemon timestamps use real time. // After two browser minutes the latest displayed tick is one or two minutes old. await advanceUsageClock(page, 120_000); await expect(card.getByTestId("usage-freshness")).toHaveText(/^Updated [12]m ago$/); await expect(card.getByText(/resets in (28|29)m/).first()).toBeVisible(); - await expect(card.getByText(/runs out in (28|29)m/)).toBeVisible(); + // The weekday drops off at local midnight, but the forecast time stays fixed. + await expect(forecast).toHaveText(new RegExp(` ${forecastTime}$`)); await expect(card.getByTestId("provider-usage-balance-credits-reset")).toHaveText( /^resets in (28|29)m\s·\s/, ); @@ -867,7 +873,7 @@ 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 ({ +test("Refresh all keeps quota visible after a timeout and shows only reset details when back on track", async ({ page, }) => { const reading = new Date(); @@ -875,7 +881,7 @@ test("Refresh all keeps quota visible and restores the forecast after a timeout" try { const transport = await installDaemonWebSocketGate(page); await openCompactUsageWithClock(page, reading); - await expectQuota(page, "40% used", /runs out in /); + await expectQuota(page, "40% used", exhaustionClock); await timeOutUsageRefresh(page, transport); await expectQuota(page, "40% used", null); @@ -884,7 +890,7 @@ test("Refresh all keeps quota visible and restores the forecast after a timeout" await login.setReport(usageReading(reading, 10)); transport.releaseHeldClientRequest(); await refreshAllUsage(page); - await expectQuota(page, "10% used", "~50% left at reset"); + await expectQuota(page, "10% used", null); await expectUsageRefreshError(page).toBeHidden(); } finally { await login.cleanup(); @@ -897,23 +903,29 @@ test("a card refresh timeout is visible alongside a newer quota forecast", async try { const transport = await installDaemonWebSocketGate(page); await openCompactUsageWithClock(page, reading); - await expectQuota(page, "40% used", /runs out in /); + await expectQuota(page, "40% used", exhaustionClock); await delayCardRefreshResponse(page, transport); - await login.setReport(usageReading(reading, 10)); + await login.setReport(usageReading(reading, 45)); await refreshAllUsage(page); - await expectQuota(page, "10% used", "~50% left at reset"); + await expectQuota(page, "45% used", exhaustionClock); await advanceUsageClock(page, 61_000); - await expectUsageRefreshError(page).toBeVisible(); - await expectQuota(page, "10% used", "~50% left at reset"); + await expect( + usageModal(page) + .getByTestId("usage-report-login-journey:account") + .getByTestId("usage-refresh-error"), + ).toHaveText("Unable to refresh usage"); + await expectQuota(page, "45% used", exhaustionClock); } finally { await login.cleanup(); } }); function expectUsageRefreshError(page: Page) { - return expect(usageModal(page).getByText("Unable to refresh usage", { exact: true })); + return expect( + usageModal(page).getByRole("alert").getByText("Unable to refresh usage", { exact: true }), + ); } async function delayCardRefreshResponse( @@ -947,7 +959,10 @@ async function expectQuota(page: Page, amount: string, forecast: string | RegExp 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(); + await expect(usage.getByRole("checkbox", { name: /^Pin Claude Session/ })).toHaveAccessibleName( + /^Pin Claude Session, \d+% used · resets in [^·]+ · [^·]+$/, + ); + await expect(usage.getByText(/^runs out /)).toBeHidden(); return; } await expect(usage.getByText(forecast)).toBeVisible(); diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index ae0f63333..1826f63ba 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -2323,11 +2323,9 @@ export const ar: TranslationResources = { resetsIn: "تتم إعادة التعيين خلال {{duration}}", resetsAtWeekday: "{{weekday}} {{time}}", resetsAtDate: "{{date}}، {{time}}", - projectedLeftAtReset: "نحو {{percentage}} متبقية عند إعادة التعيين", limitReached: "تم بلوغ الحد", mayHaveRunOut: "ربما نفدت الحصة", - runsOutNow: "ينفد الآن", - runsOutIn: "ينفد خلال {{duration}}", + runsOutAt: "ينفد عند {{time}}", justNow: "الآن", daysAgo: "قبل {{value}} يومًا", daysAgo_zero: "قبل {{value}} يوم", diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index 1cf2ef1a5..951e36271 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -2333,11 +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}}", + runsOutAt: "runs out {{time}}", justNow: "just now", daysAgo: "{{value}}d ago", hoursAgo: "{{value}}h ago", diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index e52d3239e..e99bdfb17 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -2354,11 +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}}", + runsOutAt: "agotamiento previsto {{time}}", justNow: "ahora mismo", daysAgo: "hace {{value}} d", hoursAgo: "hace {{value}} h", diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index 2d0b77156..981cfa72e 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -2355,11 +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}}", + runsOutAt: "épuisement prévu {{time}}", justNow: "à l’instant", daysAgo: "il y a {{value}} j", hoursAgo: "il y a {{value}} h", diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index 932b8397b..76d95f094 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -2328,11 +2328,9 @@ export const ja: TranslationResources = { resetsIn: "{{duration}}後にリセット", resetsAtWeekday: "{{weekday}} {{time}}", resetsAtDate: "{{date}} {{time}}", - projectedLeftAtReset: "リセット時に約{{percentage}}残る見込み", limitReached: "上限に達しました", mayHaveRunOut: "上限に達した可能性があります", - runsOutNow: "まもなく上限に到達", - runsOutIn: "{{duration}}後に上限に到達", + runsOutAt: "{{time}}に上限に到達", justNow: "たった今", daysAgo: "{{value}}日前", hoursAgo: "{{value}}時間前", diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index 1bc5d4d65..b7bad0f67 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -2316,11 +2316,9 @@ export const ko: TranslationResources = { resetsIn: "{{duration}} 후 재설정", resetsAtWeekday: "{{weekday}} {{time}}", resetsAtDate: "{{date}} {{time}}", - projectedLeftAtReset: "초기화 시 약 {{percentage}} 남을 예정", limitReached: "한도에 도달함", mayHaveRunOut: "한도를 소진했을 수 있음", - runsOutNow: "지금 한도에 도달", - runsOutIn: "{{duration}} 후 한도에 도달", + runsOutAt: "{{time}}에 한도에 도달", justNow: "방금", daysAgo: "{{value}}일 전", hoursAgo: "{{value}}시간 전", diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index 098a5f94e..62d408baf 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -2339,11 +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}}", + runsOutAt: "esgotamento previsto para {{time}}", justNow: "agora mesmo", daysAgo: "há {{value}} d", hoursAgo: "há {{value}} h", diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index 137deb08b..4185c2d48 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -2341,11 +2341,9 @@ export const ru: TranslationResources = { resetsIn: "сброс через {{duration}}", resetsAtWeekday: "{{weekday}} {{time}}", resetsAtDate: "{{date}}, {{time}}", - projectedLeftAtReset: "К сбросу останется ~{{percentage}}", limitReached: "Лимит исчерпан", mayHaveRunOut: "Лимит мог уже исчерпаться", - runsOutNow: "закончится сейчас", - runsOutIn: "закончится через {{duration}}", + runsOutAt: "закончится {{time}}", justNow: "только что", daysAgo: "{{value}} дн. назад", hoursAgo: "{{value}} ч назад", diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index 8f74dccb3..e1ba06b09 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -2282,11 +2282,9 @@ export const zhCN: TranslationResources = { resetsIn: "将在 {{duration}}后重置", resetsAtWeekday: "{{weekday}} {{time}}", resetsAtDate: "{{date}} {{time}}", - projectedLeftAtReset: "重置时约剩余 {{percentage}}", limitReached: "已达到上限", mayHaveRunOut: "额度可能已用完", - runsOutNow: "即将用尽", - runsOutIn: "将在 {{duration}}后用尽", + runsOutAt: "将在 {{time}} 用尽", justNow: "刚刚", daysAgo: "{{value}}天前", hoursAgo: "{{value}}小时前", diff --git a/packages/app/src/usage/bars.browser.test.tsx b/packages/app/src/usage/bars.browser.test.tsx index c300b845c..2e8ba2483 100644 --- a/packages/app/src/usage/bars.browser.test.tsx +++ b/packages/app/src/usage/bars.browser.test.tsx @@ -5,8 +5,10 @@ import { i18n } from "@/i18n/i18next"; import { UsageWindowBar } from "./window-bar"; import type { UsageBalance, UsageWindow } from "./types"; import { UsageBalanceBar } from "./balance-bar"; +import { UsageMeter } from "./meter"; const window: UsageWindow = { id: "session", label: "Session", usedPct: 70 }; +const exhaustedWindow: UsageWindow = { ...window, usedPct: 100 }; const balance: UsageBalance = { id: "credits", label: "Credits", unit: "usd", remaining: 12 }; const ignorePin = () => {}; @@ -53,16 +55,97 @@ it("translates mounted usage rows when the language changes", async () => { expect(container.textContent).toContain("クレジット"); }); +it("colors healthy quota bars green and keeps the warning and danger colors", () => { + act(() => + root.render( + <> + + + + + + , + ), + ); + const colors = Array.from( + container.children, + (track) => getComputedStyle(track.firstElementChild!).backgroundColor, + ); + expect(colors).toEqual([ + "rgb(21, 128, 61)", + "rgb(21, 128, 61)", + "rgb(217, 119, 6)", + "rgb(185, 28, 28)", + "rgb(212, 212, 216)", + ]); +}); + +it("keeps an exhausted quota red when a failed refresh removes its forecast", () => { + act(() => + root.render( + , + ), + ); + expect(container.textContent).toBe("Session100% used"); + const fill = container.firstElementChild!.children[1].firstElementChild!; + expect(getComputedStyle(fill).backgroundColor).toBe("rgb(185, 28, 28)"); +}); + const narrowReadingMs = Date.now(); const narrowForecastAt = new Date(narrowReadingMs).toISOString(); const narrowWindow: UsageWindow = { id: "weekly", label: "Weekly", - usedPct: 0.2, + usedPct: 6, durationSeconds: 604_800, resetsAt: new Date(narrowReadingMs + 165.5 * 3_600_000).toISOString(), }; +const onTrackWindow: UsageWindow = { + id: "session", + label: "Session", + usedPct: 40, + durationSeconds: 18_000, + resetsAt: new Date(narrowReadingMs + 3_600_000).toISOString(), +}; +const tightWindow: UsageWindow = { ...onTrackWindow, usedPct: 77 }; + +it.each([ + ["green", onTrackWindow, "rgb(21, 128, 61)"], + ["amber", tightWindow, "rgb(217, 119, 6)"], +] as const)("shows only the reset details for an on-track %s bar", (_, usageWindow, color) => { + act(() => + root.render( + , + ), + ); + + const row = container.firstElementChild!; + const [label, track, datapoints] = row.children; + expect(label.textContent).toBe(`Session${usageWindow.usedPct}% used`); + expect(datapoints.textContent).toMatch(/^resets in [^·]+\s· [^·]+$/); + expect(getComputedStyle(track.firstElementChild!).backgroundColor).toBe(color); +}); + it("shows the forecast as one more datapoint after the reset countdown, in the same line", async () => { act(() => root.render( @@ -82,7 +165,7 @@ it("shows the forecast as one more datapoint after the reset countdown, in the s const line = Array.from(container.querySelectorAll("*")).find((node) => node.textContent.startsWith("resets in"), ); - expect(line?.textContent).toMatch(/^resets in .+\s· .+\s· ~\d+% left at reset$/); + expect(line?.textContent).toMatch(/^resets in [^·]+\s· [^·]+\s· runs out .+$/); }); it("wraps the forecast below the countdown in a narrow French card instead of overlapping it", async () => { @@ -114,6 +197,6 @@ it("wraps the forecast below the countdown in a narrow French card instead of ov } const countdown = textBounds("se réinitialise"); - const forecast = textBounds("~"); + const forecast = textBounds("épuisement prévu"); expect(forecast.left >= countdown.right || forecast.top >= countdown.bottom).toBe(true); }); diff --git a/packages/app/src/usage/format.test.ts b/packages/app/src/usage/format.test.ts index 89fb9a7ed..80fc0001b 100644 --- a/packages/app/src/usage/format.test.ts +++ b/packages/app/src/usage/format.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { i18n } from "@/i18n/i18next"; import { formatDisplayPct, @@ -38,11 +38,9 @@ describe("formatAmount", () => { expect(formatPct(7, "en")).toBe("7%"); expect(formatResetLabel(twoHoursFromNow, false, NOW)).toBe("resets in 2h"); - expect(formatRunsOutLabel(twoHoursFromNow, NOW)).toBe("runs out in 2h"); await i18n.changeLanguage("ja"); expect(formatResetLabel(twoHoursFromNow, false, NOW)).toBe("2時間後にリセット"); - expect(formatRunsOutLabel(twoHoursFromNow, NOW)).toBe("2時間後に上限に到達"); expect(formatAgo(threeDaysAgo, NOW)).toBe("3日前"); }); @@ -57,18 +55,15 @@ describe("formatAmount", () => { const daysAgo = new Date(NOW - days * 24 * 60 * 60 * 1000).toISOString(); expect(formatResetLabel(daysFromNow, false, NOW)).toBe("se réinitialise dans 1\u202f234 j"); - expect(formatRunsOutLabel(daysFromNow, NOW)).toBe("s’épuise dans 1\u202f234 j"); expect(formatAgo(daysAgo, NOW)).toBe("il y a 1\u202f234 j"); }); it("selects Arabic plural forms for relative durations", async () => { await i18n.changeLanguage("ar"); const twoHoursFromNow = new Date(NOW + 2 * 60 * 60 * 1000).toISOString(); - const threeHoursFromNow = new Date(NOW + 3 * 60 * 60 * 1000).toISOString(); const twoDaysAgo = new Date(NOW - 2 * 24 * 60 * 60 * 1000).toISOString(); expect(formatResetLabel(twoHoursFromNow, false, NOW)).toBe("تتم إعادة التعيين خلال ساعتين"); - expect(formatRunsOutLabel(threeHoursFromNow, NOW)).toBe("ينفد خلال 3 ساعات"); expect(formatAgo(twoDaysAgo, NOW)).toBe("قبل يومين"); }); @@ -111,20 +106,21 @@ describe("reset countdown", () => { }); it("says two units, dropping a unit that is zero", () => { - expect(countdown(DAY + 30 * MINUTE)).toBe("resets in 1d"); expect(countdown(4 * HOUR + 59 * MINUTE)).toBe("resets in 4h 59m"); expect(countdown(HOUR)).toBe("resets in 1h"); expect(countdown(37 * MINUTE)).toBe("resets in 37m"); expect(countdown(59 * 1000)).toBe("resets in 0m"); }); - it("joins the at-risk countdown the same way", () => { - const iso = new Date(NOW + 3 * HOUR + 5 * MINUTE).toISOString(); - expect(formatRunsOutLabel(iso, NOW)).toBe("runs out in 3h 5m"); + it("shows a single day as 24 hours in the reset countdown", () => { + expect(countdown(DAY)).toBe("resets in 24h"); + expect(countdown(DAY + 30 * MINUTE)).toBe("resets in 24h"); + expect(countdown(DAY + HOUR)).toBe("resets in 1d 1h"); + expect(countdown(2 * DAY)).toBe("resets in 2d"); }); }); -describe("exact reset time", () => { +describe("exact quota times", () => { // Local-time dates, so the thresholds hold in any timezone the tests run in. const now = new Date(2026, 9, 29, 12, 0).getTime(); const at = (...args: [number, number, number, number, number]) => @@ -134,18 +130,51 @@ describe("exact reset time", () => { await i18n.changeLanguage("en"); }); - it("shows only the time within 24 hours", () => { + it("shows only the time for the same local day", () => { expect(at(2026, 9, 29, 15, 0)).toMatch(/^(3:00 PM|15:00)$/); - expect(at(2026, 9, 30, 11, 59)).toMatch(/^(11:59 AM|11:59)$/); }); - it("adds the weekday within 7 days", () => { - expect(at(2026, 9, 30, 12, 0)).toMatch(/^Fri (12:00 PM|12:00)$/); - expect(at(2026, 10, 5, 11, 59)).toMatch(/^Thu (11:59 AM|11:59)$/); + it("shows the weekday for tomorrow even when it is less than 24 hours away", () => { + expect(at(2026, 9, 30, 11, 59)).toMatch(/^Fri (11:59 AM|11:59)$/); + expect(at(2026, 10, 4, 15, 0)).toMatch(/^Wed (3:00 PM|15:00)$/); }); - it("adds the date after 7 days", () => { - expect(at(2026, 10, 5, 12, 0)).toMatch(/^Nov 5, (12:00 PM|12:00)$/); + it("includes the date on the same weekday next week even when fewer than 7 days elapse", () => { + expect(at(2026, 10, 5, 10, 0)).toMatch(/^Thu, Nov 5, (10:00 AM|10:00)$/); + }); + + it("includes the weekday and date seven or more calendar days out", () => { + expect(at(2026, 10, 5, 12, 0)).toMatch(/^Thu, Nov 5, (12:00 PM|12:00)$/); + expect(at(2026, 10, 6, 15, 0)).toMatch(/^Fri, Nov 6, (3:00 PM|15:00)$/); + }); + + it("counts calendar days across the spring daylight-saving transition", () => { + vi.stubEnv("TZ", "America/New_York"); + try { + const before = new Date(2026, 2, 7, 12); + const after = new Date(2026, 2, 14, 12); + expect(after.getTime() - before.getTime()).toBe(167 * 3_600_000); + expect(formatResetTime(after.toISOString(), before.getTime())).toMatch(/^Sat, Mar 14, /); + } finally { + vi.unstubAllEnvs(); + } + }); + + it("shows the exhaustion clock time with the same weekday and date rules as reset time", () => { + const runsOut = (...args: [number, number, number, number, number]) => + formatRunsOutLabel(new Date(...args).toISOString(), now)?.replace(/\s/g, " "); + + expect(runsOut(2026, 9, 29, 15, 0)).toMatch(/^runs out (3:00 PM|15:00)$/); + expect(runsOut(2026, 9, 30, 9, 32)).toMatch(/^runs out Fri (9:32 AM|09:32|9:32)$/); + expect(runsOut(2026, 10, 5, 15, 30)).toMatch(/^runs out Thu, Nov 5, (3:30 PM|15:30)$/); + }); + + it("uses the app language for the exhaustion label and weekday", async () => { + await i18n.changeLanguage("ja"); + const time = new Date(2026, 9, 30, 15, 30).toISOString(); + expect(formatRunsOutLabel(time, now)?.replace(/\s/g, " ")).toMatch( + /^金 (?:3:30 PM|15:30)に上限に到達$/, + ); }); it("names the weekday in the app language", async () => { diff --git a/packages/app/src/usage/format.ts b/packages/app/src/usage/format.ts index 16386810f..8bc6720fd 100644 --- a/packages/app/src/usage/format.ts +++ b/packages/app/src/usage/format.ts @@ -1,6 +1,6 @@ import type { TFunction } from "i18next"; import { i18n } from "@/i18n/i18next"; -import { formatTimeOfDay } from "@/utils/time"; +import { formatTimeOfDay, localCalendarDaysBetween } from "@/utils/time"; import type { UsageDisplayAs } from "./preferences"; import type { UsageBalanceUnit, UsageReportEntry } from "./types"; @@ -79,6 +79,7 @@ function relativeDuration(iso: string, now: number): RelativeDuration | null { const days = Math.floor(diffMs / DAY_MS); const hours = Math.floor((diffMs % DAY_MS) / HOUR_MS); const minutes = Math.floor((diffMs % HOUR_MS) / MINUTE_MS); + if (days === 1 && hours === 0) return remaining({ unit: "hours", count: 24 }); if (days > 0) return remaining({ unit: "days", count: days }, { unit: "hours", count: hours }); if (hours > 0) return remaining({ unit: "hours", count: hours }, { unit: "minutes", count: minutes }); @@ -120,8 +121,8 @@ export function formatResetLabel( } /** - * When a window resets on the clock: "3:00 PM" within a day, "Fri 3:00 PM" within a week, - * "Oct 31, 3:00 PM" after that. Names follow the app language; 12/24h follows the device. + * A clock time today, a weekday for the next six calendar days, and a weekday plus date after that. + * Names follow the app language. The clock uses the device's 12/24h preference. * Nothing for a time that has passed, where the countdown already says so. */ export function formatResetTime( @@ -135,12 +136,13 @@ export function formatResetTime( if (!Number.isFinite(diffMs) || diffMs <= 0) return null; const time = formatTimeOfDay(at); const locale = i18n.resolvedLanguage; - if (diffMs < DAY_MS) return time; - if (diffMs < 7 * DAY_MS) { + const dayDiff = localCalendarDaysBetween(new Date(now), at); + if (dayDiff === 0) return time; + if (dayDiff <= 6) { const weekday = at.toLocaleDateString(locale, { weekday: "short" }); return t("providerUsage.timing.resetsAtWeekday", { weekday, time }); } - const date = at.toLocaleDateString(locale, { month: "short", day: "numeric" }); + const date = at.toLocaleDateString(locale, { weekday: "short", month: "short", day: "numeric" }); return t("providerUsage.timing.resetsAtDate", { date, time }); } @@ -149,11 +151,8 @@ export function formatRunsOutLabel( now = Date.now(), t: TFunction = i18n.t, ): string | null { - if (!iso) return null; - const rel = relativeDuration(iso, now); - if (!rel) return null; - if (rel.kind === "now") return t("providerUsage.timing.runsOutNow"); - return t("providerUsage.timing.runsOutIn", { duration: formatRelativeDuration(rel, t) }); + const time = formatResetTime(iso, now, t); + return time ? t("providerUsage.timing.runsOutAt", { time }) : null; } export function formatAgo( diff --git a/packages/app/src/usage/meter.tsx b/packages/app/src/usage/meter.tsx index 415047780..1a398f6c6 100644 --- a/packages/app/src/usage/meter.tsx +++ b/packages/app/src/usage/meter.tsx @@ -6,14 +6,12 @@ import type { UsageTone } from "./types"; function fillToneStyle(tone: UsageTone) { switch (tone) { - case "ok": - return styles.fillOk; case "warning": return styles.fillWarning; case "danger": return styles.fillDanger; default: - return styles.fillDefault; + return styles.fillOk; } } @@ -59,9 +57,6 @@ const styles = StyleSheet.create((theme) => ({ fillQuiet: { backgroundColor: theme.colors.surface4, }, - fillDefault: { - backgroundColor: theme.colors.foregroundMuted, - }, fillOk: { backgroundColor: theme.colors.statusSuccess, }, diff --git a/packages/app/src/usage/pace.test.ts b/packages/app/src/usage/pace.test.ts index dd9fb46d3..37dbbc90b 100644 --- a/packages/app/src/usage/pace.test.ts +++ b/packages/app/src/usage/pace.test.ts @@ -23,12 +23,25 @@ describe("usage pace", () => { 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, close, Date.parse(close))).toEqual({ kind: "tight" }); expect( usagePace({ ...window, usedPct: undefined, remainingPct: 35 }, safe, Date.parse(safe)), - ).toEqual({ kind: "remaining", remainingAtResetPct: 18.75 }); + ).toEqual({ kind: "onTrack" }); + }); + + it("projects a weekly window after 100 minutes when 6% is already used", () => { + const sampledAt = "2026-11-21T10:28:17.000Z"; + const weekly: UsageWindow = { + id: "gemini-weekly", + label: "Gemini · Weekly", + durationSeconds: 604_800, + usedPct: 6, + resetsAt: "2026-11-28T08:48:17.000Z", + }; + expect(usagePace(weekly, sampledAt, Date.parse("2026-11-21T10:33:03Z"))).toEqual({ + kind: "runsOut", + at: "2026-11-22T12:34:57.000Z", + }); }); it("only forecasts with timing and an active, usable reading", () => { diff --git a/packages/app/src/usage/pace.ts b/packages/app/src/usage/pace.ts index ad2701d7f..0908a3d0b 100644 --- a/packages/app/src/usage/pace.ts +++ b/packages/app/src/usage/pace.ts @@ -5,7 +5,7 @@ type UsagePace = | { kind: "unknown" } | { kind: "reached" } | { kind: "runsOut"; at: string } - | { kind: "remaining"; remainingAtResetPct: number }; + | { kind: "onTrack" | "tight" }; /** 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 { @@ -25,13 +25,15 @@ export function usagePace(window: UsageWindow, observedAt: string | null, now: n const duration = (window.durationSeconds ?? 0) * 1_000; const sampled = Date.parse(observedAt); const elapsed = sampled - (reset - duration); + // Wait for an initial sample without holding back multi-day forecasts for several hours. + const minimumElapsed = Math.max(60_000, Math.min(duration * 0.01, 3_600_000)); if ( used == null || !Number.isFinite(used) || used < 0 || !Number.isFinite(elapsed) || sampled >= reset || - elapsed < Math.max(60_000, duration * 0.01) + elapsed < minimumElapsed ) { return { kind: "unknown" }; } @@ -41,5 +43,5 @@ export function usagePace(window: UsageWindow, observedAt: string | null, now: n const runsOut = sampled + ((100 - used) / used) * elapsed; return { kind: "runsOut", at: new Date(runsOut).toISOString() }; } - return { kind: "remaining", remainingAtResetPct: 100 - projectedAtReset }; + return { kind: projectedAtReset >= 90 ? "tight" : "onTrack" }; } diff --git a/packages/app/src/usage/window-bar.tsx b/packages/app/src/usage/window-bar.tsx index 6d211e7f0..537610617 100644 --- a/packages/app/src/usage/window-bar.tsx +++ b/packages/app/src/usage/window-bar.tsx @@ -7,7 +7,6 @@ import { StyleSheet, withUnistyles } from "react-native-unistyles"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; import { formatDisplayPct, - formatPct, formatProviderUsageLabel, formatResetLabel, formatResetTime, @@ -18,6 +17,7 @@ import { displayPercent, usageWindowRowLabel } from "./model"; import { usagePace } from "./pace"; import { UsageDatapointLine } from "./datapoint-line"; import type { UsageDisplayAs } from "./preferences"; +import { windowTone } from "./tone"; import type { UsageTone, UsageWindow } from "./types"; import { useRelativeTimeTick } from "./use-relative-time-tick"; @@ -55,13 +55,13 @@ export function UsageWindowBar({ const value = shownPct != null ? formatDisplayPct(shownPct, displayAs, i18n.resolvedLanguage, t) : "—"; const accessibilityState = useMemo(() => ({ checked: pinned }), [pinned]); + const datapoints = [countdown, exactTime, forecast?.label ?? null]; const content = { label: formatProviderUsageLabel(window.id, window.label, t), value, - countdown, - exactTime, - forecast, + datapoints, percent: shownPct ?? 0, + tone: forecast?.tone ?? windowTone(window), pinned, }; @@ -81,7 +81,7 @@ export function UsageWindowBar({ accessibilityLabel={usageWindowRowLabel({ pinLabel, value, - trailing: [countdown, exactTime, forecast?.label].filter(Boolean).join(" · "), + trailing: datapoints.filter(Boolean).join(" · "), })} accessibilityState={accessibilityState} aria-checked={pinned} @@ -96,19 +96,17 @@ export function UsageWindowBar({ function WindowRowContent({ label, value, - countdown, - exactTime, - forecast, + datapoints, percent, + tone, pinnable, pinned, }: { label: string; value: string; - countdown: string | null; - exactTime: string | null; - forecast: PaceLabel | null; + datapoints: readonly (string | null)[]; percent: number; + tone: UsageTone; pinnable: boolean; pinned: boolean; }) { @@ -123,14 +121,14 @@ function WindowRowContent({ {pinnable ? : null} - - + + ); } -interface PaceLabel { - label: string; +interface PaceDisplay { + label: string | null; tone: UsageTone; } @@ -138,7 +136,7 @@ function formatPace( pace: ReturnType, now: number, t: TFunction, -): PaceLabel | null { +): PaceDisplay | null { switch (pace.kind) { case "reached": return { label: t("providerUsage.timing.limitReached"), tone: "danger" }; @@ -149,13 +147,10 @@ function formatPace( : 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 "tight": + return { label: null, tone: "warning" }; + case "onTrack": + return { label: null, tone: "default" }; case "unknown": return null; } diff --git a/packages/app/src/utils/time.ts b/packages/app/src/utils/time.ts index 1c063d1a2..61ce230df 100644 --- a/packages/app/src/utils/time.ts +++ b/packages/app/src/utils/time.ts @@ -97,14 +97,10 @@ export function formatCompactTimeAgoAsProse(label: string): string { return label; } -/** - * How many local midnights lie between two instants: 0 for the same day, 1 for yesterday. - * Counted on the calendar rather than in elapsed time, so six days and 23 hours ago on - * today's weekday is 7, and rounded so a DST day of 23 or 25 hours still counts as one. - */ -function localCalendarDaysBetween(earlier: Date, later: Date): number { - const startOfDay = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate()); - return Math.round((startOfDay(later).getTime() - startOfDay(earlier).getTime()) / DAY_MS); +/** Count local calendar dates using equally spaced UTC values for their year, month and day. */ +export function localCalendarDaysBetween(earlier: Date, later: Date): number { + const calendarDay = (date: Date) => Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()); + return (calendarDay(later) - calendarDay(earlier)) / DAY_MS; } // Cached Intl formatter. Explicitly carrying `hourCycle` from the resolved diff --git a/plugins/antigravity-provider/server/usage.test.ts b/plugins/antigravity-provider/server/usage.test.ts index 3b30c5daa..69f0c7a02 100644 --- a/plugins/antigravity-provider/server/usage.test.ts +++ b/plugins/antigravity-provider/server/usage.test.ts @@ -67,13 +67,21 @@ it("discovers the resolved account and maps the CLI's quota buckets", async () = windows: [ { id: "gemini-5h", + label: "Gemini · 5h", shortLabel: "5h", + durationSeconds: 18_000, usedPct: 75, remainingPct: 25, resetsAt: "2026-11-19T14:25:08Z", }, { id: "gemini-weekly", shortLabel: "wk", usedPct: expect.closeTo(30), summary: true }, - { id: "disabled", shortLabel: "wk", usedPct: null, remainingPct: null }, + { + id: "disabled", + label: "Gemini · Weekly · Disabled", + shortLabel: "wk", + usedPct: null, + remainingPct: null, + }, ], }); }); @@ -102,9 +110,14 @@ it("uses compact group and period shorthands when multiple groups are reported", expect(await source.fetch(account!.input)).toMatchObject({ status: "available", windows: [ - { id: "gemini-weekly", shortLabel: "Gemini wk" }, - { id: "gemini-5h", shortLabel: "Gemini 5h" }, - { id: "3p-weekly", shortLabel: "Claude and GPT wk" }, + { + id: "gemini-weekly", + label: "Gemini · Weekly", + shortLabel: "Gemini wk", + durationSeconds: 604_800, + }, + { id: "gemini-5h", label: "Gemini · 5h", shortLabel: "Gemini 5h" }, + { id: "3p-weekly", label: "Claude and GPT · Weekly", shortLabel: "Claude and GPT wk" }, ], }); }); diff --git a/plugins/antigravity-provider/server/usage.ts b/plugins/antigravity-provider/server/usage.ts index d1960e252..0c15399ca 100644 --- a/plugins/antigravity-provider/server/usage.ts +++ b/plugins/antigravity-provider/server/usage.ts @@ -48,6 +48,11 @@ function accountKey(env: ProviderLaunch["env"]): string { ); } +function formatWindowLabel(name: string, window: string): string { + if (window.trim().toLowerCase() === "5h") return "5h"; + return name.trim().replace(/(?:\s+Limit)?\s+Remaining$/i, ""); +} + function shortWindow(window: string): string { const trimmed = window.trim(); const normalized = trimmed.toLowerCase(); @@ -67,18 +72,16 @@ function windowDurationSeconds(window: string): number | undefined { } } -function shortGroupName(name: string): string { +function formatGroupLabel(name: string): string { return name .trim() - .replace(/\s+models$/i, "") + .replace(/(?:^|\s+)models$/i, "") .trim(); } -function formatShortLabel(groupName: string, window: string, includeGroup: boolean): string { +function formatShortLabel(groupLabel: string, window: string): string { const period = shortWindow(window); - if (!includeGroup) return period; - const scope = shortGroupName(groupName); - return scope ? `${scope} ${period}` : period; + return groupLabel ? `${groupLabel} ${period}` : period; } export class Usage { @@ -129,15 +132,22 @@ export class Usage { if (!data.command) throw new Error("agy did not return usage data"); const groups = data.command.data.groups; const includeGroup = groups.length > 1; - const windows = groups.flatMap((group) => - group.buckets.flatMap((bucket) => { + const windows = groups.flatMap((group) => { + const groupLabel = formatGroupLabel(group.name); + return group.buckets.flatMap((bucket) => { if (!bucket.disabled && bucket.remaining_fraction == null) return []; const used = bucket.disabled ? null : (1 - bucket.remaining_fraction!) * 100; return [ windowFromUsedPct({ id: bucket.id, - label: `${group.name} · ${bucket.name}${bucket.disabled ? " · Disabled" : ""}`, - shortLabel: formatShortLabel(group.name, bucket.window, includeGroup), + label: [ + groupLabel, + formatWindowLabel(bucket.name, bucket.window), + bucket.disabled ? "Disabled" : null, + ] + .filter(Boolean) + .join(" · "), + shortLabel: formatShortLabel(includeGroup ? groupLabel : "", bucket.window), summary: !bucket.disabled && bucket.window === "weekly", utilizationPct: used, durationSeconds: windowDurationSeconds(bucket.window), @@ -145,8 +155,8 @@ export class Usage { tone: used === null ? "default" : toneFromUsedPct(used), }), ]; - }), - ); + }); + }); if (windows.length === 0) return unavailable({ kind: "no_quota", detail: "No usage quota reported by agy" }); return { status: "available", windows };