-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGraphRAGPanel.tsx
More file actions
1428 lines (1292 loc) · 59 KB
/
GraphRAGPanel.tsx
File metadata and controls
1428 lines (1292 loc) · 59 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
import React, { FC, useContext, useState, useRef, useEffect, useMemo } from "react";
import { AiOutlineRobot, AiOutlineSend, AiOutlineQuestionCircle, AiOutlineInfoCircle } from "react-icons/ai";
import { BsGithub } from "react-icons/bs";
import { FaMicrosoft } from "react-icons/fa6";
import { SiGoogle } from "react-icons/si";
import { VscSettings } from "react-icons/vsc";
import { Tooltip } from 'bootstrap';
import { GraphContext } from "../lib/context";
import { useNotifications } from "../lib/notifications";
import { API_ENDPOINTS } from "../lib/config";
import { ANIMATION_DURATION } from "../lib/consts";
import { Coordinates } from "sigma/types";
interface APIKeys {
githubToken: string;
openaiKey: string;
azureOpenAIKey: string;
azureOpenAIEndpoint: string;
azureOpenAIDeployment: string;
geminiKey: string;
}
interface Message {
id: string;
type: 'user' | 'assistant' | 'system';
content: string;
timestamp: Date;
actions?: Array<{
label: string;
action: string;
data?: any;
}>;
}
interface GraphRAGState {
graphHash: string;
isReady: boolean;
messages: Message[];
selectedProvider: string;
lastSetupTime?: Date;
}
// Separate interface for session-only API keys
interface SessionAPIKeys {
githubToken: string;
openaiKey: string;
azureOpenAIKey: string;
azureOpenAIEndpoint: string;
azureOpenAIDeployment: string;
geminiKey: string;
}
const GraphRAGPanel: FC = () => {
const { notify } = useNotifications();
const { graphFile, data, setNavState, navState, sigma, computedData } = useContext(GraphContext);
const messagesEndRef = useRef<HTMLDivElement>(null);
const tooltipRefs = useRef<{ [key: string]: Tooltip }>({});
// Generate unique message IDs
const generateMessageId = () => {
return `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
};
// Session-only API keys (not persisted to disk)
const getSessionAPIKeys = (): SessionAPIKeys => {
try {
const saved = sessionStorage.getItem('graphrag_session_keys');
return saved ? JSON.parse(saved) : {
githubToken: "",
openaiKey: "",
azureOpenAIKey: "",
azureOpenAIEndpoint: "",
azureOpenAIDeployment: "",
geminiKey: "",
};
} catch {
return {
githubToken: "",
openaiKey: "",
azureOpenAIKey: "",
azureOpenAIEndpoint: "",
azureOpenAIDeployment: "",
geminiKey: "",
};
}
};
const setSessionAPIKeys = (keys: Partial<SessionAPIKeys>) => {
try {
const current = getSessionAPIKeys();
const updated = { ...current, ...keys };
sessionStorage.setItem('graphrag_session_keys', JSON.stringify(updated));
} catch (error) {
console.error('Failed to save session API keys:', error);
}
};
const clearSessionAPIKeys = () => {
try {
sessionStorage.removeItem('graphrag_session_keys');
} catch (error) {
console.error('Failed to clear session API keys:', error);
}
};
// Clean up GraphRAG database on server
const cleanupGraphRAGDatabase = async () => {
try {
const sessionId = sessionStorage.getItem('graphrag_session_id') || '';
if (sessionId) {
const response = await fetch(API_ENDPOINTS.GRAPHRAG_CLEANUP, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ sessionId }),
});
if (response.ok) {
console.log('GraphRAG database cleanup completed');
} else {
console.warn('GraphRAG database cleanup failed:', response.statusText);
}
}
} catch (error) {
console.error('Failed to cleanup GraphRAG database:', error);
}
};
// Clear all GraphRAG data (API keys and state)
const clearAllGraphRAGData = () => {
try {
// Clear session storage (API keys)
sessionStorage.removeItem('graphrag_session_keys');
// Clear localStorage (GraphRAG state)
localStorage.removeItem('graphrag_state');
} catch (error) {
console.error('Failed to clear GraphRAG data:', error);
}
};
// Clear sensitive data when component unmounts or page unloads
useEffect(() => {
const handleBeforeUnload = () => {
// Only clear when the entire browser tab is being closed
clearAllGraphRAGData();
// Clean up database on server (synchronous for beforeunload)
cleanupGraphRAGDatabase();
};
const handlePageHide = () => {
// Clear everything when page is hidden (browser tab closed)
clearAllGraphRAGData();
// Clean up database on server (asynchronous for pagehide)
cleanupGraphRAGDatabase();
};
// Don't clear on visibility change (switching between tabs in same page)
// const handleVisibilityChange = () => {
// if (document.visibilityState === 'hidden') {
// clearAllGraphRAGData();
// }
// };
window.addEventListener('beforeunload', handleBeforeUnload);
window.addEventListener('pagehide', handlePageHide);
// document.addEventListener('visibilitychange', handleVisibilityChange);
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
window.removeEventListener('pagehide', handlePageHide);
// document.removeEventListener('visibilitychange', handleVisibilityChange);
// Don't clear on component unmount (just switching tabs)
// clearAllGraphRAGData();
};
}, []);
// Load persisted state from localStorage
const loadPersistedState = (): GraphRAGState | null => {
try {
const saved = localStorage.getItem('graphrag_state');
if (!saved) return null;
const parsed = JSON.parse(saved);
// Convert string timestamps back to Date objects
if (parsed.messages && Array.isArray(parsed.messages)) {
parsed.messages = parsed.messages.map((msg: any) => ({
...msg,
timestamp: new Date(msg.timestamp)
}));
}
// Convert lastSetupTime if it exists
if (parsed.lastSetupTime) {
parsed.lastSetupTime = new Date(parsed.lastSetupTime);
}
return parsed;
} catch {
return null;
}
};
// Save state to localStorage (excluding sensitive data)
const saveState = (state: Partial<GraphRAGState>) => {
try {
const current = loadPersistedState() || {
graphHash: '',
isReady: false,
messages: [{
id: generateMessageId(),
type: 'assistant',
content: 'Hello! I\'m your GraphRAG assistant. I can help you analyze your GitHub repository graph with AI-powered insights. Let\'s get started by setting up the system.',
timestamp: new Date()
}],
selectedProvider: "openai"
};
const updated = { ...current, ...state };
localStorage.setItem('graphrag_state', JSON.stringify(updated));
} catch (error) {
console.error('Failed to save GraphRAG state:', error);
}
};
// Initialize state from localStorage or defaults
const [graphragState, setGraphragState] = useState<GraphRAGState>(() => {
const saved = loadPersistedState();
if (saved && saved.graphHash === '') {
return saved;
}
return {
graphHash: '',
isReady: false,
messages: [{
id: generateMessageId(),
type: 'assistant',
content: 'Hello! I\'m your GraphRAG assistant. I can help you analyze your GitHub repository graph with AI-powered insights. Let\'s get started by setting up the system.',
timestamp: new Date()
}],
selectedProvider: "openai"
};
});
// State for graph change confirmation
const [showGraphChangeDialog, setShowGraphChangeDialog] = useState(false);
const [pendingGraphHash, setPendingGraphHash] = useState('');
const [showRebuildPrompt, setShowRebuildPrompt] = useState(false);
const hasShownRebuildPrompt = useRef(false);
// Detect graph changes
useEffect(() => {
if ('' && '' !== graphragState.graphHash) {
setPendingGraphHash('');
setShowGraphChangeDialog(true);
}
}, [graphragState.graphHash]);
// Check backend health and reset state if needed
useEffect(() => {
const checkBackendHealth = async () => {
if (graphragState.isReady) {
try {
const response = await fetch(API_ENDPOINTS.GRAPHRAG_HEALTH, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
}
});
if (!response.ok) {
// Backend is not ready, reset the state but preserve existing messages
updateState(prevState => ({
isReady: false,
messages: [...prevState.messages, {
id: generateMessageId(),
type: 'system' as const,
content: '⚠️ GraphRAG backend was restarted. Please set up the system again.',
timestamp: new Date()
}]
}));
notify({
type: "warning",
message: "GraphRAG backend was restarted. Please set up the system again.",
});
}
} catch (error) {
// Backend is not reachable, reset the state but preserve existing messages
updateState(prevState => ({
isReady: false,
messages: [...prevState.messages, {
id: generateMessageId(),
type: 'system' as const,
content: '❌ Cannot connect to GraphRAG backend. Please ensure the server is running.',
timestamp: new Date()
}]
}));
notify({
type: "error",
message: "Cannot connect to GraphRAG backend. Please ensure the server is running.",
});
}
}
};
checkBackendHealth();
}, [graphragState.isReady]);
// Handle graph change confirmation
const handleGraphChangeConfirm = (useNewGraph: boolean) => {
if (useNewGraph) {
// Reset state for new graph
const newState: GraphRAGState = {
graphHash: '',
isReady: false,
messages: [{
id: generateMessageId(),
type: 'assistant',
content: 'Hello! I\'m your GraphRAG assistant. I can help you analyze your GitHub repository graph with AI-powered insights. Let\'s get started by setting up the system.',
timestamp: new Date()
}],
selectedProvider: graphragState.selectedProvider
};
setGraphragState(newState);
saveState(newState);
}
setShowGraphChangeDialog(false);
setPendingGraphHash('');
};
// Update state and persist changes
const updateState = (updates: Partial<GraphRAGState> | ((prevState: GraphRAGState) => Partial<GraphRAGState>)) => {
const newState = typeof updates === 'function'
? { ...graphragState, ...updates(graphragState) }
: { ...graphragState, ...updates };
setGraphragState(newState);
saveState(newState);
};
// Local state variables
const [query, setQuery] = useState<string>("");
const [isLoading, setIsLoading] = useState<boolean>(false);
const [isSetupLoading, setIsSetupLoading] = useState<boolean>(false);
const [showSetup, setShowSetup] = useState<boolean>(true);
const [setupProgress, setSetupProgress] = useState<string>("");
const [progressData, setProgressData] = useState<{
current_step: string;
current: number;
total: number;
message: string;
status: string;
} | null>(null);
// Session API keys state for UI
const [sessionAPIKeys, setSessionAPIKeysState] = useState<SessionAPIKeys>(getSessionAPIKeys());
// Update session API keys when they change
const updateSessionAPIKeys = (keys: Partial<SessionAPIKeys>) => {
setSessionAPIKeys(keys);
setSessionAPIKeysState(getSessionAPIKeys());
};
// Load configuration from backend on component mount
useEffect(() => {
const loadConfiguration = async () => {
try {
const response = await fetch('/api/config/keys');
if (response.ok) {
const data = await response.json();
if (data.success && data.keys) {
const keys = data.keys;
// Load API keys from config if not already set in session
const currentKeys = getSessionAPIKeys();
const newKeys: Partial<SessionAPIKeys> = {};
// GitHub token
if (!currentKeys.githubToken && keys.github?.token) {
newKeys.githubToken = keys.github.token;
}
// OpenAI API key
if (!currentKeys.openaiKey && keys.ai_providers?.openai?.api_key) {
newKeys.openaiKey = keys.ai_providers.openai.api_key;
}
// Azure OpenAI
if (!currentKeys.azureOpenAIKey && keys.ai_providers?.azure_openai?.api_key) {
newKeys.azureOpenAIKey = keys.ai_providers.azure_openai.api_key;
}
if (!currentKeys.azureOpenAIEndpoint && keys.ai_providers?.azure_openai?.endpoint) {
newKeys.azureOpenAIEndpoint = keys.ai_providers.azure_openai.endpoint;
}
if (!currentKeys.azureOpenAIDeployment && keys.ai_providers?.azure_openai?.deployment_name) {
newKeys.azureOpenAIDeployment = keys.ai_providers.azure_openai.deployment_name;
}
// Google GenAI
if (!currentKeys.geminiKey && keys.ai_providers?.google_genai?.api_key) {
newKeys.geminiKey = keys.ai_providers.google_genai.api_key;
}
// Update session keys if any were loaded from config
if (Object.keys(newKeys).length > 0) {
updateSessionAPIKeys(newKeys);
}
}
}
} catch (error) {
console.log('Could not load configuration:', error);
// This is not an error - config loading is optional
}
};
loadConfiguration();
}, []);
// Calculate graph statistics using the same logic as download control
const graphStats = useMemo(() => {
if (!data || !data.graph) {
return {
nodes: 0,
edges: 0,
hasData: false
};
}
const graph = data.graph;
// Use the same logic as download control to determine visible nodes
const visibleNodes = new Set<string>();
if (computedData.filteredNodes) {
// Use filtered nodes as the base - these are the active/visible nodes
computedData.filteredNodes.forEach(node => {
if (graph.hasNode(node)) {
visibleNodes.add(node);
}
});
} else {
// If no filters are applied, include all nodes
graph.forEachNode((node) => {
visibleNodes.add(node);
});
}
// Count edges where BOTH source AND target nodes are visible (same as download control)
let visibleEdges = 0;
graph.forEachEdge((edge, attributes, source, target) => {
if (visibleNodes.has(source) && visibleNodes.has(target)) {
visibleEdges++;
}
});
return {
nodes: visibleNodes.size,
edges: visibleEdges,
hasData: true
};
}, [data, computedData.filteredNodes]);
// Debug: Log graph statistics changes
useEffect(() => {
console.log('Graph statistics updated:', graphStats);
}, [graphStats]);
// Update showSetup based on isReady state
useEffect(() => {
setShowSetup(!graphragState.isReady);
}, [graphragState.isReady]);
// Auto-scroll to bottom when new messages are added
useEffect(() => {
// Only auto-scroll if we're near the bottom
if (messagesEndRef.current) {
const container = messagesEndRef.current.parentElement;
if (container) {
const isNearBottom = container.scrollHeight - container.scrollTop - container.clientHeight < 100;
if (isNearBottom) {
messagesEndRef.current.scrollIntoView({ behavior: 'smooth' });
}
}
}
}, [graphragState.messages]);
// Debug: Log messages when they change
useEffect(() => {
// console.log('Messages updated:', graphragState.messages.length, graphragState.messages);
// console.log('Message types:', graphragState.messages.map(m => ({ id: m.id, type: m.type, content: m.content.substring(0, 50) + '...' })));
}, [graphragState.messages]);
// Initialize tooltips
useEffect(() => {
// Cleanup existing tooltips
Object.values(tooltipRefs.current).forEach(tooltip => {
tooltip.dispose();
});
tooltipRefs.current = {};
// Initialize new tooltips
const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
tooltipTriggerList.forEach(tooltipTriggerEl => {
const id = tooltipTriggerEl.id;
if (id) {
try {
const tooltip = new Tooltip(tooltipTriggerEl, {
trigger: 'hover',
html: true
});
tooltipRefs.current[id] = tooltip;
} catch (error) {
console.error('Error initializing tooltip:', error);
}
}
});
// Cleanup tooltips when component unmounts
return () => {
Object.values(tooltipRefs.current).forEach(tooltip => {
tooltip.dispose();
});
tooltipRefs.current = {};
};
}, []);
const handleAPIKeyChange = (key: keyof SessionAPIKeys, value: string) => {
updateSessionAPIKeys({ [key]: value });
};
const validateAPIKeys = (): boolean => {
const apiKeys = getSessionAPIKeys();
if (graphragState.selectedProvider === "openai" && !apiKeys.openaiKey) {
notify({
type: "error",
message: "Please enter your OpenAI API key",
});
return false;
}
if (graphragState.selectedProvider === "azure_openai" && (!apiKeys.azureOpenAIKey || !apiKeys.azureOpenAIEndpoint || !apiKeys.azureOpenAIDeployment)) {
notify({
type: "error",
message: "Please enter all Azure OpenAI credentials",
});
return false;
}
if (graphragState.selectedProvider === "gemini" && !apiKeys.geminiKey) {
notify({
type: "error",
message: "Please enter your Gemini API key",
});
return false;
}
return true;
};
const handleSetup = async () => {
if (!validateAPIKeys()) {
return;
}
if (!graphFile?.textContent) {
notify({
type: "error",
message: "No graph data available. Please load a graph first.",
});
return;
}
setIsSetupLoading(true);
setProgressData(null);
// Add user message showing they clicked setup
const newMessages = [...graphragState.messages, {
id: generateMessageId(),
type: 'user' as const,
content: 'Please set up the GraphRAG system for me.',
timestamp: new Date()
}];
updateState({ messages: newMessages });
const setupMessages = [...newMessages, {
id: generateMessageId(),
type: 'system' as const,
content: `🔄 Starting GraphRAG setup for ${graphStats.nodes.toLocaleString()} repositories...`,
timestamp: new Date()
}];
updateState({ messages: setupMessages });
// console.log('About to create EventSource...');
// Reset progress status before creating EventSource
// try {
// await fetch('http://localhost:5002/api/graphrag-reset-progress', {
// method: 'POST',
// headers: { 'Content-Type': 'application/json' }
// });
// console.log('Progress status reset');
// } catch (error) {
// console.log('Could not reset progress status:', error);
// }
// Start listening for progress updates
// console.log('Creating EventSource connection to:', 'http://localhost:5002/api/graphrag-progress');
// const eventSource = new EventSource('http://localhost:5002/api/graphrag-progress');
// console.log('EventSource created, readyState:', eventSource.readyState);
try {
// Generate session ID for this GraphRAG session
const sessionId = `graphrag_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
sessionStorage.setItem('graphrag_session_id', sessionId);
const response = await fetch(API_ENDPOINTS.GRAPHRAG_SETUP, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
provider: graphragState.selectedProvider,
apiKeys: getSessionAPIKeys(),
graphFile: graphFile.textContent,
sessionId: sessionId
})
});
const result = await response.json();
if (result.success) {
const finalMessages = [...graphragState.messages, {
id: generateMessageId(),
type: 'assistant' as const,
content: '🎉 GraphRAG setup completed successfully! You can now ask questions about your repository graph.',
timestamp: new Date()
}];
updateState({
isReady: true,
messages: finalMessages,
lastSetupTime: new Date()
});
// Update the stored graph hash after successful setup
sessionStorage.setItem('graphrag_last_graph_hash', '');
// Also update simple statistics
sessionStorage.setItem('graphrag_last_stats', JSON.stringify({
nodes: data?.graph.nodes().length || 0,
edges: data?.graph.edges().length || 0
}));
} else {
notify({
type: "error",
message: result.error || "Setup failed",
});
const errorMessages = [...graphragState.messages, {
id: generateMessageId(),
type: 'system' as const,
content: `❌ Setup failed: ${result.error || 'Unknown error'}`,
timestamp: new Date()
}];
updateState({ messages: errorMessages });
}
} catch (error) {
console.error('Setup error:', error);
notify({
type: "error",
message: "Failed to setup GraphRAG system",
});
const errorMessages = [...graphragState.messages, {
id: generateMessageId(),
type: 'system' as const,
content: `❌ Setup failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
timestamp: new Date()
}];
updateState({ messages: errorMessages });
} finally {
setIsSetupLoading(false);
}
};
const handleQuery = async () => {
if (!query.trim()) {
return;
}
if (!graphragState.isReady) {
notify({
type: "error",
message: "Please complete setup first",
});
return;
}
const userMessage = query.trim();
setQuery("");
setIsLoading(true);
// Add user message
const newMessages = [...graphragState.messages, {
id: generateMessageId(),
type: 'user' as const,
content: userMessage,
timestamp: new Date()
}];
updateState({ messages: newMessages });
try {
const response = await fetch(API_ENDPOINTS.GRAPHRAG_QUERY, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
query: userMessage,
provider: graphragState.selectedProvider,
apiKeys: getSessionAPIKeys(),
}),
});
const data = await response.json();
if (data.success) {
const updatedMessages = [...newMessages, {
id: generateMessageId(),
type: 'assistant' as const,
content: data.result,
timestamp: new Date()
}];
updateState({ messages: updatedMessages });
} else {
const errorMessages = [...newMessages, {
id: generateMessageId(),
type: 'assistant' as const,
content: `❌ Error: ${data.error || data.message}`,
timestamp: new Date()
}];
updateState({ messages: errorMessages });
notify({
type: "error",
message: data.error || data.message,
});
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
const errorMessages = [...newMessages, {
id: generateMessageId(),
type: 'assistant' as const,
content: `❌ Error: ${errorMessage}`,
timestamp: new Date()
}];
updateState({ messages: errorMessages });
notify({
type: "error",
message: errorMessage,
});
} finally {
setIsLoading(false);
}
};
// Check for graph changes only when user navigates to GraphRAG tab
useEffect(() => {
if (!data || !graphFile?.textContent) return;
// Use graphStats which accounts for filtered nodes
const currentNodeCount = graphStats.nodes;
const currentEdgeCount = graphStats.edges;
// Get stored statistics
const storedStats = sessionStorage.getItem('graphrag_last_stats');
// Only check for changes if we have previous stats (not first visit)
if (storedStats) {
try {
const { nodes: lastNodeCount, edges: lastEdgeCount } = JSON.parse(storedStats);
// Check if statistics have changed
if (lastNodeCount !== currentNodeCount || lastEdgeCount !== currentEdgeCount) {
console.log('Graph statistics changed! User navigated to GraphRAG tab.', {
previous: { nodes: lastNodeCount, edges: lastEdgeCount },
current: { nodes: currentNodeCount, edges: currentEdgeCount }
});
// Only show the prompt if we haven't already shown it for this session
if (!hasShownRebuildPrompt.current) {
// Add a system message to the chat asking if user wants to rebuild
const changeMessage = {
id: generateMessageId(),
type: 'system' as const,
content: `📊 **Graph Structure Changed**\n\nI noticed the graph structure has changed since you last used GraphRAG:\n\n**Previous:** ${lastNodeCount} nodes, ${lastEdgeCount} edges\n**Current:** ${currentNodeCount} nodes, ${currentEdgeCount} edges\n\nWould you like me to rebuild the GraphRAG database to include the latest changes?`,
timestamp: new Date(),
actions: [
{
label: "Rebuild GraphRAG",
action: "rebuild",
data: { previous: { nodes: lastNodeCount, edges: lastEdgeCount }, current: { nodes: currentNodeCount, edges: currentEdgeCount } }
},
{
label: "Keep Existing",
action: "keep",
data: { previous: { nodes: lastNodeCount, edges: lastEdgeCount }, current: { nodes: currentNodeCount, edges: currentEdgeCount } }
}
]
};
updateState({
messages: [...graphragState.messages, changeMessage]
});
setShowRebuildPrompt(true);
hasShownRebuildPrompt.current = true;
}
} else {
// No changes detected, just update stored statistics
sessionStorage.setItem('graphrag_last_stats', JSON.stringify({
nodes: currentNodeCount,
edges: currentEdgeCount
}));
}
} catch (error) {
console.error('Error parsing stored stats:', error);
// Update stored statistics on error
sessionStorage.setItem('graphrag_last_stats', JSON.stringify({
nodes: currentNodeCount,
edges: currentEdgeCount
}));
}
} else {
// First visit - just store initial statistics without alerting
sessionStorage.setItem('graphrag_last_stats', JSON.stringify({
nodes: currentNodeCount,
edges: currentEdgeCount
}));
}
}, [graphFile?.textContent]); // Only trigger when component mounts (user switches to tab)
// Handle action button clicks in messages
const handleMessageAction = (action: string, data: any) => {
if (action === 'rebuild') {
// Trigger GraphRAG rebuild
handleSetup().then(() => {
// Update stored statistics after successful setup
sessionStorage.setItem('graphrag_last_stats', JSON.stringify({
nodes: data.current.nodes,
edges: data.current.edges
}));
// Add confirmation message
const confirmMessage = {
id: generateMessageId(),
type: 'assistant' as const,
content: '✅ GraphRAG database has been rebuilt with the latest graph structure. You can now ask questions about your updated graph!',
timestamp: new Date()
};
updateState({
messages: [...graphragState.messages, confirmMessage]
});
});
} else if (action === 'keep') {
// User chose to keep existing database
sessionStorage.setItem('graphrag_last_stats', JSON.stringify({
nodes: data.current.nodes,
edges: data.current.edges
}));
// Add confirmation message
const confirmMessage = {
id: generateMessageId(),
type: 'assistant' as const,
content: '👍 Got it! I\'ll keep using the existing GraphRAG database. You can continue asking questions about your graph.',
timestamp: new Date()
};
updateState({
messages: [...graphragState.messages, confirmMessage]
});
}
setShowRebuildPrompt(false);
hasShownRebuildPrompt.current = false; // Reset so they can see the prompt again if they make more changes
};
const getProviderIcon = (provider: string) => {
switch (provider) {
case "openai":
return <AiOutlineRobot className="me-2" />;
case "azure_openai":
return <FaMicrosoft className="me-2" />;
case "gemini":
return <SiGoogle className="me-2" />;
default:
return <AiOutlineRobot className="me-2" />;
}
};
const formatTime = (date: Date | string) => {
const dateObj = typeof date === 'string' ? new Date(date) : date;
return dateObj.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
};
const renderMessageContent = (content: string) => {
// Parse repository links in format [repository_name](repo_id)
const linkRegex = /\[([^\]]+)\]\(([^)]+)\)/g;
const parts = [];
let lastIndex = 0;
let match;
while ((match = linkRegex.exec(content)) !== null) {
// Add text before the link
if (match.index > lastIndex) {
parts.push(content.slice(lastIndex, match.index));
}
// Add the clickable link
const repoName = match[1];
const repoId = match[2];
parts.push(
<button
key={`link-${match.index}`}
className="btn btn-link p-0 text-decoration-none"
style={{ color: '#007bff', fontWeight: 'bold' }}
onClick={() => handleRepoClick(repoId)}
title={`Click to focus on ${repoName} in the graph`}
>
{repoName}
</button>
);
lastIndex = match.index + match[0].length;
}
// Add remaining text
if (lastIndex < content.length) {
parts.push(content.slice(lastIndex));
}
// If no markdown links were found, try to detect owner/repo patterns
if (parts.length === 1 && typeof parts[0] === 'string') {
return detectAndLinkRepositories(parts[0]);
}
return parts.length > 0 ? parts : content;
};
const detectAndLinkRepositories = (text: string) => {
// Pattern to match owner/repo format (e.g., "cozodb/cozo", "vmware/differential-datalog")
const repoPattern = /\b([a-zA-Z0-9](?:[a-zA-Z0-9]|-(?=[a-zA-Z0-9]))*)\/([a-zA-Z0-9](?:[a-zA-Z0-9]|-(?=[a-zA-Z0-9]))*)\b/g;
const parts = [];
let lastIndex = 0;
let match;
while ((match = repoPattern.exec(text)) !== null) {
// Add text before the match
if (match.index > lastIndex) {
parts.push(text.slice(lastIndex, match.index));
}
// Check if this repository exists in the graph
const repoName = match[0]; // e.g., "cozodb/cozo"
const nodeId = findNodeByRepoName(repoName);
if (nodeId) {
// Add the clickable link
parts.push(
<button
key={`repo-link-${match.index}`}
className="btn btn-link p-0 text-decoration-none"
style={{ color: '#007bff', fontWeight: 'bold' }}
onClick={() => handleRepoClick(nodeId)}
title={`Click to focus on ${repoName} in the graph`}
>
{repoName}
</button>
);
} else {
// Repository not found in graph, just add as text
parts.push(repoName);
}
lastIndex = match.index + match[0].length;
}
// Add remaining text
if (lastIndex < text.length) {
parts.push(text.slice(lastIndex));
}
return parts.length > 0 ? parts : text;
};
const findNodeByRepoName = (repoName: string): string | null => {
if (!data?.graph) return null;
// Search through all nodes to find one with matching label
const nodes = data.graph.nodes();