Skip to content

[Grida AI] Image Playground - #313

Merged
softmarshmallow merged 10 commits into
mainfrom
ai
Apr 29, 2025
Merged

softmarshmallow merged 10 commits into
mainfrom
ai

Conversation

@softmarshmallow

@softmarshmallow softmarshmallow commented Apr 29, 2025 •

Copy link
Copy Markdown
Member

Image Playground - for Model testing

day-228-grida-ai-image-playground.mp4

Summary by CodeRabbit

  • New Features

    • Introduced an interactive Image Playground for generating AI images with prompt input, model and size selection, and credit tracking.
    • Added display of remaining AI credits and reset time for authenticated users.
    • Added API endpoints to fetch available OpenAI models and remaining AI credits.
    • New rate limiting system for AI image generation using user-based credits.
  • Enhancements

    • Modularized and improved the resource card layout in the library with a new ImageCard component.
    • Expanded and documented available AI image models with detailed metadata.
    • Improved tooltip support by wrapping the main layout with a tooltip provider.
    • Enhanced ChatBox with customizable file type acceptance and placeholder text.
    • Enabled image file input support in chat component.
  • Bug Fixes

    • Conditional rendering of color swatches and generator info in library object details to prevent empty displays.
  • Refactor

    • Switched image model fetching to a dedicated OpenAI models endpoint.
    • Updated image generation API to support broader model input and improved metadata in responses.
    • Replaced direct OpenAI API calls with a unified model registry.
  • Chores

    • Updated react-timer-hook dependency to the latest version.
  • Removals

    • Removed the previous AI image playground component in favor of the new, feature-rich playground.

@codesandbox

codesandbox Bot commented Apr 29, 2025

Copy link
Copy Markdown

Review or Edit in CodeSandbox

Open the branch in Web Editor • VS Code • Insiders

Open Preview

@vercel

vercel Bot commented Apr 29, 2025 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
grida ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 29, 2025 0:52am
8 Skipped Deployments
Name Status Preview Comments Updated (UTC)
code ⬜️ Ignored (Inspect) Apr 29, 2025 0:52am
legacy ⬜️ Ignored (Inspect) Apr 29, 2025 0:52am
backgrounds ⬜️ Skipped (Inspect) Apr 29, 2025 0:52am
blog ⬜️ Skipped (Inspect) Apr 29, 2025 0:52am
docs ⬜️ Skipped (Inspect) Apr 29, 2025 0:52am
legacy-www ⬜️ Skipped (Inspect) Apr 29, 2025 0:52am
sites ⬜️ Skipped (Inspect) Apr 29, 2025 0:52am
viewer ⬜️ Skipped (Inspect) Apr 29, 2025 0:52am

@coderabbitai

coderabbitai Bot commented Apr 29, 2025 •

Copy link
Copy Markdown

Walkthrough

This update introduces a comprehensive AI image generation playground with enhanced model selection, size configuration, and credit tracking. Several new API endpoints are added for managing AI credits, listing available models, and enforcing rate limits with Upstash Redis. The AI image generation endpoint is refactored to support flexible model input and to integrate the new credit-based rate limiting. The UI now features a modular image playground, improved chat box with customizable file input, and refined resource card components. The AI library is enriched with detailed model metadata and library object types. Tooltips and responsive layouts are introduced for better user experience.

Changes

File(s) Change Summary
editor/app/(api)/private/ai/credits/route.ts
editor/app/(api)/private/ai/ratelimit.ts
Added new API endpoints for fetching remaining AI credits and enforcing credit-based rate limiting using Upstash Redis.
editor/app/(api)/private/ai/generate/image/route.ts Refactored image generation endpoint to support flexible model input, switched to new credit-based rate limiting, improved response typing, and included generation metadata.
editor/app/(api)/private/ai/models/openai/route.ts
editor/app/(api)/private/ai/models/route.ts
Added new endpoint for listing OpenAI models; refactored model listing to use a local AI registry instead of direct OpenAI API calls.
editor/app/(dev)/canvas/tools/ai/_hooks/use-models.ts Updated the model fetch endpoint in the hook to use the new OpenAI models API route.
editor/app/(dev)/canvas/tools/ai/image/page.tsx Deleted the previous image playground page component.
editor/app/(dev)/canvas/tools/ai/page.tsx Updated ChatBox import path and added image file accept prop.
editor/app/(dev)/layout.tsx Wrapped children in a TooltipProvider for global tooltip context.
editor/app/(dev)/playground/image/_components/image-frame.tsx Added a new GenerationImageFrame component for displaying generated images with loading and timing features.
editor/app/(dev)/playground/image/_page.tsx Added a new, comprehensive image playground component with hooks for generation, credits, and model configuration.
editor/app/(dev)/playground/image/page.tsx Added a wrapper page component for the new image playground, including page metadata.
editor/app/(library)/library/o/[id]/page.tsx Improved descriptive text selection, conditional color rendering, and added generator display in the library object page.
editor/app/(library)/library/page.tsx Refactored resource card rendering into a new ImageCard component and improved grid responsiveness and card details.
editor/components/chat/chatbox.tsx Enhanced ChatBox with customizable file input accept type, placeholder, and improved focus/styling.
editor/components/chat/index.ts Re-exported chatbox module for easier imports.
editor/lib/ai/ai.ts Added detailed AI model metadata registry, new types for providers, vendors, and image models, and credit value constant.
editor/lib/library/index.ts Introduced Library namespace with detailed Object and Author types.
editor/package.json Updated "react-timer-hook" dependency version.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant PlaygroundUI
    participant API
    participant RateLimiter
    participant AIModel

    User->>PlaygroundUI: Enter prompt, select model/size, click Generate
    PlaygroundUI->>API: POST /private/ai/generate/image (prompt, model, size)
    API->>RateLimiter: ai_credit_limit()
    RateLimiter-->>API: { success, remaining, headers }
    alt Credits available
        API->>AIModel: generateImage(model, prompt, size)
        AIModel-->>API: { imageUrl, modelId, timestamp }
        API-->>PlaygroundUI: { imageUrl, modelId, timestamp, headers }
    else Out of credits
        API-->>PlaygroundUI: 429 Too Many Requests
    end
    PlaygroundUI-->>User: Display generated image or error
Loading
sequenceDiagram
    participant User
    participant PlaygroundUI
    participant API

    User->>PlaygroundUI: Open playground page
    PlaygroundUI->>API: GET /private/ai/credits
    API-->>PlaygroundUI: { remaining, reset }
    PlaygroundUI-->>User: Show remaining credits
Loading

Poem

In the playground where images bloom,
Credits counted, models loom.
With prompts and sizes, dreams take flight,
A rabbit’s joy in every byte!
Tooltips twinkle, colors bright,
Hop along—create, delight!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between debfb03 and 6c7fb34.

📒 Files selected for processing (2)
  • editor/app/(dev)/playground/image/_page.tsx (1 hunks)
  • editor/components/chat/chatbox.tsx (6 hunks)
✅ Files skipped from review due to trivial changes (1)
  • editor/app/(dev)/playground/image/_page.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • editor/components/chat/chatbox.tsx
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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.
    • Generate unit testing code for this file.
    • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai 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

Documentation and Community

  • 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 10

🔭 Outside diff range comments (2)
editor/app/(api)/private/ai/generate/image/route.ts (2)

80-88: ⚠️ Potential issue

model.modelId may be undefined

openai.image() and replicate.image() usually expose id, not modelId.
Persisting undefined breaks relational integrity and makes the UI show “unknown model”.

-      model: model.modelId,
+      model: (model as any).modelId ?? (model as any).id,

127-178: 🛠️ Refactor suggestion

Mixed use of two Supabase clients

upload_generated_to_library accepts a client argument but still uses service_role.library for the upload. Using two different clients in the same transaction risks permission drift and makes the call site confusing.

Either:

  1. Pass only service_role.library and drop the client parameter, or
  2. Consistently use the injected client everywhere.
-  const { data: uploaded, error: upload_err } =
-    await service_role.library.storage
+  const { data: uploaded, error: upload_err } =
+    await client.storage

and similar for later calls.

🧹 Nitpick comments (12)
editor/app/(api)/private/ai/ratelimit.ts (1)

5-8: Rate limiter configuration seems appropriate.

The sliding window policy of 20 requests per 30 days seems reasonable for an AI image generation service. However, consider making these values configurable through environment variables for easier adjustments.

 const ratelimit = new Ratelimit({
   redis: Redis.fromEnv(),
-  limiter: Ratelimit.slidingWindow(20, "30d"),
+  limiter: Ratelimit.slidingWindow(
+    Number(process.env.AI_CREDIT_LIMIT ?? 20),
+    process.env.AI_CREDIT_PERIOD ?? "30d"
+  ),
 });
editor/lib/ai/ai.ts (2)

84-103: Consider extracting RecraftV3Style to its own file if it grows further.

While the current implementation is fine, if you add more model-specific types in the future, consider moving them to separate files to maintain this file's readability.


105-199: Well-structured model registry with comprehensive metadata.

The model registry provides detailed information about each supported AI model, including size constraints, style options, and pricing. The as const assertion ensures type safety.

Two suggestions for improvement:

  1. Consider adding JSDoc comments to document the purpose and usage of the models constant
  2. It might be worth adding versioning information for each model to track changes over time
editor/app/(api)/private/ai/credits/route.ts (1)

12-21: Simplify the response structure for better readability.

The current response structure has unnecessary nesting and explicit status code that can be simplified.

Consider simplifying the response structure:

-  return NextResponse.json(
-    {
-      data,
-    },
-    {
-      status: 200,
-    }
-  );
+  return NextResponse.json({ data });

The default status is already 200, so it doesn't need to be explicitly specified unless you're setting a different status.

editor/app/(library)/library/page.tsx (1)

91-136: Well-structured ImageCard component with proper typing.

The component has clear prop types and a clean layout structure. However, consider moving this component to a separate file if it will be reused elsewhere in the application.

+// Consider moving this component to a separate file, e.g., components/library/ImageCard.tsx
editor/components/chat/chatbox.tsx (1)

36-36: Fix typo in variable name.

The variable name is misspelled as "attatchment" instead of "attachment".

-const [attatchment, setAttachment] = React.useState<Attachment>();
+const [attachment, setAttachment] = React.useState<Attachment>();

Remember to update all usages of this variable throughout the component (e.g., in lines 83, 100).

editor/app/(dev)/playground/image/_components/image-frame.tsx (2)

1-7: Inconsistent utility import path.

The cn utility is imported from "@/utils" here but from "@/utils/cn" in the ChatBox component.

-import { cn } from "@/utils";
+import { cn } from "@/utils/cn";

60-61: Consider debouncing the timer display.

The timer updates every 100ms which might cause flickering. Consider updating less frequently or using a technique to smooth the display.

-          <span className="font-mono text-xs">
-            {(totalMilliseconds / 1000).toFixed(1)}s
-          </span>
+          <span className="font-mono text-xs">
+            {Math.floor(totalMilliseconds / 100) / 10}s
+          </span>
editor/app/(api)/private/ai/generate/image/route.ts (3)

33-34: Remove or use the captured client IP

const ip = req.headers.get("x-forwarded-for");
The variable is never used, which is a minor dead-code smell. Either pass it to ai_credit_limit() (see next comment) or drop the assignment.


92-99: Use local variable to satisfy the TS ‘satisfies’ check

… satisfies GenerateImageApiResponse inside a function argument is legal but harms readability. Consider preparing the payload first:

-  return NextResponse.json({
-    data: { … },
-  } satisfies GenerateImageApiResponse);
+  const payload: GenerateImageApiResponse = { data: { … } };
+  return NextResponse.json(payload);

187-204: Rename helper to avoid shadowing

The local generateImage shadows the imported experimental_generateImage, which can confuse readers and autocomplete.

-async function generateImage({
+async function generateImageWithSdk({
…
-  return await experimental_generateImage({
+  return experimental_generateImage({
editor/app/(dev)/playground/image/_page.tsx (1)

122-140: Reset size when switching models

Selecting a new model leaves the old size intact, even if the chosen model does not support it, leading to 400-level API errors.

Inside select:

  setCard(ai.image.models[modelId]);
  setModelId(modelId);
+ const firstSupported = ai.image.models[modelId]?.sizes?.[0];
+ if (firstSupported) {
+   const [w, h] = firstSupported;
+   setConfig({ width: w, height: h });
+ }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b038923 and debfb03.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (19)
  • editor/app/(api)/private/ai/credits/route.ts (1 hunks)
  • editor/app/(api)/private/ai/generate/image/route.ts (6 hunks)
  • editor/app/(api)/private/ai/models/openai/route.ts (1 hunks)
  • editor/app/(api)/private/ai/models/route.ts (1 hunks)
  • editor/app/(api)/private/ai/ratelimit.ts (1 hunks)
  • editor/app/(dev)/canvas/tools/ai/_hooks/use-models.ts (1 hunks)
  • editor/app/(dev)/canvas/tools/ai/image/page.tsx (0 hunks)
  • editor/app/(dev)/canvas/tools/ai/page.tsx (2 hunks)
  • editor/app/(dev)/layout.tsx (2 hunks)
  • editor/app/(dev)/playground/image/_components/image-frame.tsx (1 hunks)
  • editor/app/(dev)/playground/image/_page.tsx (1 hunks)
  • editor/app/(dev)/playground/image/page.tsx (1 hunks)
  • editor/app/(library)/library/o/[id]/page.tsx (4 hunks)
  • editor/app/(library)/library/page.tsx (2 hunks)
  • editor/components/chat/chatbox.tsx (6 hunks)
  • editor/components/chat/index.ts (1 hunks)
  • editor/lib/ai/ai.ts (2 hunks)
  • editor/lib/library/index.ts (1 hunks)
  • editor/package.json (1 hunks)
💤 Files with no reviewable changes (1)
  • editor/app/(dev)/canvas/tools/ai/image/page.tsx
🧰 Additional context used
🧬 Code Graph Analysis (2)
editor/components/chat/chatbox.tsx (1)
editor/lib/file/index.ts (1)
  • BucketFileUploaderFn (51-51)
editor/app/(api)/private/ai/ratelimit.ts (1)
editor/lib/supabase/server.ts (1)
  • createClient (41-43)
🔇 Additional comments (36)
editor/package.json (1)

186-186: Package version update looks good.

The update from react-timer-hook v3.0.7 to v4.0.5 is appropriate for supporting new components that utilize timer functionality in the image generation playground.

editor/app/(dev)/layout.tsx (1)

6-6: Good addition of TooltipProvider.

Adding the TooltipProvider at the layout level ensures tooltips are available throughout the application, which is essential for the new image playground UI components.

Also applies to: 36-38

editor/lib/library/index.ts (2)

1-39: Well-structured Library.Object type definition.

The Library.Object type is comprehensive and includes all necessary properties for representing library items with proper type safety. The nullable fields are appropriately marked.


41-52: Clear Author type definition.

The Library.Author type properly defines all properties needed for author entities. This will provide good type safety when working with author data throughout the application.

editor/app/(api)/private/ai/ratelimit.ts (1)

10-19: Good implementation of credit checking function.

The ai_credit_remaining function is well-structured and returns the necessary information without consuming credits.

editor/lib/ai/ai.ts (4)

2-2: Good addition of credit-to-USD conversion constant.

This constant will be useful for calculating costs and displaying pricing information throughout the application.


4-9: Well-defined type system for AI providers and vendors.

The clear separation between providers (service platforms like OpenAI, Replicate) and vendors (actual model creators) provides good structure for the AI system.


58-64: Good type definitions for image sizes and aspect ratios.

These type definitions create a strong type system for working with image dimensions and aspect ratios. The template literal types are particularly well-implemented.


66-82: Comprehensive ImageModelCard type definition.

The type covers all necessary metadata for AI image models including technical constraints, performance characteristics, and credit costs. This will enable consistent handling of different models throughout the application.

editor/app/(dev)/canvas/tools/ai/page.tsx (2)

13-13: Improved import path using module alias.

Good change from relative import to module alias, which improves maintainability.


194-194: Added file type restriction for uploads.

Adding the accept="image/*" prop to ChatBox component is a good enhancement that restricts uploads to image files only, improving the user experience by preventing invalid file uploads.

editor/app/(dev)/canvas/tools/ai/_hooks/use-models.ts (1)

6-8:

Details

❓ Verification inconclusive

Updated API endpoint to use the OpenAI-specific route.

The hook now correctly points to the new OpenAI-specific endpoint /private/ai/models/openai. This change aligns with the new backend routes structure.


🏁 Script executed:

#!/bin/bash
# Verify that the OpenAI models endpoint exists
fd --type file "route.ts" | xargs grep -l "private/ai/models/openai"

Length of output: 66


🏁 Script executed:

#!/bin/bash
# Broadly search for the updated OpenAI models endpoint across all files
rg -n "/private/ai/models/openai"

Length of output: 238


Verify backend route for OpenAI models endpoint

I searched the entire codebase and only found the new /private/ai/models/openai URL in the client hook. There’s no evidence of a corresponding server-side route.
Please confirm that the backend has been updated to expose this endpoint before merging.

• Location needing confirmation:

  • editor/app/(dev)/canvas/tools/ai/_hooks/use-models.ts (lines 6–8)
editor/components/chat/index.ts (1)

1-1: Added barrel export for chat components.

This is a good practice for component organization, making imports cleaner throughout the application. The barrel file makes it easy to import the ChatBox component from @/components/chat instead of having to use longer paths.

editor/app/(api)/private/ai/models/route.ts (1)

2-5: LGTM: Clean implementation using centralized AI configuration.

The change to use the centralized ai module is a good approach. This separates concerns between model definition and API routes, making the code more maintainable.

editor/app/(dev)/playground/image/page.tsx (1)

1-12: LGTM: Clean page implementation with proper metadata.

The implementation follows Next.js best practices with proper metadata configuration and a clean component structure. The separation of the page wrapper from the actual implementation in _page.tsx is a good approach for maintainability.

editor/app/(library)/library/o/[id]/page.tsx (5)

49-51: Good improvement with text fallback mechanism.

Creating a fallback mechanism that selects the first available descriptive string enhances the user experience by ensuring content is always displayed.


52-52: Well-implemented conditional rendering check.

This boolean flag prevents unnecessary rendering when colors are unavailable, which is good for performance optimization.


55-55: Improved container styling.

Enhanced container styling with max-w-4xl mx-auto and text-center improves layout consistency and content alignment.


77-96: Clean conditional rendering of color swatches.

The implementation correctly uses the has_colors check to conditionally render the color swatches section, preventing layout issues when no colors are available.


128-130: Nice addition of generator metadata display.

Adding the conditional display of the generator information enhances the metadata completeness, which is valuable for AI-generated images.

editor/app/(library)/library/page.tsx (4)

7-8: Good type import for improved type safety.

Adding the Library type import from "@/lib/library" strengthens type safety throughout the component.


73-73: Improved responsive grid layout.

The enhanced grid layout with responsive column counts (1 to 5 columns) based on screen size improves the user experience across different devices.


82-82: Good component modularization.

Replacing inline JSX with a dedicated ImageCard component improves code organization and maintainability.


130-130: Consistent author attribution with @ symbol.

Adding the "@" prefix to author names creates a consistent social-media-like attribution style, which is a nice UX touch.

editor/components/chat/chatbox.tsx (6)

7-9: Updated imports for better organization.

The import changes, particularly moving to type-only import for FileIO and updating the cn utility import path, improve code organization.


25-27: Enhanced component flexibility with new props.

Adding customizable placeeholder and accept props improves the component's reusability across different contexts.

Also applies to: 32-34


43-44: Good conditional check for image accept types.

The acceptsImage check elegantly determines whether to show the image upload button based on the accept prop.


72-72: Improved focus management.

Adding a ref to the textarea and focusing it when clicking anywhere in the container enhances the user experience.

Also applies to: 98-98


123-125: Enhanced textarea styling and customization.

The improved textarea styling with proper padding and text size, along with the customizable placeholder, creates a better user experience.


137-146: Well-implemented conditional rendering for image upload.

The image upload button is only shown when the accept prop includes "image/", which is a clean implementation of conditional UI elements.

editor/app/(dev)/playground/image/_components/image-frame.tsx (4)

8-27: Well-structured component props.

The component has clearly defined props with appropriate TypeScript types, making it easy to understand and use.


28-32: Effective use of useStopwatch hook.

The stopwatch configuration with autoStart and customizable interval is a good approach for tracking generation time.


34-38: Good use of useEffect for timer control.

Pausing the timer when the image is loaded is a nice touch that provides accurate timing information.


47-65: Elegant loading and content states.

The conditional rendering with skeleton, shine border effect, and timer during loading, followed by the image when available, creates a polished user experience.

editor/app/(api)/private/ai/generate/image/route.ts (1)

42-49: Pass a user identifier to the rate-limiter

ai_credit_limit() is invoked without any context. If the helper expects a user-ID or IP address, the limiter may always return null or treat all users as the same bucket, defeating the purpose.

-  const rate = await ai_credit_limit();
+  const rate = await ai_credit_limit({
+    userId: userdata.user.id,
+    ip,
+  });

Please check the helper’s signature and ensure it receives enough information to differentiate callers.

editor/app/(dev)/playground/image/_page.tsx (1)

78-84: Validate timestamp parsing

new Date(r.data.timestamp) may yield Invalid Date if the backend returns undefined (see API comment). Add a guard:

-      setEnd(new Date(r.data.timestamp));
+      setEnd(r.data.timestamp ? new Date(r.data.timestamp) : null);

Comment on lines +21 to +46
export async function ai_credit_limit() {
const client = await createClient();

const { data: userdata, error: auth_err } = await client.auth.getUser();
if (auth_err) throw new Error(auth_err.message);
const user_id = userdata.user.id;

// limit
const { success, limit, reset, remaining } = await ratelimit.limit(
`ratelimit_u_${user_id}`
);

const ratelimit_headers = {
"x-ratelimit-limit": limit.toString(),
"x-ratelimit-reset": reset.toString(),
"x-ratelimit-remaining": remaining.toString(),
};

return {
success: success,
limit,
reset,
remaining,
headers: ratelimit_headers,
};
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Credit limiting implementation could be improved.

The ai_credit_limit function works correctly, but there are a few improvements that could be made:

  1. Consider adding error handling for the rate limit operation
  2. The function could be more reusable by accepting a user_id parameter like the ai_credit_remaining function
-export async function ai_credit_limit() {
+export async function ai_credit_limit(options?: { user_id?: string }) {
+  let user_id: string;
+  
+  if (options?.user_id) {
+    user_id = options.user_id;
+  } else {
     const client = await createClient();
  
     const { data: userdata, error: auth_err } = await client.auth.getUser();
     if (auth_err) throw new Error(auth_err.message);
-    const user_id = userdata.user.id;
+    user_id = userdata.user.id;
+  }

   // limit
-  const { success, limit, reset, remaining } = await ratelimit.limit(
-    `ratelimit_u_${user_id}`
-  );
+  try {
+    const { success, limit, reset, remaining } = await ratelimit.limit(
+      `ratelimit_u_${user_id}`
+    );
  
-  const ratelimit_headers = {
-    "x-ratelimit-limit": limit.toString(),
-    "x-ratelimit-reset": reset.toString(),
-    "x-ratelimit-remaining": remaining.toString(),
-  };
+    const ratelimit_headers = {
+      "x-ratelimit-limit": limit.toString(),
+      "x-ratelimit-reset": reset.toString(),
+      "x-ratelimit-remaining": remaining.toString(),
+    };
  
-  return {
-    success: success,
-    limit,
-    reset,
-    remaining,
-    headers: ratelimit_headers,
-  };
+    return {
+      success: success,
+      limit,
+      reset,
+      remaining,
+      headers: ratelimit_headers,
+    };
+  } catch (error) {
+    console.error("Error applying rate limit:", error);
+    throw new Error("Failed to apply rate limit");
+  }
 }
📝 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.

Suggested change
export async function ai_credit_limit() {
const client = await createClient();
const { data: userdata, error: auth_err } = await client.auth.getUser();
if (auth_err) throw new Error(auth_err.message);
const user_id = userdata.user.id;
// limit
const { success, limit, reset, remaining } = await ratelimit.limit(
`ratelimit_u_${user_id}`
);
const ratelimit_headers = {
"x-ratelimit-limit": limit.toString(),
"x-ratelimit-reset": reset.toString(),
"x-ratelimit-remaining": remaining.toString(),
};
return {
success: success,
limit,
reset,
remaining,
headers: ratelimit_headers,
};
}
export async function ai_credit_limit(options?: { user_id?: string }) {
let user_id: string;
if (options?.user_id) {
user_id = options.user_id;
} else {
const client = await createClient();
const { data: userdata, error: auth_err } = await client.auth.getUser();
if (auth_err) throw new Error(auth_err.message);
user_id = userdata.user.id;
}
try {
const { success, limit, reset, remaining } = await ratelimit.limit(
`ratelimit_u_${user_id}`
);
const ratelimit_headers = {
"x-ratelimit-limit": limit.toString(),
"x-ratelimit-reset": reset.toString(),
"x-ratelimit-remaining": remaining.toString(),
};
return {
success: success,
limit,
reset,
remaining,
headers: ratelimit_headers,
};
} catch (error) {
console.error("Error applying rate limit:", error);
throw new Error("Failed to apply rate limit");
}
}
🤖 Prompt for AI Agents (early access)
In editor/app/(api)/private/ai/ratelimit.ts around lines 21 to 46, improve the ai_credit_limit function by adding error handling for the ratelimit.limit call to catch and handle any potential errors gracefully. Also, refactor the function to accept a user_id parameter instead of fetching it internally, making the function more reusable and consistent with ai_credit_remaining. Adjust the function signature and remove the internal user retrieval logic accordingly.

Comment on lines +1 to +11
import OpenAI from "openai";
import { NextResponse } from "next/server";

const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});

export async function GET() {
const result = await openai.models.list();
return NextResponse.json({ data: result.data });
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Missing error handling for OpenAI API calls.

The implementation fetches OpenAI models but lacks error handling for API failures, which could lead to unhandled exceptions being propagated to the client. This could result in poor user experience if the OpenAI service is temporarily unavailable.

Add try/catch block to gracefully handle potential API errors:

export async function GET() {
+  try {
    const result = await openai.models.list();
    return NextResponse.json({ data: result.data });
+  } catch (error) {
+    console.error("Error fetching OpenAI models:", error);
+    return NextResponse.json(
+      { error: "Failed to fetch OpenAI models" },
+      { status: 500 }
+    );
+  }
}

Consider implementing response caching to improve performance and reduce unnecessary API calls:

export async function GET() {
+  // Consider adding caching here with a reasonable TTL
+  // since model lists don't change frequently
  try {
    const result = await openai.models.list();
    return NextResponse.json({ data: result.data });
  } catch (error) {
    console.error("Error fetching OpenAI models:", error);
    return NextResponse.json(
      { error: "Failed to fetch OpenAI models" },
      { status: 500 }
    );
  }
}
📝 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.

Suggested change
import OpenAI from "openai";
import { NextResponse } from "next/server";
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
export async function GET() {
const result = await openai.models.list();
return NextResponse.json({ data: result.data });
}
import OpenAI from "openai";
import { NextResponse } from "next/server";
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
export async function GET() {
// Consider adding caching here with a reasonable TTL
// since model lists don't change frequently
try {
const result = await openai.models.list();
return NextResponse.json({ data: result.data });
} catch (error) {
console.error("Error fetching OpenAI models:", error);
return NextResponse.json(
{ error: "Failed to fetch OpenAI models" },
{ status: 500 }
);
}
}
🤖 Prompt for AI Agents (early access)
In editor/app/(api)/private/ai/models/openai/route.ts lines 1 to 11, the OpenAI API call lacks error handling which can cause unhandled exceptions if the API fails. Wrap the call to openai.models.list() inside a try/catch block to catch any errors and return a proper error response using NextResponse with an appropriate status code and message. Additionally, consider adding response caching headers to the successful response to improve performance and reduce redundant API calls.

Comment on lines +5 to +21
export async function GET() {
const client = await createClient();
const u = await client.auth.getUser();
if (u.error) {
return new NextResponse("Unauthorized", { status: 401 });
}

const data = await ai_credit_remaining({ user_id: u.data.user.id });
return NextResponse.json(
{
data,
},
{
status: 200,
}
);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling for credit retrieval failures.

While authentication errors are properly handled, there's no error handling for the ai_credit_remaining function call, which could fail due to Redis connection issues or other problems.

Add try/catch block to handle potential errors from the credit retrieval function:

export async function GET() {
  const client = await createClient();
  const u = await client.auth.getUser();
  if (u.error) {
    return new NextResponse("Unauthorized", { status: 401 });
  }

+  try {
    const data = await ai_credit_remaining({ user_id: u.data.user.id });
    return NextResponse.json(
      {
        data,
      },
      {
        status: 200,
      }
    );
+  } catch (error) {
+    console.error("Error retrieving AI credits:", error);
+    return NextResponse.json(
+      { error: "Failed to retrieve AI credits" },
+      { status: 500 }
+    );
+  }
}
📝 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.

Suggested change
export async function GET() {
const client = await createClient();
const u = await client.auth.getUser();
if (u.error) {
return new NextResponse("Unauthorized", { status: 401 });
}
const data = await ai_credit_remaining({ user_id: u.data.user.id });
return NextResponse.json(
{
data,
},
{
status: 200,
}
);
}
export async function GET() {
const client = await createClient();
const u = await client.auth.getUser();
if (u.error) {
return new NextResponse("Unauthorized", { status: 401 });
}
try {
const data = await ai_credit_remaining({ user_id: u.data.user.id });
return NextResponse.json(
{
data,
},
{
status: 200,
}
);
} catch (error) {
console.error("Error retrieving AI credits:", error);
return NextResponse.json(
{ error: "Failed to retrieve AI credits" },
{ status: 500 }
);
}
}
🤖 Prompt for AI Agents (early access)
In editor/app/(api)/private/ai/credits/route.ts between lines 5 and 21, the GET function lacks error handling for the ai_credit_remaining call, which may fail due to Redis or other issues. Wrap the call to ai_credit_remaining in a try/catch block, and in the catch block return an appropriate error response (e.g., 500 status with an error message) to handle potential failures gracefully.

return (
<figure
className={cn(
"relative w-full h-auto min-h-64 aspect-square overflow-hidden rounded",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Verification agent

❓ Verification inconclusive

Verify Tailwind class compatibility.

The min-h-64 class might not be a standard Tailwind class unless you've extended your Tailwind configuration.


🏁 Script executed:

#!/bin/bash
# Check if min-h-64 is defined in Tailwind config
grep -r "min-h-" --include="tailwind.config.*" .

Length of output: 48


🏁 Script executed:

#!/bin/bash
# Search for any custom minHeight definitions in Tailwind config
grep -Rn "minHeight" --include="tailwind.config.*" .

# Search for theme.extend blocks to see if min-h-64 is added under minHeight
grep -Rn "extend" --include="tailwind.config.*" . | grep -A5 "minHeight"

Length of output: 123


Invalid Tailwind Utility: min-h-64
The min-h-64 class isn’t included in Tailwind’s default min-height scale (which only provides 0, full, screen, min, and max). Since no custom minHeight extension was found in your Tailwind config, this utility will have no effect.

Please choose one of the following:

  • Extend your Tailwind config under theme.extend.minHeight to include a 64: '16rem' entry.
  • Replace min-h-64 with a valid default utility (e.g., min-h-full, min-h-screen) or an arbitrary value syntax: min-h-[16rem].

Locations to update:

  • editor/app/(dev)/playground/image/_components/image-frame.tsx: line 43
🤖 Prompt for AI Agents (early access)
In editor/app/(dev)/playground/image/_components/image-frame.tsx at line 43, the Tailwind class 'min-h-64' is invalid as it is not part of the default Tailwind min-height utilities and no custom extension exists. Fix this by either extending the Tailwind config under theme.extend.minHeight to add '64: "16rem"' or replace 'min-h-64' with a valid default class like 'min-h-full' or use the arbitrary value syntax 'min-h-[16rem]' directly in the class list.

Comment on lines +101 to +115
function getImageModel(
model: ai.image.ProviderModel | ai.image.ImageModelId
): ImageModel | null {
if (typeof model === "string") {
const card = ai.image.models[model];
if (!card) return null;
switch (card.provider) {
case "openai":
return openai.image(card.id);
case "replicate":
return replicate.image(card.id);
default:
return null;
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Guard against unknown providers

The default branch silently returns null, which then throws a generic “Model not found” error. Adding the provider name to the message helps debugging:

-      default:
-        return null;
+      default:
+        throw new Error(`Unsupported image provider: ${card.provider}`);
📝 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.

Suggested change
function getImageModel(
model: ai.image.ProviderModel | ai.image.ImageModelId
): ImageModel | null {
if (typeof model === "string") {
const card = ai.image.models[model];
if (!card) return null;
switch (card.provider) {
case "openai":
return openai.image(card.id);
case "replicate":
return replicate.image(card.id);
default:
return null;
}
}
function getImageModel(
model: ai.image.ProviderModel | ai.image.ImageModelId
): ImageModel | null {
if (typeof model === "string") {
const card = ai.image.models[model];
if (!card) return null;
switch (card.provider) {
case "openai":
return openai.image(card.id);
case "replicate":
return replicate.image(card.id);
default:
throw new Error(`Unsupported image provider: ${card.provider}`);
}
}
// ...rest of function...
}
🤖 Prompt for AI Agents (early access)
In editor/app/(api)/private/ai/generate/image/route.ts around lines 101 to 115, the default case in the switch statement silently returns null for unknown providers, causing a generic error later. Modify the default case to throw an error that includes the unknown provider name to improve debugging clarity.

Comment on lines +65 to +77
const model = getImageModel(body.model);
if (!model) throw new Error("Model not found");

// generate image
const generation = await generateImage({
prompt: body.prompt,
width: body.width,
height: body.height,
model: body.model,
model: model,
});

const meta = generation.responses[0];

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Potential mismatch between SDK response and accessed fields

  1. experimental_generateImage usually returns { image, createdAt, modelId } (or an images array) — the property responses is not documented.
  2. meta.timestamp and meta.modelId might therefore be undefined, breaking the client code that parses them into Date objects.

Please confirm the shape of the SDK response and adjust:

-  const meta = generation.responses[0];
+  const meta = {
+    modelId: generation.modelId ?? model.modelId ?? model.id,
+    timestamp: generation.createdAt ?? new Date(),
+  };
📝 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.

Suggested change
const model = getImageModel(body.model);
if (!model) throw new Error("Model not found");
// generate image
const generation = await generateImage({
prompt: body.prompt,
width: body.width,
height: body.height,
model: body.model,
model: model,
});
const meta = generation.responses[0];
const model = getImageModel(body.model);
if (!model) throw new Error("Model not found");
// generate image
const generation = await generateImage({
prompt: body.prompt,
width: body.width,
height: body.height,
model: model,
});
const meta = {
modelId: generation.modelId ?? model.modelId ?? model.id,
timestamp: generation.createdAt ?? new Date(),
};
🤖 Prompt for AI Agents (early access)
In editor/app/(api)/private/ai/generate/image/route.ts around lines 65 to 77, the code accesses generation.responses[0], but the SDK's experimental_generateImage method returns an object with properties like image, createdAt, and modelId or an images array, not a responses array. Verify the actual response structure from the SDK, then update the code to access the correct fields such as createdAt and modelId directly from the response object or from the first element of the images array, ensuring these values are defined before parsing them into Date objects.

Comment on lines +100 to +110
const [remaining, setRemaining] = useState(0);
const [reset, setReset] = useState(0);

const refresh = useCallback(async () => {
const r = await fetch(`/private/ai/credits`, {
method: "GET",
}).then((res) => res.json());
setRemaining(r.data.remaining);
setReset(r.data.reset);
}, []);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Gracefully degrade when credit lookup fails

useCredits assumes the /credits endpoint always responds 200. If it fails, remaining stays 0 and the UI hides the reason.

Add basic error handling:

-    const r = await fetch(…).then((res) => res.json());
+    try {
+      const res = await fetch(…);
+      if (!res.ok) return;
+      const r = await res.json();
+      …
+    } catch { /* optionally notify */ }

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents (early access)
In editor/app/(dev)/playground/image/_page.tsx around lines 100 to 110, the fetch call to `/private/ai/credits` assumes a successful 200 response and does not handle errors, causing the UI to incorrectly show zero credits without explanation. Modify the refresh function to include a try-catch block around the fetch call, and in the catch block, set an error state or provide fallback values to indicate the failure gracefully. This will ensure the UI can display an appropriate message or state when the credit lookup fails.

Comment on lines +291 to +297
<div className="px-2 py-1 bg-muted rounded-md border flex gap-1 items-center">
<CommandIcon className="size-3" />
<span className="text-sm font-mono">
{credits.remaining?.toString()}
</span>
</div>
</TooltipTrigger>

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Disable generation when out of credits

Users can still press ⏎ with zero credits and receive a 429. Disable the ChatBox accordingly:

-    disabled={loading}
+    disabled={loading || credits.remaining === 0}

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents (early access)
In editor/app/(dev)/playground/image/_page.tsx around lines 291 to 297, the ChatBox component should be disabled when the user has zero credits to prevent triggering a 429 error. Add a condition to disable the ChatBox input or submission functionality when credits.remaining is zero or undefined, ensuring users cannot generate content without available credits.

Comment on lines +45 to +63
const generate = useCallback(
async ({
model,
prompt,
width,
height,
}: {
model: ai.image.ProviderModel | ai.image.ImageModelId;
prompt: string;
width: number;
height: number;
}) => {
setImage(null);
setKey((k) => k + 1);
setStart(new Date());
setEnd(null);
setLoading(true);
const r: GenerateImageApiResponse = await fetch(
`/private/ai/generate/image`,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle fetch failures to avoid unhandled rejections

The current implementation never catches network or 4xx/5xx errors. A failed request leaves the hook stuck in the loading state and throws in the console.

-      const r: GenerateImageApiResponse = await fetch(…)
-        .then((res) => res.json());
+      try {
+        const res = await fetch(…);
+        if (!res.ok) throw new Error(await res.text());
+        const r: GenerateImageApiResponse = await res.json();
+        …
+      } catch (err) {
+        console.error("Image generation failed:", err);
+        setLoading(false);
+        return;
+      }
📝 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.

Suggested change
const generate = useCallback(
async ({
model,
prompt,
width,
height,
}: {
model: ai.image.ProviderModel | ai.image.ImageModelId;
prompt: string;
width: number;
height: number;
}) => {
setImage(null);
setKey((k) => k + 1);
setStart(new Date());
setEnd(null);
setLoading(true);
const r: GenerateImageApiResponse = await fetch(
`/private/ai/generate/image`,
const generate = useCallback(
async ({
model,
prompt,
width,
height,
}: {
model: ai.image.ProviderModel | ai.image.ImageModelId;
prompt: string;
width: number;
height: number;
}) => {
setImage(null);
setKey((k) => k + 1);
setStart(new Date());
setEnd(null);
setLoading(true);
- const r: GenerateImageApiResponse = await fetch(
- `/private/ai/generate/image`,
- /* original fetch options */
- ).then((res) => res.json());
+ try {
+ const res = await fetch(
+ `/private/ai/generate/image`,
+ /* original fetch options */
+ );
+ if (!res.ok) {
+ throw new Error(await res.text());
+ }
+ const r: GenerateImageApiResponse = await res.json();
+ // … existing success-handling logic (e.g., setImage, setEnd, setLoading(false))
+ } catch (err) {
+ console.error("Image generation failed:", err);
+ setLoading(false);
+ return;
+ }
},
[/* dependencies */]
);
🤖 Prompt for AI Agents (early access)
In editor/app/(dev)/playground/image/_page.tsx around lines 45 to 63, the async fetch call lacks error handling, causing unhandled promise rejections and the loading state to remain true on failure. Wrap the fetch and subsequent logic in a try-catch block, set loading to false in both success and failure cases, and handle errors gracefully by updating state or logging the error to prevent the hook from getting stuck.

This branch was successfully deployed

1 active and 6 inactive deployments
Preview – grida — 6c7fb34f Deployed Apr 29, 2025 by vercel[bot]
Preview – sites — 6c7fb34f Deployed Apr 29, 2025 by vercel[bot]
Preview – docs — 6c7fb34f Deployed Apr 29, 2025 by vercel[bot]
Preview – backgrounds — 6c7fb34f Deployed Apr 29, 2025 by vercel[bot]
Preview – viewer — 6c7fb34f Deployed Apr 29, 2025 by vercel[bot]
Preview – blog — 6c7fb34f Deployed Apr 29, 2025 by vercel[bot]
Preview – legacy-www — 6c7fb34f Deployed Apr 29, 2025 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant