Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions apps/web/app/admin/error.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
"use client"

// Catches errors thrown from any /admin/* route. Without this, a
// useSuspenseQuery failure (Supabase blip, 5xx) escapes to the root
// error boundary and takes the admin chrome down with it.

export default function AdminError({
error,
reset,
}: {
error: Error & { digest?: string }
reset: () => void
}) {
return (
<div className="rounded-lg border border-destructive/30 bg-destructive/5 p-6">
<h2 className="text-lg font-semibold text-destructive">
Something went wrong in the admin area
</h2>
<p className="mt-2 text-sm text-muted-foreground">
{error.message || "Unknown error"}
</p>
{error.digest ? (
<p className="mt-1 font-mono text-xs text-muted-foreground">
Ref: {error.digest}
</p>
) : null}
<button
type="button"
onClick={reset}
className="mt-4 inline-flex items-center rounded-md border border-border bg-background px-3 py-1.5 text-sm font-medium hover:bg-muted"
>
Try again
</button>
</div>
)
}
51 changes: 51 additions & 0 deletions apps/web/app/admin/layout.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/* @vitest-environment jsdom */
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"

vi.mock("next/headers", () => ({
headers: vi.fn().mockResolvedValue(new Headers()),
}))
vi.mock("next/navigation", () => ({
redirect: vi.fn((url: string) => {
throw new Error(`REDIRECT:${url}`)
}),
}))
vi.mock("@/lib/auth", () => ({
auth: { api: { getSession: vi.fn() } },
}))

import { auth } from "@/lib/auth"
import AdminLayout from "./layout"

describe("AdminLayout", () => {
beforeEach(() => {
vi.clearAllMocks()
})

afterEach(() => {
vi.restoreAllMocks()
})

it("redirects to /device when no session", async () => {
vi.mocked(auth.api.getSession).mockResolvedValueOnce(null as never)
await expect(AdminLayout({ children: null })).rejects.toThrow(/REDIRECT:\/device/)
})

it("redirects to /device when session has no user.id", async () => {
vi.mocked(auth.api.getSession).mockResolvedValueOnce({ user: {} } as never)
await expect(AdminLayout({ children: null })).rejects.toThrow(/REDIRECT:\/device/)
})

it("does not redirect when a valid session exists", async () => {
// Behavioral assertion: with a session, AdminLayout resolves instead
// of throwing the redirect sentinel. Asserting on the root element's
// component identity (function name, type === "div") was brittle —
// wrapping the shell in QueryProvider shouldn't break this test.
vi.mocked(auth.api.getSession).mockResolvedValueOnce({
user: { id: "u1", email: "me@example.com" },
} as never)
const { redirect } = await import("next/navigation")
const out = await AdminLayout({ children: null })
expect(out).toBeDefined()
expect(redirect).not.toHaveBeenCalled()
})
})
43 changes: 43 additions & 0 deletions apps/web/app/admin/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { headers } from "next/headers"
import Link from "next/link"
import { redirect } from "next/navigation"
import type { ReactNode } from "react"
import { auth } from "@/lib/auth"
import { QueryProvider } from "@/components/providers/query-provider"

// Auth-gated surface — never safe to cache or statically render.
export const dynamic = "force-dynamic"

// Auth-gated shell for the admin surface. Server component so
// redirects happen before any client JS ships. Intentionally minimal —
// real shell chrome lives in the first real admin feature's PR.
//
// QueryProvider lives here (not in the root layout) because TanStack
// Query is a hosted-tier concern — the scaffolded docs site is pure
// SSR and doesn't need a client QueryClient or the dep weight. Any
// future hosted-tier surface (e.g., /console, /billing) should either
// nest under /admin or wrap its own QueryProvider the same way.
export default async function AdminLayout({ children }: { children: ReactNode }) {
const session = await auth.api.getSession({ headers: await headers() })
if (!session?.user?.id) {
redirect("/device")
}

return (
<QueryProvider>
<div className="min-h-screen bg-background">
<header className="border-b border-border px-6 py-4">
<nav className="mx-auto flex max-w-5xl items-center justify-between">
<Link href="/admin/usage" className="text-sm font-semibold">
helpbase admin
</Link>
<span className="text-xs text-muted-foreground">
{session.user.email ?? session.user.id}
</span>
</nav>
</header>
<main className="mx-auto max-w-5xl px-6 py-8">{children}</main>
</div>
</QueryProvider>
)
}
26 changes: 26 additions & 0 deletions apps/web/app/admin/usage/loading.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
export default function Loading() {
return <UsageCardSkeleton />
}

