Skip to content

feat(web): TanStack Query v5 foundation + /admin/usage SSR demo - #7

Merged
Codehagen merged 8 commits into
mainfrom
feat/tanstack-query-foundation
Apr 17, 2026
Merged

Codehagen merged 8 commits into
mainfrom
feat/tanstack-query-foundation

Conversation

@Codehagen

@Codehagen Codehagen commented Apr 17, 2026 •

Copy link
Copy Markdown
Owner

Summary

Sets up TanStack Query v5 in apps/web so the forthcoming tenant/usage admin UI can do useQuery(someOptions()) on day one — correct cache keys, staleTime, devtools, error flow. Plus a live SSR demo at /admin/usage proving the hydration pattern works end-to-end.

What ships:

  • Provider infrastructure — lib/query-client.ts (makeQueryClient() factory), lib/get-query-client.ts (server cache() per request / client singleton), components/providers/query-provider.tsx (with dev-only Devtools via next/dynamic so they tree-shake from prod)
  • Query key + options factories — lib/query-keys.ts and lib/query-options.ts. Hierarchical keys (usageKeys, tenantKeys) enable precise invalidation; queryOptions() wrappers share config between client hooks and future server prefetches
  • Typed fetcher — lib/fetchers.ts with ApiError that maps the WireErrorBody shape from @workspace/shared/llm-wire
  • Data layer extraction — lib/data/usage.ts with getUsageTodayForUser(). /api/v1/usage/today now delegates to this so both the CLI (HTTP) and future server components (direct call) share one source of truth. Wire shape unchanged.
  • First hooks — useUsageToday, useMyTenants
  • SSR demo — /admin/usage uses setQueryData(key, data, { updatedAt: Date.now() }) + <HydrationBoundary> + client useSuspenseQuery. Zero content flash, no client refetch on mount.
  • CLI banner — unrelated to TanStack Query but bundled in this PR. helpbase --help now shows a gradient ANSI-Shadow logo, gated on process.stdout.isTTY so piped output stays clean.

