Repository navigation
[Grida AI] Prompt Playground - Experts, Model selection, Image Attatchments - #308
Conversation
Review or Edit in CodeSandboxOpen the branch in Web Editor • VS Code • Insiders |
WalkthroughThis 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
Sequence Diagram(s)Chat Submission with Attachment FlowsequenceDiagram
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)
Possibly related PRs
Poem
✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
|
The latest updates on your projects. Learn more about Vercel for Git ↗︎
7 Skipped Deployments
|
There was a problem hiding this comment.
Actionable comments posted: 3
🔭 Outside diff range comments (2)
editor/scaffolds/asset/editor-file-uploader.ts (1)
100-124: 🛠️ Refactor suggestion
useCallbackis 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 anduseCallbackcan’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 suggestionMissing error handling for
generateRejections (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_vanillastring – consider DRY factory
If_vanillagrows, every preset imports the entire text each time, slightly inflating bundle size. A lightweight factory can concatenatesystem+ optionalexperton 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 failureIf
uploaderrejects,setAttachmentis never called, yet the promise is shown as “Failed” viatoast.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
onSubmitfires even when bothtxt.trim()andattachmentare 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:systemmsgloses separation between sectionsConcatenating 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
📒 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 underEnv.storageremoves 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
PortableNodetype 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
StreamingResponsetype 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
useDummyPublicUploadhook provides a clean abstraction for uploading files to a temporary storage bucket. The implementation:
- Uses environment configuration via
Env.storage.BUCKET_DUMMY- Generates unique path prefixes with UUIDs to prevent collisions
- 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 undefinedform_id
state.form.form_idis 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 -eecho "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 ofpublicUrlvariable:"
rg "publicUrl" -n .</details> </blockquote></details> </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
| interface ModelSelectorProps extends PopoverProps { | ||
| onValueChange?: (model: Model) => void; | ||
| } | ||
|
|
||
| export function ModelSelector({ ...props }: ModelSelectorProps) { | ||
| const [open, setOpen] = React.useState(false); |
There was a problem hiding this comment.
🛠️ 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}>| onSelect={() => { | ||
| setSelectedModel(model); | ||
| props.onValueChange?.(model); | ||
| setOpen(false); | ||
| }} |
There was a problem hiding this comment.
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.
| onSelect={() => { | |
| setSelectedModel(model); | |
| props.onValueChange?.(model); | |
| setOpen(false); | |
| }} | |
| onSelect={() => { | |
| setSelectedModel(model); | |
| onValueChange?.(model); | |
| setOpen(false); | |
| }} |
| const __env = ` | ||
| <environment> | ||
| - now is "${new Date().toISOString()}". | ||
| </environment> | ||
| `; | ||
|
|
There was a problem hiding this comment.
🛠️ 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.
| const __env = ` | |
| <environment> | |
| - now is "${new Date().toISOString()}". | |
| </environment> | |
| `; | |
| export const makeEnvBlock = () => ` | |
| <environment> | |
| - now is "${new Date().toISOString()}". | |
| </environment> | |
| `; |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (4)
editor/app/(dev)/canvas/tools/ai/_components/chatbox.tsx (2)
72-79: Guard against empty submissions
onSubmitfires 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:disabledstate should propagate to the image‑picker buttonWhen the component is disabled, the paper‑clip button still opens the file dialog.
Disable the button or early‑return fromopenFilePickerto avoid unexpected uploads in read‑only mode.editor/app/(dev)/canvas/tools/ai/_data/presets.ts (2)
106-137: Minor typos in expert prompt stringsThe 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__typographyare full‑blown multi‑KB strings that are imported by any module referencingpresets.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
📒 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 staleuploaderreference
useEffectis intentionally ignoringuploaderin 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, adduploaderto the dependency list.
| uploader?: FileIO.BucketFileUploaderFn; | ||
| className?: string; | ||
| }) { | ||
| const [attatchment, setAttachment] = React.useState<Attachment>(); |
There was a problem hiding this comment.
🛠️ 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
| 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", | ||
| }); | ||
| } | ||
| } |
There was a problem hiding this comment.
🛠️ 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.
day-255-grida-ai-prompt-playground-image-uploads.mp4
Summary by CodeRabbit
New Features
Improvements
Documentation
Chores