export function UsageCardSkeleton() {
return (
<section className="rounded-lg border border-border bg-card p-6">
<div className="h-5 w-40 animate-pulse rounded bg-muted" />
<div className="mt-2 h-4 w-56 animate-pulse rounded bg-muted" />

<dl className="mt-6 grid grid-cols-2 gap-4">
<div>
<div className="h-3 w-12 animate-pulse rounded bg-muted" />
<div className="mt-2 h-8 w-24 animate-pulse rounded bg-muted" />
</div>
<div>
<div className="h-3 w-20 animate-pulse rounded bg-muted" />
<div className="mt-2 h-8 w-24 animate-pulse rounded bg-muted" />
</div>
</dl>

<div className="mt-4 h-2 w-full animate-pulse rounded-full bg-muted" />
<div className="mt-3 h-3 w-48 animate-pulse rounded bg-muted" />
</section>
)
}
45 changes: 45 additions & 0 deletions apps/web/app/admin/usage/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { HydrationBoundary, dehydrate } from "@tanstack/react-query"
import type { Metadata } from "next"
import { headers } from "next/headers"
import { redirect } from "next/navigation"
import { Suspense } from "react"
import { auth } from "@/lib/auth"
import { getUsageTodayForUser } from "@/lib/data/usage"
import { getQueryClient } from "@/lib/get-query-client"
import { usageKeys } from "@/lib/query-keys"
import { UsageCard } from "./usage-card"
import { UsageCardSkeleton } from "./loading"

export const metadata: Metadata = {
title: "Usage · helpbase admin",
robots: { index: false, follow: false },
}

// Keep this route dynamic. Auth-gated + per-user data is never safe to
// prerender, and we want a defensive barrier against future PPR/ISR
// project-wide config flipping this to cached-by-default.
export const dynamic = "force-dynamic"

export default async function UsagePage() {
// The layout already auth-gates, but we also need `userId` + `email`
// here to call the data layer. Re-resolving is cheap (cookie → session
// via Better Auth's in-memory cache for the same request).
const session = await auth.api.getSession({ headers: await headers() })
if (!session?.user?.id) redirect("/device")

// Direct data-layer call + setQueryData avoids a self-HTTP round-trip.
// `updatedAt: Date.now()` is critical: without it the hydrated entry
// has dataUpdatedAt=0, so useSuspenseQuery treats it as stale and
// refetches on mount — defeating the whole point of seeding.
const queryClient = getQueryClient()
const data = await getUsageTodayForUser(session.user.id, session.user.email ?? "")
queryClient.setQueryData(usageKeys.today(), data, { updatedAt: Date.now() })

return (
<HydrationBoundary state={dehydrate(queryClient)}>
<Suspense fallback={<UsageCardSkeleton />}>
<UsageCard />
</Suspense>
</HydrationBoundary>
)
}
62 changes: 62 additions & 0 deletions apps/web/app/admin/usage/usage-card.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/* @vitest-environment jsdom */
import "@testing-library/jest-dom/vitest"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { cleanup, render, screen } from "@testing-library/react"
import { Suspense, type ReactNode } from "react"
import { afterEach, describe, expect, it } from "vitest"
import { usageKeys } from "@/lib/query-keys"
import { UsageCard } from "./usage-card"

// Vitest doesn't wire @testing-library/react's auto-cleanup unless
// `globals: true` is set in vitest.config — this project doesn't set
// it, so we clean up between tests manually.
afterEach(() => cleanup())

function wrap(children: ReactNode, client: QueryClient) {
return (
<QueryClientProvider client={client}>
<Suspense fallback={<p>loading</p>}>{children}</Suspense>
</QueryClientProvider>
)
}

describe("UsageCard", () => {
it("renders pre-seeded usage data without hitting the network", () => {
const queryClient = new QueryClient()
queryClient.setQueryData(usageKeys.today(), {
email: "founder@example.com",
quota: {
usedToday: 42_000,
dailyLimit: 500_000,
resetAt: "2026-04-18T00:00:00.000Z",
},
})

render(wrap(<UsageCard />, queryClient))

// Locale-agnostic: Node's default locale differs between dev boxes
// and CI runners, so assert on elements and substrings that don't
// depend on toLocaleString's thousands separator.
expect(screen.getByText("Today\u2019s usage")).toBeInTheDocument()
expect(screen.getByText("founder@example.com")).toBeInTheDocument()
const bar = screen.getByRole("progressbar")
// 42,000 / 500,000 = 8.4% → rounded to 8
expect(bar.getAttribute("aria-valuenow")).toBe("8")
})

it("computes the progress bar from used/limit", () => {
const queryClient = new QueryClient()
queryClient.setQueryData(usageKeys.today(), {
email: "",
quota: {
usedToday: 125_000,
dailyLimit: 500_000,
resetAt: "2026-04-18T00:00:00.000Z",
},
})

render(wrap(<UsageCard />, queryClient))
const bar = screen.getByRole("progressbar")
expect(bar.getAttribute("aria-valuenow")).toBe("25")
})
})
48 changes: 48 additions & 0 deletions apps/web/app/admin/usage/usage-card.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"use client"

