page.tsx 66.6 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
"use client";

import type React from "react";
import { useEffect, useRef, useState, useMemo } from "react";
import {
  Activity, Bot, Database, Eye, FileText, Layers3, Loader2,
  RefreshCw, RotateCcw, Search,
  Trash2, Upload, MessageSquare, MoreVertical, X, Filter, Folder, Eraser,
  CheckSquare, Square, ChevronDown, ChevronRight, Wrench, CheckCircle2, BookOpen,
  FileImage, FileSpreadsheet, FileArchive, FileCode, AlertCircle, Download, Maximize2
} from "lucide-react";
import { cn } from "@/lib/utils";
import { MessageBubble, type ReasoningStep } from "@/components/MessageBubble";
import type { RagChunk, RagFile, RagMessage, RagReasoningStep } from "@/lib/rag-types";
import { clearRagHistory, deleteRagAction, fetchRagChunk, fetchRagChunks, fetchRagFiles, fetchRagStats, postRagAction, streamRagQuery } from "@/lib/rag-api";

const statusColor: Record<string, string> = {
  Pending: "bg-amber-50 text-amber-700 border-amber-200",
  Uploading: "bg-blue-50 text-blue-700 border-blue-200",
  Indexing: "bg-indigo-50 text-indigo-700 border-indigo-200",
  Indexed: "bg-emerald-50 text-emerald-700 border-emerald-200",
  Disabled: "bg-slate-100 text-slate-600 border-slate-200",
  Failed: "bg-red-50 text-red-700 border-red-200",
};

const getFileIcon = (format: string) => {
  const f = format.toLowerCase();
  if (f === "pdf") return <FileImage className="w-4 h-4 text-rose-500" />;
  if (f === "xlsx" || f === "xls" || f === "csv") return <FileSpreadsheet className="w-4 h-4 text-emerald-500" />;
  if (f === "docx" || f === "doc") return <FileText className="w-4 h-4 text-blue-500" />;
  if (f === "pptx" || f === "ppt") return <FileArchive className="w-4 h-4 text-orange-500" />;
  if (f === "json" || f === "ts" || f === "tsx" || f === "js" || f === "py") return <FileCode className="w-4 h-4 text-slate-500" />;
  return <FileText className="w-4 h-4 text-slate-500" />;
};

const metadataLabels: Record<string, string> = {
  chunk_id: "切片ID",
  file_id: "文件ID",
  parent_chunk_id: "父切片ID",
  chunk_level: "层级",
  chunk_index: "序号",
  source_index: "引用序号",
  source_name: "来源",
  title_path: "标题",
  page_start: "起始页",
  page_end: "结束页",
  slide_number: "幻灯片",
  sheet_name: "工作表",
  row_start: "起始行",
  row_end: "结束行",
  status: "状态",
  page_type: "页面类型",
  brand: "品牌",
  brand_series: "品牌体系",
  business_category: "业务分类",
  sub_business: "子业务",
  content_kind: "内容类型",
  section_title: "章节",
  parse_method: "解析方式",
  parse_methods: "解析方式列表",
};

interface UploadQueueItem {
  file: File;
  name: string;
  status: 'pending' | 'uploading' | 'success' | 'error';
  errorMsg?: string;
}

