use-send-shared-message.ts
Overview
use-send-shared-message.ts is a custom React hook module designed to facilitate sending and managing chat messages within a "shared chat" context, typically involving conversations shared between users and agents or chatbots. It handles message input, sending messages to a backend API via Server-Sent Events (SSE), managing message states, and retrieving chat session parameters from the URL.
This file integrates multiple hooks and utilities to provide a seamless chat experience by managing message lifecycle events (input, send, receive, error handling) and maintaining UI state such as loading indicators and message lists.
Exports and Main Functionalities
1. useSendButtonDisabled(value: string): boolean
Purpose:
Determines whether the send button should be disabled based on the current input value.
Parameters:
value(string): The current text input from the user.
Returns:
boolean: true if the trimmed input is empty (button should be disabled), otherwisefalse.
Usage Example:
const isDisabled = useSendButtonDisabled(inputValue);
<button disabled={isDisabled}>Send</button>
2. useGetSharedChatSearchParams(): SharedChatParams
Purpose:
Parses and returns relevant chat-related parameters from the URL search parameters.
Returns:
An object containing:
Property | Type | Description |
|---|---|---|
|
| Source identifier of shared chat (agent or chatbot) |
| `string \ | null` |
| `string \ | null` |
|
| Additional data prefixed by |
|
| Whether avatar display is visible |
Usage Example:
const { from, sharedId, locale, data, visibleAvatar } = useGetSharedChatSearchParams();
3. useSendSharedMessage(): UseSendSharedMessageReturn
Purpose:
Primary hook that manages the sending of shared chat messages, message input state, message list management, error handling, and session initialization.
Returns:
An object with properties and methods for chat UI interaction:
Property / Method | Type | Description |
|---|---|---|
|
| Sends the message when Enter key is pressed, appending document IDs |
|
| Handler for text input change |
|
| Current message input value |
|
| Indicates if a send request is in progress |
|
| Placeholder loading indicator (always false here) |
|
| List of chat messages, including both questions and answers |
|
| Indicates if an error occurred during message sending or session initiation |
|
| Stops the SSE message output stream |
|
| Ref to the scroll container for messages |
|
| Ref to the message container |
|
| Removes all messages from the message list |
|
| Removes all messages except the first one |
Detailed Explanation of useSendSharedMessage
Internal Dependencies and Hooks Used
useGetSharedChatSearchParams: Extracts URL parameters relevant to the conversation.useCreateNextSharedConversation: Provides the methodcreateSharedConversationto initialize a new conversation on the backend.useHandleMessageInputChange: Manages the input text state and change handlers.useSendMessageWithSse: Sends messages to the server using SSE and receives streaming answers.useSelectDerivedMessages: Manages the chat message list, including adding/removing messages and scrolling behavior.
Key Internal Functions
sendMessage(message: Message, id?: string): Promise<void>
Sends a message to the backend API.
Parameters:
message: The message object containing content and metadata.id: Optional conversation ID. Defaults to the current conversation ID if not provided.
On failure (non-200 response or error code), it resets the input value and removes the last message from the UI.
handleSendMessage(message: Message): Promise<void>
Sends a message, initializing a conversation if none exists.
If
conversationIdis empty, it callscreateSharedConversationto get a new conversation ID.Uses
sendMessageinternally.
fetchSessionId(): Promise<void>
Called on mount to initialize the chat session.
Sends an empty question to the backend with additional data.
Sets an error state and displays an error message if the response indicates failure.
handlePressEnter(documentIds: string[]): void
Triggered when the user presses Enter in the input field.
Checks if input is non-empty and if the previous response is done.
Generates a UUID for the new message.
Adds the user's question to the message list and sends it.
React Effects
On mount (
useEffect),fetchSessionIdis called to initialize the session.When a new answer is received (
answer.answer), it is appended to the message list viaaddNewestAnswer.
Important Implementation Details
Message Sending via SSE:
The sending and receiving of message completions use Server-Sent Events for streaming answers (useSendMessageWithSse).URL Parameter Parsing:
Parsing of URL parameters is done carefully to separate generic parameters from those prefixed withdata_, allowing flexible data passing via the URL.Message Lifecycle Management:
Adding/removing messages from the UI is done throughuseSelectDerivedMessages, ensuring UI consistency and scroll handling.Error Handling:
The utility functionisCompletionErrorchecks the HTTP status and API response code to detect errors and trigger UI rollback and notifications.UUID for Messages:
Each user message is assigned a UUID to uniquely identify it, which is necessary for managing messages in the UI and backend.
Interaction with Other System Components
Backend API:
Communicates with REST endpoints (e.g.,/api/v1/agentbots/:id/completionsor/api/v1/chatbots/:id/completions) to send questions and receive answers via SSE.Hooks:
Depends on several custom hooks (useCreateNextSharedConversation,useHandleMessageInputChange,useSendMessageWithSse,useSelectDerivedMessages) from the application, indicating a modular hook-based architecture.UI Components:
This hook is designed to be used within a React component responsible for rendering the chat interface, managing input fields, message lists, and loading/error states.URL Routing:
Relies on URL parameters (viauseSearchParamsfromumirouting library) for contextual information about the shared chat session.
Usage Example
import React from 'react';
import { useSendSharedMessage, useSendButtonDisabled } from './use-send-shared-message';
const SharedChatComponent = () => {
const {
value,
handleInputChange,
handlePressEnter,
sendLoading,
derivedMessages,
hasError,
stopOutputMessage,
scrollRef,
messageContainerRef,
} = useSendSharedMessage();
const isDisabled = useSendButtonDisabled(value);
const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter') {
handlePressEnter([]);
}
};
return (
<div ref={messageContainerRef}>
<div ref={scrollRef}>
{derivedMessages.map(msg => (
<div key={msg.id}>{msg.content}</div>
))}
</div>
<input
value={value}
onChange={handleInputChange}
onKeyDown={onKeyDown}
disabled={sendLoading}
/>
<button onClick={() => handlePressEnter([])} disabled={isDisabled || sendLoading}>
Send
</button>
{hasError && <div>Error sending message.</div>}
</div>
);
};
Mermaid Diagram: Flowchart of Main Functions and Their Relationships
flowchart TD
A[useSendSharedMessage] --> B[useGetSharedChatSearchParams]
A --> C[useCreateNextSharedConversation]
A --> D[useHandleMessageInputChange]
A --> E[useSendMessageWithSse]
A --> F[useSelectDerivedMessages]
A --> G[fetchSessionId]
A --> H[sendMessage]
A --> I[handleSendMessage]
A --> J[handlePressEnter]
G --> E
H --> E
I --> H
J --> I
J --> F
J --> D
The main hook
useSendSharedMessageorchestrates URL param extraction, conversation creation, input handling, message sending with SSE, and message list management.handlePressEntertriggers sending a message, which may create a conversation first, then send the message.fetchSessionIdinitializes the session on load.sendMessageis the core function sending messages through SSE.
Summary
This file encapsulates the core logic for a shared chat message sending feature within a React application, using hooks to coordinate UI state, backend communication, and session management. It supports seamless message streaming, error handling, and conversation lifecycle management, enabling rich chat experiences in shared or embedded chat scenarios.