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(feedback): chat and message level feedback #20

Merged
merged 24 commits into from
Sep 3, 2024
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
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
2 changes: 1 addition & 1 deletion apps/nextjs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
"@oakai/exports": "*",
"@oakai/logger": "*",
"@oakai/prettier-config": "*",
"@oaknational/oak-components": "^1.0.0",
"@oaknational/oak-components": "^1.26.0",
"@oaknational/oak-consent-client": "^2.1.0",
"@prisma/client": "^5.13.0",
"@prisma/extension-accelerate": "^1.0.0",
Expand Down
64 changes: 10 additions & 54 deletions apps/nextjs/src/app/actions.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,9 @@
"use server";

import { auth } from "@clerk/nextjs/server";
import {
AilaPersistedChat,
AilaPersistedChatWithMissingMessageIds,
chatSchema,
chatSchemaWithMissingMessageIds,
} from "@oakai/aila/src/protocol/schema";
import { AilaPersistedChat, chatSchema } from "@oakai/aila/src/protocol/schema";
import { Prisma, prisma } from "@oakai/db";
import * as Sentry from "@sentry/nextjs";
import { nanoid } from "nanoid";

function assertChatMessageIdsAreUniqueWithinTheScopeOfThisChat(
chat: AilaPersistedChatWithMissingMessageIds,
): boolean {
let updated = false;
const usedIds = new Set<string>();
chat.messages = chat.messages.map((message) => {
if (!message.id || usedIds.has(message.id)) {
let newId = nanoid(16);
while (usedIds.has(newId)) {
newId = nanoid(16);
}
message.id = newId;
updated = true;
}
usedIds.add(message.id);
return message;
});
return updated;
}

