Skip to content

[Grida Canvas] Image Playground Canvas - #276

Merged
softmarshmallow merged 29 commits into
mainfrom
canary
May 7, 2025
Merged

softmarshmallow merged 29 commits into
mainfrom
canary

Conversation

@softmarshmallow

@softmarshmallow softmarshmallow commented Mar 12, 2025 •

Copy link
Copy Markdown
Member

Image Playground Canvas

👉 https://grida.co/playground/image

This PR introduces,

  • core canvas features, edges - tool for rendering network graphs between nodes. (WIP)
  • a minimal demo of infinite canvas based image generation playground
  • auth gate, minimal rate-limit based credits control
day-231-grida-canvas-image-playground.mp4

Summary by CodeRabbit

  • New Features

    • Introduced a catalog page for AI image generation models with detailed model cards and added an "AI Models" link to the site footer and sitemap.
    • Added support for edges and network graphs in the canvas editor, including visual rendering of edges between nodes.
    • Enhanced AI image generation API to accept flexible image dimensions, aspect ratios, and provide accurate image metadata.
    • Added a new AI image model ("Flux Schnell") and updated existing model metadata with default sizes and speed labels.
    • Added new React hooks for AI credits management, image generation, and image model configuration.
    • Introduced authentication flows supporting popup-based Google sign-in and a reusable authentication dialog component.
    • Added a minimal chat box component and modularized chat UI with context-driven design.
    • Provided new hooks and utilities for session management and managing pending callbacks.
    • Added a transparency grid control panel and a network example page in the canvas editor.
    • Added node ID generation and retrieval utilities in the document editor API.
  • Improvements

    • Refactored chat box into composable, context-driven components for better state sharing and extensibility.
    • Simplified and improved the structure of canvas and playground pages, including sidebar and tooltip providers.
    • Improved AI image generation rate limiting to dynamically adjust based on model cost.
    • Enhanced color utility to support 8-character hex codes with alpha transparency.
    • Updated editor surface to always render transparency grid and enable horizontal scrolling with touch support.
    • Simplified header component by offloading session-dependent call-to-action rendering to a dedicated component.
  • Bug Fixes

    • Prevented errors in object key extraction by safely handling null or undefined values.
  • Documentation

    • Added API draft documentation demonstrating how to insert custom nodes in the canvas editor.
  • Chores

    • Added "image-size" as a new dependency.

@codesandbox

codesandbox Bot commented Mar 12, 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 Mar 12, 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 May 7, 2025 8:21am
9 Skipped Deployments
Name Status Preview Comments Updated (UTC)
code ⬜️ Ignored (Inspect) May 7, 2025 8:21am
legacy ⬜️ Ignored (Inspect) May 7, 2025 8:21am
legacy-www ⬜️ Ignored (Inspect) Visit Preview May 7, 2025 8:21am
backgrounds ⬜️ Skipped (Inspect) May 7, 2025 8:21am
blog ⬜️ Skipped (Inspect) May 7, 2025 8:21am
docs ⬜️ Skipped (Inspect) May 7, 2025 8:21am
sites ⬜️ Skipped (Inspect) May 7, 2025 8:21am
viewer ⬜️ Skipped (Inspect) May 7, 2025 8:21am
www ⬜️ Skipped (Inspect) May 7, 2025 8:21am

@coderabbitai

coderabbitai Bot commented Apr 30, 2025 •

Copy link
Copy Markdown

Walkthrough

This update introduces edge and network graph support to the canvas editor, expands AI image generation capabilities with flexible sizing and aspect ratios, adds a comprehensive AI model catalog, and modularizes the chat box UI. New hooks, types, and components are added for session management, authentication flows, and improved document initialization. Numerous UI and infrastructure refinements are included.

Changes

Files / Areas Change Summary
editor/app/(api)/private/ai/generate/image/route.ts, editor/app/(api)/private/ai/ratelimit.ts AI image generation API updated for optional width/height, aspect ratio, dynamic rate limiting, and accurate dimension extraction; rate limit function signature changed to accept a cost parameter.
editor/app/(dev)/canvas/examples/network/page.tsx, editor/grida/index.ts, editor/grida-react-canvas/viewport/surface.tsx, editor/grida-react-canvas/viewport/ui/network-arrow.tsx, editor/grida-react-canvas/viewport/ui/network-curve.tsx Introduced network/edge support in canvas: new example, edge types, rendering overlays, and arrow/curve components.
editor/app/(dev)/playground/image/_page.tsx, editor/app/(dev)/playground/image/page.tsx, editor/lib/ai/hooks/index.ts, editor/lib/ai/hooks/use-credits.ts, editor/lib/ai/hooks/use-generate-image.ts, editor/lib/ai/hooks/use-image-model.ts Refactored image playground into a document editor with integrated AI image generation; added hooks for credits, image generation, and model config.
editor/lib/ai/ai.ts Extended AI image model metadata, added new model, and improved type definitions.
editor/app/(www)/(ai)/ai/models/page.tsx, editor/www/data/sitemap.ts, editor/www/footer.tsx, editor/app/sitemap.ts Added AI models catalog page, updated sitemap and footer to include AI models.
editor/components/chat/chatbox.tsx, editor/components/chat/index.ts, editor/components/chat/minimal-chatbox.tsx, editor/app/(dev)/canvas/tools/ai/page.tsx Refactored chat box into modular/context-based components; added and used minimal chat box.
editor/grida-react-canvas/provider.tsx, editor/grida-react-canvas/state.ts, editor/grida-react-canvas/action.ts Extended document/editor APIs with node ID creation, node retrieval, and refined scene typing; allowed explicit node IDs on insert.
editor/app/(dev)/canvas/minimal/page.tsx, editor/app/(dev)/canvas/examples/[example]/page.tsx, editor/app/(workbench)/[org]/[proj]/[id]/canvas/page.tsx, editor/scaffolds/playground-canvas/playground.tsx Simplified/sanitized canvas and playground components; removed swipe-back disabling.
editor/app/(dev)/canvas/tools/transparency-grid/page.tsx, editor/grida-react-canvas/renderer.tsx Improved transparency grid controls and always rendered background grid.
editor/app/(dev)/playground/image/_components/image-frame.tsx Suppressed ESLint warning for effect dependencies.
editor/hooks/use-pending-callback.tsx Added hook for managing pending callbacks.
editor/lib/supabase/use-session.ts Added hook for Supabase session management.
editor/scaffolds/auth/continue-with-auth-dialog.tsx, editor/scaffolds/auth/continue-with-google-button.tsx, editor/scaffolds/auth/use-continue-with-auth.tsx Added authentication dialog, Google sign-in enhancements, and context/provider for authenticated actions.
editor/services/new/index.ts Refactored document scene initialization to use new scene factory.
editor/package.json Added image-size dependency; cleaned up pnpm config.
editor/www/header.tsx, editor/www/header-cta.tsx Moved session/CTA logic to new component; removed internal session management.
packages/grida-canvas-io-figma/lib.ts Added edges property to Figma scene export.
packages/grida-cmath/index.ts Extended hex color parsing to support RGBA hex strings.
editor/grida-react-canvas/api.md Added API usage draft for custom node insertion.
editor/grida/mixed/index.ts Improved safety in key extraction from possibly nullish objects.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CanvasEditor
    participant AIImageAPI
    participant RateLimiter
    participant ImageModelResolver

    User->>CanvasEditor: Request AI image (prompt, size, aspect_ratio)
    CanvasEditor->>ImageModelResolver: Resolve model & metadata
    CanvasEditor->>RateLimiter: Check credits (model.avg_credit)
    RateLimiter-->>CanvasEditor: Allow/Reject
    alt Allowed
        CanvasEditor->>AIImageAPI: Generate image (with prompt, size/aspect)
        AIImageAPI-->>CanvasEditor: Return image bytes
        CanvasEditor->>CanvasEditor: Extract actual image dimensions
        CanvasEditor-->>User: Insert image node with accurate metadata
    else Rejected
        CanvasEditor-->>User: Show rate limit/credit error
    end
