@retrivora-ai/rag-engine 2.3.9 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -28,6 +28,9 @@ import {
28
28
  Mic,
29
29
  MicOff,
30
30
  Paperclip,
31
+ MessageSquare,
32
+ Plus,
33
+ Trash,
31
34
  } from 'lucide-react';
32
35
  import { DocumentUpload } from './DocumentUpload';
33
36
  import { MessageBubble } from './MessageBubble';
@@ -104,7 +107,9 @@ export function ChatWindow({
104
107
  apiUrl,
105
108
  retrivoraApiBase,
106
109
  licenseKey: licenseKeyProp,
107
- headers
110
+ headers,
111
+ sessionId: sessionIdProp,
112
+ showHistory = false,
108
113
  }: ChatWindowProps) {
109
114
  const {
110
115
  ui,
@@ -123,15 +128,94 @@ export function ChatWindow({
123
128
  const windowRef = useRef<HTMLDivElement>(null);
124
129
  const bottomRef = useRef<HTMLDivElement>(null);
125
130
  const inputRef = useRef<HTMLTextAreaElement>(null);
126
- const { messages, send, clear, isLoading, error, stop, submitFeedback } = useRagChat(projectId, {
131
+
132
+ // Manage active session ID internally if showHistory is enabled
133
+ const [internalSessionId, setInternalSessionId] = useState(sessionIdProp || 'default');
134
+ const activeSessionId = sessionIdProp || internalSessionId;
135
+
136
+ const {
137
+ messages,
138
+ send,
139
+ clear,
140
+ isLoading,
141
+ error,
142
+ stop,
143
+ submitFeedback,
144
+ loadHistory,
145
+ clearHistory: dbClearHistory
146
+ } = useRagChat(projectId, {
127
147
  namespace: projectId,
128
148
  apiUrl,
129
149
  retrivoraApiBase: effectiveApiBase,
130
150
  licenseKey: effectiveLicenseKey,
131
151
  headers: effectiveHeaders,
132
152
  persist: projectSettings?.widget.persistConversations,
153
+ sessionId: activeSessionId,
133
154
  });
134
155
 
156
+ // Automatically fetch conversation history when activeSessionId changes
157
+ useEffect(() => {
158
+ if (activeSessionId) {
159
+ loadHistory(activeSessionId);
160
+ }
161
+ }, [activeSessionId, loadHistory]);
162
+
163
+ const [sessions, setSessions] = useState<{ id: string; title: string; lastMessageAt?: string }[]>([]);
164
+
165
+ const fetchSessions = useCallback(async () => {
166
+ try {
167
+ const base = effectiveApiBase || '/api/retrivora';
168
+ const res = await fetch(`${base}/sessions`);
169
+ if (res.ok) {
170
+ const data = await res.json();
171
+ if (data.sessions) {
172
+ const normalized = data.sessions.map((s: any) => {
173
+ if (typeof s === 'string') {
174
+ let lastMsgTime: string | undefined = undefined;
175
+ try {
176
+ const parts = s.split('_');
177
+ if (parts.length > 1) {
178
+ const ts = parseInt(parts[1], 10);
179
+ if (!isNaN(ts)) {
180
+ lastMsgTime = new Date(ts).toISOString();
181
+ }
182
+ }
183
+ } catch {}
184
+ return {
185
+ id: s,
186
+ title: s.startsWith('session_')
187
+ ? 'Chat Session'
188
+ : s === 'default' ? 'Main Session' : s,
189
+ lastMessageAt: lastMsgTime
190
+ };
191
+ }
192
+ return {
193
+ id: s?.id || String(s),
194
+ title: s?.title || (s?.id && s.id.startsWith('session_') ? `Chat Session` : s?.id || String(s)),
195
+ lastMessageAt: s?.lastMessageAt
196
+ };
197
+ });
198
+ setSessions(normalized);
199
+ }
200
+ }
201
+ } catch (e) {
202
+ console.warn('[ChatWindow] Failed to load sessions list:', e);
203
+ }
204
+ }, [effectiveApiBase]);
205
+
206
+ useEffect(() => {
207
+ if (showHistory && mounted) {
208
+ fetchSessions();
209
+ }
210
+ }, [showHistory, mounted, fetchSessions, activeSessionId]);
211
+
212
+ // Refresh sessions list when a stream finishes so new chats appear dynamically in the sidebar
213
+ useEffect(() => {
214
+ if (!isLoading && showHistory && mounted) {
215
+ fetchSessions();
216
+ }
217
+ }, [isLoading, showHistory, mounted, fetchSessions]);
218
+
135
219
  const [suggestions, setSuggestions] = useState<string[]>([]);
136
220
  const [isSuggesting, setIsSuggesting] = useState(false);
137
221
 
@@ -304,10 +388,20 @@ export function ChatWindow({
304
388
  }
305
389
  };
306
390
 
307
- const clearHistory = () => {
391
+ const clearHistory = async () => {
308
392
  clear();
309
393
  setSuggestions([]);
310
394
  setIsSuggesting(false);
395
+ if (activeSessionId) {
396
+ try {
397
+ await dbClearHistory(activeSessionId);
398
+ if (showHistory) {
399
+ fetchSessions();
400
+ }
401
+ } catch (e) {
402
+ console.error('[ChatWindow] Failed to clear remote history:', e);
403
+ }
404
+ }
311
405
  };
312
406
 
313
407
  const isEmpty = messages.length === 0;
@@ -362,23 +456,154 @@ export function ChatWindow({
362
456
  return (
363
457
  <div
364
458
  ref={windowRef}
365
- className={`relative flex flex-col h-full flex-1 border border-slate-200 dark:border-white/10 shadow-2xl transition-all duration-300 ${currentRadius} ${isGlass
459
+ className={`relative flex h-full flex-1 border border-slate-200 dark:border-white/10 shadow-2xl transition-all duration-300 ${currentRadius} ${isGlass
366
460
  ? 'bg-white/90 dark:bg-[#0f0f1a]/90 backdrop-blur-xl'
367
461
  : 'bg-white dark:bg-[#0f0f1a]'
368
462
  } ${className}`}
369
463
  style={{ '--primary': ui.primaryColor, '--accent': ui.accentColor, ...style } as React.CSSProperties}
370
464
  >
371
- {/* Resize Handle (Top-Left) */}
372
- {onResizeStart && (
373
- <div
374
- onMouseDown={onResizeStart}
375
- className="absolute top-0 left-0 w-6 h-6 cursor-nw-resize z-[100] group flex items-start justify-start p-1"
376
- title="Drag to resize"
377
- >
378
- <div className="w-2.5 h-2.5 border-t-2 border-l-2 border-slate-300 dark:border-white/20 group-hover:border-slate-500 dark:group-hover:border-white/50 transition-colors rounded-tl-[2px]" />
465
+ {/* Left History Sidebar */}
466
+ {showHistory && (
467
+ <div className="w-64 border-r border-slate-200 dark:border-white/10 bg-slate-50 dark:bg-[#131322] flex flex-col h-full shrink-0 select-none">
468
+ {/* Sidebar Header / New Chat */}
469
+ <div className="p-3 border-b border-slate-200 dark:border-white/10">
470
+ <button
471
+ onClick={() => {
472
+ const newId = `session_${Date.now()}`;
473
+ setInternalSessionId(newId);
474
+ setSessions(prev => [
475
+ { id: newId, title: `Chat Session ${prev.length + 1}`, lastMessageAt: new Date().toISOString() },
476
+ ...prev
477
+ ]);
478
+ }}
479
+ className="w-full flex items-center justify-center gap-1.5 py-2 px-3 bg-[var(--primary)] hover:opacity-90 text-white rounded-xl text-xs font-bold transition-all shadow-sm cursor-pointer"
480
+ >
481
+ <Plus className="w-3.5 h-3.5 stroke-[2.5]" />
482
+ New Chat
483
+ </button>
484
+ </div>
485
+
486
+ {/* Sessions List */}
487
+ <div className="flex-1 overflow-y-auto p-2 space-y-4 scrollbar-thin">
488
+ {sessions.length === 0 ? (
489
+ <div className="text-center text-slate-400 dark:text-white/20 text-xs py-8 font-medium">
490
+ No previous chats
491
+ </div>
492
+ ) : (
493
+ (() => {
494
+ const now = new Date();
495
+ const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate());
496
+ const startOfYesterday = new Date(startOfToday.getTime() - 24 * 60 * 60 * 1000);
497
+ const startOf7DaysAgo = new Date(startOfToday.getTime() - 7 * 24 * 60 * 60 * 1000);
498
+
499
+ const todayGroup: typeof sessions = [];
500
+ const yesterdayGroup: typeof sessions = [];
501
+ const previousGroup: typeof sessions = [];
502
+ const olderGroup: typeof sessions = [];
503
+
504
+ for (const s of sessions) {
505
+ const date = s.lastMessageAt ? new Date(s.lastMessageAt) : new Date();
506
+ if (date >= startOfToday) {
507
+ todayGroup.push(s);
508
+ } else if (date >= startOfYesterday) {
509
+ yesterdayGroup.push(s);
510
+ } else if (date >= startOf7DaysAgo) {
511
+ previousGroup.push(s);
512
+ } else {
513
+ olderGroup.push(s);
514
+ }
515
+ }
516
+
517
+ const renderGroup = (title: string, list: typeof sessions) => {
518
+ if (list.length === 0) return null;
519
+ return (
520
+ <div className="space-y-1.5">
521
+ <div className="flex items-center px-2 py-1 select-none">
522
+ <span className="text-[9px] font-black uppercase tracking-wider text-slate-400 dark:text-white/30">{title}</span>
523
+ <div className="flex-grow border-t border-slate-200 dark:border-white/10 ml-2" />
524
+ </div>
525
+ {list.map((s) => {
526
+ const isActive = s.id === activeSessionId;
527
+ const timeString = s.lastMessageAt
528
+ ? new Date(s.lastMessageAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
529
+ : '';
530
+
531
+ return (
532
+ <div
533
+ key={s.id}
534
+ className={`group relative flex items-center justify-between p-2 rounded-xl text-xs font-semibold transition-all ${
535
+ isActive
536
+ ? 'bg-slate-200/70 dark:bg-white/10 text-slate-900 dark:text-white'
537
+ : 'text-slate-500 hover:bg-slate-200/30 dark:hover:bg-white/5 hover:text-slate-800 dark:hover:text-slate-200'
538
+ }`}
539
+ >
540
+ <button
541
+ onClick={() => setInternalSessionId(s.id)}
542
+ className="flex-1 flex items-center gap-2 text-left min-w-0 pr-6 cursor-pointer"
543
+ >
544
+ <MessageSquare className="w-3.5 h-3.5 opacity-60 shrink-0 mt-0.5" />
545
+ <div className="truncate flex-1">
546
+ <div className="truncate leading-snug">{s.title || 'Conversation'}</div>
547
+ {timeString && (
548
+ <div className="text-[10px] text-slate-400 dark:text-white/30 font-medium mt-0.5">
549
+ {timeString}
550
+ </div>
551
+ )}
552
+ </div>
553
+ </button>
554
+
555
+ <button
556
+ onClick={async (e) => {
557
+ e.stopPropagation();
558
+ try {
559
+ await dbClearHistory(s.id);
560
+ setSessions(prev => prev.filter(x => x.id !== s.id));
561
+ if (activeSessionId === s.id) {
562
+ setInternalSessionId('default');
563
+ }
564
+ } catch (err) {
565
+ console.error('Failed to delete session:', err);
566
+ }
567
+ }}
568
+ title="Delete conversation"
569
+ className="absolute right-2 opacity-0 group-hover:opacity-100 hover:text-rose-500 dark:hover:text-rose-400 p-1 rounded-md hover:bg-slate-200 dark:hover:bg-white/10 transition-all cursor-pointer text-slate-400"
570
+ >
571
+ <Trash className="w-3.5 h-3.5" />
572
+ </button>
573
+ </div>
574
+ );
575
+ })}
576
+ </div>
577
+ );
578
+ };
579
+
580
+ return (
581
+ <>
582
+ {renderGroup('Today', todayGroup)}
583
+ {renderGroup('Yesterday', yesterdayGroup)}
584
+ {renderGroup('Previous 7 Days', previousGroup)}
585
+ {renderGroup('Older', olderGroup)}
586
+ </>
587
+ );
588
+ })()
589
+ )}
590
+ </div>
379
591
  </div>
380
592
  )}
381
- {/* ── Header ── */}
593
+
594
+ {/* Main Chat Viewport */}
595
+ <div className="relative flex flex-col h-full flex-1 min-w-0">
596
+ {/* Resize Handle (Top-Left) */}
597
+ {onResizeStart && (
598
+ <div
599
+ onMouseDown={onResizeStart}
600
+ className="absolute top-0 left-0 w-6 h-6 cursor-nw-resize z-[100] group flex items-start justify-start p-1"
601
+ title="Drag to resize"
602
+ >
603
+ <div className="w-2.5 h-2.5 border-t-2 border-l-2 border-slate-300 dark:border-white/20 group-hover:border-slate-500 dark:group-hover:border-white/50 transition-colors rounded-tl-[2px]" />
604
+ </div>
605
+ )}
606
+ {/* ── Header ── */}
382
607
  <div
383
608
  className="flex items-center justify-between px-5 py-4 border-b border-slate-200 dark:border-white/10"
384
609
  style={{ background: `linear-gradient(135deg, ${ui.primaryColor}15, ${ui.accentColor}10)` }}
@@ -521,21 +746,38 @@ export function ChatWindow({
521
746
  )}
522
747
  </div>
523
748
  </div>
524
- ) : (
525
- messages.map((msg, index) => (
526
- <MessageBubble
527
- key={msg.id}
528
- message={msg}
529
- sources={msg.sources}
530
- isStreaming={isLoading && index === messages.length - 1 && msg.role === 'assistant'}
531
- primaryColor={ui.primaryColor}
532
- accentColor={ui.accentColor}
533
- onAddToCart={onAddToCart}
534
- viewportSize={viewportSize}
535
- onFeedback={submitFeedback}
536
- />
537
- ))
538
- )}
749
+ ) : (() => {
750
+ let lastDayGroup = '';
751
+ return messages.map((msg, index) => {
752
+ const currentDayGroup = formatMessageDayLegend(msg.createdAt);
753
+ const showDaySeparator = currentDayGroup !== lastDayGroup;
754
+ lastDayGroup = currentDayGroup;
755
+
756
+ return (
757
+ <React.Fragment key={msg.id}>
758
+ {showDaySeparator && (
759
+ <div className="flex items-center my-6 select-none justify-center w-full">
760
+ <div className="flex-grow border-t border-slate-200 dark:border-white/10" />
761
+ <span className="mx-4 text-[9px] font-black text-slate-400 dark:text-zinc-500 uppercase tracking-widest bg-slate-100 dark:bg-zinc-900 border border-slate-200 dark:border-zinc-800 px-3 py-1 rounded-full shrink-0">
762
+ {currentDayGroup}
763
+ </span>
764
+ <div className="flex-grow border-t border-slate-200 dark:border-white/10" />
765
+ </div>
766
+ )}
767
+ <MessageBubble
768
+ message={msg}
769
+ sources={msg.sources}
770
+ isStreaming={isLoading && index === messages.length - 1 && msg.role === 'assistant'}
771
+ primaryColor={ui.primaryColor}
772
+ accentColor={ui.accentColor}
773
+ onAddToCart={onAddToCart}
774
+ viewportSize={viewportSize}
775
+ onFeedback={submitFeedback}
776
+ />
777
+ </React.Fragment>
778
+ );
779
+ });
780
+ })()}
539
781
 
540
782
  {/* Typing indicator (only if assistant hasn't started replying yet) */}
541
783
  {isLoading && messages[messages.length - 1]?.role !== 'assistant' && (
@@ -679,6 +921,32 @@ export function ChatWindow({
679
921
  Press Enter to send · Shift+Enter for new line
680
922
  </p>
681
923
  </div>
924
+ </div>
682
925
  </div>
683
926
  );
684
927
  }
928
+
929
+ function formatMessageDayLegend(dateStr?: string | Date): string {
930
+ if (!dateStr) return 'Today';
931
+ try {
932
+ const d = new Date(dateStr);
933
+ const now = new Date();
934
+
935
+ // Check if today
936
+ if (d.toDateString() === now.toDateString()) {
937
+ return 'Today';
938
+ }
939
+
940
+ // Check if yesterday
941
+ const yesterday = new Date(now);
942
+ yesterday.setDate(now.getDate() - 1);
943
+ if (d.toDateString() === yesterday.toDateString()) {
944
+ return 'Yesterday';
945
+ }
946
+
947
+ // Otherwise return formatted date
948
+ return d.toLocaleDateString([], { weekday: 'long', month: 'short', day: 'numeric' });
949
+ } catch {
950
+ return 'Today';
951
+ }
952
+ }
@@ -38,7 +38,24 @@ export function ConfigProvider({
38
38
  const headersInput = config?.headers;
39
39
  const retrivoraApiBaseInput = config?.retrivoraApiBase;
40
40
  const embeddingInput = config?.embedding;
41
- const uiInput = config?.ui;
41
+ const uiInput = useMemo(() => {
42
+ const flatUi: Partial<UIConfig> = {};
43
+ if (config?.primaryColor) flatUi.primaryColor = config.primaryColor;
44
+ if (config?.secondaryColor) flatUi.accentColor = config.secondaryColor;
45
+ if (config?.accentColor) flatUi.accentColor = config.accentColor;
46
+ if (config?.theme) flatUi.theme = config.theme;
47
+ if (config?.borderRadius) flatUi.borderRadius = config.borderRadius;
48
+ if (config?.visualStyle) flatUi.visualStyle = config.visualStyle;
49
+ return { ...flatUi, ...config?.ui };
50
+ }, [
51
+ config?.ui,
52
+ config?.primaryColor,
53
+ config?.secondaryColor,
54
+ config?.accentColor,
55
+ config?.theme,
56
+ config?.borderRadius,
57
+ config?.visualStyle
58
+ ]);
42
59
  const explicitSettings = useMemo(
43
60
  () => projectSettingsInput
44
61
  ? normalizeProjectSettings(projectId, projectSettingsInput)
@@ -42,6 +42,7 @@ export interface LicenseTierConfig {
42
42
  requestsPerMinute: number;
43
43
  tokensPerDay: number;
44
44
  };
45
+ systemPrompt?: string;
45
46
  }
46
47
 
47
48
  export interface ProviderCredentials {
@@ -219,8 +220,9 @@ export class LicenseConfigResolver {
219
220
  provider: llmProvider,
220
221
  model: tierConfig.llmModel,
221
222
  apiKey: llmApiKey,
222
- maxTokens: tierConfig.maxTokens,
223
+ maxTokens: tierConfig?.maxTokens,
223
224
  temperature: 0.7,
225
+ systemPrompt: tierConfig?.systemPrompt,
224
226
  options: {},
225
227
  };
226
228
 
@@ -152,6 +152,7 @@ export interface UIConfig {
152
152
  allowResize?: boolean;
153
153
  /** Whether to enable voice search input. Defaults to true. */
154
154
  enableVoiceInput?: boolean;
155
+ theme?: 'light' | 'dark' | 'system';
155
156
  }
156
157
 
157
158
  // ---------------------------------------------------------------------------
@@ -34,6 +34,8 @@ import {
34
34
  export interface RuntimeTierConfig {
35
35
  llmModel?: string;
36
36
  embeddingModel?: string;
37
+ /** Custom system prompt from project configuration */
38
+ systemPrompt?: string;
37
39
  /** LiteLLM master key for authenticating with llm.retrivora.com */
38
40
  litellmApiKey?: string;
39
41
  /** LiteLLM gateway base URL (defaults to https://llm.retrivora.com/api/v1) */
@@ -292,8 +294,8 @@ export function getEnvConfig(env: Record<string, string | undefined> = process.e
292
294
  model: llmModel,
293
295
  apiKey: llmApiKey,
294
296
  baseUrl: llmBaseUrl,
295
- systemPrompt: readString(env, 'LLM_SYSTEM_PROMPT'),
296
- maxTokens: readNumber(env, 'LLM_MAX_TOKENS', 4096),
297
+ systemPrompt: readString(env, 'LLM_SYSTEM_PROMPT') ?? rt?.systemPrompt,
298
+ maxTokens: readNumber(env, 'LLM_MAX_TOKENS', rt?.maxTokens ?? 4096),
297
299
  temperature: readNumber(env, 'LLM_TEMPERATURE', 0.7),
298
300
  options: {
299
301
  profile: llmProfile,
@@ -330,10 +332,10 @@ export function getEnvConfig(env: Record<string, string | undefined> = process.e
330
332
  allowUpload: (readString(env, 'NEXT_PUBLIC_ALLOW_UPLOAD') ?? readString(env, 'UI_ALLOW_UPLOAD') ?? 'false') === 'true',
331
333
  },
332
334
  rag: {
333
- topK: readNumber(env, 'RAG_TOP_K', 5),
335
+ topK: readNumber(env, 'RAG_TOP_K', rt?.topK ?? 5),
334
336
  scoreThreshold: readNumber(env, 'RAG_SCORE_THRESHOLD', 0),
335
- chunkSize: readNumber(env, 'RAG_CHUNK_SIZE', 1000),
336
- chunkOverlap: readNumber(env, 'RAG_CHUNK_OVERLAP', 200),
337
+ chunkSize: readNumber(env, 'RAG_CHUNK_SIZE', rt?.chunkSize ?? 1000),
338
+ chunkOverlap: readNumber(env, 'RAG_CHUNK_OVERLAP', rt?.chunkOverlap ?? 200),
337
339
  filterableFields: readString(env, 'RAG_FILTERABLE_FIELDS')?.split(',').map(f => f.trim()),
338
340
  // Query pipeline toggles — read from .env.local
339
341
  useQueryTransformation: readString(env, 'RAG_USE_QUERY_TRANSFORMATION') === 'true',
@@ -25,6 +25,7 @@ export const DEFAULT_CONFIG: ClientConfig = {
25
25
  allowUpload: true,
26
26
  allowResize: true,
27
27
  enableVoiceInput: true,
28
+ theme: 'light'
28
29
  },
29
30
  };
30
31
 
@@ -1581,6 +1581,8 @@ export function createRagHandler(
1581
1581
  if (pathname.endsWith('/suggestions')) return 'suggestions';
1582
1582
  if (pathname.endsWith('/feedback')) return 'feedback';
1583
1583
  if (pathname.endsWith('/history')) return 'history';
1584
+ if (pathname.endsWith('/history/clear')) return 'history/clear';
1585
+ if (pathname.endsWith('/sessions')) return 'sessions';
1584
1586
  } catch { /* silent */ }
1585
1587
 
1586
1588
  // 3. Fall back to resolved context params
@@ -1588,7 +1590,11 @@ export function createRagHandler(
1588
1590
  ? await context.params
1589
1591
  : context?.params;
1590
1592
 
1591
- const segments: string[] = resolvedParams?.retrivora || resolvedParams?.params?.retrivora || [];
1593
+ const segments: string[] = resolvedParams?.retrivora ||
1594
+ resolvedParams?.params?.retrivora ||
1595
+ resolvedParams?.rag ||
1596
+ resolvedParams?.params?.rag ||
1597
+ [];
1592
1598
  const joined = segments.join('/');
1593
1599
  return joined || 'chat';
1594
1600
  }