Skip to content

Conversation

@Kitenite
Copy link
Contributor

@Kitenite Kitenite commented Sep 9, 2025

Description

Related Issues

Type of Change

  • Bug fix
  • New feature
  • Documentation update
  • Release
  • Refactor
  • Other (please describe):

Testing

Screenshots (if applicable)

Additional Notes


Important

Improves project creation reliability by ensuring readiness of components and adds default chat conversation for new projects.

  • Behavior:
    • Ensures project creation resumes only when canvas, conversations, and sandbox are ready in use-start-project.tsx.
    • Automatically creates a default chat conversation for new projects in project.ts.
  • State Management:
    • Introduces ProjectReadyState interface in use-start-project.tsx to track readiness of canvas, conversations, and sandbox.
    • Adds updateProjectReadyState() function to update readiness state.
  • Misc:
    • Removes unused loading state checks in use-start-project.tsx.
    • Exports conversation defaults in index.ts.

This description was created by Ellipsis for 5920c93. You can customize this summary. It will automatically update as commits are pushed.


Summary by CodeRabbit

  • New Features

    • Automatically creates a default chat conversation for every new project, available immediately after setup.
    • Project startup now applies canvas, frames and conversations asynchronously so each component becomes available as soon as ready.
  • Bug Fixes

    • Improves reliability by resuming creation only when all project parts report ready, reducing race conditions.
    • Adds retry support and clearer error aggregation with user-facing error toasts on failures.

@vercel
Copy link

vercel bot commented Sep 9, 2025

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

Project Deployment Preview Comments Updated (UTC)
web Ready Ready Preview Comment Sep 9, 2025 5:05pm
1 Skipped Deployment
Project Deployment Preview Comments Updated (UTC)
docs Skipped Skipped Sep 9, 2025 5:05pm

@supabase
Copy link

supabase bot commented Sep 9, 2025

This pull request has been ignored for the connected project wowaemfasoptxrdjhilu because there are no changes detected in apps/backend/supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

@coderabbitai
Copy link

coderabbitai bot commented Sep 9, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

Reworks client startup hook to track per-subsystem readiness (canvas, conversations, sandbox), gate resume-create on combined readiness, and expand resumeCreate to complete creation with chat context and retries. Server project creation now inserts a default conversation in the same transaction. DB defaults barrel re-exports conversation defaults.

Changes

Cohort / File(s) Summary
Client Hook: Project Start & Resume
apps/web/client/src/app/project/[id]/_hooks/use-start-project.tsx
Replaces single boolean ready flag with projectReadyState {canvas, conversations, sandbox} and updateProjectReadyState. Applies canvas/frames and conversations when available (conversations applied async). Marks sandbox ready when sandbox.session.isConnecting becomes false. Derives isProjectReady from all readiness flags and gates resumeCreate on it; expands resumeCreate to validate projectId, build combined chat context (including image contexts), send an edit message, mark creation request COMPLETED, handle errors/toasts, and reset processedRequestIdRef on failures. Consolidates error aggregation and removes isLoading-based gating.
Server: Project Creation Transaction
apps/web/client/src/server/api/routers/project/project.ts
Imports conversations table and createDefaultConversation; during project creation transaction inserts a default conversation (via createDefaultConversation(newProject.id)) after default frames are created and before inserting the creation request; transaction ordering adjusted accordingly.
DB Defaults Barrel
packages/db/src/defaults/index.ts
Re-exports conversation defaults with export * from './conversation' to expose createDefaultConversation/conversation defaults from the defaults barrel.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Client
  participant API as Project API
  participant DB
  rect rgba(200,235,255,0.25)
  note right of API: Single DB transaction for project creation
  Client->>API: createProject(request)
  API->>DB: Insert project
  API->>DB: Insert default frames/canvases
  API->>DB: Insert default conversation (createDefaultConversation)
  API->>DB: Insert creation request
  DB-->>API: Commit
  API-->>Client: Project created (with conversation)
  end
Loading
sequenceDiagram
  autonumber
  participant Hook as useStartProject
  participant State as ProjectReadyState
  participant Resume as resumeCreate
  Note over Hook,State: projectReadyState = {canvas, conversations, sandbox}
  State-->>Hook: updates (canvasWithFrames / conversations / sandbox.session)
  opt conversations apply
    Hook->>Hook: apply conversations asynchronously
  end
  alt all subsystems ready && creationRequest exists
    Hook->>Resume: resumeCreate(creationRequest)
    Resume-->>Hook: mark COMPLETED / error, send toasts, reset processedRequestIdRef on failure
  else not ready
    Note over Hook: wait for readiness
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • bug: resume create request race condition #2817 — Modifies the same use-start-project creationRequest gating and project creation flow; likely overlaps with readiness/effect dependency changes.
  • feat: new project frames #2673 — Changes project creation defaults (frames/canvases); interacts with insertion ordering and default seeding in the same router.
  • feat: add branching #2763 — Touches the client startup flow and server defaults for conversations/branches; relevant to resumeCreate and default conversation insertion.

