diff --git a/apps/web/src/components/usage/UsageLimitLayoutControls.tsx b/apps/web/src/components/usage/UsageLimitLayoutControls.tsx new file mode 100644 index 0000000000000..ad07ef2e5bac5 --- /dev/null +++ b/apps/web/src/components/usage/UsageLimitLayoutControls.tsx @@ -0,0 +1,148 @@ +import { + DndContext, + KeyboardSensor, + PointerSensor, + closestCenter, + pointerWithin, + type CollisionDetection, + type KeyboardCoordinateGetter, + useSensor, + useSensors, +} from "@dnd-kit/core"; +import { restrictToVerticalAxis } from "@dnd-kit/modifiers"; +import { SortableContext, type useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable"; +import { useGT } from "gt-react"; +import { GripVerticalIcon } from "lucide-react"; +import type { ReactNode } from "react"; + +import { cn } from "../../lib/utils"; +import { Button } from "../ui/button"; + +const limitCollisionDetection: CollisionDetection = (args) => { + const collisions = pointerWithin(args); + return collisions.length > 0 ? collisions : closestCenter(args); +}; + +export function UsageLimitSortableList({ + items, + onReorder, + children, +}: { + readonly items: string[]; + readonly onReorder: (active: string, over: string) => void; + readonly children: ReactNode; +}) { + const gt = useGT(); + const position = (id: string | number) => items.indexOf(String(id)) + 1; + const keyboardCoordinates: KeyboardCoordinateGetter = ( + event, + { context, currentCoordinates }, + ) => { + if (event.code !== "ArrowUp" && event.code !== "ArrowDown") return; + event.preventDefault(); + const index = items.indexOf(String(context.over?.id ?? context.active?.id)); + const target = items[index + (event.code === "ArrowDown" ? 1 : -1)]; + const rect = target === undefined ? undefined : context.droppableRects.get(target); + if (!rect || !context.collisionRect) return; + return { + ...currentCoordinates, + y: + currentCoordinates.y + + rect.top + + rect.height / 2 - + (context.collisionRect.top + context.collisionRect.height / 2), + }; + }; + const sensors = useSensors( + useSensor(PointerSensor, { activationConstraint: { distance: 4 } }), + useSensor(KeyboardSensor, { coordinateGetter: keyboardCoordinates }), + ); + return ( + + gt("Picked up item at position {position}.", { position: position(active.id) }), + onDragOver: ({ over }) => + over ? gt("Moved to position {position}.", { position: position(over.id) }) : undefined, + onDragEnd: ({ over }) => + over + ? gt("Dropped at position {position}.", { position: position(over.id) }) + : gt("Reorder canceled."), + onDragCancel: () => gt("Reorder canceled."), + }, + }} + onDragEnd={({ active, over }) => { + if (over && active.id !== over.id) onReorder(String(active.id), String(over.id)); + }} + > + + {children} + + + ); +} + +export function UsageLimitLayoutControls({ + label, + hidden, + attributes, + listeners, + handleRef, + isDragging, + pinned = false, + onToggleVisibility, + children, +}: { + readonly label: string; + readonly hidden: boolean; + readonly attributes: ReturnType["attributes"]; + readonly listeners: ReturnType["listeners"]; + readonly handleRef: ReturnType["setActivatorNodeRef"]; + readonly isDragging: boolean; + readonly pinned?: boolean; + readonly onToggleVisibility: () => void; + readonly children?: ReactNode; +}) { + const gt = useGT(); + const visibilityLabel = hidden ? gt("Show {label}", { label }) : gt("Hide {label}", { label }); + return ( + + ); +} diff --git a/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx b/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx index ab114fbbd6f21..5b0431d307c2e 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx @@ -2,13 +2,19 @@ import { EnvironmentId, ProviderDriverKind, ProviderInstanceId, + UsageLimitSourceId, + type ServerProviderUsageWindow, type ServerProvider, } from "@t3tools/contracts"; import { CHATGPT_USAGE_URL } from "@t3tools/shared/usageLimits"; import { describe, expect, it } from "vite-plus/test"; +import { cdp, commands, page, userEvent } from "vite-plus/test/browser"; + +import "../../index.css"; import { render } from "../../../test/render"; import { UsageLimitsPooled } from "./UsageLimitsPooled"; +import { USAGE_LIMIT_LAYOUT_KEY } from "./usageLimitLayout"; const checkedAt = "2026-10-25T16:00:00.000Z"; @@ -35,7 +41,268 @@ function managedChatGpt(instanceId: string, displayName: string): ServerProvider }; } -describe("UsageLimitsPooled ChatGPT usage card", () => { +function isolatedLayoutStorage() { + const saved = window.localStorage.getItem(USAGE_LIMIT_LAYOUT_KEY); + window.localStorage.removeItem(USAGE_LIMIT_LAYOUT_KEY); + return { + [Symbol.dispose]() { + if (saved === null) window.localStorage.removeItem(USAGE_LIMIT_LAYOUT_KEY); + else window.localStorage.setItem(USAGE_LIMIT_LAYOUT_KEY, saved); + }, + }; +} + +async function dragHandle(source: HTMLElement | SVGElement, target: HTMLElement | SVGElement) { + await userEvent.hover(source.closest(".group\\/limit-row")!); + await userEvent.hover(source); + const from = source.getBoundingClientRect(); + const to = target.getBoundingClientRect(); + const frame = window.frameElement?.getBoundingClientRect(); + const x = from.x + from.width / 2 + (frame?.x ?? 0); + const y = from.y + from.height / 2 + (frame?.y ?? 0); + const endY = to.y + to.height / 2 + (frame?.y ?? 0); + await cdp().send("Input.dispatchMouseEvent", { + type: "mousePressed", + x, + y, + button: "left", + buttons: 1, + clickCount: 1, + }); + try { + await cdp().send("Input.dispatchMouseEvent", { type: "mouseMoved", x, y: y + 8, buttons: 1 }); + await expect.element(source).toHaveAttribute("aria-pressed", "true"); + for (let step = 1; step <= 8; step++) { + await cdp().send("Input.dispatchMouseEvent", { + type: "mouseMoved", + x, + y: y + ((endY - y) * step) / 8, + buttons: 1, + }); + } + } finally { + await cdp().send("Input.dispatchMouseEvent", { + type: "mouseReleased", + x, + y: endY, + button: "left", + buttons: 0, + clickCount: 1, + }); + } +} + +describe("UsageLimitsPooled", () => { + it("arranges limits inline and restores hidden providers without losing collapsed state", async () => { + using _storage = isolatedLayoutStorage(); + await page.viewport(1000, 1000); + const weekly: ServerProviderUsageWindow = { + id: "weekly", + kind: "weekly", + label: "Weekly", + usedPercent: 40, + }; + const presentations = new Map([ + [ + EnvironmentId.make("desk"), + { + entry: { target: { label: "Desk" } }, + serverConfig: { + providers: [], + usageLimitSources: [ + { + id: UsageLimitSourceId.make("test-hub"), + kind: "cliproxy" as const, + label: "Hub", + checkedAt, + accounts: [ + { + id: "codex", + driver: ProviderDriverKind.make("codex"), + usageLimits: { + checkedAt, + windows: [ + weekly, + { ...weekly, id: "session", kind: "session" as const, label: "Session" }, + ], + }, + }, + { + id: "gemini", + driver: ProviderDriverKind.make("antigravity"), + usageLimits: { + checkedAt, + windows: [{ ...weekly, id: "gemini-weekly", label: "Gemini · Weekly" }], + }, + }, + ], + }, + ], + }, + }, + ], + ]); + await using screen = await render( + , + ); + expect(screen.getByRole("button", { name: "Customize limits" }).elements()).toHaveLength(0); + const collapse = screen.getByRole("button", { name: "Collapse Codex limits" }); + const collapseIndicator = collapse.element().parentElement!; + await expect.element(collapseIndicator).toHaveStyle({ opacity: "0" }); + collapse.element().focus(); + await expect.element(collapse).toHaveFocus(); + await expect.element(collapseIndicator).toHaveStyle({ opacity: "1" }); + collapse.element().blur(); + await expect.element(collapseIndicator).toHaveStyle({ opacity: "0" }); + await screen.getByRole("heading", { name: /Codex/ }).hover(); + await expect.element(collapseIndicator).toHaveStyle({ opacity: "1" }); + await screen.getByRole("button", { name: "Collapse Codex limits" }).click(); + await expect.element(screen.getByText("Session", { exact: true })).not.toBeInTheDocument(); + + await screen.getByRole("button", { name: "Expand Codex limits" }).click(); + screen.getByRole("button", { name: "Collapse Codex limits" }).element().blur(); + await commands.resetPointer(); + expect(screen.getByRole("dialog").elements()).toHaveLength(0); + const providerReorder = screen + .getByRole("button", { name: "Reorder Codex", exact: true }) + .element().parentElement!; + const windowReorder = screen + .getByRole("button", { name: "Reorder Codex Weekly", exact: true }) + .element().parentElement!; + await expect.element(providerReorder).toHaveStyle({ opacity: "0" }); + await expect.element(windowReorder).toHaveStyle({ opacity: "0" }); + await screen.getByRole("heading", { name: /Codex/ }).hover(); + await expect.element(providerReorder).toHaveStyle({ opacity: "1" }); + await expect.element(windowReorder).toHaveStyle({ opacity: "0" }); + await screen.getByText("Weekly", { exact: true }).hover(); + await expect.element(windowReorder).toHaveStyle({ opacity: "1" }); + await expect.element(providerReorder).toHaveStyle({ opacity: "0" }); + await commands.resetPointer(); + await expect.element(providerReorder).toHaveStyle({ opacity: "0" }); + await expect.element(screen.getByText("Session", { exact: true })).toBeVisible(); + expect(screen.getByRole("button", { name: /Antigravity Gemini/ }).elements()).toHaveLength(0); + await screen.getByText("Weekly", { exact: true }).hover(); + await screen.getByRole("button", { name: "Hide Codex Weekly", exact: true }).click(); + await expect.element(screen.getByText("Weekly", { exact: true })).not.toBeInTheDocument(); + await expect.element(screen.getByRole("button", { name: "1 item hidden" })).toHaveFocus(); + await screen.getByRole("button", { name: "1 item hidden" }).click(); + await screen.getByRole("button", { name: "Show Codex Weekly", exact: true }).click(); + await expect + .element(screen.getByRole("button", { name: "1 item hidden" })) + .not.toBeInTheDocument(); + await expect + .element(screen.getByRole("button", { name: "Collapse Codex limits" })) + .toHaveFocus(); + await screen.getByRole("heading", { name: /Antigravity/ }).hover(); + await screen.getByRole("button", { name: "Hide Antigravity", exact: true }).click(); + await expect.element(screen.getByText("Gemini · Weekly")).not.toBeInTheDocument(); + await screen.getByRole("button", { name: "1 item hidden" }).click(); + await expect.element(screen.getByText("Gemini · Weekly")).toBeVisible(); + const revealedSegment = screen.getByRole("button", { name: "gemini: 60% left" }); + await revealedSegment.click(); + await expect.element(revealedSegment).toHaveAttribute("aria-expanded", "true"); + await expect + .element(screen.getByRole("dialog").getByText("Left", { exact: true })) + .toBeVisible(); + await screen.getByRole("button", { name: "1 item hidden" }).click(); + await expect.element(revealedSegment).not.toBeInTheDocument(); + await expect.element(screen.getByRole("dialog")).not.toBeInTheDocument(); + await screen.getByRole("button", { name: "1 item hidden" }).click(); + await screen.getByRole("button", { name: "Show Antigravity", exact: true }).click(); + await screen.getByRole("heading", { name: /Antigravity/ }).hover(); + await screen.getByRole("button", { name: "Collapse Antigravity limits" }).click(); + const providerHandle = screen.getByRole("button", { name: "Reorder Codex", exact: true }); + await userEvent.keyboard("{Shift}"); + providerHandle.element().focus(); + await expect.element(providerReorder).toHaveStyle({ opacity: "1" }); + await userEvent.keyboard("[Space]"); + await expect.element(providerHandle).toHaveAttribute("aria-pressed", "true"); + await userEvent.keyboard("[ArrowDown]"); + await userEvent.keyboard("[Space]"); + await expect.element(providerHandle).toHaveFocus(); + await expect.element(providerHandle).not.toHaveAttribute("aria-pressed", "true"); + await expect + .element(screen.getByRole("heading", { level: 2 }).first()) + .toHaveTextContent("Antigravity"); + const weeklyHandle = screen.getByRole("button", { name: "Reorder Codex Weekly", exact: true }); + weeklyHandle.element().focus(); + await userEvent.keyboard("[Space]"); + await userEvent.keyboard("[ArrowUp]"); + await userEvent.keyboard("[Space]"); + await expect.element(weeklyHandle).toHaveFocus(); + const saved = JSON.parse(window.localStorage.getItem(USAGE_LIMIT_LAYOUT_KEY)!); + expect(saved.providerOrder).toEqual(["antigravity", "codex"]); + expect(saved.windowOrder).toEqual([ + JSON.stringify(["codex", "weekly", "weekly"]), + JSON.stringify(["codex", "session", "session"]), + ]); + await userEvent.keyboard("[Space]"); + await userEvent.keyboard("[ArrowDown]"); + await userEvent.keyboard("[Escape]"); + expect(JSON.parse(window.localStorage.getItem(USAGE_LIMIT_LAYOUT_KEY)!)).toEqual(saved); + await screen.getByRole("heading", { name: /Codex/ }).hover(); + await screen.getByRole("button", { name: "Collapse Codex limits" }).click(); + await screen.getByRole("button", { name: "Hide Codex", exact: true }).click(); + await expect.element(screen.getByRole("heading", { name: /Codex/ })).not.toBeInTheDocument(); + + await expect.element(screen.getByRole("button", { name: "1 item hidden" })).toHaveFocus(); + await screen.getByRole("button", { name: "1 item hidden" }).click(); + await screen.getByRole("button", { name: "Show Codex", exact: true }).click(); + await expect + .element(screen.getByRole("button", { name: "1 item hidden" })) + .not.toBeInTheDocument(); + await expect + .element(screen.getByRole("button", { name: "Expand Codex limits" })) + .toHaveAttribute("aria-expanded", "false"); + await screen.rerender( + , + ); + await expect + .element(screen.getByRole("button", { name: "Expand Codex limits" })) + .toHaveAttribute("aria-expanded", "false"); + await screen.getByRole("button", { name: "Expand Codex limits" }).click(); + await expect.element(screen.getByText("Session", { exact: true })).toBeVisible(); + + await screen.getByRole("button", { name: "Reset layout" }).click(); + await expect + .element(screen.getByRole("button", { name: "Collapse Codex limits" })) + .toHaveFocus(); + await expect + .element(screen.getByRole("heading", { level: 2 }).first()) + .toHaveTextContent("Codex"); + await screen.getByRole("heading", { name: /Antigravity/ }).hover(); + await screen.getByRole("button", { name: "Collapse Antigravity limits" }).click(); + await dragHandle( + screen.getByRole("button", { name: "Reorder Codex", exact: true }).element(), + screen.getByRole("button", { name: "Reorder Antigravity", exact: true }).element(), + ); + await expect + .element(screen.getByRole("heading", { level: 2 }).first()) + .toHaveTextContent("Antigravity"); + await dragHandle( + screen.getByRole("button", { name: "Reorder Codex Session", exact: true }).element(), + screen.getByRole("button", { name: "Reorder Codex Weekly", exact: true }).element(), + ); + await commands.resetPointer(); + await expect + .element( + screen.getByRole("button", { name: "Reorder Codex Session", exact: true }).element() + .parentElement!, + ) + .toHaveStyle({ opacity: "0" }); + expect(JSON.parse(window.localStorage.getItem(USAGE_LIMIT_LAYOUT_KEY)!)).toMatchObject({ + providerOrder: ["antigravity", "codex"], + windowOrder: [ + JSON.stringify(["codex", "weekly", "weekly"]), + JSON.stringify(["codex", "session", "session"]), + ], + }); + }); + it("names the managed connections it covers", async () => { const presentations = new Map([ [ diff --git a/apps/web/src/components/usage/UsageLimitsPooled.tsx b/apps/web/src/components/usage/UsageLimitsPooled.tsx index 245b3021e4cd2..62c214b6bcb90 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.tsx @@ -13,11 +13,12 @@ import { } from "@t3tools/shared/usageLimits"; import { T, useGT, useMessages } from "gt-react"; import type { Popover as PopoverPrimitive } from "@base-ui/react/popover"; +import { useSortable } from "@dnd-kit/sortable"; +import { CSS } from "@dnd-kit/utilities"; import { normalizeProviderAccentColor } from "@t3tools/client-runtime/state/provider-instance-display"; -import { AlertTriangleIcon, ExternalLinkIcon, TicketIcon } from "lucide-react"; +import { AlertTriangleIcon, ChevronRightIcon, ExternalLinkIcon, TicketIcon } from "lucide-react"; import { createContext, - Fragment, type ReactNode, type RefObject, use, @@ -27,6 +28,7 @@ import { } from "react"; import { ensureLocalApi } from "../../localApi"; +import { useLocalStorage } from "../../hooks/useLocalStorage"; import { usePrimarySettings } from "../../hooks/useSettings"; import { cn } from "../../lib/utils"; import { formatUpcomingTimestamp } from "../../timestampFormat"; @@ -38,6 +40,16 @@ import { OpenAI } from "../Icons"; import { Alert, AlertTitle } from "../ui/alert"; import { Popover, PopoverCreateHandle, PopoverPopup, PopoverTrigger } from "../ui/popover"; import { PaceIcon, ResetCreditDialog, barColor, usePaceMark, useResetCredit } from "./UsageLimits"; +import { UsageLimitLayoutControls, UsageLimitSortableList } from "./UsageLimitLayoutControls"; +import { + DEFAULT_LIMIT_LAYOUT, + limitWindowKey, + moveLimitItem, + orderLimitItems, + USAGE_LIMIT_LAYOUT_KEY, + UsageLimitLayoutSchema, + type UsageLimitLayout, +} from "./usageLimitLayout"; import { collectExternalUsageLinks, collectLimitNotices, @@ -251,24 +263,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 @@ -392,150 +402,74 @@ function SegmentTriggers({ .filter(Boolean) .join(", "); return ( - <> - + } + > +
+ {/* Clipped inside the rounded clip so the bar's own corners keep their antialiasing. */} +
+
- } - > -
- {/* Clipped inside the rounded clip so the bar's own corners keep their antialiasing. */} -
+ {remaining < 100 && reset && refillPercent > 0 ? (
- {remaining < 100 && reset && refillPercent > 0 ? ( -
- ) : null} -
-
- {paceMark ? ( - - ) : null} - - {index} - -
- {showAccountName ? ( - ) : null} - {/* A single-account bar repeats the headline percentage. */} - {showAccountName ? ( - - {remaining}% - - ) : null} - {resetsIn || credits ? ( - - {refillIn ?? ""} - {credits ? ( - <> - {resetsIn ? ( - - · - - ) : null} - - - {credits} - - - ) : null} - - ) : null}
- - - - ); -} - -function LegendRow({ - payload, - color, - now, - index, -}: { - readonly payload: SegmentPayload; - readonly color: string; - readonly now: number; - readonly index: number; -}) { - const popover = use(SegmentPopoverContext) ?? undefined; - const { account, window } = payload; - const remaining = remainingPercent(window); - const m = useMessages(); - const resetsIn = formatResetsIn(window, now, m, "refill"); - const credits = account.limits.resetCredits?.availableCount ?? 0; - const gt = useGT(); - return ( - } - className="min-w-0 @2xl/pool:hidden" - > - +
+ {paceMark ? ( - {`${gt("Segment")} `} - {index} - - - {remaining}% - - {resetsIn ?? ""} - {credits ? ( - <> - {resetsIn ? · : null} - - - {credits} - - - {gt( - "{count, plural, one {{count} reset credit banked} other {{count} reset credits banked}}", - { count: credits }, - )} - - + ) : null} +
+ {showAccountName ? ( + ) : null} - + {/* A single-account bar repeats the headline percentage. */} + {showAccountName ? ( + {remaining}% + ) : null} + {resetsIn || credits ? ( + + {refillIn ?? ""} + {credits ? ( + <> + {resetsIn ? ( + + · + + ) : null} + + + {credits} + + + ) : null} + + ) : null} +
); } @@ -552,7 +486,7 @@ function PoolBar({ const restores = new Map(pool.resets.map((reset) => [reset.member.account.key, reset])); const gt = useGT(); return ( -
+
- + {gt("$0 cap")}
) : null, @@ -590,22 +521,77 @@ function PoolBar({ } function PoolWindowCard({ + id, pool, color, now, label, description, + controlLabel, + arrangeable, + onToggleVisibility, + hidden, }: { readonly pool: LimitPoolWindow; readonly color: string; readonly now: number; readonly label?: string | null | undefined; readonly description?: string | undefined; + readonly id: string; + readonly controlLabel: string; + readonly arrangeable: boolean; + readonly onToggleVisibility: () => void; + readonly hidden: boolean; }) { + const { + attributes, + listeners, + setNodeRef, + setActivatorNodeRef, + transform, + transition, + isDragging, + } = useSortable({ id }); const nextRefill = pool.resets.find((reset) => reset.restoresPercent > 0); + const style = { transform: CSS.Translate.toString(transform), transition }; + const controls = ( +