use-agent-request.ts
Overview
The use-agent-request.ts file provides a collection of React custom hooks for managing agent-related data and operations within the application. It primarily facilitates interaction with the backend agent service APIs, handling fetching, updating, deleting, and other agent lifecycle operations.
These hooks leverage the React Query library (@tanstack/react-query) for data fetching and caching, providing reactive state updates, caching, background refetching, and mutation capabilities.
This file abstracts the complexity of API communication and state management, exposing easy-to-use hooks for components to interact with agent data such as agent lists, templates, settings, canvas files, logs, versioning, and more.
Detailed Explanation of Exports
Constants and Types
enum AgentApiAction
Defines string constants representing the various agent API actions supported. These keys are used as query or mutation keys in React Query to uniquely identify requests and cache entries.
Example values:
FetchAgentListUpdateAgentSettingDeleteAgentFetchAgentDetailResetAgentSetAgent... and others.
EmptyDsl
A constant representing the default empty DSL (Domain Specific Language) structure for a new agent flow. It contains:
A graph with a single "begin" node.
Components metadata keyed by node ID.
Retrieval references, history, path (empty arrays).
Globals containing system-level variables like query, user ID, conversation turns, and files.
This object is useful for initializing a new agent's DSL when creating or resetting agents.
Hooks for Fetching Data
useFetchAgentTemplates(): IFlowTemplate[]
Fetches a list of agent flow templates.
Uses
useQueryto cache and retrieve templates.Returns an array of
IFlowTemplate.Automatically fetches using
agentService.listTemplates().
Usage Example:
const templates = useFetchAgentTemplates();
console.log(templates); // array of flow templates
useFetchAgentListByPage()
Fetches paginated list of agent canvases filtered by a search string.
Uses internal hooks
useHandleSearchChangeanduseGetPaginationWithRouterto manage search input and pagination.Debounces search input for 500ms to reduce API calls.
Returns:
data: array ofIFlow(agent canvases)loading: boolean loading statesearchString: current search stringhandleInputChange: input change handler for search boxpagination: current pagination info including total resultssetPagination: setter to update pagination
Usage Example:
const {
data: agents,
loading,
searchString,
handleInputChange,
pagination,
setPagination,
} = useFetchAgentListByPage();
useFetchAgent(): { data: IFlow; loading: boolean; refetch: () => void }
Fetch detailed data for a single agent by ID or shared ID.
Uses URL params (
useParams()) or shared chat params.Fetches canvas data including DSL messages, which are processed to add UUIDs.
Returns:
data: agent flow (IFlow)loading: boolean loading staterefetch: function to manually refetch data
useFetchAgentAvatar(): { data: IFlow; loading: boolean; refetch: () => void }
Fetches avatar information for an agent identified by shared ID.
Uses shared chat parameters.
Returns avatar data loaded from
agentService.fetchAgentAvatar.
useFetchAgentLog(searchParams: IAgentLogsRequest)
Fetches logs for a given agent ID with filtering options.
Uses URL param ID and
searchParamsfor filters.Returns logs data (
IAgentLogsResponse) and loading state.
useFetchExternalAgentInputs()
Fetches inputs for an external agent identified by shared ID.
Returns data of type
IInputsand loading/refetch controls.
useFetchInputForm(componentId?: string)
Fetches input form schema for a specific component within an agent.
Requires agent ID from URL and component ID.
Returns form data as a generic record.
useFetchVersionList()
Fetches a list of versions for the current agent.
Returns array of version metadata including creation date, title, and ID.
useFetchVersion(version_id?: string): { data?: IFlow; loading: boolean }
Fetches a specific version of an agent by version ID.
Only fetches if
version_idis provided.Returns optional
IFlowdata and loading state.
useFetchPrompt()
Fetches prompt strings related to agents.
Returns a record of string keys to string values representing prompts.
Hooks for Mutations (Create, Update, Delete)
useUpdateAgentSetting()
Updates settings for an agent canvas.
On success, invalidates the agent list query to refresh data.
Returns:
data: mutation response codeloading: mutation pending stateupdateAgentSetting: async function to perform update
useDeleteAgent()
Deletes one or more agent canvases by their IDs.
On success, invalidates agent list query.
Returns:
data: deleted canvas IDs or empty listloading: mutation statedeleteAgent: async delete function
useResetAgent()
Resets the current agent's canvas.
Uses URL param ID.
Returns mutation response data, loading, and reset function.
useSetAgent(showMessage = true)
Creates or updates an agent canvas.
Accepts parameters including ID, title, DSL, avatar.
Shows a success message on operation if
showMessageis true.Invalidates agent list query on success.
Returns mutation data, loading, and set function.
useUploadCanvasFile()
Uploads one or more files to the current agent's canvas.
Supports single or multiple files.
Uses FormData for file transmission.
Shows success or error messages.
Returns mutation data, loading, and upload function.
useUploadCanvasFileWithProgress(identifier?: Nullable<string>)
Uploads files to an agent canvas with progress callbacks.
Supports progress, success, and error callbacks for each file.
Uses FormData.
If
identifieris not specified, uses URL param ID.Returns mutation data, loading, and upload function.
useTestDbConnect()
Tests database connection parameters.
Shows success or error messages based on response.
Returns mutation data, loading state, and test function.
useDebugSingle()
Debugs a single agent request with provided input data.
Uses URL param ID.
Shows error message if debugging fails.
Returns data, loading, and debug function.
useSetAgentSetting()
Updates settings of the current agent canvas.
Uses URL param ID.
On success, invalidates agent detail query.
Shows success or error messages.
Returns data, loading, and update function.
Hooks for Tracing and Logs
useFetchMessageTrace(isStopFetchTrace: boolean, canvasId?: string)
Fetches trace data for a specific message in an agent canvas.
Uses URL param ID or passed
canvasId.Polls every 3 seconds unless
isStopFetchTraceis true.Requires a message ID to fetch trace.
Returns trace data array, loading state, refetch function, and setter for message ID.
Important Implementation Details
React Query Integration: All data fetching and mutations use React Query hooks (
useQuery,useMutation, anduseQueryClient) for caching, background updates, and automatic refetching.Debouncing: The
useFetchAgentListByPagehook debounces search input to optimize API calls.File Upload Handling: Separate hooks for file uploads with and without progress callbacks, both using FormData for file transmission.
Message Processing: When fetching agent canvas, message lists are processed to include UUIDs to maintain unique keys.
Query Invalidation: After mutation operations like update, delete, or set, relevant queries are invalidated to keep cached data fresh.
Error and Success Messaging: Uses a centralized UI message component to display success/error feedback to users.
URL Parameters Usage: Many hooks derive the agent identifier from URL parameters (
useParams) or shared chat parameters (useGetSharedChatSearchParams).
Interaction with Other Parts of the System
agentService: This file heavily depends on
agentServicemodule which encapsulates all API calls related to agent data.React Query: Uses React Query for caching and asynchronous state management.
UI Components: Integrates with UI message component (
message) for user feedback.Routing: Relies on
umirouting hooks to obtain parameters for API queries.Utilities: Uses utility functions such as
buildMessageListWithUuidto process messages.Constants and Interfaces: Imports constants like
AgentGlobalsand interfaces likeIFlow,IFlowTemplatefor typing and default values.
Visual Diagram
flowchart TD
A[useFetchAgentTemplates]
B[useFetchAgentListByPage]
C[useFetchAgent]
D[useUpdateAgentSetting]
E[useDeleteAgent]
F[useResetAgent]
G[useSetAgent]
H[useUploadCanvasFile]
I[useUploadCanvasFileWithProgress]
J[useFetchMessageTrace]
K[useTestDbConnect]
L[useDebugSingle]
M[useFetchInputForm]
N[useFetchVersionList]
O[useFetchVersion]
P[useFetchAgentAvatar]
Q[useFetchAgentLog]
R[useFetchExternalAgentInputs]
S[useSetAgentSetting]
T[useFetchPrompt]
A --> agentService.listTemplates
B --> agentService.listCanvasTeam
C --> agentService.fetchCanvas
D --> agentService.settingCanvas
E --> agentService.removeCanvas
F --> agentService.resetCanvas
G --> agentService.setCanvas
H --> agentService.uploadCanvasFile
I --> agentService.uploadCanvasFile
J --> fetchTrace
K --> agentService.testDbConnect
L --> agentService.debugSingle
M --> agentService.inputForm
N --> agentService.fetchVersionList
O --> agentService.fetchVersion
P --> agentService.fetchAgentAvatar
Q --> fetchAgentLogsByCanvasId
R --> agentService.fetchExternalAgentInputs
S --> agentService.settingCanvas
T --> agentService.fetchPrompt
style A fill:#f9f,stroke:#333,stroke-width:1px
style B fill:#ccf,stroke:#333,stroke-width:1px
style C fill:#cfc,stroke:#333,stroke-width:1px
style D fill:#fcf,stroke:#333,stroke-width:1px
style E fill:#fcc,stroke:#333,stroke-width:1px
style F fill:#cff,stroke:#333,stroke-width:1px
style G fill:#ffc,stroke:#333,stroke-width:1px
style H fill:#fc9,stroke:#333,stroke-width:1px
style I fill:#9cf,stroke:#333,stroke-width:1px
style J fill:#99f,stroke:#333,stroke-width:1px
style K fill:#f99,stroke:#333,stroke-width:1px
style L fill:#f6c,stroke:#333,stroke-width:1px
style M fill:#6f9,stroke:#333,stroke-width:1px
style N fill:#6cf,stroke:#333,stroke-width:1px
style O fill:#f96,stroke:#333,stroke-width:1px
style P fill:#9f6,stroke:#333,stroke-width:1px
style Q fill:#f69,stroke:#333,stroke-width:1px
style R fill:#69f,stroke:#333,stroke-width:1px
style S fill:#fc6,stroke:#333,stroke-width:1px
style T fill:#6ff,stroke:#333,stroke-width:1px
Summary
The use-agent-request.ts file is a vital layer in the application that abstracts agent API interactions into reusable React hooks. It manages agent data fetching, creation, updates, deletions, file uploads, tracing, debugging, and versioning — all integrated with React Query for effective state management and caching.
These hooks enable components to easily work with agent-related data through a clean and consistent interface, promoting maintainability and scalability of the agent management features in the application.