Add a panel for observing the API requests #29
Create a panel for observing API requests in the demo app.
It was always possible to track them in the network panel, but because of some technical limitations, the requests intercepted by the service worker (= all the "API requests" could only appear there after they have been completed (no "PENDING" state).
Summary by CodeRabbit#
New Features
- Live API requests panel with real-time list, per-request details, pending indicators, and a clear action.
- Toggle to show/hide the API requests panel and persisted panel visibility.
- API latency simulator with preset options and persisted selection.
Documentation
- Added validating-your-code guidance, a dev-server warning, and coding style preferences.
Style
- Updated global typography and added a new slab font option.
Chores
- Added a placeholder user and adjusted resizable panel layout and header composition.
- 1
🚀 Preview Deployment#
Status: ✅ Ready!
Preview URL: Open Preview
Commit:
6ef72184a54803318d03e9162b11559020383050Built and deployed successfully
Actionable comments posted: 4
🧹 Nitpick comments (5)
src/components/ApiPanelToggle.tsx (1)
29-32: Consider defensive handling of missing user preferences.The
updatemethod assumes the user preferences record exists. If it doesn't exist yet, this could fail silently or throw an error.🔎 Proposed defensive check or upsert pattern
onClick={() => - userPreferencesCollection.update(USER_PLACEHOLDER.id, (draft) => { - draft.networkPanel = - draft.networkPanel === "open" ? "closed" : "open"; - }) + { + const exists = userPreferencesCollection.get(USER_PLACEHOLDER.id); + if (exists) { + userPreferencesCollection.update(USER_PLACEHOLDER.id, (draft) => { + draft.networkPanel = + draft.networkPanel === "open" ? "closed" : "open"; + }); + } else { + userPreferencesCollection.insert({ + id: USER_PLACEHOLDER.id, + networkPanel: "open" + }); + } + } }Alternatively, verify that the user preferences record is always initialized during app bootstrap (e.g., in
src/routes/_tutorial._db.tsx).src/components/ui/resizable.tsx (1)
40-40: Verifytext-backgroundis intentional for the resize handle.The class
text-backgroundsets the text color to the background color, which may hide any text content. This appears intentional for styling theGripVerticalIcon, but worth confirming.If this is meant to style the icon specifically, consider adding a comment explaining the color choice:
className={cn( - "bg-border text-background dark:text-current focus-visible:ring-ring relative flex w-px items-center justify-center after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:outline-hidden data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:translate-x-0 data-[panel-group-direction=vertical]:after:-translate-y-1/2 [&[data-panel-group-direction=vertical]>div]:rotate-90", + // Icon color matches theme: text-background in light mode, current color in dark mode + "bg-border text-background dark:text-current focus-visible:ring-ring relative flex w-px items-center justify-center after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:outline-hidden data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:translate-x-0 data-[panel-group-direction=vertical]:after:-translate-y-1/2 [&[data-panel-group-direction=vertical]>div]:rotate-90", className, )}src/routes/_tutorial._db.tsx (1)
26-36: Consider removing the redundant SSR guard.The
typeof window !== "undefined"check is unnecessary since the route already hasssr: false(line 13), ensuring this component only renders on the client.🔎 Proposed simplification
function RouteComponent() { useEffect(() => { - if (typeof window !== "undefined") { - const existingUser = userPreferencesCollection.get(USER_PLACEHOLDER.id); - - if (!existingUser) { - userPreferencesCollection.insert({ - id: USER_PLACEHOLDER.id, - }); - } + const existingUser = userPreferencesCollection.get(USER_PLACEHOLDER.id); + + if (!existingUser) { + userPreferencesCollection.insert({ + id: USER_PLACEHOLDER.id, + }); } }, []); return <Outlet />; }src/components/ApiRequestsPanel.tsx (1)
19-24: Await the delete operation or removeasync.The function is marked
asyncbut doesn't awaitapiRequestsCollection.delete(). This could swallow errors. Either await the operation or simplify by removingasync.🔎 Proposed fix
async function clearRequests() { const ids = (await apiRequestsCollection.toArrayWhenReady()).map( ({ id }) => id, ); - apiRequestsCollection.delete(ids); + await apiRequestsCollection.delete(ids); }src/routes/_tutorial._db.projects.tsx (1)
44-52: Consider renamingnetworkPaneltoapiPanelfor consistency.The property
networkPanelin the user preferences schema is inconsistent with the "Api" naming convention used throughout the UI layer (ApiPanelToggle,ApiRequestsPanel,apiRequestsCollection). RenamingnetworkPaneltoapiPanelwould align the state property with the broader naming pattern. The change is localized to 5 usages across 3 files (UserPreferences schema, ApiPanelToggle, and MainLayout).📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between d5e0120f9db278ded81328dfe6a68d455cb34c57 and 046db060d282ff6eabff06ea0103d398be5e1bda.
📒 Files selected for processing (18)
AGENTS.mdsrc/USER_PLACEHOLDER_CONSTANT.tssrc/client/pgliteHelpers.tssrc/collections/UserPreferences.tssrc/collections/apiRequests.tssrc/components/ApiLatencyConfigurator.tsxsrc/components/ApiPanelToggle.tsxsrc/components/ApiRequestsPanel.tsxsrc/components/AppSidebar.tsxsrc/components/Header.tsxsrc/components/tutorial/index.tsxsrc/components/ui/resizable.tsxsrc/components/ui/sidebar.tsxsrc/data/tutorial/optimistic-updates.mdxsrc/routes/__root.tsxsrc/routes/_tutorial._db.projects.tsxsrc/routes/_tutorial._db.tsxsrc/styles.css
💤 Files with no reviewable changes (1)
- src/components/AppSidebar.tsx
🧰 Additional context used
📓 Path-based instructions (2)
src/**/*.{tsx,ts}
📄 CodeRabbit inference engine (AGENTS.md)
src/**/*.{tsx,ts}: The project uses TanStack Start framework (@tanstack/start) with React for the frontend Useshadcn/uifor UI componentsFiles:
src/collections/UserPreferences.tssrc/components/ApiPanelToggle.tsxsrc/components/ApiLatencyConfigurator.tsxsrc/components/ui/resizable.tsxsrc/components/ApiRequestsPanel.tsxsrc/routes/__root.tsxsrc/USER_PLACEHOLDER_CONSTANT.tssrc/components/tutorial/index.tsxsrc/components/ui/sidebar.tsxsrc/routes/_tutorial._db.projects.tsxsrc/client/pgliteHelpers.tssrc/components/Header.tsxsrc/routes/_tutorial._db.tsxsrc/collections/apiRequests.ts
src/**/*.{tsx,ts,css}
📄 CodeRabbit inference engine (AGENTS.md)
Use
tailwindcss(v4) for stylingFiles:
src/collections/UserPreferences.tssrc/components/ApiPanelToggle.tsxsrc/components/ApiLatencyConfigurator.tsxsrc/components/ui/resizable.tsxsrc/components/ApiRequestsPanel.tsxsrc/routes/__root.tsxsrc/USER_PLACEHOLDER_CONSTANT.tssrc/components/tutorial/index.tsxsrc/components/ui/sidebar.tsxsrc/routes/_tutorial._db.projects.tsxsrc/client/pgliteHelpers.tssrc/components/Header.tsxsrc/styles.csssrc/routes/_tutorial._db.tsxsrc/collections/apiRequests.ts
🧠 Learnings (18)
📚 Learning: 2025-12-24T15:55:57.541Z
Learnt from: CR Repo: fulopkovacs/trytanstackdb.com PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-12-24T15:55:57.541Z Learning: Never use npm, yarn, or any other package manager in this projectApplied to files:
AGENTS.md
📚 Learning: 2025-12-24T15:55:57.541Z
Learnt from: CR Repo: fulopkovacs/trytanstackdb.com PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-12-24T15:55:57.541Z Learning: Always use pnpm instead of npm for all package management tasksApplied to files:
AGENTS.md
📚 Learning: 2025-12-24T15:55:57.541Z
Learnt from: CR Repo: fulopkovacs/trytanstackdb.com PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-12-24T15:55:57.541Z Learning: Use `pnpm install` instead of `npm install` for installing dependenciesApplied to files:
AGENTS.md
📚 Learning: 2025-12-24T15:55:57.541Z
Learnt from: CR Repo: fulopkovacs/trytanstackdb.com PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-12-24T15:55:57.541Z Learning: Use `pnpm lint` for linting the codebaseApplied to files:
AGENTS.md
📚 Learning: 2025-12-24T15:55:57.541Z
Learnt from: CR Repo: fulopkovacs/trytanstackdb.com PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-12-24T15:55:57.541Z Learning: Use `pnpm build` for creating a production buildApplied to files:
AGENTS.md
📚 Learning: 2025-12-24T15:55:57.541Z
Learnt from: CR Repo: fulopkovacs/trytanstackdb.com PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-12-24T15:55:57.541Z Learning: Use `pnpm dev` for starting the development serverApplied to files:
AGENTS.md
📚 Learning: 2025-12-24T15:55:57.541Z
Learnt from: CR Repo: fulopkovacs/trytanstackdb.com PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-12-24T15:55:57.541Z Learning: Use `pnpm run test` for running testsApplied to files:
AGENTS.md
📚 Learning: 2025-12-24T15:55:57.541Z
Learnt from: CR Repo: fulopkovacs/trytanstackdb.com PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-12-24T15:55:57.541Z Learning: Use `pnpm run <script>` instead of `npm run <script>` for running scriptsApplied to files:
AGENTS.md
📚 Learning: 2025-12-24T15:55:57.541Z
Learnt from: CR Repo: fulopkovacs/trytanstackdb.com PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-12-24T15:55:57.541Z Learning: Use `pnpm add <package>` instead of `npm install <package>` for adding packagesApplied to files:
AGENTS.md
📚 Learning: 2025-12-24T15:55:57.541Z
Learnt from: CR Repo: fulopkovacs/trytanstackdb.com PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-12-24T15:55:57.541Z Learning: Use `pnpm format` for code formattingApplied to files:
AGENTS.md
📚 Learning: 2025-12-24T15:55:57.541Z
Learnt from: CR Repo: fulopkovacs/trytanstackdb.com PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-12-24T15:55:57.541Z Learning: Applies to **/__test__/**/*.{ts,tsx} : Use `vitest` for writing and running testsApplied to files:
AGENTS.md
📚 Learning: 2025-12-24T15:55:57.541Z
Learnt from: CR Repo: fulopkovacs/trytanstackdb.com PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-12-24T15:55:57.541Z Learning: Use `pnpm typecheck` for type checkingApplied to files:
AGENTS.md
📚 Learning: 2025-12-24T15:55:57.541Z
Learnt from: CR Repo: fulopkovacs/trytanstackdb.com PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-12-24T15:55:57.541Z Learning: Applies to src/**/*.{tsx,ts} : The project uses TanStack Start framework (`tanstack/start`) with React for the frontendApplied to files:
AGENTS.mdsrc/routes/__root.tsx
📚 Learning: 2025-12-24T15:25:07.106Z
Learnt from: fulopkovacs Repo: fulopkovacs/trytanstackdb.com PR: 22 File: src/components/TodoBoards.tsx:63-81 Timestamp: 2025-12-24T15:25:07.106Z Learning: In Tailwind CSS v4, prefer canonical classes using bg-linear-to-* (e.g., bg-linear-to-b, bg-linear-to-t, bg-linear-to-r) over the older bg-gradient-to-* syntax. This aligns with Tailwind LSP's suggestCanonicalClasses rule. Apply across TSX files (e.g., src/components/*.tsx); replace occurrences of bg-gradient-to-* with the corresponding bg-linear-to-* equivalents and verify gradients visually.Applied to files:
src/components/ApiPanelToggle.tsxsrc/components/ApiLatencyConfigurator.tsxsrc/components/ui/resizable.tsxsrc/components/ApiRequestsPanel.tsxsrc/routes/__root.tsxsrc/components/tutorial/index.tsxsrc/components/ui/sidebar.tsxsrc/routes/_tutorial._db.projects.tsxsrc/components/Header.tsxsrc/routes/_tutorial._db.tsx
📚 Learning: 2025-12-24T15:55:57.541Z
Learnt from: CR Repo: fulopkovacs/trytanstackdb.com PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-12-24T15:55:57.541Z Learning: Applies to src/**/*.{tsx,ts} : Use `shadcn/ui` for UI componentsApplied to files:
src/components/ui/resizable.tsxsrc/routes/__root.tsx
📚 Learning: 2025-12-24T15:55:57.541Z
Learnt from: CR Repo: fulopkovacs/trytanstackdb.com PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-12-24T15:55:57.541Z Learning: Applies to src/route/__root.tsx : The root route is located at `src/route/__root.tsx` in TanStack StartApplied to files:
src/routes/__root.tsxsrc/routes/_tutorial._db.projects.tsxsrc/routes/_tutorial._db.tsx
📚 Learning: 2025-12-24T15:55:57.541Z
Learnt from: CR Repo: fulopkovacs/trytanstackdb.com PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-12-24T15:55:57.541Z Learning: Applies to src/**/*.{tsx,ts,css} : Use `tailwindcss` (v4) for stylingApplied to files:
src/routes/__root.tsx
📚 Learning: 2025-12-24T15:55:57.541Z
Learnt from: CR Repo: fulopkovacs/trytanstackdb.com PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-12-24T15:55:57.541Z Learning: Applies to src/**/*route*.{tsx,ts} : Use TanStack Router (`tanstack/router`) for routingApplied to files:
src/routes/__root.tsxsrc/routes/_tutorial._db.projects.tsxsrc/components/Header.tsxsrc/routes/_tutorial._db.tsx
🧬 Code graph analysis (7)
src/components/ApiPanelToggle.tsx (4)
src/collections/UserPreferences.ts (1)
userPreferencesCollection(12-19)
src/USER_PLACEHOLDER_CONSTANT.ts (1)
USER_PLACEHOLDER(7-12)
src/components/ui/tooltip.tsx (3)
Tooltip(59-59)TooltipTrigger(59-59)TooltipContent(59-59)
src/components/ui/button.tsx (1)
Button(63-63)
src/data/tutorial/optimistic-updates.mdx (1)
src/components/NetworkLatencyConfigurator.tsx (1)
option(80-96)
src/components/ApiLatencyConfigurator.tsx (3)
src/client/pgliteHelpers.ts (2)
API_LATENCY_LOCALSTORAGE_KEY(17-17)apiLatencyInMsSchema(18-22)
src/utils/highlight-collection-related-info.tsx (1)
HighlightWrapper(6-28)
src/components/NetworkLatencyConfigurator.tsx (5)
option(80-96)NetworkLatencyConfigurator(28-101)savedLatency(41-47)handleSelectLatency(88-90)handleSelectLatency(32-39)
src/components/ApiRequestsPanel.tsx (5)
src/collections/apiRequests.ts (2)
apiRequestsCollection(17-28)ApiRequest(6-15)
src/components/ui/collapsible.tsx (3)
Collapsible(31-31)CollapsibleTrigger(31-31)CollapsibleContent(31-31)
src/components/ui/badge.tsx (1)
Badge(48-48)
src/components/ui/button.tsx (1)
Button(63-63)
src/components/ui/scroll-area.tsx (1)
ScrollArea(62-62)
src/USER_PLACEHOLDER_CONSTANT.ts (2)
src/db/schema.ts (2)
UserRecord(31-31)users(23-28)
src/routes/_tutorial.tsx (1)
user(21-25)
src/client/pgliteHelpers.ts (3)
src/local-api/helpers.ts (4)
requestSchema(21-25)APIType(19-19)deconstructResponseFromHandler(70-96)constructRequestForHandler(50-68)
src/local-api/index.ts (1)
API(7-12)
src/collections/apiRequests.ts (1)
apiRequestsCollection(17-28)
src/components/Header.tsx (2)
src/components/ApiLatencyConfigurator.tsx (1)
ApiLatencyConfigurator(28-98)
src/components/ApiPanelToggle.tsx (1)
ApiPanelToggle(8-44)
🔇 Additional comments (15)
AGENTS.md (1)
54-61: LGTM!The documentation additions clearly communicate important guidelines for AI agents working on the codebase. The restriction on running the dev server and the coding style preferences are well-articulated.
src/components/ApiPanelToggle.tsx (1)
9-18: LGTM!The query structure using
useLiveQueryis correctly implemented and follows TanStack DB patterns. The use ofUSER_PLACEHOLDER.idis appropriate for a tutorial/demo context.src/styles.css (1)
143-148: LGTM on font variable definitions!The new font variables are well-structured with appropriate fallbacks. Space Grotesk for sans-serif and Iosevka Term Slab Web for monospace align with the PR's objectives.
src/routes/__root.tsx (1)
55-58: LGTM!The Iosevka Term Slab Web font is properly loaded from a reliable CDN source. The unhinted variant is appropriate for web usage and aligns with the font variable definition in
src/styles.css.src/components/Header.tsx (2)
1-10: LGTM!The component imports and integration are clean. The renaming from
NetworkLatencyConfiguratortoApiLatencyConfiguratoris consistent with the PR's goal of clarifying that the latency applies specifically to API requests.
84-86: LGTM!The
ApiPanelToggleis correctly wrapped inClientOnlyfor SSR compatibility and positioned appropriately at the end of the header.src/collections/UserPreferences.ts (1)
7-10: No changes needed. The usage of.default()on the enum field follows the correct Zod 4 pattern as documented in the official Zod guidelines.Likely an incorrect or invalid review comment.
src/components/ui/sidebar.tsx (1)
238-238: The sidebar positioning works correctly with the new resizable layout.The
absolutepositioning on line 238 is properly anchored to the ancestordivwithclassName="h-full flex relative"inprojects.tsx, which provides the necessary positioning context. The sidebar container withinset-y-0and side positioning (left-0 or right-0) displays correctly without layout issues.src/components/tutorial/index.tsx (1)
18-18: LGTM!The highlight enum value correctly aligns with the codebase-wide rename from "network" to "API" latency terminology.
src/data/tutorial/optimistic-updates.mdx (1)
30-34: LGTM!The tutorial content consistently reflects the renamed API latency terminology and updated highlight IDs.
src/USER_PLACEHOLDER_CONSTANT.ts (1)
1-12: LGTM!The placeholder constant is well-structured with proper type checking via
satisfies. The comment clearly documents its purpose as a future-proof placeholder.src/collections/apiRequests.ts (1)
1-28: LGTM!Well-structured collection definition with a comprehensive
ApiRequesttype. The use ofunknownfor body types and the"pending" | numberstatus union provides appropriate flexibility for request tracking.src/components/ApiLatencyConfigurator.tsx (1)
28-36: LGTM!The component rename and API terminology updates are consistent with the codebase-wide changes.
src/client/pgliteHelpers.ts (2)
83-95: Well-designed request tracking flow.Inserting the pending record immediately (before processing) allows the UI to show loading states in real-time. The request ID generation and metadata capture are appropriate for tracking request lifecycle.
98-106: LGTM: Delay simulation and request processing are correct.The
apiLatencyInMsSchemacorrectly handles localStorage values and provides a safe fallback (1,000ms) using Zod 4's.catch(). Request processing appropriately uses the handler with constructed request/response helpers.@@ -106,2 +102,21 @@102+ await new Promise((resolve) => setTimeout(resolve, delay));103+104+ const response = await deconstructResponseFromHandler(105+ await handler(constructRequestForHandler(requestData)),106+ );107+108+ const duration = performance.now() - startTime;109+110+ apiRequestsCollection.update(requestId, (draft) => {111+ draft.responseBody = response.body;112+ draft.status = response.status;113+ draft.duration = duration;114+115+ return draft;116+ });117+118+ return response;119+ } else {120+ throw new Error("No handler found for this request");106121 }107122 }⚠️ Potential issue | 🟠 Major
Wrap request processing in try-catch to handle failures.
If an error occurs after inserting the pending record (line 87), the tracking record will remain in "pending" state indefinitely. Users will see requests that never complete. Wrap the request processing logic in a try-catch block and update the record with error status.
🔎 Proposed fix to handle errors
async function processRequestInMainThread(body: any) { const requestData = requestSchema.parse(body); const handler = (API as APIType)[requestData.pathname][ requestData.method ]; if (handler) { // Generate unique request ID for tracking const requestId = `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`; const startTime = performance.now(); // Emit "started" event immediately so UI shows pending state apiRequestsCollection.insert({ id: requestId, timestamp: Date.now(), method: requestData.method, pathname: requestData.pathname, requestBody: requestData.requestBody, status: "pending", duration: null, }); + try { // Simulate a delay for demonstration purposes const delay = apiLatencyInMsSchema.parse( localStorage.getItem(API_LATENCY_LOCALSTORAGE_KEY), ); await new Promise((resolve) => setTimeout(resolve, delay)); const response = await deconstructResponseFromHandler( await handler(constructRequestForHandler(requestData)), ); const duration = performance.now() - startTime; apiRequestsCollection.update(requestId, (draft) => { draft.responseBody = response.body; draft.status = response.status; draft.duration = duration; return draft; }); return response; + } catch (error) { + const duration = performance.now() - startTime; + apiRequestsCollection.update(requestId, (draft) => { + draft.status = 500; + draft.duration = duration; + draft.responseBody = { error: error instanceof Error ? error.message : 'Unknown error' }; + return draft; + }); + throw error; + } } else { throw new Error("No handler found for this request"); } }Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In src/client/pgliteHelpers.ts around lines 76 to 122, wrap the logic that executes the handler (everything after inserting the pending record through computing duration and updating the collection) in a try-catch so any thrown error will update the apiRequestsCollection record from "pending" to an error state instead of staying pending; in the catch, compute duration, update the record by setting status to "error" (and optionally responseBody to the error message or normalized error object and duration), then rethrow the error so upstream callers still receive it; ensure the normal success path still updates the record as it does now and that the try block begins immediately after the pending insert and encloses the delay, handler call, deconstruction, and success update.✅ Addressed in commits 420034e to ab38c25
src/components/ApiLatencyConfigurator.tsx lines 26 to 32@@ -32,16 +32,13 @@32- function handleSelectLatency(option: NetworkLatencyOption) {33- localStorage.setItem(34- NETWORK_LATENCY_LOCALSTORAGE_KEY,35- option.value.toString(),36- );32+ function handleSelectLatency(option: ApiLatencyOption) {33+ localStorage.setItem(API_LATENCY_LOCALSTORAGE_KEY, option.value.toString());3734 setSelectedLatency(option.value);3835 setIsOpen(false);3936 }40374138 useEffect(() => {4239 // get the saved latency from localStorage43- const savedLatency = localStorage.getItem(NETWORK_LATENCY_LOCALSTORAGE_KEY);44- const latency = networkLatencyInMsSchema.parse(savedLatency);40+ const savedLatency = localStorage.getItem(API_LATENCY_LOCALSTORAGE_KEY);41+ const latency = apiLatencyInMsSchema.parse(savedLatency);454246- setSelectedLatency(latency as NetworkLatency);43+ setSelectedLatency(latency as ApiLatency);4744 }, []);⚠️ Potential issue | 🟡 Minor
Unsafe type cast may cause runtime inconsistencies.
The
latency as ApiLatencycast on line 43 assumes the parsed value is always one of0 | 1000 | 2000 | 5000. However,apiLatencyInMsSchemaonly parses to an integer with a default/catch of1000—it doesn't validate against theApiLatencyunion. If localStorage contains an unexpected value like3000, the UI state won't match the type.🔎 Proposed fix using a validation helper
+const validLatencies = new Set([0, 1000, 2000, 5000]); + +function isValidApiLatency(value: number): value is ApiLatency { + return validLatencies.has(value); +} + useEffect(() => { // get the saved latency from localStorage const savedLatency = localStorage.getItem(API_LATENCY_LOCALSTORAGE_KEY); const latency = apiLatencyInMsSchema.parse(savedLatency); - setSelectedLatency(latency as ApiLatency); + setSelectedLatency(isValidApiLatency(latency) ? latency : 1_000); }, []);📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
const validLatencies = new Set([0, 1000, 2000, 5000]); function isValidApiLatency(value: number): value is ApiLatency { return validLatencies.has(value); } useEffect(() => { // get the saved latency from localStorage const savedLatency = localStorage.getItem(API_LATENCY_LOCALSTORAGE_KEY); const latency = apiLatencyInMsSchema.parse(savedLatency); setSelectedLatency(isValidApiLatency(latency) ? latency : 1_000); }, []);🤖 Prompt for AI Agents
In src/components/ApiLatencyConfigurator.tsx around lines 38 to 44, the code unsafely casts the parsed localStorage value to ApiLatency which can allow invalid numbers (e.g. 3000) into state; replace the cast with explicit validation: parse the saved value, check it against the allowed ApiLatency set (0, 1000, 2000, 5000) or use a refined zod/schema that only accepts those union values, and if validation fails fall back to the default (1000) before calling setSelectedLatency, ensuring the state always holds a valid ApiLatency.src/components/ApiRequestsPanel.tsx lines 156 to 173Outdated@@ -0,0 +153,21 @@153+ [],154+ );155+156+ const scrollRef = useRef<HTMLDivElement>(null);157+ const prevRequestsLengthRef = useRef(requests.length);158+159+ // Auto-scroll to bottom when new requests are added160+ if (prevRequestsLengthRef.current !== requests.length) {161+ prevRequestsLengthRef.current = requests.length;162+ // Schedule scroll after render163+ setTimeout(() => {164+ if (scrollRef.current) {165+ const scrollContainer = scrollRef.current.querySelector(166+ '[data-slot="scroll-area-viewport"]',167+ );168+ if (scrollContainer) {169+ scrollContainer.scrollTop = scrollContainer.scrollHeight;170+ }171+ }172+ }, 0);173+ }🛠️ Refactor suggestion | 🟠 Major
Move auto-scroll logic into a
useEffect.The current implementation performs side effects (setTimeout, DOM manipulation) during render, which violates React's rendering rules. The comparison and scroll scheduling should be moved to a
useEffectto ensure predictable behavior.🔎 Proposed fix
const scrollRef = useRef<HTMLDivElement>(null); -const prevRequestsLengthRef = useRef(requests.length); +const prevRequestsLengthRef = useRef(0); -// Auto-scroll to bottom when new requests are added -if (prevRequestsLengthRef.current !== requests.length) { - prevRequestsLengthRef.current = requests.length; - // Schedule scroll after render - setTimeout(() => { +// Auto-scroll to bottom when new requests are added +useEffect(() => { + if (prevRequestsLengthRef.current !== requests.length && requests.length > prevRequestsLengthRef.current) { + prevRequestsLengthRef.current = requests.length; if (scrollRef.current) { const scrollContainer = scrollRef.current.querySelector( '[data-slot="scroll-area-viewport"]', ); if (scrollContainer) { scrollContainer.scrollTop = scrollContainer.scrollHeight; } } - }, 0); -} + } + prevRequestsLengthRef.current = requests.length; +}, [requests.length]);📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
const scrollRef = useRef<HTMLDivElement>(null); const prevRequestsLengthRef = useRef(0); // Auto-scroll to bottom when new requests are added useEffect(() => { if (prevRequestsLengthRef.current !== requests.length && requests.length > prevRequestsLengthRef.current) { prevRequestsLengthRef.current = requests.length; if (scrollRef.current) { const scrollContainer = scrollRef.current.querySelector( '[data-slot="scroll-area-viewport"]', ); if (scrollContainer) { scrollContainer.scrollTop = scrollContainer.scrollHeight; } } } prevRequestsLengthRef.current = requests.length; }, [requests.length]);🤖 Prompt for AI Agents
In src/components/ApiRequestsPanel.tsx around lines 156-173, the auto-scroll logic currently runs during render (using setTimeout and DOM manipulation) which must be moved into a useEffect; wrap the comparison of prevRequestsLengthRef.current !== requests.length and the setTimeout DOM scroll inside a useEffect that depends on requests.length, update prevRequestsLengthRef inside that effect, schedule the scroll after render (setTimeout or requestAnimationFrame) and store the timer id so you can clear it in the effect cleanup to avoid leaks, and keep using scrollRef.current.querySelector('[data-slot="scroll-area-viewport"]') to set scrollTop = scrollHeight.src/styles.css lines 10 to 12Outdated@@ -7,6 +7,6 @@7788 body {99 @apply m-0;10- font-family:11- 'Space Grotesk', -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu',12- 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;10+ /* font-family: */11+ /* 'Space Grotesk', -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', */12+ /* 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; */⚠️ Potential issue | 🔴 Critical
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash # Check Tailwind config and font usage echo "=== Checking for Tailwind config files ===" fd -e ts -e js -e cjs -e json tailwind | head -20 echo -e "\n=== Checking Tailwind config content ===" find . -maxdepth 2 -name "tailwind.config.*" -o -name "tailwind.config.ts" | head -5 | xargs -I {} cat {} 2>/dev/null echo -e "\n=== Checking for font usage in tsx/ts files ===" rg "font-(sans|mono|serif)" --type tsx --type ts -c 2>/dev/null | head -20 echo -e "\n=== Checking CSS variables usage in components ===" rg "var\(--font" --type tsx --type ts -B1 -A1 2>/dev/null | head -30 echo -e "\n=== Checking styles.css for complete context ===" wc -l src/styles.css 2>/dev/nullRepository: fulopkovacs/trytanstackdb.com
Length of output: 327
🏁 Script executed:
#!/bin/bash # Read the relevant sections of styles.css echo "=== Lines 1-30 (including lines 10-12) ===" sed -n '1,30p' src/styles.css | cat -n echo -e "\n=== Lines 140-160 (font variables section) ===" sed -n '140,160p' src/styles.css | cat -n echo -e "\n=== Checking for tailwind directives ===" head -20 src/styles.css | cat -n echo -e "\n=== Searching for @tailwind directives ===" rg "@tailwind" src/styles.css -B1 -A1 echo -e "\n=== Checking package.json for tailwind ===" rg "tailwind" package.json echo -e "\n=== Checking for font usage in HTML/components ===" rg "font-(sans|mono|serif)" -t tsx -t ts 2>/dev/null | head -10Repository: fulopkovacs/trytanstackdb.com
Length of output: 2697
🏁 Script executed:
#!/bin/bash echo "=== Searching for usage of --font-sans and --font-mono CSS variables ===" rg "var\(--font-(sans|mono)" . --type css --type tsx --type ts -B2 -A2 echo -e "\n=== Checking if body or any element applies the font variables ===" rg "font-family.*var\(--font" . --type css -B1 -A1 echo -e "\n=== Searching for Tailwind config inline or in different locations ===" find . -type f \( -name "*.config.*" -o -name "tailwind.*" \) ! -path "*/node_modules/*" 2>/dev/null echo -e "\n=== Check if tailwind config is in a non-standard location ===" rg "fontFamily|fonts" -t ts -t js --type-add="ts:*.ts" --type-add="js:*.js" 2>/dev/null | grep -i tailwind | head -10Repository: fulopkovacs/trytanstackdb.com
Length of output: 431
🏁 Script executed:
#!/bin/bash echo "=== Reading vite.config.ts ===" cat vite.config.ts echo -e "\n=== Checking if any element has font utilities applied ===" rg "font-sans|font-mono|font-serif" . --type tsx --type ts -c 2>/dev/null | head -20 echo -e "\n=== Checking default Tailwind behavior in v4 ===" rg "@apply.*font" src/styles.css -B2 -A2Repository: fulopkovacs/trytanstackdb.com
Length of output: 1180
The body font-family removal has broken font application—there is no mechanism to apply fonts.
The commented-out body font-family has not been replaced. The CSS variables
--font-sansand--font-monoare defined in:rootbut are never used anywhere in the codebase. There are no Tailwind font utilities (e.g.,@apply font-sans) applied to the body or any other elements, and the Tailwind configuration does not customize thefontFamilytheme. Without these, the body will render in the browser's default serif font instead of the intended Space Grotesk. Either apply@apply font-sansto the body, configure fonts in the Tailwind theme, or restore an explicit font-family declaration.🤖 Prompt for AI Agents
In src/styles.css around lines 10-12, the body font-family was commented out and the CSS vars --font-sans / --font-mono defined in :root are never applied; restore actual font usage by either (a) adding a body rule that applies Tailwind’s font utility (e.g., add a body selector with "@apply font-sans") and ensure tailwind.config.js maps fontFamily.sans to "var(--font-sans)", or (b) restore an explicit font-family declaration on body that references the CSS variable (e.g., font-family: var(--font-sans), system-ui, sans-serif); pick one approach and implement it so the intended Space Grotesk font is applied site-wide.Actionable comments posted: 0
♻️ Duplicate comments (1)
src/components/ApiLatencyConfigurator.tsx (1)
45-47: Unsafe type cast remains unaddressed.The cast
latency as ApiLatencyon line 47 was flagged in a previous review. While the schema's.catch(1_000)provides a safe default, the type assertion bypasses TypeScript's type checking. If you implement the schema fix suggested above (preserving the union type), this cast would become unnecessary.🧹 Nitpick comments (3)
src/components/ApiRequestsPanel.tsx (1)
22-27: Await thedeletecall for proper async handling.The
clearRequestsfunction isasyncbut doesn't await thedeleteoperation. This could lead to unexpected behavior if the caller relies on the operation completing.🔎 Proposed fix
async function clearRequests() { const ids = (await apiRequestsCollection.toArrayWhenReady()).map( ({ id }) => id, ); - apiRequestsCollection.delete(ids); + await apiRequestsCollection.delete(ids); }src/client/pgliteHelpers.ts (1)
4-5: Potential circular import between modules.There's a circular dependency:
pgliteHelpers.tsimportsapiLatencyInMsSchemafromApiLatencyConfigurator.tsx, whileApiLatencyConfigurator.tsximportsAPI_LATENCY_LOCALSTORAGE_KEYfrompgliteHelpers.ts. While this may work at runtime due to how the imports resolve, consider extracting the shared constants and schema to a dedicated module (e.g.,src/config/apiLatency.ts) to make the dependency graph cleaner and avoid potential issues during bundling or testing.Also applies to: 17-17
src/components/ApiLatencyConfigurator.tsx (1)
11-17: Schema type inference doesn't produce the expected union type.The
apiLatencyInMsSchemauses.transform((t) => parseInt(t, 10))which results inz.infer<typeof apiLatencyInMsSchema>beingnumberrather than the expected union0 | 1000 | 2000 | 5000. This makes theApiLatencytype effectivelynumber, weakening type safety.🔎 Proposed fix to preserve the union type
-export const apiLatencyInMsSchema = z - .enum(["0", "1000", "2000", "5000"]) - .transform((t) => parseInt(t, 10)) - .default(1_000) - .catch(1_000); +const API_LATENCIES = [0, 1000, 2000, 5000] as const; +export type ApiLatency = (typeof API_LATENCIES)[number]; + +export const apiLatencyInMsSchema = z + .enum(["0", "1000", "2000", "5000"]) + .transform((t) => parseInt(t, 10) as ApiLatency) + .default(1_000 as ApiLatency) + .catch(1_000 as ApiLatency); -type ApiLatency = z.infer<typeof apiLatencyInMsSchema>;📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 046db060d282ff6eabff06ea0103d398be5e1bda and ab38c25de3d299ea2746c15dd4926c022a3b40c6.
📒 Files selected for processing (4)
src/client/pgliteHelpers.tssrc/components/ApiLatencyConfigurator.tsxsrc/components/ApiRequestsPanel.tsxsrc/styles.css
🚧 Files skipped from review as they are similar to previous changes (1)
- src/styles.css
🧰 Additional context used
📓 Path-based instructions (2)
src/**/*.{tsx,ts}
📄 CodeRabbit inference engine (AGENTS.md)
src/**/*.{tsx,ts}: The project uses TanStack Start framework (@tanstack/start) with React for the frontend Useshadcn/uifor UI componentsFiles:
src/components/ApiRequestsPanel.tsxsrc/components/ApiLatencyConfigurator.tsxsrc/client/pgliteHelpers.ts
src/**/*.{tsx,ts,css}
📄 CodeRabbit inference engine (AGENTS.md)
Use
tailwindcss(v4) for stylingFiles:
src/components/ApiRequestsPanel.tsxsrc/components/ApiLatencyConfigurator.tsxsrc/client/pgliteHelpers.ts
🧠 Learnings (2)
📚 Learning: 2025-12-24T15:25:07.106Z
Learnt from: fulopkovacs Repo: fulopkovacs/trytanstackdb.com PR: 22 File: src/components/TodoBoards.tsx:63-81 Timestamp: 2025-12-24T15:25:07.106Z Learning: In Tailwind CSS v4, prefer canonical classes using bg-linear-to-* (e.g., bg-linear-to-b, bg-linear-to-t, bg-linear-to-r) over the older bg-gradient-to-* syntax. This aligns with Tailwind LSP's suggestCanonicalClasses rule. Apply across TSX files (e.g., src/components/*.tsx); replace occurrences of bg-gradient-to-* with the corresponding bg-linear-to-* equivalents and verify gradients visually.Applied to files:
src/components/ApiRequestsPanel.tsxsrc/components/ApiLatencyConfigurator.tsx
📚 Learning: 2025-12-24T15:55:57.541Z
Learnt from: CR Repo: fulopkovacs/trytanstackdb.com PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-12-24T15:55:57.541Z Learning: Applies to src/**/*.{tsx,ts} : The project uses TanStack Start framework (`tanstack/start`) with React for the frontendApplied to files:
src/client/pgliteHelpers.ts
🧬 Code graph analysis (1)
src/components/ApiRequestsPanel.tsx (5)
src/collections/apiRequests.ts (2)
apiRequestsCollection(17-28)ApiRequest(6-15)
src/components/ui/collapsible.tsx (3)
Collapsible(31-31)CollapsibleTrigger(31-31)CollapsibleContent(31-31)
src/components/ui/badge.tsx (1)
Badge(48-48)
src/components/ui/button.tsx (1)
Button(63-63)
src/components/ui/scroll-area.tsx (1)
ScrollArea(62-62)
🔇 Additional comments (7)
src/components/ApiRequestsPanel.tsx (4)
29-65: LGTM!The helper functions
formatDuration,getMethodColor, andgetStatusColorare well-implemented with proper handling for all cases including edge cases (null duration, pending status, and default fallbacks).
67-91: LGTM!The
JsonViewercomponent is well-structured with proper null/undefined handling and appropriate overflow controls for displaying JSON content.
93-146: LGTM!The
RequestItemcomponent is well-implemented with proper handling of the pending state, accessible button element withtype="button", and conditional rendering of the response body only when the request is complete.
148-199: LGTM!The main
ApiRequestsPanelcomponent properly usesuseLiveQueryfor reactive data fetching, handles the empty state gracefully, and correctly disables the clear button when there are no requests.src/client/pgliteHelpers.ts (2)
71-131: LGTM! Error handling has been properly implemented.The
processRequestInMainThreadfunction now correctly wraps the request processing in a try-catch block, ensuring that if an error occurs after inserting the pending record, the tracking record is updated with error status (500), duration, and error message instead of remaining in "pending" state indefinitely.
77-78: Request ID generation is acceptable for this use case.The combination of
Date.now()and a random base36 string provides sufficient uniqueness for a local-only demo collection. For production use, considercrypto.randomUUID()for stronger guarantees.src/components/ApiLatencyConfigurator.tsx (1)
32-101: LGTM!The component logic is well-structured with proper state management, localStorage persistence, and clean UI using shadcn/ui components. The popover provides helpful context about the service worker limitation.
Actionable comments posted: 0
🧹 Nitpick comments (1)
src/components/ApiLatencyConfigurator.tsx (1)
11-17: Schema validation is correct; unsafe cast removed.The zod schema correctly validates input values through
.enum(["0", "1000", "2000", "5000"]), ensuring only valid latencies can pass through at runtime. The.catch(1_000)fallback guarantees a safe default for any invalid values. The unsafe type cast mentioned in the previous review has been removed.Note: The inferred type
ApiLatencyisnumberrather than the literal union0 | 1000 | 2000 | 5000. While runtime behavior is safe, you could optionally refine this for stricter TypeScript checking.🔎 Optional: Stricter type-level validation
If you want TypeScript to enforce the literal union type, you could define it explicitly:
+type ApiLatency = 0 | 1000 | 2000 | 5000; + export const apiLatencyInMsSchema = z .enum(["0", "1000", "2000", "5000"]) .transform((t) => parseInt(t, 10)) .default(1_000) - .catch(1_000); + .catch(1_000) as unknown as z.ZodType<ApiLatency>; -type ApiLatency = z.infer<typeof apiLatencyInMsSchema>;This makes
ApiLatencya precise union type rather thannumber.📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between f87aa4c75207824dc79effbd1d2a42680222bfe9 and ff208d77616c8161ed5adf45dbc05b89671fe612.
📒 Files selected for processing (1)
src/components/ApiLatencyConfigurator.tsx
🧰 Additional context used
📓 Path-based instructions (2)
src/**/*.{tsx,ts}
📄 CodeRabbit inference engine (AGENTS.md)
src/**/*.{tsx,ts}: The project uses TanStack Start framework (@tanstack/start) with React for the frontend Useshadcn/uifor UI componentsFiles:
src/components/ApiLatencyConfigurator.tsx
src/**/*.{tsx,ts,css}
📄 CodeRabbit inference engine (AGENTS.md)
Use
tailwindcss(v4) for stylingFiles:
src/components/ApiLatencyConfigurator.tsx
🧠 Learnings (1)
📚 Learning: 2025-12-24T15:25:07.106Z
Learnt from: fulopkovacs Repo: fulopkovacs/trytanstackdb.com PR: 22 File: src/components/TodoBoards.tsx:63-81 Timestamp: 2025-12-24T15:25:07.106Z Learning: In Tailwind CSS v4, prefer canonical classes using bg-linear-to-* (e.g., bg-linear-to-b, bg-linear-to-t, bg-linear-to-r) over the older bg-gradient-to-* syntax. This aligns with Tailwind LSP's suggestCanonicalClasses rule. Apply across TSX files (e.g., src/components/*.tsx); replace occurrences of bg-gradient-to-* with the corresponding bg-linear-to-* equivalents and verify gradients visually.Applied to files:
src/components/ApiLatencyConfigurator.tsx
🧬 Code graph analysis (1)
src/components/ApiLatencyConfigurator.tsx (2)
src/client/pgliteHelpers.ts (1)
API_LATENCY_LOCALSTORAGE_KEY(17-17)
src/utils/highlight-collection-related-info.tsx (1)
HighlightWrapper(6-28)
🔇 Additional comments (4)
src/components/ApiLatencyConfigurator.tsx (4)
19-30: LGTM!The type definition and options array are well-structured and align perfectly with the schema-validated latency values.
32-40: LGTM!The component state management and handler logic correctly persist the selected latency value to localStorage using the shared constant key.
42-48: LGTM! The unsafe cast has been addressed.The effect correctly loads and validates the saved latency value using the zod schema, which ensures only valid values reach state. The unsafe type cast mentioned in the previous review is no longer present.
50-101: LGTM!The UI implementation correctly:
- Uses the updated terminology (API latency vs. network latency)
- Provides visual feedback through icon coloring based on selected latency
- Renders options dynamically from the validated options array
- Includes helpful explanatory text about service worker behavior
Actionable comments posted: 0
♻️ Duplicate comments (1)
src/components/ApiLatencyConfigurator.tsx (1)
26-32: Previous type safety concern is mitigated by schema design.The
apiLatencyInMsSchemauses.catch(1_000)which guarantees a valid fallback for any invalid localStorage value. Since the enum only accepts valid latency strings ("0", "1000", "2000", "5000") and the catch ensures 1000 on parse failure, the returned value will always be a validApiLatency. The previous concern about unsafe casting is effectively addressed by the schema's defensive design.🧹 Nitpick comments (1)
src/components/ApiLatencyConfigurator.tsx (1)
39-49: Consider extracting the nested ternary for readability.The conditional class logic for
GlobeIconis deeply nested. While functional, a lookup object could improve clarity.🔎 Optional refactor using a color map
+const latencyColorClasses: Record<ApiLatency, string> = { + 0: "text-green-500 dark:text-green-300", + 1000: "text-foreground", + 2000: "text-orange-400 dark:text-orange-300", + 5000: "text-destructive dark:text-destructive", +}; + <GlobeIcon - className={cn( - selectedLatency === 0 - ? "text-green-500 dark:text-green-300" - : selectedLatency === 2000 - ? "text-orange-400 dark:text-orange-300" - : selectedLatency === 5000 - ? "text-destructive dark:text-destructive" - : "text-foreground", - )} + className={latencyColorClasses[selectedLatency]} />📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between ff208d77616c8161ed5adf45dbc05b89671fe612 and fd9af9446de6aed12612a386de2b16cd7a24c421.
📒 Files selected for processing (7)
src/client/pgliteHelpers.tssrc/components/ApiLatencyConfigurator.tsxsrc/components/ApiPanelToggle.tsxsrc/routes/_tutorial._db.projects.tsxsrc/routes/_tutorial._db.tsxsrc/utils/USER_PLACEHOLDER_CONSTANT.tssrc/utils/apiLatency.ts
🧰 Additional context used
📓 Path-based instructions (2)
src/**/*.{tsx,ts}
📄 CodeRabbit inference engine (AGENTS.md)
src/**/*.{tsx,ts}: The project uses TanStack Start framework (@tanstack/start) with React for the frontend Useshadcn/uifor UI componentsFiles:
src/utils/USER_PLACEHOLDER_CONSTANT.tssrc/routes/_tutorial._db.tsxsrc/routes/_tutorial._db.projects.tsxsrc/utils/apiLatency.tssrc/components/ApiPanelToggle.tsxsrc/components/ApiLatencyConfigurator.tsxsrc/client/pgliteHelpers.ts
src/**/*.{tsx,ts,css}
📄 CodeRabbit inference engine (AGENTS.md)
Use
tailwindcss(v4) for stylingFiles:
src/utils/USER_PLACEHOLDER_CONSTANT.tssrc/routes/_tutorial._db.tsxsrc/routes/_tutorial._db.projects.tsxsrc/utils/apiLatency.tssrc/components/ApiPanelToggle.tsxsrc/components/ApiLatencyConfigurator.tsxsrc/client/pgliteHelpers.ts
🧠 Learnings (4)
📚 Learning: 2025-12-24T15:55:57.541Z
Learnt from: CR Repo: fulopkovacs/trytanstackdb.com PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-12-24T15:55:57.541Z Learning: Applies to src/route/__root.tsx : The root route is located at `src/route/__root.tsx` in TanStack StartApplied to files:
src/routes/_tutorial._db.tsxsrc/routes/_tutorial._db.projects.tsx
📚 Learning: 2025-12-24T15:55:57.541Z
Learnt from: CR Repo: fulopkovacs/trytanstackdb.com PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-12-24T15:55:57.541Z Learning: Applies to src/**/*route*.{tsx,ts} : Use TanStack Router (`tanstack/router`) for routingApplied to files:
src/routes/_tutorial._db.tsxsrc/routes/_tutorial._db.projects.tsx
📚 Learning: 2025-12-24T15:25:07.106Z
Learnt from: fulopkovacs Repo: fulopkovacs/trytanstackdb.com PR: 22 File: src/components/TodoBoards.tsx:63-81 Timestamp: 2025-12-24T15:25:07.106Z Learning: In Tailwind CSS v4, prefer canonical classes using bg-linear-to-* (e.g., bg-linear-to-b, bg-linear-to-t, bg-linear-to-r) over the older bg-gradient-to-* syntax. This aligns with Tailwind LSP's suggestCanonicalClasses rule. Apply across TSX files (e.g., src/components/*.tsx); replace occurrences of bg-gradient-to-* with the corresponding bg-linear-to-* equivalents and verify gradients visually.Applied to files:
src/routes/_tutorial._db.tsxsrc/routes/_tutorial._db.projects.tsxsrc/components/ApiPanelToggle.tsxsrc/components/ApiLatencyConfigurator.tsx
📚 Learning: 2025-12-24T15:55:57.541Z
Learnt from: CR Repo: fulopkovacs/trytanstackdb.com PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-12-24T15:55:57.541Z Learning: Applies to src/**/*.{tsx,ts} : The project uses TanStack Start framework (`tanstack/start`) with React for the frontendApplied to files:
src/client/pgliteHelpers.ts
🧬 Code graph analysis (4)
src/utils/USER_PLACEHOLDER_CONSTANT.ts (2)
src/db/schema.ts (2)
UserRecord(31-31)users(23-28)
src/routes/_tutorial.tsx (1)
user(21-25)
src/routes/_tutorial._db.projects.tsx (6)
src/collections/UserPreferences.ts (1)
userPreferencesCollection(12-19)
src/utils/USER_PLACEHOLDER_CONSTANT.ts (1)
USER_PLACEHOLDER(7-12)
src/components/Header.tsx (1)
Header(11-89)
src/components/ui/resizable.tsx (6)
ResizablePanelGroup(54-54)ResizablePanel(54-54)ResizableHandle(54-54)ResizablePanel(23-27)ResizablePanelGroup(7-21)ResizableHandle(29-52)
src/components/ApiRequestsPanel.tsx (1)
ApiRequestsPanel(148-199)
src/routes/_tutorial._db.projects.$projectId.tsx (2)
SharedLayout(10-16)RouteComponent(18-27)
src/components/ApiLatencyConfigurator.tsx (2)
src/utils/apiLatency.ts (5)
ApiLatency(11-11)ApiLatencyOption(13-17)API_LATENCY_LOCALSTORAGE_KEY(3-3)apiLatencyInMsSchema(5-9)apiLatencyOptions(19-24)
src/utils/highlight-collection-related-info.tsx (1)
HighlightWrapper(6-28)
src/client/pgliteHelpers.ts (4)
src/local-api/helpers.ts (4)
requestSchema(21-25)APIType(19-19)deconstructResponseFromHandler(70-96)constructRequestForHandler(50-68)
src/local-api/index.ts (1)
API(7-12)
src/collections/apiRequests.ts (1)
apiRequestsCollection(17-28)
src/utils/apiLatency.ts (2)
apiLatencyInMsSchema(5-9)API_LATENCY_LOCALSTORAGE_KEY(3-3)
🔇 Additional comments (10)
src/components/ApiPanelToggle.tsx (1)
8-43: Well-structured toggle component with good accessibility.The component correctly uses
useLiveQueryto reactively read user preferences and updates the collection directly on click. The aria-label and tooltip provide good accessibility. The variant toggle between "default" and "outline" gives clear visual feedback of the panel state.src/utils/apiLatency.ts (2)
5-11: Clean schema design with appropriate defaults and fallbacks.The Zod schema properly parses string values from localStorage, transforms to integers, and provides both a default and catch fallback to 1000ms. The type inference via
z.inferensures type safety across consumers.
19-24: Consistent options configuration.The
apiLatencyOptionsarray provides a well-structured set of presets with labels, values, and semantic colors that align with the latency severity (green for no latency, red for high latency).src/client/pgliteHelpers.ts (2)
78-91: Good request tracking implementation with immediate pending state visibility.The unique ID generation and immediate insertion of a pending record enables the UI to show loading states as intended by the PR objectives. This solves the limitation where service worker requests couldn't show pending state in the browser network panel.
100-128: Proper error handling with record cleanup.The try-catch block correctly updates the tracking record on both success and failure paths, ensuring no orphaned "pending" records remain. The error is re-thrown to allow upstream handling while still providing observability.
src/utils/USER_PLACEHOLDER_CONSTANT.ts (1)
1-12: Clean constant extraction with proper type safety.Using
satisfies UserRecordensures type compatibility while preserving the literal types. This extraction helps avoid circular dependencies and provides a single source of truth for the placeholder user across the codebase.src/routes/_tutorial._db.tsx (1)
26-36: Proper initialization of user preferences on route mount.The effect correctly checks for existing preferences before inserting, preventing duplicates. The SSR guard (
typeof window !== "undefined") is a good defensive practice even withssr: falseon the route.src/routes/_tutorial._db.projects.tsx (3)
27-37: Good reactive query pattern for user preferences.The
useLiveQuerycorrectly fetches user preferences filtered by the placeholder user ID. This ensures the layout reactively responds to preference changes.
42-65: Well-implemented resizable panel layout.The conditional rendering of the API requests panel based on
networkPanelstate works correctly. The size constraints (minSize={50},minSize={15},maxSize={50}) provide reasonable bounds for the resizable panels. ThedefaultSizecorrectly adjusts based on whether the panel is open.
43-46: The code already handles undefined preferences gracefully.When
userPreferencesis undefined,defaultSizeevaluates to 100 and the main panel renders at full width—this is the intended behavior. The parent route (_tutorial._db.tsx) has abeforeLoadhook that initializes the database and ensures the user preferences record exists via auseEffect, plus it displays a loading state (FakeProgressIndicator) during initialization. The secondaryApiRequestsPanelis already conditionally rendered only whenuserPreferences?.networkPanel === "open"(line 52), so no additional handling is needed here.Actionable comments posted: 2
🧹 Nitpick comments (1)
src/components/ApiRequestsPanel.tsx (1)
78-94: Consider extracting method color logic to a helper function.The deeply nested ternary for method badge colors could be extracted to a helper function for improved readability and maintainability.
🔎 Proposed refactor
Add this helper function near the top of the file:
function getMethodColorClasses(method: ApiRequest["method"]): string { switch (method) { case "GET": return "bg-blue-100 text-blue-700 border-blue-700/30 dark:bg-blue-500/20 dark:text-blue-400 dark:border-blue-500/30"; case "POST": return "bg-green-200 text-green-700 border-green-400 dark:bg-green-500/20 dark:text-green-400 dark:border-green-500/30"; case "PATCH": return "bg-yellow-200 text-yellow-700 border-yellow-700/30 dark:bg-yellow-500/20 dark:text-yellow-400 dark:border-yellow-500/30"; case "DELETE": return "bg-red-100 text-red-500 border-red-400 dark:bg-red-500/20 dark:text-red-400 dark:border-red-500/30"; default: return "bg-gray-200 text-gray-600 border-gray-400 dark:bg-gray-500/20 dark:text-gray-400 dark:border-gray-500/30"; } }Then simplify the Badge:
<Badge variant="outline" - className={cn( - `font-mono text-[10px] px-1.5 py-0`, - request.method === "GET" - ? "bg-blue-100 text-blue-700 border-blue-700/30 dark:bg-blue-500/20 dark:text-blue-400 dark:border-blue-500/30" - : request.method === "POST" - ? "bg-green-200 text-green-700 border-green-400 dark:bg-green-500/20 dark:text-green-400 dark:border-green-500/30" - : request.method === "PATCH" - ? "bg-yellow-200 text-yellow-700 border-yellow-700/30 dark:bg-yellow-500/20 dark:text-yellow-400 dark:border-yellow-500/30" - : request.method === "DELETE" - ? "bg-red-100 text-red-500 border-red-400 dark:bg-red-500/20 dark:text-red-400 dark:border-red-500/30" - : "bg-gray-200 text-gray-600 border-gray-400 dark:bg-gray-500/20 dark:text-gray-400 dark:border-gray-500/30", - )} + className={cn("font-mono text-[10px] px-1.5 py-0", getMethodColorClasses(request.method))} >📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between fd9af9446de6aed12612a386de2b16cd7a24c421 and b7130124859c790dc1cf569ed54ef211cad7b81a.
📒 Files selected for processing (1)
src/components/ApiRequestsPanel.tsx
🧰 Additional context used
📓 Path-based instructions (2)
src/**/*.{tsx,ts}
📄 CodeRabbit inference engine (AGENTS.md)
src/**/*.{tsx,ts}: The project uses TanStack Start framework (@tanstack/start) with React for the frontend Useshadcn/uifor UI componentsFiles:
src/components/ApiRequestsPanel.tsx
src/**/*.{tsx,ts,css}
📄 CodeRabbit inference engine (AGENTS.md)
Use
tailwindcss(v4) for stylingFiles:
src/components/ApiRequestsPanel.tsx
🧠 Learnings (1)
📚 Learning: 2025-12-24T15:25:07.106Z
Learnt from: fulopkovacs Repo: fulopkovacs/trytanstackdb.com PR: 22 File: src/components/TodoBoards.tsx:63-81 Timestamp: 2025-12-24T15:25:07.106Z Learning: In Tailwind CSS v4, prefer canonical classes using bg-linear-to-* (e.g., bg-linear-to-b, bg-linear-to-t, bg-linear-to-r) over the older bg-gradient-to-* syntax. This aligns with Tailwind LSP's suggestCanonicalClasses rule. Apply across TSX files (e.g., src/components/*.tsx); replace occurrences of bg-gradient-to-* with the corresponding bg-linear-to-* equivalents and verify gradients visually.Applied to files:
src/components/ApiRequestsPanel.tsx
🧬 Code graph analysis (1)
src/components/ApiRequestsPanel.tsx (2)
src/collections/apiRequests.ts (2)
apiRequestsCollection(17-28)ApiRequest(6-15)
src/lib/utils.ts (1)
cn(4-6)
🪛 GitHub Actions: CI/CD
src/components/ApiRequestsPanel.tsx
[warning] 1-1: assist/source/organizeImports: Imports are not organized. Run Biome organize imports.
🔇 Additional comments (1)
src/components/ApiRequestsPanel.tsx (1)
141-192: LGTM! Clean component structure.The main component is well-structured with:
- Proper use of
useLiveQueryfor reactive data - Clean layout with header, scrollable content, and empty state
- Good accessibility practices (sr-only text, semantic button elements)
- Appropriate use of shadcn/ui primitives
The descending timestamp order (newest first) pairs well with the absence of auto-scroll, making new requests immediately visible at the top.
@@ -0,0 +1 @@1+import { useLiveQuery } from "@tanstack/react-db";⚠️ Potential issue | 🟡 Minor
Organize imports per Biome configuration.
The pipeline reports that imports are not organized according to the project's Biome rules.
Run the following command to fix:
npx biome check --write src/components/ApiRequestsPanel.tsx🧰 Tools
🪛 GitHub Actions: CI/CD
[warning] 1-1: assist/source/organizeImports: Imports are not organized. Run Biome organize imports.
🤖 Prompt for AI Agents
In src/components/ApiRequestsPanel.tsx around line 1 the imports are not organized per the project's Biome configuration; run the formatter/organizer or manually reorder and fix imports to match Biome rules (group external packages, then internal modules, remove unused imports, and apply the established sort order), or simply run the suggested command `npx biome check --write src/components/ApiRequestsPanel.tsx` to auto-fix the import ordering and formatting.✅ Addressed in commit 6ef7218
src/components/ApiRequestsPanel.tsx line 104Outdated@@ -0,0 +84,21 @@84+ : request.method === "POST"85+ ? "bg-green-200 text-green-700 border-green-400 dark:bg-green-500/20 dark:text-green-400 dark:border-green-500/30"86+ : request.method === "PATCH"87+ ? "bg-yellow-200 text-yellow-700 border-yellow-700/30 dark:bg-yellow-500/20 dark:text-yellow-400 dark:border-yellow-500/30"88+ : request.method === "DELETE"89+ ? "bg-red-100 text-red-500 border-red-400 dark:bg-red-500/20 dark:text-red-400 dark:border-red-500/30"90+ : "bg-gray-200 text-gray-600 border-gray-400 dark:bg-gray-500/20 dark:text-gray-400 dark:border-gray-500/30",91+ )}92+ >93+ {request.method}94+ </Badge>95+ <span className="flex-1 font-mono text-xs truncate">96+ {request.pathname}97+ </span>98+ {isPending ? (99+ <LoaderIcon className="h-3 w-3 text-orange-400 animate-spin" />100+ ) : (101+ <span102+ className={cn(103+ "text-xs font-mono",104+ request.status === "pending"⚠️ Potential issue | 🟡 Minor
Remove unreachable condition.
At Line 104, the check
request.status === "pending"can never be true because this code is inside the!isPendingbranch. SinceisPendingis defined asrequest.status === "pending"(Line 68), whenisPendingis false, the status cannot be"pending".🔎 Proposed fix
<span className={cn( "text-xs font-mono", - request.status === "pending" - ? "text-orange-400 dark:text-orange-300" - : request.status >= 200 && request.status < 300 + request.status >= 200 && request.status < 300 ? "text-green-500 dark:text-green-300" : request.status >= 400 ? "text-destructive" : "text-yellow-500 dark:text-yellow-400", )} >📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
<span className={cn( "text-xs font-mono", request.status >= 200 && request.status < 300 ? "text-green-500 dark:text-green-300" : request.status >= 400 ? "text-destructive" : "text-yellow-500 dark:text-yellow-400", )} >🤖 Prompt for AI Agents
In src/components/ApiRequestsPanel.tsx around line 104, the condition `request.status === "pending"` is unreachable because this code is inside the branch where `isPending` (defined as `request.status === "pending"` at line 68) is false; remove that redundant check and either (a) delete the condition entirely and rely on the surrounding non-pending branch logic, or (b) replace it with the correct status check intended for this branch (e.g., `"completed"`/`"failed"`/`"running"`) so the condition can actually be true.Actionable comments posted: 0
♻️ Duplicate comments (2)
src/components/ApiRequestsPanel.tsx (2)
1-1: Organize imports per Biome configuration.The pipeline reports that imports are not organized according to the project's Biome rules.
Run the following command to fix:
npx biome check --write src/components/ApiRequestsPanel.tsx
104-104: Remove unreachable condition.At Line 104, the check
request.status === "pending"can never be true because this code is inside the!isPendingbranch. SinceisPendingis defined asrequest.status === "pending"(Line 68), whenisPendingis false, the status cannot be"pending".🔎 Proposed fix
<span className={cn( "text-xs font-mono", - request.status === "pending" - ? "text-orange-400 dark:text-orange-300" - : request.status >= 200 && request.status < 300 + request.status >= 200 && request.status < 300 ? "text-green-500 dark:text-green-300" : request.status >= 400 ? "text-destructive" : "text-yellow-500 dark:text-yellow-400", )} >🧹 Nitpick comments (1)
src/components/ApiRequestsPanel.tsx (1)
78-94: Consider extracting method color logic to a helper function.The nested ternary chain spanning lines 82-90 is quite long and could be harder to maintain. Extracting this logic into a helper function would improve readability.
🔎 Proposed refactor
Add this helper function before the
RequestItemcomponent:function getMethodColor(method: ApiRequest["method"]) { const colors = { GET: "bg-blue-100 text-blue-700 border-blue-700/30 dark:bg-blue-500/20 dark:text-blue-400 dark:border-blue-500/30", POST: "bg-green-200 text-green-700 border-green-400 dark:bg-green-500/20 dark:text-green-400 dark:border-green-500/30", PATCH: "bg-yellow-200 text-yellow-700 border-yellow-700/30 dark:bg-yellow-500/20 dark:text-yellow-400 dark:border-yellow-500/30", DELETE: "bg-red-100 text-red-500 border-red-400 dark:bg-red-500/20 dark:text-red-400 dark:border-red-500/30", }; return colors[method] ?? "bg-gray-200 text-gray-600 border-gray-400 dark:bg-gray-500/20 dark:text-gray-400 dark:border-gray-500/30"; }Then simplify the Badge className:
<Badge variant="outline" className={cn( `font-mono text-[10px] px-1.5 py-0`, - request.method === "GET" - ? "bg-blue-100 text-blue-700 border-blue-700/30 dark:bg-blue-500/20 dark:text-blue-400 dark:border-blue-500/30" - : request.method === "POST" - ? "bg-green-200 text-green-700 border-green-400 dark:bg-green-500/20 dark:text-green-400 dark:border-green-500/30" - : request.method === "PATCH" - ? "bg-yellow-200 text-yellow-700 border-yellow-700/30 dark:bg-yellow-500/20 dark:text-yellow-400 dark:border-yellow-500/30" - : request.method === "DELETE" - ? "bg-red-100 text-red-500 border-red-400 dark:bg-red-500/20 dark:text-red-400 dark:border-red-500/30" - : "bg-gray-200 text-gray-600 border-gray-400 dark:bg-gray-500/20 dark:text-gray-400 dark:border-gray-500/30", + getMethodColor(request.method), )} >📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between b7130124859c790dc1cf569ed54ef211cad7b81a and 6ef72184a54803318d03e9162b11559020383050.
📒 Files selected for processing (1)
src/components/ApiRequestsPanel.tsx
🧰 Additional context used
📓 Path-based instructions (2)
src/**/*.{tsx,ts}
📄 CodeRabbit inference engine (AGENTS.md)
src/**/*.{tsx,ts}: The project uses TanStack Start framework (@tanstack/start) with React for the frontend Useshadcn/uifor UI componentsFiles:
src/components/ApiRequestsPanel.tsx
src/**/*.{tsx,ts,css}
📄 CodeRabbit inference engine (AGENTS.md)
Use
tailwindcss(v4) for stylingFiles:
src/components/ApiRequestsPanel.tsx
🧠 Learnings (1)
📚 Learning: 2025-12-24T15:25:07.106Z
Learnt from: fulopkovacs Repo: fulopkovacs/trytanstackdb.com PR: 22 File: src/components/TodoBoards.tsx:63-81 Timestamp: 2025-12-24T15:25:07.106Z Learning: In Tailwind CSS v4, prefer canonical classes using bg-linear-to-* (e.g., bg-linear-to-b, bg-linear-to-t, bg-linear-to-r) over the older bg-gradient-to-* syntax. This aligns with Tailwind LSP's suggestCanonicalClasses rule. Apply across TSX files (e.g., src/components/*.tsx); replace occurrences of bg-gradient-to-* with the corresponding bg-linear-to-* equivalents and verify gradients visually.Applied to files:
src/components/ApiRequestsPanel.tsx
🧬 Code graph analysis (1)
src/components/ApiRequestsPanel.tsx (2)
src/collections/apiRequests.ts (2)
apiRequestsCollection(17-28)ApiRequest(6-15)
src/lib/utils.ts (1)
cn(4-6)
🔇 Additional comments (2)
src/components/ApiRequestsPanel.tsx (2)
40-64: LGTM!The
JsonViewercomponent correctly handles null/undefined cases and provides a clean collapsible interface for JSON payloads.
141-192: LGTM!The main
ApiRequestsPanelcomponent correctly usesuseLiveQueryto fetch and order API requests, renders a clean header with request count and clear functionality, and provides a scrollable list with appropriate empty state messaging.fuko merged thisc160dd4
fuko closed this
Sign in to join this conversation.
Walkthrough#
Adds API request tracking and an API-latency configurator: new collections (apiRequests, userPreferences), UI for viewing/toggling live API requests, latency simulation wired into request processing, layout changes to surface the requests panel, plus related utilities, styles, and docs updates.
Changes#
AGENTS.md,src/data/tutorial/optimistic-updates.mdxsrc/utils/apiLatency.ts,src/utils/USER_PLACEHOLDER_CONSTANT.tsUSER_PLACEHOLDERconstant.src/collections/apiRequests.ts,src/collections/UserPreferences.tsApiRequesttype andapiRequestsCollection(local-only); newuserPreferencesCollection(localStorage-backed).src/client/pgliteHelpers.tssrc/components/ApiLatencyConfigurator.tsxapiLatencyschema/options and storage key; updated labels/IDs.src/components/ApiRequestsPanel.tsx,src/components/ApiPanelToggle.tsxuserPreferences.src/routes/_tutorial._db.projects.tsx,src/routes/_tutorial._db.tsxuserPreferences; client effect to seedUSER_PLACEHOLDER.src/components/Header.tsx,src/components/AppSidebar.tsx,src/components/tutorial/index.tsxApiLatencyConfiguratorand includesApiPanelToggle; removedSidebarHeader; tutorial highlight enum updated toapiLatencyConfigurator.src/components/ui/resizable.tsx,src/components/ui/sidebar.tsx,src/styles.css,src/routes/__root.tsx.coderabbit.yamlin_progress_fortune: falseflag under reviews.Sequence Diagram(s)#
Estimated code review effort#
🎯 4 (Complex) | ⏱️ ~45 minutes
Possibly related PRs#
Pre-merge checks and finishing touches#
❌ Failed checks (1 warning)
@coderabbitai generate docstringsto improve docstring coverage.✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands and usage tips.