-
Notifications
You must be signed in to change notification settings - Fork 264
Expand file tree
/
Copy pathchatThread.tsx
More file actions
341 lines (302 loc) · 12.8 KB
/
chatThread.tsx
File metadata and controls
341 lines (302 loc) · 12.8 KB
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
'use client';
import { useToast } from '@/components/hooks/use-toast';
import { Button } from '@/components/ui/button';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Separator } from '@/components/ui/separator';
import { CustomSlateEditor } from '@/features/chat/customSlateEditor';
import { AdditionalChatRequestParams, CustomEditor, LanguageModelInfo, SBChatMessage, SearchScope, Source } from '@/features/chat/types';
import { createUIMessage, getAllMentionElements, resetEditor, slateContentToString } from '@/features/chat/utils';
import { useDomain } from '@/hooks/useDomain';
import { useChat } from '@ai-sdk/react';
import { CreateUIMessage, DefaultChatTransport } from 'ai';
import { ArrowDownIcon } from 'lucide-react';
import { useNavigationGuard } from 'next-navigation-guard';
import { Fragment, useCallback, useEffect, useRef, useState } from 'react';
import { Descendant } from 'slate';
import { useMessagePairs } from '../../useMessagePairs';
import { useSelectedLanguageModel } from '../../useSelectedLanguageModel';
import { ChatBox } from '../chatBox';
import { ChatBoxToolbar } from '../chatBox/chatBoxToolbar';
import { ChatThreadListItem } from './chatThreadListItem';
import { ErrorBanner } from './errorBanner';
import { useRouter } from 'next/navigation';
import { usePrevious } from '@uidotdev/usehooks';
import { RepositoryQuery, SearchContextQuery } from '@/lib/types';
type ChatHistoryState = {
scrollOffset?: number;
}
interface ChatThreadProps {
id?: string | undefined;
initialMessages?: SBChatMessage[];
inputMessage?: CreateUIMessage<SBChatMessage>;
languageModels: LanguageModelInfo[];
repos: RepositoryQuery[];
searchContexts: SearchContextQuery[];
selectedSearchScopes: SearchScope[];
onSelectedSearchScopesChange: (items: SearchScope[]) => void;
isChatReadonly: boolean;
}
export const ChatThread = ({
id: defaultChatId,
initialMessages,
inputMessage,
languageModels,
repos,
searchContexts,
selectedSearchScopes,
onSelectedSearchScopesChange,
isChatReadonly,
}: ChatThreadProps) => {
const domain = useDomain();
const [isErrorBannerVisible, setIsErrorBannerVisible] = useState(false);
const scrollAreaRef = useRef<HTMLDivElement>(null);
const latestMessagePairRef = useRef<HTMLDivElement>(null);
const hasSubmittedInputMessage = useRef(false);
const [isAutoScrollEnabled, setIsAutoScrollEnabled] = useState(false);
const { toast } = useToast();
const router = useRouter();
const [isContextSelectorOpen, setIsContextSelectorOpen] = useState(false);
// Initial state is from attachments that exist in in the chat history.
const [sources, setSources] = useState<Source[]>(
initialMessages?.flatMap((message) =>
message.parts
.filter((part) => part.type === 'data-source')
.map((part) => part.data)
) ?? []
);
const { selectedLanguageModel } = useSelectedLanguageModel({
initialLanguageModel: languageModels.length > 0 ? languageModels[0] : undefined,
});
const {
messages,
sendMessage: _sendMessage,
error,
status,
stop,
id: chatId,
} = useChat<SBChatMessage>({
id: defaultChatId,
messages: initialMessages,
transport: new DefaultChatTransport({
api: '/api/chat',
headers: {
"X-Org-Domain": domain,
}
}),
onData: (dataPart) => {
// Keeps sources added by the assistant in sync.
if (dataPart.type === 'data-source') {
setSources((prev) => [...prev, dataPart.data]);
}
}
});
const sendMessage = useCallback((message: CreateUIMessage<SBChatMessage>) => {
if (!selectedLanguageModel) {
toast({
description: "Failed to send message. No language model selected.",
variant: "destructive",
});
return;
}
// Keeps sources added by the user in sync.
const sources = message.parts
.filter((part) => part.type === 'data-source')
.map((part) => part.data);
setSources((prev) => [...prev, ...sources]);
_sendMessage(message, {
body: {
selectedSearchScopes,
languageModelId: selectedLanguageModel.model,
} satisfies AdditionalChatRequestParams,
});
}, [_sendMessage, selectedLanguageModel, toast, selectedSearchScopes]);
const messagePairs = useMessagePairs(messages);
useNavigationGuard({
enabled: status === "streaming" || status === "submitted",
confirm: () => window.confirm("You have unsaved changes that will be lost.")
});
// When the chat is finished, refresh the page to update the chat history.
const prevStatus = usePrevious(status);
useEffect(() => {
const wasPending = prevStatus === "submitted" || prevStatus === "streaming";
const isFinished = status === "error" || status === "ready";
if (wasPending && isFinished) {
router.refresh();
}
}, [prevStatus, status, router]);
useEffect(() => {
if (!inputMessage || hasSubmittedInputMessage.current) {
return;
}
sendMessage(inputMessage);
setIsAutoScrollEnabled(true);
hasSubmittedInputMessage.current = true;
}, [inputMessage, sendMessage]);
// Track scroll position changes.
useEffect(() => {
const scrollElement = scrollAreaRef.current?.querySelector('[data-radix-scroll-area-viewport]') as HTMLElement;
if (!scrollElement) return;
let timeout: NodeJS.Timeout | null = null;
const handleScroll = () => {
const scrollOffset = scrollElement.scrollTop;
const threshold = 50; // pixels from bottom to consider "at bottom"
const { scrollHeight, clientHeight } = scrollElement;
const isAtBottom = scrollHeight - scrollOffset - clientHeight <= threshold;
setIsAutoScrollEnabled(isAtBottom);
// Debounce the history state update
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(() => {
history.replaceState(
{
scrollOffset,
} satisfies ChatHistoryState,
'',
window.location.href
);
}, 300);
};
scrollElement.addEventListener('scroll', handleScroll, { passive: true });
return () => {
scrollElement.removeEventListener('scroll', handleScroll);
if (timeout) {
clearTimeout(timeout);
}
};
}, []);
useEffect(() => {
const scrollElement = scrollAreaRef.current?.querySelector('[data-radix-scroll-area-viewport]') as HTMLElement;
if (!scrollElement) {
return;
}
const { scrollOffset } = (history.state ?? {}) as ChatHistoryState;
scrollElement.scrollTo({
top: scrollOffset ?? 0,
behavior: 'instant',
});
}, []);
// When messages are being streamed, scroll to the latest message
// assuming auto scrolling is enabled.
useEffect(() => {
if (
!latestMessagePairRef.current ||
!isAutoScrollEnabled ||
messages.length === 0
) {
return;
}
latestMessagePairRef.current.scrollIntoView({
behavior: 'smooth',
block: 'end',
inline: 'nearest',
});
}, [isAutoScrollEnabled, messages]);
// Keep the error state & banner visibility in sync.
useEffect(() => {
if (error) {
setIsErrorBannerVisible(true);
}
}, [error]);
const onSubmit = useCallback((children: Descendant[], editor: CustomEditor) => {
const text = slateContentToString(children);
const mentions = getAllMentionElements(children);
const message = createUIMessage(text, mentions.map(({ data }) => data), selectedSearchScopes);
sendMessage(message);
setIsAutoScrollEnabled(true);
resetEditor(editor);
}, [sendMessage, selectedSearchScopes]);
return (
<>
{error && (
<ErrorBanner
error={error}
isVisible={isErrorBannerVisible}
onClose={() => setIsErrorBannerVisible(false)}
/>
)}
<ScrollArea
ref={scrollAreaRef}
className="flex flex-col h-full w-full p-4 overflow-hidden"
>
{
messagePairs.length === 0 ? (
<div className="flex items-center justify-center text-center h-full">
<p className="text-muted-foreground">no messages</p>
</div>
) : (
<>
{messagePairs.map(([userMessage, assistantMessage], index) => {
const isLastPair = index === messagePairs.length - 1;
const isStreaming = isLastPair && (status === "streaming" || status === "submitted");
return (
<Fragment key={index}>
<ChatThreadListItem
index={index}
chatId={chatId}
userMessage={userMessage}
assistantMessage={assistantMessage}
isStreaming={isStreaming}
sources={sources}
ref={isLastPair ? latestMessagePairRef : undefined}
/>
{index !== messagePairs.length - 1 && (
<Separator className="my-12" />
)}
</Fragment>
);
})}
</>
)
}
{
(!isAutoScrollEnabled && status === "streaming") && (
<div className="absolute bottom-5 left-0 right-0 h-10 flex flex-row items-center justify-center">
<Button
variant="outline"
size="icon"
className="rounded-full animate-bounce-slow h-8 w-8"
onClick={() => {
latestMessagePairRef.current?.scrollIntoView({
behavior: 'instant',
block: 'end',
inline: 'nearest',
});
}}
>
<ArrowDownIcon className="w-4 h-4" />
</Button>
</div>
)
}
</ScrollArea>
{!isChatReadonly && (
<div className="border rounded-md w-full max-w-3xl mx-auto mb-8 shadow-sm">
<CustomSlateEditor>
<ChatBox
onSubmit={onSubmit}
className="min-h-[80px]"
preferredSuggestionsBoxPlacement="top-start"
isGenerating={status === "streaming" || status === "submitted"}
onStop={stop}
languageModels={languageModels}
selectedSearchScopes={selectedSearchScopes}
searchContexts={searchContexts}
/>
<div className="w-full flex flex-row items-center bg-accent rounded-b-md px-2">
<ChatBoxToolbar
languageModels={languageModels}
repos={repos}
searchContexts={searchContexts}
selectedSearchScopes={selectedSearchScopes}
onSelectedSearchScopesChange={onSelectedSearchScopesChange}
isContextSelectorOpen={isContextSelectorOpen}
onContextSelectorOpenChanged={setIsContextSelectorOpen}
/>
</div>
</CustomSlateEditor>
</div>
)}
</>
);
}