aboutsummaryrefslogtreecommitdiff
path: root/apps/web/components/views/chat/chat-messages.tsx
blob: 60a82132905777ffd3ae7a5e84a73f3bef78f9a5 (plain) (blame)
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
"use client"

import { useChat, useCompletion, type UIMessage } from "@ai-sdk/react"
import { cn } from "@lib/utils"
import { Button } from "@ui/components/button"
import { DefaultChatTransport } from "ai"
import {
	ArrowUp,
	Check,
	ChevronDown,
	ChevronRight,
	Copy,
	RotateCcw,
	X,
	Square
} from "lucide-react"
import { useCallback, useEffect, useRef, useState } from "react"
import { toast } from "sonner"
import { Streamdown } from "streamdown"
import { TextShimmer } from "@/components/text-shimmer"
import { usePersistentChat, useProject } from "@/stores"
import { useGraphHighlights } from "@/stores/highlights"
import { modelNames, ModelIcon } from "@/lib/models"
import { Spinner } from "../../spinner"
import { areUIMessageArraysEqual } from "@/stores/chat"

interface MemoryResult {
	documentId?: string
	title?: string
	content?: string
	url?: string
	score?: number
}

interface ExpandableMemoriesProps {
	foundCount: number
	results: MemoryResult[]
}

interface MessagePart {
	type: string
	state?: string
	text?: string
	output?: {
		count?: number
		results?: Array<{
			documentId?: string
			title?: string
			content?: string
			url?: string
			score?: number
		}>
	}
}

interface ChatMessage {
	id: string
	role: "user" | "assistant"
	parts: MessagePart[]
}

function ExpandableMemories({ foundCount, results }: ExpandableMemoriesProps) {
	const [isExpanded, setIsExpanded] = useState(false)

	if (foundCount === 0) {
		return (
			<div className="text-sm flex items-center gap-2 text-muted-foreground">
				<Check className="size-4" /> No memories found
			</div>
		)
	}

	return (
		<div className="text-sm">
			<button
				className="flex items-center gap-2 text-muted-foreground hover:text-foreground transition-colors"
				onClick={() => setIsExpanded(!isExpanded)}
				type="button"
			>
				{isExpanded ? (
					<ChevronDown className="size-4" />
				) : (
					<ChevronRight className="size-4" />
				)}
				Related memories
			</button>

			{isExpanded && results.length > 0 && (
				<div className="mt-2 ml-6 space-y-2 max-h-48 overflow-y-auto grid grid-cols-3 gap-2">
					{results.map((result, index) => {
						const isClickable =
							result.url &&
							(result.url.startsWith("http://") ||
								result.url.startsWith("https://"))

						const content = (
							<>
								{result.title && (
									<div className="font-medium text-sm mb-1 text-foreground">
										{result.title}
									</div>
								)}
								{result.content && (
									<div className="text-xs text-muted-foreground line-clamp-2">
										{result.content}
									</div>
								)}
								{result.url && (
									<div className="text-xs text-blue-600 dark:text-blue-400 mt-1 truncate">
										{result.url}
									</div>
								)}
								{result.score && (
									<div className="text-xs text-muted-foreground mt-1">
										Score: {(result.score * 100).toFixed(1)}%
									</div>
								)}
							</>
						)

						if (isClickable) {
							return (
								<a
									className="block p-2 bg-accent/50 rounded-md border border-border hover:bg-accent transition-colors cursor-pointer"
									href={result.url}
									key={result.documentId || index}
									rel="noopener noreferrer"
									target="_blank"
								>
									{content}
								</a>
							)
						}

						return (
							<div
								className="p-2 bg-accent/50 rounded-md border border-border"
								key={result.documentId || index}
							>
								{content}
							</div>
						)
					})}
				</div>
			)}
		</div>
	)
}

