Skip to content

[Playground] Refactor AI types and move definitions to types.ts#7964

Merged
joaquim-verges merged 1 commit into
mainfrom
Refactor_AI_types_and_move_definitions_to_types.ts
Sep 2, 2025
Merged

[Playground] Refactor AI types and move definitions to types.ts#7964
joaquim-verges merged 1 commit into
mainfrom
Refactor_AI_types_and_move_definitions_to_types.ts

Conversation

@joaquim-verges

@joaquim-verges joaquim-verges commented Sep 2, 2025

Copy link
Copy Markdown
Member

PR-Codex overview

This PR primarily focuses on refactoring and reorganizing type definitions related to NebulaContext, NebulaSwapData, and NebulaUserMessage. It enhances type imports in chat.ts and types.ts, while simplifying and consolidating type structures for better clarity and usability.

Detailed summary

  • Moved type imports to chat.ts from local definitions.
  • Consolidated NebulaContext, NebulaSwapData, and NebulaUserMessage types in types.ts.
  • Simplified ChatMessage structure with new types.
  • Updated properties in RenderMessage to align with new type definitions.
  • Removed redundant type definitions in ChatPageContent.tsx.

✨ Ask PR-Codex anything about this PR by commenting with /codex {your question}

Summary by CodeRabbit

  • Refactor
    • Centralized shared API types to reduce duplication and ensure consistent data shapes across the chat experience.
    • Standardized transaction/message field naming for better alignment and future compatibility.
    • Improved typing for wallet metadata and image content to support clearer rendering and interactions.
    • Streamlined imports and removed local type definitions for a cleaner, more maintainable codebase.
    • No functional or UI changes expected; existing chat behavior, streaming, and actions continue to work as before.

@vercel

vercel Bot commented Sep 2, 2025

Copy link
Copy Markdown

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

Project Deployment Preview Comments Updated (UTC)
thirdweb_playground Ready Ready Preview Comment Sep 2, 2025 8:53am
4 Skipped Deployments
Project Deployment Preview Comments Updated (UTC)
docs-v2 Skipped Skipped Sep 2, 2025 8:53am
nebula Skipped Skipped Sep 2, 2025 8:53am
thirdweb-www Skipped Skipped Sep 2, 2025 8:53am
wallet-ui Skipped Skipped Sep 2, 2025 8:53am

@vercel vercel Bot temporarily deployed to Preview – thirdweb-www September 2, 2025 08:49 Inactive
@vercel vercel Bot temporarily deployed to Preview – docs-v2 September 2, 2025 08:49 Inactive
@vercel vercel Bot temporarily deployed to Preview – wallet-ui September 2, 2025 08:49 Inactive
@vercel vercel Bot temporarily deployed to Preview – nebula September 2, 2025 08:49 Inactive
@changeset-bot

changeset-bot Bot commented Sep 2, 2025

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 40ba112

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai

coderabbitai Bot commented Sep 2, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Centralizes 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

Cohort / File(s) Summary of Changes
Centralized API types and constants
apps/playground-web/src/app/ai/api/types.ts
Added API_URL constant; introduced/expanded public types: NebulaContext, NebulaSwapData, WalletMeta, ChatMessage; extended NebulaUserMessageContentItem image variant with image_url and b64; consolidated NebulaTxData/NebulaUserMessage exports.
API chat imports consolidation
apps/playground-web/src/app/ai/api/chat.ts
Removed inline API_URL and Nebula type declarations; now imports API_URL, NebulaContext, NebulaSwapData, NebulaTxData, NebulaUserMessage from ./types; logic unchanged.
UI component type adoption and field alignment
apps/playground-web/src/app/ai/components/ChatPageContent.tsx
Replaced local type definitions with imports from ../api/types (ChatMessage, NebulaContext, NebulaUserMessage, WalletMeta); updated references from chainId to chain_id in rendering and transaction construction; adjusted ConnectButton/TransactionButton usages accordingly.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Warning

Review ran into problems

🔥 Problems

Errors were encountered while retrieving linked issues.

