@terryavg/neptune-ai-chatbot 1.0.2 → 1.0.3

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/README.md CHANGED
@@ -34,6 +34,7 @@ function App() {
34
34
  streamingText="AI is thinking..."
35
35
  welcomeMessagePrimary="Welcome!"
36
36
  welcomeMessageSecondary="How can I assist you today?"
37
+ welcomeIcon="local path to your icon"
37
38
  />
38
39
  );
39
40
  }
@@ -72,7 +73,6 @@ All customization options are available through props with full TypeScript suppo
72
73
  | `headerBackgroundColorDark` | `string` | `"#1F1F1F"` | Background color for the header (dark mode) |
73
74
  | `vectorColor` | `string` | `"#9333EA"` | Base color for vector search results (light mode) - automatically generates variations |
74
75
  | `vectorColorDark` | `string` | `"#A855F7"` | Base color for vector search results (dark mode) - automatically generates variations |
75
- | `debug` | `boolean` | `false` | Enable debug mode for console logs |
76
76
  | `localDebug` | `LocalDebugConfig` | - | Configuration for local development (see below) |
77
77
  | `onToolStart` | `(metadata: any) => void` | - | Callback fired when a tool starts executing during streaming |
78
78
  | `onToolInput` | `(metadata: any) => void` | - | Callback fired when tool input is available during streaming |
@@ -128,24 +128,4 @@ The `localDebug` prop is used when the component runs **outside of a Neptune env
128
128
  baseUrl: "http://localhost:3000"
129
129
  }}
130
130
  />
131
- ```
132
-
133
- The `localDebug` object includes:
134
- - `username` - Username for local authentication
135
- - `password` - Password for local authentication
136
- - `baseUrl` - Base URL for the local API server
137
-
138
- ## Features
139
-
140
- - 🎨 **Fully Customizable** - Theme colors, text, and UI elements
141
- - 🌓 **Dark Mode Support** - Built-in light and dark theme support
142
- - 📎 **Multiple File Attachments** - Upload multiple images and PDFs
143
- - ⚡ **Real-time Streaming** - See AI responses as they're generated
144
- - 💬 **Conversation History** - Automatic conversation management and persistence
145
- - 📱 **Responsive Design** - Works seamlessly on desktop and mobile
146
- - ♿ **Accessible** - ARIA labels and keyboard navigation support
147
- - 🔧 **TypeScript** - Full type safety with comprehensive JSDoc documentation
148
-
149
- ## License
150
-
151
- MIT
131
+ ```
@@ -0,0 +1,510 @@
1
+ import {
2
+ chatClient
3
+ } from "./chunk-VONUV37R.mjs";
4
+ import "./chunk-FWCSY2DS.mjs";
5
+
6
+ // app/components/chat-input.tsx
7
+ import {
8
+ useState,
9
+ useRef,
10
+ useEffect
11
+ } from "react";
12
+ import { Send, Paperclip, X, FileText } from "lucide-react";
13
+ import { jsx, jsxs } from "react/jsx-runtime";
14
+ function ChatInput({
15
+ conversationId,
16
+ agentId,
17
+ onAddUserMessage,
18
+ onStreamStart,
19
+ onStreamUpdate,
20
+ onStreamEnd,
21
+ onError,
22
+ messages,
23
+ isStreaming,
24
+ disabled = false,
25
+ onThreadCreated,
26
+ onToolExecutionStart,
27
+ onToolExecutionEnd,
28
+ onToolStart,
29
+ onToolInput,
30
+ onToolFinish,
31
+ onChunk,
32
+ onFinish,
33
+ accentColor = "#8B7FD9",
34
+ streaming = true,
35
+ theme = "light",
36
+ inputBackgroundColor = "#ffffff",
37
+ inputBackgroundColorDark = "#303030"
38
+ }) {
39
+ const [input, setInput] = useState("");
40
+ const [isSubmitting, setIsSubmitting] = useState(false);
41
+ const [attachments, setAttachments] = useState([]);
42
+ const textareaRef = useRef(null);
43
+ const fileInputRef = useRef(null);
44
+ const abortControllerRef = useRef(null);
45
+ useEffect(() => {
46
+ if (textareaRef.current) {
47
+ textareaRef.current.style.height = "inherit";
48
+ textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`;
49
+ }
50
+ }, [input]);
51
+ const handleFileChange = async (e) => {
52
+ const files = e.target.files;
53
+ if (!files || files.length === 0) return;
54
+ const newAttachments = [];
55
+ for (let i = 0; i < files.length; i++) {
56
+ const file = files[i];
57
+ const isImage = file.type.startsWith("image/");
58
+ const isPdf = file.type === "application/pdf";
59
+ if (!isImage && !isPdf) {
60
+ onError({
61
+ title: "Unsupported File Type",
62
+ message: `File "${file.name}" is not supported. Only images (PNG, JPG, GIF, etc.) and PDF files are supported at this time.`
63
+ });
64
+ continue;
65
+ }
66
+ if (file.size > 10 * 1024 * 1024) {
67
+ onError({
68
+ title: "File Too Large",
69
+ message: `File "${file.name}" exceeds the 10MB size limit. Please choose a smaller file.`
70
+ });
71
+ continue;
72
+ }
73
+ try {
74
+ const base64data = await fileToBase64(file);
75
+ if (isImage) {
76
+ newAttachments.push({
77
+ name: file.name,
78
+ type: "image",
79
+ mediaType: file.type,
80
+ data: base64data,
81
+ image: base64data
82
+ });
83
+ } else {
84
+ newAttachments.push({
85
+ name: file.name,
86
+ type: "file",
87
+ mediaType: file.type,
88
+ data: base64data,
89
+ filename: file.name
90
+ });
91
+ }
92
+ } catch (error) {
93
+ console.error("File processing error:", error);
94
+ onError({
95
+ title: "File Processing Error",
96
+ message: `There was an unexpected error processing "${file.name}". Please try again.`
97
+ });
98
+ }
99
+ }
100
+ setAttachments((prev) => [...prev, ...newAttachments]);
101
+ };
102
+ const handlePaste = async (e) => {
103
+ var _a;
104
+ const clipboardItems = (_a = e.clipboardData) == null ? void 0 : _a.items;
105
+ if (!clipboardItems) return;
106
+ for (let i = 0; i < clipboardItems.length; i++) {
107
+ const item = clipboardItems[i];
108
+ const trimmedItemType = item.type.trim();
109
+ if (trimmedItemType.includes("image")) {
110
+ e.preventDefault();
111
+ const file = item.getAsFile();
112
+ if (!file) continue;
113
+ if (file.size > 5 * 1024 * 1024) {
114
+ onError({
115
+ title: "Image Too Large",
116
+ message: "The pasted image exceeds the 5MB size limit. Please paste a smaller image."
117
+ });
118
+ return;
119
+ }
120
+ try {
121
+ const base64data = await fileToBase64(file);
122
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
123
+ const filename = `pasted-image-${timestamp}.${trimmedItemType.split("/")[1] || "png"}`;
124
+ setAttachments((prev) => [...prev, {
125
+ name: filename,
126
+ type: "image",
127
+ mediaType: trimmedItemType,
128
+ data: base64data,
129
+ image: base64data
130
+ }]);
131
+ return;
132
+ } catch (error) {
133
+ console.error("Error processing pasted image:", error);
134
+ onError({
135
+ title: "Image Processing Error",
136
+ message: "There was an unexpected error processing the pasted image. Please try again."
137
+ });
138
+ }
139
+ }
140
+ }
141
+ };
142
+ const fileToBase64 = (file) => {
143
+ return new Promise((resolve, reject) => {
144
+ const reader = new FileReader();
145
+ reader.readAsDataURL(file);
146
+ reader.onload = () => {
147
+ if (typeof reader.result === "string") {
148
+ resolve(reader.result);
149
+ } else {
150
+ reject(new Error("Failed to convert file to base64"));
151
+ }
152
+ };
153
+ reader.onerror = (error) => reject(error);
154
+ });
155
+ };
156
+ const clearAttachments = () => {
157
+ setAttachments([]);
158
+ if (fileInputRef.current) {
159
+ fileInputRef.current.value = "";
160
+ }
161
+ };
162
+ const removeAttachment = (index) => {
163
+ setAttachments((prev) => prev.filter((_, i) => i !== index));
164
+ };
165
+ const handleAttachmentClick = () => {
166
+ var _a;
167
+ (_a = fileInputRef.current) == null ? void 0 : _a.click();
168
+ };
169
+ const handleSubmit = async (e) => {
170
+ e.preventDefault();
171
+ if (!input.trim() && attachments.length === 0 || isSubmitting || disabled) return;
172
+ if (!agentId) {
173
+ onError({
174
+ title: "Missing Configuration",
175
+ message: "Assistant ID or Agent ID is not set. Please ensure it is provided in the URL (e.g., ?assistantId=your-id or ?agentId=your-id)."
176
+ });
177
+ setIsSubmitting(false);
178
+ return;
179
+ }
180
+ let accumulatedResponse = "";
181
+ let errorOccurred = false;
182
+ let finalErrorMessage = "";
183
+ let metadata = null;
184
+ try {
185
+ setIsSubmitting(true);
186
+ const abortController = new AbortController();
187
+ abortControllerRef.current = abortController;
188
+ const userMessageText = input.trim();
189
+ let messageContentParts = [];
190
+ if (userMessageText) {
191
+ messageContentParts.push({
192
+ type: "text",
193
+ text: userMessageText
194
+ });
195
+ }
196
+ attachments.forEach((attachment) => {
197
+ if (attachment.type === "image") {
198
+ messageContentParts.push({
199
+ type: "image",
200
+ image: attachment.image || attachment.data,
201
+ mediaType: attachment.mediaType
202
+ });
203
+ } else {
204
+ messageContentParts.push({
205
+ type: "file",
206
+ data: attachment.data,
207
+ mediaType: attachment.mediaType,
208
+ filename: attachment.filename || attachment.name
209
+ });
210
+ }
211
+ });
212
+ const finalMessageContent = messageContentParts.length === 1 && messageContentParts[0].type === "text" && attachments.length === 0 ? messageContentParts[0].text : messageContentParts;
213
+ setInput("");
214
+ clearAttachments();
215
+ const isTemporary = conversationId.startsWith("temp-");
216
+ if (!isTemporary) {
217
+ onAddUserMessage({
218
+ id: `local-user-${Date.now()}`,
219
+ content: finalMessageContent,
220
+ role: "user",
221
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
222
+ });
223
+ }
224
+ onStreamStart();
225
+ const { stream, threadId, conversation } = await chatClient.messages.sendMessage(
226
+ agentId,
227
+ conversationId,
228
+ finalMessageContent,
229
+ messages,
230
+ abortController.signal,
231
+ void 0,
232
+ // stepData
233
+ conversationId.startsWith("temp-"),
234
+ // isTemporary - detect by ID prefix
235
+ streaming
236
+ // streaming mode
237
+ );
238
+ if (threadId && threadId !== conversationId && onThreadCreated) {
239
+ onThreadCreated(conversationId, threadId, conversation);
240
+ }
241
+ if (!streaming) {
242
+ const reader = stream.getReader();
243
+ const decoder = new TextDecoder();
244
+ let responseText = "";
245
+ while (true) {
246
+ const { done, value } = await reader.read();
247
+ if (done) break;
248
+ responseText += decoder.decode(value, { stream: true });
249
+ }
250
+ const response = JSON.parse(responseText);
251
+ const outputText = response.output || "";
252
+ accumulatedResponse = outputText;
253
+ onStreamUpdate(outputText);
254
+ metadata = response;
255
+ } else {
256
+ const reader = stream.getReader();
257
+ const decoder = new TextDecoder();
258
+ let done = false;
259
+ let buffer = "";
260
+ let isToolExecuting = false;
261
+ let currentToolName = "";
262
+ while (!done) {
263
+ try {
264
+ if (abortController.signal.aborted) {
265
+ break;
266
+ }
267
+ const { value, done: readerDone } = await reader.read();
268
+ done = readerDone;
269
+ if (value) {
270
+ buffer += decoder.decode(value, { stream: true });
271
+ const lines = buffer.split("\n");
272
+ buffer = lines.pop() || "";
273
+ for (const line of lines) {
274
+ if (!line.trim()) continue;
275
+ if (line.startsWith("data: ")) {
276
+ const jsonString = line.substring(6);
277
+ if (jsonString === "[DONE]") {
278
+ done = true;
279
+ break;
280
+ }
281
+ try {
282
+ const event = JSON.parse(jsonString);
283
+ switch (event.type) {
284
+ case "start-step":
285
+ break;
286
+ case "tool-input-start":
287
+ currentToolName = event.toolName || "Unknown Tool";
288
+ isToolExecuting = true;
289
+ if (onToolExecutionStart) {
290
+ onToolExecutionStart(
291
+ currentToolName
292
+ );
293
+ }
294
+ if (onToolStart) {
295
+ onToolStart(event);
296
+ }
297
+ break;
298
+ case "tool-input-delta":
299
+ break;
300
+ case "tool-input-available":
301
+ if (onToolInput) {
302
+ onToolInput(event);
303
+ }
304
+ break;
305
+ case "tool-output-available":
306
+ if (isToolExecuting && onToolExecutionEnd) {
307
+ onToolExecutionEnd();
308
+ }
309
+ isToolExecuting = false;
310
+ currentToolName = "";
311
+ if (onToolFinish) {
312
+ onToolFinish(event);
313
+ }
314
+ break;
315
+ case "finish-step":
316
+ if (isToolExecuting && onToolExecutionEnd) {
317
+ onToolExecutionEnd();
318
+ }
319
+ isToolExecuting = false;
320
+ currentToolName = "";
321
+ break;
322
+ case "text-delta":
323
+ accumulatedResponse += event.delta;
324
+ onStreamUpdate(event.delta);
325
+ if (onChunk) {
326
+ onChunk(event.delta);
327
+ }
328
+ break;
329
+ case "data-finish-result":
330
+ metadata = event.data;
331
+ if (onFinish) {
332
+ onFinish(event.data);
333
+ }
334
+ break;
335
+ case "error":
336
+ throw new Error(
337
+ event.errorText || "Stream error occurred"
338
+ );
339
+ // Ignore other event types
340
+ default:
341
+ break;
342
+ }
343
+ } catch (parseError) {
344
+ console.error(
345
+ "Error parsing SSE event:",
346
+ parseError
347
+ );
348
+ }
349
+ }
350
+ }
351
+ }
352
+ } catch (streamReadError) {
353
+ console.error(
354
+ "Error reading stream chunk:",
355
+ streamReadError
356
+ );
357
+ errorOccurred = true;
358
+ finalErrorMessage = "An error occurred while reading the response.";
359
+ onError({
360
+ title: "Stream Error",
361
+ message: finalErrorMessage
362
+ });
363
+ done = true;
364
+ }
365
+ }
366
+ }
367
+ } catch (error) {
368
+ console.error("Error during chat submission:", error);
369
+ if ((error == null ? void 0 : error.name) === "AbortError") {
370
+ return;
371
+ }
372
+ errorOccurred = true;
373
+ let title = "Request Error";
374
+ let localMessage = "An unexpected error occurred. Please try again.";
375
+ if (error == null ? void 0 : error.isConfigurationError) {
376
+ title = "Configuration Error";
377
+ localMessage = error.message || "Assistant ID is missing or invalid.";
378
+ } else if (error == null ? void 0 : error.isApiError) {
379
+ title = `API Error (${error.status})`;
380
+ localMessage = error.message || error.statusText || "An error occurred processing your request.";
381
+ } else if (error == null ? void 0 : error.isNetworkError) {
382
+ title = "Network Error";
383
+ localMessage = error.message || "Failed to connect to the server.";
384
+ } else if (error instanceof Error) {
385
+ localMessage = error.message;
386
+ }
387
+ finalErrorMessage = localMessage;
388
+ onError({ title, message: finalErrorMessage });
389
+ } finally {
390
+ onStreamEnd(
391
+ errorOccurred ? finalErrorMessage : accumulatedResponse,
392
+ metadata
393
+ );
394
+ setIsSubmitting(false);
395
+ abortControllerRef.current = null;
396
+ }
397
+ };
398
+ useEffect(() => {
399
+ if (!isStreaming && abortControllerRef.current) {
400
+ abortControllerRef.current.abort();
401
+ abortControllerRef.current = null;
402
+ }
403
+ }, [isStreaming]);
404
+ const handleKeyDown = (e) => {
405
+ if (e.key === "Enter" && !e.shiftKey) {
406
+ e.preventDefault();
407
+ handleSubmit(e);
408
+ }
409
+ };
410
+ return /* @__PURE__ */ jsxs(
411
+ "form",
412
+ {
413
+ onSubmit: handleSubmit,
414
+ className: "chat-input relative px-2 pt-3 pb-3 flex w-full items-center border rounded-2xl shadow-sm overflow-hidden",
415
+ style: {
416
+ borderColor: accentColor,
417
+ backgroundColor: theme === "dark" ? inputBackgroundColorDark : inputBackgroundColor
418
+ },
419
+ children: [
420
+ attachments.length > 0 && /* @__PURE__ */ jsx("div", { className: "absolute top-0 left-0 right-0 bg-gray-100 dark:bg-gray-700 p-2 flex flex-wrap gap-2 max-h-24 overflow-y-auto", children: attachments.map((att, index) => {
421
+ const isImage = att.type === "image";
422
+ return /* @__PURE__ */ jsxs(
423
+ "div",
424
+ {
425
+ className: "flex items-center space-x-2 bg-white dark:bg-gray-800 rounded-lg px-2 py-1 border border-gray-200 dark:border-gray-600",
426
+ children: [
427
+ isImage ? /* @__PURE__ */ jsx("div", { className: "w-6 h-6 rounded overflow-hidden bg-white", children: /* @__PURE__ */ jsx(
428
+ "img",
429
+ {
430
+ src: att.image || att.data,
431
+ alt: "Preview",
432
+ className: "w-full h-full object-cover"
433
+ }
434
+ ) }) : /* @__PURE__ */ jsx(
435
+ FileText,
436
+ {
437
+ size: 16,
438
+ className: "text-gray-600 dark:text-gray-300"
439
+ }
440
+ ),
441
+ /* @__PURE__ */ jsx("span", { className: "text-xs truncate max-w-[120px]", children: att.name }),
442
+ /* @__PURE__ */ jsx(
443
+ "button",
444
+ {
445
+ type: "button",
446
+ onClick: () => removeAttachment(index),
447
+ className: "text-gray-500 hover:text-red-600 dark:text-gray-400 dark:hover:text-red-400",
448
+ children: /* @__PURE__ */ jsx(X, { size: 14 })
449
+ }
450
+ )
451
+ ]
452
+ },
453
+ index
454
+ );
455
+ }) }),
456
+ /* @__PURE__ */ jsx(
457
+ "textarea",
458
+ {
459
+ ref: textareaRef,
460
+ value: input,
461
+ onChange: (e) => setInput(e.target.value),
462
+ onKeyDown: handleKeyDown,
463
+ onPaste: handlePaste,
464
+ placeholder: disabled ? "Please complete the form above..." : "Type a message...",
465
+ className: `max-h-32 min-h-8 w-full resize-none bg-transparent py-2 pl-6 pr-16 focus:outline-none text-base ${attachments.length > 0 ? "mt-28" : ""} ${disabled ? "opacity-50 cursor-not-allowed" : ""}`,
466
+ rows: 1,
467
+ disabled: isSubmitting || disabled
468
+ }
469
+ ),
470
+ /* @__PURE__ */ jsx(
471
+ "input",
472
+ {
473
+ type: "file",
474
+ ref: fileInputRef,
475
+ onChange: handleFileChange,
476
+ accept: "application/pdf,image/*",
477
+ multiple: true,
478
+ className: "hidden"
479
+ }
480
+ ),
481
+ /* @__PURE__ */ jsx(
482
+ "button",
483
+ {
484
+ type: "button",
485
+ onClick: handleAttachmentClick,
486
+ disabled: isSubmitting || isStreaming || disabled,
487
+ className: "p-2 absolute bottom-3 right-12 rounded-full enabled:hover:bg-gray-300 enabled:dark:hover:bg-gray-700 disabled:opacity-40",
488
+ style: { color: accentColor },
489
+ "aria-label": "Attach file or image",
490
+ children: /* @__PURE__ */ jsx(Paperclip, { size: 20 })
491
+ }
492
+ ),
493
+ /* @__PURE__ */ jsx(
494
+ "button",
495
+ {
496
+ type: "submit",
497
+ disabled: !input.trim() && attachments.length === 0 || isSubmitting || disabled,
498
+ className: "ml-2 p-2 absolute bottom-3 right-3 rounded-full enabled:hover:bg-gray-300 enabled:dark:hover:bg-gray-700 disabled:opacity-40",
499
+ style: { color: accentColor },
500
+ "aria-label": "Send message",
501
+ children: /* @__PURE__ */ jsx(Send, { size: 20 })
502
+ }
503
+ )
504
+ ]
505
+ }
506
+ );
507
+ }
508
+ export {
509
+ ChatInput as default
510
+ };