@retrivora-ai/rag-engine 2.4.2 → 2.4.5

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.
Files changed (140) hide show
  1. package/dist/{BatchProcessor-zbQMaZHm.d.mts → BatchProcessor-Csy_K1qQ.d.mts} +2 -0
  2. package/dist/{BatchProcessor-D42E706a.d.ts → BatchProcessor-Dg18zZGk.d.ts} +2 -0
  3. package/dist/handlers/index.js +31 -5
  4. package/dist/handlers/index.mjs +31 -5
  5. package/dist/index.d.mts +3 -3
  6. package/dist/index.d.ts +3 -3
  7. package/dist/index.js +41 -21
  8. package/dist/index.min.css +2 -0
  9. package/dist/index.mjs +41 -21
  10. package/dist/server.d.mts +2 -2
  11. package/dist/server.d.ts +2 -2
  12. package/dist/server.js +32 -5
  13. package/dist/server.mjs +32 -5
  14. package/package.json +5 -4
  15. package/src/LicensedRetrivora.ts +0 -278
  16. package/src/app/api/chat/route.ts +0 -4
  17. package/src/app/api/health/route.ts +0 -5
  18. package/src/app/api/ingest/route.ts +0 -27
  19. package/src/app/api/suggestions/route.ts +0 -5
  20. package/src/app/api/upload/route.ts +0 -5
  21. package/src/app/constants.tsx +0 -270
  22. package/src/app/favicon.ico +0 -0
  23. package/src/app/globals.css +0 -449
  24. package/src/app/layout.tsx +0 -22
  25. package/src/app/page.tsx +0 -64
  26. package/src/app/types.ts +0 -30
  27. package/src/browser.tsx +0 -139
  28. package/src/components/ChatWidget.tsx +0 -393
  29. package/src/components/ChatWindow.tsx +0 -952
  30. package/src/components/CodeViewer.tsx +0 -56
  31. package/src/components/ConfigProvider.tsx +0 -123
  32. package/src/components/DocumentUpload.tsx +0 -354
  33. package/src/components/DynamicChart.tsx +0 -297
  34. package/src/components/HourglassLoader.tsx +0 -87
  35. package/src/components/MarkdownComponents.tsx +0 -186
  36. package/src/components/MessageBubble.tsx +0 -498
  37. package/src/components/ObservabilityPanel.tsx +0 -374
  38. package/src/components/ProductCard.tsx +0 -107
  39. package/src/components/ProductCarousel.tsx +0 -97
  40. package/src/components/SourceCard.tsx +0 -61
  41. package/src/components/ThemeProvider.tsx +0 -8
  42. package/src/components/ThemeToggle.tsx +0 -29
  43. package/src/components/ThinkingBlock.tsx +0 -75
  44. package/src/components/UIDispatcher.tsx +0 -342
  45. package/src/components/VisualizationRenderer.tsx +0 -621
  46. package/src/components/constants.tsx +0 -503
  47. package/src/config/ConfigBuilder.ts +0 -285
  48. package/src/config/EmbeddingStrategy.ts +0 -148
  49. package/src/config/LicenseConfigResolver.ts +0 -298
  50. package/src/config/RagConfig.ts +0 -328
  51. package/src/config/UniversalProfiles.ts +0 -82
  52. package/src/config/constants.ts +0 -64
  53. package/src/config/serverConfig.ts +0 -378
  54. package/src/config/uiConstants.ts +0 -47
  55. package/src/core/BatchProcessor.ts +0 -385
  56. package/src/core/CircuitBreaker.ts +0 -118
  57. package/src/core/ConfigFetcher.ts +0 -220
  58. package/src/core/ConfigResolver.ts +0 -165
  59. package/src/core/ConfigValidator.ts +0 -197
  60. package/src/core/DatabaseStorage.ts +0 -526
  61. package/src/core/FreeTierLimitsGuard.ts +0 -281
  62. package/src/core/LLMRouter.ts +0 -79
  63. package/src/core/LangChainAgent.ts +0 -132
  64. package/src/core/LicenseValidator.ts +0 -284
  65. package/src/core/LicenseVerifier.ts +0 -261
  66. package/src/core/MultiAgentCoordinator.ts +0 -239
  67. package/src/core/Pipeline.ts +0 -1279
  68. package/src/core/PluginManager.ts +0 -277
  69. package/src/core/ProjectSettings.ts +0 -247
  70. package/src/core/ProviderHealthCheck.ts +0 -133
  71. package/src/core/ProviderInterfaces.ts +0 -37
  72. package/src/core/ProviderRegistry.ts +0 -156
  73. package/src/core/QueryProcessor.ts +0 -399
  74. package/src/core/Retrivora.ts +0 -98
  75. package/src/core/VectorPlugin.ts +0 -193
  76. package/src/core/mcp.ts +0 -261
  77. package/src/exceptions/index.ts +0 -131
  78. package/src/handlers/index.ts +0 -1625
  79. package/src/hooks/useHydrated.ts +0 -13
  80. package/src/hooks/useProjectSettings.ts +0 -105
  81. package/src/hooks/useRagChat.ts +0 -436
  82. package/src/hooks/useStoredMessages.ts +0 -64
  83. package/src/index.css +0 -4269
  84. package/src/index.ts +0 -137
  85. package/src/lib/plugin.ts +0 -24
  86. package/src/llm/ILLMProvider.ts +0 -60
  87. package/src/llm/LLMFactory.ts +0 -141
  88. package/src/llm/providers/AnthropicProvider.ts +0 -215
  89. package/src/llm/providers/GeminiProvider.ts +0 -311
  90. package/src/llm/providers/GroqProvider.ts +0 -184
  91. package/src/llm/providers/OllamaProvider.ts +0 -232
  92. package/src/llm/providers/OpenAIProvider.ts +0 -188
  93. package/src/llm/providers/QwenProvider.ts +0 -199
  94. package/src/llm/providers/UniversalLLMAdapter.ts +0 -422
  95. package/src/llm/utils.ts +0 -46
  96. package/src/providers/graphdb/BaseGraphProvider.ts +0 -43
  97. package/src/providers/graphdb/SimpleGraphProvider.ts +0 -66
  98. package/src/providers/vectordb/BaseVectorProvider.ts +0 -98
  99. package/src/providers/vectordb/ChromaDBProvider.ts +0 -130
  100. package/src/providers/vectordb/MilvusProvider.ts +0 -134
  101. package/src/providers/vectordb/MongoDBProvider.ts +0 -250
  102. package/src/providers/vectordb/MultiTablePostgresProvider.ts +0 -461
  103. package/src/providers/vectordb/PineconeProvider.ts +0 -295
  104. package/src/providers/vectordb/PostgreSQLProvider.ts +0 -227
  105. package/src/providers/vectordb/QdrantProvider.ts +0 -294
  106. package/src/providers/vectordb/RedisProvider.ts +0 -105
  107. package/src/providers/vectordb/UniversalVectorProvider.ts +0 -221
  108. package/src/providers/vectordb/WeaviateProvider.ts +0 -172
  109. package/src/rag/DocumentChunker.ts +0 -144
  110. package/src/rag/EntityExtractor.ts +0 -90
  111. package/src/rag/LlamaIndexIngestor.ts +0 -60
  112. package/src/rag/Reranker.ts +0 -106
  113. package/src/rendering/IntentClassifier.ts +0 -167
  114. package/src/rendering/RendererRegistry.ts +0 -164
  115. package/src/rendering/RuleEngine.ts +0 -67
  116. package/src/rendering/VisualizationDecisionEngine.ts +0 -164
  117. package/src/rendering/__tests__/VisualizationDecisionEngine.test.ts +0 -237
  118. package/src/rendering/index.ts +0 -12
  119. package/src/rendering/rules/Rule1SpecificInfoRule.ts +0 -28
  120. package/src/rendering/rules/Rule2ComparisonRule.ts +0 -24
  121. package/src/rendering/rules/Rule3ProductDiscoveryRule.ts +0 -28
  122. package/src/rendering/rules/Rule4AnalyticalRule.ts +0 -38
  123. package/src/rendering/rules/Rule5MixedResponseRule.ts +0 -29
  124. package/src/rendering/rules/Rule6SmallResultSetRule.ts +0 -24
  125. package/src/rendering/rules/Rule7LargeTableRule.ts +0 -35
  126. package/src/rendering/types.ts +0 -96
  127. package/src/server.ts +0 -156
  128. package/src/tailwind.css +0 -194
  129. package/src/telemetry/TelemetryService.ts +0 -330
  130. package/src/types/chat.ts +0 -89
  131. package/src/types/index.ts +0 -278
  132. package/src/types/pdf-parse.d.ts +0 -13
  133. package/src/types/props.ts +0 -169
  134. package/src/utils/DocumentParser.ts +0 -111
  135. package/src/utils/ProductExtractor.ts +0 -350
  136. package/src/utils/SchemaMapper.ts +0 -176
  137. package/src/utils/UITransformer.ts +0 -1812
  138. package/src/utils/synonyms.ts +0 -80
  139. package/src/utils/templateUtils.ts +0 -78
  140. package/src/version.ts +0 -6
@@ -1,13 +0,0 @@
1
- 'use client';
2
-
3
- import * as React from 'react';
4
-
5
- const emptySubscribe = () => () => {};
6
-
7
- export function useHydrated(): boolean {
8
- return React.useSyncExternalStore(
9
- emptySubscribe,
10
- () => true,
11
- () => false
12
- );
13
- }
@@ -1,105 +0,0 @@
1
- 'use client';
2
-
3
- import { useEffect, useMemo, useState } from 'react';
4
- import { ConfigFetcher, RemoteConfig } from '../core/ConfigFetcher';
5
- import {
6
- ProjectChatSettings,
7
- createDefaultProjectSettings,
8
- normalizeProjectSettings,
9
- } from '../core/ProjectSettings';
10
-
11
- export interface UseProjectSettingsOptions {
12
- licenseKey?: string;
13
- enabled?: boolean;
14
- initialSettings?: Partial<ProjectChatSettings>;
15
- }
16
-
17
- export interface UseProjectSettingsReturn {
18
- settings: ProjectChatSettings;
19
- remoteConfig: RemoteConfig | null;
20
- isLoading: boolean;
21
- error: string | null;
22
- reload: () => Promise<void>;
23
- }
24
-
25
- export function useProjectSettings(
26
- projectId: string,
27
- options: UseProjectSettingsOptions = {}
28
- ): UseProjectSettingsReturn {
29
- const initialSettings = useMemo(
30
- () => normalizeProjectSettings(projectId, options.initialSettings || createDefaultProjectSettings(projectId)),
31
- [options.initialSettings, projectId]
32
- );
33
- const [settings, setSettings] = useState<ProjectChatSettings>(initialSettings);
34
- const [remoteConfig, setRemoteConfig] = useState<RemoteConfig | null>(null);
35
- const [isLoading, setIsLoading] = useState(false);
36
- const [error, setError] = useState<string | null>(null);
37
-
38
- async function reload() {
39
- if (options.enabled === false || !options.licenseKey) {
40
- setSettings(initialSettings);
41
- setRemoteConfig(null);
42
- return;
43
- }
44
-
45
- setIsLoading(true);
46
- setError(null);
47
-
48
- try {
49
- const config = await ConfigFetcher.fetchRemoteConfig(projectId, options.licenseKey);
50
- setRemoteConfig(config);
51
- setSettings(config?.projectSettings || initialSettings);
52
- } catch (err) {
53
- const message = err instanceof Error ? err.message : 'Failed to load project settings';
54
- setError(message);
55
- setSettings(initialSettings);
56
- } finally {
57
- setIsLoading(false);
58
- }
59
- }
60
-
61
- useEffect(() => {
62
- let cancelled = false;
63
-
64
- async function load() {
65
- if (options.enabled === false || !options.licenseKey) {
66
- setSettings(initialSettings);
67
- setRemoteConfig(null);
68
- return;
69
- }
70
-
71
- setIsLoading(true);
72
- setError(null);
73
-
74
- try {
75
- const config = await ConfigFetcher.fetchRemoteConfig(projectId, options.licenseKey);
76
- if (!cancelled) {
77
- setRemoteConfig(config);
78
- setSettings(config?.projectSettings || initialSettings);
79
- }
80
- } catch (err) {
81
- if (!cancelled) {
82
- const message = err instanceof Error ? err.message : 'Failed to load project settings';
83
- setError(message);
84
- setSettings(initialSettings);
85
- }
86
- } finally {
87
- if (!cancelled) setIsLoading(false);
88
- }
89
- }
90
-
91
- load();
92
-
93
- return () => {
94
- cancelled = true;
95
- };
96
- }, [initialSettings, options.enabled, options.licenseKey, projectId]);
97
-
98
- return {
99
- settings,
100
- remoteConfig,
101
- isLoading,
102
- error,
103
- reload,
104
- };
105
- }
@@ -1,436 +0,0 @@
1
- 'use client';
2
-
3
- /**
4
- * useRagChat — headless React hook for the RAG chat pipeline.
5
- *
6
- * Use this when you want to build a COMPLETELY CUSTOM UI but still leverage
7
- * the RAG backend. The hook handles all state: messages, loading, errors,
8
- * localStorage persistence, and the /api/chat round-trip.
9
- *
10
- * Consumes the SSE stream format produced by `createStreamHandler`:
11
- * data: { type: "text", text: "..." }
12
- * data: { type: "metadata", sources: [...] }
13
- * data: { type: "error", error: "..." }
14
- *
15
- * Usage:
16
- * const { messages, send, clear, isLoading, error } = useRagChat('my-project');
17
- *
18
- * Then build any UI on top of the returned state.
19
- */
20
-
21
- import { useState, useCallback, useRef, useEffect } from 'react';
22
- import { VectorMatch, RagMessage, UseRagChatOptions, UseRagChatReturn, ObservabilityTrace } from '../types';
23
- import { useStoredMessages } from './useStoredMessages';
24
-
25
- // ─── SSE Frame Parser ──────────────────────────────────────────────────────────
26
-
27
- interface SseTextFrame { type: 'text'; text: string }
28
- interface SseThinkingFrame { type: 'thinking'; text: string }
29
- interface SseMetaFrame { type: 'metadata'; sources?: VectorMatch[]; thinkingMs?: number }
30
- interface SseErrorFrame { type: 'error'; error: string }
31
- interface SseUiFrame { type: 'ui_transformation'; data: unknown }
32
- interface SseObservabilityFrame { type: 'observability'; data: ObservabilityTrace }
33
- type SseFrame = SseTextFrame | SseThinkingFrame | SseMetaFrame | SseErrorFrame | SseUiFrame | SseObservabilityFrame;
34
-
35
- /**
36
- * Parse all complete SSE frames from a raw chunk string.
37
- * Handles cases where a single `read()` value contains multiple frames.
38
- */
39
- function parseSseChunk(raw: string): SseFrame[] {
40
- const frames: SseFrame[] = [];
41
- // Split on double-newline (SSE frame boundary)
42
- for (const block of raw.split('\n\n')) {
43
- for (const line of block.split('\n')) {
44
- if (!line.startsWith('data: ')) continue;
45
- try {
46
- const frame = JSON.parse(line.slice(6)) as SseFrame;
47
- if (frame && typeof frame === 'object' && 'type' in frame) {
48
- frames.push(frame);
49
- }
50
- } catch {
51
- // Ignore malformed frames
52
- }
53
- }
54
- }
55
- return frames;
56
- }
57
-
58
- // ─── Hook ─────────────────────────────────────────────────────────────────────
59
-
60
- export function useRagChat(
61
- projectId: string,
62
- options: UseRagChatOptions = {}
63
- ): UseRagChatReturn {
64
- const {
65
- apiUrl,
66
- retrivoraApiBase = '/api/retrivora',
67
- namespace,
68
- persist = true,
69
- onReply,
70
- onError,
71
- } = options;
72
- const primaryUrl = apiUrl || `${retrivoraApiBase.replace(/\/$/, '')}/chat`;
73
- const storageKey = `rag_chat_${projectId}`;
74
-
75
- const [messages, setMessages] = useStoredMessages<RagMessage>(storageKey, persist);
76
- const [isLoading, setIsLoading] = useState(false);
77
- const [error, setError] = useState<string | null>(null);
78
- const lastInputRef = useRef<string>('');
79
- const messagesRef = useRef<RagMessage[]>(messages);
80
- const abortControllerRef = useRef<AbortController | null>(null);
81
-
82
- useEffect(() => {
83
- messagesRef.current = messages;
84
- }, [messages]);
85
-
86
- // ── Core send function ────────────────────────────────────────────────────
87
- const sendMessage = useCallback(
88
- async (text: string, opts?: { skipUserMessage?: boolean }) => {
89
- const trimmed = text.trim();
90
- if (!trimmed || isLoading) return;
91
-
92
- lastInputRef.current = trimmed;
93
-
94
- const userMsgId = opts?.skipUserMessage
95
- ? (messagesRef.current.filter((m) => m.role === 'user').pop()?.id || `user_${Date.now()}`)
96
- : `user_${Date.now()}`;
97
-
98
- if (!opts?.skipUserMessage) {
99
- const userMessage: RagMessage = {
100
- id: userMsgId,
101
- role: 'user',
102
- content: trimmed,
103
- createdAt: new Date().toISOString(),
104
- };
105
-
106
- setMessages((prev) => [...prev, userMessage]);
107
- }
108
- setError(null);
109
- setIsLoading(true);
110
-
111
- // Abort any existing call
112
- if (abortControllerRef.current) {
113
- abortControllerRef.current.abort();
114
- }
115
-
116
- const controller = new AbortController();
117
- abortControllerRef.current = controller;
118
-
119
- try {
120
- const history = messagesRef.current.map(({ role, content }) => ({ role, content }));
121
- const assistantMessageId = `assistant_${Date.now()}`;
122
-
123
- const payloadBody = JSON.stringify({
124
- message: trimmed,
125
- history,
126
- namespace: namespace ?? projectId,
127
- sessionId: options.sessionId || 'default',
128
- messageId: assistantMessageId,
129
- userMessageId: userMsgId,
130
- });
131
-
132
- const getHeader = (headersObj: Record<string, string> | undefined, name: string) => {
133
- if (!headersObj) return undefined;
134
- const target = name.toLowerCase();
135
- for (const [k, v] of Object.entries(headersObj)) {
136
- if (k.toLowerCase() === target) return v;
137
- }
138
- return undefined;
139
- };
140
-
141
- const resolvedLicenseKey =
142
- options.licenseKey ||
143
- getHeader(options.headers, 'x-license-key') ||
144
- getHeader(options.headers, 'authorization')?.replace(/^Bearer\s+/i, '') ||
145
- (typeof process !== 'undefined'
146
- ? (process.env.NEXT_PUBLIC_RETRIVORA_LICENSE_KEY || process.env.RETRIVORA_LICENSE_KEY)
147
- : '') ||
148
- '';
149
-
150
- const fetchHeaders: Record<string, string> = {
151
- 'Content-Type': 'application/json',
152
- ...(resolvedLicenseKey ? { 'x-license-key': resolvedLicenseKey } : {}),
153
- ...(options.headers || {})
154
- };
155
-
156
- let response = await fetch(primaryUrl, {
157
- method: 'POST',
158
- headers: fetchHeaders,
159
- signal: controller.signal,
160
- body: payloadBody,
161
- });
162
-
163
- // Dynamic Fallback: If primaryUrl (e.g. /api/retrivora/chat) returns 404, retry fallback to /api/chat
164
- if (response.status === 404 && !apiUrl && primaryUrl !== '/api/chat') {
165
- console.warn(`[Retrivora SDK] ⚠️ Chat endpoint "${primaryUrl}" returned 404. Retrying fallback to "/api/chat"...`);
166
- response = await fetch('/api/chat', {
167
- method: 'POST',
168
- headers: fetchHeaders,
169
- signal: controller.signal,
170
- body: payloadBody,
171
- });
172
- }
173
-
174
- if (!response.ok) {
175
- const errorData = await response.json().catch(() => ({}));
176
- if (
177
- response.status === 403 ||
178
- response.status === 401 ||
179
- (typeof errorData.error === 'string' && errorData.error.toLowerCase().includes('license')) ||
180
- errorData.error?.type === 'license_revoked'
181
- ) {
182
- throw new Error('Your Retrivora license is no longer valid. Please contact your administrator or obtain a valid license key.');
183
- }
184
- throw new Error(errorData.error?.message || errorData.error || `Server returned ${response.status}`);
185
- }
186
-
187
- if (!response.body) {
188
- throw new Error('No response body received from server');
189
- }
190
-
191
- const reader = response.body.getReader();
192
- const decoder = new TextDecoder();
193
- let assistantContent = '';
194
- let thinkingContent = '';
195
- let thinkingMs: number | undefined;
196
- let sources: VectorMatch[] = [];
197
- let uiTransformation: unknown = null;
198
- let trace: ObservabilityTrace | undefined;
199
- let buffer = '';
200
-
201
- // ── RAF-based render batching ─────────────────────────────────────
202
- // Accumulate text chunks in a ref and flush to React state at ~60fps
203
- // instead of calling setMessages on every SSE frame. This eliminates
204
- // O(N) ReactMarkdown re-parses where N = number of token chunks.
205
- let pendingFlush = false;
206
- const pendingContentRef = { current: '' };
207
- const pendingThinkingRef = { current: '' };
208
-
209
- const flushTextUpdate = (msgId: string) => {
210
- pendingFlush = false;
211
- const snapshot = pendingContentRef.current;
212
- const thinkingSnapshot = pendingThinkingRef.current;
213
- setMessages((prev) =>
214
- prev.map((msg) =>
215
- msg.id === msgId
216
- ? {
217
- ...msg,
218
- content: snapshot,
219
- thinking: thinkingSnapshot || undefined,
220
- }
221
- : msg
222
- )
223
- );
224
- };
225
-
226
- const scheduleFlush = (msgId: string) => {
227
- if (!pendingFlush) {
228
- pendingFlush = true;
229
- requestAnimationFrame(() => flushTextUpdate(msgId));
230
- }
231
- };
232
- // ─────────────────────────────────────────────────────────────────
233
-
234
- // Add a placeholder assistant message
235
- setMessages((prev) => [
236
- ...prev,
237
- {
238
- id: assistantMessageId,
239
- role: 'assistant',
240
- content: '',
241
- createdAt: new Date().toISOString(),
242
- },
243
- ]);
244
-
245
- while (true) {
246
- const { done, value } = await reader.read();
247
- if (done) break;
248
-
249
- buffer += decoder.decode(value, { stream: true });
250
- const frames = parseSseChunk(buffer);
251
-
252
- // Clear processed frames from buffer (approximate by matching last found frame boundary)
253
- const lastIndex = buffer.lastIndexOf('\n\n');
254
- if (lastIndex !== -1) {
255
- buffer = buffer.slice(lastIndex + 2);
256
- }
257
-
258
- for (const frame of frames) {
259
- if (frame.type === 'text') {
260
- assistantContent += frame.text;
261
- pendingContentRef.current = assistantContent;
262
- scheduleFlush(assistantMessageId);
263
- } else if (frame.type === 'thinking') {
264
- thinkingContent += frame.text;
265
- pendingThinkingRef.current = thinkingContent;
266
- scheduleFlush(assistantMessageId);
267
- } else if (frame.type === 'metadata') {
268
- sources = frame.sources ?? [];
269
- thinkingMs = frame.thinkingMs;
270
- } else if (frame.type === 'ui_transformation') {
271
- uiTransformation = frame.data;
272
- } else if (frame.type === 'observability') {
273
- trace = frame.data;
274
- } else if (frame.type === 'error') {
275
- throw new Error(frame.error);
276
- }
277
- }
278
- }
279
-
280
- // Process any remaining buffered data
281
- if (buffer.trim()) {
282
- for (const frame of parseSseChunk(buffer)) {
283
- if (frame.type === 'text' && frame.text) assistantContent += frame.text;
284
- else if (frame.type === 'thinking' && frame.text) thinkingContent += frame.text;
285
- else if (frame.type === 'metadata') {
286
- sources = frame.sources ?? [];
287
- thinkingMs = frame.thinkingMs;
288
- }
289
- else if (frame.type === 'observability') trace = frame.data;
290
- }
291
- }
292
-
293
- // Final message with all accumulated data
294
- const finalMsg: RagMessage = {
295
- id: assistantMessageId,
296
- role: 'assistant',
297
- content: assistantContent,
298
- sources: sources.length > 0 ? sources : undefined,
299
- uiTransformation: uiTransformation ?? undefined,
300
- trace,
301
- thinking: thinkingContent || undefined,
302
- thinkingMs: thinkingMs,
303
- createdAt: new Date().toISOString(),
304
- };
305
- setMessages((prev) =>
306
- prev.map((msg) => (msg.id === assistantMessageId ? finalMsg : msg))
307
- );
308
- onReply?.(finalMsg);
309
- } catch (err) {
310
- if (err instanceof Error && err.name === 'AbortError') {
311
- //console.log('[useRagChat] Streaming stopped by user.');
312
- return;
313
- }
314
- let msg = err instanceof Error ? err.message : 'Something went wrong. Please try again.';
315
- if (
316
- msg.includes('403') ||
317
- msg.toLowerCase().includes('license') ||
318
- msg.toLowerCase().includes('revoked') ||
319
- msg.toLowerCase().includes('terminated')
320
- ) {
321
- msg = 'Your Retrivora license key has been terminated, suspended, or revoked. Access denied.';
322
- }
323
- setError(msg);
324
- onError?.(msg);
325
- } finally {
326
- setIsLoading(false);
327
- abortControllerRef.current = null;
328
- }
329
- },
330
- [apiUrl, isLoading, namespace, onError, onReply, projectId, setMessages, options.headers, options.sessionId]
331
- );
332
-
333
- const clear = useCallback(() => {
334
- setMessages([]);
335
- setError(null);
336
- if (persist) localStorage.removeItem(storageKey);
337
- }, [persist, setMessages, storageKey]);
338
-
339
- const retry = useCallback(async () => {
340
- if (lastInputRef.current) {
341
- const latestMessage = messagesRef.current[messagesRef.current.length - 1];
342
- await sendMessage(lastInputRef.current, {
343
- skipUserMessage: latestMessage?.role === 'user' && latestMessage.content === lastInputRef.current,
344
- });
345
- }
346
- }, [sendMessage]);
347
-
348
- const stop = useCallback(() => {
349
- if (abortControllerRef.current) {
350
- abortControllerRef.current.abort();
351
- abortControllerRef.current = null;
352
- }
353
- setIsLoading(false);
354
- }, []);
355
-
356
- const loadHistory = useCallback(async (sessionId: string) => {
357
- setIsLoading(true);
358
- setError(null);
359
- try {
360
- const res = await fetch(`${retrivoraApiBase}/history?sessionId=${encodeURIComponent(sessionId)}`);
361
- if (!res.ok) throw new Error(`Failed to load history: ${res.statusText}`);
362
- const data = await res.json();
363
- const loadedMessages = (data.history || []).map((msg: any) => ({
364
- id: msg.id,
365
- role: msg.role,
366
- content: msg.content,
367
- sources: msg.sources,
368
- uiTransformation: msg.uiTransformation,
369
- trace: msg.trace,
370
- createdAt: msg.createdAt,
371
- }));
372
- setMessages(loadedMessages);
373
- } catch (err) {
374
- const msg = err instanceof Error ? err.message : 'Failed to load history';
375
- setError(msg);
376
- onError?.(msg);
377
- } finally {
378
- setIsLoading(false);
379
- }
380
- }, [retrivoraApiBase, onError, setMessages]);
381
-
382
- const clearHistory = useCallback(async (sessionId: string) => {
383
- setIsLoading(true);
384
- setError(null);
385
- try {
386
- const res = await fetch(`${retrivoraApiBase}/history/clear`, {
387
- method: 'POST',
388
- headers: { 'Content-Type': 'application/json' },
389
- body: JSON.stringify({ sessionId }),
390
- });
391
- if (!res.ok) throw new Error(`Failed to clear history: ${res.statusText}`);
392
- setMessages([]);
393
- if (persist) localStorage.removeItem(storageKey);
394
- } catch (err) {
395
- const msg = err instanceof Error ? err.message : 'Failed to clear history';
396
- setError(msg);
397
- onError?.(msg);
398
- } finally {
399
- setIsLoading(false);
400
- }
401
- }, [retrivoraApiBase, onError, persist, setMessages, storageKey]);
402
-
403
- const submitFeedback = useCallback(async (messageId: string, rating: 'thumbs_up' | 'thumbs_down', comment?: string) => {
404
- try {
405
- const res = await fetch(`${retrivoraApiBase}/feedback`, {
406
- method: 'POST',
407
- headers: { 'Content-Type': 'application/json' },
408
- body: JSON.stringify({
409
- messageId,
410
- sessionId: options.sessionId || 'default',
411
- rating,
412
- comment,
413
- }),
414
- });
415
- if (!res.ok) throw new Error(`Failed to submit feedback: ${res.statusText}`);
416
- } catch (err) {
417
- const msg = err instanceof Error ? err.message : 'Failed to submit feedback';
418
- onError?.(msg);
419
- throw err;
420
- }
421
- }, [retrivoraApiBase, onError, options.sessionId]);
422
-
423
- return {
424
- messages,
425
- isLoading,
426
- error,
427
- send: sendMessage,
428
- clear,
429
- retry,
430
- setMessages,
431
- stop,
432
- loadHistory,
433
- clearHistory,
434
- submitFeedback,
435
- };
436
- }
@@ -1,64 +0,0 @@
1
- 'use client';
2
-
3
- import * as React from 'react';
4
-
5
- export interface StoredMessage {
6
- id: string;
7
- role: 'user' | 'assistant' | 'system';
8
- content: string;
9
- createdAt?: string;
10
- sources?: unknown;
11
- }
12
-
13
- function readStoredMessages(storageKey: string): StoredMessage[] {
14
- if (typeof window === 'undefined') {
15
- return [];
16
- }
17
-
18
- const saved = window.localStorage.getItem(storageKey);
19
- if (!saved) {
20
- return [];
21
- }
22
-
23
- try {
24
- const parsed = JSON.parse(saved);
25
- return Array.isArray(parsed) ? (parsed as StoredMessage[]) : [];
26
- } catch {
27
- return [];
28
- }
29
- }
30
-
31
- export function useStoredMessages<T extends StoredMessage>(
32
- storageKey: string,
33
- persist: boolean
34
- ): [T[], React.Dispatch<React.SetStateAction<T[]>>] {
35
- const [messages, setMessages] = React.useState<T[]>([]);
36
- const isLoaded = React.useRef(false);
37
-
38
- // Load from localStorage only on client-side mount to prevent hydration mismatch
39
- React.useEffect(() => {
40
- if (persist) {
41
- const loaded = readStoredMessages(storageKey) as T[];
42
- if (loaded.length > 0) {
43
- setMessages(loaded);
44
- }
45
- }
46
- isLoaded.current = true;
47
- }, [storageKey, persist]);
48
-
49
- // Save to localStorage only after initialization has completed to avoid overwriting with empty array
50
- React.useEffect(() => {
51
- if (!isLoaded.current || !persist || typeof window === 'undefined') {
52
- return;
53
- }
54
-
55
- if (messages.length === 0) {
56
- window.localStorage.removeItem(storageKey);
57
- return;
58
- }
59
-
60
- window.localStorage.setItem(storageKey, JSON.stringify(messages));
61
- }, [messages, persist, storageKey]);
62
-
63
- return [messages, setMessages];
64
- }