Errors (1)
  • TEAM-0000: Entity not found: Issue - Could not find referenced Issue.
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch Refactor_AI_types_and_move_definitions_to_types.ts

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions github-actions Bot added the Playground Changes involving the Playground codebase. label Sep 2, 2025
@joaquim-verges joaquim-verges changed the title Refactor AI types and move definitions to types.ts [Playground] Refactor AI types and move definitions to types.ts Sep 2, 2025
@joaquim-verges joaquim-verges marked this pull request as ready for review September 2, 2025 08:50

Copy link
Copy Markdown
Member Author

How to use the Graphite Merge Queue

Add either label to this PR to merge it via the merge queue:

  • merge-queue - adds this PR to the back of the merge queue
  • hotfix - for urgent hot fixes, skip the queue and merge this PR next

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.

@joaquim-verges joaquim-verges requested review from a team as code owners September 2, 2025 08:50
@codecov

codecov Bot commented Sep 2, 2025

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 56.52%. Comparing base (89eeac1) to head (40ba112).
⚠️ Report is 5 commits behind head on main.

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     
Flag Coverage Δ
packages 56.52% <ø> (-0.02%) ⬇️
see 2 files with indirect coverage changes
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actions

github-actions Bot commented Sep 2, 2025

Copy link
Copy Markdown
Contributor

size-limit report 📦

Path Size Loading time (3g) Running time (snapdragon) Total time
thirdweb (esm) 64.01 KB (0%) 1.3 s (0%) 235 ms (+196.69% 🔺) 1.6 s
thirdweb (cjs) 357.32 KB (0%) 7.2 s (0%) 700 ms (+17.45% 🔺) 7.9 s
thirdweb (minimal + tree-shaking) 5.73 KB (0%) 115 ms (0%) 72 ms (+954% 🔺) 186 ms
thirdweb/chains (tree-shaking) 526 B (0%) 11 ms (0%) 56 ms (+3402.97% 🔺) 66 ms
thirdweb/react (minimal + tree-shaking) 19.15 KB (0%) 383 ms (0%) 86 ms (+542.72% 🔺) 469 ms

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 NaN in chain_ids and replaces the loose Record with 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 in types.ts mix concerns; a constants.ts would 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 undefined simplifies checks and aligns with typical TS style for optional fields.


39-56: Align hex-address typing and tx value semantics.

transaction.to is correctly constrained to 0x${string} here. Consider matching NebulaTxData.to to 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 NebulaSwapData doesn'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. Prefer request_id when 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 undefined before 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 7eed8e6 and 40ba112.

📒 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 @/types or local types.ts barrels
Prefer type aliases over interface except for nominal shapes
Avoid any and unknown unless 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 @/types where applicable
Prefer type aliases over interface except for nominal shapes
Avoid any and unknown unless 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.ts
  • apps/playground-web/src/app/ai/components/ChatPageContent.tsx
  • apps/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.ts
  • apps/playground-web/src/app/ai/components/ChatPageContent.tsx
  • apps/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
Use NavLink for internal navigation with automatic active states in dashboard and playground apps
Use Tailwind CSS only – no inline styles or CSS modules
Use cn() from @/lib/utils for conditional class logic
Use design system tokens (e.g., bg-card, border-border, text-muted-foreground)
Server Components (Node edge): Start files with import "server-only";
Client Components (browser): Begin files with 'use client';
Always call getAuthToken() to retrieve JWT from cookies on server side
Use Authorization: Bearer header – never embed tokens in URLs
Return typed results (e.g., Project[], User[]) – avoid any
Wrap client-side data fetching calls in React Query (@tanstack/react-query)
Use descriptive, stable queryKeys for React Query cache hits
Configure staleTime/cacheTime in React Query based on freshness (default ≥ 60s)
Keep tokens secret via internal API routes or server actions
Never import posthog-js in server components

Files:

  • apps/playground-web/src/app/ai/api/types.ts
  • apps/playground-web/src/app/ai/components/ChatPageContent.tsx
  • apps/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.ts file

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.

@joaquim-verges joaquim-verges merged commit df6f8e2 into main Sep 2, 2025
27 checks passed
@joaquim-verges joaquim-verges deleted the Refactor_AI_types_and_move_definitions_to_types.ts branch September 2, 2025 09:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Playground Changes involving the Playground codebase.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant