Skip to content

[Grida AI] Prompt Playground - Experts, Model selection, Image Attatchments - #308

Merged
softmarshmallow merged 5 commits into
mainfrom
ai
Apr 22, 2025
Merged

softmarshmallow merged 5 commits into
mainfrom
ai

Conversation

@softmarshmallow

@softmarshmallow softmarshmallow commented Apr 22, 2025 •

Copy link
Copy Markdown
Member
day-255-grida-ai-prompt-playground-image-uploads.mp4

Summary by CodeRabbit

  • New Features

    • Added support for image attachments in the chat input, including image upload, preview, and submission alongside text.
    • Introduced a modular preset system with base and expert-level prompts for design generation.
    • Added a toggle to switch between raw JSON and canvas view for generated responses.
    • Enhanced model selection with external change notification.
    • Introduced a new public temporary storage upload hook for development and playground use.
  • Improvements

    • Improved HTML rendering logic for design responses, with better attribute and text handling.
    • Enhanced storage configuration via environment-based bucket management.
    • Centralized and streamlined file upload hooks for asset management.
    • Extended generation function to accept user input with attachments.
  • Documentation

    • Expanded the Grida Standard Library README with a detailed asset object model example and additional asset categories.
  • Chores

    • Refactored and reorganized storage and upload-related code for maintainability and consistency.

@codesandbox

codesandbox Bot commented Apr 22, 2025

Copy link
Copy Markdown

Review or Edit in CodeSandbox

Open the branch in Web Editor • VS Code • Insiders

Open Preview

@coderabbitai

coderabbitai Bot commented Apr 22, 2025 •

Copy link
Copy Markdown

Walkthrough

This update introduces several enhancements and refactorings across the editor's AI canvas tools and asset management infrastructure. The AI chat interface now supports image attachments, with corresponding backend changes to handle structured user messages containing text and files. The preset system is modularized to allow layered system and expert prompts. Storage bucket constants are centralized within an environment namespace, and storage/upload logic is moved to a shared platform scaffold, replacing local implementations. New TypeScript types and validation schemas are introduced for design data structures. The UI for the AI canvas playground is improved with better system message composition, model selection, and response viewing options, including raw JSON output. Documentation is also expanded for the asset library.

Changes

File(s) Change Summary
editor/app/(dev)/canvas/tools/ai/_components/canvas.tsx Refactored imports, improved attribute handling and text rendering in renderJSONToHTML, updated function signature to use PortableNode.
editor/app/(dev)/canvas/tools/ai/_components/chatbox.tsx Enhanced ChatBox to support image attachments, new Attachment type, file picker integration, uploader support, UI for image preview, and updated submission logic.
editor/app/(dev)/canvas/tools/ai/_components/model-selector.tsx Added onValueChange callback prop to ModelSelectorProps and component to notify external components of model selection changes.
editor/app/(dev)/canvas/tools/ai/_data/presets.ts Modularized preset system, added optional expert field, split system prompts into base and expert segments, and restructured presets array for specialization.
editor/app/(dev)/canvas/tools/ai/generate.ts Updated generate to accept structured user messages with attachments, introduced UserAttachment type, and adjusted message construction logic.
editor/app/(dev)/canvas/tools/ai/page.tsx Added systemmsg utility, extended state for multiple system messages and raw view toggle, improved UI for system/context messages and response viewing, integrated new chatbox and model selector props.
editor/app/(dev)/canvas/tools/ai/schema.ts Introduced new types for design data structures (PortableNode, StreamingResponse, etc.) and a Zod validation schema for design requests.
editor/app/(dev)/dev/grid/editor.tsx Changed import path for useDummyPublicUpload, removed unused imports.
editor/env.ts Added Env.storage namespace with centralized storage bucket constants and documentation.
editor/scaffolds/asset/editor-file-uploader.ts Removed local storage/upload hooks, switched to platform storage imports, replaced bucket constants with Env.storage, removed useDummyPublicUpload.
editor/scaffolds/asset/k.ts Deleted file containing storage bucket constants.
editor/scaffolds/platform/storage/index.ts Added module to re-export storage/upload hooks from platform scaffold.
editor/scaffolds/platform/storage/use-dummy-public-upload.ts Added useDummyPublicUpload hook for uploading to public, temporary storage bucket.
editor/scaffolds/platform/storage/use-upload.ts Added hooks for Supabase storage client and file upload with metadata return.
library/README.md Expanded documentation with asset categories, API announcement, and a detailed Asset Object Model JSON example.

