Skip to content

Improve the mermaid output in CLI - #1174

Merged
isamu merged 2 commits into
receptron:mainfrom
kawamataryo:improve-mermaid
Jul 24, 2025
Merged

isamu merged 2 commits into
receptron:mainfrom
kawamataryo:improve-mermaid

Conversation

@kawamataryo

@kawamataryo kawamataryo commented Jul 24, 2025 •

Copy link
Copy Markdown
Contributor

I have improved the Mermaid output in the CLI, updating it to display agent names and support nested graphs.

$ node lib/graphai_cli.js test_yaml/map1.yaml -m
flowchart TD
  n_source1(source1)
  n_source2(source2)
  n_source3(source3)
  n_source4(source4)
  subgraph n_nestedNode[nestedNode: mapAgent]
    n_nestedNode_node2(node2<br/>stringTemplateAgent)
  end
  n_source1 -- fruit --> n_nestedNode
  n_source2 -- fruit --> n_nestedNode
  n_source3 -- fruit --> n_nestedNode
  n_source4 -- fruit --> n_nestedNode
  n_result(result<br/>sleeperAgent)
  n_nestedNode --> n_result
  class n_source1,n_source2,n_source3,n_source4 staticNode
  class n_nestedNode_node2,n_result computedNode
  class n_nestedNode nestedGraph
CleanShot 2025-07-24 at 21 13 33@2x

Summary by CodeRabbit

  • New Features
    • Enhanced Mermaid diagram generation with improved hierarchical support, allowing for nested subgraphs and clearer node classification.
  • Refactor
    • Reworked the internal logic for Mermaid diagram creation to provide more organized and readable output.
  • Tests
    • Added comprehensive tests to ensure accurate Mermaid diagram generation for various graph structures.
  • Chores
    • Updated CLI test script to include a new sample for Mermaid diagram generation.

@coderabbitai

coderabbitai Bot commented Jul 24, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

The changes refactor the Mermaid diagram generation logic for graph structures in the CLI package, introducing recursive processing and hierarchical state accumulation. Node classification, subgraph support, and output formatting are improved. A comprehensive test suite is added for the new logic, and a test shell script is updated to include a new test case.

Changes

File(s) Change Summary
packages/cli/lib/mermaid.d.ts Refactored import to use import { type GraphData } syntax; no changes to exported declarations.
packages/cli/lib/mermaid.js Rewrote Mermaid graph generation: now recursively processes nodes, supports subgraphs, and accumulates output before printing.
packages/cli/src/mermaid.ts Major refactor: introduced recursive node processing, stateful Mermaid syntax construction, node classification, and improved output formatting.
packages/cli/tests/test_mermaid.ts Added new test suite for mermaid function, covering various graph structures and validating output.
packages/cli/scripts/test.sh Added a new CLI command invocation for test_yaml/map1.yml -m to the test shell script.

Sequence Diagram(s)

sequenceDiagram
    participant CLI_User
    participant CLI
    participant mermaid.ts
    participant Console

    CLI_User->>CLI: Run CLI with -m option and YAML file
    CLI->>mermaid.ts: Call mermaid(graphData)
    mermaid.ts->>mermaid.ts: Recursively process nodes and subgraphs
    mermaid.ts->>mermaid.ts: Accumulate Mermaid syntax lines and node classes
    mermaid.ts->>Console: Output final Mermaid diagram as a single string
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~18 minutes

Poem

A graph of nodes, both deep and wide,
Now drawn with care and nested pride.
Subgraphs bloom in Mermaid’s flow,
Agents and statics in neat rows.
With tests to check each branch and leaf,
The rabbit hops in code relief!
🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

packages/cli/lib/mermaid.d.ts

