@retrivora-ai/rag-engine 2.3.8 → 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)
@@ -11,6 +11,19 @@ interface FileState {
11
11
  error?: string;
12
12
  }
13
13
 
14
+ function decodeLicenseTier(licenseKey?: string): string {
15
+ if (!licenseKey) return 'free';
16
+ try {
17
+ const parts = licenseKey.split('.');
18
+ if (parts.length >= 2) {
19
+ const base64 = parts[1].replace(/-/g, '+').replace(/_/g, '/');
20
+ const payload = JSON.parse(atob(base64));
21
+ return payload?.tier || 'free';
22
+ }
23
+ } catch { /* ignore */ }
24
+ return 'free';
25
+ }
26
+
14
27
  export function DocumentUpload({ namespace, uploadUrl, retrivoraApiBase, onUploadComplete, className = '' }: DocumentUploadProps) {
15
28
  const { ui, embedding, projectId, licenseKey, headers: configHeaders, retrivoraApiBase: configuredApiBase } = useConfig();
16
29
  const [fileStates, setFileStates] = useState<FileState[]>([]);
@@ -25,7 +38,17 @@ export function DocumentUpload({ namespace, uploadUrl, retrivoraApiBase, onUploa
25
38
  namespaceUsed: string;
26
39
  } | null>(null);
27
40
 
28
- const isFreeTier = !projectId || projectId.includes('free') || projectId.includes('demo');
41
+ const resolvedLicenseKey = licenseKey ||
42
+ configHeaders?.['x-license-key'] ||
43
+ configHeaders?.['X-License-Key'] ||
44
+ configHeaders?.['authorization']?.replace(/^Bearer\s+/i, '') ||
45
+ configHeaders?.['Authorization']?.replace(/^Bearer\s+/i, '');
46
+
47
+ const licenseTier = decodeLicenseTier(resolvedLicenseKey);
48
+ const isFreeTier = !projectId ||
49
+ projectId.includes('free') ||
50
+ projectId.includes('demo') ||
51
+ ['free_trial', 'free_tier', 'free', 'hobby'].includes(licenseTier.toLowerCase());
29
52
 
30
53
  const MULTI_DIMENSION_MODELS: Record<string, number[]> = {
31
54
  'text-embedding-3-small': [512, 1536],
@@ -195,22 +218,18 @@ export function DocumentUpload({ namespace, uploadUrl, retrivoraApiBase, onUploa
195
218
  <select
196
219
  value={dimension}
197
220
  onChange={(e) => setDimension(Number(e.target.value))}
198
- disabled={isUploading}
221
+ disabled={isUploading || availableDimensions.length <= 1}
199
222
  className="px-3 py-1.5 rounded-lg bg-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 text-slate-800 dark:text-white/90 outline-none focus:border-emerald-500 transition-colors text-sm font-medium cursor-pointer"
200
223
  >
201
- {COMMON_DIMENSIONS.map(dim => {
202
- const isDisabled = isFreeTier && dim !== 768;
203
- return (
204
- <option
205
- key={dim}
206
- value={dim}
207
- disabled={isDisabled}
208
- className="bg-white dark:bg-slate-900 text-slate-800 dark:text-white disabled:text-slate-400 dark:disabled:text-white/30"
209
- >
210
- {dim}
211
- </option>
212
- );
213
- })}
224
+ {availableDimensions.map(dim => (
225
+ <option
226
+ key={dim}
227
+ value={dim}
228
+ className="bg-white dark:bg-slate-900 text-slate-800 dark:text-white"
229
+ >
230
+ {dim}
231
+ </option>
232
+ ))}
214
233
  </select>
215
234
  </div>
216
235
  </div>
@@ -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) */
@@ -233,7 +235,10 @@ export function getEnvConfig(env: Record<string, string | undefined> = process.e
233
235
 
234
236
  // Default gateway: always use LiteLLM at llm.retrivora.com for end-users
235
237
  // End-users provide license key + project ID; the gateway validates and routes internally
236
- const defaultGatewayUrl = 'https://llm.retrivora.com/api/v1';
238
+ const controlPlaneUrl = readString(env, 'RETRIVORA_CONTROL_PLANE_URL') ?? readString(env, 'NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL');
239
+ const defaultGatewayUrl = controlPlaneUrl
240
+ ? `${controlPlaneUrl.replace(/\/$/, '')}/api/v1`
241
+ : 'https://llm.retrivora.com/api/v1';
237
242
 
238
243
  // ── Runtime-injected tier config (from /api/v1/config + /api/v1/credentials) ──
239
244
  // Priority: explicit env var > injected runtime config > static tier fallback
@@ -248,7 +253,7 @@ export function getEnvConfig(env: Record<string, string | undefined> = process.e
248
253
  // llmApiKey: LITELLM_MASTER_KEY env wins, then injected litellm key, then licenseKey
249
254
  const llmApiKey = readString(env, 'LITELLM_MASTER_KEY') ?? rt?.litellmApiKey ?? base?.llm?.apiKey ?? licenseKey;
250
255
  const llmProfile = readString(env, 'LLM_UNIVERSAL_PROFILE') ?? (base?.llm?.options?.profile as string) ?? 'litellm';
251
-
256
+
252
257
  console.log('[serverConfig] 🔧 LLM Configuration:', {
253
258
  baseUrl: llmBaseUrl,
254
259
  model: llmModel,
@@ -256,7 +261,7 @@ export function getEnvConfig(env: Record<string, string | undefined> = process.e
256
261
  hasApiKey: !!llmApiKey,
257
262
  source: rt?.llmModel ? 'runtime-injected' : 'env/fallback',
258
263
  });
259
-
264
+
260
265
  const defaultEmbeddingProvider = 'universal_rest';
261
266
  const embeddingProvider = (readEnum(env, 'EMBEDDING_PROVIDER', defaultEmbeddingProvider, EMBEDDING_PROVIDERS) ?? base?.embedding?.provider ?? defaultEmbeddingProvider) as EmbeddingProvider;
262
267
  const embeddingBaseUrl = readString(env, 'LITELLM_BASE_URL') ?? readString(env, 'EMBEDDING_BASE_URL') ?? readString(env, 'LLM_BASE_URL') ?? base?.embedding?.baseUrl ?? rt?.embeddingBaseUrl ?? rt?.llmBaseUrl ?? defaultGatewayUrl;
@@ -264,6 +269,14 @@ export function getEnvConfig(env: Record<string, string | undefined> = process.e
264
269
  // embeddingApiKey: same key as LLM (LiteLLM gateway handles both)
265
270
  const embeddingApiKey = readString(env, 'LITELLM_MASTER_KEY') ?? rt?.litellmApiKey ?? base?.embedding?.apiKey ?? licenseKey;
266
271
  const embeddingProfile = readString(env, 'EMBEDDING_UNIVERSAL_PROFILE') ?? (base?.embedding?.options?.profile as string) ?? 'litellm';
272
+
273
+ console.log('[serverConfig] 🔧 Embedding Configuration:', {
274
+ baseUrl: embeddingBaseUrl,
275
+ model: embeddingModel,
276
+ provider: embeddingProvider,
277
+ hasApiKey: !!embeddingApiKey,
278
+ source: rt?.embeddingModel ? 'runtime-injected' : 'env/fallback',
279
+ });
267
280
 
268
281
  return {
269
282
  projectId,
@@ -281,8 +294,8 @@ export function getEnvConfig(env: Record<string, string | undefined> = process.e
281
294
  model: llmModel,
282
295
  apiKey: llmApiKey,
283
296
  baseUrl: llmBaseUrl,
284
- systemPrompt: readString(env, 'LLM_SYSTEM_PROMPT'),
285
- 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),
286
299
  temperature: readNumber(env, 'LLM_TEMPERATURE', 0.7),
287
300
  options: {
288
301
  profile: llmProfile,
@@ -319,10 +332,10 @@ export function getEnvConfig(env: Record<string, string | undefined> = process.e
319
332
  allowUpload: (readString(env, 'NEXT_PUBLIC_ALLOW_UPLOAD') ?? readString(env, 'UI_ALLOW_UPLOAD') ?? 'false') === 'true',
320
333
  },
321
334
  rag: {
322
- topK: readNumber(env, 'RAG_TOP_K', 5),
335
+ topK: readNumber(env, 'RAG_TOP_K', rt?.topK ?? 5),
323
336
  scoreThreshold: readNumber(env, 'RAG_SCORE_THRESHOLD', 0),
324
- chunkSize: readNumber(env, 'RAG_CHUNK_SIZE', 1000),
325
- 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),
326
339
  filterableFields: readString(env, 'RAG_FILTERABLE_FIELDS')?.split(',').map(f => f.trim()),
327
340
  // Query pipeline toggles — read from .env.local
328
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
 
@@ -113,6 +113,7 @@ export class ConfigFetcher {
113
113
  for (const baseUrl of controlPlaneUrls) {
114
114
  try {
115
115
  const url = `${baseUrl}/api/v1/config?projectId=${encodeURIComponent(projectId)}`;
116
+ console.log(`[ConfigFetcher] Fetching config from: ${url}`);
116
117
  const res = await fetch(url, {
117
118
  method: 'GET',
118
119
  headers: {
@@ -122,6 +123,11 @@ export class ConfigFetcher {
122
123
  },
123
124
  });
124
125
 
126
+ console.log(`[ConfigFetcher] Response status: ${res.status}`);
127
+ if (!res.ok) {
128
+ console.warn(`[ConfigFetcher] Error text: ${await res.text()}`);
129
+ }
130
+
125
131
  if (res.ok) {
126
132
  const data = await res.json();
127
133
  // NOTE: The config API intentionally does NOT return vectorDb.apiKey (server-only secret).
@@ -998,6 +998,8 @@ export function createLicenseHandler(
998
998
 
999
999
  const projectId = body?.projectId || config.projectId || '';
1000
1000
 
1001
+ console.log(`[DEBUG] createLicenseHandler: projectId="${projectId}", body.projectId="${body?.projectId}", config.projectId="${config.projectId}"`);
1002
+
1001
1003
  const payload = await LicenseVerifier.verifyAsync(licenseKey, projectId);
1002
1004
 
1003
1005
  return NextResponse.json({
@@ -1579,6 +1581,8 @@ export function createRagHandler(
1579
1581
  if (pathname.endsWith('/suggestions')) return 'suggestions';
1580
1582
  if (pathname.endsWith('/feedback')) return 'feedback';
1581
1583
  if (pathname.endsWith('/history')) return 'history';
1584
+ if (pathname.endsWith('/history/clear')) return 'history/clear';
1585
+ if (pathname.endsWith('/sessions')) return 'sessions';
1582
1586
  } catch { /* silent */ }
1583
1587
 
1584
1588
  // 3. Fall back to resolved context params
@@ -1586,7 +1590,11 @@ export function createRagHandler(
1586
1590
  ? await context.params
1587
1591
  : context?.params;
1588
1592
 
1589
- 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
+ [];
1590
1598
  const joined = segments.join('/');
1591
1599
  return joined || 'chat';
1592
1600
  }