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

build: release candidate #53

Merged
merged 3 commits into from
Sep 4, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
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
14 changes: 14 additions & 0 deletions apps/nextjs/src/components/AppComponents/Chat/Chat/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,20 @@
import { type LooseLessonPlan } from "@oakai/aila/src/protocol/schema";
import { type Message } from "ai/react";

export function findMessageIdFromContent({ content }: { content: string }) {
return content
.split(`␞`)
.map((s) => {
try {
return JSON.parse(s.trim());
} catch (e) {
// ignore invalid JSON
return null;
}
})
.find((i) => i?.type === "id")?.value;
}

export function findLatestServerSideState(workingMessages: Message[]) {
console.log("Finding latest server-side state", { workingMessages });
const lastMessage = workingMessages[workingMessages.length - 1];
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 @@ -4,8 +4,8 @@ import { LooseLessonPlan } from "@oakai/aila/src/protocol/schema";
import { sectionToMarkdown } from "@oakai/aila/src/protocol/sectionToMarkdown";
import { lessonSectionTitlesAndMiniDescriptions } from "data/lessonSectionTitlesAndMiniDescriptions";

import { sectionTitle } from "./chat-dropdownsection";
import { notEmpty } from "./chat-lessonPlanDisplay";
import { sectionTitle } from "./drop-down-section";
import { MemoizedReactMarkdownWithStyles } from "./markdown";

const LessonPlanMapToMarkDown = ({
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 Expand Up @@ -221,6 +220,7 @@ function ChatMessagePart({
text: TextMessagePart,
action: ActionMessagePart,
moderation: ModerationMessagePart,
id: IdMessagePart,
}[part.type];

if (!PartComponent) {
Expand Down Expand Up @@ -282,6 +282,10 @@ function StateMessagePart({ part }: Readonly<{ part: StateDocument }>) {
return null;
}

function IdMessagePart() {
return null;
}

function ActionMessagePart({
// eslint-disable-next-line @typescript-eslint/no-unused-vars
part,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
CommentDocumentSchema,
ErrorDocument,
ErrorDocumentSchema,
MessageIdDocumentSchema,
ModerationDocument,
ModerationDocumentSchema,
PatchDocument,
Expand Down Expand Up @@ -54,6 +55,7 @@ export function parseMessageParts(content: string): MessagePart[] {
action: ActionDocumentSchema,
text: TextDocumentSchema,
bad: BadDocumentSchema,
id: MessageIdDocumentSchema,
};

const parts = extractMessageParts(content)
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 @@ -131,7 +131,7 @@ const ChatRightHandSideLesson = ({
});
}}
>
<LessonPlanProgressBar lessonPlan={lessonPlan} />
<LessonPlanProgressBar />
</button>

<div className="w-full pt-9 sm:pt-20">
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,38 @@
import { sectionToMarkdown } from "@oakai/aila/src/protocol/sectionToMarkdown";
import { OakFlex } from "@oaknational/oak-components";
import { lessonSectionTitlesAndMiniDescriptions } from "data/lessonSectionTitlesAndMiniDescriptions";

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

const ChatSection = ({
objectKey,
value,
}: {
objectKey: string;
value: unknown;
}) => {
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={sectionTitle(objectKey)}
sectionContent={
lessonSectionTitlesAndMiniDescriptions[objectKey]?.description
}
/>
<FlagButton />
</OakFlex>
</OakFlex>
);
};

export default ChatSection;
Loading
Loading