[Playground] Refactor AI types and move definitions to types.ts#7964
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
WalkthroughCentralizes API_URL and Nebula-related types into a shared types module. Updates chat API file to import constants and types from the new module. Refactors ChatPageContent to consume these public types and adjust transaction field names from chainId to chain_id in usage. No functional behavior changes reported. Changes
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Warning Review ran into problems🔥 ProblemsErrors were encountered while retrieving linked issues. Errors (1)
✨ Finishing Touches
🧪 Generate unit tests
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
How to use the Graphite Merge QueueAdd either label to this PR to merge it via the merge queue:
You must have a Graphite account in order to use the merge queue. Sign up using this link. An organization admin has enabled the Graphite Merge Queue in this repository. Please do not merge from GitHub as this will restart CI on PRs being processed by the merge queue. This stack of pull requests is managed by Graphite. Learn more about stacking. |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #7964 +/- ##
==========================================
- Coverage 56.53% 56.52% -0.02%
==========================================
Files 904 904
Lines 58623 58623
Branches 4146 4146
==========================================
- Hits 33144 33138 -6
- Misses 25373 25380 +7
+ Partials 106 105 -1
🚀 New features to boost your workflow:
|
size-limit report 📦
|
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
apps/playground-web/src/app/ai/api/chat.ts (1)
16-27: Strongly type request body and filter invalid chain IDs.Avoids
NaNinchain_idsand replaces the looseRecordwith a proper shape.- const body: Record<string, string | boolean | object> = { + type ChatBody = { + messages: NebulaUserMessage[]; + stream: true; + context?: { + chain_ids: number[]; + session_id?: string; + wallet_address: string | null; + }; + }; + const body: ChatBody = { messages: [params.message], stream: true, }; @@ - body.context = { - chain_ids: params.context.chainIds?.map(Number) || [], + body.context = { + chain_ids: (params.context.chainIds ?? []) + .map((x) => Number(x)) + .filter((x) => Number.isFinite(x)), session_id: params.context.sessionId ?? undefined, wallet_address: params.context.walletAddress, };
🧹 Nitpick comments (11)
apps/playground-web/src/app/ai/api/types.ts (4)
1-1: Normalize API_URL and avoid double schemes; consider moving constant out of types barrel.Prevents
https://https://...and trailing slash issues. Constants intypes.tsmix concerns; aconstants.tswould be cleaner.-export const API_URL = `https://${process.env.NEXT_PUBLIC_API_URL || "api.thirdweb.com"}`; +export const API_URL = (() => { + const raw = (process.env.NEXT_PUBLIC_API_URL ?? "api.thirdweb.com").trim(); + const withScheme = raw.startsWith("http") ? raw : `https://${raw}`; + return withScheme.replace(/\/+$/, ""); +})();
33-37: Prefer undefined over null for optionals.Using
undefinedsimplifies checks and aligns with typical TS style for optional fields.
39-56: Align hex-address typing and tx value semantics.
transaction.tois correctly constrained to0x${string}here. Consider matchingNebulaTxData.toto the same constraint for consistency.export type NebulaTxData = { chain_id: number; data: `0x${string}`; - to: string; + to: `0x${string}`; value: string; };
64-76: Preserve presence source (optional).The server presence payload includes
source; keeping it helps UX/debugging while remaining backward‑compatible.| { texts: string[]; type: "presence"; + source?: "user" | "reviewer" | (string & {}); }apps/playground-web/src/app/ai/api/chat.ts (3)
10-15: Add explicit return type.Matches repo TS guideline for explicit return types.
-export async function promptNebula(params: { +export async function promptNebula(params: { message: NebulaUserMessage; handleStream: (res: ChatStreamedResponse) => void; abortController: AbortController; context: undefined | NebulaContext; -}) { +}): Promise<void> {
46-55: Parse JSON once and guard shape for delta events.Prevents repeated parsing and accidental undefined access.
- params.handleStream({ - data: { - v: JSON.parse(event.data).v, - }, - event: "delta", - }); + const parsed = JSON.parse(event.data) as { v?: string }; + if (typeof parsed.v !== "string") break; + params.handleStream({ data: { v: parsed.v }, event: "delta" });
83-112: Runtime type safety for action payloads.
as NebulaTxData/as NebulaSwapDatadoesn't validate. Consider a lightweight type guard (or zod) to fail fast on malformed payloads.If you want, I can add minimal type guards like
isNebulaTxData()/isNebulaSwapData()here.apps/playground-web/src/app/ai/components/ChatPageContent.tsx (4)
190-193: Avoid empty-string addresses in connectedWalletsMeta.Filter wallets without an address to prevent downstream surprises.
- const connectedWalletsMeta: WalletMeta[] = connectedWallets.map((x) => ({ - address: x.getAccount()?.address || "", - walletId: x.id, - })); + const connectedWalletsMeta: WalletMeta[] = connectedWallets + .map((x) => { + const addr = x.getAccount()?.address; + return addr ? { address: addr, walletId: x.id } : undefined; + }) + .filter((x): x is WalletMeta => !!x);
506-509: Use stable keys.
{${index}-${message}}stringifies objects to[object Object]and can be unstable. Preferrequest_idwhen available, else index.- key={`${index}-${message}`} + key={ + message.type === "assistant" && message.request_id + ? message.request_id + : `m-${index}` + }
655-656: Minor: Avoid repeated defineChain calls.Cache
defineChain(id)locally for the block to reduce repeated work.Also applies to: 671-672, 688-689
695-698: Guard empty presence messages.Prevents rendering
undefinedbefore the first presence text arrives.- {message.texts[message.texts.length - 1]} + {message.texts.length > 0 + ? message.texts[message.texts.length - 1] + : "Thinking..."}
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (3)
apps/playground-web/src/app/ai/api/chat.ts(1 hunks)apps/playground-web/src/app/ai/api/types.ts(2 hunks)apps/playground-web/src/app/ai/components/ChatPageContent.tsx(4 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.{ts,tsx}: Write idiomatic TypeScript with explicit function declarations and return types
Limit each file to one stateless, single-responsibility function for clarity
Re-use shared types from@/typesor localtypes.tsbarrels
Prefer type aliases over interface except for nominal shapes
Avoidanyandunknownunless unavoidable; narrow generics when possible
Choose composition over inheritance; leverage utility types (Partial,Pick, etc.)
Comment only ambiguous logic; avoid restating TypeScript in prose
**/*.{ts,tsx}: Use explicit function declarations and explicit return types in TypeScript
Limit each file to one stateless, single‑responsibility function
Re‑use shared types from@/typeswhere applicable
Prefertypealiases overinterfaceexcept for nominal shapes
Avoidanyandunknownunless unavoidable; narrow generics when possible
Prefer composition over inheritance; use utility types (Partial, Pick, etc.)
Lazy‑import optional features and avoid top‑level side‑effects to reduce bundle size
Files:
apps/playground-web/src/app/ai/api/types.tsapps/playground-web/src/app/ai/components/ChatPageContent.tsxapps/playground-web/src/app/ai/api/chat.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (CLAUDE.md)
Load heavy dependencies inside async paths to keep initial bundle lean (lazy loading)
Files:
apps/playground-web/src/app/ai/api/types.tsapps/playground-web/src/app/ai/components/ChatPageContent.tsxapps/playground-web/src/app/ai/api/chat.ts
apps/{dashboard,playground-web}/**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
apps/{dashboard,playground-web}/**/*.{ts,tsx}: Import UI primitives from@/components/ui/*(Button, Input, Select, Tabs, Card, Sidebar, Badge, Separator) in dashboard and playground apps
UseNavLinkfor internal navigation with automatic active states in dashboard and playground apps
Use Tailwind CSS only – no inline styles or CSS modules
Usecn()from@/lib/utilsfor conditional class logic
Use design system tokens (e.g.,bg-card,border-border,text-muted-foreground)
Server Components (Node edge): Start files withimport "server-only";
Client Components (browser): Begin files with'use client';
Always callgetAuthToken()to retrieve JWT from cookies on server side
UseAuthorization: Bearerheader – never embed tokens in URLs
Return typed results (e.g.,Project[],User[]) – avoidany
Wrap client-side data fetching calls in React Query (@tanstack/react-query)
Use descriptive, stablequeryKeysfor React Query cache hits
ConfigurestaleTime/cacheTimein React Query based on freshness (default ≥ 60s)
Keep tokens secret via internal API routes or server actions
Never importposthog-jsin server components
Files:
apps/playground-web/src/app/ai/api/types.tsapps/playground-web/src/app/ai/components/ChatPageContent.tsxapps/playground-web/src/app/ai/api/chat.ts
**/types.ts
📄 CodeRabbit inference engine (AGENTS.md)
Provide and re‑use local type barrels in a
types.tsfile
Files:
apps/playground-web/src/app/ai/api/types.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
- GitHub Check: E2E Tests (pnpm, vite)
- GitHub Check: E2E Tests (pnpm, esbuild)
- GitHub Check: Size
- GitHub Check: Lint Packages
- GitHub Check: Analyze (javascript)
🔇 Additional comments (3)
apps/playground-web/src/app/ai/api/types.ts (1)
58-63: LGTM on WalletMeta.Simple, reusable shape matches usage in ChatPage.
apps/playground-web/src/app/ai/api/chat.ts (1)
2-8: LGTM: Centralized imports.Importing API_URL and types from the barrel reduces duplication.
apps/playground-web/src/app/ai/components/ChatPageContent.tsx (1)
34-40: LGTM: Consuming centralized types.Imports from the shared types module look consistent.

PR-Codex overview
This PR primarily focuses on refactoring and reorganizing type definitions related to
NebulaContext,NebulaSwapData, andNebulaUserMessage. It enhances type imports inchat.tsandtypes.ts, while simplifying and consolidating type structures for better clarity and usability.Detailed summary
chat.tsfrom local definitions.NebulaContext,NebulaSwapData, andNebulaUserMessagetypes intypes.ts.ChatMessagestructure with new types.RenderMessageto align with new type definitions.ChatPageContent.tsx.Summary by CodeRabbit