flow-hooks.ts
Overview
The flow-hooks.ts file provides a comprehensive set of custom React hooks primarily leveraging the React Query library for managing asynchronous data fetching and mutations related to "flows" within the application. These hooks interface with the backend through the flowService API client to perform CRUD operations, fetch flow templates, versions, and details, run flows, reset flows, test database connections, and debug individual flow components.
This file abstracts and encapsulates the complexities of data fetching, caching, and state management, enabling React components to easily consume flow-related data and perform mutations with built-in loading states and error handling via UI feedback (using Ant Design's message component).
Detailed Explanation of Exports (Hooks and Constants)
Constants
EmptyDsl
Type:
DSLDescription:
Represents a default empty flow DSL (Domain Specific Language) structure used as a template for new flows.
It contains a single "begin" node with no edges and no messages, references, history, or answers.Structure Details:
graph: Defines nodes and edges of the flow graph.Contains one node with:
id: Identifier set to BeginId (imported constant).type:'beginNode'.position: Coordinates{ x: 50, y: 200 }.data: Label and name of the node.sourcePosition and
targetPosition: Indicate connection points.
components: Contains component definitions keyed by node ids.The "begin" component includes:
component_name:'Begin'.params: empty object.downstream: Array with a single string'Answer:China'(indicating downstream nodes).upstream: Empty array.
Other fields:
messages,reference,history,path, and answer initialized as empty arrays.
Hooks
Note on React Query usage:
Most hooks useuseQueryfor fetching data anduseMutationfor performing POST/PUT/DELETE operations. They provide loading states, data results, and mutation functions while managing cache invalidations and UI notifications.
useFetchFlowTemplates
Purpose: Fetches a list of available flow templates.
Returns: ResponseType<IFlowTemplate[]> - an array of flow templates.
Details:
Uses
useQuerywith key['fetchFlowTemplates'].Calls flowService.listTemplates() to get templates.
Prepends a "blank" template (
EmptyDsl) to the list with localized title and description usingreact-i18next.
Usage Example:
const templates = useFetchFlowTemplates(); console.log(templates); // Array of flow templates including a blank template.
useFetchFlowList
Purpose: Fetches the list of all flows (canvases).
Returns:
{ data: IFlow[]; loading: boolean }Details:
Uses
useQuerywith key['fetchFlowList'].Calls
flowService.listCanvas()to get the flow list.Provides loading state and the data array.
Usage Example:
const { data, loading } = useFetchFlowList(); if (!loading) { // Render flow list }
useFetchListVersion
Purpose: Fetches all versions for a specified flow canvas.
Parameters:
canvas_id: string- ID of the flow canvas.
Returns:
data: Array of versions with{ created_at, title, id }.loading: boolean.
Details:
Uses
useQuerywith key['fetchListVersion'].Calls
flowService.getListVersion({}, canvas_id)to fetch versions.
Usage Example:
const { data: versions, loading } = useFetchListVersion("canvas-123");
useFetchVersion
Purpose: Fetches a specific version of a flow by version ID.
Parameters:
version_id?: string- Optional version ID.
Returns:
data?: IFlow- The flow version data or undefined if no version_id.loading: boolean.
Details:
Query enabled only if
version_idis provided.Calls
flowService.getVersion({}, version_id).
Usage Example:
const { data: version, loading } = useFetchVersion("version-abc");
useFetchFlow
Purpose: Fetches detailed flow (canvas) data for the current route or shared chat.
Returns:
data: IFlowloading: booleanrefetch: function to refetch data manually.
Details:
Uses
useParamsto get flowidfrom URL.Uses
useGetSharedChatSearchParamsto check for sharedId.Calls
flowService.getCanvas({}, sharedId || id).Processes messages in the DSL by adding UUIDs with
buildMessageListWithUuid.
Usage Example:
const { data: flow, loading, refetch } = useFetchFlow();
useSettingFlow
Purpose: Mutation hook to update flow canvas settings.
Returns:
data: mutation response data.loading: boolean.settingFlow: async mutation function.
Details:
Calls
flowService.settingCanvas(params).Shows success or error message on mutation result.
Usage Example:
const { settingFlow, loading } = useSettingFlow(); settingFlow({ id: '123', title: 'Updated Title' });
useFetchFlowSSE
Purpose: Fetches flow data using Server-Sent Events (SSE) for live updates.
Returns:
data: IFlowloading: booleanrefetch: function to manually refetch.
Details:
Uses sharedId from
useGetSharedChatSearchParams.Calls
flowService.getCanvasSSE({}, sharedId).Processes messages in DSL with UUIDs.
Usage Example:
const { data, loading, refetch } = useFetchFlowSSE();
useSetFlow
Purpose: Mutation hook to create or update a flow canvas.
Returns:
data: mutation response data.loading: boolean.setFlow: async mutation function.
Parameters for mutation:
{ id?: string; title?: string; dsl?: DSL; avatar?: string }
Details:
Calls
flowService.setCanvas(params).Shows success message based on create or update.
Invalidates
fetchFlowListquery to refresh flow list cache.
Usage Example:
const { setFlow } = useSetFlow(); setFlow({ title: "New Flow", dsl: EmptyDsl });
useDeleteFlow
Purpose: Mutation hook to delete one or more flow canvases.
Returns:
data: mutation response data.loading: boolean.deleteFlow: async mutation function.
Parameters for mutation:
canvasIds: string[]- Array of flow canvas IDs to delete.
Details:
Calls
flowService.removeCanvas({ canvasIds }).Invalidates
'infiniteFetchFlowListTeam'query to refresh related lists.
Usage Example:
const { deleteFlow } = useDeleteFlow(); deleteFlow(['id1', 'id2']);
useRunFlow
Purpose: Mutation hook to execute (run) a flow.
Returns:
data: run result data.loading: boolean.runFlow: async mutation function.
Parameters for mutation:
{ id: string; dsl: DSL }
Details:
Calls
flowService.runCanvas(params).Displays success message on successful run.
Usage Example:
const { runFlow } = useRunFlow(); runFlow({ id: 'flow-123', dsl: currentDsl });
useResetFlow
Purpose: Mutation hook to reset a flow canvas to its initial state.
Returns:
data: mutation response data.loading: boolean.resetFlow: async mutation function.
Details:
Uses
idfrom URL params.Calls
flowService.resetCanvas({ id }).
Usage Example:
const { resetFlow } = useResetFlow(); resetFlow();
useTestDbConnect
Purpose: Mutation hook to test database connection parameters.
Returns:
data: test connection response.loading: boolean.testDbConnect: async mutation function.
Parameters for mutation:
params: any- Database connection parameters.
Details:
Calls
flowService.testDbConnect(params).Shows success or error message based on response.
Usage Example:
const { testDbConnect } = useTestDbConnect(); testDbConnect(dbParams);
useFetchInputElements
Purpose: Fetches input elements for a given flow component.
Parameters:
componentId?: string- ID of the component.
Returns:
data: array of input elements.loading: boolean.
Details:
Uses
idfrom URL params.Calls
flowService.getInputElements({ id, component_id: componentId }).Query enabled only if both
idandcomponentIdare truthy.
Usage Example:
const { data: inputs, loading } = useFetchInputElements("component-123");
useDebugSingle
Purpose: Mutation hook to debug a single flow component or node.
Returns:
data: debug result data.loading: boolean.debugSingle: async mutation function.
Parameters for mutation:
IDebugSingleRequestBody- Debug request parameters.
Details:
Uses
idfrom URL params.Calls
flowService.debugSingle({ id, ...params }).Shows error message if debugging fails.
Usage Example:
const { debugSingle } = useDebugSingle(); debugSingle({ nodeId: 'node-1', input: {...} });
Important Implementation Details and Algorithms
React Query Integration:
The file extensively usesuseQueryfor fetching and caching data anduseMutationfor performing data modifications with automatic cache invalidation and UI feedback.UUID for Messages:
When fetching flow details (useFetchFlow,useFetchFlowSSE), the messages within the DSL are processed usingbuildMessageListWithUuidto ensure each message has a unique identifier. This is essential for stable React rendering and tracking message updates.Localized UI Messages:
Usesreact-i18nextfor translation of UI messages (e.g., success notifications).Dependency on URL Params:
Hooks such asuseFetchFlow,useResetFlow,useFetchInputElements, anduseDebugSinglerely on the React Router'suseParamshook to extract IDs from the current route.Error Handling:
Mutation hooks display success or error messages using Ant Design'smessagecomponent depending on the API response codes.Cache Invalidation:
After mutations that change flow data (setFlow,deleteFlow), relevant queries are invalidated to trigger refetching and maintain UI consistency.
Interaction with Other Parts of the System
API Service (
flowService):
All data interactions are routed through theflowServiceAPI client, which abstracts HTTP calls to backend endpoints related to flow operations.UI Components:
React components use these hooks to fetch and mutate flow data, relying on the hooks for state (loading, data) and mutation functions.Routing:
Hooks depend on route parameters (id) and shared chat parameters (sharedId) to determine which flow or version to fetch or mutate.Localization:
Integration withi18nfor translating UI strings.Utilities:
Uses utility functions likebuildMessageListWithUuidfor message processing and Lodash'sgetandsetfor safe object manipulation.
Mermaid Diagram: Flow of Hook Functions and Their Relationships
flowchart TD
A[Flow Hooks Module] --> B[useFetchFlowTemplates]
A --> C[useFetchFlowList]
A --> D[useFetchListVersion]
A --> E[useFetchVersion]
A --> F[useFetchFlow]
A --> G[useFetchFlowSSE]
A --> H[useSettingFlow]
A --> I[useSetFlow]
A --> J[useDeleteFlow]
A --> K[useRunFlow]
A --> L[useResetFlow]
A --> M[useTestDbConnect]
A --> N[useFetchInputElements]
A --> O[useDebugSingle]
F -->|depends on| P[useParams]
L -->|depends on| P
N -->|depends on| P
O -->|depends on| P
F -->|uses| Q[buildMessageListWithUuid]
G -->|uses| Q
H -->|calls| R[flowService.settingCanvas]
I -->|calls| S[flowService.setCanvas]
J -->|calls| T[flowService.removeCanvas]
K -->|calls| U[flowService.runCanvas]
L -->|calls| V[flowService.resetCanvas]
M -->|calls| W[flowService.testDbConnect]
N -->|calls| X[flowService.getInputElements]
O -->|calls| Y[flowService.debugSingle]
B -->|calls| Z[flowService.listTemplates]
C -->|calls| AA[flowService.listCanvas]
D -->|calls| AB[flowService.getListVersion]
E -->|calls| AC[flowService.getVersion]
F -->|calls| AD[flowService.getCanvas]
G -->|calls| AE[flowService.getCanvasSSE]
Summary
The flow-hooks.ts file is a core utility module that provides React hooks for interacting with flow-related backend APIs in an efficient and declarative way using React Query. It covers a wide range of operations including fetching flow templates, lists, versions, details, running, resetting, testing connections, and debugging. The file ensures UI responsiveness with loading states and user feedback via notifications, and helps keep React components clean by abstracting data logic.
This modular approach promotes reusability, maintainability, and a consistent data-fetching pattern across the flow-related features in the application.