ChatInterface.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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. }
  34. const ChatInterface: React.FC<ChatInterfaceProps> = ({
  35. files,
  36. settings,
  37. models,
  38. groups,
  39. selectedGroups,
  40. onGroupSelectionChange,
  41. onOpenGroupSelection,
  42. selectedFiles,
  43. onClearFileSelection,
  44. onMobileUploadClick,
  45. currentHistoryId,
  46. historyMessages,
  47. onHistoryMessagesLoaded,
  48. onPreviewSource,
  49. onOpenFile,
  50. onHistoryIdCreated
  51. }) => {
  52. const { t, language } = useLanguage();
  53. const [messages, setMessages] = useState<Message[]>([]);
  54. const [input, setInput] = useState('');
  55. const [isLoading, setIsLoading] = useState(false);
  56. const [sources, setSources] = useState<ChatSource[]>([]);
  57. const [showSources, setShowSources] = useState(false);
  58. const messagesEndRef = useRef<HTMLDivElement>(null);
  59. const inputRef = useRef<HTMLTextAreaElement>(null);
  60. const lastSubmitTime = useRef<number>(0);
  61. // Debug logging
  62. // console.log('ChatInterface Render:', {
  63. // selectedFilesCount: selectedFiles?.length,
  64. // totalFilesCount: files.length,
  65. // selectedFiles: selectedFiles,
  66. // matchedFiles: files.filter(f => selectedFiles?.includes(f.id)).map(f => f.name)
  67. // });
  68. // 履歴メッセージの読み込みを処理
  69. // 履歴メッセージの読み込みを処理
  70. useEffect(() => {
  71. if (historyMessages && historyMessages.length > 0) {
  72. const convertedMessages: Message[] = historyMessages.map(msg => ({
  73. id: msg.id,
  74. role: msg.role === 'user' ? Role.USER : Role.MODEL,
  75. text: msg.content,
  76. timestamp: new Date(msg.createdAt).getTime(),
  77. sources: msg.sources // Attach sources to message
  78. }));
  79. setMessages(convertedMessages);
  80. // 履歴メッセージが読み込まれたことを親コンポーネントに通知
  81. onHistoryMessagesLoaded?.();
  82. }
  83. }, [historyMessages, onHistoryMessagesLoaded]);
  84. useEffect(() => {
  85. const welcomeText = t('welcomeMessage');
  86. setMessages((prevMessages) => {
  87. if (prevMessages.length === 0) {
  88. return [
  89. {
  90. id: 'welcome',
  91. role: Role.MODEL,
  92. text: welcomeText,
  93. timestamp: Date.now(),
  94. },
  95. ];
  96. }
  97. const hasWelcome = prevMessages.some(m => m.id === 'welcome');
  98. if (hasWelcome) {
  99. return prevMessages.map(m =>
  100. m.id === 'welcome'
  101. ? { ...m, text: welcomeText }
  102. : m
  103. );
  104. }
  105. return prevMessages;
  106. });
  107. }, [t]);
  108. const scrollToBottom = () => {
  109. messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  110. };
  111. useEffect(() => {
  112. scrollToBottom();
  113. }, [messages]);
  114. const handleSend = async () => {
  115. if (!input.trim() || isLoading) return;
  116. // デバウンス機構:500ms以内の重複送信を防止
  117. const now = Date.now();
  118. if (now - lastSubmitTime.current < 500) {
  119. console.log('Preventing duplicate submission');
  120. return;
  121. }
  122. lastSubmitTime.current = now;
  123. const userText = input.trim();
  124. // 入力欄を即座にクリアして高さをリセットし、重複送信を防止
  125. setInput('');
  126. if (inputRef.current) {
  127. inputRef.current.style.height = 'auto';
  128. inputRef.current.blur(); // フォーカスを外す
  129. }
  130. // Resolve Model Config
  131. const selectedModel = models.find(m => m.id === settings.selectedLLMId && m.type === 'llm');
  132. if (!selectedModel) {
  133. const errorMsg: Message = {
  134. id: generateUUID(),
  135. role: Role.MODEL,
  136. text: `${t('errorNoModel')} - LLM ID: ${settings.selectedLLMId}, Models: ${models.length} `,
  137. timestamp: Date.now(),
  138. isError: true,
  139. };
  140. setMessages(prev => [...prev, errorMsg]);
  141. return;
  142. }
  143. const newMessage: Message = {
  144. id: generateUUID(),
  145. role: Role.USER,
  146. text: userText,
  147. timestamp: Date.now(),
  148. };
  149. setIsLoading(true);
  150. setMessages((prev) => [...prev, newMessage]);
  151. const authToken = localStorage.getItem('authToken');
  152. if (!authToken) {
  153. const errorMsg: Message = {
  154. id: generateUUID(),
  155. role: Role.MODEL,
  156. text: t('needLogin'),
  157. timestamp: Date.now(),
  158. isError: true,
  159. };
  160. setMessages(prev => [...prev, errorMsg]);
  161. setIsLoading(false);
  162. return;
  163. }
  164. try {
  165. const history: ChatMsg[] = messages
  166. .filter(m => m.id !== 'welcome')
  167. .map(m => ({
  168. role: m.role === Role.USER ? 'user' : 'assistant',
  169. content: m.text,
  170. }));
  171. const botMessageId = generateUUID();
  172. let botContent = '';
  173. // 初期ボットメッセージを追加
  174. const botMessage: Message = {
  175. id: botMessageId,
  176. role: Role.MODEL,
  177. text: '',
  178. timestamp: Date.now(),
  179. };
  180. setMessages(prev => [...prev, botMessage]);
  181. const stream = chatService.streamChat(
  182. userText,
  183. history,
  184. authToken,
  185. language,
  186. settings.selectedEmbeddingId,
  187. settings.selectedLLMId, // Pass selected LLM ID
  188. selectedGroups.length > 0 ? selectedGroups : undefined, // グループフィルタを渡す
  189. selectedFiles?.length > 0 ? selectedFiles : undefined, // ファイルフィルタを渡す
  190. currentHistoryId, // 履歴IDを渡す
  191. settings.enableRerank, // Rerankスイッチを渡す
  192. settings.selectedRerankId, // RerankモデルIDを渡す
  193. settings.temperature, // 温度パラメータを渡す
  194. settings.maxTokens, // 最大トークン数を渡す
  195. settings.topK, // Top-Kパラメータを渡す
  196. settings.similarityThreshold, // 類似度しきい値を渡す
  197. settings.rerankSimilarityThreshold // Rerankしきい値を渡す
  198. );
  199. for await (const chunk of stream) {
  200. if (chunk.type === 'content') {
  201. botContent += chunk.data;
  202. setMessages(prev =>
  203. prev.map(msg =>
  204. msg.id === botMessageId
  205. ? { ...msg, text: botContent }
  206. : msg
  207. )
  208. );
  209. } else if (chunk.type === 'sources') {
  210. // Attach sources to the current bot message
  211. setMessages(prev =>
  212. prev.map(msg =>
  213. msg.id === botMessageId
  214. ? { ...msg, sources: chunk.data }
  215. : msg
  216. )
  217. );
  218. } else if (chunk.type === 'historyId') {
  219. onHistoryIdCreated?.(chunk.data);
  220. } else if (chunk.type === 'error') {
  221. setMessages(prev =>
  222. prev.map(msg =>
  223. msg.id === botMessageId
  224. ? { ...msg, text: t('errorMessage').replace('$1', chunk.data), isError: true }
  225. : msg
  226. )
  227. );
  228. break;
  229. }
  230. }
  231. } catch (error: any) {
  232. console.error('Chat error:', error);
  233. let errorText = t('errorGeneric');
  234. if (error.message === "API_KEY_MISSING") errorText = t('apiError');
  235. else if (error.message.includes("OpenAI API Error")) errorText = `OpenAI Error: ${error.message} `;
  236. else if (error.message === "GEMINI_API_ERROR") errorText = t('geminiError');
  237. else if (error.message) errorText = `Error: ${error.message} `;
  238. const errorMessage: Message = {
  239. id: generateUUID(),
  240. role: Role.MODEL,
  241. text: errorText,
  242. timestamp: Date.now(),
  243. isError: true,
  244. };
  245. setMessages((prev) => [...prev, errorMessage]);
  246. } finally {
  247. setIsLoading(false);
  248. lastSubmitTime.current = 0;
  249. }
  250. };
  251. const handleKeyDown = (e: React.KeyboardEvent) => {
  252. if (e.key === 'Enter' && !e.shiftKey) {
  253. e.preventDefault();
  254. if (!isLoading && input.trim()) {
  255. handleSend();
  256. }
  257. }
  258. };
  259. const handleInputResize = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
  260. setInput(e.target.value);
  261. e.target.style.height = 'auto';
  262. e.target.style.height = `${Math.min(e.target.scrollHeight, 200)} px`;
  263. };
  264. return (
  265. <div className="flex flex-col h-full bg-slate-50 relative overflow-hidden">
  266. <div className="flex-1 overflow-y-auto p-4 md:p-6 space-y-6 scrollbar-hide">
  267. {messages.map((msg) => (
  268. <ChatMessage
  269. key={msg.id}
  270. message={msg}
  271. onPreviewSource={onPreviewSource}
  272. onOpenFile={onOpenFile}
  273. />
  274. ))}
  275. {isLoading && (
  276. <div className="flex justify-start animate-in fade-in duration-300">
  277. <div className="flex flex-row gap-3">
  278. <div className="w-8 h-8 rounded-full bg-white border border-slate-200 flex items-center justify-center shadow-sm">
  279. <Loader2 className="w-4 h-4 text-purple-600 animate-spin" />
  280. </div>
  281. <div className="bg-white border border-slate-100 px-4 py-3 rounded-2xl rounded-tl-none shadow-sm flex items-center">
  282. <span className="text-sm text-slate-500">{t('analyzing')}</span>
  283. </div>
  284. </div>
  285. </div>
  286. )}
  287. <div ref={messagesEndRef} />
  288. </div>
  289. <div className="p-4 bg-gradient-to-t from-slate-50 via-slate-50 to-transparent shrink-0">
  290. <div className="max-w-3xl mx-auto">
  291. {((selectedFiles && selectedFiles.length > 0) || true) && (
  292. <div className="mb-2 flex flex-wrap gap-2 animate-in slide-in-from-bottom-2">
  293. {/* Group Selection Button */}
  294. <button
  295. type="button"
  296. onClick={onOpenGroupSelection}
  297. className={`flex items-center gap-2 px-3 py-1 rounded-full text-xs font-medium transition-colors border ${selectedGroups.length > 0
  298. ? 'bg-slate-100 text-slate-700 border-slate-300 hover:bg-slate-200'
  299. : 'bg-slate-50 text-slate-600 border-slate-200 hover:bg-slate-100'
  300. }`}
  301. title={t('selectKnowledgeGroup')}
  302. >
  303. <Database size={12} />
  304. <span className="truncate max-w-[150px]">
  305. {selectedGroups.length === 0
  306. ? t('allKnowledgeGroups')
  307. : selectedGroups.length <= 1
  308. ? (groups.find(g => g.id === selectedGroups[0])?.name || t('unknownGroup'))
  309. : t('selectedGroupsCount').replace('$1', selectedGroups.length.toString())}
  310. </span>
  311. </button>
  312. {files.filter(f => selectedFiles?.includes(f.id)).map(file => (
  313. <div key={file.id} className="flex items-center gap-1 bg-blue-100 text-blue-700 px-2 py-1 rounded-full text-xs font-medium border border-blue-200">
  314. <span className="truncate max-w-[150px]">{file.name}</span>
  315. <button
  316. onClick={onClearFileSelection}
  317. className="hover:bg-blue-200 rounded-full p-0.5 transition-colors"
  318. >
  319. <X size={12} />
  320. </button>
  321. </div>
  322. ))}
  323. </div>
  324. )}
  325. <div className="bg-white rounded-xl shadow-lg border border-slate-200 flex items-end p-2 transition-shadow focus-within:shadow-xl focus-within:border-blue-300">
  326. <button
  327. onClick={onMobileUploadClick}
  328. className="md:hidden p-3 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
  329. >
  330. <Paperclip className="w-5 h-5" />
  331. </button>
  332. <textarea
  333. ref={inputRef}
  334. value={input}
  335. onChange={handleInputResize}
  336. onKeyDown={handleKeyDown}
  337. placeholder={files.length > 0 ? t('placeholderWithFiles') : t('placeholderEmpty')}
  338. className="flex-1 max-h-40 min-h-[50px] bg-transparent border-none focus:ring-0 text-slate-700 placeholder:text-slate-400 resize-none py-3 px-3"
  339. rows={1}
  340. disabled={files.length === 0 && messages.length < 2 && false} // Disable logic might need review, relaxed for now
  341. />
  342. <button
  343. onClick={handleSend}
  344. disabled={!input.trim() || isLoading}
  345. className={`p - 3 rounded - lg mb - 0.5 ml - 2 transition - all ${input.trim() && !isLoading
  346. ? 'bg-blue-600 text-white hover:bg-blue-700 shadow-md transform hover:scale-105'
  347. : 'bg-slate-100 text-slate-400 cursor-not-allowed'
  348. } `}
  349. type="button"
  350. >
  351. {isLoading ? (
  352. <Loader2 className="w-5 h-5 animate-spin" />
  353. ) : (
  354. <Send className="w-5 h-5" />
  355. )}
  356. </button>
  357. </div>
  358. <p className="text-center text-[10px] text-slate-400 mt-2">
  359. {t('aiDisclaimer')}
  360. </p>
  361. </div>
  362. </div>
  363. </div>
  364. );
  365. };
  366. export default ChatInterface;