Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add notifications components #1148

Merged
merged 19 commits into from
Sep 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion backend/routes/crawl_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,16 @@ async def crawl_endpoint(
user_openai_api_key=request.headers.get("Openai-Api-Key", None),
)
if crawl_notification:
notification_message = {
"status": message["type"],
"message": message["message"],
"name": crawl_website.url,
}
update_notification_by_id(
crawl_notification.id,
NotificationUpdatableProperties(
status=NotificationsStatusEnum.Done, message=str(message)
status=NotificationsStatusEnum.Done,
message=str(notification_message),
),
)
return message
10 changes: 9 additions & 1 deletion backend/routes/upload_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,12 +97,20 @@ async def upload_file(
brain_id=brain_id,
openai_api_key=openai_api_key,
)
if not file.file:
raise Exception("File not found")

if upload_notification:
notification_message = {
"status": message["type"],
"message": message["message"],
"name": file.file.filename if file.file else "",
mamadoudicko marked this conversation as resolved.
Show resolved Hide resolved
}
update_notification_by_id(
upload_notification.id,
NotificationUpdatableProperties(
status=NotificationsStatusEnum.Done, message=str(message)
status=NotificationsStatusEnum.Done,
message=str(notification_message),
),
)

Expand Down
27 changes: 6 additions & 21 deletions frontend/app/chat/[chatId]/components/ActionsBar/ActionsBar.tsx
Original file line number Diff line number Diff line change
@@ -1,35 +1,20 @@
import { useParams } from "next/navigation";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { AiOutlineLoading3Quarters } from "react-icons/ai";

import { useChatApi } from "@/lib/api/chat/useChatApi";

import { ChatInput, KnowledgeToFeed } from "./components";
import { useActionBar } from "./hooks/useActionBar";
import { useKnowledgeUploader } from "./hooks/useKnowledgeUploader";
import { checkIfHasPendingRequest } from "./utils/checkIfHasPendingRequest";