Oops! Something went wrong! :(

ESLint: 9.31.0

ESLint couldn't find an eslint.config.(js|mjs|cjs) file.

From ESLint v9.0.0, the default configuration file is now eslint.config.js.
If you are using a .eslintrc.* file, please follow the migration guide
to update your configuration file to the new format:

https://eslint.org/docs/latest/use/configure/migration-guide

If you still have problems after following the migration guide, please stop by
https://eslint.org/chat/help to chat with the team.

packages/cli/src/mermaid.ts

Oops! Something went wrong! :(

ESLint: 9.31.0

ESLint couldn't find an eslint.config.(js|mjs|cjs) file.

From ESLint v9.0.0, the default configuration file is now eslint.config.js.
If you are using a .eslintrc.* file, please follow the migration guide
to update your configuration file to the new format:

https://eslint.org/docs/latest/use/configure/migration-guide

If you still have problems after following the migration guide, please stop by
https://eslint.org/chat/help to chat with the team.

packages/cli/lib/mermaid.js

Oops! Something went wrong! :(

ESLint: 9.31.0

ESLint couldn't find an eslint.config.(js|mjs|cjs) file.

From ESLint v9.0.0, the default configuration file is now eslint.config.js.
If you are using a .eslintrc.* file, please follow the migration guide
to update your configuration file to the new format:

https://eslint.org/docs/latest/use/configure/migration-guide

If you still have problems after following the migration guide, please stop by
https://eslint.org/chat/help to chat with the team.

  • 1 others

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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 generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@kawamataryo
kawamataryo marked this pull request as ready for review July 24, 2025 12:14
@kawamataryo kawamataryo changed the title Improve mermaid output Improve mermaid output in CLI Jul 24, 2025
@kawamataryo kawamataryo changed the title Improve mermaid output in CLI Improve the mermaid output in CLI Jul 24, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (7)
packages/cli/tests/test_mermaid.ts (3)

6-17: Consider test isolation for console.log mocking

The current implementation modifies the global console.log, which could cause issues if tests run in parallel. Consider using a more isolated approach or ensure tests run sequentially.


19-23: Enhance assertion messages for better debugging

When assertions fail, it would be helpful to show the actual output for easier debugging.

-const assertOutputContains = (output: string, expectedStrings: string[]): void => {
-  expectedStrings.forEach(expected => {
-    assert(output.includes(expected), `Expected output to contain: "${expected}"`);
-  });
-};
+const assertOutputContains = (output: string, expectedStrings: string[]): void => {
+  expectedStrings.forEach(expected => {
+    assert(output.includes(expected), 
+      `Expected output to contain: "${expected}"\nActual output:\n${output}`);
+  });
+};

1-202: Consider adding edge case tests

The test suite covers happy path scenarios well, but consider adding tests for edge cases such as:

  • Malformed graph data
  • Circular dependencies
  • Invalid node references
  • Nodes with special characters that might need escaping
packages/cli/lib/mermaid.js (2)

18-35: Consider adding type safety for inputs parameter

The processConnections function accepts inputs as any, which bypasses type checking. Since this is generated from TypeScript, ensure the source file uses proper typing.


41-41: Handle empty agent names in subgraph labels

When node.agent is falsy, the subgraph label shows a trailing colon (e.g., "nodeId: "). Consider omitting the colon when there's no agent.

-        state.lines.push(formatLine(`subgraph ${mermaidNodeId}[${nodeId}: ${node.agent || ""}]`, depth));
+        const agentLabel = node.agent ? `: ${node.agent}` : "";
+        state.lines.push(formatLine(`subgraph ${mermaidNodeId}[${nodeId}${agentLabel}]`, depth));
packages/cli/src/mermaid.ts (2)

56-56: Improve empty agent name handling in subgraph labels

Similar to the JavaScript file, consider cleaner handling of empty agent names.

-    state.lines.push(formatLine(`subgraph ${mermaidNodeId}[${nodeId}: ${node.agent || ""}]`, depth));
+    const agentLabel = node.agent ? `: ${node.agent}` : "";
+    state.lines.push(formatLine(`subgraph ${mermaidNodeId}[${nodeId}${agentLabel}]`, depth));

12-14: Consider additional sanitization for Mermaid special characters

The current sanitization only handles dots, but Mermaid diagrams may have issues with other special characters like quotes, brackets, or parentheses in node IDs.

 const sanitizeNodeId = (nodeId: string): string => {
-  return `n_${nodeId.replace(/\./g, "_")}`;
+  return `n_${nodeId.replace(/[.\-\[\]()'"]/g, "_")}`;
 };
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fb874dd and 58db83e.

📒 Files selected for processing (5)
  • packages/cli/lib/mermaid.d.ts (1 hunks)
  • packages/cli/lib/mermaid.js (1 hunks)
  • packages/cli/scripts/test.sh (1 hunks)
  • packages/cli/src/mermaid.ts (1 hunks)
  • packages/cli/tests/test_mermaid.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build (22.x)
🔇 Additional comments (1)
packages/cli/lib/mermaid.d.ts (1)

1-1: Good use of type-only import syntax

Using import { type GraphData } clearly indicates this is a type-only import, which is a TypeScript best practice that helps with bundling and prevents potential runtime errors.

Comment on lines +76 to 88
const mermaid = (graphData) => {
const state = {
lines: ["flowchart TD"],
staticNodes: [],
computedNodes: [],
nestedGraphNodes: [],
};
Object.entries(graphData.nodes).forEach(([nodeId, node]) => {
processNode(nodeId, node, "", state);
});
addNodeClasses(state);
console.log(state.lines.join("\n"));
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add input validation for graphData

The function assumes graphData.nodes exists and is iterable. Consider adding validation to handle malformed input gracefully.

 const mermaid = (graphData) => {
+    if (!graphData || !graphData.nodes || typeof graphData.nodes !== 'object') {
+        console.log("flowchart TD");
+        return;
+    }
     const state = {
         lines: ["flowchart TD"],
         staticNodes: [],
         computedNodes: [],
         nestedGraphNodes: [],
     };
     Object.entries(graphData.nodes).forEach(([nodeId, node]) => {
         processNode(nodeId, node, "", state);
     });
     addNodeClasses(state);
     console.log(state.lines.join("\n"));
 };
📝 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 mermaid = (graphData) => {
const state = {
lines: ["flowchart TD"],
staticNodes: [],
computedNodes: [],
nestedGraphNodes: [],
};
Object.entries(graphData.nodes).forEach(([nodeId, node]) => {
processNode(nodeId, node, "", state);
});
addNodeClasses(state);
console.log(state.lines.join("\n"));
};
const mermaid = (graphData) => {
if (!graphData || !graphData.nodes || typeof graphData.nodes !== 'object') {
console.log("flowchart TD");
return;
}
const state = {
lines: ["flowchart TD"],
staticNodes: [],
computedNodes: [],
nestedGraphNodes: [],
};
Object.entries(graphData.nodes).forEach(([nodeId, node]) => {
processNode(nodeId, node, "", state);
});
addNodeClasses(state);
console.log(state.lines.join("\n"));
};
🤖 Prompt for AI Agents
In packages/cli/lib/mermaid.js around lines 76 to 88, the function mermaid
assumes graphData.nodes exists and is iterable, which can cause errors if the
input is malformed. Add input validation at the start of the function to check
if graphData and graphData.nodes are defined and that graphData.nodes is an
object or iterable. If the validation fails, handle it gracefully by either
returning early or throwing a clear error message.

node lib/graphai_cli.js test_yaml/map1.yaml
node lib/graphai_cli.js test_yaml/test_base.yml
node lib/graphai_cli.js test_yaml/test_base.yml -v
node lib/graphai_cli.js test_yaml/map1.yml -m

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify file extension consistency

The test uses test_yaml/map1.yml while line 5 references test_yaml/map1.yaml. Please verify if both files exist or if this is a typo.


🏁 Script executed:

#!/bin/bash
# Check if both map1.yaml and map1.yml files exist
fd -t f "^map1\.(yaml|yml)$" test_yaml/

Length of output: 139


🏁 Script executed:

#!/bin/bash
# Search for any files named map1.yaml or map1.yml in the repository
fd -t f '^map1\.yaml$'
fd -t f '^map1\.yml$'

Length of output: 81


Fix the file extension in the test script

Only map1.yaml exists under packages/cli/test_yaml/, so the reference to .yml is a typo. Please update the script accordingly.

• File: packages/cli/scripts/test.sh
Line: 8
Change:

- node lib/graphai_cli.js test_yaml/map1.yml -m
+ node lib/graphai_cli.js test_yaml/map1.yaml -m
🤖 Prompt for AI Agents
In packages/cli/scripts/test.sh at line 8, the script references a file with the
extension .yml, but the correct file extension is .yaml. Update the file path in
the command from test_yaml/map1.yml to test_yaml/map1.yaml to match the existing
file.

return BASE_INDENT + BASE_INDENT.repeat(depth) + content;
};

const processConnections = (inputs: any, targetNodeId: string, parentPath: string, state: MermaidState): void => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Replace any types with proper TypeScript types

Using any defeats the purpose of TypeScript's type safety. Consider defining proper types for inputs and node parameters.

// Add these type definitions at the top of the file
type NodeInputs = Record<string, unknown> | unknown;
type GraphNode = {
  agent?: string;
  graph?: GraphData;
  inputs?: NodeInputs;
  update?: unknown;
  value?: unknown;
};

// Then update the function signatures:
// Line 28:
const processConnections = (inputs: NodeInputs, targetNodeId: string, parentPath: string, state: MermaidState): void => {

// Line 50:
const processNode = (nodeId: string, node: GraphNode, parentPath: string, state: MermaidState): void => {

Also applies to: 50-50

🤖 Prompt for AI Agents
In packages/cli/src/mermaid.ts at lines 28 and 50, replace the use of `any`
types for the `inputs` and `node` parameters with proper TypeScript types to
improve type safety. Define the types `NodeInputs` as `Record<string, unknown> |
unknown` and `GraphNode` as an object with optional properties `agent`, `graph`,
`inputs`, `update`, and `value`. Then update the function signatures of
`processConnections` and `processNode` to use these types instead of `any`.

Comment on lines +95 to 110
export const mermaid = (graphData: GraphData): void => {
const state: MermaidState = {
lines: ["flowchart TD"],
staticNodes: [],
computedNodes: [],
nestedGraphNodes: [],
};

Object.entries(graphData.nodes).forEach(([nodeId, node]) => {
processNode(nodeId, node, "", state);
});

addNodeClasses(state);

console.log(state.lines.join("\n"));
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add input validation and error handling

The function should validate the input structure to handle edge cases gracefully.

 export const mermaid = (graphData: GraphData): void => {
+  if (!graphData?.nodes || typeof graphData.nodes !== 'object') {
+    console.log("flowchart TD");
+    return;
+  }
+
   const state: MermaidState = {
     lines: ["flowchart TD"],
     staticNodes: [],
     computedNodes: [],
     nestedGraphNodes: [],
   };

   Object.entries(graphData.nodes).forEach(([nodeId, node]) => {
-    processNode(nodeId, node, "", state);
+    if (node && typeof node === 'object') {
+      processNode(nodeId, node, "", state);
+    }
   });

   addNodeClasses(state);

   console.log(state.lines.join("\n"));
 };
📝 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 const mermaid = (graphData: GraphData): void => {
const state: MermaidState = {
lines: ["flowchart TD"],
staticNodes: [],
computedNodes: [],
nestedGraphNodes: [],
};
Object.entries(graphData.nodes).forEach(([nodeId, node]) => {
processNode(nodeId, node, "", state);
});
addNodeClasses(state);
console.log(state.lines.join("\n"));
};
export const mermaid = (graphData: GraphData): void => {
if (!graphData?.nodes || typeof graphData.nodes !== 'object') {
console.log("flowchart TD");
return;
}
const state: MermaidState = {
lines: ["flowchart TD"],
staticNodes: [],
computedNodes: [],
nestedGraphNodes: [],
};
Object.entries(graphData.nodes).forEach(([nodeId, node]) => {
if (node && typeof node === 'object') {
processNode(nodeId, node, "", state);
}
});
addNodeClasses(state);
console.log(state.lines.join("\n"));
};
🤖 Prompt for AI Agents
In packages/cli/src/mermaid.ts around lines 95 to 110, the mermaid function
lacks input validation and error handling for the graphData parameter. Add
checks to ensure graphData and its nodes property exist and are of the expected
types before processing. If validation fails, handle the error gracefully by
logging an informative message or throwing an error to prevent runtime
exceptions.

@isamu
isamu merged commit 7d55f71 into receptron:main Jul 24, 2025
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