All files / src/components/chat ChatBox.tsx

4.19% Statements 7/167
0% Branches 0/67
0% Functions 0/38
4.57% Lines 7/153

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405                                                                                                                  1x 1x 1x                                                                 1x   1x   1x                                   1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
import { v4 as uuid } from "uuid";
import React, { ReactElement, useCallback, useEffect, useRef, useState } from "react";
import Chat, { MessageProps, useMessages } from "@chatui/core";
import { QuickReplyItemProps } from "@chatui/core/lib/components/QuickReplies";
import { useTranslation } from "react-i18next";
import "../../css/scrollbar.css";
import "./ChatBox.less";
import { MessageContainerHandle } from "@chatui/core/lib/components/MessageContainer";
import { NavbarProps } from "@chatui/core/lib/components/Navbar";
import {
  askAiAssistant,
  ChatMessageProps,
  listHistoricalChatMessages,
  pullChatMessages
} from "./FetchUtils";
import { autoFocusTextarea } from '@utils/BrowserUtils';
import ReconnectableSocket, { SocketInterface } from "@utils/WebsocketUtils";
import { WEBSOCKET_SERVER_URL } from "@config/base";
import { DisplayMode } from "@props/RecordProps";
import { useSlashCommand } from "@utils/hooks";
 
export type Message<T> = {
  content?: T;
  uuid: string;
  type: "PENDING" | "RECEIVED" | "SYSTEM";
  position: "left" | "right";
  user: {
    id: number;
  }
}
 
type IMessage<T> = Message<T> & MessageProps;
 
export type PendingMessage<T> = Message<T> & {
  type: "PENDING";
  status: "pending" | "fail";
  createdAt: number;
  content: T;
}
 
type IPendingMessage<T> = PendingMessage<T> & MessageProps;
 
export type SystemMessage = Message<never> & {
  type: "SYSTEM";
  category: "typing";
  createdAt: number;
}
 
type ISystemMessage = SystemMessage & MessageProps;
 
export type ReceivedMessage<T> = Message<T> & {
  type: "RECEIVED";
  index: number;
  createdAt: number;
  content: T;
}
 
export const isPendingMessage = <T,>(message: Message<T>): message is PendingMessage<T> => message.type === "PENDING";
export const isReceivedMessage = <T,>(message: Message<T>): message is ReceivedMessage<T> => message.type === "RECEIVED";
export const isSystemMessage = <T,>(message: Message<T>): message is SystemMessage => message.type === "SYSTEM";
 
type IReceivedMessage<T> = ReceivedMessage<T> & MessageProps;
 
enum ChatWebSocketDownstreamType {
  SESSION_READY = "SESSION_READY",
  MESSAGE = "MESSAGE",
  TYPING = "TYPING",
}
 
interface ChatDownstreamReadyData {
  type: ChatWebSocketDownstreamType.SESSION_READY;
}
 
interface ChatDownstreamMessageData {
  type: ChatWebSocketDownstreamType.MESSAGE;
  payload: {
    conversationId: number;
    type: 'NEW_MESSAGE' | 'UPDATE_MESSAGE';
    message: ChatMessageProps;
  }
}
 
interface ChatDownstreamTypingData {
  type: ChatWebSocketDownstreamType.TYPING;
  payload: {
    conversationId: number;
    userId: number;
  }
}
 
type ChatDownstreamData = ChatDownstreamReadyData | ChatDownstreamMessageData | ChatDownstreamTypingData;
 
export const isChatDownstreamReadyData = (data: ChatDownstreamData): data is ChatDownstreamReadyData => data.type === ChatWebSocketDownstreamType.SESSION_READY;
 
export const isChatDownstreamMessageData = (data: ChatDownstreamData): data is ChatDownstreamMessageData => data.type === ChatWebSocketDownstreamType.MESSAGE;
 
export const isChatDownstreamTypingData = (data: ChatDownstreamData): data is ChatDownstreamTypingData => data.type === ChatWebSocketDownstreamType.TYPING;
 
