@admin-layout/tailwind-chat-pro 12.2.4-alpha.102

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 (65) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/LICENSE +21 -0
  3. package/lib/components/index.d.ts +2 -0
  4. package/lib/components/index.d.ts.map +1 -0
  5. package/lib/components/messages-container-ui/DefaultInputToolBar.d.ts +21 -0
  6. package/lib/components/messages-container-ui/DefaultInputToolBar.d.ts.map +1 -0
  7. package/lib/components/messages-container-ui/DefaultInputToolBar.js +46 -0
  8. package/lib/components/messages-container-ui/DefaultInputToolBar.js.map +1 -0
  9. package/lib/components/messages-container-ui/DefaultMessageGroup.d.ts +16 -0
  10. package/lib/components/messages-container-ui/DefaultMessageGroup.d.ts.map +1 -0
  11. package/lib/components/messages-container-ui/DefaultMessageGroup.js +64 -0
  12. package/lib/components/messages-container-ui/DefaultMessageGroup.js.map +1 -0
  13. package/lib/components/messages-container-ui/ErrorFixCard.d.ts +10 -0
  14. package/lib/components/messages-container-ui/ErrorFixCard.d.ts.map +1 -0
  15. package/lib/components/messages-container-ui/ErrorFixCard.js +219 -0
  16. package/lib/components/messages-container-ui/ErrorFixCard.js.map +1 -0
  17. package/lib/components/messages-container-ui/FilesList.d.ts +19 -0
  18. package/lib/components/messages-container-ui/FilesList.d.ts.map +1 -0
  19. package/lib/components/messages-container-ui/FilesList.js +75 -0
  20. package/lib/components/messages-container-ui/FilesList.js.map +1 -0
  21. package/lib/components/messages-container-ui/MessagesContainerUI.d.ts +98 -0
  22. package/lib/components/messages-container-ui/MessagesContainerUI.d.ts.map +1 -0
  23. package/lib/components/messages-container-ui/MessagesContainerUI.js +88 -0
  24. package/lib/components/messages-container-ui/MessagesContainerUI.js.map +1 -0
  25. package/lib/components/messages-container-ui/ModernMessageGroup.d.ts +46 -0
  26. package/lib/components/messages-container-ui/ModernMessageGroup.d.ts.map +1 -0
  27. package/lib/components/messages-container-ui/ModernMessageGroup.js +1568 -0
  28. package/lib/components/messages-container-ui/ModernMessageGroup.js.map +1 -0
  29. package/lib/components/messages-container-ui/PlanModeView.d.ts +107 -0
  30. package/lib/components/messages-container-ui/PlanModeView.d.ts.map +1 -0
  31. package/lib/components/messages-container-ui/PlanModeView.js +294 -0
  32. package/lib/components/messages-container-ui/PlanModeView.js.map +1 -0
  33. package/lib/components/messages-container-ui/index.d.ts +12 -0
  34. package/lib/components/messages-container-ui/index.d.ts.map +1 -0
  35. package/lib/components/messages-container-ui/messenger-slot-fill-name-enum.d.ts +16 -0
  36. package/lib/components/messages-container-ui/messenger-slot-fill-name-enum.d.ts.map +1 -0
  37. package/lib/components/messages-container-ui/messenger-slot-fill-name-enum.js +16 -0
  38. package/lib/components/messages-container-ui/messenger-slot-fill-name-enum.js.map +1 -0
  39. package/lib/components/messages-container-ui/modernStreaming.d.ts +11 -0
  40. package/lib/components/messages-container-ui/modernStreaming.d.ts.map +1 -0
  41. package/lib/components/messages-container-ui/modernStreaming.js +17 -0
  42. package/lib/components/messages-container-ui/modernStreaming.js.map +1 -0
  43. package/lib/components/messages-container-ui/types.d.ts +63 -0
  44. package/lib/components/messages-container-ui/types.d.ts.map +1 -0
  45. package/lib/index.d.ts +2 -0
  46. package/lib/index.d.ts.map +1 -0
  47. package/lib/index.js +1 -0
  48. package/lib/index.js.map +1 -0
  49. package/lib/routes.json +1 -0
  50. package/package.json +48 -0
  51. package/rollup.config.mjs +34 -0
  52. package/src/components/index.ts +1 -0
  53. package/src/components/messages-container-ui/DefaultInputToolBar.tsx +63 -0
  54. package/src/components/messages-container-ui/DefaultMessageGroup.tsx +75 -0
  55. package/src/components/messages-container-ui/ErrorFixCard.tsx +239 -0
  56. package/src/components/messages-container-ui/FilesList.tsx +89 -0
  57. package/src/components/messages-container-ui/MessagesContainerUI.tsx +178 -0
  58. package/src/components/messages-container-ui/ModernMessageGroup.tsx +1885 -0
  59. package/src/components/messages-container-ui/PlanModeView.tsx +457 -0
  60. package/src/components/messages-container-ui/index.ts +18 -0
  61. package/src/components/messages-container-ui/messenger-slot-fill-name-enum.ts +15 -0
  62. package/src/components/messages-container-ui/modernStreaming.tsx +18 -0
  63. package/src/components/messages-container-ui/types.ts +68 -0
  64. package/src/index.ts +1 -0
  65. package/tsconfig.json +27 -0
@@ -0,0 +1,1885 @@
1
+ import { Slot } from '@common-stack/components-pro';
2
+ import { AiAgentMessageRole, IAuthUser, IPost } from 'common';
3
+ import { differenceInMinutes, format } from 'date-fns';
4
+ import { marked } from 'marked';
5
+ import React, { useEffect, useMemo, useState } from 'react';
6
+ import ReactMarkdown from 'react-markdown';
7
+ import remarkBreaks from 'remark-breaks';
8
+ import remarkGfm from 'remark-gfm';
9
+ import { MessengerSlotFillNameEnum } from './messenger-slot-fill-name-enum';
10
+ import { FilesList } from './FilesList';
11
+ import { ErrorFixCard } from './ErrorFixCard';
12
+
13
+ // Configure marked for better markdown rendering
14
+ marked.setOptions({
15
+ breaks: true, // Convert line breaks to <br>
16
+ gfm: true, // GitHub Flavored Markdown
17
+ headerIds: false, // Disable header IDs for cleaner HTML
18
+ mangle: false, // Don't mangle email addresses
19
+ });
20
+
21
+ const ASSISTANT_RESPONSE_THEME_CLASS = 'llm-response-theme';
22
+ const ASSISTANT_RESPONSE_CLASS = 'llm-response';
23
+ const ASSISTANT_RESPONSE_BUBBLE_CLASS = 'llm-response__bubble';
24
+ const ASSISTANT_RESPONSE_MARKDOWN_CLASS = 'llm-response__markdown';
25
+ const USER_MESSAGE_TEXT_SIZE_CLASS = 'text-base';
26
+ const USER_MESSAGE_PROSE_SIZE_CLASS = 'prose-base';
27
+ /** Pasted queries longer than this collapse behind a "Show more" toggle. */
28
+ const USER_MESSAGE_COLLAPSE_CHAR_THRESHOLD = 600;
29
+ const USER_MESSAGE_COLLAPSED_MAX_HEIGHT = 220;
30
+
31
+ function getAssistantResponseClasses(innerClassName?: string): string {
32
+ return [ASSISTANT_RESPONSE_MARKDOWN_CLASS, innerClassName].filter(Boolean).join(' ');
33
+ }
34
+
35
+ export function AssistantResponseWrapper({
36
+ children,
37
+ bubbleClassName,
38
+ }: {
39
+ children: React.ReactNode;
40
+ bubbleClassName?: string;
41
+ }) {
42
+ return (
43
+ <div className={ASSISTANT_RESPONSE_THEME_CLASS}>
44
+ <div className={ASSISTANT_RESPONSE_CLASS}>
45
+ <div className={[ASSISTANT_RESPONSE_BUBBLE_CLASS, bubbleClassName].filter(Boolean).join(' ')}>
46
+ {children}
47
+ </div>
48
+ </div>
49
+ </div>
50
+ );
51
+ }
52
+
53
+ // Enhanced CSS styles for HTML content rendering with prettification
54
+ const htmlContentStyles = `
55
+ .html-content {
56
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
57
+ line-height: 1.6;
58
+ color: inherit;
59
+ }
60
+
61
+ .html-content h1, .html-content h2, .html-content h3, .html-content h4, .html-content h5, .html-content h6 {
62
+ margin-top: 1.5rem;
63
+ margin-bottom: 1rem;
64
+ font-weight: 600;
65
+ line-height: 1.25;
66
+ color: inherit;
67
+ }
68
+
69
+ .html-content h1 {
70
+ font-size: 1.875rem;
71
+ border-bottom: 2px solid #e5e7eb;
72
+ padding-bottom: 0.5rem;
73
+ }
74
+ .${ASSISTANT_RESPONSE_THEME_CLASS} {
75
+ --llm-content-max-width: 100%;
76
+ --llm-font-sans: 'Avenir Next', 'Segoe UI', sans-serif;
77
+ --llm-font-mono: 'IBM Plex Mono', 'SFMono-Regular', Menlo, Consolas, monospace;
78
+ --llm-color-bg: #ffffff;
79
+ --llm-color-surface: #f6f7f8;
80
+ --llm-color-surface-2: #eef1f4;
81
+ --llm-color-surface-hover: #e9edf2;
82
+ --llm-color-border: #e3e7ee;
83
+ --llm-color-border-strong: #cfd7e3;
84
+ --llm-color-text: #121926;
85
+ --llm-color-text-secondary: #667085;
86
+ --llm-color-marker: #8e98a8;
87
+ --llm-color-link-underline: rgba(18, 25, 38, 0.18);
88
+ --llm-color-code-bg: rgba(249, 115, 22, 0.1);
89
+ --llm-color-code-text: #d96b00;
90
+ --llm-color-code-block-border: #ebeef3;
91
+ --llm-shadow-soft: 0 1px 2px rgba(18, 25, 38, 0.04), 0 10px 32px rgba(18, 25, 38, 0.05);
92
+ --llm-radius-bubble: 1.5rem;
93
+ --llm-radius-code: 0.85rem;
94
+ --llm-line-height-body: 1.62;
95
+ --llm-line-height-mobile: 1.55;
96
+ --llm-line-height-heading: 1.35;
97
+ --llm-space-heading-top: 1.45rem;
98
+ --llm-space-heading-bottom: 0.75rem;
99
+ --llm-space-paragraph: 1rem;
100
+ --llm-space-list: 0.9rem;
101
+ color: inherit;
102
+ background: transparent;
103
+ }
104
+
105
+ .${ASSISTANT_RESPONSE_THEME_CLASS}[data-color-mode='dark'],
106
+ [data-color-mode='dark'] .${ASSISTANT_RESPONSE_THEME_CLASS} {
107
+ --llm-color-bg: #0f1115;
108
+ --llm-color-surface: #171a20;
109
+ --llm-color-surface-2: #1f2530;
110
+ --llm-color-surface-hover: #232a36;
111
+ --llm-color-border: #2a3240;
112
+ --llm-color-border-strong: #364052;
113
+ --llm-color-text: #f3f5f8;
114
+ --llm-color-text-secondary: #aab3c2;
115
+ --llm-color-marker: #7f8999;
116
+ --llm-color-link-underline: rgba(243, 245, 248, 0.24);
117
+ --llm-color-code-bg: rgba(251, 146, 60, 0.14);
118
+ --llm-color-code-text: #ffb36b;
119
+ --llm-color-code-block-border: #262d39;
120
+ --llm-shadow-soft: 0 1px 2px rgba(0, 0, 0, 0.28), 0 14px 36px rgba(0, 0, 0, 0.3);
121
+ }
122
+
123
+ .${ASSISTANT_RESPONSE_CLASS} {
124
+ position: relative;
125
+ display: flex;
126
+ flex-direction: column;
127
+ align-items: flex-start;
128
+ justify-content: center;
129
+ width: 100%;
130
+ max-width: var(--llm-content-max-width);
131
+ font-family: var(--llm-font-sans);
132
+ color: inherit;
133
+ }
134
+
135
+ .${ASSISTANT_RESPONSE_BUBBLE_CLASS} {
136
+ position: relative;
137
+ width: 100%;
138
+ min-height: 1.75rem;
139
+ border-radius: var(--llm-radius-bubble);
140
+ color: inherit;
141
+ word-break: break-word;
142
+ }
143
+
144
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} {
145
+ position: relative;
146
+ width: 100%;
147
+ max-width: none;
148
+ color: inherit;
149
+ font-size: 1rem;
150
+ line-height: var(--llm-line-height-body);
151
+ }
152
+
153
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} > :first-child {
154
+ margin-top: 0;
155
+ }
156
+
157
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} > :last-child {
158
+ margin-bottom: 0;
159
+ }
160
+
161
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} p,
162
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} li,
163
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} th,
164
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} td,
165
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} blockquote,
166
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS}.html-content,
167
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS}.assistant-html-content {
168
+ color: inherit;
169
+ }
170
+
171
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} p,
172
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS}.html-content p,
173
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS}.assistant-html-content p {
174
+ margin: 0 0 var(--llm-space-paragraph);
175
+ white-space: pre-wrap;
176
+ }
177
+
178
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} h1,
179
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} h2,
180
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} h3,
181
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} h4,
182
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} h5,
183
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} h6 {
184
+ margin: var(--llm-space-heading-top) 0 var(--llm-space-heading-bottom);
185
+ font-weight: 600;
186
+ letter-spacing: -0.02em;
187
+ line-height: var(--llm-line-height-heading);
188
+ color: inherit;
189
+ }
190
+
191
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} h1 { font-size: 1.75rem; }
192
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} h2 { font-size: 1.5rem; }
193
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} h3 { font-size: 1.25rem; }
194
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} h4 { font-size: 1.05rem; }
195
+
196
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} strong,
197
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} b {
198
+ font-weight: 600;
199
+ color: inherit;
200
+ }
201
+
202
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} em,
203
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} i {
204
+ color: var(--llm-color-text-secondary);
205
+ }
206
+
207
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} a {
208
+ color: currentColor;
209
+ text-decoration: underline;
210
+ text-decoration-color: var(--llm-color-link-underline);
211
+ text-underline-offset: 0.18em;
212
+ transition: color 120ms ease, text-decoration-color 120ms ease;
213
+ }
214
+
215
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} a:hover {
216
+ color: inherit;
217
+ text-decoration-color: currentColor;
218
+ }
219
+
220
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} ul,
221
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} ol {
222
+ margin: 0.35rem 0 var(--llm-space-list);
223
+ padding-left: 1.15rem;
224
+ }
225
+
226
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} ul {
227
+ list-style-type: disc;
228
+ }
229
+
230
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} ol {
231
+ list-style-type: decimal;
232
+ /* Wider gutter so multi-digit markers (e.g. "60.") aren't clipped at the
233
+ content's left edge — long numbered content (verse, step lists) showed
234
+ "0." for line 60. */
235
+ padding-left: 2rem;
236
+ }
237
+
238
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} li {
239
+ margin: 0.28rem 0;
240
+ padding-inline-start: 0.1rem;
241
+ /* \`normal\` collapses the stray "\\n" react-markdown inserts between <li>
242
+ and its child <p>; with \`pre-wrap\` that newline rendered as a blank
243
+ first line, stranding the marker above its text. Intra-paragraph
244
+ whitespace is preserved by the \`li > p\` rule below. */
245
+ white-space: normal;
246
+ }
247
+
248
+ /* Loose list items wrap their text in <p>. Keep pre-wrap for the text but
249
+ drop the paragraph margins so each item is a single tight line — fixes
250
+ poems / verse the model emits as numbered lists rendering as a sprawling,
251
+ double-spaced listicle. */
252
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} li > p {
253
+ margin-top: 0;
254
+ white-space: pre-wrap;
255
+ }
256
+
257
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} li > p:last-child {
258
+ margin-bottom: 0;
259
+ }
260
+
261
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} li > ul,
262
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} li > ol {
263
+ margin-top: 0.35rem;
264
+ margin-bottom: 0.15rem;
265
+ white-space: normal;
266
+ }
267
+
268
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} ::marker {
269
+ color: var(--llm-color-marker);
270
+ }
271
+
272
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} hr {
273
+ margin: 1.25rem 0;
274
+ border: 0;
275
+ border-top: 1px solid var(--llm-color-border);
276
+ }
277
+
278
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} blockquote {
279
+ margin: 1rem 0;
280
+ padding: 0.2rem 0 0.2rem 1rem;
281
+ border-left: 2px solid var(--llm-color-border-strong);
282
+ background: transparent;
283
+ color: var(--llm-color-text-secondary);
284
+ }
285
+
286
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} blockquote p {
287
+ margin-bottom: 0;
288
+ color: inherit;
289
+ }
290
+
291
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} :not(pre) > code,
292
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} .llm-inline-code {
293
+ display: inline-block;
294
+ padding: 0.08rem 0.38rem;
295
+ border: 0;
296
+ border-radius: 0.32rem;
297
+ font-family: var(--llm-font-mono);
298
+ font-size: 0.875em;
299
+ line-height: 1.45;
300
+ background: var(--llm-color-code-bg);
301
+ color: var(--llm-color-code-text);
302
+ box-decoration-break: clone;
303
+ -webkit-box-decoration-break: clone;
304
+ }
305
+
306
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} table {
307
+ width: 100%;
308
+ margin: 1rem 0 1.1rem;
309
+ border-collapse: separate;
310
+ border-spacing: 0;
311
+ border: 1px solid var(--llm-color-border);
312
+ border-radius: 1rem;
313
+ overflow: hidden;
314
+ box-shadow: var(--llm-shadow-soft);
315
+ }
316
+
317
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} thead {
318
+ background: var(--llm-color-surface);
319
+ }
320
+
321
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} th,
322
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} td {
323
+ padding: 0.85rem 1rem;
324
+ border-bottom: 1px solid var(--llm-color-border);
325
+ text-align: left;
326
+ vertical-align: top;
327
+ }
328
+
329
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} th {
330
+ font-size: 0.8rem;
331
+ font-weight: 600;
332
+ letter-spacing: 0.02em;
333
+ color: var(--llm-color-text-secondary);
334
+ background: var(--llm-color-surface);
335
+ }
336
+
337
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} td {
338
+ color: var(--llm-color-text);
339
+ background: var(--llm-color-bg);
340
+ }
341
+
342
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} tbody tr:last-child td {
343
+ border-bottom: 0;
344
+ }
345
+
346
+ @media (max-width: 768px) {
347
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} {
348
+ font-size: 0.95rem;
349
+ line-height: var(--llm-line-height-mobile);
350
+ }
351
+
352
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} th,
353
+ .${ASSISTANT_RESPONSE_MARKDOWN_CLASS} td {
354
+ padding: 0.75rem 0.8rem;
355
+ }
356
+ }
357
+ * we must neutralize it so it doesn't override the pill background/padding.
358
+ */
359
+ .user-message .message-container {
360
+ background: transparent !important;
361
+ padding-top: 0 !important;
362
+ padding-bottom: 0 !important;
363
+ margin: 0 !important;
364
+ transition: none !important;
365
+ box-shadow: none !important;
366
+ }
367
+
368
+ /* Safety net: long unbroken tokens (file paths, CSS selectors, URLs) inside a
369
+ pasted user query must never push the bubble past its own width — wrap
370
+ anywhere rather than overflow the card. */
371
+ .user-message,
372
+ .user-message * {
373
+ max-width: 100%;
374
+ overflow-wrap: anywhere;
375
+ }
376
+
377
+ /* Assistant replies must read as plain text on the page — no card. A shared
378
+ global class (.message-container, from @messenger-box/tailwind-ui-inbox)
379
+ ships its own pill background/padding; neutralize it here the same way the
380
+ user bubble already does above. */
381
+ .${ASSISTANT_RESPONSE_THEME_CLASS},
382
+ .${ASSISTANT_RESPONSE_CLASS},
383
+ .${ASSISTANT_RESPONSE_BUBBLE_CLASS},
384
+ .${ASSISTANT_RESPONSE_THEME_CLASS} .message-container {
385
+ background: transparent !important;
386
+ box-shadow: none !important;
387
+ }
388
+ .${ASSISTANT_RESPONSE_THEME_CLASS} .message-container {
389
+ padding: 0 !important;
390
+ margin: 0 !important;
391
+ }
392
+
393
+ /* Code block container styling */
394
+ .code-block-container {
395
+ background: #ffffff;
396
+ border: 1px solid #e5e7eb;
397
+ border-radius: 8px;
398
+ overflow: hidden;
399
+ margin: 1rem 0;
400
+ box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
401
+ }
402
+
403
+ .code-block-header {
404
+ background: #f9fafb;
405
+ padding: 0.5rem 1rem;
406
+ border-bottom: 1px solid #e5e7eb;
407
+ font-weight: 600;
408
+ color: #374151;
409
+ font-size: 0.875rem;
410
+ text-transform: uppercase;
411
+ letter-spacing: 0.05em;
412
+ }
413
+
414
+ `;
415
+
416
+ // Hook to inject CSS styles
417
+ const useInjectStyles = () => {
418
+ useEffect(() => {
419
+ const styleElementPresent = !!document.getElementById('html-content-styles');
420
+
421
+ // Check if styles are already injected
422
+ if (styleElementPresent) {
423
+ return;
424
+ }
425
+
426
+ // Create and inject style element
427
+ const styleElement = document.createElement('style');
428
+ styleElement.id = 'html-content-styles';
429
+ styleElement.textContent = htmlContentStyles;
430
+ document.head.appendChild(styleElement);
431
+
432
+ // Cleanup function
433
+ return () => {
434
+ const existingStyle = document.getElementById('html-content-styles');
435
+ if (existingStyle) {
436
+ existingStyle.remove();
437
+ }
438
+ };
439
+ }, []);
440
+ };
441
+
442
+ interface ModernMessageGroupProps {
443
+ showAuthorName?: boolean;
444
+ showAvatar?: boolean;
445
+ showTimestamp?: boolean;
446
+ messages: IPost[];
447
+ currentUser: IAuthUser;
448
+ onOpen: (element?: any) => void;
449
+ onMessageClick: (msg: IPost) => void;
450
+ isDesktopView?: boolean;
451
+ isSmallScreen?: boolean;
452
+ sandboxErrors?: any[];
453
+ currentFiles?: Record<string, string>;
454
+ onFixError?: (errorMessage: string) => Promise<void>;
455
+ onRecreateSandbox?: (fragmentId: string) => void;
456
+ /** When true, code blocks show copy and download actions in header and footer (default: true) */
457
+ showCopyDownloadOnCodeBlock?: boolean;
458
+ }
459
+
460
+ interface MessageGroupProps {
461
+ showAuthorName?: boolean;
462
+ showAvatar?: boolean;
463
+ showTimestamp?: boolean;
464
+ author: any;
465
+ messages: IPost[];
466
+ currentUser: IAuthUser;
467
+ onOpen: (element?: any) => void;
468
+ onMessageClick: (msg: IPost) => void;
469
+ isDesktopView?: boolean;
470
+ isSmallScreen?: boolean;
471
+ showCopyDownloadOnCodeBlock?: boolean;
472
+ }
473
+
474
+ // Enhanced utility function to group messages by user and time
475
+ export const groupMessagesByUserAndTime = (messages: IPost[], timeThresholdMinutes = 5): IPost[][] => {
476
+ if (!messages || messages.length === 0) return [];
477
+
478
+ const groups: IPost[][] = [];
479
+ let currentGroup: IPost[] = [];
480
+ let lastMessage: IPost | null = null;
481
+
482
+ for (const message of messages) {
483
+ if (typeof message === 'string') continue; // Skip date separators
484
+
485
+ const shouldStartNewGroup =
486
+ !lastMessage ||
487
+ lastMessage.author?.id !== message.author?.id ||
488
+ differenceInMinutes(new Date(message.createdAt), new Date(lastMessage.createdAt)) > timeThresholdMinutes;
489
+
490
+ if (shouldStartNewGroup) {
491
+ if (currentGroup.length > 0) {
492
+ groups.push(currentGroup);
493
+ }
494
+ currentGroup = [message];
495
+ } else {
496
+ currentGroup.push(message);
497
+ }
498
+
499
+ lastMessage = message;
500
+ }
501
+
502
+ if (currentGroup.length > 0) {
503
+ groups.push(currentGroup);
504
+ }
505
+
506
+ return groups;
507
+ };
508
+
509
+ // Enhanced content detection that properly identifies different content types
510
+ export const detectContentType = (value: string): 'html' | 'markdown' | 'code' | 'text' => {
511
+ if (!value) return 'text';
512
+
513
+ const trimmed = value.trim();
514
+
515
+ // Check for markdown patterns FIRST (before code, as markdown can contain code blocks)
516
+ const markdownPatterns = [
517
+ /^#{1,6}\s+.+$/gm, // Headers (must have text after #)
518
+ /^\s*[-*+]\s+.+$/gm, // Unordered lists
519
+ /^\s*\d+\.\s+.+$/gm, // Numbered lists
520
+ /\[.+?\]\(.+?\)/g, // Links
521
+ /!\[.+?\]\(.+?\)/g, // Images
522
+ /```[\s\S]*?```/g, // Fenced code blocks (markdown feature)
523
+ /^\s*>\s+/gm, // Blockquotes
524
+ /\*\*.*?\*\*/g, // Bold
525
+ /\*[^*].*?\*/g, // Italic (not just asterisks)
526
+ /^\s*\|.+\|/gm, // Tables
527
+ ];
528
+
529
+ // Count markdown patterns - if we have multiple, it's likely markdown
530
+ const markdownMatches = markdownPatterns.filter((pattern) => {
531
+ const matches = trimmed.match(pattern);
532
+ return matches && matches.length > 0;
533
+ }).length;
534
+
535
+ // If we have 2+ markdown patterns, it's definitely markdown
536
+ if (markdownMatches >= 2) return 'markdown';
537
+
538
+ // If we have headers or lists, it's likely markdown
539
+ if (/^#{1,6}\s+/gm.test(trimmed) || /^\s*[-*+]\s+/gm.test(trimmed) || /^\s*\d+\.\s+/gm.test(trimmed)) {
540
+ return 'markdown';
541
+ }
542
+
543
+ // Check for pure code patterns (without markdown context)
544
+ const pureCodePatterns = [
545
+ /^---\s*\w+\.\w+\s*---$/gm, // File separators (standalone)
546
+ /^@tailwind\s+\w+/gm, // Tailwind directives at start
547
+ /^export\s+default\s*\{/gm, // JS/TS exports at start
548
+ /^import\s+.*\s+from\s+['"]/gm, // Import statements at start
549
+ ];
550
+
551
+ const hasPureCodePatterns = pureCodePatterns.some((pattern) => pattern.test(trimmed));
552
+ if (hasPureCodePatterns && markdownMatches === 0) return 'code';
553
+
554
+ // Check for HTML patterns
555
+ const htmlPatterns = [
556
+ /<[a-z][\s\S]*?>/i, // HTML tags
557
+ /&[a-z0-9#]+;/i, // HTML entities
558
+ /<[^>]+>[^<]*<\/[^>]+>/i, // HTML structure
559
+ ];
560
+
561
+ const hasHtmlPatterns = htmlPatterns.some((pattern) => pattern.test(trimmed));
562
+ // Only return HTML if it's clearly HTML and not markdown
563
+ if (hasHtmlPatterns && markdownMatches === 0) return 'html';
564
+
565
+ // Default to text, but FormattedMessageContent will still try to parse as markdown
566
+ return 'text';
567
+ };
568
+
569
+ // Legacy function for backward compatibility
570
+ const isProbablyHTML = (value: string): boolean => {
571
+ return detectContentType(value) === 'html';
572
+ };
573
+
574
+ /** Map message type (THINKING, TOOLUSE, etc.) to slot fill name for Kimi-like streaming UI */
575
+ const getMessageSlotName = (type: string | undefined): string | null => {
576
+ if (!type) return null;
577
+ const t = String(type).toUpperCase();
578
+ if (t === 'THINKING') return MessengerSlotFillNameEnum.THINKING_NAME;
579
+ if (t === 'TOOLUSE') return MessengerSlotFillNameEnum.TOOLUSE_NAME;
580
+ if (t === 'CODEBLOCK') return MessengerSlotFillNameEnum.CODEBLOCK_NAME;
581
+ if (t === 'SERVICE') return MessengerSlotFillNameEnum.SERVICE_NAME;
582
+ if (t === 'AIASSISTANT' || t === 'ASSISTANT') return MessengerSlotFillNameEnum.AIASSISTANT_NAME;
583
+ if (t === 'TRAVEL') return MessengerSlotFillNameEnum.TRAVEL_NAME;
584
+ if (t === 'MEDIA') return MessengerSlotFillNameEnum.MEDIA_NAME;
585
+ if (t === 'WORKFLOW') return MessengerSlotFillNameEnum.WORKFLOW_NAME;
586
+ if (t === 'CONNECTOR') return MessengerSlotFillNameEnum.CONNECTOR_NAME;
587
+ // Shared catch-all card (shopping, design, page/resume, …). Routes type:'generic' to the
588
+ // registered `generic` Fill (MessageGeneric); without this the generic Fill never mounts.
589
+ if (t === 'GENERIC') return MessengerSlotFillNameEnum.GENERIC_NAME;
590
+ return null;
591
+ };
592
+
593
+ // Enhanced sanitizer that allows most HTML tags while maintaining security
594
+ const sanitizeHtml = (html: string): string => {
595
+ try {
596
+ if (typeof window === 'undefined' || typeof window.DOMParser === 'undefined') {
597
+ return html
598
+ .replace(/<script[\s\S]*?>[\s\S]*?<\/script>/gi, '')
599
+ .replace(/<style[\s\S]*?>[\s\S]*?<\/style>/gi, '')
600
+ .replace(/on\w+\s*=\s*"[^"]*"/gi, '')
601
+ .replace(/on\w+\s*=\s*'[^']*'/gi, '')
602
+ .replace(/on\w+\s*=\s*[^\s>]+/gi, '')
603
+ .replace(/javascript:/gi, '')
604
+ .replace(/data:text\/html/gi, '');
605
+ }
606
+
607
+ const parser = new window.DOMParser();
608
+ const doc = parser.parseFromString(html, 'text/html');
609
+
610
+ // Only remove the most dangerous tags
611
+ const dangerousTags = ['script', 'style'];
612
+ dangerousTags.forEach((tag) => {
613
+ doc.querySelectorAll(tag).forEach((el) => el.remove());
614
+ });
615
+
616
+ const walker = doc.createTreeWalker(doc.body, (NodeFilter as any).SHOW_ELEMENT);
617
+ let node = walker.nextNode() as Element | null;
618
+ while (node) {
619
+ Array.from(node.attributes).forEach((attr) => {
620
+ const name = attr.name.toLowerCase();
621
+ const value = (attr.value || '').toLowerCase();
622
+
623
+ // Remove event handlers and javascript protocols
624
+ if (name.startsWith('on') || value.startsWith('javascript:')) {
625
+ node?.removeAttribute(attr.name);
626
+ }
627
+
628
+ // Allow most attributes but validate URLs for src/href
629
+ if ((name === 'src' || name === 'href') && !/^https?:|^\/.*/.test(attr.value)) {
630
+ node?.removeAttribute(attr.name);
631
+ }
632
+ });
633
+ node = walker.nextNode() as Element | null;
634
+ }
635
+
636
+ return doc.body.innerHTML;
637
+ } catch (e) {
638
+ return html.replace(/<script[\s\S]*?>[\s\S]*?<\/script>/gi, '');
639
+ }
640
+ };
641
+
642
+ // Function to prettify HTML content
643
+ const prettifyHtmlContent = (htmlContent: string): string => {
644
+ // Add semantic classes for better styling
645
+ let prettified = htmlContent;
646
+
647
+ // Enhance headings with better styling
648
+ prettified = prettified.replace(/<h([1-6])>/g, '<h$1 class="html-heading html-heading-$1">');
649
+
650
+ // Enhance lists with better styling
651
+ prettified = prettified.replace(/<ul>/g, '<ul class="html-list html-list-unordered">');
652
+ prettified = prettified.replace(/<ol>/g, '<ol class="html-list html-list-ordered">');
653
+
654
+ // Enhance paragraphs with better spacing
655
+ prettified = prettified.replace(/<p>/g, '<p class="html-paragraph">');
656
+
657
+ // Enhance code blocks
658
+ prettified = prettified.replace(/<code>/g, '<code class="html-inline-code">');
659
+ prettified = prettified.replace(/<pre>/g, '<pre class="html-code-block">');
660
+
661
+ // Enhance blockquotes
662
+ prettified = prettified.replace(/<blockquote>/g, '<blockquote class="html-blockquote">');
663
+
664
+ // Enhance tables
665
+ prettified = prettified.replace(/<table>/g, '<table class="html-table">');
666
+ prettified = prettified.replace(/<th>/g, '<th class="html-table-header">');
667
+ prettified = prettified.replace(/<td>/g, '<td class="html-table-cell">');
668
+
669
+ // Add info boxes for certain content patterns
670
+ prettified = prettified.replace(
671
+ /<p>(Note|Tip|Info|Warning|Error):\s*(.*?)<\/p>/gi,
672
+ '<div class="html-info-box"><strong>$1:</strong> $2</div>',
673
+ );
674
+
675
+ return prettified;
676
+ };
677
+
678
+ // Minimal Builder-like blocks renderer (text/image/button/columns)
679
+ const BuilderLikeRenderer: React.FC<{ blocks?: any[] }> = ({ blocks }) => {
680
+ if (!blocks || !Array.isArray(blocks) || blocks.length === 0) return null;
681
+
682
+ return (
683
+ <div className="space-y-3">
684
+ {blocks.map((block, idx) => {
685
+ const type = block?.['@type'] || block?.type;
686
+ if (!type) return null;
687
+
688
+ if (/text/i.test(type)) {
689
+ const html = sanitizeHtml(block?.text || block?.data?.text || '');
690
+ return (
691
+ <div
692
+ key={idx}
693
+ className="max-w-none text-gray-800"
694
+ dangerouslySetInnerHTML={{ __html: html }}
695
+ />
696
+ );
697
+ }
698
+
699
+ if (/image/i.test(type)) {
700
+ const src = block?.src || block?.image || block?.data?.src;
701
+ const alt = block?.alt || block?.data?.alt || '';
702
+ if (!src) return null;
703
+ return (
704
+ <div key={idx} className="rounded-lg overflow-hidden border border-gray-200">
705
+ <img className="w-full h-auto" src={src} alt={alt} />
706
+ </div>
707
+ );
708
+ }
709
+
710
+ if (/button/i.test(type)) {
711
+ const text = block?.text || block?.data?.text || 'Button';
712
+ const href = block?.href || block?.link || block?.data?.href || '#';
713
+ return (
714
+ <a
715
+ key={idx}
716
+ href={href}
717
+ target="_blank"
718
+ rel="noopener noreferrer"
719
+ className="inline-flex items-center px-3 py-1.5 rounded-md bg-blue-600 text-white text-sm hover:bg-blue-700"
720
+ >
721
+ {text}
722
+ </a>
723
+ );
724
+ }
725
+
726
+ if (/columns?/i.test(type)) {
727
+ const cols = block?.columns || block?.data?.columns || [];
728
+ return (
729
+ <div key={idx} className="grid grid-cols-1 sm:grid-cols-2 gap-3">
730
+ {cols.map((col: any, colIdx: number) => (
731
+ <div key={colIdx} className="space-y-2">
732
+ <BuilderLikeRenderer blocks={col?.blocks || col?.children} />
733
+ </div>
734
+ ))}
735
+ </div>
736
+ );
737
+ }
738
+
739
+ return (
740
+ <div key={idx} className="message-container">
741
+ <pre className="text-xs text-gray-600 overflow-x-auto">{JSON.stringify(block, null, 2)}</pre>
742
+ </div>
743
+ );
744
+ })}
745
+ </div>
746
+ );
747
+ };
748
+
749
+ // Code block with optional header (language + copy) and footer (copy + download) per Image 2
750
+ const CodeBlockWithActions: React.FC<{
751
+ content: string;
752
+ language?: string;
753
+ showCopyDownload?: boolean;
754
+ }> = ({ content, language, showCopyDownload = true }) => {
755
+ const [copied, setCopied] = React.useState(false);
756
+
757
+ const handleCopy = React.useCallback(() => {
758
+ navigator.clipboard.writeText(content).then(() => {
759
+ setCopied(true);
760
+ setTimeout(() => setCopied(false), 2000);
761
+ });
762
+ }, [content]);
763
+
764
+ const handleDownload = React.useCallback(() => {
765
+ const ext =
766
+ language === 'jsx' || language === 'tsx' ? '.tsx' : language === 'js' || language === 'ts' ? '.ts' : '.txt';
767
+ const blob = new Blob([content], { type: 'text/plain' });
768
+ const url = URL.createObjectURL(blob);
769
+ const a = document.createElement('a');
770
+ a.href = url;
771
+ a.download = `snippet${ext}`;
772
+ a.click();
773
+ URL.revokeObjectURL(url);
774
+ }, [content, language]);
775
+
776
+ const langLabel = (language || 'code').toUpperCase();
777
+
778
+ /**
779
+ * Duplicate / copy: back square offset top-left (only its top-left shows behind),
780
+ * front square on top toward bottom-right — matches typical “two sheets” reference art.
781
+ */
782
+ const IconCopy = ({ className }: { className?: string }) => (
783
+ <svg className={className} viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden>
784
+ <rect
785
+ x="3.25"
786
+ y="3.25"
787
+ width="10.5"
788
+ height="10.5"
789
+ rx="2.25"
790
+ ry="2.25"
791
+ stroke="currentColor"
792
+ strokeWidth="1.5"
793
+ strokeLinecap="round"
794
+ strokeLinejoin="round"
795
+ />
796
+ <rect
797
+ x="8.75"
798
+ y="8.75"
799
+ width="10.5"
800
+ height="10.5"
801
+ rx="2.25"
802
+ ry="2.25"
803
+ stroke="currentColor"
804
+ strokeWidth="1.5"
805
+ strokeLinecap="round"
806
+ strokeLinejoin="round"
807
+ />
808
+ </svg>
809
+ );
810
+
811
+ /** Arrow into tray (download) */
812
+ const IconDownload = ({ className }: { className?: string }) => (
813
+ <svg
814
+ className={className}
815
+ viewBox="0 0 24 24"
816
+ fill="none"
817
+ stroke="currentColor"
818
+ strokeWidth={1.5}
819
+ strokeLinecap="round"
820
+ strokeLinejoin="round"
821
+ aria-hidden
822
+ >
823
+ <path d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3" />
824
+ </svg>
825
+ );
826
+
827
+ const IconCheck = ({ className }: { className?: string }) => (
828
+ <svg
829
+ className={className}
830
+ viewBox="0 0 24 24"
831
+ fill="none"
832
+ stroke="currentColor"
833
+ strokeWidth={1.75}
834
+ strokeLinecap="round"
835
+ strokeLinejoin="round"
836
+ aria-hidden
837
+ >
838
+ <path d="M5 13l4 4L19 7" />
839
+ </svg>
840
+ );
841
+
842
+ const iconMuted = 'text-slate-500 hover:text-slate-600';
843
+
844
+ return (
845
+ <div className="rounded-xl bg-white overflow-hidden my-3 shadow-sm ring-1 ring-slate-200/60">
846
+ {/* Header: label + copy — padding aligned with inner code gutter (image 3) */}
847
+ <div className="flex items-center justify-between px-4 pt-4 pb-3 bg-white">
848
+ <span className="text-[11px] font-semibold uppercase tracking-wide text-slate-500">{langLabel}</span>
849
+ <button
850
+ type="button"
851
+ onClick={handleCopy}
852
+ className={`p-1 rounded-md hover:bg-slate-100/80 transition-colors ${iconMuted}`}
853
+ title="Copy"
854
+ aria-label="Copy to clipboard"
855
+ >
856
+ <IconCopy className="w-[15px] h-[15px] shrink-0" />
857
+ </button>
858
+ </div>
859
+ {/* Code body: white, no inner border (single flat surface inside the card) */}
860
+ <div className="px-4 pb-4">
861
+ <div className="overflow-x-auto bg-white py-4">
862
+ <pre className="text-sm text-slate-900 font-mono leading-relaxed whitespace-pre-wrap break-words m-0 p-0 border-0 bg-transparent">
863
+ <code className="bg-transparent">{content}</code>
864
+ </pre>
865
+ </div>
866
+ </div>
867
+ {showCopyDownload && (
868
+ <div className="flex items-center justify-start gap-0.5 px-4 pb-3 pt-0 mt-2 bg-white">
869
+ <button
870
+ type="button"
871
+ onClick={handleCopy}
872
+ className={`p-1 rounded-md hover:bg-slate-100/80 transition-colors ${iconMuted}`}
873
+ title={copied ? 'Copied' : 'Copy'}
874
+ aria-label={copied ? 'Copied' : 'Copy to clipboard'}
875
+ >
876
+ {copied ? (
877
+ <IconCheck className="w-[15px] h-[15px] text-emerald-600" />
878
+ ) : (
879
+ <IconCopy className="w-[15px] h-[15px] shrink-0" />
880
+ )}
881
+ </button>
882
+ <button
883
+ type="button"
884
+ onClick={handleDownload}
885
+ className={`p-1 rounded-md hover:bg-slate-100/80 transition-colors ${iconMuted}`}
886
+ title="Download"
887
+ aria-label="Download"
888
+ >
889
+ <IconDownload className="w-[15px] h-[15px] shrink-0" />
890
+ </button>
891
+ </div>
892
+ )}
893
+ </div>
894
+ );
895
+ };
896
+
897
+ // Infer language from file extension or content
898
+ const inferCodeLanguage = (section: string, filename?: string): string => {
899
+ if (filename) {
900
+ const ext = filename.split('.').pop()?.toLowerCase();
901
+ const map: Record<string, string> = {
902
+ tsx: 'tsx',
903
+ jsx: 'jsx',
904
+ ts: 'ts',
905
+ js: 'js',
906
+ css: 'css',
907
+ html: 'html',
908
+ json: 'json',
909
+ };
910
+ return map[ext ?? ''] ?? ext ?? 'code';
911
+ }
912
+ if (/\bimport\b.*from\s+['"]react['"]/i.test(section) || /<\w+[\s>]/.test(section)) return 'jsx';
913
+ if (/\bimport\b/.test(section) && /\.(ts|tsx)\b/.test(section)) return 'ts';
914
+ return 'code';
915
+ };
916
+
917
+ // Enhanced code formatter for raw code content
918
+ export const CodeFormatter: React.FC<{
919
+ content: string;
920
+ showCopyDownload?: boolean;
921
+ variant?: 'default' | 'user';
922
+ /** When variant is `user`, use primary-foreground only on plan-mode bubbles (bg-primary). */
923
+ planMode?: boolean;
924
+ }> = ({ content, showCopyDownload = true, variant = 'default', planMode = false }) => {
925
+ if (!content) return null;
926
+
927
+ // Split content by file separators and format each section
928
+ const sections = content.split(/(---\s*\w+\.\w+\s*---)/g);
929
+
930
+ return (
931
+ <div className={variant === 'user' ? '' : 'message-container'}>
932
+ <div className="space-y-4">
933
+ {sections.map((section, index) => {
934
+ if (!section.trim()) return null;
935
+
936
+ // Check if this is a file separator
937
+ const fileMatch = section.match(/---\s*(\w+\.\w+)\s*---/);
938
+ if (fileMatch) {
939
+ return (
940
+ <div key={index} className="code-block-container">
941
+ <div className="code-block-header">📄 {fileMatch[1]}</div>
942
+ </div>
943
+ );
944
+ }
945
+
946
+ // Format the code content
947
+ const lines = section.trim().split('\n');
948
+ const isCode = lines.some(
949
+ (line) =>
950
+ line.includes('@tailwind') ||
951
+ line.includes('export default') ||
952
+ line.includes('import ') ||
953
+ line.includes('{') ||
954
+ line.includes('}') ||
955
+ line.includes('//') ||
956
+ line.includes('/*'),
957
+ );
958
+
959
+ if (isCode) {
960
+ const lang = inferCodeLanguage(section);
961
+ return (
962
+ <CodeBlockWithActions
963
+ key={index}
964
+ content={section.trim()}
965
+ language={lang}
966
+ showCopyDownload={showCopyDownload}
967
+ />
968
+ );
969
+ }
970
+
971
+ // Regular text content
972
+ return (
973
+ <div
974
+ key={index}
975
+ className={`${variant === 'user' ? USER_MESSAGE_TEXT_SIZE_CLASS : 'text-sm'} ${
976
+ variant === 'user' ? 'text-foreground' : 'text-gray-700'
977
+ } leading-relaxed whitespace-pre-wrap break-words`}
978
+ >
979
+ {section.trim()}
980
+ </div>
981
+ );
982
+ })}
983
+ </div>
984
+ </div>
985
+ );
986
+ };
987
+
988
+ // Enhanced markdown renderer using marked (similar to MessageBubble.tsx)
989
+ export const FormattedMessageContent: React.FC<{
990
+ content: string;
991
+ variant?: 'default' | 'user';
992
+ /** When variant is `user`, use primary-foreground only on plan-mode bubbles (bg-primary). */
993
+ planMode?: boolean;
994
+ /**
995
+ * When true, fenced code blocks use the same copy/download UI as elsewhere.
996
+ * Implemented via react-markdown (safe) instead of raw HTML from marked.
997
+ */
998
+ showCopyDownloadOnCodeBlock?: boolean;
999
+ }> = ({ content, variant = 'default', planMode = false, showCopyDownloadOnCodeBlock = false }) => {
1000
+ if (!content) return null;
1001
+
1002
+ // Parse markdown using marked - be more aggressive in detection
1003
+ const { htmlContent, markdownSource } = useMemo(() => {
1004
+ try {
1005
+ const trimmed = content.trim();
1006
+
1007
+ // Comprehensive markdown detection patterns
1008
+ const markdownIndicators = [
1009
+ /^#{1,6}\s+.+$/gm, // Headers with text
1010
+ /^\s*[-*+]\s+.+$/gm, // Unordered lists
1011
+ /^\s*\d+\.\s+.+$/gm, // Numbered lists
1012
+ /\[.+?\]\(.+?\)/g, // Links
1013
+ /!\[.+?\]\(.+?\)/g, // Images
1014
+ /```[\s\S]*?```/g, // Fenced code blocks
1015
+ /^\s*>\s+/gm, // Blockquotes
1016
+ /\*\*[^*]+\*\*/g, // Bold text
1017
+ /\*[^*\n]+\*/g, // Italic text (not just asterisks)
1018
+ /^\s*\|.+\|/gm, // Tables
1019
+ /~~.+~~/g, // Strikethrough
1020
+ ];
1021
+
1022
+ // Check if content has markdown patterns
1023
+ const hasMarkdown = markdownIndicators.some((pattern) => {
1024
+ const matches = trimmed.match(pattern);
1025
+ return matches && matches.length > 0;
1026
+ });
1027
+
1028
+ // Also check for common markdown characters that suggest markdown content
1029
+ const hasMarkdownChars = /[#*`>|\[\]()]/.test(trimmed) && trimmed.length > 10;
1030
+
1031
+ // If we detect markdown, parse it
1032
+ if (hasMarkdown || hasMarkdownChars) {
1033
+ const parsed = marked.parse(trimmed, { async: false }) as string;
1034
+ // Only return if parsing actually produced HTML (not just the same text)
1035
+ if (parsed && parsed.trim() !== trimmed && parsed.includes('<')) {
1036
+ return { htmlContent: parsed, markdownSource: trimmed as string };
1037
+ }
1038
+ }
1039
+
1040
+ return { htmlContent: null as string | null, markdownSource: null as string | null };
1041
+ } catch (error) {
1042
+ console.error('Error parsing markdown:', error);
1043
+ return { htmlContent: null as string | null, markdownSource: null as string | null };
1044
+ }
1045
+ }, [content]);
1046
+
1047
+ const userMarkdownClasses = `${USER_MESSAGE_TEXT_SIZE_CLASS} prose ${USER_MESSAGE_PROSE_SIZE_CLASS} max-w-none leading-relaxed break-words
1048
+ prose-p:my-2 prose-p:text-foreground
1049
+ prose-pre:my-2 prose-pre:bg-transparent prose-pre:border-0 prose-pre:p-0
1050
+ prose-ul:my-2 prose-ol:my-2
1051
+ prose-code:break-words prose-code:bg-muted prose-code:text-foreground prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded prose-code:text-sm prose-code:font-mono
1052
+ prose-headings:font-semibold prose-headings:text-foreground prose-headings:mt-4 prose-headings:mb-2
1053
+ prose-h1:text-2xl prose-h1:border-b prose-h1:border-border prose-h1:pb-2
1054
+ prose-h2:text-xl prose-h2:border-b prose-h2:border-border prose-h2:pb-1
1055
+ prose-h3:text-lg
1056
+ prose-h4:text-base
1057
+ prose-a:text-foreground prose-a:underline hover:prose-a:text-foreground
1058
+ prose-strong:font-semibold prose-strong:text-foreground
1059
+ prose-em:text-muted-foreground
1060
+ prose-blockquote:border-l-2 prose-blockquote:border-border prose-blockquote:pl-4 prose-blockquote:py-2 prose-blockquote:bg-transparent prose-blockquote:my-3 prose-blockquote:italic prose-blockquote:text-muted-foreground
1061
+ prose-table:w-full prose-table:border prose-table:border-border prose-table:rounded-md prose-table:my-4
1062
+ prose-th:px-3 prose-th:py-2 prose-th:text-left prose-th:font-semibold prose-th:bg-muted prose-th:border prose-th:border-border
1063
+ prose-td:px-3 prose-td:py-2 prose-td:border prose-td:border-border prose-td:text-foreground
1064
+ prose-li:my-1 prose-li:text-foreground
1065
+ prose-hr:my-4 prose-hr:border-border
1066
+ !prose-p:text-foreground !prose-li:text-foreground !prose-strong:text-foreground !prose-em:text-muted-foreground !prose-a:text-foreground !prose-code:text-foreground`;
1067
+
1068
+ const userHtmlClasses = `${USER_MESSAGE_TEXT_SIZE_CLASS} prose ${USER_MESSAGE_PROSE_SIZE_CLASS} max-w-none leading-relaxed break-words
1069
+ prose-p:my-2 prose-p:text-foreground
1070
+ prose-pre:my-2 prose-pre:bg-muted prose-pre:border prose-pre:border-border prose-pre:rounded prose-pre:p-3
1071
+ prose-ul:my-2 prose-ol:my-2
1072
+ prose-pre:whitespace-pre-wrap prose-pre:break-words prose-pre:overflow-x-auto
1073
+ prose-code:break-words prose-code:bg-muted prose-code:text-foreground prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded prose-code:text-sm prose-code:font-mono
1074
+ prose-headings:font-semibold prose-headings:text-foreground prose-headings:mt-4 prose-headings:mb-2
1075
+ prose-h1:text-2xl prose-h1:border-b prose-h1:border-border prose-h1:pb-2
1076
+ prose-h2:text-xl prose-h2:border-b prose-h2:border-border prose-h2:pb-1
1077
+ prose-h3:text-lg
1078
+ prose-h4:text-base
1079
+ prose-a:text-foreground prose-a:underline hover:prose-a:text-foreground
1080
+ prose-strong:font-semibold prose-strong:text-foreground
1081
+ prose-em:text-muted-foreground
1082
+ prose-blockquote:border-l-2 prose-blockquote:border-border prose-blockquote:pl-4 prose-blockquote:py-2 prose-blockquote:bg-transparent prose-blockquote:my-3 prose-blockquote:italic prose-blockquote:text-muted-foreground
1083
+ prose-table:w-full prose-table:border prose-table:border-border prose-table:rounded-md prose-table:my-4
1084
+ prose-th:px-3 prose-th:py-2 prose-th:text-left prose-th:font-semibold prose-th:bg-muted prose-th:border prose-th:border-border
1085
+ prose-td:px-3 prose-td:py-2 prose-td:border prose-td:border-border prose-td:text-foreground
1086
+ prose-li:my-1 prose-li:text-foreground
1087
+ prose-hr:my-4 prose-hr:border-border
1088
+ !prose-p:text-foreground !prose-li:text-foreground !prose-strong:text-foreground !prose-em:text-muted-foreground !prose-a:text-foreground !prose-code:text-foreground`;
1089
+
1090
+ const markdownComponents = useMemo(() => {
1091
+ const isUserVariant = variant === 'user';
1092
+ const userTextClass = 'text-foreground';
1093
+ const userMutedTextClass = 'text-muted-foreground';
1094
+ const userLinkClass = 'text-foreground underline underline-offset-2 hover:text-foreground/80';
1095
+
1096
+ return {
1097
+ p: ({ children }: { children?: React.ReactNode }) =>
1098
+ isUserVariant ? (
1099
+ <p className={`break-words mb-4 last:mb-0 leading-relaxed ${userTextClass}`}>{children}</p>
1100
+ ) : (
1101
+ <p>{children}</p>
1102
+ ),
1103
+ h1: ({ children }: { children?: React.ReactNode }) =>
1104
+ isUserVariant ? (
1105
+ <h1 className={`text-2xl font-semibold mt-6 mb-3 first:mt-0 ${userTextClass}`}>{children}</h1>
1106
+ ) : (
1107
+ <h1>{children}</h1>
1108
+ ),
1109
+ h2: ({ children }: { children?: React.ReactNode }) =>
1110
+ isUserVariant ? (
1111
+ <h2 className={`text-xl font-semibold mt-5 mb-3 first:mt-0 ${userTextClass}`}>{children}</h2>
1112
+ ) : (
1113
+ <h2>{children}</h2>
1114
+ ),
1115
+ h3: ({ children }: { children?: React.ReactNode }) =>
1116
+ isUserVariant ? (
1117
+ <h3 className={`text-lg font-semibold mt-4 mb-2 first:mt-0 ${userTextClass}`}>{children}</h3>
1118
+ ) : (
1119
+ <h3>{children}</h3>
1120
+ ),
1121
+ h4: ({ children }: { children?: React.ReactNode }) =>
1122
+ isUserVariant ? (
1123
+ <h4 className={`text-base font-semibold mt-4 mb-2 first:mt-0 ${userTextClass}`}>{children}</h4>
1124
+ ) : (
1125
+ <h4>{children}</h4>
1126
+ ),
1127
+ blockquote: ({ children }: { children?: React.ReactNode }) =>
1128
+ isUserVariant ? (
1129
+ <blockquote
1130
+ className={`border-l-2 border-border pl-4 py-2 bg-transparent my-3 italic ${userMutedTextClass}`}
1131
+ >
1132
+ {children}
1133
+ </blockquote>
1134
+ ) : (
1135
+ <blockquote>{children}</blockquote>
1136
+ ),
1137
+ hr: () => (isUserVariant ? <hr className="my-4 border-border" /> : <hr />),
1138
+ ul: ({ children }: { children?: React.ReactNode }) => (
1139
+ <ul
1140
+ className={
1141
+ isUserVariant
1142
+ ? `list-disc pl-5 mb-4 space-y-1.5 marker:text-muted-foreground [&_ul]:mt-1.5 [&_ol]:mt-1.5 ${userTextClass}`
1143
+ : 'list-disc pl-5'
1144
+ }
1145
+ >
1146
+ {children}
1147
+ </ul>
1148
+ ),
1149
+ ol: ({ children }: { children?: React.ReactNode }) => (
1150
+ <ol
1151
+ className={
1152
+ isUserVariant
1153
+ ? `list-decimal pl-5 mb-4 space-y-1.5 marker:text-muted-foreground [&_ul]:mt-1.5 [&_ol]:mt-1.5 ${userTextClass}`
1154
+ : 'list-decimal pl-5'
1155
+ }
1156
+ >
1157
+ {children}
1158
+ </ol>
1159
+ ),
1160
+ li: ({ children }: { children?: React.ReactNode }) => (
1161
+ <li
1162
+ className={
1163
+ isUserVariant
1164
+ ? `break-words whitespace-pre-wrap leading-relaxed [&>ul]:whitespace-normal [&>ol]:whitespace-normal ${userMutedTextClass}`
1165
+ : 'break-words whitespace-pre-wrap leading-relaxed [&>ul]:whitespace-normal [&>ol]:whitespace-normal'
1166
+ }
1167
+ >
1168
+ {children}
1169
+ </li>
1170
+ ),
1171
+ a: ({ href, children }: { href?: string; children?: React.ReactNode }) =>
1172
+ isUserVariant ? (
1173
+ <a href={href} className={userLinkClass}>
1174
+ {children}
1175
+ </a>
1176
+ ) : (
1177
+ <a href={href}>{children}</a>
1178
+ ),
1179
+ table: ({
1180
+ children,
1181
+ ...props
1182
+ }: React.TableHTMLAttributes<HTMLTableElement> & { children?: React.ReactNode }) =>
1183
+ isUserVariant ? (
1184
+ <div className="overflow-x-auto my-4 w-full rounded-md border border-border">
1185
+ <table className="w-full text-sm" {...props}>
1186
+ {children}
1187
+ </table>
1188
+ </div>
1189
+ ) : (
1190
+ <div className="overflow-x-auto my-4 w-full">
1191
+ <table {...props}>{children}</table>
1192
+ </div>
1193
+ ),
1194
+ thead: ({ children }: { children?: React.ReactNode }) =>
1195
+ isUserVariant ? <thead className="bg-muted text-left">{children}</thead> : <thead>{children}</thead>,
1196
+ th: ({ children }: { children?: React.ReactNode }) =>
1197
+ isUserVariant ? (
1198
+ <th className={`px-3 py-2 text-left font-semibold ${userTextClass}`}>{children}</th>
1199
+ ) : (
1200
+ <th>{children}</th>
1201
+ ),
1202
+ td: ({ children }: { children?: React.ReactNode }) =>
1203
+ isUserVariant ? <td className={`px-3 py-2 ${userMutedTextClass}`}>{children}</td> : <td>{children}</td>,
1204
+ pre: ({ children }: { children?: React.ReactNode }) => <>{children}</>,
1205
+ code: ({ className, children, ...rest }: { className?: string; children?: React.ReactNode }) => {
1206
+ const match = /language-(\w+)/.exec(className || '');
1207
+ const text = String(children).replace(/\n$/, '');
1208
+ if (match) {
1209
+ return (
1210
+ <div className="not-prose max-w-none">
1211
+ <CodeBlockWithActions
1212
+ content={text}
1213
+ language={match[1]}
1214
+ showCopyDownload={showCopyDownloadOnCodeBlock}
1215
+ />
1216
+ </div>
1217
+ );
1218
+ }
1219
+ if (text.includes('\n')) {
1220
+ return (
1221
+ <div className="not-prose max-w-none">
1222
+ <CodeBlockWithActions
1223
+ content={text}
1224
+ language="code"
1225
+ showCopyDownload={showCopyDownloadOnCodeBlock}
1226
+ />
1227
+ </div>
1228
+ );
1229
+ }
1230
+ return (
1231
+ <code
1232
+ className={
1233
+ isUserVariant
1234
+ ? `rounded px-1.5 py-0.5 text-sm font-mono bg-muted text-foreground break-words ${className || ''}`
1235
+ : `llm-inline-code break-words ${className || ''}`
1236
+ }
1237
+ {...rest}
1238
+ >
1239
+ {children}
1240
+ </code>
1241
+ );
1242
+ },
1243
+ };
1244
+ }, [planMode, showCopyDownloadOnCodeBlock, variant]);
1245
+
1246
+ // Fenced code copy/download needs React tree (not marked HTML)
1247
+ if (showCopyDownloadOnCodeBlock && markdownSource) {
1248
+ if (variant === 'user') {
1249
+ return (
1250
+ <div className={userMarkdownClasses}>
1251
+ <ReactMarkdown remarkPlugins={[remarkGfm, remarkBreaks]} components={markdownComponents}>
1252
+ {markdownSource}
1253
+ </ReactMarkdown>
1254
+ </div>
1255
+ );
1256
+ }
1257
+
1258
+ return (
1259
+ <AssistantResponseWrapper>
1260
+ <div className={getAssistantResponseClasses('min-w-0')}>
1261
+ <ReactMarkdown remarkPlugins={[remarkGfm, remarkBreaks]} components={markdownComponents}>
1262
+ {markdownSource}
1263
+ </ReactMarkdown>
1264
+ </div>
1265
+ </AssistantResponseWrapper>
1266
+ );
1267
+ }
1268
+
1269
+ // If markdown was parsed, render as HTML with prose styling
1270
+ if (htmlContent) {
1271
+ if (variant === 'user') {
1272
+ return <div className={userHtmlClasses} dangerouslySetInnerHTML={{ __html: htmlContent }} />;
1273
+ }
1274
+
1275
+ return (
1276
+ <AssistantResponseWrapper>
1277
+ <div
1278
+ className={getAssistantResponseClasses('min-w-0')}
1279
+ dangerouslySetInnerHTML={{ __html: htmlContent }}
1280
+ />
1281
+ </AssistantResponseWrapper>
1282
+ );
1283
+ }
1284
+
1285
+ // For plain text content
1286
+ return variant === 'user' ? (
1287
+ <p
1288
+ className={`${USER_MESSAGE_TEXT_SIZE_CLASS} leading-relaxed whitespace-pre-wrap break-words text-foreground`}
1289
+ >
1290
+ {content}
1291
+ </p>
1292
+ ) : (
1293
+ <AssistantResponseWrapper>
1294
+ <div className={getAssistantResponseClasses()}>
1295
+ <p className="leading-relaxed whitespace-pre-wrap break-words">{content}</p>
1296
+ </div>
1297
+ </AssistantResponseWrapper>
1298
+ );
1299
+ };
1300
+
1301
+ // Detect predominant text direction (RTL/LTR) for international content
1302
+ const detectTextDirection = (text: string): 'rtl' | 'ltr' => {
1303
+ if (!text) return 'ltr';
1304
+ const rtlRanges = /[\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC]/g; // Hebrew, Arabic, etc.
1305
+ const ltrRanges = /[A-Za-z\u00C0-\u024F\u1E00-\u1EFF]/g;
1306
+ const rtlCount = (text.match(rtlRanges) || []).length;
1307
+ const ltrCount = (text.match(ltrRanges) || []).length;
1308
+ return rtlCount > ltrCount ? 'rtl' : 'ltr';
1309
+ };
1310
+
1311
+ // Lightweight language heuristic for lang attribute
1312
+ const detectLanguageTag = (text: string): string => {
1313
+ if (!text) return 'en';
1314
+ if (/\p{Script=Arabic}/u.test(text)) return 'ar';
1315
+ if (/[\u0590-\u05FF]/.test(text)) return 'he';
1316
+ if (/[\u0600-\u06FF]/.test(text)) return 'fa';
1317
+ if (/[\u0900-\u097F]/.test(text)) return 'hi';
1318
+ if (/[\u4E00-\u9FFF]/.test(text)) return 'zh';
1319
+ if (/[\u3040-\u309F\u30A0-\u30FF]/.test(text)) return 'ja';
1320
+ if (/[\uAC00-\uD7AF]/.test(text)) return 'ko';
1321
+ if (/[\u0400-\u04FF]/.test(text)) return 'ru';
1322
+ if (/[\u0E00-\u0E7F]/.test(text)) return 'th';
1323
+ return 'en';
1324
+ };
1325
+
1326
+ // Attempt to parse Builder.io-like JSON blocks embedded as message string
1327
+ const tryExtractBuilderBlocks = (content?: string): any[] | null => {
1328
+ if (!content || content.length < 2) return null;
1329
+ try {
1330
+ const trimmed = content.trim();
1331
+ const jsonMatch = trimmed.match(/([\[{][\s\S]*[\]}])/);
1332
+ const jsonText = jsonMatch ? jsonMatch[1] : trimmed;
1333
+ const parsed = JSON.parse(jsonText);
1334
+ if (Array.isArray(parsed)) {
1335
+ if (parsed.length && (parsed[0]['@type'] || parsed[0].type)) return parsed;
1336
+ } else if (parsed && typeof parsed === 'object') {
1337
+ if (Array.isArray(parsed.blocks)) return parsed.blocks;
1338
+ if (Array.isArray(parsed?.data?.blocks)) return parsed.data.blocks;
1339
+ }
1340
+ return null;
1341
+ } catch {
1342
+ return null;
1343
+ }
1344
+ };
1345
+
1346
+ const ModernMessageGroup: React.FC<MessageGroupProps> = ({
1347
+ author,
1348
+ messages,
1349
+ currentUser,
1350
+ showAuthorName = false,
1351
+ showAvatar = false,
1352
+ showTimestamp = false,
1353
+ onOpen,
1354
+ onMessageClick,
1355
+ isDesktopView = false,
1356
+ isSmallScreen = false,
1357
+ showCopyDownloadOnCodeBlock = false,
1358
+ }) => {
1359
+ // Inject CSS styles for HTML content
1360
+ useInjectStyles();
1361
+
1362
+ // Preserve server / store order for posts (TOOLUSE, THINKING, etc.); no client-side reordering
1363
+ const displayMessages = messages;
1364
+
1365
+ //const isOwnMessage = author?.id === currentUser?.id;
1366
+ //const isOwnMessage = messages.some((message: any) => (message as any)?.propsConfiguration?.contents?.role === AiAgentMessageRole.User);
1367
+ const isOwnMessage =
1368
+ displayMessages.some(
1369
+ (message: any) => (message as any)?.propsConfiguration?.contents?.role === AiAgentMessageRole.User,
1370
+ ) ||
1371
+ (Array.isArray(author?.alias) &&
1372
+ typeof currentUser?.authUserId === 'string' &&
1373
+ author.alias.some((alias: string) => alias?.toLowerCase() === currentUser.authUserId.toLowerCase()));
1374
+
1375
+ const authorName =
1376
+ author?.givenName && author?.familyName
1377
+ ? `${author.givenName} ${author.familyName}`
1378
+ : author?.username || 'Unknown User';
1379
+
1380
+ const firstMessage = displayMessages[0];
1381
+ const formatTime = (timestamp: string) => {
1382
+ const date = new Date(timestamp);
1383
+ return format(date, 'h:mm a');
1384
+ };
1385
+
1386
+ // Determine if this is an AI/system message for special styling
1387
+ const isSystemMessage =
1388
+ author?.username?.toLowerCase().includes('ai') ||
1389
+ author?.username?.toLowerCase().includes('assistant') ||
1390
+ author?.username?.toLowerCase().includes('system');
1391
+ // const isSystemMessage = messages.some(
1392
+ // (message: any) => (message as any)?.propsConfiguration?.contents?.role === AiAgentMessageRole.Assistant,
1393
+ // );
1394
+
1395
+ // For user messages, don't show group header, just individual messages with avatars
1396
+ if (isOwnMessage) {
1397
+ return (
1398
+ <div
1399
+ className={`min-h-fit ${
1400
+ isDesktopView ? 'space-y-1 mb-3' : isSmallScreen ? 'space-y-0.5 mb-2' : 'space-y-0.5 mb-2'
1401
+ }`}
1402
+ >
1403
+ {displayMessages.map((message, index) => (
1404
+ <ModernMessageBubble
1405
+ key={message.id}
1406
+ message={message}
1407
+ isOwnMessage={isOwnMessage}
1408
+ isSystemMessage={isSystemMessage}
1409
+ isFirstInGroup={index === 0}
1410
+ isLastInGroup={index === displayMessages.length - 1}
1411
+ onMessageClick={onMessageClick}
1412
+ formatTime={formatTime}
1413
+ showAuthorName={showAuthorName}
1414
+ showAvatar={showAvatar}
1415
+ showTimestamp={showTimestamp}
1416
+ showCopyDownloadOnCodeBlock={showCopyDownloadOnCodeBlock}
1417
+ />
1418
+ ))}
1419
+ </div>
1420
+ );
1421
+ }
1422
+
1423
+ // For other messages (non-user), show the traditional group layout
1424
+ return (
1425
+ <div
1426
+ className={`group transition-all duration-300 ease-in-out ${
1427
+ isDesktopView ? 'mb-4 px-4 py-3' : isSmallScreen ? 'mb-2 px-2 py-1' : 'mb-3 px-3 py-1'
1428
+ } rounded-lg`}
1429
+ >
1430
+ <div
1431
+ className={`flex items-start ${
1432
+ isDesktopView ? 'space-x-4' : isSmallScreen ? 'space-x-2' : 'space-x-3'
1433
+ }`}
1434
+ >
1435
+ {/* Enhanced Avatar - Only show for non-system messages */}
1436
+ {/* {!isSystemMessage && (
1437
+ <div className="flex-shrink-0 mt-1">
1438
+ <div className="relative rounded-lg overflow-hidden">
1439
+ <img
1440
+ className={`cursor-pointer hover:opacity-80 transition-opacity ${
1441
+ isDesktopView ? 'w-12 h-12' : isSmallScreen ? 'w-8 h-8' : 'w-10 h-10'
1442
+ } rounded-lg object-cover`}
1443
+ src={author?.picture || '/default-avatar.svg'}
1444
+ alt={authorName}
1445
+ onClick={() => onOpen(firstMessage)}
1446
+ onError={(e) => {
1447
+ e.currentTarget.src = '/default-avatar.svg';
1448
+ }}
1449
+ />
1450
+ </div>
1451
+ </div>
1452
+ )} */}
1453
+
1454
+ <div className="flex-1 min-w-0 overflow-hidden">
1455
+ {/* Enhanced author header - Only show for non-system messages */}
1456
+ {/* {!isSystemMessage && (
1457
+ <div className="flex items-center space-x-3 mb-2">
1458
+ <span className="font-semibold truncate text-gray-900">{authorName}</span>
1459
+ </div>
1460
+ )} */}
1461
+
1462
+ {/* Enhanced Messages with rich formatting */}
1463
+ <div className="space-y-1">
1464
+ {displayMessages.map((message, index) => (
1465
+ <ModernMessageBubble
1466
+ key={message.id}
1467
+ message={message}
1468
+ isOwnMessage={isOwnMessage}
1469
+ isSystemMessage={isSystemMessage}
1470
+ isFirstInGroup={index === 0}
1471
+ isLastInGroup={index === displayMessages.length - 1}
1472
+ onMessageClick={onMessageClick}
1473
+ formatTime={formatTime}
1474
+ showTimestamp={showTimestamp}
1475
+ showCopyDownloadOnCodeBlock={showCopyDownloadOnCodeBlock}
1476
+ />
1477
+ ))}
1478
+ </div>
1479
+ </div>
1480
+ </div>
1481
+ </div>
1482
+ );
1483
+ };
1484
+
1485
+ interface ModernMessageBubbleProps {
1486
+ showAuthorName?: boolean;
1487
+ showAvatar?: boolean;
1488
+ showTimestamp?: boolean;
1489
+ message: IPost;
1490
+ isOwnMessage: boolean;
1491
+ isSystemMessage: boolean;
1492
+ isFirstInGroup: boolean;
1493
+ isLastInGroup: boolean;
1494
+ onMessageClick: (msg: IPost) => void;
1495
+ formatTime: (timestamp: string) => string;
1496
+ showCopyDownloadOnCodeBlock?: boolean;
1497
+ }
1498
+
1499
+ const ModernMessageBubble: React.FC<ModernMessageBubbleProps> = ({
1500
+ showAuthorName = false,
1501
+ showAvatar = false,
1502
+ showTimestamp = false,
1503
+ message,
1504
+ isOwnMessage,
1505
+ isSystemMessage,
1506
+ isFirstInGroup,
1507
+ isLastInGroup,
1508
+ onMessageClick,
1509
+ formatTime,
1510
+ showCopyDownloadOnCodeBlock = false,
1511
+ }) => {
1512
+ const handleClick = () => {
1513
+ onMessageClick?.(message);
1514
+ };
1515
+ const [expanded, setExpanded] = useState(false);
1516
+
1517
+ const isAssistantRole = (message as any)?.propsConfiguration?.contents?.role === AiAgentMessageRole.Assistant;
1518
+ const messageMode =
1519
+ (message as any)?.propsConfiguration?.contents?.mode ??
1520
+ (message as any)?.propsConfiguration?.content?.mode ??
1521
+ (message as any)?.props?.mode;
1522
+ const isPlanMode = messageMode === 'plan';
1523
+ const isLongUserMessage =
1524
+ !isAssistantRole && ((message as any)?.message?.length ?? 0) > USER_MESSAGE_COLLAPSE_CHAR_THRESHOLD;
1525
+ const isCollapsed = isLongUserMessage && !expanded;
1526
+ // For user messages, create a right-aligned layout with avatar and name
1527
+ if (isOwnMessage) {
1528
+ const authorName =
1529
+ message.author?.givenName && message.author?.familyName
1530
+ ? `${message.author.givenName} ${message.author.familyName}`
1531
+ : message.author?.username || 'You';
1532
+
1533
+ return (
1534
+ <div className="py-1 px-1 sm:px-2 -mx-1 sm:-mx-2 group">
1535
+ <div className="flex items-start justify-end gap-2">
1536
+ <div className="flex flex-col items-end max-w-[85%] min-w-0">
1537
+ {showAuthorName && (
1538
+ <div className="flex items-end space-x-2 mb-0.5">
1539
+ <span className="text-sm font-semibold text-foreground">{authorName}</span>
1540
+ </div>
1541
+ )}
1542
+
1543
+ {/* User message bubble (Image 2) */}
1544
+ <div
1545
+ className={`${isAssistantRole ? 'text-sm' : USER_MESSAGE_TEXT_SIZE_CLASS} ${
1546
+ isAssistantRole
1547
+ ? 'cursor-pointer rounded-2xl border border-border bg-muted text-foreground px-4 py-2.5'
1548
+ : 'user-message rounded-[22px] rounded-br-[4px] px-4 py-3 bg-muted text-foreground shadow-sm'
1549
+ }`}
1550
+ onClick={isAssistantRole ? handleClick : undefined}
1551
+ dir={detectTextDirection((message as any)?.message || '')}
1552
+ lang={detectLanguageTag((message as any)?.message || '')}
1553
+ >
1554
+ {message.message && (
1555
+ <div
1556
+ className={`max-w-none ${isCollapsed ? 'relative overflow-hidden' : ''}`}
1557
+ style={isCollapsed ? { maxHeight: USER_MESSAGE_COLLAPSED_MAX_HEIGHT } : undefined}
1558
+ >
1559
+ {isCollapsed && (
1560
+ <div className="pointer-events-none absolute inset-x-0 bottom-0 h-16 bg-gradient-to-t from-muted to-transparent" />
1561
+ )}
1562
+ {(() => {
1563
+ const contentType = detectContentType(message.message);
1564
+
1565
+ if (contentType === 'code') {
1566
+ return (
1567
+ <CodeFormatter
1568
+ content={message.message}
1569
+ showCopyDownload={showCopyDownloadOnCodeBlock}
1570
+ variant={isAssistantRole ? 'default' : 'user'}
1571
+ planMode={!isAssistantRole && isPlanMode}
1572
+ />
1573
+ );
1574
+ } else if (contentType === 'html') {
1575
+ if (isAssistantRole) {
1576
+ return (
1577
+ <AssistantResponseWrapper>
1578
+ <div
1579
+ className={getAssistantResponseClasses('min-w-0')}
1580
+ dangerouslySetInnerHTML={{
1581
+ __html: prettifyHtmlContent(
1582
+ sanitizeHtml(message.message),
1583
+ ),
1584
+ }}
1585
+ />
1586
+ </AssistantResponseWrapper>
1587
+ );
1588
+ }
1589
+
1590
+ return (
1591
+ <div
1592
+ className="text-foreground html-content"
1593
+ dangerouslySetInnerHTML={{
1594
+ __html: prettifyHtmlContent(sanitizeHtml(message.message)),
1595
+ }}
1596
+ />
1597
+ );
1598
+ } else {
1599
+ return (
1600
+ <FormattedMessageContent
1601
+ content={message.message}
1602
+ variant={isAssistantRole ? 'default' : 'user'}
1603
+ planMode={!isAssistantRole && isPlanMode}
1604
+ showCopyDownloadOnCodeBlock={showCopyDownloadOnCodeBlock}
1605
+ />
1606
+ );
1607
+ }
1608
+ })()}
1609
+ </div>
1610
+ )}
1611
+
1612
+ {isLongUserMessage && (
1613
+ <button
1614
+ type="button"
1615
+ onClick={(e) => {
1616
+ e.stopPropagation();
1617
+ setExpanded((v) => !v);
1618
+ }}
1619
+ className="mt-1 flex items-center gap-1 text-sm font-medium text-muted-foreground hover:text-foreground"
1620
+ >
1621
+ {expanded ? 'Show less' : 'Show more'}
1622
+ <svg
1623
+ viewBox="0 0 24 24"
1624
+ fill="none"
1625
+ stroke="currentColor"
1626
+ strokeWidth={2}
1627
+ strokeLinecap="round"
1628
+ strokeLinejoin="round"
1629
+ className={`h-3.5 w-3.5 transition-transform ${expanded ? 'rotate-180' : ''}`}
1630
+ aria-hidden
1631
+ >
1632
+ <path d="M6 9l6 6 6-6" />
1633
+ </svg>
1634
+ </button>
1635
+ )}
1636
+
1637
+ {tryExtractBuilderBlocks((message as any)?.message)?.length ? (
1638
+ <div className="mt-2">
1639
+ <BuilderLikeRenderer blocks={tryExtractBuilderBlocks((message as any)?.message)} />
1640
+ </div>
1641
+ ) : null}
1642
+
1643
+ {(message as any)?.props?.blocks?.length ? (
1644
+ <div className="mt-2">
1645
+ <BuilderLikeRenderer blocks={(message as any).props.blocks} />
1646
+ </div>
1647
+ ) : null}
1648
+
1649
+ {message.files?.totalCount > 0 && (
1650
+ <div className="mt-2">
1651
+ <FilesList uploaded files={message.files.data} />
1652
+ </div>
1653
+ )}
1654
+ {showTimestamp ? (
1655
+ <div className="text-[10px] mt-1 text-right text-muted-foreground">
1656
+ {formatTime(message.createdAt)}
1657
+ </div>
1658
+ ) : null}
1659
+ </div>
1660
+ </div>
1661
+
1662
+ {/* User avatar on the right */}
1663
+ {showAvatar && (
1664
+ <div className="flex-shrink-0 mt-0.5">
1665
+ <img
1666
+ className={`w-8 h-8 sm:w-10 sm:h-10 rounded-lg ${
1667
+ isAssistantRole ? '' : 'cursor-pointer hover:opacity-80'
1668
+ } transition-opacity object-cover`}
1669
+ src={message.author?.picture || '/default-avatar.svg'}
1670
+ alt={authorName}
1671
+ //onClick={isAssistantRole ? undefined : handleClick}
1672
+ onClick={isAssistantRole ? handleClick : undefined}
1673
+ onError={(e) => {
1674
+ e.currentTarget.src = '/default-avatar.svg';
1675
+ }}
1676
+ />
1677
+ </div>
1678
+ )}
1679
+ </div>
1680
+ </div>
1681
+ );
1682
+ }
1683
+
1684
+ // For other messages (left-aligned) — use Slot for streaming types (THINKING, TOOLUSE, etc.) like Kimi
1685
+ const attachment =
1686
+ (message as any)?.props?.attachment ?? (message as any)?.propsConfiguration?.contents?.attachment;
1687
+ const slotName = getMessageSlotName((message as any)?.type);
1688
+ // Don't show THINKING slot when attachment has no meaningful content or when dismissed
1689
+ const isThinkingSlot = slotName === MessengerSlotFillNameEnum.THINKING_NAME;
1690
+ const shouldShowThinkingSlot =
1691
+ !!attachment &&
1692
+ attachment.dismissed !== true &&
1693
+ (attachment.isThinking === true || (attachment.thought != null && String(attachment.thought).trim() !== ''));
1694
+ const shouldShowSlot = isThinkingSlot ? shouldShowThinkingSlot : !!attachment;
1695
+ const hasStreamingSlot = !!slotName && shouldShowSlot;
1696
+ return (
1697
+ <div
1698
+ className={`group/message w-full min-w-0 px-0 py-2 ${
1699
+ isSystemMessage || isAssistantRole ? 'cursor-pointer' : ''
1700
+ }`}
1701
+ onClick={isSystemMessage || isAssistantRole ? handleClick : undefined}
1702
+ >
1703
+ <div className="flex items-start justify-between gap-3">
1704
+ <div className="flex-1 min-w-0">
1705
+ {/* Slot fill for streaming message types (THINKING, TOOLUSE, CODEBLOCK, SERVICE, AIASSISTANT) */}
1706
+ {slotName && shouldShowSlot && (
1707
+ <Slot
1708
+ name={slotName}
1709
+ fillProps={{
1710
+ active: true,
1711
+ message,
1712
+ index: 0,
1713
+ onMessageClick,
1714
+ }}
1715
+ />
1716
+ )}
1717
+ {/* Default content when no slot or attachment (slot returns null when active: false) */}
1718
+ {!hasStreamingSlot && message.message && (
1719
+ <div
1720
+ className="min-w-0 relative max-w-full w-full text-foreground"
1721
+ dir={detectTextDirection((message as any)?.message || '')}
1722
+ lang={detectLanguageTag((message as any)?.message || '')}
1723
+ >
1724
+ {(() => {
1725
+ const contentType = detectContentType(message.message);
1726
+
1727
+ // Markdown and text both go through FormattedMessageContent
1728
+ // which will intelligently detect and render markdown
1729
+ if (contentType === 'code') {
1730
+ return (
1731
+ <CodeFormatter
1732
+ content={message.message}
1733
+ showCopyDownload={showCopyDownloadOnCodeBlock}
1734
+ />
1735
+ );
1736
+ } else if (contentType === 'html') {
1737
+ return (
1738
+ <AssistantResponseWrapper>
1739
+ <div
1740
+ className={getAssistantResponseClasses(
1741
+ 'min-w-0 relative max-w-full w-full',
1742
+ )}
1743
+ dangerouslySetInnerHTML={{
1744
+ __html: prettifyHtmlContent(sanitizeHtml(message.message)),
1745
+ }}
1746
+ />
1747
+ </AssistantResponseWrapper>
1748
+ );
1749
+ } else {
1750
+ // Handle both 'markdown' and 'text' - FormattedMessageContent
1751
+ // will detect markdown patterns and render accordingly
1752
+ return (
1753
+ <FormattedMessageContent
1754
+ content={message.message}
1755
+ showCopyDownloadOnCodeBlock={showCopyDownloadOnCodeBlock}
1756
+ />
1757
+ );
1758
+ }
1759
+ })()}
1760
+ </div>
1761
+ )}
1762
+
1763
+ {!hasStreamingSlot && tryExtractBuilderBlocks((message as any)?.message)?.length ? (
1764
+ <div className="mt-3 p-3 bg-gray-50 rounded-lg border border-gray-200">
1765
+ <BuilderLikeRenderer blocks={tryExtractBuilderBlocks((message as any)?.message)} />
1766
+ </div>
1767
+ ) : null}
1768
+
1769
+ {!hasStreamingSlot && (message as any)?.props?.blocks?.length ? (
1770
+ <div className="mt-3 p-3 bg-gray-50 rounded-lg border border-gray-200">
1771
+ <BuilderLikeRenderer blocks={(message as any).props.blocks} />
1772
+ </div>
1773
+ ) : null}
1774
+
1775
+ {!hasStreamingSlot && message.files?.totalCount > 0 ? (
1776
+ <div className="mt-3 p-3 bg-gray-50 rounded-lg border border-gray-200">
1777
+ <FilesList uploaded files={message.files.data} />
1778
+ </div>
1779
+ ) : null}
1780
+ </div>
1781
+
1782
+ {/* Action buttons on hover - Only show for non-system messages */}
1783
+ {/* {!isSystemMessage && (
1784
+ <div className="flex-shrink-0 mt-1">
1785
+ <div className="opacity-0 group-hover/message:opacity-100 transition-opacity duration-200 flex space-x-1">
1786
+ <button className="p-1 hover:bg-gray-200 rounded transition-colors">
1787
+ <svg
1788
+ className="w-3 h-3 text-gray-400"
1789
+ fill="none"
1790
+ stroke="currentColor"
1791
+ viewBox="0 0 24 24"
1792
+ >
1793
+ <path
1794
+ strokeLinecap="round"
1795
+ strokeLinejoin="round"
1796
+ strokeWidth={2}
1797
+ d="M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.367 2.684 3 3 0 00-5.367-2.684z"
1798
+ />
1799
+ </svg>
1800
+ </button>
1801
+ <button className="p-1 hover:bg-gray-200 rounded transition-colors">
1802
+ <svg
1803
+ className="w-3 h-3 text-gray-400"
1804
+ fill="none"
1805
+ stroke="currentColor"
1806
+ viewBox="0 0 24 24"
1807
+ >
1808
+ <path
1809
+ strokeLinecap="round"
1810
+ strokeLinejoin="round"
1811
+ strokeWidth={2}
1812
+ d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"
1813
+ />
1814
+ </svg>
1815
+ </button>
1816
+ </div>
1817
+ </div>
1818
+ )} */}
1819
+ </div>
1820
+ {showTimestamp ? (
1821
+ <div className="text-[10px] text-gray-500 mt-1 text-right">{formatTime(message.createdAt)}</div>
1822
+ ) : null}
1823
+ </div>
1824
+ );
1825
+ };
1826
+
1827
+ export const ModernMessageGroupComponent: React.FC<ModernMessageGroupProps> = ({
1828
+ messages,
1829
+ currentUser,
1830
+ showAuthorName = false,
1831
+ showAvatar = false,
1832
+ showTimestamp = false,
1833
+ onOpen,
1834
+ onMessageClick,
1835
+ isDesktopView = false,
1836
+ isSmallScreen = false,
1837
+ sandboxErrors = [],
1838
+ currentFiles = {},
1839
+ onFixError,
1840
+ showCopyDownloadOnCodeBlock = false,
1841
+ }) => {
1842
+ // Inject CSS styles for HTML content
1843
+ useInjectStyles();
1844
+
1845
+ // Filter out non-message items (like date strings)
1846
+ const actualMessages = messages.filter((msg) => typeof msg !== 'string') as IPost[];
1847
+
1848
+ // Group messages by user and time
1849
+ const messageGroups = groupMessagesByUserAndTime(actualMessages);
1850
+
1851
+ return (
1852
+ <div className={`min-h-fit ${isDesktopView ? 'space-y-6' : isSmallScreen ? 'space-y-4' : 'space-y-5'}`}>
1853
+ {messageGroups.map((group, groupIndex) => {
1854
+ const author = group[0]?.author;
1855
+ return (
1856
+ <ModernMessageGroup
1857
+ key={`group-${groupIndex}-${group[0]?.id}`}
1858
+ author={author}
1859
+ messages={group}
1860
+ currentUser={currentUser}
1861
+ onOpen={onOpen}
1862
+ onMessageClick={onMessageClick}
1863
+ isDesktopView={isDesktopView}
1864
+ isSmallScreen={isSmallScreen}
1865
+ showAuthorName={showAuthorName}
1866
+ showAvatar={showAvatar}
1867
+ showTimestamp={showTimestamp}
1868
+ showCopyDownloadOnCodeBlock={showCopyDownloadOnCodeBlock}
1869
+ />
1870
+ );
1871
+ })}
1872
+
1873
+ {sandboxErrors?.map((error) => (
1874
+ <div key={error.id} className="px-2">
1875
+ <ErrorFixCard
1876
+ error={error}
1877
+ onFixError={onFixError || (() => Promise.resolve())}
1878
+ currentFiles={currentFiles}
1879
+ isFixing={false}
1880
+ />
1881
+ </div>
1882
+ ))}
1883
+ </div>
1884
+ );
1885
+ };