page.tsx 90 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 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086
"use client";

import { useState, useEffect, useMemo, useRef, useCallback } 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, Check,
  X, AlertCircle, Eye, LogOut as Eject, Folder, Square, RefreshCw,
  FileImage, FileSpreadsheet, FileArchive, FileCode,
  ChevronLeft, ChevronsLeft, ChevronsRight, PanelLeft, Database
} from "lucide-react";
import { cn } from "@/lib/utils";
import { MessageBubble, type ReasoningStep } from "@/components/MessageBubble";
import FrontmatterCard from "@/components/FrontmatterCard";
import ConfirmDialog from "@/components/ConfirmDialog";
import SessionSidebar from "@/components/SessionSidebar";
import Toast, { type ToastState } from "@/components/Toast";
import { KbTreePicker } from "@/components/system/OrgTree";
import Perm from "@/components/Perm";
import {
  createSession,
  deleteSession,
  fetchMe,
  fetchSessionMessages,
  listReadableKbs,
  listSessions,
  type CurrentUser,
  type KbInfo,
  type SessionItem,
  type SessionMessage,
} from "@/lib/auth";
import { parseFrontmatter } from "@/lib/frontmatter";
import * as XLSX from "xlsx";
import type { SheetData } from "x-data-spreadsheet";
import "x-data-spreadsheet/dist/xspreadsheet.css";
import type { FileItem, UploadQueueItem, PreviewStatus } from "@/types/wiki";
import { workbookToSpreadsheetData, SPREADSHEET_MAX_FILE_BYTES, SPREADSHEET_MAX_ROWS } from "@/lib/spreadsheet";
import { buildTree, getPaginationRange, PAGE_SIZE_OPTIONS, canDirectIframePreview, needsControlledPreview, needsSpreadsheetPreview } from "@/lib/wikiFiles";
import { getFileIcon } from "@/components/wiki/fileIcons";
import { LintModal } from "@/components/wiki/LintModal";
import { PreviewModal } from "@/components/wiki/PreviewModal";
import { UploadModal } from "@/components/wiki/UploadModal";

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 [previewStatus, setPreviewStatus] = useState<PreviewStatus>("idle");
  const [isPreviewLoading, setIsPreviewLoading] = useState(false);
  const [spreadsheetSheets, setSpreadsheetSheets] = useState<SheetData[] | null>(null);
  const [spreadsheetTruncated, setSpreadsheetTruncated] = useState(false);
  const latestPreviewRequestIdRef = useRef<string | null>(null);
  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 [isZipDownloading, setIsZipDownloading] = useState(false);
  const [abortController, setAbortController] = useState<AbortController | null>(null);

  // 会话由后端持久化:前端只持有当前会话 id 与列表,不再自行生成 sessionId。
  const [currentUser, setCurrentUser] = useState<CurrentUser | null>(null);
  const [sessions, setSessions] = useState<SessionItem[]>([]);
  const [currentSessionId, setCurrentSessionId] = useState<string | null>(null);
  // 切换会话时拉取消息(只影响消息区),与会话列表加载区分开
  const [sessionsLoading, setSessionsLoading] = useState(false);
  // 仅首次拉取会话列表时为真,避免切换会话时侧栏误报「加载中」
  const [listLoading, setListLoading] = useState(false);
  // 新建会话进行中,用于禁用按钮 + 转圈
  const [creatingSession, setCreatingSession] = useState(false);
  // 防连点的实际守卫。setState 要等下次渲染才生效,快速连点时读 state 仍是旧的 false
  // 会漏进第二次请求,一次性建出多个会话;ref 是同步写入,才真正拦得住。
  const creatingSessionRef = useRef(false);
  // 会话列表默认展开
  const [showSessionList, setShowSessionList] = useState(true);
  // 接口失败等场景的全局提示
  const [toast, setToast] = useState<ToastState | null>(null);
  const showToast = useCallback((message: string, type: ToastState["type"] = "error") => {
    setToast({ message, type });
  }, []);
  const [pendingDeleteSession, setPendingDeleteSession] = useState<SessionItem | null>(null);
  const [deletingSession, setDeletingSession] = useState(false);

  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 restoreMessages = (messages: SessionMessage[]) =>
    messages.map((msg) => ({
      role: (msg.role === "assistant" ? "ai" : "user") as "user" | "ai",
      content: msg.content,
      reasoning: (msg.reasoning || undefined) as ReasoningStep[] | undefined,
      // 历史重放:用落库的总耗时显示秒数(非流式,MessageBubble 会优先采用)
      serverDurationMs: msg.durationMs && msg.durationMs > 0 ? msg.durationMs : undefined,
    }));

  const refreshSessions = useCallback(async () => {
    try {
      const data = await listSessions(30, 0);
      setSessions(data.items);
      return data.items;
    } catch {
      return [] as SessionItem[];
    }
  }, []);

  const openSession = useCallback(async (id: string) => {
    setCurrentSessionId(id);
    // 先清空旧消息再拉新会话,切换时消息区显示加载态而非停留在上一会话内容;
    // 注意这里只动 sessionsLoading(消息区),不碰会话列表的加载态。
    setChatHistory([]);
    setSessionsLoading(true);
    try {
      const data = await fetchSessionMessages(id);
      setChatHistory(restoreMessages(data.messages));
    } catch {
      setChatHistory([]);
    } finally {
      setSessionsLoading(false);
    }
  }, []);

  // 不加 useCallback:消费方 SessionSidebar 不是 memo 组件,包了也不省渲染,
  // 反而让编译器无法保留 memo 而整体跳过优化。防连点由 ref 保证,与函数是否稳定无关。
  const handleNewSession = async () => {
    // 防连点:新建进行中直接忽略后续点击,避免一次性建出多个会话
    if (creatingSessionRef.current) return;
    creatingSessionRef.current = true;
    setCreatingSession(true);
    try {
      // 带上当前会话 id:后端据此对上一个会话触发收尾沉淀(未达轮数门槛会跳过)
      const data = await createSession(currentSessionId);
      setCurrentSessionId(data.id);
      setChatHistory([]);
      setQuery("");
      await refreshSessions();
    } catch {
      /* 新建失败时保持现状,用户可重试 */
    } finally {
      creatingSessionRef.current = false;
      setCreatingSession(false);
    }
  };

  const handleDeleteSession = useCallback(async () => {
    if (!pendingDeleteSession) return;
    const target = pendingDeleteSession;
    setDeletingSession(true);
    try {
      await deleteSession(target.id);
    } catch {
      // 删除失败:保留弹窗让用户重试
      setDeletingSession(false);
      return;
    }
    // 删除已落库(沉淀在后端后台跑),立即关弹窗并从列表摘掉该项。
    // 后面的「刷新列表 + 切到另一个会话」不再压着确认框的 loading 转圈。
    setSessions((prev) => prev.filter((s) => s.id !== target.id));
    setPendingDeleteSession(null);
    setDeletingSession(false);

    const remaining = await refreshSessions();
    // 删的是当前会话时,切到最近一个;列表空了就自动新建
    if (target.id === currentSessionId) {
      if (remaining.length > 0) {
        await openSession(remaining[0].id);
      } else {
        const data = await createSession(null).catch(() => null);
        if (data) {
          setCurrentSessionId(data.id);
          setChatHistory([]);
          await refreshSessions();
        }
      }
    }
  }, [pendingDeleteSession, currentSessionId, refreshSessions, openSession]);

  // 每次打开 Copilot 面板:拉取登录态与会话列表,并默认落到「最近一个有内容的会话」,
  // 避免因最新会话是空的「新会话」而打开即空白。若当前已停在一个有内容的会话上则不打扰。
  useEffect(() => {
    if (!isChatOpen) return;

    let cancelled = false;
    (async () => {
      let me = currentUser;
      if (!me) {
        me = await fetchMe().catch(() => null);
        if (cancelled || !me) return;
        setCurrentUser(me);
      }

      setListLoading(true);
      const items = await refreshSessions();
      setListLoading(false);
      if (cancelled) return;

      const current = items.find((s) => s.id === currentSessionId);
      // 当前未选中、已失效、或停在空会话上 → 跳到最近一个有内容的会话
      if (!current || current.totalTurns === 0) {
        const target = items.find((s) => s.totalTurns > 0) ?? items[0];
        if (target) {
          if (target.id !== currentSessionId) await openSession(target.id);
        } else {
          // 一个会话都没有:新建一个空会话兜底
          const data = await createSession(null).catch(() => null);
          if (data && !cancelled) {
            setCurrentSessionId(data.id);
            setChatHistory([]);
            await refreshSessions();
          }
        }
      }
    })();

    return () => {
      cancelled = true;
    };
    // 仅在面板开关切换时触发;其余依赖为闭包读取的当时值,无需追踪
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isChatOpen]);

  const currentSessionTitle =
    sessions.find((s) => s.id === currentSessionId)?.title || "新会话";

  useEffect(() => {
    if (!isModalOpen) return undefined;

    const previousBodyOverflow = document.body.style.overflow;
    const previousBodyOverscrollBehavior = document.body.style.overscrollBehavior;
    document.body.style.overflow = "hidden";
    document.body.style.overscrollBehavior = "contain";

    return () => {
      document.body.style.overflow = previousBodyOverflow;
      document.body.style.overscrollBehavior = previousBodyOverscrollBehavior;
    };
  }, [isModalOpen]);

  const [searchQuery, setSearchQuery] = useState("");
  const [searchInput, setSearchInput] = useState("");
  const [sortBy, setSortBy] = useState<"name" | "time" | "size" | "status" | "format" | "id" | "word_count" | "token">("time");
  const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");
  const [statusFilter, setStatusFilter] = useState<"All" | FileItem["status"]>("All");
  const [formatFilter, setFormatFilter] = useState("All");
  const [formatOptions, setFormatOptions] = useState<string[]>([]);
  // 多知识库:可读库列表、列表过滤库、上传目标库、Copilot 选用库集合
  const [readableKbs, setReadableKbs] = useState<KbInfo[]>([]);
  const [listKbFilter, setListKbFilter] = useState("");   // 筛选 token:"" =全部;kbId=单库;grp:xxx=某中心
  const [listKbIds, setListKbIds] = useState<string[]>([]); // 该 token 覆盖的库 id(选中心=其下全部库)
  const [uploadKbId, setUploadKbId] = useState("");        // 上传目标库
  const [copilotKbIds, setCopilotKbIds] = useState<Set<string>>(new Set()); // 已勾选的库;空集=本次不检索任何库
  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 params = new URLSearchParams({
        page: String(page),
        page_size: String(size),
        search,
        sort_by: sortBy,
        sort_order: sortOrder,
        status: statusFilter,
        format: formatFilter,
      });
      // token 非空=按其覆盖的库集合过滤(单库=1 个,中心=其下全部库)
      if (listKbFilter && listKbIds.length) params.set("kbIds", listKbIds.join(","));
      const res = await fetch(`${API_BASE}/files?${params.toString()}`, { credentials: "include" });
      if (!res.ok) {
        throw new Error(`服务返回 ${res.status}`);
      }
      const data = await res.json();
      setFiles(data.files || []);
      setTotalCount(data.total || 0);
      const responseFormats = data.filter_options?.formats;
      if (Array.isArray(responseFormats)) {
        setFormatOptions(responseFormats.filter((format): format is string => typeof format === "string" && format.length > 0));
      } else {
        const fallbackFormats = ((data.files || []) as FileItem[])
          .map((file) => file.format)
          .filter((format) => format.length > 0);
        setFormatOptions(Array.from(new Set<string>(fallbackFormats)).sort());
      }
    } catch (e) {
      console.error("Failed to fetch files", e);
      showToast(
        "无法加载文件列表,后端服务可能未启动或异常,请稍后重试。",
        "error"
      );
    } finally {
      if (isInitial) setIsInitialLoading(false);
    }
  };

  useEffect(() => {
    Promise.resolve().then(() => {
      void fetchFiles(currentPage, pageSize, searchQuery, true);
    });
  }, [currentPage, pageSize, searchQuery, sortBy, sortOrder, statusFilter, formatFilter, listKbFilter, listKbIds, refreshTrigger]);

  // 载入当前用户可读知识库;默认上传目标为基础库(base 排最前);Copilot 默认全选可读库
  useEffect(() => {
    listReadableKbs()
      .then((d) => {
        setReadableKbs(d.items);
        const base = d.items.find((k) => k.kbType === "base") || d.items[0];
        if (base) setUploadKbId((prev) => prev || base.id);
        setCopilotKbIds(new Set(d.items.map((k) => k.id))); // 默认全选
      })
      .catch(() => {});
  }, []);

  const filteredFiles = useMemo(() => {
    return [...uploadingFiles, ...files.filter(f => !uploadingFiles.some(u => u.name === f.name))];
  }, [files, uploadingFiles]);

  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" },
        credentials: "include",
        body: JSON.stringify({
          files: pendingFiles.map(q => ({ name: q.name })),
          kbId: uploadKbId || null,
        })
      });

      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 handleDownloadWikiZip = async () => {
    if (wikiLinks.length === 0 || isZipDownloading) return;
    setIsZipDownloading(true);
    try {
      // 后端 download_batch 以 WIKI_DIR 为根拼接路径,须先剥掉 ware/wiki/ 前缀(与 buildTree 一致),
      // 否则 join 出 .../ware/wiki/ware/wiki/... 找不到文件,导致 zip 为空。
      const paths = wikiLinks.map((l) => l.replace(/^ware\/wiki\//, ""));
      const res = await fetch(`${API_BASE}/wiki/download_batch`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ paths }),
      });
      if (!res.ok) {
        alert("打包下载失败");
        return;
      }
      const blob = await res.blob();
      const srcName = files.find(f => f.id === selectedFileId)?.name || "wiki";
      const zipName = `${srcName.replace(/\.[^.]+$/, "")}_wiki.zip`;
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = zipName;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    } catch {
      alert("打包下载失败");
    } finally {
      setIsZipDownloading(false);
    }
  };

  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 handleBatchEgress = async () => {
    const ids = Array.from(selectedIds);
    const toEgress = ids.filter(id => {
      const file = files.find(f => f.id === id);
      return file && file.status === "Indexed";
    });

    if (toEgress.length === 0) {
      alert("请先选择已索引的文件");
      return;
    }

    const skippedCount = ids.length - toEgress.length;
    const confirmMsg = skippedCount > 0
      ? `选中的项目中,有 ${skippedCount} 个文件不是“已索引”状态,无法摄出。\n确定摄出其余 ${toEgress.length} 个文件吗?`
      : `确定摄出选中的 ${toEgress.length} 个文件吗?`;
    if (!confirm(confirmMsg)) return;

    try {
      const res = await fetch(`${API_BASE}/wiki/batch_egress`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ids: toEgress }),
      });
      if (!res.ok) {
        const error = await res.json().catch(() => ({ detail: "批量摄出失败" }));
        alert(error.detail || "批量摄出失败");
        return;
      }
      setSelectedIds(new Set());
      await fetchFiles();
      if (selectedFileId && toEgress.includes(selectedFileId)) {
        setWikiContent("");
        setViewMode("wiki_tree");
      }
    } catch {
      alert("批量摄出请求发生错误");
      await fetchFiles();
    }
  };

  const handleBatchCancelIngest = async () => {
    const toCancel = Array.from(selectedIds).filter(id => {
      const file = files.find(f => f.id === id);
      return file && file.status === "Ingesting";
    });

    if (toCancel.length === 0) {
      alert("请先选择正在摄入的文件");
      return;
    }

    if (!confirm(`确定终止选中的 ${toCancel.length} 个摄入任务吗?终止后状态会回到“待处理”。`)) return;

    setFiles(prev => prev.map(f => toCancel.includes(f.id) ? { ...f, status: "Pending" } : f));
    try {
      const res = await fetch(`${API_BASE}/wiki/ingest/cancel`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ids: toCancel }),
      });
      if (!res.ok) {
        const error = await res.json().catch(() => ({ detail: "批量终止失败" }));
        alert(error.detail || "批量终止失败");
      }
      setSelectedIds(new Set());
      await fetchFiles();
    } catch {
      alert("批量终止请求发生错误");
      await fetchFiles();
    }
  };

  const fetchPreview = async (id: string) => {
    latestPreviewRequestIdRef.current = id;
    const targetFile = files.find(f => f.id === id);
    if (targetFile && canDirectIframePreview(targetFile.name)) {
      setPreviewStatus("ready");
      setPreviewContent("");
      setIsPreviewLoading(false);
      return;
    }

    setSpreadsheetSheets(null);
    setSpreadsheetTruncated(false);

    if (targetFile && needsSpreadsheetPreview(targetFile.name)) {
      setIsPreviewLoading(true);
      setPreviewStatus("loading");
      setPreviewContent("");
      try {
        const res = await fetch(`${API_BASE}/files/view/${encodeURIComponent(id)}`);
        if (latestPreviewRequestIdRef.current !== id) return;
        if (!res.ok) {
          setPreviewStatus("error");
          setPreviewContent("预览加载失败");
          return;
        }
        const contentLength = Number(res.headers.get("content-length") || 0);
        if (contentLength > SPREADSHEET_MAX_FILE_BYTES) {
          setPreviewStatus("error");
          setPreviewContent("文件过大,不支持在线预览,请下载查看完整内容。");
          return;
        }
        const buffer = await res.arrayBuffer();
        if (latestPreviewRequestIdRef.current !== id) return;
        const workbook = XLSX.read(buffer, { type: "array" });
        const { sheets, truncated } = workbookToSpreadsheetData(workbook);
        if (latestPreviewRequestIdRef.current !== id) return;
        setSpreadsheetSheets(sheets);
        setSpreadsheetTruncated(truncated);
        setPreviewStatus("ready");
      } catch (e) {
        console.error("Excel 预览解析失败", e);
        if (latestPreviewRequestIdRef.current !== id) return;
        setPreviewStatus("error");
        setPreviewContent("该文件解析失败,可能已加密或已损坏,请下载后用本地工具打开。");
      } finally {
        if (latestPreviewRequestIdRef.current === id) setIsPreviewLoading(false);
      }
      return;
    }

    setIsPreviewLoading(true);
    setPreviewStatus("loading");
    setPreviewContent("正在加载预览...");
    try {
      const res = await fetch(`${API_BASE}/files/view/${encodeURIComponent(id)}`);
      if (res.ok) {
        const contentType = res.headers.get("content-type") || "";
        if (contentType.includes("application/json")) {
          const data = await res.json();
          if (data.type === "text_preview") {
            setPreviewContent(data.content);
          } else {
            setPreviewContent(data.content || "无法解析文档内容");
          }
        } else {
          setPreviewContent("");
        }
        setPreviewStatus("ready");
      } else if (res.status === 202) {
        const data = await res.json().catch(() => null);
        setPreviewStatus("missing");
        setPreviewContent(data?.detail?.message || "预览 PDF 尚未生成,请稍后刷新或先发起摄入。");
      } else {
        setPreviewStatus("error");
        setPreviewContent("预览加载失败");
      }
    } catch {
      setPreviewStatus("error");
      setPreviewContent("预览请求发生错误");
    } finally {
      setIsPreviewLoading(false);
    }
  };

  const onSelectFile = async (id: string) => {
    setSelectedFileId(id);
    setPreviewStatus("idle");
    setPreviewContent("");
    setIsPreviewLoading(false);
    // 强制跳转到原始文档预览模式
    setViewMode("raw");
    setIsModalOpen(true);
    setWikiLinks([]);
    setSelectedWikiPath(null);
    const file = files.find(f => f.id === id);
    if (file?.status === "Indexed") {
      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);
  };

  /** 预览弹窗左侧文件树点选:拉取该 Wiki 文件正文。 */
  const handleSelectWikiFile = async (path: string) => {
    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 {
      setWikiContent("文件加载失败");
    }
  };

  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,
                    time: data.time ?? reasoning[existingIndex].time
                  };
                } else {
                  reasoning.push({
                    id: stepId,
                    type: data.type,
                    content: data.content,
                    name: data.name,
                    time: data.time
                  });
                }
                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("");

    setChatHistory(prev => [...prev, { role: "user", content: userMessage }]);
    setIsLoading(true);
    setIsChatOpen(true);

    const controller = new AbortController();
    setAbortController(controller);

    // 本轮实际生效的会话 id。首次提问时 currentSessionId 还是 null,
    // 会话由后端建好经响应头回传;收尾刷新要用这个值,读闭包里的 state 会漏掉首轮。
    let activeSessionId = currentSessionId;

    try {
      // 历史不再由前端传递:后端按 sessionId 从会话记忆中装配
      // (滚动摘要 + 未摘原文),前端只负责带上会话标识。
      const response = await fetch(`${API_BASE}/wiki/query`, {
        method: "POST",
        credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          query: userMessage,
          sessionId: currentSessionId,
          // 传当前勾选的库 id;空集([])=用户明确未选→后端本次不检索任何库(不回落全部)
          kbIds: copilotKbIds.size > 0 ? Array.from(copilotKbIds) : [],
        }),
        signal: controller.signal,
      });

      // 后端可能自动新建了会话(首次提问或原会话失效),据响应头同步
      const returnedSessionId = response.headers.get("X-Session-Id");
      if (returnedSessionId && returnedSessionId !== currentSessionId) {
        setCurrentSessionId(returnedSessionId);
        activeSessionId = returnedSessionId;
      }

      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);
              // 记忆子系统本次发生过异常:弹小提示,提醒用户通知管理员维护
              if (data.data?.memoryWarning) {
                showToast("记忆服务暂时异常,本次部分记忆功能未生效,请通知管理员维护", "warning");
              }
              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,
                    time: data.time ?? reasoning[existingIndex].time
                  };
                } else {
                  reasoning.push({
                    id: stepId,
                    type: data.type,
                    content: data.content,
                    name: data.name,
                    time: data.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 {
        const detail = e instanceof Error ? e.message : "未知错误";
        setChatHistory(prev => [...prev, { role: "ai", content: "咨询 AI 助手时发生错误,请稍后再试。" }]);
        showToast(`问答请求失败:${detail}`, "error");
      }
    } 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;
      });
      // 本轮问答收尾:刷新会话列表,让标题与「N 轮」计数保持最新。
      // 放在这里而非 effect 里观察 isLoading——刷新是「问答结束」这个事件的后续动作,
      // 用 effect 追 isLoading 会在任何令其变化的路径上误触发。
      if (activeSessionId && currentUser) refreshSessions();
    }
  };

  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 renderTokenTitle = (file: FileItem) => {
    if (file.status !== "Indexed" || !file.meta) return undefined;
    const llmTotal =
      typeof file.meta.total_tokens === "object" && file.meta.total_tokens !== null
        ? file.meta.total_tokens.total_tokens || 0
        : file.meta.total_tokens || 0;
    const input =
      file.meta.input_tokens ??
      (typeof file.meta.total_tokens === "object" && file.meta.total_tokens !== null ? file.meta.total_tokens.input_tokens : 0) ??
      0;
    const output =
      file.meta.output_tokens ??
      (typeof file.meta.total_tokens === "object" && file.meta.total_tokens !== null ? file.meta.total_tokens.output_tokens : 0) ??
      0;
    const vlm = file.meta.vlm_total_tokens ?? 0;
    const cached = file.meta.cached_input_tokens ?? 0;
    const overall = file.meta.overall_total_tokens ?? (llmTotal + vlm);
    const hitRate = input > 0 ? ((cached / input) * 100).toFixed(1) : "0.0";
    const mode = file.meta.ingest_mode ? `\n路线: ${file.meta.ingest_mode}` : "";
    return `总消耗: ${overall}(LLM ${llmTotal} = 输入 ${input} + 输出 ${output};VLM ${vlm})\n缓存命中: ${cached} (${hitRate}%)${mode}`;
  };

  const handleSort = (field: typeof sortBy, defaultOrder: "asc" | "desc") => {
    setCurrentPage(1);
    if (sortBy === field) {
      setSortOrder(sortOrder === "asc" ? "desc" : "asc");
    } else {
      setSortBy(field);
      setSortOrder(defaultOrder);
    }
  };

  const renderSortLabel = (label: string, field: typeof sortBy) => (
    <span className="inline-flex items-center gap-1 whitespace-nowrap">
      <span>{label}</span>
      <span className="inline-block w-3 text-center text-[11px] leading-none">
        {sortBy === field ? (sortOrder === "asc" ? "↑" : "↓") : ""}
      </span>
    </span>
  );

  return (
    <>
      <Toast toast={toast} onClose={() => setToast(null)} />

      {/* 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>

            <Perm code="wiki:file:upload">
              <button
                onClick={() => {
                  setUploadQueue([]);
                  // 上传目标默认跟随当前筛选(仅当筛选是单个库时);否则取基础库
                  const base = readableKbs.find((k) => k.kbType === "base");
                  const single = listKbIds.length === 1 ? listKbIds[0] : "";
                  setUploadKbId(single || base?.id || "");
                  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>
            </Perm>
          </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>

          {/* 知识库过滤:选某个库或某中心(=其下全部库)的文件(默认全部可读库) */}
          <KbTreePicker
            mode="single"
            kbs={readableKbs}
            value={listKbFilter}
            onChange={(token, kbIds) => { setListKbFilter(token); setListKbIds(kbIds); setCurrentPage(1); }}
            allowAll
            allLabel="全部知识库"
            allowGroupSelect
            showAccessBadge
            panelWidthClass="w-[26rem]"
          />

          {/* 状态 / 文件类型 筛选(从表头上移至此,与知识库选择同排) */}
          <select
            value={statusFilter}
            onChange={(e) => { setStatusFilter(e.target.value as typeof statusFilter); setCurrentPage(1); }}
            className="h-8 rounded-lg border border-slate-200 bg-white px-2 text-xs font-semibold text-slate-600 outline-none transition hover:border-slate-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20"
            title="按状态筛选"
          >
            <option value="All">全部状态</option>
            <option value="Indexed">已索引</option>
            <option value="Pending">待处理</option>
            <option value="Ingesting">摄入中</option>
            <option value="Uploading">上传中</option>
            <option value="Failed">失败</option>
          </select>
          <select
            value={formatFilter}
            onChange={(e) => { setFormatFilter(e.target.value); setCurrentPage(1); }}
            className="h-8 rounded-lg border border-slate-200 bg-white px-2 text-xs font-semibold text-slate-600 outline-none transition hover:border-slate-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20"
            title="按文件类型筛选"
          >
            <option value="All">全部类型</option>
            {formatOptions.map((format) => (
              <option key={format} value={format}>{format}</option>
            ))}
          </select>

          {selectedIds.size > 0 && (
            <div className="flex gap-2 animate-in fade-in slide-in-from-left-2 duration-200">
              <Perm code="wiki:file:batchIngest">
                <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>
              </Perm>
              <Perm code="wiki:file:batchEgress">
                <button
                  onClick={handleBatchEgress}
                  className="text-xs font-bold bg-amber-50 text-amber-600 px-4 py-2 rounded-lg flex items-center gap-2 hover:bg-amber-100 transition"
                >
                  <Eject className="w-3.5 h-3.5 rotate-180" /> 批量摄出
                </button>
              </Perm>
              <Perm code="wiki:file:batchStop">
                <button
                  onClick={handleBatchCancelIngest}
                  className="text-xs font-bold bg-rose-50 text-rose-600 px-4 py-2 rounded-lg flex items-center gap-2 hover:bg-rose-100 transition"
                >
                  <Square className="w-3.5 h-3.5 fill-current" /> 批量终止
                </button>
              </Perm>
              <Perm code="wiki:file:batchRemove">
              <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>
              </Perm>
            </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 table-fixed divide-y divide-slate-100">
              <thead className="sticky top-0 z-20 bg-slate-50/95 backdrop-blur">
                <tr>
                  <th scope="col" className="w-16 px-4 py-4 text-left text-xs font-bold text-slate-400 uppercase tracking-wider"></th>
                  <th
                    scope="col"
                    className="w-[26%] px-4 py-4 text-left text-xs font-bold text-slate-400 uppercase tracking-wider cursor-pointer whitespace-nowrap hover:text-blue-600 transition"
                    onClick={() => handleSort("name", "asc")}
                  >
                    {renderSortLabel("文件名", "name")}
                  </th>
                  <th
                    scope="col"
                    className="w-[104px] px-4 py-3 text-left text-xs font-bold text-slate-400 uppercase tracking-wider cursor-pointer whitespace-nowrap hover:text-blue-600 transition"
                    onClick={() => handleSort("status", "asc")}
                  >
                    {renderSortLabel("状态", "status")}
                  </th>
                  <th
                    scope="col"
                    className="w-[110px] px-4 py-3 text-left text-xs font-bold text-slate-400 uppercase tracking-wider cursor-pointer whitespace-nowrap hover:text-blue-600 transition"
                    onClick={() => handleSort("format", "asc")}
                  >
                    {renderSortLabel("文件类型", "format")}
                  </th>
                  <th
                    scope="col"
                    className="w-[92px] px-4 py-4 text-left text-xs font-bold text-slate-400 uppercase tracking-wider cursor-pointer whitespace-nowrap hover:text-blue-600 transition"
                    onClick={() => handleSort("size", "desc")}
                  >
                    {renderSortLabel("大小", "size")}
                  </th>
                  <th
                    scope="col"
                    className="w-[118px] px-4 py-4 text-left text-xs font-bold text-slate-400 uppercase tracking-wider cursor-pointer whitespace-nowrap hover:text-blue-600 transition"
                    onClick={() => handleSort("time", "desc")}
                  >
                    {renderSortLabel("上传时间", "time")}
                  </th>
                  <th
                    scope="col"
                    className="w-[96px] px-4 py-4 text-left text-xs font-bold text-slate-400 uppercase tracking-wider whitespace-nowrap"
                  >
                    上传用户
                  </th>
                  <th
                    scope="col"
                    className="w-[120px] px-4 py-4 text-left text-xs font-bold text-slate-400 uppercase tracking-wider whitespace-nowrap"
                  >
                    所属知识库
                  </th>
                  <th
                    scope="col"
                    className="w-[88px] px-4 py-4 text-left text-xs font-bold text-slate-400 uppercase tracking-wider cursor-pointer select-none whitespace-nowrap hover:text-slate-600"
                    onClick={() => handleSort("word_count", "desc")}
                  >
                    {renderSortLabel("字数", "word_count")}
                  </th>
                  <th
                    scope="col"
                    className="w-[124px] px-4 py-4 text-left text-xs font-bold text-slate-400 uppercase tracking-wider cursor-pointer select-none whitespace-nowrap hover:text-slate-600"
                    onClick={() => handleSort("token", "desc")}
                  >
                    {renderSortLabel("Token 消耗", "token")}
                  </th>
                  <th scope="col" className="w-[104px] px-4 py-4 text-left text-xs font-bold text-slate-400 uppercase tracking-wider whitespace-nowrap">处理时长</th>
                  <th scope="col" className="w-[92px] px-4 py-4 text-right text-xs font-bold text-slate-400 uppercase tracking-wider whitespace-nowrap">操作</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-4 py-4"><div className="w-5 h-5 bg-slate-100 rounded" /></td>
                      <td className="px-4 py-4"><div className="h-4 bg-slate-100 rounded w-3/4" /></td>
                      <td className="px-4 py-4"><div className="h-4 bg-slate-50 rounded w-16" /></td>
                      <td className="px-4 py-4"><div className="h-4 bg-slate-50 rounded w-14" /></td>
                      <td className="px-4 py-4"><div className="h-4 bg-slate-50 rounded w-12" /></td>
                      <td className="px-4 py-4"><div className="h-4 bg-slate-50 rounded w-24" /></td>
                      <td className="px-4 py-4"><div className="h-4 bg-slate-50 rounded w-16" /></td>
                      <td className="px-4 py-4"><div className="h-4 bg-slate-50 rounded w-20" /></td>
                      <td className="px-4 py-4"><div className="h-4 bg-slate-50 rounded w-16" /></td>
                      <td className="px-4 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"
                      )}
                      // eslint-disable-next-line react-hooks/refs -- ref access happens after the row click starts preview loading.
                      onClick={() => onSelectFile(file.id)}
                    >
                      <td className="px-4 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-4 py-4 whitespace-nowrap">
                        <div className="flex min-w-0 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="min-w-0 flex-1 truncate text-sm font-semibold text-slate-700" title={file.name}>
                            {file.name}
                          </span>
                        </div>
                      </td>
                      <td className="px-4 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-4 py-4 whitespace-nowrap">
                        <span className="inline-flex items-center rounded-md bg-slate-50 px-2 py-1 text-xs font-bold text-slate-600 border border-slate-100">
                          {file.format}
                        </span>
                      </td>
                      <td className="px-4 py-4 whitespace-nowrap text-xs text-slate-500 font-medium">
                        {file.size}
                      </td>
                      <td className="px-4 py-4 whitespace-nowrap text-xs text-slate-500 font-medium">
                        {file.time}
                      </td>
                      <td className="px-4 py-4 whitespace-nowrap text-xs text-slate-500 font-medium">
                        {file.uploaded_by_name || "—"}
                      </td>
                      <td className="px-4 py-4 text-xs text-slate-500 font-medium truncate" title={file.kb_name || ""}>
                        {file.kb_name || "—"}
                      </td>
                      <td className="px-4 py-4 whitespace-nowrap text-xs text-slate-500 font-medium">
                        {file.word_count ? file.word_count.toLocaleString() : "--"}
                      </td>
                      <td className="px-4 py-4 whitespace-nowrap">
                        <span className="text-xs font-bold text-slate-700" title={renderTokenTitle(file)}>
                          {file.status === "Indexed" && file.meta
                            ? renderTokenCount(file.meta.overall_total_tokens ?? file.meta.total_tokens)
                            : "--"}
                        </span>
                      </td>
                      <td className="px-4 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-4 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('-') && (
                            <>
                              <Perm code="wiki:file:ingest">
                                <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>
                              </Perm>
                              <Perm code="wiki:file:remove">
                                <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>
                              </Perm>
                            </>
                          )}
                          {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" && (
                            <Perm code="wiki:file:egress">
                              <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>
                            </Perm>
                          )}
                          {!file.id.startsWith('-') && (
                            <Perm code="wiki:file:download">
                              <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>
                            </Perm>
                          )}
                        </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(与「系统管理」分页风格统一;保留 pr-24 定位,避免遮挡右下角「咨询 Wiki AI」按钮) */}
        <div className="mt-6 flex shrink-0 items-center justify-end pb-6 pr-24">
          <div className="flex flex-wrap items-center gap-3 text-sm text-slate-500">
            <span className="whitespace-nowrap">
              共 <span className="font-semibold text-slate-700">{totalCount}</span> 个文件
            </span>
            <select
              value={pageSize}
              onChange={(e) => {
                const size = Number(e.target.value);
                setPageSize(size);
                setCurrentPage(1);
              }}
              className="rounded-lg border border-slate-200 bg-white px-3 py-1 text-sm text-slate-700 outline-none transition focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20"
            >
              {PAGE_SIZE_OPTIONS.map(size => (
                <option key={size} value={size}>{size} 条/页</option>
              ))}
            </select>
            <div className="flex items-center gap-1">
              <button
                onClick={() => setCurrentPage(1)}
                disabled={currentPage === 1}
                title="第一页"
                className="rounded-lg p-1.5 text-slate-500 transition hover:bg-blue-50 disabled:cursor-not-allowed disabled:opacity-30"
              >
                <ChevronsLeft className="w-4 h-4" />
              </button>
              <button
                onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                disabled={currentPage === 1}
                title="上一页"
                className="rounded-lg p-1.5 text-slate-500 transition hover:bg-blue-50 disabled:cursor-not-allowed disabled:opacity-30"
              >
                <ChevronLeft className="w-4 h-4" />
              </button>

              {getPaginationRange(currentPage, Math.max(1, Math.ceil(totalCount / pageSize))).map((page, idx) => (
                page === "ellipsis" ? (
                  <span key={`ellipsis-${idx}`} className="px-1 text-slate-300 select-none">…</span>
                ) : (
                  <button
                    key={page}
                    onClick={() => setCurrentPage(page)}
                    className={cn(
                      "min-w-[2rem] rounded-lg px-2 py-1 text-sm font-medium transition",
                      page === currentPage
                        ? "bg-blue-600 text-white shadow-sm shadow-blue-500/25"
                        : "text-slate-600 hover:bg-blue-50"
                    )}
                  >
                    {page}
                  </button>
                )
              ))}

              <button
                onClick={() => setCurrentPage(p => (p * pageSize >= totalCount ? p : p + 1))}
                disabled={currentPage * pageSize >= totalCount}
                title="下一页"
                className="rounded-lg p-1.5 text-slate-500 transition hover:bg-blue-50 disabled:cursor-not-allowed disabled:opacity-30"
              >
                <ChevronRight className="w-4 h-4" />
              </button>
              <button
                onClick={() => setCurrentPage(Math.max(1, Math.ceil(totalCount / pageSize)))}
                disabled={currentPage * pageSize >= totalCount}
                title="最后一页"
                className="rounded-lg p-1.5 text-slate-500 transition hover:bg-blue-50 disabled:cursor-not-allowed disabled:opacity-30"
              >
                <ChevronsRight className="w-4 h-4" />
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* 3. Preview Modal */}
      <PreviewModal
        open={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        apiBase={API_BASE}
        file={selectedFileObj}
        fileId={selectedFileId}
        viewMode={viewMode}
        onViewModeChange={setViewMode}
        previewStatus={previewStatus}
        previewContent={previewContent}
        isPreviewLoading={isPreviewLoading}
        spreadsheetSheets={spreadsheetSheets}
        spreadsheetTruncated={spreadsheetTruncated}
        onRefreshPreview={fetchPreview}
        wikiLinks={wikiLinks}
        isZipDownloading={isZipDownloading}
        onDownloadWikiZip={handleDownloadWikiZip}
        selectedWikiPath={selectedWikiPath}
        wikiContent={wikiContent}
        onSelectWikiFile={handleSelectWikiFile}
      />

      {/* 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={cn(
            // 侧栏展开时面板整体变宽,而不是压缩消息区——浮层本就窄,
            // 挤压聊天区会明显劣化阅读体验。
            "fixed bottom-28 right-8 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 transition-[width] duration-200",
            showSessionList ? "w-[1020px]" : "w-[800px]"
          )}
        >
          <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 min-w-0">
              <button
                onClick={() => setShowSessionList((v) => !v)}
                className="p-2 hover:bg-white/10 rounded-lg transition-colors text-blue-100 hover:text-white shrink-0"
                title={showSessionList ? "收起会话列表" : "展开会话列表"}
              >
                <PanelLeft className="w-4 h-4" />
              </button>
              <div className="w-10 h-10 bg-white/20 rounded-xl flex items-center justify-center backdrop-blur-md shrink-0">
                <MessageSquare className="w-5 h-5" />
              </div>
              <div className="min-w-0">
                <h3 className="font-bold text-sm truncate">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 truncate max-w-[280px]">
                    {currentSessionTitle}
                  </span>
                </div>
              </div>
            </div>
            {/* 关闭按钮:新建会话在左侧列表顶部,用户信息在全局右上角,此处不再重复 */}
            <button
              onClick={() => setIsChatOpen(false)}
              className="p-2 hover:bg-white/10 rounded-lg transition-colors text-blue-100 hover:text-white shrink-0"
              title="收起"
            >
              <X className="w-4 h-4" />
            </button>
          </div>

          <div className="flex-1 flex min-h-0">
            {showSessionList && (
              <SessionSidebar
                sessions={sessions}
                currentId={currentSessionId}
                loading={listLoading}
                creating={creatingSession}
                onSelect={openSession}
                onCreate={handleNewSession}
                onDelete={setPendingDeleteSession}
              />
            )}
            <div className="flex-1 flex flex-col min-w-0">

          <div className="flex-1 overflow-y-auto p-6 scrollbar-thin bg-slate-50/50 flex flex-col">
            {sessionsLoading && (
              <div className="flex-1 flex items-center justify-center text-slate-400 text-xs gap-2">
                <Loader2 className="w-4 h-4 animate-spin text-blue-600" />
                加载会话…
              </div>
            )}
            {!sessionsLoading && 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="mb-2">
              <KbTreePicker
                mode="multi"
                kbs={readableKbs}
                selected={copilotKbIds}
                onChangeMulti={setCopilotKbIds}
                labelPrefix="知识库:"
                openUp
                buttonClassName="flex items-center gap-1.5 rounded-lg border border-slate-200 bg-slate-50 px-3 py-1.5 text-xs font-medium text-slate-600 transition hover:border-blue-300 hover:text-blue-600"
              />
            </div>
            <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>
          </div>
        </div>
      )}

      {/* 删除会话的二次确认。删除立即生效,学到的内容由后台异步并入长期记忆。 */}
      <ConfirmDialog
        open={!!pendingDeleteSession}
        title="删除该会话?"
        description={`「${pendingDeleteSession?.title || ""}」将从列表中移除。系统会在后台把本次对话学到的内容更新进长期记忆。`}
        confirmText="删除"
        loading={deletingSession}
        onConfirm={handleDeleteSession}
        onCancel={() => setPendingDeleteSession(null)}
      />

      {/* 5. Lint Modal */}
      <LintModal
        open={isLintModalOpen}
        onClose={() => setIsLintModalOpen(false)}
        isLinting={isLinting}
        lintHistory={lintHistory}
        lintEndRef={lintEndRef}
      />

      <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>

      <UploadModal
        open={isUploadModalOpen}
        onClose={() => setIsUploadModalOpen(false)}
        readableKbs={readableKbs}
        uploadKbId={uploadKbId}
        onUploadKbChange={setUploadKbId}
        uploadQueue={uploadQueue}
        onQueueChange={setUploadQueue}
        onSelectFiles={handleUploadSelect}
        onConfirm={handleUploadConfirm}
        onFinish={() => {
          setUploadQueue([]);
          setIsUploadModalOpen(false);
          fetchFiles(1, pageSize, searchQuery, false);
        }}
      />
    </>
  );
}