ChatInterface.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. import React, { useState, useRef, useEffect } from 'react';
  2. import { Send, Loader2, Paperclip, X, Search, Database } from 'lucide-react';
  3. import { useLanguage } from '../contexts/LanguageContext';
  4. import {
  5. AppSettings,
  6. KnowledgeFile,
  7. ModelConfig,
  8. Message,
  9. Role,
  10. KnowledgeGroup
  11. } from '../types';
  12. import ChatMessage from './ChatMessage'; // Assuming ChatMessage is a default export based on original code
  13. import SearchResultsPanel from './SearchResultsPanel';
  14. import { chatService, ChatMessage as ChatMsg, ChatSource } from '../services/chatService';
  15. import { generateUUID } from '../utils/uuid';
  16. interface ChatInterfaceProps {
  17. files: KnowledgeFile[];
  18. settings: AppSettings;
  19. models: ModelConfig[];
  20. groups: KnowledgeGroup[];
  21. selectedGroups: string[];
  22. onGroupSelectionChange?: (groupIds: string[]) => void;
  23. onOpenGroupSelection?: () => void; // New prop
  24. selectedFiles?: string[];
  25. onClearFileSelection?: () => void;
  26. onMobileUploadClick: () => void;
  27. currentHistoryId?: string;
  28. historyMessages?: any[] | null;
  29. onHistoryMessagesLoaded?: () => void;
  30. onPreviewSource?: (source: ChatSource) => void;
  31. onOpenFile?: (source: ChatSource) => void;
  32. onHistoryIdCreated?: (historyId: string) => void;
  33. authToken?: string; // Add optional auth token prop
  34. }
  35. const ChatInterface: React.FC<ChatInterfaceProps> = ({
  36. files,
  37. settings,
  38. models,
  39. groups,
  40. selectedGroups,
  41. onGroupSelectionChange,
  42. onOpenGroupSelection,
  43. selectedFiles,
  44. onClearFileSelection,
  45. onMobileUploadClick,
  46. currentHistoryId,
  47. historyMessages,
  48. onHistoryMessagesLoaded,
  49. onPreviewSource,
  50. onOpenFile,
  51. onHistoryIdCreated,
  52. authToken
  53. }) => {
  54. const { t, language } = useLanguage();
  55. const [messages, setMessages] = useState<Message[]>([]);
  56. const [input, setInput] = useState('');
  57. const [isLoading, setIsLoading] = useState(false);
  58. const [sources, setSources] = useState<ChatSource[]>([]);
  59. const [showSources, setShowSources] = useState(false);
  60. const messagesEndRef = useRef<HTMLDivElement>(null);
  61. const inputRef = useRef<HTMLTextAreaElement>(null);
  62. const lastSubmitTime = useRef<number>(0);
  63. // Debug logging
  64. // console.log('ChatInterface Render:', {
  65. // selectedFilesCount: selectedFiles?.length,
  66. // totalFilesCount: files.length,
  67. // selectedFiles: selectedFiles,
  68. // matchedFiles: files.filter(f => selectedFiles?.includes(f.id)).map(f => f.name)
  69. // });
  70. // Handle loading of history messages
  71. // Handle loading of history messages
  72. useEffect(() => {
  73. if (historyMessages && historyMessages.length > 0) {
  74. const convertedMessages: Message[] = historyMessages.map(msg => ({
  75. id: msg.id,
  76. role: msg.role === 'user' ? Role.USER : Role.MODEL,
  77. text: msg.content,
  78. timestamp: new Date(msg.createdAt).getTime(),
  79. sources: msg.sources // Attach sources to message
  80. }));
  81. setMessages(convertedMessages);
  82. // Notify parent component that history messages have been loaded
  83. onHistoryMessagesLoaded?.();
  84. }
  85. }, [historyMessages, onHistoryMessagesLoaded]);
  86. useEffect(() => {
  87. const welcomeText = t('welcomeMessage');
  88. setMessages((prevMessages) => {
  89. if (prevMessages.length === 0) {
  90. return [
  91. {
  92. id: 'welcome',
  93. role: Role.MODEL,
  94. text: welcomeText,
  95. timestamp: Date.now(),
  96. },
  97. ];
  98. }
  99. const hasWelcome = prevMessages.some(m => m.id === 'welcome');
  100. if (hasWelcome) {
  101. return prevMessages.map(m =>
  102. m.id === 'welcome'
  103. ? { ...m, text: welcomeText }
  104. : m
  105. );
  106. }
  107. return prevMessages;
  108. });
  109. }, [t]);
  110. const scrollToBottom = () => {
  111. messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  112. };
  113. useEffect(() => {
  114. scrollToBottom();
  115. }, [messages]);
  116. const handleSend = async () => {
  117. if (!input.trim() || isLoading) return;
  118. // Debounce mechanism: prevent duplicate submissions within 500ms
  119. const now = Date.now();
  120. if (now - lastSubmitTime.current < 500) {
  121. console.log('Preventing duplicate submission');
  122. return;
  123. }
  124. lastSubmitTime.current = now;
  125. const userText = input.trim();
  126. // Instantly clear input field and reset height to prevent duplicate submission
  127. setInput('');
  128. if (inputRef.current) {
  129. inputRef.current.style.height = 'auto';
  130. inputRef.current.blur(); // Remove focus
  131. }
  132. // Resolve Model Config
  133. const selectedModel = models.find(m => m.id === settings.selectedLLMId && m.type === 'llm');
  134. if (!selectedModel) {
  135. const errorMsg: Message = {
  136. id: generateUUID(),
  137. role: Role.MODEL,
  138. text: `${t('errorNoModel')} - LLM ID: ${settings.selectedLLMId}, Models: ${models.length} `,
  139. timestamp: Date.now(),
  140. isError: true,
  141. };
  142. setMessages(prev => [...prev, errorMsg]);
  143. return;
  144. }
  145. const newMessage: Message = {
  146. id: generateUUID(),
  147. role: Role.USER,
  148. text: userText,
  149. timestamp: Date.now(),
  150. };
  151. setIsLoading(true);
  152. setMessages((prev) => [...prev, newMessage]);
  153. const effectiveToken = authToken || localStorage.getItem('kb_api_key') || localStorage.getItem('authToken');
  154. if (!effectiveToken) {
  155. const errorMsg: Message = {
  156. id: generateUUID(),
  157. role: Role.MODEL,
  158. text: t('needLogin'),
  159. timestamp: Date.now(),
  160. isError: true,
  161. };
  162. setMessages(prev => [...prev, errorMsg]);
  163. setIsLoading(false);
  164. return;
  165. }
  166. try {
  167. const history: ChatMsg[] = messages
  168. .filter(m => m.id !== 'welcome')
  169. .map(m => ({
  170. role: m.role === Role.USER ? 'user' : 'assistant',
  171. content: m.text,
  172. }));
  173. const botMessageId = generateUUID();
  174. let botContent = '';
  175. // Add initial bot message
  176. const botMessage: Message = {
  177. id: botMessageId,
  178. role: Role.MODEL,
  179. text: '',
  180. timestamp: Date.now(),
  181. };
  182. setMessages(prev => [...prev, botMessage]);
  183. const stream = chatService.streamChat(
  184. userText,
  185. history,
  186. effectiveToken,
  187. language,
  188. settings.selectedEmbeddingId,
  189. settings.selectedLLMId, // Pass selected LLM ID
  190. selectedGroups.length > 0 ? selectedGroups : undefined, // Pass group filter
  191. selectedFiles?.length > 0 ? selectedFiles : undefined, // Pass file filter
  192. currentHistoryId, // Pass history ID
  193. settings.enableRerank, // Pass Rerank switch
  194. settings.selectedRerankId, // Pass Rerank model ID
  195. settings.temperature, // Pass temperature parameter
  196. settings.maxTokens, // Pass max tokens
  197. settings.topK, // Pass Top-K parameter
  198. settings.similarityThreshold, // Pass similarity threshold
  199. settings.rerankSimilarityThreshold, // Pass Rerank threshold
  200. settings.enableQueryExpansion, // Pass query expansion
  201. settings.enableHyDE // Pass HyDE
  202. );
  203. for await (const chunk of stream) {
  204. if (chunk.type === 'content') {
  205. botContent += chunk.data;
  206. setMessages(prev =>
  207. prev.map(msg =>
  208. msg.id === botMessageId
  209. ? { ...msg, text: botContent }
  210. : msg
  211. )
  212. );
  213. } else if (chunk.type === 'sources') {
  214. // Attach sources to the current bot message
  215. setMessages(prev =>
  216. prev.map(msg =>
  217. msg.id === botMessageId
  218. ? { ...msg, sources: chunk.data }
  219. : msg
  220. )
  221. );
  222. } else if (chunk.type === 'historyId') {
  223. onHistoryIdCreated?.(chunk.data);
  224. } else if (chunk.type === 'error') {
  225. setMessages(prev =>
  226. prev.map(msg =>
  227. msg.id === botMessageId
  228. ? { ...msg, text: t('errorMessage').replace('$1', chunk.data), isError: true }
  229. : msg
  230. )
  231. );
  232. break;
  233. }
  234. }
  235. } catch (error: any) {
  236. console.error('Chat error:', error);
  237. let errorText = t('errorGeneric');
  238. if (error.message === "API_KEY_MISSING") errorText = t('apiError');
  239. else if (error.message.includes("OpenAI API Error")) errorText = `OpenAI Error: ${error.message} `;
  240. else if (error.message === "GEMINI_API_ERROR") errorText = t('geminiError');
  241. else if (error.message) errorText = `Error: ${error.message} `;
  242. const errorMessage: Message = {
  243. id: generateUUID(),
  244. role: Role.MODEL,
  245. text: errorText,
  246. timestamp: Date.now(),
  247. isError: true,
  248. };
  249. setMessages((prev) => [...prev, errorMessage]);
  250. } finally {
  251. setIsLoading(false);
  252. lastSubmitTime.current = 0;
  253. }
  254. };
  255. const handleKeyDown = (e: React.KeyboardEvent) => {
  256. if (e.key === 'Enter' && !e.shiftKey) {
  257. e.preventDefault();
  258. if (!isLoading && input.trim()) {
  259. handleSend();
  260. }
  261. }
  262. };
  263. const handleInputResize = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
  264. setInput(e.target.value);
  265. e.target.style.height = 'auto';
  266. e.target.style.height = `${Math.min(e.target.scrollHeight, 200)} px`;
  267. };
  268. return (
  269. <div className="flex flex-col h-full bg-transparent relative overflow-hidden">
  270. <div className="flex-1 overflow-y-auto px-4 md:px-8 pt-6 pb-32 space-y-8 scrollbar-hide">
  271. {messages.map((msg) => (
  272. <ChatMessage
  273. key={msg.id}
  274. message={msg}
  275. onPreviewSource={onPreviewSource}
  276. onOpenFile={onOpenFile}
  277. />
  278. ))}
  279. {isLoading && (
  280. <div className="flex justify-start animate-in fade-in slide-in-from-left-2 duration-300">
  281. <div className="flex flex-row gap-4 items-start translate-x-1">
  282. <div className="w-9 h-9 rounded-xl bg-white/80 backdrop-blur-sm border border-slate-200/50 flex items-center justify-center shadow-sm">
  283. <Loader2 className="w-4 h-4 text-indigo-600 animate-spin" />
  284. </div>
  285. <div className="bg-white/80 backdrop-blur-md border border-white/40 px-5 py-3.5 rounded-2xl rounded-tl-none shadow-sm flex items-center">
  286. <div className="flex items-center gap-2">
  287. <div className="flex gap-1">
  288. <span className="w-1.5 h-1.5 bg-indigo-400 rounded-full animate-bounce [animation-delay:-0.3s]"></span>
  289. <span className="w-1.5 h-1.5 bg-indigo-400 rounded-full animate-bounce [animation-delay:-0.15s]"></span>
  290. <span className="w-1.5 h-1.5 bg-indigo-400 rounded-full animate-bounce"></span>
  291. </div>
  292. <span className="text-sm font-medium text-slate-500 ml-2 tracking-wide uppercase text-[10px]">{t('analyzing')}</span>
  293. </div>
  294. </div>
  295. </div>
  296. </div>
  297. )}
  298. <div ref={messagesEndRef} />
  299. </div>
  300. <div className="absolute bottom-6 left-0 right-0 px-4 md:px-8 pointer-events-none">
  301. <div className="max-w-4xl mx-auto pointer-events-auto">
  302. {((selectedFiles && selectedFiles.length > 0) || true) && (
  303. <div className="mb-3 flex flex-wrap gap-2 animate-in slide-in-from-bottom-2 duration-300">
  304. {/* Group Selection Button */}
  305. <button
  306. type="button"
  307. onClick={onOpenGroupSelection}
  308. className={`flex items-center gap-2 px-3.5 py-1.5 rounded-full text-xs font-semibold transition-all border shadow-sm ${selectedGroups.length > 0
  309. ? 'bg-blue-600 text-white border-blue-500 hover:bg-blue-700'
  310. : 'bg-white/90 backdrop-blur-md text-slate-600 border-slate-200/60 hover:bg-white'
  311. }`}
  312. title={t('selectKnowledgeGroup')}
  313. >
  314. <Database size={13} className={selectedGroups.length > 0 ? "text-blue-100" : "text-blue-500"} />
  315. <span className="truncate max-w-[150px]">
  316. {selectedGroups.length === 0
  317. ? t('allKnowledgeGroups')
  318. : selectedGroups.length <= 1
  319. ? (groups.find(g => g.id === selectedGroups[0])?.name || t('unknownGroup'))
  320. : t('selectedGroupsCount').replace('$1', selectedGroups.length.toString())}
  321. </span>
  322. </button>
  323. {files.filter(f => selectedFiles?.includes(f.id)).map(file => (
  324. <div key={file.id} className="flex items-center gap-1.5 bg-indigo-50 text-indigo-700 px-3 py-1.5 rounded-full text-xs font-semibold border border-indigo-100 shadow-sm animate-in zoom-in-95">
  325. <span className="truncate max-w-[150px]">{file.title || file.name}</span>
  326. <button
  327. onClick={onClearFileSelection}
  328. className="hover:bg-indigo-200/50 rounded-full p-0.5 transition-colors"
  329. >
  330. <X size={12} />
  331. </button>
  332. </div>
  333. ))}
  334. </div>
  335. )}
  336. <div className="bg-white rounded-2xl border border-slate-200 shadow-sm flex items-end p-2.5 transition-all duration-300 focus-within:ring-2 focus-within:ring-blue-500/20 focus-within:border-blue-400 group/input">
  337. <button
  338. onClick={onMobileUploadClick}
  339. className="md:hidden p-3 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded-xl transition-colors"
  340. >
  341. <Paperclip className="w-5 h-5" />
  342. </button>
  343. <textarea
  344. ref={inputRef}
  345. value={input}
  346. onChange={handleInputResize}
  347. onKeyDown={handleKeyDown}
  348. placeholder={files.length > 0 ? t('placeholderWithFiles') : t('placeholderEmpty')}
  349. className="flex-1 max-h-[250px] min-h-[48px] bg-transparent border-none focus:ring-0 text-slate-800 placeholder:text-slate-400/80 resize-none py-3 px-4 text-[15px] leading-relaxed"
  350. rows={1}
  351. disabled={files.length === 0 && messages.length < 2 && false}
  352. />
  353. <button
  354. onClick={handleSend}
  355. disabled={!input.trim() || isLoading}
  356. className={`p-3 rounded-xl mb-0.5 ml-2 transition-all duration-300 ${input.trim() && !isLoading
  357. ? 'bg-gradient-to-br from-blue-600 to-indigo-600 text-white hover:shadow-lg hover:shadow-blue-500/30 transform hover:-translate-y-0.5 active:translate-y-0 active:scale-95'
  358. : 'bg-slate-100 text-slate-300 cursor-not-allowed'
  359. } `}
  360. type="button"
  361. >
  362. {isLoading ? (
  363. <Loader2 className="w-5 h-5 animate-spin" />
  364. ) : (
  365. <Send className="w-5 h-5" />
  366. )}
  367. </button>
  368. </div>
  369. <p className="text-center text-[10px] text-slate-400/80 mt-3 font-medium tracking-tight uppercase">
  370. {t('aiDisclaimer')}
  371. </p>
  372. </div>
  373. </div>
  374. </div>
  375. );
  376. };
  377. export default ChatInterface;