@smart-cloud/ai-kit-ui 1.5.14 → 1.5.16

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 (55) hide show
  1. package/dist/LocaleDirectionProvider.d.ts +5 -0
  2. package/dist/ai-feature/AiFeature.d.ts +1 -0
  3. package/dist/index.cjs +9 -9
  4. package/dist/index.js +9 -9
  5. package/dist/locale.d.ts +13 -0
  6. package/package.json +35 -19
  7. package/eslint.config.js +0 -18
  8. package/src/ShadowBoundary.tsx +0 -229
  9. package/src/ai-chatbot/AiChatbot.tsx +0 -2325
  10. package/src/ai-chatbot/attachmentStorage.ts +0 -238
  11. package/src/ai-chatbot/index.tsx +0 -1
  12. package/src/ai-feature/AiFeature.tsx +0 -2334
  13. package/src/ai-feature/AiFeatureBorder.tsx +0 -22
  14. package/src/ai-feature/ProofreadDiff.tsx +0 -118
  15. package/src/ai-feature/index.tsx +0 -2
  16. package/src/ai-feature/utils.tsx +0 -20
  17. package/src/doc-search/DocSearch.tsx +0 -1313
  18. package/src/doc-search/index.tsx +0 -1
  19. package/src/doc-search/initialFilters.ts +0 -10
  20. package/src/errorHandling.ts +0 -305
  21. package/src/i18n/ar.ts +0 -254
  22. package/src/i18n/de.ts +0 -257
  23. package/src/i18n/en.ts +0 -269
  24. package/src/i18n/es.ts +0 -257
  25. package/src/i18n/fr.ts +0 -258
  26. package/src/i18n/he.ts +0 -250
  27. package/src/i18n/hi.ts +0 -256
  28. package/src/i18n/hu.ts +0 -269
  29. package/src/i18n/id.ts +0 -256
  30. package/src/i18n/index.ts +0 -47
  31. package/src/i18n/it.ts +0 -259
  32. package/src/i18n/ja.ts +0 -256
  33. package/src/i18n/ko.ts +0 -254
  34. package/src/i18n/nb.ts +0 -254
  35. package/src/i18n/nl.ts +0 -255
  36. package/src/i18n/pl.ts +0 -258
  37. package/src/i18n/pt.ts +0 -254
  38. package/src/i18n/ru.ts +0 -254
  39. package/src/i18n/sv.ts +0 -253
  40. package/src/i18n/th.ts +0 -252
  41. package/src/i18n/tr.ts +0 -256
  42. package/src/i18n/ua.ts +0 -257
  43. package/src/i18n/zh.ts +0 -247
  44. package/src/index.tsx +0 -7
  45. package/src/poweredBy.tsx +0 -39
  46. package/src/styles/ai-kit-ui.css +0 -1006
  47. package/src/useAiRun.ts +0 -182
  48. package/src/withAiKitShell.tsx +0 -363
  49. package/tests/ai-disclosures.test.ts +0 -126
  50. package/tests/doc-search-initial-filters.test.ts +0 -20
  51. package/tests/error-handling.test.ts +0 -140
  52. package/tsconfig.json +0 -32
  53. package/tsconfig.node.json +0 -13
  54. package/tsconfig.types.json +0 -13
  55. package/tsup.config.ts +0 -22
