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