function useStickyAutoScroll(triggerKeys: ReadonlyArray<unknown>) {
	const scrollContainerRef = useRef<HTMLDivElement>(null)
	const bottomRef = useRef<HTMLDivElement>(null)
	const [isAutoScroll, setIsAutoScroll] = useState(true)
	const [isFarFromBottom, setIsFarFromBottom] = useState(false)

	const scrollToBottom = useCallback((behavior: ScrollBehavior = "auto") => {
		const node = bottomRef.current
		if (node) node.scrollIntoView({ behavior, block: "end" })
	}, [])

	useEffect(function observeBottomVisibility() {
		const container = scrollContainerRef.current
		const sentinel = bottomRef.current
		if (!container || !sentinel) return

		const observer = new IntersectionObserver(
			(entries) => {
				if (!entries || entries.length === 0) return
				const isIntersecting = entries.some((e) => e.isIntersecting)
				setIsAutoScroll(isIntersecting)
			},
			{ root: container, rootMargin: "0px 0px 80px 0px", threshold: 0 },
		)
		observer.observe(sentinel)
		return () => observer.disconnect()
	}, [])

	useEffect(
		function observeContentResize() {
			const container = scrollContainerRef.current
			if (!container) return
			const resizeObserver = new ResizeObserver(() => {
				if (isAutoScroll) scrollToBottom("auto")
				const distanceFromBottom =
					container.scrollHeight - container.scrollTop - container.clientHeight
				setIsFarFromBottom(distanceFromBottom > 100)
			})
			resizeObserver.observe(container)
			return () => resizeObserver.disconnect()
		},
		[isAutoScroll, scrollToBottom],
	)

	function enableAutoScroll() {
		setIsAutoScroll(true)
	}

	useEffect(
		function autoScrollOnNewContent() {
			if (isAutoScroll) scrollToBottom("auto")
		},
		[isAutoScroll, scrollToBottom, ...triggerKeys],
	)

	const recomputeDistanceFromBottom = useCallback(() => {
		const container = scrollContainerRef.current
		if (!container) return
		const distanceFromBottom =
			container.scrollHeight - container.scrollTop - container.clientHeight
		setIsFarFromBottom(distanceFromBottom > 100)
	}, [])

	useEffect(() => {
		recomputeDistanceFromBottom()
	}, [recomputeDistanceFromBottom, ...triggerKeys])

	function onScroll() {
		recomputeDistanceFromBottom()
	}

	return {
		scrollContainerRef,
		bottomRef,
		isAutoScroll,
		isFarFromBottom,
		onScroll,
		enableAutoScroll,
		scrollToBottom,
	} as const
}

