use-send-message.ts
Overview
The use-send-message.ts file provides a React custom hook useSendMessageBySSE designed to send chat messages to a backend service and receive real-time streamed responses using Server-Sent Events (SSE). It manages the lifecycle of an SSE connection, processes incoming events related to chat workflows, and maintains an up-to-date list of message events in the React component's state.
This file encapsulates the logic for communicating with an API endpoint that completes conversations (likely an AI or chatbot backend), parsing the streamed JSON events, handling errors, and providing control to stop the message stream on demand.
Detailed Explanation
Enumerations
MessageEventType
An enum representing the types of events that can be emitted by the chat workflow backend:
Event | Description |
|---|---|
Indicates the beginning of a workflow. | |
A node (step) in the workflow has started. | |
A node in the workflow has finished. | |
| A message event carrying chat content. |
End of a message sequence. | |
The entire workflow is finished. | |
User input data event. | |
Logs associated with a node execution. |
Interfaces & Types
These interfaces define the structure of various event payloads received from the backend:
IAnswerEvent<T>: Generic structure for an answer event with metadata and data payload of typeT.INodeData: Data about a node execution including inputs, outputs, errors, and timing.
IInputData: User input data with content and tips.IMessageData: Content of a chat message, with optional flags indicating thinking state.IMessageEndData: Contains a reference object pointing to relevant contextual data.ILogData: Extends INodeData with specific logs related to node execution.Union types such as
INodeEvent,IMessageEvent,IMessageEndEvent,IInputEvent, ILogEvent represent specialized answer events with specific data payloads.IChatEvent: Union of the main event types relevant to chats.IEventList: Array of chat events.
Hook: useSendMessageBySSE
This is the exported React hook providing the main functionality.
Purpose
To send a chat message request to the backend API.
To listen for streamed server-sent events representing the conversation progress.
To collect and maintain the list of incoming events (
answerList).To provide control utilities such as stopping the stream (
stopOutputMessage) and resetting the answer list.
Parameters
url?: string(default:api.completeConversation): The endpoint URL to send the chat message request.
Return Values (object)
Property | Type | Description |
|---|---|---|
|
| Function to send the chat message with body data. |
| Array of events collected from the SSE stream. | |
|
| Indicates if the sending/streaming is complete. |
| State setter to manually set | |
|
| Clears the answer list after a delay. |
|
| Aborts the active SSE connection to stop streaming. |
Internal Logic and Methods
initializeSseRef
Initializes or resets the internal
AbortControllerused to abort the fetch request.
resetAnswerList
Clears
answerListafter a 1-second delay, using a timer.Ensures no memory leaks by clearing any existing timer.
send
Sends a POST request to the specified url with the provided request body.
Attaches authorization headers using
getAuthorization().Uses Fetch API to open a streaming connection.
Pipes the response through
TextDecoderStreamandEventSourceParserStreamto parse SSE events.Reads the stream asynchronously, parsing each event's JSON payload.
On each parsed event:
Logs the data for debugging.
Checks for error codes (e.g., 500), displaying messages via UI.
Appends the event to
answerList.
Handles stream completion by setting done = true and resetting the answer list.
Supports cancellation via an
AbortController.Returns an object containing the fetch
responseand parsed JSONdataon success.Catches and logs exceptions, cleaning up the state appropriately.
stopOutputMessage
Calls
abort()on the currentAbortControllerto terminate the SSE stream.
Usage Example
import React from 'react';
import { useSendMessageBySSE } from './use-send-message';
const ChatComponent = () => {
const { send, answerList, done, stopOutputMessage } = useSendMessageBySSE();
const handleSendMessage = async () => {
const body = { message: 'Hello!' };
await send(body);
};
return (
<div>
<button onClick={handleSendMessage} disabled={!done}>Send Message</button>
<button onClick={stopOutputMessage}>Stop</button>
<ul>
{answerList.map((event, index) => (
<li key={index}>{JSON.stringify(event)}</li>
))}
</ul>
</div>
);
};
Important Implementation Details
Use of
EventSourceParserStream: This utility transforms the raw fetch response stream into parsed SSE events, enabling incremental processing of streamed JSON messages.AbortController for Cancellation: The hook manages an
AbortControllerto allow cancellation of ongoing requests, which is vital for user experience and resource management.State Management: React's
useStateanduseRefhooks manage the event list, streaming status, timers, and abort controllers.Handling Streaming Responses: The while-loop with
reader.read()processes partial data as it arrives, enabling low-latency UI updates.Error Notification: Integrates with UI message component to show errors when the backend returns error codes.
Interaction With Other Parts of the System
API Endpoint: The hook sends requests to the
api.completeConversationendpoint, which is expected to send back SSE streams representing chat events.Authorization: Uses
getAuthorization()utility to supply authorization headers, implying integration with authentication logic.UI Messaging: Uses a UI component
messageto display user-facing error messages.Event Types and Interfaces: Imports event type constants and interfaces from shared folders, indicating coordinated schema definitions across the app.
Utilities: Uses
EventSourceParserStreamfor parsing SSE, which is a specialized utility, and React hooks for state management.
Mermaid Diagram
flowchart TD
A[useSendMessageBySSE Hook] --> B(send function)
A --> C(answerList state)
A --> D(done state)
A --> E(resetAnswerList function)
A --> F(stopOutputMessage function)
B --> G[Fetch POST Request]
G --> H[Response Stream]
H --> I[TextDecoderStream]
I --> J[EventSourceParserStream]
J --> K[Reader.read() Loop]
K --> L[Parse JSON Event]
L --> M{If error code 500?}
M -- Yes --> N[Show error via message.error]
M -- No --> O[Append event to answerList]
K --> P[On done]
P --> Q[Set done=true, resetAnswerList]
F --> R[AbortController.abort()]
B --> S[Return {response, data}]
Summary
The use-send-message.ts file provides a robust React hook for sending messages to a chat backend and receiving real-time event streams using Server-Sent Events. It manages connection lifecycle, event parsing, error handling, and state updates, abstracting away complex streaming logic to enable easy integration into chat UI components.
This module is essential for enabling interactive, streaming chat experiences within the application, supporting workflows and node-based message event structures.