Skip to content

Commit

Permalink
refactor: Change message sender field to be fully capitalized
Browse files Browse the repository at this point in the history
  • Loading branch information
tjtanjin committed Nov 22, 2024
1 parent a9314e4 commit b7d2c9d
Show file tree
Hide file tree
Showing 12 changed files with 54 additions and 42 deletions.
4 changes: 2 additions & 2 deletions __tests__/hooks/internal/useChatHistoryInternal.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,14 @@ describe("useChatHistoryInternal Hook", () => {
const initialChatHistory = [
{
id: generateSecureUUID(),
sender: "user",
sender: "USER",
content: "Hello",
type: "string",
timestamp: new Date().toUTCString()
},
{
id: generateSecureUUID(),
sender: "bot",
sender: "BOT",
content: "Hi there!",
type: "string",
timestamp: new Date().toUTCString()
Expand Down
14 changes: 7 additions & 7 deletions __tests__/hooks/internal/useMessagesInternal.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ describe("useMessagesInternal", () => {
const { result } = renderHook(() => useMessagesInternal());

await act(async () => {
const messageId = await result.current.injectMessage("Test message", "bot");
const messageId = await result.current.injectMessage("Test message", "BOT");
expect(messageId).toBeTruthy();
});

Expand All @@ -76,7 +76,7 @@ describe("useMessagesInternal", () => {

it("should remove a message correctly", async () => {
const mockMessageId = "test-id";
const mockMessage: Message = { id: mockMessageId, content: "Test", sender: "bot", type: "text",
const mockMessage: Message = { id: mockMessageId, content: "Test", sender: "BOT", type: "text",
timestamp: String(Date.now()) };
(useMessagesContext as jest.Mock).mockReturnValue({
messages: [mockMessage],
Expand All @@ -98,25 +98,25 @@ describe("useMessagesInternal", () => {
const { result } = renderHook(() => useMessagesInternal());

await act(async () => {
const messageId = await result.current.streamMessage("Test stream", "bot");
const messageId = await result.current.streamMessage("Test stream", "BOT");
expect(messageId).toBeTruthy();
});

expect(mockSetMessages).toHaveBeenCalled();
expect(mockSetUnreadCount).toHaveBeenCalledWith(expect.any(Function));
expect(mockStreamMessageMap.current.has("bot")).toBeTruthy();
expect(mockStreamMessageMap.current.has("BOT")).toBeTruthy();
});

it("should end stream message correctly", async () => {
mockStreamMessageMap.current.set("bot", "test-id");
mockStreamMessageMap.current.set("BOT", "test-id");
const { result } = renderHook(() => useMessagesInternal());

await act(async () => {
const success = await result.current.endStreamMessage("bot");
const success = await result.current.endStreamMessage("BOT");
expect(success).toBeTruthy();
});

expect(mockStreamMessageMap.current.has("bot")).toBeFalsy();
expect(mockStreamMessageMap.current.has("BOT")).toBeFalsy();
});

});
20 changes: 10 additions & 10 deletions __tests__/services/AudioService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ describe("AudioService.processAudio (Inline Mocks)", () => {
// calls process audio
const message: Message = {
id: generateSecureUUID(),
sender: "user",
sender: "USER",
content: "Hello, how can I assist you today?",
type: "string",
timestamp: Date.now().toString(),
Expand All @@ -93,7 +93,7 @@ describe("AudioService.processAudio (Inline Mocks)", () => {
// defines message to be from user
const message: Message = {
id: generateSecureUUID(),
sender: "user",
sender: "USER",
content: "I need help with my account.",
type: "string",
timestamp: Date.now().toString(),
Expand Down Expand Up @@ -121,7 +121,7 @@ describe("AudioService.processAudio (Inline Mocks)", () => {
// defines message content as an object
const message: Message = {
id: generateSecureUUID(),
sender: "bot",
sender: "BOT",
content: React.createElement("div"),
type: "object",
timestamp: Date.now().toString(),
Expand Down Expand Up @@ -152,7 +152,7 @@ describe("AudioService.processAudio (Inline Mocks)", () => {
// calls process audio
const message: Message = {
id: generateSecureUUID(),
sender: "bot",
sender: "BOT",
content: "Welcome back! How can I help you today?",
type: "string",
timestamp: Date.now().toString(),
Expand All @@ -178,7 +178,7 @@ describe("AudioService.processAudio (Inline Mocks)", () => {
// calls process audio, but voice is toggled off
const message: Message = {
id: generateSecureUUID(),
sender: "bot",
sender: "BOT",
content: "Let me know if you need any assistance.",
type: "string",
timestamp: Date.now().toString(),
Expand All @@ -204,7 +204,7 @@ describe("AudioService.processAudio (Inline Mocks)", () => {
// calls process audio
const message: Message = {
id: generateSecureUUID(),
sender: "bot",
sender: "BOT",
content: "Hello! How can I assist you today?",
type: "string",
timestamp: Date.now().toString(),
Expand Down Expand Up @@ -237,7 +237,7 @@ describe("AudioService.processAudio (Inline Mocks)", () => {
// calls process audio
const message: Message = {
id: generateSecureUUID(),
sender: "bot",
sender: "BOT",
content: "This is a test message without a specified voice.",
type: "string",
timestamp: Date.now().toString(),
Expand Down Expand Up @@ -268,7 +268,7 @@ describe("AudioService.processAudio (Inline Mocks)", () => {

const message: Message = {
id: generateSecureUUID(),
sender: "bot",
sender: "BOT",
content: "<b>Hello!</b> How can I assist you today?",
type: "string",
timestamp: Date.now().toString(),
Expand All @@ -294,7 +294,7 @@ describe("AudioService.processAudio (Inline Mocks)", () => {

const message: Message = {
id: generateSecureUUID(),
sender: "bot",
sender: "BOT",
content: "<b>Hello!</b> How can I assist you today?",
type: "string",
timestamp: Date.now().toString(),
Expand All @@ -320,7 +320,7 @@ describe("AudioService.processAudio (Inline Mocks)", () => {

const message: Message = {
id: generateSecureUUID(),
sender: "bot",
sender: "BOT",
content: "",
type: "string",
timestamp: Date.now().toString(),
Expand Down
2 changes: 1 addition & 1 deletion __tests__/services/ChatHistoryService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ describe("ChatHistoryService", () => {

const mockMessage: Message = {
id: "1",
sender: "user",
sender: "USER",
content: "Hello good sir!",
type: "text",
timestamp: "2021-01-01T00:00:00Z",
Expand Down
10 changes: 5 additions & 5 deletions __tests__/utils/messageBuilder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ describe("createMessage", () => {
const mockId = "mocked-uuid";
mockedGenerateSecureUUID.mockReturnValue(mockId);
const content = "This is a test message";
const sender = "bot";
const sender = "BOT";

// creates message
const message = createMessage(content, sender);
Expand All @@ -46,7 +46,7 @@ describe("createMessage", () => {
const mockId = "mocked-uuid";
mockedGenerateSecureUUID.mockReturnValue(mockId);
const content = React.createElement("div");
const sender = "user";
const sender = "USER";

// creates message
const message = createMessage(content, sender);
Expand All @@ -71,7 +71,7 @@ describe("createMessage", () => {
const mockId = "mocked-uuid";
mockedGenerateSecureUUID.mockReturnValue(mockId);
const content = "";
const sender = "bot";
const sender = "BOT";

// creates message
const message = createMessage(content, sender);
Expand All @@ -96,7 +96,7 @@ describe("createMessage", () => {
const mockId = "mocked-uuid";
mockedGenerateSecureUUID.mockReturnValue(mockId);
const content = 'Special characters! @#$%^&*()_+-=[]{}|;\':",.<>/?`~';
const sender = "user";
const sender = "USER";

// creates message
const message = createMessage(content, sender);
Expand Down Expand Up @@ -139,7 +139,7 @@ describe("createMessage", () => {
React.createElement('li', null, 'Item 3')
)
);
const sender = "bot";
const sender = "BOT";

// creates message
const message = createMessage(content, sender);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ const FileAttachmentButton = () => {

// sends media display if file details are valid
await injectMessage(<MediaDisplay file={files[i]} fileType={fileDetails.fileType}
fileUrl={fileDetails.fileUrl}/>, "user");
fileUrl={fileDetails.fileUrl}/>, "USER");
}
await handleSubmitText("📄 " + fileNames.join(", "), settings.fileAttachment?.sendFileName);
await fileHandler({userInput: inputRef.current?.value as string, prevPath: getPrevPath(),
Expand Down
2 changes: 1 addition & 1 deletion src/components/Buttons/VoiceButton/VoiceButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ const VoiceButton = () => {

// sends media display if file details are valid
await injectMessage(<MediaDisplay file={audioFile} fileType={fileDetails.fileType}
fileUrl={fileDetails.fileUrl}/>, "user");
fileUrl={fileDetails.fileUrl}/>, "USER");
}

/**
Expand Down
4 changes: 2 additions & 2 deletions src/components/ChatBotBody/ChatBotBody.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -212,13 +212,13 @@ const ChatBotBody = ({
onScroll={updateIsScrolling}
>
{messages.map((message, index) => {
if (message.sender === "system") {
if (message.sender.toUpperCase() === "SYSTEM") {
return <div key={index}>{message.content}</div>
}

return (
<div key={index}>
{message.sender === "user"
{message.sender.toUpperCase() === "USER"
? renderUserMessage(message, index)
: renderBotMessage(message, index)}
</div>
Expand Down
28 changes: 20 additions & 8 deletions src/hooks/internal/useMessagesInternal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ export const useMessagesInternal = () => {
* @param useMarkup boolean indicating whether markup is used
*/
const simulateStream = useCallback(async (message: Message, streamSpeed: number, useMarkup: boolean) => {
// always convert to uppercase for checks
message.sender = message.sender.toUpperCase();

// stop bot typing when simulating stream
setIsBotTyping(false);

Expand Down Expand Up @@ -113,7 +116,10 @@ export const useMessagesInternal = () => {
* @param sender sender of the message, defaults to bot
*/
const injectMessage = useCallback(async (content: string | JSX.Element,
sender = "bot"): Promise<string | null> => {
sender = "BOT"): Promise<string | null> => {

// always convert to uppercase for checks
sender = sender.toUpperCase();

let message = createMessage(content, sender);

Expand All @@ -127,17 +133,17 @@ export const useMessagesInternal = () => {
}

let useMarkup = false;
if (sender === "bot") {
if (sender === "BOT") {
useMarkup = settings.botBubble?.dangerouslySetInnerHtml as boolean;
} else if (sender === "user") {
} else if (sender === "USER") {
useMarkup = settings.userBubble?.dangerouslySetInnerHtml as boolean;
}

processAudio(settings, audioToggledOn, isChatWindowOpen, message, useMarkup);
const isBotStream = typeof message.content === "string"
&& message.sender === "bot" && settings?.botBubble?.simStream;
&& message.sender === "BOT" && settings?.botBubble?.simStream;
const isUserStream = typeof message.content === "string"
&& message.sender === "user" && settings?.userBubble?.simStream;
&& message.sender === "USER" && settings?.userBubble?.simStream;

// handles post-message inject event
setUnreadCount(prev => prev + 1);
Expand Down Expand Up @@ -197,7 +203,10 @@ export const useMessagesInternal = () => {
* @param sender sender of the message, defaults to bot
*/
const streamMessage = useCallback(async (content: string | JSX.Element,
sender = "bot"): Promise<string | null> => {
sender = "BOT"): Promise<string | null> => {

// always convert to uppercase for checks
sender = sender.toUpperCase();

if (!streamMessageMap.current.has(sender)) {
const message = createMessage(content, sender);
Expand Down Expand Up @@ -261,7 +270,10 @@ export const useMessagesInternal = () => {
* be made mandatory. Another key implication of not using `endStreamMessage` in v2 is that the stop stream
* message event will not be emitted, which may be problematic for logic (or plugins) that rely on this event.
*/
const endStreamMessage = useCallback(async (sender = "bot"): Promise<boolean> => {
const endStreamMessage = useCallback(async (sender = "BOT"): Promise<boolean> => {
// always convert to uppercase for checks
sender = sender.toUpperCase();

// nothing to end if not streaming
if (!streamMessageMap.current.has(sender)) {
return true;
Expand Down Expand Up @@ -306,7 +318,7 @@ export const useMessagesInternal = () => {

const lastMessage = updatedMessages[updatedMessages.length - 1];
// if message is sent by user or is bot typing or bot is embedded, return
if (!lastMessage || lastMessage.sender === "user") {
if (!lastMessage || lastMessage.sender === "USER") {
shouldNotify = false;
}

Expand Down
4 changes: 2 additions & 2 deletions src/hooks/internal/useSubmitInputInternal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,12 +78,12 @@ export const useSubmitInputInternal = () => {
if (settings?.sensitiveInput?.hideInUserBubble) {
return;
} else if (settings?.sensitiveInput?.maskInUserBubble) {
await injectMessage("*".repeat(settings.sensitiveInput?.asterisksCount as number ?? 10), "user");
await injectMessage("*".repeat(settings.sensitiveInput?.asterisksCount as number ?? 10), "USER");
return;
}
}

await injectMessage(userInput, "user");
await injectMessage(userInput, "USER");
}, [flowRef, getCurrPath, settings, injectMessage, textAreaSensitiveMode]);

/**
Expand Down
2 changes: 1 addition & 1 deletion src/services/AudioService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export const processAudio = (settings: Settings, voiceToggledOn: boolean,
isChatWindowOpen: boolean, message: Message, useMarkup: boolean) => {

// Add check for empty message content
if (settings.audio?.disabled || message.sender === "user" || typeof message.content !== "string"
if (settings.audio?.disabled || message.sender.toUpperCase() === "USER" || typeof message.content !== "string"
|| (!isChatWindowOpen && !settings.general?.embedded) || !voiceToggledOn
|| message.content.trim() === "") { // Check for empty message content
return;
Expand Down
4 changes: 2 additions & 2 deletions src/services/ChatHistoryService.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ const saveChatHistory = async (messages: Message[]) => {
for (let i = messages.length - 1; i >= offset; i--) {
const message = messages[i];

if (message.sender === "system") {
if (message.sender.toUpperCase() === "SYSTEM") {
break;
}

Expand Down Expand Up @@ -127,7 +127,7 @@ const parseMessageToString = (message: Message) => {
id: message.id,
content: ReactDOMServer.renderToString(message.content),
type: message.type,
sender: message.sender,
sender: message.sender.toUpperCase(),
timestamp: message.timestamp
});
return clonedMessage;
Expand Down

0 comments on commit b7d2c9d

Please sign in to comment.