Sequence Diagram(s)

Chat Submission with Attachment Flow

sequenceDiagram
    participant User
    participant ChatBox
    participant FileUploader
    participant PlaygroundPage
    participant generate()
    participant Backend

    User->>ChatBox: Enter text / Attach image
    ChatBox->>FileUploader: Upload image (if any)
    FileUploader-->>ChatBox: Return uploaded image metadata
    ChatBox->>PlaygroundPage: onValueCommit({ text, attachments })
    PlaygroundPage->>generate(): Call with structured user message
    generate()->>Backend: Send message (text + attachments)
    Backend-->>generate(): Streaming response
    generate()-->>PlaygroundPage: Return response
    PlaygroundPage-->>User: Display response (canvas or JSON)
Loading

Possibly related PRs

  • [Grida AI] System prompt playground #307: Introduced the initial Canvas component and basic renderJSONToHTML function, which this PR refines and extends with improved HTML rendering and attribute handling.

Poem

🐇
In the meadow of code, new features bloom,
ChatBox now shares images, dispelling the gloom.
Presets grow smarter, with experts in tow,
Storage buckets gather where environment winds blow.
Types and schemas line up in neat little rows,
While asset docs sparkle with all that it knows.
A hop, a leap, our editor grows!

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

@vercel

vercel Bot commented Apr 22, 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 22, 2025 0:46am
legacy-www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 22, 2025 0:46am
7 Skipped Deployments
Name Status Preview Comments Updated (UTC)
code ⬜️ Ignored (Inspect) Apr 22, 2025 0:46am
legacy ⬜️ Ignored (Inspect) Apr 22, 2025 0:46am
sites ⬜️ Ignored (Inspect) Apr 22, 2025 0:46am
backgrounds ⬜️ Skipped (Inspect) Apr 22, 2025 0:46am
blog ⬜️ Skipped (Inspect) Apr 22, 2025 0:46am
docs ⬜️ Skipped (Inspect) Apr 22, 2025 0:46am
viewer ⬜️ Skipped (Inspect) Apr 22, 2025 0:46am

@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: 3

🔭 Outside diff range comments (2)
editor/scaffolds/asset/editor-file-uploader.ts (1)

100-124: 🛠️ Refactor suggestion

useCallback is ineffective here – function is re‑created on every render

__make_asset_uploader({ … }) is executed before React memoises the value, so a new uploader function is produced on every render and useCallback can’t stabilise its reference.

-const uploadPrivate = useCallback(
-  __make_asset_uploader({ createAsset, storage, is_public: false }),
-  [storage, createAsset],
-);
+const uploadPrivate = React.useMemo(
+  () => __make_asset_uploader({ createAsset, storage, is_public: false }),
+  [storage, createAsset],
+);

Do the same for uploadPublic.
This removes unnecessary re‑creation and prevents downstream re‑renders.

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

53-71: 🛠️ Refactor suggestion

Missing error handling for generate

Rejections (network errors, validation issues) will remain unhandled, leaving the UI in a busy state forever.

-generate({ … }).then(
+generate({ … })
+  .then(
     async ({ output }) => { … }
-)
+  )
+  .catch((e) => {
+    console.error("generation failed", e);
+    toast.error("Failed to generate response");
+    setStreamBusy(false);
+  });
🧹 Nitpick comments (10)
editor/app/(dev)/canvas/tools/ai/_data/presets.ts (2)

114-145: Typos in expert prompt may confuse the LLM
Small misspellings can reduce the model’s confidence:

  • “expoert” → “expert”
  • “mordern” → “modern”
  • “Wehn” → “When”
  • “textx” → “texts”
  • “a aesthetic” → “an aesthetic”

Fixing them keeps the instructions clean.

