Skip to content

Commit

Permalink
refactor: Improve simulate streaming checks
Browse files Browse the repository at this point in the history
  • Loading branch information
tjtanjin committed Nov 24, 2024
1 parent ef8852d commit da44e95
Showing 1 changed file with 9 additions and 13 deletions.
22 changes: 9 additions & 13 deletions src/hooks/internal/useMessagesInternal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,15 +56,13 @@ export const useMessagesInternal = () => {
// stop bot typing when simulating stream
setIsBotTyping(false);

if (!streamMessageMap.current.has(message.sender)) {
// set an initial empty message to be used for streaming
setMessages(prevMessages => {
const updatedMessages = [...prevMessages, createMessage("", message.sender)];
handlePostMessagesUpdate(updatedMessages);
return updatedMessages;
});
streamMessageMap.current.set(message.sender, message.id);
}
// set an initial empty message to be used for simulating streaming
const placeholderMessage = createMessage("", message.sender);
setMessages(prevMessages => {
const updatedMessages = [...prevMessages, placeholderMessage];
handlePostMessagesUpdate(updatedMessages);
return updatedMessages;
});

// initialize default message to empty with stream index position 0
let streamMessage = message.content as string | string[];
Expand All @@ -88,8 +86,7 @@ export const useMessagesInternal = () => {
setMessages((prevMessages) => {
const updatedMessages = [...prevMessages];
for (let i = updatedMessages.length - 1; i >= 0; i--) {
if (updatedMessages[i].sender === message.sender
&& typeof updatedMessages[i].content === "string") {
if (updatedMessages[i].id === placeholderMessage.id) {
const character = streamMessage[streamIndex];
if (character) {
message.content += character;
Expand All @@ -105,9 +102,8 @@ export const useMessagesInternal = () => {
});

await simStreamDoneTask;
streamMessageMap.current.delete(message.sender);
saveChatHistory(messages);
}, [messages, streamMessageMap]);
}, [messages]);

/**
* Injects a message at the end of the messages array.
Expand Down

0 comments on commit da44e95

Please sign in to comment.