Repository navigation
feat(web): TanStack Query v5 foundation + /admin/usage SSR demo - #7
Conversation
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.
lib/fetchers.ts — fetchJson<T>() 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.
… hooks 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.
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. <HydrationBoundary state={dehydrate(queryClient)}>
5. client <UsageCard /> 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.
Unrelated to TanStack Query work but bundled into this PR.
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.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Warning Rate limit exceeded
Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 50 minutes and 27 seconds. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (7)
📝 WalkthroughWalkthroughThis PR introduces a hosted-tier admin dashboard with usage tracking. It includes server-side authentication for Changes
Sequence DiagramsequenceDiagram
participant Client
participant AdminLayout as Server:<br/>AdminLayout
participant Auth as auth.api
participant Supabase as Supabase RPC
participant QueryCache as React Query<br/>Cache
participant UsageCard as Client:<br/>UsageCard
Client->>AdminLayout: GET /admin/usage
AdminLayout->>Auth: getSession(headers)
Auth->>AdminLayout: Session + user.id
AdminLayout->>Supabase: get_user_tokens_today(user_id)
Supabase->>AdminLayout: token count
AdminLayout->>QueryCache: setQueryData(usageKeys.today(), data)
AdminLayout->>Client: HydrationBoundary + Suspense
Client->>UsageCard: Render (with cache pre-populated)
UsageCard->>QueryCache: useSuspenseQuery(usageKeys.today())
QueryCache->>UsageCard: Return cached data (no network)
UsageCard->>Client: Display usage metrics & progress bar
Estimated Code Review Effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly Related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
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 <QueryProvider> (a function component) not <div>. 116 tests green, typecheck clean, next build clean.
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (9)
packages/cli/src/lib/help.ts (1)
51-58: LGTM — banner insertion delegates suppression correctly.Gating is handled inside
renderBanner()(JSON/quiet/non-TTY/width), and stripping the trailing\nbefore pushing avoids a double blank line given the surroundinglines.push("")separators.One small nit:
linesstarts empty, so line 54 produces a leading blank line at the very top of the help output when the banner renders. If you'd prefer the banner to be flush with the top of the terminal, drop the firstlines.push(""):Optional tweak
if (banner) { - lines.push("") lines.push(banner.replace(/\n$/, "")) lines.push("") }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/cli/src/lib/help.ts` around lines 51 - 58, The banner insertion currently prepends an empty string before the banner which causes a leading blank line in the output; in the banner handling block around renderBanner() and the lines array, remove the initial lines.push("") so the banner is not preceded by a blank line (keep the trailing blank line after the banner if you still want separation from the rest of the help output).packages/cli/src/lib/banner.ts (1)
24-45: Guard againstGRAYS/LOGO_LINESlength drift.
GRAYShas exactly 6 entries to match the 6 logo lines today. If someone editsLOGO_LINES(e.g., adds a blank padding line or a tagline) without also extendingGRAYS,GRAYS[i]becomesundefinedand the output embeds the literal string"undefined"before each extra line rather than rendering uncolored. A cheap defense:Proposed fix
- if (!canColor()) return LOGO_LINES.join("\n") + "\n" - return LOGO_LINES.map((line, i) => `${GRAYS[i]}${line}${RESET}`).join("\n") + "\n" + if (!canColor()) return LOGO_LINES.join("\n") + "\n" + return ( + LOGO_LINES.map((line, i) => { + const color = GRAYS[i] ?? GRAYS[GRAYS.length - 1] + return `${color}${line}${RESET}` + }).join("\n") + "\n" + )🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/cli/src/lib/banner.ts` around lines 24 - 45, The mapping in renderBanner assumes GRAYS and LOGO_LINES are same length, which can lead to "undefined" output if LOGO_LINES grows; update the return that builds the colored lines to guard against length drift by using a safe color lookup (e.g., const color = GRAYS[i] ?? "" or color = GRAYS[Math.min(i, GRAYS.length - 1)]) and only append RESET when a color was applied, so replace the current LOGO_LINES.map((line, i) => `${GRAYS[i]}${line}${RESET}`) with a version that uses the safe color variable and conditional RESET to avoid embedding "undefined" when GRAYS is shorter than LOGO_LINES.apps/web/app/admin/layout.test.tsx (1)
42-49: Fragile identity check on the root element.Asserting
out.type.name === "QueryProvider"depends onFunction.prototype.namestaying intact. It's fine for Vitest-on-source today, but will silently fail ifQueryProvideris ever wrapped inmemo/forwardRef/HOC (the wrapped type has no matchingname). Consider importingQueryProviderand assertingout.type === QueryProviderfor a reference-equal check.Proposed fix
+import { QueryProvider } from "@/components/providers/query-provider" @@ - expect(typeof out.type).toBe("function") - expect(out.type).toHaveProperty("name", "QueryProvider") + expect(out.type).toBe(QueryProvider)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web/app/admin/layout.test.tsx` around lines 42 - 49, The test currently checks the root by inspecting out.type.name === "QueryProvider", which is fragile; instead import the actual QueryProvider component and assert reference equality: in the test that calls AdminLayout({ children: null }) (variable out) replace the typeof/out.type.name assertions with an import of QueryProvider and a strict equality assertion that out.type === QueryProvider to ensure the test still passes if the component is wrapped in memo/forwardRef/HOC.apps/web/app/api/v1/usage/today/route.ts (1)
24-29: Swallowed error loses diagnostic signal.
catch {}discards the underlying error (Supabase RPC failure, unexpected throw ingetUsageTodayForUser, etc.) and always maps to"Supabase is unavailable.". For a route that fails closed on DB errors, you'll want a log line to correlate 503s with the actual cause — otherwise this is effectively a black box in production.Proposed fix
- try { - const body = await getUsageTodayForUser(session.user.id, session.user.email ?? "") - return NextResponse.json(body) - } catch { - return wireError(503, "internal_error", "Supabase is unavailable.") - } + try { + const body = await getUsageTodayForUser(session.user.id, session.user.email ?? "") + return NextResponse.json(body) + } catch (err) { + console.error("[/api/v1/usage/today] getUsageTodayForUser failed", err) + return wireError(503, "internal_error", "Supabase is unavailable.") + }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web/app/api/v1/usage/today/route.ts` around lines 24 - 29, The catch block currently swallows errors; change it to catch the thrown error (e.g., catch (err)) and log the diagnostic details before returning the 503 via wireError. Specifically, in the route surrounding the call to getUsageTodayForUser(session.user.id, session.user.email ?? ""), capture the error object, emit a log line (console.error or the app logger) that includes context such as session.user.id and the error/stack, then return the existing wireError(503, "internal_error", "Supabase is unavailable.") to preserve behavior while retaining diagnostics.apps/web/lib/data/usage.ts (1)
27-28: Consider clampingusedTodayto ≥ 0.
Number.isFiniteguards againstNaN/Infinitybut still admits negative values (e.g., if the RPC ever returns a signed delta or a malformed bigint string that parses to a negative number). A negativeusedTodayflows into the quota shape and can produce a negative progress bar and aremaining > dailyLimitin downstream consumers.Proposed fix
- const parsed = Number(data ?? 0) - const usedToday = Number.isFinite(parsed) ? parsed : 0 + const parsed = Number(data ?? 0) + const usedToday = Number.isFinite(parsed) && parsed >= 0 ? parsed : 0🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web/lib/data/usage.ts` around lines 27 - 28, The current assignment lets negative numbers slip through: after parsing Number(data) (symbol parsed) and before assigning usedToday, clamp the value to be non-negative (e.g., set usedToday = Math.max(0, parsed) or equivalent) so downstream quota shapes never see negative usage; update the usedToday assignment in the same scope where parsed is computed to enforce usedToday >= 0.apps/web/app/admin/usage/usage-card.test.tsx (1)
39-40: Locale-dependent number assertions.
"42,000"/"500,000"assumeen-USIntl formatting. IfUsageCardusestoLocaleString()without an explicit locale, a CI runner withLANG=Cor a small-ICU Node build can render"42000"and flake these tests. Consider pinning the locale inUsageCard(e.g.toLocaleString("en-US")) or asserting on a locale-stable substring.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web/app/admin/usage/usage-card.test.tsx` around lines 39 - 40, Tests assume en-US number formatting which can flake on different locales; update the code that formats numbers in the UsageCard component to explicitly use a stable locale (e.g. call toLocaleString("en-US") or use new Intl.NumberFormat("en-US").format(...)) so the rendered strings match the test, or alternatively change the tests in usage-card.test.tsx to assert a locale-stable substring/regex (e.g. assert digits like /42000/ and /500000/ or use Number(...) comparisons) instead of exact "42,000"/"500,000" strings. Ensure you modify the UsageCard formatting call (or the two expect(...) assertions) so CI is not locale-dependent.apps/web/hooks/use-usage-today.test.tsx (1)
44-58: Consider assertingApiErrorinstance directly.Since
fetchers.tsexportsApiError, assertingtoBeInstanceOf(ApiError)(instead ofError) and accessing.status/.codevia the typed class would be a stronger, less cast-heavy check. Minor.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web/hooks/use-usage-today.test.tsx` around lines 44 - 58, Change the test to assert the specific ApiError class exported from fetchers.ts rather than a generic Error: import or reference ApiError and replace expect(result.current.error).toBeInstanceOf(Error) with expect(result.current.error).toBeInstanceOf(ApiError), then assert typed properties directly (e.g., expect((result.current.error as ApiError).status).toBe(401) and expect((result.current.error as ApiError).code).toBe("auth_required")) so useUsageToday test verifies error is an ApiError with correct status and code.apps/web/app/admin/usage/usage-card.tsx (1)
31-40: Consider adding an accessible name to the progressbar.The element has
role="progressbar"witharia-valuenow/min/max, but no accessible name. Screen readers will announce the value without context. Consideraria-label="Daily usage"oraria-labelledbypointing at the heading/"Used"<dt>.♿ Proposed tweak
<div className="h-full bg-primary transition-[width] duration-300" style={{ width: `${pct}%` }} role="progressbar" + aria-label="Daily token usage" aria-valuenow={pct} aria-valuemin={0} aria-valuemax={100} />🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web/app/admin/usage/usage-card.tsx` around lines 31 - 40, The progressbar div with role="progressbar" in the UsageCard component lacks an accessible name; update that element to include an accessible label by adding either aria-label (e.g., "Daily usage") or aria-labelledby that references the adjacent heading/Used <dt> element so screen readers get context; locate the div using the pct variable and the role="progressbar" attributes in usage-card.tsx and add the appropriate aria attribute.apps/web/lib/fetchers.ts (1)
24-27: Headers spread only works for plain-objectHeadersInit.
RequestInit.headerscan beHeaders,string[][], orRecord<string, string>. Spreading aHeadersinstance or tuple array via...(init?.headers ?? {})silently drops the headers. All current callers pass plain objects, so it's not a live bug, but worth narrowing the parameter type or normalizing vianew Headers(init?.headers)to prevent future footguns.🛡️ Optional hardening
- const res = await fetch(input, { - ...init, - credentials: "same-origin", - headers: { - Accept: "application/json", - ...(init?.headers ?? {}), - }, - }) + const headers = new Headers(init?.headers) + if (!headers.has("Accept")) headers.set("Accept", "application/json") + const res = await fetch(input, { + ...init, + credentials: "same-origin", + headers, + })🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web/lib/fetchers.ts` around lines 24 - 27, The headers spread currently uses ...(init?.headers ?? {}) which silently drops values if init.headers is a Headers instance or string[][]; change to normalize headers first (e.g., const normalized = Object.fromEntries(new Headers(init?.headers));) and then use headers: { Accept: "application/json", ...normalized } so all HeadersInit variants are preserved; update any relevant function signatures or typings (the local init variable / RequestInit parameter) if you prefer to narrow the accepted header type instead.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@apps/web/lib/fetchers.ts`:
- Line 45: The fetch helper returns (await res.json()) as T which will throw on
empty/204 responses; update the fetchJson function to guard against no-body
responses by checking res.status === 204 (and optionally headers like
Content-Length === '0' or missing Content-Type) and return undefined as T in
that case before calling res.json(), preserving existing error-wrapping behavior
(ApiError) for non-OK responses.
In `@packages/cli/src/lib/banner.ts`:
- Around line 34-45: renderBanner currently gates on stdout TTY while it calls
canColor (which checks stderr TTY), creating an inconsistency with other
decorative helpers; move the stdout TTY check out of renderBanner into its
caller renderGroupedHelp so renderBanner only follows the standard stderr-based
decoration gate (i.e., call canColor()/canDecorate() inside renderBanner and
remove the process.stdout.isTTY check), or alternatively rename renderBanner to
renderHelpBanner if you want to keep the stdout-specific behavior—prefer the
first approach: remove the stdout gate from renderBanner and enforce stdout-only
emission in renderGroupedHelp before calling renderBanner.
---
Nitpick comments:
In `@apps/web/app/admin/layout.test.tsx`:
- Around line 42-49: The test currently checks the root by inspecting
out.type.name === "QueryProvider", which is fragile; instead import the actual
QueryProvider component and assert reference equality: in the test that calls
AdminLayout({ children: null }) (variable out) replace the typeof/out.type.name
assertions with an import of QueryProvider and a strict equality assertion that
out.type === QueryProvider to ensure the test still passes if the component is
wrapped in memo/forwardRef/HOC.
In `@apps/web/app/admin/usage/usage-card.test.tsx`:
- Around line 39-40: Tests assume en-US number formatting which can flake on
different locales; update the code that formats numbers in the UsageCard
component to explicitly use a stable locale (e.g. call toLocaleString("en-US")
or use new Intl.NumberFormat("en-US").format(...)) so the rendered strings match
the test, or alternatively change the tests in usage-card.test.tsx to assert a
locale-stable substring/regex (e.g. assert digits like /42000/ and /500000/ or
use Number(...) comparisons) instead of exact "42,000"/"500,000" strings. Ensure
you modify the UsageCard formatting call (or the two expect(...) assertions) so
CI is not locale-dependent.
In `@apps/web/app/admin/usage/usage-card.tsx`:
- Around line 31-40: The progressbar div with role="progressbar" in the
UsageCard component lacks an accessible name; update that element to include an
accessible label by adding either aria-label (e.g., "Daily usage") or
aria-labelledby that references the adjacent heading/Used <dt> element so screen
readers get context; locate the div using the pct variable and the
role="progressbar" attributes in usage-card.tsx and add the appropriate aria
attribute.
In `@apps/web/app/api/v1/usage/today/route.ts`:
- Around line 24-29: The catch block currently swallows errors; change it to
catch the thrown error (e.g., catch (err)) and log the diagnostic details before
returning the 503 via wireError. Specifically, in the route surrounding the call
to getUsageTodayForUser(session.user.id, session.user.email ?? ""), capture the
error object, emit a log line (console.error or the app logger) that includes
context such as session.user.id and the error/stack, then return the existing
wireError(503, "internal_error", "Supabase is unavailable.") to preserve
behavior while retaining diagnostics.
In `@apps/web/hooks/use-usage-today.test.tsx`:
- Around line 44-58: Change the test to assert the specific ApiError class
exported from fetchers.ts rather than a generic Error: import or reference
ApiError and replace expect(result.current.error).toBeInstanceOf(Error) with
expect(result.current.error).toBeInstanceOf(ApiError), then assert typed
properties directly (e.g., expect((result.current.error as
ApiError).status).toBe(401) and expect((result.current.error as
ApiError).code).toBe("auth_required")) so useUsageToday test verifies error is
an ApiError with correct status and code.
In `@apps/web/lib/data/usage.ts`:
- Around line 27-28: The current assignment lets negative numbers slip through:
after parsing Number(data) (symbol parsed) and before assigning usedToday, clamp
the value to be non-negative (e.g., set usedToday = Math.max(0, parsed) or
equivalent) so downstream quota shapes never see negative usage; update the
usedToday assignment in the same scope where parsed is computed to enforce
usedToday >= 0.
In `@apps/web/lib/fetchers.ts`:
- Around line 24-27: The headers spread currently uses ...(init?.headers ?? {})
which silently drops values if init.headers is a Headers instance or string[][];
change to normalize headers first (e.g., const normalized =
Object.fromEntries(new Headers(init?.headers));) and then use headers: { Accept:
"application/json", ...normalized } so all HeadersInit variants are preserved;
update any relevant function signatures or typings (the local init variable /
RequestInit parameter) if you prefer to narrow the accepted header type instead.
In `@packages/cli/src/lib/banner.ts`:
- Around line 24-45: The mapping in renderBanner assumes GRAYS and LOGO_LINES
are same length, which can lead to "undefined" output if LOGO_LINES grows;
update the return that builds the colored lines to guard against length drift by
using a safe color lookup (e.g., const color = GRAYS[i] ?? "" or color =
GRAYS[Math.min(i, GRAYS.length - 1)]) and only append RESET when a color was
applied, so replace the current LOGO_LINES.map((line, i) =>
`${GRAYS[i]}${line}${RESET}`) with a version that uses the safe color variable
and conditional RESET to avoid embedding "undefined" when GRAYS is shorter than
LOGO_LINES.
In `@packages/cli/src/lib/help.ts`:
- Around line 51-58: The banner insertion currently prepends an empty string
before the banner which causes a leading blank line in the output; in the banner
handling block around renderBanner() and the lines array, remove the initial
lines.push("") so the banner is not preceded by a blank line (keep the trailing
blank line after the banner if you still want separation from the rest of the
help output).
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: b66b7076-b2f5-433a-a49f-7428d8d1d5f4
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (27)
apps/web/app/admin/error.tsxapps/web/app/admin/layout.test.tsxapps/web/app/admin/layout.tsxapps/web/app/admin/usage/loading.tsxapps/web/app/admin/usage/page.tsxapps/web/app/admin/usage/usage-card.test.tsxapps/web/app/admin/usage/usage-card.tsxapps/web/app/api/v1/usage/today/route.tsapps/web/components/providers/query-provider.tsxapps/web/hooks/use-my-tenants.test.tsxapps/web/hooks/use-my-tenants.tsapps/web/hooks/use-usage-today.test.tsxapps/web/hooks/use-usage-today.tsapps/web/lib/data/usage.test.tsapps/web/lib/data/usage.tsapps/web/lib/fetchers.test.tsapps/web/lib/fetchers.tsapps/web/lib/get-query-client.tsapps/web/lib/query-client.tsapps/web/lib/query-keys.test.tsapps/web/lib/query-keys.tsapps/web/lib/query-options.tsapps/web/package.jsonpackages/cli/src/lib/banner.tspackages/cli/src/lib/help.tsregistry/helpbase/components/tenant-search-trigger.tsxscripts/sync-templates.mjs
💤 Files with no reviewable changes (1)
- registry/helpbase/components/tenant-search-trigger.tsx
| 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" |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
rg -nP '\brenderBanner\s*\(' --type=tsRepository: Codehagen/helpbase
Length of output: 200
🏁 Script executed:
cat -n packages/cli/src/lib/banner.tsRepository: Codehagen/helpbase
Length of output: 2185
🏁 Script executed:
cat -n packages/cli/src/lib/help.ts | head -100Repository: Codehagen/helpbase
Length of output: 4349
🏁 Script executed:
cat -n packages/cli/src/lib/tty.tsRepository: Codehagen/helpbase
Length of output: 4138
The stdout TTY gate is intentional for help rendering but consider clarifying its scope for consistency.
The code's stdout gate is reasonable for its current use case: renderBanner() is only called in renderGroupedHelp() (help.ts:52), which returns text that Commander writes to stdout. However, this deviates from the broader pattern where all other decorative helpers (canColor(), canSpinner(), canDecorate()) gate on stderr TTY per the tty.ts design principle (lines 3-6): "stdout is reserved for composable output; stderr hosts everything else... Any call that produces decorative output MUST check the relevant gate here first."
Since renderBanner() imports and calls canColor() which itself checks isStderrTTY(), there's a subtle inconsistency: the outer guard uses stdout while the color decision uses stderr.
To improve clarity and maintainability, either:
- Rename to
renderHelpBanner()to make the stdout-specific intent explicit, or - Move the stdout gate to the
help.tscall site and haverenderBanner()gate on stderr like other decorations.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli/src/lib/banner.ts` around lines 34 - 45, renderBanner currently
gates on stdout TTY while it calls canColor (which checks stderr TTY), creating
an inconsistency with other decorative helpers; move the stdout TTY check out of
renderBanner into its caller renderGroupedHelp so renderBanner only follows the
standard stderr-based decoration gate (i.e., call canColor()/canDecorate()
inside renderBanner and remove the process.stdout.isTTY check), or alternatively
rename renderBanner to renderHelpBanner if you want to keep the stdout-specific
behavior—prefer the first approach: remove the stdout gate from renderBanner and
enforce stdout-only emission in renderGroupedHelp before calling renderBanner.
There was a problem hiding this comment.
Thanks for flagging, but I think this is a false positive worth explaining.
CodeRabbit claims: the process.stdout.isTTY gate deviates from the tty.ts principle that "all other decorative helpers gate on stderr TTY."
The actual tty.ts contract (lines 3–6):
stdout is reserved for composable output (JSON, URLs, paths, file contents). stderr hosts everything else: spinners, prompts, notes, next-step blocks, summary tables, update notices, error messages.
The stderr-TTY gates on canColor() / canSpinner() / canDecorate() exist because those helpers write to stderr. Gating on the destination stream’s TTY is the correct pairing.
The banner is different: it is inlined into renderGroupedHelp() and returned to Commander, which writes help output to stdout. I could move help to stderr (like gh, stripe) as a separate architectural change, but so long as the banner is part of stdout help output, process.stdout.isTTY is the only semantically-correct gate: when stdout is piped, isTTY is false, banner returns "", and composable output is preserved.
A stderr-TTY gate here would produce the wrong behavior: rendering the banner into piped stdout whenever someone has a TTY on stderr (which is ~always), breaking helpbase --help | grep / completion generators / any downstream parse.
Leaving as-is. Happy to revisit if help output moves to stderr.
There was a problem hiding this comment.
@Codehagen, you're absolutely right — this is a false positive on my part. The core principle in tty.ts is to gate on the destination stream's TTY, not to unconditionally use stderr's TTY. Since renderGroupedHelp() returns a string that Commander writes to stdout, process.stdout.isTTY is the only semantically correct gate here. A stderr-TTY check would defeat the purpose and silently corrupt piped output like helpbase --help | grep.
Thanks for the detailed explanation — I've noted this for future reviews.
(๑˃ᴗ˂)ว
✏️ Learnings added
Learnt from: Codehagen
Repo: Codehagen/helpbase PR: 7
File: packages/cli/src/lib/banner.ts:34-45
Timestamp: 2026-04-17T20:46:59.135Z
Learning: In `packages/cli/src/lib/banner.ts` (helpbase CLI, TypeScript), `renderBanner()` intentionally gates on `process.stdout.isTTY` — not stderr TTY — because the banner is inlined into `renderGroupedHelp()` which Commander writes to stdout. The tty.ts principle is to gate on the *destination stream's* TTY: stderr-based helpers (`canColor`, `canSpinner`, `canDecorate`) check stderr TTY because they write to stderr; stdout-bound decorations must check stdout TTY. Flagging the stdout TTY gate here as inconsistent with the tty.ts pattern is a false positive.
Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.
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.
Summary
Sets up TanStack Query v5 in
apps/webso the forthcoming tenant/usage admin UI can douseQuery(someOptions())on day one — correct cache keys, staleTime, devtools, error flow. Plus a live SSR demo at/admin/usageproving the hydration pattern works end-to-end.What ships:
lib/query-client.ts(makeQueryClient()factory),lib/get-query-client.ts(servercache()per request / client singleton),components/providers/query-provider.tsx(with dev-only Devtools vianext/dynamicso they tree-shake from prod)lib/query-keys.tsandlib/query-options.ts. Hierarchical keys (usageKeys,tenantKeys) enable precise invalidation;queryOptions()wrappers share config between client hooks and future server prefetcheslib/fetchers.tswithApiErrorthat maps theWireErrorBodyshape from@workspace/shared/llm-wirelib/data/usage.tswithgetUsageTodayForUser()./api/v1/usage/todaynow delegates to this so both the CLI (HTTP) and future server components (direct call) share one source of truth. Wire shape unchanged.useUsageToday,useMyTenants/admin/usageusessetQueryData(key, data, { updatedAt: Date.now() })+<HydrationBoundary>+ clientuseSuspenseQuery. Zero content flash, no client refetch on mount.helpbase --helpnow shows a gradient ANSI-Shadow logo, gated onprocess.stdout.isTTYso piped output stays clean.Decisions locked during planning:
refetchOnWindowFocus: false(admin UI doesn't need real-time freshness; avoids thundering herds)setQueryDataoverprefetchQueryfor server seeding (avoids self-HTTP; shared-queryFn possible only with more abstraction — revisit if needed)authClient.useSession()stays untouched — wrapping it in TanStack Query would duplicate state and regress the phase-reducer testsTest Coverage
next buildclean (/admin/usagecorrectly emitted as ƒ dynamic)Pre-Landing Review
Ran
/review(Claude adversarial subagent) on the full 6-commit diff. Surfaced 11 findings, all resolved before push (commit4a0630f):Three P1 fixes — genuine production failure modes:
lib/query-client.ts— droppedshouldDehydrateQueryoverride that includedpendingqueries. Pattern only applies to streaming SSR withprefetchQuery; with oursetQueryDataapproach it would ship unresolvable promises.app/admin/usage/page.tsx— added{ updatedAt: Date.now() }tosetQueryData. Without it, the hydrated entry hasdataUpdatedAt=0anduseSuspenseQueryrefetches on mount, defeating the whole SSR seed.app/admin/error.tsx(new) — route-level error boundary. Without it, any Supabase blip escapesuseSuspenseQueryto the root error page and takes the admin chrome down.Five P2 fixes: Number-parse validation in usage data layer, pct clamp +
suppressHydrationWarningon date,dynamic = "force-dynamic"on admin routes, email fallback, CLI bannerisTTYgate.Three INVESTIGATE items skipped as scope creep (devtools strict-mode flakiness, server QueryClient
gcTimetimer theoretical concern, fetcher request-id capture).Architecture
NOT in scope (captured for later)
authClient.useSession()to TanStack QueryTest plan
pnpm --filter web test— 116/116 passpnpm --filter web typecheck— cleanpnpm --filter web build— clean,/admin/usageshows as ƒ (dynamic)/admin/usagesigned in — quota card renders on first paint, no flash/admin/usagesigned out — redirects to/devicehelpbase --helpshows banner;helpbase --help | catdoes not🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Removals