Loading
sequenceDiagram
    participant User
    participant CanvasEditor
    participant NetworkOverlay

    User->>CanvasEditor: Add nodes and connect with edge
    CanvasEditor->>NetworkOverlay: Render edges between nodes
    NetworkOverlay->>CanvasEditor: Compute anchor positions
    NetworkOverlay-->>User: Display Bezier curves/arrows between nodes
Loading

Possibly related PRs

  • [Grida AI] Image Playground #313: Refactors the same AI image generation API route, broadening model input types, switching to a new rate limiting function, and enhancing response metadata; overlaps with this PR in model resolution and rate limiting logic.

Suggested labels

west

Poem

In a meadow of nodes where edges entwine,
The canvas now sparkles with networks divine.
AI paints with sizes both wide and tall,
And chat boxes modularly answer the call.
Models cataloged, credits in view—
Oh, what a spring for the code to renew!
🐇✨

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

Support

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

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.

@softmarshmallow softmarshmallow changed the title [Grida Canvas] Network Graph [Grida Canvas] Image Playground Canvas Apr 30, 2025
@softmarshmallow
softmarshmallow marked this pull request as ready for review May 7, 2025 06:54
@vercel
vercel Bot temporarily deployed to Preview – backgrounds May 7, 2025 06:54 Inactive
@vercel
vercel Bot temporarily deployed to Preview – viewer May 7, 2025 06:54 Inactive
@vercel
vercel Bot temporarily deployed to Preview – docs May 7, 2025 06:54 Inactive
@vercel
vercel Bot temporarily deployed to Preview – blog May 7, 2025 06:54 Inactive
@vercel
vercel Bot temporarily deployed to Preview – sites May 7, 2025 06:54 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: 15

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

205-226: 🛠️ Refactor suggestion

Parameter mismatch across providers

OpenAI accepts a fixed size string, Replicate models often require explicit width/height or aspect_ratio. The current logic passes both size & aspectRatio unconditionally, which may be silently ignored or error depending on SDK implementation. It would be safer to branch by model.provider.

-  size: size,
-  aspectRatio: aspect_ratio,
+  ...(model.provider === "openai" && size ? { size } : {}),
+  ...(model.provider === "replicate"
+      ? { width, height, aspectRatio: aspect_ratio }
+      : {}),
🧹 Nitpick comments (34)
editor/app/(dev)/playground/image/_components/image-frame.tsx (1)

35-39: Re-enable exhaustive-deps or memoize pause: Suppressing react-hooks/exhaustive-deps hides missing dependency warnings, but pause should be either included in the dependency array or guaranteed stable. For example, add pause to the deps:

-useEffect(() => {
  if (image) {
    pause();
  }
  // eslint-disable-next-line react-hooks/exhaustive-deps
}, [image]);
+useEffect(() => {
  if (image) {
    pause();
  }
}, [image, pause]);

This prevents stale closures and maintains lint compliance.

editor/grida-react-canvas/api.md (2)

1-3: Consolidate document heading: The file declares # API - Working draft and then repeats the title in plain text. Retain a single level-1 heading and remove duplicate text for clarity:

# API - Working Draft for Grida React Canvas

This streamlines the document structure.


