forked from Greyisheep/apiconf-agent
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathChat.tsx
More file actions
207 lines (176 loc) · 6.94 KB
/
Chat.tsx
File metadata and controls
207 lines (176 loc) · 6.94 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
import React, { useCallback, useEffect, useRef, useState } from 'react';
import ReactMarkdown from 'react-markdown';
import TypingIndicator from './TypingIndicator';
import remarkGfm from 'remark-gfm';
import styles from './Chat.module.css';
import type { Message,ChatProps,HandleSendType } from '../../types/DataTypes'
import Header from './sub-components/Header';
import WelcomePromptSuggestions from './sub-components/WelcomePromptSuggestions';
import InputArea from './sub-components/InputArea';
const Chat: React.FC<ChatProps> = ({ onMenuClick, resetSignal }) => {
const [messages, setMessages] = useState<Message[]>([]);
const [input, setInput] = useState('');
const [isTyping, setIsTyping] = useState(false);
const [processedMessages, setProcessedMessages] = useState<Set<string>>(new Set());
const [hasProcessedUrlMessage, setHasProcessedUrlMessage] = useState(false);
const [error, setError] = useState<string | null>(null);
const getOrCreateId = (key: string) => {
let id = localStorage.getItem(key);
if (!id) {
id = Math.random().toString(36).substring(2, 15) + Date.now().toString(36);
localStorage.setItem(key, id);
}
return id;
};
const userId = getOrCreateId('apiconf_user_id');
const sessionId = getOrCreateId('apiconf_session_id');
const handleSend:HandleSendType = useCallback(async (messageToSend: string) => {
if (!messageToSend.trim()) return;
// Save the first user message as the preview for the history
const isFirstUserMessage = messages.filter(m => m.sender === 'user').length === 0;
if (isFirstUserMessage) {
localStorage.setItem(`session_preview_${sessionId}`, messageToSend);
}
if (processedMessages.has(messageToSend)) {
console.log('Message already processed:', messageToSend);
return;
}
console.log('Sending message to /api/v1/agents/chat:', messageToSend);
const userMessage: Message = {
text: messageToSend,
sender: 'user',
timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
};
setMessages((prevMessages) => [...prevMessages, userMessage]);
setIsTyping(true);
setError(null);
try {
const response = await fetch('/api/v1/agents/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
message: messageToSend,
user_id: userId,
session_id: sessionId,
}),
});
if (!response.ok) {
throw new Error(`Network response was not ok: ${response.status}`);
}
const result = await response.json();
console.log('API response:', result);
const botMessage: Message = {
text: result.data.response,
sender: 'bot',
timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
};
setMessages((prevMessages) => [...prevMessages, botMessage]);
setProcessedMessages((prev) => new Set(prev).add(messageToSend));
// Clear URL parameters after processing
if (window.location.search) {
window.history.replaceState({}, document.title, window.location.pathname);
}
} catch (error) {
console.error('Error fetching chat response:', error);
setError('Sorry, I seem to be having trouble connecting. Please try again later.');
const errorMessage: Message = {
text: 'Sorry, I seem to be having trouble connecting. Please try again later.',
sender: 'bot',
timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
};
setMessages((prevMessages) => [...prevMessages, errorMessage]);
} finally {
setIsTyping(false);
}
}, [processedMessages, userId, sessionId, messages]);
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
handleSend(input);
setInput('');
};
const messagesEndRef = useRef<null | HTMLDivElement>(null);
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
};
useEffect(() => {
scrollToBottom();
}, [messages, isTyping]);
// Handle URL parameter from external page
useEffect(() => {
if (hasProcessedUrlMessage) return;
console.log('=== URL DEBUGGING ===');
console.log('Current URL:', window.location.href);
console.log('Search params:', window.location.search);
console.log('Pathname:', window.location.pathname);
// Use native URLSearchParams to ensure we get the URL parameter
const urlParams = new URLSearchParams(window.location.search);
const messageFromUrl = urlParams.get('message');
console.log('All URL params:', Object.fromEntries(urlParams));
console.log('Message from URL:', messageFromUrl);
if (messageFromUrl) {
const decodedMessage = decodeURIComponent(messageFromUrl);
console.log('Decoded message:', decodedMessage);
console.log('About to send message to API...');
setHasProcessedUrlMessage(true);
// Add a small delay to ensure the component is fully mounted
setTimeout(() => {
handleSend(decodedMessage);
}, 100);
} else {
console.log('No message parameter found in URL');
}
}, [handleSend, hasProcessedUrlMessage]);
useEffect(() => {
// A reset signal tells the chat to clear its messages.
// This is used for starting a new chat or restoring an old one.
if (resetSignal !== undefined && resetSignal > 0) {
setMessages([]);
setProcessedMessages(new Set());
}
}, [resetSignal]);
return (
<div className={styles.chat}>
{/* header */}
<Header onMenuClick={onMenuClick}/>
<div className={styles.content}>
<div className={styles.messages}>
{messages.length === 0 ? (
<WelcomePromptSuggestions handleSend={handleSend}/>
) : (
messages.map((msg, index) => (
<div
key={index}
className={`${styles.message} ${
msg.sender === 'user' ? styles.user : styles.bot
}`}
>
<div className={styles.messageContent}>
{msg.sender === 'bot' ? (
<ReactMarkdown remarkPlugins={[remarkGfm]}>
{msg.text}
</ReactMarkdown>
) : (
msg.text
)}
</div>
<div className={styles.timestamp}>{msg.timestamp}</div>
</div>
))
)}
{isTyping && (
<div className={`${styles.message} ${styles.bot} ${styles.typing}`}>
<TypingIndicator />
<span>Ndu is typing...</span>
</div>
)}
{error && <div className={styles.error}>{error}</div>}
<div ref={messagesEndRef} />
</div>
</div>
<InputArea input={input} setInput={setInput} handleSubmit={handleSubmit}/>
</div>
);
};
export default Chat;