IndexingModalWithMode.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. /**
  2. * Processing mode selection (Fast/Precise) support
  3. */
  4. import React, { useState, useEffect } from 'react';
  5. import { createPortal } from 'react-dom';
  6. import { ModelConfig, RawFile, IndexingConfig } from '../types';
  7. import { useLanguage } from '../contexts/LanguageContext';
  8. import { useToast } from '../contexts/ToastContext';
  9. import { useConfirm } from '../contexts/ConfirmContext';
  10. import { Layers, FileText, Database, X, ArrowRight, Files, Info, Zap, Target, AlertTriangle, Clock, DollarSign } from 'lucide-react';
  11. import { formatBytes } from '../utils/fileUtils';
  12. import { chunkConfigService } from '../services/chunkConfigService';
  13. import { uploadService } from '../services/uploadService';
  14. interface IndexingModalWithModeProps {
  15. isOpen: boolean;
  16. onClose: () => void;
  17. files?: RawFile[];
  18. embeddingModels: ModelConfig[];
  19. defaultEmbeddingId: string;
  20. onConfirm: (config: IndexingConfig) => void;
  21. isReconfiguring?: boolean;
  22. }
  23. const IndexingModalWithMode: React.FC<IndexingModalWithModeProps> = ({
  24. isOpen,
  25. onClose,
  26. files = [],
  27. embeddingModels,
  28. defaultEmbeddingId,
  29. onConfirm,
  30. isReconfiguring = false
  31. }) => {
  32. const { t } = useLanguage();
  33. const { showWarning, showInfo } = useToast();
  34. const { confirm } = useConfirm();
  35. // Configuration state
  36. const [chunkSize, setChunkSize] = useState(200);
  37. const [chunkOverlap, setChunkOverlap] = useState(40);
  38. const [selectedEmbedding, setSelectedEmbedding] = useState('');
  39. const [mode, setMode] = useState<'fast' | 'precise'>('fast');
  40. const [userSelectedMode, setUserSelectedMode] = useState(false); // Track if user manually selected mode
  41. // Mode recommendation info
  42. const [modeRecommendation, setModeRecommendation] = useState<any>(null);
  43. const [isLoadingRecommendation, setIsLoadingRecommendation] = useState(false);
  44. // Limit info state
  45. const [limits, setLimits] = useState<{
  46. maxChunkSize: number;
  47. maxOverlapSize: number;
  48. minOverlapSize: number;
  49. defaultChunkSize: number;
  50. defaultOverlapSize: number;
  51. modelInfo: {
  52. name: string;
  53. maxInputTokens: number;
  54. maxBatchSize: number;
  55. expectedDimensions: number;
  56. };
  57. } | null>(null);
  58. const [isLoadingLimits, setIsLoadingLimits] = useState(false);
  59. // Get auth token
  60. const getAuthToken = () => {
  61. return localStorage.getItem('authToken') || '';
  62. };
  63. // Load mode recommendation when files change
  64. useEffect(() => {
  65. if (!isOpen || !files || files.length === 0) return;
  66. const loadRecommendation = async () => {
  67. setIsLoadingRecommendation(true);
  68. try {
  69. // Use first file for recommendation (assume similar types)
  70. const file = files[0];
  71. const rec = await uploadService.recommendMode(file.file);
  72. setModeRecommendation(rec);
  73. // Auto-select recommended mode if user hasn't manually selected one
  74. if (!isReconfiguring && !userSelectedMode) {
  75. setMode(rec.recommendedMode);
  76. showInfo(t('recommendationMsg', rec.recommendedMode === 'precise' ? t('preciseMode') : t('fastMode'), t(rec.reason, ...(rec.reasonArgs || []))));
  77. }
  78. } catch (error) {
  79. console.error('モード推奨の取得に失敗しました:', error);
  80. } finally {
  81. setIsLoadingRecommendation(false);
  82. }
  83. };
  84. loadRecommendation();
  85. }, [isOpen, files, isReconfiguring]);
  86. // Load config limits when selected model changes
  87. useEffect(() => {
  88. if (!isOpen || !selectedEmbedding) {
  89. setLimits(null);
  90. return;
  91. }
  92. const loadLimits = async () => {
  93. setIsLoadingLimits(true);
  94. try {
  95. const token = getAuthToken();
  96. if (!token) return;
  97. const limitData = await chunkConfigService.getLimits(selectedEmbedding, token);
  98. setLimits(limitData);
  99. // Auto-adjust if current values exceed new limits
  100. if (chunkSize > limitData.maxChunkSize) {
  101. setChunkSize(limitData.maxChunkSize);
  102. showWarning(t('autoAdjustChunk', limitData.maxChunkSize));
  103. }
  104. if (chunkOverlap > limitData.maxOverlapSize) {
  105. setChunkOverlap(limitData.maxOverlapSize);
  106. showWarning(t('autoAdjustOverlap', limitData.maxOverlapSize));
  107. }
  108. if (chunkOverlap < limitData.minOverlapSize) {
  109. setChunkOverlap(limitData.minOverlapSize);
  110. // Only show warning if it was manually set below the new minimum
  111. if (chunkOverlap < limitData.minOverlapSize) {
  112. showWarning(t('autoAdjustOverlapMin', limitData.minOverlapSize));
  113. }
  114. }
  115. } catch (error) {
  116. console.error('設定制限の読み込みに失敗しました:', error);
  117. showWarning(t('loadLimitsFailed'));
  118. } finally {
  119. setIsLoadingLimits(false);
  120. }
  121. };
  122. loadLimits();
  123. }, [isOpen, selectedEmbedding]);
  124. // Track isOpen state change, reset only on open
  125. const [prevOpen, setPrevOpen] = useState(false);
  126. // Initialize modal
  127. useEffect(() => {
  128. if (isOpen && !prevOpen) {
  129. // Execute initialization only when going from closed to open
  130. console.log('DEBUG: IndexingModalWithMode opening, files:', files);
  131. // Set default embedding model
  132. const enabledModels = embeddingModels.filter(m => m.isEnabled !== false);
  133. const validDefault = enabledModels.find(m => m.id === defaultEmbeddingId);
  134. if (validDefault) {
  135. setSelectedEmbedding(defaultEmbeddingId);
  136. } else if (enabledModels.length > 0) {
  137. setSelectedEmbedding(enabledModels[0].id);
  138. } else {
  139. setSelectedEmbedding('');
  140. }
  141. // Reset to defaults
  142. setChunkSize(200);
  143. setChunkOverlap(40);
  144. if (!isReconfiguring) {
  145. setMode('fast');
  146. setUserSelectedMode(false); // Reset user selection status
  147. }
  148. setModeRecommendation(null);
  149. }
  150. setPrevOpen(isOpen);
  151. }, [isOpen, prevOpen, defaultEmbeddingId, embeddingModels, isReconfiguring]);
  152. // Handle chunk size change
  153. const handleChunkSizeChange = (value: number) => {
  154. if (limits && value > limits.maxChunkSize) {
  155. showWarning(t('maxValueMsg', limits.maxChunkSize));
  156. setChunkSize(limits.maxChunkSize);
  157. return;
  158. }
  159. setChunkSize(value);
  160. // Auto-adjust overlap if it exceeds 50% of new chunk size
  161. if (chunkOverlap > value * 0.5) {
  162. setChunkOverlap(Math.floor(value * 0.5));
  163. }
  164. };
  165. // Handle overlap size change
  166. const handleChunkOverlapChange = (value: number) => {
  167. if (limits && value > limits.maxOverlapSize) {
  168. showWarning(t('maxValueMsg', limits.maxOverlapSize));
  169. setChunkOverlap(limits.maxOverlapSize);
  170. return;
  171. }
  172. if (limits && value < limits.minOverlapSize) {
  173. // Don't show warning here, just set to min if they slide too low
  174. setChunkOverlap(limits.minOverlapSize);
  175. return;
  176. }
  177. // Check if it exceeds 50% of chunk size
  178. const maxOverlapByRatio = Math.floor(chunkSize * 0.5);
  179. if (value > maxOverlapByRatio) {
  180. showWarning(t('overlapRatioLimit', maxOverlapByRatio));
  181. setChunkOverlap(maxOverlapByRatio);
  182. return;
  183. }
  184. setChunkOverlap(value);
  185. };
  186. // Render limits info
  187. const renderLimitsInfo = () => {
  188. if (!limits || isLoadingLimits) {
  189. return null;
  190. }
  191. return (
  192. <div className="bg-blue-50 border border-blue-200 rounded-lg p-3 text-xs">
  193. <div className="flex items-center gap-2 mb-2 font-semibold text-blue-800">
  194. <Info className="w-4 h-4" />
  195. {t('modelLimitsInfo')}
  196. </div>
  197. <div className="grid grid-cols-2 gap-2 text-blue-700">
  198. <div>{t('model')}: <span className="font-medium">{limits.modelInfo.name}</span></div>
  199. <div>{t('maxChunkSize')}: <span className="font-medium">{limits.maxChunkSize} tokens</span></div>
  200. <div>{t('maxOverlapSize')}: <span className="font-medium">{limits.maxOverlapSize} tokens</span></div>
  201. <div>{t('maxBatchSize')}: <span className="font-medium">{limits.modelInfo.maxBatchSize}</span></div>
  202. </div>
  203. {limits.modelInfo.maxInputTokens > limits.maxChunkSize && (
  204. <div className="mt-1 text-blue-600 text-[10px]">
  205. ⚠️ {t('envLimitWeaker')}: {limits.maxChunkSize} &lt; {limits.modelInfo.maxInputTokens}
  206. </div>
  207. )}
  208. </div>
  209. );
  210. };
  211. // Render mode recommendation info
  212. const renderModeRecommendation = () => {
  213. if (!modeRecommendation || isLoadingRecommendation) {
  214. return null;
  215. }
  216. return (
  217. <div className="space-y-2 p-3 bg-purple-50 border border-purple-200 rounded-lg text-xs">
  218. <div className="font-semibold text-purple-800 flex items-center gap-2">
  219. <Target className="w-4 h-4" />
  220. {t('processingMode')}
  221. </div>
  222. <div className="text-purple-700">
  223. <strong>{t('recommendationReason')}:</strong> {t(modeRecommendation.reason, ...(modeRecommendation.reasonArgs || []))}
  224. </div>
  225. {modeRecommendation.warnings && modeRecommendation.warnings.length > 0 && (
  226. <div className="mt-1 space-y-1">
  227. {modeRecommendation.warnings.map((warning: string, idx: number) => (
  228. <div key={idx} className="text-purple-800 flex items-start gap-1">
  229. <AlertTriangle className="w-3 h-3 mt-0.5 flex-shrink-0" />
  230. <span>{t(warning as any)}</span>
  231. </div>
  232. ))}
  233. </div>
  234. )}
  235. </div>
  236. );
  237. };
  238. // Render current mode description
  239. const renderModeDescription = () => {
  240. if (mode === 'fast') {
  241. return (
  242. <div className="text-xs text-slate-600 bg-slate-50 p-2 rounded border border-slate-200">
  243. <div className="font-semibold text-slate-700 mb-1 flex items-center gap-1">
  244. <Zap className="w-3 h-3 text-yellow-600" />
  245. {t('fastModeFeatures')}
  246. </div>
  247. <ul className="list-disc list-inside space-y-0.5 text-[11px]">
  248. <li>{t('fastFeature1')}</li>
  249. <li>{t('fastFeature2')}</li>
  250. <li>{t('fastFeature3')}</li>
  251. <li>{t('fastFeature4')}</li>
  252. <li>{t('fastFeature5')}</li>
  253. </ul>
  254. </div>
  255. );
  256. }
  257. return (
  258. <div className="text-xs text-slate-600 bg-slate-50 p-2 rounded border border-slate-200">
  259. <div className="font-semibold text-slate-700 mb-1 flex items-center gap-1">
  260. <Target className="w-3 h-3 text-blue-600" />
  261. {t('preciseModeFeatures')}
  262. </div>
  263. <ul className="list-disc list-inside space-y-0.5 text-[11px]">
  264. <li>{t('preciseFeature1')}</li>
  265. <li>{t('preciseFeature2')}</li>
  266. <li>{t('preciseFeature3')}</li>
  267. <li>{t('preciseFeature4')}</li>
  268. <li>{t('preciseFeature5')}</li>
  269. <li>{t('preciseFeature6')}</li>
  270. </ul>
  271. </div>
  272. );
  273. };
  274. if (!isOpen) return null;
  275. return createPortal(
  276. <>
  277. <div
  278. className="fixed inset-0 z-[100] bg-black/50 backdrop-blur-sm transition-opacity"
  279. onClick={onClose}
  280. />
  281. <div className="fixed right-0 top-0 h-full w-full max-w-lg bg-white shadow-2xl z-[101] transform transition-transform duration-300 ease-in-out animate-in slide-in-from-right flex flex-col">
  282. {/* Header */}
  283. <div className="p-5 border-b border-slate-100 bg-slate-50 shrink-0">
  284. <div className="flex justify-between items-start">
  285. <div>
  286. <h2 className="text-lg font-bold text-slate-800 flex items-center gap-2">
  287. <Database className="w-5 h-5 text-blue-600" />
  288. {isReconfiguring ? t('reconfigureTitle') : t('indexingConfigTitle')}
  289. </h2>
  290. <p className="text-xs text-slate-500 mt-1">
  291. {isReconfiguring ? t('reconfigureDesc') : t('indexingConfigDesc')}
  292. </p>
  293. </div>
  294. <button
  295. onClick={(e) => {
  296. e.stopPropagation();
  297. onClose();
  298. }}
  299. className="p-2 hover:bg-slate-200 rounded-full transition-colors active:scale-90"
  300. >
  301. <X className="w-5 h-5 text-slate-500" />
  302. </button>
  303. </div>
  304. </div>
  305. <div className="flex-1 overflow-y-auto p-5 space-y-6">
  306. {/* Pending files - only show when there are files */}
  307. {files && files.length > 0 && (
  308. <div>
  309. <h3 className="text-sm font-semibold text-slate-700 mb-2 flex items-center gap-2">
  310. <Files className="w-4 h-4 text-slate-500" />
  311. {t('pendingFiles')}
  312. </h3>
  313. <div className="space-y-1 max-h-32 overflow-y-auto bg-slate-50 rounded-lg p-2 border border-slate-200">
  314. {files.map((file, index) => (
  315. <div key={index} className="text-xs text-slate-600 flex items-center justify-between py-1 px-2 hover:bg-white rounded transition-colors">
  316. <span className="truncate flex-1">{file.name}</span>
  317. <span className="text-slate-400 ml-2">{formatBytes(file.size)}</span>
  318. </div>
  319. ))}
  320. </div>
  321. </div>
  322. )}
  323. {/* Processing mode selection */}
  324. {!isReconfiguring && (
  325. <div>
  326. <h3 className="text-sm font-semibold text-slate-700 mb-2 flex items-center gap-2">
  327. <Target className="w-4 h-4 text-slate-500" />
  328. {t('processingMode')}
  329. {isLoadingRecommendation && <span className="text-xs text-blue-600 ml-2">{t('analyzingFile')}</span>}
  330. </h3>
  331. {/* Mode recommendation info */}
  332. {renderModeRecommendation()}
  333. {/* Mode selection */}
  334. <div className="grid grid-cols-2 gap-3 mt-3">
  335. {/* Fast Mode */}
  336. <button
  337. onClick={() => {
  338. setMode('fast');
  339. setUserSelectedMode(true); // ユーザーによる手動選択をマーク
  340. }}
  341. className={`relative p-3 rounded-lg border-2 text-left transition-all ${mode === 'fast'
  342. ? 'border-blue-500 bg-blue-50'
  343. : 'border-slate-200 hover:border-slate-300'
  344. }`}
  345. >
  346. <div className="flex items-center gap-2 mb-2">
  347. <Zap className="w-4 h-4 text-yellow-600" />
  348. <span className="font-semibold text-sm">{t('fastMode')}</span>
  349. </div>
  350. <div className="text-xs text-slate-600 leading-relaxed">
  351. {t('fastModeDesc')}
  352. </div>
  353. {mode === 'fast' && (
  354. <div className="absolute top-2 right-2 text-blue-600">
  355. <div className="w-2 h-2 bg-blue-600 rounded-full"></div>
  356. </div>
  357. )}
  358. </button>
  359. {/* Precise Mode */}
  360. <button
  361. onClick={() => {
  362. setMode('precise');
  363. setUserSelectedMode(true); // ユーザーによる手動選択をマーク
  364. }}
  365. className={`relative p-3 rounded-lg border-2 text-left transition-all ${mode === 'precise'
  366. ? 'border-purple-500 bg-purple-50'
  367. : 'border-slate-200 hover:border-slate-300'
  368. }`}
  369. >
  370. <div className="flex items-center gap-2 mb-2">
  371. <Target className="w-4 h-4 text-purple-600" />
  372. <span className="font-semibold text-sm">{t('preciseMode')}</span>
  373. </div>
  374. <div className="text-xs text-slate-600 leading-relaxed">
  375. {t('preciseModeDesc')}
  376. </div>
  377. {mode === 'precise' && (
  378. <div className="absolute top-2 right-2 text-purple-600">
  379. <div className="w-2 h-2 bg-purple-600 rounded-full"></div>
  380. </div>
  381. )}
  382. </button>
  383. </div>
  384. {/* Mode description */}
  385. <div className="mt-3">
  386. {renderModeDescription()}
  387. </div>
  388. </div>
  389. )}
  390. {/* Embedding model selection */}
  391. <div>
  392. <h3 className="text-sm font-semibold text-slate-700 mb-2 flex items-center gap-2">
  393. <Layers className="w-4 h-4 text-slate-500" />
  394. {t('embeddingModel')}
  395. </h3>
  396. <select
  397. className="w-full text-sm border border-slate-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 outline-none"
  398. value={selectedEmbedding}
  399. onChange={(e) => setSelectedEmbedding(e.target.value)}
  400. >
  401. <option value="">{t('pleaseSelect')}</option>
  402. {embeddingModels.filter(m => m.isEnabled !== false).map(model => (
  403. <option key={model.id} value={model.id}>
  404. {model.name} ({model.modelId})
  405. </option>
  406. ))}
  407. </select>
  408. </div>
  409. {/* Chunk config */}
  410. <div>
  411. <h3 className="text-sm font-semibold text-slate-700 mb-2 flex items-center gap-2">
  412. <FileText className="w-4 h-4 text-slate-500" />
  413. {t('chunkConfig')}
  414. </h3>
  415. <div className="space-y-3">
  416. {/* Chunk size */}
  417. <div>
  418. <div className="flex justify-between mb-1 text-xs">
  419. <span className="text-slate-600">{t('chunkSize')}</span>
  420. <span className="font-mono font-semibold text-blue-600">{chunkSize}</span>
  421. </div>
  422. <input
  423. type="range"
  424. min="50"
  425. max={limits?.maxChunkSize || 8191}
  426. value={chunkSize}
  427. onChange={(e) => handleChunkSizeChange(Number(e.target.value))}
  428. className="w-full h-2 bg-slate-200 rounded-lg appearance-none cursor-pointer accent-blue-600"
  429. disabled={!selectedEmbedding || isLoadingLimits}
  430. />
  431. <div className="flex justify-between text-[10px] text-slate-400 mt-1">
  432. <span>{t('min')}: 50</span>
  433. <span>{t('max')}: {limits?.maxChunkSize || '-'}</span>
  434. </div>
  435. </div>
  436. {/* Overlap size */}
  437. <div>
  438. <div className="flex justify-between mb-1 text-xs">
  439. <span className="text-slate-600">{t('chunkOverlap')}</span>
  440. <span className="font-mono font-semibold text-blue-600">{chunkOverlap}</span>
  441. </div>
  442. <input
  443. type="range"
  444. min={limits?.minOverlapSize || 25}
  445. max={limits?.maxOverlapSize || 200}
  446. value={chunkOverlap}
  447. onChange={(e) => handleChunkOverlapChange(Number(e.target.value))}
  448. className="w-full h-2 bg-slate-200 rounded-lg appearance-none cursor-pointer accent-blue-600"
  449. disabled={!selectedEmbedding || isLoadingLimits}
  450. />
  451. <div className="flex justify-between text-[10px] text-slate-400 mt-1">
  452. <span>{t('min')}: {limits?.minOverlapSize || 25}</span>
  453. <span>{t('max')}: {limits?.maxOverlapSize || '-'}</span>
  454. </div>
  455. </div>
  456. </div>
  457. </div>
  458. {isReconfiguring && renderLimitsInfo()}
  459. {/* Optimization tips */}
  460. {limits && (
  461. <div className="bg-amber-50 border border-amber-200 rounded-lg p-3 text-xs text-amber-800">
  462. <p className="font-medium mb-1">💡 {t('optimizationTips')}</p>
  463. <ul className="list-disc list-inside space-y-0.5 text-[11px]">
  464. {chunkSize > 800 && <li>{t('tipChunkTooLarge')}</li>}
  465. {chunkOverlap < chunkSize * 0.1 && <li>{t('tipOverlapSmall').replace('$1', `${Math.floor(chunkSize * 0.1)}`)}</li>}
  466. {chunkSize === limits.maxChunkSize && <li>{t('tipMaxValues')}</li>}
  467. {mode === 'precise' && <li>{t('tipPreciseCost')}</li>}
  468. </ul>
  469. </div>
  470. )}
  471. </div>
  472. {/* Footer buttons */}
  473. <div className="p-4 border-t border-slate-100 bg-slate-50 flex justify-end gap-2 shrink-0">
  474. <button
  475. onClick={(e) => {
  476. e.stopPropagation();
  477. onClose();
  478. }}
  479. className="px-4 py-2 text-sm text-slate-600 hover:bg-slate-200 rounded-lg transition-colors active:scale-95"
  480. >
  481. {t('cancel')}
  482. </button>
  483. <button
  484. onClick={async () => {
  485. if (!selectedEmbedding) {
  486. showWarning(t('selectEmbeddingFirst'));
  487. return;
  488. }
  489. if (!isReconfiguring && mode === 'precise') {
  490. // Precise mode confirmation
  491. if (!(await confirm(t('confirmPreciseCost')))) {
  492. return;
  493. }
  494. }
  495. onConfirm({
  496. chunkSize,
  497. chunkOverlap,
  498. embeddingModelId: selectedEmbedding,
  499. mode,
  500. });
  501. }}
  502. disabled={isLoadingLimits}
  503. className="px-4 py-2 text-sm bg-blue-600 text-white hover:bg-blue-700 rounded-lg shadow-sm flex items-center gap-2 transition-transform active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed"
  504. >
  505. <Database className="w-4 h-4" />
  506. {t('startProcessing')}
  507. </button>
  508. </div>
  509. </div>
  510. </>,
  511. document.body
  512. );
  513. };
  514. export default IndexingModalWithMode;