export default function RagWorkspace() {
  const [files, setFiles] = useState<RagFile[]>([]);
  const [chunks, setChunks] = useState<RagChunk[]>([]);
  const [selected, setSelected] = useState<RagFile | null>(null);
  const [selectedChunk, setSelectedChunk] = useState<RagChunk | null>(null);
  
  // Filtering & Selection
  const [searchQuery, setSearchQuery] = useState("");
  const [statusFilter, setStatusFilter] = useState<string>("All");
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());

  // Chunk Hierarchy
  const [expandedParents, setExpandedParents] = useState<Set<string>>(new Set());

  const toggleParent = (parentId: string, e: React.MouseEvent) => {
    e.stopPropagation();
    const next = new Set(expandedParents);
    if (next.has(parentId)) next.delete(parentId);
    else next.add(parentId);
    setExpandedParents(next);
  };

  const groupedChunks = useMemo(() => {
    const parentMap = new Map<string, { parent: RagChunk, children: RagChunk[] }>();
    const rootItems: { type: 'group', parent: RagChunk, children: RagChunk[] }[] = [];
    const orphanItems: { type: 'chunk', chunk: RagChunk }[] = [];

    chunks.forEach(chunk => {
      if (chunk.chunk_level === "parent" || !chunk.parent_chunk_id) {
        const group = { type: 'group' as const, parent: chunk, children: [] };
        parentMap.set(chunk.chunk_id, group);
        rootItems.push(group);
      }
    });

    chunks.forEach(chunk => {
      if (chunk.chunk_level === "child" && chunk.parent_chunk_id) {
        if (parentMap.has(chunk.parent_chunk_id)) {
          parentMap.get(chunk.parent_chunk_id)!.children.push(chunk);
        } else {
          orphanItems.push({ type: 'chunk', chunk });
        }
      }
    });

    return [...rootItems, ...orphanItems];
  }, [chunks]);

  // QA Drawer
  const [isChatOpen, setIsChatOpen] = useState(false);
  const [query, setQuery] = useState("");
  const [messages, setMessages] = useState<RagMessage[]>([]);
  const [previewChunk, setPreviewChunk] = useState<RagChunk | null>(null);
  const [previewLoading, setPreviewLoading] = useState(false);
  const [metadataZoom, setMetadataZoom] = useState(false);
  
  const [loading, setLoading] = useState(false);
  const [isOffline, setIsOffline] = useState(false);
  const [isUploadModalOpen, setIsUploadModalOpen] = useState(false);
  const [uploadQueue, setUploadQueue] = useState<UploadQueueItem[]>([]);
  const [stats, setStats] = useState<Record<string, number | boolean | string>>({});
  const [sessionId, setSessionId] = useState(() => `rag-${Date.now()}-${Math.random().toString(36).slice(2)}`);
  const inputRef = useRef<HTMLInputElement>(null);
  const chatEndRef = useRef<HTMLDivElement>(null);
  const chatAbortRef = useRef<AbortController | null>(null);
  const actionRunning = useRef(false);
  const selectedMetadataEntries = useMemo(
    () => selectedChunk ? buildChunkMetadataEntries(selectedChunk) : [],
    [selectedChunk]
  );

  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;

    setUploadQueue(prev => prev.map(q => q.status === 'pending' ? { ...q, status: 'uploading' } : q));

    try {
      const API_BASE = process.env.NEXT_PUBLIC_API_URL || "/api";
      const initRes = await fetch(`${API_BASE}/rag/upload/init`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          files: pendingFiles.map(q => ({ name: q.name }))
        })
      });

      if (!initRes.ok) {
        const errorData = await initRes.json().catch(() => ({ detail: "初始化上传失败" }));
        const errorMsg = errorData.detail || "初始化上传失败";
        setUploadQueue(prev => prev.map(q => pendingFiles.some(pf => pf.name === q.name) ? { ...q, status: 'error', errorMsg } : q));
        return;
      }

      const initData = await initRes.json();
      const mapping = initData.mapping || {};

      for (const q of pendingFiles) {
        const fileId = mapping[q.name];
        if (!fileId) {
          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}/rag/upload/${encodeURIComponent(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 {
      refresh();
    }
  };

  const refresh = async () => {
    try {
      const [fileData, statData] = await Promise.all([fetchRagFiles(), fetchRagStats()]);
      setFiles(fileData.files);
      setStats(statData);
      setIsOffline(false);
    } catch (error) {
      console.error(error);
      setIsOffline(true);
    }
  };

  useEffect(() => {
    Promise.resolve().then(() => {
      void refresh();
    });
    // const interval = setInterval(() => {
    //   void refresh();
    // }, 5000);
    // return () => clearInterval(interval);
  }, []);

  useEffect(() => {
    chatEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages]);

  const selectFile = async (file: RagFile) => {
    setSelected(file);
    setSelectedChunk(null);
    setExpandedParents(new Set());
    setChunks(await fetchRagChunks(file.id));
  };

  const runAction = async (action: () => Promise<unknown>, successMsg?: string) => {
    if (actionRunning.current) return;
    actionRunning.current = true;
    setLoading(true);
    try {
      await action();
      if (successMsg) alert(successMsg);
      await refresh();
      if (selected) setChunks(await fetchRagChunks(selected.id));
    } catch (error) {
      alert(error instanceof Error ? error.message : "操作失败");
    } finally {
      actionRunning.current = false;
      setLoading(false);
    }
  };

  const askV2 = () => {
    if (!query.trim() || loading) return;
    const userText = query.trim();
    const history = messages
      .filter((m) => m.content.trim())
      .map((m) => ({ role: m.role, content: m.content }));
    setQuery("");
    setMessages((prev) => [
      ...prev,
      { role: "user", content: userText },
      { role: "assistant", content: "", reasoning: [], startTime: Date.now() },
    ]);
    setLoading(true);
    chatAbortRef.current = streamRagQuery({ query: userText, sessionId, history }, (event) => {
      if (event.type === "answer_delta") {
        setMessages((prev) => updateLastMessage(prev, { contentAppend: event.content || "" }));
      }
      if (event.type === "thinking_delta") {
        setMessages((prev) => updateLastMessage(prev, { thinkingAppend: event.content || "" }));
      }
      if (event.type === "reasoning_step") {
        setMessages((prev) => updateLastMessage(prev, { reasoningStep: event.data as RagReasoningStep }));
      }
      if (event.type === "intent" || event.type === "retrieval_done") {
        setMessages((prev) => updateLastMessage(prev, { meta: { [event.type]: event.data } }));
      }
      // Sources are intentionally ignored here. The backend includes them in
      // the done payload after answer streaming is complete.
      if (event.type === "done") {
        const doneData = event.data as { sources?: RagChunk[]; duration_ms?: number; tokens?: number };
        setMessages((prev) => updateLastMessage(prev, { sources: doneData.sources, meta: { done: doneData }, endTime: Date.now() }));
        setLoading(false);
        chatAbortRef.current = null;
      }
      if (event.type === "error") {
        setMessages((prev) => updateLastMessage(prev, { contentAppend: `\n\n请求发生错误: ${event.content || "未知错误"}`, endTime: Date.now() }));
        setLoading(false);
        chatAbortRef.current = null;
      }
    });
  };

  const clearHistoryV2 = async () => {
    const sessionToClear = sessionId;
    chatAbortRef.current?.abort();
    chatAbortRef.current = null;
    setLoading(false);
    setMessages([]);
    setPreviewChunk(null);
    setSessionId(`rag-${Date.now()}-${Math.random().toString(36).slice(2)}`);
    try {
      await clearRagHistory(sessionToClear);
    } catch (error) {
      alert(error instanceof Error ? error.message : "清空对话失败");
    }
  };

  const openSourcePreview = async (source: RagChunk) => {
    setPreviewLoading(true);
    try {
      setPreviewChunk(await fetchRagChunk(source.chunk_id));
    } catch {
      setPreviewChunk(source);
    } finally {
      setPreviewLoading(false);
    }
  };

  const filteredFiles = useMemo(() => {
    return files.filter(f => {
      if (statusFilter !== "All" && f.status !== statusFilter) return false;
      if (searchQuery && !f.name.toLowerCase().includes(searchQuery.toLowerCase())) return false;
      return true;
    });
  }, [files, searchQuery, statusFilter]);

  const toggleSelect = (id: string, e: React.MouseEvent) => {
    e.stopPropagation();
    const next = new Set(selectedIds);
    if (next.has(id)) next.delete(id);
    else next.add(id);
    setSelectedIds(next);
  };

  const handleBatchIndex = async () => {
    const ids = Array.from(selectedIds);
    if (!ids.length) return alert("请先勾选文件");
    await runAction(() => postRagAction("/rag/batch_index", { ids }), "批量索引任务已提交");
    setSelectedIds(new Set());
  };

  const handleBatchErase = async () => {
    const ids = Array.from(selectedIds);
    if (!ids.length) return alert("请先勾选文件");
    if (!confirm(`确认批量擦除 ${ids.length} 个文件的索引吗?`)) return;
    await runAction(() => postRagAction("/rag/batch_delete_index", { ids }), "批量擦除任务已完成");
    setSelectedIds(new Set());
  };

  const handleBatchDelete = async () => {
    const ids = Array.from(selectedIds);
    if (!ids.length) return alert("请先勾选文件");
    if (!confirm(`确认批量删除 ${ids.length} 个文件吗?`)) return;
    await runAction(() => postRagAction("/rag/files/batch_delete", { ids }), "批量删除成功");
    setSelectedIds(new Set());
  };

  const handleBatchDownload = async () => {
    const ids = Array.from(selectedIds);
    if (!ids.length) return alert("请先勾选文件");

    setLoading(true);
    try {
      const API_BASE = process.env.NEXT_PUBLIC_API_URL || "/api";
      const res = await fetch(`${API_BASE}/rag/files/batch_download`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ids })
      });
      
      if (!res.ok) {
        const errorData = await res.json().catch(() => ({ detail: "下载失败" }));
        throw new Error(errorData.detail || "下载失败");
      }
      
      const blob = await res.blob();
      
      let filename = ids.length === 1 ? "download" : "batch_download.zip";
      const disposition = res.headers.get('Content-Disposition');
      if (disposition && disposition.includes("filename*=utf-8''")) {
        filename = decodeURIComponent(disposition.split("filename*=utf-8''")[1]);
      } else if (disposition && disposition.includes('filename=')) {
        filename = disposition.split('filename=')[1].replace(/"/g, '');
      } else if (ids.length === 1) {
        const selectedFile = files.find(f => f.id === ids[0]);
        if (selectedFile) filename = selectedFile.name;
      }
      
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = filename;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
      
      setSelectedIds(new Set());
    } catch (error) {
      alert(error instanceof Error ? error.message : "下载失败");
    } finally {
      setLoading(false);
    }
  };



  return (
    <main className="min-h-screen bg-[#f6f8fb] text-slate-900 relative">
      <header className="border-b border-slate-200 bg-white/90 px-6 py-4">
        <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
          <div>
            <div className="flex items-center gap-2 text-sm font-semibold text-blue-700">
              <Database className="h-4 w-4" />
              RAG 工作台
              {isOffline ? (
                <span className="ml-2 flex items-center gap-1.5 rounded-full bg-red-50 px-2 py-0.5 text-xs text-red-600 border border-red-200">
                  <span className="h-1.5 w-1.5 rounded-full bg-red-500 animate-pulse"></span>
                  服务离线
                </span>
              ) : (
                <span className="ml-2 flex items-center gap-1.5 rounded-full bg-emerald-50 px-2 py-0.5 text-xs text-emerald-600 border border-emerald-200">
                  <span className="h-1.5 w-1.5 rounded-full bg-emerald-500"></span>
                  服务在线
                </span>
              )}
            </div>
            <h1 className="mt-1 text-2xl font-semibold tracking-tight">知识库索引与检索增强</h1>
          </div>
          <div className="grid grid-cols-3 gap-2 text-xs text-slate-500">
            {[
              ["文件", stats.files ?? 0],
              ["已索引", stats.indexed ?? 0],
              ["切片", stats.chunks ?? 0],
            ].map(([label, value]) => (
              <div key={String(label)} className="rounded-lg border border-slate-200 bg-white px-3 py-2 text-center">
                <div className="text-lg font-semibold text-slate-900">{String(value)}</div>
                <div>{String(label)}</div>
              </div>
            ))}
          </div>
        </div>
      </header>

      {/* 两栏布局 */}
      <div className="grid min-h-[calc(100vh-92px)] grid-cols-1 gap-4 p-4 xl:grid-cols-[400px_minmax(0,1fr)]">
        
        {/* 左侧栏:文件列表 */}
        <section className="flex flex-col rounded-lg border border-slate-200 bg-white h-[calc(100vh-124px)]">
          <div className="flex items-center justify-between border-b border-slate-100 p-3">
            <div className="flex items-center gap-2 font-semibold">
              <FileText className="h-4 w-4" />
              文件库
            </div>
            <div className="flex gap-1">
              <button title="批量索引" onClick={handleBatchIndex} className="rounded-md p-1.5 hover:bg-slate-100 text-slate-600">
                <Activity className="h-4 w-4" />
              </button>
              <button title="批量擦除" onClick={handleBatchErase} className="rounded-md p-1.5 hover:bg-slate-100 text-slate-600">
                <Eraser className="h-4 w-4" />
              </button>
              <button title="批量删除" onClick={handleBatchDelete} className="rounded-md p-1.5 hover:bg-slate-100 text-slate-600">
                <Trash2 className="h-4 w-4" />
              </button>
              <button title="批量下载" onClick={handleBatchDownload} className="rounded-md p-1.5 hover:bg-slate-100 text-slate-600">
                <Download className="h-4 w-4" />
              </button>

              <button title="刷新" onClick={() => refresh()} className="rounded-md p-1.5 hover:bg-slate-100 text-slate-600">
                <RefreshCw className="h-4 w-4" />
              </button>
              <button title="上传" onClick={() => setIsUploadModalOpen(true)} className="rounded-md p-1.5 hover:bg-slate-100 text-slate-600">
                <Upload className="h-4 w-4" />
              </button>
            </div>
          </div>
          
          <div className="p-3 border-b border-slate-100 bg-slate-50 flex flex-col gap-2">
            <div className="flex items-center gap-2 rounded-md border border-slate-200 bg-white px-3 py-1.5 focus-within:border-blue-400 focus-within:ring-1 focus-within:ring-blue-400">
              <Search className="h-4 w-4 text-slate-400" />
              <input 
                value={searchQuery} 
                onChange={(e) => setSearchQuery(e.target.value)} 
                className="min-w-0 flex-1 outline-none text-sm" 
                placeholder="搜索文件名..." 
              />
            </div>
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <input 
                  type="checkbox" 
                  className="cursor-pointer rounded border-slate-300 text-blue-600 focus:ring-blue-500"
                  checked={filteredFiles.length > 0 && selectedIds.size === filteredFiles.length}
                  onChange={(e) => {
                    if (e.target.checked) {
                      setSelectedIds(new Set(filteredFiles.map(f => f.id)));
                    } else {
                      setSelectedIds(new Set());
                    }
                  }}
                  title="全选/取消全选"
                />
                <Filter className="h-3.5 w-3.5 text-slate-400" />
                <select 
                  className="text-xs bg-transparent outline-none text-slate-600 cursor-pointer"
                  value={statusFilter}
                  onChange={(e) => setStatusFilter(e.target.value)}
                >
                  <option value="All">全部状态</option>
                  <option value="Indexed">已索引 (Indexed)</option>
                  <option value="Indexing">索引中 (Indexing)</option>
                  <option value="Pending">待处理 (Pending)</option>
                  <option value="Failed">失败 (Failed)</option>
                </select>
              </div>
              {selectedIds.size > 0 && <span className="text-xs text-blue-600 font-medium">已选 {selectedIds.size} 项</span>}
            </div>
          </div>

          <div className="flex-1 overflow-y-auto p-2">
            {filteredFiles.map((file) => (
              <div
                key={file.id}
                onClick={() => selectFile(file)}
                className={cn(
                  "group mb-2 w-full rounded-lg border p-3 text-left transition cursor-pointer hover:border-blue-200 hover:bg-blue-50/40 relative", 
                  selected?.id === file.id ? "border-blue-300 bg-blue-50" : "border-slate-200 bg-white"
                )}
              >
                <div className="flex items-start gap-3">
                  <div className="pt-0.5" onClick={(e) => toggleSelect(file.id, e)}>
                    {selectedIds.has(file.id) ? (
                      <CheckSquare className="h-4 w-4 text-blue-600" />
                    ) : (
                      <Square className="h-4 w-4 text-slate-300 group-hover:text-slate-400" />
                    )}
                  </div>
                  <div className="min-w-0 flex-1">
                    <div className="truncate text-sm font-semibold">{file.name}</div>
                    <div className="mt-1 flex items-center gap-2 text-xs text-slate-500">
                      <span className={cn("shrink-0 rounded px-1.5 py-0.5 text-[10px]", statusColor[file.status] || statusColor.Pending)}>
                        {file.status}
                      </span>
                      <span>{file.parent_chunk_count} 父 / {file.child_chunk_count} 子切片</span>
                    </div>
                  </div>
                  {/* Inline File Actions (Hover to show) */}
                  <div className="opacity-0 group-hover:opacity-100 transition-opacity absolute right-2 top-2 flex items-center gap-1 bg-white/90 backdrop-blur-sm p-1 rounded-md shadow-sm border border-slate-100">
                    {file.status === "Indexing" && (
                      <span className="flex items-center gap-1.5 px-2 py-1.5 text-xs text-blue-500 font-medium">
                        <Loader2 className="h-3.5 w-3.5 animate-spin" />
                        正在索引...
                      </span>
                    )}
                    {file.status === "Indexed" && (
                      <button 
                        title="删除索引" 
                        onClick={(e) => { e.stopPropagation(); if(confirm(`确认删除 ${file.name} 的索引吗?`)) runAction(() => deleteRagAction(`/rag/index/${file.id}`)); }} 
                        className="flex items-center justify-center p-1.5 rounded text-amber-600 hover:bg-amber-50 hover:text-amber-700 transition"
                      >
                        <Eraser className="h-4 w-4" />
                      </button>
                    )}
                    {file.status !== "Indexed" && file.status !== "Indexing" && (
                      <>
                        <button 
                          title="生成索引" 
                          onClick={(e) => { e.stopPropagation(); runAction(() => postRagAction(`/rag/index/${file.id}`)); }} 
                          className="flex items-center justify-center p-1.5 rounded text-blue-600 hover:bg-blue-50 hover:text-blue-700 transition"
                        >
                          <Activity className="h-4 w-4" />
                        </button>
                        <button 
                          title="删除文件" 
                          onClick={(e) => { e.stopPropagation(); if(confirm(`确认删除 ${file.name} 及其索引吗?`)) runAction(() => deleteRagAction(`/rag/files/${file.id}`)); }} 
                          className="flex items-center justify-center p-1.5 rounded text-red-600 hover:bg-red-50 hover:text-red-700 transition"
                        >
                          <X className="h-4 w-4" />
                        </button>
                      </>
                    )}
                  </div>
                </div>
                {file.status !== "Indexing" && file.error_message && <div className="mt-2 line-clamp-2 text-xs text-red-600 ml-7">{file.error_message}</div>}
              </div>
            ))}
            {filteredFiles.length === 0 && <div className="text-center text-sm text-slate-400 py-10">暂无匹配文件</div>}
          </div>
        </section>

        {/* 右侧栏:切片详情 */}
        <section className="rounded-lg border border-slate-200 bg-white h-[calc(100vh-124px)] flex flex-col">
          <div className="flex flex-wrap items-center justify-between gap-2 border-b border-slate-100 p-3 shrink-0">
            <div className="flex items-center gap-2 font-semibold">
              <Layers3 className="h-4 w-4" />
              {selected ? `文件切片:${selected.name}` : "切片预览"}
            </div>
          </div>
          <div className="flex-1 grid grid-cols-1 overflow-hidden lg:grid-cols-[minmax(0,1fr)_340px]">
            <div className="overflow-y-auto p-3 bg-slate-50/50">
              {groupedChunks.map((item) => {
                if (item.type === 'chunk') {
                  const chunk = item.chunk;
                  return (
                    <button key={chunk.chunk_id} onClick={() => setSelectedChunk(chunk)} className={cn("mb-2 w-full rounded-lg border p-3 text-left hover:bg-slate-50 transition", selectedChunk?.chunk_id === chunk.chunk_id ? "border-blue-300 bg-blue-50 shadow-sm" : "border-slate-200 bg-white")}>
                      <div className="flex items-center justify-between">
                        <span className="text-xs font-semibold text-slate-500">{chunk.chunk_level} #{chunk.chunk_index}</span>
                        <span className="rounded bg-slate-100 px-2 py-0.5 text-[11px] text-slate-600 border border-slate-200">{chunk.page_type || "general"}</span>
                      </div>
                      <div className="mt-2 line-clamp-3 text-sm leading-6 text-slate-700">{chunk.content}</div>
                    </button>
                  );
                } else {
                  const { parent, children } = item;
                  const isExpanded = expandedParents.has(parent.chunk_id);
                  return (
                    <div key={parent.chunk_id} className="mb-2">
                      <button onClick={() => setSelectedChunk(parent)} className={cn("w-full rounded-lg border p-3 text-left hover:bg-slate-50 transition flex flex-col", selectedChunk?.chunk_id === parent.chunk_id ? "border-blue-300 bg-blue-50 shadow-sm" : "border-slate-200 bg-white")}>
                        <div className="flex items-center justify-between w-full">
                          <div className="flex items-center gap-2">
                            {children.length > 0 && (
                              <div 
                                onClick={(e) => toggleParent(parent.chunk_id, e)}
                                className="p-1 hover:bg-slate-200 rounded cursor-pointer -ml-1 text-slate-500"
                              >
                                {isExpanded ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
                              </div>
                            )}
                            <span className="text-xs font-semibold text-blue-600">Parent #{parent.chunk_index}</span>
                          </div>
                          <div className="flex items-center gap-2">
                            {children.length > 0 && <span className="text-[10px] text-slate-400">{children.length} 个子块</span>}
                            <span className="rounded bg-slate-100 px-2 py-0.5 text-[11px] text-slate-600 border border-slate-200">{parent.page_type || "general"}</span>
                          </div>
                        </div>
                        <div className={cn("mt-2 line-clamp-3 text-sm leading-6 text-slate-700 w-full", children.length > 0 && "ml-7 w-[calc(100%-28px)]")}>{parent.content}</div>
                      </button>
                      
                      {isExpanded && children.length > 0 && (
                        <div className="mt-2 ml-4 pl-4 border-l-2 border-slate-100 flex flex-col gap-2">
                          {children.map(child => (
                            <button key={child.chunk_id} onClick={() => setSelectedChunk(child)} className={cn("w-full rounded-lg border p-3 text-left hover:bg-slate-50 transition", selectedChunk?.chunk_id === child.chunk_id ? "border-blue-300 bg-blue-50 shadow-sm" : "border-slate-200 bg-white")}>
                              <div className="flex items-center justify-between">
                                <span className="text-xs font-semibold text-slate-500">Child #{child.chunk_index}</span>
                                <span className="rounded bg-slate-100 px-2 py-0.5 text-[11px] text-slate-600 border border-slate-200">{child.page_type || "general"}</span>
                              </div>
                              <div className="mt-2 line-clamp-3 text-sm leading-6 text-slate-700">{child.content}</div>
                            </button>
                          ))}
                        </div>
                      )}
                    </div>
                  );
                }
              })}
              {!selected && <div className="flex h-full items-center justify-center text-sm text-slate-400 flex-col gap-2"><Folder className="h-8 w-8 text-slate-200"/>从左侧选择文件后查看切片</div>}
            </div>
            <aside className="border-t border-slate-100 bg-white p-4 lg:border-l lg:border-t-0 flex flex-col h-full overflow-hidden">
              {selectedChunk ? (
                <>
                  <div className="mb-3 flex items-center justify-between gap-2 font-semibold shrink-0">
                    <div className="flex items-center gap-2">
                    <Eye className="h-4 w-4 text-blue-600" />
                      切片元数据
                    </div>
                    <div className="flex items-center gap-1.5">
                      <span className="rounded-full bg-blue-50 px-2 py-0.5 text-[11px] font-medium text-blue-700 border border-blue-100">
                        {selectedMetadataEntries.length} 个字段
                      </span>
                      <button
                        onClick={() => setMetadataZoom(true)}
                        title="放大查看元数据"
                        className="rounded-md p-1 text-slate-400 transition-colors hover:bg-slate-100 hover:text-blue-600"
                      >
                        <Maximize2 className="h-3.5 w-3.5" />
                      </button>
                    </div>
                  </div>
                  <div className="max-h-72 shrink-0 overflow-auto rounded-lg border border-slate-100 bg-slate-50/60 px-3">
                    <MetadataList entries={selectedMetadataEntries} />
                  </div>
                  <div className="mt-4 flex-1 overflow-auto">
                    <div className="text-xs font-semibold text-slate-400 mb-2">完整内容</div>
                    <pre className="whitespace-pre-wrap rounded-lg border border-slate-200 bg-white p-3 text-sm leading-7 text-slate-800 font-sans shadow-sm">{selectedChunk.content}</pre>
                  </div>
                </>
              ) : (
                <div className="flex h-full items-center justify-center text-sm text-slate-400 text-center px-4">
                  点击左侧切片查看详细内容及元数据标签。
                </div>
              )}
            </aside>
          </div>
        </section>
      </div>

      {/* Floating Action Button for QA */}
      <button 
        onClick={() => setIsChatOpen(!isChatOpen)}
        className={cn(
          "fixed bottom-8 right-8 h-14 w-14 rounded-full shadow-lg transition-all duration-300 flex items-center justify-center z-50 group",
          isChatOpen ? "bg-slate-900 text-white rotate-90" : "bg-blue-600 text-white hover:bg-blue-700 hover:scale-105"
        )}
      >
        {isChatOpen ? <X className="h-6 w-6" /> : <MessageSquare className="h-6 w-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">
          RAG 知识库问答
        </span>
      </button>

      {/* Chat Drawer / Floating Window —— 统一为 Wiki 问答风格(MessageBubble + 知识来源 + 停止按钮) */}
      {isChatOpen && (
        <div className="fixed bottom-24 right-8 w-[800px] h-[800px] bg-white rounded-3xl shadow-[0_20px_50px_rgba(0,0,0,0.15)] border border-slate-200 z-50 flex flex-col animate-in fade-in slide-in-from-bottom-10 duration-300 overflow-hidden">
          <div className="p-6 border-b border-slate-100 flex items-center justify-between bg-gradient-to-r from-blue-600 to-indigo-700 text-white">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-white/20 rounded-xl flex items-center justify-center backdrop-blur-md">
                <MessageSquare className="w-5 h-5" />
              </div>
              <div>
                <h3 className="font-bold text-sm">RAG Copilot</h3>
                <div className="flex items-center gap-1.5">
                  <div className="w-1.5 h-1.5 bg-emerald-400 rounded-full animate-pulse" />
                  <span className="text-[10px] text-blue-100 font-medium uppercase tracking-wider">知识库问答</span>
                </div>
              </div>
            </div>
            <div className="flex gap-2">
              <button title="清空对话" onClick={clearHistoryV2} className="p-2 hover:bg-white/10 rounded-lg transition-colors text-blue-100 hover:text-white">
                <Trash2 className="h-4 w-4" />
              </button>
              <button title="关闭" onClick={() => setIsChatOpen(false)} className="p-2 hover:bg-white/10 rounded-lg transition-colors text-blue-100 hover:text-white">
                <X className="h-4 w-4" />
              </button>
            </div>
          </div>

          <div className="flex-1 overflow-y-auto p-6 scrollbar-thin bg-slate-50/50 flex flex-col">
            {messages.length === 0 && (
              <div className="h-full flex flex-col items-center justify-center text-slate-400 space-y-4">
                <Bot className="h-12 w-12 text-slate-200" />
                <p className="text-sm">您可以问我关于产品、政策、排障等问题</p>
              </div>
            )}
            {messages.map((m, idx) => {
              const isLast = idx === messages.length - 1;
              const isStreaming = loading && isLast && m.role === "assistant";
              const done = m.meta?.done as { duration_ms?: number } | undefined;
              return (
                <div key={`msg-${idx}`}>
                  {m.role === "assistant" && <RagSummaryChips message={m} />}
                  <MessageBubble
                    role={m.role === "assistant" ? "ai" : "user"}
                    content={m.content}
                    reasoning={toWikiReasoning(m)}
                    isStreaming={isStreaming}
                    startTime={m.startTime}
                    endTime={m.endTime}
                    serverDurationMs={done?.duration_ms}
                  />
                  {m.role === "assistant" && !!m.sources?.length && (
                    <div className="ml-12 -mt-3 mb-6 max-w-[90%]">
                      <SourceList sources={m.sources} onPreviewSource={openSourcePreview} />
                    </div>
                  )}
                </div>
              );
            })}
            {loading && messages[messages.length - 1]?.role !== "assistant" && (
              <div className="flex gap-3">
                <div className="w-9 h-9 bg-blue-600 rounded-xl flex items-center justify-center text-white shrink-0 shadow-md font-bold text-xs">AI</div>
                <div className="bg-white p-4 rounded-2xl rounded-tl-none shadow-sm border border-slate-100 flex items-center gap-2">
                  <Loader2 className="w-4 h-4 animate-spin text-blue-600" />
                  <span className="text-xs text-slate-500">正在检索知识库...</span>
                </div>
              </div>
            )}
            <div ref={chatEndRef} />
          </div>

          <div className="p-6 border-t border-slate-100 bg-white">
            <div className="relative">
              <input
                type="text"
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                onKeyDown={(e) => e.key === "Enter" && askV2()}
                placeholder="输入问题,AI 将实时检索知识库..."
                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"
              />
              {loading ? (
                <button
                  onClick={() => { chatAbortRef.current?.abort(); chatAbortRef.current = null; setLoading(false); }}
                  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={askV2}
                  disabled={loading || !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>
      )}
      {(previewChunk || previewLoading) && (
        <div className="fixed inset-0 z-[60] flex items-center justify-center bg-slate-900/35 p-6">
          <div className="flex max-h-[82vh] w-full max-w-2xl flex-col overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-2xl">
            <div className="flex items-center justify-between border-b border-slate-100 px-4 py-3">
              <div className="flex min-w-0 items-center gap-2">
                <FileText className="h-4 w-4 text-blue-600" />
                <div className="min-w-0">
                  <div className="truncate text-sm font-semibold text-slate-800">{previewChunk?.source_name || "片段预览"}</div>
                  <div className="truncate text-xs text-slate-400">{previewChunk ? `${chunkPosition(previewChunk)} · ${previewChunk.title_path || "-"}` : "正在加载..."}</div>
                </div>
              </div>
              <button onClick={() => setPreviewChunk(null)} className="rounded p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-700">
                <X className="h-4 w-4" />
              </button>
            </div>
            <div className="overflow-y-auto p-4">
              {previewLoading && !previewChunk ? (
                <div className="flex items-center gap-2 text-sm text-slate-400">
                  <Loader2 className="h-4 w-4 animate-spin" />
                  加载片段中...
                </div>
              ) : (
                <>
                  <div className="mb-3 grid grid-cols-2 gap-2 text-xs text-slate-500">
                    <div className="rounded-lg bg-slate-50 p-2">召回路径:{previewChunk?.score?.retrieval_type ?? "父块命中"}</div>
                    <div className="rounded-lg bg-slate-50 p-2">分数:{previewChunk?.score?.rerank_score ?? previewChunk?.score?.vector_score ?? "-"}</div>
                  </div>
                  <pre className="whitespace-pre-wrap rounded-xl border border-slate-200 bg-slate-50 p-4 font-sans text-sm leading-7 text-slate-800">{previewChunk?.content}</pre>
                </>
              )}
            </div>
          </div>
        </div>
      )}

      {/* 切片元数据放大查看 */}
      {metadataZoom && selectedChunk && (
        <div className="fixed inset-0 z-[70] flex items-center justify-center bg-slate-900/40 p-6 backdrop-blur-sm" onClick={() => setMetadataZoom(false)}>
          <div className="flex max-h-[85vh] w-full max-w-3xl flex-col overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-2xl" onClick={(e) => e.stopPropagation()}>
            <div className="flex items-center justify-between border-b border-slate-100 px-5 py-4">
              <div className="flex items-center gap-2 font-semibold text-slate-800">
                <Eye className="h-4 w-4 text-blue-600" />
                切片元数据
                <span className="rounded bg-slate-100 px-2 py-0.5 text-[11px] font-medium text-slate-500">
                  {selectedChunk.chunk_level} #{selectedChunk.chunk_index} · {selectedMetadataEntries.length} 个字段
                </span>
              </div>
              <button onClick={() => setMetadataZoom(false)} className="rounded p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-700">
                <X className="h-4 w-4" />
              </button>
            </div>
            <div className="overflow-y-auto px-5 py-2">
              <MetadataList entries={selectedMetadataEntries} grid />
            </div>
          </div>
        </div>
      )}

      {isUploadModalOpen && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center p-8 bg-slate-900/60 backdrop-blur-sm animate-in fade-in duration-300">
          <div className="bg-white w-full max-w-2xl rounded-3xl shadow-2xl flex flex-col overflow-hidden animate-in zoom-in-95 duration-300">
            <header className="px-8 py-6 border-b border-slate-100 flex items-center justify-between bg-slate-50/50">
              <div className="flex items-center gap-3">
                <div className="p-2.5 bg-blue-100 text-blue-600 rounded-xl">
                  <Upload className="w-5 h-5" />
                </div>
                <div>
                  <h2 className="text-xl font-bold text-slate-800">上传新文件</h2>
                  <p className="text-xs text-slate-500 mt-0.5">支持 PDF, Word, Excel, PPT, Markdown</p>
                </div>
              </div>
              <button
                onClick={() => {
                  if (uploadQueue.some(q => q.status === 'uploading')) {
                    if (!confirm("尚有文件正在上传,确定要关闭吗?这可能会中断上传进程。")) return;
                  }
                  setIsUploadModalOpen(false);
                  setUploadQueue([]);
                  refresh();
                }}
                className="p-2 hover:bg-slate-200 rounded-xl transition-colors text-slate-400 hover:text-slate-800"
              >
                <X className="w-5 h-5" />
              </button>
            </header>

            <div className="p-8 flex flex-col gap-6 bg-white min-h-[300px] max-h-[60vh] overflow-auto">
              {uploadQueue.length === 0 ? (
                <div className="flex-1 flex flex-col items-center justify-center border-2 border-dashed border-slate-200 rounded-2xl bg-slate-50 hover:bg-blue-50/50 hover:border-blue-300 transition-colors p-10 relative group">
                  <input
                    type="file"
                    multiple
                    onChange={handleUploadSelect}
                    className="absolute inset-0 w-full h-full opacity-0 cursor-pointer z-10"
                    title="点击或拖拽文件到此处"
                  />
                  <div className="w-16 h-16 bg-white shadow-sm rounded-full flex items-center justify-center mb-4 group-hover:scale-110 transition-transform">
                    <Upload className="w-8 h-8 text-blue-500" />
                  </div>
                  <h3 className="text-lg font-bold text-slate-700">点击或拖拽文件到此处</h3>
                  <p className="text-sm text-slate-400 mt-2 text-center max-w-xs">
                    上传的文件将进入“文件库”,稍后您可以发起批量索引。
                  </p>
                </div>
              ) : (
                <div className="flex flex-col gap-3">
                  <div className="flex items-center justify-between mb-2">
                    <h3 className="text-sm font-bold text-slate-700">待上传列表 ({uploadQueue.length})</h3>
                    {!uploadQueue.some(q => q.status === 'uploading') && (
                      <label className="text-xs font-bold text-blue-600 bg-blue-50 px-3 py-1.5 rounded-lg cursor-pointer hover:bg-blue-100 transition-colors">
                        + 继续添加
                        <input type="file" multiple className="hidden" onChange={handleUploadSelect} />
                      </label>
                    )}
                  </div>
                  {uploadQueue.map((item, idx) => (
                    <div key={idx} className="flex items-center gap-4 p-4 bg-slate-50 border border-slate-100 rounded-xl">
                      <div className="p-2 bg-white rounded-lg shadow-sm border border-slate-100">
                        {getFileIcon(item.name.split('.').pop() || "")}
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center justify-between mb-1">
                          <span className="text-sm font-semibold text-slate-700 truncate" title={item.name}>{item.name}</span>
                          <span className="text-xs font-medium text-slate-500">{(item.file.size / 1024 / 1024).toFixed(2)} MB</span>
                        </div>
                        {item.status === 'uploading' ? (
                          <div className="flex items-center gap-1.5 mt-1 text-xs font-bold text-blue-600">
                            <Loader2 className="w-3.5 h-3.5 animate-spin" /> 上传中...
                          </div>
                        ) : item.status === 'success' ? (
                          <div className="flex items-center gap-1.5 mt-1 text-xs font-bold text-emerald-600">
                            <CheckCircle2 className="w-3.5 h-3.5" /> 上传成功
                          </div>
                        ) : item.status === 'error' ? (
                          <div className="flex items-center gap-1.5 mt-1 text-xs font-bold text-red-600" title={item.errorMsg}>
                            <AlertCircle className="w-3.5 h-3.5" /> {item.errorMsg || "上传失败"}
                          </div>
                        ) : (
                          <div className="flex items-center gap-1.5 mt-1 text-xs font-bold text-slate-400">
                            等待上传...
                          </div>
                        )}
                      </div>
                      {item.status !== 'uploading' && (
                        <button
                          onClick={() => setUploadQueue(prev => prev.filter((_, i) => i !== idx))}
                          className="p-2 hover:bg-slate-200 rounded-lg text-slate-400 hover:text-slate-700 transition-colors"
                          title="移除该项"
                        >
                          <X className="w-4 h-4" />
                        </button>
                      )}
                    </div>
                  ))}
                </div>
              )}
            </div>

            {uploadQueue.length > 0 && (
              <footer className="px-8 py-4 border-t border-slate-100 bg-slate-50 flex items-center justify-end gap-3">
                <button
                  onClick={() => {
                    if (uploadQueue.some(q => q.status === 'uploading')) {
                      if (!confirm("尚有文件正在上传,确定要关闭吗?这可能会中断上传进程。")) return;
                    }
                    setUploadQueue([]);
                    setIsUploadModalOpen(false);
                    refresh();
                  }}
                  disabled={uploadQueue.some(q => q.status === 'uploading')}
                  className="px-6 py-2.5 rounded-xl font-bold text-sm text-slate-600 hover:bg-slate-200 transition-colors disabled:opacity-50"
                >
                  取消
                </button>
                {uploadQueue.every(q => q.status === 'success' || q.status === 'error') ? (
                  <button
                    onClick={() => {
                      setUploadQueue([]);
                      setIsUploadModalOpen(false);
                      refresh();
                    }}
                    className="flex items-center gap-2 px-6 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-xl font-bold text-sm transition-colors shadow-lg shadow-emerald-500/30"
                  >
                    <CheckCircle2 className="w-4 h-4" /> 确认
                  </button>
                ) : (
                  <button
                    onClick={handleUploadConfirm}
                    disabled={uploadQueue.some(q => q.status === 'uploading')}
                    className="flex items-center gap-2 px-6 py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-xl font-bold text-sm transition-colors shadow-lg shadow-blue-500/30 disabled:opacity-50"
                  >
                    {uploadQueue.some(q => q.status === 'uploading') ? (
                      <><Loader2 className="w-4 h-4 animate-spin" /> 上传中...</>
                    ) : (
                      <><Upload className="w-4 h-4" /> 确认上传</>
                    )}
                  </button>
                )}
              </footer>
            )}
          </div>
        </div>
      )}
      </main>
  );
}

function updateLastMessage(messages: RagMessage[], patch: { contentAppend?: string; thinkingAppend?: string; sources?: RagChunk[]; reasoningStep?: RagReasoningStep; meta?: Record<string, unknown>; endTime?: number }) {
  const next = [...messages];
  const last = next[next.length - 1];
  if (!last) return messages;
  const reasoning = [...(last.reasoning || [])];
  if (patch.reasoningStep) {
    const existing = reasoning.findIndex((item) => item.id === patch.reasoningStep!.id);
    if (existing >= 0) reasoning[existing] = { ...reasoning[existing], ...patch.reasoningStep };
    else reasoning.push(patch.reasoningStep);
  }
  next[next.length - 1] = {
    ...last,
    content: last.content + (patch.contentAppend || ""),
    thinking: (last.thinking || "") + (patch.thinkingAppend || ""),
    sources: patch.sources ?? last.sources,
    reasoning,
    endTime: patch.endTime || last.endTime,
    meta: { ...(last.meta || {}), ...(patch.meta || {}) },
  };
  return next;
}

// 把 RAG 的推理步骤 + thinking 映射为 Wiki MessageBubble 所用的 ReasoningStep[],
// 从而复用 Wiki 那套「查看思考过程 (N 步, 秒数)」折叠 UI,风格完全一致。
// 每步展开都是实质内容(意图全字段 / 各路召回 / 片段列表带分数);末尾再挂一个
// 「完整检索数据 (JSON)」折叠块,评测/排障时点开即见全量数据(复用 response 折叠 UI)。
function toWikiReasoning(message: RagMessage): ReasoningStep[] {
  const steps: ReasoningStep[] = [];
  for (const step of message.reasoning || []) {
    steps.push({ id: step.id, type: "thought", content: ragStepText(step), time: formatElapsedSeconds(step.elapsed_ms) });
  }
  const done = message.meta?.done as Record<string, unknown> | undefined;
  if (done && (done.retrieval || done.intent)) {
    const detail = { intent: done.intent, retrieval: done.retrieval, citations: done.citations };
    steps.push({ id: "debug-json", type: "response", name: "完整检索数据 (JSON)", content: safeJsonString(detail) });
  }
  if (message.thinking?.trim()) {
    steps.push({ id: "thinking", type: "thought", content: message.thinking });
  }
  return steps;
}

function formatElapsedSeconds(elapsedMs?: number): string | undefined {
  if (typeof elapsedMs !== "number" || elapsedMs < 0) return undefined;
  const seconds = elapsedMs / 1000;
  return `耗时 ${seconds < 10 ? seconds.toFixed(1) : Math.round(seconds)}s`;
}

function safeJsonString(value: unknown): string {
  try {
    return JSON.stringify(value, null, 2);
  } catch {
    return String(value);
  }
}

function pageLabel(s: Record<string, unknown>): string | undefined {
  const start = s.page_start;
  const end = s.page_end;
  if (typeof start !== "number") return undefined;
  return typeof end === "number" && end !== start ? `P${start}-${end}` : `P${start}`;
}

// 单条 RAG 推理步骤 → 可读多行文本(标题 + 关键信息)。MessageBubble 对 thought 类型按
// whitespace-pre-wrap 渲染,故可多行铺开。
function ragStepText(step: RagReasoningStep): string {
  const data = (step.data || {}) as Record<string, unknown>;
  const num = (k: string) => (typeof data[k] === "number" ? String(data[k]) : undefined);
  const str = (k: string) => (typeof data[k] === "string" && data[k] ? String(data[k]) : undefined);
  const arr = (k: string) => (Array.isArray(data[k]) ? (data[k] as unknown[]) : []);
  const obj = (k: string) => (data[k] && typeof data[k] === "object" && !Array.isArray(data[k]) ? (data[k] as Record<string, unknown>) : {});
  switch (step.phase) {
    case "history":
      return `${step.title}:${num("messages") ?? 0} 条上下文`;
    case "intent": {
      const lines = [`意图:${str("intent") ?? "-"}`];
      const intents = arr("intents").map(String);
      if (intents.length > 1) lines.push(`候选意图:${intents.join(" > ")}`);
      const standalone = str("standalone_query");
      if (standalone) lines.push(`检索问题:${standalone}`);
      const subs = arr("sub_queries").map(String);
      if (subs.length) lines.push(`子查询:${subs.map((q, i) => `${i + 1}) ${q}`).join("  ")}`);
      const labels = Object.entries(obj("query_labels")).filter(([, v]) => v);
      if (labels.length) lines.push(`业务标签:${labels.map(([k, v]) => `${k}=${v}`).join(" · ")}`);
      if (data.degraded === true) lines.push("⚠️ 查询理解降级,本次意图不可信");
      return lines.join("\n");
    }
    case "retrieval": {
      if (step.status !== "done") return `${step.title}…`;
      const lines = [`命中 ${num("chunk_count") ?? 0} 个片段`];
      const recall = Object.entries(obj("recall"));
      if (recall.length) lines.push(`各路召回:${recall.map(([k, v]) => `${k}=${v}`).join("  ")}`);
      const boosts = Object.keys(obj("soft_boosts"));
      if (boosts.length) lines.push(`软提升维度:${boosts.join(", ")}`);
      return `${step.title}:${lines.join("\n")}`;
    }
    case "sources": {
      const sources = arr("sources") as Record<string, unknown>[];
      if (!sources.length) return `${step.title}:${num("source_count") ?? 0} 个`;
      const lines = sources.map((s, i) => {
        const loc = [pageLabel(s), s.section_title].filter(Boolean).join(" · ");
        const rerank = typeof s.rerank_score === "number" ? ` [rerank ${(s.rerank_score as number).toFixed(3)}]` : "";
        return `[${s.source_index ?? i + 1}] ${s.source_name ?? "-"}${loc ? " — " + loc : ""}${rerank}`;
      });
      return `${step.title}:${sources.length} 个\n${lines.join("\n")}`;
    }
    case "answer":
      return step.status === "done"
        ? `${step.title}:${num("answer_length") ?? 0} 字 · ${num("tokens") ?? 0} tokens`
        : `${step.title}(${str("model") ?? ""})`;
    default:
      return step.title;
  }
}

// 检索概况:从推理步骤 + done 里抽关键指标,做成常驻 chip 置顶,无需展开即可见。
function ragSummaryChips(message: RagMessage): { label: string; value: string }[] {
  const steps = message.reasoning || [];
  const stepData = (phase: string) => {
    const s = steps.find((item) => item.phase === phase && item.status === "done") || steps.find((item) => item.phase === phase);
    return (s?.data || {}) as Record<string, unknown>;
  };
  const chips: { label: string; value: string }[] = [];
  const intentData = stepData("intent");
  const intent = intentData.intent;
  if (typeof intent === "string" && intent) chips.push({ label: "意图", value: intentData.degraded === true ? `${intent}(降级)` : intent });
  const retrievalData = stepData("retrieval");
  const recall = retrievalData.recall && typeof retrievalData.recall === "object" ? Object.keys(retrievalData.recall as object) : [];
  if (recall.length) chips.push({ label: "变体", value: String(recall.length) });
  if (typeof retrievalData.chunk_count === "number") chips.push({ label: "召回", value: String(retrievalData.chunk_count) });
  const done = message.meta?.done as Record<string, unknown> | undefined;
  if (done) {
    if (typeof done.tokens === "number") chips.push({ label: "tokens", value: String(done.tokens) });
    if (typeof done.duration_ms === "number") chips.push({ label: "耗时", value: `${((done.duration_ms as number) / 1000).toFixed(1)}s` });
  }
  return chips;
}

function RagSummaryChips({ message }: { message: RagMessage }) {
  const chips = ragSummaryChips(message);
  if (!chips.length) return null;
  return (
    <div className="ml-12 mb-2 flex flex-wrap items-center gap-1.5">
      {chips.map((chip) => (
        <span key={chip.label} className="inline-flex items-center gap-1 rounded-md border border-slate-200 bg-white px-2 py-0.5 text-[11px] text-slate-600">
          <span className="text-slate-400">{chip.label}</span>
          <span className="font-semibold text-slate-700">{chip.value}</span>
        </span>
      ))}
    </div>
  );
}

function SourceList({ sources, onPreviewSource }: { sources: RagChunk[]; onPreviewSource: (source: RagChunk) => void }) {
  return (
    <div className="mt-3 rounded-xl border border-slate-200 bg-white p-3">
      <div className="mb-2 flex items-center gap-2 text-xs font-semibold text-slate-600">
        <BookOpen className="h-3.5 w-3.5 text-blue-600" />
        知识来源
      </div>
      <div className="space-y-2">
        {sources.map((source, index) => (
          <button
            key={`${source.chunk_id}-${index}`}
            onClick={() => onPreviewSource(source)}
            className="w-full rounded-lg border border-slate-100 bg-slate-50 px-3 py-2 text-left text-xs text-slate-600 hover:border-blue-200 hover:bg-blue-50"
          >
            <div className="flex items-center justify-between gap-3">
              <span className="min-w-0 truncate font-medium text-slate-800">[{source.source_index ?? index + 1}] {source.source_name}</span>
              <span className="flex shrink-0 items-center gap-1 text-[10px] text-slate-400">
                <span className="rounded border border-emerald-100 bg-emerald-50 px-1.5 py-0.5 text-emerald-600">引用</span>
                <span>{chunkPosition(source)}</span>
              </span>
            </div>
            <div className="mt-1 line-clamp-2 text-[11px] leading-5 text-slate-500">{source.title_path || source.content}</div>
          </button>
        ))}
      </div>

      
    </div>
  );
}

function chunkPosition(chunk: RagChunk) {
  if (chunk.page_start) return chunk.page_end && chunk.page_end !== chunk.page_start ? `P${chunk.page_start}-${chunk.page_end}` : `P${chunk.page_start}`;
  if (chunk.slide_number) return `Slide ${chunk.slide_number}`;
  if (chunk.sheet_name) return chunk.sheet_name;
  return "-";
}

// 元数据按引擎层语义分组,组内按固定顺序排列——避免所有字段混成一坨、无序。
// 未匹配到任何组的键归入「其他」并按字母序排。
const METADATA_GROUPS: { title: string; keys: string[] }[] = [
  { title: "身份", keys: ["chunk_id", "file_id", "document_id", "parent_chunk_id", "chunk_level", "chunk_index", "source_index", "status"] },
  { title: "定位", keys: ["source_name", "title_path", "section_title", "section_path", "page_start", "page_end", "slide_number", "sheet_name", "row_start", "row_end", "char_start", "char_end"] },
  { title: "内容", keys: ["content_kind", "content_role", "table_header", "table_markdown", "table_row_count", "table_id"] },
  { title: "解析质量", keys: ["parse_method", "parse_methods", "parse_status", "parse_quality", "parser_version", "chunker_version"] },
  { title: "业务标签", keys: ["brand", "brand_series", "business_category", "sub_business", "page_type", "intent_type"] },
];

function groupMetadataEntries(entries: [string, unknown][]): { title: string; items: [string, unknown][] }[] {
  const map = new Map(entries);
  const used = new Set<string>();
  const groups: { title: string; items: [string, unknown][] }[] = [];
  for (const g of METADATA_GROUPS) {
    const items: [string, unknown][] = [];
    for (const k of g.keys) {
      if (map.has(k)) {
        items.push([k, map.get(k)]);
        used.add(k);
      }
    }
    if (items.length) groups.push({ title: g.title, items });
  }
  const rest = entries.filter(([k]) => !used.has(k)).sort((a, b) => a[0].localeCompare(b[0]));
  if (rest.length) groups.push({ title: "其他", items: rest });
  return groups;
}

function MetadataRow({ entryKey, value }: { entryKey: string; value: unknown }) {
  return (
    <div className="border-b border-slate-100 py-1.5 last:border-b-0">
      <div className="flex items-center justify-between gap-2">
        <span className="text-[11px] font-medium text-slate-500">{metadataLabels[entryKey] || entryKey}</span>
        <code className="shrink-0 text-[9px] text-slate-300">{entryKey}</code>
      </div>
      {isStructuredMetadataValue(value) ? (
        <pre className="mt-1 max-h-48 overflow-auto whitespace-pre-wrap break-all rounded border border-slate-100 bg-white p-2 text-[11px] leading-5 text-slate-600">
          {formatMetadataValue(value)}
        </pre>
      ) : (
        <div className="mt-0.5 whitespace-pre-wrap break-words text-[13px] leading-5 text-slate-800">
          {formatMetadataValue(value)}
        </div>
      )}
    </div>
  );
}

// 元数据字段:按类型分组展示,每组一个小标题。grid 时组内两列铺开(放大弹窗用)。
function MetadataList({ entries, grid = false }: { entries: [string, unknown][]; grid?: boolean }) {
  if (!entries.length) {
    return (
      <div className="rounded-md border border-dashed border-slate-200 bg-white p-3 text-center text-xs text-slate-400">
        暂无元数据
      </div>
    );
  }
  const groups = groupMetadataEntries(entries);
  return (
    <div className="space-y-3 py-1">
      {groups.map((group) => (
        <div key={group.title}>
          <div className="mb-1 flex items-center gap-1.5">
            <span className="h-3 w-0.5 rounded-full bg-blue-400" />
            <span className="text-[10px] font-bold uppercase tracking-wider text-slate-400">
              {group.title}
              <span className="ml-1 text-slate-300">({group.items.length})</span>
            </span>
          </div>
          <div className={grid ? "grid grid-cols-1 gap-x-8 sm:grid-cols-2" : ""}>
            {group.items.map(([key, value]) => (
              <MetadataRow key={key} entryKey={key} value={value} />
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

function buildChunkMetadataEntries(chunk: RagChunk): [string, unknown][] {
  const metadata =
    chunk.metadata_json && typeof chunk.metadata_json === "object" && !Array.isArray(chunk.metadata_json)
      ? chunk.metadata_json
      : {};
  const merged: Record<string, unknown> = {
    chunk_id: chunk.chunk_id,
    file_id: chunk.file_id,
    parent_chunk_id: chunk.parent_chunk_id,
    chunk_level: chunk.chunk_level,
    chunk_index: chunk.chunk_index,
    source_index: chunk.source_index,
    source_name: chunk.source_name,
    title_path: chunk.title_path,
    page_start: chunk.page_start,
    page_end: chunk.page_end,
    slide_number: chunk.slide_number,
    sheet_name: chunk.sheet_name,
    row_start: chunk.row_start,
    row_end: chunk.row_end,
    status: chunk.status,
    page_type: chunk.page_type,
    brand: chunk.brand,
    business_category: chunk.business_category,
    ...metadata,
  };

  return Object.entries(merged)
    .filter(([, value]) => value !== undefined && value !== null && value !== "")
    .sort(([left], [right]) => {
      const leftKnown = metadataLabels[left] ? 0 : 1;
      const rightKnown = metadataLabels[right] ? 0 : 1;
      if (leftKnown !== rightKnown) return leftKnown - rightKnown;
      return left.localeCompare(right);
    });
}

function isStructuredMetadataValue(value: unknown) {
  return Array.isArray(value) || (typeof value === "object" && value !== null);
}

function formatMetadataValue(value: unknown) {
  if (value === null) return "-";
  if (value === undefined) return "-";
  if (typeof value === "boolean") return value ? "true" : "false";
  if (typeof value === "string") return value || "-";
  if (typeof value === "number") return Number.isFinite(value) ? String(value) : "-";
  try {
    return JSON.stringify(value, null, 2);
  } catch {
    return String(value);
  }
}