Deep Dive: Visual Graph Editor

The agent canvas editor is RAGFlow's flagship feature: a drag-drop interface for composing agent DSLs as directed graphs. Under the hood, it's powered by @xyflow/react (React Flow v12) with Zustand state management, real-time serialization to JSON, and node type registry for extensibility.

🎨 Canvas Architecture

Core Components

Canvas Container

src/pages/agent/index.tsx

Wraps @xyflow/react's ReactFlow provider. Initializes:

  • Node/edge types (registered in nodeTypes/edgeTypes)
  • Zustand store (graph state)
  • Event handlers (onNodesChange, onEdgesChange)
  • Keyboard shortcuts (delete, duplicate node)

Zustand Store

src/pages/agent/store.ts (21KB)

Single source of truth for:

  • nodes[] array + edges[] array
  • selectedNodes, selectedEdges
  • Viewport (zoom, pan)
  • Modal state (edit panel)
  • Undo/redo stack

Node Registry

src/components/canvas/NodeCard.tsx

Extensible node type system:

  • Map type → React component (Input, Output, LLM, Tool)
  • Each node has: inputs[], outputs[], config{}
  • Drag ports to create edges
  • Right-click context menu

Serialization

src/pages/agent/utils/

Convert between graph ↔ JSON DSL:

  • nodes[] + edges[] → JSON spec for backend
  • Backend JSON → nodes[] + edges[]
  • Validate graph (no cycles, required inputs)
  • Export/import formats (YAML, JSON)

🔄 User Interaction Flow

1. Load Agent

// User clicks agent in list
const handleSelectAgent = (agentId: string) => {
    const { data: agent } = useAgentDetail(agentId);
    // Deserialize JSON → nodes[] + edges[]
    const { nodes, edges } = parseAgentDSL(agent.dsl);
    store.setNodes(nodes);
    store.setEdges(edges);
};

2. Add Node

// Drag from toolbar or double-click canvas
const handleCanvasClick = (event, pos) => {
    const nodeId = generateId();
    const newNode = {
        id: nodeId,
        type: 'llm',  // LLM node
        position: pos,
        data: { label: 'GPT-4', model: 'gpt-4' }
    };
    store.addNode(newNode);
    store.selectNode(nodeId);  // Highlight for editing
};

3. Connect Nodes

// React Flow handles drag from output port → input port
const onConnect = (connection) => {
    const edge = {
        id: `${connection.source}-${connection.target}`,
        source: connection.source,
        target: connection.target,
        animated: true
    };
    store.addEdge(edge);
};

4. Edit Node Config

// Double-click node → open edit panel
const handleNodeClick = (e, node) => {
    store.selectNode(node.id);
    store.openEditPanel(node.id);  // Show form with node config
};

// Form submission
const handleUpdateNode = (config) => {
    store.updateNodeData(selectedNodeId, config);
    // Form uses RagFlow dynamic form builder
};

5. Save Agent

// Click save button
const handleSave = async () => {
    const { nodes, edges } = store.getState();
    
    // Validate
    if (!validateGraph(nodes, edges)) {
        toast.error('Invalid graph');
        return;
    }
    
    // Serialize to JSON DSL
    const dsl = serializeGraph(nodes, edges);
    
    // Send to backend
    agentMutation.mutate({
        id: agentId,
        dsl: JSON.stringify(dsl)
    });
};

📊 Graph Serialization Format

JSON DSL structure: Backend expects this format.

{
  "version": "1.0",
  "nodes": [
    {
      "id": "node-1",
      "type": "llm",
      "config": {
        "model": "gpt-4",
        "temperature": 0.7,
        "system_prompt": "You are a helpful assistant"
      }
    },
    {
      "id": "node-2",
      "type": "tool",
      "config": {
        "name": "search",
        "params": ["query"]
      }
    }
  ],
  "edges": [
    {
      "source": "node-1",
      "target": "node-2",
      "label": "execute"
    }
  ]
}

🛠️ Advanced Features

Undo/Redo

Zustand store maintains history stack:

store.addToHistory(currentState);
// Ctrl+Z to undo
// Ctrl+Shift+Z to redo

Node Validation

Each node has JSON schema defining required fields:

const llmNodeSchema = {
  type: 'object',
  required: ['model', 'system_prompt'],
  properties: {
    model: { type: 'string', enum: ['gpt-4', 'gpt-3.5', 'claude'] },
    temperature: { type: 'number', min: 0, max: 2 },
    system_prompt: { type: 'string', minLength: 1 }
  }
};

Dynamic Node Types

Node registry is extensible. Register custom nodes:

// In node registry
registerNodeType('custom-tool', {
  component: CustomToolNode,
  category: 'tools',
  description: 'Custom integration tool',
  schema: customToolSchema
});

Multi-Select & Group

Select multiple nodes with Ctrl+Click; drag to move group. React Flow handles bounding box calculation.

Minimap

Small viewport showing full graph in corner; drag minimap selection to pan main canvas.

⚡ Performance Considerations

🐛 Common Issues & Debugging

