Skip to content

Open source CapCut alternative.

TypeScript

feat(site): add a usage tab with per-product history, pagination, and per-call token detail

David Le2cbfe57c0f20
diff --git a/site/src/app/api/billing/usage/route.ts b/site/src/app/api/billing/usage/route.ts
index 7f445295..4eb62914 100644
--- a/site/src/app/api/billing/usage/route.ts
+++ b/site/src/app/api/billing/usage/route.ts
@@ -1,6 +1,9 @@
import { NextResponse } from "next/server";
-import { inferenceUsageRoutes } from "@/lib/credits/inference";
+import { Prisma } from "@/generated/prisma/client";
+
+import { creditMicrosToString } from "@/lib/credits/amounts";
+import { readInferenceUsageBreakdown } from "@/lib/credits/inference";
import { visionCallGrantRemaining } from "@/lib/credits/vision-grants";
import {
donkeySessionUserId,
@@ -11,37 +14,71 @@ import { prisma } from "@/lib/prisma";
export const dynamic = "force-dynamic";
-// Current-period Vision API call usage vs quota, plus recent API calls, for the
-// settings UI. Reads the authoritative per-period counter on the subscription;
-// the recent list is independent so it runs in parallel.
+// Up to 5 pages of 25 in the usage tab — fetched per product so a busy product
+// can't starve the other tab out of the recent window.
+const recentPerProduct = 125;
+
+const recentSelect = {
+ billingStatus: true,
+ createdAt: true,
+ creditCostMicros: true,
+ errorCode: true,
+ model: true,
+ normalizedUsage: true,
+ requestKind: true,
+ status: true,
+} satisfies Prisma.InferenceUsageEventSelect;
+
+type RecentEvent = Prisma.InferenceUsageEventGetPayload<{
+ select: typeof recentSelect;
+}>;
+
+function toRecentCall(event: RecentEvent, product: "app" | "vision") {
+ return {
+ billingStatus: event.billingStatus,
+ // Credits are dollar-denominated (1 credit = $1), so this string is USD.
+ costCredits: creditMicrosToString(event.creditCostMicros),
+ createdAt: event.createdAt.toISOString(),
+ errorCode: event.errorCode,
+ model: event.model,
+ product,
+ requestKind: event.requestKind,
+ status: event.status,
+ // Per-call token breakdown — what actually drove the cost. Large input =
+ // long question/context; large output = long answer.
+ usage: readInferenceUsageBreakdown(event.normalizedUsage),
+ };
+}
+
+// Current-period Vision API call usage vs quota, plus recent calls, for the
+// settings UI. "included" billingStatus is the third-party Vision API (API-key)
+// product; everything else is app usage billed to the user's credits — including
+// the app's own vision_parse calls on the same route. Fetching the two products
+// separately keeps each tab's history independent.
export const GET = withDonkeyAuth(async (request) => {
const userId = donkeySessionUserId(request);
if (!userId) {
return unauthorizedResponse();
}
- const [subscription, recent, extraRemaining] = await Promise.all([
- prisma.visionApiSubscription.findUnique({ where: { userId } }),
- prisma.inferenceUsageEvent.findMany({
- orderBy: { createdAt: "desc" },
- select: {
- createdAt: true,
- model: true,
- requestKind: true,
- status: true,
- },
- take: 20,
- // billingStatus "included" = the API-key path, so this list never mixes
- // in the user's Mac-app (credit-billed) vision calls.
- where: {
- billingStatus: "included",
- route: inferenceUsageRoutes.vision,
- userId,
- },
- }),
- // One-time vision-call grants (signup bonus, top-ups) on top of any plan.
- visionCallGrantRemaining(userId),
- ]);
+ const [subscription, appRecent, visionRecent, extraRemaining] =
+ await Promise.all([
+ prisma.visionApiSubscription.findUnique({ where: { userId } }),
+ prisma.inferenceUsageEvent.findMany({
+ orderBy: { createdAt: "desc" },
+ select: recentSelect,
+ take: recentPerProduct,
+ where: { billingStatus: { not: "included" }, userId },
+ }),
+ prisma.inferenceUsageEvent.findMany({
+ orderBy: { createdAt: "desc" },
+ select: recentSelect,
+ take: recentPerProduct,
+ where: { billingStatus: "included", userId },
+ }),
+ // One-time vision-call grants (signup bonus, top-ups) on top of any plan.
+ visionCallGrantRemaining(userId),
+ ]);
const limit = subscription?.monthlyCallQuota ?? 0;
const used = subscription?.periodCallCount ?? 0;
@@ -52,12 +89,10 @@ export const GET = withDonkeyAuth(async (request) => {
limit,
periodEnd: subscription?.currentPeriodEnd?.toISOString() ?? null,
periodStart: subscription?.currentPeriodStart?.toISOString() ?? null,
- recent: recent.map((event) => ({
- createdAt: event.createdAt.toISOString(),
- model: event.model,
- requestKind: event.requestKind,
- status: event.status,
- })),
+ recent: [
+ ...appRecent.map((event) => toRecentCall(event, "app")),
+ ...visionRecent.map((event) => toRecentCall(event, "vision")),
+ ],
remaining: Math.max(0, limit - used),
used,
});
diff --git a/site/src/app/app/settings/SettingsShell.tsx b/site/src/app/app/settings/SettingsShell.tsx
index f867a8e4..91e0bd45 100644
--- a/site/src/app/app/settings/SettingsShell.tsx
+++ b/site/src/app/app/settings/SettingsShell.tsx
@@ -10,6 +10,7 @@ import { Skeleton } from "@/components/ui/skeleton";
const navItems = [
{ href: "/app/settings", label: "Overview" },
+ { href: "/app/settings/usage", label: "Usage" },
{ href: "/app/settings/api-keys", label: "API keys" },
];
diff --git a/site/src/app/app/settings/_components/UsageCard.tsx b/site/src/app/app/settings/_components/UsageCard.tsx
index feb2dd5e..1498d81f 100644
--- a/site/src/app/app/settings/_components/UsageCard.tsx
+++ b/site/src/app/app/settings/_components/UsageCard.tsx
@@ -1,33 +1,37 @@
"use client";
-import { useUsage } from "@/queries/billing";
-import { Badge } from "@/components/ui/badge";
-import {
- Card,
- CardContent,
- CardDescription,
- CardHeader,
- CardTitle,
-} from "@/components/ui/card";
+import { useProSubscription, useUsage } from "@/queries/billing";
+import { Card, CardContent } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import {
Table,
TableBody,
TableCell,
- TableHead,
- TableHeader,
TableRow,
} from "@/components/ui/table";
+import { formatUsd } from "@/lib/credits/format-usd";
+
+// One labeled usage line (product on the left, status/amount on the right).
+function UsageRow({ label, value }: { label: string; value: string }) {
+ return (
+ <TableRow>
+ <TableCell className="font-medium text-foreground">{label}</TableCell>
+ <TableCell className="text-right text-muted-foreground">
+ {value}
+ </TableCell>
+ </TableRow>
+ );
+}
export function UsageCard() {
const usage = useUsage();
+ const pro = useProSubscription();
+ // Only gate on the Vision usage query; the Pro row degrades on its own so a
+ // slow or failing Pro request never blocks the Vision summary from rendering.
if (usage.isLoading) {
return (
<Card>
- <CardHeader>
- <Skeleton className="h-6 w-32" />
- </CardHeader>
<CardContent>
<Skeleton className="h-24 w-full" />
</CardContent>
@@ -43,22 +47,53 @@ export function UsageCard() {
? Math.min(100, Math.round((data.used / limit) * 100))
: 0;
+ // Donkey Pro is the app-inference subscription; its included allowance is spent
+ // separately from the Vision API quota below. Used = allowance − remaining.
+ const proData = pro.data;
+ const proActive = proData?.isActive ?? false;
+ const proAllowance =
+ proData?.monthlyAllowance != null
+ ? Number.parseFloat(proData.monthlyAllowance)
+ : null;
+ const proRemaining = Number.parseFloat(proData?.allowanceRemaining ?? "0");
+ const proUsed =
+ proAllowance != null ? Math.max(0, proAllowance - proRemaining) : null;
+
+ // Don't assert "No Pro plan" while the Pro query is still loading or errored —
+ // that would mislabel an actual Pro user. Only claim it once we have data.
+ const proStatus = pro.isLoading
+ ? "Loading…"
+ : proActive && proUsed != null && proData?.monthlyAllowance != null
+ ? `${formatUsd(String(proUsed))} of ${formatUsd(proData.monthlyAllowance)} used this month`
+ : pro.isError
+ ? "Unavailable"
+ : "No Pro plan — using credits";
+
+ const visionStatus =
+ data && limit > 0
+ ? `${data.used.toLocaleString()} of ${limit.toLocaleString()} calls used · ${data.remaining.toLocaleString()} remaining`
+ : extra > 0
+ ? "No subscription — using your extra calls"
+ : "No active plan — subscribe to start making calls";
+
return (
<Card>
- <CardHeader>
- <CardTitle>Usage this period</CardTitle>
- <CardDescription>
- {data && limit > 0
- ? `${data.used.toLocaleString()} of ${limit.toLocaleString()} calls used · ${data.remaining.toLocaleString()} remaining`
- : extra > 0
- ? "No subscription — using your extra calls."
- : "No active plan — subscribe to start making calls."}
- </CardDescription>
- </CardHeader>
<CardContent className="space-y-4">
+ <Table>
+ <TableBody>
+ <UsageRow label="Donkey Pro (app)" value={proStatus} />
+ <UsageRow label="Vision API" value={visionStatus} />
+ {extra > 0 ? (
+ <UsageRow
+ label="Extra Vision API calls"
+ value={`${extra.toLocaleString()} available`}
+ />
+ ) : null}
+ </TableBody>
+ </Table>
{data && limit > 0 ? (
<div
- aria-label="Quota used"
+ aria-label="Vision API quota used"
className="h-2 w-full overflow-hidden rounded-full bg-muted"
>
<div
@@ -67,57 +102,6 @@ export function UsageCard() {
/>
</div>
) : null}
-
- {extra > 0 ? (
- <div className="flex items-baseline justify-between rounded-md border bg-muted/40 px-3 py-2">
- <span className="text-sm font-medium text-foreground">
- Extra calls
- </span>
- <span className="text-sm text-muted-foreground">
- {extra.toLocaleString()} available
- </span>
- </div>
- ) : null}
-
- <div>
- <h3 className="mb-2 text-sm font-medium">Recent calls</h3>
- {data && data.recent.length > 0 ? (
- <Table>
- <TableHeader>
- <TableRow>
- <TableHead>When</TableHead>
- <TableHead>Kind</TableHead>
- <TableHead>Model</TableHead>
- <TableHead>Status</TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {data.recent.map((event, index) => (
- <TableRow key={`${event.createdAt}-${index}`}>
- <TableCell>
- {new Date(event.createdAt).toLocaleString()}
- </TableCell>
- <TableCell>{event.requestKind}</TableCell>
- <TableCell>{event.model}</TableCell>
- <TableCell>
- <Badge
- variant={
- event.status === "succeeded"
- ? "secondary"
- : "destructive"
- }
- >
- {event.status}
- </Badge>
- </TableCell>
- </TableRow>
- ))}
- </TableBody>
- </Table>
- ) : (
- <p className="text-sm text-muted-foreground">No calls yet.</p>
- )}
- </div>
</CardContent>
</Card>
);
diff --git a/site/src/app/app/settings/_components/UsageHistoryCard.tsx b/site/src/app/app/settings/_components/UsageHistoryCard.tsx
new file mode 100644
index 00000000..2b3d1889
--- /dev/null
+++ b/site/src/app/app/settings/_components/UsageHistoryCard.tsx
@@ -0,0 +1,341 @@
+"use client";
+
+import { Fragment, useRef, useState, type KeyboardEvent } from "react";
+
+import { useUsage, type VisionUsage } from "@/queries/billing";
+import { Badge } from "@/components/ui/badge";
+import {
+ Card,
+ CardContent,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { Skeleton } from "@/components/ui/skeleton";
+import { formatUsd } from "@/lib/credits/format-usd";
+import {
+ Pagination,
+ PaginationContent,
+ PaginationItem,
+ PaginationLink,
+ PaginationNext,
+ PaginationPrevious,
+} from "@/components/ui/pagination";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table";
+import { cn } from "@/lib/utils";
+
+type RecentCall = VisionUsage["recent"][number];
+
+// Stable identity for a call so expansion state survives a background refetch
+// (which can reorder/prepend rows) instead of being pinned to an array index.
+function callKey(call: RecentCall): string {
+ return `${call.createdAt}-${call.product}-${call.requestKind}-${call.costCredits}`;
+}
+
+// Cost rounds to cents for most calls, but per-token app calls are often a small
+// fraction of a cent — show enough precision that they aren't all "$0.00".
+function formatCallCost(call: RecentCall): string {
+ if (call.billingStatus === "included") {
+ return "Included";
+ }
+ const value = Number.parseFloat(call.costCredits);
+ if (!Number.isFinite(value) || value <= 0) {
+ return "$0.00";
+ }
+ // ≥1¢ uses the shared formatter so money renders identically across cards.
+ if (value >= 0.01) {
+ return formatUsd(call.costCredits);
+ }
+ // Sub-cent: up to 6 decimal places (micro-dollar precision), trailing 0s cut.
+ return `$${value.toFixed(6).replace(/0+$/, "").replace(/\.$/, "")}`;
+}
+
+function formatTokens(value: number): string {
+ return value.toLocaleString();
+}
+
+function formatDuration(millis: number): string {
+ return millis >= 1000 ? `${(millis / 1000).toFixed(1)}s` : `${millis}ms`;
+}
+
+const tabs = [
+ { key: "app", label: "App" },
+ { key: "vision", label: "Vision API" },
+] as const;
+
+type TabKey = (typeof tabs)[number]["key"];
+
+// Page the table client-side, capped so the control never grows past 5 pages.
+const ROWS_PER_PAGE = 25;
+const MAX_PAGES = 5;
+
+function CallDetail({ call }: { call: RecentCall }) {
+ const { usage } = call;
+ const imageBilled = usage.generationCount > 0;
+ const tokenBilled =
+ usage.inputTokens > 0 || usage.outputTokens > 0 || usage.totalTokens > 0;
+
+ const stats: { label: string; value: string }[] = [];
+ if (imageBilled) {
+ stats.push({
+ label: "Images generated",
+ value: formatTokens(usage.generationCount),
+ });
+ }
+ if (tokenBilled) {
+ stats.push(
+ {
+ label: "Input tokens",
+ value:
+ usage.cachedInputTokens > 0
+ ? `${formatTokens(usage.inputTokens)} (${formatTokens(usage.cachedInputTokens)} cached)`
+ : formatTokens(usage.inputTokens),
+ },
+ { label: "Output tokens", value: formatTokens(usage.outputTokens) },
+ { label: "Total tokens", value: formatTokens(usage.totalTokens) },
+ );
+ }
+ // Only some (audio-priced) calls report a duration; omit it otherwise.
+ if (usage.durationMillis > 0) {
+ stats.push({ label: "Duration", value: formatDuration(usage.durationMillis) });
+ }
+
+ // Explain what drove the cost in terms of how the call is priced.
+ const explanation = imageBilled
+ ? "Image generation is priced per image, not by tokens."
+ : tokenBilled
+ ? "Cost is driven by tokens: a large input means a long question or lots of context, a large output means a long answer."
+ : "No billable usage was recorded for this call.";
+
+ return (
+ <div className="space-y-3 px-2 py-1 text-sm">
+ <p className="text-muted-foreground">{explanation}</p>
+ {stats.length > 0 ? (
+ <dl className="grid grid-cols-2 gap-x-8 gap-y-1 sm:grid-cols-4">
+ {stats.map((stat) => (
+ <div key={stat.label}>
+ <dt className="text-xs text-muted-foreground">{stat.label}</dt>
+ <dd className="font-medium tabular-nums">{stat.value}</dd>
+ </div>
+ ))}
+ </dl>
+ ) : null}
+ {call.errorCode ? (
+ <p className="text-destructive">Error: {call.errorCode}</p>
+ ) : null}
+ </div>
+ );
+}
+
+export function UsageHistoryCard() {
+ const usage = useUsage();
+ const [tab, setTab] = useState<TabKey>("app");
+ const [page, setPage] = useState(1);
+ // Keyed by call identity (not row index) so a refetch can't leave the open
+ // detail pinned to whatever row now sits at that index.
+ const [expanded, setExpanded] = useState<string | null>(null);
+ // One ref per rendered row so arrow keys can move focus to the sibling row.
+ const rowRefs = useRef<(HTMLTableRowElement | null)[]>([]);
+
+ if (usage.isLoading) {
+ return (
+ <Card>
+ <CardHeader>
+ <Skeleton className="h-6 w-40" />
+ </CardHeader>
+ <CardContent>
+ <Skeleton className="h-64 w-full" />
+ </CardContent>
+ </Card>
+ );
+ }
+
+ const recent = usage.data?.recent ?? [];
+ const rows = recent.filter((call) => call.product === tab);
+
+ const totalPages = Math.min(
+ MAX_PAGES,
+ Math.max(1, Math.ceil(rows.length / ROWS_PER_PAGE)),
+ );
+ // Clamp in case rows shrank (refetch / tab switch) below the current page.
+ const currentPage = Math.min(page, totalPages);
+ const pageStart = (currentPage - 1) * ROWS_PER_PAGE;
+ const pageRows = rows.slice(pageStart, pageStart + ROWS_PER_PAGE);
+
+ const selectTab = (next: TabKey) => {
+ setTab(next);
+ setPage(1);
+ setExpanded(null);
+ };
+
+ const goToPage = (next: number) => {
+ setPage(next);
+ setExpanded(null);
+ };
+
+ const focusRow = (index: number) => {
+ const call = pageRows[index];
+ if (!call) {
+ return;
+ }
+ setExpanded(callKey(call));
+ rowRefs.current[index]?.focus();
+ };
+
+ const onRowKeyDown = (event: KeyboardEvent<HTMLTableRowElement>, index: number) => {
+ if (event.key === "ArrowDown") {
+ event.preventDefault();
+ focusRow(Math.min(index + 1, pageRows.length - 1));
+ } else if (event.key === "ArrowUp") {
+ event.preventDefault();
+ focusRow(Math.max(index - 1, 0));
+ } else if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ const key = callKey(pageRows[index]);
+ setExpanded(expanded === key ? null : key);
+ } else if (event.key === "Escape") {
+ setExpanded(null);
+ }
+ };
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>Usage history</CardTitle>
+ </CardHeader>
+ <CardContent className="space-y-4">
+ <div className="inline-flex rounded-md border p-0.5">
+ {tabs.map((item) => (
+ <button
+ key={item.key}
+ onClick={() => selectTab(item.key)}
+ type="button"
+ className={cn(
+ "rounded px-3 py-1 text-sm font-medium transition-colors",
+ tab === item.key
+ ? "bg-muted text-foreground"
+ : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ {item.label}
+ </button>
+ ))}
+ </div>
+
+ {rows.length > 0 ? (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Date</TableHead>
+ <TableHead>Kind</TableHead>
+ <TableHead>Model</TableHead>
+ <TableHead className="text-right">Cost</TableHead>
+ <TableHead>Status</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {pageRows.map((call, index) => {
+ const key = callKey(call);
+ const isOpen = expanded === key;
+ return (
+ <Fragment key={`${key}-${pageStart + index}`}>
+ <TableRow
+ ref={(el) => {
+ rowRefs.current[index] = el;
+ }}
+ aria-expanded={isOpen}
+ className="cursor-pointer outline-none focus-visible:bg-muted/50"
+ onClick={() => {
+ setExpanded(isOpen ? null : key);
+ rowRefs.current[index]?.focus();
+ }}
+ onKeyDown={(event) => onRowKeyDown(event, index)}
+ tabIndex={0}
+ >
+ <TableCell>
+ {new Date(call.createdAt).toLocaleString()}
+ </TableCell>
+ <TableCell>{call.requestKind}</TableCell>
+ <TableCell>{call.model}</TableCell>
+ <TableCell className="text-right tabular-nums">
+ {formatCallCost(call)}
+ </TableCell>
+ <TableCell>
+ <Badge
+ variant={
+ call.status === "succeeded"
+ ? "secondary"
+ : "destructive"
+ }
+ >
+ {call.status}
+ </Badge>
+ </TableCell>
+ </TableRow>
+ {isOpen ? (
+ <TableRow className="hover:bg-transparent">
+ <TableCell className="bg-muted/30" colSpan={5}>
+ <CallDetail call={call} />
+ </TableCell>
+ </TableRow>
+ ) : null}
+ </Fragment>
+ );
+ })}
+ </TableBody>
+ </Table>
+ ) : (
+ <p className="text-sm text-muted-foreground">
+ No {tab === "app" ? "app" : "Vision API"} calls yet.
+ </p>
+ )}
+
+ {totalPages > 1 ? (
+ <Pagination>
+ <PaginationContent>
+ <PaginationItem>
+ <PaginationPrevious
+ aria-disabled={currentPage <= 1}
+ className={
+ currentPage <= 1 ? "pointer-events-none opacity-50" : undefined
+ }
+ onClick={() => goToPage(Math.max(1, currentPage - 1))}
+ />
+ </PaginationItem>
+ {Array.from({ length: totalPages }, (_, i) => i + 1).map(
+ (pageNumber) => (
+ <PaginationItem key={pageNumber}>
+ <PaginationLink
+ className={pageNumber === currentPage ? "bg-card" : undefined}
+ isActive={pageNumber === currentPage}
+ onClick={() => goToPage(pageNumber)}
+ >
+ {pageNumber}
+ </PaginationLink>
+ </PaginationItem>
+ ),
+ )}
+ <PaginationItem>
+ <PaginationNext
+ aria-disabled={currentPage >= totalPages}
+ className={
+ currentPage >= totalPages
+ ? "pointer-events-none opacity-50"
+ : undefined
+ }
+ onClick={() => goToPage(Math.min(totalPages, currentPage + 1))}
+ />
+ </PaginationItem>
+ </PaginationContent>
+ </Pagination>
+ ) : null}
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/site/src/app/app/settings/page.tsx b/site/src/app/app/settings/page.tsx
index 3ecff364..7925b67f 100644
--- a/site/src/app/app/settings/page.tsx
+++ b/site/src/app/app/settings/page.tsx
@@ -4,7 +4,6 @@ import { CreditsCard } from "@/app/app/settings/_components/CreditsCard";
import { ProCard } from "@/app/app/settings/_components/ProCard";
import { SubscriptionCard } from "@/app/app/settings/_components/SubscriptionCard";
import { SuperuserCreditsCard } from "@/app/app/settings/_components/SuperuserCreditsCard";
-import { UsageCard } from "@/app/app/settings/_components/UsageCard";
export default function SettingsOverviewPage() {
return (
@@ -19,7 +18,6 @@ export default function SettingsOverviewPage() {
<ProCard />
<CreditsCard />
<SubscriptionCard />
- <UsageCard />
<SuperuserCreditsCard />
</div>
);
diff --git a/site/src/app/app/settings/usage/page.tsx b/site/src/app/app/settings/usage/page.tsx
new file mode 100644
index 00000000..c8b24133
--- /dev/null
+++ b/site/src/app/app/settings/usage/page.tsx
@@ -0,0 +1,19 @@
+"use client";
+
+import { UsageCard } from "@/app/app/settings/_components/UsageCard";
+import { UsageHistoryCard } from "@/app/app/settings/_components/UsageHistoryCard";
+
+export default function UsagePage() {
+ return (
+ <div className="space-y-8">
+ <div>
+ <h1 className="text-2xl font-semibold">Usage</h1>
+ <p className="mt-1 text-sm text-muted-foreground">
+ Your recent Donkey app and Vision API calls.
+ </p>
+ </div>
+ <UsageCard />
+ <UsageHistoryCard />
+ </div>
+ );
+}
diff --git a/site/src/components/ui/pagination.tsx b/site/src/components/ui/pagination.tsx
new file mode 100644
index 00000000..eee72fd9
--- /dev/null
+++ b/site/src/components/ui/pagination.tsx
@@ -0,0 +1,123 @@
+import * as React from "react"
+import {
+ ChevronLeftIcon,
+ ChevronRightIcon,
+ MoreHorizontalIcon,
+} from "lucide-react"
+import { type VariantProps } from "class-variance-authority"
+
+import { cn } from "@/lib/utils"
+import { buttonVariants } from "@/components/ui/button"
+
+function Pagination({ className, ...props }: React.ComponentProps<"nav">) {
+ return (
+ <nav
+ role="navigation"
+ aria-label="pagination"
+ data-slot="pagination"
+ className={cn("mx-auto flex w-full justify-center", className)}
+ {...props}
+ />
+ )
+}
+
+function PaginationContent({ className, ...props }: React.ComponentProps<"ul">) {
+ return (
+ <ul
+ data-slot="pagination-content"
+ className={cn("flex flex-row items-center gap-1", className)}
+ {...props}
+ />
+ )
+}
+
+function PaginationItem({ ...props }: React.ComponentProps<"li">) {
+ return <li data-slot="pagination-item" {...props} />
+}
+
+type PaginationLinkProps = {
+ isActive?: boolean
+} & Pick<VariantProps<typeof buttonVariants>, "size"> &
+ React.ComponentProps<"button">
+
+function PaginationLink({
+ className,
+ isActive,
+ size = "icon",
+ ...props
+}: PaginationLinkProps) {
+ return (
+ <button
+ type="button"
+ aria-current={isActive ? "page" : undefined}
+ data-slot="pagination-link"
+ data-active={isActive}
+ className={cn(
+ buttonVariants({ variant: isActive ? "outline" : "ghost", size }),
+ className,
+ )}
+ {...props}
+ />
+ )
+}
+
+function PaginationPrevious({
+ className,
+ ...props
+}: React.ComponentProps<typeof PaginationLink>) {
+ return (
+ <PaginationLink
+ aria-label="Go to previous page"
+ size="default"
+ className={cn("gap-1 px-2.5", className)}
+ {...props}
+ >
+ <ChevronLeftIcon />
+ <span className="hidden sm:block">Previous</span>
+ </PaginationLink>
+ )
+}
+
+function PaginationNext({
+ className,
+ ...props
+}: React.ComponentProps<typeof PaginationLink>) {
+ return (
+ <PaginationLink
+ aria-label="Go to next page"
+ size="default"
+ className={cn("gap-1 px-2.5", className)}
+ {...props}
+ >
+ <span className="hidden sm:block">Next</span>
+ <ChevronRightIcon />
+ </PaginationLink>
+ )
+}
+
+function PaginationEllipsis({
+ className,
+ ...props
+}: React.ComponentProps<"span">) {
+ return (
+ <span
+ aria-hidden
+ data-slot="pagination-ellipsis"
+ className={cn("flex size-8 items-center justify-center", className)}
+ {...props}
+ >
+ <MoreHorizontalIcon className="size-4" />
+ <span className="sr-only">More pages</span>
+ </span>
+ )
+}
+
+export {
+ Pagination,
+ PaginationContent,
+ PaginationLink,
+ PaginationItem,
+ PaginationPrevious,
+ PaginationNext,
+ PaginationEllipsis,
+}
diff --git a/site/src/lib/credits/inference.ts b/site/src/lib/credits/inference.ts
index baa38693..9721c03e 100644
--- a/site/src/lib/credits/inference.ts
+++ b/site/src/lib/credits/inference.ts
@@ -1329,6 +1329,48 @@ function normalizedUsageJson(usage: NormalizedUsage): JsonObject {
};
}
+// The token/usage numbers the usage UI surfaces to explain a call's cost. Read
+// here, right next to normalizedUsageJson which writes them, so the field names
+// stay in sync — renaming a field updates both in one place.
+export type InferenceUsageBreakdown = {
+ inputTokens: number;
+ cachedInputTokens: number;
+ outputTokens: number;
+ totalTokens: number;
+ generationCount: number;
+ durationMillis: number;
+};
+
+export function readInferenceUsageBreakdown(
+ normalizedUsage: unknown,
+): InferenceUsageBreakdown {
+ const source =
+ normalizedUsage &&
+ typeof normalizedUsage === "object" &&
+ !Array.isArray(normalizedUsage)
+ ? (normalizedUsage as Record<string, unknown>)
+ : {};
+ // Values are written as stringified BigInts (see normalizedUsageJson).
+ const num = (key: keyof InferenceUsageBreakdown): number => {
+ const value = source[key];
+ const parsed =
+ typeof value === "string"
+ ? Number(value)
+ : typeof value === "number"
+ ? value
+ : 0;
+ return Number.isFinite(parsed) ? parsed : 0;
+ };
+ return {
+ cachedInputTokens: num("cachedInputTokens"),
+ durationMillis: num("durationMillis"),
+ generationCount: num("generationCount"),
+ inputTokens: num("inputTokens"),
+ outputTokens: num("outputTokens"),
+ totalTokens: num("totalTokens"),
+ };
+}
+
function nestedJsonValue(
value: JsonObject,
objectKey: string,
diff --git a/site/src/queries/billing.ts b/site/src/queries/billing.ts
index bafe252f..c585ce1f 100644
--- a/site/src/queries/billing.ts
+++ b/site/src/queries/billing.ts
@@ -48,11 +48,28 @@ export type VisionUsage = {
extraRemaining: number;
periodStart: string | null;
periodEnd: string | null;
+ // Recent inference calls across products (app + Vision API), newest first.
recent: {
createdAt: string;
- model: string;
+ // "app" = Pro/credit-billed app inference; "vision" = Vision API call.
+ product: "app" | "vision";
requestKind: string;
+ model: string;
status: string;
+ // USD cost charged to credits; "included" calls (Vision quota/grants) are 0.
+ costCredits: string;
+ billingStatus: string;
+ errorCode: string | null;
+ // Token breakdown that explains the cost.
+ usage: {
+ inputTokens: number;
+ cachedInputTokens: number;
+ outputTokens: number;
+ totalTokens: number;
+ // Images produced by asset_generation calls (priced per image).
+ generationCount: number;
+ durationMillis: number;
+ };
}[];
};