-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathBotBubble.tsx
More file actions
624 lines (582 loc) · 24.3 KB
/
BotBubble.tsx
File metadata and controls
624 lines (582 loc) · 24.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
import { createEffect, Show, createSignal, onMount, For } from 'solid-js';
import { Avatar } from '../avatars/Avatar';
import { Marked } from '@ts-stack/markdown';
import DOMPurify from 'dompurify';
import { FeedbackRatingType, sendFeedbackQuery, sendFileDownloadQuery, updateFeedbackQuery } from '@/queries/sendMessageQuery';
import { FileUpload, IAction, MessageType } from '../Bot';
import { CopyToClipboardButton, ThumbsDownButton, ThumbsUpButton } from '../buttons/FeedbackButtons';
import { RegenerateResponseButton } from '../buttons/RegenerateResponseButton';
import { TTSButton } from '../buttons/TTSButton';
import FeedbackContentDialog from '../FeedbackContentDialog';
import { AgentReasoningBubble } from './AgentReasoningBubble';
import { TickIcon, XIcon } from '../icons';
import { SourceBubble } from '../bubbles/SourceBubble';
import { DateTimeToggleTheme } from '@/features/bubble/types';
import { WorkflowTreeView } from '../treeview/WorkflowTreeView';
import { ThinkingCard } from './ThinkingBubble';
type Props = {
message: MessageType;
chatflowid: string;
chatId: string;
apiHost?: string;
onRequest?: (request: RequestInit) => Promise<void>;
fileAnnotations?: any;
showAvatar?: boolean;
avatarSrc?: string;
backgroundColor?: string;
textColor?: string;
chatFeedbackStatus?: boolean;
fontSize?: number;
feedbackColor?: string;
isLoading: boolean;
dateTimeToggle?: DateTimeToggleTheme;
showAgentMessages?: boolean;
sourceDocsTitle?: string;
renderHTML?: boolean;
handleActionClick: (elem: any, action: IAction | undefined | null) => void;
handleSourceDocumentsClick: (src: any) => void;
onRegenerateResponse?: () => void;
// TTS props
isTTSEnabled?: boolean;
isTTSLoading?: Record<string, boolean>;
isTTSPlaying?: Record<string, boolean>;
handleTTSClick?: (messageId: string, messageText: string) => void;
handleTTSStop?: (messageId: string) => void;
hasCustomHeader?: boolean;
dialogContainer?: HTMLElement;
};
const defaultBackgroundColor = '#f7f8ff';
const defaultTextColor = '#303235';
const defaultFontSize = 16;
const defaultFeedbackColor = '#3B81F6';
export const BotBubble = (props: Props) => {
let botDetailsEl: HTMLDetailsElement | undefined;
Marked.setOptions({ isNoP: true, sanitize: props.renderHTML !== undefined ? !props.renderHTML : true });
const [rating, setRating] = createSignal('');
const [feedbackId, setFeedbackId] = createSignal('');
const [showFeedbackContentDialog, setShowFeedbackContentModal] = createSignal(false);
const [copiedMessage, setCopiedMessage] = createSignal(false);
const [thumbsUpColor, setThumbsUpColor] = createSignal(props.feedbackColor ?? defaultFeedbackColor); // default color
const [thumbsDownColor, setThumbsDownColor] = createSignal(props.feedbackColor ?? defaultFeedbackColor); // default color
// Store a reference to the bot message element for the copyMessageToClipboard function
const [botMessageElement, setBotMessageElement] = createSignal<HTMLElement | null>(null);
const setBotMessageRef = (el: HTMLSpanElement) => {
if (el) {
el.innerHTML = Marked.parse(props.message.message);
// Apply textColor to all links, headings, and other markdown elements except code
const textColor = props.textColor ?? defaultTextColor;
el.querySelectorAll('a, h1, h2, h3, h4, h5, h6, strong, em, blockquote, li').forEach((element) => {
(element as HTMLElement).style.color = textColor;
});
// Code blocks (with pre) get white text
el.querySelectorAll('pre').forEach((element) => {
(element as HTMLElement).style.color = '#FFFFFF';
// Also ensure any code elements inside pre have white text
element.querySelectorAll('code').forEach((codeElement) => {
(codeElement as HTMLElement).style.color = '#FFFFFF';
});
});
// Inline code (not in pre) gets green text
el.querySelectorAll('code:not(pre code)').forEach((element) => {
(element as HTMLElement).style.color = '#4CAF50'; // Green color
});
// Set target="_blank" for links
el.querySelectorAll('a').forEach((link) => {
link.target = '_blank';
});
// Store the element ref for the copy function
setBotMessageElement(el);
if (props.message.rating) {
setRating(props.message.rating);
if (props.message.rating === 'THUMBS_UP') {
setThumbsUpColor('#006400');
} else if (props.message.rating === 'THUMBS_DOWN') {
setThumbsDownColor('#8B0000');
}
}
if (props.fileAnnotations && props.fileAnnotations.length) {
for (const annotations of props.fileAnnotations) {
const button = document.createElement('button');
button.textContent = annotations.fileName;
button.className =
'py-2 px-4 mb-2 justify-center font-semibold text-white focus:outline-none flex items-center disabled:opacity-50 disabled:cursor-not-allowed disabled:brightness-100 transition-all filter hover:brightness-90 active:brightness-75 file-annotation-button';
button.addEventListener('click', function () {
downloadFile(annotations);
});
const svgContainer = document.createElement('div');
svgContainer.className = 'ml-2';
svgContainer.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-download" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="#ffffff" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2 -2v-2" /><path d="M7 11l5 5l5 -5" /><path d="M12 4l0 12" /></svg>`;
button.appendChild(svgContainer);
el.appendChild(button);
}
}
}
};
const downloadFile = async (fileAnnotation: any) => {
try {
const response = await sendFileDownloadQuery({
apiHost: props.apiHost,
body: { fileName: fileAnnotation.fileName, chatflowId: props.chatflowid, chatId: props.chatId } as any,
onRequest: props.onRequest,
});
const blob = new Blob([response.data]);
const downloadUrl = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = downloadUrl;
link.download = fileAnnotation.fileName;
document.body.appendChild(link);
link.click();
link.remove();
} catch (error) {
console.error('Download failed:', error);
}
};
const copyMessageToClipboard = async () => {
try {
const text = botMessageElement() ? botMessageElement()?.textContent : '';
await navigator.clipboard.writeText(text || '');
setCopiedMessage(true);
setTimeout(() => {
setCopiedMessage(false);
}, 2000); // Hide the message after 2 seconds
} catch (error) {
console.error('Error copying to clipboard:', error);
}
};
const saveToLocalStorage = (rating: FeedbackRatingType) => {
const chatDetails = localStorage.getItem(`${props.chatflowid}_EXTERNAL`);
if (!chatDetails) return;
try {
const parsedDetails = JSON.parse(chatDetails);
const messages: MessageType[] = parsedDetails.chatHistory || [];
const message = messages.find((msg) => msg.messageId === props.message.messageId);
if (!message) return;
message.rating = rating;
localStorage.setItem(`${props.chatflowid}_EXTERNAL`, JSON.stringify({ ...parsedDetails, chatHistory: messages }));
} catch (e) {
return;
}
};
const isValidURL = (url: string): URL | undefined => {
try {
return new URL(url);
} catch (err) {
return undefined;
}
};
const removeDuplicateURL = (message: MessageType) => {
const visitedURLs: string[] = [];
const newSourceDocuments: any = [];
message.sourceDocuments.forEach((source: any) => {
if (isValidURL(source.metadata.source) && !visitedURLs.includes(source.metadata.source)) {
visitedURLs.push(source.metadata.source);
newSourceDocuments.push(source);
} else if (!isValidURL(source.metadata.source)) {
newSourceDocuments.push(source);
}
});
return newSourceDocuments;
};
const onThumbsUpClick = async () => {
if (rating() === '') {
const body = {
chatflowid: props.chatflowid,
chatId: props.chatId,
messageId: props.message?.messageId as string,
rating: 'THUMBS_UP' as FeedbackRatingType,
content: '',
};
const result = await sendFeedbackQuery({
chatflowid: props.chatflowid,
apiHost: props.apiHost,
body,
onRequest: props.onRequest,
});
if (result.data) {
const data = result.data as any;
let id = '';
if (data && data.id) id = data.id;
setRating('THUMBS_UP');
setFeedbackId(id);
setShowFeedbackContentModal(true);
// update the thumbs up color state
setThumbsUpColor('#006400');
saveToLocalStorage('THUMBS_UP');
}
}
};
const onThumbsDownClick = async () => {
if (rating() === '') {
const body = {
chatflowid: props.chatflowid,
chatId: props.chatId,
messageId: props.message?.messageId as string,
rating: 'THUMBS_DOWN' as FeedbackRatingType,
content: '',
};
const result = await sendFeedbackQuery({
chatflowid: props.chatflowid,
apiHost: props.apiHost,
body,
onRequest: props.onRequest,
});
if (result.data) {
const data = result.data as any;
let id = '';
if (data && data.id) id = data.id;
setRating('THUMBS_DOWN');
setFeedbackId(id);
setShowFeedbackContentModal(true);
// update the thumbs down color state
setThumbsDownColor('#8B0000');
saveToLocalStorage('THUMBS_DOWN');
}
}
};
const submitFeedbackContent = async (text: string) => {
const body = {
content: text,
};
const result = await updateFeedbackQuery({
id: feedbackId(),
apiHost: props.apiHost,
body,
onRequest: props.onRequest,
});
if (result.data) {
setFeedbackId('');
setShowFeedbackContentModal(false);
}
};
onMount(() => {
if (botDetailsEl && props.isLoading) {
botDetailsEl.open = true;
}
});
createEffect(() => {
if (botDetailsEl && props.isLoading) {
botDetailsEl.open = true;
} else if (botDetailsEl && !props.isLoading) {
botDetailsEl.open = false;
}
});
const renderArtifacts = (item: Partial<FileUpload>) => {
// Instead of onMount, we'll use a callback ref to apply styles
const setArtifactRef = (el: HTMLSpanElement) => {
if (el) {
const textColor = props.textColor ?? defaultTextColor;
// Apply textColor to all elements except code blocks
el.querySelectorAll('a, h1, h2, h3, h4, h5, h6, strong, em, blockquote, li').forEach((element) => {
(element as HTMLElement).style.color = textColor;
});
// Code blocks (with pre) get white text
el.querySelectorAll('pre').forEach((element) => {
(element as HTMLElement).style.color = '#FFFFFF';
// Also ensure any code elements inside pre have white text
element.querySelectorAll('code').forEach((codeElement) => {
(codeElement as HTMLElement).style.color = '#FFFFFF';
});
});
// Inline code (not in pre) gets green text
el.querySelectorAll('code:not(pre code)').forEach((element) => {
(element as HTMLElement).style.color = '#4CAF50'; // Green color
});
el.querySelectorAll('a').forEach((link) => {
link.target = '_blank';
});
}
};
return (
<>
<Show when={item.type === 'png' || item.type === 'jpeg'}>
<div class="flex items-center justify-center p-0 m-0">
<img
class="w-full h-full bg-cover"
src={(() => {
const isFileStorage = typeof item.data === 'string' && item.data.startsWith('FILE-STORAGE::');
return isFileStorage
? `${props.apiHost}/api/v1/get-upload-file?chatflowId=${props.chatflowid}&chatId=${props.chatId}&fileName=${(
item.data as string
).replace('FILE-STORAGE::', '')}`
: (item.data as string);
})()}
/>
</div>
</Show>
<Show when={item.type === 'html'}>
<div class="mt-2">
<div innerHTML={DOMPurify.sanitize(item.data as string)} />
</div>
</Show>
<Show when={item.type !== 'png' && item.type !== 'jpeg' && item.type !== 'html'}>
<span
ref={setArtifactRef}
innerHTML={Marked.parse(item.data as string)}
class="prose"
style={{
'background-color': props.backgroundColor ?? defaultBackgroundColor,
color: props.textColor ?? defaultTextColor,
'border-radius': '6px',
'font-size': props.fontSize ? `${props.fontSize}px` : `${defaultFontSize}px`,
}}
/>
</Show>
</>
);
};
const formatDateTime = (dateTimeString: string | undefined, showDate: boolean | undefined, showTime: boolean | undefined) => {
if (!dateTimeString) return '';
try {
const date = new Date(dateTimeString);
// Check if the date is valid
if (isNaN(date.getTime())) {
console.error('Invalid ISO date string:', dateTimeString);
return '';
}
let formatted = '';
if (showDate) {
const dateFormatter = new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric',
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
});
const [{ value: month }, , { value: day }, , { value: year }] = dateFormatter.formatToParts(date);
formatted = `${month.charAt(0).toUpperCase() + month.slice(1)} ${day}, ${year}`;
}
if (showTime) {
const timeFormatter = new Intl.DateTimeFormat('en-US', {
hour: 'numeric',
minute: '2-digit',
hour12: true,
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
});
const timeString = timeFormatter.format(date).toLowerCase();
formatted = formatted ? `${formatted}, ${timeString}` : timeString;
}
return formatted;
} catch (error) {
console.error('Error formatting date:', error);
return '';
}
};
return (
<div>
<div class="flex flex-row justify-start mb-2 items-start host-container" style={{ 'margin-right': '50px' }}>
<Show when={props.showAvatar}>
<Avatar initialAvatarSrc={props.avatarSrc} />
</Show>
<div class="flex flex-col justify-start">
{props.showAgentMessages &&
props.message.agentFlowExecutedData &&
Array.isArray(props.message.agentFlowExecutedData) &&
props.message.agentFlowExecutedData.length > 0 && (
<div>
<WorkflowTreeView
workflowData={props.message.agentFlowExecutedData}
indentationLevel={24}
apiHost={props.apiHost}
chatflowid={props.chatflowid}
chatId={props.chatId}
hasCustomHeader={props.hasCustomHeader}
dialogContainer={props.dialogContainer}
/>
</div>
)}
{props.showAgentMessages && props.message.agentReasoning && (
<details ref={botDetailsEl} class="mb-2 px-4 py-2 ml-2 chatbot-host-bubble rounded-[6px]">
<summary class="cursor-pointer">
<span class="italic">Agent Messages</span>
</summary>
<br />
<For each={props.message.agentReasoning}>
{(agent) => {
const agentMessages = agent.messages ?? [];
let msgContent = agent.instructions || (agentMessages.length > 1 ? agentMessages.join('\\n') : agentMessages[0]);
if (agentMessages.length === 0 && !agent.instructions) msgContent = `<p>Finished</p>`;
return (
<AgentReasoningBubble
agentName={agent.agentName ?? ''}
agentMessage={msgContent}
agentArtifacts={agent.artifacts}
backgroundColor={props.backgroundColor}
textColor={props.textColor}
fontSize={props.fontSize}
apiHost={props.apiHost}
chatflowid={props.chatflowid}
chatId={props.chatId}
renderHTML={props.renderHTML}
/>
);
}}
</For>
</details>
)}
{props.message.artifacts && props.message.artifacts.length > 0 && (
<div class="flex flex-row items-start flex-wrap w-full gap-2">
<For each={props.message.artifacts}>
{(item) => {
return item !== null ? <>{renderArtifacts(item)}</> : null;
}}
</For>
</div>
)}
{props.message.thinking && (
<div class="ml-2 mb-1 max-w-full">
<ThinkingCard
thinking={props.message.thinking}
thinkingDuration={props.message.thinkingDuration}
isThinking={props.message.isThinking}
backgroundColor={props.backgroundColor ?? defaultBackgroundColor}
textColor={props.textColor ?? defaultTextColor}
/>
</div>
)}
{props.message.message && (
<span
ref={setBotMessageRef}
class="px-4 py-2 ml-2 max-w-full chatbot-host-bubble prose"
data-testid="host-bubble"
style={{
'background-color': props.backgroundColor ?? defaultBackgroundColor,
color: props.textColor ?? defaultTextColor,
'border-radius': '6px',
'font-size': props.fontSize ? `${props.fontSize}px` : `${defaultFontSize}px`,
}}
/>
)}
{props.message.action && (
<div class="px-4 py-2 flex flex-row justify-start space-x-2">
<For each={props.message.action.elements || []}>
{(action) => {
return (
<>
{(action.type === 'approve-button' && action.label === 'Yes') || action.type === 'agentflowv2-approve-button' ? (
<button
type="button"
class="px-4 py-2 font-medium text-green-600 border border-green-600 rounded-full hover:bg-green-600 hover:text-white transition-colors duration-300 flex items-center space-x-2"
onClick={() => props.handleActionClick(action, props.message.action)}
>
<TickIcon />
{action.label}
</button>
) : (action.type === 'reject-button' && action.label === 'No') || action.type === 'agentflowv2-reject-button' ? (
<button
type="button"
class="px-4 py-2 font-medium text-red-600 border border-red-600 rounded-full hover:bg-red-600 hover:text-white transition-colors duration-300 flex items-center space-x-2"
onClick={() => props.handleActionClick(action, props.message.action)}
>
<XIcon isCurrentColor={true} />
{action.label}
</button>
) : (
<button type="button">{action.label}</button>
)}
</>
);
}}
</For>
</div>
)}
</div>
</div>
<div>
{props.message.sourceDocuments && props.message.sourceDocuments.length && (
<>
<Show when={props.sourceDocsTitle}>
<span class="px-2 py-[10px] font-semibold">{props.sourceDocsTitle}</span>
</Show>
<div style={{ display: 'flex', 'flex-direction': 'row', width: '100%', 'flex-wrap': 'wrap' }}>
<For each={[...removeDuplicateURL(props.message)]}>
{(src) => {
const URL = isValidURL(src.metadata.source);
return (
<SourceBubble
pageContent={src.metadata.title ? src.metadata.title : URL ? URL.pathname : src.pageContent}
metadata={src.metadata}
onSourceClick={() => {
if (URL) {
window.open(src.metadata.source, '_blank');
} else {
props.handleSourceDocumentsClick(src);
}
}}
/>
);
}}
</For>
</div>
</>
)}
</div>
<div>
<div class={`flex items-center px-2 pb-2 ${props.showAvatar ? 'ml-10' : ''}`}>
<Show when={props.isTTSEnabled && (props.message.id || props.message.messageId)}>
<TTSButton
feedbackColor={props.feedbackColor}
isLoading={(() => {
const messageId = props.message.id || props.message.messageId;
return !!(messageId && props.isTTSLoading?.[messageId]);
})()}
isPlaying={(() => {
const messageId = props.message.id || props.message.messageId;
return !!(messageId && props.isTTSPlaying?.[messageId]);
})()}
onClick={() => {
const messageId = props.message.id || props.message.messageId;
if (!messageId) return; // Don't allow TTS for messages without valid IDs
const messageText = props.message.message || '';
if (props.isTTSLoading?.[messageId]) {
return; // Prevent multiple clicks while loading
}
if (props.isTTSPlaying?.[messageId]) {
props.handleTTSStop?.(messageId);
} else {
props.handleTTSClick?.(messageId, messageText);
}
}}
/>
</Show>
{props.chatFeedbackStatus && props.message.messageId && (
<>
<RegenerateResponseButton class="regenerate-response-button" feedbackColor={props.feedbackColor} onClick={() => props.onRegenerateResponse?.()} />
<CopyToClipboardButton feedbackColor={props.feedbackColor} onClick={() => copyMessageToClipboard()} />
<Show when={copiedMessage()}>
<div class="copied-message" style={{ color: props.feedbackColor ?? defaultFeedbackColor }}>
Copied!
</div>
</Show>
{rating() === '' || rating() === 'THUMBS_UP' ? (
<ThumbsUpButton feedbackColor={thumbsUpColor()} isDisabled={rating() === 'THUMBS_UP'} rating={rating()} onClick={onThumbsUpClick} />
) : null}
{rating() === '' || rating() === 'THUMBS_DOWN' ? (
<ThumbsDownButton
feedbackColor={thumbsDownColor()}
isDisabled={rating() === 'THUMBS_DOWN'}
rating={rating()}
onClick={onThumbsDownClick}
/>
) : null}
<Show when={props.message.dateTime}>
<div class="text-sm text-gray-500 ml-2">
{formatDateTime(props.message.dateTime, props?.dateTimeToggle?.date, props?.dateTimeToggle?.time)}
</div>
</Show>
</>
)}
</div>
<Show when={showFeedbackContentDialog()}>
<FeedbackContentDialog
isOpen={showFeedbackContentDialog()}
onClose={() => setShowFeedbackContentModal(false)}
onSubmit={submitFeedbackContent}
backgroundColor={props.backgroundColor}
textColor={props.textColor}
/>
</Show>
</div>
</div>
);
};