From 119c5957d3b60664b211e27a9610e803b2edc6e6 Mon Sep 17 00:00:00 2001 From: meglerhagen Date: Fri, 17 Apr 2026 22:21:17 +0200 Subject: [PATCH 1/8] feat(web): wire TanStack Query provider into root layout MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds @tanstack/react-query@^5 + @tanstack/react-query-devtools (dev). New lib/query-client.ts exports makeQueryClient() with the project defaults (staleTime: 60s, gcTime: 5m, refetchOnWindowFocus: false, retry: 1). lib/get-query-client.ts implements the canonical Next.js App Router split — cache()-backed per-request client on the server, module-level singleton on the client. Provider is dev-only import via next/dynamic so devtools tree-shake out of prod. QueryProvider wraps inside ThemeProvider in app/layout.tsx so class- on-html happens before paint. --- apps/web/app/layout.tsx | 5 ++- .../components/providers/query-provider.tsx | 29 ++++++++++++++ apps/web/lib/get-query-client.ts | 21 ++++++++++ apps/web/lib/query-client.ts | 18 +++++++++ apps/web/package.json | 2 + pnpm-lock.yaml | 38 +++++++++++++++++++ 6 files changed, 112 insertions(+), 1 deletion(-) create mode 100644 apps/web/components/providers/query-provider.tsx create mode 100644 apps/web/lib/get-query-client.ts create mode 100644 apps/web/lib/query-client.ts diff --git a/apps/web/app/layout.tsx b/apps/web/app/layout.tsx index 047a9f1..f52e9b6 100644 --- a/apps/web/app/layout.tsx +++ b/apps/web/app/layout.tsx @@ -2,6 +2,7 @@ import { Geist, Geist_Mono } from "next/font/google" import "@workspace/ui/globals.css" import { ThemeProvider } from "@/components/theme-provider" +import { QueryProvider } from "@/components/providers/query-provider" import { cn } from "@workspace/ui/lib/utils" const geist = Geist({ subsets: ["latin"], variable: "--font-sans" }) @@ -29,7 +30,9 @@ export default function RootLayout({ > - {children} + + {children} + 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/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..d4f5be2 --- /dev/null +++ b/apps/web/lib/query-client.ts @@ -0,0 +1,18 @@ +import { QueryClient, defaultShouldDehydrateQuery } from "@tanstack/react-query" + +export function makeQueryClient(): QueryClient { + return new QueryClient({ + defaultOptions: { + queries: { + staleTime: 60_000, + gcTime: 5 * 60_000, + refetchOnWindowFocus: false, + retry: 1, + }, + dehydrate: { + shouldDehydrateQuery: (query) => + defaultShouldDehydrateQuery(query) || query.state.status === "pending", + }, + }, + }) +} 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/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 From 3f375f4d387b89188d352594da35d14377799c67 Mon Sep 17 00:00:00 2001 From: meglerhagen Date: Fri, 17 Apr 2026 22:21:55 +0200 Subject: [PATCH 2/8] feat(web): add fetchJson, query-key factories, queryOptions wrappers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit lib/fetchers.ts — fetchJson() with typed ApiError. Forwards same-origin cookies so Better Auth sessions flow automatically from client fetches. Error body parses WireErrorBody shape from @workspace/shared/llm-wire; error.code maps the server's wire code (auth_required, quota_exceeded, etc.) for hook consumers. lib/query-keys.ts — hierarchical factories for usage + tenants. Hierarchy lets callers invalidate precisely: tenantKeys.all invalidates every tenant-scoped query, tenantKeys.detail(id) only one. lib/query-options.ts — usageTodayOptions() and myTenantsOptions() wrap queryKey + queryFn + staleTime in one place so hooks and server prefetches share the same config. Tests snapshot every key shape (renaming would silently break cache invalidation across every caller) and assert 2xx/4xx/5xx fetcher paths. --- apps/web/lib/fetchers.test.ts | 79 +++++++++++++++++++++++++++++++++ apps/web/lib/fetchers.ts | 46 +++++++++++++++++++ apps/web/lib/query-keys.test.ts | 49 ++++++++++++++++++++ apps/web/lib/query-keys.ts | 17 +++++++ apps/web/lib/query-options.ts | 31 +++++++++++++ 5 files changed, 222 insertions(+) create mode 100644 apps/web/lib/fetchers.test.ts create mode 100644 apps/web/lib/fetchers.ts create mode 100644 apps/web/lib/query-keys.test.ts create mode 100644 apps/web/lib/query-keys.ts create mode 100644 apps/web/lib/query-options.ts 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..170d56f --- /dev/null +++ b/apps/web/lib/fetchers.ts @@ -0,0 +1,46 @@ +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 { + const res = await fetch(input, { + ...init, + credentials: "same-origin", + headers: { + Accept: "application/json", + ...(init?.headers ?? {}), + }, + }) + + 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, + ) + } + + return (await res.json()) as T +} 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"), + }) +} From bf2130fe8abdb6f1a37038519dbba53702c13bcf Mon Sep 17 00:00:00 2001 From: meglerhagen Date: Fri, 17 Apr 2026 22:22:08 +0200 Subject: [PATCH 3/8] feat(web): extract usage data layer, add useUsageToday + useMyTenants hooks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit lib/data/usage.ts — pure getUsageTodayForUser(userId, email) so the HTTP route (CLI consumers) and server-component prefetching can share the Supabase call without either self-requesting the API over HTTP or duplicating quota math. /api/v1/usage/today route refactored to delegate. Wire shape and CLI behavior unchanged. hooks/use-usage-today + hooks/use-my-tenants wrap useQuery around the queryOptions factories. First real consumers of TanStack Query in the project. --- apps/web/app/api/v1/usage/today/route.ts | 31 ++++--------- apps/web/hooks/use-my-tenants.test.tsx | 59 ++++++++++++++++++++++++ apps/web/hooks/use-my-tenants.ts | 8 ++++ apps/web/hooks/use-usage-today.test.tsx | 59 ++++++++++++++++++++++++ apps/web/hooks/use-usage-today.ts | 8 ++++ apps/web/lib/data/usage.test.ts | 42 +++++++++++++++++ apps/web/lib/data/usage.ts | 32 +++++++++++++ 7 files changed, 216 insertions(+), 23 deletions(-) create mode 100644 apps/web/hooks/use-my-tenants.test.tsx create mode 100644 apps/web/hooks/use-my-tenants.ts create mode 100644 apps/web/hooks/use-usage-today.test.tsx create mode 100644 apps/web/hooks/use-usage-today.ts create mode 100644 apps/web/lib/data/usage.test.ts create mode 100644 apps/web/lib/data/usage.ts diff --git a/apps/web/app/api/v1/usage/today/route.ts b/apps/web/app/api/v1/usage/today/route.ts index e0dd922..f32ecab 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,10 @@ 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 { 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/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..e9e3987 --- /dev/null +++ b/apps/web/hooks/use-usage-today.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 { 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(Error) + // ApiError shape (from lib/fetchers.ts) + expect((result.current.error as Error & { code?: string }).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..5b2b0c5 --- /dev/null +++ b/apps/web/lib/data/usage.ts @@ -0,0 +1,32 @@ +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}`) + } + + return { + email, + quota: { + usedToday: Number(data ?? 0), + dailyLimit: DAILY_USER_LIMIT, + resetAt: nextUtcMidnightIso(), + }, + } +} From a448f444610f5dc6acd00a7a2111347cdc22d337 Mon Sep 17 00:00:00 2001 From: meglerhagen Date: Fri, 17 Apr 2026 22:22:08 +0200 Subject: [PATCH 4/8] feat(web): add /admin/usage SSR demo page MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Server component at app/admin/usage/page.tsx demonstrates the TanStack Query SSR pattern for Next.js App Router: 1. auth-gate via Better Auth session cookie 2. call getUsageTodayForUser() directly (no self-HTTP) 3. setQueryData(usageKeys.today(), data) on the per-request client 4. 5. client uses useSuspenseQuery — zero content flash admin/layout.tsx auth-gates the shell and redirects to /device when unauthenticated. loading.tsx is the Suspense skeleton. This is the canonical pattern any future admin feature should follow. --- apps/web/app/admin/layout.test.tsx | 50 +++++++++++++++++ apps/web/app/admin/layout.tsx | 29 ++++++++++ apps/web/app/admin/usage/loading.tsx | 26 +++++++++ apps/web/app/admin/usage/page.tsx | 39 +++++++++++++ apps/web/app/admin/usage/usage-card.test.tsx | 58 ++++++++++++++++++++ apps/web/app/admin/usage/usage-card.tsx | 45 +++++++++++++++ 6 files changed, 247 insertions(+) create mode 100644 apps/web/app/admin/layout.test.tsx create mode 100644 apps/web/app/admin/layout.tsx create mode 100644 apps/web/app/admin/usage/loading.tsx create mode 100644 apps/web/app/admin/usage/page.tsx create mode 100644 apps/web/app/admin/usage/usage-card.test.tsx create mode 100644 apps/web/app/admin/usage/usage-card.tsx diff --git a/apps/web/app/admin/layout.test.tsx b/apps/web/app/admin/layout.test.tsx new file mode 100644 index 0000000..59f4cde --- /dev/null +++ b/apps/web/app/admin/layout.test.tsx @@ -0,0 +1,50 @@ +/* @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("renders layout with children when session exists", async () => { + vi.mocked(auth.api.getSession).mockResolvedValueOnce({ + user: { id: "u1", email: "me@example.com" }, + } as never) + const out = await AdminLayout({ children: null }) + expect(out).toBeDefined() + // The returned element is a plain React element — inspect the tree + // instead of rendering to DOM (requires Link/Suspense shims otherwise). + expect(out).toMatchObject({ + type: "div", + }) + }) +}) diff --git a/apps/web/app/admin/layout.tsx b/apps/web/app/admin/layout.tsx new file mode 100644 index 0000000..d70942b --- /dev/null +++ b/apps/web/app/admin/layout.tsx @@ -0,0 +1,29 @@ +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" + +// 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. +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..6ddadc6 --- /dev/null +++ b/apps/web/app/admin/usage/page.tsx @@ -0,0 +1,39 @@ +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 }, +} + +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. + // Client's useSuspenseQuery reads the seeded cache, sees fresh-within- + // staleTime, and never triggers queryFn — so no content flash. + const queryClient = getQueryClient() + const data = await getUsageTodayForUser(session.user.id, session.user.email ?? "") + queryClient.setQueryData(usageKeys.today(), data) + + 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..9c59ba4 --- /dev/null +++ b/apps/web/app/admin/usage/usage-card.test.tsx @@ -0,0 +1,58 @@ +/* @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)) + + expect(screen.getByText("Today\u2019s usage")).toBeInTheDocument() + expect(screen.getByText("founder@example.com")).toBeInTheDocument() + expect(screen.getByText("42,000")).toBeInTheDocument() + expect(screen.getByText("500,000")).toBeInTheDocument() + }) + + 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..c7d1834 --- /dev/null +++ b/apps/web/app/admin/usage/usage-card.tsx @@ -0,0 +1,45 @@ +"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 + const pct = dailyLimit > 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()} +

+
+ ) +} From 74094b39abca53624ed405c14cda51accb079f9c Mon Sep 17 00:00:00 2001 From: meglerhagen Date: Fri, 17 Apr 2026 22:22:13 +0200 Subject: [PATCH 5/8] feat(cli): add banner to --help output Unrelated to TanStack Query work but bundled into this PR. --- packages/cli/src/lib/banner.ts | 40 ++++++++++++++++++++++++++++++++++ packages/cli/src/lib/help.ts | 9 ++++++++ 2 files changed, 49 insertions(+) create mode 100644 packages/cli/src/lib/banner.ts diff --git a/packages/cli/src/lib/banner.ts b/packages/cli/src/lib/banner.ts new file mode 100644 index 0000000..6b0ebe5 --- /dev/null +++ b/packages/cli/src/lib/banner.ts @@ -0,0 +1,40 @@ +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 "" + 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() ?? "") From 4a0630f553f687e78f93cc5aa568d8eb4693f264 Mon Sep 17 00:00:00 2001 From: meglerhagen Date: Fri, 17 Apr 2026 22:28:07 +0200 Subject: [PATCH 6/8] fix: address pre-landing review findings (3 P1 + 5 P2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit P1 fixes — genuine production failure modes: - lib/query-client.ts: drop `shouldDehydrateQuery` override that includes pending queries. Pattern only applies to streaming SSR with prefetchQuery; with our setQueryData approach it would ship unresolvable promises to the client. - app/admin/usage/page.tsx: pass `{ updatedAt: Date.now() }` to setQueryData. Without it, the hydrated entry has dataUpdatedAt=0, useSuspenseQuery treats it as stale, and refetches on mount — defeating the whole point of SSR seeding. - app/admin/error.tsx (new): route-level error boundary under /admin. useSuspenseQuery throws to the nearest boundary; without this, any Supabase blip takes the admin chrome down with it. P2 fixes — correctness + hardening: - lib/data/usage.ts: validate Number() parse. Supabase returns bigint as string; Number("junk") is NaN and flows silently into the UI as width: NaN%. - app/admin/usage/usage-card.tsx: clamp pct to [0, 100] (negative usedToday from future quota refunds would break the bar). suppressHydrationWarning on toLocaleString() output (server and client locales differ). - app/admin/{layout,usage/page}.tsx: `export const dynamic = "force-dynamic"` as defensive barrier against future PPR/ISR. - app/admin/layout.tsx: `{session.user.email ?? session.user.id}` so the header never renders empty when email is missing. - packages/cli/src/lib/banner.ts: gate on process.stdout.isTTY. Stdout is reserved for composable output; piping --help into grep or a completion generator would otherwise see ANSI escapes and decorative glyphs in the buffer. 116 tests, typecheck, and next build all green after fixes. --- apps/web/app/admin/error.tsx | 36 +++++++++++++++++++++++++ apps/web/app/admin/layout.tsx | 7 ++++- apps/web/app/admin/usage/page.tsx | 12 ++++++--- apps/web/app/admin/usage/usage-card.tsx | 6 +++-- apps/web/lib/data/usage.ts | 8 +++++- apps/web/lib/query-client.ts | 6 +---- packages/cli/src/lib/banner.ts | 6 +++++ 7 files changed, 69 insertions(+), 12 deletions(-) create mode 100644 apps/web/app/admin/error.tsx 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.tsx b/apps/web/app/admin/layout.tsx index d70942b..2a10037 100644 --- a/apps/web/app/admin/layout.tsx +++ b/apps/web/app/admin/layout.tsx @@ -4,6 +4,9 @@ import { redirect } from "next/navigation" import type { ReactNode } from "react" import { auth } from "@/lib/auth" +// 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. @@ -20,7 +23,9 @@ export default async function AdminLayout({ children }: { children: ReactNode }) helpbase admin - {session.user.email} + + {session.user.email ?? session.user.id} +
{children}
diff --git a/apps/web/app/admin/usage/page.tsx b/apps/web/app/admin/usage/page.tsx index 6ddadc6..906281e 100644 --- a/apps/web/app/admin/usage/page.tsx +++ b/apps/web/app/admin/usage/page.tsx @@ -15,6 +15,11 @@ export const metadata: Metadata = { 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 @@ -23,11 +28,12 @@ export default async function UsagePage() { if (!session?.user?.id) redirect("/device") // Direct data-layer call + setQueryData avoids a self-HTTP round-trip. - // Client's useSuspenseQuery reads the seeded cache, sees fresh-within- - // staleTime, and never triggers queryFn — so no content flash. + // `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) + queryClient.setQueryData(usageKeys.today(), data, { updatedAt: Date.now() }) return ( diff --git a/apps/web/app/admin/usage/usage-card.tsx b/apps/web/app/admin/usage/usage-card.tsx index c7d1834..35e89dc 100644 --- a/apps/web/app/admin/usage/usage-card.tsx +++ b/apps/web/app/admin/usage/usage-card.tsx @@ -6,7 +6,9 @@ import { usageTodayOptions } from "@/lib/query-options" export function UsageCard() { const { data } = useSuspenseQuery(usageTodayOptions()) const { usedToday, dailyLimit, resetAt } = data.quota - const pct = dailyLimit > 0 ? Math.min(100, Math.round((usedToday / dailyLimit) * 100)) : 0 + // 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 (
@@ -37,7 +39,7 @@ export function UsageCard() { /> -

+

Resets at {new Date(resetAt).toLocaleString()}

diff --git a/apps/web/lib/data/usage.ts b/apps/web/lib/data/usage.ts index 5b2b0c5..b751e53 100644 --- a/apps/web/lib/data/usage.ts +++ b/apps/web/lib/data/usage.ts @@ -21,10 +21,16 @@ export async function getUsageTodayForUser( 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. + const parsed = Number(data ?? 0) + const usedToday = Number.isFinite(parsed) ? parsed : 0 + return { email, quota: { - usedToday: Number(data ?? 0), + usedToday, dailyLimit: DAILY_USER_LIMIT, resetAt: nextUtcMidnightIso(), }, diff --git a/apps/web/lib/query-client.ts b/apps/web/lib/query-client.ts index d4f5be2..c17d609 100644 --- a/apps/web/lib/query-client.ts +++ b/apps/web/lib/query-client.ts @@ -1,4 +1,4 @@ -import { QueryClient, defaultShouldDehydrateQuery } from "@tanstack/react-query" +import { QueryClient } from "@tanstack/react-query" export function makeQueryClient(): QueryClient { return new QueryClient({ @@ -9,10 +9,6 @@ export function makeQueryClient(): QueryClient { refetchOnWindowFocus: false, retry: 1, }, - dehydrate: { - shouldDehydrateQuery: (query) => - defaultShouldDehydrateQuery(query) || query.state.status === "pending", - }, }, }) } diff --git a/packages/cli/src/lib/banner.ts b/packages/cli/src/lib/banner.ts index 6b0ebe5..bd75b3c 100644 --- a/packages/cli/src/lib/banner.ts +++ b/packages/cli/src/lib/banner.ts @@ -33,6 +33,12 @@ 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" From 4446493198d9121ea0ff3ca7397e00fde83ac850 Mon Sep 17 00:00:00 2001 From: meglerhagen Date: Fri, 17 Apr 2026 22:36:42 +0200 Subject: [PATCH 7/8] fix(sync): scope TanStack Query + admin files to hosted tier only MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI drift gate failed because new files referenced @workspace/shared/llm-wire imports the scaffolder's transform map doesn't know. But the real fix is architectural, not a new transform entry: TanStack Query is a hosted-tier concern, not something the scaffolded docs site (pure SSR, no client server state) should ship. Changes: - Move QueryProvider from app/layout.tsx → app/admin/layout.tsx. Any future hosted-tier surface wraps its own QueryProvider the same way. Scaffolded docs site stays provider-free and @tanstack-free. - Add to HOSTED_TIER_EXCLUDES in scripts/sync-templates.mjs: app/admin/, components/providers/, hooks/use-usage-today.*, hooks/use-my-tenants.*, lib/data/, lib/fetchers.*, lib/query-client.ts, lib/get-query-client.ts, lib/query-keys.*, lib/query-options.ts - Fix registry filter semantics. syncRegistry's lib/components filters used array .includes() for exact-match, so directory-prefix entries like "lib/data/" didn't exclude anything. Changed to startsWith to match the templates target's behavior. Side effect: tenant-search-trigger.tsx (already in HOSTED_TIER_EXCLUDES) now correctly drops from the registry too — pre-existing leak, fixed as part of the consistency pass. - Update admin/layout.test.tsx's root-element assertion since the top element is now (a function component) not
. 116 tests green, typecheck clean, next build clean. --- apps/web/app/admin/layout.test.tsx | 6 +- apps/web/app/admin/layout.tsx | 35 +++++++----- apps/web/app/layout.tsx | 5 +- .../components/tenant-search-trigger.tsx | 57 ------------------- scripts/sync-templates.mjs | 31 +++++++++- 5 files changed, 54 insertions(+), 80 deletions(-) delete mode 100644 registry/helpbase/components/tenant-search-trigger.tsx diff --git a/apps/web/app/admin/layout.test.tsx b/apps/web/app/admin/layout.test.tsx index 59f4cde..beb007b 100644 --- a/apps/web/app/admin/layout.test.tsx +++ b/apps/web/app/admin/layout.test.tsx @@ -43,8 +43,8 @@ describe("AdminLayout", () => { expect(out).toBeDefined() // The returned element is a plain React element — inspect the tree // instead of rendering to DOM (requires Link/Suspense shims otherwise). - expect(out).toMatchObject({ - type: "div", - }) + // Root is , a function component. + expect(typeof out.type).toBe("function") + expect(out.type).toHaveProperty("name", "QueryProvider") }) }) diff --git a/apps/web/app/admin/layout.tsx b/apps/web/app/admin/layout.tsx index 2a10037..a4e80be 100644 --- a/apps/web/app/admin/layout.tsx +++ b/apps/web/app/admin/layout.tsx @@ -3,6 +3,7 @@ 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" @@ -10,6 +11,12 @@ 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) { @@ -17,18 +24,20 @@ export default async function AdminLayout({ children }: { children: ReactNode }) } return ( -
-
- -
-
{children}
-
+ +
+
+ +
+
{children}
+
+
) } diff --git a/apps/web/app/layout.tsx b/apps/web/app/layout.tsx index f52e9b6..047a9f1 100644 --- a/apps/web/app/layout.tsx +++ b/apps/web/app/layout.tsx @@ -2,7 +2,6 @@ import { Geist, Geist_Mono } from "next/font/google" import "@workspace/ui/globals.css" import { ThemeProvider } from "@/components/theme-provider" -import { QueryProvider } from "@/components/providers/query-provider" import { cn } from "@workspace/ui/lib/utils" const geist = Geist({ subsets: ["latin"], variable: "--font-sans" }) @@ -30,9 +29,7 @@ export default function RootLayout({ > - - {children} - + {children} 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)) From 5723dfb0125143ca336854b698cde183445be0db Mon Sep 17 00:00:00 2001 From: meglerhagen Date: Fri, 17 Apr 2026 22:46:14 +0200 Subject: [PATCH 8/8] fix: address CodeRabbit review on PR #7 (8 of 11 findings) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Actionable: - lib/fetchers.ts: guard 204 No Content before res.json() (would throw SyntaxError bypassing ApiError). Normalize init.headers via `new Headers()` so Headers instances and string[][] don't get silently dropped by the object spread. Nitpicks: - app/api/v1/usage/today/route.ts: log the underlying error with userId before returning 503, so a RPC-failure spike doesn't require guessing from request timing. - lib/data/usage.ts: clamp usedToday to Math.max(0, parsed) at the data layer. UsageCard already clamps, but enforcing at the source keeps the wire shape sane for any future consumer. - app/admin/usage/usage-card.tsx: add aria-label="Daily token usage" to the progressbar so screen readers announce context. - app/admin/usage/usage-card.test.tsx: assert on aria-valuenow instead of toLocaleString() output. Default Node locale differs between dev boxes and CI runners; "42,000" would fail on a de-DE runner that renders "42.000". - app/admin/layout.test.tsx: replace fragile `type.name` identity check with a behavioral assertion (redirect not called when session exists). Wrapping the shell in QueryProvider shouldn't break the test. - hooks/use-usage-today.test.tsx: assert `instanceof ApiError` directly with typed `status`/`code` access, dropping the `Error & { code?: string }` cast. Skipped (with reasons): - banner.ts:45 stdout TTY gate — CodeRabbit called this inconsistent with tty.ts's "decorative helpers gate on stderr" principle. False positive: tty.ts gates stderr because those helpers *write to stderr*. The banner writes to stdout (it's inside Commander's help output). Gating on the destination TTY is correct. Will reply on the PR. - help.ts leading blank line before banner — intentional separator. - banner.ts GRAYS/LOGO_LINES length-drift guard — same file, unlikely regression, not worth the extra code. 116 tests green, typecheck clean. --- apps/web/app/admin/layout.test.tsx | 13 +++++++------ apps/web/app/admin/usage/usage-card.test.tsx | 8 ++++++-- apps/web/app/admin/usage/usage-card.tsx | 1 + apps/web/app/api/v1/usage/today/route.ts | 9 ++++++++- apps/web/hooks/use-usage-today.test.tsx | 8 +++++--- apps/web/lib/data/usage.ts | 5 +++-- apps/web/lib/fetchers.ts | 15 +++++++++++---- 7 files changed, 41 insertions(+), 18 deletions(-) diff --git a/apps/web/app/admin/layout.test.tsx b/apps/web/app/admin/layout.test.tsx index beb007b..92fff1b 100644 --- a/apps/web/app/admin/layout.test.tsx +++ b/apps/web/app/admin/layout.test.tsx @@ -35,16 +35,17 @@ describe("AdminLayout", () => { await expect(AdminLayout({ children: null })).rejects.toThrow(/REDIRECT:\/device/) }) - it("renders layout with children when session exists", async () => { + 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() - // The returned element is a plain React element — inspect the tree - // instead of rendering to DOM (requires Link/Suspense shims otherwise). - // Root is , a function component. - expect(typeof out.type).toBe("function") - expect(out.type).toHaveProperty("name", "QueryProvider") + expect(redirect).not.toHaveBeenCalled() }) }) diff --git a/apps/web/app/admin/usage/usage-card.test.tsx b/apps/web/app/admin/usage/usage-card.test.tsx index 9c59ba4..168fe2d 100644 --- a/apps/web/app/admin/usage/usage-card.test.tsx +++ b/apps/web/app/admin/usage/usage-card.test.tsx @@ -34,10 +34,14 @@ describe("UsageCard", () => { 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() - expect(screen.getByText("42,000")).toBeInTheDocument() - expect(screen.getByText("500,000")).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", () => { diff --git a/apps/web/app/admin/usage/usage-card.tsx b/apps/web/app/admin/usage/usage-card.tsx index 35e89dc..137ee5b 100644 --- a/apps/web/app/admin/usage/usage-card.tsx +++ b/apps/web/app/admin/usage/usage-card.tsx @@ -33,6 +33,7 @@ export function UsageCard() { 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} diff --git a/apps/web/app/api/v1/usage/today/route.ts b/apps/web/app/api/v1/usage/today/route.ts index f32ecab..2cb35a2 100644 --- a/apps/web/app/api/v1/usage/today/route.ts +++ b/apps/web/app/api/v1/usage/today/route.ts @@ -24,7 +24,14 @@ export async function GET(req: NextRequest): Promise { try { const body = await getUsageTodayForUser(session.user.id, session.user.email ?? "") return NextResponse.json(body) - } catch { + } 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.") } } diff --git a/apps/web/hooks/use-usage-today.test.tsx b/apps/web/hooks/use-usage-today.test.tsx index e9e3987..5f62331 100644 --- a/apps/web/hooks/use-usage-today.test.tsx +++ b/apps/web/hooks/use-usage-today.test.tsx @@ -3,6 +3,7 @@ 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() { @@ -52,8 +53,9 @@ describe("useUsageToday", () => { const { result } = renderHook(() => useUsageToday(), { wrapper: makeWrapper() }) await waitFor(() => expect(result.current.isError).toBe(true)) - expect(result.current.error).toBeInstanceOf(Error) - // ApiError shape (from lib/fetchers.ts) - expect((result.current.error as Error & { code?: string }).code).toBe("auth_required") + 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/lib/data/usage.ts b/apps/web/lib/data/usage.ts index b751e53..213e4ba 100644 --- a/apps/web/lib/data/usage.ts +++ b/apps/web/lib/data/usage.ts @@ -23,9 +23,10 @@ export async function getUsageTodayForUser( // 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. + // 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) ? parsed : 0 + const usedToday = Number.isFinite(parsed) ? Math.max(0, parsed) : 0 return { email, diff --git a/apps/web/lib/fetchers.ts b/apps/web/lib/fetchers.ts index 170d56f..27d52eb 100644 --- a/apps/web/lib/fetchers.ts +++ b/apps/web/lib/fetchers.ts @@ -18,13 +18,16 @@ export class ApiError extends Error { // 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: { - Accept: "application/json", - ...(init?.headers ?? {}), - }, + headers: merged, }) if (!res.ok) { @@ -42,5 +45,9 @@ export async function fetchJson(input: string, init?: RequestInit): Promise