-
Notifications
You must be signed in to change notification settings - Fork 4.5k
Expand file tree
/
Copy pathChatPanel.tsx
More file actions
427 lines (402 loc) · 14.9 KB
/
Copy pathChatPanel.tsx
File metadata and controls
427 lines (402 loc) · 14.9 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
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
'use client'
import { memo, useCallback, useState, useRef, useEffect, useId } from 'react'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'
import { Bot, User, Send, Square, Loader2, FileText, Lightbulb, StickyNote, Clock } from 'lucide-react'
import { MarkdownRenderer } from '@/components/ui/markdown-renderer'
import {
SourceChatMessage,
SourceChatContextIndicator,
BaseChatSession
} from '@/lib/types/api'
import { ModelSelector } from './ModelSelector'
import { ContextIndicator } from '@/components/common/ContextIndicator'
import { SessionManager } from '@/components/sources/SessionManager'
import { MessageActions } from '@/components/sources/MessageActions'
import { convertReferencesToCompactMarkdown, createCompactReferenceLinkComponent } from '@/lib/utils/source-references'
import { useModalManager } from '@/lib/hooks/use-modal-manager'
import { toast } from 'sonner'
import { useTranslation } from '@/lib/hooks/use-translation'
interface NotebookContextStats {
sourcesInsights: number
sourcesFull: number
notesCount: number
tokenCount?: number
charCount?: number
}
interface ChatPanelProps {
messages: SourceChatMessage[]
isStreaming: boolean
contextIndicators: SourceChatContextIndicator | null
onSendMessage: (message: string, modelOverride?: string) => void
onCancel?: () => void
modelOverride?: string
onModelChange?: (model?: string) => void
// Session management props
sessions?: BaseChatSession[]
currentSessionId?: string | null
onCreateSession?: (title: string) => void
onSelectSession?: (sessionId: string) => void
onDeleteSession?: (sessionId: string) => void
onUpdateSession?: (sessionId: string, title: string) => void
loadingSessions?: boolean
// Generic props for reusability
title?: string
contextType?: 'source' | 'notebook'
// Notebook context stats (for notebook chat)
notebookContextStats?: NotebookContextStats
// Notebook ID for saving notes
notebookId?: string
}
export function ChatPanel({
messages,
isStreaming,
contextIndicators,
onSendMessage,
onCancel,
modelOverride,
onModelChange,
sessions = [],
currentSessionId,
onCreateSession,
onSelectSession,
onDeleteSession,
onUpdateSession,
loadingSessions = false,
title,
contextType = 'source',
notebookContextStats,
notebookId
}: ChatPanelProps) {
const { t } = useTranslation()
const [sessionManagerOpen, setSessionManagerOpen] = useState(false)
const scrollAreaRef = useRef<HTMLDivElement>(null)
const messagesEndRef = useRef<HTMLDivElement>(null)
const { openModal } = useModalManager()
// Stable reference-click handler so memoized messages don't re-render on
// composer keystrokes (which no longer re-render this component at all, since
// the input state lives in the ChatComposer child).
const handleReferenceClick = useCallback((type: string, id: string) => {
const modalType = type === 'source_insight' ? 'insight' : type as 'source' | 'note' | 'insight'
try {
openModal(modalType, id)
// Note: The modal system uses URL parameters and doesn't throw errors for missing items.
// The modal component itself will handle displaying "not found" states.
// This try-catch is here for future enhancements or unexpected errors.
} catch {
toast.error(t('common.noResults'))
}
}, [openModal, t])
// Auto-scroll to bottom when new messages arrive
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
}, [messages])
return (
<>
<Card className="flex flex-col h-full flex-1 overflow-hidden">
<CardHeader className="pb-3 flex-shrink-0">
<div className="flex items-center justify-between">
<CardTitle className="flex items-center gap-2 text-xs font-semibold uppercase tracking-[0.13em] text-muted-foreground">
<span aria-hidden className="h-3.5 w-[3px] rounded-full bg-teal" />
{title || (contextType === 'source' ? t('chat.chatWith', { name: t('navigation.sources') }) : t('chat.chatWith', { name: t('common.notebook') }))}
</CardTitle>
{onSelectSession && onCreateSession && onDeleteSession && (
<Dialog open={sessionManagerOpen} onOpenChange={setSessionManagerOpen}>
<Button
variant="ghost"
size="sm"
className="gap-2 text-muted-foreground"
onClick={() => setSessionManagerOpen(true)}
disabled={loadingSessions}
>
<Clock className="h-4 w-4" />
<span className="text-xs">{t('chat.sessions')}</span>
</Button>
<DialogContent className="sm:max-w-[420px] p-0 overflow-hidden">
<DialogTitle className="sr-only">{t('chat.sessionsTitle')}</DialogTitle>
<SessionManager
sessions={sessions}
currentSessionId={currentSessionId ?? null}
onCreateSession={(title) => onCreateSession?.(title)}
onSelectSession={(sessionId) => {
onSelectSession(sessionId)
setSessionManagerOpen(false)
}}
onUpdateSession={(sessionId, title) => onUpdateSession?.(sessionId, title)}
onDeleteSession={(sessionId) => onDeleteSession?.(sessionId)}
loadingSessions={loadingSessions}
/>
</DialogContent>
</Dialog>
)}
</div>
</CardHeader>
<CardContent className="flex-1 flex flex-col min-h-0 p-0">
<ScrollArea className="flex-1 min-h-0 px-4" ref={scrollAreaRef}>
<div className="space-y-4 py-4">
{messages.length === 0 ? (
<div className="text-center text-muted-foreground py-8">
<Bot className="h-12 w-12 mx-auto mb-4 opacity-50" />
<p className="text-sm">
{t('chat.startConversation', { type: contextType === 'source' ? t('navigation.sources') : t('common.notebook') })}
</p>
<p className="text-xs mt-2">{t('chat.askQuestions')}</p>
</div>
) : (
messages.map((message) => (
<ChatMessage
key={message.id}
message={message}
notebookId={notebookId}
onReferenceClick={handleReferenceClick}
/>
))
)}
{isStreaming && (
<div className="flex gap-3 justify-start">
<div className="flex-shrink-0">
<div className="h-8 w-8 rounded-full bg-teal-tint flex items-center justify-center">
<Bot className="h-4 w-4 text-teal" />
</div>
</div>
<div className="rounded-lg px-4 py-2 bg-card border">
<Loader2 className="h-4 w-4 animate-spin" />
</div>
</div>
)}
<div ref={messagesEndRef} />
</div>
</ScrollArea>
{/* Context Indicators */}
{contextIndicators && (
<div className="border-t px-4 py-2">
<div className="flex flex-wrap gap-2 text-xs">
{contextIndicators.sources?.length > 0 && (
<Badge variant="outline" className="gap-1">
<FileText className="h-3 w-3" />
{contextIndicators.sources.length} {t('navigation.sources')}
</Badge>
)}
{contextIndicators.insights?.length > 0 && (
<Badge variant="outline" className="gap-1">
<Lightbulb className="h-3 w-3" />
{contextIndicators.insights.length} {contextIndicators.insights.length === 1 ? t('common.insight') : t('common.insights')}
</Badge>
)}
{contextIndicators.notes?.length > 0 && (
<Badge variant="outline" className="gap-1">
<StickyNote className="h-3 w-3" />
{contextIndicators.notes.length} {contextIndicators.notes.length === 1 ? t('common.note') : t('common.notes')}
</Badge>
)}
</div>
</div>
)}
{/* Notebook Context Indicator */}
{notebookContextStats && (
<ContextIndicator
sourcesInsights={notebookContextStats.sourcesInsights}
sourcesFull={notebookContextStats.sourcesFull}
notesCount={notebookContextStats.notesCount}
tokenCount={notebookContextStats.tokenCount}
charCount={notebookContextStats.charCount}
/>
)}
{/* Input Area */}
<ChatComposer
onSendMessage={onSendMessage}
onCancel={onCancel}
isStreaming={isStreaming}
modelOverride={modelOverride}
onModelChange={onModelChange}
/>
</CardContent>
</Card>
</>
)
}
// Composer owns the input state so keystrokes (including IME composition) only
// re-render this small component instead of the whole message history.
interface ChatComposerProps {
onSendMessage: (message: string, modelOverride?: string) => void
onCancel?: () => void
isStreaming: boolean
modelOverride?: string
onModelChange?: (model?: string) => void
}
function ChatComposer({
onSendMessage,
onCancel,
isStreaming,
modelOverride,
onModelChange
}: ChatComposerProps) {
const { t } = useTranslation()
const chatInputId = useId()
const [input, setInput] = useState('')
const handleSend = () => {
if (input.trim() && !isStreaming) {
onSendMessage(input.trim(), modelOverride)
setInput('')
}
}
const handleKeyDown = (e: React.KeyboardEvent) => {
// Detect platform for correct modifier key
const isMac = typeof navigator !== 'undefined' && navigator.userAgent.toUpperCase().indexOf('MAC') >= 0
const isModifierPressed = isMac ? e.metaKey : e.ctrlKey
if (e.key === 'Enter' && isModifierPressed) {
e.preventDefault()
handleSend()
}
}
// Detect platform for placeholder text
const isMac = typeof navigator !== 'undefined' && navigator.userAgent.toUpperCase().indexOf('MAC') >= 0
const keyHint = isMac ? '⌘+Enter' : 'Ctrl+Enter'
return (
<div className="flex-shrink-0 p-4 space-y-3 border-t">
{/* Model selector */}
{onModelChange && (
<div className="flex items-center justify-between">
<span className="text-xs text-muted-foreground">{t('chat.model')}</span>
<ModelSelector
currentModel={modelOverride}
onModelChange={onModelChange}
disabled={isStreaming}
/>
</div>
)}
<div className="flex gap-2 items-end min-w-0">
<Textarea
id={chatInputId}
name="chat-message"
autoComplete="off"
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={handleKeyDown}
placeholder={`${t('chat.sendPlaceholder')} (${t('chat.pressToSend', { key: keyHint })})`}
disabled={isStreaming}
className="flex-1 min-h-[40px] max-h-[100px] resize-none py-2 px-3 min-w-0"
rows={1}
/>
{isStreaming ? (
onCancel ? (
<Button
onClick={onCancel}
size="icon"
variant="secondary"
aria-label={t('chat.stop')}
title={t('chat.stop')}
className="h-[40px] w-[40px] flex-shrink-0"
>
<Square className="h-4 w-4" />
</Button>
) : (
// No cancel callback (e.g. notebook chat, which is not streamed) —
// show a disabled spinner rather than a dead Stop button.
<Button
disabled
size="icon"
aria-label={t('common.saving')}
className="h-[40px] w-[40px] flex-shrink-0"
>
<Loader2 className="h-4 w-4 animate-spin" />
</Button>
)
) : (
<Button
onClick={handleSend}
disabled={!input.trim()}
size="icon"
className="h-[40px] w-[40px] flex-shrink-0"
>
<Send className="h-4 w-4" />
</Button>
)}
</div>
</div>
)
}
// Single chat message row. Memoized so historical messages don't re-render when
// unrelated state (e.g. the composer input) changes.
interface ChatMessageProps {
message: SourceChatMessage
notebookId?: string
onReferenceClick: (type: string, id: string) => void
}
const ChatMessage = memo(function ChatMessage({
message,
notebookId,
onReferenceClick
}: ChatMessageProps) {
return (
<div
className={`flex gap-3 ${
message.type === 'human' ? 'justify-end' : 'justify-start'
}`}
>
{message.type === 'ai' && (
<div className="flex-shrink-0">
<div className="h-8 w-8 rounded-full bg-teal-tint flex items-center justify-center">
<Bot className="h-4 w-4 text-teal" />
</div>
</div>
)}
<div className="flex flex-col gap-2 max-w-[80%]">
<div
className={`rounded-lg px-4 py-2 border ${
message.type === 'human'
? 'bg-muted'
: 'bg-card'
}`}
>
{message.type === 'ai' ? (
<AIMessageContent
content={message.content}
onReferenceClick={onReferenceClick}
/>
) : (
<p className="text-sm break-all">{message.content}</p>
)}
</div>
{message.type === 'ai' && (
<MessageActions
content={message.content}
notebookId={notebookId}
/>
)}
</div>
{message.type === 'human' && (
<div className="flex-shrink-0">
<div className="h-8 w-8 rounded-full bg-muted border flex items-center justify-center">
<User className="h-4 w-4 text-muted-foreground" />
</div>
</div>
)}
</div>
)
})
// Helper component to render AI messages with clickable references
function AIMessageContent({
content,
onReferenceClick
}: {
content: string
onReferenceClick: (type: string, id: string) => void
}) {
const { t } = useTranslation()
// Convert references to compact markdown with numbered citations
const markdownWithCompactRefs = convertReferencesToCompactMarkdown(content, t('common.references'))
// Create custom link component for compact references
const LinkComponent = createCompactReferenceLinkComponent(onReferenceClick)
return (
<MarkdownRenderer components={{
a: LinkComponent
}}>
{markdownWithCompactRefs}
</MarkdownRenderer>
)
}