1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
|
import { useEffect, useRef, useState } from "react";
import Markdown from "react-markdown";
import ChatInputForm from "./ChatInputForm";
import Navbar from "./Navbar";
import SharedCard from "./memories/SharedCard";
import { User } from "@supermemory/shared/types";
import { CoreMessage } from "ai";
import { AnimatePresence, motion } from "framer-motion";
import { ChevronDown, ChevronUp } from "lucide-react";
import { useChatStream } from "~/lib/hooks/use-chat-stream";
import { Memory } from "~/lib/types/memory";
interface ChatProps {
user: User;
chatMessages: CoreMessage[];
initialThreadUuid?: string;
}
function Chat({ user, chatMessages, initialThreadUuid }: ChatProps) {
const {
threadUuid,
chatMessages: chatMessagesStreamed,
input,
setInput,
sendMessage,
isLoading,
} = useChatStream(chatMessages, initialThreadUuid);
const [expandedMessageIndexes, setExpandedMessageIndexes] = useState<number[]>([]);
const [shouldAutoScroll, setShouldAutoScroll] = useState(true);
const messagesEndRef = useRef<HTMLDivElement>(null);
const scrollContainerRef = useRef<HTMLDivElement>(null);
const [streamingText, setStreamingText] = useState("");
const hasAnnotations = chatMessagesStreamed.some(
(message) => message.role === "assistant" && message.annotations?.length,
);
const toggleExpand = (index: number) => {
setExpandedMessageIndexes((prev) =>
prev.includes(index) ? prev.filter((i) => i !== index) : [...prev, index],
);
};
const scrollToBottom = () => {
if (messagesEndRef.current && shouldAutoScroll) {
messagesEndRef.current.scrollIntoView({ behavior: "smooth" });
}
};
useEffect(() => {
scrollToBottom();
}, [chatMessagesStreamed]);
useEffect(() => {
const lastMessage = chatMessagesStreamed[chatMessagesStreamed.length - 1];
if (lastMessage?.role === "assistant" && isLoading) {
setStreamingText(lastMessage.content as string);
} else {
setStreamingText("");
}
}, [chatMessagesStreamed, isLoading]);
const handleScroll = () => {
if (!scrollContainerRef.current) return;
const { scrollTop, scrollHeight, clientHeight } = scrollContainerRef.current;
const isAtBottom = Math.abs(scrollHeight - clientHeight - scrollTop) < 10;
setShouldAutoScroll(isAtBottom);
};
const renderAttachments = (attachments: any[]) => (
<div className="flex flex-wrap gap-4 mb-4">
{attachments.map((attachment) => (
<motion.div
key={attachment.name}
className="relative"
initial={{ scale: 0.9, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
transition={{ duration: 0.2 }}
>
{attachment.url.endsWith(".png") ||
attachment.url.endsWith(".jpg") ||
attachment.url.endsWith(".jpeg") ? (
<img
src={attachment.url}
alt={attachment.name}
className="max-w-[300px] rounded-lg shadow-sm"
/>
) : (
<div className="p-4 border rounded-lg">
<a
href={attachment.url}
className="text-blue-500 hover:underline"
target="_blank"
rel="noopener noreferrer"
>
{attachment.name}
</a>
</div>
)}
</motion.div>
))}
</div>
);
const renderMessageContent = (content: string | any, isLatestAndLoading: boolean) => (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.5 }}
>
<Markdown className="prose dark:prose-invert prose-lg w-full">
{isLatestAndLoading ? streamingText : typeof content === "string" ? content.replace(/<context>[\s\S]*?<\/context>/g, "") : content}
</Markdown>
</motion.div>
);
const groupAnnotationsByHost = (annotations: Memory[]) => {
return annotations.reduce(
(acc, curr) => {
let host = "";
try {
const url = new URL(curr.url || "");
host = url.host;
} catch {
host = "unknown";
}
if (!acc[host]) acc[host] = [];
acc[host].push(curr);
return acc;
},
{} as Record<string, Memory[]>,
);
};
const renderAnnotations = (messageAnnotations: Memory[], index: number, isMobile = false) => {
const isExpanded = expandedMessageIndexes.includes(index);
const groupedAnnotations = groupAnnotationsByHost(messageAnnotations);
return (
<div
className={
isMobile ? "lg:hidden mb-4" : "hidden lg:block w-[320px] flex-shrink-0 -translate-y-12"
}
>
<AnimatePresence>
{!isExpanded ? (
<motion.button
onClick={() => toggleExpand(index)}
className={`text-${isMobile ? "xs" : "sm"} text-muted-foreground hover:text-foreground transition-colors flex items-center gap-1`}
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
>
<ChevronDown className={`w-${isMobile ? "3" : "4"} h-${isMobile ? "3" : "4"}`} />
{messageAnnotations.length} relevant{" "}
{messageAnnotations.length === 1 ? "item" : "items"}
</motion.button>
) : (
<motion.div
className="space-y-4"
initial={{ opacity: 0, [isMobile ? "y" : "x"]: isMobile ? 10 : 20 }}
animate={{ opacity: 1, [isMobile ? "y" : "x"]: 0 }}
exit={{ opacity: 0, [isMobile ? "y" : "x"]: isMobile ? -10 : 20 }}
>
<div className={`text-${isMobile ? "xs" : "sm"} font-medium text-muted-foreground`}>
Related Context
</div>
<div className={isMobile ? "flex gap-2 overflow-x-auto pb-2" : "space-y-6"}>
{isMobile
? messageAnnotations.map((annotation, i) => (
<motion.div
key={i}
className="flex-shrink-0 w-[200px] scale-90"
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.2, delay: i * 0.1 }}
>
<SharedCard data={annotation} />
</motion.div>
))
: Object.entries(groupedAnnotations).map(([host, items], i) => (
<div key={host} className="space-y-2">
{items.length > 1 && (
<div className="text-xs text-muted-foreground">
{host} ({items.length} items)
</div>
)}
<div className="space-y-2">
{items.map((annotation, j) => (
<motion.div
key={j}
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.2, delay: j * 0.1 }}
>
<SharedCard data={annotation} />
</motion.div>
))}
</div>
</div>
))}
</div>
<motion.button
onClick={() => toggleExpand(index)}
className={`flex items-center gap-${isMobile ? "1" : "2"} text-${isMobile ? "xs" : "sm"} text-muted-foreground hover:text-foreground transition-colors`}
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
>
<ChevronUp className={`w-${isMobile ? "3" : "4"} h-${isMobile ? "3" : "4"}`} />
Show less
</motion.button>
</motion.div>
)}
</AnimatePresence>
</div>
);
};
return (
<div>
<Navbar user={user} />
<div
className="p-4 font-geist md:p-24 md:pt-16 h-[calc(100vh-64px)] overflow-y-auto"
ref={scrollContainerRef}
onScroll={handleScroll}
>
<div className="grid grid-cols-12 gap-8">
<div
className={`col-span-12 ${hasAnnotations ? "lg:col-start-2" : "lg:col-start-3"} relative`}
>
<div className="space-y-8 pb-24">
{chatMessagesStreamed.map((message, index) => {
const isLatestAndLoading = index === chatMessagesStreamed.length - 1 && isLoading && message.role === "assistant";
if (message.role === "user") {
return (
<motion.div
key={index}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3 }}
>
{message.experimental_attachments &&
renderAttachments(message.experimental_attachments)}
<Markdown className={"text-xl"}>{message.content}</Markdown>
</motion.div>
);
}
if (message.role === "assistant") {
const messageAnnotations = message.annotations?.[0]
? (message.annotations[0] as unknown as Memory[])
: undefined;
return (
<motion.div
key={index}
className="relative w-full"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3 }}
>
<>
{messageAnnotations &&
messageAnnotations.length > 0 &&
renderAnnotations(messageAnnotations, index, true)}
<div className="flex gap-8">
<div className="flex-1">{renderMessageContent(message.content, isLatestAndLoading)}</div>
{messageAnnotations &&
messageAnnotations.length > 0 &&
renderAnnotations(messageAnnotations, index)}
</div>
</>
</motion.div>
);
}
return null;
})}
{isLoading && !chatMessagesStreamed[chatMessagesStreamed.length - 1]?.content && (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
className="flex gap-8"
>
<div className="flex-1">
<div className="animate-pulse space-y-4">
{[3 / 4, 1 / 2, 2 / 3, 1 / 3].map((width, i) => (
<div key={i} className={`h-6 bg-muted rounded w-${width}`} />
))}
</div>
</div>
{hasAnnotations && (
<div className="hidden lg:block w-[320px] flex-shrink-0 -translate-y-12">
<div className="animate-pulse space-y-4">
{[...Array(2)].map((_, i) => (
<div key={i} className="h-[160px] bg-muted rounded" />
))}
</div>
</div>
)}
</motion.div>
)}
<div ref={messagesEndRef} />
</div>
<div
className={`fixed bottom-8 ${hasAnnotations ? "lg:w-[calc(66.666667%-2rem)]" : "lg:w-[calc(66.666667%)]"} w-[calc(100%-2rem)] left-1/2 -translate-x-1/2`}
>
<ChatInputForm
submit={sendMessage}
user={user}
input={input}
setInput={setInput}
isLoading={isLoading}
mini
/>
</div>
</div>
</div>
</div>
</div>
);
}
export default Chat;
|