diff --git a/apps/web/app/admin/error.tsx b/apps/web/app/admin/error.tsx
new file mode 100644
index 0000000..2bd0a3f
--- /dev/null
+++ b/apps/web/app/admin/error.tsx
@@ -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 (
+
+
+ Something went wrong in the admin area
+
+
+ {error.message || "Unknown error"}
+
+ {error.digest ? (
+
+ Ref: {error.digest}
+
+ ) : null}
+
+
+ )
+}
diff --git a/apps/web/app/admin/layout.test.tsx b/apps/web/app/admin/layout.test.tsx
new file mode 100644
index 0000000..92fff1b
--- /dev/null
+++ b/apps/web/app/admin/layout.test.tsx
@@ -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()
+ })
+})
diff --git a/apps/web/app/admin/layout.tsx b/apps/web/app/admin/layout.tsx
new file mode 100644
index 0000000..a4e80be
--- /dev/null
+++ b/apps/web/app/admin/layout.tsx
@@ -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 (
+
+
+
+
+
+ {children}
+
+
+ )
+}
diff --git a/apps/web/app/admin/usage/loading.tsx b/apps/web/app/admin/usage/loading.tsx
new file mode 100644
index 0000000..5a40c75
--- /dev/null
+++ b/apps/web/app/admin/usage/loading.tsx
@@ -0,0 +1,26 @@
+export default function Loading() {
+ return
+}
+
+export function UsageCardSkeleton() {
+ return (
+
+ )
+}
diff --git a/apps/web/app/admin/usage/page.tsx b/apps/web/app/admin/usage/page.tsx
new file mode 100644
index 0000000..906281e
--- /dev/null
+++ b/apps/web/app/admin/usage/page.tsx
@@ -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 (
+
+ }>
+
+
+
+ )
+}
diff --git a/apps/web/app/admin/usage/usage-card.test.tsx b/apps/web/app/admin/usage/usage-card.test.tsx
new file mode 100644
index 0000000..168fe2d
--- /dev/null
+++ b/apps/web/app/admin/usage/usage-card.test.tsx
@@ -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 (
+
+ loading}>{children}
+
+ )
+}
+
+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(, 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(, queryClient))
+ const bar = screen.getByRole("progressbar")
+ expect(bar.getAttribute("aria-valuenow")).toBe("25")
+ })
+})
diff --git a/apps/web/app/admin/usage/usage-card.tsx b/apps/web/app/admin/usage/usage-card.tsx
new file mode 100644
index 0000000..137ee5b
--- /dev/null
+++ b/apps/web/app/admin/usage/usage-card.tsx
@@ -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 (
+
+ Today’s usage
+
+ Signed in as {data.email}
+
+
+
+
+
- Used
+ - {usedToday.toLocaleString()}
+
+
+
- Daily limit
+ - {dailyLimit.toLocaleString()}
+
+
+
+
+
+
+ Resets at {new Date(resetAt).toLocaleString()}
+
+
+ )
+}
diff --git a/apps/web/app/api/v1/usage/today/route.ts b/apps/web/app/api/v1/usage/today/route.ts
index e0dd922..2cb35a2 100644
--- a/apps/web/app/api/v1/usage/today/route.ts
+++ b/apps/web/app/api/v1/usage/today/route.ts
@@ -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 .
- * 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"
@@ -25,21 +21,17 @@ export async function GET(req: NextRequest): Promise {
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)
}
diff --git a/apps/web/components/providers/query-provider.tsx b/apps/web/components/providers/query-provider.tsx
new file mode 100644
index 0000000..34baeb3
--- /dev/null
+++ b/apps/web/components/providers/query-provider.tsx
@@ -0,0 +1,29 @@
+"use client"
+
+import { QueryClientProvider } from "@tanstack/react-query"
+import dynamic from "next/dynamic"
+import type { ReactNode } from "react"
+import { getQueryClient } from "@/lib/get-query-client"
+
+// Devtools are dev-only: dynamic-imported so webpack can tree-shake
+// the package out of the production bundle (not just no-op at runtime).
+const ReactQueryDevtools =
+ process.env.NODE_ENV === "production"
+ ? () => null
+ : dynamic(
+ () =>
+ import("@tanstack/react-query-devtools").then((m) => ({
+ default: m.ReactQueryDevtools,
+ })),
+ { ssr: false },
+ )
+
+export function QueryProvider({ children }: { children: ReactNode }) {
+ const queryClient = getQueryClient()
+ return (
+
+ {children}
+
+
+ )
+}
diff --git a/apps/web/hooks/use-my-tenants.test.tsx b/apps/web/hooks/use-my-tenants.test.tsx
new file mode 100644
index 0000000..98d4d40
--- /dev/null
+++ b/apps/web/hooks/use-my-tenants.test.tsx
@@ -0,0 +1,59 @@
+/* @vitest-environment jsdom */
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
+import { renderHook, waitFor } from "@testing-library/react"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import type { ReactNode } from "react"
+import { useMyTenants } from "./use-my-tenants"
+
+function makeWrapper() {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ })
+ return function Wrapper({ children }: { children: ReactNode }) {
+ return {children}
+ }
+}
+
+describe("useMyTenants", () => {
+ beforeEach(() => {
+ vi.stubGlobal("fetch", vi.fn())
+ })
+
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ })
+
+ it("returns a tenant list", async () => {
+ vi.mocked(fetch).mockResolvedValueOnce({
+ ok: true,
+ status: 200,
+ statusText: "OK",
+ json: async () => ({
+ tenants: [
+ { id: "t1", slug: "acme", name: "Acme" },
+ { id: "t2", slug: "beta", name: null },
+ ],
+ }),
+ } as Response)
+
+ const { result } = renderHook(() => useMyTenants(), { wrapper: makeWrapper() })
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true))
+ expect(result.current.data?.tenants).toHaveLength(2)
+ expect(result.current.data?.tenants[0]?.slug).toBe("acme")
+ })
+
+ it("handles empty tenant list", async () => {
+ vi.mocked(fetch).mockResolvedValueOnce({
+ ok: true,
+ status: 200,
+ statusText: "OK",
+ json: async () => ({ tenants: [] }),
+ } as Response)
+
+ const { result } = renderHook(() => useMyTenants(), { wrapper: makeWrapper() })
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true))
+ expect(result.current.data?.tenants).toEqual([])
+ })
+})
diff --git a/apps/web/hooks/use-my-tenants.ts b/apps/web/hooks/use-my-tenants.ts
new file mode 100644
index 0000000..24c5412
--- /dev/null
+++ b/apps/web/hooks/use-my-tenants.ts
@@ -0,0 +1,8 @@
+"use client"
+
+import { useQuery } from "@tanstack/react-query"
+import { myTenantsOptions } from "@/lib/query-options"
+
+export function useMyTenants() {
+ return useQuery(myTenantsOptions())
+}
diff --git a/apps/web/hooks/use-usage-today.test.tsx b/apps/web/hooks/use-usage-today.test.tsx
new file mode 100644
index 0000000..5f62331
--- /dev/null
+++ b/apps/web/hooks/use-usage-today.test.tsx
@@ -0,0 +1,61 @@
+/* @vitest-environment jsdom */
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
+import { renderHook, waitFor } from "@testing-library/react"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import type { ReactNode } from "react"
+import { ApiError } from "@/lib/fetchers"
+import { useUsageToday } from "./use-usage-today"
+
+function makeWrapper() {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ })
+ return function Wrapper({ children }: { children: ReactNode }) {
+ return {children}
+ }
+}
+
+describe("useUsageToday", () => {
+ beforeEach(() => {
+ vi.stubGlobal("fetch", vi.fn())
+ })
+
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ })
+
+ it("returns the usage payload on success", async () => {
+ vi.mocked(fetch).mockResolvedValueOnce({
+ ok: true,
+ status: 200,
+ statusText: "OK",
+ json: async () => ({
+ email: "user@example.com",
+ quota: { usedToday: 12345, dailyLimit: 500000, resetAt: "2026-04-18T00:00:00Z" },
+ }),
+ } as Response)
+
+ const { result } = renderHook(() => useUsageToday(), { wrapper: makeWrapper() })
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true))
+ expect(result.current.data?.email).toBe("user@example.com")
+ expect(result.current.data?.quota.usedToday).toBe(12345)
+ })
+
+ it("surfaces 401 as an error with auth_required code", async () => {
+ vi.mocked(fetch).mockResolvedValueOnce({
+ ok: false,
+ status: 401,
+ statusText: "Unauthorized",
+ json: async () => ({ error: "auth_required", message: "Sign in." }),
+ } as Response)
+
+ const { result } = renderHook(() => useUsageToday(), { wrapper: makeWrapper() })
+
+ await waitFor(() => expect(result.current.isError).toBe(true))
+ expect(result.current.error).toBeInstanceOf(ApiError)
+ const err = result.current.error as ApiError
+ expect(err.status).toBe(401)
+ expect(err.code).toBe("auth_required")
+ })
+})
diff --git a/apps/web/hooks/use-usage-today.ts b/apps/web/hooks/use-usage-today.ts
new file mode 100644
index 0000000..823a0b6
--- /dev/null
+++ b/apps/web/hooks/use-usage-today.ts
@@ -0,0 +1,8 @@
+"use client"
+
+import { useQuery } from "@tanstack/react-query"
+import { usageTodayOptions } from "@/lib/query-options"
+
+export function useUsageToday() {
+ return useQuery(usageTodayOptions())
+}
diff --git a/apps/web/lib/data/usage.test.ts b/apps/web/lib/data/usage.test.ts
new file mode 100644
index 0000000..b9d580f
--- /dev/null
+++ b/apps/web/lib/data/usage.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it, vi } from "vitest"
+import { getUsageTodayForUser } from "./usage"
+
+vi.mock("@/lib/supabase-admin", () => ({
+ getServiceRoleClient: vi.fn(),
+}))
+
+import { getServiceRoleClient } from "@/lib/supabase-admin"
+
+describe("getUsageTodayForUser", () => {
+ it("returns a UsageTodayResponse with usedToday + dailyLimit", async () => {
+ vi.mocked(getServiceRoleClient).mockReturnValue({
+ rpc: vi.fn().mockResolvedValue({ data: 42_000, error: null }),
+ } as unknown as ReturnType)
+
+ const out = await getUsageTodayForUser("user-1", "u@example.com")
+
+ expect(out.email).toBe("u@example.com")
+ expect(out.quota.usedToday).toBe(42_000)
+ expect(out.quota.dailyLimit).toBe(500_000)
+ expect(typeof out.quota.resetAt).toBe("string")
+ })
+
+ it("coerces null RPC result to 0", async () => {
+ vi.mocked(getServiceRoleClient).mockReturnValue({
+ rpc: vi.fn().mockResolvedValue({ data: null, error: null }),
+ } as unknown as ReturnType)
+
+ const out = await getUsageTodayForUser("user-1", "")
+ expect(out.quota.usedToday).toBe(0)
+ })
+
+ it("throws when the RPC returns an error", async () => {
+ vi.mocked(getServiceRoleClient).mockReturnValue({
+ rpc: vi
+ .fn()
+ .mockResolvedValue({ data: null, error: { message: "db offline" } }),
+ } as unknown as ReturnType)
+
+ await expect(getUsageTodayForUser("user-1", "")).rejects.toThrow(/db offline/)
+ })
+})
diff --git a/apps/web/lib/data/usage.ts b/apps/web/lib/data/usage.ts
new file mode 100644
index 0000000..213e4ba
--- /dev/null
+++ b/apps/web/lib/data/usage.ts
@@ -0,0 +1,39 @@
+import type { UsageTodayResponse } from "@workspace/shared/llm-wire"
+import { getServiceRoleClient } from "@/lib/supabase-admin"
+import { DAILY_USER_LIMIT, nextUtcMidnightIso } from "@/app/api/v1/llm/_shared"
+
+/**
+ * Pure data function shared by the HTTP route (CLI consumers) and
+ * server-component prefetching for /admin/usage.
+ *
+ * Throws on Supabase errors so the caller can shape the HTTP envelope
+ * or the React error boundary separately.
+ */
+export async function getUsageTodayForUser(
+ userId: string,
+ email: string,
+): Promise {
+ const client = getServiceRoleClient()
+ const { data, error } = await client.rpc("get_user_tokens_today", {
+ p_user_id: userId,
+ })
+ if (error) {
+ throw new Error(`Supabase RPC get_user_tokens_today failed: ${error.message}`)
+ }
+
+ // Supabase returns bigint columns as strings to preserve precision.
+ // Number() of a non-numeric string is NaN, which flows silently into
+ // the UI as "NaN" and a broken progress bar. Clamp to 0 on parse fail
+ // or negative values (quota-refund scenarios should never flip to red).
+ const parsed = Number(data ?? 0)
+ const usedToday = Number.isFinite(parsed) ? Math.max(0, parsed) : 0
+
+ return {
+ email,
+ quota: {
+ usedToday,
+ dailyLimit: DAILY_USER_LIMIT,
+ resetAt: nextUtcMidnightIso(),
+ },
+ }
+}
diff --git a/apps/web/lib/fetchers.test.ts b/apps/web/lib/fetchers.test.ts
new file mode 100644
index 0000000..3613505
--- /dev/null
+++ b/apps/web/lib/fetchers.test.ts
@@ -0,0 +1,79 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { ApiError, fetchJson } from "./fetchers"
+
+describe("fetchJson", () => {
+ const originalFetch = global.fetch
+
+ beforeEach(() => {
+ global.fetch = vi.fn()
+ })
+
+ afterEach(() => {
+ global.fetch = originalFetch
+ })
+
+ function mockResponse(status: number, body: unknown, ok = status >= 200 && status < 300) {
+ return {
+ ok,
+ status,
+ statusText: `HTTP ${status}`,
+ json: async () => body,
+ } as Response
+ }
+
+ it("returns parsed body on 2xx", async () => {
+ vi.mocked(global.fetch).mockResolvedValueOnce(mockResponse(200, { hello: "world" }))
+ const data = await fetchJson<{ hello: string }>("/api/x")
+ expect(data).toEqual({ hello: "world" })
+ })
+
+ it("forwards same-origin credentials by default", async () => {
+ vi.mocked(global.fetch).mockResolvedValueOnce(mockResponse(200, {}))
+ await fetchJson("/api/x")
+ const init = vi.mocked(global.fetch).mock.calls[0]?.[1]
+ expect(init?.credentials).toBe("same-origin")
+ })
+
+ it("maps 401 with WireErrorBody to ApiError with code", async () => {
+ vi.mocked(global.fetch).mockResolvedValueOnce(
+ mockResponse(401, { error: "auth_required", message: "Sign in." }),
+ )
+ const err = await fetchJson("/api/x").catch((e) => e)
+ expect(err).toBeInstanceOf(ApiError)
+ expect((err as ApiError).status).toBe(401)
+ expect((err as ApiError).code).toBe("auth_required")
+ expect((err as ApiError).message).toBe("Sign in.")
+ })
+
+ it("maps 5xx without parsable body to a generic ApiError", async () => {
+ vi.mocked(global.fetch).mockResolvedValueOnce({
+ ok: false,
+ status: 503,
+ statusText: "Service Unavailable",
+ json: async () => {
+ throw new Error("not json")
+ },
+ } as unknown as Response)
+
+ const err = await fetchJson("/api/x").catch((e) => e)
+ expect(err).toBeInstanceOf(ApiError)
+ expect((err as ApiError).status).toBe(503)
+ expect((err as ApiError).code).toBe("http_503")
+ expect((err as ApiError).body).toBeNull()
+ })
+
+ it("preserves additional fields on WireErrorBody (quota_exceeded)", async () => {
+ vi.mocked(global.fetch).mockResolvedValueOnce(
+ mockResponse(429, {
+ error: "quota_exceeded",
+ message: "Daily cap hit.",
+ usedToday: 10,
+ dailyLimit: 10,
+ resetAt: "2026-04-18T00:00:00Z",
+ }),
+ )
+ const err = (await fetchJson("/api/x").catch((e) => e)) as ApiError
+ expect(err.body?.usedToday).toBe(10)
+ expect(err.body?.resetAt).toBe("2026-04-18T00:00:00Z")
+ })
+})
diff --git a/apps/web/lib/fetchers.ts b/apps/web/lib/fetchers.ts
new file mode 100644
index 0000000..27d52eb
--- /dev/null
+++ b/apps/web/lib/fetchers.ts
@@ -0,0 +1,53 @@
+import type { WireErrorBody } from "@workspace/shared/llm-wire"
+
+export class ApiError extends Error {
+ readonly status: number
+ readonly code: string
+ readonly body: WireErrorBody | null
+
+ constructor(status: number, code: string, message: string, body: WireErrorBody | null = null) {
+ super(message)
+ this.name = "ApiError"
+ this.status = status
+ this.code = code
+ this.body = body
+ }
+}
+
+// Web client fetcher. Same-origin → Better Auth cookies forward automatically,
+// so we don't need to plumb a bearer token. CLI path uses the shared
+// `fetchUsageToday` in packages/shared/src/llm.ts instead.
+export async function fetchJson(input: string, init?: RequestInit): Promise {
+ // Normalize headers so Headers instances and string[][] inputs don't get
+ // dropped by the object spread. Accept always ends up set unless the caller
+ // explicitly overrode it.
+ const merged = new Headers(init?.headers)
+ if (!merged.has("Accept")) merged.set("Accept", "application/json")
+
+ const res = await fetch(input, {
+ ...init,
+ credentials: "same-origin",
+ headers: merged,
+ })
+
+ if (!res.ok) {
+ let body: WireErrorBody | null = null
+ try {
+ body = (await res.json()) as WireErrorBody
+ } catch {
+ // non-JSON error body — fall through with null
+ }
+ throw new ApiError(
+ res.status,
+ body?.error ?? `http_${res.status}`,
+ body?.message ?? res.statusText ?? "Request failed",
+ body,
+ )
+ }
+
+ // 204 No Content (or any 2xx with empty body) would make res.json() throw
+ // a SyntaxError that bypasses ApiError. Short-circuit before the parse.
+ if (res.status === 204) return undefined as T
+
+ return (await res.json()) as T
+}
diff --git a/apps/web/lib/get-query-client.ts b/apps/web/lib/get-query-client.ts
new file mode 100644
index 0000000..6b0a222
--- /dev/null
+++ b/apps/web/lib/get-query-client.ts
@@ -0,0 +1,21 @@
+import { cache } from "react"
+import type { QueryClient } from "@tanstack/react-query"
+import { makeQueryClient } from "./query-client"
+
+// On the server, `cache()` gives us one fresh QueryClient per request —
+// no cross-request data leaks. On the client, we want a long-lived
+// singleton that survives route changes (otherwise Devtools disconnects
+// and in-flight queries get cancelled mid-navigation).
+let browserQueryClient: QueryClient | undefined
+
+export const getServerQueryClient = cache(() => makeQueryClient())
+
+export function getQueryClient(): QueryClient {
+ if (typeof window === "undefined") {
+ return getServerQueryClient()
+ }
+ if (!browserQueryClient) {
+ browserQueryClient = makeQueryClient()
+ }
+ return browserQueryClient
+}
diff --git a/apps/web/lib/query-client.ts b/apps/web/lib/query-client.ts
new file mode 100644
index 0000000..c17d609
--- /dev/null
+++ b/apps/web/lib/query-client.ts
@@ -0,0 +1,14 @@
+import { QueryClient } from "@tanstack/react-query"
+
+export function makeQueryClient(): QueryClient {
+ return new QueryClient({
+ defaultOptions: {
+ queries: {
+ staleTime: 60_000,
+ gcTime: 5 * 60_000,
+ refetchOnWindowFocus: false,
+ retry: 1,
+ },
+ },
+ })
+}
diff --git a/apps/web/lib/query-keys.test.ts b/apps/web/lib/query-keys.test.ts
new file mode 100644
index 0000000..268e911
--- /dev/null
+++ b/apps/web/lib/query-keys.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it } from "vitest"
+import { usageKeys, tenantKeys } from "./query-keys"
+
+// Query keys are the cache's primary index. Renaming any of these
+// silently breaks invalidation in every caller — so we snapshot them.
+describe("query-keys", () => {
+ describe("usageKeys", () => {
+ it("all is ['usage']", () => {
+ expect(usageKeys.all).toEqual(["usage"])
+ })
+
+ it("today is ['usage', 'today']", () => {
+ expect(usageKeys.today()).toEqual(["usage", "today"])
+ })
+
+ it("today() is a prefix of all (for invalidation)", () => {
+ const today = usageKeys.today()
+ expect(today.slice(0, usageKeys.all.length)).toEqual(Array.from(usageKeys.all))
+ })
+ })
+
+ describe("tenantKeys", () => {
+ it("all is ['tenants']", () => {
+ expect(tenantKeys.all).toEqual(["tenants"])
+ })
+
+ it("mine is ['tenants', 'mine']", () => {
+ expect(tenantKeys.mine()).toEqual(["tenants", "mine"])
+ })
+
+ it("details is ['tenants', 'detail']", () => {
+ expect(tenantKeys.details()).toEqual(["tenants", "detail"])
+ })
+
+ it("detail(id) includes id", () => {
+ expect(tenantKeys.detail("abc-123")).toEqual(["tenants", "detail", "abc-123"])
+ })
+
+ it("detail(id) is under details()", () => {
+ const detail = tenantKeys.detail("x")
+ const details = tenantKeys.details()
+ expect(detail.slice(0, details.length)).toEqual(Array.from(details))
+ })
+
+ it("different ids produce different keys", () => {
+ expect(tenantKeys.detail("a")).not.toEqual(tenantKeys.detail("b"))
+ })
+ })
+})
diff --git a/apps/web/lib/query-keys.ts b/apps/web/lib/query-keys.ts
new file mode 100644
index 0000000..a50d2fc
--- /dev/null
+++ b/apps/web/lib/query-keys.ts
@@ -0,0 +1,17 @@
+// Query key factories. Hierarchical so invalidation can target a
+// single entity or a whole family:
+// invalidateQueries({ queryKey: tenantKeys.all }) → everything
+// invalidateQueries({ queryKey: tenantKeys.detail(5) }) → one tenant
+// Matches the qk-factory-pattern rule in .claude/skills/tanstack-query-best-practices.
+
+export const usageKeys = {
+ all: ["usage"] as const,
+ today: () => [...usageKeys.all, "today"] as const,
+}
+
+export const tenantKeys = {
+ all: ["tenants"] as const,
+ mine: () => [...tenantKeys.all, "mine"] as const,
+ details: () => [...tenantKeys.all, "detail"] as const,
+ detail: (id: string) => [...tenantKeys.details(), id] as const,
+}
diff --git a/apps/web/lib/query-options.ts b/apps/web/lib/query-options.ts
new file mode 100644
index 0000000..99f830e
--- /dev/null
+++ b/apps/web/lib/query-options.ts
@@ -0,0 +1,31 @@
+import { queryOptions } from "@tanstack/react-query"
+import type { UsageTodayResponse } from "@workspace/shared/llm-wire"
+import { fetchJson } from "./fetchers"
+import { usageKeys, tenantKeys } from "./query-keys"
+
+export interface TenantSummary {
+ id: string
+ slug: string
+ name: string | null
+}
+
+export interface MyTenantsResponse {
+ tenants: TenantSummary[]
+}
+
+export function usageTodayOptions() {
+ return queryOptions({
+ queryKey: usageKeys.today(),
+ queryFn: () => fetchJson("/api/v1/usage/today"),
+ // Quota ticks up as the user issues LLM calls — keep it a bit fresher
+ // than the QueryClient-level default.
+ staleTime: 30_000,
+ })
+}
+
+export function myTenantsOptions() {
+ return queryOptions({
+ queryKey: tenantKeys.mine(),
+ queryFn: () => fetchJson("/api/v1/tenants/mine"),
+ })
+}
diff --git a/apps/web/package.json b/apps/web/package.json
index 7ac201c..d8bbba7 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -21,6 +21,7 @@
"@modelcontextprotocol/sdk": "^1.29.0",
"@react-email/components": "^1.0.12",
"@supabase/supabase-js": "^2.103.0",
+ "@tanstack/react-query": "^5.99.0",
"@vercel/kv": "^3.0.0",
"@workspace/shared": "workspace:*",
"@workspace/ui": "workspace:*",
@@ -45,6 +46,7 @@
"@react-email/ui": "6.0.0",
"@tailwindcss/postcss": "^4.1.18",
"@tailwindcss/typography": "^0.5.19",
+ "@tanstack/react-query-devtools": "^5.99.0",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
"@testing-library/user-event": "^14.6.1",
diff --git a/packages/cli/src/lib/banner.ts b/packages/cli/src/lib/banner.ts
new file mode 100644
index 0000000..bd75b3c
--- /dev/null
+++ b/packages/cli/src/lib/banner.ts
@@ -0,0 +1,46 @@
+import { canColor, isJsonMode, isQuiet } from "./tty.js"
+
+/**
+ * ANSI-Shadow rendering of "HELPBASE" with a top-to-bottom grayscale gradient.
+ *
+ * Each line is 64 display columns. Skip when the terminal is narrower so we
+ * don't wrap into garbage, and skip under --json/--quiet so composable output
+ * stays clean. Without color (NO_COLOR, piped stdout) we emit the glyphs
+ * without SGR so the shape still comes through.
+ */
+
+const LOGO_LINES = [
+ "██╗ ██╗███████╗██╗ ██████╗ ██████╗ █████╗ ███████╗███████╗",
+ "██║ ██║██╔════╝██║ ██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔════╝",
+ "███████║█████╗ ██║ ██████╔╝██████╔╝███████║███████╗█████╗ ",
+ "██╔══██║██╔══╝ ██║ ██╔═══╝ ██╔══██╗██╔══██║╚════██║██╔══╝ ",
+ "██║ ██║███████╗███████╗██║ ██████╔╝██║ ██║███████║███████╗",
+ "╚═╝ ╚═╝╚══════╝╚══════╝╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚══════╝",
+]
+
+const LOGO_WIDTH = 64
+
+// 256-color grays, lightest at top. Readable on both light and dark terminals.
+const GRAYS = [
+ "\x1b[38;5;250m",
+ "\x1b[38;5;248m",
+ "\x1b[38;5;245m",
+ "\x1b[38;5;243m",
+ "\x1b[38;5;240m",
+ "\x1b[38;5;238m",
+]
+const RESET = "\x1b[0m"
+
+export function renderBanner(): string {
+ if (isJsonMode() || isQuiet()) return ""
+ // Stdout is reserved for composable output (JSON, URLs, paths). When
+ // not a TTY, we're being piped into `grep` / a completion generator /
+ // another process — escape sequences AND decorative glyphs break the
+ // downstream parse. isTTY is undefined in non-TTY envs (not false), so
+ // coerce explicitly.
+ if (!process.stdout.isTTY) return ""
+ const cols = process.stdout.columns ?? 80
+ if (cols < LOGO_WIDTH + 2) return ""
+ if (!canColor()) return LOGO_LINES.join("\n") + "\n"
+ return LOGO_LINES.map((line, i) => `${GRAYS[i]}${line}${RESET}`).join("\n") + "\n"
+}
diff --git a/packages/cli/src/lib/help.ts b/packages/cli/src/lib/help.ts
index 9a00ae6..6f2364a 100644
--- a/packages/cli/src/lib/help.ts
+++ b/packages/cli/src/lib/help.ts
@@ -1,5 +1,6 @@
import type { Command } from "commander"
import pc from "picocolors"
+import { renderBanner } from "./banner.js"
/**
* Grouped `--help` rendering.
@@ -47,6 +48,14 @@ export function renderGroupedHelp(program: Command): string {
const seen = new Set()
const lines: string[] = []
+ // Banner (suppressed under --json/--quiet and on narrow terminals).
+ const banner = renderBanner()
+ if (banner) {
+ lines.push("")
+ lines.push(banner.replace(/\n$/, ""))
+ lines.push("")
+ }
+
// Synopsis + description
lines.push(`${pc.bold("helpbase")} ${pc.dim(`v${program.version() ?? ""}`)}`)
lines.push(program.description() ?? "")
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c6cbc69..743384e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -44,6 +44,9 @@ importers:
'@supabase/supabase-js':
specifier: ^2.103.0
version: 2.103.0
+ '@tanstack/react-query':
+ specifier: ^5.99.0
+ version: 5.99.0(react@19.2.4)
'@vercel/kv':
specifier: ^3.0.0
version: 3.0.0
@@ -111,6 +114,9 @@ importers:
'@tailwindcss/typography':
specifier: ^0.5.19
version: 0.5.19(tailwindcss@4.1.18)
+ '@tanstack/react-query-devtools':
+ specifier: ^5.99.0
+ version: 5.99.0(@tanstack/react-query@5.99.0(react@19.2.4))(react@19.2.4)
'@testing-library/jest-dom':
specifier: ^6.9.1
version: 6.9.1
@@ -2945,6 +2951,23 @@ packages:
peerDependencies:
tailwindcss: '>=3.0.0 || insiders || >=4.0.0-alpha.20 || >=4.0.0-beta.1'
+ '@tanstack/query-core@5.99.0':
+ resolution: {integrity: sha512-3Jv3WQG0BCcH7G+7lf/bP8QyBfJOXeY+T08Rin3GZ1bshvwlbPt7NrDHMEzGdKIOmOzvIQmxjk28YEQX60k7pQ==}
+
+ '@tanstack/query-devtools@5.99.0':
+ resolution: {integrity: sha512-m4ufXaJ8FjWXw7xDtyzE/6fkZAyQFg9WrbMrUpt8ZecRJx58jiFOZ2lxZMphZdIpAnIeto/S8stbwLKLusyckQ==}
+
+ '@tanstack/react-query-devtools@5.99.0':
+ resolution: {integrity: sha512-CqqX7LCU9yOfCY/vBURSx2YSD83ryfX+QkfkaKionTfg1s2Hdm572Ro99gW3QPoJjzvsj1HM4pnN4nbDy3MXKA==}
+ peerDependencies:
+ '@tanstack/react-query': ^5.99.0
+ react: ^18 || ^19
+
+ '@tanstack/react-query@5.99.0':
+ resolution: {integrity: sha512-OY2bCqPemT1LlqJ8Y2CUau4KELnIhhG9Ol3ZndPbdnB095pRbPo1cHuXTndg8iIwtoHTgwZjyaDnQ0xD0mYwAw==}
+ peerDependencies:
+ react: ^18 || ^19
+
'@testing-library/dom@10.4.1':
resolution: {integrity: sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==}
engines: {node: '>=18'}
@@ -9715,6 +9738,21 @@ snapshots:
postcss-selector-parser: 6.0.10
tailwindcss: 4.1.18
+ '@tanstack/query-core@5.99.0': {}
+
+ '@tanstack/query-devtools@5.99.0': {}
+
+ '@tanstack/react-query-devtools@5.99.0(@tanstack/react-query@5.99.0(react@19.2.4))(react@19.2.4)':
+ dependencies:
+ '@tanstack/query-devtools': 5.99.0
+ '@tanstack/react-query': 5.99.0(react@19.2.4)
+ react: 19.2.4
+
+ '@tanstack/react-query@5.99.0(react@19.2.4)':
+ dependencies:
+ '@tanstack/query-core': 5.99.0
+ react: 19.2.4
+
'@testing-library/dom@10.4.1':
dependencies:
'@babel/code-frame': 7.29.0
diff --git a/registry/helpbase/components/tenant-search-trigger.tsx b/registry/helpbase/components/tenant-search-trigger.tsx
deleted file mode 100644
index 50a53ea..0000000
--- a/registry/helpbase/components/tenant-search-trigger.tsx
+++ /dev/null
@@ -1,57 +0,0 @@
-"use client"
-
-/**
- * Search trigger button for tenant subdomains.
- *
- * Visually matches the apex SearchTrigger inlined in components/header.tsx
- * but is its own component so the tenant layout (server component) can
- * mount it without pulling in the whole apex header's theme-toggle and
- * nav logic, which belong to helpbase.dev itself, not tenant pages.
- *
- * The ⌘K shortcut is owned by SearchDialog's global keydown listener;
- * this button just simulates that keydown so mouse users get the same
- * effect as keyboard users.
- */
-export function TenantSearchTrigger() {
- return (
-
- )
-}
-
-function SearchIcon({ className }: { className?: string }) {
- return (
-
- )
-}
diff --git a/scripts/sync-templates.mjs b/scripts/sync-templates.mjs
index 016373d..7dafa4b 100644
--- a/scripts/sync-templates.mjs
+++ b/scripts/sync-templates.mjs
@@ -84,6 +84,23 @@ const HOSTED_TIER_EXCLUDES = [
"lib/waitlist.ts",
"lib/rate-limit.ts",
"components/tenant-search-trigger.tsx",
+ // Admin dashboard + TanStack Query foundation: hosted-tier only.
+ // The scaffolded docs site is pure SSR — it has no client server-state
+ // to manage and doesn't need to ship @tanstack/react-query.
+ "app/admin/",
+ "components/providers/",
+ "hooks/use-usage-today.ts",
+ "hooks/use-my-tenants.ts",
+ "hooks/use-usage-today.test.tsx",
+ "hooks/use-my-tenants.test.tsx",
+ "lib/data/",
+ "lib/fetchers.ts",
+ "lib/fetchers.test.ts",
+ "lib/query-client.ts",
+ "lib/get-query-client.ts",
+ "lib/query-keys.ts",
+ "lib/query-keys.test.ts",
+ "lib/query-options.ts",
]
// Import transform map. Each @workspace/* prefix maps to a local @/* path.
@@ -944,9 +961,13 @@ function syncRegistry() {
}
mkdirSync(REGISTRY, { recursive: true })
- // Copy components/ (all 8 component files)
+ // Copy components/ (all 8 component files). Filter mirrors the templates
+ // target's semantics (startsWith) so directory-prefix entries in
+ // HOSTED_TIER_EXCLUDES like "components/providers/" actually exclude.
const componentFiles = walkFiles(join(APPS_WEB, "components")).filter(
- (f) => !f.endsWith(".gitkeep"),
+ (f) =>
+ !f.endsWith(".gitkeep") &&
+ !HOSTED_TIER_EXCLUDES.some((p) => `components/${f}`.startsWith(p)),
)
for (const rel of componentFiles) {
copyAppsWebFileToRegistry(join("components", rel))
@@ -955,8 +976,12 @@ function syncRegistry() {
// Copy lib/ (apps/web lib files: content, search, toc, etc.)
// Excludes hosted-tier files (tenant-content, hosted-mdx-components, supabase).
+ // startsWith matches both exact file entries ("lib/auth.ts") and directory
+ // entries ("lib/data/").
const libFiles = walkFiles(join(APPS_WEB, "lib")).filter(
- (f) => !f.endsWith(".gitkeep") && !HOSTED_TIER_EXCLUDES.includes(`lib/${f}`),
+ (f) =>
+ !f.endsWith(".gitkeep") &&
+ !HOSTED_TIER_EXCLUDES.some((p) => `lib/${f}`.startsWith(p)),
)
for (const rel of libFiles) {
copyAppsWebFileToRegistry(join("lib", rel))