-You are expoert in poster design.
+You are an expert in poster design.
…
- - In mordern design, it's all about…
+ - In modern design, it's all about…
…
- - Wehn we choose to use lines…
+ - When we choose to use lines…
…
- - Use smaller texts. bold is not always better. small textx can bring…
+ - Use smaller texts. Bold is not always better. Small texts can bring…
…
- - a aesthetic poster design have a diagonal flow…
+ - an aesthetic poster design has a diagonal flow…

177-195: Preset objects share the same _vanilla string – consider DRY factory
If _vanilla grows, every preset imports the entire text each time, slightly inflating bundle size. A lightweight factory can concatenate system + optional expert on demand:

function makePreset(id: string, name: string, expert?: string): Preset {
  return { id, name, system: _vanilla, expert };
}

export const presets: Preset[] = [
  makePreset("vanilla", "Grida AI - Vanilla"),
  makePreset("ui_expert", "Grida AI - UI Expert", _ui_expert),
  makePreset("poster_expert", "Grida AI - Poster Expert", _poster_expert),
];

Not urgent, but will keep maintenance easier as the list grows.

editor/app/(dev)/canvas/tools/ai/schema.ts (1)

31-76: Comprehensive Zod validation schema with descriptive annotations.

The request schema is well-structured with descriptive annotations that will help both developers and AI understand the expected format. The optional fields for dimensions allow flexibility while ensuring core elements like colors and HTML structure are validated.

Consider adding specific validation rules for color formats (e.g., hex codes) and size constraints for optimal performance.

  colors: z
    .array(z.string())
+   .refine(colors => colors.every(color => /^#([0-9A-F]{3}){1,2}$/i.test(color) || 
+                                        /^rgb\(\d{1,3},\s*\d{1,3},\s*\d{1,3}\)$/i.test(color)), 
+          "Colors should be in hex (#RGB or #RRGGBB) or RGB format")
    .describe("list of main colors used in the design - the brand colors"),
library/README.md (1)

22-22: Typo in API announcement.

There's a spelling error in the API announcement.

-## (Working Draft) - API comming soon.
+## (Working Draft) - API coming soon.
editor/scaffolds/platform/storage/use-upload.ts (1)

23-31: Consider adding more specific error messages.

While there is error handling in place, the error messages could be more specific to help with debugging.

-            throw new Error("Failed to upload file");
+            throw new Error(`Failed to upload file: ${error.message}`);
editor/app/(dev)/canvas/tools/ai/generate.ts (1)

60-78: Consider checking for empty attachments array.

The code could benefit from checking if the attachments array is empty to avoid unnecessary processing.