Issue Cause Debug Step
Nodes not rendering nodeTypes not registered Check nodeTypes object in Agent Canvas Canvas & Execution — Canvas & Execution" class="xref">Canvas.tsx
Edges disappear after save Serialization bug in edge format Log JSON DSL before sending to backend
Drag-drop not working React Flow wrapper CSS missing Ensure .react-flow has width/height
Node position off-screen Viewport not initialized Call fitView() after loading nodes

📚 Reference

Next Steps

{{TOPIC_NAME}}

Focus Deep-Dive

{{TOPIC_SUBTITLE}}

{{TOPIC_DESC}}

📚 What is this & why does it matter?

{{TOPIC_WHAT_WHY}} — Replace with 2-4 plain-English sentences explaining what this topic is and why a developer should understand it.

💡 Real-world analogy

{{TOPIC_ANALOGY}} — A vivid metaphor for this specific topic. 3-5 sentences.

❓ The Problem

{{THE_PROBLEM}} — 100+ words. What specific problem does this mechanism solve? What would happen without it? Paint a picture of the pain: "Without this, every request would..." or "The naive approach fails because..."

💡 The Approach

{{THE_APPROACH}} — 150+ words. How does this solution work, in narrative form? Walk through the key insight that makes the solution work. Don't just describe steps — explain WHY each step is necessary and what it contributes.

Contents

Overview

Primary role

Replace with the one-sentence job this mechanism performs inside the parent module.

Main inputs

Replace with the state, packets, structures, or conditions that feed this topic.

Key decisions

Replace with the most important branch or arbitration choices visible in the code.

Outputs / side effects

Replace with what changes after this mechanism runs: metadata, requests, counters, state, or responses.

flowchart TD
  A["Input / Trigger"] --> B["Phase 1"]
  B --> C["Phase 2"]
  C --> D["Phase 3"]
  D --> E["Output / Result"]

Replace with context-specific description of the overview diagram.

Decision Points

DecisionWhat controls itWhy it matters
Main branchCondition or mask from codeExplain how it changes the path or state
Fallback pathMiss / error / invalid state / resource pressureExplain the alternative behavior

How It Works

Detailed explanation of the mechanism, algorithm, or protocol. This is where the focus page adds value over the brief L2 mention. Anchor every paragraph to concrete symbols, tables, masks, counters, or states from the real code.

Phase/Step 1

Detailed explanation of the first phase. Include specific variable names, thresholds, or conditions from the source code.

// Replace with actual code from the source
void step1_example() {
    // ...
}
Key detail: Explain a non-obvious implementation detail visible in the code above.

Phase/Step 2

Continue with subsequent phases...

Behavior Diagram

stateDiagram-v2
    [*] --> Idle
    Idle --> Active : trigger
    Active --> Processing : start
    Processing --> Done : complete
    Processing --> Error : fail
    Error --> Idle : reset
    Done --> Idle : next

Replace with description of state transitions or message sequences specific to this topic.

Writing target: this section should explain dynamic behavior that a reader would otherwise have to reconstruct by reading several functions side by side.

Annotated Code Walkthrough

Walk through the actual source code step by step, with explanations between each snippet.

First, the entry point receives the input and validates it:

// Replace with real code snippet from source
void entry_point(Input& input) {
    if (!validate(input)) return;
    // ...
}

Then the core processing happens here — note the key decision point:

// Next real code snippet
Result process(Input& input) {
    // The critical branch:
    if (input.type == FAST_PATH) {
        return fast_process(input);
    }
    return slow_process(input);
}
Performance note: The fast path avoids X overhead. The slow path is taken in ~Y% of cases.

Edge Cases & Error Handling

ScenarioBehaviorCode Location
Edge case 1What happensfile.cc:123
Edge case 2What happensfile.cc:456

🔄 Why Not Alternatives?

Understanding why the current approach was chosen requires seeing what was rejected:

AlternativeHow It WorksWhy It Was RejectedWhen It Would Be Better
Alternative ABrief descriptionSpecific reason: performance, complexity, correctnessUnder what conditions this would actually be the right choice
Alternative BBrief descriptionSpecific reasonWhen it would win

⚖️ Complexity & Tradeoffs

What This Approach Costs

DimensionCostBenefit
Time complexityO(?)What this buys
Space complexityO(?)What this enables
Code complexityLines / indirectionWhat this simplifies elsewhere
Maintenance burdenWhat's hard to changeWhat's easy to extend

The honest truth: {{HONEST_ASSESSMENT}} — 50+ words. Where does this approach struggle? What would you change with unlimited time? What technical debt exists?

🚨 Failure Recovery

Failure ScenarioDetectionRecovery StrategyData Loss Risk
Crash mid-operationHow detectedHow the system recovers🟢 None / 🔴 Possible
Invalid inputValidation checkError path🟢 None

Configuration

Knob / ParameterDefaultDescription
param_1valueWhat it controls and how it affects this topic
param_2valueDescription

See also:

Directory Map

Source files for this topic
submod_name/
├── relevant_file_a.ext        ← Role: brief annotation
├── relevant_file_b.ext        ← Role: brief annotation
└── relevant_file_c.ext        ← Role: brief annotation