@@ -1,2325 +0,0 @@
1
- import {
2
- ActionIcon,
3
- Anchor,
4
- Box,
5
- Button,
6
- Group,
7
- Input,
8
- List,
9
- Modal,
10
- Stack,
11
- Text,
12
- Textarea,
13
- } from "@mantine/core";
14
- import {
15
- IconMaximize,
16
- IconMessage,
17
- IconMicrophone,
18
- IconMinimize,
19
- IconPaperclip,
20
- IconPencil,
21
- IconPlayerStop,
22
- IconSend,
23
- IconTrash,
24
- IconX,
25
- } from "@tabler/icons-react";
26
-
27
- import {
28
- DEFAULT_CHATBOT_AI_DISCLOSURE,
29
- formatAiDisclosure,
30
- getStoreSelect,
31
- sendChatMessage,
32
- sendFeedbackMessage,
33
- type AiChatbotLabels,
34
- type AiChatbotProps,
35
- type AiKitStatusEvent,
36
- type HistoryStorageMode,
37
- } from "@smart-cloud/ai-kit-core";
38
- import { useSelect } from "@wordpress/data";
39
- import { I18n } from "aws-amplify/utils";
40
- import React, {
41
- FC,
42
- useCallback,
43
- useEffect,
44
- useMemo,
45
- useRef,
46
- useState,
47
- } from "react";
48
- import ReactMarkdown from "react-markdown";
49
- import remarkGfm from "remark-gfm";
50
-
51
- import { translations } from "../i18n";
52
- import { useAiRun } from "../useAiRun";
53
- import { AiKitShellInjectedProps, withAiKitShell } from "../withAiKitShell";
54
- import {
55
- cleanupDanglingAttachments,
56
- clearAllAttachments,
57
- loadAttachmentBlob,
58
- persistAttachmentBlob,
59
- } from "./attachmentStorage";
60
-
61
- I18n.putVocabularies(translations);
62
-
63
- const TWENTY_FOUR_HOURS_MS = 24 * 60 * 60 * 1000;
64
-
65
- const USE_AUDIO = false; // Set to true to enable audio recording feature (requires backend support for audio input)
66
-
67
- // New: history storage support
68
- const DEFAULT_PRESERVATION_TIME_DAYS = 1;
69
- const DEFAULT_HISTORY_STORAGE: HistoryStorageMode = "localstorage";
70
- const HISTORY_STORAGE_KEY = `ai-kit-chatbot-history-v1:${
71
- typeof window !== "undefined" ? window.location.hostname : "unknown"
72
- }`;
73
-
74
- export const DEFAULT_CHATBOT_LABELS: Required<AiChatbotLabels> = {
75
- modalTitle: "AI Assistant",
76
-
77
- aiDisclosureLabel: DEFAULT_CHATBOT_AI_DISCLOSURE,
78
-
79
- userLabel: "User",
80
- assistantLabel: "Assistant",
81
- assistantThinkingLabel: "Assistant is thinking...",
82
-
83
- askMeLabel: "Ask me",
84
-
85
- sendLabel: "Send",
86
- cancelLabel: "Cancel",
87
-
88
- resetLabel: "Reset",
89
- confirmLabel: "Confirm",
90
- clickAgainToConfirmLabel: "Click again to confirm",
91
-
92
- notSentLabel: "Not sent",
93
- editLabel: "Edit",
94
-
95
- readyLabel: "Ready.",
96
- readyEmptyLabel: "I'm ready to assist you.",
97
-
98
- addLabel: "Add",
99
- addImageLabel: "Add image",
100
- removeImageLabel: "Remove image",
101
-
102
- closeChatLabel: "Close chat",
103
- maximizeLabel: "Maximize",
104
- restoreSizeLabel: "Restore size",
105
-
106
- referencesLabel: "References",
107
- referenceLabel: "Reference",
108
-
109
- acceptResponseLabel: "Accept response",
110
- rejectResponseLabel: "Reject response",
111
-
112
- placeholder: "Ask anything…",
113
-
114
- emptyResponseLabel: "Empty response",
115
- unexpectedErrorLabel: "Unexpected error",
116
- };
117
-
118
- type CitationLike = {
119
- url?: string;
120
- sourceUrl?: string;
121
- title?: string;
122
- snippet?: string;
123
- };
124
-
125
- type ChatResponse = {
126
- result: string;
127
- sessionId?: string;
128
- citations?: CitationLike[];
129
- metadata?: {
130
- citationCount?: number;
131
- modelId?: string;
132
- requestId?: string;
133
- messageId?: string;
134
- outputTokens?: number;
135
- maxTokens?: number;
136
- stopReason?: string;
137
- };
138
- };
139
-
140
- type ChatMessageAttachment = {
141
- id: string;
142
- name: string;
143
- type: string;
144
- size: number;
145
- blobId?: string;
146
- objectUrl?: string | null;
147
- blob?: Blob;
148
- duration?: number; // For audio/video attachments
149
- mediaType?: "image" | "audio"; // Distinguish media types
150
- };
151
-
152
- type ChatMessage = {
153
- id: string;
154
- role: "user" | "assistant";
155
- content: string;
156
- citations?: CitationLike[];
157
- createdAt: number;
158
- feedback?: "accepted" | "rejected";
159
- clientStatus?: "pending" | "canceled";
160
- attachments?: ChatMessageAttachment[];
161
- };
162
-
163
- type ComposerImage = {
164
- id: string;
165
- file: File;
166
- objectUrl: string;
167
- };
168
-
169
- type ComposerAudio = {
170
- id: string;
171
- blob: Blob;
172
- objectUrl: string;
173
- duration: number;
174
- };
175
-
176
- type PersistedAttachment = Omit<ChatMessageAttachment, "objectUrl" | "blob">;
177
-
178
- type PersistedChatMessage = Omit<ChatMessage, "attachments"> & {
179
- attachments?: PersistedAttachment[];
180
- };
181
-
182
- type ActiveOp = "chat" | "feedback" | null;
183
-
184
- function createMessageId(prefix: string) {
185
- return `${prefix}-${Math.random().toString(36).slice(2)}-${Date.now().toString(
186
- 36,
187
- )}`;
188
- }
189
-
190
- // Image input is an explicit opt-in because not every configured frontend
191
- // model is multimodal. A positive maxImages value is the capability gate.
192
- const DEFAULT_MAX_IMAGES = 0;
193
- const DEFAULT_MAX_BYTES = 5 * 1024 * 1024;
194
-
195
- const isAbortLike = (e: Error & { code?: string }) => {
196
- const name = (e?.name || "").toString();
197
- const code = (e?.code || "").toString();
198
- const msg = (e?.message || "").toString();
199
- return (
200
- name === "AbortError" ||
201
- code === "ABORT_ERR" ||
202
- /abort|aborted|cancel/i.test(msg)
203
- );
204
- };
205
-
206
- const formatStatusEvent = (
207
- event: AiKitStatusEvent | null,
208
- labels: AiChatbotLabels,
209
- ): string | null => {
210
- if (!event) return null;
211
-
212
- const step = event.step;
213
- const msg = I18n.get((event.message ?? "").trim());
214
- const p = typeof event.progress === "number" ? event.progress : null;
215
- const pct = p == null ? null : Math.round(p * 100);
216
-
217
- switch (step) {
218
- case "decide":
219
- return msg || I18n.get("Checking capabilities...");
220
- case "on-device:init":
221
- return msg || I18n.get("Initializing on-device AI...");
222
- case "on-device:download":
223
- return pct == null
224
- ? msg || I18n.get("Downloading model...")
225
- : msg || `${I18n.get("Downloading model...")} ${pct}%`;
226
- case "on-device:ready":
227
- return msg || I18n.get("On-device model ready...");
228
- case "on-device:run":
229
- return msg || I18n.get("Running on-device...");
230
- case "backend:request":
231
- case "backend:waiting":
232
- case "backend:response":
233
- return I18n.get(
234
- labels.assistantThinkingLabel ??
235
- DEFAULT_CHATBOT_LABELS.assistantThinkingLabel,
236
- );
237
- case "done":
238
- return msg || I18n.get("Done.");
239
- case "error":
240
- return msg || I18n.get("An error occurred.");
241
- default:
242
- return msg || null;
243
- }
244
- };
245
-
246
- // New: small helpers for storage
247
- function getHistoryStorage(mode: HistoryStorageMode): Storage | null {
248
- if (typeof window === "undefined") return null;
249
- try {
250
- if (mode === "localstorage") return window.localStorage;
251
- if (mode === "sessionstorage") return window.sessionStorage;
252
- return null;
253
- } catch {
254
- return null;
255
- }
256
- }
257
-
258
- const createObjectUrl = (blob: Blob): string | null => {
259
- if (typeof window === "undefined") return null;
260
- if (typeof URL === "undefined" || typeof URL.createObjectURL !== "function")
261
- return null;
262
- try {
263
- return URL.createObjectURL(blob);
264
- } catch {
265
- return null;
266
- }
267
- };
268
-
269
- const revokeObjectUrlSafe = (url?: string | null) => {
270
- if (!url) return;
271
- if (typeof window === "undefined") return;
272
- if (typeof URL === "undefined" || typeof URL.revokeObjectURL !== "function")
273
- return;
274
- try {
275
- URL.revokeObjectURL(url);
276
- } catch {
277
- // ignore
278
- }
279
- };
280
-
281
- const disposeMessageAttachments = (attachments?: ChatMessageAttachment[]) => {
282
- if (!attachments || attachments.length === 0) return;
283
- attachments.forEach((att) => revokeObjectUrlSafe(att.objectUrl));
284
- };
285
-
286
- const disposeMessagesAttachments = (messages: ChatMessage[]) => {
287
- messages.forEach((msg) => disposeMessageAttachments(msg.attachments));
288
- };
289
-
290
- type PersistedChat = {
291
- version: 1;
292
- lastUserSentAt: number | null;
293
- session?: { id: string; storedAt: number } | null;
294
- messages: PersistedChatMessage[];
295
- };
296
-
297
- const AiChatbotBase: FC<AiChatbotProps & AiKitShellInjectedProps> = (props) => {
298
- const {
299
- rootElement,
300
- store,
301
-
302
- // AiWorkerProps (formatting/behavior)
303
- previewMode,
304
- title,
305
- openButtonTitle,
306
- openButtonIcon,
307
- showOpenButtonTitle = true,
308
- showOpenButtonIcon = true,
309
- colorMode,
310
- language,
311
- onClose,
312
-
313
- // AiChatbotProps
314
- context,
315
- placeholder,
316
- maxImages,
317
- maxImageBytes,
318
- maxTokens,
319
-
320
- // New
321
- historyStorage = DEFAULT_HISTORY_STORAGE,
322
- emptyHistoryAfterDays = DEFAULT_PRESERVATION_TIME_DAYS,
323
- labels: labelsOverride,
324
- openButtonIconLayout = "top",
325
- openButtonPosition = "bottom-right",
326
- } = props;
327
-
328
- const labels = useMemo(
329
- () => ({ ...DEFAULT_CHATBOT_LABELS, ...(labelsOverride || {}) }),
330
- [labelsOverride],
331
- );
332
-
333
- // NOTE: showOpenButton is intentionally ignored for AiChatbot (always true).
334
- // NOTE: variation is intentionally ignored for AiChatbot (always "modal").
335
-
336
- const ai = useAiRun();
337
-
338
- const [question, setQuestion] = useState("");
339
- const [composerImages, setComposerImages] = useState<ComposerImage[]>([]);
340
- const [composerAudio, setComposerAudio] = useState<ComposerAudio | null>(
341
- null,
342
- );
343
- const [recording, setRecording] = useState<boolean>(false);
344
- const [audioLevel, setAudioLevel] = useState<number>(0);
345
- const mediaRecorderRef = useRef<MediaRecorder | null>(null);
346
- const audioChunksRef = useRef<Blob[]>([]);
347
- const audioContextRef = useRef<AudioContext | null>(null);
348
- const analyserRef = useRef<AnalyserNode | null>(null);
349
- const animationFrameRef = useRef<number | null>(null);
350
- const [messages, setMessages] = useState<ChatMessage[]>([]);
351
- const [statusLineError, setStatusLineError] = useState<string | null>(null);
352
- const [resetDialogOpen, setResetDialogOpen] = useState(false);
353
- const [isMaximized, setIsMaximized] = useState(false);
354
- const [maxEnter, setMaxEnter] = useState(false);
355
- const [opened, setOpened] = useState(false);
356
- const [stickToBottom, setStickToBottom] = useState(true);
357
- const [previewAttachment, setPreviewAttachment] = useState<{
358
- url: string;
359
- title?: string;
360
- } | null>(null);
361
- const [historyReady, setHistoryReady] = useState(false);
362
-
363
- const [wheelHostEl, setWheelHostEl] = useState<HTMLDivElement | null>(null);
364
- const [scrollerEl, setScrollerEl] = useState<HTMLDivElement | null>(null);
365
- const [bodyScrollable, setBodyScrollable] = useState(false);
366
-
367
- const [activeOp, setActiveOp] = useState<ActiveOp>(null);
368
- const activeOpRef = useRef<ActiveOp>(activeOp);
369
- useEffect(() => {
370
- activeOpRef.current = activeOp;
371
- }, [activeOp]);
372
-
373
- const maxEnterRafRef = useRef<number | null>(null);
374
- const cancelRequestedRef = useRef(false);
375
-
376
- const [hoveredMessageId, setHoveredMessageId] = useState<string | null>(null);
377
-
378
- const fileInputRef = useRef<HTMLInputElement>(null);
379
- const questionInputRef = useRef<HTMLTextAreaElement>(null);
380
- const sessionRef = useRef<{ id: string; storedAt: number } | null>(null);
381
- const chatContainerRef = useRef<HTMLDivElement>(null);
382
-
383
- const disposeComposerImageList = useCallback((list: ComposerImage[]) => {
384
- list.forEach((img) => revokeObjectUrlSafe(img.objectUrl));
385
- }, []);
386
-
387
- const clearComposerImages = useCallback(() => {
388
- disposeComposerImageList(composerImagesRef.current);
389
- setComposerImages([]);
390
- if (fileInputRef.current) fileInputRef.current.value = "";
391
- }, [disposeComposerImageList]);
392
-
393
- const clearComposerAudio = useCallback(() => {
394
- if (composerAudioRef.current) {
395
- revokeObjectUrlSafe(composerAudioRef.current.objectUrl);
396
- }
397
- setComposerAudio(null);
398
- audioChunksRef.current = [];
399
- setAudioLevel(0);
400
- }, []);
401
-
402
- const startRecording = useCallback(async () => {
403
- try {
404
- // Clear question input when starting audio recording
405
- setQuestion("");
406
- // Clear any existing audio
407
- clearComposerAudio();
408
-
409
- const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
410
- const mediaRecorder = new MediaRecorder(stream, {
411
- mimeType: "audio/webm",
412
- });
413
-
414
- // Setup audio analysis for visual feedback
415
- const audioContext = new AudioContext();
416
- const source = audioContext.createMediaStreamSource(stream);
417
- const analyser = audioContext.createAnalyser();
418
- analyser.fftSize = 2048;
419
- analyser.smoothingTimeConstant = 0.8;
420
- source.connect(analyser);
421
-
422
- audioContextRef.current = audioContext;
423
- analyserRef.current = analyser;
424
-
425
- // Monitor audio level
426
- const dataArray = new Uint8Array(analyser.fftSize);
427
- const updateLevel = () => {
428
- if (!analyserRef.current) return;
429
- analyserRef.current.getByteTimeDomainData(dataArray);
430
-
431
- let sum = 0;
432
- for (let i = 0; i < dataArray.length; i++) {
433
- const normalized = (dataArray[i]! - 128) / 128;
434
- sum += normalized * normalized;
435
- }
436
- const rms = Math.sqrt(sum / dataArray.length);
437
- const level = Math.min(100, rms * 200);
438
- setAudioLevel(level);
439
-
440
- animationFrameRef.current = requestAnimationFrame(updateLevel);
441
- };
442
- updateLevel();
443
-
444
- audioChunksRef.current = [];
445
- const recordStartTime = Date.now();
446
-
447
- mediaRecorder.ondataavailable = (event) => {
448
- if (event.data.size > 0) {
449
- audioChunksRef.current.push(event.data);
450
- }
451
- };
452
-
453
- mediaRecorder.onstop = () => {
454
- const audioBlob = new Blob(audioChunksRef.current, {
455
- type: "audio/webm",
456
- });
457
- const duration = (Date.now() - recordStartTime) / 1000; // duration in seconds
458
- const objectUrl = createObjectUrl(audioBlob);
459
-
460
- if (objectUrl) {
461
- setComposerAudio({
462
- id: createMessageId("composer-audio"),
463
- blob: audioBlob,
464
- objectUrl,
465
- duration,
466
- });
467
- }
468
-
469
- stream.getTracks().forEach((track) => track.stop());
470
-
471
- // Cleanup audio analysis
472
- if (animationFrameRef.current) {
473
- cancelAnimationFrame(animationFrameRef.current);
474
- animationFrameRef.current = null;
475
- }
476
- if (audioContextRef.current) {
477
- audioContextRef.current.close();
478
- audioContextRef.current = null;
479
- }
480
- analyserRef.current = null;
481
- setAudioLevel(0);
482
- };
483
-
484
- mediaRecorderRef.current = mediaRecorder;
485
- mediaRecorder.start();
486
- setRecording(true);
487
- } catch (error) {
488
- console.error("Failed to start recording:", error);
489
- }
490
- }, [clearComposerAudio]);
491
-
492
- const stopRecording = useCallback(() => {
493
- if (mediaRecorderRef.current && recording) {
494
- mediaRecorderRef.current.stop();
495
- setRecording(false);
496
- }
497
- }, [recording]);
498
-
499
- // Cleanup on unmount
500
- useEffect(() => {
501
- return () => {
502
- if (animationFrameRef.current) {
503
- cancelAnimationFrame(animationFrameRef.current);
504
- }
505
- if (audioContextRef.current) {
506
- audioContextRef.current.close();
507
- }
508
- clearComposerAudio();
509
- };
510
- }, [clearComposerAudio]);
511
-
512
- // New: persist timestamp of last actually-sent user message
513
- const [lastUserSentAt, setLastUserSentAt] = useState<number | null>(null);
514
-
515
- // Keep latest values in refs for stable callbacks
516
- const questionRef = useRef(question);
517
- const messagesRef = useRef(messages);
518
- const lastUserSentAtRef = useRef(lastUserSentAt);
519
- const composerImagesRef = useRef(composerImages);
520
- const composerAudioRef = useRef(composerAudio);
521
-
522
- useEffect(() => {
523
- questionRef.current = question;
524
- }, [question]);
525
- useEffect(() => {
526
- composerImagesRef.current = composerImages;
527
- }, [composerImages]);
528
- useEffect(() => {
529
- composerAudioRef.current = composerAudio;
530
- }, [composerAudio]);
531
- useEffect(() => {
532
- messagesRef.current = messages;
533
- }, [messages]);
534
- useEffect(() => {
535
- lastUserSentAtRef.current = lastUserSentAt;
536
- }, [lastUserSentAt]);
537
-
538
- useEffect(() => {
539
- if (language) {
540
- I18n.setLanguage(language || "en");
541
- }
542
- }, [language]);
543
-
544
- const showChatbotPreview: boolean = useSelect(() =>
545
- getStoreSelect(store).isShowChatbotPreview(),
546
- );
547
-
548
- const resolvedMaxImages = useMemo(
549
- () => Math.max(0, maxImages ?? DEFAULT_MAX_IMAGES),
550
- [maxImages],
551
- );
552
-
553
- const resolvedMaxBytes = useMemo(
554
- () => Math.max(0, maxImageBytes ?? DEFAULT_MAX_BYTES),
555
- [maxImageBytes],
556
- );
557
-
558
- const imageAttachmentsEnabled = resolvedMaxImages > 0;
559
-
560
- useEffect(() => {
561
- if (!imageAttachmentsEnabled && composerImagesRef.current.length > 0) {
562
- clearComposerImages();
563
- }
564
- }, [clearComposerImages, imageAttachmentsEnabled]);
565
-
566
- const hasMessages = messages.length > 0;
567
-
568
- const isChatBusy = useMemo(
569
- () => ai.busy && activeOp === "chat",
570
- [ai.busy, activeOp],
571
- );
572
-
573
- const canSend = useMemo(() => {
574
- if (isChatBusy) return false;
575
- // Can send if we have text OR audio
576
- return question.trim().length > 0 || composerAudio !== null;
577
- }, [question, isChatBusy, composerAudio]);
578
-
579
- const openButtonLabel = useMemo(() => {
580
- const resolvedOpenButtonTitle = openButtonTitle?.trim();
581
- const resolvedAskMeLabel = labels.askMeLabel?.trim();
582
- const raw =
583
- resolvedOpenButtonTitle ||
584
- resolvedAskMeLabel ||
585
- DEFAULT_CHATBOT_LABELS.askMeLabel;
586
- const translated = I18n.get(raw).trim();
587
- return translated || I18n.get(DEFAULT_CHATBOT_LABELS.askMeLabel);
588
- }, [openButtonTitle, labels.askMeLabel, language]);
589
-
590
- const modalTitle = useMemo(() => {
591
- const raw =
592
- title?.trim() ||
593
- labels.modalTitle?.trim() ||
594
- DEFAULT_CHATBOT_LABELS.modalTitle;
595
- return I18n.get(raw).trim() || I18n.get(DEFAULT_CHATBOT_LABELS.modalTitle);
596
- }, [title, labels.modalTitle, language]);
597
-
598
- const textareaPlaceholder = useMemo(() => {
599
- const raw = placeholder ? placeholder : labels.placeholder;
600
- return I18n.get(raw);
601
- }, [placeholder, labels.placeholder, language]);
602
-
603
- const aiDisclosure = useMemo(() => {
604
- const template = I18n.get(
605
- labels.aiDisclosureLabel?.trim() || DEFAULT_CHATBOT_AI_DISCLOSURE,
606
- );
607
- return formatAiDisclosure(template, modalTitle);
608
- }, [labels.aiDisclosureLabel, language, modalTitle]);
609
-
610
- const rootClassName = useMemo(() => {
611
- const base = "ai-docs-ask";
612
- const pos = `ai-open-btn--${openButtonPosition}`;
613
- return `${base} ${pos}`;
614
- }, [openButtonPosition]);
615
-
616
- const adjustChatHeight = useCallback(() => {
617
- const el = chatContainerRef.current;
618
- if (!el) return;
619
- try {
620
- const vh = window.innerHeight || document.documentElement.clientHeight;
621
- const minHeight = 360;
622
- const maxHeightCap = 1000;
623
- const viewportMax = Math.floor(vh * 0.8);
624
- const target = Math.max(minHeight, Math.min(viewportMax, maxHeightCap));
625
- el.style.height = `${target}px`;
626
- } catch {
627
- // ignore
628
- }
629
- }, []);
630
-
631
- const scrollToBottom = useCallback(() => {
632
- const el = scrollerEl;
633
- if (!el) return;
634
- window.setTimeout(() => {
635
- try {
636
- el.scrollTop = el.scrollHeight;
637
- } catch {
638
- // ignore
639
- }
640
- }, 50);
641
- }, [scrollerEl]);
642
-
643
- const closeModal = useCallback(() => {
644
- setOpened(false);
645
- if (isMaximized) setIsMaximized(false);
646
- setMaxEnter(false);
647
- onClose?.();
648
- }, [isMaximized, onClose]);
649
-
650
- useEffect(() => {
651
- if (!opened) return;
652
- adjustChatHeight();
653
- window.addEventListener("resize", adjustChatHeight);
654
- return () => window.removeEventListener("resize", adjustChatHeight);
655
- }, [opened, adjustChatHeight]);
656
-
657
- useEffect(() => {
658
- if (!opened || !isMaximized) return;
659
- document.body.style.overflow = "hidden";
660
- return () => {
661
- document.body.style.overflow = "";
662
- };
663
- }, [opened, isMaximized, closeModal]);
664
-
665
- const composerPreviews = useMemo(
666
- () =>
667
- composerImages.map((img) => ({
668
- id: img.id,
669
- url: img.objectUrl,
670
- title: img.file.name,
671
- })),
672
- [composerImages],
673
- );
674
-
675
- useEffect(() => {
676
- if (!hasMessages) setStickToBottom(true);
677
- }, [hasMessages]);
678
-
679
- useEffect(() => {
680
- return () => {
681
- disposeComposerImageList(composerImagesRef.current);
682
- };
683
- }, [disposeComposerImageList]);
684
-
685
- useEffect(() => {
686
- const el = scrollerEl;
687
- if (!el) return;
688
- const handleScroll = () => {
689
- const distanceFromBottom =
690
- el.scrollHeight - (el.scrollTop + el.clientHeight);
691
- setStickToBottom(distanceFromBottom < 20);
692
- };
693
- el.addEventListener("scroll", handleScroll);
694
- return () => {
695
- el.removeEventListener("scroll", handleScroll);
696
- };
697
- }, [opened, scrollerEl]);
698
-
699
- useEffect(() => {
700
- if (!stickToBottom) return;
701
- const el = scrollerEl;
702
- if (!el) return;
703
- if (el.scrollHeight > el.clientHeight) {
704
- el.scrollTop = el.scrollHeight;
705
- }
706
- }, [messages, ai.busy, stickToBottom, scrollerEl]);
707
-
708
- useEffect(() => {
709
- if (!opened) {
710
- setPreviewAttachment(null);
711
- }
712
- }, [opened]);
713
-
714
- const statusText = useMemo(() => {
715
- if (!ai.busy) return null;
716
- return formatStatusEvent(ai.statusEvent, labels) || I18n.get("Working…");
717
- }, [ai.busy, ai.statusEvent, language, labels]);
718
-
719
- const lastCanceledUserMessageId = useMemo(() => {
720
- for (let i = messages.length - 1; i >= 0; i--) {
721
- const m = messages[i];
722
- if (m.role === "user" && m.clientStatus === "canceled") return m.id;
723
- }
724
- return null;
725
- }, [messages]);
726
-
727
- const markLastPendingAs = useCallback(
728
- (status: "canceled" | null) => {
729
- setMessages((prev) => {
730
- const idx = [...prev]
731
- .map((m, i) => ({ m, i }))
732
- .reverse()
733
- .find(
734
- (x) => x.m.role === "user" && x.m.clientStatus === "pending",
735
- )?.i;
736
-
737
- if (idx == null) return prev;
738
-
739
- const next = prev.slice();
740
- const target = next[idx];
741
- next[idx] = {
742
- ...target,
743
- clientStatus: status ?? undefined,
744
- };
745
- return next;
746
- });
747
- },
748
- [setMessages],
749
- );
750
-
751
- const cancelChat = useCallback(() => {
752
- if (!ai.busy || activeOpRef.current !== "chat") return;
753
-
754
- cancelRequestedRef.current = true;
755
- try {
756
- ai.cancel();
757
- } catch {
758
- // ignore
759
- }
760
-
761
- // UI: treat as "not sent"
762
- markLastPendingAs("canceled");
763
- setActiveOp(null);
764
-
765
- // feedback-only status line error should not persist into chat cancel
766
- setStatusLineError(null);
767
-
768
- scrollToBottom();
769
- }, [ai, markLastPendingAs, scrollToBottom]);
770
-
771
- const onPickImages = useCallback(
772
- (e: React.ChangeEvent<HTMLInputElement>) => {
773
- if (!imageAttachmentsEnabled) {
774
- e.currentTarget.value = "";
775
- return;
776
- }
777
-
778
- const existing = composerImagesRef.current;
779
- const files = Array.from(e.target.files || []);
780
- const remaining = Math.max(0, resolvedMaxImages - existing.length);
781
-
782
- if (remaining === 0) {
783
- e.currentTarget.value = "";
784
- return;
785
- }
786
-
787
- const picked: ComposerImage[] = [];
788
-
789
- for (const file of files) {
790
- if (picked.length >= remaining) break;
791
- const okType = /image\/(jpeg|png|gif|webp)/i.test(file.type);
792
- const okSize = file.size <= resolvedMaxBytes;
793
- const duplicate = [...existing, ...picked].some(
794
- (x) =>
795
- x.file.name === file.name &&
796
- x.file.size === file.size &&
797
- x.file.lastModified === file.lastModified,
798
- );
799
-
800
- if (!okType || !okSize || duplicate) continue;
801
-
802
- const objectUrl = createObjectUrl(file);
803
- if (!objectUrl) continue;
804
-
805
- picked.push({
806
- id: createMessageId("composer-image"),
807
- file,
808
- objectUrl,
809
- });
810
- }
811
-
812
- if (picked.length) setComposerImages((prev) => [...prev, ...picked]);
813
- e.currentTarget.value = "";
814
- },
815
- [imageAttachmentsEnabled, resolvedMaxImages, resolvedMaxBytes],
816
- );
817
-
818
- const removeImage = useCallback((ix: number) => {
819
- setComposerImages((prev) => {
820
- if (ix < 0 || ix >= prev.length) return prev;
821
- const target = prev[ix];
822
- if (target) revokeObjectUrlSafe(target.objectUrl);
823
- return prev.filter((_, i) => i !== ix);
824
- });
825
- }, []);
826
-
827
- // New: clear feedback errors back to Ready after a short time
828
- const statusLineErrorTimerRef = useRef<number | null>(null);
829
- useEffect(() => {
830
- if (!statusLineError) return;
831
- if (statusLineErrorTimerRef.current) {
832
- window.clearTimeout(statusLineErrorTimerRef.current);
833
- statusLineErrorTimerRef.current = null;
834
- }
835
- statusLineErrorTimerRef.current = window.setTimeout(() => {
836
- setStatusLineError(null);
837
- statusLineErrorTimerRef.current = null;
838
- }, 6000);
839
- return () => {
840
- if (statusLineErrorTimerRef.current) {
841
- window.clearTimeout(statusLineErrorTimerRef.current);
842
- statusLineErrorTimerRef.current = null;
843
- }
844
- };
845
- }, [statusLineError]);
846
-
847
- const buildUserAttachments = useCallback(
848
- async (
849
- images: ComposerImage[],
850
- audio?: ComposerAudio | null,
851
- ): Promise<ChatMessageAttachment[]> => {
852
- const shouldPersist = historyStorage !== "nostorage";
853
- const attachments: ChatMessageAttachment[] = [];
854
-
855
- // Build image attachments
856
- if (images.length > 0) {
857
- const imageAttachments = await Promise.all(
858
- images.map(async (img) => {
859
- const attachmentId = createMessageId("attachment-image");
860
- let blobId: string | undefined;
861
- if (shouldPersist) {
862
- try {
863
- const persisted = await persistAttachmentBlob(
864
- attachmentId,
865
- img.file,
866
- {
867
- name: img.file.name,
868
- type: img.file.type,
869
- size: img.file.size,
870
- },
871
- );
872
- blobId = persisted ?? undefined;
873
- } catch (error) {
874
- console.warn("[AiChatbot] Failed to persist image", error);
875
- }
876
- }
877
-
878
- const objectUrl = createObjectUrl(img.file);
879
-
880
- return {
881
- id: attachmentId,
882
- name: img.file.name,
883
- type: img.file.type || "application/octet-stream",
884
- size: img.file.size,
885
- blobId,
886
- objectUrl: objectUrl ?? undefined,
887
- blob: img.file,
888
- mediaType: "image" as const,
889
- } satisfies ChatMessageAttachment;
890
- }),
891
- );
892
- attachments.push(...imageAttachments.filter(Boolean));
893
- }
894
-
895
- // Build audio attachment
896
- if (audio) {
897
- const attachmentId = createMessageId("attachment-audio");
898
- let blobId: string | undefined;
899
- if (shouldPersist) {
900
- try {
901
- const persisted = await persistAttachmentBlob(
902
- attachmentId,
903
- audio.blob,
904
- {
905
- name: `audio-${Date.now()}.webm`,
906
- type: audio.blob.type,
907
- size: audio.blob.size,
908
- },
909
- );
910
- blobId = persisted ?? undefined;
911
- } catch (error) {
912
- console.warn("[AiChatbot] Failed to persist audio", error);
913
- }
914
- }
915
-
916
- const objectUrl = createObjectUrl(audio.blob);
917
-
918
- attachments.push({
919
- id: attachmentId,
920
- name: `audio-${Date.now()}.webm`,
921
- type: audio.blob.type || "audio/webm",
922
- size: audio.blob.size,
923
- blobId,
924
- objectUrl: objectUrl ?? undefined,
925
- blob: audio.blob,
926
- duration: audio.duration,
927
- mediaType: "audio" as const,
928
- } satisfies ChatMessageAttachment);
929
- }
930
-
931
- return attachments;
932
- },
933
- [historyStorage],
934
- );
935
-
936
- const hydratePersistedMessages = useCallback(
937
- async (stored: PersistedChatMessage[]): Promise<ChatMessage[]> => {
938
- const hydrated: ChatMessage[] = [];
939
-
940
- for (const msg of stored) {
941
- let attachments: ChatMessageAttachment[] | undefined;
942
- if (msg.attachments && msg.attachments.length > 0) {
943
- attachments = [];
944
- for (const att of msg.attachments) {
945
- let blob: Blob | undefined;
946
- if (att.blobId) {
947
- try {
948
- const loaded = await loadAttachmentBlob(att.blobId);
949
- blob = loaded?.blob ?? undefined;
950
- } catch (error) {
951
- console.warn("[AiChatbot] Failed to hydrate attachment", error);
952
- }
953
- }
954
-
955
- if (!blob) {
956
- continue;
957
- }
958
-
959
- const objectUrl = blob ? createObjectUrl(blob) : null;
960
-
961
- attachments.push({
962
- ...att,
963
- objectUrl: objectUrl ?? undefined,
964
- blob: blob ?? undefined,
965
- });
966
- }
967
- }
968
-
969
- hydrated.push({
970
- ...msg,
971
- attachments,
972
- });
973
- }
974
-
975
- return hydrated;
976
- },
977
- [],
978
- );
979
-
980
- const restoreAttachmentsToComposer = useCallback(
981
- async (attachments?: ChatMessageAttachment[]) => {
982
- if (!attachments || attachments.length === 0) {
983
- clearComposerImages();
984
- return;
985
- }
986
-
987
- const restored: ComposerImage[] = [];
988
-
989
- for (const attachment of attachments) {
990
- let blob: Blob | undefined = attachment.blob;
991
- if (!blob && attachment.blobId) {
992
- try {
993
- const loaded = await loadAttachmentBlob(attachment.blobId);
994
- blob = loaded?.blob ?? undefined;
995
- } catch (error) {
996
- console.warn("[AiChatbot] Failed to reload attachment", error);
997
- }
998
- }
999
-
1000
- if (!blob) continue;
1001
-
1002
- const file =
1003
- blob instanceof File
1004
- ? blob
1005
- : new File([blob], attachment.name || "attachment", {
1006
- type:
1007
- attachment.type || blob.type || "application/octet-stream",
1008
- });
1009
-
1010
- const objectUrl = createObjectUrl(file);
1011
- if (!objectUrl) continue;
1012
-
1013
- restored.push({
1014
- id: createMessageId("composer-image"),
1015
- file,
1016
- objectUrl,
1017
- });
1018
-
1019
- if (restored.length >= resolvedMaxImages) break;
1020
- }
1021
-
1022
- if (restored.length === 0) {
1023
- clearComposerImages();
1024
- return;
1025
- }
1026
-
1027
- setComposerImages((prev) => {
1028
- disposeComposerImageList(prev);
1029
- return restored;
1030
- });
1031
-
1032
- if (fileInputRef.current) fileInputRef.current.value = "";
1033
- },
1034
- [clearComposerImages, disposeComposerImageList, resolvedMaxImages],
1035
- );
1036
-
1037
- const openAttachmentPreview = useCallback(
1038
- (url?: string | null, title?: string) => {
1039
- if (!url) return;
1040
- setPreviewAttachment({ url, title });
1041
- },
1042
- [],
1043
- );
1044
-
1045
- const closeAttachmentPreview = useCallback(() => {
1046
- setPreviewAttachment(null);
1047
- }, []);
1048
-
1049
- const resetConversation = useCallback(() => {
1050
- disposeMessagesAttachments(messagesRef.current);
1051
- clearComposerImages();
1052
- clearComposerAudio();
1053
- setMessages([]);
1054
- setStatusLineError(null);
1055
- sessionRef.current = null;
1056
- setLastUserSentAt(null);
1057
- setStickToBottom(true);
1058
- setResetDialogOpen(false);
1059
-
1060
- const storage = getHistoryStorage(historyStorage);
1061
- if (storage) {
1062
- try {
1063
- storage.removeItem(HISTORY_STORAGE_KEY);
1064
- } catch {
1065
- // ignore
1066
- }
1067
- }
1068
-
1069
- void clearAllAttachments();
1070
- }, [clearComposerImages, clearComposerAudio, historyStorage]);
1071
-
1072
- const handleResetClick = useCallback(() => {
1073
- // Open confirmation dialog
1074
- setResetDialogOpen(true);
1075
- }, []);
1076
-
1077
- const confirmReset = useCallback(() => {
1078
- // If a chat is in-flight, cancel first (then reset)
1079
- if (ai.busy && activeOpRef.current === "chat") {
1080
- cancelChat();
1081
- }
1082
- resetConversation();
1083
- }, [ai.busy, cancelChat, resetConversation]);
1084
-
1085
- const cancelReset = useCallback(() => {
1086
- setResetDialogOpen(false);
1087
- }, []);
1088
-
1089
- const sendFeedbackToServer = useCallback(
1090
- async (messageId: string, feedbackType: "accepted" | "rejected") => {
1091
- // feedback should NOT spam status; only show errors
1092
- if (ai.busy) return;
1093
-
1094
- try {
1095
- const activeSessionId =
1096
- sessionRef.current &&
1097
- Date.now() - sessionRef.current.storedAt <
1098
- emptyHistoryAfterDays * TWENTY_FOUR_HOURS_MS
1099
- ? sessionRef.current.id
1100
- : undefined;
1101
- if (!activeSessionId) return;
1102
-
1103
- setActiveOp("feedback");
1104
- setStatusLineError(null);
1105
-
1106
- await ai.run(async ({ signal, onStatus }) => {
1107
- await sendFeedbackMessage(
1108
- {
1109
- sessionId: activeSessionId,
1110
- feedbackMessageId: messageId,
1111
- feedbackType,
1112
- },
1113
- {
1114
- signal,
1115
- onStatus,
1116
- context,
1117
- },
1118
- );
1119
- return null;
1120
- });
1121
-
1122
- // success: keep Ready (no extra UI)
1123
- setStatusLineError(null);
1124
- } catch (e) {
1125
- const msg =
1126
- (e as Error)?.message?.trim() || I18n.get("An error occurred.");
1127
- // feedback error: ONLY status line (auto-clears back to Ready)
1128
- setStatusLineError(msg);
1129
- console.error("Failed to send feedback", e);
1130
- } finally {
1131
- setActiveOp((prev) => (prev === "feedback" ? null : prev));
1132
- }
1133
- },
1134
- [ai, language],
1135
- );
1136
-
1137
- const updateFeedback = useCallback(
1138
- (messageId: string, verdict: "accepted" | "rejected") => {
1139
- // optimistic toggle (and allow "clear" by clicking same verdict again)
1140
- setMessages((prev) =>
1141
- prev.map((msg) => {
1142
- if (msg.id !== messageId || msg.role !== "assistant") return msg;
1143
- if (msg.feedback === verdict) return { ...msg, feedback: undefined };
1144
- return { ...msg, feedback: verdict };
1145
- }),
1146
- );
1147
- void sendFeedbackToServer(messageId, verdict);
1148
- },
1149
- [sendFeedbackToServer],
1150
- );
1151
-
1152
- const ask = useCallback(async () => {
1153
- const trimmed = questionRef.current.trim();
1154
- const selectedAudio = composerAudioRef.current;
1155
-
1156
- // Can send if we have text OR audio
1157
- if ((!trimmed && !selectedAudio) || ai.busy) return;
1158
-
1159
- cancelRequestedRef.current = false;
1160
- setStatusLineError(null);
1161
- setActiveOp("chat");
1162
- const selectedImages = imageAttachmentsEnabled
1163
- ? [...composerImagesRef.current]
1164
- : [];
1165
- const userAttachments = await buildUserAttachments(
1166
- selectedImages,
1167
- selectedAudio,
1168
- );
1169
-
1170
- const userMessageId = createMessageId("user");
1171
- const userMessageCreatedAt = Date.now();
1172
- const userMessage: ChatMessage = {
1173
- id: userMessageId,
1174
- role: "user",
1175
- content: trimmed || (selectedAudio ? "[Audio message]" : ""),
1176
- createdAt: userMessageCreatedAt,
1177
- clientStatus: "pending",
1178
- attachments: userAttachments.length ? userAttachments : undefined,
1179
- };
1180
-
1181
- // optimistic UI
1182
- setQuestion("");
1183
- clearComposerImages();
1184
- clearComposerAudio();
1185
- setMessages((prev) => [...prev, userMessage]);
1186
-
1187
- if (!opened) setOpened(true);
1188
- scrollToBottom();
1189
-
1190
- try {
1191
- const activeSessionId =
1192
- sessionRef.current &&
1193
- Date.now() - sessionRef.current.storedAt <
1194
- emptyHistoryAfterDays * TWENTY_FOUR_HOURS_MS
1195
- ? sessionRef.current.id
1196
- : undefined;
1197
-
1198
- const res = (await ai.run(async ({ signal, onStatus }) => {
1199
- const out = await sendChatMessage(
1200
- {
1201
- sessionId: activeSessionId,
1202
- message: trimmed || undefined,
1203
- audio: selectedAudio?.blob,
1204
- images: selectedImages.map((img) => img.file),
1205
- maxTokens,
1206
- },
1207
- {
1208
- signal,
1209
- onStatus,
1210
- context,
1211
- },
1212
- );
1213
- return out;
1214
- })) as ChatResponse | null;
1215
-
1216
- // If user clicked cancel while request was in-flight, ignore output
1217
- if (cancelRequestedRef.current) {
1218
- markLastPendingAs("canceled");
1219
- return;
1220
- }
1221
-
1222
- if (!res) {
1223
- throw new Error(I18n.get(ai.error ?? labels.emptyResponseLabel));
1224
- }
1225
-
1226
- if (res.sessionId) {
1227
- sessionRef.current = {
1228
- id: res.sessionId,
1229
- storedAt: Date.now(),
1230
- };
1231
- }
1232
-
1233
- const resultText =
1234
- typeof res.result === "string" ? res.result.trim() : "";
1235
- if (!resultText) {
1236
- throw new Error(I18n.get(ai.error ?? labels.emptyResponseLabel));
1237
- }
1238
-
1239
- if (res.metadata?.stopReason === "max_tokens") {
1240
- console.warn("Chat response hit the backend output token limit", {
1241
- maxTokens: res.metadata?.maxTokens,
1242
- requestId: res.metadata?.requestId,
1243
- modelId: res.metadata?.modelId,
1244
- outputTokens: res.metadata?.outputTokens,
1245
- });
1246
- }
1247
-
1248
- const assistantMessage: ChatMessage = {
1249
- id: res.metadata?.messageId || createMessageId("assistant"),
1250
- role: "assistant",
1251
- content: resultText,
1252
- citations: res.citations,
1253
- createdAt: Date.now(),
1254
- };
1255
-
1256
- setMessages((prev) => {
1257
- const cleared = prev.map((m) =>
1258
- m.id === userMessageId ? { ...m, clientStatus: undefined } : m,
1259
- );
1260
- return [...cleared, assistantMessage];
1261
- });
1262
-
1263
- // mark last sent timestamp on successful request completion
1264
- setLastUserSentAt(userMessageCreatedAt);
1265
- } catch (e) {
1266
- // Cancel: treat as not sent, no error bubble
1267
- if (
1268
- cancelRequestedRef.current ||
1269
- isAbortLike(e as Error & { code?: string })
1270
- ) {
1271
- markLastPendingAs("canceled");
1272
- return;
1273
- }
1274
-
1275
- const msg =
1276
- (e as Error)?.message?.trim() || I18n.get(labels.unexpectedErrorLabel);
1277
- setStatusLineError(msg);
1278
-
1279
- // show error inside chat (assistant side)
1280
- setMessages((prev) => {
1281
- const cleared = prev.map((m) =>
1282
- m.id === userMessageId ? { ...m, clientStatus: undefined } : m,
1283
- );
1284
- return [
1285
- ...cleared,
1286
- {
1287
- id: createMessageId("assistant-error"),
1288
- role: "assistant",
1289
- content: `⚠️ ${msg}`,
1290
- createdAt: Date.now(),
1291
- },
1292
- ];
1293
- });
1294
-
1295
- // still consider the message "sent" (server error happened after sending)
1296
- setLastUserSentAt(userMessageCreatedAt);
1297
- } finally {
1298
- setActiveOp((prev) => (prev === "chat" ? null : prev));
1299
- cancelRequestedRef.current = false;
1300
- if (questionInputRef.current) questionInputRef.current.focus();
1301
- scrollToBottom();
1302
- }
1303
- }, [
1304
- ai,
1305
- buildUserAttachments,
1306
- clearComposerImages,
1307
- clearComposerAudio,
1308
- opened,
1309
- scrollToBottom,
1310
- markLastPendingAs,
1311
- labels.emptyResponseLabel,
1312
- labels.unexpectedErrorLabel,
1313
- language,
1314
- imageAttachmentsEnabled,
1315
- ]);
1316
-
1317
- const handleQuestionKeyDown = useCallback(
1318
- (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
1319
- if (e.key === "Enter" && !e.shiftKey) {
1320
- e.preventDefault();
1321
- if (canSend) void ask();
1322
- }
1323
- },
1324
- [ask, canSend],
1325
- );
1326
-
1327
- const handleOpenClick = useCallback(() => {
1328
- setOpened(true);
1329
- }, []);
1330
-
1331
- useEffect(() => {
1332
- return () => {
1333
- if (maxEnterRafRef.current != null) {
1334
- cancelAnimationFrame(maxEnterRafRef.current);
1335
- maxEnterRafRef.current = null;
1336
- }
1337
- };
1338
- }, []);
1339
-
1340
- const handleToggleMaximize = useCallback(() => {
1341
- setIsMaximized((prev) => {
1342
- const next = !prev;
1343
-
1344
- if (maxEnterRafRef.current != null) {
1345
- cancelAnimationFrame(maxEnterRafRef.current);
1346
- maxEnterRafRef.current = null;
1347
- }
1348
-
1349
- // When maximizing: apply ai-max-enter for one render frame,
1350
- // then remove it so CSS can animate to the final state.
1351
- if (next) {
1352
- setMaxEnter(true);
1353
- requestAnimationFrame(() => {
1354
- maxEnterRafRef.current = requestAnimationFrame(() => {
1355
- setMaxEnter(false);
1356
- maxEnterRafRef.current = null;
1357
- });
1358
- });
1359
- } else {
1360
- // When restoring size: no need for enter helper
1361
- setMaxEnter(false);
1362
- }
1363
-
1364
- return next;
1365
- });
1366
- }, []);
1367
-
1368
- const handleEditCanceled = useCallback(
1369
- (msg: ChatMessage) => {
1370
- setQuestion(msg.content);
1371
- void (async () => {
1372
- await restoreAttachmentsToComposer(msg.attachments);
1373
- setMessages((prev) => prev.filter((m) => m.id !== msg.id));
1374
- disposeMessageAttachments(msg.attachments);
1375
- queueMicrotask(() => questionInputRef.current?.focus());
1376
- })();
1377
- },
1378
- [restoreAttachmentsToComposer],
1379
- );
1380
-
1381
- const renderOpenButtonIcon = useMemo(() => {
1382
- if (!showOpenButtonIcon) return null;
1383
- if (openButtonIcon) {
1384
- return (
1385
- <img
1386
- src={openButtonIcon}
1387
- className="ai-open-btn-icon"
1388
- alt={I18n.get(labels.askMeLabel || openButtonLabel)}
1389
- />
1390
- );
1391
- }
1392
- return <IconMessage size={18} />;
1393
- }, [showOpenButtonIcon, openButtonIcon, labels, openButtonLabel, language]);
1394
-
1395
- const openButtonContent = useMemo(() => {
1396
- const iconEl = renderOpenButtonIcon;
1397
- const textEl = showOpenButtonTitle ? (
1398
- <Text inherit>{openButtonLabel}</Text>
1399
- ) : null;
1400
-
1401
- if (!showOpenButtonIcon && !textEl) return null;
1402
- if (!showOpenButtonIcon) return textEl;
1403
- if (!showOpenButtonTitle) return iconEl;
1404
-
1405
- switch (openButtonIconLayout) {
1406
- case "top":
1407
- return (
1408
- <Stack gap={4} align="center">
1409
- {iconEl}
1410
- {textEl}
1411
- </Stack>
1412
- );
1413
- case "bottom":
1414
- return (
1415
- <Stack gap={4} align="center">
1416
- {textEl}
1417
- {iconEl}
1418
- </Stack>
1419
- );
1420
- case "right":
1421
- return (
1422
- <Group gap={6} align="center">
1423
- {textEl}
1424
- {iconEl}
1425
- </Group>
1426
- );
1427
- case "left":
1428
- default:
1429
- return (
1430
- <Group gap={6} align="center">
1431
- {iconEl}
1432
- {textEl}
1433
- </Group>
1434
- );
1435
- }
1436
- }, [
1437
- renderOpenButtonIcon,
1438
- showOpenButtonIcon,
1439
- showOpenButtonTitle,
1440
- openButtonLabel,
1441
- openButtonIconLayout,
1442
- ]);
1443
-
1444
- const showStatusBubble = useMemo(() => isChatBusy, [isChatBusy]);
1445
-
1446
- // Status line: hidden only while waiting for assistant (no duplicate).
1447
- const showStatusLine = useMemo(() => {
1448
- if (isChatBusy) return false;
1449
- return true;
1450
- }, [isChatBusy]);
1451
-
1452
- const statusLineText = useMemo(() => {
1453
- if (statusLineError) return statusLineError;
1454
- return hasMessages
1455
- ? I18n.get(labels.readyLabel)
1456
- : I18n.get(labels.readyEmptyLabel);
1457
- }, [
1458
- statusLineError,
1459
- hasMessages,
1460
- labels.readyLabel,
1461
- labels.readyEmptyLabel,
1462
- language,
1463
- ]);
1464
-
1465
- const sendOrCancelLabel = useMemo(() => {
1466
- if (isChatBusy) return I18n.get(labels.cancelLabel);
1467
- return I18n.get(labels.sendLabel);
1468
- }, [isChatBusy, labels.cancelLabel, labels.sendLabel, language]);
1469
-
1470
- const sendOrCancelIcon = useMemo(() => {
1471
- if (isChatBusy) return <IconPlayerStop size={18} />;
1472
- return <IconSend size={18} />;
1473
- }, [isChatBusy]);
1474
-
1475
- const onSendOrCancel = useCallback(() => {
1476
- if (isChatBusy) {
1477
- cancelChat();
1478
- return;
1479
- }
1480
- void ask();
1481
- }, [isChatBusy, cancelChat, ask]);
1482
-
1483
- useEffect(() => {
1484
- if (!opened) return;
1485
- if (!wheelHostEl || !scrollerEl) return;
1486
-
1487
- const isScrollableNow = () => {
1488
- const cs = window.getComputedStyle(scrollerEl);
1489
- const overflowY = cs.overflowY;
1490
- const canOverflow = overflowY === "auto" || overflowY === "scroll";
1491
-
1492
- const sh = Math.ceil(scrollerEl.scrollHeight);
1493
- const ch = Math.floor(scrollerEl.clientHeight);
1494
- const hasOverflow = sh > ch;
1495
- return canOverflow && hasOverflow;
1496
- };
1497
- let enabled = false;
1498
-
1499
- const onWheel = (e: WheelEvent) => {
1500
- if (!isScrollableNow()) return;
1501
-
1502
- e.preventDefault();
1503
-
1504
- const max = scrollerEl.scrollHeight - scrollerEl.clientHeight;
1505
- scrollerEl.scrollTop = Math.max(
1506
- 0,
1507
- Math.min(max, scrollerEl.scrollTop + e.deltaY),
1508
- );
1509
- };
1510
-
1511
- const sync = () => {
1512
- const shouldEnable = isScrollableNow();
1513
- setBodyScrollable(shouldEnable);
1514
- if (shouldEnable === enabled) return;
1515
- enabled = shouldEnable;
1516
- if (enabled) {
1517
- wheelHostEl.addEventListener("wheel", onWheel, { passive: false });
1518
- } else {
1519
- wheelHostEl.removeEventListener("wheel", onWheel as EventListener);
1520
- }
1521
- };
1522
-
1523
- sync();
1524
-
1525
- const ro = new ResizeObserver(sync);
1526
- ro.observe(scrollerEl);
1527
-
1528
- const mo = new MutationObserver(sync);
1529
- mo.observe(scrollerEl, {
1530
- childList: true,
1531
- subtree: true,
1532
- characterData: true,
1533
- });
1534
-
1535
- window.addEventListener("resize", sync);
1536
-
1537
- return () => {
1538
- if (enabled)
1539
- wheelHostEl.removeEventListener("wheel", onWheel as EventListener);
1540
- ro.disconnect();
1541
- mo.disconnect();
1542
- window.removeEventListener("resize", sync);
1543
- };
1544
- }, [opened, wheelHostEl, scrollerEl]);
1545
-
1546
- // -----------------------------
1547
- // History persistence
1548
- // -----------------------------
1549
-
1550
- useEffect(() => {
1551
- let canceled = false;
1552
- const storage = getHistoryStorage(historyStorage);
1553
- if (!storage) {
1554
- if (historyStorage === "nostorage") {
1555
- void clearAllAttachments();
1556
- }
1557
- setHistoryReady(true);
1558
- return;
1559
- }
1560
-
1561
- (async () => {
1562
- try {
1563
- const raw = storage.getItem(HISTORY_STORAGE_KEY);
1564
- if (!raw) {
1565
- setHistoryReady(true);
1566
- return;
1567
- }
1568
-
1569
- const parsed = JSON.parse(raw) as PersistedChat;
1570
- const last =
1571
- typeof parsed?.lastUserSentAt === "number"
1572
- ? parsed.lastUserSentAt
1573
- : null;
1574
-
1575
- if (
1576
- !last ||
1577
- Date.now() - last > emptyHistoryAfterDays * TWENTY_FOUR_HOURS_MS
1578
- ) {
1579
- storage.removeItem(HISTORY_STORAGE_KEY);
1580
- await clearAllAttachments();
1581
- setHistoryReady(true);
1582
- return;
1583
- }
1584
-
1585
- const loadedMessages = Array.isArray(parsed.messages)
1586
- ? parsed.messages
1587
- : [];
1588
-
1589
- const normalized = loadedMessages.map((m) => {
1590
- if (m?.role === "user" && m.clientStatus === "pending") {
1591
- return { ...m, clientStatus: "canceled" as const };
1592
- }
1593
- return m;
1594
- });
1595
-
1596
- const hydrated = await hydratePersistedMessages(normalized);
1597
-
1598
- if (canceled) {
1599
- disposeMessagesAttachments(hydrated);
1600
- return;
1601
- }
1602
-
1603
- setMessages(hydrated);
1604
- setLastUserSentAt(last);
1605
-
1606
- if (parsed.session && parsed.session.id) {
1607
- sessionRef.current = parsed.session;
1608
- }
1609
- } catch (error) {
1610
- console.warn("[AiChatbot] Failed to load history", error);
1611
- try {
1612
- storage.removeItem(HISTORY_STORAGE_KEY);
1613
- } catch {
1614
- // ignore
1615
- }
1616
- } finally {
1617
- if (!canceled) setHistoryReady(true);
1618
- }
1619
- })();
1620
-
1621
- return () => {
1622
- canceled = true;
1623
- };
1624
- }, [historyStorage, emptyHistoryAfterDays, hydratePersistedMessages]);
1625
-
1626
- useEffect(() => {
1627
- if (!historyReady) return;
1628
-
1629
- const storage = getHistoryStorage(historyStorage);
1630
- if (!storage) return;
1631
-
1632
- const last = lastUserSentAtRef.current;
1633
-
1634
- if (!last) {
1635
- return;
1636
- }
1637
-
1638
- if (Date.now() - last > emptyHistoryAfterDays * TWENTY_FOUR_HOURS_MS) {
1639
- try {
1640
- storage.removeItem(HISTORY_STORAGE_KEY);
1641
- } catch {
1642
- // ignore
1643
- }
1644
- void cleanupDanglingAttachments(new Set());
1645
- return;
1646
- }
1647
-
1648
- const persistableMessages: PersistedChatMessage[] = messages.map(
1649
- ({ attachments, ...rest }) => ({
1650
- ...rest,
1651
- attachments: attachments?.map(
1652
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
1653
- ({ objectUrl, blob, ...persisted }) => persisted,
1654
- ),
1655
- }),
1656
- );
1657
-
1658
- const payload: PersistedChat = {
1659
- version: 1,
1660
- lastUserSentAt: last,
1661
- session: sessionRef.current,
1662
- messages: persistableMessages,
1663
- };
1664
-
1665
- try {
1666
- storage.setItem(HISTORY_STORAGE_KEY, JSON.stringify(payload));
1667
- } catch {
1668
- // ignore
1669
- }
1670
-
1671
- const validIds = new Set<string>();
1672
- persistableMessages.forEach((msg) => {
1673
- msg.attachments?.forEach((att) => {
1674
- if (att.blobId) validIds.add(att.blobId);
1675
- });
1676
- });
1677
-
1678
- void cleanupDanglingAttachments(validIds);
1679
- }, [
1680
- historyReady,
1681
- messages,
1682
- lastUserSentAt,
1683
- historyStorage,
1684
- emptyHistoryAfterDays,
1685
- ]);
1686
-
1687
- if (
1688
- (previewMode && !showChatbotPreview) ||
1689
- (!previewMode && showChatbotPreview)
1690
- ) {
1691
- return null;
1692
- }
1693
-
1694
- return (
1695
- <Group className={rootClassName}>
1696
- {!opened && (
1697
- <Button
1698
- variant="filled"
1699
- className={
1700
- showOpenButtonTitle
1701
- ? "ai-launcher-button ai-launcher-text"
1702
- : "ai-launcher-button"
1703
- }
1704
- onClick={handleOpenClick}
1705
- aria-label={openButtonLabel}
1706
- title={openButtonLabel}
1707
- data-ai-kit-open-button
1708
- >
1709
- {openButtonContent}
1710
- </Button>
1711
- )}
1712
-
1713
- {opened && (
1714
- <Modal.Root
1715
- ref={chatContainerRef}
1716
- opened={opened}
1717
- lockScroll={false}
1718
- trapFocus={false}
1719
- closeOnEscape={true}
1720
- onClose={closeModal}
1721
- className={
1722
- rootClassName +
1723
- " ai-chat-container" +
1724
- (isMaximized ? " maximized" : "") +
1725
- (isMaximized && maxEnter ? " ai-max-enter" : "")
1726
- }
1727
- portalProps={{ target: rootElement, reuseTargetNode: true }}
1728
- data-ai-kit-theme={colorMode}
1729
- data-ai-kit-variation="modal"
1730
- >
1731
- <div className="ai-chat-container-internal" ref={setWheelHostEl}>
1732
- <Modal.Header className="ai-chat-header-bar">
1733
- <Modal.Title className="ai-chat-title">{modalTitle}</Modal.Title>
1734
- <Group gap="4px" align="center" justify="center">
1735
- {typeof window !== "undefined" && window.innerWidth > 600 && (
1736
- <ActionIcon
1737
- variant="subtle"
1738
- c="var(--ai-kit-chat-icon-color, var(--ai-kit-color-text))"
1739
- onClick={handleToggleMaximize}
1740
- title={
1741
- isMaximized
1742
- ? I18n.get(labels.restoreSizeLabel)
1743
- : I18n.get(labels.maximizeLabel)
1744
- }
1745
- aria-label={
1746
- isMaximized
1747
- ? I18n.get(labels.restoreSizeLabel)
1748
- : I18n.get(labels.maximizeLabel)
1749
- }
1750
- data-ai-kit-maximize-button
1751
- >
1752
- {isMaximized ? (
1753
- <IconMinimize size={16} />
1754
- ) : (
1755
- <IconMaximize size={16} />
1756
- )}
1757
- </ActionIcon>
1758
- )}
1759
- <Modal.CloseButton
1760
- aria-label={I18n.get(labels.closeChatLabel)}
1761
- />
1762
- </Group>
1763
- </Modal.Header>
1764
-
1765
- <Modal.Body
1766
- className="ai-chat-scroll"
1767
- ref={setScrollerEl}
1768
- data-scrollable={bodyScrollable ? "true" : "false"}
1769
- >
1770
- {messages.map((msg) => {
1771
- const isUser = msg.role === "user";
1772
- const isLastCanceled =
1773
- isUser &&
1774
- msg.clientStatus === "canceled" &&
1775
- msg.id === lastCanceledUserMessageId;
1776
-
1777
- return (
1778
- <Group
1779
- key={msg.id}
1780
- justify={isUser ? "flex-end" : "flex-start"}
1781
- className={"ai-chat-row " + msg.role}
1782
- onMouseEnter={() => setHoveredMessageId(msg.id)}
1783
- onMouseLeave={() =>
1784
- setHoveredMessageId((cur) =>
1785
- cur === msg.id ? null : cur,
1786
- )
1787
- }
1788
- >
1789
- <Stack
1790
- gap={4}
1791
- w="100%"
1792
- style={{
1793
- alignItems: isUser ? "flex-end" : "flex-start",
1794
- }}
1795
- >
1796
- <Stack className="ai-chat-bubble">
1797
- <Text className="ai-chat-header">
1798
- <Text
1799
- fw="bolder"
1800
- size="xs"
1801
- style={{ whiteSpace: "nowrap" }}
1802
- >
1803
- {isUser
1804
- ? I18n.get(labels.userLabel)
1805
- : I18n.get(labels.assistantLabel)}
1806
- </Text>
1807
- &nbsp;
1808
- <Text size="xs" style={{ whiteSpace: "nowrap" }}>
1809
- {new Date(msg.createdAt).toLocaleTimeString([], {
1810
- hour: "2-digit",
1811
- minute: "2-digit",
1812
- })}
1813
- </Text>
1814
- </Text>
1815
-
1816
- {msg.role === "assistant" ? (
1817
- <ReactMarkdown remarkPlugins={[remarkGfm]}>
1818
- {msg.content}
1819
- </ReactMarkdown>
1820
- ) : (
1821
- <Text size="sm" miw="100px">
1822
- {msg.content}
1823
- </Text>
1824
- )}
1825
- </Stack>
1826
-
1827
- {msg.attachments && msg.attachments.length > 0 && (
1828
- <Stack
1829
- gap="xs"
1830
- style={{ maxWidth: "min(400px, 100%)" }}
1831
- >
1832
- {/* Image attachments */}
1833
- {msg.attachments.filter(
1834
- (att) =>
1835
- att.mediaType === "image" ||
1836
- (!att.mediaType && att.type.startsWith("image/")),
1837
- ).length > 0 && (
1838
- <Group
1839
- className="ai-thumbs ai-message-thumbs"
1840
- gap="xs"
1841
- >
1842
- {msg.attachments
1843
- .filter(
1844
- (att) =>
1845
- att.mediaType === "image" ||
1846
- (!att.mediaType &&
1847
- att.type.startsWith("image/")),
1848
- )
1849
- .map((attachment) => (
1850
- <button
1851
- key={attachment.id}
1852
- type="button"
1853
- className="thumb"
1854
- style={{
1855
- backgroundImage: attachment.objectUrl
1856
- ? `url(${attachment.objectUrl})`
1857
- : undefined,
1858
- backgroundSize: "cover",
1859
- backgroundPosition: "center",
1860
- backgroundRepeat: "no-repeat",
1861
- }}
1862
- onClick={() =>
1863
- openAttachmentPreview(
1864
- attachment.objectUrl,
1865
- attachment.name,
1866
- )
1867
- }
1868
- disabled={!attachment.objectUrl}
1869
- title={
1870
- attachment.name || I18n.get("View image")
1871
- }
1872
- aria-label={
1873
- attachment.name || I18n.get("View image")
1874
- }
1875
- >
1876
- {!attachment.objectUrl && (
1877
- <Text size="xs" c="dimmed">
1878
- {I18n.get("Image no longer available")}
1879
- </Text>
1880
- )}
1881
- </button>
1882
- ))}
1883
- </Group>
1884
- )}
1885
-
1886
- {/* Audio attachments */}
1887
- {msg.attachments
1888
- .filter(
1889
- (att) =>
1890
- att.mediaType === "audio" ||
1891
- (!att.mediaType &&
1892
- att.type.startsWith("audio/")),
1893
- )
1894
- .map((attachment) => (
1895
- <Box
1896
- key={attachment.id}
1897
- p="sm"
1898
- style={{
1899
- backgroundColor:
1900
- "var(--ai-kit-chat-surface-subtle)",
1901
- borderRadius: "var(--ai-kit-radius-sm)",
1902
- border:
1903
- "1px solid var(--ai-kit-chat-border-color)",
1904
- }}
1905
- >
1906
- {attachment.objectUrl ? (
1907
- <Stack gap="xs">
1908
- <audio
1909
- className="ai-kit-audio-player"
1910
- controls
1911
- src={attachment.objectUrl}
1912
- preload="metadata"
1913
- />
1914
- {attachment.duration && (
1915
- <Text
1916
- size="xs"
1917
- c="dimmed"
1918
- style={{ textAlign: "right" }}
1919
- >
1920
- {Math.round(attachment.duration)}s
1921
- </Text>
1922
- )}
1923
- </Stack>
1924
- ) : (
1925
- <Text size="xs" c="dimmed">
1926
- {I18n.get("Audio no longer available")}
1927
- </Text>
1928
- )}
1929
- </Box>
1930
- ))}
1931
- </Stack>
1932
- )}
1933
-
1934
- {isLastCanceled && (
1935
- <Group justify="flex-end" gap="xs">
1936
- <Text size="xs" c="dimmed">
1937
- <em>{I18n.get(labels.notSentLabel)}</em>
1938
- </Text>
1939
- {hoveredMessageId === msg.id && (
1940
- <ActionIcon
1941
- size="sm"
1942
- variant="subtle"
1943
- onClick={() => handleEditCanceled(msg)}
1944
- title={I18n.get(labels.editLabel)}
1945
- aria-label={I18n.get(labels.editLabel)}
1946
- data-ai-kit-edit-button
1947
- >
1948
- <IconPencil size={14} />
1949
- </ActionIcon>
1950
- )}
1951
- </Group>
1952
- )}
1953
-
1954
- {msg.citations && msg.citations.length > 0 && (
1955
- <Stack className="ai-citations">
1956
- <Text fw="bold" size="sm" mb="xs">
1957
- {I18n.get(labels.referencesLabel)}
1958
- </Text>
1959
- <List spacing="xs" size="sm">
1960
- {msg.citations.map((c, i) => {
1961
- const link = c.sourceUrl || c.url;
1962
- const citeTitle =
1963
- c.title ||
1964
- link ||
1965
- `${I18n.get(labels.referenceLabel)} #${i + 1}`;
1966
- return (
1967
- <List.Item key={i}>
1968
- {link ? (
1969
- <Anchor
1970
- href={link}
1971
- target="_blank"
1972
- rel="noreferrer"
1973
- >
1974
- {citeTitle}
1975
- </Anchor>
1976
- ) : (
1977
- <Text>{citeTitle}</Text>
1978
- )}
1979
- {c.snippet ? (
1980
- <Text size="xs" c="dimmed" mt={4}>
1981
- {c.snippet}
1982
- </Text>
1983
- ) : null}
1984
- </List.Item>
1985
- );
1986
- })}
1987
- </List>
1988
- </Stack>
1989
- )}
1990
-
1991
- {msg.role === "assistant" && (
1992
- <Group className="ai-feedback" gap="xs">
1993
- <Button
1994
- className={
1995
- msg.feedback === "accepted" ? "active" : undefined
1996
- }
1997
- onClick={() => updateFeedback(msg.id, "accepted")}
1998
- aria-label={I18n.get(labels.acceptResponseLabel)}
1999
- disabled={ai.busy}
2000
- data-ai-kit-feedback-accept-button
2001
- >
2002
- 👍
2003
- </Button>
2004
- <Button
2005
- type="button"
2006
- className={
2007
- msg.feedback === "rejected" ? "active" : undefined
2008
- }
2009
- onClick={() => updateFeedback(msg.id, "rejected")}
2010
- aria-label={I18n.get(labels.rejectResponseLabel)}
2011
- disabled={ai.busy}
2012
- data-ai-kit-feedback-reject-button
2013
- >
2014
- 👎
2015
- </Button>
2016
- </Group>
2017
- )}
2018
- </Stack>
2019
- </Group>
2020
- );
2021
- })}
2022
-
2023
- {/* Progress/status bubble (assistant side) - ONLY while waiting for chat answer */}
2024
- {showStatusBubble && (
2025
- <Group
2026
- justify="flex-start"
2027
- className="ai-chat-row assistant status"
2028
- >
2029
- <Stack className="ai-chat-bubble typing">
2030
- {statusText ? (
2031
- <Text size="sm" c="dimmed">
2032
- <em>{statusText}</em>
2033
- </Text>
2034
- ) : null}
2035
- <div className="typing-indicator">
2036
- <span />
2037
- <span />
2038
- <span />
2039
- </div>
2040
- </Stack>
2041
- </Group>
2042
- )}
2043
- </Modal.Body>
2044
-
2045
- {/* Status line (below bubbles) */}
2046
- {showStatusLine && (
2047
- <Group
2048
- className="ai-status-line"
2049
- role={statusLineError ? "alert" : "status"}
2050
- aria-live={statusLineError ? "assertive" : "polite"}
2051
- >
2052
- <Text className="ai-status-text">
2053
- <em>{statusLineText}</em>
2054
- </Text>
2055
- </Group>
2056
- )}
2057
-
2058
- <Text
2059
- className="ai-generated-content-disclosure ai-chatbot-generated-content-disclosure"
2060
- size="xs"
2061
- c="dimmed"
2062
- role="note"
2063
- data-ai-kit-ai-disclosure
2064
- >
2065
- {aiDisclosure}
2066
- </Text>
2067
-
2068
- <Stack className="ai-box ai-box-open">
2069
- {/* Reset confirmation dialog (Yes/No) */}
2070
- <Modal
2071
- opened={resetDialogOpen}
2072
- onClose={cancelReset}
2073
- centered
2074
- title={I18n.get("Reset conversation")}
2075
- style={{ zIndex: "var(--mb-z-index)", position: "fixed" }}
2076
- left={0}
2077
- >
2078
- <Text size="sm">
2079
- {I18n.get("Are you sure you want to reset the conversation?")}
2080
- </Text>
2081
- <Group justify="flex-end" mt="md">
2082
- <Button
2083
- variant="default"
2084
- onClick={cancelReset}
2085
- data-ai-kit-no-button
2086
- >
2087
- {I18n.get("No")}
2088
- </Button>
2089
- <Button
2090
- color="var(--ai-kit-color-danger, red)"
2091
- onClick={confirmReset}
2092
- disabled={!hasMessages && !isChatBusy}
2093
- data-ai-kit-yes-button
2094
- >
2095
- {I18n.get("Yes")}
2096
- </Button>
2097
- </Group>
2098
- </Modal>
2099
-
2100
- <Group>
2101
- <Textarea
2102
- className="ai-message"
2103
- ref={questionInputRef}
2104
- placeholder={textareaPlaceholder}
2105
- value={question}
2106
- onChange={(e) => {
2107
- setQuestion(e.target.value);
2108
- // Clear audio when typing
2109
- if (composerAudio) {
2110
- clearComposerAudio();
2111
- }
2112
- }}
2113
- onKeyDown={handleQuestionKeyDown}
2114
- rows={3}
2115
- disabled={recording || !!composerAudio}
2116
- />
2117
- </Group>
2118
-
2119
- {/* Audio level indicator when recording */}
2120
- {USE_AUDIO && recording && (
2121
- <Stack gap="xs" mt="xs">
2122
- <Text size="xs" c="dimmed">
2123
- <em>{I18n.get("Recording...")}</em>
2124
- </Text>
2125
- <div
2126
- style={{
2127
- width: "100%",
2128
- height: "4px",
2129
- backgroundColor: "var(--mantine-color-gray-3)",
2130
- borderRadius: "2px",
2131
- overflow: "hidden",
2132
- }}
2133
- >
2134
- <div
2135
- style={{
2136
- width: `${audioLevel}%`,
2137
- height: "100%",
2138
- backgroundColor: "var(--mantine-color-red-6)",
2139
- transition: "width 0.1s ease",
2140
- }}
2141
- />
2142
- </div>
2143
- </Stack>
2144
- )}
2145
-
2146
- {/* Audio playback when recorded */}
2147
- {USE_AUDIO && composerAudio && !recording && (
2148
- <Stack gap="xs" mt="xs">
2149
- <Text size="xs" c="dimmed">
2150
- <em>
2151
- {I18n.get("Audio recorded")} (
2152
- {Math.round(composerAudio.duration)}s)
2153
- </em>
2154
- </Text>
2155
- <audio
2156
- className="ai-kit-audio-player"
2157
- controls
2158
- src={composerAudio.objectUrl}
2159
- />
2160
- </Stack>
2161
- )}
2162
-
2163
- <Group className="ai-actions" justify="space-between" w="100%">
2164
- <Group justify="flex-start">
2165
- <Button
2166
- variant="light"
2167
- leftSection={<IconTrash size={18} />}
2168
- onClick={handleResetClick}
2169
- disabled={!hasMessages && !isChatBusy}
2170
- data-ai-kit-reset-button
2171
- >
2172
- {I18n.get(labels.resetLabel)}
2173
- </Button>
2174
- </Group>
2175
-
2176
- <Group justify="flex-end">
2177
- {/* Microphone button */}
2178
- {USE_AUDIO && (
2179
- <>
2180
- {composerAudio ? (
2181
- <Button
2182
- variant="outline"
2183
- leftSection={<IconX size={18} />}
2184
- onClick={clearComposerAudio}
2185
- disabled={isChatBusy}
2186
- title={I18n.get("Clear audio")}
2187
- data-ai-kit-clear-audio-button
2188
- >
2189
- {I18n.get("Clear")}
2190
- </Button>
2191
- ) : (
2192
- <Button
2193
- variant="outline"
2194
- leftSection={<IconMicrophone size={18} />}
2195
- onClick={recording ? stopRecording : startRecording}
2196
- disabled={isChatBusy}
2197
- title={
2198
- recording
2199
- ? I18n.get("Stop recording")
2200
- : I18n.get("Record audio")
2201
- }
2202
- color={recording ? "red" : undefined}
2203
- data-ai-kit-microphone-button
2204
- >
2205
- {recording ? I18n.get("Stop") : I18n.get("Record")}
2206
- </Button>
2207
- )}
2208
- </>
2209
- )}
2210
-
2211
- {imageAttachmentsEnabled && (
2212
- <>
2213
- <Button
2214
- variant="outline"
2215
- leftSection={<IconPaperclip size={18} />}
2216
- onClick={() => fileInputRef.current?.click()}
2217
- disabled={
2218
- composerImages.length >= resolvedMaxImages ||
2219
- isChatBusy ||
2220
- recording ||
2221
- !!composerAudio
2222
- }
2223
- title={I18n.get(labels.addImageLabel)}
2224
- data-ai-kit-add-image-button
2225
- >
2226
- {I18n.get(labels.addLabel)}
2227
- </Button>
2228
- <Input
2229
- ref={fileInputRef}
2230
- type="file"
2231
- accept="image/png,image/jpeg,image/gif,image/webp"
2232
- style={{ display: "none" }}
2233
- multiple
2234
- onChange={onPickImages}
2235
- />
2236
- </>
2237
- )}
2238
-
2239
- {/* Send -> Cancel switch (ChatGPT-like) */}
2240
- <Button
2241
- leftSection={sendOrCancelIcon}
2242
- variant="filled"
2243
- onClick={onSendOrCancel}
2244
- disabled={!isChatBusy && !canSend}
2245
- data-ai-kit-send-button
2246
- >
2247
- {sendOrCancelLabel}
2248
- </Button>
2249
- </Group>
2250
- </Group>
2251
-
2252
- {composerPreviews.length > 0 && (
2253
- <Group className="ai-thumbs" mt="xs" gap="xs">
2254
- {composerPreviews.map(({ url, title }, i) => (
2255
- <div
2256
- key={composerImages[i]?.id ?? i}
2257
- role="button"
2258
- tabIndex={0}
2259
- className="thumb"
2260
- style={{
2261
- backgroundImage: url ? `url(${url})` : undefined,
2262
- backgroundSize: "cover",
2263
- backgroundPosition: "center",
2264
- backgroundRepeat: "no-repeat",
2265
- overflow: "visible",
2266
- }}
2267
- aria-label={title || I18n.get("View image")}
2268
- onClick={() => openAttachmentPreview(url, title)}
2269
- onKeyDown={(evt) => {
2270
- if (evt.key === "Enter" || evt.key === " ") {
2271
- evt.preventDefault();
2272
- openAttachmentPreview(url, title);
2273
- }
2274
- }}
2275
- >
2276
- <Button
2277
- variant="white"
2278
- onClick={(evt) => {
2279
- evt.stopPropagation();
2280
- removeImage(i);
2281
- }}
2282
- aria-label={I18n.get(labels.removeImageLabel)}
2283
- mt="-xs"
2284
- mr="-xs"
2285
- size="xs"
2286
- p={0}
2287
- className="remove-image-button"
2288
- title={I18n.get(labels.removeImageLabel)}
2289
- data-ai-kit-remove-image-button
2290
- >
2291
- X
2292
- </Button>
2293
- </div>
2294
- ))}
2295
- </Group>
2296
- )}
2297
- </Stack>
2298
- </div>
2299
- </Modal.Root>
2300
- )}
2301
-
2302
- <Modal
2303
- opened={!!previewAttachment}
2304
- onClose={closeAttachmentPreview}
2305
- centered
2306
- size="auto"
2307
- title={previewAttachment?.title || I18n.get("Image preview")}
2308
- >
2309
- {previewAttachment && (
2310
- <img
2311
- src={previewAttachment.url}
2312
- alt={previewAttachment.title || I18n.get("Image preview")}
2313
- style={{ maxWidth: "100%", maxHeight: "70vh" }}
2314
- />
2315
- )}
2316
- </Modal>
2317
- </Group>
2318
- );
2319
- };
2320
-
2321
- export const AiChatbot = withAiKitShell(AiChatbotBase, {
2322
- showOpenButton: true,
2323
- variation: "modal",
2324
- overlayWholeComponent: true,
2325
- });