diff --git a/apps/web/src/components/usage/UsageLimits.tsx b/apps/web/src/components/usage/UsageLimits.tsx index a36b220ee3ef..63134602e230 100644 --- a/apps/web/src/components/usage/UsageLimits.tsx +++ b/apps/web/src/components/usage/UsageLimits.tsx @@ -8,10 +8,10 @@ import { ServerProviderUsageWindow, UsageProviderKind, } from "@t3tools/contracts"; -import { useAtomValue } from "@effect/atom-react"; import { normalizeProviderAccentColor } from "@t3tools/client-runtime/state/provider-instance-display"; import { type LimitPace, + type LimitPresentations, paceOf, paceRemainingPercent, remainingPercent, @@ -23,7 +23,6 @@ import { Fragment, useLayoutEffect, useState } from "react"; import { usePrimarySettings } from "../../hooks/useSettings"; import { observeResize } from "../../lib/observeResize"; -import { environmentPresentations } from "../../state/presentation"; import { useEnvironmentScope, readEnvironmentScope } from "../../state/session"; import { serverEnvironment } from "../../state/server"; import { useAtomCommand } from "../../state/use-atom-command"; @@ -39,7 +38,6 @@ import { } from "../ui/alert-dialog"; import { Button } from "../ui/button"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; -import { UsageLimitsPooled } from "./UsageLimitsPooled"; import { formatResetsIn, resetCreditChoices } from "@t3tools/shared/usageLimitsCopy"; import { PROVIDER_PRESENTATION } from "./usageProviders"; @@ -388,22 +386,17 @@ export function ResetCredits({ ); } -/** Advance now only on explicit refresh to avoid page repaints from ticking. */ -export function UsageLimitsSection({ - selectedEnvironmentIds, - hiddenProviders, - now, -}: { - readonly selectedEnvironmentIds: ReadonlySet | null; - readonly hiddenProviders: ReadonlySet; - readonly now: number; -}) { - const presentations = useAtomValue(environmentPresentations.presentationsWithProvidersAtom); +export function selectLimitPresentations( + presentations: LimitPresentations, + selectedEnvironmentIds: ReadonlySet | null, + hiddenProviders: ReadonlySet, +): LimitPresentations { + if (selectedEnvironmentIds === null && hiddenProviders.size === 0) return presentations; const hiddenDrivers = new Set( [...hiddenProviders].map((provider) => PROVIDER_PRESENTATION[provider].driverKind), ); const isVisible = (driver: ServerProvider["driver"]) => !hiddenDrivers.has(driver); - const selected = new Map( + return new Map( [...presentations].flatMap(([id, presentation]) => { if (selectedEnvironmentIds !== null && !selectedEnvironmentIds.has(id)) return []; const config = presentation.serverConfig; @@ -428,5 +421,4 @@ export function UsageLimitsSection({ ]; }), ); - return ; } diff --git a/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx b/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx index ab114fbbd6f2..6ff0bb5f181e 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx @@ -1,14 +1,29 @@ +import "~/index.css"; import { EnvironmentId, ProviderDriverKind, ProviderInstanceId, type ServerProvider, } from "@t3tools/contracts"; -import { CHATGPT_USAGE_URL } from "@t3tools/shared/usageLimits"; -import { describe, expect, it } from "vite-plus/test"; +import { + CHATGPT_USAGE_URL, + collectLimitAccounts, + collectLimitPools, +} from "@t3tools/shared/usageLimits"; +import { useRef, useState } from "react"; +import { describe, expect, it, vi } from "vite-plus/test"; +import { cdp, page, userEvent } from "vite-plus/test/browser"; import { render } from "../../../test/render"; -import { UsageLimitsPooled } from "./UsageLimitsPooled"; +import { ToastProvider } from "../ui/toast"; +import { LimitsLayoutMenu, UsageLimitsPooled } from "./UsageLimitsPooled"; +import { + DEFAULT_USAGE_LIMITS_LAYOUT, + hideLimitWindow, + limitWindowKey, + showLimitWindow, + type UsageLimitsLayout, +} from "./usageLimitsLayout"; const checkedAt = "2026-10-25T16:00:00.000Z"; @@ -52,7 +67,7 @@ describe("UsageLimitsPooled ChatGPT usage card", () => { ], ]); await using screen = await render( - , + , ); await expect @@ -63,3 +78,417 @@ describe("UsageLimitsPooled ChatGPT usage card", () => { .toBeVisible(); }); }); + +function quotaProvider( + driver: string, + windows: NonNullable["windows"], + instanceId = driver, +): ServerProvider { + const provider = managedChatGpt(instanceId, driver); + return { + ...provider, + driver: ProviderDriverKind.make(driver), + usageLimits: { checkedAt, windows }, + }; +} + +const presentations = new Map([ + [ + EnvironmentId.make("desk"), + { + entry: { target: { label: "Desk" } }, + serverConfig: { + providers: [ + quotaProvider("codex", [ + { id: "weekly", kind: "weekly", label: "Weekly", usedPercent: 76 }, + ]), + quotaProvider( + "codex", + [{ id: "weekly", kind: "weekly", label: "Weekly", usedPercent: 20 }], + "codex_work", + ), + quotaProvider("cursor", [ + { id: "totalPercentUsed", kind: "monthly", label: "Overall", usedPercent: 25 }, + ]), + quotaProvider("antigravity", [ + { id: "gemini-5h", kind: "session", label: "Gemini 5-hour", usedPercent: 3 }, + { id: "gemini-weekly", kind: "weekly", label: "Gemini Weekly", usedPercent: 50 }, + { + id: "gemini-argon-wtu-weekly", + kind: "weekly", + label: "Gemini 4 Argon Weekly", + usedPercent: 0, + }, + ]), + ], + }, + }, + ], +]); +const pools = collectLimitPools(collectLimitAccounts(presentations), Date.parse(checkedAt)); + +/** + * The page owns the saved layout and the header menu; this stands in for both. Another tab writes + * `storage.layout` directly, which this view sees only on its own next save. + */ +function LayoutExample({ + writable = true, + storage = { layout: DEFAULT_USAGE_LIMITS_LAYOUT }, +}: { + readonly writable?: boolean; + readonly storage?: { layout: UsageLimitsLayout }; +}) { + const [layout, setLayout] = useState(storage.layout); + const layoutMenu = useRef(null); + const change = (update: (current: UsageLimitsLayout) => UsageLimitsLayout) => { + if (!writable) return false; + storage.layout = update(storage.layout); + setLayout(storage.layout); + return true; + }; + return ( + // Toasts stay until closed, so a test sees an Undo retire because of the layout, not a timer. + + setLayout(DEFAULT_USAGE_LIMITS_LAYOUT)} + /> + layoutMenu.current?.focus()} + /> + + ); +} + +const cardOf = (element: Element) => element.closest("[data-limit-card]")!; +const headingRowOf = (name: string) => + page.getByRole("heading", { name, exact: true }).element().parentElement!.parentElement!; + +function geometry(card: Element, heading: Element) { + const [summary, bar] = [...card.children]; + return [card, summary!, bar!, heading].map((element) => element.getBoundingClientRect().toJSON()); +} + +function intersects(a: DOMRect, b: DOMRect) { + return a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom; +} + +/** A control's box, grown to the pseudo-element that enlarges its touch target. */ +function touchTarget(control: HTMLElement) { + const box = control.getBoundingClientRect(); + const after = getComputedStyle(control, "::after"); + if (after.position !== "absolute") return box; + const left = box.left + control.clientLeft + Number.parseFloat(after.left); + const top = box.top + control.clientTop + Number.parseFloat(after.top); + const target = new DOMRect( + left, + top, + Number.parseFloat(after.width), + Number.parseFloat(after.height), + ); + return new DOMRect( + Math.min(box.left, target.left), + Math.min(box.top, target.top), + Math.max(box.right, target.right) - Math.min(box.left, target.left), + Math.max(box.bottom, target.bottom) - Math.min(box.top, target.top), + ); +} + +it("reveals card and provider actions without moving the layout", async () => { + await using screen = await render(); + const hide = screen.getByRole("button", { name: "Hide Antigravity · Gemini Weekly" }); + const card = cardOf(hide.element()); + const cluster = hide.element().parentElement!.parentElement!; + const heading = headingRowOf("Antigravity"); + const providerActions = screen.getByRole("group", { name: "Antigravity", exact: true }); + const rest = geometry(card, heading); + expect(getComputedStyle(cluster).opacity).toBe("0"); + // Invisible actions cannot be clicked or tapped by accident. + expect(getComputedStyle(cluster).pointerEvents).toBe("none"); + + await userEvent.hover(card); + await vi.waitFor(() => expect(getComputedStyle(cluster).opacity).toBe("1")); + expect(geometry(card, heading)).toEqual(rest); + + await userEvent.hover(heading); + const providerCluster = providerActions.element().parentElement!; + await vi.waitFor(() => expect(getComputedStyle(providerCluster).opacity).toBe("1")); + expect(geometry(card, heading)).toEqual(rest); + + // The bar's segment and legend rows come first, then the card's actions. + const barControls = [...card.children[1]!.querySelectorAll("button")]; + barControls.at(-1)!.focus(); + await userEvent.tab(); + await expect + .element(screen.getByRole("button", { name: "Move Antigravity · Gemini Weekly up" })) + .toHaveFocus(); + await vi.waitFor(() => expect(getComputedStyle(cluster).opacity).toBe("1")); + expect(geometry(card, heading)).toEqual(rest); + + // The notch never covers a card's content, in the compact and the wide bar layout. + for (const width of ["360px", "1000px"]) { + screen.container.style.width = width; + for (const each of screen.container.querySelectorAll("[data-limit-card]")) { + const notch = each.lastElementChild!.getBoundingClientRect(); + for (const content of [...each.children].slice(0, -1)) { + expect(intersects(notch, content.getBoundingClientRect())).toBe(false); + } + } + } +}); + +it("reorders providers and limits with the keyboard", async () => { + await using screen = await render(); + const moveProvider = screen.getByRole("button", { name: "Move Antigravity up" }); + moveProvider.element().focus(); + await userEvent.keyboard("{Enter}"); + await expect.element(moveProvider).toHaveFocus(); + await expect + .element(screen.getByRole("status")) + .toHaveTextContent("Antigravity moved to position 2 of 3."); + expect( + [...screen.container.querySelectorAll("h2")].map((heading) => heading.textContent), + ).toEqual(["Codex", "Antigravity", "Cursor"]); + + const moveWindow = screen.getByRole("button", { name: "Move Antigravity · Gemini Weekly up" }); + moveWindow.element().focus(); + await userEvent.keyboard("{Enter}"); + await expect.element(moveWindow).toHaveFocus(); + await expect + .element(screen.getByRole("status")) + .toHaveTextContent("Antigravity · Gemini Weekly moved to position 1 of 3."); + const weekly = screen.getByText("Gemini Weekly", { exact: true }).element(); + const session = screen.getByText("Gemini 5-hour", { exact: true }).element(); + expect(weekly.compareDocumentPosition(session) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + // A provider with one visible limit has nothing to reorder it against. + const cursor = cardOf(screen.getByRole("button", { name: "Hide Cursor · Overall" }).element()); + expect(cursor.querySelector('[aria-label^="Move"]')).toBeNull(); +}); + +it("hides limits, moves focus to a neighbor and restores them", async () => { + await using screen = await render(); + const layoutMenu = page.getByRole("button", { name: /^Limits layout/ }); + + // An open segment popover closes when its card is hidden. + const codexHide = screen.getByRole("button", { name: "Hide Codex · Weekly" }); + const codexCard = cardOf(codexHide.element()); + await userEvent.hover(codexCard.children[1]!.querySelector("button")!); + await vi.waitFor(() => + expect(document.querySelector('[data-slot="popover-popup"]')).not.toBeNull(), + ); + codexHide.element().focus(); + await userEvent.keyboard("{Enter}"); + await vi.waitFor(() => expect(document.querySelector('[data-slot="popover-popup"]')).toBeNull()); + await expect.element(screen.getByRole("button", { name: "Hide Cursor · Overall" })).toHaveFocus(); + await expect.element(page.getByText("Codex · Weekly hidden")).toBeVisible(); + await expect.element(screen.getByRole("status")).toHaveTextContent(""); + await expect.element(layoutMenu).toHaveAccessibleName("Limits layout, 1 hidden"); + + await page.getByRole("button", { name: "Undo" }).click(); + await expect.element(screen.getByRole("button", { name: "Hide Codex · Weekly" })).toHaveFocus(); + await expect.element(layoutMenu).toHaveAccessibleName("Limits layout"); + + // The last card has no next neighbor, so focus moves back; with none left it lands on the menu. + // With the pointer: hovering the card makes its actions clickable. + const argonHide = screen.getByRole("button", { + name: "Hide Antigravity · Gemini 4 Argon Weekly", + }); + await userEvent.hover(cardOf(argonHide.element())); + await argonHide.click(); + const previous = [ + "Hide Antigravity · Gemini Weekly", + "Hide Antigravity · Gemini 5-hour", + "Hide Cursor · Overall", + "Hide Codex · Weekly", + ]; + for (const name of previous) { + await expect.element(screen.getByRole("button", { name })).toHaveFocus(); + await userEvent.keyboard("{Enter}"); + } + await expect.element(layoutMenu).toHaveFocus(); + await expect.element(layoutMenu).toHaveAccessibleName("Limits layout, 5 hidden"); + await expect.element(screen.getByText("All limits in this view are hidden.")).toBeVisible(); + + await layoutMenu.click(); + await page.getByRole("menuitem", { name: "Show Antigravity · Gemini 5-hour" }).click(); + await expect.element(screen.getByText("Gemini 5-hour", { exact: true })).toBeVisible(); + await expect.element(layoutMenu).toHaveFocus(); + + await layoutMenu.click(); + await page.getByRole("menuitem", { name: "Reset layout" }).click(); + await expect.element(layoutMenu).toHaveAccessibleName("Limits layout"); + expect(screen.container.querySelectorAll("[data-limit-card]")).toHaveLength(5); + await layoutMenu.click(); + await expect + .element(page.getByRole("menuitem", { name: "Reset layout" })) + .toHaveAttribute("aria-disabled", "true"); +}); + +it("ties each Undo to the hide it reports", async () => { + await using screen = await render(); + const layoutMenu = page.getByRole("button", { name: /^Limits layout/ }); + const undo = page.getByRole("button", { name: "Undo" }); + const hideCodex = () => { + screen.getByRole("button", { name: "Hide Codex · Weekly" }).element().focus(); + return userEvent.keyboard("{Enter}"); + }; + await hideCodex(); + await expect.element(undo).toBeVisible(); + + // Restoring it from the header retires that toast, so it cannot undo a later hide. + await layoutMenu.click(); + await page.getByRole("menuitem", { name: "Show Codex · Weekly" }).click(); + await expect.element(undo).not.toBeInTheDocument(); + await hideCodex(); + await vi.waitFor(() => expect(undo.elements()).toHaveLength(1)); + await undo.click(); + await expect.element(screen.getByRole("button", { name: "Hide Codex · Weekly" })).toHaveFocus(); + await expect.element(layoutMenu).toHaveAccessibleName("Limits layout"); +}); + +it("leaves another tab's hides to that tab's Undo", async () => { + const storage = { layout: DEFAULT_USAGE_LIMITS_LAYOUT }; + await using screen = await render(); + const undo = page.getByRole("button", { name: "Undo" }); + const key = (driver: string, kind: "weekly" | "monthly", id: string) => + limitWindowKey(ProviderDriverKind.make(driver), { kind, id }); + const argon = key("antigravity", "weekly", "gemini-argon-wtu-weekly"); + const cursor = key("cursor", "monthly", "totalPercentUsed"); + const codex = key("codex", "weekly", "weekly"); + const hide = async (name: string) => { + screen + .getByRole("button", { name: `Hide ${name}` }) + .element() + .focus(); + await userEvent.keyboard("{Enter}"); + }; + const otherTabRehides = (window: string) => { + storage.layout = hideLimitWindow(showLimitWindow(storage.layout, window), window, "other-tab"); + }; + + // Before this view hears of it, another tab shows Argon and hides it again. + await hide("Antigravity · Gemini 4 Argon Weekly"); + otherTabRehides(argon); + await undo.click(); + await expect.element(undo).not.toBeInTheDocument(); + expect(storage.layout.hiddenWindowIds?.[argon]).toBe("other-tab"); + + // Once this view saves and sees the other tab's hide, it retires its own Undo. + await hide("Cursor · Overall"); + await expect.element(undo).toBeVisible(); + otherTabRehides(cursor); + screen.getByRole("button", { name: "Move Antigravity up" }).element().focus(); + await userEvent.keyboard("{Enter}"); + await expect.element(undo).not.toBeInTheDocument(); + + // A hide that arrives after the other tab's own offers no Undo here. + storage.layout = hideLimitWindow(storage.layout, codex, "other-tab"); + await hide("Codex · Weekly"); + await expect.element(screen.getByText("Gemini Weekly", { exact: true })).toBeVisible(); + expect(screen.container.querySelectorAll("[data-limit-card]")).toHaveLength(2); + await expect.element(page.getByText("Codex · Weekly hidden")).not.toBeInTheDocument(); + expect(storage.layout.hiddenWindowIds?.[codex]).toBe("other-tab"); +}); + +it("hides one limit per double-click while the next card slides under the pointer", async () => { + await using screen = await render(); + const hide = screen.getByRole("button", { name: "Hide Antigravity · Gemini 5-hour" }); + await userEvent.hover(cardOf(hide.element())); + await userEvent.dblClick(hide); + await expect.element(page.getByText("Antigravity · Gemini 5-hour hidden")).toBeVisible(); + await expect + .element(screen.getByRole("button", { name: "Hide Antigravity · Gemini Weekly" })) + .toHaveFocus(); + expect(screen.container.querySelectorAll("[data-limit-card]")).toHaveLength(4); + + // Separate activations still act each time. + await userEvent.keyboard("{Enter}"); + await expect + .element(screen.getByRole("button", { name: "Hide Antigravity · Gemini 4 Argon Weekly" })) + .toHaveFocus(); + expect(screen.container.querySelectorAll("[data-limit-card]")).toHaveLength(3); +}); + +it("keeps focus and stays quiet when the layout cannot be saved", async () => { + await using screen = await render(); + const hide = screen.getByRole("button", { name: "Hide Codex · Weekly" }); + hide.element().focus(); + await userEvent.keyboard("{Enter}"); + await expect.element(hide).toHaveFocus(); + await expect.element(screen.getByRole("status")).toHaveTextContent(""); + await expect.element(page.getByRole("button", { name: "Undo" })).not.toBeInTheDocument(); +}); + +function expectCardTouchTarget(card: Element, previous: Element | undefined) { + card.scrollIntoView({ block: "center" }); + const trigger = card.querySelector('[data-limit-action="more"]')!; + const target = touchTarget(trigger); + expect(target.width).toBeGreaterThanOrEqual(44); + expect(target.height).toBeGreaterThanOrEqual(44); + for (const x of [target.left + 1, target.left + target.width / 2, target.right - 1]) { + for (const y of [target.top + 1, target.top + target.height / 2, target.bottom - 1]) { + expect(document.elementFromPoint(x, y)?.closest("button")).toBe(trigger); + } + } + if (previous && previous.parentElement === card.parentElement) { + expect(target.top).toBeGreaterThanOrEqual(previous.getBoundingClientRect().bottom); + } + for (const control of card.children[1]!.querySelectorAll("button")) { + if (control.getClientRects().length === 0) continue; + expect(intersects(target, touchTarget(control))).toBe(false); + } +} + +it("offers the same actions from a menu on touch", async () => { + const session = cdp(); + await session.send("Emulation.setTouchEmulationEnabled", { enabled: true, maxTouchPoints: 5 }); + await using _touch = { + async [Symbol.asyncDispose]() { + await session.send("Emulation.setTouchEmulationEnabled", { enabled: false }); + }, + }; + expect(matchMedia("(pointer: coarse)").matches).toBe(true); + const viewport = { width: innerWidth, height: innerHeight }; + await page.viewport(900, 800); + await using _viewport = { + [Symbol.asyncDispose]: () => page.viewport(viewport.width, viewport.height), + }; + await using screen = await render(); + await expect + .element(screen.getByRole("button", { name: "Hide Antigravity · Gemini Weekly" })) + .not.toBeInTheDocument(); + const more = screen.getByRole("button", { name: "More actions for Antigravity · Gemini Weekly" }); + await expect.element(more).toBeVisible(); + // Every point of each card's 44px target reaches its menu, and the target stays clear of the + // previous card (and its legend rows) and of the card's own bar and legend, compact and wide. + for (const width of [360, 900]) { + await page.viewport(width, 800); + const cards = [...screen.container.querySelectorAll("[data-limit-card]")]; + for (const [index, card] of cards.entries()) { + expectCardTouchTarget(card, cards[index - 1]); + } + } + await page.viewport(900, 800); + + await more.click(); + await page.getByRole("menuitem", { name: "Move up" }).click(); + await expect.element(more).toHaveFocus(); + const weekly = screen.getByText("Gemini Weekly", { exact: true }).element(); + const session5h = screen.getByText("Gemini 5-hour", { exact: true }).element(); + expect(weekly.compareDocumentPosition(session5h) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + + await more.click(); + await page.getByRole("menuitem", { name: "Hide" }).click(); + await expect + .element(screen.getByRole("button", { name: "More actions for Antigravity · Gemini 5-hour" })) + .toHaveFocus(); + await expect.element(page.getByText("Antigravity · Gemini Weekly hidden")).toBeVisible(); +}); diff --git a/apps/web/src/components/usage/UsageLimitsPooled.tsx b/apps/web/src/components/usage/UsageLimitsPooled.tsx index c3932252691e..393b8743a42e 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.tsx @@ -7,6 +7,7 @@ import { type LimitPool, type LimitPoolMember, type LimitPoolWindow, + type LimitPresentations, paceRemainingPercent, remainingPercent, type ResetCreditChoice, @@ -14,21 +15,35 @@ import { import { T, useGT, useMessages } from "gt-react"; import type { Popover as PopoverPrimitive } from "@base-ui/react/popover"; import { normalizeProviderAccentColor } from "@t3tools/client-runtime/state/provider-instance-display"; -import { AlertTriangleIcon, ExternalLinkIcon, TicketIcon } from "lucide-react"; +import { + AlertTriangleIcon, + ArrowDownIcon, + ArrowUpIcon, + EllipsisIcon, + ExternalLinkIcon, + EyeIcon, + EyeOffIcon, + LayoutListIcon, + RotateCcwIcon, + TicketIcon, +} from "lucide-react"; import { createContext, - Fragment, + type MouseEvent, type ReactNode, + type Ref, type RefObject, use, + useEffect, useLayoutEffect, useRef, useState, } from "react"; +import { flushSync } from "react-dom"; import { ensureLocalApi } from "../../localApi"; import { usePrimarySettings } from "../../hooks/useSettings"; -import { cn } from "../../lib/utils"; +import { cn, randomUUID } from "../../lib/utils"; import { formatUpcomingTimestamp } from "../../timestampFormat"; import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon"; import { providerClients } from "../settings/providerDriverMeta"; @@ -36,7 +51,17 @@ import { RedactedSensitiveText } from "../settings/RedactedSensitiveText"; import { Button } from "../ui/button"; import { OpenAI } from "../Icons"; import { Alert, AlertTitle } from "../ui/alert"; +import { + Menu, + MenuGroup, + MenuGroupLabel, + MenuItem, + MenuPopup, + MenuSeparator, + MenuTrigger, +} from "../ui/menu"; import { Popover, PopoverCreateHandle, PopoverPopup, PopoverTrigger } from "../ui/popover"; +import { toastManager } from "../ui/toast"; import { PaceIcon, ResetCreditDialog, barColor, usePaceMark, useResetCredit } from "./UsageLimits"; import { collectExternalUsageLinks, @@ -45,6 +70,17 @@ import { formatResetsIn, resetCreditChoices, } from "@t3tools/shared/usageLimitsCopy"; +import { + DEFAULT_USAGE_LIMITS_LAYOUT, + hideLimitWindow, + limitWindowKey, + moveLimitItem, + orderLimitItems, + showLimitWindow, + type LimitMoveDirection, + type UsageLimitsLayout, + type UsageLimitsLayoutUpdate, +} from "./usageLimitsLayout"; function accountInitials(email: string): string { const [local = "", domain = ""] = email.split("@"); @@ -251,24 +287,22 @@ function ActiveSegmentPopover({ handle, actions, payload, - pools, + windows, now, }: { readonly handle: ReturnType>; readonly actions: RefObject; readonly payload: SegmentPayload; - readonly pools: readonly LimitPool[]; + readonly windows: readonly LimitPoolWindow[]; readonly now: number; }) { - const available = pools.some((pool) => - displayLimitWindows(pool).some((window) => - window.members.some( - (member) => - member.account.key === payload.account.key && - member.window.id === payload.window.id && - member.window.kind === payload.window.kind && - Boolean(member.account.redeem) === Boolean(payload.redeem), - ), + const available = windows.some((window) => + window.members.some( + (member) => + member.account.key === payload.account.key && + member.window.id === payload.window.id && + member.window.kind === payload.window.kind && + Boolean(member.account.redeem) === Boolean(payload.redeem), ), ); // The trigger is gone, so the popup has nothing to anchor to: an exit transition would @@ -597,16 +631,23 @@ function PoolWindowCard({ now, label, description, + limitKey, + actions, }: { readonly pool: LimitPoolWindow; readonly color: string; readonly now: number; readonly label?: string | null | undefined; readonly description?: string | undefined; + readonly limitKey: string; + readonly actions?: ReactNode; }) { const nextRefill = pool.resets.find((reset) => reset.restoresPercent > 0); return ( -
+
{label !== null ? ( {label ?? pool.label} @@ -632,38 +673,248 @@ function PoolWindowCard({ {description ? (

{description}

) : null} + {actions} +
+ ); +} + +type MoveLimit = (direction: LimitMoveDirection, control: HTMLElement, label: string) => void; + +// Touch has no hover to reveal the buttons, so it gets one menu instead. Only one of the +// two is displayed, which keeps the other out of the tab order and accessibility tree. +const FINE_POINTER_ONLY = "flex pointer-coarse:hidden [@media(hover:none)]:hidden"; +const TOUCH_ONLY = "hidden pointer-coarse:flex [@media(hover:none)]:flex"; +// Invisible actions ignore the pointer, so a touch on a hybrid device reveals them before it can act. +const REVEAL_ACTIONS = + "pointer-events-none opacity-0 transition-opacity duration-100 group-focus-within/actions:pointer-events-auto group-focus-within/actions:opacity-100 group-hover/actions:pointer-events-auto group-hover/actions:opacity-100 motion-reduce:transition-none pointer-coarse:pointer-events-auto pointer-coarse:opacity-100 [@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100"; +const LIMIT_FOCUS_TARGETS = '[data-limit-action="hide"], [data-limit-action="more"]'; + +// Each action reflows the list, so a double-click's second click would act on whatever slid +// under the pointer. Keyboard activations report a detail of 0 and always act. +const singleClick = + (action: (control: HTMLElement) => void) => (event: MouseEvent) => { + if (event.detail <= 1) action(event.currentTarget); + }; + +function LimitActions({ + label, + position, + count, + onMove, + onHide, + className, +}: { + readonly label: string; + readonly position: number; + readonly count: number; + readonly onMove: MoveLimit; + readonly onHide?: ((control: HTMLElement) => void) | undefined; + readonly className: string; +}) { + const gt = useGT(); + const trigger = useRef(null); + const canMove = count > 1; + if (!canMove && !onHide) return null; + const first = position === 0; + const last = position === count - 1; + const up = gt("Move {label} up", { label }); + const down = gt("Move {label} down", { label }); + const hide = gt("Hide {label}", { label }); + const more = gt("More actions for {label}", { label }); + const fromMenu = (action: (control: HTMLElement) => void) => () => { + if (trigger.current) action(trigger.current); + }; + return ( +
+
+ {canMove ? ( + <> + + + + ) : null} + {onHide ? ( + + ) : null} +
+
+ + } + > + + + {canMove ? ( + <> + onMove(-1, control, label))} + > + + onMove(1, control, label))} + > + + + ) : null} + {onHide ? ( + + + ) : null} + + +
); } -function PoolSection({ pool, now }: { readonly pool: LimitPool; readonly now: number }) { +type LayoutSectionEditor = { + readonly providerPosition: number; + readonly providerCount: number; + readonly moveProvider: MoveLimit; + readonly moveWindow: (key: string, ...move: Parameters) => void; + readonly hideWindow: (key: string, label: string, control: HTMLElement) => void; +}; + +const providerLabel = (driver: LimitPool["driver"]) => + providerClients.get(driver)?.label ?? String(driver); + +function describeLimitWindow( + pool: LimitPool, + window: LimitPoolWindow, + m: ReturnType, +) { + const details = + pool.driver === "cursor" ? cursorUsageWindowDetails(window.id, pool, m) : undefined; + const provider = providerLabel(pool.driver); + // Cursor hides a lone window's label on the card; its actions still need a name of their own. + return { details, name: `${provider} · ${details?.label ?? window.label}` }; +} + +function orderLimitSections(pools: readonly LimitPool[], layout: UsageLimitsLayout) { + return orderLimitItems(pools, layout.providerOrder, (pool) => pool.driver).map((pool) => ({ + pool, + windows: orderLimitItems(displayLimitWindows(pool), layout.windowOrder, (window) => + limitWindowKey(pool.driver, window), + ), + })); +} + +function PoolSection({ + pool, + windows, + now, + editor, +}: { + readonly pool: LimitPool; + readonly windows: readonly LimitPoolWindow[]; + readonly now: number; + readonly editor?: LayoutSectionEditor | undefined; +}) { const color = barColor(pool.driver); - const label = providerClients.get(pool.driver)?.label ?? String(pool.driver); - const windows = displayLimitWindows(pool); + const label = providerLabel(pool.driver); const m = useMessages(); return ( -
-

- - {label} -

- {windows.map((window) => { - const details = - pool.driver === "cursor" ? cursorUsageWindowDetails(window.id, pool, m) : undefined; +
+
+ {/* The actions hang off the name so the row keeps its height and never meets a card's. */} +
+

+ + {label} +

+ {editor ? ( + + ) : null} +
+
+ {windows.map((window, index) => { + const key = limitWindowKey(pool.driver, window); + const { details, name } = describeLimitWindow(pool, window, m); return ( editor.moveWindow(key, ...move)} + onHide={(control) => editor.hideWindow(key, name, control)} + className={cn( + "absolute end-3 top-0 flex -translate-y-1/2 bg-background px-1", + REVEAL_ACTIONS, + )} + /> + ) : null + } /> ); })} @@ -671,32 +922,312 @@ function PoolSection({ pool, now }: { readonly pool: LimitPool; readonly now: nu ); } +/** Header menu that restores hidden limits in the current view and resets the saved layout. */ +export function LimitsLayoutMenu({ + ref, + pools, + layout, + onLayoutChange, + onReset, +}: { + readonly ref?: Ref; + readonly pools: readonly LimitPool[]; + readonly layout: UsageLimitsLayout; + readonly onLayoutChange: (update: UsageLimitsLayoutUpdate) => boolean; + readonly onReset: () => void; +}) { + const gt = useGT(); + const m = useMessages(); + const hiddenWindows = new Set(layout.hiddenWindows); + const hidden = orderLimitSections(pools, layout).flatMap(({ pool, windows }) => + windows.flatMap((window) => { + const key = limitWindowKey(pool.driver, window); + return hiddenWindows.has(key) + ? [{ key, name: describeLimitWindow(pool, window, m).name }] + : []; + }), + ); + const layoutLabel = gt("Limits layout"); + const count = hidden.length; + const hiddenLabel = + count > 0 + ? gt("{count, plural, one {{count} hidden} other {{count} hidden}}", { + count, + $context: "usage limits hidden from the page", + }) + : undefined; + const customized = + layout.providerOrder.length > 0 || + layout.windowOrder.length > 0 || + layout.hiddenWindows.length > 0; + return ( + + 0 + ? gt( + "{count, plural, one {Limits layout, {count} hidden} other {Limits layout, {count} hidden}}", + { count }, + ) + : layoutLabel + } + title={layoutLabel} + render={ + ); +} + +function useLimitUndoToasts(hiddenWindowIds: UsageLimitsLayout["hiddenWindowIds"]) { + const undoToasts = useRef( + new Map< + string, + { readonly toastId: ReturnType; readonly hideId: string } + >(), + ); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- retires Undo toasts in the global toast manager once their hide is no longer the saved one, whether through Undo, the header menu, a reset or another tab + useEffect(() => { + for (const [key, undo] of undoToasts.current) { + if (hiddenWindowIds?.[key] === undo.hideId) continue; + undoToasts.current.delete(key); + toastManager.close(undo.toastId); + } + }, [hiddenWindowIds]); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- an unmounted view can no longer tell whether its Undo toasts still match the saved layout + useEffect(() => { + const toasts = undoToasts.current; + return () => { + for (const undo of toasts.values()) toastManager.close(undo.toastId); + toasts.clear(); + }; + }, []); + return undoToasts; +} + export function UsageLimitsPooled({ presentations, + allPresentations = presentations, + pools, now, + layout = DEFAULT_USAGE_LIMITS_LAYOUT, + onLayoutChange, + focusLayoutMenu, }: { - readonly presentations: Parameters[0]; + readonly presentations: LimitPresentations; + readonly allPresentations?: LimitPresentations; + readonly pools: readonly LimitPool[]; readonly now: number; + readonly layout?: UsageLimitsLayout; + readonly onLayoutChange?: ((update: UsageLimitsLayoutUpdate) => boolean) | undefined; + /** Takes focus when the last limit in view is hidden. */ + readonly focusLayoutMenu?: (() => void) | undefined; }) { const gt = useGT(); const m = useMessages(); const [segmentPopover] = useState(() => PopoverCreateHandle()); + const [announcement, setAnnouncement] = useState(""); const segmentPopoverActions = useRef(null); - const pools = collectLimitPools(collectLimitAccounts(presentations), now); + const root = useRef(null); + const hiddenWindows = new Set(layout.hiddenWindows); + const sections = orderLimitSections(pools, layout).flatMap(({ pool, windows }) => { + const visible = windows.filter( + (window) => !hiddenWindows.has(limitWindowKey(pool.driver, window)), + ); + return visible.length > 0 ? [{ pool, windows: visible }] : []; + }); + const undoToasts = useLimitUndoToasts(layout.hiddenWindowIds); + const move = ( + field: "providerOrder" | "windowOrder", + key: string, + visibleKeys: (hidden: ReadonlySet) => readonly string[], + direction: LimitMoveDirection, + button: HTMLElement, + label: string, + ) => { + if (!onLayoutChange) return; + const allPools = + allPresentations === presentations + ? pools + : collectLimitPools(collectLimitAccounts(allPresentations), now); + const defaultKeys = + field === "providerOrder" + ? allPools.map((pool) => pool.driver) + : allPools.flatMap((pool) => + displayLimitWindows(pool).map((window) => limitWindowKey(pool.driver, window)), + ); + // Applied to the latest saved layout, which another tab may have changed since this render. + const outcome: { moved: { position: number; total: number } | null } = { moved: null }; + // A keyed item can lose focus when React moves it to a new position. + const saved = flushSync(() => + onLayoutChange((current) => { + const visible = visibleKeys(new Set(current.hiddenWindows)); + const order = moveLimitItem(current[field], visible, key, direction, defaultKeys); + const position = orderLimitItems(visible, order, (id) => id).indexOf(key) + 1; + outcome.moved = order === current[field] ? null : { position, total: visible.length }; + return outcome.moved ? { ...current, [field]: order } : current; + }), + ); + button.focus({ preventScroll: true }); + button.scrollIntoView({ block: "nearest", inline: "nearest" }); + if (!saved || !outcome.moved) return; + setAnnouncement( + gt("{label} moved to position {position} of {total}.", { label, ...outcome.moved }), + ); + }; + const focusLimitActions = (card: Element | null | undefined) => { + const control = [...(card?.querySelectorAll(LIMIT_FOCUS_TARGETS) ?? [])].find( + (element) => element.getClientRects().length > 0, + ); + if (!control) return false; + control.focus({ preventScroll: true }); + control.scrollIntoView({ block: "nearest", inline: "nearest" }); + return true; + }; + /** Undoes the hide `hideId` if it is still the saved one. Returns whether the layout saved. */ + const undoHide = (key: string, hideId: string) => { + if (!onLayoutChange) return false; + // Judged against the latest saved layout, which another tab may have changed since this render. + const outcome: { shown: boolean } = { shown: false }; + const saved = flushSync(() => + onLayoutChange((current) => { + const next = showLimitWindow(current, key, hideId); + outcome.shown = next !== current; + return next; + }), + ); + if (!saved || !outcome.shown) return saved; + // A changed filter can keep the restored card out of view. + const card = root.current?.querySelector(`[data-limit-card="${CSS.escape(key)}"]`); + if (!focusLimitActions(card)) focusLayoutMenu?.(); + return true; + }; + const hideWindow = (key: string, label: string, control: HTMLElement) => { + if (!onLayoutChange) return; + const cards = [...(root.current?.querySelectorAll("[data-limit-card]") ?? [])]; + const index = cards.findIndex((card) => card.contains(control)); + const neighbors = [...cards.slice(index + 1), ...cards.slice(0, Math.max(index, 0)).reverse()]; + const hideId = randomUUID(); + const outcome: { hidden: boolean } = { hidden: false }; + const saved = flushSync(() => + onLayoutChange((current) => { + const next = hideLimitWindow(current, key, hideId); + outcome.hidden = next !== current; + return next; + }), + ); + if (!saved) return; + if (!neighbors.some((card) => card.isConnected && focusLimitActions(card))) focusLayoutMenu?.(); + // Another tab hid it first, so its Undo belongs there. + if (!outcome.hidden) return; + const previous = undoToasts.current.get(key); + if (previous) toastManager.close(previous.toastId); + // The toast region is live, so it also announces the change. + const toastId = toastManager.add({ + type: "success", + title: gt("{label} hidden", { label }), + actionProps: { + children: gt("Undo"), + onClick: () => { + // A failed save keeps the toast for a retry; a later hide leaves nothing to undo. + if (undoHide(key, hideId)) toastManager.close(toastId); + }, + }, + }); + undoToasts.current.set(key, { toastId, hideId }); + }; const notices = collectLimitNotices(presentations, m); const externalLinks = collectExternalUsageLinks(presentations, m); return ( -
+
+ + {announcement} + {pools.length === 0 && notices.length === 0 && externalLinks.length === 0 ? (

No provider on the selected environments reports subscription limits.

) : null} + {pools.length > 0 && sections.length === 0 ? ( +

+ All limits in this view are hidden. +

+ ) : null} - {pools.map((pool) => ( - - - + {sections.map(({ pool, windows }, index) => ( + + move( + "providerOrder", + pool.driver, + (hidden) => + pools + .filter((each) => + displayLimitWindows(each).some( + (window) => !hidden.has(limitWindowKey(each.driver, window)), + ), + ) + .map((each) => each.driver), + ...moveAction, + ), + moveWindow: (key, ...moveAction) => + move( + "windowOrder", + key, + (hidden) => + displayLimitWindows(pool) + .map((window) => limitWindowKey(pool.driver, window)) + .filter((windowKey) => !hidden.has(windowKey)), + ...moveAction, + ), + hideWindow, + } + : undefined + } + /> ))} @@ -706,7 +1237,7 @@ export function UsageLimitsPooled({ handle={segmentPopover} actions={segmentPopoverActions} payload={payload} - pools={pools} + windows={sections.flatMap(({ windows }) => windows)} now={now} /> ) : null diff --git a/apps/web/src/components/usage/UsagePage.tsx b/apps/web/src/components/usage/UsagePage.tsx index adb05afb92eb..bede33a38568 100644 --- a/apps/web/src/components/usage/UsagePage.tsx +++ b/apps/web/src/components/usage/UsagePage.tsx @@ -1,5 +1,10 @@ import { ChatGptUsageButton } from "../settings/ChatGptUsageButton"; -import { usesChatGptSharing } from "@t3tools/shared/usageLimits"; +import { + collectLimitAccounts, + collectLimitPools, + displayLimitWindows, + usesChatGptSharing, +} from "@t3tools/shared/usageLimits"; import { RefreshIcon } from "~/components/ui/refresh-icon"; import { useAtomValue } from "@effect/atom-react"; import { Atom } from "effect/reactivity"; @@ -32,6 +37,7 @@ import { import { cn } from "../../lib/utils"; import { usePrimarySettings } from "../../hooks/useSettings"; +import { useStableCallback } from "../../hooks/useStableCallback"; import { resolveHour12 } from "../../timestampFormat"; import { appAtomRegistry } from "~/rpc/atomRegistry"; import { environmentPresentations } from "../../state/presentation"; @@ -68,6 +74,7 @@ import { ScrollArea } from "../ui/scroll-area"; import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; import { AppRouteModal, AppRouteModalClose } from "../AppRouteModal"; import { Skeleton } from "../ui/skeleton"; +import { toastManager } from "../ui/toast"; import { Toggle, ToggleGroup } from "../ui/toggle-group"; import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; import { @@ -77,7 +84,8 @@ import { WorkspaceBreadcrumbText, } from "../WorkspaceBreadcrumb"; import { WorkspacePageContainer } from "../WorkspacePageContainer"; -import { UsageLimitsSection } from "./UsageLimits"; +import { selectLimitPresentations } from "./UsageLimits"; +import { LimitsLayoutMenu, UsageLimitsPooled } from "./UsageLimitsPooled"; import { UsagePriceOverrides } from "./UsagePriceOverrides"; import { UsageProviderChart } from "./UsageProviderChart"; import { SpeedPremium, UsageModelDialog } from "./UsageModelDialog"; @@ -104,8 +112,10 @@ import { import { readUsagePagePreferences, saveUsagePagePreferences, + useSavedUsageLimitsLayout, type UsagePagePreferences, } from "./usagePagePreferences"; +import { DEFAULT_USAGE_LIMITS_LAYOUT, type UsageLimitsLayoutUpdate } from "./usageLimitsLayout"; function isUsageMetric(value: string | null | undefined): value is UsageMetric { return METRIC_OPTIONS.some((option) => option.value === value); @@ -115,6 +125,10 @@ function isUsageWindowDays(value: number): value is UsagePagePreferences["window return WINDOW_OPTIONS.some((option) => option.days === value); } +function selectUsageWindow(days: UsagePagePreferences["windowDays"]) { + return { days, window: makeWindow(days, undefined, days === 1 ? "hour" : "day") }; +} + const providerLabel = (provider: UsageProviderKind) => PROVIDER_PRESENTATION[provider].label; function usageLoading( @@ -191,16 +205,14 @@ export function UsagePage() { ? gt("{label} ({shortcut})", { label: m(option.label), shortcut }) : m(option.label); }; - const [windowSelection, setWindowSelection] = useState(() => ({ - days: preferences.windowDays, - window: makeWindow( - preferences.windowDays, - undefined, - preferences.windowDays === 1 ? "hour" : "day", - ), - })); + const [windowSelection, setWindowSelection] = useState(() => + selectUsageWindow(preferences.windowDays), + ); const metric = preferences.metric; const showingLimits = metric === "limits"; + const limitsLayout = useSavedUsageLimitsLayout() ?? DEFAULT_USAGE_LIMITS_LAYOUT; + const layoutMenuRef = useRef(null); + const compactLayoutMenuRef = useRef(null); const [isRefreshing, setIsRefreshing] = useState(false); const [limitsNow, setLimitsNow] = useState(() => Date.now()); const refreshingRef = useRef(false); @@ -227,6 +239,15 @@ export function UsagePage() { const presentationsWithProviders = useAtomValue( environmentPresentations.presentationsWithProvidersAtom, ); + const limitPresentations = showingLimits + ? selectLimitPresentations(presentationsWithProviders, selectedEnvironmentIds, hiddenProviders) + : null; + const limitPools = limitPresentations + ? collectLimitPools(collectLimitAccounts(limitPresentations), limitsNow) + : []; + const layoutAvailable = + selectedEnvironments.length > 0 && + limitPools.some((pool) => displayLimitWindows(pool).length > 0); const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, { reportFailure: false, }); @@ -236,22 +257,32 @@ export function UsagePage() { ); const updatePreferences = (patch: Partial) => { - const nextPreferences = { ...preferences, ...patch }; - setPreferences(nextPreferences); - saveUsagePagePreferences(nextPreferences); + setPreferences((current) => ({ ...current, ...patch })); + saveUsagePagePreferences((current) => ({ ...current, ...patch })); }; const selectWindow = (days: number) => { if (!isUsageWindowDays(days)) return; updatePreferences({ windowDays: days }); - setWindowSelection({ - days, - window: makeWindow(days, undefined, days === 1 ? "hour" : "day"), - }); + setWindowSelection(selectUsageWindow(days)); }; const selectMetric = (nextMetric: UsageMetric) => { if (nextMetric === "limits") setLimitsNow(Date.now()); updatePreferences({ metric: nextMetric }); }; + const updateLimitsLayout = useStableCallback((update?: UsageLimitsLayoutUpdate) => { + const saved = saveUsagePagePreferences((current) => ({ + ...current, + limitsLayout: update?.(current.limitsLayout ?? DEFAULT_USAGE_LIMITS_LAYOUT), + })); + if (!saved) toastManager.add({ type: "error", title: gt("Could not save. Try again.") }); + return saved; + }); + const resetLimitsLayout = useStableCallback(() => updateLimitsLayout()); + // Only one header variant is displayed at a time. + const focusLayoutMenu = () => + [layoutMenuRef.current, compactLayoutMenuRef.current] + .find((button) => button?.getClientRects().length) + ?.focus(); const refreshLimits = (automatic = false) => // Settled so the timestamp still advances when a refresh throws. settlePromise(() => @@ -369,6 +400,28 @@ export function UsagePage() { }); const windowOptionLabel = WINDOW_OPTIONS.find((option) => option.days === windowDays)?.label; const metricOptionLabel = METRIC_OPTIONS.find((option) => option.value === metric)?.label; + const limitsLayoutMenu = (ref: typeof layoutMenuRef) => + layoutAvailable ? ( + + ) : null; + const refreshButton = ( + + ); const topbarContent = (
@@ -440,16 +493,8 @@ export function UsagePage() { ))} - + {limitsLayoutMenu(layoutMenuRef)} + {refreshButton}
{showingLimits ? null : ( @@ -497,16 +542,8 @@ export function UsagePage() { ))} - + {limitsLayoutMenu(compactLayoutMenuRef)} + {refreshButton}
); @@ -531,11 +568,15 @@ export function UsagePage() { ? gt("Select an environment to see limits.") : gt("Select an environment to see usage.")}

- ) : showingLimits ? ( - ) : shown === null ? ( diff --git a/apps/web/src/components/usage/usageLimitsLayout.test.ts b/apps/web/src/components/usage/usageLimitsLayout.test.ts new file mode 100644 index 000000000000..5d9ee142c1a1 --- /dev/null +++ b/apps/web/src/components/usage/usageLimitsLayout.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + hideLimitWindow, + moveLimitItem, + orderLimitItems, + showLimitWindow, +} from "./usageLimitsLayout"; + +describe("usage limits ordering", () => { + it("keeps saved positions outside the current filter and appends new items in default order", () => { + const savedOrder = ["codex", "cursor", "claude"]; + const editedOrder = moveLimitItem(savedOrder, ["codex", "claude"], "claude", -1); + expect(editedOrder).toEqual(["claude", "cursor", "codex"]); + expect( + orderLimitItems( + ["grok", "codex", "antigravity", "claude", "cursor"], + editedOrder, + (id) => id, + ), + ).toEqual(["claude", "cursor", "codex", "grok", "antigravity"]); + }); + + it("keeps the default slots of filtered providers on the first move", () => { + const defaults = ["codex", "cursor", "claude", "antigravity"]; + expect(moveLimitItem([], ["codex", "claude"], "claude", -1, defaults)).toEqual([ + "claude", + "cursor", + "codex", + "antigravity", + ]); + }); + + it("moves the requested item when a filter changes the visible default order", () => { + const defaults = ["codex", "cursor", "claude", "antigravity"]; + const visible = ["claude", "codex", "antigravity"]; + const editedOrder = moveLimitItem([], visible, "claude", 1, defaults); + expect(editedOrder).toEqual(["codex", "cursor", "claude", "antigravity"]); + expect(orderLimitItems(visible, editedOrder, (id) => id)).toEqual([ + "codex", + "claude", + "antigravity", + ]); + }); + + it("applies a move from a stale view to the latest saved order", () => { + // Another tab raised D after this one rendered A B C D; lowering A keeps D above C. + const latest = ["A", "B", "D", "C"]; + expect(moveLimitItem(latest, ["A", "B", "C", "D"], "A", 1)).toEqual(["B", "A", "D", "C"]); + // C is already last in the latest order, so there is nothing to move it past. + expect(moveLimitItem(latest, ["A", "B", "C", "D"], "C", 1)).toBe(latest); + }); +}); + +describe("usage limits visibility", () => { + const empty = { providerOrder: [], windowOrder: [], hiddenWindows: [] }; + + it("undoes only the hide that is still saved", () => { + const hidden = hideLimitWindow(empty, "A", "first"); + expect(hideLimitWindow(hidden, "A", "second")).toBe(hidden); + const rehidden = hideLimitWindow(showLimitWindow(hidden, "A"), "A", "second"); + expect(showLimitWindow(rehidden, "A", "first")).toBe(rehidden); + expect(showLimitWindow(rehidden, "A", "second")).toEqual({ ...empty, hiddenWindowIds: {} }); + }); + + it("shows a limit hidden before hides had an identity", () => { + const saved = { ...empty, hiddenWindows: ["A", "B"] }; + expect(showLimitWindow(saved, "A", "any")).toBe(saved); + expect(showLimitWindow(saved, "A")).toEqual({ + ...empty, + hiddenWindows: ["B"], + hiddenWindowIds: {}, + }); + }); +}); diff --git a/apps/web/src/components/usage/usageLimitsLayout.ts b/apps/web/src/components/usage/usageLimitsLayout.ts new file mode 100644 index 000000000000..c866090bee46 --- /dev/null +++ b/apps/web/src/components/usage/usageLimitsLayout.ts @@ -0,0 +1,102 @@ +import type { LimitPool, LimitPoolWindow } from "@t3tools/shared/usageLimits"; +import * as Schema from "effect/Schema"; + +export const UsageLimitsLayoutSchema = Schema.Struct({ + providerOrder: Schema.Array(Schema.String), + windowOrder: Schema.Array(Schema.String), + hiddenWindows: Schema.Array(Schema.String), + /** + * The latest hide of each hidden window, so an Undo reverses only the hide it reports. Layouts + * saved before it, or shown elsewhere, have no entry and no Undo to match. + */ + hiddenWindowIds: Schema.optional(Schema.Record(Schema.String, Schema.String)), +}); + +export type UsageLimitsLayout = typeof UsageLimitsLayoutSchema.Type; +export type UsageLimitsLayoutUpdate = (current: UsageLimitsLayout) => UsageLimitsLayout; +export type LimitMoveDirection = -1 | 1; + +export const DEFAULT_USAGE_LIMITS_LAYOUT: UsageLimitsLayout = { + providerOrder: [], + windowOrder: [], + hiddenWindows: [], +}; + +export function limitWindowKey( + driver: LimitPool["driver"], + window: Pick, +): string { + return JSON.stringify([driver, window.kind, window.id]); +} + +export function orderLimitItems( + items: readonly T[], + order: readonly string[], + key: (item: T) => string, +): readonly T[] { + if (order.length === 0) return items; + const ranks = new Map(order.map((id, index) => [id, index])); + const rank = (item: T) => ranks.get(key(item)) ?? order.length; + return [...items].sort((left, right) => rank(left) - rank(right)); +} + +/** + * Moves `key` past its neighbor in the visible list as `order` ranks it now, so a view rendered + * before another tab's change still applies its intent to the latest order. `visibleKeys` are in + * default display order. Saved items outside the view keep their slots. Returns `order` itself + * when there is nothing to move past. + */ +export function moveLimitItem( + order: readonly string[], + visibleKeys: readonly string[], + key: string, + direction: LimitMoveDirection, + defaultKeys: readonly string[] = visibleKeys, +): readonly string[] { + const current = orderLimitItems(visibleKeys, order, (id) => id); + const index = current.indexOf(key); + const neighbor = current[index + direction]; + if (index < 0 || neighbor === undefined) return order; + const moved = [...current]; + moved[index] = neighbor; + moved[index + direction] = key; + const visible = new Set(visibleKeys); + let next = 0; + return [...new Set([...order, ...defaultKeys, ...visibleKeys])].map((id) => + visible.has(id) ? (moved[next++] ?? id) : id, + ); +} + +/** Hides `key` as the hide `hideId`. Returns `layout` itself when `key` is already hidden. */ +export function hideLimitWindow( + layout: UsageLimitsLayout, + key: string, + hideId: string, +): UsageLimitsLayout { + if (layout.hiddenWindows.includes(key)) return layout; + return { + ...layout, + hiddenWindows: [...layout.hiddenWindows, key], + hiddenWindowIds: { ...layout.hiddenWindowIds, [key]: hideId }, + }; +} + +/** + * Shows `key`. With `hideId`, only while that hide is still the latest one, so a stale Undo cannot + * reverse a later hide. Returns `layout` itself when there is nothing to show. + */ +export function showLimitWindow( + layout: UsageLimitsLayout, + key: string, + hideId?: string, +): UsageLimitsLayout { + if (!layout.hiddenWindows.includes(key)) return layout; + if (hideId !== undefined && layout.hiddenWindowIds?.[key] !== hideId) return layout; + return { + ...layout, + hiddenWindows: layout.hiddenWindows.filter((window) => window !== key), + hiddenWindowIds: Object.fromEntries( + Object.entries(layout.hiddenWindowIds ?? {}).filter(([window]) => window !== key), + ), + }; +} diff --git a/apps/web/src/components/usage/usagePagePreferences.test.ts b/apps/web/src/components/usage/usagePagePreferences.test.ts index 075076a9b3c5..b214f3b9699f 100644 --- a/apps/web/src/components/usage/usagePagePreferences.test.ts +++ b/apps/web/src/components/usage/usagePagePreferences.test.ts @@ -14,7 +14,7 @@ beforeEach(() => { values.set(key, value); }, }; - vi.stubGlobal("window", { localStorage: storage }); + vi.stubGlobal("window", { localStorage: storage, dispatchEvent: () => true }); vi.spyOn(console, "error").mockImplementation(() => {}); }); @@ -24,14 +24,42 @@ afterEach(() => { }); describe("Usage page preferences", () => { - it("round-trips hidden providers and reads older saves without them", () => { - saveUsagePagePreferences({ metric: "cost", windowDays: 7, hiddenProviders: ["codex"] }); - expect(readUsagePagePreferences().hiddenProviders).toEqual(["codex"]); + it("round-trips usage preferences and reads older saves without a limits layout", () => { + const limitsLayout = { + providerOrder: ["claudeAgent", "antigravity"], + windowOrder: ['["antigravity","weekly","gemini-weekly"]'], + hiddenWindows: ['["antigravity","weekly","gemini-argon-wtu-weekly"]'], + }; + const preferences = { metric: "cost", windowDays: 7, hiddenProviders: ["codex"] } as const; + saveUsagePagePreferences({ ...preferences, limitsLayout }); + expect(readUsagePagePreferences()).toEqual({ ...preferences, limitsLayout }); + + // Changing the metric in another client reads the layout saved by the first. + saveUsagePagePreferences((current) => ({ ...current, metric: "tokens" })); + expect(readUsagePagePreferences()).toEqual({ ...preferences, metric: "tokens", limitsLayout }); + + saveUsagePagePreferences((current) => ({ ...current, limitsLayout: undefined })); + expect(readUsagePagePreferences()).toEqual({ ...preferences, metric: "tokens" }); values.set(key, '{"metric":"tokens","windowDays":30}'); expect(readUsagePagePreferences()).toEqual({ metric: "tokens", windowDays: 30 }); }); + it("reports rejected writes and keeps the saved layout available", () => { + const limitsLayout = { providerOrder: ["codex"], windowOrder: [], hiddenWindows: [] }; + const preferences = { metric: "limits", windowDays: 30, limitsLayout } as const; + saveUsagePagePreferences(preferences); + vi.spyOn(storage, "setItem").mockImplementationOnce(() => { + throw new DOMException("Storage is full", "QuotaExceededError"); + }); + const resetLayout = () => + saveUsagePagePreferences((current) => ({ ...current, limitsLayout: undefined })); + + expect(resetLayout()).toBe(false); + expect(readUsagePagePreferences()).toEqual(preferences); + expect(resetLayout()).toBe(true); + }); + // regression: #10189 an invalid saved usage selection was never replaced it.each([ "not-json", diff --git a/apps/web/src/components/usage/usagePagePreferences.ts b/apps/web/src/components/usage/usagePagePreferences.ts index 1aeaefc43da1..64338e7ffc82 100644 --- a/apps/web/src/components/usage/usagePagePreferences.ts +++ b/apps/web/src/components/usage/usagePagePreferences.ts @@ -1,31 +1,44 @@ import { UsageProviderKind } from "@t3tools/contracts"; import * as Schema from "effect/Schema"; -import { getLocalStorageItem, setLocalStorageItem } from "../../hooks/useLocalStorage"; +import { + readLocalStorageValue, + useLocalStorage, + writeLocalStorageValue, +} from "../../hooks/useLocalStorage"; +import { UsageLimitsLayoutSchema } from "./usageLimitsLayout"; const STORAGE_KEY = "t3code:usage-page-preferences:v1"; const UsagePagePreferencesSchema = Schema.Struct({ metric: Schema.Literals(["cost", "tokens", "limits"]), windowDays: Schema.Literals([1, 7, 30, 90]), hiddenProviders: Schema.optional(Schema.Array(UsageProviderKind)), + limitsLayout: Schema.optional(UsageLimitsLayoutSchema), }); export type UsagePagePreferences = typeof UsagePagePreferencesSchema.Type; const DEFAULT_PREFERENCES: UsagePagePreferences = { metric: "limits", windowDays: 30 }; export function readUsagePagePreferences(): UsagePagePreferences { - try { - return getLocalStorageItem(STORAGE_KEY, UsagePagePreferencesSchema) ?? DEFAULT_PREFERENCES; - } catch (error) { - console.error("Could not read Usage page preferences.", error); - return DEFAULT_PREFERENCES; - } + return readLocalStorageValue(STORAGE_KEY, DEFAULT_PREFERENCES, UsagePagePreferencesSchema); } -export function saveUsagePagePreferences(preferences: UsagePagePreferences): void { - try { - setLocalStorageItem(STORAGE_KEY, preferences, UsagePagePreferencesSchema); - } catch (error) { - console.error("Could not save Usage page preferences.", error); - } +export function saveUsagePagePreferences( + preferences: UsagePagePreferences | ((current: UsagePagePreferences) => UsagePagePreferences), +): boolean { + return writeLocalStorageValue( + STORAGE_KEY, + preferences, + DEFAULT_PREFERENCES, + UsagePagePreferencesSchema, + ); +} + +export function useSavedUsageLimitsLayout() { + const [preferences] = useLocalStorage( + STORAGE_KEY, + DEFAULT_PREFERENCES, + UsagePagePreferencesSchema, + ); + return preferences.limitsLayout; } diff --git a/apps/web/src/hooks/useLocalStorage.ts b/apps/web/src/hooks/useLocalStorage.ts index 6d3834286c74..fb1625fcb8f1 100644 --- a/apps/web/src/hooks/useLocalStorage.ts +++ b/apps/web/src/hooks/useLocalStorage.ts @@ -157,7 +157,7 @@ export function writeLocalStorageValue( value: T | ((val: T) => T), initialValue: T, schema: Schema.Codec, -): void { +): boolean { try { let valueToStore: T; if (typeof value === "function") { @@ -186,8 +186,10 @@ export function writeLocalStorageValue( setLocalStorageItem(key, valueToStore, schema); } dispatchLocalStorageChange(key); + return true; } catch (error) { console.error("[LOCALSTORAGE] Could not update stored value.", error); + return false; } } diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 3a71e9206344..75bee7bbc511 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -12178,9 +12178,20 @@ "4df3ff1be768a7ab": "{name}: {remaining} % übrig", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "0-$-Limit", + "90505e3bfadccee0": "{label} nach oben verschieben", + "33234f46946de376": "{label} nach unten verschieben", + "68e588f6255f796f": "{label} ausblenden", + "050ab24d4c4f1e41": "Limit-Layout", + "c3185b3b04cd5b5e": "{count, plural, one {{count} ausgeblendet} other {{count} ausgeblendet}}", + "3fa021245e4ad1d1": "{count, plural, one {Limit-Layout, {count} ausgeblendet} other {Limit-Layout, {count} ausgeblendet}}", + "afc7569ca717f8cc": "Ausgeblendet", + "191e6f4ba689bb5d": "Layout zurücksetzen", + "bbd35f7979a24a2e": "{label} wurde an Position {position} von {total} verschoben.", + "f3f87fb82052fd8e": "{label} ausgeblendet", "a16b48709357a5a7": "Nutzung verwalten", "a00e74aaa421c524": "übrig", "8bd6f07136317c8f": "Kein Anbieter in den ausgewählten Umgebungen meldet Abo-Limits.", + "aa9a8302e7c6c99f": "Alle Limits in dieser Ansicht sind ausgeblendet.", "87f5d0c61b335f38": "Nutzung in ChatGPT mit deinem verbundenen Konto ansehen.", "5b4c71b36b979e80": "Kosten", "fce17caaa0d1a45b": "Ohne Preis", @@ -12207,12 +12218,13 @@ } ], "b93dc3faeb8d9b2e": "{label} ({shortcut})", + "1eee306da7eb0382": "Speichern fehlgeschlagen. Versuch es erneut.", "71efdf870da332e8": "{start} bis {end}", + "67070d5478b6aeec": "Limits aktualisieren", + "93a3e5869ba37c86": "Nutzung aktualisieren", "77100b4211d5cf8c": "Navigationspfad der Nutzung", "2f96360836544ae6": "Nutzungszeitraum", "9e5383009cd3f93b": "Nutzungsmetrik", - "67070d5478b6aeec": "Limits aktualisieren", - "93a3e5869ba37c86": "Nutzung aktualisieren", "5dc5cdee2153cd8d": "Verbinde eine Umgebung, um Limits zu sehen.", "a9b664b4dc630ffa": "Verbinde eine Umgebung, um die Nutzung zu sehen.", "d2d071e45a2d6b89": "Wähle eine Umgebung, um Limits zu sehen.", @@ -12333,7 +12345,6 @@ "757c752842c88658": "Verwende nicht negative Zahlen für Preise.", "a308e844f2e82778": "Modellzuordnungen dürfen auf {target} keinen Zyklus bilden.", "b6be43c36bab124c": "Server aktualisieren, um Modelle zuzuordnen", - "1eee306da7eb0382": "Speichern fehlgeschlagen. Versuch es erneut.", "c8fa587fc0be1938": "Limits", "14955bff9f2f90cd": "Letzte 24 Std.", "2cddd6095abc734a": "7 Tage", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 65ed2a4db1b8..cca808cf3354 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -12186,9 +12186,20 @@ "4df3ff1be768a7ab": "{name}: {remaining}% left", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "$0 cap", + "90505e3bfadccee0": "Move {label} up", + "33234f46946de376": "Move {label} down", + "68e588f6255f796f": "Hide {label}", + "050ab24d4c4f1e41": "Limits layout", + "c3185b3b04cd5b5e": "{count, plural, one {{count} hidden} other {{count} hidden}}", + "3fa021245e4ad1d1": "{count, plural, one {Limits layout, {count} hidden} other {Limits layout, {count} hidden}}", + "afc7569ca717f8cc": "Hidden", + "191e6f4ba689bb5d": "Reset layout", + "bbd35f7979a24a2e": "{label} moved to position {position} of {total}.", + "f3f87fb82052fd8e": "{label} hidden", "a16b48709357a5a7": "Manage usage", "a00e74aaa421c524": "left", "8bd6f07136317c8f": "No provider on the selected environments reports subscription limits.", + "aa9a8302e7c6c99f": "All limits in this view are hidden.", "87f5d0c61b335f38": "View usage in ChatGPT with your connected account.", "5b4c71b36b979e80": "Cost", "fce17caaa0d1a45b": "Unpriced", @@ -12215,12 +12226,13 @@ } ], "b93dc3faeb8d9b2e": "{label} ({shortcut})", + "1eee306da7eb0382": "Could not save. Try again.", "71efdf870da332e8": "{start} to {end}", + "67070d5478b6aeec": "Refresh limits", + "93a3e5869ba37c86": "Refresh usage", "77100b4211d5cf8c": "Usage breadcrumb", "2f96360836544ae6": "Usage period", "9e5383009cd3f93b": "Usage metric", - "67070d5478b6aeec": "Refresh limits", - "93a3e5869ba37c86": "Refresh usage", "5dc5cdee2153cd8d": "Connect an environment to see limits.", "a9b664b4dc630ffa": "Connect an environment to see usage.", "d2d071e45a2d6b89": "Select an environment to see limits.", @@ -12341,7 +12353,6 @@ "757c752842c88658": "Use non-negative numbers for prices.", "a308e844f2e82778": "Model mappings cannot form a cycle on {target}.", "b6be43c36bab124c": "Update server to map models", - "1eee306da7eb0382": "Could not save. Try again.", "c8fa587fc0be1938": "Limits", "14955bff9f2f90cd": "Past 24h", "2cddd6095abc734a": "7 days", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index dae05eda74dd..b189685e7d51 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -12171,9 +12171,20 @@ "4df3ff1be768a7ab": "{name}: queda un {remaining}%", "7aaaff1c6484f25c": "Segmento", "8bcab2ef61de6518": "Límite de 0 $", + "90505e3bfadccee0": "Subir {label}", + "33234f46946de376": "Bajar {label}", + "68e588f6255f796f": "Ocultar {label}", + "050ab24d4c4f1e41": "Disposición de los límites", + "c3185b3b04cd5b5e": "{count, plural, one {{count} oculto} other {{count} ocultos}}", + "3fa021245e4ad1d1": "{count, plural, one {Disposición de los límites, {count} oculto} other {Disposición de los límites, {count} ocultos}}", + "afc7569ca717f8cc": "Ocultos", + "191e6f4ba689bb5d": "Restablecer la disposición", + "bbd35f7979a24a2e": "{label} se movió a la posición {position} de {total}.", + "f3f87fb82052fd8e": "Oculto: {label}", "a16b48709357a5a7": "Gestionar uso", "a00e74aaa421c524": "restante", "8bd6f07136317c8f": "Ningún proveedor de los entornos seleccionados informa de límites de suscripción.", + "aa9a8302e7c6c99f": "Todos los límites de esta vista están ocultos.", "87f5d0c61b335f38": "Consulta el uso en ChatGPT con tu cuenta conectada.", "5b4c71b36b979e80": "Coste", "fce17caaa0d1a45b": "Sin precio", @@ -12200,12 +12211,13 @@ } ], "b93dc3faeb8d9b2e": "{label} ({shortcut})", + "1eee306da7eb0382": "No se pudo guardar. Inténtalo de nuevo.", "71efdf870da332e8": "Del {start} al {end}", + "67070d5478b6aeec": "Actualizar límites", + "93a3e5869ba37c86": "Actualizar uso", "77100b4211d5cf8c": "Ruta de navegación de uso", "2f96360836544ae6": "Periodo de uso", "9e5383009cd3f93b": "Métrica de uso", - "67070d5478b6aeec": "Actualizar límites", - "93a3e5869ba37c86": "Actualizar uso", "5dc5cdee2153cd8d": "Conecta un entorno para ver los límites.", "a9b664b4dc630ffa": "Conecta un entorno para ver el uso.", "d2d071e45a2d6b89": "Selecciona un entorno para ver los límites.", @@ -12326,7 +12338,6 @@ "757c752842c88658": "Usa números no negativos para los precios.", "a308e844f2e82778": "Las asignaciones de modelos no pueden formar un ciclo en {target}.", "b6be43c36bab124c": "Actualiza el servidor para asignar modelos", - "1eee306da7eb0382": "No se pudo guardar. Inténtalo de nuevo.", "c8fa587fc0be1938": "Límites", "14955bff9f2f90cd": "Últimas 24 h", "2cddd6095abc734a": "7 días", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 6054810c0c23..15e01bea104e 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -12176,9 +12176,20 @@ "4df3ff1be768a7ab": "{name} : {remaining} % restant", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "Plafond de 0 $", + "90505e3bfadccee0": "Monter {label}", + "33234f46946de376": "Descendre {label}", + "68e588f6255f796f": "Masquer {label}", + "050ab24d4c4f1e41": "Disposition des limites", + "c3185b3b04cd5b5e": "{count, plural, one {{count} masquée} other {{count} masquées}}", + "3fa021245e4ad1d1": "{count, plural, one {Disposition des limites, {count} masquée} other {Disposition des limites, {count} masquées}}", + "afc7569ca717f8cc": "Masquées", + "191e6f4ba689bb5d": "Réinitialiser la disposition", + "bbd35f7979a24a2e": "{label} a été déplacé à la position {position} sur {total}.", + "f3f87fb82052fd8e": "Masqué : {label}", "a16b48709357a5a7": "Gérer l’utilisation", "a00e74aaa421c524": "restant", "8bd6f07136317c8f": "Aucun fournisseur des environnements sélectionnés ne signale de limites d’abonnement.", + "aa9a8302e7c6c99f": "Toutes les limites de cette vue sont masquées.", "87f5d0c61b335f38": "Consultez l’utilisation dans ChatGPT avec votre compte connecté.", "5b4c71b36b979e80": "Coût", "fce17caaa0d1a45b": "Sans prix", @@ -12205,12 +12216,13 @@ } ], "b93dc3faeb8d9b2e": "{label} ({shortcut})", + "1eee306da7eb0382": "Impossible d’enregistrer. Réessayez.", "71efdf870da332e8": "Du {start} au {end}", + "67070d5478b6aeec": "Actualiser les limites", + "93a3e5869ba37c86": "Actualiser l’utilisation", "77100b4211d5cf8c": "Fil d’Ariane de l’utilisation", "2f96360836544ae6": "Période d’utilisation", "9e5383009cd3f93b": "Métrique d’utilisation", - "67070d5478b6aeec": "Actualiser les limites", - "93a3e5869ba37c86": "Actualiser l’utilisation", "5dc5cdee2153cd8d": "Connectez un environnement pour voir les limites.", "a9b664b4dc630ffa": "Connectez un environnement pour voir l’utilisation.", "d2d071e45a2d6b89": "Sélectionnez un environnement pour voir les limites.", @@ -12331,7 +12343,6 @@ "757c752842c88658": "Utilisez des nombres positifs ou nuls pour les prix.", "a308e844f2e82778": "Les correspondances de modèles ne peuvent pas former de cycle sur {target}.", "b6be43c36bab124c": "Mettez à jour le serveur pour faire correspondre des modèles", - "1eee306da7eb0382": "Impossible d’enregistrer. Réessayez.", "c8fa587fc0be1938": "Limites", "14955bff9f2f90cd": "Dernières 24 h", "2cddd6095abc734a": "7 jours", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 188d63866545..dee4fc1e7c94 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -12127,9 +12127,20 @@ "4df3ff1be768a7ab": "{name}: 残り {remaining}%", "7aaaff1c6484f25c": "セグメント", "8bcab2ef61de6518": "上限 $0", + "90505e3bfadccee0": "{label} を上へ移動", + "33234f46946de376": "{label} を下へ移動", + "68e588f6255f796f": "{label} を非表示にする", + "050ab24d4c4f1e41": "上限のレイアウト", + "c3185b3b04cd5b5e": "{count, plural, other {{count} 件非表示}}", + "3fa021245e4ad1d1": "{count, plural, other {上限のレイアウト、{count} 件非表示}}", + "afc7569ca717f8cc": "非表示", + "191e6f4ba689bb5d": "レイアウトをリセット", + "bbd35f7979a24a2e": "{label} を {total} 件中 {position} 番目に移動しました。", + "f3f87fb82052fd8e": "{label} を非表示にしました", "a16b48709357a5a7": "使用量を管理", "a00e74aaa421c524": "残り", "8bd6f07136317c8f": "選択した環境には、サブスクリプションの上限を報告するプロバイダーがありません。", + "aa9a8302e7c6c99f": "この画面の上限はすべて非表示です。", "87f5d0c61b335f38": "接続したアカウントで ChatGPT の使用量を表示します。", "5b4c71b36b979e80": "コスト", "fce17caaa0d1a45b": "価格不明", @@ -12156,12 +12167,13 @@ } ], "b93dc3faeb8d9b2e": "{label} ({shortcut})", + "1eee306da7eb0382": "保存できませんでした。もう一度お試しください。", "71efdf870da332e8": "{start}〜{end}", + "67070d5478b6aeec": "上限を更新", + "93a3e5869ba37c86": "使用量を更新", "77100b4211d5cf8c": "使用量のパンくずリスト", "2f96360836544ae6": "使用量の期間", "9e5383009cd3f93b": "使用量の指標", - "67070d5478b6aeec": "上限を更新", - "93a3e5869ba37c86": "使用量を更新", "5dc5cdee2153cd8d": "上限を表示するには環境に接続してください。", "a9b664b4dc630ffa": "使用量を表示するには環境に接続してください。", "d2d071e45a2d6b89": "上限を表示するには環境を選択してください。", @@ -12282,7 +12294,6 @@ "757c752842c88658": "価格には 0 以上の数値を使用してください。", "a308e844f2e82778": "{target} ではモデルのマッピングを循環させることはできません。", "b6be43c36bab124c": "モデルをマッピングするにはサーバーを更新してください", - "1eee306da7eb0382": "保存できませんでした。もう一度お試しください。", "c8fa587fc0be1938": "上限", "14955bff9f2f90cd": "過去 24 時間", "2cddd6095abc734a": "7 日間", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index fd4f1a5af2fc..53a5b3323f39 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -12123,9 +12123,20 @@ "4df3ff1be768a7ab": "{name}: {remaining}% 남음", "7aaaff1c6484f25c": "구간", "8bcab2ef61de6518": "$0 한도", + "90505e3bfadccee0": "{label} 위로 이동", + "33234f46946de376": "{label} 아래로 이동", + "68e588f6255f796f": "{label} 숨기기", + "050ab24d4c4f1e41": "한도 레이아웃", + "c3185b3b04cd5b5e": "{count, plural, other {{count}개 숨김}}", + "3fa021245e4ad1d1": "{count, plural, other {한도 레이아웃, {count}개 숨김}}", + "afc7569ca717f8cc": "숨김", + "191e6f4ba689bb5d": "레이아웃 초기화", + "bbd35f7979a24a2e": "{label}을(를) {total}개 중 {position}번째로 이동했습니다.", + "f3f87fb82052fd8e": "{label} 숨김", "a16b48709357a5a7": "사용량 관리", "a00e74aaa421c524": "남음", "8bd6f07136317c8f": "선택한 환경에 구독 한도를 보고하는 제공자가 없습니다.", + "aa9a8302e7c6c99f": "이 화면의 모든 한도가 숨겨져 있습니다.", "87f5d0c61b335f38": "연결된 계정으로 ChatGPT에서 사용량을 확인하세요.", "5b4c71b36b979e80": "비용", "fce17caaa0d1a45b": "가격 없음", @@ -12152,12 +12163,13 @@ } ], "b93dc3faeb8d9b2e": "{label}({shortcut})", + "1eee306da7eb0382": "저장할 수 없습니다. 다시 시도하세요.", "71efdf870da332e8": "{start}~{end}", + "67070d5478b6aeec": "한도 새로 고침", + "93a3e5869ba37c86": "사용량 새로 고침", "77100b4211d5cf8c": "사용량 이동 경로", "2f96360836544ae6": "사용량 기간", "9e5383009cd3f93b": "사용량 지표", - "67070d5478b6aeec": "한도 새로 고침", - "93a3e5869ba37c86": "사용량 새로 고침", "5dc5cdee2153cd8d": "한도를 보려면 환경을 연결하세요.", "a9b664b4dc630ffa": "사용량을 보려면 환경을 연결하세요.", "d2d071e45a2d6b89": "한도를 보려면 환경을 선택하세요.", @@ -12278,7 +12290,6 @@ "757c752842c88658": "가격에는 음수가 아닌 숫자를 사용하세요.", "a308e844f2e82778": "{target}에서 모델 매핑이 순환을 이룰 수 없습니다.", "b6be43c36bab124c": "모델을 매핑하려면 서버를 업데이트하세요", - "1eee306da7eb0382": "저장할 수 없습니다. 다시 시도하세요.", "c8fa587fc0be1938": "한도", "14955bff9f2f90cd": "지난 24시간", "2cddd6095abc734a": "7일", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index f8450e8032e5..6180b44f43b8 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -12176,9 +12176,20 @@ "4df3ff1be768a7ab": "{name}: {remaining}% restante", "7aaaff1c6484f25c": "Segmento", "8bcab2ef61de6518": "Limite de $0", + "90505e3bfadccee0": "Mover {label} para cima", + "33234f46946de376": "Mover {label} para baixo", + "68e588f6255f796f": "Ocultar {label}", + "050ab24d4c4f1e41": "Layout dos limites", + "c3185b3b04cd5b5e": "{count, plural, one {{count} oculto} other {{count} ocultos}}", + "3fa021245e4ad1d1": "{count, plural, one {Layout dos limites, {count} oculto} other {Layout dos limites, {count} ocultos}}", + "afc7569ca717f8cc": "Ocultos", + "191e6f4ba689bb5d": "Redefinir layout", + "bbd35f7979a24a2e": "{label} foi movido para a posição {position} de {total}.", + "f3f87fb82052fd8e": "Oculto: {label}", "a16b48709357a5a7": "Gerenciar uso", "a00e74aaa421c524": "restante", "8bd6f07136317c8f": "Nenhum provedor nos ambientes selecionados informa limites de assinatura.", + "aa9a8302e7c6c99f": "Todos os limites desta visualização estão ocultos.", "87f5d0c61b335f38": "Veja o uso no ChatGPT com sua conta conectada.", "5b4c71b36b979e80": "Custo", "fce17caaa0d1a45b": "Sem preço", @@ -12205,12 +12216,13 @@ } ], "b93dc3faeb8d9b2e": "{label} ({shortcut})", + "1eee306da7eb0382": "Não foi possível salvar. Tente novamente.", "71efdf870da332e8": "{start} a {end}", + "67070d5478b6aeec": "Atualizar limites", + "93a3e5869ba37c86": "Atualizar uso", "77100b4211d5cf8c": "Trilha de navegação do uso", "2f96360836544ae6": "Período de uso", "9e5383009cd3f93b": "Métrica de uso", - "67070d5478b6aeec": "Atualizar limites", - "93a3e5869ba37c86": "Atualizar uso", "5dc5cdee2153cd8d": "Conecte um ambiente para ver os limites.", "a9b664b4dc630ffa": "Conecte um ambiente para ver o uso.", "d2d071e45a2d6b89": "Selecione um ambiente para ver os limites.", @@ -12331,7 +12343,6 @@ "757c752842c88658": "Use números não negativos para os preços.", "a308e844f2e82778": "Os mapeamentos de modelos não podem formar um ciclo em {target}.", "b6be43c36bab124c": "Atualize o servidor para mapear modelos", - "1eee306da7eb0382": "Não foi possível salvar. Tente novamente.", "c8fa587fc0be1938": "Limites", "14955bff9f2f90cd": "Últimas 24 h", "2cddd6095abc734a": "7 dias", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 75b7db757cf0..eb30ad327b68 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -12177,9 +12177,20 @@ "4df3ff1be768a7ab": "{name}: осталось {remaining}%", "7aaaff1c6484f25c": "Сегмент", "8bcab2ef61de6518": "Лимит $0", + "90505e3bfadccee0": "Переместить {label} вверх", + "33234f46946de376": "Переместить {label} вниз", + "68e588f6255f796f": "Скрыть {label}", + "050ab24d4c4f1e41": "Отображение лимитов", + "c3185b3b04cd5b5e": "{count, plural, one {Скрыт {count}} few {Скрыто {count}} many {Скрыто {count}} other {Скрыто {count}}}", + "3fa021245e4ad1d1": "{count, plural, one {Отображение лимитов, скрыт {count}} few {Отображение лимитов, скрыто {count}} many {Отображение лимитов, скрыто {count}} other {Отображение лимитов, скрыто {count}}}", + "afc7569ca717f8cc": "Скрытые", + "191e6f4ba689bb5d": "Сбросить настройки отображения", + "bbd35f7979a24a2e": "{label} перемещено на позицию {position} из {total}.", + "f3f87fb82052fd8e": "Скрыто: {label}", "a16b48709357a5a7": "Управление использованием", "a00e74aaa421c524": "осталось", "8bd6f07136317c8f": "Ни один провайдер в выбранных окружениях не сообщает лимиты подписки.", + "aa9a8302e7c6c99f": "Все лимиты в этом представлении скрыты.", "87f5d0c61b335f38": "Смотрите использование в ChatGPT через подключённый аккаунт.", "5b4c71b36b979e80": "Стоимость", "fce17caaa0d1a45b": "Без цены", @@ -12206,12 +12217,13 @@ } ], "b93dc3faeb8d9b2e": "{label} ({shortcut})", + "1eee306da7eb0382": "Не удалось сохранить. Попробуйте ещё раз.", "71efdf870da332e8": "С {start} по {end}", + "67070d5478b6aeec": "Обновить лимиты", + "93a3e5869ba37c86": "Обновить использование", "77100b4211d5cf8c": "Навигация по использованию", "2f96360836544ae6": "Период использования", "9e5383009cd3f93b": "Метрика использования", - "67070d5478b6aeec": "Обновить лимиты", - "93a3e5869ba37c86": "Обновить использование", "5dc5cdee2153cd8d": "Подключите окружение, чтобы увидеть лимиты.", "a9b664b4dc630ffa": "Подключите окружение, чтобы увидеть использование.", "d2d071e45a2d6b89": "Выберите окружение, чтобы увидеть лимиты.", @@ -12332,7 +12344,6 @@ "757c752842c88658": "Цены должны быть неотрицательными числами.", "a308e844f2e82778": "Сопоставления моделей не могут образовывать цикл в {target}.", "b6be43c36bab124c": "Обновите сервер, чтобы сопоставлять модели", - "1eee306da7eb0382": "Не удалось сохранить. Попробуйте ещё раз.", "c8fa587fc0be1938": "Лимиты", "14955bff9f2f90cd": "За 24 ч", "2cddd6095abc734a": "7 дней", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 6a3525acc863..092a1b252091 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -12184,9 +12184,20 @@ "4df3ff1be768a7ab": "{name}: {remaining} % kvar", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "Tak på 0 $", + "90505e3bfadccee0": "Flytta upp {label}", + "33234f46946de376": "Flytta ned {label}", + "68e588f6255f796f": "Dölj {label}", + "050ab24d4c4f1e41": "Gränsernas layout", + "c3185b3b04cd5b5e": "{count, plural, one {{count} dold} other {{count} dolda}}", + "3fa021245e4ad1d1": "{count, plural, one {Gränsernas layout, {count} dold} other {Gränsernas layout, {count} dolda}}", + "afc7569ca717f8cc": "Dolda", + "191e6f4ba689bb5d": "Återställ layout", + "bbd35f7979a24a2e": "{label} flyttades till position {position} av {total}.", + "f3f87fb82052fd8e": "{label} dold", "a16b48709357a5a7": "Hantera användning", "a00e74aaa421c524": "kvar", "8bd6f07136317c8f": "Ingen leverantör i de valda miljöerna rapporterar abonnemangsgränser.", + "aa9a8302e7c6c99f": "Alla gränser i den här vyn är dolda.", "87f5d0c61b335f38": "Visa användning i ChatGPT med ditt anslutna konto.", "5b4c71b36b979e80": "Kostnad", "fce17caaa0d1a45b": "Utan pris", @@ -12213,12 +12224,13 @@ } ], "b93dc3faeb8d9b2e": "{label} ({shortcut})", + "1eee306da7eb0382": "Kunde inte spara. Försök igen.", "71efdf870da332e8": "{start} till {end}", + "67070d5478b6aeec": "Uppdatera gränser", + "93a3e5869ba37c86": "Uppdatera användning", "77100b4211d5cf8c": "Sökväg i användning", "2f96360836544ae6": "Användningsperiod", "9e5383009cd3f93b": "Användningsmått", - "67070d5478b6aeec": "Uppdatera gränser", - "93a3e5869ba37c86": "Uppdatera användning", "5dc5cdee2153cd8d": "Anslut en miljö för att se gränser.", "a9b664b4dc630ffa": "Anslut en miljö för att se användning.", "d2d071e45a2d6b89": "Välj en miljö för att se gränser.", @@ -12339,7 +12351,6 @@ "757c752842c88658": "Använd icke-negativa tal för priser.", "a308e844f2e82778": "Modellmappningar får inte bilda en cykel på {target}.", "b6be43c36bab124c": "Uppdatera servern för att mappa modeller", - "1eee306da7eb0382": "Kunde inte spara. Försök igen.", "c8fa587fc0be1938": "Gränser", "14955bff9f2f90cd": "Senaste 24 h", "2cddd6095abc734a": "7 dagar", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index af1ca50a064b..e635c1537bf4 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -12202,9 +12202,20 @@ "4df3ff1be768a7ab": "{name}:剩余 {remaining}%", "7aaaff1c6484f25c": "分段", "8bcab2ef61de6518": "上限 $0", + "90505e3bfadccee0": "上移 {label}", + "33234f46946de376": "下移 {label}", + "68e588f6255f796f": "隐藏 {label}", + "050ab24d4c4f1e41": "限额布局", + "c3185b3b04cd5b5e": "{count, plural, other {已隐藏 {count} 项}}", + "3fa021245e4ad1d1": "{count, plural, other {限额布局,已隐藏 {count} 项}}", + "afc7569ca717f8cc": "已隐藏", + "191e6f4ba689bb5d": "重置布局", + "bbd35f7979a24a2e": "已将 {label} 移到第 {position} 位,共 {total} 项。", + "f3f87fb82052fd8e": "已隐藏 {label}", "a16b48709357a5a7": "管理用量", "a00e74aaa421c524": "剩余", "8bd6f07136317c8f": "选中的环境上没有提供方报告订阅限制。", + "aa9a8302e7c6c99f": "此视图中的所有限额均已隐藏。", "87f5d0c61b335f38": "用已连接的账户在 ChatGPT 中查看用量。", "5b4c71b36b979e80": "费用", "fce17caaa0d1a45b": "未定价", @@ -12231,12 +12242,13 @@ } ], "b93dc3faeb8d9b2e": "{label}({shortcut})", + "1eee306da7eb0382": "无法保存,请重试。", "71efdf870da332e8": "{start} 至 {end}", + "67070d5478b6aeec": "刷新限制", + "93a3e5869ba37c86": "刷新用量", "77100b4211d5cf8c": "用量导航", "2f96360836544ae6": "用量时间范围", "9e5383009cd3f93b": "用量指标", - "67070d5478b6aeec": "刷新限制", - "93a3e5869ba37c86": "刷新用量", "5dc5cdee2153cd8d": "连接一个环境即可查看用量限制。", "a9b664b4dc630ffa": "连接一个环境即可查看用量。", "d2d071e45a2d6b89": "选择一个环境即可查看限制。", @@ -12357,7 +12369,6 @@ "757c752842c88658": "价格请使用非负数。", "a308e844f2e82778": "{target} 上的模型映射不能形成循环。", "b6be43c36bab124c": "更新服务器后才能映射模型", - "1eee306da7eb0382": "无法保存,请重试。", "c8fa587fc0be1938": "限制", "14955bff9f2f90cd": "过去 24 小时", "2cddd6095abc734a": "7 天", diff --git a/docs/user/usage.md b/docs/user/usage.md index 43f4c94a1932..81f264e757c2 100644 --- a/docs/user/usage.md +++ b/docs/user/usage.md @@ -135,6 +135,12 @@ the bar show each account's quota, countdown, and credits. Tap a row to open its The same account signed in on more than one environment, or reported by a hub as well, counts once. Filter with the environment dropdown to see what a single machine has. +On web and desktop, hover a provider or card in **Usage → Limits**, or tab to it, to move it up or +down or to hide a card. On a touch screen, use the **⋯** button on the provider or card instead. +After hiding a card, choose **Undo** to bring it back. The layout button next to refresh shows how +many cards in the current view are hidden; open it to show one again or choose **Reset layout** +to restore the default order and show every card. Your layout is saved on this client. + When a Claude or Codex account has no overall weekly quota left, its pooled session contribution shows 0% left. The next refill depends on both reset times: an exhausted session must also reset, and a partly spent session may only regain its unused portion when the week resets. Missing or diff --git a/packages/shared/src/usageLimits.test.ts b/packages/shared/src/usageLimits.test.ts index 0019c74e1d5c..9daf8eb3a5c8 100644 --- a/packages/shared/src/usageLimits.test.ts +++ b/packages/shared/src/usageLimits.test.ts @@ -1365,6 +1365,21 @@ describe("pooled account columns", () => { expect(pool!.windows[1]!.resets.map((reset) => reset.restoresPercent)).toEqual([40, 20]); }); + it("keeps a Codex monthly allowance distinct from the individual credit window", () => { + const monthly = { ...weekly, id: "primary", kind: "monthly", label: "Monthly" } as const; + const individual = { ...monthly, id: "individual", label: "Monthly credit limit" }; + const driver = ProviderDriverKind.make("codex"); + const monthAccount = { ...account("month", [monthly]), driver }; + const creditAccount = { ...account("credit", [individual]), driver }; + const [both] = collectLimitPools([monthAccount, creditAccount], now); + const [creditOnly] = collectLimitPools([creditAccount], now); + expect(both?.windows.map((row) => [row.id, row.members.length])).toEqual([ + ["monthly", 1], + ["monthly:individual", 1], + ]); + expect(creditOnly?.windows.map((row) => row.id)).toEqual(["monthly:individual"]); + }); + it("falls back to weekly resets when no account reports a session", () => { const [pool] = collectLimitPools( [ diff --git a/packages/shared/src/usageLimits.ts b/packages/shared/src/usageLimits.ts index 711f3637d0a9..fe91f71b14bc 100644 --- a/packages/shared/src/usageLimits.ts +++ b/packages/shared/src/usageLimits.ts @@ -617,9 +617,11 @@ function planCapacity(account: LimitAccount, kind: ServerProviderUsageWindow["ki return undefined; } -// Codex ids name slots, so pool by kind; other drivers' ids identify distinct allowances. +// Codex's time limits use slot ids. Its individual credit has a distinct allowance. function poolKey(driver: ServerProvider["driver"], window: ServerProviderUsageWindow): string { - return driver === "codex" ? window.kind : `${window.kind}:${window.id}`; + return driver === "codex" && window.id !== "individual" + ? window.kind + : `${window.kind}:${window.id}`; } function poolMember(account: LimitAccount, reported: ServerProviderUsageWindow, now: number) {