@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,498 +0,0 @@
1
- 'use client';
2
-
3
- import React from 'react';
4
- import { Bot, User, ChevronDown, ChevronRight, Activity, Copy, Check, ThumbsUp, ThumbsDown, Clock } from 'lucide-react';
5
- import ReactMarkdown from 'react-markdown';
6
- import { MessageBubbleProps, Product, UITransformationResponse } from '../types';
7
- import { SourceCard } from './SourceCard';
8
- import { ProductCarousel } from './ProductCarousel';
9
- import { VisualizationRenderer } from './VisualizationRenderer';
10
- import { ObservabilityPanel } from './ObservabilityPanel';
11
- import HourglassLoader from './HourglassLoader';
12
- import {
13
- extractStructuredPayload,
14
- isLikelyUiOnlyMessage,
15
- extractProductsFromSources,
16
- extractProductsFromContent,
17
- deduplicateProducts,
18
- looksLikeStructuredPayload,
19
- stripStructuredUiLabels,
20
- stripMarkdownTables
21
- } from '../utils/ProductExtractor';
22
- import { createMarkdownComponents } from './MarkdownComponents';
23
- import { UIDispatcher } from './UIDispatcher';
24
- import { ThinkingBlock } from './ThinkingBlock';
25
-
26
- function normalizePlusSeparatedLists(raw: string): string {
27
- return raw
28
- .split('\n')
29
- .map((line) => {
30
- const productListLine =
31
- /[—:]\s*\d+\s+\+\s+[A-Za-z]/.test(line) ||
32
- /\b(products?|categories?|in stock|out of stock)\b/i.test(line);
33
- if (!productListLine) return line;
34
-
35
- return line.replace(/\s+\+\s+(?=[A-Za-z0-9])/g, ', ');
36
- })
37
- .join('\n');
38
- }
39
-
40
- function stripLeakedAnswerWrappers(raw: string): string {
41
- return raw
42
- .replace(/<prose\s+answer(?:\s+in\s+[^>]*)?>[\s\S]*?<\/prose>/gi, '$1')
43
- .replace(/<\/?prose(?:\s+answer)?[^>]*>/gi, '')
44
- .replace(/\n{3,}/g, '\n\n')
45
- .trim();
46
- }
47
-
48
- function formatTime(isoString?: string): string {
49
- if (!isoString) return '';
50
- try {
51
- const d = new Date(isoString);
52
- return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
53
- } catch {
54
- return '';
55
- }
56
- }
57
-
58
- // ─── Feedback Buttons ─────────────────────────────────────────────────────────
59
-
60
- interface FeedbackBarProps {
61
- messageId: string;
62
- onFeedback: (messageId: string, rating: 'thumbs_up' | 'thumbs_down') => void;
63
- primaryColor: string;
64
- }
65
-
66
- function FeedbackBar({ messageId, onFeedback, primaryColor }: FeedbackBarProps) {
67
- const [rating, setRating] = React.useState<'thumbs_up' | 'thumbs_down' | null>(null);
68
- const [submitting, setSubmitting] = React.useState(false);
69
-
70
- const handleRate = async (r: 'thumbs_up' | 'thumbs_down') => {
71
- if (rating !== null || submitting) return;
72
- setSubmitting(true);
73
- setRating(r);
74
- try {
75
- await onFeedback(messageId, r);
76
- } catch {
77
- // Rating already set optimistically — keep it
78
- } finally {
79
- setSubmitting(false);
80
- }
81
- };
82
-
83
- const isLocked = rating !== null;
84
-
85
- return (
86
- <div className="flex items-center gap-1">
87
- {/* Divider */}
88
- <span className="h-3 w-px bg-slate-200 dark:bg-white/10 mx-1" />
89
-
90
- {/* Thumbs Up */}
91
- <button
92
- onClick={() => handleRate('thumbs_up')}
93
- disabled={isLocked}
94
- title={rating === 'thumbs_up' ? 'You liked this' : 'Good response'}
95
- className={`group relative flex items-center justify-center w-6 h-6 rounded-lg transition-all duration-200 cursor-pointer border ${
96
- rating === 'thumbs_up'
97
- ? 'bg-emerald-50 dark:bg-emerald-500/10 border-emerald-200 dark:border-emerald-500/25 text-emerald-600 dark:text-emerald-400 scale-110'
98
- : rating === 'thumbs_down'
99
- ? 'opacity-30 border-transparent text-slate-300 dark:text-white/20 cursor-not-allowed'
100
- : 'border-transparent text-slate-300 dark:text-white/20 hover:text-emerald-500 dark:hover:text-emerald-400 hover:bg-emerald-50 dark:hover:bg-emerald-500/10 hover:border-emerald-200 dark:hover:border-emerald-500/20 hover:scale-110'
101
- }`}
102
- >
103
- <ThumbsUp className="w-3 h-3" />
104
- {/* Tooltip */}
105
- {!isLocked && (
106
- <span className="absolute -top-8 left-1/2 -translate-x-1/2 px-2 py-1 text-[10px] font-medium bg-slate-800 dark:bg-slate-700 text-white rounded-lg opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none whitespace-nowrap shadow-lg z-10">
107
- Good response
108
- </span>
109
- )}
110
- </button>
111
-
112
- {/* Thumbs Down */}
113
- <button
114
- onClick={() => handleRate('thumbs_down')}
115
- disabled={isLocked}
116
- title={rating === 'thumbs_down' ? 'You disliked this' : 'Bad response'}
117
- className={`group relative flex items-center justify-center w-6 h-6 rounded-lg transition-all duration-200 cursor-pointer border ${
118
- rating === 'thumbs_down'
119
- ? 'bg-rose-50 dark:bg-rose-500/10 border-rose-200 dark:border-rose-500/25 text-rose-600 dark:text-rose-400 scale-110'
120
- : rating === 'thumbs_up'
121
- ? 'opacity-30 border-transparent text-slate-300 dark:text-white/20 cursor-not-allowed'
122
- : 'border-transparent text-slate-300 dark:text-white/20 hover:text-rose-500 dark:hover:text-rose-400 hover:bg-rose-50 dark:hover:bg-rose-500/10 hover:border-rose-200 dark:hover:border-rose-500/20 hover:scale-110'
123
- }`}
124
- >
125
- <ThumbsDown className="w-3 h-3" />
126
- {!isLocked && (
127
- <span className="absolute -top-8 left-1/2 -translate-x-1/2 px-2 py-1 text-[10px] font-medium bg-slate-800 dark:bg-slate-700 text-white rounded-lg opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none whitespace-nowrap shadow-lg z-10">
128
- Bad response
129
- </span>
130
- )}
131
- </button>
132
-
133
- {/* Confirmation pill */}
134
- {isLocked && (
135
- <span className={`ml-1 text-[10px] font-semibold px-2 py-0.5 rounded-full border transition-all duration-300 ${
136
- rating === 'thumbs_up'
137
- ? 'text-emerald-600 dark:text-emerald-400 bg-emerald-50 dark:bg-emerald-500/10 border-emerald-200 dark:border-emerald-500/20'
138
- : 'text-rose-600 dark:text-rose-400 bg-rose-50 dark:bg-rose-500/10 border-rose-200 dark:border-rose-500/20'
139
- }`}>
140
- {rating === 'thumbs_up' ? 'Helpful' : 'Not helpful'}
141
- </span>
142
- )}
143
- </div>
144
- );
145
- }
146
-
147
- // ─── Main component ───────────────────────────────────────────────────────────
148
-
149
- export function MessageBubble({
150
- message,
151
- sources,
152
- isStreaming = false,
153
- primaryColor = '#6366f1',
154
- accentColor = '#8b5cf6',
155
- onAddToCart,
156
- viewportSize = 'large',
157
- onFeedback,
158
- }: MessageBubbleProps) {
159
- const isUser = message.role === 'user';
160
- const isCompact = viewportSize === 'compact';
161
- const isMedium = viewportSize === 'medium';
162
-
163
- const [showSources, setShowSources] = React.useState(false);
164
- const [showTrace, setShowTrace] = React.useState(false);
165
- const [copied, setCopied] = React.useState(false);
166
-
167
- const handleCopy = React.useCallback(async () => {
168
- try {
169
- await navigator.clipboard.writeText(message.content);
170
- setCopied(true);
171
- setTimeout(() => setCopied(false), 2000);
172
- } catch (err) {
173
- console.error('Failed to copy text:', err);
174
- }
175
- }, [message.content]);
176
-
177
- const structuredContent = React.useMemo(
178
- () => isUser ? { payload: null, text: message.content } : extractStructuredPayload(message.content),
179
- [isUser, message.content],
180
- );
181
-
182
- const hasRichUI = React.useMemo(() => {
183
- if (message.uiTransformation) {
184
- const type = (message.uiTransformation as UITransformationResponse).type;
185
- if (type && !['text', 'table'].includes(type)) return true;
186
- }
187
- if (structuredContent.payload) {
188
- return /\"?(?:view|type|chartType)\"?\s*:\s*\"?(?:chart|carousel|pie|bar|line|product_carousel)\"?/i.test(structuredContent.payload);
189
- }
190
- return false;
191
- }, [message.uiTransformation, structuredContent.payload]);
192
-
193
- const uiTransformationType = (message.uiTransformation as UITransformationResponse | undefined)?.type;
194
- const shouldSuppressProductCarousel = Boolean(
195
- uiTransformationType && !['text', 'product_carousel', 'carousel'].includes(uiTransformationType),
196
- );
197
-
198
- const shouldRenderStructuredOnly = !isUser && hasRichUI && isLikelyUiOnlyMessage(structuredContent.text);
199
-
200
- // ── Extraction ─────────────────────────────────────────────────────────────
201
-
202
- const productsFromSources = React.useMemo<Product[]>(() => {
203
- return extractProductsFromSources(sources, isUser);
204
- }, [sources, isUser]);
205
-
206
- const { productsFromContent, cleanContent } = React.useMemo(() => {
207
- if (isUser) {
208
- return { productsFromContent: [] as Product[], cleanContent: message.content };
209
- }
210
-
211
- const payloadCandidates = [
212
- structuredContent.payload,
213
- ...Array.from(structuredContent.text.matchAll(/```(?:json|ui)?\s*([\s\S]*?)\s*```/g)).map(m => m[1])
214
- ].filter(Boolean) as string[];
215
-
216
- return extractProductsFromContent(
217
- message.content,
218
- structuredContent.text,
219
- payloadCandidates,
220
- productsFromSources,
221
- isStreaming
222
- );
223
- }, [message.content, isUser, structuredContent, productsFromSources, isStreaming]);
224
-
225
- const allProducts = React.useMemo<Product[]>(() => {
226
- return deduplicateProducts(productsFromSources, productsFromContent, message.content);
227
- }, [productsFromSources, productsFromContent, message.content]);
228
-
229
- const processedMarkdown = React.useMemo<string>(() => {
230
- let raw = structuredContent.payload ? structuredContent.text : (cleanContent || message.content);
231
-
232
- raw = raw.replace(/\$\s*(\d+)(?!\.\d)/g, '$1');
233
- raw = normalizePlusSeparatedLists(raw);
234
- raw = stripLeakedAnswerWrappers(raw);
235
- raw = raw.replace(/\*\*([^*\n]+)\*\*(\s*[—\-–:]\s*)/g, '$1$2');
236
- raw = raw
237
- .split('\n')
238
- .filter((line, idx, arr) => {
239
- const trimmed = line.trim();
240
- return !trimmed || arr.findIndex(l => l.trim() === trimmed) === idx;
241
- })
242
- .join('\n');
243
-
244
- const hasStructuredUiBlock = Boolean(structuredContent.payload) || /```(?:ui|json|chart)\s*[\s\S]*?"(?:view|chartType|type|data|items|rows|products|results)"\s*:/i.test(raw);
245
-
246
- raw = raw.replace(/([^\n])\n\|/g, '$1\n\n|')
247
- .replace(/(\|[^\n]*\|)\n\n+(?=\|)/g, '$1\n');
248
-
249
- if (!isStreaming) {
250
- raw = raw.replace(/(?:^|\n)\s*\{[\s\S]*\}\s*(?:\n|$)/g, (match) => {
251
- if (match.includes('```')) return match;
252
- if (!looksLikeStructuredPayload(match)) return match;
253
- const type = match.includes('"view"') || match.includes('"chartType"') || match.includes('"type": "pie"') || match.includes('"type":"pie"') || match.includes('"type": "bar"') || match.includes('"type":"bar"') || match.includes('"type": "line"') || match.includes('"type":"line"')
254
- ? 'ui'
255
- : 'json';
256
- return `\n\n\`\`\`${type}\n${match.trim()}\n\`\`\`\n\n`;
257
- });
258
- }
259
-
260
- if (hasStructuredUiBlock) {
261
- raw = stripStructuredUiLabels(stripMarkdownTables(raw))
262
- .replace(/\n{3,}/g, '\n\n')
263
- .trim();
264
- }
265
-
266
- return raw;
267
- }, [cleanContent, message.content, isStreaming, structuredContent]);
268
-
269
- // ── Markdown component overrides ───────────────────────────────────────────
270
- const markdownComponents = React.useMemo(
271
- () => createMarkdownComponents({ primaryColor, accentColor, isStreaming, onAddToCart, viewportSize }),
272
- [primaryColor, accentColor, isStreaming, onAddToCart, viewportSize],
273
- );
274
-
275
- const timeLabel = formatTime(message.createdAt);
276
- const isCompleted = !isStreaming && message.content;
277
-
278
- // ── Render ─────────────────────────────────────────────────────────────────
279
- return (
280
- <div className={`flex ${isCompact ? 'gap-2' : 'gap-3'} ${isUser ? 'flex-row-reverse' : 'flex-row'} items-start`}>
281
- {/* Avatar */}
282
- <div
283
- className={`flex-shrink-0 ${isCompact ? 'w-7 h-7' : 'w-8 h-8'} rounded-full flex items-center justify-center shadow-md transition-all duration-300 ${
284
- isUser
285
- ? 'text-white'
286
- : 'bg-gradient-to-br from-slate-100 to-slate-200 dark:from-white/10 dark:to-white/5 text-slate-600 dark:text-white/70 ring-1 ring-slate-200/80 dark:ring-white/10'
287
- } ${isStreaming && !isUser ? 'ring-2 ring-offset-1 ring-offset-transparent animate-pulse' : ''}`}
288
- style={isUser ? { background: `linear-gradient(135deg, ${primaryColor}, ${accentColor})` } : {}}
289
- >
290
- {isUser
291
- ? <User className={`${isCompact ? 'w-3.5 h-3.5' : 'w-4 h-4'} text-white`} />
292
- : <Bot className={`${isCompact ? 'w-3.5 h-3.5' : 'w-4 h-4'}`} />
293
- }
294
- </div>
295
-
296
- <div className={`flex flex-col gap-1 min-w-0 ${isCompact ? 'max-w-[94%]' : isMedium ? 'max-w-[92%]' : 'max-w-[90%]'} ${isUser ? 'items-end' : 'items-start'}`}>
297
- {/* Thinking Steps */}
298
- {!isUser && message.thinking && (
299
- <ThinkingBlock
300
- thinking={message.thinking}
301
- thinkingMs={message.thinkingMs}
302
- isStreaming={isStreaming && !message.content}
303
- />
304
- )}
305
-
306
- {/* Bubble */}
307
- <div
308
- className={`relative group ${isCompact ? 'px-3 py-2.5 text-[13px]' : 'px-4 py-3 text-sm'} rounded-2xl leading-relaxed transition-shadow duration-200 ${
309
- isUser
310
- ? 'text-white rounded-tr-sm shadow-md hover:shadow-lg'
311
- : 'bg-white dark:bg-white/5 border border-slate-200/80 dark:border-white/10 text-slate-800 dark:text-white/90 rounded-tl-sm shadow-sm hover:shadow-md hover:border-slate-300/60 dark:hover:border-white/15'
312
- }`}
313
- style={
314
- isUser ? { background: `linear-gradient(135deg, ${primaryColor}, ${accentColor})` } : {}
315
- }
316
- >
317
- {/* Floating Copy Button for completed assistant messages */}
318
- {!isUser && isCompleted && (
319
- <button
320
- onClick={handleCopy}
321
- className={`absolute top-2 right-2 p-1.5 rounded-lg border transition-all duration-200 cursor-pointer ${
322
- copied
323
- ? 'bg-emerald-500/10 border-emerald-500/20 text-emerald-500 dark:text-emerald-400'
324
- : 'bg-white/60 dark:bg-white/5 hover:bg-white dark:hover:bg-white/10 border-slate-200/60 dark:border-white/10 text-slate-300 dark:text-white/20 hover:text-slate-600 dark:hover:text-white/60 hover:border-slate-300 dark:hover:border-white/20'
325
- } opacity-0 group-hover:opacity-100 backdrop-blur-sm shadow-sm scale-95 group-hover:scale-100`}
326
- title={copied ? 'Copied!' : 'Copy response'}
327
- >
328
- {copied ? <Check className="w-3.5 h-3.5" /> : <Copy className="w-3.5 h-3.5" />}
329
- </button>
330
- )}
331
-
332
- {isStreaming && !message.content ? (
333
- <span className="flex items-center gap-1 py-1">
334
- <span className="w-1.5 h-1.5 rounded-full bg-slate-400 dark:bg-white/60 animate-bounce [animation-delay:0ms]" />
335
- <span className="w-1.5 h-1.5 rounded-full bg-slate-400 dark:bg-white/60 animate-bounce [animation-delay:150ms]" />
336
- <span className="w-1.5 h-1.5 rounded-full bg-slate-400 dark:bg-white/60 animate-bounce [animation-delay:300ms]" />
337
- </span>
338
- ) : (
339
- <div className={`prose ${isCompact ? 'prose-xs' : 'prose-sm'} max-w-none break-words ${isUser ? 'prose-invert' : 'dark:prose-invert'}`}>
340
- {!isUser && structuredContent.payload && (
341
- <UIDispatcher
342
- rawContent={structuredContent.payload}
343
- primaryColor={primaryColor}
344
- accentColor={accentColor}
345
- isStreaming={isStreaming}
346
- onAddToCart={onAddToCart}
347
- viewportSize={viewportSize}
348
- />
349
- )}
350
-
351
- {!shouldRenderStructuredOnly && (
352
- <ReactMarkdown components={markdownComponents}>
353
- {processedMarkdown}
354
- </ReactMarkdown>
355
- )}
356
-
357
- {isStreaming && (
358
- <span
359
- className="inline-block w-2.5 h-4 ml-1.5 animate-[pulse_1.2s_infinite] align-middle rounded-sm"
360
- style={{ backgroundColor: primaryColor }}
361
- />
362
- )}
363
- </div>
364
- )}
365
- </div>
366
-
367
- {/* Auto-generated visualization */}
368
- {(() => {
369
- if (isUser || structuredContent.payload) return null;
370
-
371
- if (isStreaming && !message.uiTransformation && sources && sources.length > 0) {
372
- const hasProductSource = sources.some(s =>
373
- s.metadata && Object.keys(s.metadata).some(k =>
374
- ['name','title','price','brand','image','product','sku','category'].includes(k.toLowerCase())
375
- )
376
- );
377
- if (hasProductSource) {
378
- return (
379
- <div className="w-full mt-3">
380
- <VisualizationRenderer
381
- data={{ type: 'product_carousel', title: 'Recommended Products', description: 'Loading...', data: [] }}
382
- primaryColor={primaryColor}
383
- onAddToCart={onAddToCart}
384
- className="rounded-3xl border border-slate-200/60 dark:border-white/10 bg-white/90 dark:bg-slate-900/80 p-4"
385
- isStreaming={true}
386
- />
387
- </div>
388
- );
389
- }
390
- }
391
-
392
- if (!message.uiTransformation) return null;
393
- const ui = message.uiTransformation as UITransformationResponse;
394
- const textContent = (ui.data as { content?: string })?.content ?? '';
395
-
396
- const isNegativeOrFallbackText =
397
- textContent.toLowerCase().includes('cannot answer') ||
398
- textContent.toLowerCase().includes('no relevant data') ||
399
- textContent.toLowerCase().includes('no data available') ||
400
- (typeof ui.title === 'string' && ui.title.toLowerCase().includes('no data')) ||
401
- (typeof ui.description === 'string' && ui.description.toLowerCase().includes('no relevant data'));
402
-
403
- const shouldShow =
404
- !isNegativeOrFallbackText &&
405
- ui.type !== 'text' &&
406
- (ui.type === 'table' || !['text', 'table'].includes(ui.type));
407
-
408
- if (!shouldShow) return null;
409
- return (
410
- <div className="w-full mt-3">
411
- <VisualizationRenderer
412
- data={ui}
413
- primaryColor={primaryColor}
414
- onAddToCart={onAddToCart}
415
- className="rounded-3xl border border-slate-200/60 dark:border-white/10 bg-white/90 dark:bg-slate-900/80 p-4"
416
- isStreaming={isStreaming}
417
- />
418
- </div>
419
- );
420
- })()}
421
-
422
- {/* Product Carousel */}
423
- {!isUser && !hasRichUI && !shouldSuppressProductCarousel && allProducts.length > 0 && (
424
- <div className="w-full mt-1">
425
- <ProductCarousel
426
- products={allProducts}
427
- primaryColor={primaryColor}
428
- onAddToCart={onAddToCart}
429
- />
430
- </div>
431
- )}
432
-
433
- {/* Footer actions: Sources, Trace, Timestamp & Feedback */}
434
- {!isUser && (
435
- <div className={`flex items-center gap-3 mt-1.5 w-full flex-wrap ${isCompact ? 'gap-2' : 'gap-3'}`}>
436
- {/* Sources toggle */}
437
- {sources && sources.length > 0 && (
438
- <button
439
- onClick={() => setShowSources(s => !s)}
440
- className="text-[11px] text-indigo-400 hover:text-indigo-300 dark:text-indigo-400/70 dark:hover:text-indigo-300 transition-colors flex items-center gap-1 font-medium"
441
- >
442
- {showSources ? <ChevronDown className="w-3 h-3" /> : <ChevronRight className="w-3 h-3" />}
443
- {sources.length} source{sources.length !== 1 ? 's' : ''}
444
- </button>
445
- )}
446
-
447
- {/* Trace toggle */}
448
- {message.trace && (
449
- <button
450
- onClick={() => setShowTrace(t => !t)}
451
- className="text-[11px] text-emerald-500/70 hover:text-emerald-400 dark:text-emerald-500/50 dark:hover:text-emerald-400 transition-colors flex items-center gap-1 font-medium"
452
- >
453
- <Activity className="w-3 h-3" />
454
- {showTrace ? 'Hide trace' : 'Trace'}
455
- </button>
456
- )}
457
-
458
- {/* Spacer */}
459
- <div className="flex-1" />
460
-
461
- {/* Timestamp */}
462
- {timeLabel && isCompleted && (
463
- <span className="flex items-center gap-1 text-[10px] text-slate-300 dark:text-white/20 font-medium select-none">
464
- <Clock className="w-2.5 h-2.5" />
465
- {timeLabel}
466
- </span>
467
- )}
468
-
469
- {/* Feedback thumbs — only for completed, non-user messages with an ID */}
470
- {isCompleted && onFeedback && message.id && (
471
- <FeedbackBar
472
- messageId={message.id}
473
- onFeedback={onFeedback}
474
- primaryColor={primaryColor}
475
- />
476
- )}
477
- </div>
478
- )}
479
-
480
- {/* Expandable areas */}
481
- <div className="w-full flex flex-col gap-2 min-w-0">
482
- {showSources && sources && sources.length > 0 && (
483
- <div className="mt-1 flex flex-col gap-2">
484
- {sources.map((src, i) => (
485
- <SourceCard key={src.id} source={src} index={i} />
486
- ))}
487
- </div>
488
- )}
489
-
490
- {showTrace && message.trace && (
491
- <ObservabilityPanel trace={message.trace} primaryColor={primaryColor} />
492
- )}
493
- </div>
494
-
495
- </div>
496
- </div>
497
- );
498
- }