-    if (user.attachments) {
+    if (user.attachments && user.attachments.length > 0) {
editor/app/(dev)/canvas/tools/ai/_components/chatbox.tsx (3)

32-33: Typo in state variable name

attatchment (double “t”) is used throughout. Apart from the spelling issue (which leaks to prop lists later) it can confuse future readers and auto‑completion.

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

(and rename usages).


40-58: Upload errors are swallowed – attachment state never reflects failure

If uploader rejects, setAttachment is never called, yet the promise is shown as “Failed” via toast.promise. Consider resetting the file picker or showing an inline error so the user understands the attachment wasn’t sent.

-task.then((result) => {
-  setAttachment({ … });
-});
+task
+  .then((result) => {
+    setAttachment({ … });
+  })
+  .catch(() => {
+    // Optionally show a visual cue or reset picker
+    setAttachment(undefined);
+  });

69-75: Prevent empty submissions

onSubmit fires even when both txt.trim() and attachment are empty, generating an empty chat message.

-if (disabled) return;
+if (disabled || (!txt.trim() && !attachment)) return;

Improves UX and avoids wasted round‑trips.

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

24-33: systemmsg loses separation between sections

Concatenating without blank lines makes the template/context block run directly after the previous tag, which some models can mis‑parse.

-if (template) {
-  txt += `<template>\n${template}\n</template>`;
+if (template) {
+  txt += `\n\n<template>\n${template}\n</template>`;
 }

Apply the same spacing for the context block.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1fd3be6 and 0f7c4e2.

📒 Files selected for processing (15)
  • editor/app/(dev)/canvas/tools/ai/_components/canvas.tsx (3 hunks)
  • editor/app/(dev)/canvas/tools/ai/_components/chatbox.tsx (2 hunks)
  • editor/app/(dev)/canvas/tools/ai/_components/model-selector.tsx (2 hunks)
  • editor/app/(dev)/canvas/tools/ai/_data/presets.ts (2 hunks)
  • editor/app/(dev)/canvas/tools/ai/generate.ts (1 hunks)
  • editor/app/(dev)/canvas/tools/ai/page.tsx (5 hunks)
  • editor/app/(dev)/canvas/tools/ai/schema.ts (1 hunks)
  • editor/app/(dev)/dev/grid/editor.tsx (1 hunks)
  • editor/env.ts (1 hunks)
  • editor/scaffolds/asset/editor-file-uploader.ts (3 hunks)
  • editor/scaffolds/asset/k.ts (0 hunks)
  • editor/scaffolds/platform/storage/index.ts (1 hunks)
  • editor/scaffolds/platform/storage/use-dummy-public-upload.tsx (1 hunks)
  • editor/scaffolds/platform/storage/use-upload.ts (1 hunks)
  • library/README.md (1 hunks)
💤 Files with no reviewable changes (1)
  • editor/scaffolds/asset/k.ts
🧰 Additional context used
🪛 LanguageTool
library/README.md

[grammar] ~11-~11: Nouns are not usually modified by plural nouns. Is it possible that you meant to use the singular or possessive form here?
Context: ...mbols - logos - patterns - wallpapers - icons - colors - sizes - objects - components...

(PLURAL_MODIFIER)

🔇 Additional comments (30)
editor/env.ts (1)

12-44: Good move – bucket names are now centralised 👍
Centralising storage buckets under Env.storage removes duplication and lowers the risk of typos across the codebase. Nothing blocking here.

editor/app/(dev)/canvas/tools/ai/schema.ts (3)

3-12: Well-structured node type definition for portable designs.

The PortableNode type provides a comprehensive structure for representing both HTML and SVG elements with appropriate attributes. The flexibility to handle nested children recursively and optional styling properties will make rendering and manipulation more robust.


14-19: Good reference types for portable assets.

The reference types for images and fonts provide a clean way to track external assets used within designs. Using a consistent ID-based reference system will help maintain relationships between elements and their resources.


21-29: Well-defined response type for streaming design data.

The StreamingResponse type creates a clear contract for what the AI design generation will return. Including both metadata (dimensions, colors) and structural elements (HTML node hierarchy and images) provides a complete representation of generated designs.

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

48-48: Updated import path for storage module.

Good refactoring - the import has been updated to use the new centralized storage module instead of the previous asset-specific implementation. This aligns with the broader restructuring of storage upload hooks.

editor/scaffolds/platform/storage/index.ts (1)

1-2: Clean barrel file implementation for platform storage.

This barrel file pattern provides a clean public API for the storage module, making imports simpler for consumers. It centralizes all storage-related functionality in one location, which improves maintainability.

editor/scaffolds/platform/storage/use-dummy-public-upload.tsx (1)

7-15: Well-implemented hook for temporary file uploads.

The useDummyPublicUpload hook provides a clean abstraction for uploading files to a temporary storage bucket. The implementation:

  1. Uses environment configuration via Env.storage.BUCKET_DUMMY
  2. Generates unique path prefixes with UUIDs to prevent collisions
  3. Has clear documentation explaining its purpose

This approach centralizes storage logic and improves maintainability.

library/README.md (3)

3-4: Clear introduction added to the library documentation.

The introduction succinctly explains the purpose of the Grida Standard Library, establishing it as a free and open-source collection of design assets that supports both the Editor and AI components.


7-20: Asset categories expanded to include more design elements.

The expanded list of asset categories (symbols, logos, patterns, etc.) provides a more comprehensive overview of what's available in the library, which aligns well with the improvements to asset handling in the PR.

🧰 Tools
🪛 LanguageTool

[grammar] ~11-~11: Nouns are not usually modified by plural nouns. Is it possible that you meant to use the singular or possessive form here?
Context: ...mbols - logos - patterns - wallpapers - icons - colors - sizes - objects - components...

(PLURAL_MODIFIER)


24-56: Comprehensive Asset Object Model documentation added.

The JSON example provides an excellent reference for the asset metadata structure. This detailed schema documents all the important properties of assets, which is valuable for developers who will interact with the library.

editor/app/(dev)/canvas/tools/ai/_components/canvas.tsx (7)

1-3: Improved imports with explicit type reference.

Good practice to import React hooks explicitly and add the PortableNode type import, improving code readability and type safety.


17-17: Added full-screen styling to iframe body.

Adding Tailwind classes for width and height ensures the content fully utilizes the available space in the iframe.


63-63: Enhanced function signature with proper typing.

The updated function signature correctly defines the parameter as a PortableNode or string, improving type safety.


68-78: Expanded destructuring for better attribute handling.

The enhanced destructuring captures more properties from the node, making the code more explicit about what attributes are being used.


80-87: Created unified attributes map for cleaner attribute handling.

Excellent refactoring to consolidate all attributes into a single map, which simplifies the code and reduces repetition.


89-95: Improved attribute string generation with null/undefined filtering.

The enhanced attribute string generation properly filters out undefined or null values, preventing invalid HTML attributes.


97-101: Enhanced children rendering with text prioritization.

The updated children rendering logic intelligently prioritizes the text property, with fallbacks to children as string or array, making the component more flexible.

editor/scaffolds/platform/storage/use-upload.ts (4)

7-9: Well-implemented storage client hook with proper memoization.

The useStorageClient hook correctly uses useMemo to prevent unnecessary re-creation of the client on each render.


11-16: Flexible upload hook with support for dynamic paths.

The useUpload hook accepts both static strings and dynamic functions for path generation, providing excellent flexibility.


17-51: Comprehensive upload implementation with error handling.

The upload callback handles the entire upload process well, including input validation, error handling, and result formatting.


35-43: Clean result object construction with TypeScript validation.

The upload result object is well-structured and uses the satisfies operator to ensure proper typing.

editor/app/(dev)/canvas/tools/ai/generate.ts (7)

3-11: Expanded imports to support rich content types.

The updated imports include all necessary types for handling text, files, and images in AI messages.


14-15: Improved schema handling with external schema import.

Importing the schema from a dedicated module is better for maintainability than using an inline schema.


19-24: Well-defined UserAttachment type for file uploads.

The UserAttachment type clearly defines the structure for both file and image attachments, supporting the new attachment functionality.


36-40: Function signature extended to support structured user input.

The generate function now accepts a user object containing text and optional attachments, making it more flexible.


48-48: Updated assertion for better input validation.

The assertion now correctly checks for either prompt or user input, ensuring at least one is provided.


50-86: Well-implemented message construction for complex user input.

The code elegantly constructs a CoreUserMessage with both text and attachments when user input is provided.


92-92: Updated message handling in streamObject call.

The streamObject call now correctly uses the constructed user message when available.

editor/scaffolds/asset/editor-file-uploader.ts (2)

130-135: Potential undefined form_id

state.form.form_id is dereferenced without a safety check. If the editor state is still boot‑strapping, this will throw.

-() => `${state.form.form_id}/${nanoid()}`
+() => {
+  if (!state.form?.form_id) {
+    throw new Error("form_id not available yet");
+  }
+  return `${state.form.form_id}/${nanoid()}`;
+}

Either guard here or ensure the hook is used only after the form exists.


54-57: ```shell
#!/bin/bash
set -e

echo "1) Occurrences of getPublicUrl:"
rg "getPublicUrl" -n .

echo
echo "2) Occurrences of createSignedUrl:"
rg "createSignedUrl" -n .

echo
echo "3) References to .data.publicUrl:"
rg ".data.publicUrl" -n .

echo
echo "4) Assignments or uses of publicUrl variable:"
rg "publicUrl" -n .


</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

Comment on lines +25 to 30
interface ModelSelectorProps extends PopoverProps {
onValueChange?: (model: Model) => void;
}

export function ModelSelector({ ...props }: ModelSelectorProps) {
const [open, setOpen] = React.useState(false);

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

Avoid leaking the custom prop into Radix‑UI’s <Popover>
ModelSelectorProps extends PopoverProps, but the new onValueChange is not a valid prop that Radix’ <Popover> understands.
Because you later pass the entire props object to <Popover> (<Popover ...{props}>), this extra prop will be forwarded all the way down to the underlying DOM node, triggering the React warning: “React does not recognize the onValueChange prop on a DOM element”.

Separate the custom prop before spreading:

-export function ModelSelector({ ...props }: ModelSelectorProps) {
-  const [open, setOpen] = React.useState(false);
+export function ModelSelector({ onValueChange, ...popoverProps }: ModelSelectorProps) {
+  const [open, setOpen] = React.useState(false);
   const [selectedModel, setSelectedModel] = React.useState<Model>();
   …
-    <Popover open={open} onOpenChange={setOpen} {...props}>
+    <Popover open={open} onOpenChange={setOpen} {...popoverProps}>

Comment on lines 59 to 63
onSelect={() => {
setSelectedModel(model);
props.onValueChange?.(model);
setOpen(false);
}}

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

Pass the callback captured above, not the entire props bag
After destructuring, replace props.onValueChange?.(model) with onValueChange?.(model):

-  setSelectedModel(model);
-  props.onValueChange?.(model);
+  setSelectedModel(model);
+  onValueChange?.(model);

This keeps the implementation consistent with the earlier refactor and avoids accidental coupling to the original props object.

📝 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
onSelect={() => {
setSelectedModel(model);
props.onValueChange?.(model);
setOpen(false);
}}
onSelect={() => {
setSelectedModel(model);
onValueChange?.(model);
setOpen(false);
}}

Comment on lines 70 to 75
const __env = `
<environment>
- now is "${new Date().toISOString()}".
</environment>
`;

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

Timestamp becomes stale after the first import
"${new Date().toISOString()}" is evaluated once at build/server‑startup time because it lives in a module‑level const. If the intent is to tell the model “current time of request”, inject the timestamp at execution time (e.g. inside the generate function) instead of baking it here.

-const __env = `
-<environment>
-  - now is "${new Date().toISOString()}".
-</environment>
-`;
+export const makeEnvBlock = () => `
+<environment>
+  - now is "${new Date().toISOString()}".
+</environment>
+`;

Then use makeEnvBlock() when assembling the final system prompt.

📝 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 __env = `
<environment>
- now is "${new Date().toISOString()}".
</environment>
`;
export const makeEnvBlock = () => `
<environment>
- now is "${new Date().toISOString()}".
</environment>
`;

@vercel
vercel Bot temporarily deployed to Preview – legacy-www April 22, 2025 12:39 Inactive
@vercel
vercel Bot temporarily deployed to Preview – backgrounds April 22, 2025 12:39 Inactive
@vercel
vercel Bot temporarily deployed to Preview – blog April 22, 2025 12:39 Inactive
@vercel
vercel Bot temporarily deployed to Preview – docs April 22, 2025 12:39 Inactive
@vercel
vercel Bot temporarily deployed to Preview – viewer April 22, 2025 12:39 Inactive
@vercel
vercel Bot temporarily deployed to Preview – sites April 22, 2025 12:39 Inactive

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (4)
editor/app/(dev)/canvas/tools/ai/_components/chatbox.tsx (2)

72-79: Guard against empty submissions

onSubmit fires even when both the text area is blank and no attachment is present, producing empty messages in the chat history.

-  const onSubmit = () => {
+  const onSubmit = () => {
     if (disabled) return;
+    if (!txt.trim() && !attachment) return;
     onValueCommit?.({
-      text: txt,
-      attachments: attachment ? [attachment] : [],
+      text: txt.trim(),
+      attachments: attachment ? [attachment] : [],
     });
     clear();
   };

126-134: disabled state should propagate to the image‑picker button

When the component is disabled, the paper‑clip button still opens the file dialog.
Disable the button or early‑return from openFilePicker to avoid unexpected uploads in read‑only mode.

editor/app/(dev)/canvas/tools/ai/_data/presets.ts (2)

106-137: Minor typos in expert prompt strings

The literal text that will be shown to the model contains several misspellings (expoert, aesthetic, Wehn, mordern, textx).
While not a functional bug, polishing the prompt improves credibility and may slightly influence model behaviour.

Example fixes:

-You are expoert in poster design.
+You are an expert in poster design.

- - a aesthetic poster design have a diagonal flow of the content.
+ - An aesthetic poster design has a diagonal flow of the content.

- - Wehn we choose to use lines as a design element,
+ - When we choose to use lines as a design element,

70-104: Large template literals loaded eagerly

_vanilla, __format_rules, and __typography are full‑blown multi‑KB strings that are imported by any module referencing presets.ts. If bundle size becomes a concern, consider converting them to lazy factories (() => string) so they are only interpolated when the preset is actually selected.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0f7c4e2 and c28b8a8.

📒 Files selected for processing (3)
  • editor/app/(dev)/canvas/tools/ai/_components/chatbox.tsx (2 hunks)
  • editor/app/(dev)/canvas/tools/ai/_data/presets.ts (2 hunks)
  • editor/app/(workbench)/[org]/[proj]/(console)/(campaign)/campaigns/[campaign]/design/template-duo-001-viewer.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • editor/app/(workbench)/[org]/[proj]/(console)/(campaign)/campaigns/[campaign]/design/template-duo-001-viewer.tsx
🧰 Additional context used
🧬 Code Graph Analysis (1)
editor/app/(dev)/canvas/tools/ai/_components/chatbox.tsx (1)
editor/lib/file/index.ts (1)
  • BucketFileUploaderFn (51-51)
🔇 Additional comments (1)
editor/app/(dev)/canvas/tools/ai/_components/chatbox.tsx (1)

52-57: Dependency omission may cause stale uploader reference

useEffect is intentionally ignoring uploader in its deps array (eslint disabled).
If the parent swaps the uploader implementation (e.g. user changes target bucket), the effect will still call the old function. Unless you have a strong reason, add uploader to the dependency list.

uploader?: FileIO.BucketFileUploaderFn;
className?: string;
}) {
const [attatchment, setAttachment] = React.useState<Attachment>();

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

Typo : attatchment → attachment

The state variable is miss‑spelled and the same typo is propagated to every usage.
Apart from harming readability, this will also trip up IDE “rename symbol” refactors and search‑and‑replace in the future.

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

Remember to rename all subsequent references (attatchment → attachment) in this file.

Also applies to: 70-70, 92-100, 96-96

Comment on lines +41 to +59
if (plainFiles.length === 1) {
const file = plainFiles[0];
const task = uploader?.(file).then((result) => {
setAttachment({
type: "image",
filename: file.name,
mimeType: file.type,
url: result.publicUrl,
});
});

if (task) {
toast.promise(task, {
loading: "Uploading...",
success: "Uploaded",
error: "Failed to upload",
});
}
}

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

Missing error‑branch side‑effects in upload promise

toast.promise will show an error toast, but when the upload fails the component still keeps the selected file in plainFiles, leaving the UI in an “attachment pending” limbo.
Consider clearing the file picker selection and the local attachment state in the .catch branch so the user can retry.

-const task = uploader?.(file).then((result) => {
-  setAttachment({ … });
-});
+const task = uploader?.(file)
+  .then((result) => {
+    setAttachment({ … });
+  })
+  .catch(() => {
+    // reset so the picker can be used again
+    clearFilePicker();          // pseudo – depends on lib API
+    setAttachment(undefined);
+  });

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

This branch was successfully deployed

1 active and 6 inactive deployments
Preview – grida — c28b8a8a Deployed Apr 22, 2025 by vercel[bot]
Preview – viewer — c28b8a8a Deployed Apr 22, 2025 by vercel[bot]
Preview – sites — c28b8a8a Deployed Apr 22, 2025 by vercel[bot]
Preview – legacy-www — c28b8a8a Deployed Apr 22, 2025 by vercel[bot]
Preview – backgrounds — c28b8a8a Deployed Apr 22, 2025 by vercel[bot]
Preview – blog — c28b8a8a Deployed Apr 22, 2025 by vercel[bot]
Preview – docs — c28b8a8a Deployed Apr 22, 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