page.tsx
78.2 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
"use client";
import { useState, useEffect, useMemo, useRef } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import {
FileText, Upload, Trash2, Search, BookOpen, MessageSquare,
ChevronRight, Activity, Download, Loader2, CheckCircle2,
Clock, HardDrive, Filter, MoreVertical, LayoutGrid, List as ListIcon,
ShieldCheck, Zap, Globe, Settings, LogOut, ChevronDown, Check,
X, AlertCircle, Eye, LogOut as Eject, Folder, Square, RefreshCw,
FileImage, FileSpreadsheet, FileArchive, FileCode
} from "lucide-react";
import { cn } from "@/lib/utils";
import { MessageBubble, type ReasoningStep } from "@/components/MessageBubble";
interface UploadQueueItem {
file: File;
name: string;
status: 'pending' | 'uploading' | 'success' | 'error';
errorMsg?: string;
}
interface FileItem {
id: string;
name: string;
time: string;
full_time?: string;
format: string;
size: string;
size_raw?: number;
word_count?: number;
status: "Indexed" | "Pending" | "Ingesting" | "Uploading" | "Failed";
meta?: {
ingest_duration?: string;
total_tokens?: number | { total_tokens: number; input_tokens: number; output_tokens: number };
ingest_time?: string;
};
}
interface TreeFolder {
name: string;
type: "folder";
children: Record<string, TreeFolder | TreeFile>;
}
interface TreeFile {
name: string;
type: "file";
path: string;
}
const buildTree = (links: string[]) => {
const root: TreeFolder = { name: "root", type: "folder", children: {} };
links.forEach(link => {
const cleanLink = link.replace(/^ware\/wiki\//, '');
const parts = cleanLink.split('/');
let current = root;
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
if (i === parts.length - 1) {
current.children[part] = { name: part, type: "file", path: cleanLink };
} else {
if (!current.children[part]) {
current.children[part] = { name: part, type: "folder", children: {} };
}
current = current.children[part] as TreeFolder;
}
}
});
return root;
};
const TreeNode = ({ node, level = 0, onSelect, selectedPath }: { node: TreeFolder | TreeFile, level?: number, onSelect: (path: string) => void, selectedPath: string | null }) => {
const [isOpen, setIsOpen] = useState(true);
if (node.type === "file") {
return (
<div
className={cn(
"flex items-center gap-2 py-1.5 px-2 rounded-lg cursor-pointer transition-colors text-sm",
selectedPath === node.path ? "bg-blue-100 text-blue-700 font-medium" : "hover:bg-slate-100 text-slate-600"
)}
style={{ paddingLeft: `${level * 12 + 8}px` }}
onClick={() => onSelect(node.path)}
>
<FileText className="w-4 h-4 shrink-0" />
<span className="truncate">{node.name}</span>
</div>
);
}
const children = Object.values(node.children).sort((a, b) => {
if (a.type === b.type) return a.name.localeCompare(b.name);
return a.type === "folder" ? -1 : 1;
});
return (
<div>
<div
className="flex items-center gap-2 py-1.5 px-2 rounded-lg cursor-pointer hover:bg-slate-100 text-slate-700 transition-colors text-sm font-medium"
style={{ paddingLeft: `${level * 12 + 8}px` }}
onClick={() => setIsOpen(!isOpen)}
>
<Folder className="w-4 h-4 shrink-0 text-blue-500" />
<span className="truncate">{node.name}</span>
</div>
{isOpen && (
<div className="flex flex-col gap-0.5 mt-0.5">
{children.map(child => (
<TreeNode key={child.name} node={child} level={level + 1} onSelect={onSelect} selectedPath={selectedPath} />
))}
</div>
)}
</div>
);
};
export default function EnterpriseWiki() {
const [files, setFiles] = useState<FileItem[]>([]);
const [uploadingFiles, setUploadingFiles] = useState<FileItem[]>([]);
const [isInitialLoading, setIsInitialLoading] = useState(true);
const [selectedFileId, setSelectedFileId] = useState<string | null>(null);
const [wikiContent, setWikiContent] = useState<string>("");
const [previewContent, setPreviewContent] = useState<string>("");
const [isPreviewLoading, setIsPreviewLoading] = useState(false);
const [viewMode, setViewMode] = useState<"raw" | "wiki_tree">("raw");
const [selectedWikiPath, setSelectedWikiPath] = useState<string | null>(null);
const [query, setQuery] = useState("");
const [chatHistory, setChatHistory] = useState<{
role: "user" | "ai";
content: string;
reasoning?: ReasoningStep[];
startTime?: number;
endTime?: number;
isStreaming?: boolean;
serverDurationMs?: number;
}[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [isDeleting, setIsDeleting] = useState<string | null>(null);
const [isChatOpen, setIsChatOpen] = useState(false);
const [isModalOpen, setIsModalOpen] = useState(false);
const [isLintModalOpen, setIsLintModalOpen] = useState(false);
const [isUploadModalOpen, setIsUploadModalOpen] = useState(false);
const [uploadQueue, setUploadQueue] = useState<UploadQueueItem[]>([]);
const [lintHistory, setLintHistory] = useState<{
role: "user" | "ai";
content: string;
reasoning?: ReasoningStep[];
startTime?: number;
endTime?: number;
}[]>([]);
const [isLinting, setIsLinting] = useState(false);
const [wikiLinks, setWikiLinks] = useState<string[]>([]);
const [abortController, setAbortController] = useState<AbortController | null>(null);
const [sessionId] = useState(() => "session-" + Date.now() + "-" + Math.random().toString(36).substring(2, 9));
const chatEndRef = useRef<HTMLDivElement>(null);
const lintEndRef = useRef<HTMLDivElement>(null);
useEffect(() => {
chatEndRef.current?.scrollIntoView({ behavior: "smooth" });
}, [chatHistory]);
useEffect(() => {
lintEndRef.current?.scrollIntoView({ behavior: "smooth" });
}, [lintHistory]);
const [searchQuery, setSearchQuery] = useState("");
const [searchInput, setSearchInput] = useState("");
const [sortBy, setSortBy] = useState<"name" | "time" | "size">("time");
const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");
const [currentPage, setCurrentPage] = useState(1);
const [pageSize, setPageSize] = useState(10);
const [totalCount, setTotalCount] = useState(0);
const [refreshTrigger, setRefreshTrigger] = useState(0);
// Selection state
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
const API_BASE = process.env.NEXT_PUBLIC_API_URL || "/api";
const fetchFiles = async (page = currentPage, size = pageSize, search = searchQuery, isInitial = false) => {
if (isInitial) setIsInitialLoading(true);
try {
const res = await fetch(`${API_BASE}/files?page=${page}&page_size=${size}&search=${encodeURIComponent(search)}`);
const data = await res.json();
setFiles(data.files || []);
setTotalCount(data.total || 0);
} catch (e) {
console.error("Failed to fetch files", e);
} finally {
if (isInitial) setIsInitialLoading(false);
}
};
useEffect(() => {
Promise.resolve().then(() => {
void fetchFiles(currentPage, pageSize, searchQuery, true);
});
}, [currentPage, pageSize, searchQuery, refreshTrigger]);
const filteredFiles = useMemo(() => {
const combinedFiles = [...uploadingFiles, ...files.filter(f => !uploadingFiles.some(u => u.name === f.name))];
combinedFiles.sort((a, b) => {
let comparison = 0;
if (sortBy === "name") {
comparison = a.name.localeCompare(b.name);
} else if (sortBy === "time") {
comparison = (a.full_time || a.time).localeCompare(b.full_time || b.time);
} else if (sortBy === "size") {
comparison = (a.size_raw || 0) - (b.size_raw || 0);
}
return sortOrder === "asc" ? comparison : -comparison;
});
return combinedFiles;
}, [files, uploadingFiles, sortBy, sortOrder]);
const handleUploadSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.files && e.target.files.length > 0) {
const selectedFiles = Array.from(e.target.files);
const duplicatesInQueue: string[] = [];
const duplicatesInSelection: string[] = [];
const validFiles: UploadQueueItem[] = [];
const existingNames = new Set(uploadQueue.map(item => item.name));
const seenInSelection = new Set<string>();
for (const file of selectedFiles) {
if (existingNames.has(file.name)) {
duplicatesInQueue.push(file.name);
} else if (seenInSelection.has(file.name)) {
duplicatesInSelection.push(file.name);
} else {
seenInSelection.add(file.name);
validFiles.push({
file,
name: file.name,
status: 'pending'
});
}
}
if (validFiles.length > 0) {
setUploadQueue(prev => [...prev, ...validFiles]);
}
const tips: string[] = [];
if (duplicatesInQueue.length > 0) {
tips.push(`以下文件已在上传列表中,已自动过滤:\n${duplicatesInQueue.join(', ')}`);
}
if (duplicatesInSelection.length > 0) {
tips.push(`选择的文件中存在同名文件,已自动去重:\n${duplicatesInSelection.join(', ')}`);
}
if (tips.length > 0) {
alert(tips.join('\n\n'));
}
}
e.target.value = '';
};
const handleUploadConfirm = async () => {
const pendingFiles = uploadQueue.filter(q => q.status === 'pending');
if (pendingFiles.length === 0) return;
// 先把当前待上传的文件状态更新为 uploading
setUploadQueue(prev => prev.map(q => q.status === 'pending' ? { ...q, status: 'uploading' } : q));
try {
const initRes = await fetch(`${API_BASE}/upload/init`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
files: pendingFiles.map(q => ({ name: q.name }))
})
});
if (!initRes.ok) {
const errorData = await initRes.json().catch(() => ({ detail: "初始化上传失败" }));
const errorMsg = errorData.detail || "初始化上传失败";
setUploadQueue(prev => prev.map(q => pendingFiles.some(pf => pf.name === q.name) ? { ...q, status: 'error', errorMsg } : q));
return;
}
const { mapping, errors } = await initRes.json();
// 先把后端返回错误的文件标记为 error
if (errors && Object.keys(errors).length > 0) {
setUploadQueue(prev => prev.map(q => {
if (errors[q.name]) {
return { ...q, status: 'error', errorMsg: errors[q.name] };
}
return q;
}));
}
for (const q of pendingFiles) {
const fileId = mapping[q.name];
if (!fileId) {
// 如果后端没有返回它的 ID,且之前也没有标记为 error,说明可能存在未知的初始化缺失
if (!errors || !errors[q.name]) {
setUploadQueue(prev => prev.map(item => item.name === q.name ? { ...item, status: 'error', errorMsg: "初始化失败" } : item));
}
continue;
}
const formData = new FormData();
formData.append("file", q.file);
try {
const res = await fetch(`${API_BASE}/upload/${fileId}`, {
method: "POST",
body: formData,
});
if (res.ok) {
setUploadQueue(prev => prev.map(item => item.name === q.name ? { ...item, status: 'success' } : item));
} else {
const errDetail = await res.json().catch(() => ({ detail: "文件保存失败" }));
setUploadQueue(prev => prev.map(item => item.name === q.name ? { ...item, status: 'error', errorMsg: errDetail.detail || "保存失败" } : item));
}
} catch {
setUploadQueue(prev => prev.map(item => item.name === q.name ? { ...item, status: 'error', errorMsg: "上传出错" } : item));
}
}
} catch {
setUploadQueue(prev => prev.map(q => pendingFiles.some(pf => pf.name === q.name) ? { ...q, status: 'error', errorMsg: "网络请求异常" } : q));
} finally {
fetchFiles();
}
};
const handleDelete = async (id: string) => {
const targetFile = files.find(f => f.id === id);
if (targetFile && targetFile.status !== "Pending" && targetFile.status !== "Failed") {
alert("只有待处理或失败的文件才能删除!");
return;
}
if (!confirm(`确定彻底删除 ${targetFile?.name} 吗?`)) return;
setIsDeleting(id);
// 如果删除的是当前选中的文件,先清除选中状态以卸载预览组件 (释放 iframe 句柄)
const isSelected = selectedFileId === id;
if (isSelected) {
// 尝试彻底销毁 iframe 的连接
const iframe = document.querySelector('iframe');
if (iframe) iframe.src = "about:blank";
setSelectedFileId(null);
setWikiContent("");
// 延长等待时间到 1s,给浏览器更多时间释放句柄
await new Promise(resolve => setTimeout(resolve, 1000));
}
try {
const response = await fetch(`${API_BASE}/files/${encodeURIComponent(id)}`, {
method: "DELETE",
mode: "cors"
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({ detail: "未知错误" }));
throw new Error(errorData.detail || `服务器返回状态码: ${response.status}`);
}
fetchFiles();
} catch (error) {
console.error("Delete failed:", error);
const msg = error instanceof Error ? error.message : "请检查网络或后端服务状态";
alert(`删除失败: ${msg}`);
} finally {
setIsDeleting(null);
}
};
const handleDownload = (id: string, name: string) => {
const downloadUrl = `${API_BASE}/files/download/${encodeURIComponent(id)}`;
const a = document.createElement("a");
a.href = downloadUrl;
a.download = name;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
};
const handleEgress = async (id: string) => {
const targetFile = files.find(f => f.id === id);
if (!confirm(`确定将 ${targetFile?.name} 从 Wiki 知识库中摄出吗?这会删除所有生成的 Wiki 页面。`)) return;
try {
const res = await fetch(`${API_BASE}/wiki/egress/${encodeURIComponent(id)}`, { method: "DELETE" });
if (!res.ok) {
const error = await res.json();
alert(error.detail || "摄出失败");
} else {
fetchFiles();
if (selectedFileId === id) {
setWikiContent("");
setViewMode("wiki_tree");
}
}
} catch {
alert("摄出请求发生错误");
}
};
const handleIngest = async (id: string) => {
setFiles(prev => prev.map(f => f.id === id ? { ...f, status: "Ingesting" } : f));
try {
const res = await fetch(`${API_BASE}/wiki/ingest/${encodeURIComponent(id)}`, { method: "POST" });
if (!res.ok) {
const error = await res.json();
alert(error.detail || "摄入失败");
}
await fetchFiles();
} catch {
alert("摄入过程发生错误");
await fetchFiles();
}
};
const handleBatchIngest = async () => {
const toIngest = Array.from(selectedIds).filter(id => {
const file = files.find(f => f.id === id);
return file && (file.status === "Pending" || file.status === "Failed");
});
if (toIngest.length === 0) {
alert("请先选择待处理或失败的文件");
return;
}
setFiles(prev => prev.map(f => toIngest.includes(f.id) ? { ...f, status: "Ingesting" } : f));
setSelectedIds(new Set());
try {
await fetch(`${API_BASE}/wiki/batch_ingest`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ids: toIngest }),
});
fetchFiles();
} catch {
alert("批量处理发生错误");
fetchFiles();
}
};
const viewWiki = async (name: string) => {
setWikiContent("正在调取 AI 摘要...");
try {
const res = await fetch(`${API_BASE}/wiki/content/${encodeURIComponent(name)}`);
if (!res.ok) {
setWikiContent("暂无 Wiki 摘要。请点击下方“摄入”按钮通过 AI 生成深度摘要。");
return;
}
const data = await res.json();
setWikiContent(data.content);
} catch {
setWikiContent("内容加载失败,请检查网络连接。");
}
};
const fetchPreview = async (id: string) => {
const targetFile = files.find(f => f.id === id);
if (targetFile?.name.toLowerCase().endsWith(".pdf")) return;
setIsPreviewLoading(true);
setPreviewContent("正在加载预览...");
try {
const res = await fetch(`${API_BASE}/files/view/${encodeURIComponent(id)}`);
if (res.ok) {
const contentType = res.headers.get("content-type");
if (contentType && contentType.includes("application/json")) {
const data = await res.json();
if (data.type === "text_preview") {
setPreviewContent(data.content);
} else {
setPreviewContent(data.content || "无法解析文档内容");
}
} else {
const text = await res.text();
setPreviewContent(text);
}
} else {
setPreviewContent("预览加载失败");
}
} catch {
setPreviewContent("预览请求发生错误");
} finally {
setIsPreviewLoading(false);
}
};
const onSelectFile = async (id: string) => {
setSelectedFileId(id);
// 强制跳转到原始文档预览模式
setViewMode("raw");
setIsModalOpen(true);
setWikiLinks([]);
setSelectedWikiPath(null);
const file = files.find(f => f.id === id);
if (file?.status === "Indexed") {
viewWiki(file.name);
try {
const res = await fetch(`${API_BASE}/files/${encodeURIComponent(id)}/wiki_links`);
if (res.ok) {
const data = await res.json();
setWikiLinks(data.links || []);
}
} catch {
console.error("Failed to fetch wiki links");
}
} else {
setWikiContent("");
}
fetchPreview(id);
};
const handleLint = async () => {
setIsLintModalOpen(true);
setLintHistory([{ role: "user", content: "请对 Wiki 知识库进行全面的健康检查。" }]);
setIsLinting(true);
try {
const response = await fetch(`${API_BASE}/wiki/lint`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ query: "对知识库进行全面的 Lint 检查" }),
});
if (!response.body) throw new Error("ReadableStream not supported");
const reader = response.body.getReader();
const decoder = new TextDecoder();
let aiResponse = "";
let buffer = "";
const messageMap: Record<string, string> = {};
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop() || "";
for (const line of lines) {
const trimmedLine = line.trim();
if (!trimmedLine || !trimmedLine.startsWith("data: ")) continue;
const dataStr = trimmedLine.slice(6).trim();
if (dataStr === "[DONE]") break;
try {
const data = JSON.parse(dataStr);
const m_id = data.id || `msg-${Date.now()}`;
if (["thought", "call", "response"].includes(data.type)) {
setLintHistory(prev => {
const newHistory = [...prev];
let lastIdx = newHistory.length - 1;
if (lastIdx < 0 || newHistory[lastIdx].role !== "ai") {
newHistory.push({ role: "ai", content: "", reasoning: [], startTime: Date.now() });
lastIdx = newHistory.length - 1;
}
const last = newHistory[lastIdx];
const reasoning = [...(last.reasoning || [])];
const stepId = data.id || `${data.type}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
const existingIndex = reasoning.findIndex(r => r.id === stepId);
if (existingIndex !== -1) {
reasoning[existingIndex] = {
...reasoning[existingIndex],
type: (data.type && data.type !== 'thought') ? data.type : reasoning[existingIndex].type,
content: data.content,
name: data.name || reasoning[existingIndex].name
};
} else {
reasoning.push({
id: stepId,
type: data.type,
content: data.content,
name: data.name
});
}
newHistory[lastIdx] = { ...last, reasoning };
return newHistory;
});
} else if (data.type === "bot" || data.type === "stream") {
const content = data.content;
if (content === undefined || content === null) continue;
if (data.type === "bot") {
messageMap[m_id] = content;
aiResponse = Object.values(messageMap).join("");
} else {
aiResponse += content;
}
setLintHistory(prev => {
const newHistory = [...prev];
const lastIdx = newHistory.length - 1;
if (lastIdx < 0 || newHistory[lastIdx].role !== "ai") {
newHistory.push({ role: "ai", content: aiResponse, reasoning: [], startTime: Date.now() });
} else {
newHistory[lastIdx] = {
...newHistory[lastIdx],
content: aiResponse,
startTime: newHistory[lastIdx].startTime || Date.now()
};
}
return newHistory;
});
}
} catch (error) {
console.error("Parse error", error, dataStr);
}
}
}
} catch (error) {
setLintHistory(prev => [...prev, { role: "ai", content: "健康检查发生错误,请稍后再试。" }]);
} finally {
setIsLinting(false);
setLintHistory(prev => {
if (prev.length === 0) return prev;
const newHistory = [...prev];
const lastIdx = newHistory.length - 1;
if (newHistory[lastIdx].role === "ai") {
newHistory[lastIdx] = {
...newHistory[lastIdx],
endTime: Date.now()
};
}
return newHistory;
});
}
};
const handleQuery = async () => {
if (!query.trim()) return;
const userMessage = query;
setQuery("");
const historyToSend = chatHistory
.filter(msg => msg.content && msg.content.trim())
.slice(-16)
.map(msg => ({
role: msg.role === "ai" ? "assistant" : "user",
content: msg.content
}));
setChatHistory(prev => [...prev, { role: "user", content: userMessage }]);
setIsLoading(true);
setIsChatOpen(true);
const controller = new AbortController();
setAbortController(controller);
try {
const response = await fetch(`${API_BASE}/wiki/query`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
query: userMessage,
history: historyToSend,
sessionId: sessionId
}),
signal: controller.signal,
});
if (!response.body) throw new Error("ReadableStream not supported");
// 检查 HTTP 状态码,若后端返回错误直接提示
if (!response.ok) {
const errData = await response.json().catch(() => ({ detail: `服务器错误 ${response.status}` }));
throw new Error(errData.detail || `服务器错误 ${response.status}`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let aiResponse = "";
let buffer = "";
const messageMap: Record<string, string> = {};
// 超时保护:90 秒内没有任何 SSE 数据则自动断开
const TIMEOUT_MS = 90_000;
let lastEventTime = Date.now();
let streamFinished = false;
let streamError: Error | null = null;
while (!streamFinished) {
// 检查超时
if (Date.now() - lastEventTime > TIMEOUT_MS) {
reader.cancel();
throw new Error("等待响应超时(90秒),请检查后端服务是否正常运行。");
}
const { value, done } = await reader.read();
if (done) break;
lastEventTime = Date.now(); // 收到数据,刷新计时
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop() || "";
for (const line of lines) {
const trimmedLine = line.trim();
if (!trimmedLine || !trimmedLine.startsWith("data: ")) continue;
const dataStr = trimmedLine.slice(6).trim();
if (dataStr === "[DONE]") {
streamFinished = true;
setIsLoading(false);
setAbortController(null);
break;
}
if (dataStr === "[INIT]") continue;
try {
const data = JSON.parse(dataStr);
const m_id = data.id || `msg-${Date.now()}`;
if (data.type === "heartbeat") {
continue;
}
if (data.type === "done") {
streamFinished = true;
setIsLoading(false);
setAbortController(null);
setChatHistory(prev => {
if (prev.length === 0) return prev;
const newHistory = [...prev];
for (let i = newHistory.length - 1; i >= 0; i--) {
if (newHistory[i].role === "ai") {
newHistory[i] = {
...newHistory[i],
isStreaming: false,
endTime: newHistory[i].endTime || Date.now(),
// 服务器权威耗时:用于显示真实的「思考过程秒数」
serverDurationMs: data.data?.duration_ms ?? newHistory[i].serverDurationMs
};
break;
}
}
return newHistory;
});
break;
}
if (data.type === "error") {
streamError = new Error(data.content || "Wiki 查询失败");
streamFinished = true;
setIsLoading(false);
setAbortController(null);
break;
}
if (data.type === "sources") {
const sources = data.content;
setChatHistory(prev => {
if (prev.length === 0) return prev;
const newHistory = [...prev];
const lastIdx = newHistory.length - 1;
const last = newHistory[lastIdx];
if (last.role === "ai") {
const reasoning = [...(last.reasoning || [])];
const stepId = data.id || `source-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
const existingIndex = reasoning.findIndex(r => r.id === stepId);
if (existingIndex !== -1) {
reasoning[existingIndex] = { ...reasoning[existingIndex], data: sources };
} else {
reasoning.push({
id: stepId,
type: 'sources',
content: '引用来源数据',
data: sources,
time: new Date(data.ts || Date.now()).toLocaleTimeString('zh-CN', { hour12: false })
});
}
newHistory[lastIdx] = { ...last, reasoning, isStreaming: true, endTime: undefined };
}
return newHistory;
});
} else if (["thought", "call", "response"].includes(data.type)) {
setChatHistory(prev => {
const newHistory = [...prev];
let lastIdx = newHistory.length - 1;
if (lastIdx < 0 || newHistory[lastIdx].role !== "ai") {
newHistory.push({ role: "ai", content: "", reasoning: [], startTime: Date.now(), isStreaming: true });
lastIdx = newHistory.length - 1;
}
const last = newHistory[lastIdx];
const reasoning = [...(last.reasoning || [])];
const stepId = data.id || `${data.type}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
const existingIndex = reasoning.findIndex(r => r.id === stepId);
if (existingIndex !== -1) {
reasoning[existingIndex] = {
...reasoning[existingIndex],
type: (data.type && data.type !== 'thought') ? data.type : reasoning[existingIndex].type,
content: data.content,
name: data.name || reasoning[existingIndex].name
};
} else {
reasoning.push({
id: stepId,
type: data.type,
content: data.content,
name: data.name,
time: new Date(data.ts || Date.now()).toLocaleTimeString('zh-CN', { hour12: false })
});
}
newHistory[lastIdx] = { ...last, reasoning, isStreaming: true, endTime: undefined };
return newHistory;
});
} else if (data.type === "bot" || data.type === "stream") {
const content = data.content;
if (content === undefined || content === null) continue;
if (data.type === "bot") {
// 如果是 bot 类型,通常是完整消息或消息片段的替换
messageMap[m_id] = content;
// 重新组合所有非推理消息
aiResponse = Object.values(messageMap).join("");
} else {
// 如果是 stream 类型,则是追加增量
aiResponse += content;
}
setChatHistory(prev => {
const newHistory = [...prev];
const lastIdx = newHistory.length - 1;
if (lastIdx < 0 || newHistory[lastIdx].role !== "ai") {
newHistory.push({ role: "ai", content: aiResponse, reasoning: [], startTime: Date.now(), isStreaming: true });
} else {
newHistory[lastIdx] = {
...newHistory[lastIdx],
content: aiResponse,
startTime: newHistory[lastIdx].startTime || Date.now(),
isStreaming: true,
endTime: undefined
};
}
return newHistory;
});
}
} catch (e) {
console.error("Parse error", e, dataStr);
}
}
if (streamError) {
throw streamError;
}
}
} catch (e) {
if (e instanceof Error && e.name === 'AbortError') {
setChatHistory(prev => [...prev, { role: "ai", content: "已手动终止回答。" }]);
} else {
setChatHistory(prev => [...prev, { role: "ai", content: "咨询 AI 助手时发生错误,请稍后再试。" }]);
}
} finally {
setIsLoading(false);
setAbortController(null);
setChatHistory(prev => {
if (prev.length === 0) return prev;
const newHistory = [...prev];
const lastIdx = newHistory.length - 1;
const finishedAt = Date.now();
for (let i = 0; i < newHistory.length; i++) {
if (newHistory[i].role === "ai" && newHistory[i].isStreaming) {
newHistory[i] = {
...newHistory[i],
isStreaming: false,
endTime: newHistory[i].endTime || finishedAt
};
}
}
if (newHistory[lastIdx].role === "ai" && !newHistory[lastIdx].endTime) {
newHistory[lastIdx] = {
...newHistory[lastIdx],
isStreaming: false,
endTime: finishedAt
};
}
return newHistory;
});
}
};
const handleStopChat = () => {
if (abortController) {
abortController.abort();
setAbortController(null);
setIsLoading(false);
}
};
const toggleSelect = (name: string, e: React.MouseEvent) => {
e.stopPropagation();
const newSet = new Set(selectedIds);
if (newSet.has(name)) newSet.delete(name);
else newSet.add(name);
setSelectedIds(newSet);
};
const toggleSelectAll = () => {
if (selectedIds.size === filteredFiles.length) {
setSelectedIds(new Set());
} else {
setSelectedIds(new Set(filteredFiles.map(f => f.id)));
}
};
const selectedFileObj = useMemo(() => files.find(f => f.id === selectedFileId), [files, selectedFileId]);
const renderTokenCount = (total_tokens: number | { total_tokens: number; input_tokens: number; output_tokens: number } | undefined) => {
if (typeof total_tokens === 'object' && total_tokens !== null) {
return (total_tokens.total_tokens || 0).toString();
}
return (total_tokens || 0).toString();
};
const getFileIcon = (format: string) => {
const f = format.toLowerCase();
if (f === "pdf") return <FileImage className="w-4 h-4 text-rose-500" />;
if (f === "xlsx" || f === "xls" || f === "csv") return <FileSpreadsheet className="w-4 h-4 text-emerald-500" />;
if (f === "docx" || f === "doc") return <FileText className="w-4 h-4 text-blue-500" />;
if (f === "pptx" || f === "ppt") return <FileArchive className="w-4 h-4 text-orange-500" />;
if (f === "json" || f === "ts" || f === "tsx" || f === "js" || f === "py") return <FileCode className="w-4 h-4 text-slate-500" />;
return <FileText className="w-4 h-4 text-slate-500" />;
};
return (
<>
{/* Main Content Area: File Management Table */}
<header className="px-10 py-8 border-b border-slate-100 bg-white shrink-0">
<div className="flex items-center justify-between">
<div>
<h1 className="text-4xl font-bold text-slate-800 tracking-tight">Wiki 知识库</h1>
<p className="text-base text-slate-400 mt-2">管理您的企业文档与 AI 生成的 Wiki 知识</p>
</div>
<div className="flex items-center gap-4">
<div className="flex items-center gap-4 w-fit">
<div className="relative group w-80">
<button
onClick={() => {
setCurrentPage(1);
setSearchQuery(searchInput);
setRefreshTrigger(prev => prev + 1);
}}
title="查询"
className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-blue-500 transition-colors z-10"
>
<Search className="w-5 h-5" />
</button>
<input
type="text"
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") {
setCurrentPage(1);
setSearchQuery(searchInput);
setRefreshTrigger(prev => prev + 1);
}
}}
placeholder="搜索文件名..."
className="w-full pl-11 pr-10 py-2.5 bg-slate-50 border border-slate-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all"
/>
{searchInput && (
<button
onClick={() => {
setSearchInput("");
setSearchQuery("");
setCurrentPage(1);
setRefreshTrigger(prev => prev + 1);
}}
title="清除"
className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 transition-colors"
>
<X className="w-4 h-4" />
</button>
)}
</div>
<button
onClick={() => {
setCurrentPage(1);
setSearchQuery(searchInput);
setRefreshTrigger(prev => prev + 1);
}}
className="flex items-center gap-2 px-5 py-2.5 bg-blue-50 text-blue-600 rounded-xl cursor-pointer hover:bg-blue-100 transition font-bold text-sm h-[42px]"
>
查询
</button>
</div>
<button
onClick={handleLint}
className="flex items-center gap-2 px-5 py-2.5 bg-emerald-50 text-emerald-600 rounded-xl cursor-pointer hover:bg-emerald-100 transition font-bold text-sm h-[42px]"
>
<ShieldCheck className="w-4 h-4" />
健康检查
</button>
<button
onClick={() => { setUploadQueue([]); setIsUploadModalOpen(true); }}
className="flex items-center gap-2 px-5 py-2.5 bg-blue-600 text-white rounded-xl cursor-pointer hover:bg-blue-700 transition shadow-lg shadow-blue-500/20 font-bold text-sm h-[42px]"
>
<Upload className="w-4 h-4" />
上传文件
</button>
</div>
</div>
</header>
{/* Toolbar */}
<div className="px-8 py-4 bg-white border-b border-slate-100 flex items-center justify-between shrink-0">
<div className="flex items-center gap-4">
<div className="flex items-center gap-2">
<button
onClick={toggleSelectAll}
className="w-5 h-5 border border-slate-300 rounded bg-white flex items-center justify-center hover:border-blue-500 transition"
>
{selectedIds.size > 0 && (
selectedIds.size === filteredFiles.length ? <Check className="w-3 h-3 text-blue-600" /> : <div className="w-2 h-[2px] bg-blue-600" />
)}
</button>
<span className="text-sm font-medium text-slate-600">
{selectedIds.size > 0 ? `已选择 ${selectedIds.size} 项` : "全选"}
</span>
</div>
<div className="w-[1px] h-4 bg-slate-200 mx-2"></div>
{selectedIds.size > 0 && (
<div className="flex gap-2 animate-in fade-in slide-in-from-left-2 duration-200">
<button
onClick={handleBatchIngest}
className="text-xs font-bold bg-blue-50 text-blue-600 px-4 py-2 rounded-lg flex items-center gap-2 hover:bg-blue-100 transition"
>
<Zap className="w-3.5 h-3.5" /> 批量摄入
</button>
<button
onClick={async () => {
const ids = Array.from(selectedIds);
const toDelete = ids.filter(id => {
const f = files.find(file => file.id === id);
return f && (f.status === "Pending" || f.status === "Failed");
});
if (toDelete.length === 0) {
alert("选中的项目中没有处于“待处理”或“失败”状态的文件,无法删除。请先对已索引的文件执行“摄出”操作。");
return;
}
const restrictedCount = ids.length - toDelete.length;
const confirmMsg = restrictedCount > 0
? `选中的项目中,有 ${restrictedCount} 个文件已摄入,无法删除。\n确定删除其余 ${toDelete.length} 个“待处理”的文件吗?`
: `确定删除选中的 ${toDelete.length} 个文件吗?`;
if (confirm(confirmMsg)) {
setIsDeleting("batch");
// 如果批量删除中包含当前选中的文件,先清除选中状态以卸载预览组件 (释放 iframe 句柄)
const isSelectedIncluded = selectedFileId && toDelete.includes(selectedFileId);
if (isSelectedIncluded) {
const iframe = document.querySelector('iframe');
if (iframe) iframe.src = "about:blank";
setSelectedFileId(null);
setWikiContent("");
await new Promise(resolve => setTimeout(resolve, 1000));
}
try {
const response = await fetch(`${API_BASE}/files/batch_delete`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ids: toDelete })
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({ detail: "未知错误" }));
throw new Error(errorData.detail || `服务器返回状态码: ${response.status}`);
}
} catch (e) {
console.error("Batch delete failed", e);
const msg = e instanceof Error ? e.message : "请检查网络或后端服务状态";
alert(`批量删除失败: ${msg}`);
}
setSelectedIds(new Set());
fetchFiles();
setIsDeleting(null);
}
}}
className="text-xs font-bold bg-red-50 text-red-600 px-4 py-2 rounded-lg flex items-center gap-2 hover:bg-red-100 transition"
>
<Trash2 className="w-3.5 h-3.5" /> 批量删除
</button>
</div>
)}
</div>
</div>
{/* Table View */}
<div className="flex-1 overflow-auto scrollbar-thin p-8 flex flex-col">
<div className="min-w-full inline-block align-middle flex-1">
<div className="border border-slate-100 rounded-2xl overflow-hidden shadow-sm">
<table className="min-w-full divide-y divide-slate-100">
<thead className="bg-slate-50/80">
<tr>
<th scope="col" className="px-6 py-4 text-left text-xs font-bold text-slate-400 uppercase tracking-wider w-12"></th>
<th
scope="col"
className="px-6 py-4 text-left text-xs font-bold text-slate-400 uppercase tracking-wider cursor-pointer hover:text-blue-600 transition"
onClick={() => {
if (sortBy === "name") setSortOrder(sortOrder === "asc" ? "desc" : "asc");
else { setSortBy("name"); setSortOrder("asc"); }
}}
>
文件名 {sortBy === "name" && (sortOrder === "asc" ? "↑" : "↓")}
</th>
<th scope="col" className="px-6 py-4 text-left text-xs font-bold text-slate-400 uppercase tracking-wider">状态</th>
<th
scope="col"
className="px-6 py-4 text-left text-xs font-bold text-slate-400 uppercase tracking-wider cursor-pointer hover:text-blue-600 transition"
onClick={() => {
if (sortBy === "size") setSortOrder(sortOrder === "asc" ? "desc" : "asc");
else { setSortBy("size"); setSortOrder("desc"); }
}}
>
大小 {sortBy === "size" && (sortOrder === "asc" ? "↑" : "↓")}
</th>
<th
scope="col"
className="px-6 py-4 text-left text-xs font-bold text-slate-400 uppercase tracking-wider cursor-pointer hover:text-blue-600 transition"
onClick={() => {
if (sortBy === "time") setSortOrder(sortOrder === "asc" ? "desc" : "asc");
else { setSortBy("time"); setSortOrder("desc"); }
}}
>
上传时间 {sortBy === "time" && (sortOrder === "asc" ? "↑" : "↓")}
</th>
<th scope="col" className="px-6 py-4 text-left text-xs font-bold text-slate-400 uppercase tracking-wider">字数</th>
<th scope="col" className="px-6 py-4 text-left text-xs font-bold text-slate-400 uppercase tracking-wider">Token 消耗</th>
<th scope="col" className="px-6 py-4 text-left text-xs font-bold text-slate-400 uppercase tracking-wider">处理时长</th>
<th scope="col" className="px-6 py-4 text-right text-xs font-bold text-slate-400 uppercase tracking-wider">操作</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-slate-50">
{isInitialLoading ? (
[1, 2, 3, 4, 5].map(i => (
<tr key={i} className="animate-pulse">
<td className="px-6 py-4"><div className="w-5 h-5 bg-slate-100 rounded" /></td>
<td className="px-6 py-4"><div className="h-4 bg-slate-100 rounded w-3/4" /></td>
<td className="px-6 py-4"><div className="h-4 bg-slate-50 rounded w-16" /></td>
<td className="px-6 py-4"><div className="h-4 bg-slate-50 rounded w-12" /></td>
<td className="px-6 py-4"><div className="h-4 bg-slate-50 rounded w-24" /></td>
<td className="px-6 py-4"><div className="h-4 bg-slate-50 rounded w-16" /></td>
<td className="px-6 py-4"><div className="h-4 bg-slate-50 rounded w-16" /></td>
<td className="px-6 py-4"><div className="h-4 bg-slate-100 rounded ml-auto w-20" /></td>
</tr>
))
) : (
filteredFiles.map((file) => (
<tr
key={file.id}
className={cn(
"group hover:bg-slate-50/80 transition-colors cursor-pointer",
selectedFileId === file.id && "bg-blue-50/30"
)}
onClick={() => onSelectFile(file.id)}
>
<td className="px-6 py-4 whitespace-nowrap" onClick={(e) => e.stopPropagation()}>
<button
onClick={(e) => toggleSelect(file.id, e)}
className={cn(
"w-5 h-5 border rounded flex items-center justify-center transition-all",
selectedIds.has(file.id) ? "bg-blue-600 border-blue-600 text-white" : "bg-white border-slate-200 group-hover:border-slate-300"
)}
>
{selectedIds.has(file.id) && <Check className="w-3 h-3" />}
</button>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<div className="flex items-center gap-3">
<div className="p-2 bg-slate-100 rounded-lg text-slate-500 group-hover:text-blue-600 transition-colors">
{getFileIcon(file.format)}
</div>
<span className="text-sm font-semibold text-slate-700 truncate max-w-[500px]" title={file.name}>
{file.name}
</span>
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap">
{isDeleting === file.id ? (
<span className="inline-flex items-center gap-1.5 px-2 py-1 rounded-md text-[10px] font-bold bg-red-50 text-red-600 border border-red-100">
<Loader2 className="w-3 h-3 animate-spin" /> 删除中
</span>
) : (
<>
{file.status === "Indexed" ? (
<span className="inline-flex items-center gap-1.5 px-2 py-1 rounded-md text-[10px] font-bold bg-emerald-50 text-emerald-600 border border-emerald-100">
<CheckCircle2 className="w-3 h-3" /> 已索引
</span>
) : file.status === "Ingesting" ? (
<span className="inline-flex items-center gap-1.5 px-2 py-1 rounded-md text-[10px] font-bold bg-blue-50 text-blue-600 border border-blue-100 animate-pulse">
<Loader2 className="w-3 h-3 animate-spin" /> 摄入中
</span>
) : file.status === "Uploading" ? (
<span className="inline-flex items-center gap-1.5 px-2 py-1 rounded-md text-[10px] font-bold bg-purple-50 text-purple-600 border border-purple-100 animate-pulse">
<Upload className="w-3 h-3 animate-bounce" /> 上传中
</span>
) : file.status === "Failed" ? (
<span className="inline-flex items-center gap-1.5 px-2 py-1 rounded-md text-[10px] font-bold bg-red-50 text-red-600 border border-red-100">
<AlertCircle className="w-3 h-3" /> 摄入失败
</span>
) : (
<span className="inline-flex items-center gap-1.5 px-2 py-1 rounded-md text-[10px] font-bold bg-amber-50 text-amber-600 border border-amber-100">
<Clock className="w-3 h-3" /> 待处理
</span>
)}
</>
)}
</td>
<td className="px-6 py-4 whitespace-nowrap text-xs text-slate-500 font-medium">
{file.size}
</td>
<td className="px-6 py-4 whitespace-nowrap text-xs text-slate-500 font-medium">
{file.time}
</td>
<td className="px-6 py-4 whitespace-nowrap text-xs text-slate-500 font-medium">
{file.word_count ? file.word_count.toLocaleString() : "--"}
</td>
<td className="px-6 py-4 whitespace-nowrap">
<span className="text-xs font-bold text-slate-700">
{file.status === "Indexed" && file.meta ? renderTokenCount(file.meta.total_tokens) : "--"}
</span>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<span className="text-xs font-bold text-slate-700">
{file.status === "Indexed" && file.meta ? `${file.meta.ingest_duration}s` : "--"}
</span>
</td>
<td className="px-6 py-4 whitespace-nowrap text-right" onClick={(e) => e.stopPropagation()}>
<div className="flex items-center justify-end gap-2 relative z-10">
{(file.status === "Pending" || file.status === "Failed") && !file.id.startsWith('-') && (
<>
<button onClick={(e) => { e.stopPropagation(); handleIngest(file.id); }} title="开始摄入" className="p-2 bg-blue-50 hover:bg-blue-100 text-blue-600 rounded-lg cursor-pointer transition-colors">
<Zap className="w-4 h-4" />
</button>
<button onClick={(e) => { e.stopPropagation(); handleDelete(file.id); }} title="删除" className="p-2 bg-slate-50 hover:bg-red-50 text-slate-500 hover:text-red-500 rounded-lg cursor-pointer transition-colors">
<Trash2 className="w-4 h-4" />
</button>
</>
)}
{file.status === "Ingesting" && (
<button disabled title="处理中..." className="p-2 bg-slate-50 text-slate-400 rounded-lg cursor-not-allowed">
<Loader2 className="w-4 h-4 animate-spin" />
</button>
)}
{file.status === "Indexed" && (
<>
<button onClick={(e) => { e.stopPropagation(); handleEgress(file.id); }} title="撤回" className="p-2 bg-amber-50 hover:bg-amber-100 text-amber-600 rounded-lg cursor-pointer transition-colors">
<Eject className="w-4 h-4 rotate-180" />
</button>
</>
)}
{!file.id.startsWith('-') && (
<button onClick={(e) => { e.stopPropagation(); handleDownload(file.id, file.name); }} title="下载原文件" className="p-2 hover:bg-slate-100 text-slate-400 hover:text-slate-600 rounded-lg cursor-pointer transition-colors">
<Download className="w-4 h-4" />
</button>
)}
</div>
</td>
</tr>
))
)}
</tbody>
</table>
{!isInitialLoading && filteredFiles.length === 0 && (
<div className="py-20 text-center bg-white">
<Filter className="w-12 h-12 mx-auto mb-4 text-slate-200" />
<h3 className="text-lg font-bold text-slate-800">未找到匹配的文件</h3>
<p className="text-sm text-slate-400 mt-1">请尝试更换关键词或检查筛选条件</p>
</div>
)}
</div>
</div>
{/* Pagination */}
<div className="mt-6 flex items-center justify-end shrink-0 pb-6 pr-24">
<div className="flex items-center gap-6">
<div className="text-sm text-slate-500 font-medium">
共 <span className="text-slate-800">{totalCount}</span> 个文件
</div>
<div className="flex items-center gap-2">
<button
onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
disabled={currentPage === 1}
className="px-4 py-2 bg-white border border-slate-200 rounded-xl text-sm font-bold text-slate-600 hover:bg-slate-50 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition-colors"
>
上一页
</button>
<div className="text-sm font-bold text-slate-700 px-4">
第 {currentPage} 页
</div>
<button
onClick={() => setCurrentPage(p => p + 1)}
disabled={currentPage * pageSize >= totalCount}
className="px-4 py-2 bg-white border border-slate-200 rounded-xl text-sm font-bold text-slate-600 hover:bg-slate-50 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition-colors"
>
下一页
</button>
</div>
</div>
</div>
</div>
{/* 3. Preview Modal */}
{isModalOpen && (
<div className="fixed inset-0 z-[60] flex items-center justify-center p-8 bg-slate-900/60 backdrop-blur-sm animate-in fade-in duration-300">
<div className="bg-white w-full max-w-6xl h-full rounded-[2rem] shadow-2xl flex flex-col overflow-hidden animate-in zoom-in-95 duration-300">
<header className="px-8 py-6 border-b border-slate-100 flex items-center justify-between shrink-0">
<div className="flex items-center gap-4">
<div className="p-3 bg-blue-50 rounded-2xl text-blue-600">
<BookOpen className="w-6 h-6" />
</div>
<div>
<h2 className="text-xl font-bold text-slate-800 truncate max-w-md">
{selectedFileObj?.name}
</h2>
<div className="flex items-center gap-3 mt-1">
<span className="text-xs font-medium text-slate-400">大小: {selectedFileObj?.size}</span>
<span className="text-xs font-medium text-slate-400">•</span>
<span className="text-xs font-medium text-slate-400">更新: {selectedFileObj?.time}</span>
{selectedFileObj?.status === "Indexed" && (
<>
<span className="text-xs font-medium text-slate-400">•</span>
<span className="text-xs font-bold text-emerald-600 bg-emerald-50 px-2 py-0.5 rounded-full">已索引</span>
</>
)}
</div>
</div>
</div>
<div className="flex items-center gap-3">
{selectedFileId && selectedFileObj?.status === "Indexed" && (
<div className="flex bg-slate-100 p-1.5 rounded-2xl">
<button
onClick={() => setViewMode("raw")}
className={cn(
"px-6 py-2 text-sm font-bold rounded-xl transition-all",
viewMode === "raw" ? "bg-white text-blue-600 shadow-md" : "text-slate-500 hover:text-slate-800"
)}
>
原始文件预览
</button>
<button
onClick={() => { setViewMode("wiki_tree"); }}
className={cn(
"px-6 py-2 text-sm font-bold rounded-xl transition-all",
viewMode === "wiki_tree" ? "bg-white text-blue-600 shadow-md" : "text-slate-500 hover:text-slate-800"
)}
>
Wiki仓库相关文件
</button>
</div>
)}
<button
onClick={() => setIsModalOpen(false)}
className="p-3 hover:bg-slate-100 rounded-2xl transition-colors text-slate-400 hover:text-slate-800"
>
<X className="w-6 h-6" />
</button>
</div>
</header>
<div className="flex-1 overflow-hidden bg-slate-50/30 flex">
{viewMode === "raw" ? (
<div className="flex w-full h-full">
<div className="flex-1 w-full h-full p-8">
{selectedFileObj?.name?.toLowerCase().endsWith(".pdf") ? (
<iframe
key={selectedFileId}
src={`${API_BASE}/files/view/${encodeURIComponent(selectedFileId || '')}`}
className="w-full h-full rounded-3xl border border-slate-200 bg-white shadow-xl"
/>
) : (
<div className="w-full h-full bg-white rounded-3xl border border-slate-200 p-12 overflow-auto shadow-xl relative custom-scrollbar">
{isPreviewLoading && (
<div className="absolute inset-0 bg-white/50 backdrop-blur-sm flex items-center justify-center z-10">
<Loader2 className="w-10 h-10 animate-spin text-blue-600" />
</div>
)}
<pre className="text-sm text-slate-700 font-mono whitespace-pre-wrap leading-relaxed">{previewContent}</pre>
</div>
)}
</div>
</div>
) : (
<div className="flex w-full h-full">
<div className="w-80 border-r border-slate-200 bg-slate-50 flex flex-col shrink-0 overflow-y-auto custom-scrollbar">
<div className="p-4 border-b border-slate-200">
<h3 className="text-xs font-bold text-slate-500 uppercase tracking-wider flex items-center gap-2">
<BookOpen className="w-4 h-4" />
相关文件树 ({wikiLinks.length})
</h3>
</div>
<div className="p-4 flex-1 flex flex-col gap-1 overflow-x-hidden">
{wikiLinks.length > 0 ? (
<TreeNode
node={buildTree(wikiLinks)}
onSelect={async (path) => {
setSelectedWikiPath(path);
setWikiContent("正在加载文件内容...");
try {
const res = await fetch(`${API_BASE}/wiki/file?path=${encodeURIComponent(path)}`);
if (res.ok) {
const data = await res.json();
setWikiContent(data.content);
} else {
setWikiContent("文件加载失败");
}
} catch (e) {
setWikiContent("文件加载失败");
}
}}
selectedPath={selectedWikiPath}
/>
) : (
<div className="text-xs text-slate-400 p-4 text-center">
暂无相关文件
</div>
)}
</div>
</div>
<div className="flex-1 w-full h-full overflow-y-auto p-12 custom-scrollbar bg-white">
{selectedWikiPath ? (
<div className="max-w-4xl mx-auto">
<article className="prose prose-slate prose-blue max-w-none prose-headings:font-bold prose-a:text-blue-600">
<ReactMarkdown remarkPlugins={[remarkGfm]}>
{wikiContent}
</ReactMarkdown>
</article>
</div>
) : (
<div className="flex items-center justify-center h-full text-slate-400">
<div className="text-center">
<FileText className="w-12 h-12 mx-auto mb-4 opacity-50" />
<p>请在左侧选择要预览的 Wiki 文件</p>
</div>
</div>
)}
</div>
</div>
)}
</div>
</div>
</div>
)}
{/* 4. AI Copilot (Modern Chat Interface) */}
<button
onClick={() => setIsChatOpen(!isChatOpen)}
className={cn(
"fixed bottom-8 right-8 w-16 h-16 rounded-2xl shadow-2xl flex items-center justify-center transition-all duration-300 z-50 group",
isChatOpen ? "bg-slate-900 text-white rotate-90" : "bg-blue-600 text-white hover:scale-110 active:scale-95"
)}
>
{isChatOpen ? <X className="w-6 h-6" /> : <MessageSquare className="w-6 h-6" />}
<span className="absolute right-20 bg-slate-800 text-white text-[10px] px-3 py-1.5 rounded-lg opacity-0 group-hover:opacity-100 transition whitespace-nowrap pointer-events-none">
咨询 Wiki AI 助手
</span>
</button>
{isChatOpen && (
<div className="fixed bottom-28 right-8 w-[800px] bg-white rounded-3xl shadow-[0_20px_50px_rgba(0,0,0,0.15)] border border-slate-200 flex flex-col h-[800px] z-50 animate-in fade-in slide-in-from-bottom-10 duration-300 overflow-hidden">
<div className="p-6 border-b border-slate-100 flex items-center justify-between bg-gradient-to-r from-blue-600 to-indigo-700 text-white">
<div className="flex items-center gap-3">
<div className="w-10 h-10 bg-white/20 rounded-xl flex items-center justify-center backdrop-blur-md">
<MessageSquare className="w-5 h-5" />
</div>
<div>
<h3 className="font-bold text-sm">Wiki Copilot</h3>
<div className="flex items-center gap-1.5">
<div className="w-1.5 h-1.5 bg-emerald-400 rounded-full animate-pulse" />
<span className="text-[10px] text-blue-100 font-medium uppercase tracking-wider">在线支持</span>
</div>
</div>
</div>
<button
onClick={async () => {
if (confirm("确定要清空当前对话历史吗?")) {
try {
await fetch(`${API_BASE}/wiki/clear_history`, { method: "POST" });
} catch (e) {
console.error("Failed to clear backend memory", e);
}
setChatHistory([]);
setQuery("");
}
}}
className="p-2 hover:bg-white/10 rounded-lg transition-colors text-blue-100 hover:text-white"
title="清空会话"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
<div className="flex-1 overflow-y-auto p-6 scrollbar-thin bg-slate-50/50 flex flex-col">
{chatHistory.map((msg, idx) => (
<MessageBubble
key={idx}
role={msg.role}
content={msg.content}
reasoning={msg.reasoning}
isStreaming={msg.isStreaming ?? (isLoading && idx === chatHistory.length - 1 && !msg.endTime)}
startTime={msg.startTime}
endTime={msg.endTime}
serverDurationMs={msg.serverDurationMs}
/>
))}
{isLoading && chatHistory[chatHistory.length - 1]?.role !== "ai" && (
<div className="flex gap-3">
<div className="w-9 h-9 bg-blue-600 rounded-xl flex items-center justify-center text-white shrink-0 shadow-md font-bold text-xs">AI</div>
<div className="bg-white p-4 rounded-2xl rounded-tl-none shadow-sm border border-slate-100 flex items-center gap-2">
<Loader2 className="w-4 h-4 animate-spin text-blue-600" />
<span className="text-xs text-slate-500">正在查阅知识库...</span>
</div>
</div>
)}
<div ref={chatEndRef} />
</div>
<div className="p-6 border-t border-slate-100 bg-white">
<div className="relative">
<input
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && handleQuery()}
placeholder="输入问题,AI 将实时查询 Wiki..."
className="w-full text-sm bg-slate-50 border border-slate-200 rounded-2xl px-4 py-4 pr-14 focus:ring-4 focus:ring-blue-500/10 focus:border-blue-500 outline-none transition-all"
/>
{isLoading ? (
<button
onClick={handleStopChat}
className="absolute right-2 top-1/2 -translate-y-1/2 w-10 h-10 bg-red-500 text-white rounded-xl flex items-center justify-center hover:bg-red-600 shadow-md transition-all active:scale-95"
title="终止生成"
>
<Square className="w-4 h-4 fill-current" />
</button>
) : (
<button
onClick={handleQuery}
disabled={isLoading || !query.trim()}
className="absolute right-2 top-1/2 -translate-y-1/2 w-10 h-10 bg-blue-600 text-white rounded-xl flex items-center justify-center hover:bg-blue-700 shadow-md transition-all active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed"
>
<ChevronRight className="w-5 h-5" />
</button>
)}
</div>
</div>
</div>
)}
{/* 5. Lint Modal */}
{isLintModalOpen && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/40 backdrop-blur-sm p-8 animate-in fade-in duration-200">
<div className="bg-slate-50 w-full max-w-4xl h-[80vh] rounded-3xl shadow-2xl flex flex-col overflow-hidden border border-slate-200/50">
<div className="h-16 px-6 bg-white border-b border-slate-100 flex items-center justify-between shrink-0">
<div className="flex items-center gap-3">
<div className="w-10 h-10 bg-emerald-100 rounded-xl flex items-center justify-center">
<ShieldCheck className="w-5 h-5 text-emerald-600" />
</div>
<div>
<h3 className="font-bold text-sm text-slate-800">Wiki 健康检查 (Lint)</h3>
<div className="flex items-center gap-1.5">
{isLinting ? (
<>
<div className="w-1.5 h-1.5 bg-emerald-400 rounded-full animate-pulse" />
<span className="text-[10px] text-slate-500 font-medium tracking-wider">正在扫描知识库...</span>
</>
) : (
<>
<CheckCircle2 className="w-3 h-3 text-emerald-500" />
<span className="text-[10px] text-slate-500 font-medium tracking-wider">扫描完成</span>
</>
)}
</div>
</div>
</div>
<button
onClick={() => setIsLintModalOpen(false)}
className="p-2 hover:bg-slate-100 rounded-lg transition-colors text-slate-400 hover:text-slate-800"
>
<X className="w-5 h-5" />
</button>
</div>
<div className="flex-1 overflow-y-auto p-6 scrollbar-thin bg-white/50 flex flex-col">
{lintHistory.map((msg, idx) => (
<MessageBubble
key={idx}
role={msg.role}
content={msg.content}
reasoning={msg.reasoning}
isStreaming={isLinting && idx === lintHistory.length - 1}
startTime={msg.startTime}
endTime={msg.endTime}
/>
))}
<div ref={lintEndRef} />
</div>
</div>
</div>
)}
<style jsx global>{`
.custom-scrollbar::-webkit-scrollbar {
width: 6px;
}
.custom-scrollbar::-webkit-scrollbar-track {
background: transparent;
}
.custom-scrollbar::-webkit-scrollbar-thumb {
background: #E2E8F0;
border-radius: 10px;
}
.custom-scrollbar::-webkit-scrollbar-thumb:hover {
background: #CBD5E1;
}
.scrollbar-thin::-webkit-scrollbar {
width: 4px;
}
.scrollbar-thin::-webkit-scrollbar-track {
background: transparent;
}
.scrollbar-thin::-webkit-scrollbar-thumb {
background: #F1F5F9;
border-radius: 10px;
}
`}</style>
{/* Upload Modal */}
{isUploadModalOpen && (
<div className="fixed inset-0 z-[100] flex items-center justify-center p-8 bg-slate-900/60 backdrop-blur-sm animate-in fade-in duration-300">
<div className="bg-white w-full max-w-2xl rounded-3xl shadow-2xl flex flex-col overflow-hidden animate-in zoom-in-95 duration-300">
<header className="px-8 py-6 border-b border-slate-100 flex items-center justify-between bg-slate-50/50">
<div className="flex items-center gap-3">
<div className="p-2.5 bg-blue-100 text-blue-600 rounded-xl">
<Upload className="w-5 h-5" />
</div>
<div>
<h2 className="text-xl font-bold text-slate-800">上传新文件</h2>
<p className="text-xs text-slate-500 mt-0.5">支持 PDF, Word, Excel, PPT, Markdown</p>
</div>
</div>
<button onClick={() => setIsUploadModalOpen(false)} className="p-2 hover:bg-slate-200 rounded-xl transition-colors text-slate-400 hover:text-slate-800">
<X className="w-5 h-5" />
</button>
</header>
<div className="p-8 flex flex-col gap-6 bg-white min-h-[300px] max-h-[60vh] overflow-auto">
{uploadQueue.length === 0 ? (
<div className="flex-1 flex flex-col items-center justify-center border-2 border-dashed border-slate-200 rounded-2xl bg-slate-50 hover:bg-blue-50/50 hover:border-blue-300 transition-colors p-10 relative group">
<input type="file" multiple className="absolute inset-0 w-full h-full opacity-0 cursor-pointer z-10" onChange={handleUploadSelect} />
<div className="w-16 h-16 bg-white shadow-sm rounded-full flex items-center justify-center mb-4 group-hover:scale-110 transition-transform">
<Upload className="w-8 h-8 text-blue-500" />
</div>
<h3 className="text-lg font-bold text-slate-700">点击或拖拽文件到此处</h3>
<p className="text-sm text-slate-400 mt-2 text-center max-w-xs">
上传的文件将进入“原始文件大厅”,稍后您可以发起批量摄入。
</p>
</div>
) : (
<div className="flex flex-col gap-3">
<div className="flex items-center justify-between mb-2">
<h3 className="text-sm font-bold text-slate-700">待上传列表 ({uploadQueue.length})</h3>
{!uploadQueue.some(q => q.status === 'uploading') && (
<label className="text-xs font-bold text-blue-600 bg-blue-50 px-3 py-1.5 rounded-lg cursor-pointer hover:bg-blue-100 transition-colors">
+ 继续添加
<input type="file" multiple className="hidden" onChange={handleUploadSelect} />
</label>
)}
</div>
{uploadQueue.map((item, idx) => (
<div key={idx} className="flex items-center gap-4 p-4 bg-slate-50 border border-slate-100 rounded-xl">
<div className="p-2 bg-white rounded-lg shadow-sm border border-slate-100">
{getFileIcon(item.name.split('.').pop() || "")}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between mb-1">
<span className="text-sm font-semibold text-slate-700 truncate">{item.name}</span>
<span className="text-xs font-medium text-slate-500">{(item.file.size / 1024 / 1024).toFixed(2)} MB</span>
</div>
{item.status === 'uploading' ? (
<div className="flex items-center gap-1.5 mt-1 text-xs font-bold text-blue-600">
<Loader2 className="w-3.5 h-3.5 animate-spin" /> 上传中...
</div>
) : item.status === 'success' ? (
<div className="flex items-center gap-1.5 mt-1 text-xs font-bold text-emerald-600">
<CheckCircle2 className="w-3.5 h-3.5" /> 上传成功
</div>
) : item.status === 'error' ? (
<div className="flex items-center gap-1.5 mt-1 text-xs font-bold text-red-600" title={item.errorMsg}>
<AlertCircle className="w-3.5 h-3.5" /> {item.errorMsg || "上传失败"}
</div>
) : (
<div className="flex items-center gap-1.5 mt-1 text-xs font-bold text-slate-400">
等待上传...
</div>
)}
</div>
{item.status !== 'uploading' && (
<button onClick={() => setUploadQueue(prev => prev.filter((_, i) => i !== idx))} className="p-2 hover:bg-slate-200 rounded-lg text-slate-400 hover:text-slate-700 transition-colors" title="移除该项">
<X className="w-4 h-4" />
</button>
)}
</div>
))}
</div>
)}
</div>
{uploadQueue.length > 0 && (
<footer className="px-8 py-4 border-t border-slate-100 bg-slate-50 flex items-center justify-end gap-3">
<button
onClick={() => { setUploadQueue([]); setIsUploadModalOpen(false); }}
disabled={uploadQueue.some(q => q.status === 'uploading')}
className="px-6 py-2.5 rounded-xl font-bold text-sm text-slate-600 hover:bg-slate-200 transition-colors disabled:opacity-50"
>
取消
</button>
{uploadQueue.every(q => q.status === 'success' || q.status === 'error') ? (
<button
onClick={() => { setUploadQueue([]); setIsUploadModalOpen(false); fetchFiles(1, pageSize, searchQuery, false); }}
className="flex items-center gap-2 px-6 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-xl font-bold text-sm transition-colors shadow-lg shadow-emerald-500/30"
>
<CheckCircle2 className="w-4 h-4" /> 确认
</button>
) : (
<button
onClick={handleUploadConfirm}
disabled={uploadQueue.some(q => q.status === 'uploading')}
className="flex items-center gap-2 px-6 py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-xl font-bold text-sm transition-colors shadow-lg shadow-blue-500/30 disabled:opacity-50"
>
{uploadQueue.some(q => q.status === 'uploading') ? (
<><Loader2 className="w-4 h-4 animate-spin" /> 上传中...</>
) : (
<><Upload className="w-4 h-4" /> 确认上传</>
)}
</button>
)}
</footer>
)}
</div>
</div>
)}
</>
);
}