Open source CapCut alternative.
TypeScript
Add self-serve dashboard and TanStack query client
David Lee2913ce80060
diff --git a/site/src/app/dashboard/DashboardShell.tsx b/site/src/app/dashboard/DashboardShell.tsxnew file mode 100644index 00000000..4088e0fd--- /dev/null+++ b/site/src/app/dashboard/DashboardShell.tsx@@ -0,0 +1,78 @@+"use client";++import Link from "next/link";+import { usePathname, useRouter } from "next/navigation";+import { useEffect, type ReactNode } from "react";++import { authClient } from "@/lib/auth-client";+import { cn } from "@/lib/utils";+import { Skeleton } from "@/components/ui/skeleton";++const navItems = [+ { href: "/dashboard", label: "Overview" },+ { href: "/dashboard/api-keys", label: "API keys" },+];++// Dashboards are fully client-rendered. We guard on the client session and, if+// signed out, send the user to Google sign-in (API routes also enforce auth).+export function DashboardShell({ children }: { children: ReactNode }) {+ const router = useRouter();+ const pathname = usePathname();+ const { data: session, isPending } = authClient.useSession();++ useEffect(() => {+ if (!isPending && !session) {+ void authClient.signIn.social({+ callbackURL: "/dashboard",+ provider: "google",+ });+ }+ }, [isPending, session]);++ if (isPending || !session) {+ return (+ <div className="mx-auto max-w-5xl px-6 py-16">+ <Skeleton className="h-8 w-48" />+ <Skeleton className="mt-6 h-40 w-full" />+ </div>+ );+ }++ return (+ <div className="min-h-screen bg-background text-foreground">+ <header className="border-b">+ <div className="mx-auto flex max-w-5xl items-center justify-between px-6 py-4">+ <Link className="text-lg font-semibold" href="/dashboard">+ Donkey Vision API+ </Link>+ <nav className="flex items-center gap-1">+ {navItems.map((item) => (+ <Link+ key={item.href}+ href={item.href}+ className={cn(+ "rounded-md px-3 py-1.5 text-sm font-medium transition-colors",+ pathname === item.href+ ? "bg-muted text-foreground"+ : "text-muted-foreground hover:text-foreground",+ )}+ >+ {item.label}+ </Link>+ ))}+ <button+ type="button"+ onClick={() => {+ void authClient.signOut().then(() => router.push("/"));+ }}+ className="ml-2 rounded-md px-3 py-1.5 text-sm font-medium text-muted-foreground hover:text-foreground"+ >+ Sign out+ </button>+ </nav>+ </div>+ </header>+ <main className="mx-auto max-w-5xl px-6 py-10">{children}</main>+ </div>+ );+}diff --git a/site/src/app/dashboard/_components/ApiKeysManager.tsx b/site/src/app/dashboard/_components/ApiKeysManager.tsxnew file mode 100644index 00000000..0de3a1c0--- /dev/null+++ b/site/src/app/dashboard/_components/ApiKeysManager.tsx@@ -0,0 +1,179 @@+"use client";++import { useState } from "react";++import {+ useApiKeys,+ useCreateApiKey,+ useDeleteApiKey,+ type CreatedApiKey,+} from "@/queries/apiKeys";+import { useSubscription } from "@/queries/billing";+import { Button } from "@/components/ui/button";+import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+} from "@/components/ui/card";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { Skeleton } from "@/components/ui/skeleton";+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@/components/ui/table";++export function ApiKeysManager() {+ const subscription = useSubscription();+ const keys = useApiKeys();+ const createKey = useCreateApiKey();+ const deleteKey = useDeleteApiKey();++ const [name, setName] = useState("");+ const [createdKey, setCreatedKey] = useState<CreatedApiKey | null>(null);++ const hasActiveSubscription = subscription.data?.isActive ?? false;++ const handleCreate = () => {+ const trimmed = name.trim();+ if (!trimmed) {+ return;+ }+ createKey.mutate(trimmed, {+ onSuccess: (result) => {+ setCreatedKey(result);+ setName("");+ },+ });+ };++ return (+ <Card>+ <CardHeader>+ <CardTitle>Your keys</CardTitle>+ <CardDescription>+ Secrets are shown only once at creation. Store them securely.+ </CardDescription>+ </CardHeader>+ <CardContent className="space-y-6">+ {!hasActiveSubscription ? (+ <p className="text-sm text-muted-foreground">+ An active subscription is required to create API keys.+ </p>+ ) : (+ <div className="flex items-end gap-3">+ <div className="grid gap-1.5">+ <Label htmlFor="key-name">New key name</Label>+ <Input+ id="key-name"+ placeholder="Production server"+ value={name}+ onChange={(event) => setName(event.target.value)}+ />+ </div>+ <Button+ disabled={createKey.isPending || !name.trim()}+ onClick={handleCreate}+ >+ {createKey.isPending ? "Creating…" : "Create key"}+ </Button>+ </div>+ )}++ {keys.isLoading ? (+ <Skeleton className="h-24 w-full" />+ ) : keys.data && keys.data.length > 0 ? (+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>Name</TableHead>+ <TableHead>Key</TableHead>+ <TableHead>Created</TableHead>+ <TableHead>Last used</TableHead>+ <TableHead className="text-right">Actions</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {keys.data.map((key) => (+ <TableRow key={key.id}>+ <TableCell>{key.name ?? "—"}</TableCell>+ <TableCell className="font-mono text-xs">+ {(key.prefix ?? "") + (key.start ?? "")}…+ </TableCell>+ <TableCell>+ {new Date(key.createdAt).toLocaleDateString()}+ </TableCell>+ <TableCell>+ {key.lastRequest+ ? new Date(key.lastRequest).toLocaleDateString()+ : "Never"}+ </TableCell>+ <TableCell className="text-right">+ <Button+ disabled={deleteKey.isPending}+ onClick={() => deleteKey.mutate(key.id)}+ size="sm"+ variant="destructive"+ >+ Revoke+ </Button>+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ ) : (+ <p className="text-sm text-muted-foreground">No API keys yet.</p>+ )}+ </CardContent>++ <Dialog+ open={createdKey !== null}+ onOpenChange={(open) => {+ if (!open) {+ setCreatedKey(null);+ }+ }}+ >+ <DialogContent>+ <DialogHeader>+ <DialogTitle>API key created</DialogTitle>+ <DialogDescription>+ Copy this secret now. You won't be able to see it again.+ </DialogDescription>+ </DialogHeader>+ <div className="rounded-md border bg-muted p-3 font-mono text-sm break-all">+ {createdKey?.secret}+ </div>+ <DialogFooter>+ <Button+ onClick={() => {+ if (createdKey) {+ void navigator.clipboard.writeText(createdKey.secret);+ }+ }}+ variant="secondary"+ >+ Copy+ </Button>+ <Button onClick={() => setCreatedKey(null)}>Done</Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </Card>+ );+}diff --git a/site/src/app/dashboard/_components/SubscriptionCard.tsx b/site/src/app/dashboard/_components/SubscriptionCard.tsxnew file mode 100644index 00000000..ceb6b663--- /dev/null+++ b/site/src/app/dashboard/_components/SubscriptionCard.tsx@@ -0,0 +1,112 @@+"use client";++import {+ useOpenBillingPortal,+ useStartCheckout,+ useSubscription,+} from "@/queries/billing";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import {+ Card,+ CardContent,+ CardDescription,+ CardFooter,+ CardHeader,+ CardTitle,+} from "@/components/ui/card";+import { Skeleton } from "@/components/ui/skeleton";++export function SubscriptionCard() {+ const subscription = useSubscription();+ const checkout = useStartCheckout();+ const portal = useOpenBillingPortal();++ if (subscription.isLoading) {+ return (+ <Card>+ <CardHeader>+ <Skeleton className="h-6 w-40" />+ </CardHeader>+ <CardContent>+ <Skeleton className="h-16 w-full" />+ </CardContent>+ </Card>+ );+ }++ const data = subscription.data;+ const isActive = data?.isActive ?? false;++ return (+ <Card>+ <CardHeader>+ <CardTitle className="flex items-center gap-3">+ Vision API plan+ {data ? (+ <Badge variant={isActive ? "default" : "secondary"}>+ {data.status}+ </Badge>+ ) : null}+ </CardTitle>+ <CardDescription>+ {data+ ? `${data.monthlyCallQuota.toLocaleString()} API calls per month.`+ : "$50/month · 5,000 API calls per month · 3 requests/second."}+ </CardDescription>+ </CardHeader>+ <CardContent className="text-sm text-muted-foreground">+ {data ? (+ <div className="space-y-1">+ <div>+ Renews / ends:{" "}+ {data.currentPeriodEnd+ ? new Date(data.currentPeriodEnd).toLocaleDateString()+ : "—"}+ </div>+ {data.cancelAtPeriodEnd ? (+ <div className="text-foreground">+ Cancels at the end of the current period.+ </div>+ ) : null}+ </div>+ ) : (+ <p>+ Subscribe to generate API keys and start calling the Vision API.+ </p>+ )}+ </CardContent>+ <CardFooter className="gap-3">+ {data ? (+ <Button+ disabled={portal.isPending}+ onClick={() =>+ portal.mutate(undefined, {+ onSuccess: (result) => window.location.assign(result.url),+ })+ }+ variant="secondary"+ >+ {portal.isPending ? "Opening…" : "Manage billing"}+ </Button>+ ) : (+ <Button+ disabled={checkout.isPending}+ onClick={() =>+ checkout.mutate(undefined, {+ onSuccess: (result) => window.location.assign(result.url),+ })+ }+ >+ {checkout.isPending ? "Starting…" : "Subscribe — $50/mo"}+ </Button>+ )}+ {checkout.isError || portal.isError ? (+ <span className="text-sm text-destructive">+ Billing is unavailable right now.+ </span>+ ) : null}+ </CardFooter>+ </Card>+ );+}diff --git a/site/src/app/dashboard/_components/UsageCard.tsx b/site/src/app/dashboard/_components/UsageCard.tsxnew file mode 100644index 00000000..fa515842--- /dev/null+++ b/site/src/app/dashboard/_components/UsageCard.tsx@@ -0,0 +1,109 @@+"use client";++import { useUsage } from "@/queries/billing";+import { Badge } from "@/components/ui/badge";+import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+} from "@/components/ui/card";+import { Skeleton } from "@/components/ui/skeleton";+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@/components/ui/table";++export function UsageCard() {+ const usage = useUsage();++ if (usage.isLoading) {+ return (+ <Card>+ <CardHeader>+ <Skeleton className="h-6 w-32" />+ </CardHeader>+ <CardContent>+ <Skeleton className="h-24 w-full" />+ </CardContent>+ </Card>+ );+ }++ const data = usage.data;+ const pct =+ data && data.limit > 0+ ? Math.min(100, Math.round((data.used / data.limit) * 100))+ : 0;++ return (+ <Card>+ <CardHeader>+ <CardTitle>Usage this period</CardTitle>+ <CardDescription>+ {data && data.limit > 0+ ? `${data.used.toLocaleString()} of ${data.limit.toLocaleString()} calls used · ${data.remaining.toLocaleString()} remaining`+ : "No active plan — subscribe to start making calls."}+ </CardDescription>+ </CardHeader>+ <CardContent className="space-y-4">+ {data && data.limit > 0 ? (+ <div+ aria-label="Quota used"+ className="h-2 w-full overflow-hidden rounded-full bg-muted"+ >+ <div+ className="h-full rounded-full bg-primary"+ style={{ width: `${pct}%` }}+ />+ </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/dashboard/api-keys/page.tsx b/site/src/app/dashboard/api-keys/page.tsxnew file mode 100644index 00000000..3b4c443d--- /dev/null+++ b/site/src/app/dashboard/api-keys/page.tsx@@ -0,0 +1,22 @@+"use client";++import { ApiKeysManager } from "@/app/dashboard/_components/ApiKeysManager";++export default function ApiKeysPage() {+ return (+ <div className="space-y-8">+ <div>+ <h1 className="text-2xl font-semibold">API keys</h1>+ <p className="mt-1 text-sm text-muted-foreground">+ Create keys to authenticate Vision API requests. Send a key as a bearer+ token:{" "}+ <code className="rounded bg-muted px-1 py-0.5">+ Authorization: Bearer <key>+ </code>+ .+ </p>+ </div>+ <ApiKeysManager />+ </div>+ );+}diff --git a/site/src/app/dashboard/layout.tsx b/site/src/app/dashboard/layout.tsxnew file mode 100644index 00000000..388e1ac0--- /dev/null+++ b/site/src/app/dashboard/layout.tsx@@ -0,0 +1,15 @@+import type { Metadata } from "next";+import type { ReactNode } from "react";++import { DashboardShell } from "@/app/dashboard/DashboardShell";++export const metadata: Metadata = {+ title: "Dashboard | Donkey Vision API",+ description: "Manage your Vision API subscription and API keys.",+};++// QueryProvider is mounted once at the root layout, so the dashboard just needs+// its session-guarded shell here.+export default function DashboardLayout({ children }: { children: ReactNode }) {+ return <DashboardShell>{children}</DashboardShell>;+}diff --git a/site/src/app/dashboard/page.tsx b/site/src/app/dashboard/page.tsxnew file mode 100644index 00000000..b49bc0aa--- /dev/null+++ b/site/src/app/dashboard/page.tsx@@ -0,0 +1,19 @@+"use client";++import { SubscriptionCard } from "@/app/dashboard/_components/SubscriptionCard";+import { UsageCard } from "@/app/dashboard/_components/UsageCard";++export default function DashboardOverviewPage() {+ return (+ <div className="space-y-8">+ <div>+ <h1 className="text-2xl font-semibold">Overview</h1>+ <p className="mt-1 text-sm text-muted-foreground">+ Your Vision API subscription and usage this billing period.+ </p>+ </div>+ <SubscriptionCard />+ <UsageCard />+ </div>+ );+}diff --git a/site/src/app/layout.tsx b/site/src/app/layout.tsxindex 24ec3fe8..a30ae91e 100644--- a/site/src/app/layout.tsx+++ b/site/src/app/layout.tsx@@ -2,6 +2,8 @@ import type { Metadata } from "next";import { Geist, Geist_Mono } from "next/font/google";import "./globals.css";+import { QueryProvider } from "@/queries/QueryProvider";+const geistSans = Geist({variable: "--font-geist-sans",subsets: ["latin"],@@ -27,7 +29,9 @@ export default function RootLayout({lang="en"className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}>- <body className="min-h-full flex flex-col">{children}</body>+ <body className="min-h-full flex flex-col">+ <QueryProvider>{children}</QueryProvider>+ </body></html>);}diff --git a/site/src/components/ui/badge.tsx b/site/src/components/ui/badge.tsxnew file mode 100644index 00000000..b20959dd--- /dev/null+++ b/site/src/components/ui/badge.tsx@@ -0,0 +1,52 @@+import { mergeProps } from "@base-ui/react/merge-props"+import { useRender } from "@base-ui/react/use-render"+import { cva, type VariantProps } from "class-variance-authority"++import { cn } from "@/lib/utils"++const badgeVariants = cva(+ "group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-4xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!",+ {+ variants: {+ variant: {+ default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80",+ secondary:+ "bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80",+ destructive:+ "bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20",+ outline:+ "border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground",+ ghost:+ "hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50",+ link: "text-primary underline-offset-4 hover:underline",+ },+ },+ defaultVariants: {+ variant: "default",+ },+ }+)++function Badge({+ className,+ variant = "default",+ render,+ ...props+}: useRender.ComponentProps<"span"> & VariantProps<typeof badgeVariants>) {+ return useRender({+ defaultTagName: "span",+ props: mergeProps<"span">(+ {+ className: cn(badgeVariants({ variant }), className),+ },+ props+ ),+ render,+ state: {+ slot: "badge",+ variant,+ },+ })+}++export { Badge, badgeVariants }diff --git a/site/src/components/ui/card.tsx b/site/src/components/ui/card.tsxnew file mode 100644index 00000000..40cac5f9--- /dev/null+++ b/site/src/components/ui/card.tsx@@ -0,0 +1,103 @@+import * as React from "react"++import { cn } from "@/lib/utils"++function Card({+ className,+ size = "default",+ ...props+}: React.ComponentProps<"div"> & { size?: "default" | "sm" }) {+ return (+ <div+ data-slot="card"+ data-size={size}+ className={cn(+ "group/card flex flex-col gap-4 overflow-hidden rounded-xl bg-card py-4 text-sm text-card-foreground ring-1 ring-foreground/10 has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:gap-3 data-[size=sm]:py-3 data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl",+ className+ )}+ {...props}+ />+ )+}++function CardHeader({ className, ...props }: React.ComponentProps<"div">) {+ return (+ <div+ data-slot="card-header"+ className={cn(+ "group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-xl px-4 group-data-[size=sm]/card:px-3 has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-4 group-data-[size=sm]/card:[.border-b]:pb-3",+ className+ )}+ {...props}+ />+ )+}++function CardTitle({ className, ...props }: React.ComponentProps<"div">) {+ return (+ <div+ data-slot="card-title"+ className={cn(+ "font-heading text-base leading-snug font-medium group-data-[size=sm]/card:text-sm",+ className+ )}+ {...props}+ />+ )+}++function CardDescription({ className, ...props }: React.ComponentProps<"div">) {+ return (+ <div+ data-slot="card-description"+ className={cn("text-sm text-muted-foreground", className)}+ {...props}+ />+ )+}++function CardAction({ className, ...props }: React.ComponentProps<"div">) {+ return (+ <div+ data-slot="card-action"+ className={cn(+ "col-start-2 row-span-2 row-start-1 self-start justify-self-end",+ className+ )}+ {...props}+ />+ )+}++function CardContent({ className, ...props }: React.ComponentProps<"div">) {+ return (+ <div+ data-slot="card-content"+ className={cn("px-4 group-data-[size=sm]/card:px-3", className)}+ {...props}+ />+ )+}++function CardFooter({ className, ...props }: React.ComponentProps<"div">) {+ return (+ <div+ data-slot="card-footer"+ className={cn(+ "flex items-center rounded-b-xl border-t bg-muted/50 p-4 group-data-[size=sm]/card:p-3",+ className+ )}+ {...props}+ />+ )+}++export {+ Card,+ CardHeader,+ CardFooter,+ CardTitle,+ CardAction,+ CardDescription,+ CardContent,+}diff --git a/site/src/components/ui/dialog.tsx b/site/src/components/ui/dialog.tsxnew file mode 100644index 00000000..014f5aa3--- /dev/null+++ b/site/src/components/ui/dialog.tsx@@ -0,0 +1,160 @@+"use client"++import * as React from "react"+import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"++import { cn } from "@/lib/utils"+import { Button } from "@/components/ui/button"+import { XIcon } from "lucide-react"++function Dialog({ ...props }: DialogPrimitive.Root.Props) {+ return <DialogPrimitive.Root data-slot="dialog" {...props} />+}++function DialogTrigger({ ...props }: DialogPrimitive.Trigger.Props) {+ return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />+}++function DialogPortal({ ...props }: DialogPrimitive.Portal.Props) {+ return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />+}++function DialogClose({ ...props }: DialogPrimitive.Close.Props) {+ return <DialogPrimitive.Close data-slot="dialog-close" {...props} />+}++function DialogOverlay({+ className,+ ...props+}: DialogPrimitive.Backdrop.Props) {+ return (+ <DialogPrimitive.Backdrop+ data-slot="dialog-overlay"+ className={cn(+ "fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",+ className+ )}+ {...props}+ />+ )+}++function DialogContent({+ className,+ children,+ showCloseButton = true,+ ...props+}: DialogPrimitive.Popup.Props & {+ showCloseButton?: boolean+}) {+ return (+ <DialogPortal>+ <DialogOverlay />+ <DialogPrimitive.Popup+ data-slot="dialog-content"+ className={cn(+ "fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",+ className+ )}+ {...props}+ >+ {children}+ {showCloseButton && (+ <DialogPrimitive.Close+ data-slot="dialog-close"+ render={+ <Button+ variant="ghost"+ className="absolute top-2 right-2"+ size="icon-sm"+ />+ }+ >+ <XIcon+ />+ <span className="sr-only">Close</span>+ </DialogPrimitive.Close>+ )}+ </DialogPrimitive.Popup>+ </DialogPortal>+ )+}++function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {+ return (+ <div+ data-slot="dialog-header"+ className={cn("flex flex-col gap-2", className)}+ {...props}+ />+ )+}++function DialogFooter({+ className,+ showCloseButton = false,+ children,+ ...props+}: React.ComponentProps<"div"> & {+ showCloseButton?: boolean+}) {+ return (+ <div+ data-slot="dialog-footer"+ className={cn(+ "-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end",+ className+ )}+ {...props}+ >+ {children}+ {showCloseButton && (+ <DialogPrimitive.Close render={<Button variant="outline" />}>+ Close+ </DialogPrimitive.Close>+ )}+ </div>+ )+}++function DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) {+ return (+ <DialogPrimitive.Title+ data-slot="dialog-title"+ className={cn(+ "font-heading text-base leading-none font-medium",+ className+ )}+ {...props}+ />+ )+}++function DialogDescription({+ className,+ ...props+}: DialogPrimitive.Description.Props) {+ return (+ <DialogPrimitive.Description+ data-slot="dialog-description"+ className={cn(+ "text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",+ className+ )}+ {...props}+ />+ )+}++export {+ Dialog,+ DialogClose,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogOverlay,+ DialogPortal,+ DialogTitle,+ DialogTrigger,+}diff --git a/site/src/components/ui/input.tsx b/site/src/components/ui/input.tsxnew file mode 100644index 00000000..7d21babb--- /dev/null+++ b/site/src/components/ui/input.tsx@@ -0,0 +1,20 @@+import * as React from "react"+import { Input as InputPrimitive } from "@base-ui/react/input"++import { cn } from "@/lib/utils"++function Input({ className, type, ...props }: React.ComponentProps<"input">) {+ return (+ <InputPrimitive+ type={type}+ data-slot="input"+ className={cn(+ "h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",+ className+ )}+ {...props}+ />+ )+}++export { Input }diff --git a/site/src/components/ui/label.tsx b/site/src/components/ui/label.tsxnew file mode 100644index 00000000..74da65c3--- /dev/null+++ b/site/src/components/ui/label.tsx@@ -0,0 +1,20 @@+"use client"++import * as React from "react"++import { cn } from "@/lib/utils"++function Label({ className, ...props }: React.ComponentProps<"label">) {+ return (+ <label+ data-slot="label"+ className={cn(+ "flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",+ className+ )}+ {...props}+ />+ )+}++export { Label }diff --git a/site/src/components/ui/skeleton.tsx b/site/src/components/ui/skeleton.tsxnew file mode 100644index 00000000..0118624f--- /dev/null+++ b/site/src/components/ui/skeleton.tsx@@ -0,0 +1,13 @@+import { cn } from "@/lib/utils"++function Skeleton({ className, ...props }: React.ComponentProps<"div">) {+ return (+ <div+ data-slot="skeleton"+ className={cn("animate-pulse rounded-md bg-muted", className)}+ {...props}+ />+ )+}++export { Skeleton }diff --git a/site/src/components/ui/table.tsx b/site/src/components/ui/table.tsxnew file mode 100644index 00000000..abeaced4--- /dev/null+++ b/site/src/components/ui/table.tsx@@ -0,0 +1,116 @@+"use client"++import * as React from "react"++import { cn } from "@/lib/utils"++function Table({ className, ...props }: React.ComponentProps<"table">) {+ return (+ <div+ data-slot="table-container"+ className="relative w-full overflow-x-auto"+ >+ <table+ data-slot="table"+ className={cn("w-full caption-bottom text-sm", className)}+ {...props}+ />+ </div>+ )+}++function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {+ return (+ <thead+ data-slot="table-header"+ className={cn("[&_tr]:border-b", className)}+ {...props}+ />+ )+}++function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {+ return (+ <tbody+ data-slot="table-body"+ className={cn("[&_tr:last-child]:border-0", className)}+ {...props}+ />+ )+}++function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {+ return (+ <tfoot+ data-slot="table-footer"+ className={cn(+ "border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",+ className+ )}+ {...props}+ />+ )+}++function TableRow({ className, ...props }: React.ComponentProps<"tr">) {+ return (+ <tr+ data-slot="table-row"+ className={cn(+ "border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",+ className+ )}+ {...props}+ />+ )+}++function TableHead({ className, ...props }: React.ComponentProps<"th">) {+ return (+ <th+ data-slot="table-head"+ className={cn(+ "h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0",+ className+ )}+ {...props}+ />+ )+}++function TableCell({ className, ...props }: React.ComponentProps<"td">) {+ return (+ <td+ data-slot="table-cell"+ className={cn(+ "p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0",+ className+ )}+ {...props}+ />+ )+}++function TableCaption({+ className,+ ...props+}: React.ComponentProps<"caption">) {+ return (+ <caption+ data-slot="table-caption"+ className={cn("mt-4 text-sm text-muted-foreground", className)}+ {...props}+ />+ )+}++export {+ Table,+ TableHeader,+ TableBody,+ TableFooter,+ TableHead,+ TableRow,+ TableCell,+ TableCaption,+}diff --git a/site/src/queries/QueryProvider.tsx b/site/src/queries/QueryProvider.tsxnew file mode 100644index 00000000..ced2d7f9--- /dev/null+++ b/site/src/queries/QueryProvider.tsx@@ -0,0 +1,21 @@+"use client";++import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { useState, type ReactNode } from "react";++export function QueryProvider({ children }: { children: ReactNode }) {+ const [client] = useState(+ () =>+ new QueryClient({+ defaultOptions: {+ queries: {+ refetchOnWindowFocus: false,+ retry: 1,+ staleTime: 30_000,+ },+ },+ }),+ );++ return <QueryClientProvider client={client}>{children}</QueryClientProvider>;+}diff --git a/site/src/queries/apiClient.ts b/site/src/queries/apiClient.tsnew file mode 100644index 00000000..4154e0ad--- /dev/null+++ b/site/src/queries/apiClient.ts@@ -0,0 +1,50 @@+// Thin fetch wrapper shared by every query/mutation hook in this folder. All+// dashboard data access goes through here so it can be audited in one place.++export class ApiError extends Error {+ public readonly status: number;+ public readonly code: string | null;++ public constructor(message: string, status: number, code: string | null) {+ super(message);+ this.name = "ApiError";+ this.status = status;+ this.code = code;+ }+}++type ApiErrorBody = { error?: string; message?: string };++export async function apiFetch<T>(+ path: string,+ init?: RequestInit,+): Promise<T> {+ const hasBody = init?.body !== undefined;+ const response = await fetch(path, {+ ...init,+ headers: {+ ...(hasBody ? { "Content-Type": "application/json" } : {}),+ ...init?.headers,+ },+ });++ if (!response.ok) {+ let body: ApiErrorBody = {};+ try {+ body = (await response.json()) as ApiErrorBody;+ } catch {+ // Non-JSON error body; fall back to status text.+ }+ throw new ApiError(+ body.message ?? response.statusText,+ response.status,+ body.error ?? null,+ );+ }++ if (response.status === 204) {+ return undefined as T;+ }++ return (await response.json()) as T;+}diff --git a/site/src/queries/apiKeys.ts b/site/src/queries/apiKeys.tsnew file mode 100644index 00000000..87dbb474--- /dev/null+++ b/site/src/queries/apiKeys.ts@@ -0,0 +1,61 @@+"use client";++import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";++import { apiFetch } from "@/queries/apiClient";++export const apiKeysQueryKey = ["api-keys"] as const;++export type ApiKey = {+ id: string;+ name: string | null;+ start: string | null;+ prefix: string | null;+ enabled: boolean;+ createdAt: string;+ lastRequest: string | null;+ expiresAt: string | null;+};++export type CreatedApiKey = {+ apiKey: ApiKey;+ // The plaintext secret, returned exactly once at creation.+ secret: string;+};++export function useApiKeys() {+ return useQuery({+ queryFn: () =>+ apiFetch<{ apiKeys: ApiKey[] }>("/api/api-keys").then(+ (response) => response.apiKeys,+ ),+ queryKey: apiKeysQueryKey,+ });+}++export function useCreateApiKey() {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: (name: string) =>+ apiFetch<CreatedApiKey>("/api/api-keys", {+ body: JSON.stringify({ name }),+ method: "POST",+ }),+ onSuccess: () => {+ void queryClient.invalidateQueries({ queryKey: apiKeysQueryKey });+ },+ });+}++export function useDeleteApiKey() {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: (id: string) =>+ apiFetch<{ deleted: boolean }>(`/api/api-keys/${id}`, {+ method: "DELETE",+ }),+ onSuccess: () => {+ void queryClient.invalidateQueries({ queryKey: apiKeysQueryKey });+ },+ });+}diff --git a/site/src/queries/billing.ts b/site/src/queries/billing.tsnew file mode 100644index 00000000..be50fdfc--- /dev/null+++ b/site/src/queries/billing.ts@@ -0,0 +1,72 @@+"use client";++import { useMutation, useQuery } from "@tanstack/react-query";++import { apiFetch } from "@/queries/apiClient";++export const subscriptionQueryKey = ["billing", "subscription"] as const;+export const usageQueryKey = ["billing", "usage"] as const;++// Plans that the checkout route understands. Only "vision" is self-serve today;+// "pro" (the Mac app plan) is accepted by the landing card but the route returns+// "not available" until it is wired to Stripe.+export type BillingPlanKey = "vision" | "pro";++export type VisionSubscription = {+ status: string;+ isActive: boolean;+ planKey: string;+ monthlyCallQuota: number;+ currentPeriodEnd: string | null;+ cancelAtPeriodEnd: boolean;+};++export type VisionUsage = {+ used: number;+ limit: number;+ remaining: number;+ periodStart: string | null;+ periodEnd: string | null;+ recent: {+ createdAt: string;+ model: string;+ requestKind: string;+ status: string;+ }[];+};++export function useSubscription() {+ return useQuery({+ queryFn: () =>+ apiFetch<{ subscription: VisionSubscription | null }>(+ "/api/billing/subscription",+ ).then((response) => response.subscription),+ queryKey: subscriptionQueryKey,+ });+}++export function useUsage() {+ return useQuery({+ queryFn: () => apiFetch<VisionUsage>("/api/billing/usage"),+ queryKey: usageQueryKey,+ });+}++// Mutations return the Stripe URL; the caller redirects the browser. We don't+// invalidate here because the user leaves the page for Stripe.+export function useStartCheckout() {+ return useMutation({+ mutationFn: (planKey?: BillingPlanKey) =>+ apiFetch<{ url: string }>("/api/billing/checkout", {+ body: JSON.stringify({ planKey: planKey ?? "vision" }),+ method: "POST",+ }),+ });+}++export function useOpenBillingPortal() {+ return useMutation({+ mutationFn: () =>+ apiFetch<{ url: string }>("/api/billing/portal", { method: "POST" }),+ });+}