-
Notifications
You must be signed in to change notification settings - Fork 450
Expand file tree
/
Copy pathpage.tsx
More file actions
1257 lines (1140 loc) · 42.6 KB
/
Copy pathpage.tsx
File metadata and controls
1257 lines (1140 loc) · 42.6 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
"use client";
import { Loader2, Zap } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { StickToBottom, useStickToBottomContext } from "use-stick-to-bottom";
import { ProtectedRoute } from "@/components/protected-route";
import { Button } from "@/components/ui/button";
import { useIsCloudBrand } from "@/contexts/brand-context";
import { type EndpointType, useChat } from "@/contexts/chat-context";
import { useTask } from "@/contexts/task-context";
import { useChatStreaming } from "@/hooks/useChatStreaming";
import { trackLLMCall } from "@/lib/analytics";
import { FILE_CONFIRMATION, FILES_REGEX } from "@/lib/constants";
import { buildSearchPayloadFilters } from "@/lib/filter-normalization";
import { cn } from "@/lib/utils";
import { useLoadingStore } from "@/stores/loadingStore";
import { useGetConversationsQuery } from "../api/queries/useGetConversationsQuery";
import { useGetNudgesQuery } from "../api/queries/useGetNudgesQuery";
import { useGetSettingsQuery } from "../api/queries/useGetSettingsQuery";
import { AssistantMessage } from "./_components/assistant-message";
import { ChatInput, type ChatInputHandle } from "./_components/chat-input";
import { ErrorMessage } from "./_components/error-message";
import Nudges from "./_components/nudges";
import { UserMessage } from "./_components/user-message";
import type {
FunctionCall,
KnowledgeFilterData,
Message,
RequestBody,
ToolCallResult,
} from "./_types/types";
import { INITIAL_ASSISTANT_MESSAGE } from "./_types/types";
function ChatPage() {
const isDebugMode = process.env.NEXT_PUBLIC_OPENRAG_DEBUG === "true";
const isCloudBrand = useIsCloudBrand();
const {
endpoint,
setEndpoint,
currentConversationId,
conversationData,
setCurrentConversationId,
addConversationDoc,
forkFromResponse,
refreshConversations,
refreshConversationsSilent,
refreshTrigger,
refreshTriggerSilent,
previousResponseIds,
setPreviousResponseIds,
placeholderConversation,
conversationFilter,
setConversationFilter,
} = useChat();
const [messages, setMessages] = useState<Message[]>([
INITIAL_ASSISTANT_MESSAGE,
]);
const [input, setInput] = useState("");
const { loading, setLoading } = useLoadingStore();
const { setChatError } = useChat();
const [asyncMode, setAsyncMode] = useState(true);
const [expandedFunctionCalls, setExpandedFunctionCalls] = useState<
Set<string>
>(new Set());
// previousResponseIds now comes from useChat context
const [isUploading, setIsUploading] = useState(false);
const [isFilterHighlighted, setIsFilterHighlighted] = useState(false);
const [isUserInteracting, setIsUserInteracting] = useState(false);
const [isForkingInProgress, setIsForkingInProgress] = useState(false);
const [uploadedFile, setUploadedFile] = useState<File | null>(null);
const [waitingTooLong, setWaitingTooLong] = useState(false);
const chatInputRef = useRef<ChatInputHandle>(null);
const { scrollToBottom } = useStickToBottomContext();
const lastLoadedConversationRef = useRef<string | null>(null);
const { addTask } = useTask();
// Check if chat history is loading
const { isLoading: isConversationsLoading } = useGetConversationsQuery(
endpoint,
refreshTrigger + refreshTriggerSilent,
);
// Use conversation-specific filter instead of global filter
const selectedFilter = conversationFilter;
// Parse the conversation filter data
const parsedFilterData = useMemo(() => {
if (!selectedFilter?.query_data) return null;
try {
return JSON.parse(selectedFilter.query_data);
} catch (error) {
console.error("Error parsing filter data:", error);
return null;
}
}, [selectedFilter]);
// Get settings for model info used in analytics
const { data: settings } = useGetSettingsQuery();
// Use the chat streaming hook
const apiEndpoint = endpoint === "chat" ? "/api/chat" : "/api/langflow";
const {
streamingMessage,
sendMessage: sendStreamingMessage,
abortStream,
isLoading: isStreamLoading,
} = useChatStreaming({
endpoint: apiEndpoint,
onComplete: (message, responseId) => {
trackLLMCall({
mode: "chat",
model: settings?.agent?.llm_model,
inputTokens: message.usage?.input_tokens,
outputTokens: message.usage?.output_tokens,
});
setMessages((prev) => [...prev, message]);
setLoading(false);
setWaitingTooLong(false);
if (responseId) {
cancelNudges();
setPreviousResponseIds((prev) => ({
...prev,
[endpoint]: responseId,
}));
if (!currentConversationId) {
setCurrentConversationId(responseId);
refreshConversations(true);
} else {
refreshConversationsSilent();
}
// Save filter association for this response
if (conversationFilter && typeof window !== "undefined") {
const newKey = `conversation_filter_${responseId}`;
localStorage.setItem(newKey, conversationFilter.id);
console.log(
"[CHAT] Saved filter association:",
newKey,
"=",
conversationFilter.id,
);
}
}
},
onError: (error) => {
console.error("Streaming error:", error);
setLoading(false);
setWaitingTooLong(false);
// Set chat error flag to trigger test_completion=true on health checks
setChatError(true);
const errorMessage: Message = {
role: "assistant",
content:
"Sorry, I couldn't connect to the chat service. Please try again.",
timestamp: new Date(),
};
setMessages((prev) => [...prev, errorMessage]);
},
});
// Show warning if waiting too long (20 seconds)
useEffect(() => {
let timeoutId: NodeJS.Timeout | null = null;
if (isStreamLoading && !streamingMessage) {
timeoutId = setTimeout(() => {
setWaitingTooLong(true);
}, 20000); // 20 seconds
} else {
setWaitingTooLong(false);
}
return () => {
if (timeoutId) clearTimeout(timeoutId);
};
}, [isStreamLoading, streamingMessage]);
const handleEndpointChange = (newEndpoint: EndpointType) => {
setEndpoint(newEndpoint);
// Clear the conversation when switching endpoints to avoid response ID conflicts
setMessages([]);
setPreviousResponseIds({ chat: null, langflow: null });
};
const handleFileUpload = async (file: File) => {
console.log("handleFileUpload called with file:", file.name);
if (isUploading) return;
setIsUploading(true);
setLoading(true);
try {
const formData = new FormData();
formData.append("file", file);
formData.append("endpoint", endpoint);
// Add previous_response_id if we have one for this endpoint
const currentResponseId = previousResponseIds[endpoint];
if (currentResponseId) {
formData.append("previous_response_id", currentResponseId);
}
const response = await fetch("/api/upload_context", {
method: "POST",
body: formData,
});
console.log("Upload response status:", response.status);
if (!response.ok) {
const errorText = await response.text();
console.error(
"Upload failed with status:",
response.status,
"Response:",
errorText,
);
throw new Error("Failed to process document");
}
const result = await response.json();
console.log("Upload result:", result);
if (!response.ok) {
// Set chat error flag if upload fails
setChatError(true);
}
if (response.status === 201) {
// New flow: Got task ID, start tracking with centralized system
const taskId = result.task_id || result.id;
if (!taskId) {
console.error("No task ID in 201 response:", result);
throw new Error("No task ID received from server");
}
// Add task to centralized tracking
addTask(taskId);
return null;
} else if (response.ok) {
// Original flow: Direct response
const uploadMessage: Message = {
role: "user",
content: `I'm uploading a document called "${result.filename}". Here is its content:`,
timestamp: new Date(),
};
const confirmationMessage: Message = {
role: "assistant",
content: `Confirmed`,
timestamp: new Date(),
};
setMessages((prev) => [...prev, uploadMessage, confirmationMessage]);
// Add file to conversation docs
if (result.filename) {
addConversationDoc(result.filename);
}
// Update the response ID for this endpoint
if (result.response_id) {
setPreviousResponseIds((prev) => ({
...prev,
[endpoint]: result.response_id,
}));
// If this is a new conversation (no currentConversationId), set it now
if (!currentConversationId) {
setCurrentConversationId(result.response_id);
refreshConversations(true);
} else {
// For existing conversations, do a silent refresh to keep backend in sync
refreshConversationsSilent();
}
return result.response_id;
}
} else {
throw new Error(`Upload failed: ${response.status}`);
}
} catch (error) {
console.error("Upload failed:", error);
// Set chat error flag to trigger test_completion=true on health checks
setChatError(true);
const errorMessage: Message = {
role: "assistant",
content: `❌ Failed to process document. Please try again.`,
timestamp: new Date(),
error: true,
};
setMessages((prev) => [...prev.slice(0, -1), errorMessage]);
} finally {
setIsUploading(false);
setLoading(false);
}
};
const handleFilePickerClick = () => {
chatInputRef.current?.clickFileInput();
};
const handleFilterSelect = (filter: KnowledgeFilterData | null) => {
// Update conversation-specific filter
setConversationFilter(filter);
setIsFilterHighlighted(false);
};
// Auto-focus the input on component mount
useEffect(() => {
chatInputRef.current?.focusInput();
}, []);
// Explicitly handle external new conversation trigger
useEffect(() => {
const handleNewConversation = () => {
// Abort any in-flight streaming so it doesn't bleed into new chat
abortStream();
// Reset chat UI even if context state was already 'new'
setMessages([INITIAL_ASSISTANT_MESSAGE]);
setInput("");
setExpandedFunctionCalls(new Set());
setIsFilterHighlighted(false);
setLoading(false);
lastLoadedConversationRef.current = null;
// Focus input after a short delay to ensure rendering is complete
setTimeout(() => {
chatInputRef.current?.focusInput();
}, 100);
};
const handleFocusInput = () => {
chatInputRef.current?.focusInput();
};
window.addEventListener("newConversation", handleNewConversation);
window.addEventListener("focusInput", handleFocusInput);
return () => {
window.removeEventListener("newConversation", handleNewConversation);
window.removeEventListener("focusInput", handleFocusInput);
};
}, [abortStream, setLoading]);
// Load conversation data from context
useEffect(() => {
// Only load conversation data when:
// 1. conversationData exists AND
// 2. (It's a different conversation OR we're not streaming and data has changed) AND
// 3. User is not in the middle of an interaction
const isNewConversation =
lastLoadedConversationRef.current !== conversationData?.response_id;
const hasMessageCountChanged =
conversationData?.messages?.length !== messages.length;
if (
conversationData?.messages &&
(isNewConversation || (!isStreamLoading && hasMessageCountChanged)) &&
!isUserInteracting &&
!isForkingInProgress
) {
console.log(
"Loading conversation with",
conversationData.messages.length,
"messages",
);
// Convert backend message format to frontend Message interface
const convertedMessages: Message[] = conversationData.messages.map(
(msg: {
role: string;
content: string;
timestamp?: string;
response_id?: string;
error?: boolean;
chunks?: Array<{
item?: {
type?: string;
tool_name?: string;
id?: string;
inputs?: unknown;
results?: unknown;
status?: string;
};
delta?: {
tool_calls?: Array<{
id?: string;
function?: { name?: string; arguments?: string };
type?: string;
}>;
};
type?: string;
result?: unknown;
output?: unknown;
response?: unknown;
}>;
response_data?: unknown;
}) => {
const message: Message = {
role: msg.role as "user" | "assistant",
content: msg.content,
timestamp: new Date(msg.timestamp || new Date()),
error: msg.error || false,
};
// Extract function calls from chunks or response_data
if (msg.role === "assistant" && (msg.chunks || msg.response_data)) {
const functionCalls: FunctionCall[] = [];
console.log("Processing assistant message for function calls:", {
hasChunks: !!msg.chunks,
chunksLength: msg.chunks?.length,
hasResponseData: !!msg.response_data,
});
// Process chunks (streaming data)
if (msg.chunks && Array.isArray(msg.chunks)) {
for (const chunk of msg.chunks) {
// Handle Langflow format: chunks[].item.tool_call
if (chunk.item && chunk.item.type === "tool_call") {
const toolCall = chunk.item;
console.log("Found Langflow tool call:", toolCall);
functionCalls.push({
id: toolCall.id || "",
name: toolCall.tool_name || "unknown",
arguments:
(toolCall.inputs as Record<string, unknown>) || {},
argumentsString: JSON.stringify(toolCall.inputs || {}),
result: toolCall.results as
| Record<string, unknown>
| ToolCallResult[],
status:
(toolCall.status as "pending" | "completed" | "error") ||
"completed",
type: "tool_call",
});
}
// Handle OpenAI format: chunks[].delta.tool_calls
else if (chunk.delta?.tool_calls) {
for (const toolCall of chunk.delta.tool_calls) {
if (toolCall.function) {
functionCalls.push({
id: toolCall.id || "",
name: toolCall.function.name || "unknown",
arguments: toolCall.function.arguments
? JSON.parse(toolCall.function.arguments)
: {},
argumentsString: toolCall.function.arguments || "",
status: "completed",
type: toolCall.type || "function",
});
}
}
}
// Process tool call results from chunks
if (
chunk.type === "response.tool_call.result" ||
chunk.type === "tool_call_result"
) {
const lastCall = functionCalls[functionCalls.length - 1];
if (lastCall) {
lastCall.result =
(chunk.result as
| Record<string, unknown>
| ToolCallResult[]) ||
(chunk as Record<string, unknown>);
lastCall.status = "completed";
}
}
}
}
// Process response_data (non-streaming data)
if (msg.response_data && typeof msg.response_data === "object") {
// Look for tool_calls in various places in the response data
const responseData =
typeof msg.response_data === "string"
? JSON.parse(msg.response_data)
: msg.response_data;
if (
responseData.tool_calls &&
Array.isArray(responseData.tool_calls)
) {
for (const toolCall of responseData.tool_calls) {
functionCalls.push({
id: toolCall.id,
name: toolCall.function?.name || toolCall.name,
arguments:
toolCall.function?.arguments || toolCall.arguments,
argumentsString:
typeof (
toolCall.function?.arguments || toolCall.arguments
) === "string"
? toolCall.function?.arguments || toolCall.arguments
: JSON.stringify(
toolCall.function?.arguments || toolCall.arguments,
),
result: toolCall.result,
status: "completed",
type: toolCall.type || "function",
});
}
}
}
if (functionCalls.length > 0) {
console.log("Setting functionCalls on message:", functionCalls);
message.functionCalls = functionCalls;
} else {
console.log("No function calls found in message");
}
// Extract usage data from response_data
if (msg.response_data && typeof msg.response_data === "object") {
const responseData =
typeof msg.response_data === "string"
? JSON.parse(msg.response_data)
: msg.response_data;
if (responseData.usage) {
message.usage = responseData.usage;
}
}
}
return message;
},
);
setMessages(convertedMessages);
lastLoadedConversationRef.current = conversationData.response_id;
// Set the previous response ID for this conversation
setPreviousResponseIds((prev) => ({
...prev,
[conversationData.endpoint]: conversationData.response_id,
}));
// Focus input when loading a conversation
setTimeout(() => {
chatInputRef.current?.focusInput();
}, 100);
} else if (!conversationData) {
// No conversation selected (new conversation)
lastLoadedConversationRef.current = null;
}
}, [
conversationData,
isUserInteracting,
isForkingInProgress,
setPreviousResponseIds,
isStreamLoading,
messages.length,
]);
// Handle new conversation creation - only reset messages when placeholderConversation is set
useEffect(() => {
if (placeholderConversation && currentConversationId === null) {
console.log("Starting new conversation");
setMessages([INITIAL_ASSISTANT_MESSAGE]);
lastLoadedConversationRef.current = null;
// Focus input when starting a new conversation
setTimeout(() => {
chatInputRef.current?.focusInput();
}, 100);
}
}, [placeholderConversation, currentConversationId]);
// Listen for file upload events from navigation
useEffect(() => {
const handleFileUploadStart = (event: CustomEvent) => {
const { filename } = event.detail;
console.log("Chat page received file upload start event:", filename);
setLoading(true);
setIsUploading(true);
setUploadedFile(null); // Clear previous file
};
const handleFileUploaded = (event: CustomEvent) => {
const { result } = event.detail;
console.log("Chat page received file upload event:", result);
setUploadedFile(null); // Clear file after upload
// Update the response ID for this endpoint
if (result.response_id) {
setPreviousResponseIds((prev) => ({
...prev,
[endpoint]: result.response_id,
}));
}
};
const handleFileUploadComplete = () => {
console.log("Chat page received file upload complete event");
setLoading(false);
setIsUploading(false);
};
const handleFileUploadError = (event: CustomEvent) => {
const { filename, error } = event.detail;
console.log(
"Chat page received file upload error event:",
filename,
error,
);
// Replace the last message with error message
const errorMessage: Message = {
role: "assistant",
content: `❌ Upload failed for **${filename}**: ${error}`,
timestamp: new Date(),
};
setMessages((prev) => [...prev.slice(0, -1), errorMessage]);
setUploadedFile(null); // Clear file on error
};
window.addEventListener(
"fileUploadStart",
handleFileUploadStart as EventListener,
);
window.addEventListener(
"fileUploaded",
handleFileUploaded as EventListener,
);
window.addEventListener(
"fileUploadComplete",
handleFileUploadComplete as EventListener,
);
window.addEventListener(
"fileUploadError",
handleFileUploadError as EventListener,
);
return () => {
window.removeEventListener(
"fileUploadStart",
handleFileUploadStart as EventListener,
);
window.removeEventListener(
"fileUploaded",
handleFileUploaded as EventListener,
);
window.removeEventListener(
"fileUploadComplete",
handleFileUploadComplete as EventListener,
);
window.removeEventListener(
"fileUploadError",
handleFileUploadError as EventListener,
);
};
}, [endpoint, setPreviousResponseIds, setLoading]);
// Check onboarding completion
// Check if onboarding is complete (current_step >= 4 means complete)
const TOTAL_ONBOARDING_STEPS = 4;
const isOnboardingComplete =
settings?.onboarding?.current_step !== undefined &&
settings.onboarding.current_step >= TOTAL_ONBOARDING_STEPS;
// Prepare filters for nudges (same as chat)
const processedFiltersForNudges = parsedFilterData?.filters
? (() => {
return buildSearchPayloadFilters(parsedFilterData.filters);
})()
: undefined;
const { data: nudges = [], cancel: cancelNudges } = useGetNudgesQuery(
{
chatId: previousResponseIds[endpoint],
filters: processedFiltersForNudges,
limit: parsedFilterData?.limit ?? 3,
scoreThreshold: parsedFilterData?.scoreThreshold ?? 0,
},
{
enabled: isOnboardingComplete && !isConversationsLoading, // Only fetch nudges after onboarding is complete AND chat history is not loading
},
);
const handleSSEStream = async (
userMessage: Message,
previousResponseId?: string,
) => {
// Prepare filters
const processedFilters = parsedFilterData?.filters
? (() => {
return buildSearchPayloadFilters(parsedFilterData.filters);
})()
: undefined;
// Use passed previousResponseId if available, otherwise fall back to state
const responseIdToUse = previousResponseId || previousResponseIds[endpoint];
console.log("[CHAT] Sending streaming message:", {
conversationFilter: conversationFilter?.id,
currentConversationId,
responseIdToUse,
});
// Use the hook to send the message
await sendStreamingMessage({
prompt: userMessage.content,
previousResponseId: responseIdToUse || undefined,
filters: processedFilters,
filter_id: conversationFilter?.id, // ✅ Add filter_id for this conversation
limit: parsedFilterData?.limit ?? 10,
scoreThreshold: parsedFilterData?.scoreThreshold ?? 0,
});
scrollToBottom({
animation: "smooth",
duration: 1000,
});
};
const handleSendMessage = async (
inputMessage: string,
previousResponseId?: string,
) => {
if (!inputMessage.trim() || loading) return;
const userMessage: Message = {
role: "user",
content: inputMessage.trim(),
timestamp: new Date(),
};
if (messages.length === 1) {
setMessages([userMessage]);
} else {
setMessages((prev) => [...prev, userMessage]);
}
setInput("");
setLoading(true);
setIsFilterHighlighted(false);
scrollToBottom({
animation: "smooth",
duration: 1000,
});
if (asyncMode) {
await handleSSEStream(userMessage, previousResponseId);
} else {
// Original non-streaming logic
try {
const apiEndpoint = endpoint === "chat" ? "/api/chat" : "/api/langflow";
const requestBody: RequestBody = {
prompt: userMessage.content,
...(parsedFilterData?.filters
? (() => {
const processedFilters = buildSearchPayloadFilters(
parsedFilterData.filters,
);
return processedFilters ? { filters: processedFilters } : {};
})()
: {}),
limit: parsedFilterData?.limit ?? 10,
scoreThreshold: parsedFilterData?.scoreThreshold ?? 0,
};
// Add previous_response_id if we have one for this endpoint
const currentResponseId = previousResponseIds[endpoint];
if (currentResponseId) {
requestBody.previous_response_id = currentResponseId;
}
// Add filter_id if a filter is selected for this conversation
if (conversationFilter) {
requestBody.filter_id = conversationFilter.id;
}
// Debug logging
console.log("[DEBUG] Sending message with:", {
previous_response_id: requestBody.previous_response_id,
filter_id: requestBody.filter_id,
currentConversationId,
previousResponseIds,
});
const response = await fetch(apiEndpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(requestBody),
});
const result = await response.json();
if (response.ok) {
const assistantMessage: Message = {
role: "assistant",
content: result.response,
timestamp: new Date(),
usage: result.usage,
};
setMessages((prev) => [...prev, assistantMessage]);
if (result.response_id) {
cancelNudges();
}
// Store the response ID if present for this endpoint
if (result.response_id) {
console.log(
"[DEBUG] Received response_id:",
result.response_id,
"currentConversationId:",
currentConversationId,
);
setPreviousResponseIds((prev) => ({
...prev,
[endpoint]: result.response_id,
}));
// If this is a new conversation (no currentConversationId), set it now
if (!currentConversationId) {
console.log(
"[DEBUG] Setting currentConversationId to:",
result.response_id,
);
setCurrentConversationId(result.response_id);
refreshConversations(true);
} else {
console.log(
"[DEBUG] Existing conversation, doing silent refresh",
);
// For existing conversations, do a silent refresh to keep backend in sync
refreshConversationsSilent();
}
// Carry forward the filter association to the new response_id
if (conversationFilter && typeof window !== "undefined") {
const newKey = `conversation_filter_${result.response_id}`;
localStorage.setItem(newKey, conversationFilter.id);
console.log(
"[DEBUG] Saved filter association:",
newKey,
"=",
conversationFilter.id,
);
}
}
} else {
console.error("Chat failed:", result.error);
// Set chat error flag to trigger test_completion=true on health checks
setChatError(true);
const errorMessage: Message = {
role: "assistant",
content: "Sorry, I encountered an error. Please try again.",
timestamp: new Date(),
error: true,
};
setMessages((prev) => [...prev, errorMessage]);
}
} catch (error) {
console.error("Chat error:", error);
// Set chat error flag to trigger test_completion=true on health checks
setChatError(true);
const errorMessage: Message = {
role: "assistant",
content:
"Sorry, I couldn't connect to the chat service. Please try again.",
timestamp: new Date(),
error: true,
};
setMessages((prev) => [...prev, errorMessage]);
}
}
setLoading(false);
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
// Check if there's an uploaded file and upload it first
let uploadedResponseId: string | null = null;
if (uploadedFile) {
// Upload the file first
const responseId = await handleFileUpload(uploadedFile);
// Clear the file after upload
setUploadedFile(null);
// If the upload resulted in a new conversation, store the response ID
if (responseId) {
uploadedResponseId = responseId;
setPreviousResponseIds((prev) => ({
...prev,
[endpoint]: responseId,
}));
}
}
// Only send message if there's input text
if (input.trim() || uploadedFile) {
// Pass the responseId from upload (if any) to handleSendMessage
handleSendMessage(
!input.trim() ? FILE_CONFIRMATION : input,
uploadedResponseId || undefined,
);
}
};
const toggleFunctionCall = (functionCallId: string) => {
setExpandedFunctionCalls((prev) => {
const newSet = new Set(prev);
if (newSet.has(functionCallId)) {
newSet.delete(functionCallId);
} else {
newSet.add(functionCallId);
}
return newSet;
});
};
const handleForkConversation = (
messageIndex: number,
event?: React.MouseEvent,
) => {
// Prevent any default behavior and stop event propagation
if (event) {
event.preventDefault();
event.stopPropagation();
}
// Set interaction state to prevent auto-scroll interference
setIsUserInteracting(true);
setIsForkingInProgress(true);
console.log("Fork conversation called for message index:", messageIndex);
// Get messages up to and including the selected assistant message
const messagesToKeep = messages.slice(0, messageIndex + 1);
// The selected message should be an assistant message (since fork button is only on assistant messages)
const forkedMessage = messages[messageIndex];
if (forkedMessage.role !== "assistant") {
console.error("Fork button should only be on assistant messages");
setIsUserInteracting(false);
setIsForkingInProgress(false);
return;
}
// For forking, we want to continue from the response_id of the assistant message we're forking from
// Since we don't store individual response_ids per message yet, we'll use the current conversation's response_id
// This means we're continuing the conversation thread from that point
const responseIdToForkFrom =
currentConversationId || previousResponseIds[endpoint];
// Create a new conversation by properly forking
setMessages(messagesToKeep);
// Use the chat context's fork method which handles creating a new conversation properly
if (forkFromResponse) {
forkFromResponse(responseIdToForkFrom || "");
} else {
// Fallback to manual approach
setCurrentConversationId(null); // This creates a new conversation thread
// Set the response_id we want to continue from as the previous response ID
// This tells the backend to continue the conversation from this point
setPreviousResponseIds((prev) => ({
...prev,
[endpoint]: responseIdToForkFrom,
}));
}
console.log("Forked conversation with", messagesToKeep.length, "messages");
// Reset interaction state after a longer delay to ensure all effects complete
setTimeout(() => {
setIsUserInteracting(false);
setIsForkingInProgress(false);
console.log("Fork interaction complete, re-enabling auto effects");
}, 500);
// The original conversation remains unchanged in the sidebar
// This new forked conversation will get its own response_id when the user sends the next message
};
const handleSuggestionClick = (suggestion: string) => {
handleSendMessage(suggestion);
};
return (
<>
{/* Debug header - only show in debug mode */}
{isDebugMode && (