forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChat.tsx
More file actions
1040 lines (934 loc) · 29.5 KB
/
Copy pathChat.tsx
File metadata and controls
1040 lines (934 loc) · 29.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* <br/>
* <img src="https://cdn.copilotkit.ai/docs/copilotkit/images/CopilotChat.gif" width="500" />
*
* A chatbot panel component for the CopilotKit framework. The component allows for a high degree
* of customization through various props and custom CSS.
*
* ## Install Dependencies
*
* This component is part of the [@copilotkit/react-ui](https://npmjs.com/package/@copilotkit/react-ui) package.
*
* ```shell npm2yarn \"@copilotkit/react-ui"\
* npm install @copilotkit/react-core @copilotkit/react-ui
* ```
*
* ## Usage
*
* ```tsx
* import { CopilotChat } from "@copilotkit/react-ui";
* import "@copilotkit/react-ui/styles.css";
*
* <CopilotChat
* labels={{
* title: "Your Assistant",
* initial: "Hi! 👋 How can I assist you today?",
* }}
* />
* ```
*
* ### With Observability Hooks
*
* To monitor user interactions, provide the `observabilityHooks` prop.
* **Note:** This requires a `publicApiKey` in the `<CopilotKit>` provider.
*
* ```tsx
* <CopilotKit publicApiKey="YOUR_PUBLIC_API_KEY">
* <CopilotChat
* observabilityHooks={{
* onMessageSent: (message) => {
* console.log("Message sent:", message);
* },
* }}
* />
* </CopilotKit>
* ```
*
* ### Look & Feel
*
* By default, CopilotKit components do not have any styles. You can import CopilotKit's stylesheet at the root of your project:
* ```tsx title="YourRootComponent.tsx"
* ...
* import "@copilotkit/react-ui/styles.css"; // [!code highlight]
*
* export function YourRootComponent() {
* return (
* <CopilotKit>
* ...
* </CopilotKit>
* );
* }
* ```
* For more information about how to customize the styles, check out the [Customize Look & Feel](/guides/custom-look-and-feel/customize-built-in-ui-components) guide.
*/
import {
ChatContext,
ChatContextProvider,
CopilotChatIcons,
CopilotChatLabels,
} from "./ChatContext";
import { Messages as DefaultMessages } from "./Messages";
import { Input as DefaultInput } from "./Input";
import { RenderMessage as DefaultRenderMessage } from "./messages/RenderMessage";
import { AssistantMessage as DefaultAssistantMessage } from "./messages/AssistantMessage";
import { UserMessage as DefaultUserMessage } from "./messages/UserMessage";
import { ImageRenderer as DefaultImageRenderer } from "./messages/ImageRenderer";
import React, { useEffect, useRef, useState, useCallback } from "react";
import {
SystemMessageFunction,
useCopilotContext,
useCopilotChatInternal,
type OnStopGeneration,
type OnReloadMessages,
type ChatSuggestions,
} from "@copilotkit/react-core";
import {
CopilotKitError,
CopilotKitErrorCode,
CopilotErrorEvent,
Message,
Severity,
ErrorVisibility,
styledConsole,
CopilotErrorHandler,
randomUUID,
} from "@copilotkit/shared";
import {
AssistantMessageProps,
ChatError,
ComponentsMap,
CopilotObservabilityHooks,
ErrorMessageProps,
ImageRendererProps,
InputProps,
MessagesProps,
RenderMessageProps,
RenderSuggestionsListProps,
UserMessageProps,
} from "./props";
import { AttachmentQueue } from "./AttachmentQueue";
import type { Attachment, AttachmentsConfig } from "./props";
import {
getModalityFromMimeType,
exceedsMaxSize,
readFileAsBase64,
generateVideoThumbnail,
matchesAcceptFilter,
formatFileSize,
deprecationWarning,
} from "./attachment-utils";
import type { InputContent } from "@copilotkit/shared";
import { Suggestions as DefaultRenderSuggestionsList } from "./Suggestions";
/**
* Props for CopilotChat component.
*/
export interface CopilotChatProps {
/**
* Custom instructions to be added to the system message. Use this property to
* provide additional context or guidance to the language model, influencing
* its responses. These instructions can include specific directions,
* preferences, or criteria that the model should consider when generating
* its output, thereby tailoring the conversation more precisely to the
* user's needs or the application's requirements.
*/
instructions?: string;
/**
* Controls the behavior of suggestions in the chat interface.
*
* `auto` (default) - Suggestions are generated automatically:
* - When the chat is first opened (empty state)
* - After each message exchange completes
* - Uses configuration from `useCopilotChatSuggestions` hooks
*
* `manual` - Suggestions are controlled programmatically:
* - Use `setSuggestions()` to set custom suggestions
* - Use `generateSuggestions()` to trigger AI generation
* - Access via `useCopilotChat` hook
*
* `SuggestionItem[]` - Static suggestions array:
* - Always shows the same suggestions
* - No AI generation involved
*/
suggestions?: ChatSuggestions;
/**
* A callback that gets called when the in progress state changes.
*/
onInProgress?: (inProgress: boolean) => void;
/**
* A callback that gets called when a new message it submitted.
*/
onSubmitMessage?: (message: string) => void | Promise<void>;
/**
* A custom stop generation function.
*/
onStopGeneration?: OnStopGeneration;
/**
* A custom reload messages function.
*/
onReloadMessages?: OnReloadMessages;
/**
* A callback function to regenerate the assistant's response
*/
onRegenerate?: (messageId: string) => void;
/**
* A callback function when the message is copied
*/
onCopy?: (message: string) => void;
/**
* A callback function for thumbs up feedback
*/
onThumbsUp?: (message: Message) => void;
/**
* A callback function for thumbs down feedback
*/
onThumbsDown?: (message: Message) => void;
/**
* A list of markdown components to render in assistant message.
* Useful when you want to render custom elements in the message (e.g a reference tag element)
*/
markdownTagRenderers?: ComponentsMap;
/**
* Icons can be used to set custom icons for the chat window.
*/
icons?: CopilotChatIcons;
/**
* Labels can be used to set custom labels for the chat window.
*/
labels?: CopilotChatLabels;
/**
* @deprecated Use `attachments={{ enabled: true }}` instead.
* `imageUploadsEnabled` only supports images. The new `attachments` prop supports
* images, audio, video, and documents.
* See https://docs.copilotkit.ai/migration-guides/migrate-attachments
* @since 1.56.0
*
* Enable image upload button (image inputs only supported on some models)
*/
imageUploadsEnabled?: boolean;
/**
* @deprecated Use `attachments={{ enabled: true, accept: "..." }}` instead.
* The `accept` field on the `attachments` prop replaces `inputFileAccept`.
* See https://docs.copilotkit.ai/migration-guides/migrate-attachments
* @since 1.56.0
*
* The 'accept' attribute for the file input used for image uploads.
* Defaults to "image/*".
*/
inputFileAccept?: string;
/**
* Configuration for file attachments in the chat input.
* Enables users to attach images, audio, video, and documents.
*
* @example
* ```tsx
* <CopilotChat
* attachments={{
* enabled: true,
* accept: "image/*,application/pdf",
* maxSize: 10 * 1024 * 1024, // 10MB
* onUpload: async (file) => {
* const url = await uploadToS3(file);
* return { url, mimeType: file.type };
* },
* }}
* />
* ```
*/
attachments?: AttachmentsConfig;
/**
* A function that takes in context string and instructions and returns
* the system message to include in the chat request.
* Use this to completely override the system message, when providing
* instructions is not enough.
*/
makeSystemMessage?: SystemMessageFunction;
/**
* Disables inclusion of CopilotKit’s default system message. When true, no system message is sent (this also suppresses any custom message from <code>makeSystemMessage</code>).
*/
disableSystemMessage?: boolean;
/**
* A custom assistant message component to use instead of the default.
*/
AssistantMessage?: React.ComponentType<AssistantMessageProps>;
/**
* A custom user message component to use instead of the default.
*/
UserMessage?: React.ComponentType<UserMessageProps>;
/**
* A custom error message component to use instead of the default.
*/
ErrorMessage?: React.ComponentType<ErrorMessageProps>;
/**
* A custom Messages component to use instead of the default.
*/
Messages?: React.ComponentType<MessagesProps>;
/**
* @deprecated - use RenderMessage instead
*/
RenderTextMessage?: React.ComponentType<RenderMessageProps>;
/**
* @deprecated - use RenderMessage instead
*/
RenderActionExecutionMessage?: React.ComponentType<RenderMessageProps>;
/**
* @deprecated - use RenderMessage instead
*/
RenderAgentStateMessage?: React.ComponentType<RenderMessageProps>;
/**
* @deprecated - use RenderMessage instead
*/
RenderResultMessage?: React.ComponentType<RenderMessageProps>;
/**
* @deprecated - use RenderMessage instead
*/
RenderImageMessage?: React.ComponentType<RenderMessageProps>;
/**
* A custom RenderMessage component to use instead of the default.
*
* **Warning**: This is a break-glass solution to allow for custom
* rendering of messages. You are most likely looking to swap out
* the AssistantMessage and UserMessage components instead which
* are also props.
*/
RenderMessage?: React.ComponentType<RenderMessageProps>;
/**
* A custom suggestions list component to use instead of the default.
*/
RenderSuggestionsList?: React.ComponentType<RenderSuggestionsListProps>;
/**
* A custom Input component to use instead of the default.
*/
Input?: React.ComponentType<InputProps>;
/**
* @deprecated Use the v2 `CopilotChat` attachment system instead.
* See https://docs.copilotkit.ai/migration-guides/migrate-attachments
*
* A custom image rendering component to use instead of the default.
*/
ImageRenderer?: React.ComponentType<ImageRendererProps>;
/**
* A class name to apply to the root element.
*/
className?: string;
/**
* Children to render.
*/
children?: React.ReactNode;
hideStopButton?: boolean;
/**
* Event hooks for CopilotKit chat events.
* These hooks only work when publicApiKey is provided.
*/
observabilityHooks?: CopilotObservabilityHooks;
/**
* Custom error renderer for chat-specific errors.
* When provided, errors will be displayed inline within the chat interface.
*/
renderError?: (error: {
message: string;
operation?: string;
timestamp: number;
onDismiss: () => void;
onRetry?: () => void;
}) => React.ReactNode;
/**
* Optional handler for comprehensive debugging and observability.
*/
onError?: CopilotErrorHandler;
}
/**
* @deprecated Use the `Attachment` type from `@copilotkit/react-ui` instead.
* `ImageUpload` only described image payloads. `Attachment` supports images,
* audio, video, and documents.
* See https://docs.copilotkit.ai/migration-guides/migrate-attachments
* @since 1.56.0
*/
export type ImageUpload = {
contentType: string;
bytes: string;
};
export function CopilotChat({
instructions,
suggestions = "auto",
onSubmitMessage,
makeSystemMessage,
disableSystemMessage,
onInProgress,
onStopGeneration,
onReloadMessages,
onRegenerate,
onCopy,
onThumbsUp,
onThumbsDown,
markdownTagRenderers,
Messages = DefaultMessages,
RenderMessage = DefaultRenderMessage,
RenderSuggestionsList = DefaultRenderSuggestionsList,
Input = DefaultInput,
className,
icons,
labels,
AssistantMessage = DefaultAssistantMessage,
UserMessage = DefaultUserMessage,
ImageRenderer = DefaultImageRenderer,
ErrorMessage,
imageUploadsEnabled,
inputFileAccept = "image/*",
attachments,
hideStopButton,
observabilityHooks,
renderError,
onError,
// Legacy props - deprecated
RenderTextMessage,
RenderActionExecutionMessage,
RenderAgentStateMessage,
RenderResultMessage,
RenderImageMessage,
}: CopilotChatProps) {
const {
additionalInstructions,
setChatInstructions,
copilotApiConfig,
setBannerError,
setInternalErrorHandler,
removeInternalErrorHandler,
} = useCopilotContext();
// Destructure stable values to avoid object reference changes
const { publicApiKey, chatApiEndpoint } = copilotApiConfig;
// Resolve attachments config with deprecation bridge
const resolvedAttachments: AttachmentsConfig | undefined = (() => {
if (attachments) return attachments;
if (imageUploadsEnabled) {
deprecationWarning(
"imageUploadsEnabled",
"imageUploadsEnabled is deprecated. Use attachments={{ enabled: true }} instead. " +
"See https://docs.copilotkit.ai/migration-guides/migrate-attachments",
);
return { enabled: true, accept: inputFileAccept || "image/*" };
}
return undefined;
})();
const attachmentsEnabled = resolvedAttachments?.enabled ?? false;
const attachmentsAccept = resolvedAttachments?.accept ?? "*/*";
const attachmentsMaxSize = resolvedAttachments?.maxSize ?? 20 * 1024 * 1024;
const [selectedAttachments, setSelectedAttachments] = useState<Attachment[]>(
[],
);
const [dragOver, setDragOver] = useState(false);
const processFilesRef = useRef<(files: File[]) => Promise<void>>(
async () => {},
);
const [chatError, setChatError] = useState<ChatError | null>(null);
const [messageFeedback, setMessageFeedback] = useState<
Record<string, "thumbsUp" | "thumbsDown">
>({});
const fileInputRef = useRef<HTMLInputElement>(null);
// Helper function to trigger event hooks only if publicApiKey is provided
const triggerObservabilityHook = useCallback(
(hookName: keyof CopilotObservabilityHooks, ...args: any[]) => {
if (publicApiKey && observabilityHooks?.[hookName]) {
(observabilityHooks[hookName] as any)(...args);
}
if (observabilityHooks?.[hookName] && !publicApiKey) {
setBannerError(
new CopilotKitError({
message: "observabilityHooks requires a publicApiKey to function.",
code: CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR,
severity: Severity.CRITICAL,
visibility: ErrorVisibility.BANNER,
}),
);
styledConsole.publicApiKeyRequired("observabilityHooks");
}
},
[publicApiKey, observabilityHooks, setBannerError],
);
// Helper function to trigger chat error and render error UI
const triggerChatError = useCallback(
(error: any, operation: string, originalError?: any) => {
const errorMessage =
error?.message || error?.toString() || "An error occurred";
console.error(
`[CopilotKit] ${operation} error:`,
errorMessage,
originalError ?? error,
);
// Set chat error state for rendering
setChatError({
message: errorMessage,
operation,
timestamp: Date.now(),
});
const errorEvent: CopilotErrorEvent = {
type: "error",
timestamp: Date.now(),
context: {
source: "ui",
request: {
operation,
url: chatApiEndpoint,
startTime: Date.now(),
},
technical: {
environment: "browser",
userAgent:
typeof navigator !== "undefined"
? navigator.userAgent
: undefined,
stackTrace:
originalError instanceof Error ? originalError.stack : undefined,
},
},
error,
};
if (onError) {
onError(errorEvent);
}
// Also trigger observability hook if available
if (publicApiKey && observabilityHooks?.onError) {
observabilityHooks.onError(errorEvent);
}
// Show banner error if onError hook is used without publicApiKey
if (observabilityHooks?.onError && !publicApiKey) {
setBannerError(
new CopilotKitError({
message:
"observabilityHooks.onError requires a publicApiKey to function.",
code: CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR,
severity: Severity.CRITICAL,
visibility: ErrorVisibility.BANNER,
}),
);
styledConsole.publicApiKeyRequired("observabilityHooks.onError");
}
},
[publicApiKey, chatApiEndpoint, observabilityHooks, setBannerError],
);
useEffect(() => {
const id = "chat-component";
setInternalErrorHandler({
[id]: (error: CopilotErrorEvent) => {
if (!error) return;
triggerChatError(error.error, "sendMessage");
},
});
return () => {
// unregister when this instance unmounts
removeInternalErrorHandler?.(id);
};
}, [triggerChatError, setInternalErrorHandler, removeInternalErrorHandler]);
// Clipboard paste handler
useEffect(() => {
if (!attachmentsEnabled) return;
const handlePaste = async (e: ClipboardEvent) => {
const target = e.target as HTMLElement;
if (!target.parentElement?.classList.contains("copilotKitInput")) return;
const items = Array.from(e.clipboardData?.items || []);
const fileItems = items.filter(
(item) =>
item.kind === "file" &&
item.getAsFile() !== null &&
matchesAcceptFilter(item.getAsFile()!, attachmentsAccept),
);
if (fileItems.length === 0) return;
e.preventDefault();
const files = fileItems
.map((item) => item.getAsFile())
.filter((f): f is File => f !== null);
try {
await processFilesRef.current(files);
} catch (error) {
triggerChatError(error, "pasteUpload", error);
}
};
document.addEventListener("paste", handlePaste);
return () => document.removeEventListener("paste", handlePaste);
}, [
attachmentsEnabled,
attachmentsAccept,
attachmentsMaxSize,
triggerChatError,
]);
useEffect(() => {
if (!additionalInstructions?.length) {
setChatInstructions(instructions || "");
return;
}
/*
Will result in a prompt like:
You are a helpful assistant.
Additionally, follow these instructions:
- Do not answer questions about the weather.
- Do not answer questions about the stock market."
*/
const combinedAdditionalInstructions = [
instructions,
"Additionally, follow these instructions:",
...additionalInstructions.map((instruction) => `- ${instruction}`),
];
setChatInstructions(combinedAdditionalInstructions.join("\n") || "");
}, [instructions, additionalInstructions]);
const {
messages,
isLoading,
sendMessage,
stopGeneration,
reloadMessages,
suggestions: currentSuggestions,
isLoadingSuggestions,
agent,
} = useCopilotChatInternal({
suggestions,
onInProgress,
onSubmitMessage,
onStopGeneration,
onReloadMessages,
});
// makeSystemMessage,
// disableSystemMessage,
// Track loading state changes for chat start/stop events
const prevIsLoading = useRef(isLoading);
useEffect(() => {
if (prevIsLoading.current !== isLoading) {
if (isLoading) {
triggerObservabilityHook("onChatStarted");
} else {
triggerObservabilityHook("onChatStopped");
}
prevIsLoading.current = isLoading;
}
}, [isLoading, triggerObservabilityHook]);
// Wrapper for sendMessage to clear selected attachments and build multimodal content
const handleSendMessage = (text: string) => {
const hasUploading = selectedAttachments.some(
(a) => a.status === "uploading",
);
if (hasUploading) {
triggerChatError(
new Error("Attachment(s) still uploading. Please wait."),
"sendMessage",
);
// Return a promise that resolves to a dummy message to satisfy the return type
return Promise.resolve({
id: randomUUID(),
content: text,
role: "user" as const,
} as Message);
}
const currentAttachments = selectedAttachments.filter(
(a) => a.status === "ready",
);
setSelectedAttachments([]);
if (fileInputRef.current) {
fileInputRef.current.value = "";
}
// Trigger message sent event
triggerObservabilityHook("onMessageSent", text);
// Build content: if we have attachments, use InputContent[]
if (currentAttachments.length > 0) {
const contentParts: InputContent[] = [];
if (text.trim()) {
contentParts.push({ type: "text", text });
}
for (const attachment of currentAttachments) {
contentParts.push({
type: attachment.type,
source: attachment.source,
metadata: {
...(attachment.filename ? { filename: attachment.filename } : {}),
...attachment.metadata,
},
} as InputContent);
}
return sendMessage({
id: randomUUID(),
content: contentParts,
role: "user",
});
}
// Plain text message
return sendMessage({
id: randomUUID(),
content: text,
role: "user",
});
};
const chatContext = React.useContext(ChatContext);
const isVisible = chatContext ? chatContext.open : true;
const handleRegenerate = (messageId: string) => {
if (onRegenerate) {
onRegenerate(messageId);
}
// Trigger message regenerated event
triggerObservabilityHook("onMessageRegenerated", messageId);
reloadMessages(messageId);
};
const handleCopy = (message: string) => {
if (onCopy) {
onCopy(message);
}
// Trigger message copied event
triggerObservabilityHook("onMessageCopied", message);
};
const processFiles = async (files: File[]) => {
const validFiles = files.filter((file) =>
matchesAcceptFilter(file, attachmentsAccept),
);
const rejectedFiles = files.filter(
(file) => !matchesAcceptFilter(file, attachmentsAccept),
);
for (const file of rejectedFiles) {
const message = `File "${file.name}" is not accepted. Supported types: ${attachmentsAccept}`;
triggerChatError(new Error(message), "fileUpload");
resolvedAttachments?.onUploadFailed?.({
reason: "invalid-type",
file,
message,
});
}
for (const file of validFiles) {
if (exceedsMaxSize(file, attachmentsMaxSize)) {
const message = `File "${file.name}" exceeds the maximum size of ${formatFileSize(attachmentsMaxSize)}`;
triggerChatError(new Error(message), "fileUpload");
resolvedAttachments?.onUploadFailed?.({
reason: "file-too-large",
file,
message,
});
continue;
}
const modality = getModalityFromMimeType(file.type);
// Use a unique ID to track this placeholder across concurrent uploads
const placeholderId = randomUUID();
const placeholder: Attachment = {
id: placeholderId,
type: modality,
source: { type: "data", value: "", mimeType: file.type },
filename: file.name,
size: file.size,
status: "uploading",
};
setSelectedAttachments((prev) => [...prev, placeholder]);
try {
let source: Attachment["source"];
let uploadMetadata: Record<string, unknown> | undefined;
if (resolvedAttachments?.onUpload) {
const { metadata: meta, ...uploadSource } =
await resolvedAttachments.onUpload(file);
source = uploadSource;
uploadMetadata = meta;
} else {
const base64 = await readFileAsBase64(file);
source = { type: "data", value: base64, mimeType: file.type };
}
// Generate video thumbnail if applicable
let thumbnail: string | undefined;
if (modality === "video") {
thumbnail = await generateVideoThumbnail(file);
}
setSelectedAttachments((prev) =>
prev.map((att) =>
att.id === placeholderId
? {
...att,
source,
status: "ready" as const,
thumbnail,
metadata: uploadMetadata,
}
: att,
),
);
} catch (error) {
// Remove the failed placeholder
setSelectedAttachments((prev) =>
prev.filter((att) => att.id !== placeholderId),
);
const message = error instanceof Error ? error.message : String(error);
triggerChatError(
new Error(`Failed to upload "${file.name}": ${message}`),
"fileUpload",
error,
);
resolvedAttachments?.onUploadFailed?.({
reason: "upload-failed",
file,
message: `Failed to upload "${file.name}": ${message}`,
});
}
}
};
processFilesRef.current = processFiles;
const handleFileUpload = async (
event: React.ChangeEvent<HTMLInputElement>,
) => {
if (!event.target.files || event.target.files.length === 0) return;
try {
await processFiles(Array.from(event.target.files));
} catch (error) {
triggerChatError(error, "fileUpload", error);
}
};
// Drag-and-drop handlers
const handleDragOver = (e: React.DragEvent) => {
if (!attachmentsEnabled) return;
e.preventDefault();
e.stopPropagation();
setDragOver(true);
};
const handleDragLeave = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setDragOver(false);
};
const handleDrop = async (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setDragOver(false);
if (!attachmentsEnabled) return;
const files = Array.from(e.dataTransfer.files);
if (files.length > 0) {
try {
await processFiles(files);
} catch (error) {
triggerChatError(error, "dropUpload", error);
}
}
};
const handleThumbsUp = (message: Message) => {
if (onThumbsUp) {
onThumbsUp(message);
}
// Update feedback state
setMessageFeedback((prev) => ({
...prev,
[message.id]: "thumbsUp",
}));
// Trigger feedback given event
triggerObservabilityHook("onFeedbackGiven", message.id, "thumbsUp");
};
const handleThumbsDown = (message: Message) => {
if (onThumbsDown) {
onThumbsDown(message);
}
// Update feedback state
setMessageFeedback((prev) => ({
...prev,
[message.id]: "thumbsDown",
}));
// Trigger feedback given event
triggerObservabilityHook("onFeedbackGiven", message.id, "thumbsDown");
};
return (
<WrappedCopilotChat icons={icons} labels={labels} className={className}>
<div
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
className={`copilotKitChatBody${dragOver ? " copilotKitDragOver" : ""}`}
>
{/* Render error above messages if present */}
{chatError &&
renderError &&
renderError({
...chatError,
onDismiss: () => setChatError(null),
onRetry: () => {
// Clear error and potentially retry based on operation
setChatError(null);
// TODO: Implement specific retry logic based on operation type
},
})}
<Messages
AssistantMessage={AssistantMessage}
UserMessage={UserMessage}
RenderMessage={RenderMessage}
messages={messages}
inProgress={isLoading}
onRegenerate={handleRegenerate}
onCopy={handleCopy}
onThumbsUp={handleThumbsUp}
onThumbsDown={handleThumbsDown}
messageFeedback={messageFeedback}
markdownTagRenderers={markdownTagRenderers}
ImageRenderer={ImageRenderer}
ErrorMessage={ErrorMessage}
chatError={chatError}
// Legacy props - passed through to Messages component
RenderTextMessage={RenderTextMessage}
RenderActionExecutionMessage={RenderActionExecutionMessage}
RenderAgentStateMessage={RenderAgentStateMessage}
RenderResultMessage={RenderResultMessage}
RenderImageMessage={RenderImageMessage}
>
{currentSuggestions.length > 0 && (
<RenderSuggestionsList
onSuggestionClick={handleSendMessage}
suggestions={currentSuggestions}
isLoading={isLoadingSuggestions}
/>
)}
</Messages>
{attachmentsEnabled && (
<>
<AttachmentQueue
attachments={selectedAttachments}
onRemoveAttachment={(id) =>
setSelectedAttachments((prev) =>
prev.filter((att) => att.id !== id),
)
}
/>
<input
type="file"
multiple
ref={fileInputRef}
onChange={handleFileUpload}
accept={attachmentsAccept}
style={{ display: "none" }}
/>
</>
)}
<Input
inProgress={isLoading}
chatReady={Boolean(agent)}