use-save-graph.ts
Overview
The use-save-graph.ts file provides React hooks to manage the persistence and state synchronization of a flow graph within an agent-based application. It primarily handles saving the graph's data structure (nodes and edges) to a backend, resetting the agent state before running debug sessions, and automatically saving updates to the graph with debouncing.
This file integrates several custom hooks and utilities to facilitate:
Saving the current graph state to persistent storage.
Resetting the agent environment before debugging.
Watching for changes in the graph and saving them with a delay to reduce excessive network calls.
Managing loading states and update timestamps for user feedback.
Detailed Explanation of Exports
1. useSaveGraph
Purpose
Provides a hook that returns a saveGraph function to save the current graph state to the backend, along with a loading status indicating if the save operation is in progress.
Signature
useSaveGraph(showMessage?: boolean): { saveGraph: (currentNodes?: RAGFlowNodeType[]) => Promise<any>, loading: boolean }
Parameters
showMessage(optional, boolean): Controls whether to show messages (e.g., success or error notifications) during the save operation. Defaults totrue.
Returns
saveGraph: An async function that accepts an optional list of nodes (RAGFlowNodeType[]) and persists the graph data.loading: A boolean indicating if the save operation is currently running.
Behavior
Uses
useFetchAgentto obtain the current agent data.Uses
useSetAgentto persist changes.Uses
useParamsto get the current agentidfrom the URL.Uses
useBuildDslDatato convert the nodes into a DSL (Domain Specific Language) format before saving.
Usage Example
const { saveGraph, loading } = useSaveGraph();
const onSaveClick = async () => {
await saveGraph(currentNodes);
};
2. useSaveGraphBeforeOpeningDebugDrawer
Purpose
Provides a hook that returns a handleRun function which first saves the graph, then resets the agent state, and finally triggers the opening of a debug drawer UI upon successful operations.
Signature
useSaveGraphBeforeOpeningDebugDrawer(show: () => void): { handleRun: (nextNodes?: RAGFlowNodeType[]) => Promise<void>, loading: boolean }
Parameters
show: A callback function to display the debug drawer UI after saving and resetting are successful.
Returns
handleRun: An async function that saves the graph, resets the agent, and callsshow.loading: A boolean indicating if the save operation is currently running (inherited fromuseSaveGraph).
Behavior
Relies on
useSaveGraphto save the graph.Calls
useResetAgentto reset the agent state before debugging.Ensures the debug drawer only opens if both saving and resetting succeed (response code 0).
Usage Example
const { handleRun, loading } = useSaveGraphBeforeOpeningDebugDrawer(() => setShowDebugDrawer(true));
<Button onClick={() => handleRun()}>Run Debug</Button>
3. useWatchAgentChange
Purpose
A hook that monitors changes to the graph's nodes and edges, automatically saving the agent after 20 seconds of inactivity (debounced). It also tracks and provides the last save time formatted for display.
Signature
useWatchAgentChange(chatDrawerVisible: boolean): string | undefined
Parameters
chatDrawerVisible(boolean): Indicates if a chat drawer UI is currently visible. Auto-save only triggers when this is false to avoid conflicts.
Returns
time: A formatted string representing the last save time, orundefinedif no save has occurred yet.
Behavior
Fetches current nodes and edges from
useGraphStore.Uses
useSaveGraphwithout showing messages (showMessage = false).Uses
useFetchAgentto get the last update time.Updates the save time state upon successful save.
Uses
useDebounceEffectto debounce the save operation by 20 seconds after the last change to nodes or edges.Skips saving if the chat drawer is visible.
Usage Example
const lastSaveTime = useWatchAgentChange(chatDrawerVisible);
return <div>Last saved at: {lastSaveTime || 'never saved'}</div>;
Implementation Details
Debouncing Saves:
TheuseWatchAgentChangehook applies a 20-second debounce to avoid excessive saves when the graph is being actively edited. This improves performance and reduces backend load.DSL Data Building:
ThebuildDslDatafunction (fromuseBuildDslData) is used to convert the graph nodes into a DSL format that the backend expects for storage.Agent Reset Before Debug:
Before opening the debug drawer, the agent is reset by calling the reset API to clear previous session messages, ensuring a clean debug environment.Loading States:
Loading flags fromuseSetAgentprovide UI feedback during asynchronous save operations.
Interaction with Other Parts of the System
Hooks Imported:
useFetchAgent,useSetAgent,useResetAgent— API interaction hooks managing agent data fetch, save, and reset operations.useBuildDslData— Converts graph nodes into DSL data format for saving.useGraphStore— Provides access to global graph state (nodesandedges).
Utilities:
formatDate— Formats timestamps for the last save time display.useDebounceEffect(fromahooks) — Debounces the auto-save operation.
Routing:
useParams(fromumi) — Retrieves the agent id from the current URL parameters.
This file acts as the glue between the UI graph representation, agent backend APIs, and user interaction flows (saving, debugging).
Visual Diagram
flowchart TD
subgraph SaveGraphHook[useSaveGraph]
SG1[useFetchAgent: fetch agent data]
SG2[useSetAgent: save agent data]
SG3[useParams: get agent id]
SG4[useBuildDslData: build DSL from nodes]
saveGraph[saveGraph(currentNodes?)]
saveGraph --> SG4
saveGraph --> SG2
saveGraph --> SG1
saveGraph --> SG3
end
subgraph SaveGraphBeforeDebug[useSaveGraphBeforeOpeningDebugDrawer]
SGBD1[useSaveGraph]
SGBD2[useResetAgent: reset agent]
handleRun[handleRun(nextNodes?)]
handleRun --> SGBD1.saveGraph
handleRun --> SGBD2.resetAgent
handleRun --> show[show debug drawer]
end
subgraph WatchAgentChange[useWatchAgentChange]
WAC1[useGraphStore: nodes, edges]
WAC2[useSaveGraph(showMessage=false)]
WAC3[useFetchAgent: fetch flow detail]
WAC4[useDebounceEffect(20s)]
saveAgent[saveAgent()]
setSaveTime[setSaveTime(formatted time)]
saveAgent --> WAC2.saveGraph
saveAgent --> setSaveTime
WAC4 --> saveAgent
useEffectUpdateTime[update time on flowDetail change]
useEffectUpdateTime --> setSaveTime
end
SaveGraphHook --> SaveGraphBeforeDebug
SaveGraphHook --> WatchAgentChange
Summary
use-save-graph.ts provides essential React hooks for saving and managing the state of an agent flow graph. It handles asynchronous save operations, integrates with backend agent APIs, and supports user workflows including debugging and automatic saving with debouncing. This file is central to synchronizing the frontend graph state with persistent backend storage and ensuring a smooth user experience during graph editing and debugging.