Skip to content

The Open Standard for Generative UI

Copilot shell + fixes (#86)

abhithesyscc0567644bf2
diff --git a/js/package.json b/js/package.json
index 655b1e2ca..8dc16cccf 100644
--- a/js/package.json
+++ b/js/package.json
@@ -1,7 +1,7 @@
{
"name": "js",
"version": "1.0.0",
- "description": "",
+ "description": "Monorepo for Crayon's JavaScript packages. See https://crayonai.org for more information.",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
@@ -20,7 +20,6 @@
"prettier-plugin-organize-imports": "^3.2.4"
},
"keywords": [],
- "author": "",
- "license": "ISC",
- "packageManager": "[email protected]+sha512.b2dc20e2fc72b3e18848459b37359a32064663e5627a51e4c74b2c29dd8e8e0491483c3abb40789cfd578bf362fb6ba8261b05f0387d76792ed6e23ea3b1b6a0"
+ "author": "[email protected]",
+ "license": "MIT"
}
diff --git a/js/packages/react-core/package.json b/js/packages/react-core/package.json
index 1a8eb8741..0218a8423 100644
--- a/js/packages/react-core/package.json
+++ b/js/packages/react-core/package.json
@@ -1,6 +1,6 @@
{
"name": "@crayonai/react-core",
- "version": "0.6.0",
+ "version": "0.6.1",
"description": "Generative UI SDK",
"license": "MIT",
"main": "dist/index.js",
diff --git a/js/packages/react-core/src/hooks/useThreadState.ts b/js/packages/react-core/src/hooks/useThreadState.ts
index b3960bc9d..d7d8e5b79 100644
--- a/js/packages/react-core/src/hooks/useThreadState.ts
+++ b/js/packages/react-core/src/hooks/useThreadState.ts
@@ -12,6 +12,7 @@ export const useThreadState = (): ThreadState => {
const { threadManager } = useChatContext();
return {
+ isLoadingMessages: useStore(threadManager, (store) => store.isLoadingMessages),
isRunning: useStore(threadManager, (store) => store.isRunning),
messages: useStore(threadManager, (store) => store.messages),
error: useStore(threadManager, (store) => store.error),
diff --git a/js/packages/react-core/src/internal/useThreadManagerStore.ts b/js/packages/react-core/src/internal/useThreadManagerStore.ts
index 8bbcad827..715a394c1 100644
--- a/js/packages/react-core/src/internal/useThreadManagerStore.ts
+++ b/js/packages/react-core/src/internal/useThreadManagerStore.ts
@@ -10,6 +10,7 @@ export const useThreadManagerStore = (inputThreadManager: ThreadManager) => {
const [threadManagerStore] = useState(() =>
create<ThreadManager>(() => ({
+ isLoadingMessages: inputThreadManager.isLoadingMessages,
isRunning: inputThreadManager.isRunning,
messages: inputThreadManager.messages,
error: inputThreadManager.error,
@@ -28,8 +29,14 @@ export const useThreadManagerStore = (inputThreadManager: ThreadManager) => {
isRunning: inputThreadManager.isRunning,
messages: inputThreadManager.messages,
error: inputThreadManager.error,
+ isLoadingMessages: inputThreadManager.isLoadingMessages,
});
- }, [inputThreadManager.isRunning, inputThreadManager.messages, inputThreadManager.error]);
+ }, [
+ inputThreadManager.isRunning,
+ inputThreadManager.messages,
+ inputThreadManager.error,
+ inputThreadManager.isLoadingMessages,
+ ]);
if (inputThreadManagerRef.current.responseTemplates !== inputThreadManager.responseTemplates) {
throw new Error("memoize response templates");
diff --git a/js/packages/react-core/src/types/chatManager.ts b/js/packages/react-core/src/types/chatManager.ts
index 15cea00d5..5b7af9a51 100644
--- a/js/packages/react-core/src/types/chatManager.ts
+++ b/js/packages/react-core/src/types/chatManager.ts
@@ -33,6 +33,8 @@ export type ThreadActions = {
export type ThreadState = {
/** Indicates if the thread is currently processing and controls should be disabled */
isRunning?: boolean | undefined;
+ /** Indicates if the messages are currently loading */
+ isLoadingMessages: boolean | undefined;
messages: Message[];
error: Error | null | undefined;
responseTemplates: {
diff --git a/js/packages/react-core/src/useThreadListManager.ts b/js/packages/react-core/src/useThreadListManager.ts
index 9247e60f5..672172c55 100644
--- a/js/packages/react-core/src/useThreadListManager.ts
+++ b/js/packages/react-core/src/useThreadListManager.ts
@@ -50,13 +50,7 @@ export const useThreadListManager = (props: Props): DefaultManager => {
.fetchThreadList()
.then((threads) => {
const existingThreads = store.getState().threads;
- const newThreads = threads.filter(
- (t) => !existingThreads.some((t2) => t2.threadId === t.threadId),
- );
- // we merge the existing threads so that if a thread is created while the fetching is in progress
- // it won't be removed
- const updatedThreads = [...existingThreads, ...newThreads];
- set({ isLoading: false, threads: updatedThreads });
+ set({ isLoading: false, threads: mergeThreadList(existingThreads, threads) });
})
.catch((e) => {
set({ isLoading: false, error: e });
@@ -65,7 +59,7 @@ export const useThreadListManager = (props: Props): DefaultManager => {
createThread: async (firstMessage: UserMessage) => {
const thread = await propsRef.current.createThread(firstMessage);
set((state) => ({
- threads: [thread, ...state.threads],
+ threads: mergeThreadList(state.threads, [thread]),
}));
return thread;
},
@@ -106,3 +100,9 @@ export const useThreadListManager = (props: Props): DefaultManager => {
return useStore(store);
};
+
+const mergeThreadList = (existingThreads: Thread[], newThreads: Thread[]) => {
+ return Array.from(
+ new Map([...existingThreads, ...newThreads].map((t) => [t.threadId, t])).values(),
+ ).sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
+};
diff --git a/js/packages/react-core/src/useThreadManager.ts b/js/packages/react-core/src/useThreadManager.ts
index 154bad284..22a68aea1 100644
--- a/js/packages/react-core/src/useThreadManager.ts
+++ b/js/packages/react-core/src/useThreadManager.ts
@@ -29,6 +29,7 @@ export const useThreadManager = (props: Props): ThreadManager => {
error: null,
abortController: null,
isRunning: false,
+ isLoadingMessages: false,
setMessages: (messages: Message[]) => {
set({ messages });
},
@@ -51,7 +52,7 @@ export const useThreadManager = (props: Props): ThreadManager => {
const newMessages = await propsRef.current.onProcessMessage({
message,
threadManager: store.getState(),
- abortController: new AbortController(),
+ abortController,
});
store.getState().appendMessages(...newMessages);
@@ -97,8 +98,7 @@ export const useThreadManager = (props: Props): ThreadManager => {
store.setState({ messages: [] });
if (threadId) {
- const abortController = new AbortController();
- store.setState({ abortController, isRunning: true });
+ store.setState({ isLoadingMessages: true });
props
.loadThread(threadId)
.then((messages) => {
@@ -108,7 +108,7 @@ export const useThreadManager = (props: Props): ThreadManager => {
store.setState({ error });
})
.finally(() => {
- store.setState({ abortController: null, isRunning: false });
+ store.setState({ isLoadingMessages: false });
});
}
}, [props.threadId, props.shouldResetThreadState]);
diff --git a/js/packages/react-ui/.storybook/main.ts b/js/packages/react-ui/.storybook/main.ts
index fb5462dbf..87f72e4c5 100644
--- a/js/packages/react-ui/.storybook/main.ts
+++ b/js/packages/react-ui/.storybook/main.ts
@@ -34,15 +34,16 @@ const config: StorybookConfig = {
resolve: {
alias: {
"@crayonai/react-core": path.resolve(__dirname, "../../react-core/src/index.ts"),
+ "@crayonai/stream": path.resolve(__dirname, "../../stream/src/index.ts"),
},
},
optimizeDeps: {
- exclude: ["@crayonai/react-core"],
+ exclude: ["@crayonai/react-core", "@crayonai/stream"],
include: ["react", "react-dom"],
},
build: {
commonjsOptions: {
- include: [/@crayonai\/react-core/, /node_modules/],
+ include: [/@crayonai\/react-core/, /node_modules/, /@crayonai\/stream/],
},
},
});
diff --git a/js/packages/react-ui/src/components/CopilotShell/Container.tsx b/js/packages/react-ui/src/components/CopilotShell/Container.tsx
new file mode 100644
index 000000000..0a0587ab4
--- /dev/null
+++ b/js/packages/react-ui/src/components/CopilotShell/Container.tsx
@@ -0,0 +1,20 @@
+import clsx from "clsx";
+import { LayoutContextProvider } from "../../context/LayoutContext";
+import { ShellStoreProvider } from "../Shell/store";
+
+interface ContainerProps {
+ children?: React.ReactNode;
+ logoUrl: string;
+ agentName: string;
+ className?: string;
+}
+
+export const Container = ({ children, logoUrl, agentName, className }: ContainerProps) => {
+ return (
+ <ShellStoreProvider logoUrl={logoUrl} agentName={agentName}>
+ <LayoutContextProvider layout="tray">
+ <div className={clsx("crayon-copilot-shell-container", className)}>{children}</div>
+ </LayoutContextProvider>
+ </ShellStoreProvider>
+ );
+};
diff --git a/js/packages/react-ui/src/components/CopilotShell/Header.tsx b/js/packages/react-ui/src/components/CopilotShell/Header.tsx
new file mode 100644
index 000000000..dd98297c2
--- /dev/null
+++ b/js/packages/react-ui/src/components/CopilotShell/Header.tsx
@@ -0,0 +1,18 @@
+import clsx from "clsx";
+import { useShellStore } from "../Shell/store";
+
+export const Header = ({ className }: { className?: string }) => {
+ const { logoUrl, agentName } = useShellStore((state) => ({
+ logoUrl: state.logoUrl,
+ agentName: state.agentName,
+ }));
+
+ return (
+ <div className={clsx("crayon-copilot-shell-header", className)}>
+ <div className="crayon-copilot-shell-header-logo-container">
+ <img className="crayon-copilot-shell-header-logo" src={logoUrl} alt="Logo" />
+ <span className="crayon-copilot-shell-header-agent-name">{agentName}</span>
+ </div>
+ </div>
+ );
+};
diff --git a/js/packages/react-ui/src/components/CopilotShell/Thread.tsx b/js/packages/react-ui/src/components/CopilotShell/Thread.tsx
new file mode 100644
index 000000000..c7af079ee
--- /dev/null
+++ b/js/packages/react-ui/src/components/CopilotShell/Thread.tsx
@@ -0,0 +1,244 @@
+import {
+ Message,
+ MessageProvider,
+ useThreadActions,
+ useThreadManagerSelector,
+ useThreadState,
+} from "@crayonai/react-core";
+import clsx from "clsx";
+import { ArrowRight, Square } from "lucide-react";
+import React, { memo, useLayoutEffect, useRef } from "react";
+import { useComposerState } from "../../hooks/useComposerState";
+import { useScrollToBottom } from "../../hooks/useScrollToBottom";
+import { IconButton } from "../IconButton";
+import { MessageLoading as MessageLoadingComponent } from "../MessageLoading";
+
+export const ThreadContainer = ({
+ children,
+ className,
+}: {
+ children?: React.ReactNode;
+ className?: string;
+}) => {
+ return <div className={clsx("crayon-copilot-shell-thread-container", className)}>{children}</div>;
+};
+
+export const ScrollArea = ({
+ children,
+ className,
+ scrollVariant = "always",
+ userMessageSelector,
+}: {
+ children?: React.ReactNode;
+ className?: string;
+ /**
+ * Scroll to bottom once the last message is added
+ */
+ scrollVariant?: "always" | "once" | "user-message-anchor";
+ /**
+ * Selector for the user message
+ */
+ userMessageSelector?: string;
+}) => {
+ const ref = useRef<HTMLDivElement>(null);
+ const { messages, isRunning } = useThreadState();
+
+ useScrollToBottom({
+ ref,
+ lastMessage: messages[messages.length - 1] || { id: "" },
+ scrollVariant,
+ userMessageSelector,
+ isRunning,
+ });
+
+ return (
+ <div ref={ref} className={clsx("crayon-copilot-shell-thread-scroll-area", className)}>
+ {children}
+ </div>
+ );
+};
+
+const FallbackTemplate = ({ name, templateProps }: { name: string; templateProps: any }) => {
+ return (
+ <div>
+ Unable to render template: {name} with props:
+ {JSON.stringify(templateProps)}
+ </div>
+ );
+};
+
+const DefaultTextRenderer = ({
+ children,
+ className,
+}: {
+ children: React.ReactNode;
+ className?: string;
+}) => {
+ return <div className={className}>{children}</div>;
+};
+
+export const AssistantMessageContainer = ({
+ children,
+ className,
+}: {
+ children?: React.ReactNode;
+ className?: string;
+}) => {
+ return (
+ <div className={clsx("crayon-copilot-shell-thread-message-assistant", className)}>
+ <div className="crayon-copilot-shell-thread-message-assistant__content">{children}</div>
+ </div>
+ );
+};
+
+export const UserMessageContainer = ({
+ children,
+ className,
+}: {
+ children?: React.ReactNode;
+ className?: string;
+}) => {
+ return (
+ <div className={clsx("crayon-copilot-shell-thread-message-user", className)}>
+ <div className="crayon-copilot-shell-thread-message-user__content">{children}</div>
+ </div>
+ );
+};
+
+export const RenderMessage = memo(
+ ({ message, className }: { message: Message; className?: string }) => {
+ const responseTemplates = useThreadManagerSelector((store) => store.responseTemplates);
+ const MessageContainer =
+ message.role === "user" ? UserMessageContainer : AssistantMessageContainer;
+
+ if (message.role === "assistant") {
+ return (
+ <MessageContainer className={className}>
+ {message.message?.map((stringOrTemplate, i) => {
+ if (stringOrTemplate.type === "text") {
+ const TextRenderer = responseTemplates["text"]?.Component || DefaultTextRenderer;
+
+ return (
+ <TextRenderer
+ key={i}
+ className="crayon-copilot-shell-thread-message-assistant__text"
+ >
+ {stringOrTemplate.text}
+ </TextRenderer>
+ );
+ }
+
+ const Template = responseTemplates[stringOrTemplate.name];
+ const Fallback = responseTemplates["fallback"]?.Component || FallbackTemplate;
+ return Template ? (
+ <Template.Component key={i} {...stringOrTemplate.templateProps} />
+ ) : (
+ <Fallback
+ key={i}
+ name={stringOrTemplate.name}
+ templateProps={stringOrTemplate.templateProps}
+ />
+ );
+ })}
+ </MessageContainer>
+ );
+ }
+
+ return <MessageContainer>{message.message}</MessageContainer>;
+ },
+);
+
+export const MessageLoading = () => {
+ const { isRunning } = useThreadState();
+
+ if (!isRunning) {
+ return null;
+ }
+
+ return (
+ <div className="crayon-copilot-shell-thread-message-loading">
+ <MessageLoadingComponent />
+ </div>
+ );
+};
+
+export const Messages = ({
+ className,
+ loader,
+}: {
+ className?: string;
+ loader?: React.ReactNode;
+}) => {
+ const { messages } = useThreadState();
+
+ return (
+ <div className={clsx("crayon-copilot-shell-thread-messages", className)}>
+ {messages.map((message) => {
+ if (message.isVisuallyHidden) {
+ return null;
+ }
+ return (
+ <MessageProvider key={message.id} message={message}>
+ <RenderMessage message={message} />
+ </MessageProvider>
+ );
+ })}
+ {loader}
+ </div>
+ );
+};
+
+export const Composer = ({ className }: { className?: string }) => {
+ const { textContent, setTextContent } = useComposerState();
+ const { processMessage, onCancel } = useThreadActions();
+ const { isRunning } = useThreadState();
+ const inputRef = useRef<HTMLTextAreaElement>(null);
+
+ const handleSubmit = () => {
+ if (!textContent.trim() || isRunning) {
+ return;
+ }
+
+ processMessage({
+ type: "prompt",
+ role: "user",
+ message: textContent,
+ });
+
+ setTextContent("");
+ };
+
+ useLayoutEffect(() => {
+ const input = inputRef.current;
+ if (!input) {
+ return;
+ }
+
+ input.style.height = "0px";
+ input.style.height = `${input.scrollHeight}px`;
+ }, [textContent]);
+
+ return (
+ <div className={clsx("crayon-copilot-shell-thread-composer", className)}>
+ <div className="crayon-copilot-shell-thread-composer__input-wrapper">
+ <textarea
+ ref={inputRef}
+ value={textContent}
+ onChange={(e) => setTextContent(e.target.value)}
+ className="crayon-copilot-shell-thread-composer__input"
+ placeholder="Type your message..."
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && !e.shiftKey) {
+ e.preventDefault();
+ handleSubmit();
+ }
+ }}
+ />
+ <IconButton
+ onClick={isRunning ? onCancel : handleSubmit}
+ icon={isRunning ? <Square size="1em" fill="currentColor" /> : <ArrowRight size="1em" />}
+ />
+ </div>
+ </div>
+ );
+};
diff --git a/js/packages/react-ui/src/components/CopilotShell/copilotShell.scss b/js/packages/react-ui/src/components/CopilotShell/copilotShell.scss
new file mode 100644
index 000000000..16c7f0c47
--- /dev/null
+++ b/js/packages/react-ui/src/components/CopilotShell/copilotShell.scss
@@ -0,0 +1,20 @@
+@use "../../cssUtils" as cssUtils;
+@use "./thread.scss";
+@use "./header.scss";
+
+.crayon-copilot-shell-container {
+ display: flex;
+ position: relative;
+ height: 100dvh;
+ width: 530px;
+ overflow: hidden;
+
+ border: 1px solid cssUtils.$stroke-default;
+ border-width: 0 1px;
+
+ background: cssUtils.$chat-container-bg;
+ box-sizing: border-box;
+ & * {
+ box-sizing: border-box;
+ }
+}
diff --git a/js/packages/react-ui/src/components/CopilotShell/dependencies.ts b/js/packages/react-ui/src/components/CopilotShell/dependencies.ts
new file mode 100644
index 000000000..3028df8d3
--- /dev/null
+++ b/js/packages/react-ui/src/components/CopilotShell/dependencies.ts
@@ -0,0 +1,5 @@
+import buttonDeps from "../Button/dependencies";
+import iconButtonDeps from "../IconButton/dependencies";
+
+const dependencies = ["Shell", ...iconButtonDeps, ...buttonDeps];
+export default dependencies;
diff --git a/js/packages/react-ui/src/components/CopilotShell/header.scss b/js/packages/react-ui/src/components/CopilotShell/header.scss
new file mode 100644
index 000000000..e570524a0
--- /dev/null
+++ b/js/packages/react-ui/src/components/CopilotShell/header.scss
@@ -0,0 +1,28 @@
+@use "../../cssUtils" as cssUtils;
+
+.crayon-copilot-shell-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: cssUtils.$spacing-m cssUtils.$spacing-l;
+ border-bottom: 1px solid cssUtils.$stroke-default;
+ background-color: cssUtils.$bg-container;
+}
+
+.crayon-copilot-shell-header-logo-container {
+ display: flex;
+ align-items: center;
+ gap: cssUtils.$spacing-s;
+ @include cssUtils.typography(title, medium);
+}
+
+.crayon-copilot-shell-header-logo {
+ width: 32px;
+ height: 32px;
+ border-radius: cssUtils.$rounded-m;
+}
+
+.crayon-copilot-shell-header-agent-name {
+ @include cssUtils.typography(title, medium);
+ color: cssUtils.$primary-text;
+}
diff --git a/js/packages/react-ui/src/components/CopilotShell/index.ts b/js/packages/react-ui/src/components/CopilotShell/index.ts
new file mode 100644
index 000000000..f19ab917b
--- /dev/null
+++ b/js/packages/react-ui/src/components/CopilotShell/index.ts
@@ -0,0 +1,3 @@
+export * from "./Container";
+export * from "./Header";
+export * from "./Thread";
diff --git a/js/packages/react-ui/src/components/CopilotShell/stories/Shell.stories.tsx b/js/packages/react-ui/src/components/CopilotShell/stories/Shell.stories.tsx
new file mode 100644
index 000000000..0bab03593
--- /dev/null
+++ b/js/packages/react-ui/src/components/CopilotShell/stories/Shell.stories.tsx
@@ -0,0 +1,118 @@
+import {
+ ChatProvider,
+ Message,
+ useThreadListManager,
+ useThreadManager,
+} from "@crayonai/react-core";
+import {
+ Composer,
+ Container,
+ Header,
+ MessageLoading,
+ Messages,
+ ScrollArea,
+ ThreadContainer,
+} from "../../CopilotShell";
+// @ts-ignore
+import styles from "./style.module.scss";
+import logoUrl from "./thesysdev_logo.jpeg";
+
+export default {
+ title: "Copilot Shell",
+ tags: ["dev", "!autodocs"],
+};
+
+export const Default = {
+ render: (args: any) => {
+ const threadListManager = useThreadListManager({
+ createThread: async () => {
+ return {
+ threadId: crypto.randomUUID(),
+ title: "test",
+ createdAt: new Date(),
+ isRunning: false,
+ };
+ },
+ fetchThreadList: async () => {
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+ return [
+ {
+ threadId: "1",
+ title: "test",
+ createdAt: new Date(),
+ isRunning: false,
+ },
+ {
+ threadId: "2",
+ title: "test 2",
+ createdAt: new Date(),
+ isRunning: false,
+ },
+ {
+ threadId: "3",
+ title: "test 3",
+ createdAt: new Date(),
+ isRunning: false,
+ },
+ ];
+ },
+ deleteThread: async () => {},
+ updateThread: async (t) => t,
+ onSwitchToNew: () => {},
+ onSelectThread: () => {},
+ });
+
+ const threadManager = useThreadManager({
+ threadId: threadListManager.selectedThreadId,
+ loadThread: async () => {
+ return [
+ {
+ id: crypto.randomUUID(),
+ role: "user",
+ type: "prompt",
+ message: "Hello",
+ },
+ {
+ id: crypto.randomUUID(),
+ role: "assistant",
+ type: "response",
+ message: [{ type: "text", text: "Hello" }],
+ },
+ ];
+ },
+ onProcessMessage: async ({ message, threadManager, abortController }) => {
+ const newMessage = Object.assign({}, message, {
+ id: crypto.randomUUID(),
+ }) as Message;
+ threadManager.appendMessages(newMessage);
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+ return [
+ {
+ id: crypto.randomUUID(),
+ role: "assistant",
+ type: "response",
+ message: [{ type: "text", text: "sadfasdf" }],
+ },
+ ];
+ },
+ responseTemplates: [],
+ });
+
+ return (
+ <div className={styles.container}>
+ <div className={styles.left} />
+ <ChatProvider threadListManager={threadListManager} threadManager={threadManager}>
+ <Container logoUrl={logoUrl} agentName="Crayon">
+ <ThreadContainer>
+ <Header />
+ <ScrollArea>
+ <Messages loader={<MessageLoading />} />
+ </ScrollArea>
+ <Composer />
+ </ThreadContainer>
+ </Container>
+ </ChatProvider>
+ </div>
+ );
+ },
+};
diff --git a/js/packages/react-ui/src/components/CopilotShell/stories/style.module.scss b/js/packages/react-ui/src/components/CopilotShell/stories/style.module.scss
new file mode 100644
index 000000000..825d15490
--- /dev/null
+++ b/js/packages/react-ui/src/components/CopilotShell/stories/style.module.scss
@@ -0,0 +1,8 @@
+.container {
+ display: flex;
+}
+
+.left {
+ flex-grow: 1;
+ background: white;
+}
diff --git a/js/packages/react-ui/src/components/CopilotShell/stories/thesysdev_logo.jpeg b/js/packages/react-ui/src/components/CopilotShell/stories/thesysdev_logo.jpeg
new file mode 100644
index 000000000..755421486
Binary files /dev/null and b/js/packages/react-ui/src/components/CopilotShell/stories/thesysdev_logo.jpeg differ
diff --git a/js/packages/react-ui/src/components/CopilotShell/thread.scss b/js/packages/react-ui/src/components/CopilotShell/thread.scss
new file mode 100644
index 000000000..41581ea87
--- /dev/null
+++ b/js/packages/react-ui/src/components/CopilotShell/thread.scss
@@ -0,0 +1,93 @@
+@use "../../cssUtils" as cssUtils;
+
+.crayon-copilot-shell-thread-container {
+ flex: 1;
+ overflow: hidden;
+ display: flex;
+ flex-direction: column;
+}
+
+.crayon-copilot-shell-thread-scroll-area {
+ width: 100%;
+ flex: 1;
+ overflow: auto;
+ padding: cssUtils.$spacing-l;
+}
+
+.crayon-copilot-shell-thread-messages {
+ margin: 0 auto;
+ display: flex;
+ flex-direction: column;
+ gap: cssUtils.$spacing-xl;
+}
+
+.crayon-copilot-shell-thread-message-assistant {
+ width: 100%;
+ overflow: hidden;
+
+ // override theme variables so that other crayon components don't depend on chat colors
+ // this solves the case where the crayon-card component is used in the thread but without card component
+ --crayon-primary-text: #{cssUtils.$chat-assistant-response-text};
+ --crayon-container-fills: #{cssUtils.$chat-assistant-response-bg};
+
+ &__content {
+ display: flex;
+ flex-direction: column;
+ gap: cssUtils.$spacing-s;
+ overflow: hidden;
+ overflow-wrap: break-word;
+ flex-grow: 1;
+ }
+
+ &__text {
+ @include cssUtils.typography(primary, default);
+ color: cssUtils.$chat-assistant-response-text;
+ }
+}
+
+.crayon-copilot-shell-thread-message-user {
+ display: flex;
+ justify-content: flex-end;
+
+ &__content {
+ @include cssUtils.typography(primary, default);
+ padding: cssUtils.$spacing-m cssUtils.$spacing-l;
+ background-color: cssUtils.$chat-user-response-bg;
+ color: cssUtils.$chat-user-response-text;
+ border-radius: cssUtils.$rounded-2xl;
+ overflow-wrap: break-word;
+ max-width: 100%;
+ }
+}
+
+.crayon-copilot-shell-thread-composer {
+ width: 100%;
+ padding: cssUtils.$spacing-m cssUtils.$spacing-l cssUtils.$spacing-l;
+ background-color: cssUtils.$bg-container;
+
+ &__input-wrapper {
+ border: 1.256px solid cssUtils.$stroke-default;
+ display: flex;
+ align-items: flex-end;
+ gap: cssUtils.$spacing-s;
+ padding: cssUtils.$spacing-m;
+ border-radius: cssUtils.$rounded-l;
+ }
+
+ &__input {
+ flex-grow: 1;
+ padding: 0;
+ resize: none;
+ margin: auto 0px;
+ max-height: 154px;
+ outline: none;
+ border: none;
+ background: transparent;
+ overflow: hidden;
+ @include cssUtils.typography(primary, default);
+ color: cssUtils.$primary-text;
+ &::placeholder {
+ color: cssUtils.$disabled-text;
+ }
+ }
+}
diff --git a/js/packages/react-ui/src/components/CrayonChat/ComposedCopilot.tsx b/js/packages/react-ui/src/components/CrayonChat/ComposedCopilot.tsx
new file mode 100644
index 000000000..3005f6cbd
--- /dev/null
+++ b/js/packages/react-ui/src/components/CrayonChat/ComposedCopilot.tsx
@@ -0,0 +1,31 @@
+import {
+ Composer,
+ Container,
+ Header,
+ MessageLoading,
+ Messages,
+ ScrollArea,
+ ThreadContainer,
+} from "../CopilotShell";
+
+interface ComposedCopilotProps {
+ logoUrl?: string;
+ agentName?: string;
+}
+
+export const ComposedCopilot = ({
+ logoUrl = "https://crayonai.org/img/logo.png",
+ agentName = "My Agent",
+}: ComposedCopilotProps) => {
+ return (
+ <Container logoUrl={logoUrl} agentName={agentName}>
+ <ThreadContainer>
+ <Header />
+ <ScrollArea>
+ <Messages loader={<MessageLoading />} />
+ </ScrollArea>
+ <Composer />
+ </ThreadContainer>
+ </Container>
+ );
+};
diff --git a/js/packages/react-ui/src/components/CrayonChat/ComposedStandalone.tsx b/js/packages/react-ui/src/components/CrayonChat/ComposedStandalone.tsx
new file mode 100644
index 000000000..b7ca99a4d
--- /dev/null
+++ b/js/packages/react-ui/src/components/CrayonChat/ComposedStandalone.tsx
@@ -0,0 +1,45 @@
+import {
+ Composer,
+ Container,
+ MessageLoading,
+ Messages,
+ MobileHeader,
+ NewChatButton,
+ ScrollArea,
+ SidebarContainer,
+ SidebarContent,
+ SidebarHeader,
+ SidebarSeparator,
+ ThreadContainer,
+ ThreadList,
+} from "../Shell";
+
+interface ComposedStandaloneProps {
+ logoUrl?: string;
+ agentName?: string;
+}
+
+export const ComposedStandalone = ({
+ logoUrl = "https://crayonai.org/img/logo.png",
+ agentName = "My Agent",
+}: ComposedStandaloneProps) => {
+ return (
+ <Container logoUrl={logoUrl} agentName={agentName}>
+ <SidebarContainer>
+ <SidebarHeader />
+ <SidebarContent>
+ <NewChatButton />
+ <SidebarSeparator />
+ <ThreadList />
+ </SidebarContent>
+ </SidebarContainer>
+ <ThreadContainer>
+ <MobileHeader />
+ <ScrollArea>
+ <Messages loader={<MessageLoading />} />
+ </ScrollArea>
+ <Composer />
+ </ThreadContainer>
+ </Container>
+ );
+};
diff --git a/js/packages/react-ui/src/components/CrayonChat/CrayonChat.tsx b/js/packages/react-ui/src/components/CrayonChat/CrayonChat.tsx
index aca4583a1..21f71cb02 100644
--- a/js/packages/react-ui/src/components/CrayonChat/CrayonChat.tsx
+++ b/js/packages/react-ui/src/components/CrayonChat/CrayonChat.tsx
@@ -13,19 +13,9 @@ import {
} from "@crayonai/react-core";
import { useEffect, useRef } from "react";
import invariant from "tiny-invariant";
-import {
- Container,
- MobileHeader,
- NewChatButton,
- SidebarContainer,
- SidebarContent,
- SidebarHeader,
- SidebarSeparator,
- ThreadContainer,
-} from "../Shell";
-import { Composer, Messages, ScrollArea } from "../Shell/Thread";
-import { ThreadList } from "../Shell/ThreadList";
import { ThemeProvider } from "../ThemeProvider";
+import { ComposedCopilot } from "./ComposedCopilot";
+import { ComposedStandalone } from "./ComposedStandalone";
interface CrayonChatProps {
processMessage?: (params: {
@@ -39,6 +29,7 @@ interface CrayonChatProps {
logoUrl?: string;
agentName?: string;
responseTemplates?: ResponseTemplate[];
+ type?: "copilot" | "standalone";
}
export const CrayonChat = ({
@@ -49,6 +40,7 @@ export const CrayonChat = ({
agentName = "My Agent",
responseTemplates,
createThread,
+ type = "standalone",
}: CrayonChatProps) => {
invariant(processMessage || userThreadManager, "processMessage or threadManager is required");
@@ -129,23 +121,11 @@ export const CrayonChat = ({
return (
<ThemeProvider>
<ChatProvider threadListManager={threadListManager} threadManager={threadManager}>
- <Container logoUrl={logoUrl} agentName={agentName}>
- <SidebarContainer>
- <SidebarHeader />
- <SidebarContent>
- <NewChatButton />
- <SidebarSeparator />
- <ThreadList />
- </SidebarContent>
- </SidebarContainer>
- <ThreadContainer>
- <MobileHeader />
- <ScrollArea>
- <Messages />
- </ScrollArea>
- <Composer />
- </ThreadContainer>
- </Container>
+ {type === "copilot" ? (
+ <ComposedCopilot logoUrl={logoUrl} agentName={agentName} />
+ ) : (
+ <ComposedStandalone logoUrl={logoUrl} agentName={agentName} />
+ )}
</ChatProvider>
</ThemeProvider>
);
diff --git a/js/packages/react-ui/src/components/CrayonChat/stories/CrayonChat.stories.tsx b/js/packages/react-ui/src/components/CrayonChat/stories/CrayonChat.stories.tsx
new file mode 100644
index 000000000..16919999d
--- /dev/null
+++ b/js/packages/react-ui/src/components/CrayonChat/stories/CrayonChat.stories.tsx
@@ -0,0 +1,102 @@
+import { Message, useThreadListManager, useThreadManager } from "@crayonai/react-core";
+import { CrayonChat } from "../CrayonChat";
+
+export default {
+ title: "Components/CrayonChat",
+ tags: ["dev", "!autodocs"],
+ argTypes: {
+ type: {
+ control: "select",
+ options: ["standalone", "copilot"],
+ },
+ },
+};
+
+export const Default = {
+ args: {
+ type: "standalone",
+ },
+ render: (args: any) => {
+ const threadListManager = useThreadListManager({
+ createThread: async () => {
+ return {
+ threadId: crypto.randomUUID(),
+ title: "test",
+ createdAt: new Date(),
+ isRunning: false,
+ };
+ },
+ fetchThreadList: async () => {
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+ return [
+ {
+ threadId: "1",
+ title: "test",
+ createdAt: new Date(),
+ isRunning: false,
+ },
+ {
+ threadId: "2",
+ title: "test 2",
+ createdAt: new Date(),
+ isRunning: false,
+ },
+ {
+ threadId: "3",
+ title: "test 3",
+ createdAt: new Date(),
+ isRunning: false,
+ },
+ ];
+ },
+ deleteThread: async () => {},
+ updateThread: async (t) => t,
+ onSwitchToNew: () => {},
+ onSelectThread: () => {},
+ });
+
+ const threadManager = useThreadManager({
+ threadId: threadListManager.selectedThreadId,
+ loadThread: async () => {
+ return [
+ {
+ id: crypto.randomUUID(),
+ role: "user",
+ type: "prompt",
+ message: "Hello",
+ },
+ {
+ id: crypto.randomUUID(),
+ role: "assistant",
+ type: "response",
+ message: [{ type: "text", text: "Hello" }],
+ },
+ ];
+ },
+ onProcessMessage: async ({ message, threadManager, abortController }) => {
+ const newMessage = Object.assign({}, message, {
+ id: crypto.randomUUID(),
+ }) as Message;
+ threadManager.appendMessages(newMessage);
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+ return [
+ {
+ id: crypto.randomUUID(),
+ role: "assistant",
+ type: "response",
+ message: [{ type: "text", text: "sadfasdf" }],
+ },
+ ];
+ },
+ responseTemplates: [],
+ });
+
+ return (
+ <CrayonChat
+ threadListManager={threadListManager}
+ threadManager={threadManager}
+ type={args.type}
+ />
+ );
+ },
+};
diff --git a/js/packages/react-ui/src/components/MessageLoading/MessageLoading.tsx b/js/packages/react-ui/src/components/MessageLoading/MessageLoading.tsx
new file mode 100644
index 000000000..fd9cdb495
--- /dev/null
+++ b/js/packages/react-ui/src/components/MessageLoading/MessageLoading.tsx
@@ -0,0 +1,9 @@
+import clsx from "clsx";
+
+export const MessageLoading = ({ className }: { className?: string }) => {
+ return (
+ <div className={clsx("crayon-message-loading-container", className)}>
+ <div className="crayon-message-loading" />
+ </div>
+ );
+};
diff --git a/js/packages/react-ui/src/components/MessageLoading/dependencies.ts b/js/packages/react-ui/src/components/MessageLoading/dependencies.ts
new file mode 100644
index 000000000..5fad51e99
--- /dev/null
+++ b/js/packages/react-ui/src/components/MessageLoading/dependencies.ts
@@ -0,0 +1,2 @@
+const dependencies = ["MessageLoading"];
+export default dependencies;
diff --git a/js/packages/react-ui/src/components/MessageLoading/index.ts b/js/packages/react-ui/src/components/MessageLoading/index.ts
new file mode 100644
index 000000000..bfe31b54a
--- /dev/null
+++ b/js/packages/react-ui/src/components/MessageLoading/index.ts
@@ -0,0 +1 @@
+export * from "./MessageLoading";
diff --git a/js/packages/react-ui/src/components/MessageLoading/messageLoading.scss b/js/packages/react-ui/src/components/MessageLoading/messageLoading.scss
new file mode 100644
index 000000000..50b1d2f02
--- /dev/null
+++ b/js/packages/react-ui/src/components/MessageLoading/messageLoading.scss
@@ -0,0 +1,46 @@
+@use "../../cssUtils" as cssUtils;
+
+@keyframes l7 {
+ 33% {
+ background-size:
+ calc(100% / 3) 0%,
+ calc(100% / 3) 100%,
+ calc(100% / 3) 100%;
+ }
+ 50% {
+ background-size:
+ calc(100% / 3) 100%,
+ calc(100% / 3) 0%,
+ calc(100% / 3) 100%;
+ }
+ 66% {
+ background-size:
+ calc(100% / 3) 100%,
+ calc(100% / 3) 100%,
+ calc(100% / 3) 0%;
+ }
+}
+
+.crayon-message-loading-container {
+ border-radius: cssUtils.$spacing-xl;
+ border: 1px solid cssUtils.$stroke-default;
+ padding: cssUtils.$spacing-s;
+ height: 32px;
+ display: flex;
+ align-items: center;
+ width: fit-content;
+ box-sizing: border-box;
+}
+
+.crayon-message-loading {
+ width: 24px;
+ aspect-ratio: 4;
+ --_g: no-repeat
+ radial-gradient(circle closest-side, #{cssUtils.$disabled-text} 90%, transparent 90%);
+ background:
+ var(--_g) 0% 50%,
+ var(--_g) 50% 50%,
+ var(--_g) 100% 50%;
+ background-size: calc(100% / 3) 100%;
+ animation: l7 750ms infinite linear;
+}
diff --git a/js/packages/react-ui/src/components/MessageLoading/stories/MessageLoading.stories.tsx b/js/packages/react-ui/src/components/MessageLoading/stories/MessageLoading.stories.tsx
new file mode 100644
index 000000000..8b3e70803
--- /dev/null
+++ b/js/packages/react-ui/src/components/MessageLoading/stories/MessageLoading.stories.tsx
@@ -0,0 +1,37 @@
+import { Meta, StoryObj } from "@storybook/react";
+import { MessageLoading } from "../MessageLoading";
+
+const meta: Meta<typeof MessageLoading> = {
+ title: "Components/MessageLoading",
+ component: MessageLoading,
+ parameters: {
+ layout: "centered",
+ docs: {
+ description: {
+ component: "```tsx\nimport { MessageLoading } from '@crayon-ui/react-ui';\n```",
+ },
+ },
+ },
+ decorators: [
+ (Story) => (
+ <div style={{ width: "400px" }}>
+ <Story />
+ </div>
+ ),
+ ],
+ tags: ["!dev", "autodocs"],
+};
+
+export default meta;
+type Story = StoryObj<typeof MessageLoading>;
+
+export const Default: Story = {
+ render: () => <MessageLoading />,
+ parameters: {
+ docs: {
+ description: {
+ story: "A loading indicator that appears while a message is being processed.",
+ },
+ },
+ },
+};
diff --git a/js/packages/react-ui/src/components/Shell/Thread.tsx b/js/packages/react-ui/src/components/Shell/Thread.tsx
index 6658deb58..498ee10f3 100644
--- a/js/packages/react-ui/src/components/Shell/Thread.tsx
+++ b/js/packages/react-ui/src/components/Shell/Thread.tsx
@@ -11,6 +11,7 @@ import React, { memo, useLayoutEffect, useRef } from "react";
import { useComposerState } from "../../hooks/useComposerState";
import { useScrollToBottom } from "../../hooks/useScrollToBottom";
import { IconButton } from "../IconButton";
+import { MessageLoading as MessageLoadingComponent } from "../MessageLoading";
import { useShellStore } from "./store";
export const ThreadContainer = ({
@@ -41,13 +42,14 @@ export const ScrollArea = ({
userMessageSelector?: string;
}) => {
const ref = useRef<HTMLDivElement>(null);
- const { messages } = useThreadState();
+ const { messages, isRunning } = useThreadState();
useScrollToBottom({
ref,
lastMessage: messages[messages.length - 1] || { id: "" },
scrollVariant,
userMessageSelector,
+ isRunning,
});
return (
@@ -149,7 +151,27 @@ export const RenderMessage = memo(
},
);
-export const Messages = ({ className }: { className?: string }) => {
+export const MessageLoading = () => {
+ const { isRunning } = useThreadState();
+
+ if (!isRunning) {
+ return null;
+ }
+
+ return (
+ <div className="crayon-shell-thread-message-loading">
+ <MessageLoadingComponent />
+ </div>
+ );
+};
+
+export const Messages = ({
+ className,
+ loader,
+}: {
+ className?: string;
+ loader?: React.ReactNode;
+}) => {
const { messages } = useThreadState();
return (
@@ -164,6 +186,7 @@ export const Messages = ({ className }: { className?: string }) => {
</MessageProvider>
);
})}
+ {loader}
</div>
);
};
@@ -171,11 +194,11 @@ export const Messages = ({ className }: { className?: string }) => {
export const Composer = ({ className }: { className?: string }) => {
const { textContent, setTextContent } = useComposerState();
const { processMessage, onCancel } = useThreadActions();
- const { isRunning } = useThreadState();
+ const { isRunning, isLoadingMessages } = useThreadState();
const inputRef = useRef<HTMLTextAreaElement>(null);
const handleSubmit = () => {
- if (!textContent.trim() || isRunning) {
+ if (!textContent.trim() || isRunning || isLoadingMessages) {
return;
}
diff --git a/js/packages/react-ui/src/components/Shell/stories/Shell.stories.tsx b/js/packages/react-ui/src/components/Shell/stories/Shell.stories.tsx
index 6e30d4b42..40cd59f6e 100644
--- a/js/packages/react-ui/src/components/Shell/stories/Shell.stories.tsx
+++ b/js/packages/react-ui/src/components/Shell/stories/Shell.stories.tsx
@@ -8,7 +8,7 @@ import { Container } from "../Container";
import { MobileHeader } from "../MobileHeader";
import { NewChatButton } from "../NewChatButton";
import { SidebarContainer, SidebarContent, SidebarHeader, SidebarSeparator } from "../Sidebar";
-import { Composer, Messages, ScrollArea, ThreadContainer } from "../Thread";
+import { Composer, MessageLoading, Messages, ScrollArea, ThreadContainer } from "../Thread";
import { ThreadList } from "../ThreadList";
import logoUrl from "./thesysdev_logo.jpeg";
@@ -79,9 +79,9 @@ export const Default = {
const newMessage = Object.assign({}, message, {
id: crypto.randomUUID(),
}) as Message;
-
+ threadManager.appendMessages(newMessage);
+ await new Promise((resolve) => setTimeout(resolve, 1000));
return [
- newMessage,
{
id: crypto.randomUUID(),
role: "assistant",
@@ -107,7 +107,7 @@ export const Default = {
<ThreadContainer>
<MobileHeader />
<ScrollArea>
- <Messages />
+ <Messages loader={<MessageLoading />} />
</ScrollArea>
<Composer />
</ThreadContainer>
diff --git a/js/packages/react-ui/src/components/Shell/thread.scss b/js/packages/react-ui/src/components/Shell/thread.scss
index 28c4552e4..bf3b2ef96 100644
--- a/js/packages/react-ui/src/components/Shell/thread.scss
+++ b/js/packages/react-ui/src/components/Shell/thread.scss
@@ -126,3 +126,8 @@ $center-align-spacing: calc(32px + cssUtils.$spacing-s);
}
}
}
+
+.crayon-shell-thread-message-loading {
+ display: flex;
+ padding: 0 $center-align-spacing;
+}
diff --git a/js/packages/react-ui/src/components/index.scss b/js/packages/react-ui/src/components/index.scss
index fb8792fbe..d9b1db0c0 100644
--- a/js/packages/react-ui/src/components/index.scss
+++ b/js/packages/react-ui/src/components/index.scss
@@ -23,6 +23,7 @@
@forward "./RadioItem/radioItem.scss";
@forward "./Select/select.scss";
@forward "./Shell/shell.scss";
+@forward "./CopilotShell/copilotShell.scss";
@forward "./Slider/slider.scss";
@forward "./SwitchGroup/switchGroup.scss";
@forward "./SwitchItem/switchItem.scss";
@@ -35,3 +36,4 @@
@forward "./Steps/steps.scss";
@forward "./Callout/callout.scss";
@forward "./ImageGallery/imageGallery.scss";
+@forward "./MessageLoading/messageLoading.scss";
diff --git a/js/packages/react-ui/src/hooks/useScrollToBottom.ts b/js/packages/react-ui/src/hooks/useScrollToBottom.ts
index 2e9b794f5..dab1119c2 100644
--- a/js/packages/react-ui/src/hooks/useScrollToBottom.ts
+++ b/js/packages/react-ui/src/hooks/useScrollToBottom.ts
@@ -5,12 +5,14 @@ export const useScrollToBottom = <T extends HTMLElement | null, L extends { id:
lastMessage,
scrollVariant,
userMessageSelector = ".crayon-shell-thread-message-user",
+ isRunning,
}: {
ref: RefObject<T>;
// scroll to bottom when this value changes
lastMessage: L;
scrollVariant: "always" | "once" | "user-message-anchor";
userMessageSelector?: string;
+ isRunning?: boolean;
}) => {
const previousLastMessage = useRef<L | null>(null);
const lastUserMessage = useRef<HTMLElement | null>(null);
@@ -59,4 +61,13 @@ export const useScrollToBottom = <T extends HTMLElement | null, L extends { id:
previousLastMessage.current = lastMessage;
}, [ref, lastMessage, scrollVariant, userMessageSelector]);
+
+ useEffect(() => {
+ if (isRunning) {
+ ref.current?.scrollTo({
+ top: ref.current?.scrollHeight,
+ behavior: "smooth",
+ });
+ }
+ }, [isRunning]);
};
diff --git a/js/packages/react-ui/src/index.ts b/js/packages/react-ui/src/index.ts
index 476ab2ccf..bcadf2a53 100644
--- a/js/packages/react-ui/src/index.ts
+++ b/js/packages/react-ui/src/index.ts
@@ -9,6 +9,7 @@ export * from "./components/Carousel";
export * from "./components/Charts";
export * from "./components/CheckBoxGroup";
export * from "./components/CheckBoxItem";
+export * as CopilotShell from "./components/CopilotShell";
export * from "./components/CrayonChat";
export * from "./components/DatePicker";
export * from "./components/FollowUpBlock";
@@ -21,6 +22,7 @@ export * from "./components/Input";
export * from "./components/Label";
export * from "./components/ListBlock";
export * from "./components/ListItem";
+export * from "./components/MessageLoading";
export * from "./components/RadioGroup";
export * from "./components/RadioItem";
export * from "./components/Select";