function parseChatAndReportError({
sessionOutput,
Expand All @@ -39,11 +13,11 @@ function parseChatAndReportError({
sessionOutput: Prisma.JsonValue;
id: string;
userId: string;
}) {
}): AilaPersistedChat | undefined {
if (typeof sessionOutput !== "object") {
throw new Error(`sessionOutput is not an object`);
}
const parseResult = chatSchemaWithMissingMessageIds.safeParse({
const parseResult = chatSchema.safeParse({
...sessionOutput,
userId,
id,
Expand All @@ -67,9 +41,6 @@ function parseChatAndReportError({
export async function getChatById(
id: string,
): Promise<AilaPersistedChat | null> {
let chat: AilaPersistedChatWithMissingMessageIds | undefined = undefined;
let chatWithMessageIds: AilaPersistedChat | undefined = undefined;

const session = await prisma?.appSession.findUnique({
where: { id },
});
Expand All @@ -78,28 +49,13 @@ export async function getChatById(
return null;
}

chat = parseChatAndReportError({
id,
sessionOutput: session.output,
userId: session.userId,
});

if (chat) {
// Check if messages have IDs. If not, assign them and update the chat.
// This is a migration step that should be removed after all chats have unique IDs.
const updated = assertChatMessageIdsAreUniqueWithinTheScopeOfThisChat(chat);

chatWithMessageIds = chatSchema.parse(chat);
if (updated) {
await prisma?.appSession.update({
where: { id },
data: { output: chatWithMessageIds },
});
}
return chatWithMessageIds;
}

return null;
return (
parseChatAndReportError({
id,
sessionOutput: session.output,
userId: session.userId,
}) || null
);
}

export async function getChatForAuthenticatedUser(
Expand Down
2 changes: 2 additions & 0 deletions apps/nextjs/src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ export default function RootLayout({ children }: Readonly<RootLayoutProps>) {
<CookieConsentProvider>
<AnalyticsProvider
avoOptions={{
webDebugger: false,
inspector: undefined,
mantagen marked this conversation as resolved.
Show resolved Hide resolved
webDebuggerOptions: {
position: WebDebuggerPosition.BottomLeft({
bottom: 0,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { cva } from "class-variance-authority";
import { useLessonChat } from "@/components/ContextProviders/ChatProvider";

import Skeleton from "../common/Skeleton";
import DropDownSection from "./chat-dropdownsection";
import DropDownSection from "./drop-down-section";
import { GuidanceRequired } from "./guidance-required";

// @todo move these somewhere more sensible
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import { useRef } from "react";

import { LooseLessonPlan } from "@oakai/aila/src/protocol/schema";
import { sectionToMarkdown } from "@oakai/aila/src/protocol/sectionToMarkdown";
import { humanizeCamelCaseString } from "@oakai/core/src/utils/humanizeCamelCaseString";
import { lessonSectionTitlesAndMiniDescriptions } from "data/lessonSectionTitlesAndMiniDescriptions";

import { humanizeCamelCaseString } from "./chat-dropdownsection";
import { notEmpty } from "./chat-lessonPlanDisplay";
import { MemoizedReactMarkdownWithStyles } from "./markdown";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
// @see https://github.com/mckaywrigley/chatbot-ui/blob/main/components/Chat/ChatMessage.tsx
import { ReactNode, useState } from "react";

import { getMessageId } from "@oakai/aila/src/helpers/chat/getMessageId";
import {
ActionDocument,
BadDocument,
Expand Down Expand Up @@ -62,7 +61,7 @@ export function ChatMessage({
| PersistedModerationBase
| undefined;

const messageId = getMessageId(message);
const messageId = message.id;

const matchingPersistedModeration: PersistedModerationBase | undefined =
persistedModerations.find((m) => m.messageId === messageId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ export function ChatPanel({
});

await append({
id,
content: value,
role: "user",
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,6 @@ const QuickActionButtons = ({ isEmptyScreen }: QuickActionButtonsProps) => {
trackEvent("chat:continue");
lessonPlanTracking.onClickContinue();
await append({
id,
content: "Continue",
role: "user",
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ const ChatStartAccordion = () => {
</AccordionItem>
<AccordionItem value="item-4">
<div className="flex w-full items-center justify-between ">
<span className="flex w-full items-center gap-10 text-base font-bold">
<span className="flex w-full items-center gap-10 text-left text-base font-bold">
<LessonIcon />1 worksheet
</span>
</div>
Expand Down Expand Up @@ -174,7 +174,7 @@ const AccordionTrigger = React.forwardRef<
{...props}
className="flex w-full items-center justify-between "
>
<span className="flex w-full items-center gap-10 text-base font-bold">
<span className="flex w-full items-center gap-10 text-left text-base font-bold">
{children}
</span>
<Icon icon="chevron-down" size="sm" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { useState } from "react";

import {
OakBox,
OakSmallSecondaryButton,
OakTooltip,
} from "@oaknational/oak-components";
import styled from "styled-components";

const ActionButton = ({
children,
onClick,
tooltip,
}: {
children: React.ReactNode;
onClick: () => void;
tooltip: string;
}) => {
const [showTooltip, setShowTooltip] = useState(false);

return (
<OakTooltip
tooltip={tooltip}
tooltipPosition="top-left"
isOpen={showTooltip}
$background="black"
$color="white"
>
<OakBox
onMouseEnter={async () => {
await waitThenExecute(0).then(() => {
setShowTooltip(true);
});
}}
onMouseLeave={() => {
setShowTooltip(false);
}}
>
<OakSmallSecondaryWithOpaqueBorder onClick={onClick}>
{children}
</OakSmallSecondaryWithOpaqueBorder>
</OakBox>
</OakTooltip>
);
};

const OakSmallSecondaryWithOpaqueBorder = styled(OakSmallSecondaryButton)`
button {
border-color: rgba(0, 0, 0, 0.3);
}
`;

async function waitThenExecute(ms: number) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}

export default ActionButton;
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { sectionToMarkdown } from "@oakai/aila/src/protocol/sectionToMarkdown";
import { humanizeCamelCaseString } from "@oakai/core/src/utils/humanizeCamelCaseString";
import { OakFlex } from "@oaknational/oak-components";
import { lessonSectionTitlesAndMiniDescriptions } from "data/lessonSectionTitlesAndMiniDescriptions";

import { MemoizedReactMarkdownWithStyles } from "../markdown";
import FlagButton from "./flag-button";
import ModifyButton from "./modify-button";

const ChatSection = ({
objectKey,
value,
}: {
objectKey: string;
mantagen marked this conversation as resolved.
Show resolved Hide resolved
// eslint-disable-next-line @typescript-eslint/no-explicit-any
value: any;
}) => {
return (
<OakFlex $flexDirection="column">
<MemoizedReactMarkdownWithStyles
lessonPlanSectionDescription={
lessonSectionTitlesAndMiniDescriptions[objectKey]?.description
}
markdown={`${sectionToMarkdown(objectKey, value)}`}
/>
<OakFlex $gap="all-spacing-3" $mt="space-between-s" $position="relative">
<ModifyButton
section={humanizeCamelCaseString(objectKey)}
sectionContent={
lessonSectionTitlesAndMiniDescriptions[objectKey]?.description
}
/>
<FlagButton />
</OakFlex>
</OakFlex>
);
};

export default ChatSection;
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { useEffect, useRef } from "react";

import {
OakBox,
OakFlex,
OakP,
OakSmallPrimaryButton,
} from "@oaknational/oak-components";

export const DropDownFormWrapper = ({
children,
onClickActions,
setIsOpen,
selectedRadio,
title,
buttonText,
isOpen,
dropdownRef,
}: {
children: React.ReactNode;
onClickActions: (option: string) => void;
setIsOpen: (value: boolean) => void;
selectedRadio: string | null;
title: string;
buttonText: string;
isOpen: boolean;
dropdownRef: React.RefObject<HTMLDivElement>;
}) => {
const firstButtonRef = useRef<HTMLButtonElement>(null);
useEffect(() => {
if (isOpen && firstButtonRef.current) {
firstButtonRef.current.focus();
}

const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") {
setIsOpen(false);
}
};

const handleClickOutside = (event: MouseEvent) => {
if (
dropdownRef.current &&
!dropdownRef.current.contains(event.target as Node)
) {
setIsOpen(false);
}
};

document.addEventListener("keydown", handleKeyDown);
document.addEventListener("mousedown", handleClickOutside);

return () => {
document.removeEventListener("keydown", handleKeyDown);
document.removeEventListener("mousedown", handleClickOutside);
};
}, [isOpen]);

return (
<form
onSubmit={(e) => {
e.preventDefault();
if (selectedRadio) {
onClickActions(selectedRadio);
}
setIsOpen(false);
}}
>
<OakFlex
$ba="border-solid-m"
$borderRadius="border-radius-m"
$pa="inner-padding-l"
$flexDirection="column"
$position="absolute"
$top="all-spacing-7"
$background="white"
$width="all-spacing-21"
$zIndex={100}
$gap="space-between-m"
$borderColor="border-neutral-lighter"
$dropShadow="drop-shadow-standard"
>
<OakP $font="heading-6">{title}</OakP>
{children}
<OakBox>
<OakSmallPrimaryButton>{buttonText}</OakSmallPrimaryButton>
</OakBox>
</OakFlex>
</form>
);
};

export default DropDownFormWrapper;
Loading
Loading