Repository navigation
Improve the mermaid output in CLI - #1174
Conversation
WalkthroughThe 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
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~18 minutes Poem
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
packages/cli/lib/mermaid.d.tsOops! 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 still have problems after following the migration guide, please stop by packages/cli/src/mermaid.tsOops! 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 still have problems after following the migration guide, please stop by packages/cli/lib/mermaid.jsOops! 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 still have problems after following the migration guide, please stop by
Note ⚡️ Unit Test Generation is now available in beta!Learn more here, or try it out under "Finishing Touches" below. ✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (7)
packages/cli/tests/test_mermaid.ts (3)
6-17: Consider test isolation for console.log mockingThe 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 debuggingWhen 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 testsThe 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 parameterThe
processConnectionsfunction acceptsinputsasany, 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 labelsWhen
node.agentis 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 labelsSimilar 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 charactersThe 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
📒 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 syntaxUsing
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.
| 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")); | ||
| }; |
There was a problem hiding this comment.
🛠️ 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.
| 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 |
There was a problem hiding this comment.
💡 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 => { |
There was a problem hiding this comment.
🛠️ 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`.
| 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")); | ||
| }; |
There was a problem hiding this comment.
🛠️ 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.
| 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.
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 nestedGraphSummary by CodeRabbit