Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(ui): pulled out routers await of the undoTrackerActionWrapper #807

Merged
merged 1 commit into from
Jan 28, 2025

Conversation

billcookie
Copy link
Contributor

@billcookie billcookie commented Jan 28, 2025

Overview

Sub workflow redo/undo was not working when we add a new one.

What I've done

Ensured that async requests are not wrapped by the undoTrackerActionWrapper

What I haven't done

How I tested

Manually

Screenshot

Which point I want you to review particularly

Possible refactors and improvements

Memo

Summary by CodeRabbit

  • New Features

    • Enhanced workflow creation process with improved router configuration fetching
    • Added error handling for workflow addition methods
  • Refactor

    • Modularized router configuration retrieval
    • Improved error management in workflow creation logic

Copy link
Contributor

coderabbitai bot commented Jan 28, 2025

Walkthrough

The pull request modifies the useYWorkflow.ts hook to improve workflow creation and management. A new asynchronous function fetchRouterConfigs is introduced to centralize router configuration fetching. The createYWorkflow method now accepts explicit router parameters, and both handleYWorkflowAdd and handleYWorkflowAddFromSelection methods are updated with enhanced error handling and a more modular approach to fetching router configurations.

Changes

File Change Summary
ui/src/lib/yjs/useYWorkflow.ts - Added fetchRouterConfigs function for router configuration retrieval
- Updated createYWorkflow to accept explicit router parameters
- Enhanced error handling in workflow addition methods
- Separated router fetching logic from workflow creation process

Sequence Diagram

sequenceDiagram
    participant User
    participant useYWorkflow
    participant Fetcher
    participant YWorkflows

    User->>useYWorkflow: Trigger workflow add
    useYWorkflow->>Fetcher: Fetch router configs
    Fetcher-->>useYWorkflow: Return router configs
    useYWorkflow->>YWorkflows: Create workflow with routers
    YWorkflows-->>useYWorkflow: Workflow created
Loading

Possibly related PRs

Suggested reviewers

  • KaWaite

Poem

🐰 A rabbit's tale of code so bright,
Workflows dancing with router might,
Fetching configs with grace and care,
Error handling beyond compare,
Modularity takes its flight! 🚀

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

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.

Copy link

netlify bot commented Jan 28, 2025

Deploy Preview for reearth-flow ready!

Name Link
🔨 Latest commit d82349f
🔍 Latest deploy log https://app.netlify.com/sites/reearth-flow/deploys/67987d0f60e6ae000860ae6b
😎 Deploy Preview https://deploy-preview-807--reearth-flow.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

@billcookie billcookie marked this pull request as ready for review January 28, 2025 06:46
@billcookie billcookie requested a review from KaWaite as a code owner January 28, 2025 06:46
Copy link
Contributor

@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)
ui/src/lib/yjs/useYWorkflow.ts (2)

35-41: LGTM! Consider adding error handling.

Good job extracting the router fetching logic into a reusable function. The use of Promise.all for parallel fetching is efficient.

Consider adding error handling with specific error messages:

 const fetchRouterConfigs = useCallback(async () => {
+  try {
     const [inputRouter, outputRouter] = await Promise.all([
       fetcher<Action>(`${api}/actions/InputRouter`),
       fetcher<Action>(`${api}/actions/OutputRouter`),
     ]);
     return { inputRouter, outputRouter };
+  } catch (error) {
+    throw new Error(`Failed to fetch router configs: ${error.message}`);
+  }
 }, [api]);

162-252: LGTM! Consider extracting node selection logic.

The changes align well with the pattern used in handleYWorkflowAdd. Good job on maintaining consistency.

Consider extracting the node selection and position calculation logic into separate functions for better maintainability:

+const getSelectedNodesWithBatchChildren = (
+  nodes: Node[],
+  nodesByParentId: Map<string, Node[]>
+): Set<string> => {
+  const allIncludedNodeIds = new Set<string>();
+  const selectedNodes = nodes.filter((n) => n.selected);
+  
+  selectedNodes.forEach((node) => {
+    allIncludedNodeIds.add(node.id);
+    if (node.type === "batch") {
+      (nodesByParentId.get(node.id) ?? []).forEach((batchNode) =>
+        allIncludedNodeIds.add(batchNode.id)
+      );
+    }
+  });
+  
+  return allIncludedNodeIds;
+};
+
+const calculateInitialPosition = (selectedNodes: Node[]): XYPosition => ({
+  x: Math.min(...selectedNodes.map((n) => n.position.x)),
+  y: Math.min(...selectedNodes.map((n) => n.position.y))
+});

 const handleYWorkflowAddFromSelection = useCallback(
   async (nodes: Node[], edges: Edge[]) => {
     try {
       const routers = await fetchRouterConfigs();

       undoTrackerActionWrapper(() => {
         const nodesByParentId = new Map<string, Node[]>();
         nodes.forEach((node) => {
           if (node.parentId) {
             if (!nodesByParentId.has(node.parentId)) {
               nodesByParentId.set(node.parentId, []);
             }
             nodesByParentId.get(node.parentId)?.push(node);
           }
         });

         const selectedNodes = nodes.filter((n) => n.selected);
         if (selectedNodes.length === 0) return;

-        const allIncludedNodeIds = new Set<string>();
-        selectedNodes.forEach((node) => {
-          allIncludedNodeIds.add(node.id);
-          if (node.type === "batch") {
-            getBatchNodes(node.id).forEach((batchNode) =>
-              allIncludedNodeIds.add(batchNode.id)
-            );
-          }
-        });
+        const allIncludedNodeIds = getSelectedNodesWithBatchChildren(
+          nodes,
+          nodesByParentId
+        );

-        const position = {
-          x: Math.min(...selectedNodes.map((n) => n.position.x)),
-          y: Math.min(...selectedNodes.map((n) => n.position.y))
-        };
+        const position = calculateInitialPosition(selectedNodes);
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dd6e95e and d82349f.

📒 Files selected for processing (1)
  • ui/src/lib/yjs/useYWorkflow.ts (2 hunks)
🔇 Additional comments (2)
ui/src/lib/yjs/useYWorkflow.ts (2)

44-53: LGTM! Good separation of concerns.

The updated signature improves function purity by accepting routers as a parameter instead of fetching them internally. This makes the function more testable and reusable.


122-156: LGTM! Verify undo/redo behavior.

Good job moving the async router fetching outside of undoTrackerActionWrapper. This should fix the undo/redo functionality for new workflows.

Let's verify that the undo/redo functionality works correctly with the new changes:

✅ Verification successful

Verified: Async operations correctly handled with undoTrackerActionWrapper

The fix is consistently implemented across the codebase. All async operations are performed before the undoTrackerActionWrapper, and only synchronous state updates are wrapped, ensuring proper undo/redo functionality.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for other instances of async operations within undoTrackerActionWrapper
# to ensure consistency with this fix.

echo "Checking for potential async operations within undoTrackerActionWrapper..."
rg -B 3 -A 3 "undoTrackerActionWrapper.*=.*async|undoTrackerActionWrapper.*=>.*async"

echo "Checking for await usage within undoTrackerActionWrapper..."
rg -B 3 -A 3 "undoTrackerActionWrapper.*\{.*await"

Length of output: 428


Script:

#!/bin/bash
# Find all usages of undoTrackerActionWrapper with context
echo "Finding all usages of undoTrackerActionWrapper..."
rg -B 5 -A 5 "undoTrackerActionWrapper"

# Also search for any async operations near undo-related code
echo -e "\nChecking for async operations near undo-related code..."
rg -B 5 -A 5 "undo.*async|async.*undo"

Length of output: 24915

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants