hooks.ts
Overview
The hooks.ts file provides custom React hooks primarily aimed at managing chat message flows within a conversational UI, likely tied to an interactive flow or canvas system. It integrates with APIs to fetch flow details, send messages asynchronously via server-sent events (SSE), and maintain a derived state of chat messages that include user questions and system answers.
Key functionalities include:
Fetching and managing chat flow details and derived messages.
Handling user input for chat messages.
Sending chat messages to a backend service with live updates via SSE.
Managing message lifecycle: adding, removing, and updating messages dynamically.
Handling errors gracefully during message transmission.
The file acts as a bridge between UI components and backend APIs, encapsulating complex state and side effects related to chat interactions.
Detailed Explanations
Imports and Utilities
MessageType: Enum defining user/system message roles.
useFetchFlow: Hook to fetch flow details.
useSelectDerivedMessages: Hook to manage and select derived chat messages.
useHandleMessageInputChange: Hook to manage input state and changes.
useSendMessageWithSse: Hook to send messages and receive SSE updates.
api.runCanvas: API endpoint for running the chat flow.
uuid: Generates unique IDs.
antd message: UI feedback component for errors.
i18n: Internationalization for messages.
receiveMessageError: Utility to check if a response contains an error.
Hook: useSelectNextMessages
Purpose
Provides access to the current flow's reference, loading state, and the set of derived messages along with utility functions to mutate this message state.
Returns
An object containing:
reference: Reference string from the flow DSL.loading: Boolean indicating flow detail loading.derivedMessages: Array of derived chat messages.ref: React ref for messages container or state.addNewestQuestion(message): Adds a new user question message.addNewestAnswer(message): Adds a new system answer message.removeLatestMessage(): Removes the last message in the list.removeMessageById(id): Removes a message by its ID.removeMessagesAfterCurrentMessage(id): Removes all messages after a specified message ID.
Usage Example
const {
reference,
loading,
derivedMessages,
addNewestQuestion,
addNewestAnswer,
removeLatestMessage,
} = useSelectNextMessages();
Hook: useSendNextMessage
Purpose
Handles the full lifecycle of sending messages within the chat flow, from capturing user input, sending messages through an API with SSE, updating UI state with new messages, handling errors, and managing loading states.
Core Functionalities
Manages message input state (
value).Sends messages using SSE and updates derived messages.
Handles errors by displaying notifications and reverting state.
Adds new questions and answers to the message list.
Fetches initial prologue message when the component mounts.
Provides handlers for sending messages on pressing Enter.
Supports stopping message output (e.g., cancelling SSE).
Returns
An object containing:
handlePressEnter: Function to call on Enter keypress to send a message.handleInputChange: Input change handler.value: Current input value.sendLoading: Boolean indicating if sending is in progress.reference: Flow reference string.loading: Flow loading state.derivedMessages: Current list of derived messages.ref: React ref for message container/state.removeMessageById: Function to remove a message by ID.stopOutputMessage: Function to stop SSE output.
Parameters/Dependencies
Uses
useParams()from Umi to getflowIdfrom URL.Uses
useFetchFlow()for fetching and refetching flow data.Uses
useSendMessageWithSse(api.runCanvas)to send messages.
Usage Example
const {
handlePressEnter,
handleInputChange,
value,
sendLoading,
derivedMessages,
removeMessageById,
stopOutputMessage,
} = useSendNextMessage();
// Bind handleInputChange to input field onChange
// Bind handlePressEnter to input field onKeyPress (Enter)
// Display derivedMessages in chat UI
Important Implementation Details and Algorithms
Derived Messages Management: The file leverages a custom hook
useSelectDerivedMessagesto maintain a normalized list of messages reflecting the chat history. This allows precise control over message addition, removal, and updates, ensuring UI consistency.Server-Sent Events for Messaging: The
useSendMessageWithSsehook abstracts SSE communication, allowing incremental message updates (e.g., streaming answers) and controlling when the message output is done or stopped.Error Handling: The system uses a utility
receiveMessageErrorto detect and handle API errors, showing antd error messages and reverting to a safe state by removing the latest message and restoring input.Auto-fetching Prologue: On mount, the hook sends a "prologue" request to the backend to fetch any initial message or setup necessary for the flow.
Use of React
useCallbackanduseEffect: Ensures that functions and side effects are memoized and run only when dependencies change, optimizing render performance.
Interaction with Other Parts of the System
API Layer (
api.runCanvas): Interacts with backend to send/receive chat messages and flow data.Flow Data (
useFetchFlow): Fetches current flow state, including DSL reference and messages.Message State Management (
useSelectDerivedMessages): Provides message operations that this file calls to manipulate the chat history.UI Components: The hooks here are designed to be used by React components rendering chat interfaces, binding input fields and message lists to the returned handlers and state.
Localization (
i18n): Localized strings are used for user feedback during flow execution.Error Utilities and Notifications (
antd message): For reporting errors and user notifications.
Mermaid Diagram - Flowchart of Main Functions and Their Relationships
flowchart TD
A[useSendNextMessage] --> B[useSelectNextMessages]
B --> C[useFetchFlow]
B --> D[useSelectDerivedMessages]
A --> E[useHandleMessageInputChange]
A --> F[useSendMessageWithSse]
F --> G[api.runCanvas]
A --> H[handlePressEnter]
H --> I[addNewestQuestion]
F --> J[sendMessage]
J --> K[send(params)]
K --> L[API SSE response]
L --> M[answer & done states]
M --> I(addNewestAnswer)
J -.-> N[error handling]
N --> O[antMessage.error]
N --> P[removeLatestMessage]
A --> Q[fetchPrologue]
Q --> K
style A fill:#f9f,stroke:#333,stroke-width:2px
style B fill:#bbf,stroke:#333,stroke-width:1.5px
style F fill:#bfb,stroke:#333,stroke-width:1.5px
Summary
The hooks.ts file encapsulates complex chat flow logic into reusable React hooks, combining fetching, state management, SSE-driven messaging, and input handling. It serves as a core utility layer for the chat UI components, ensuring smooth user interactions and real-time message streaming with robust error handling.