shared-hooks.ts
Overview
The shared-hooks.ts file provides a set of custom React hooks designed to handle shared chat interactions within a web application. These hooks manage key functionalities such as parsing URL search parameters related to shared chat sessions, controlling user input and message sending logic, managing asynchronous message sending with server-sent events (SSE), and handling errors during chat completion requests.
Primarily, this file enables a chat interface to:
Extract contextual parameters from the URL to identify shared chat sessions.
Enable or disable the send button based on user input.
Manage the sending of messages to different backend endpoints depending on chat context.
Handle incoming streamed responses for chat answers.
Maintain the state of conversation messages and their lifecycle events (adding/removing).
Provide error handling and user feedback for failed message completions.
This file interacts closely with other hooks from the project such as chat-hooks, logic-hooks, and local hooks for message input handling, integrating with backend APIs to support real-time chat functionality.
Detailed Explanations
Utility Function: isCompletionError
const isCompletionError = (res: any) =>
res && (res?.response.status !== 200 || res?.data?.code !== 0);
Purpose: Checks if the response from the message completion API indicates an error.
Parameters:
res: Response object from the API call.
Returns:
trueif the API response status is not 200 or if the response data code is not 0, indicating an error; otherwisefalse.Usage: Used internally to detect and handle API errors when sending chat messages.
Hook: useSendButtonDisabled
export const useSendButtonDisabled = (value: string) => {
return trim(value) === '';
};
Purpose: Determines whether the send button should be disabled based on the current input value.
Parameters:
value(string): The current text input by the user.
Returns:
boolean—trueif the trimmed input is empty (disabling the send button), elsefalse.Usage Example:
const isDisabled = useSendButtonDisabled(userInput);
<button disabled={isDisabled}>Send</button>
Hook: useGetSharedChatSearchParams
export const useGetSharedChatSearchParams = () => { ... };
Purpose: Parses and extracts relevant shared chat parameters from the URL search params.
Returns: An object containing:
Property
Type
Description
fromSharedFromSource of the shared chat, e.g., Agent or Chatbot.
sharedId`string
null`
locale`string
null`
dataRecord<string, string>Additional data parameters prefixed with
data_.visibleAvatarbooleanIndicates if avatars should be visible (derived from
visible_avatarparam).Implementation Details:
Uses
useSearchParamsfromumito get the current URL parameters.Filters keys starting with
data_and strips the prefix to include them indata.Parses boolean flag for avatar visibility.
Usage Example:
const { from, sharedId, locale, data, visibleAvatar } = useGetSharedChatSearchParams();
console.log(sharedId); // e.g., "abc123"
Hook: useSendSharedMessage
export const useSendSharedMessage = () => { ... };
Purpose: Manages the sending of shared chat messages, state updates for the message list, SSE handling for streamed responses, error handling, and message input state.
Returns: An object exposing multiple handlers and state variables to be used in chat components:
Property
Type
Description
handlePressEnter(documentIds: string[]) => voidHandles sending message on Enter key press with document references.
handleInputChangeReact.ChangeEventHandlerInput change handler for message input field.
valuestringCurrent value of the message input.
sendLoadingbooleanIndicates if sending is in progress (based on SSE completion).
refReact.RefObjectRef used for scrolling or other DOM interactions related to messages.
loadingbooleanPlaceholder loading state (currently always false).
derivedMessagesMessage[]List of processed messages used in UI.
hasErrorbooleanIndicates if an error occurred during message sending.
stopOutputMessage() => voidFunction to stop the SSE stream prematurely.
Internal Implementation Details:
Parameter Extraction: Uses
useGetSharedChatSearchParamsto get chat context.Conversation Management: Utilizes
useCreateNextSharedConversationto create a new conversation if none exists.Message Input State: Managed by
useHandleMessageInputChange.Sending Messages:
Calls
useSendMessageWithSsewith dynamic API endpoint depending onfromparameter (agentbots or chatbots).sendMessagesends the message content and handles errors by restoring user input and cleaning message list.handleSendMessagecreates a new conversation if needed before sending.
Message List Management: Uses
useSelectDerivedMessagesto add/remove messages and update with the newest question/answer.Error Handling: Displays error messages using
antd'smessage.errorand updateshasError.SSE Answer Handling: Updates the message list with streamed answers as they arrive.
Input Submission:
handlePressEnterhandles pressing enter, generating a UUID for the message, adding the question to the list, and triggering message sending.Session Initialization:
fetchSessionIdtriggers an initial empty question request to establish a session ID.Effects:
On mount, fetches session ID.
On new answer, appends it to messages.
Usage Example:
const {
handlePressEnter,
handleInputChange,
value,
sendLoading,
derivedMessages,
hasError,
stopOutputMessage,
} = useSendSharedMessage();
return (
<ChatInput
value={value}
onChange={handleInputChange}
onEnter={(docIds) => handlePressEnter(docIds)}
disabled={sendLoading}
/>
);
Important Implementation Details and Algorithms
Dynamic API Endpoint:
The hook switches API endpoints based on thefromparameter (Agentor other), allowing reuse of the hook for different chatbot sources.Session Management:
On mount, an empty question is sent to initialize or fetch session metadata, ensuring the session ID is available for subsequent messages.Optimistic Update and Error Recovery:
When sending a message, the UI optimistically adds the question to the message list. If the API call fails, it restores the input value and removes the latest optimistic message.Streaming Responses (SSE):
The hook listens for streamed answers via server-sent events, incrementally updating the chat UI as the answer arrives.Message ID Handling:
Uses UUIDs for new messages to maintain unique identification across optimistic UI updates and backend synchronization.
Interaction with Other Parts of the System
useCreateNextSharedConversation(fromchat-hooks): For creating new shared conversations when none exist.useSendMessageWithSseanduseSelectDerivedMessages(fromlogic-hooks): For sending messages with SSE and managing message list state.useHandleMessageInputChange(local hook): For managing the input field state.Constants
MessageTypeandSharedFrom: Define message roles and shared chat sources.Ant Design's
messagecomponent: For UI error feedback.uuidlibrary: For generating unique message IDs.lodashutilities: For trimming and safe property access in objects.umi'suseSearchParams: For URL query parameter parsing.
This file acts as a bridge between chat UI components and backend chat APIs, encapsulating logic for message sending workflows and shared chat session management.
Mermaid Diagram
flowchart TD
A[useSendSharedMessage] --> B[useGetSharedChatSearchParams]
A --> C[useCreateNextSharedConversation]
A --> D[useHandleMessageInputChange]
A --> E[useSendMessageWithSse]
A --> F[useSelectDerivedMessages]
E --> G[send message to API via SSE]
F --> H[manage derivedMessages state]
D --> I[handle input value and changes]
C --> J[create new conversation if needed]
A --> K[handlePressEnter]
K --> L[sendMessage]
L --> G
A --> M[fetchSessionId]
M --> G
E --> N[answer updates]
N --> H
Summary
The shared-hooks.ts file is a core utility module that provides React hooks to support shared chat functionality, including URL parameter parsing, message input management, asynchronous message sending with streaming, and error handling. It integrates multiple internal hooks and external libraries to facilitate real-time chat experience with robust state and session management. This file is essential for any UI components that render or manage shared chat conversations in the system.