import { useSuspenseQuery } from "@tanstack/react-query"
import { usageTodayOptions } from "@/lib/query-options"

export function UsageCard() {
const { data } = useSuspenseQuery(usageTodayOptions())
const { usedToday, dailyLimit, resetAt } = data.quota
// Clamp both ends: negative usedToday (quota refund TODO) would otherwise
// produce width: -5% → CSS drops it → bar collapses silently.
const pct = dailyLimit > 0 ? Math.max(0, Math.min(100, Math.round((usedToday / dailyLimit) * 100))) : 0

return (
<section className="rounded-lg border border-border bg-card p-6">
<h1 className="text-lg font-semibold">Today&rsquo;s usage</h1>
<p className="mt-1 text-sm text-muted-foreground">
Signed in as <span className="font-mono">{data.email}</span>
</p>

<dl className="mt-6 grid grid-cols-2 gap-4">
<div>
<dt className="text-xs uppercase tracking-wide text-muted-foreground">Used</dt>
<dd className="mt-1 font-mono text-2xl">{usedToday.toLocaleString()}</dd>
</div>
<div>
<dt className="text-xs uppercase tracking-wide text-muted-foreground">Daily limit</dt>
<dd className="mt-1 font-mono text-2xl">{dailyLimit.toLocaleString()}</dd>
</div>
</dl>

<div className="mt-4 h-2 w-full overflow-hidden rounded-full bg-muted">
<div
className="h-full bg-primary transition-[width] duration-300"
style={{ width: `${pct}%` }}
role="progressbar"
aria-label="Daily token usage"
aria-valuenow={pct}
aria-valuemin={0}
aria-valuemax={100}
/>
</div>

<p className="mt-3 text-xs text-muted-foreground" suppressHydrationWarning>
Resets at {new Date(resetAt).toLocaleString()}
</p>
</section>
)
}
38 changes: 15 additions & 23 deletions apps/web/app/api/v1/usage/today/route.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,15 @@
import type { NextRequest } from "next/server"
import { NextResponse } from "next/server"
import type { UsageTodayResponse } from "@workspace/shared/llm-wire"
import { getServiceRoleClient } from "@/lib/supabase-admin"
import { auth } from "@/lib/auth"
import {
DAILY_USER_LIMIT,
nextUtcMidnightIso,
wireError,
} from "../../llm/_shared"
import { getUsageTodayForUser } from "@/lib/data/usage"
import { wireError } from "../../llm/_shared"

/**
* GET /api/v1/usage/today
*
* Auth: Bearer <Better Auth session token>.
* Returns the signed-in user's today-tokens snapshot, used by `helpbase whoami`.
* Returns the signed-in user's today-tokens snapshot, used by `helpbase whoami`
* and (server-prefetched) by the /admin/usage page.
*/

export const runtime = "nodejs"
Expand All @@ -25,21 +21,17 @@ export async function GET(req: NextRequest): Promise<NextResponse> {
return wireError(401, "auth_required", "Missing, malformed, or expired session token.")
}

const client = getServiceRoleClient()
const { data, error } = await client.rpc("get_user_tokens_today", {
p_user_id: session.user.id,
})
if (error) {
try {
const body = await getUsageTodayForUser(session.user.id, session.user.email ?? "")
return NextResponse.json(body)
} catch (err) {
// Log the underlying error with the user id so a 503 spike doesn't
// require guessing from request timing. `userId` is safe to log;
// email is not.
console.error("[/api/v1/usage/today] RPC failure", {
userId: session.user.id,
error: err instanceof Error ? err.message : String(err),
})
return wireError(503, "internal_error", "Supabase is unavailable.")
}

const body: UsageTodayResponse = {
email: session.user.email ?? "",
quota: {
usedToday: Number(data ?? 0),
dailyLimit: DAILY_USER_LIMIT,
resetAt: nextUtcMidnightIso(),
},
}
return NextResponse.json(body)
}
Loading
Loading