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

WorkflowStarted

Indicates the beginning of a workflow.

NodeStarted

A node (step) in the workflow has started.

NodeFinished

A node in the workflow has finished.

Message

A message event carrying chat content.

MessageEnd

End of a message sequence.

WorkflowFinished

The entire workflow is finished.

UserInputs

User input data event.

NodeLogs

Logs associated with a node execution.


Interfaces & Types

These interfaces define the structure of various event payloads received from the backend:


Hook: useSendMessageBySSE

This is the exported React hook providing the main functionality.

Purpose

Parameters

Return Values (object)

Property

Type

Description

send

async function

Function to send the chat message with body data.

answerList

IEventList

Array of events collected from the SSE stream.

done

boolean

Indicates if the sending/streaming is complete.

setDone

React.Dispatch

State setter to manually set done.

resetAnswerList

function

Clears the answer list after a delay.

stopOutputMessage

function

Aborts the active SSE connection to stop streaming.


Internal Logic and Methods

initializeSseRef

resetAnswerList

send

stopOutputMessage


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


Interaction With Other Parts of the System


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.