export function ChatMessages() {
	const { selectedProject } = useProject()
	const {
		currentChatId,
		setCurrentChatId,
		setConversation,
		getCurrentConversation,
		setConversationTitle,
		getCurrentChat,
	} = usePersistentChat()

	const storageKey = `chat-model-${currentChatId}`

	const [input, setInput] = useState("")
	const [selectedModel, setSelectedModel] = useState<
		"gpt-5" | "claude-sonnet-4.5" | "gemini-2.5-pro"
	>("gemini-2.5-pro")
	const activeChatIdRef = useRef<string | null>(null)
	const shouldGenerateTitleRef = useRef<boolean>(false)
	const hasRunInitialMessageRef = useRef<boolean>(false)
	const lastSavedMessagesRef = useRef<UIMessage[] | null>(null)
	const lastSavedActiveIdRef = useRef<string | null>(null)
	const lastLoadedChatIdRef = useRef<string | null>(null)
	const lastLoadedMessagesRef = useRef<UIMessage[] | null>(null)

	const { setDocumentIds } = useGraphHighlights()

	const { messages, sendMessage, status, stop, setMessages, id, regenerate } =
		useChat({
			id: currentChatId ?? undefined,
			transport: new DefaultChatTransport({
				api: `${process.env.NEXT_PUBLIC_BACKEND_URL}/chat`,
				credentials: "include",
				body: {
					metadata: {
						projectId: selectedProject,
						model: selectedModel,
					},
				},
			}),
			maxSteps: 10,
			onFinish: (result) => {
				const activeId = activeChatIdRef.current
				if (!activeId) return
				if (result.message.role !== "assistant") return

				if (shouldGenerateTitleRef.current) {
					const textPart = result.message.parts.find(
						(p: { type?: string; text?: string }) => p?.type === "text",
					) as { text?: string } | undefined
					const text = textPart?.text?.trim()
					if (text) {
						shouldGenerateTitleRef.current = false
						complete(text)
					}
				}
			},
		})

	useEffect(() => {
		lastLoadedMessagesRef.current = messages
	}, [messages])

	useEffect(() => {
		activeChatIdRef.current = currentChatId ?? id ?? null
	}, [currentChatId, id])

	useEffect(() => {
		if (typeof window === "undefined") return
		if (currentChatId) {
			const savedModel = sessionStorage.getItem(storageKey) as
				| "gpt-5"
				| "claude-sonnet-4.5"
				| "gemini-2.5-pro"

			if (
				savedModel &&
				["gpt-5", "claude-sonnet-4.5", "gemini-2.5-pro"].includes(savedModel)
			) {
				setSelectedModel(savedModel)
			}
		}
	}, [currentChatId, storageKey])

	useEffect(() => {
		if (typeof window === "undefined") return
		if (currentChatId && !hasRunInitialMessageRef.current) {
			// Check if there's an initial message from the home page in sessionStorage
			const storageKey = `chat-initial-${currentChatId}`
			const initialMessage = sessionStorage.getItem(storageKey)

			if (initialMessage) {
				// Clean up the storage and send the message
				sessionStorage.removeItem(storageKey)
				sendMessage({ text: initialMessage })
				hasRunInitialMessageRef.current = true
			}
		}
	}, [currentChatId, sendMessage])

	useEffect(() => {
		if (id && id !== currentChatId) {
			setCurrentChatId(id)
		}
	}, [id, currentChatId, setCurrentChatId])

	useEffect(() => {
		if (currentChatId !== lastLoadedChatIdRef.current) {
			lastLoadedMessagesRef.current = null
			lastSavedMessagesRef.current = null
		}

		if (currentChatId === lastLoadedChatIdRef.current) {
			setInput("")
			return
		}

		const msgs = getCurrentConversation()

		if (msgs && msgs.length > 0) {
			const currentMessages = lastLoadedMessagesRef.current
			if (!currentMessages || !areUIMessageArraysEqual(currentMessages, msgs)) {
				lastLoadedMessagesRef.current = msgs
				setMessages(msgs)
			}
		} else if (!currentChatId) {
			if (
				lastLoadedMessagesRef.current &&
				lastLoadedMessagesRef.current.length > 0
			) {
				lastLoadedMessagesRef.current = []
				setMessages([])
			}
		}

		lastLoadedChatIdRef.current = currentChatId
		setInput("")
	}, [currentChatId, getCurrentConversation, setMessages])

	useEffect(() => {
		const activeId = currentChatId ?? id
		if (!activeId || messages.length === 0) {
			return
		}

		if (activeId !== lastSavedActiveIdRef.current) {
			lastSavedMessagesRef.current = null
			lastSavedActiveIdRef.current = activeId
		}

		const lastSaved = lastSavedMessagesRef.current
		if (lastSaved && areUIMessageArraysEqual(lastSaved, messages)) {
			return
		}

		lastSavedMessagesRef.current = messages
		setConversation(activeId, messages)
	}, [messages, currentChatId, id, setConversation])

	const { complete } = useCompletion({
		api: `${process.env.NEXT_PUBLIC_BACKEND_URL}/chat/title`,
		credentials: "include",
		onFinish: (_, completion) => {
			const activeId = activeChatIdRef.current
			if (!completion || !activeId) return
			setConversationTitle(activeId, completion.trim())
		},
	})

	// Update graph highlights from the most recent tool-searchMemories output
	useEffect(() => {
		try {
			const lastAssistant = [...messages]
				.reverse()
				.find((m) => m.role === "assistant") as ChatMessage | undefined
			if (!lastAssistant) return
			const lastSearchPart = [...(lastAssistant.parts as MessagePart[])]
				.reverse()
				.find(
					(p) =>
						p?.type === "tool-searchMemories" &&
						p?.state === "output-available",
				) as MessagePart | undefined
			if (!lastSearchPart) return
			const output = lastSearchPart.output
			const ids = Array.isArray(output?.results)
				? ((output.results as MemoryResult[])
						.map((r) => r?.documentId)
						.filter(Boolean) as string[])
				: []
			if (ids.length > 0) {
				setDocumentIds(ids)
			}
		} catch {}
	}, [messages, setDocumentIds])

	useEffect(() => {
		const currentSummary = getCurrentChat()
		const hasTitle = Boolean(
			currentSummary?.title && currentSummary.title.trim().length > 0,
		)
		shouldGenerateTitleRef.current = !hasTitle
	}, [getCurrentChat])

	/**
	 * Handles sending a message from the input area.
	 * - Prevents sending during submitted (shows toast)
	 * - Stops streaming when active
	 * - Validates non-empty input (shows toast)
	 * Returns true when a message is sent.
	 */
	const handleSendMessage = useCallback(() => {
		if (status === "submitted") {
			toast.warning("Please wait for the current response to complete", {
				id: "wait-for-response",
			})
			return false
		}
		if (status === "streaming") {
			stop()
			return false
		}
		if (!input.trim()) {
			toast.warning("Please enter a message", { id: "empty-message" })
			return false
		}
		sendMessage({ text: input })
		setInput("")
		return true
	}, [status, input, sendMessage, stop])

	const handleKeyDown = (e: React.KeyboardEvent) => {
		if (e.key === "Enter" && !e.shiftKey) {
			e.preventDefault()
			handleSendMessage()
		}
	}

	const {
		scrollContainerRef,
		bottomRef,
		isFarFromBottom,
		onScroll,
		enableAutoScroll,
		scrollToBottom,
	} = useStickyAutoScroll([messages, status])

	return (
		<div className="h-full flex flex-col w-full">
			<div className="flex-1 relative">
				<div
					className="absolute inset-0 overflow-y-auto custom-scrollbar"
					onScroll={onScroll}
					ref={scrollContainerRef}
				>
					<div className="flex flex-col gap-2 max-w-4xl mx-auto px-4 md:px-2 pt-4 pb-7 scroll-pb-7">
						{messages.map((message) => (
							<div
								className={cn(
									"flex my-2",
									message.role === "user"
										? "items-center flex-row-reverse gap-2"
										: "flex-col",
								)}
								key={message.id}
							>
								<div
									className={cn(
										"flex flex-col gap-2 ",
										message.role === "user"
											? "bg-accent/50 px-3 py-1.5 border border-border rounded-lg"
											: "",
									)}
								>
									{message.parts
										.filter((part) =>
											[
												"text",
												"tool-searchMemories",
												"tool-addMemory",
											].includes(part.type),
										)
										.map((part, index) => {
											switch (part.type) {
												case "text":
													return (
														<div key={`${message.id}-${part.type}-${index}`}>
															<Streamdown>{part.text}</Streamdown>
														</div>
													)
												case "tool-searchMemories": {
													switch (part.state) {
														case "input-available":
														case "input-streaming":
															return (
																<div
																	className="text-sm flex items-center gap-2 text-muted-foreground"
																	key={`${message.id}-${part.type}-${index}`}
																>
																	<Spinner className="size-4" /> Searching
																	memories...
																</div>
															)
														case "output-error":
															return (
																<div
																	className="text-sm flex items-center gap-2 text-muted-foreground"
																	key={`${message.id}-${part.type}-${index}`}
																>
																	<X className="size-4" /> Error recalling
																	memories
																</div>
															)
														case "output-available": {
															const output = part.output
															const foundCount =
																typeof output === "object" &&
																output !== null &&
																"count" in output
																	? Number(output.count) || 0
																	: 0
															// @ts-expect-error
															const results = Array.isArray(output?.results)
																? // @ts-expect-error
																	output.results
																: []

															return (
																<ExpandableMemories
																	foundCount={foundCount}
																	key={`${message.id}-${part.type}-${index}`}
																	results={results}
																/>
															)
														}
														default:
															return null
													}
												}
												case "tool-addMemory": {
													switch (part.state) {
														case "input-available":
															return (
																<div
																	className="text-sm flex items-center gap-2 text-muted-foreground"
																	key={`${message.id}-${part.type}-${index}`}
																>
																	<Spinner className="size-4" /> Adding
																	memory...
																</div>
															)
														case "output-error":
															return (
																<div
																	className="text-sm flex items-center gap-2 text-muted-foreground"
																	key={`${message.id}-${part.type}-${index}`}
																>
																	<X className="size-4" /> Error adding memory
																</div>
															)
														case "output-available":
															return (
																<div
																	className="text-sm flex items-center gap-2 text-muted-foreground"
																	key={`${message.id}-${part.type}-${index}`}
																>
																	<Check className="size-4" /> Memory added
																</div>
															)
														case "input-streaming":
															return (
																<div
																	className="text-sm flex items-center gap-2 text-muted-foreground"
																	key={`${message.id}-${part.type}-${index}`}
																>
																	<Spinner className="size-4" /> Adding
																	memory...
																</div>
															)
														default:
															return null
													}
												}
												default:
													return null
											}
										})}
								</div>
								{message.role === "assistant" && (
									<div className="flex items-center gap-0.5 mt-0.5">
										<Button
											className="size-7 text-muted-foreground hover:text-foreground"
											onClick={() => {
												navigator.clipboard.writeText(
													message.parts
														.filter((p) => p.type === "text")
														?.map((p) => (p as MessagePart).text ?? "")
														.join("\n") ?? "",
												)
												toast.success("Copied to clipboard")
											}}
											size="icon"
											variant="ghost"
										>
											<Copy className="size-3.5" />
										</Button>
										<Button
											className="size-6 text-muted-foreground hover:text-foreground"
											onClick={() => regenerate({ messageId: message.id })}
											size="icon"
											variant="ghost"
										>
											<RotateCcw className="size-3.5" />
										</Button>
									</div>
								)}
							</div>
						))}
						{status === "submitted" && (
							<div className="flex text-muted-foreground justify-start gap-2 px-4 py-3 items-center w-full">
								<Spinner className="size-4" />
								<TextShimmer className="text-sm" duration={1.5}>
									Thinking...
								</TextShimmer>
							</div>
						)}
						<div ref={bottomRef} />
					</div>
				</div>

				<Button
					className={cn(
						"rounded-full w-fit mx-auto shadow-md z-10 absolute inset-x-0 bottom-4 flex justify-center",
						"transition-all duration-200 ease-out",
						isFarFromBottom
							? "opacity-100 scale-100 pointer-events-auto"
							: "opacity-0 scale-95 pointer-events-none",
					)}
					onClick={() => {
						enableAutoScroll()
						scrollToBottom("smooth")
					}}
					size="sm"
					type="button"
					variant="default"
				>
					Scroll to bottom
				</Button>
			</div>

			<div className="pb-4 px-4 md:px-2 max-w-4xl mx-auto w-full">
				<form
					className="flex flex-col items-end gap-3 border border-border rounded-[22px] p-3 relative shadow-lg dark:shadow-2xl"
					onSubmit={(e) => {
						e.preventDefault()
						const sent = handleSendMessage()
						if (sent) {
							enableAutoScroll()
							scrollToBottom("auto")
						}
					}}
				>
					<textarea
						value={input}
						onChange={(e) => setInput(e.target.value)}
						onKeyDown={handleKeyDown}
						aria-busy={status === "streaming" || status === "submitted"}
						aria-disabled={status === "submitted"}
						placeholder="Ask your follow-up question..."
						className="w-full text-foreground placeholder:text-muted-foreground rounded-md outline-none resize-none text-base leading-relaxed px-3 py-3 bg-transparent"
						rows={3}
					/>
					<div className="absolute bottom-2 right-2 flex items-center gap-4">
						<div className="flex items-center gap-1.5">
							<ModelIcon
								width={16}
								height={16}
								className="text-muted-foreground"
							/>
							<span className="text-xs text-muted-foreground">
								{modelNames[selectedModel]}
							</span>
						</div>
						{status === "streaming" || status === "submitted" ? (
							<Button
								onClick={() => stop()}
								aria-label="Stop generation"
								className="rounded-xl"
								variant="destructive"
								size="icon"
								type="button"
							>
								<Square className="size-4" />
							</Button>
						) : (
							<Button
								type="submit"
								aria-label="Send message"
								disabled={!input.trim()}
								className="text-primary-foreground rounded-xl transition-all disabled:opacity-50 disabled:cursor-not-allowed bg-primary hover:bg-primary/90"
								size="icon"
							>
								<ArrowUp className="size-4" />
							</Button>
						)}
					</div>
				</form>
			</div>
		</div>
	)
}