forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatPanel.tsx
More file actions
554 lines (512 loc) · 20.6 KB
/
Copy pathChatPanel.tsx
File metadata and controls
554 lines (512 loc) · 20.6 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
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
'use client';
import { useRef, useEffect, useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X, Send, Sparkles, Trash2, Brain, Paperclip, ArrowLeft } from 'lucide-react';
import { useChat as useChatContext } from './ChatContext';
import { ConfirmDialog } from '@/components/ui/ConfirmDialog';
import { FilePreview, ALLOWED_EXTENSIONS, MAX_FILES } from './FilePreview';
import { InlineVoiceRecorder } from './VoiceRecorder';
import { uploadChatFiles, getChatApps } from '@/lib/api';
import type { App } from '@/lib/api';
import { cn } from '@/lib/utils';
import { MixpanelManager } from '@/lib/analytics/mixpanel';
import { shouldSubmitComposerKey } from '@/lib/chatComposerKey';
import { parseChatEvidenceFromRecord } from '@/lib/chatEvidence';
import { ChatMarkdown } from './ChatMarkdown';
import { ChatEvidenceCard } from './ChatEvidenceCard';
import { PanelReveal } from '@/components/ui/PanelReveal';
interface FilePreviewItem {
file: File;
preview?: string;
uploading?: boolean;
uploadedId?: string;
}
// Quick prompts based on context
function getQuickPrompts(contextType: string | undefined): string[] {
switch (contextType) {
case 'conversation':
return [
'Summarize this conversation',
'What action items came from this?',
'What were the key decisions?',
];
case 'task':
return [
'Help me complete this task',
'Break this down into steps',
'Set a reminder for this',
];
case 'memory':
return ['Tell me more about this', 'When did I mention this?', 'Related memories'];
default:
return [
'What did I talk about today?',
'Show my pending tasks',
'What should I remember?',
];
}
}
export function ChatPanel() {
const { isOpen, closeChat, currentContext, selectedAppId, chat, clearAppContext } =
useChatContext();
const {
messages,
isLoading,
isStreaming,
streamingText,
currentThinking,
error,
sendMessage,
clearHistory,
loadHistory,
} = chat;
const [input, setInput] = useState('');
const [showClearDialog, setShowClearDialog] = useState(false);
const [isClearing, setIsClearing] = useState(false);
const [selectedFiles, setSelectedFiles] = useState<FilePreviewItem[]>([]);
const [isUploading, setIsUploading] = useState(false);
const [selectedApp, setSelectedApp] = useState<App | null>(null);
const messagesEndRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
// Fetch app info when selectedAppId changes
useEffect(() => {
if (selectedAppId) {
getChatApps()
.then((apps) => {
const app = apps.find((a) => a.id === selectedAppId);
setSelectedApp(app || null);
})
.catch(() => setSelectedApp(null));
} else {
setSelectedApp(null);
}
}, [selectedAppId]);
// Load history when panel opens
useEffect(() => {
if (isOpen) {
loadHistory();
}
}, [isOpen, loadHistory]);
// Scroll to bottom when messages change or streaming text updates
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
}, [messages, streamingText]);
// Focus input when panel opens
useEffect(() => {
if (isOpen) {
setTimeout(() => inputRef.current?.focus(), 300);
}
}, [isOpen]);
const quickPrompts = getQuickPrompts(currentContext?.type);
// Handle file selection
const handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
const files = Array.from(e.target.files || []);
if (files.length === 0) return;
// Limit to MAX_FILES
const availableSlots = MAX_FILES - selectedFiles.length;
const filesToAdd = files.slice(0, availableSlots);
// Create preview items
const newItems: FilePreviewItem[] = await Promise.all(
filesToAdd.map(async (file) => {
let preview: string | undefined;
if (file.type.startsWith('image/')) {
preview = URL.createObjectURL(file);
}
return { file, preview, uploading: true };
}),
);
setSelectedFiles((prev) => [...prev, ...newItems]);
// Upload files
setIsUploading(true);
try {
const uploadedFiles = await uploadChatFiles(filesToAdd);
// Update items with uploaded IDs
setSelectedFiles((prev) =>
prev.map((item) => {
const fileIndex = filesToAdd.indexOf(item.file);
const uploadedFile = fileIndex >= 0 ? uploadedFiles[fileIndex] : undefined;
if (uploadedFile) {
return { ...item, uploading: false, uploadedId: uploadedFile.id };
}
return item;
}),
);
} catch (err) {
console.error('Failed to upload files:', err);
// Remove failed uploads
setSelectedFiles((prev) => prev.filter((item) => !filesToAdd.includes(item.file)));
} finally {
setIsUploading(false);
}
// Reset input
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
};
// Remove file from selection
const handleRemoveFile = (index: number) => {
setSelectedFiles((prev) => {
const item = prev[index];
// Revoke object URL if it was an image
if (item.preview) {
URL.revokeObjectURL(item.preview);
}
return prev.filter((_, i) => i !== index);
});
};
// Handle voice transcript - append to input and focus
const handleVoiceTranscript = (transcript: string) => {
setInput((prev) => (prev ? `${prev} ${transcript}` : transcript));
inputRef.current?.focus();
};
const handleSend = async (text: string = input) => {
if (
(!text.trim() && !selectedFiles.some((item) => item.uploadedId)) ||
isLoading ||
isStreaming
)
return;
// Get file IDs from uploaded files
const fileIds = selectedFiles
.filter((item) => item.uploadedId)
.map((item) => item.uploadedId as string);
MixpanelManager.track('Chat Message Sent', {
message_length: text.length,
has_files: fileIds.length > 0,
file_count: fileIds.length,
});
setInput('');
setSelectedFiles([]);
await sendMessage(text, fileIds, currentContext);
};
const handleKeyDown = (e: React.KeyboardEvent) => {
if (shouldSubmitComposerKey(e)) {
e.preventDefault();
handleSend();
}
};
const handleClear = async () => {
setIsClearing(true);
try {
await clearHistory();
setShowClearDialog(false);
} finally {
setIsClearing(false);
}
};
const canSend =
(input.trim() || selectedFiles.some((f) => f.uploadedId)) &&
!isLoading &&
!isStreaming &&
!isUploading;
return (
<AnimatePresence>
{isOpen && (
<>
{/* Mobile backdrop */}
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.2 }}
className="fixed inset-0 bg-black/30 z-40 sm:hidden"
onClick={closeChat}
/>
{/* Panel - push/slide animation */}
<motion.div
initial={{ width: 0 }}
animate={{ width: 400 }}
exit={{ width: 0 }}
transition={{ type: 'spring', damping: 30, stiffness: 300 }}
className={cn(
'h-full flex-shrink-0 overflow-hidden',
'bg-bg-secondary border-l border-bg-tertiary',
'max-sm:fixed max-sm:inset-0 max-sm:z-50 max-sm:w-full',
)}
>
<PanelReveal className={cn('w-[400px] h-full flex flex-col', 'max-sm:w-full')}>
{/* Header */}
<div className="flex items-center justify-between p-4 border-b border-bg-tertiary">
<div className="flex items-center gap-3">
{/* Back button when in app-specific chat */}
{selectedAppId && (
<button
onClick={clearAppContext}
className="p-1.5 -ml-1 rounded-lg hover:bg-bg-tertiary transition-colors"
aria-label="Back to Omi chat"
title="Back to Omi"
>
<ArrowLeft className="w-4 h-4 text-text-tertiary" />
</button>
)}
<div className="w-8 h-8 rounded-full bg-white/[0.14] flex items-center justify-center">
<Sparkles className="w-4 h-4 text-text-primary" />
</div>
<div>
<h2 className="font-semibold text-text-primary">
{selectedApp ? `Chat with ${selectedApp.name}` : 'Chat with Omi'}
</h2>
{currentContext?.title && !selectedAppId && (
<p className="text-xs text-text-tertiary truncate max-w-[250px]">
Context: {currentContext.title}
</p>
)}
</div>
</div>
<div className="flex items-center gap-1">
{messages.length > 0 && (
<button
onClick={() => setShowClearDialog(true)}
className="p-2 rounded-lg hover:bg-bg-tertiary transition-colors"
aria-label="Clear chat"
title="Clear chat history"
>
<Trash2 className="w-4 h-4 text-text-quaternary hover:text-text-secondary" />
</button>
)}
<button
onClick={closeChat}
className="p-2 rounded-lg hover:bg-bg-tertiary transition-colors"
aria-label="Close chat"
>
<X className="w-5 h-5 text-text-secondary" />
</button>
</div>
</div>
{/* Error banner */}
{error && (
<div className="px-4 py-2 bg-error/10 border-b border-error/20">
<p className="text-sm text-error">{error}</p>
</div>
)}
{/* Quick prompts (shown when no messages) */}
{messages.length === 0 && !isLoading && (
<div className="p-4 border-b border-bg-tertiary">
<p className="text-xs text-text-quaternary mb-2">Quick prompts:</p>
<div className="flex flex-wrap gap-2">
{quickPrompts.map((prompt, i) => (
<button
key={i}
onClick={() => handleSend(prompt)}
disabled={isLoading || isStreaming}
className={cn(
'px-3 py-1.5 rounded-full text-sm',
'bg-bg-tertiary hover:bg-bg-quaternary',
'text-text-secondary hover:text-text-primary',
'transition-colors',
'disabled:opacity-50 disabled:cursor-not-allowed',
)}
>
{prompt}
</button>
))}
</div>
</div>
)}
{/* Messages */}
<div className="flex-1 overflow-y-auto p-4 space-y-4">
{messages.length === 0 && !isLoading ? (
<div className="flex flex-col items-center justify-center h-full text-center">
<div className="w-16 h-16 rounded-full bg-white/[0.08] flex items-center justify-center mb-4">
<Sparkles className="w-8 h-8 text-text-primary" />
</div>
<h3 className="text-lg font-medium text-text-primary mb-2">
Hi! I'm Omi
</h3>
<p className="text-text-tertiary max-w-[280px]">
Ask me anything about your conversations, tasks, or memories.
</p>
</div>
) : (
<>
{/* Rendered messages */}
{messages.map((message) => (
<div
key={message.id}
className={cn(
'flex',
message.sender === 'human' ? 'justify-end' : 'justify-start',
)}
>
{message.sender === 'human' ? (
<div className="max-w-[80%] rounded-2xl px-4 py-2.5 bg-text-primary text-bg-primary">
<p className="text-sm whitespace-pre-wrap">{message.text}</p>
</div>
) : (
<div className="max-w-[80%] min-w-0">
<div className="rounded-2xl px-4 py-2.5 bg-bg-tertiary text-text-primary">
<ChatMarkdown>{message.text}</ChatMarkdown>
</div>
<ChatEvidenceCard
envelope={parseChatEvidenceFromRecord(message)}
/>
</div>
)}
</div>
))}
{/* Thinking indicator */}
{currentThinking && (
<div className="flex justify-start">
<div className="max-w-[80%] rounded-2xl px-4 py-2.5 bg-bg-tertiary/50 border border-white/20">
<div className="flex items-center gap-2 text-text-primary mb-1">
<Brain className="w-3 h-3" />
<span className="text-xs font-medium">Thinking...</span>
</div>
<p className="text-xs text-text-quaternary whitespace-pre-wrap line-clamp-3">
{currentThinking}
</p>
</div>
</div>
)}
{/* Streaming text (AI response in progress) */}
{streamingText && (
<div className="flex justify-start">
<div className="max-w-[80%] rounded-2xl px-4 py-2.5 bg-bg-tertiary text-text-primary">
<ChatMarkdown isStreaming>{streamingText}</ChatMarkdown>
</div>
</div>
)}
{/* Loading indicator (before streaming starts) */}
{isStreaming && !streamingText && !currentThinking && (
<div className="flex justify-start">
<div className="bg-bg-tertiary rounded-2xl px-4 py-3">
<div className="flex gap-1">
<div
className="w-2 h-2 bg-text-quaternary rounded-full animate-bounce"
style={{ animationDelay: '0ms' }}
/>
<div
className="w-2 h-2 bg-text-quaternary rounded-full animate-bounce"
style={{ animationDelay: '150ms' }}
/>
<div
className="w-2 h-2 bg-text-quaternary rounded-full animate-bounce"
style={{ animationDelay: '300ms' }}
/>
</div>
</div>
</div>
)}
</>
)}
{/* Loading state when fetching history */}
{isLoading && messages.length === 0 && (
<div className="flex justify-center py-8">
<div className="flex gap-1">
<div
className="w-2 h-2 bg-text-quaternary rounded-full animate-bounce"
style={{ animationDelay: '0ms' }}
/>
<div
className="w-2 h-2 bg-text-quaternary rounded-full animate-bounce"
style={{ animationDelay: '150ms' }}
/>
<div
className="w-2 h-2 bg-text-quaternary rounded-full animate-bounce"
style={{ animationDelay: '300ms' }}
/>
</div>
</div>
)}
<div ref={messagesEndRef} />
</div>
{/* Input area */}
<div className="border-t border-bg-tertiary">
{/* File preview bar */}
{selectedFiles.length > 0 && (
<FilePreview
files={selectedFiles}
onRemove={handleRemoveFile}
disabled={isLoading || isStreaming}
/>
)}
<div className="p-4">
<div className="flex items-center gap-2">
{/* File attach button */}
<button
onClick={() => fileInputRef.current?.click()}
disabled={
isLoading || isStreaming || selectedFiles.length >= MAX_FILES
}
className={cn(
'p-2 rounded-lg flex-shrink-0',
'text-text-tertiary hover:text-text-primary hover:bg-bg-tertiary',
'disabled:opacity-50 disabled:cursor-not-allowed',
'transition-colors',
)}
title={
selectedFiles.length >= MAX_FILES
? `Max ${MAX_FILES} files`
: 'Attach file'
}
>
<Paperclip className="w-5 h-5" />
</button>
<input
ref={fileInputRef}
type="file"
multiple
accept={ALLOWED_EXTENSIONS}
onChange={handleFileSelect}
className="hidden"
/>
{/* Text input */}
<input
ref={inputRef}
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Ask anything..."
disabled={isLoading || isStreaming}
className={cn(
'flex-1 px-4 py-3 rounded-xl',
'bg-bg-tertiary border border-bg-quaternary',
'text-text-primary placeholder:text-text-quaternary',
'focus:outline-none focus:ring-2 focus:ring-white/25',
'transition-shadow',
'disabled:opacity-50 disabled:cursor-not-allowed',
)}
/>
{/* Inline voice recorder */}
<InlineVoiceRecorder
onTranscript={handleVoiceTranscript}
disabled={isLoading || isStreaming}
/>
{/* Send button */}
<button
onClick={() => handleSend()}
disabled={!canSend}
className={cn(
'p-3 rounded-xl flex-shrink-0',
'bg-text-primary text-bg-primary hover:bg-text-primary/90',
'disabled:opacity-50 disabled:cursor-not-allowed',
'transition-colors',
)}
aria-label="Send message"
>
<Send className="w-5 h-5 text-white" />
</button>
</div>
</div>
</div>
</PanelReveal>
</motion.div>
{/* Clear chat confirmation dialog */}
<ConfirmDialog
open={showClearDialog}
onOpenChange={setShowClearDialog}
title="Clear chat history?"
description="This will permanently delete all messages in this conversation. This action cannot be undone."
confirmLabel="Clear history"
cancelLabel="Cancel"
variant="danger"
onConfirm={handleClear}
isLoading={isClearing}
/>
</>
)}
</AnimatePresence>
);
}