5-5: Use heading syntax instead of emphasis: Replace **Insert custom node** with a proper markdown heading (e.g., ### Insert Custom Node) to improve semantics and accessibility.

🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

5-5: Emphasis used instead of a heading
null

(MD036, no-emphasis-as-heading)

editor/scaffolds/playground-canvas/playground.tsx (2)

898-908: TODO marked for API integration

The TODO indicates a plan to refactor this function to use the Grida library API. This is a good practice to document future improvements.

Consider adding more specificity to the TODO comment, such as which API method to use and potentially a JIRA/GitHub issue reference for tracking.


910-930: TODO marked for API integration

Similar to the previous TODO, this marks a function for future refactoring to use the Grida library API.

For better maintainability and to avoid duplication, consider moving both functions to a utility file that could be imported by this component until the refactoring is complete.

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

21-21: Good enhancement for variable cost rate limiting.

The parameter addition to ai_credit_limit and the implementation of the rate option allow for dynamic credit consumption based on the specific AI model's cost rather than treating all operations equally.

This approach is more fair and efficient - it enables fine-grained control over resource allocation where expensive operations consume more credits than simple ones.

Also applies to: 30-31


7-7:

Details

❓ Verification inconclusive

Significant rate limit increase.

The sliding window limit has been increased from 20 to 500 over a 30-day period. This is a 25x increase in allowed AI operations. Ensure this aligns with your infrastructure capacity and business model.


🏁 Script executed:

#!/bin/bash
# Check for any related infrastructure capacity planning documentation
fd -t f "capacity|planning|infrastructure" -e md -e txt | xargs cat | grep -i "rate limit\|ai credit\|usage projection"

Length of output: 121


Evaluate Infrastructure Capacity for Increased AI Rate Limit

The sliding window limit was raised from 20 to 500 over a 30-day period (a 25× increase). Please confirm this aligns with your infrastructure throughput, cost model, and upstream API allowances:

  • Coordinate with SRE/DevOps to validate queuing, database load, and network bandwidth under the new cap.
  • Update or create internal capacity-planning documentation to reflect the change.
  • Adjust monitoring and alerting thresholds for AI usage to catch unexpected spikes.
editor/services/new/index.ts (1)

15-15: Unused import added.

The GridFileStorageQueueProvider is imported but not used in this file. Either remove the unused import or document why it's needed.

-import { GridFileStorageQueueProvider } from "@/scaffolds/grid/providers";
editor/scaffolds/auth/continue-with-auth-dialog.tsx (1)

32-32: Add alt text to GridaLogo for better accessibility.

The GridaLogo is missing an alt text attribute. While it appears to be decorative in this context, it's a good practice to add an alt attribute for screen readers.

-            <GridaLogo className="h-8 w-8" />
+            <GridaLogo className="h-8 w-8" aria-label="Grida logo" />
editor/hooks/use-pending-callback.tsx (1)

58-64: Remove unnecessary catch clause.

The catch clause that only rethrows the original error is redundant and can be removed.

   try {
     setState((prev) => ({ ...prev, isExecuting: true }));
     await state.callback();
-  } catch (error) {
-    // Let the error propagate up
-    throw error;
   } finally {
     setState({ callback: null, isExecuting: false });
   }
🧰 Tools
🪛 Biome (1.9.4)

[error] 63-63: The catch clause that only rethrows the original error is useless.

An unnecessary catch clause can be confusing.
Unsafe fix: Remove the catch clause.

(lint/complexity/noUselessCatch)

editor/lib/ai/hooks/use-generate-image.ts (1)

73-80: Consider adding error state to the returned object.

The hook returns various states but doesn't include any error state that consumers could use to display error messages.

+  const [error, setError] = useState<Error | null>(null);

   // In the catch block of the generate function:
+  setError(error);

   return {
     key,
     loading,
     image,
     start,
     end,
     generate,
+    error,
   };
editor/app/(www)/(ai)/ai/models/page.tsx (2)

108-124: Style-badge “+N more” does not convey full list access

The “+N more” badge is not interactive, so users cannot discover the hidden styles.
Consider wrapping it in a HoverCard (or linking to a detail page) to preserve discoverability and accessibility.


163-170: Minor type-guard optimisation

The inline filter callback redundantly checks for !== undefined; Object.values<T>(models) already returns T[], not (T | undefined)[], if models is typed as a record.
If models really can contain undefined, prefer narrowing once and memoising, e.g. with useMemo, to avoid filtering on every render.

editor/scaffolds/auth/use-continue-with-auth.tsx (1)

70-81: Modal can leave unresolved Promises

If the user closes the dialog without authenticating, the Promise returned by withAuth neither resolves nor rejects, potentially hanging UI flows.
Provide a rejection path in onOpenChange={setIsOpen} when open becomes false and !session.

editor/scaffolds/auth/continue-with-google-button.tsx (1)

31-33: Accessibility: add aria-label

The button has no accessible name beyond its text. Adding an aria-label="Continue with Google" (or wrapping in <Button> from your design system) ensures assistive technologies recognise it if icon/text order changes.

editor/grida-react-canvas/provider.tsx (1)

1431-1433: Add JSDoc comment for the createNodeId function.

The implementation of createNodeId is straightforward, but it would benefit from JSDoc documentation explaining its purpose and usage. This is particularly important since it's being exposed as part of the public API.

+ /**
+  * Creates a unique node ID for use when creating new nodes in the document.
+  * @returns A unique string ID
+  */
  const createNodeId = useCallback(() => {
    return nid();
  }, []);
editor/grida-react-canvas/viewport/ui/network-curve.tsx (4)

1-6: Proper imports for network curve component.

The component correctly imports the necessary dependencies, but there are commented-out imports that should either be implemented or removed to keep the codebase clean.

import { cmath } from "@grida/cmath";
-// import { color_connection_line } from "../theme";
-// import { get_direction } from "./math";
import { NetworkArrow } from "./network-arrow";
import { cn } from "@/utils";

7-54: Clean implementation of the BezierCurvedLine component.

The component is well-structured for rendering a curved line between two points, with an arrow at the end. However, there are commented-out code lines (lines 20, 31, 41, 50) that should be cleaned up.

The component also uses hardcoded values for the arrow size (12) and direction ("e"), which could be made configurable via props for more flexibility.

export function BezierCurvedLine({
  id,
  a,
  b,
  width = 2,
  className,
+  arrowSize = 12,
+  arrowDirection = "e",
}: {
  id?: string;
  width?: number;
  className?: string;
  a: cmath.Vector2;
  b: cmath.Vector2;
+  arrowSize?: number;
+  arrowDirection?: "n" | "s" | "e" | "w";
}) {
-  // const direction = get_direction(a, b);

  return (
    <svg
      id={id}
      fill="transparent"
      style={{
        overflow: "visible",
        position: "absolute",
        pointerEvents: "none",
-        // transform: `translate(${a[0]}px, ${a[1]}px)`,
        zIndex: 10,
      }}
      className={cn("text-foreground", className)}
    >
      <path
        strokeWidth={width}
        d={make_bazier_curved_svg_path_data(
          a,
          b,
          "x"
-          // direction_to_axis_map[direction]
        )}
        className="stroke-current"
      />
      <NetworkArrow
-        size={12}
+        size={arrowSize}
        b={b}
        width={width}
-        direction="e"
+        direction={arrowDirection}
-        // direction={direction}
      />
    </svg>
  );
}

56-61: Unused direction to axis mapping.

This mapping is currently unused as the related code is commented out. It should either be used or removed to avoid dead code.

-const direction_to_axis_map = {
-  n: "v",
-  s: "v",
-  e: "h",
-  w: "h",
-} as const;

80-98: Fix typo in function name "bazier" → "bezier".

The helper function has a typo in its name: make_bazier_curved_svg_path_data should be make_bezier_curved_svg_path_data.

-function make_bazier_curved_svg_path_data(
+function make_bezier_curved_svg_path_data(
  a: cmath.Vector2,
  b: cmath.Vector2,
  axis: "x" | "y" = "x"
) {
  // function implementation...
}

And update the function call in the component:

d={make_bezier_curved_svg_path_data(
  a,
  b,
  "x"
)}
editor/lib/ai/hooks/use-image-model.ts (1)

30-87: Comprehensive size parsing and validation logic.

The setSize function handles multiple input formats flexibly and validates against the model's supported sizes. However, there's an unused variable declaration that should be cleaned up.

In the setSize function, you declare local variables _width, _height, and _aspect_ratio that are used for parsing, but then you also declare width, height, and aspect_ratio for validation. The latter set is correctly used in the final state update. You could simplify this by using only one set of variables:

- let _width: number | null = null;
- let _height: number | null = null;
- let _aspect_ratio: ai.image.AspectRatioString | null = null;

  let width: number | null = null;
  let height: number | null = null;
  let aspect_ratio: ai.image.AspectRatioString | null = null;

  // parse size
  if (typeof size === "string") {
    if (size.includes("x")) {
      const [widthStr, heightStr] = size.split("x");
-     _width = parseInt(widthStr);
-     _height = parseInt(heightStr);
+     width = parseInt(widthStr);
+     height = parseInt(heightStr);
    } else if (size.includes(":")) {
-     _aspect_ratio = size as ai.image.AspectRatioString;
+     aspect_ratio = size as ai.image.AspectRatioString;
    }
  } else if (typeof size === "object") {
    if ("width" in size && "height" in size) {
-     _width = size.width;
-     _height = size.height;
+     width = size.width;
+     height = size.height;
    } else if ("aspect_ratio" in size) {
-     _aspect_ratio = size.aspect_ratio as ai.image.AspectRatioString;
+     aspect_ratio = size.aspect_ratio as ai.image.AspectRatioString;
    }
  }

  // validate size
  if (card.sizes) {
    const _size = card.sizes?.find(([w, h, r]) => {
-     return (w === _width && h === _height) || r === _aspect_ratio;
+     return (w === width && h === height) || r === aspect_ratio;
    });

    if (_size) {
      const [w, h, r] = _size;
      width = w;
      height = h;
      aspect_ratio = r;
    }
  }
editor/grida-react-canvas/viewport/ui/network-arrow.tsx (1)

52-70: Parameter naming can be misleading & path is left open

  1. The helper receives { width, height } but internally const w = width / 2; – so width actually ends up as “full arrow width”, while w is half of that.
    A more explicit variable name (halfWidth) would make this clearer.

  2. Because the path is not closed (Z), using fill in CSS will produce an empty shape.
    If arrows are ever meant to be filled, add Z or use strokeLinejoin="round" for aesthetics.

Example diff:

-const w = width / 2;
+const halfWidth = width / 2;
...
-      return `M${x - height},${y + w} L${x},${y} L${x - height},${y - w}`;
+      return `M${x - height},${y + halfWidth} L${x},${y} L${x - height},${y - halfWidth} Z`;
editor/grida-react-canvas/viewport/surface.tsx (1)

332-339: Forced horizontal scroll reset may thrash layout

onScroll={(e) => (e.target as HTMLDivElement).scrollLeft = 0} is executed on every scroll tick, creating an immediate additional scroll event and potentially hurting performance.

If horizontal scrolling should be disabled, prefer CSS:

overscroll-behavior-x: contain; /* already present */
overflow-x: hidden;             /* instead of 'scroll' */

or guard the assignment:

if (et.scrollLeft !== 0) et.scrollLeft = 0;
editor/lib/ai/ai.ts (1)

82-87: Consider marking the default size as readonly

The default size tuple represents static metadata – making it immutable prevents accidental runtime mutation:

-  default: {
+  readonly default: {
editor/grida/index.ts (4)

289-307: Edge schema lacks direction info & immutable guards

Edge2D currently stores only two points. For future routing, you may need a readonly direction?: "undirected" | "directed" flag (or similar metadata) and readonly qualifiers on immutable fields (id, type). Adding them now avoids a breaking change later.

 export interface Edge2D {
-  id: string;
-  readonly type: "edge";
+  readonly id: string;
+  readonly type: "edge";
+  direction?: "undirected" | "directed";

454-458: Minor: allow callers to pre-seed edges

init_scene always overrides edges with a new empty array, ignoring a provided init.edges. Consider using the same pattern used for children:

-edges: [],
+edges: init.edges ?? [],

950-956: Prototype _ $id should be namespaced or symbol-based

Exposing _$id in public typings risks accidental persistence when prototypes are serialised.
Using a branded Symbol('prototypeId') avoids key-collision and keeps the field non-enumerable.


2056-2085: createContainerNode helper – expose padding object support

padding is initialised to 0, but the interface allows an object form. Accepting { paddingTop, ... } in partial and normalising internally would improve ergonomics.

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

52-56: Race-condition: credit consumption before generation success

Credits are decremented (ai_credit_limit) before the generation call. If the generation fails (network error, model quota), the user still loses credits. Consider performing the credit deduction only after successful generation, or refund on failure.

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

198-207: IME / composition input is not respected

Enter is intercepted unconditionally for submission. While !e.shiftKey guards multi-line input, it still fires while the user is composing characters (e.g. Korean, Japanese) causing premature submission.

-        if (e.key === "Enter" && !e.shiftKey) {
+        if (
+          e.key === "Enter" &&
+          !e.shiftKey &&
+          !e.nativeEvent.isComposing
+        ) {

A tiny change, but it prevents a frustrating UX for CJK users.


248-261: Submit button ignores global disabled state in UI

ChatBoxSubmit disables the <Button> but the icon’s color/state remains unchanged, giving no visual cue. Consider using the variant="secondary" or reducing opacity when disabled is true so users instantly understand the form is busy.

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

24-26: Unused import GenerationImageFrame—will fail the no-unused-vars lint rule

GenerationImageFrame isn’t referenced after the refactor. Remove the import to keep the build green.

-import { GenerationImageFrame } from "./_components/image-frame";

131-132: Destructured values key, image, start, end are no longer used

const { generate, key, loading, image, start, end } = useGenerateImage();

Only generate and loading are referenced later. Unused symbols will trigger TypeScript/ESLint errors and incur unnecessary re-renders.

-const { generate, key, loading, image, start, end } = useGenerateImage();
+const { generate, loading } = useGenerateImage();

370-374: Spelling nit: Hotkyes → Hotkeys

Small typo in component name; correcting improves readability and discoverability.

-function Hotkyes() {
+function Hotkeys() {

Remember to update the JSX <Hotkyes /> invocation above.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0060084 and bf44a1f.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (45)
  • editor/app/(api)/private/ai/generate/image/route.ts (5 hunks)
  • editor/app/(api)/private/ai/ratelimit.ts (3 hunks)
  • editor/app/(dev)/canvas/examples/[example]/page.tsx (1 hunks)
  • editor/app/(dev)/canvas/examples/network/page.tsx (1 hunks)
  • editor/app/(dev)/canvas/minimal/page.tsx (2 hunks)
  • editor/app/(dev)/canvas/tools/ai/page.tsx (2 hunks)
  • editor/app/(dev)/canvas/tools/transparency-grid/page.tsx (1 hunks)
  • editor/app/(dev)/playground/image/_components/image-frame.tsx (1 hunks)
  • editor/app/(dev)/playground/image/_page.tsx (3 hunks)
  • editor/app/(dev)/playground/image/page.tsx (2 hunks)
  • editor/app/(workbench)/[org]/[proj]/[id]/canvas/page.tsx (0 hunks)
  • editor/app/(www)/(ai)/ai/models/page.tsx (1 hunks)
  • editor/app/sitemap.ts (2 hunks)
  • editor/components/chat/chatbox.tsx (2 hunks)
  • editor/components/chat/index.ts (1 hunks)
  • editor/components/chat/minimal-chatbox.tsx (1 hunks)
  • editor/grida-react-canvas/action.ts (1 hunks)
  • editor/grida-react-canvas/api.md (1 hunks)
  • editor/grida-react-canvas/provider.tsx (7 hunks)
  • editor/grida-react-canvas/renderer.tsx (1 hunks)
  • editor/grida-react-canvas/state.ts (2 hunks)
  • editor/grida-react-canvas/viewport/surface.tsx (5 hunks)
  • editor/grida-react-canvas/viewport/ui/network-arrow.tsx (1 hunks)
  • editor/grida-react-canvas/viewport/ui/network-curve.tsx (1 hunks)
  • editor/grida/index.ts (9 hunks)
  • editor/grida/mixed/index.ts (1 hunks)
  • editor/hooks/use-pending-callback.tsx (1 hunks)
  • editor/lib/ai/ai.ts (5 hunks)
  • editor/lib/ai/hooks/index.ts (1 hunks)
  • editor/lib/ai/hooks/use-credits.ts (1 hunks)
  • editor/lib/ai/hooks/use-generate-image.ts (1 hunks)
  • editor/lib/ai/hooks/use-image-model.ts (1 hunks)
  • editor/lib/supabase/use-session.ts (1 hunks)
  • editor/package.json (2 hunks)
  • editor/scaffolds/auth/continue-with-auth-dialog.tsx (1 hunks)
  • editor/scaffolds/auth/continue-with-google-button.tsx (2 hunks)
  • editor/scaffolds/auth/use-continue-with-auth.tsx (1 hunks)
  • editor/scaffolds/playground-canvas/playground.tsx (2 hunks)
  • editor/services/new/index.ts (2 hunks)
  • editor/www/data/sitemap.ts (1 hunks)
  • editor/www/footer.tsx (1 hunks)
  • editor/www/header-cta.tsx (1 hunks)
  • editor/www/header.tsx (4 hunks)
  • packages/grida-canvas-io-figma/lib.ts (1 hunks)
  • packages/grida-cmath/index.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • editor/app/(workbench)/[org]/[proj]/[id]/canvas/page.tsx
🧰 Additional context used
🧬 Code Graph Analysis (14)
editor/app/(dev)/playground/image/page.tsx (1)
editor/app/(dev)/playground/image/_page.tsx (1)
  • ImagePlayground (71-123)
editor/www/footer.tsx (2)
editor/kits/minimal-tiptap/extensions/link/link.ts (1)
  • Link (7-97)
editor/app/sitemap.ts (1)
  • sitemap (3-116)
editor/app/(dev)/canvas/tools/ai/page.tsx (1)
editor/components/chat/minimal-chatbox.tsx (1)
  • MinimalChatBox (15-49)
editor/grida-react-canvas/renderer.tsx (2)
packages/grida-canvas-transparency-grid/component.tsx (1)
  • TransparencyGrid (14-49)
packages/grida-cmath/index.ts (2)
  • transform (831-839)
  • transform (1277-1313)
editor/lib/supabase/use-session.ts (1)
editor/lib/supabase/client.ts (1)
  • createBrowserClient (22-23)
editor/components/chat/minimal-chatbox.tsx (2)
editor/lib/file/index.ts (1)
  • BucketFileUploaderFn (51-51)
editor/components/chat/chatbox.tsx (7)
  • ChatBox (266-266)
  • ChatBoxHeader (267-267)
  • ChatBoxAttachmentPreview (271-271)
  • ChatBoxTextArea (269-269)
  • ChatBoxFooter (268-268)
  • ChatBoxAttachmentUploader (270-270)
  • ChatBoxSubmit (272-272)
editor/scaffolds/auth/continue-with-auth-dialog.tsx (2)
desktop/src/components/grida-logo.tsx (1)
  • GridaLogo (3-30)
editor/scaffolds/auth/continue-with-google-button.tsx (1)
  • ContinueWithGoogleButton (13-81)
editor/www/header.tsx (1)
editor/www/header-cta.tsx (1)
  • HeaderCTA (8-21)
editor/grida-react-canvas/viewport/ui/network-curve.tsx (2)
editor/grida/index.ts (1)
  • Vector2 (2101-2101)
editor/grida-react-canvas/viewport/ui/network-arrow.tsx (1)
  • NetworkArrow (5-34)
editor/grida-react-canvas/state.ts (1)
editor/grida/index.ts (3)
  • Document (392-395)
  • IBitmapsRepository (261-268)
  • Scene (409-438)
editor/grida-react-canvas/viewport/ui/network-arrow.tsx (1)
editor/grida/index.ts (1)
  • Vector2 (2101-2101)
editor/app/(api)/private/ai/generate/image/route.ts (2)
editor/lib/ai/ai.ts (5)
  • AspectRatioString (60-60)
  • ProviderModel (12-20)
  • ImageModelId (58-58)
  • ImageModelCard (66-87)
  • SizeString (62-62)
editor/app/(api)/private/ai/ratelimit.ts (1)
  • ai_credit_limit (21-47)
editor/components/chat/chatbox.tsx (1)
editor/lib/file/index.ts (1)
  • BucketFileUploaderFn (51-51)
editor/grida/index.ts (2)
editor/grida-react-canvas/document-query.ts (1)
  • nodes (586-588)
packages/grida-canvas-io-figma/lib.ts (1)
  • document (178-244)
🪛 markdownlint-cli2 (0.17.2)
editor/grida-react-canvas/api.md

5-5: Emphasis used instead of a heading
null

(MD036, no-emphasis-as-heading)

🪛 Biome (1.9.4)
editor/hooks/use-pending-callback.tsx

[error] 63-63: The catch clause that only rethrows the original error is useless.

An unnecessary catch clause can be confusing.
Unsafe fix: Remove the catch clause.

(lint/complexity/noUselessCatch)


[error] 6-6: Don't use 'Function' as a type.

Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.

(lint/complexity/noBannedTypes)


[error] 6-6: Don't use 'Function' as a type.

Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.

(lint/complexity/noBannedTypes)


[error] 16-16: Don't use 'Function' as a type.

Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.

(lint/complexity/noBannedTypes)


[error] 16-16: Don't use 'Function' as a type.

Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.

(lint/complexity/noBannedTypes)


[error] 40-40: Don't use 'Function' as a type.

Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.

(lint/complexity/noBannedTypes)


[error] 40-40: Don't use 'Function' as a type.

Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.

(lint/complexity/noBannedTypes)

🔇 Additional comments (58)
editor/package.json (2)

146-146: LGTM: Adding image-size dependency.

The addition of the image-size package is appropriate for handling image dimension extraction functionality, which will be used for determining the width and height of generated images.


253-253: LGTM: Simplified pnpm configuration.

The removal of the empty nested "overrides": {} property simplifies the configuration while maintaining the same functionality.

editor/lib/supabase/use-session.ts (1)

1-24: Well-structured authentication session hook implementation.

This new hook effectively manages Supabase authentication sessions with proper React patterns:

  • Memoized client creation prevents unnecessary re-renders
  • Appropriate subscription cleanup in the effect's return function
  • Correct dependency array for the useEffect
  • Clean type safety with the Session type

The implementation follows best practices for React hooks working with external services.

editor/app/(dev)/canvas/examples/[example]/page.tsx (1)

4-4: LGTM: Import order adjustment.

The repositioning of the import statement is a minor stylistic change that doesn't affect functionality. It simply aligns the import order with conventions used in other example pages.

editor/www/footer.tsx (1)

87-92: LGTM: New AI Models link added to Resources section.

The addition of the AI Models link follows the existing pattern for footer links, with consistent styling and proper navigation path. This link provides users with direct access to the new AI Models catalog page.

editor/www/data/sitemap.ts (1)

10-10: New ai_models sitemap link added: The new entry ai_models: "/ai/models" correctly reflects the AI Models catalog route. Verify this link is utilized in the footer and any other navigation components to ensure discoverability of the AI Models page.

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

13-13: Import MinimalChatBox instead of ChatBox: Updating this import to MinimalChatBox aligns with the modular chat UI refactor. Ensure no unused ChatBox imports remain in this or related files.


190-195: Replace <ChatBox> with <MinimalChatBox>: The usage of MinimalChatBox maintains prop compatibility while leveraging the slimmed-down chat interface. Confirm that onValueCommit, uploader, and accept behavior match expectations and update any associated styles if needed.

editor/components/chat/index.ts (1)

2-2: Re-export MinimalChatBox: Exposing MinimalChatBox via the chat index streamlines imports across the app. Confirm the public API surface is documented and update any references in the docs or code samples accordingly.

editor/lib/ai/hooks/index.ts (1)

1-3: Module export organization looks good.

The index file provides a clean central point for importing AI-related hooks throughout the application.

editor/grida-react-canvas/renderer.tsx (1)

117-122: Always rendering TransparencyGrid improves visual consistency.

This modification ensures the transparency grid is always visible, which enhances visual clarity for complex scenes with nodes and edges, aligning with the network graph visualization objectives of this PR.

editor/grida-react-canvas/action.ts (1)

553-556: Adding optional ID support for node prototypes enables better graph management.

The optional id parameter allows for explicit node identification during insertion, which is essential for managing edges and references between nodes in network graphs.

editor/app/(dev)/canvas/tools/transparency-grid/page.tsx (1)

40-57: Nice UI enhancements for transparency grid controls.

The addition of a control panel with a Reset button and display of current zoom/offset values improves usability of the demo. The panel is well-positioned and provides useful feedback to users.

editor/grida/mixed/index.ts (1)

98-99: Good defensive programming!

Adding the nullish coalescing operator (??) to handle potential null or undefined values in the objects array prevents runtime errors when calling Object.keys(). This makes the code more robust against unexpected input.

packages/grida-canvas-io-figma/lib.ts (1)

235-236: Added edges support for network graphs

Adding the empty edges array property to the scene document structure is a good first step for supporting network graph rendering between nodes as mentioned in the PR objectives.

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

3-4: Added necessary UI providers

Adding imports for sidebar and tooltip providers is essential for the enhanced UI functionality in the image playground.


13-19: Improved component structure with context providers

Wrapping the ImagePlayground component with TooltipProvider and SidebarProvider properly establishes the UI context hierarchy, ensuring tooltip and sidebar functionality is available throughout the component tree.

editor/app/sitemap.ts (2)

90-94: Added new AI models section to sitemap.

This addition aligns with the expanded AI image generation capabilities mentioned in the PR summary, providing SEO discoverability for the new AI model catalog.


18-18:

Details

❓ Verification inconclusive

Reduced crawl frequency for several sections.

The change frequency for multiple site sections has been reduced (e.g., blog from weekly to monthly, tools from daily to yearly). This could reduce your site's search engine freshness if these sections are actually updated more frequently than the new settings indicate.

Also applies to: 97-97, 102-102, 107-107, 112-112


🏁 Script executed:

#!/bin/bash
# Check update frequency of these sections by looking at commit history
echo "Checking update frequency for blog content:"
git log --since="3 months ago" --name-only --pretty=format: | grep -i "blog" | sort | uniq -c | sort -nr | head -5

echo -e "\nChecking update frequency for tools content:"
git log --since="6 months ago" --name-only --pretty=format: | grep -i "tools" | sort | uniq -c | sort -nr | head -5

Length of output: 201


Confirm content update cadence before finalizing crawl settings

Commit history shows no changes to “blog” files in the last 3 months or “tools” files in the last 6 months, so the reduced changeFrequency values (monthly for blog, yearly for tools) match the repo’s activity. However, if these sections are updated via an external CMS or other processes not captured in Git, please verify their true update cadence before shipping.

• Files to review:

  • editor/app/sitemap.ts (lines 18, 97, 102, 107, 112)
editor/services/new/index.ts (1)

254-261: Improved scene initialization approach.

Simplified the scene initialization by removing explicit properties and relying on the init_scene function to provide defaults. This follows the principle of having a single source of truth for initialization logic.

This change supports the PR objective of introducing edge and network graph support to the canvas editor by centralizing initialization logic that may now include edge-related defaults.

editor/app/(dev)/canvas/examples/network/page.tsx (3)

1-5: Good imports and module organization.

Clean imports and proper organization of modules. You're correctly importing both the editor component and the necessary utilities from grida and cmath libraries.


6-46: Well-structured document initialization with edge support.

The document structure is well-defined, demonstrating the new edge/network graph functionality. The nodes and their connection are clearly specified.

Note that you've included commented-out code on lines 25-26 that shows an alternative way to define edge connections using absolute positions instead of anchors. Consider either removing these comments if they're not needed or adding a brief explanation comment about why both approaches are shown.


48-54: Clean component implementation.

The page component follows React best practices and properly renders the full-screen editor with the demo network graph.

packages/grida-cmath/index.ts (1)

3296-3320: Enhanced support for RGBA colors in hex format.

Your implementation now correctly handles 8-character hex strings (#RRGGBBAA) for colors with alpha channel. The alpha value is properly normalized from 0-255 to a 0-1 range.

The error message has been appropriately updated to include the new supported format. This enhancement improves color handling for the canvas by supporting transparency, which is essential for the network graph feature.

editor/www/header-cta.tsx (2)

1-21: Well-structured authentication-aware header component.

The HeaderCTA component cleanly handles user authentication state using the useSession hook. The conditional rendering for showing the "Sign in" button only for unauthenticated users is implemented well, and I like the responsive design consideration with the hidden md:block class.


23-37: Clear conditional CTA rendering based on auth state.

The internal CTA component follows a clean pattern for conditional rendering based on authentication state. It directs users to either the dashboard (if signed in) or the general CTA page (if not signed in).

editor/components/chat/minimal-chatbox.tsx (3)

1-14: Good component imports and organization.

The imports are well-organized, bringing in all necessary chat box subcomponents. This demonstrates good modularity and component composition approach.


15-29: Well-typed props interface with reasonable defaults.

The component has a clear props interface with appropriate TypeScript types. The default placeholder text is sensible, and optional props are correctly marked with question marks.


30-49: Clean component composition pattern.

The component follows an excellent composition pattern, assembling smaller focused components into a cohesive UI. The structure with header, text area, and footer is logical and makes the code easy to understand and maintain.

This approach of composing specialized components rather than a monolithic implementation enhances maintainability and reusability. It allows for more flexibility in how the chat UI can be customized in different contexts.

editor/scaffolds/auth/continue-with-auth-dialog.tsx (3)

14-18: Great interface design for auth props.

The interface is well-defined with optional properties that allow for flexible authentication configurations.


20-26: Well-implemented dialog component with proper prop handling.

The component properly extends Dialog props and handles authentication-specific parameters in a clean way. The usage of skipBrowserRedirect with the Google login button enables a popup-based auth flow that doesn't navigate away from the current page, which improves user experience.

Also applies to: 28-48


4-4:

Details

❌ Incorrect review comment

Check default import path for GridaLogo component.

The import for GridaLogo uses a path alias @/components/grida-logo, but based on the relevant code snippets provided, this component seems to be located in desktop/src/components/grida-logo.tsx. Ensure the path alias is correctly configured in your project to resolve to the right location.


🏁 Script executed:

#!/bin/bash
# Verify if GridaLogo component is accessible from the imported path
find . -name "grida-logo.tsx" | grep -v "node_modules"

Length of output: 172


🏁 Script executed:

#!/bin/bash
# Locate and inspect path aliases in TypeScript/JS configs

echo "=== editor/tsconfig.json ==="
if [ -f editor/tsconfig.json ]; then
  grep -R -n '"paths"\|"baseUrl"' -C3 editor/tsconfig.json || echo "  (no alias config found)"
else
  echo "  editor/tsconfig.json not found"
fi

echo
echo "=== tsconfig.json (root) ==="
if [ -f tsconfig.json ]; then
  grep -R -n '"paths"\|"baseUrl"' -C3 tsconfig.json || echo "  (no alias config found)"
else
  echo "  tsconfig.json not found"
fi

Length of output: 428


Import path for GridaLogo is correctly configured
The editor’s tsconfig.json maps @/* → ./*, so import { GridaLogo } from "@/components/grida-logo"; resolves to editor/components/grida-logo.tsx, which exists. No changes needed.

Likely an incorrect or invalid review comment.

editor/app/(dev)/canvas/minimal/page.tsx (4)

41-41: Component name improvement.

The component has been renamed from CanvasPlayground to MinimalCanvasDemo, which better reflects its purpose as a minimal demonstration of canvas functionality.


75-81: Clean sidebar implementation.

The sidebars are now implemented as floating elements that are siblings of the main canvas container rather than being nested inside. This simplifies the DOM hierarchy while maintaining the same functionality.

Also applies to: 101-122


82-82: Improved layout structure.

The container div now uses fixed positioning covering the entire viewport, which simplifies the layout structure while maintaining the full-screen canvas experience.


83-99: Well-structured editor surface composition.

The editor surface composition maintains a logical hierarchy of components with proper nesting of clipboard sync, dropzone, context menu, viewport root, and other UI elements.

editor/hooks/use-pending-callback.tsx (2)

23-39: Great example documentation.

The JSDoc comment includes a clear example that demonstrates how to use the hook, which is very helpful for developers.


49-67: Well-implemented state management.

The hook properly maintains state for the callback and execution status, preventing concurrent executions of the same callback.

🧰 Tools
🪛 Biome (1.9.4)

[error] 63-63: The catch clause that only rethrows the original error is useless.

An unnecessary catch clause can be confusing.
Unsafe fix: Remove the catch clause.

(lint/complexity/noUselessCatch)

editor/lib/ai/hooks/use-generate-image.ts (1)

16-21: Well-structured state management.

The hook uses separate state variables for different aspects of the image generation process, making the code easier to understand and maintain.

editor/scaffolds/auth/use-continue-with-auth.tsx (1)

55-67: Effect cleanup resets hasHandledSession every render

Because the cleanup function sets hasHandledSession.current = false, toggling session from truthy → truthy (token refresh) will re-run handleAuthSuccess even though no user action occurred.
Consider tying the flag to a specific pendingState.id or removing the reset unless a new pending callback is queued.

editor/scaffolds/auth/continue-with-google-button.tsx (1)

6-12: redirect_uri vs redirectTo mismatch

Supabase expects options.redirectTo; the additional redirect_uri search param may be redundant or conflict with backend handling.
Verify that /auth/callback propagates the intended redirect and remove unused query keys to avoid open-redirect risks.

editor/grida-react-canvas/provider.tsx (4)

39-39: Clean import of node ID generator utility.

The import of the nid utility is appropriately placed at the top of the file with other imports.


2005-2005: API extension to expose node ID creation functionality.

Exposing the createNodeId function in the hook's return value enables consumers to generate consistent node IDs, which is necessary for the new edge connection functionality.


2391-2391: Including edges from scene in useEventTarget hook.

Properly destructuring the edges property from the scene object to make it available within the hook.


2835-2835: Exposing edges through the useEventTarget hook return value.

This change appropriately exposes the edges property to consumers of the useEventTarget hook, enabling integration with the network graph rendering system.

editor/www/header.tsx (3)

1-22: Clean up imports and refactor session management.

Good refactoring to separate concerns by importing the dedicated HeaderCTA component instead of managing session state directly in the header component.


51-53: Improved header container layout.

The layout adjustments simplify the markup structure while maintaining the same visual presentation.


123-123: Delegate call-to-action rendering to specialized component.

Using the HeaderCTA component here improves separation of concerns and makes the header component more focused on its primary responsibility of navigation.

editor/lib/ai/hooks/use-image-model.ts (3)

1-9: Well-defined default image size configuration.

The default size configuration is appropriately defined with type safety for the aspect ratio string.


11-29: Clean implementation of model selection and state management.

The hook follows React patterns for state management and provides a clean select callback for model switching. The state initialization with the default model is well-implemented.


89-98: Clean and comprehensive hook return API.

The hook returns a complete set of values and functions needed for image model configuration, with appropriate naming conventions.

editor/grida-react-canvas/state.ts (2)

886-889: IDocumentEditorInit.document.scenes typing looks good but may break existing callers

scenes is now strongly typed as Record<string, IDocumentSceneInit>.
Any caller that previously passed an array or a plain object without id | name | constraints will now fail to compile.
Please make sure every place that builds an IDocumentEditorInit value is adjusted accordingly (tests, storybook fixtures, etc.).


949-952: Silent behavioural change – default when_not_removable switched to "deactivate"

Changing the default from "ignore" ➜ "deactivate" means that previously-ignored remove actions will now flip active=false on the node.
Before this lands, double-check:

  1. Hotkeys / menu flows that rely on “nothing happens” still behave acceptably.
  2. Any consumer that inspects the active flag (export, rendering, etc.) won’t regress.

If this was intentional – great, but please call it out explicitly in the PR description / changelog so downstreams are aware.

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

219-254: Validate aspect-ratio math on the new “Flux Schnell” model

A few listed dimensions do not exactly match the declared ratio (e.g. 1536×640 vs 21:9 → 2.40 vs 2.33).
If this metadata feeds UI filters or server-side validation, the mismatch can cause false rejections. Double-check the manufacturer’s spec or round the ratio string to the nearest integer pair.

-[1536, 640, "21:9"],
+[1536, 640, "12:5"],  # ratio 2.40

64-66:

Details

✅ Verification successful

Check for dangling references to removed SizeWithAspectRatio type

SizeSpec replaces the old SizeWithAspectRatio, but other files may still import / reference the previous alias. To avoid type-errors at build time, run a quick grep across the repo:

and update any remaining usages.


🏁 Script executed:

#!/bin/bash
rg --line-number --fixed-strings "SizeWithAspectRatio" || true

Length of output: 61


All references to SizeWithAspectRatio have been removed
Verified via a repository-wide grep—no occurrences of the old alias remain. The new SizeSpec fully replaces it, so no further updates are needed.

editor/grida/index.ts (2)

410-412: Scene now extends IEdges – update initialisers & migrations

Any code that manually spreads a Scene object (tests, fixtures, migrations) must now include an edges: [] field or rely on init_scene. Failing to do so will break JSON-schema validation.


1944-1946: 🛠️ Refactor suggestion

Inconsistent default size for basic nodes (0 vs 100)

createNodeDataFromPrototypeWithoutChildren assigns width/height = 100 for most nodes, but rectangles still receive 0. This inconsistency complicates hit-testing logic that assumes non-zero dimensions.

-width: 0,
-height: 0,
+width: 100,
+height: 100,

Likely an incorrect or invalid review comment.

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

133-157: Callback type mismatch: attachments are silently discarded

ChatBox invokes onValueCommit with { text, attachments }, but onCommit is declared to accept only { text }. In strict function-type mode this is not assignable and will break the build; at runtime attachments are always ignored.

Either handle the attachments or widen the parameter type:

-const onCommit = (value: { text: string }) => {
+const onCommit = (value: { text: string; attachments: Attachment[] }) => {
   const id = editor.createNodeId();
   ...

(and propagate the generic Attachment type import).

This also enables future use cases such as generating images based on a reference picture.

Comment on lines +3 to +24
export function useCredits() {
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);
}, []);

useEffect(() => {
refresh();
}, [refresh]);

return {
remaining,
reset,
refresh,
};
}

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

Well-implemented React hook for credit management.

This credit tracking hook follows React best practices with proper state management, memoization via useCallback, and cleanup. The API exposed is clean and intuitive.

However, there's no error handling for the fetch request. Consider adding error handling to gracefully manage API failures.

 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);
+  try {
+    const response = await fetch(`/private/ai/credits`, {
+      method: "GET",
+    });
+    if (!response.ok) {
+      throw new Error(`Failed to fetch credits: ${response.status}`);
+    }
+    const r = await response.json();
+    setRemaining(r.data.remaining);
+    setReset(r.data.reset);
+  } catch (error) {
+    console.error("Error fetching credits:", error);
+    // Optionally set an error state here to show in the UI
+  }
 }, []);
📝 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 function useCredits() {
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);
}, []);
useEffect(() => {
refresh();
}, [refresh]);
return {
remaining,
reset,
refresh,
};
}
export function useCredits() {
const [remaining, setRemaining] = useState(0);
const [reset, setReset] = useState(0);
const refresh = useCallback(async () => {
try {
const response = await fetch(`/private/ai/credits`, {
method: "GET",
});
if (!response.ok) {
throw new Error(`Failed to fetch credits: ${response.status}`);
}
const r = await response.json();
setRemaining(r.data.remaining);
setReset(r.data.reset);
} catch (error) {
console.error("Error fetching credits:", error);
// Optionally set an error state here to show in the UI
}
}, []);
useEffect(() => {
refresh();
}, [refresh]);
return {
remaining,
reset,
refresh,
};
}
🤖 Prompt for AI Agents (early access)
In editor/lib/ai/hooks/use-credits.ts around lines 3 to 24, the fetch request
inside the refresh function lacks error handling, which can cause unhandled
promise rejections or silent failures. Wrap the fetch call in a try-catch block
to catch any errors during the API request, and handle them gracefully by
logging the error or updating state to reflect the failure. This ensures the
hook remains robust and does not break the component using it when the API call
fails.

Comment thread editor/hooks/use-pending-callback.tsx Resolved
Comment thread editor/hooks/use-pending-callback.tsx Resolved
Comment thread editor/hooks/use-pending-callback.tsx Resolved
Comment on lines +41 to +56
const r: GenerateImageApiResponse = await fetch(
`/private/ai/generate/image`,
{
body: JSON.stringify({
model,
width,
height,
aspect_ratio,
prompt,
} satisfies GenerateImageApiRequestBody),
method: "POST",
headers: {
"Content-Type": "application/json",
},
}
).then((res) => res.json());

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

Add error handling for API requests.

The fetch request doesn't include any error handling. If the API call fails or returns a non-JSON response, it could result in unhandled exceptions.

-      const r: GenerateImageApiResponse = await fetch(
-        `/private/ai/generate/image`,
-        {
-          body: JSON.stringify({
-            model,
-            width,
-            height,
-            aspect_ratio,
-            prompt,
-          } satisfies GenerateImageApiRequestBody),
-          method: "POST",
-          headers: {
-            "Content-Type": "application/json",
-          },
-        }
-      ).then((res) => res.json());
+      try {
+        const response = await fetch(
+          `/private/ai/generate/image`,
+          {
+            body: JSON.stringify({
+              model,
+              width,
+              height,
+              aspect_ratio,
+              prompt,
+            } satisfies GenerateImageApiRequestBody),
+            method: "POST",
+            headers: {
+              "Content-Type": "application/json",
+            },
+          }
+        );
+        
+        if (!response.ok) {
+          throw new Error(`Image generation failed: ${response.status} ${response.statusText}`);
+        }
+        
+        const r: GenerateImageApiResponse = await response.json();

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

🤖 Prompt for AI Agents (early access)
In editor/lib/ai/hooks/use-generate-image.ts around lines 41 to 56, the fetch
request lacks error handling, which can cause unhandled exceptions if the API
call fails or returns invalid JSON. Wrap the fetch call in a try-catch block to
catch network or parsing errors, check the response status before parsing JSON,
and handle non-OK responses gracefully by throwing or returning an appropriate
error.

Comment on lines +1063 to +1066
const n = getNodeById(p.target);
const cx = (n as any).left + (n as any).width / 2;
const cy = (n as any).top + (n as any).height / 2;
return vector2ToSurfaceSpace([cx, cy], transform);

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

Node center calculation assumes left/top props exist

The centre is derived via (n as any).left + width / 2, but many node definitions use x / y (or position) instead of left / top.

Consider normalising through a helper already used elsewhere (e.g. getNodeBoundingRect) to avoid undefined maths:

- const cx = n.left + n.width / 2;
- const cy = n.top + n.height / 2;
+ const rect = getNodeBoundingRect(n); // ← shared util
+ const cx = rect.x + rect.width / 2;
+ const cy = rect.y + rect.height / 2;
📝 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 n = getNodeById(p.target);
const cx = (n as any).left + (n as any).width / 2;
const cy = (n as any).top + (n as any).height / 2;
return vector2ToSurfaceSpace([cx, cy], transform);
const n = getNodeById(p.target);
const rect = getNodeBoundingRect(n); // ← shared util
const cx = rect.x + rect.width / 2;
const cy = rect.y + rect.height / 2;
return vector2ToSurfaceSpace([cx, cy], transform);
🤖 Prompt for AI Agents (early access)
In editor/grida-react-canvas/viewport/surface.tsx around lines 1063 to 1066, the
code calculates the node center using left and top properties which may not
exist on all node types, causing incorrect or undefined values. Replace this
calculation by using a helper function like getNodeBoundingRect that normalizes
node position and size, then compute the center from the bounding rectangle's x,
y, width, and height to ensure consistent and correct center coordinates.

Comment on lines +1057 to +1069
const get_pos = (p: grida.program.document.EdgePoint) => {
switch (p.type) {
case "position":
return vector2ToSurfaceSpace([p.x, p.y], transform);
case "anchor":
try {
const n = getNodeById(p.target);
const cx = (n as any).left + (n as any).width / 2;
const cy = (n as any).top + (n as any).height / 2;
return vector2ToSurfaceSpace([cx, cy], transform);
} catch (e) {}
}
};

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

Swallowing errors hides edge-resolution problems

get_pos catches any exception from getNodeById but silently continues, returning undefined.
This makes debugging broken edges hard.

-        try {
-          const n = getNodeById(p.target);
-          ...
-        } catch (e) {}
+        const n = getNodeById(p.target);
+        if (!n) {
+          console.warn(`[Edge] target node '${p.target}' not found for edge '${id}'.`);
+          return;
+        }

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

🤖 Prompt for AI Agents (early access)
In editor/grida-react-canvas/viewport/surface.tsx around lines 1057 to 1069, the
get_pos function catches errors from getNodeById but silently ignores them,
causing it to return undefined and making debugging difficult. Modify the catch
block to log the error or rethrow it so that edge-resolution problems are
visible during debugging instead of being swallowed silently.

Comment thread editor/lib/ai/ai.ts
Comment on lines +73 to 80
speed_label: "fastest" | "fast" | "medium" | "slow" | "slowest";
speed_max: string;
min_width: number;
max_width: number;
min_height: number;
max_height: number;
sizes: SizeWithAspectRatio[] | null;
sizes: SizeSpec[] | null;
avg_ppi: number;

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

New "fastest" speed label may break existing enum switches

Down-stream UI components or logic that use a finite switch / mapping on speed_label will now receive an unexpected value. Please audit those call-sites (e.g. badge colour mapping, rate-limit calculator) to ensure they include "fastest" and fall back gracefully.

-case "fast":
+case "fast":
+case "fastest":

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

🤖 Prompt for AI Agents (early access)
In editor/lib/ai/ai.ts around lines 73 to 80, the addition of the "fastest"
value to the speed_label union type may cause downstream switch statements or
mappings to break if they do not handle this new case. Review all usages of
speed_label in the codebase, especially UI components like badge color mappings
and rate-limit calculators, and update their switch or conditional logic to
include a case for "fastest". Also, ensure that all switches have a default or
fallback case to handle unexpected values gracefully.

Comment on lines +13 to 14
import imageSize from "image-size";
import ai from "@/lib/ai";

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

image-size may throw – wrap in try/catch

If the generated bytes are corrupt or an unsupported format, imageSize throws, resulting in a 500. Guard it to return a 422 validation error instead.

-const { width, height } = imageSize(generation.image.uint8Array);
+let width = body.width, height = body.height;
+try {
+  ({ width, height } = imageSize(generation.image.uint8Array));
+} catch (e) {
+  return NextResponse.json(
+    { message: "Failed to read dimensions", error: (e as Error).message },
+    { status: 422 }
+  );
+}
🤖 Prompt for AI Agents (early access)
In editor/app/(api)/private/ai/generate/image/route.ts around lines 13 to 14,
the import of image-size is fine but when calling imageSize on generated bytes,
it may throw an error if the image is corrupt or unsupported. Wrap the call to
imageSize in a try/catch block and in the catch, return a 422 validation error
response instead of letting the error propagate and cause a 500 server error.

Comment on lines +91 to +104
useEffect(() => {
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",
});
}
if (task) {
toast.promise(task, {

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

Broken optional–chain triggers a runtime TypeError when uploader is undefined

uploader?.(file) may legitimately return undefined, but the chained .then(...) is still executed, dereferencing undefined and crashing the component the moment a user picks a file without an uploader prop.
Refactor to guard the promise creation explicitly:

-      const task = uploader?.(file).then((result) => {
+      let task: Promise<UploadResult> | undefined;
+      if (uploader) {
+        task = uploader(file).then((result) => {
           setAttachment({
             type: "image",
             filename: file.name,
             mimeType: file.type,
             url: result.publicUrl,
           });
         });
+      }
-      if (task) {
+      if (task) {
         toast.promise(task, {
           loading: "Uploading...",
           success: "Uploaded",
           error: "Failed to upload",
         });
       }

Without this fix, file-picking silently breaks in any context where uploader is omitted.

📝 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
useEffect(() => {
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",
});
}
if (task) {
toast.promise(task, {
useEffect(() => {
if (plainFiles.length === 1) {
const file = plainFiles[0];
let task: Promise<UploadResult> | undefined;
if (uploader) {
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",
});
}
}
}, [plainFiles, uploader]);
🤖 Prompt for AI Agents (early access)
In editor/components/chat/chatbox.tsx around lines 91 to 104, the optional
chaining on uploader followed by .then causes a runtime TypeError when uploader
is undefined because .then is called on undefined. To fix this, explicitly check
if uploader is defined before calling it and chaining .then. Only create the
promise and call .then if uploader exists; otherwise, skip this logic to prevent
the error.

@vercel
vercel Bot temporarily deployed to Preview – backgrounds May 7, 2025 08:09 Inactive
@vercel
vercel Bot temporarily deployed to Preview – blog May 7, 2025 08:09 Inactive
@vercel
vercel Bot temporarily deployed to Preview – viewer May 7, 2025 08:09 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: 0

🧹 Nitpick comments (2)
editor/hooks/use-pending-callback.tsx (2)

60-68: Consider removing the unnecessary catch clause

The catch clause only rethrows the error without additional processing, making it redundant.

 try {
   setState((prev) => ({ ...prev, isExecuting: true }));
   await state.callback();
-} catch (error) {
-  // Let the error propagate up
-  throw error;
 } finally {
   setState({ callback: null, isExecuting: false });
 }
🧰 Tools
🪛 Biome (1.9.4)

[error] 65-65: The catch clause that only rethrows the original error is useless.

An unnecessary catch clause can be confusing.
Unsafe fix: Remove the catch clause.

(lint/complexity/noUselessCatch)


32-40: Minor improvement to example code

Since executeCallback returns a Promise, the await keyword in the example isn't necessary unless you specifically want to wait for its completion before proceeding.

// Set a callback to be executed later
handlers.setCallback(() => () => console.log('Hello'));

// Execute the callback when ready
-await handlers.executeCallback();
+handlers.executeCallback();

Alternatively, if waiting for completion is intended, add a comment explaining why:

// Wait for callback to complete before proceeding
await handlers.executeCallback();
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2996ed2 and 2c44994.

📒 Files selected for processing (2)
  • editor/hooks/use-pending-callback.tsx (1 hunks)
  • editor/scaffolds/auth/use-continue-with-auth.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • editor/scaffolds/auth/use-continue-with-auth.tsx
🧰 Additional context used
🪛 Biome (1.9.4)
editor/hooks/use-pending-callback.tsx

[error] 65-65: The catch clause that only rethrows the original error is useless.

An unnecessary catch clause can be confusing.
Unsafe fix: Remove the catch clause.

(lint/complexity/noUselessCatch)

🔇 Additional comments (4)
editor/hooks/use-pending-callback.tsx (4)

3-4: Good choice defining a custom function type

Using a custom type Fn instead of the generic Function type addresses the issues flagged in previous reviews. This approach provides better type safety while maintaining flexibility.


8-13: Well-structured interface with proper JSDoc

The PendingCallbackState interface is properly typed with the custom Fn type and includes helpful documentation comments explaining each property.


18-23: Clear handler interface with descriptive comments

The PendingCallbackHandlers interface is well-defined and includes descriptive JSDoc comments that clearly explain the purpose of each method.


25-41: Excellent documentation with examples

The hook includes comprehensive JSDoc comments explaining its purpose, usage scenario, and even provides a code example, which significantly improves developer experience.

This branch was successfully deployed

2 active (1 outdated) and 5 inactive deployments
Preview – grida — 2c44994b Deployed May 7, 2025 by vercel[bot]
Preview – backgrounds — 2c44994b Deployed May 7, 2025 by vercel[bot]
Preview – sites — 2c44994b Deployed May 7, 2025 by vercel[bot]
Preview – viewer — 2c44994b Deployed May 7, 2025 by vercel[bot]
Preview – blog — 2c44994b Deployed May 7, 2025 by vercel[bot]
Preview – docs — 2c44994b Deployed May 7, 2025 by vercel[bot]
Preview – legacy-www — 44367169 Deployed May 2, 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