use-save-graph.ts
Overview
The use-save-graph.ts file provides a set of React hooks designed to manage the saving and state synchronization of a graph-based flow or agent configuration within an application. It primarily handles saving the current state of a flow graph to a backend service, resetting the agent before debugging, and automatically persisting changes with debounced effects. These hooks encapsulate complex interactions with APIs and global state stores, ensuring a smooth user experience when editing, saving, and running graph-based agents.
Detailed Explanation of Exports
1. useSaveGraph(showMessage: boolean = true)
Purpose
A custom React hook to save the current graph (agent flow) state to the backend.
Parameters
showMessage(optional,boolean): Defaults totrue. Controls whether user feedback messages (e.g., success or error notifications) should be displayed during the save operation.
Returns
An object containing:
saveGraph:asyncfunction that saves the graph.loading:booleanindicating if the save operation is in progress.
Usage
const { saveGraph, loading } = useSaveGraph();
async function onSave() {
await saveGraph();
}
Description
Fetches the current agent data via
useFetchAgent.Uses
useSetAgentto perform the save operation.Retrieves the current agent ID from URL parameters (
useParams).Builds a DSL (Domain Specific Language) representation of the graph via
useBuildDslData.The
saveGraphfunction accepts an optional list of nodes (RAGFlowNodeType[]) to override the current nodes during save.Calls
setAgentwith an object containing:id: agent identifiertitle: agent title from current datadsl: generated DSL from the graph data
2. useSaveGraphBeforeOpeningDebugDrawer(show: () => void)
Purpose
A React hook to save the graph and reset the agent before opening a debug drawer (a UI panel for debugging).
Parameters
show: a callback function that opens the debug drawer UI.
Returns
An object containing:
handleRun: an async function that saves the graph, resets the agent, and then triggers the debug drawer to open.loading: boolean indicating if saving or resetting is in progress.
Usage
const { handleRun, loading } = useSaveGraphBeforeOpeningDebugDrawer(() => openDebugDrawer());
<button onClick={() => handleRun()}>Run Debug</button>
Description
Internally uses
useSaveGraphto save the current graph.Uses
useResetAgentto reset the agent state on the backend.handleRunperforms these steps sequentially:Save the current graph.
If save succeeds (
code === 0), reset the agent.If reset succeeds (
code === 0), calls theshowcallback to open the debug drawer.
Ensures the agent is in a clean state before debugging runs.
3. useWatchAgentChange(chatDrawerVisible: boolean)
Purpose
Monitors changes in the graph's nodes and edges, automatically saves the agent after a debounce delay when changes occur, and tracks the last save timestamp.
Parameters
chatDrawerVisible:booleanindicating whether the chat or debug drawer is currently visible. Saves are skipped when the drawer is open.
Returns
The last saved time as a formatted string (
string | undefined).
Usage
const lastSavedTime = useWatchAgentChange(chatDrawerVisible);
return <div>Last saved at: {lastSavedTime}</div>
Description
Uses global graph state (
useGraphStore) to watchnodesandedges.Uses
useFetchAgentto get current agent details, including last update time.Uses
useSaveGraphinternally but disables showing messages (showMessage = false).Stores last save time in local state and formats it using
formatDate.Saves the agent asynchronously only if the chat drawer is not visible.
Uses
useDebounceEffectfromahooksto debounce save calls, only saving 20 seconds after the last change to nodes or edges.Updates the last save time upon successful save.
Important Implementation Details and Algorithms
Debounced Auto-Saving:
TheuseWatchAgentChangehook uses a debounced effect to avoid excessive save calls during rapid graph edits. It waits for 20 seconds of inactivity before triggering a save, optimizing network and backend usage.Sequential Async Workflow in
handleRun:
The run handler ensures the agent is first saved, then reset, and only after both succeed is the debug drawer shown. This sequential process guarantees a consistent agent state during debugging.DSL Building:
The graph is converted to a DSL (Domain Specific Language) format before saving, usinguseBuildDslData. This abstraction allows the backend to process the flow graph consistently.State Management:
The hooks rely on global state management (useGraphStore) for graph data and agent fetching/updating hooks (useFetchAgent,useSetAgent,useResetAgent) to interact with the backend.
Interaction with Other Parts of the System
Backend API:
useFetchAgent: Fetches agent data from the server.useSetAgent: Sends updates to persist agent data.useResetAgent: Resets the agent's runtime state.
Routing:
UsesuseParamsfromumito extract the agent ID from the URL, linking the saved graph to the correct agent.Graph Store:
UsesuseGraphStoreto read the current graph nodes and edges, reflecting the user's current editing state.DSL Builder:
useBuildDslDataconverts the current graph nodes into a DSL representation expected by the backend API.UI Components:
The save and reset hooks are likely used by UI components such as editors and debug drawers that manage the flow graph and show debugging information.
Visual Diagram
flowchart TD
A[useSaveGraph] -->|calls| B[useFetchAgent]
A -->|calls| C[useSetAgent]
A -->|calls| D[useBuildDslData]
A -->|uses| E[useParams]
F[useSaveGraphBeforeOpeningDebugDrawer] -->|calls| A
F -->|calls| G[useResetAgent]
F -->|executes| H[show() callback]
I[useWatchAgentChange] -->|reads| J[useGraphStore (nodes, edges)]
I -->|calls| A
I -->|calls| B
I -->|uses| K[formatDate]
I -->|uses| L[useDebounceEffect]
style A fill:#f9f,stroke:#333,stroke-width:1px
style F fill:#bbf,stroke:#333,stroke-width:1px
style I fill:#bfb,stroke:#333,stroke-width:1px
Legend:
Pink:
useSaveGraphcore saving logic.Blue:
useSaveGraphBeforeOpeningDebugDrawerhandles save + reset + debug drawer opening.Green:
useWatchAgentChangemonitors changes and auto-saves.
Summary
This file is a utility layer that abstracts the complexity of saving and synchronizing the graph-based agent flows with backend persistence and UI workflows. It provides reusable hooks for saving the graph, preparing the agent for debugging, and automatically persisting changes with debouncing, thereby enhancing developer productivity and user experience in flow-based agent editing applications.