Poem

I nibble through code with a twitch in my nose,
Frames, chats, and sandboxes lining in rows.
I wait till each piece says “ready” and true —
Then thump! I resume and the project pops through. 🐇🥕

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fb89d35 and 5920c93.

📒 Files selected for processing (1)
  • apps/web/client/src/app/project/[id]/_hooks/use-start-project.tsx (2 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch bug/resume-create

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

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

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)
apps/web/client/src/app/project/[id]/_hooks/use-start-project.tsx (1)

52-56: Good guard; consider strengthening readiness to data presence + no errors.

The isProjectReady gate fixes the race, but it currently flips true solely when loading flags are false. If any query resolves with an error or without required data, resumeCreate could still fire prematurely.

  • Suggest: require canvas/conversations data presence and no query errors before allowing resumeCreate.

Diff for readiness computation (Lines 106-115):

-    useEffect(() => {
-        const allQueriesResolved =
-            !isUserLoading &&
-            !isCanvasLoading &&
-            !isConversationsLoading &&
-            !isCreationRequestLoading;
-
-        setIsProjectReady(allQueriesResolved);
-    }, [isUserLoading, isCanvasLoading, isConversationsLoading, isCreationRequestLoading]);
+    useEffect(() => {
+        const allQueriesResolved =
+            !isUserLoading &&
+            !isCanvasLoading &&
+            !isConversationsLoading &&
+            !isCreationRequestLoading;
+        const noErrors = !userError && !canvasError && !conversationsError && !creationRequestError;
+        const dataPresent = !!canvasWithFrames && Array.isArray(conversations) && conversations.length > 0;
+        setIsProjectReady(allQueriesResolved && noErrors && dataPresent);
+    }, [
+        isUserLoading, isCanvasLoading, isConversationsLoading, isCreationRequestLoading,
+        userError, canvasError, conversationsError, creationRequestError,
+        canvasWithFrames, conversations
+    ]);
  • Nit: to avoid any chance of cross-project bleed, reset processedRequestIdRef when projectId changes:
// outside selected range; add near other effects
useEffect(() => {
  processedRequestIdRef.current = null;
}, [editorEngine.projectId]);

This aligns with the provided TSX guidelines around effect deps and race avoidance.

Would you like me to push a patch with the above readiness tweak?

apps/web/client/src/server/api/routers/project/project.ts (1)

295-299: Creating a default conversation inside the project creation transaction is a solid fix.

  • Ensures the client can safely gate on conversations being loaded before resuming the create flow.
  • Order (before creation request) is sensible.

Optional: if duplicate-creation retries are possible, consider ON CONFLICT DO NOTHING on a unique (projectId, some-default-flag) to guarantee idempotency.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ae14ab2 and fb89d35.

📒 Files selected for processing (3)
  • apps/web/client/src/app/project/[id]/_hooks/use-start-project.tsx (1 hunks)
  • apps/web/client/src/server/api/routers/project/project.ts (2 hunks)
  • packages/db/src/defaults/index.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.tsx

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.tsx: In React providers managing MobX stores, create the observable store with useState(() => new Store()) to ensure a stable instance
Keep a ref (e.g., storeRef.current) to the MobX store to avoid stale closures in effects
Use setTimeout(() => store.clear(), 0) for delayed cleanup of MobX stores to avoid race conditions
Separate project changes from branch updates by using proper effect dependency arrays
Do not use useMemo to hold MobX observable instances; React may drop memoized values causing data loss
Do not clean up MobX stores synchronously during navigation; perform delayed cleanup instead
Do not include the MobX store instance in effect dependency arrays when it causes infinite loops

Files:

  • apps/web/client/src/app/project/[id]/_hooks/use-start-project.tsx
🧠 Learnings (1)
📚 Learning: 2025-09-07T23:36:29.678Z
Learnt from: CR
PR: onlook-dev/onlook#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-07T23:36:29.678Z
Learning: Applies to **/*.tsx : Separate project changes from branch updates by using proper effect dependency arrays

Applied to files:

  • apps/web/client/src/app/project/[id]/_hooks/use-start-project.tsx
🧬 Code graph analysis (1)
apps/web/client/src/server/api/routers/project/project.ts (1)
packages/db/src/defaults/conversation.ts (1)
  • createDefaultConversation (4-13)
🔇 Additional comments (2)
packages/db/src/defaults/index.ts (1)

3-3: Barrel export for conversation defaults looks good.

This makes the new defaults available to server consumers; aligns with the new import in project router.

apps/web/client/src/server/api/routers/project/project.ts (1)

10-14: Imports updated to include conversations and createDefaultConversation.

Matches the new barrel export; no issues.

@vercel vercel bot temporarily deployed to Preview – docs September 9, 2025 17:02 Inactive
@Kitenite Kitenite merged commit 4e87122 into main Sep 9, 2025
4 of 6 checks passed
@Kitenite Kitenite deleted the bug/resume-create branch September 9, 2025 17:03
if (creationRequest && processedRequestIdRef.current !== creationRequest.id) {
const isProjectReady = Object.values(projectReadyState).every((value) => value);
if (creationRequest && processedRequestIdRef.current !== creationRequest.id && isProjectReady) {
console.error('Resume create', creationRequest, isProjectReady, processedRequestIdRef.current);
Copy link
Contributor

Choose a reason for hiding this comment

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

It appears there's a console.error statement that was likely added for debugging purposes but left in the production code. This will generate error messages in the console during normal project creation flows, which could be confusing for users and developers alike.

Consider either:

  1. Removing this line entirely if the debugging is no longer needed
  2. Changing to console.debug() or console.log() if the information is still valuable
  3. Implementing a proper logging system with appropriate log levels

Since this appears in a core project creation flow, keeping the console clean of false error messages would improve the developer experience.

Suggested change
console.error('Resume create', creationRequest, isProjectReady, processedRequestIdRef.current);
console.debug('Resume create', creationRequest, isProjectReady, processedRequestIdRef.current);

Spotted by Diamond

Fix in Graphite


Is this helpful? React 👍 or 👎 to let us know.

Comment on lines +67 to +73
const applyConversations = async () => {
if (conversations) {
await editorEngine.chat.conversation.applyConversations(conversations);
updateProjectReadyState({ conversations: true });
}
};
applyConversations();
Copy link
Contributor

Choose a reason for hiding this comment

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

The async applyConversations function lacks error handling, which could lead to inconsistent state. If editorEngine.chat.conversation.applyConversations() fails, the component would still mark conversations as ready through updateProjectReadyState({ conversations: true }).

Consider adding error handling:

const applyConversations = async () => {
  if (conversations) {
    try {
      await editorEngine.chat.conversation.applyConversations(conversations);
      updateProjectReadyState({ conversations: true });
    } catch (error) {
      console.error('Failed to apply conversations:', error);
      // Either set an error state or retry logic here
    }
  }
};

This ensures the ready state is only updated when conversations are successfully applied.

Suggested change
const applyConversations = async () => {
if (conversations) {
await editorEngine.chat.conversation.applyConversations(conversations);
updateProjectReadyState({ conversations: true });
}
};
applyConversations();
const applyConversations = async () => {
if (conversations) {
try {
await editorEngine.chat.conversation.applyConversations(conversations);
updateProjectReadyState({ conversations: true });
} catch (error) {
console.error('Failed to apply conversations:', error);
// Either set an error state or retry logic here
}
}
};
applyConversations();

Spotted by Diamond

Fix in Graphite


Is this helpful? React 👍 or 👎 to let us know.

updateProjectReadyState({ conversations: true });
}
};
applyConversations();
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider wrapping the async function 'applyConversations' in a try/catch block to handle potential errors during conversation application.

Suggested change
applyConversations();
applyConversations().catch(console.error);

if (creationRequest && processedRequestIdRef.current !== creationRequest.id) {
const isProjectReady = Object.values(projectReadyState).every((value) => value);
if (creationRequest && processedRequestIdRef.current !== creationRequest.id && isProjectReady) {
console.error('Resume create', creationRequest, isProjectReady, processedRequestIdRef.current);
Copy link
Contributor

Choose a reason for hiding this comment

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

Remove or refactor the console.error used for logging 'Resume create' before production deployment to avoid verbose debugging output.

Suggested change
console.error('Resume create', creationRequest, isProjectReady, processedRequestIdRef.current);

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.

2 participants