export interface ChatBoxProps<T> {
  userId: number;
  conversationId: number;
  handleSetConversationBarrier: () => void;
  setDisplay: (displayMode: DisplayMode) => void;
  navbar?: NavbarProps;
  renderNavbar?: () => React.ReactNode;
  // fetchHistory: (conversationId: number, stopIndex?: number) => Promise<Array<ReceivedMessage<T>>>;
  // pullFunc: (conversationId: number, latestMsgIndex: number) => Promise<Array<ReceivedMessage<T>>>;
  // askFunc: (conversationId: number, message: PendingMessage<T>) => Promise<ReceivedMessage<T>>;
  renderMessageContent: (message: Message<T>) => React.ReactNode;
  handleSend: (type: string, content: string) => T;
  quickReplies?: QuickReplyItemProps[];
  onQuickReplyClick?: ((item: QuickReplyItemProps, index: number) => void) | undefined;
}
 
export const ChatBox = <T,>(props: ChatBoxProps<T>): ReactElement => {
  const {
    conversationId, renderMessageContent, userId, handleSend,
    quickReplies, onQuickReplyClick, navbar, renderNavbar, setDisplay, handleSetConversationBarrier,
  } = props;
 
  const [loading, setLoading] = useState<boolean>(true);
  const askingMsgIndexRef = useRef(0);
  const minIndexRef = useRef(-1);
  const maxIndexRef = useRef(0);
  const { current: sendingMessagesRecord } = useRef<Record<string, IPendingMessage<T>>>({});
  const loadingHistoryPromiseRef = useRef<Promise<void> | undefined>(undefined);
  const messagesRef = useRef<MessageContainerHandle>(null);
  const { messages, prependMsgs, updateMsg, appendMsg, deleteMsg, resetList } = useMessages([]);
  const { t } = useTranslation();
  const [websocket, setWebsocket] = useState<SocketInterface | undefined>(undefined);
  const typingMessageUuidRecordRef = useRef<Record<number, string>>({});
  const { processSlashCommand, isSlashCommand } = useSlashCommand(handleSetConversationBarrier, setDisplay);
 
  const convertToChatMessage = useCallback((item: ChatMessageProps): IReceivedMessage<T> => {
    return {
      _id: item.uuid,
      uuid: item.uuid,
      type: "RECEIVED",
      index: item.msgIndex,
      createdAt: item.dateCreated,
      content: JSON.parse(item.content),
      user: {
        id: item.userId,
      },
      position: item.userId === userId ? "right" : "left",
    };
  }, [userId]);
 
  const fetchHistory = useCallback(async (conversationId: number, stopIndex?: number, limit?: number): Promise<Array<IReceivedMessage<T>>> =>
    listHistoricalChatMessages(conversationId, stopIndex, limit).then((res) => res.msgs.map(convertToChatMessage)),
    [convertToChatMessage]);
 
  const send = useCallback((message: IPendingMessage<T>): Promise<IReceivedMessage<T>> => {
    return askAiAssistant(conversationId, "application/json", JSON.stringify(message.content), message.uuid)
      .then(convertToChatMessage);
  }, [conversationId, convertToChatMessage]);
 
  const receiveMessages = useCallback((rawMessages: Array<ReceivedMessage<T>>): void => {
    if (rawMessages.length === 0) {
      return;
    }
    const messages: Array<IReceivedMessage<T>> = rawMessages.map(msg => ({
      ...msg,
      _id: msg.uuid,
    }));
    messages.sort((a, b) => a.index - b.index);
    let i = messages[0].index;
    // validate the message is successive
    for (const msg of messages) {
      if (msg.index !== i) {
        console.warn("invalid data", messages);
        return;
      }
      i += 1;
    }
    // console.log(`Messages ${messages.map(msg => msg.index)} received, minIndex: ${minIndexRef.current}, maxIndex: ${maxIndexRef.current}`);
    if (messages[messages.length - 1].index > askingMsgIndexRef.current) {
      messages.forEach(msg => {
        const typingMessageUuid = typingMessageUuidRecordRef.current[msg.user.id];
        if (typingMessageUuid) {
          deleteMsg(typingMessageUuid);
        }
      });
    }
    messages.forEach(message => {
      const pendingMsg = sendingMessagesRecord[message.uuid];
      if (pendingMsg) {
        // TODO optimize
        delete sendingMessagesRecord[message.uuid];
        deleteMsg(message.uuid);
      }
    });
 
    if (minIndexRef.current === -1) {
      minIndexRef.current = messages[0].index;
      maxIndexRef.current = messages[messages.length - 1].index;
      resetList(messages);
      messagesRef.current?.scrollToEnd();
      // console.log(`Initial messages ${messages.map(msg => msg.index)}`);
      return;
    }
    if (messages[messages.length - 1].index < minIndexRef.current - 1 || maxIndexRef.current < messages[0].index - 1) {
      // invalid data
      console.warn("Invalid data", minIndexRef.current, maxIndexRef.current, messages);
      return;
    }
    let msgs = messages;
    // prepend
    if (msgs[0].index < minIndexRef.current) {
      const splitPoint = msgs.findIndex(message => message.index === minIndexRef.current);
      if (splitPoint === -1) {
        prependMsgs(msgs);
        minIndexRef.current = msgs[0].index;
        // console.log(`Messages ${msgs.map(msg => msg.index)} prepended`);
        return;
      }
      const prependMessages = msgs.slice(0, splitPoint);
      prependMsgs(prependMessages);
      minIndexRef.current = prependMessages[0].index;
      // console.log(`Messages ${prependMessages.map(msg => msg.index)} prepended`);
      msgs = msgs.slice(splitPoint);
    }
    // update
    if (msgs[0].index <= maxIndexRef.current) {
      const splitPoint = msgs.findIndex(message => message.index > maxIndexRef.current);
      if (splitPoint === -1) {
        msgs.forEach(message => updateMsg(message.uuid, message));
        // console.log(`Messages ${msgs.map(msg => msg.index)} updated`);
        return;
      }
      const updateMessages = msgs.slice(0, splitPoint);
      updateMessages.forEach(message => updateMsg(message.uuid, message));
      // console.log(`Messages ${updateMessages.map(msg => msg.index)} updated`);
      msgs = msgs.slice(splitPoint);
    }
    // append
    if (msgs.length > 0) {
      maxIndexRef.current = msgs[msgs.length - 1].index;
      msgs.forEach(message => appendMsg(message));
      // console.log(`Messages ${msgs.map(msg => msg.index)} appended`);
    }
  }, [appendMsg, deleteMsg, prependMsgs, resetList, sendingMessagesRecord, updateMsg]);
 
  const sendMessage = useCallback((content: T): void => {
    const id = uuid();
    const sendingMessage: IPendingMessage<T> = {
      _id: id,
      uuid: id,
      content,
      type: "PENDING",
      status: "pending",
      createdAt: Date.now(),
      user: {
        id: userId,
      },
      position: "right",
    };
    sendingMessagesRecord[sendingMessage.uuid] = sendingMessage;
    appendMsg(sendingMessage);
    send(sendingMessage)
      .then((resp) => {
        askingMsgIndexRef.current = resp.index;
        receiveMessages([resp]);
      })
      .catch((e) => {
        console.warn("Failed to ask", e);
        const msg = sendingMessagesRecord[sendingMessage.uuid];
        if (msg) {
          msg.status = "fail";
        }
        updateMsg(sendingMessage.uuid, sendingMessage);
      });
  }, [userId, sendingMessagesRecord, appendMsg, send, receiveMessages, updateMsg]);
 
  const hasMoreHistory = (): boolean => {
    return minIndexRef.current > 1;
  };
 
  const loadMoreHistory = useCallback(async (force = false): Promise<void> => {
    if (!force && !hasMoreHistory()) {
      return;
    }
    if (loadingHistoryPromiseRef.current) {
      return loadingHistoryPromiseRef.current;
    }
    setLoading(true);
    loadingHistoryPromiseRef.current = fetchHistory(conversationId, minIndexRef.current > 0 ? minIndexRef.current : undefined)
      .then(receiveMessages)
      .finally(() => {
        setLoading(false);
        loadingHistoryPromiseRef.current = undefined;
      });
    await loadingHistoryPromiseRef.current;
  }, [conversationId, fetchHistory, receiveMessages]);
 
  const pullMessages = useCallback(async (): Promise<void> => {
    try {
      const resp = await pullChatMessages(conversationId, maxIndexRef.current)
        .then((res) => Promise.all(res.msgs.map(convertToChatMessage)));
      receiveMessages(resp);
    } catch (e) {
      console.error(e);
    }
  }, [conversationId, convertToChatMessage, receiveMessages]);
 
  useEffect(() => {
    const websocket = ReconnectableSocket(`${WEBSOCKET_SERVER_URL}/websocket/chat`);
    setWebsocket(websocket);
    return () => {
      websocket.close();
    };
  }, []);
 
  useEffect(() => {
    const subscribe = (): void => {
      websocket?.send(JSON.stringify({
        conversationIds: [conversationId.toString()],
      }));
    };
 
    const onMessage = (text: string): void => {
      const data = JSON.parse(text);
      if (isChatDownstreamReadyData(data)) {
        subscribe();
      }
      if (isChatDownstreamMessageData(data)) {
        if (data.payload.conversationId !== conversationId) {
          return;
        }
        if (data.payload.type === 'NEW_MESSAGE') {
          if (data.payload.message.msgIndex <= maxIndexRef.current) {
            return;
          }
          if (data.payload.message.msgIndex === maxIndexRef.current + 1) {
            // merge message if the message is the next message
            receiveMessages([convertToChatMessage(data.payload.message)]);
          } else {
            // or pull messages if the message is not the next message
            pullMessages();
          }
        }
        if (data.payload.type === 'UPDATE_MESSAGE') {
          fetchHistory(conversationId, data.payload.message.msgIndex + 1, 1).then(receiveMessages);
        }
      }
      if (isChatDownstreamTypingData(data)) {
        if (typingMessageUuidRecordRef.current[data.payload.userId]) {
          deleteMsg(typingMessageUuidRecordRef.current[data.payload.userId]);
        }
        const typingMessageUuid = uuid();
        const typingMessage: ISystemMessage = {
          uuid: typingMessageUuid,
          _id: typingMessageUuid,
          type: "SYSTEM",
          category: "typing",
          createdAt: Date.now(),
          position: "left",
          user: {
            id: data.payload.userId,
          }
        };
        typingMessageUuidRecordRef.current[data.payload.userId] = typingMessageUuid;
        appendMsg(typingMessage);
      }
    };
    if (websocket) {
      if (websocket.isConnected()) {
        subscribe();
      } else {
        websocket.on(onMessage);
      }
    }
    return () => {
      websocket?.off(onMessage);
    };
  }, [appendMsg, conversationId, convertToChatMessage, deleteMsg, fetchHistory, pullMessages, receiveMessages, websocket]);
 
  useEffect(() => {
    loadMoreHistory(true);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
 
  autoFocusTextarea("Composer-input");
 
  return <Chat
    messagesRef={messagesRef}
    renderNavbar={renderNavbar}
    navbar={navbar}
    messages={messages}
    renderMessageContent={(message: MessageProps) => renderMessageContent(message as IMessage<T>)}
    onSend={(type, content) => {
      if (isSlashCommand(content)) {
        processSlashCommand(content);
      } else {
        sendMessage(handleSend(type, content));
      }
    }}
    onRefresh={loadMoreHistory}
    quickReplies={quickReplies}
    onQuickReplyClick={onQuickReplyClick}
    loadMoreText={loading ? t("assistant:Loading") : (hasMoreHistory() ? t("assistant:Load more") : t("assistant:No more"))}
    placeholder={t("assistant:Type a message...")}
  />;
};