export const ActionsBar = (): JSX.Element => {
const { shouldDisplayUploadCard, setShouldDisplayUploadCard } =
useActionBar();
const {
shouldDisplayUploadCard,
setShouldDisplayUploadCard,
hasPendingRequests,
} = useActionBar();
const { addContent, contents, feedBrain, removeContent } =
useKnowledgeUploader();
const { getHistory } = useChatApi();
const { t } = useTranslation(["chat"]);
const [hasPendingRequests, setHasPendingRequests] = useState(false);
const params = useParams();

useEffect(() => {
const updateNotificationsStatus = async () => {
const chatId = params?.chatId as string | undefined;
if (chatId !== undefined) {
const history = await getHistory(chatId);
setHasPendingRequests(checkIfHasPendingRequest(history));
}
};
void updateNotificationsStatus();
}, [getHistory, params?.chatId]);
const { t } = useTranslation(["chat"]);

return (
<>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,9 +114,6 @@ export const useMentionInput = ({
const keyBindingFn = useCallback(
// eslint-disable-next-line complexity
(e: React.KeyboardEvent<HTMLDivElement>) => {
console.log({
editorContent: getEditorText(editorState),
});
if (mentionTriggers.includes(e.key as MentionTriggerType)) {
setOpen(true);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { IoMdCloseCircle } from "react-icons/io";

import { getFileIcon } from "./helpers/getFileIcon";
import { getFileIcon } from "@/lib/helpers/getFileIcon";

import { FeedTitleDisplayer } from "../FeedTitleDisplayer";

type FileFeedItemProps = {
Expand All @@ -20,7 +21,7 @@ export const FileFeedItem = ({
className="absolute top-2 right-2 cursor-pointer text-gray-400 text-2xl"
onClick={onRemove}
/>
<div className="flex items-center">
<div className="flex items-center gap-1">
{icon}
<FeedTitleDisplayer title={file.name} truncate />
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ import { useTranslation } from "react-i18next";
import { useSupabase } from "@/lib/context/SupabaseProvider";
import { useToast } from "@/lib/hooks";
import { redirectToLogin } from "@/lib/router/redirectToLogin";
import { SupportedFileExtensionsWithDot } from "@/lib/types/SupportedFileExtensions";
import { useEventTracking } from "@/services/analytics/useEventTracking";

import { FeedItemType } from "../../../../../types";
import { SupportedFileExtensionsWithDot } from "../types";

type UseFileUploaderProps = {
addContent: (content: FeedItemType) => void;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,23 @@
import { useState } from "react";
import { useEffect, useState } from "react";

import { useChatContext } from "@/lib/context";

import { checkIfHasPendingRequest } from "../utils/checkIfHasPendingRequest";

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export const useActionBar = () => {
const [shouldDisplayUploadCard, setShouldDisplayUploadCard] = useState(false);

const [hasPendingRequests, setHasPendingRequests] = useState(false);
const { notifications } = useChatContext();

useEffect(() => {
setHasPendingRequests(checkIfHasPendingRequest(notifications));
}, [notifications]);

return {
shouldDisplayUploadCard,
setShouldDisplayUploadCard,
hasPendingRequests,
};
};
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { ChatItem } from "../../../types";
import { Notification } from "../../../types";

export const checkIfHasPendingRequest = (chatItems: ChatItem[]): boolean => {
return chatItems.some(
(item) =>
item.item_type === "NOTIFICATION" && item.body.status === "Pending"
);
export const checkIfHasPendingRequest = (
notifications: Notification[]
): boolean => {
return notifications.some((item) => item.status === "Pending");
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { useChatContext } from "@/lib/context";

import { ChatDialogue } from "./components/ChatDialogue";
import { ShortCuts } from "./components/ShortCuts";
import { getMergedChatMessagesWithDoneStatusNotificationsReduced } from "./utils/getMergedChatMessagesWithDoneStatusNotificationsReduced";

export const ChatDialogueArea = (): JSX.Element => {
const { messages, notifications } = useChatContext();

const chatItems = getMergedChatMessagesWithDoneStatusNotificationsReduced(
messages,
notifications
);

const shouldDisplayShortcuts = chatItems.length === 0;

if (!shouldDisplayShortcuts) {
return <ChatDialogue chatItems={chatItems} />;
}

return <ShortCuts />;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { render } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";

import { ChatMessage } from "@/app/chat/[chatId]/types";

import { ChatDialogue } from "..";
import { getMergedChatMessagesWithDoneStatusNotificationsReduced } from "../../../utils/getMergedChatMessagesWithDoneStatusNotificationsReduced";

vi.mock("@/lib/context/SupabaseProvider", () => ({
useSupabase: () => ({
session: {
user: {},
},
}),
}));

vi.mock("../hooks/useChatDialogue", () => ({
useChatDialogue: vi.fn(() => ({
chatListRef: vi.fn(),
})),
}));

describe("ChatDialogue", () => {
it("should render chat messages correctly", () => {
const messages: ChatMessage[] = [
{
assistant: "Test assistant message",
message_id: "123",
user_message: "Test user message",
prompt_title: "Test prompt name",
brain_name: "Test brain name",
chat_id: "",
message_time: "",
},
];
const chatItems = getMergedChatMessagesWithDoneStatusNotificationsReduced(
messages,
[]
);
const { getAllByTestId } = render(<ChatDialogue chatItems={chatItems} />);
expect(getAllByTestId("brain-tags")).toBeDefined();
expect(getAllByTestId("prompt-tags")).toBeDefined();
expect(getAllByTestId("chat-message-text")).toBeDefined();
});

it("should render placeholder text when history is empty", () => {
const { getByTestId } = render(<ChatDialogue chatItems={[]} />);

expect(getByTestId("empty-history-message")).toBeDefined();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { ChatItemWithGroupedNotifications } from "../../../../types";
import { ChatNotification } from "../ChatNotification/ChatNotification";
import { QADisplay } from "../QADisplay";

type ChatItemProps = {
content: ChatItemWithGroupedNotifications;
};
export const ChatItem = ({ content }: ChatItemProps): JSX.Element => {
if (content.item_type === "MESSAGE") {
return <QADisplay content={content.body} />;
}

return <ChatNotification content={content.body} />;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./ChatItem";
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { Notification } from "@/app/chat/[chatId]/types";

import { NotificationDisplayer } from "./components";

type NotificationProps = {
content: Notification[];
};

export const ChatNotification = ({
content,
}: NotificationProps): JSX.Element => {
return (
<div className="flex flex-col flex-1 p-3 rounded-xl bg-blue-50 max-w-[50%]">
{content.map((notification) => (
<NotificationDisplayer key={notification.id} content={notification} />
))}
</div>
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { Fragment, useState } from "react";
import { MdLink } from "react-icons/md";

import { Notification } from "@/app/chat/[chatId]/types";
import { getFileIcon } from "@/lib/helpers/getFileIcon";

import { NotificationMessage, notificationStatusToIcon } from "./types";

type NotificationDisplayerProps = {
content: Notification;
};

export const NotificationDisplayer = ({
content,
}: NotificationDisplayerProps): JSX.Element => {
const { message: nonParsedMessage, action } = content;
const [isHovered, setIsHovered] = useState(false);
if (nonParsedMessage === null || nonParsedMessage === undefined) {
return <Fragment />;
}

const { message, status, name } = JSON.parse(
nonParsedMessage.replace(/'/g, '"')
) as NotificationMessage;

return (
<>
<div
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
className="flex flex-row flex-1 gap-1 p-3 rounded-md items-center"
>
<span className="text-gray-400 mb-1 text-2xl">
{notificationStatusToIcon[status]}
</span>
<div className=" flex flex-row rounded-md bg-white p-3 flex-1">
<div className="flex flex-row items-center gap-1">
<div className="bg-gray-200 p-1 rounded-md items-center justify-center flex">
{action === "CRAWL" ? <MdLink /> : getFileIcon(name)}
</div>
<span className="text-md flex flex-1">{name}</span>
</div>
</div>
</div>
<div>{isHovered ? <div>{message}</div> : <div></div>}</div>
</>
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
export type NotificationMessage = {
message: string;
status: "warning" | "error" | "success";
name: string;
};
export const notificationStatusToIcon = {
warning: "⚠️",
error: "❌",
success: "✅",
};
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./NotificationDisplayer/NotificationDisplayer";
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { ChatMessage } from "@/app/chat/[chatId]/types";

import { MessageRow } from "./components";

type QADisplayProps = {
content: ChatMessage;
};
export const QADisplay = ({ content }: QADisplayProps): JSX.Element => {
const { assistant, message_id, user_message, brain_name, prompt_title } =
content;

return (
<>
<MessageRow
key={`user-${message_id}`}
speaker={"user"}
text={user_message}
promptName={prompt_title}
brainName={brain_name}
/>
<MessageRow
key={`assistant-${message_id}`}
speaker={"assistant"}
text={assistant}
brainName={brain_name}
promptName={prompt_title}
/>
</>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,16 @@ import { cn } from "@/lib/utils";
import { QuestionBrain } from "./components/QuestionBrain";
import { QuestionPrompt } from "./components/QuestionPrompt";

type ChatMessageProps = {
type MessageRowProps = {
speaker: string;
text: string;
brainName?: string | null;
promptName?: string | null;
};

export const ChatMessage = React.forwardRef(
export const MessageRow = React.forwardRef(
(
{ speaker, text, brainName, promptName }: ChatMessageProps,
{ speaker, text, brainName, promptName }: MessageRowProps,
ref: React.Ref<HTMLDivElement>
) => {
const isUserSpeaker = speaker === "user";
Expand Down Expand Up @@ -52,4 +52,4 @@ export const ChatMessage = React.forwardRef(
}
);

ChatMessage.displayName = "ChatMessage";
MessageRow.displayName = "MessageRow";
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./MessageRow";
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./MessageRow";
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from "./QADisplay";
export * from "./components/MessageRow/MessageRow";
Loading