Decisions locked during planning:

  • refetchOnWindowFocus: false (admin UI doesn't need real-time freshness; avoids thundering herds)
  • setQueryData over prefetchQuery for server seeding (avoids self-HTTP; shared-queryFn possible only with more abstraction — revisit if needed)
  • Better Auth's authClient.useSession() stays untouched — wrapping it in TanStack Query would duplicate state and regress the phase-reducer tests

Test Coverage

  • 24 new tests across 7 files — query-keys snapshots, fetcher error mapping (2xx/4xx/5xx), hook integration (happy + 401 + empty), data-layer Supabase RPC mocks, admin layout auth-gate (null/missing-id/valid-session), UsageCard seeded-cache rendering + progress-bar math
  • Suite: 116 passed, 0 failed (92 existing + 24 new)
  • Typecheck clean, next build clean (/admin/usage correctly emitted as ƒ dynamic)

Pre-Landing Review

Ran /review (Claude adversarial subagent) on the full 6-commit diff. Surfaced 11 findings, all resolved before push (commit 4a0630f):

Three P1 fixes — genuine production failure modes:

  1. lib/query-client.ts — dropped shouldDehydrateQuery override that included pending queries. Pattern only applies to streaming SSR with prefetchQuery; with our setQueryData approach it would ship unresolvable promises.
  2. app/admin/usage/page.tsx — added { updatedAt: Date.now() } to setQueryData. Without it, the hydrated entry has dataUpdatedAt=0 and useSuspenseQuery refetches on mount, defeating the whole SSR seed.
  3. app/admin/error.tsx (new) — route-level error boundary. Without it, any Supabase blip escapes useSuspenseQuery to the root error page and takes the admin chrome down.

Five P2 fixes: Number-parse validation in usage data layer, pct clamp + suppressHydrationWarning on date, dynamic = "force-dynamic" on admin routes, email fallback, CLI banner isTTY gate.

Three INVESTIGATE items skipped as scope creep (devtools strict-mode flakiness, server QueryClient gcTime timer theoretical concern, fetcher request-id capture).

Architecture

Server:  cache(makeQueryClient) → one QueryClient per request
Client:  module-level singleton  → survives route changes

Provider tree:
  RootLayout (server)
   └─ <ThemeProvider>
       └─ <QueryProvider>
           └─ children

SSR flow (/admin/usage):
  getSession → getUsageTodayForUser() → setQueryData(key, data, {updatedAt})
    → <HydrationBoundary state={dehydrate(queryClient)}>
        → <UsageCard /> uses useSuspenseQuery → cache hit, no network

NOT in scope (captured for later)

  • Persistence / offline support
  • Mutations + optimistic updates (no POST/PATCH/DELETE consumers yet)
  • Migration of authClient.useSession() to TanStack Query

Test plan

  • pnpm --filter web test — 116/116 pass
  • pnpm --filter web typecheck — clean
  • pnpm --filter web build — clean, /admin/usage shows as ƒ (dynamic)
  • Manual: visit /admin/usage signed in — quota card renders on first paint, no flash
  • Manual: visit /admin/usage signed out — redirects to /device
  • Manual: helpbase --help shows banner; helpbase --help | cat does not

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added admin dashboard with authentication protection for authorized users.
    • Introduced usage tracking page displaying quota usage, daily limits, and reset times with visual progress indicator.
    • Added error handling for admin routes with recovery options.
  • Removals

    • Removed search trigger from tenant interface.

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.
@vercel

vercel Bot commented Apr 17, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
helpbase Ready Ready Preview, Comment Apr 17, 2026 8:47pm

Request Review

@coderabbitai

coderabbitai Bot commented Apr 17, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Codehagen has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 50 minutes and 27 seconds before requesting another review.

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 1b9d1010-db3a-4e3f-bd95-98a5a92910e9

📥 Commits

Reviewing files that changed from the base of the PR and between 4446493 and 5723dfb.

📒 Files selected for processing (7)
  • apps/web/app/admin/layout.test.tsx
  • apps/web/app/admin/usage/usage-card.test.tsx
  • apps/web/app/admin/usage/usage-card.tsx
  • apps/web/app/api/v1/usage/today/route.ts
  • apps/web/hooks/use-usage-today.test.tsx
  • apps/web/lib/data/usage.ts
  • apps/web/lib/fetchers.ts
📝 Walkthrough

Walkthrough

This PR introduces a hosted-tier admin dashboard with usage tracking. It includes server-side authentication for /admin/* routes, a React Query-based usage page with server-side data prefetching and client-side hydration, supporting infrastructure (query keys, options, fetchers, hooks), comprehensive tests, and updates to the build-time sync script to exclude admin-only features from the open-source registry.

Changes

Cohort / File(s) Summary
Admin Layout & Error Boundary
apps/web/app/admin/error.tsx, apps/web/app/admin/layout.tsx, apps/web/app/admin/layout.test.tsx
New server-side admin layout enforcing force-dynamic rendering and session-based authentication, redirecting unauthenticated users to /device. Renders admin chrome with header and main content area wrapped in QueryProvider. Client-side error boundary component handles and displays admin-route errors with optional digest and retry button. Layout tests verify auth checks and redirect behavior.
Admin Usage Page & Components
apps/web/app/admin/usage/page.tsx, apps/web/app/admin/usage/usage-card.tsx, apps/web/app/admin/usage/usage-card.test.tsx, apps/web/app/admin/usage/loading.tsx
New async usage page with server-side session validation and React Query data prefetch, returning hydrated boundary for client-side UsageCard with suspend fallback. UsageCard client component uses useSuspenseQuery to display email, quota metrics, progress bar, and reset timestamp. Loading skeleton provides visual placeholder during data fetch. Tests verify data rendering and progress bar computation.
React Query Infrastructure
apps/web/lib/query-client.ts, apps/web/lib/get-query-client.ts, apps/web/components/providers/query-provider.tsx, apps/web/lib/query-keys.ts, apps/web/lib/query-keys.test.ts, apps/web/lib/query-options.ts
New Query client factory with server-side caching and browser-side singleton pattern. Query key and options factories for usage and tenants endpoints. QueryProvider component wires client to tree and conditionally loads React Query Devtools in non-production. Tests validate key structure and option configurations.
React Query Hooks
apps/web/hooks/use-usage-today.ts, apps/web/hooks/use-usage-today.test.tsx, apps/web/hooks/use-my-tenants.ts, apps/web/hooks/use-my-tenants.test.tsx
New client hooks wrapping React Query useQuery for usage and tenant data. Tests mock fetch and validate loading states, data transforms, and error handling including error code preservation.
API Integration & Data Fetchers
apps/web/lib/fetchers.ts, apps/web/lib/fetchers.test.ts, apps/web/lib/data/usage.ts, apps/web/lib/data/usage.test.ts
New ApiError class and generic fetchJson utility handling JSON responses, error parsing, and credential-based requests. getUsageTodayForUser function calls Supabase RPC for token usage with error propagation and fallback to zero. Tests validate error mapping, body preservation, and Supabase RPC behavior.
API Route Refactor
apps/web/app/api/v1/usage/today/route.ts
Refactored endpoint to delegate usage fetching to getUsageTodayForUser, wrapping call in error handling that converts Supabase unavailability to 503. Updated comment noting server-side usage prefetch by admin page.
CLI & Package Configuration
packages/cli/src/lib/banner.ts, packages/cli/src/lib/help.ts, apps/web/package.json
New banner rendering function with terminal detection, color/width awareness, and output suppression in JSON/quiet modes. Integrated banner into CLI help output. Added React Query and Devtools dependencies.
Build & Monorepo Sync
scripts/sync-templates.mjs, registry/helpbase/components/tenant-search-trigger.tsx
Extended hosted-tier exclusions list to cover admin dashboard and query infrastructure, preventing syncing to open-source registry. Removed TenantSearchTrigger component from registry. Updated sync filtering to use directory-prefix matching for granular exclusions.

Sequence Diagram

sequenceDiagram
    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
Loading

Estimated Code Review Effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly Related PRs

Poem

🐰 A dashboard blooms with queries bright,
React Query keeps data tight,
From server cache to client hands,
Usage metrics, hydrated strands,
The admin realm now sees the light! ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The PR title clearly summarizes the main changes: introducing TanStack Query v5 foundation and an SSR demo at /admin/usage. It is concise, specific, and directly reflects the primary objectives.
Description check ✅ Passed The PR description is comprehensive and well-structured. It includes a detailed summary of changes, test coverage metrics (24 new tests, 116 passed), explicit decision justifications, architecture diagrams, and a test plan section. All major required information is present and complete.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/tanstack-query-foundation

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 \n before pushing avoids a double blank line given the surrounding lines.push("") separators.

One small nit: lines starts 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 first lines.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 against GRAYS/LOGO_LINES length drift.

GRAYS has exactly 6 entries to match the 6 logo lines today. If someone edits LOGO_LINES (e.g., adds a blank padding line or a tagline) without also extending GRAYS, GRAYS[i] becomes undefined and 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 on Function.prototype.name staying intact. It's fine for Vitest-on-source today, but will silently fail if QueryProvider is ever wrapped in memo/forwardRef/HOC (the wrapped type has no matching name). Consider importing QueryProvider and asserting out.type === QueryProvider for 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 in getUsageTodayForUser, 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 clamping usedToday to ≥ 0.

Number.isFinite guards against NaN/Infinity but 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 negative usedToday flows into the quota shape and can produce a negative progress bar and a remaining > dailyLimit in 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" assume en-US Intl formatting. If UsageCard uses toLocaleString() without an explicit locale, a CI runner with LANG=C or a small-ICU Node build can render "42000" and flake these tests. Consider pinning the locale in UsageCard (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 asserting ApiError instance directly.

Since fetchers.ts exports ApiError, asserting toBeInstanceOf(ApiError) (instead of Error) and accessing .status/.code via 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" with aria-valuenow/min/max, but no accessible name. Screen readers will announce the value without context. Consider aria-label="Daily usage" or aria-labelledby pointing 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-object HeadersInit.

RequestInit.headers can be Headers, string[][], or Record<string, string>. Spreading a Headers instance 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 via new 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

📥 Commits

Reviewing files that changed from the base of the PR and between da7433b and 4446493.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (27)
  • apps/web/app/admin/error.tsx
  • apps/web/app/admin/layout.test.tsx
  • apps/web/app/admin/layout.tsx
  • apps/web/app/admin/usage/loading.tsx
  • apps/web/app/admin/usage/page.tsx
  • apps/web/app/admin/usage/usage-card.test.tsx
  • apps/web/app/admin/usage/usage-card.tsx
  • apps/web/app/api/v1/usage/today/route.ts
  • apps/web/components/providers/query-provider.tsx
  • apps/web/hooks/use-my-tenants.test.tsx
  • apps/web/hooks/use-my-tenants.ts
  • apps/web/hooks/use-usage-today.test.tsx
  • apps/web/hooks/use-usage-today.ts
  • apps/web/lib/data/usage.test.ts
  • apps/web/lib/data/usage.ts
  • apps/web/lib/fetchers.test.ts
  • apps/web/lib/fetchers.ts
  • apps/web/lib/get-query-client.ts
  • apps/web/lib/query-client.ts
  • apps/web/lib/query-keys.test.ts
  • apps/web/lib/query-keys.ts
  • apps/web/lib/query-options.ts
  • apps/web/package.json
  • packages/cli/src/lib/banner.ts
  • packages/cli/src/lib/help.ts
  • registry/helpbase/components/tenant-search-trigger.tsx
  • scripts/sync-templates.mjs
💤 Files with no reviewable changes (1)
  • registry/helpbase/components/tenant-search-trigger.tsx

Comment thread apps/web/lib/fetchers.ts Resolved
Comment on lines +34 to +45
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"

@coderabbitai coderabbitai Bot Apr 17, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
rg -nP '\brenderBanner\s*\(' --type=ts

Repository: Codehagen/helpbase

Length of output: 200


🏁 Script executed:

cat -n packages/cli/src/lib/banner.ts

Repository: Codehagen/helpbase

Length of output: 2185


🏁 Script executed:

cat -n packages/cli/src/lib/help.ts | head -100

Repository: Codehagen/helpbase

Length of output: 4349


🏁 Script executed:

cat -n packages/cli/src/lib/tty.ts

Repository: 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:

  1. Rename to renderHelpBanner() to make the stdout-specific intent explicit, or
  2. Move the stdout gate to the help.ts call site and have renderBanner() 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.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@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.
@Codehagen
Codehagen merged commit e31c6b4 into main Apr 17, 2026
5 checks passed
@Codehagen
Codehagen deleted the feat/tanstack-query-foundation branch April 17, 2026 20:52

This branch was successfully deployed

1 active deployment
Preview — 5723dfb0 Deployed Apr 17, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant