Elffuss BraidHub

kikocis/utopia public

c83424aa778c · 71.9 KiBRawPermalink
1import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
3import { Link, useSearch } from "@tanstack/react-router";
4import {
5 BookOpen,
6 History as HistoryIcon,
7 KeyRound,
8 RefreshCw,
9 Search,
10 Settings as SettingsIcon,
11 Upload,
12 Waypoints,
13 X,
14} from "lucide-react";
15import { api, type Doc, type ExtractionDrop, type SourceView } from "../api";
16import { S } from "../i18n";
17import { useKb, useKbId } from "../kb";
18import { toast } from "../toast";
19import { Chip, type ChipTone, DangerConfirm, Loading, Pager } from "../ui";
20import {
21 KIND_ICON,
22 SOURCE_ICONS,
23 sourceIcon,
24 SourcesRail,
25 SYNC_DOT,
26 SYNCING_KINDS,
27 type LibrarySelection,
28} from "./SourcesRail";
29
30const PAGE_SIZE = 15;
31
32const STATUS_TONE: Record<string, ChipTone> = {
33 pending: "neutral",
34 parsing: "warn",
35 indexing: "warn",
36 embedding: "warn",
37 ready: "info",
38 failed: "danger",
39};
40
41const GRAPH_TONE: Record<string, ChipTone> = {
42 queued: "neutral",
43 extracting: "warn",
44 done: "violet",
45 failed: "danger",
46};
47
48/** 调度器产出的值:interval 与 cron 互斥。 */
49interface ScheduleValue {
50 sync_interval_minutes: number | null;
51 sync_cron: string | null;
52}
53
54const pad2 = (n: number | string) => String(n).padStart(2, "0");
55
56/** 同步日程的人话展示(advanced 自定义表达式按原样显示)。 */
57function scheduleLabel(s: SourceView): string {
58 if (s.sync_cron) {
59 const daily = s.sync_cron.match(/^(\d{1,2}) (\d{1,2}) \* \* \*$/);
60 if (daily) return S.library.schedule.dailyAt(`${pad2(daily[2])}:${pad2(daily[1])}`);
61 const weekly = s.sync_cron.match(/^(\d{1,2}) (\d{1,2}) \* \* ([A-Za-z,-]+)$/);
62 if (weekly) return `${weekly[3]} ${pad2(weekly[2])}:${pad2(weekly[1])}`;
63 return s.sync_cron;
64 }
65 if (s.sync_interval_minutes) return S.library.intervalEvery(s.sync_interval_minutes);
66 return S.library.intervalManual;
67}
68
69type ScheduleMode = "manual" | "interval" | "daily" | "weekly" | "advanced";
70
71/** 已存日程 → 选择器初始状态(编辑模式回显;识别不了的 cron 落到 Advanced)。 */
72function scheduleToPickerState(initial?: ScheduleValue) {
73 const base = {
74 mode: "manual" as ScheduleMode,
75 every: 30,
76 unit: "minutes" as "minutes" | "hours",
77 time: "09:00",
78 days: new Set([0]),
79 cron: "",
80 };
81 if (!initial) return base;
82 if (initial.sync_cron) {
83 const daily = initial.sync_cron.match(/^(\d{1,2}) (\d{1,2}) \* \* \*$/);
84 if (daily)
85 return { ...base, mode: "daily" as ScheduleMode, time: `${pad2(daily[2])}:${pad2(daily[1])}` };
86 const weekly = initial.sync_cron.match(/^(\d{1,2}) (\d{1,2}) \* \* ([A-Za-z,]+)$/);
87 if (weekly) {
88 const idx = weekly[3]
89 .split(",")
90 .map((n) => (S.library.schedule.daysShort as readonly string[]).indexOf(n))
91 .filter((i) => i >= 0);
92 if (idx.length)
93 return {
94 ...base,
95 mode: "weekly" as ScheduleMode,
96 time: `${pad2(weekly[2])}:${pad2(weekly[1])}`,
97 days: new Set(idx),
98 };
99 }
100 return { ...base, mode: "advanced" as ScheduleMode, cron: initial.sync_cron };
101 }
102 if (initial.sync_interval_minutes) {
103 const m = initial.sync_interval_minutes;
104 return m % 60 === 0
105 ? { ...base, mode: "interval" as ScheduleMode, every: m / 60, unit: "hours" as const }
106 : { ...base, mode: "interval" as ScheduleMode, every: m, unit: "minutes" as const };
107 }
108 return base;
109}
110
111/** 可视化同步日程选择器:Manual / Interval / Daily / Weekly 构建,Advanced 才暴露 cron。 */
112function SchedulePicker({
113 onChange,
114 initial,
115}: {
116 onChange: (v: ScheduleValue) => void;
117 /** 编辑模式的既有日程;新建缺省从 Manual 起步 */
118 initial?: ScheduleValue;
119}) {
120 type Mode = ScheduleMode;
121 const [init] = useState(() => scheduleToPickerState(initial));
122 const [mode, setMode] = useState<Mode>(init.mode);
123 const [every, setEvery] = useState(init.every);
124 const [unit, setUnit] = useState<"minutes" | "hours">(init.unit);
125 const [time, setTime] = useState(init.time);
126 const [days, setDays] = useState<Set<number>>(init.days);
127 const [cron, setCron] = useState(init.cron);
128
129 const emit = (
130 m: Mode,
131 v: { every?: number; unit?: string; time?: string; days?: Set<number>; cron?: string },
132 ) => {
133 const t = v.time ?? time;
134 const [hh, mm] = t.split(":").map(Number);
135 // 时间格式未成形时(手输中途)不更新日程,保留上一个有效值
136 if ((m === "daily" || m === "weekly") && (Number.isNaN(hh) || Number.isNaN(mm))) return;
137 switch (m) {
138 case "manual":
139 return onChange({ sync_interval_minutes: null, sync_cron: null });
140 case "interval": {
141 const n = Math.max(1, v.every ?? every);
142 const u = v.unit ?? unit;
143 return onChange({
144 sync_interval_minutes: u === "hours" ? n * 60 : n,
145 sync_cron: null,
146 });
147 }
148 case "daily":
149 return onChange({ sync_interval_minutes: null, sync_cron: `${mm} ${hh} * * *` });
150 case "weekly": {
151 const ds = [...(v.days ?? days)].sort();
152 const names = ds.map((i) => S.library.schedule.daysShort[i]).join(",");
153 return onChange({
154 sync_interval_minutes: null,
155 sync_cron: ds.length ? `${mm} ${hh} * * ${names}` : null,
156 });
157 }
158 case "advanced":
159 return onChange({
160 sync_interval_minutes: null,
161 sync_cron: (v.cron ?? cron).trim() || null,
162 });
163 }
164 };
165
166 const modes: { key: Mode; label: string }[] = [
167 { key: "manual", label: S.library.schedule.manual },
168 { key: "interval", label: S.library.schedule.interval },
169 { key: "daily", label: S.library.schedule.daily },
170 { key: "weekly", label: S.library.schedule.weekly },
171 { key: "advanced", label: S.library.schedule.advanced },
172 ];
173
174 return (
175 <div>
176 <div className="flex rounded-lg overflow-hidden border border-white/10 mb-2">
177 {modes.map(({ key, label }) => (
178 <button
179 key={key}
180 onClick={() => {
181 setMode(key);
182 emit(key, {});
183 }}
184 className={`flex-1 px-2 py-1.5 text-[11px] transition-colors ${
185 mode === key
186 ? "bg-white/10 text-neutral-100"
187 : "text-neutral-500 hover:bg-white/[0.05] hover:text-neutral-300"
188 }`}
189 >
190 {label}
191 </button>
192 ))}
193 </div>
194
195 {mode === "interval" && (
196 <div className="flex items-center gap-2 text-sm text-neutral-400">
197 {S.library.schedule.every}
198 <input
199 type="number"
200 min={1}
201 className="input-dark u-input-plain w-16 px-2 py-1.5 text-sm u-num text-center"
202 value={every}
203 onChange={(e) => {
204 const n = Number(e.target.value) || 1;
205 setEvery(n);
206 emit("interval", { every: n });
207 }}
208 />
209 {/* 两个选项不配下拉:分段切换,与上方模式条同配方 */}
210 <div className="flex rounded-lg overflow-hidden border border-white/10">
211 {(["minutes", "hours"] as const).map((u) => (
212 <button
213 key={u}
214 onClick={() => {
215 setUnit(u);
216 emit("interval", { unit: u });
217 }}
218 className={`px-3 py-1.5 text-xs transition-colors ${
219 unit === u
220 ? "bg-white/10 text-neutral-100"
221 : "text-neutral-500 hover:bg-white/[0.05] hover:text-neutral-300"
222 }`}
223 >
224 {S.library.schedule[u]}
225 </button>
226 ))}
227 </div>
228 </div>
229 )}
230
231 {(mode === "daily" || mode === "weekly") && (
232 <div className="space-y-2">
233 {mode === "weekly" && (
234 <div className="flex gap-1">
235 {S.library.schedule.daysShort.map((d, i) => (
236 <button
237 key={d}
238 onClick={() => {
239 const next = new Set(days);
240 if (next.has(i)) next.delete(i);
241 else next.add(i);
242 setDays(next);
243 emit("weekly", { days: next });
244 }}
245 className={`flex-1 rounded-lg px-1 py-1.5 text-[11px] transition-colors ${
246 days.has(i)
247 ? "bg-white text-black font-medium"
248 : "bg-white/[0.05] text-neutral-500 hover:text-neutral-300"
249 }`}
250 >
251 {d}
252 </button>
253 ))}
254 </div>
255 )}
256 <div className="flex items-center gap-2 text-sm text-neutral-400">
257 {S.library.schedule.at}
258 {/* 24h 纯文本输入:原生 time 控件块头大且跟随系统语言("上午 09:00") */}
259 <input
260 className={`input-dark u-input-plain w-[4.2rem] px-2 py-1.5 text-sm u-num text-center ${
261 /^([01]?\d|2[0-3]):[0-5]\d$/.test(time) ? "" : "!border-[var(--u-danger)]"
262 }`}
263 placeholder="09:00"
264 value={time}
265 onChange={(e) => {
266 const t = e.target.value;
267 setTime(t);
268 if (/^([01]?\d|2[0-3]):[0-5]\d$/.test(t)) emit(mode, { time: t });
269 }}
270 />
271 </div>
272 </div>
273 )}
274
275 {mode === "advanced" && (
276 <div>
277 {/* 表达式用 mono,placeholder 回默认字体(u-placeholder-sans) */}
278 <input
279 className="input-dark w-full px-3 py-2 text-sm font-mono u-placeholder-sans"
280 placeholder={S.library.schedule.cronPlaceholder}
281 value={cron}
282 onChange={(e) => {
283 setCron(e.target.value);
284 emit("advanced", { cron: e.target.value });
285 }}
286 />
287 <a
288 href={S.library.schedule.cronDocsUrl}
289 target="_blank"
290 rel="noreferrer"
291 className="mt-1.5 inline-block text-[10.5px] text-neutral-500 underline decoration-white/20 underline-offset-2 hover:text-neutral-300 transition-colors"
292 >
293 {S.library.schedule.whatIsCron}
294 </a>
295 </div>
296 )}
297 </div>
298 );
299}
300
301export function Library() {
302 const { kb } = useKb();
303 const queryClient = useQueryClient();
304 const fileInput = useRef<HTMLInputElement>(null);
305 // 从文档查看页的来源栏跳回时带 ?src= 定位到对应文件夹
306 const { src } = useSearch({ from: "/app/kb/$kbId/library" });
307 const [dragging, setDragging] = useState(false);
308 const [selection, setSelection] = useState<LibrarySelection>(src ?? "all");
309 const [adding, setAdding] = useState(false);
310 const [editing, setEditing] = useState(false);
311 // api 来源密钥弹窗(随时可查看/轮换)
312 const [tokenReveal, setTokenReveal] = useState<{ sourceId: string } | null>(null);
313 const [cleaning, setCleaning] = useState(false);
314 const [reExtracting, setReExtracting] = useState(false);
315 const [rebuilding, setRebuilding] = useState(false);
316 // 失败详情弹窗:{文件名, 哪条管道, 原文}
317 const [errorView, setErrorView] = useState<{
318 file: string;
319 kind: string;
320 text: string;
321 } | null>(null);
322 // 丢弃详情弹窗:这篇文档抽出来却没落地的事实
323 const [dropsView, setDropsView] = useState<{ file: string; rows: ExtractionDrop[] } | null>(
324 null,
325 );
326 const [showHistory, setShowHistory] = useState(false);
327 const [page, setPage] = useState(0);
328 const [filter, setFilter] = useState("");
329 // 按抽取状态筛。**空 = 不筛**——五篇失败混在二十七篇里,从前只能一页页看
330 const [graphFilter, setGraphFilter] = useState("");
331
332
333 // 切换文件夹回到第一页、清空过滤、退出历史视图
334 useEffect(() => {
335 setPage(0);
336 setFilter("");
337 setShowHistory(false);
338 }, [selection]);
339 // 过滤词变化回到第一页
340 useEffect(() => setPage(0), [filter]);
341
342 // 状态变化经 SSE 事件流推送(useKbEvents 挂在 Shell),无需轮询
343 const docs = useQuery({
344 // **服务端筛选与分页**:作用域、名字、抽取状态、页码都进 queryKey,
345 // 换任何一个都重新取一页。从前是一次取回整库、客户端切片
346 queryKey: ["documents", kb?.id, selection, filter, graphFilter, page],
347 queryFn: () =>
348 api.documents(kb!.id, {
349 source: selection === "all" ? undefined : selection === "uploads" ? "none" : selection,
350 q: filter.trim() || undefined,
351 graph: graphFilter || undefined,
352 limit: PAGE_SIZE,
353 offset: page * PAGE_SIZE,
354 }),
355 enabled: !!kb,
356 placeholderData: (prev) => prev,
357 });
358 const sources = useQuery({
359 queryKey: ["sources", kb?.id],
360 queryFn: () => api.sources(kb!.id),
361 enabled: !!kb,
362 });
363 // 整库一次取回后按文档分组:抽取丢弃的行数很小,好过每行发一个请求
364 const drops = useQuery({
365 queryKey: ["extraction-drops", kb?.id],
366 queryFn: () => api.extractionDrops(kb!.id),
367 enabled: !!kb,
368 });
369 const dropsByDoc = useMemo(() => {
370 const m = new Map<string, ExtractionDrop[]>();
371 for (const d of drops.data?.drops ?? []) {
372 const list = m.get(d.document_id);
373 if (list) list.push(d);
374 else m.set(d.document_id, [d]);
375 }
376 return m;
377 }, [drops.data]);
378
379 const invalidate = () => {
380 queryClient.invalidateQueries({ queryKey: ["documents", kb?.id] });
381 queryClient.invalidateQueries({ queryKey: ["docCount", kb?.id] });
382 queryClient.invalidateQueries({ queryKey: ["sources", kb?.id] });
383 // 重抽会重写这篇文档的丢弃信号,跟着文档一起失效
384 queryClient.invalidateQueries({ queryKey: ["extraction-drops", kb?.id] });
385 };
386
387 // 一键重试这个作用域里全部失败的。**逐篇入队在服务端做**——排队还带着
388 // 别的动作(解雇在跑的任务、清增量标记),绕过去会留下半截状态
389 const retryFailed = useMutation({
390 mutationFn: () =>
391 api.retryFailedDocs(
392 kb!.id,
393 selection === "all"
394 ? undefined
395 : selection === "uploads"
396 ? "none"
397 : selection,
398 ),
399 onSuccess: (r) => {
400 toast.success(S.library.retryQueued(r.queued));
401 invalidate();
402 },
403 onError: (e: Error) => toast.error(e.message),
404 });
405
406 const upload = useMutation({
407 // 选中 folder 来源时,上传直接归入该文件夹
408 mutationFn: (files: FileList | File[]) => {
409 const folder = sources.data?.sources.find(
410 (s) => s.id === selection && s.kind === "folder",
411 );
412 return api.upload(kb!.id, Array.from(files), folder?.id);
413 },
414 onSuccess: invalidate,
415 });
416 const remove = useMutation({ mutationFn: (id: string) => api.deleteDocument(id), onSuccess: invalidate });
417 const extract = useMutation({ mutationFn: (id: string) => api.extractDocument(id), onSuccess: invalidate });
418 const reprocess = useMutation({
419 mutationFn: (id: string) => api.reprocessDocument(id),
420 onSuccess: invalidate,
421 });
422 // 本库角色:门控"重建图谱"入口(KB admin 起步,与 API 端一致)
423 const kbDetail = useQuery({
424 queryKey: ["kbOne", kb?.id],
425 queryFn: () => api.kbDetail(kb!.id),
426 enabled: !!kb,
427 });
428 const myRole = kbDetail.data?.my_role ?? "";
429 const canEdit = ["editor", "admin", "owner"].includes(myRole);
430 const canRebuild = ["admin", "owner"].includes(myRole);
431
432 const reExtractSource = useMutation({
433 mutationFn: (sourceId: string) => api.reExtractSource(kb!.id, sourceId),
434 onSuccess: (r) => {
435 toast.success(S.library.queuedDocs(r.queued));
436 setReExtracting(false);
437 invalidate();
438 },
439 onError: (e) => toast.error((e as Error).message),
440 });
441 const rebuildGraph = useMutation({
442 mutationFn: () => api.rebuildGraph(kb!.id),
443 onSuccess: (r) => {
444 toast.success(S.library.rebuildDone(r.entities_removed, r.facts_removed, r.queued));
445 setRebuilding(false);
446 invalidate();
447 },
448 onError: (e) => toast.error((e as Error).message),
449 });
450 const syncNow = useMutation({
451 mutationFn: (sourceId: string) => api.syncSource(kb!.id, sourceId),
452 onSuccess: invalidate,
453 });
454 const removeSource = useMutation({
455 mutationFn: (sourceId: string) => api.deleteSource(kb!.id, sourceId),
456 onSuccess: () => {
457 setSelection("all");
458 invalidate();
459 },
460 });
461 const cleanupMissing = useMutation({
462 mutationFn: (sourceId: string) => api.cleanupMissing(kb!.id, sourceId),
463 onSuccess: () => {
464 setCleaning(false);
465 invalidate();
466 },
467 });
468
469 // 只有手动语义的目的地可上传:All/Uploads/folder。拉取型来源(url/rss/api/custom)
470 // 由同步填充,手动塞文件会在下次同步时变成"来源里不存在"的孤儿
471 const canUpload =
472 selection === "all" ||
473 selection === "uploads" ||
474 sources.data?.sources.find((s) => s.id === selection)?.kind === "folder";
475
476 const onDrop = useCallback(
477 (e: React.DragEvent) => {
478 e.preventDefault();
479 setDragging(false);
480 if (!canUpload) return;
481 if (e.dataTransfer.files.length && kb) upload.mutate(e.dataTransfer.files);
482 },
483 [kb, upload, canUpload],
484 );
485
486 if (!kb) return <Loading>{S.nav.loading}</Loading>;
487
488 // 服务端已经切好了这一页:筛选、作用域、页码都在请求里
489 const pagedDocs = docs.data?.docs ?? [];
490 const totalDocs = docs.data?.total ?? 0;
491 // 整库可抽的篇数。**重建是库级动作**,不该显示当前来源的数字
492 const kbStats = useQuery({
493 queryKey: ["docCount", kb?.id],
494 queryFn: () => api.documents(kb!.id, { limit: 1, offset: 0 }),
495 enabled: !!kb,
496 });
497 const kbReady = kbStats.data?.ready ?? 0;
498 const sourceList = sources.data?.sources ?? [];
499 const selectedSource = sourceList.find((s) => s.id === selection);
500 const safePage = page;
501 const query = filter.trim().toLowerCase();
502
503 return (
504 <div className="h-full flex">
505 <SourcesRail
506 kbId={kb.id}
507 active={selection}
508 onSelect={setSelection}
509 onAdd={() => setAdding(true)}
510 />
511
512 {/* 文档区(scrollbar-gutter 常驻:视图切换时滚动条出没不再引起水平抖动) */}
513 <div
514 className="flex-1 min-w-0 overflow-y-auto u-scroll px-8 py-6 [scrollbar-gutter:stable]"
515 onDragOver={(e) => {
516 e.preventDefault();
517 if (canUpload) setDragging(true);
518 }}
519 onDragLeave={() => setDragging(false)}
520 onDrop={onDrop}
521 >
522 {/* 工作页居左:与 Review/Ontology 同规——左缘随栏起步,切页不跳 */}
523 <div className="max-w-4xl">
524 <div className="flex items-center justify-between mb-4">
525 <h1 className="u-title text-lg">
526 {selectedSource?.name ??
527 (selection === "uploads" ? S.library.uploads : S.library.title)}
528 </h1>
529 <div className="flex items-center gap-2">
530 {/* 历史视图下过滤框只藏不撤(invisible 保留占位),标题行高度不塌、不抖 */}
531 <div className={`relative ${showHistory ? "invisible" : ""}`}>
532 <Search
533 size={13}
534 className="absolute left-2.5 top-1/2 -translate-y-1/2 text-neutral-500 pointer-events-none"
535 />
536 <input
537 className="input-dark w-52 pl-8 pr-7 py-1.5 text-[13px]"
538 placeholder={S.library.filterPlaceholder}
539 value={filter}
540 onChange={(e) => setFilter(e.target.value)}
541 onKeyDown={(e) => e.key === "Escape" && setFilter("")}
542 />
543 {filter && (
544 <button
545 onClick={() => setFilter("")}
546 className="absolute right-2 top-1/2 -translate-y-1/2 text-neutral-500 hover:text-neutral-200"
547 >
548 <X size={12} />
549 </button>
550 )}
551 </div>
552 {/* 按抽取状态筛。**选项写死成那五个**,不按库里实际有的填——
553 它是一组固定的管道状态,而「这个库现在没有失败的」正是用户
554 想通过筛一下确认的事 */}
555 <select
556 className="input-dark px-2 py-1.5 text-[13px] shrink-0"
557 value={graphFilter}
558 onChange={(e) => {
559 setGraphFilter(e.target.value);
560 setPage(0);
561 }}
562 >
563 <option value="">{S.library.anyStatus}</option>
564 <option value="failed">{S.library.statusFailed}</option>
565 <option value="done">{S.library.statusDone}</option>
566 <option value="queued">{S.library.statusQueued}</option>
567 <option value="extracting">{S.library.statusExtracting}</option>
568 <option value="none">{S.library.statusNone}</option>
569 </select>
570 {/* 一键重试。**只在真有失败时出现**——没有失败的库不该看到一个
571 点了什么都不会发生的按钮。数字写在按钮上,点之前就知道会动几篇 */}
572 {(docs.data?.failed ?? 0) > 0 && canUpload && (
573 <button
574 onClick={() => retryFailed.mutate()}
575 disabled={retryFailed.isPending}
576 className="u-btn u-btn-ghost px-3 py-1.5 text-xs flex items-center gap-1.5 shrink-0"
577 >
578 <RefreshCw size={12} />
579 {S.library.retryFailed(docs.data!.failed)}
580 </button>
581 )}
582 {/* 全库重建:清算语义,仅 KB admin;放在 All documents 视图 */}
583 {selection === "all" && canRebuild && (
584 <button
585 onClick={() => setRebuilding(true)}
586 className="u-btn u-btn-ghost px-3 py-1.5 text-xs flex items-center gap-1.5 shrink-0 !text-[var(--u-danger)]"
587 >
588 <RefreshCw size={12} />
589 {S.library.rebuild}
590 </button>
591 )}
592 {canUpload && (
593 <button
594 onClick={() => fileInput.current?.click()}
595 className="u-btn u-btn-ghost px-3 py-1.5 text-xs flex items-center gap-1.5 shrink-0"
596 >
597 <Upload size={12} />
598 {S.library.upload}
599 </button>
600 )}
601 </div>
602 <input
603 ref={fileInput}
604 type="file"
605 multiple
606 hidden
607 accept=".pdf,.docx,.xlsx,.xls,.ods,.pptx,.md,.txt,.html,.htm,.csv,.tsv,.json,.yaml,.yml,.xml,.log"
608 onChange={(e) => e.target.files?.length && upload.mutate(e.target.files)}
609 />
610 </div>
611
612 {selectedSource && (
613 <SourceBar
614 kbId={kb.id}
615 source={selectedSource}
616 syncing={syncNow.isPending}
617 historyOpen={showHistory}
618 onToggleHistory={() => setShowHistory((v) => !v)}
619 onSync={() => syncNow.mutate(selectedSource.id)}
620 onEdit={() => setEditing(true)}
621 onCleanup={() => setCleaning(true)}
622 onReExtract={canEdit ? () => setReExtracting(true) : undefined}
623 onToken={() => setTokenReveal({ sourceId: selectedSource.id })}
624 />
625 )}
626
627 {/* 抽取进度。**数来自服务端**,按来源作用域算——从前是数当前页里的,
628 翻一页进度条就跳 */}
629 {(() => {
630 const pending = docs.data?.extracting ?? 0;
631 if (pending === 0) return null;
632 const total = (docs.data?.ready ?? 0) + pending;
633 const done = total - pending;
634 return (
635 <div className="mb-3 glass rounded-xl px-4 py-2.5">
636 <div className="flex items-center justify-between text-xs text-neutral-400 mb-1.5">
637 <span>{S.library.extractProgress(done, total)}</span>
638 <span className="u-num text-neutral-600">
639 {Math.round((done / Math.max(total, 1)) * 100)}%
640 </span>
641 </div>
642 <div className="h-1 rounded-full bg-white/[0.06] overflow-hidden">
643 <div
644 className="h-full bg-[var(--u-warn)] transition-[width] duration-500"
645 style={{ width: `${(done / Math.max(total, 1)) * 100}%` }}
646 />
647 </div>
648 </div>
649 );
650 })()}
651
652 {upload.isPending && (
653 <div className="mb-3 text-sm text-[var(--u-warn)]">{S.library.uploading}</div>
654 )}
655 {upload.isError && (
656 <div className="mb-3 text-sm text-rose-400">
657 {S.library.uploadFailed}: {String((upload.error as Error).message)}
658 </div>
659 )}
660
661 {showHistory && selectedSource ? (
662 <RunsPanel kbId={kb.id} sourceId={selectedSource.id} />
663 ) : (
664 <>
665 <div className={`glass rounded-2xl glass-hover ${dragging ? "u-highlight" : ""}`}>
666 {pagedDocs.length ? (
667 <table className="w-full text-sm">
668 <thead>
669 <tr className="text-left text-xs text-neutral-500 border-b border-white/10">
670 <th className="px-4 py-2.5 font-medium">{S.library.colFile}</th>
671 {selection === "all" && (
672 <th className="px-4 py-2.5 font-medium">{S.library.colSource}</th>
673 )}
674 <th className="px-4 py-2.5 font-medium">{S.library.colStatus}</th>
675 <th className="px-4 py-2.5 font-medium">{S.library.colGraph}</th>
676 <th className="px-4 py-2.5 font-medium">{S.library.colChunks}</th>
677 <th className="px-4 py-2.5 font-medium">{S.library.colSize}</th>
678 <th className="px-4 py-2.5"></th>
679 </tr>
680 </thead>
681 <tbody>
682 {pagedDocs.map((d) => (
683 <DocRow
684 key={d.id}
685 doc={d}
686 source={
687 selection === "all"
688 ? (sourceList.find((s) => s.id === d.source_id) ?? null)
689 : undefined
690 }
691 onDelete={() => remove.mutate(d.id)}
692 onExtract={() => extract.mutate(d.id)}
693 onReprocess={() => reprocess.mutate(d.id)}
694 onShowError={(kind, text) =>
695 setErrorView({ file: d.filename, kind, text })
696 }
697 drops={dropsByDoc.get(d.id)}
698 onShowDrops={(rows) => setDropsView({ file: d.filename, rows })}
699 />
700 ))}
701 </tbody>
702 </table>
703 ) : query || graphFilter ? (
704 <div className="py-20 text-center text-sm text-neutral-500">
705 {S.library.filterNoMatch}
706 </div>
707 ) : (
708 <div className="py-20 text-center text-sm text-neutral-500">
709 {canUpload ? (
710 <>
711 {S.library.dropHint}
712 <div className="mt-2 text-xs text-neutral-600">{S.library.formats}</div>
713 </>
714 ) : (
715 S.library.emptyPull
716 )}
717 </div>
718 )}
719 </div>
720
721 <Pager
722 total={totalDocs}
723 pageSize={PAGE_SIZE}
724 page={safePage}
725 onPage={setPage}
726 />
727 </>
728 )}
729 </div>
730 </div>
731
732 {adding && (
733 <SourceModal
734 kbId={kb.id}
735 onDone={(id, isApi) => {
736 setAdding(false);
737 if (id) setSelection(id);
738 // api 来源建好直接打开密钥弹窗(onboarding:端点 + 密钥一步拿全)
739 if (id && isApi) setTokenReveal({ sourceId: id });
740 invalidate();
741 }}
742 />
743 )}
744 {tokenReveal && (
745 <TokenModal
746 kbId={kb.id}
747 sourceId={tokenReveal.sourceId}
748 onClose={() => setTokenReveal(null)}
749 />
750 )}
751 {editing && selectedSource && (
752 <SourceEditModal
753 kbId={kb.id}
754 source={selectedSource}
755 onDone={() => {
756 setEditing(false);
757 invalidate();
758 }}
759 onDelete={() => {
760 setEditing(false);
761 removeSource.mutate(selectedSource.id);
762 }}
763 />
764 )}
765 {cleaning && selectedSource && (
766 <DangerConfirm
767 title={S.library.cleanupTitle}
768 hint={S.library.cleanupHint(selectedSource.missing_count, selectedSource.name)}
769 confirmLabel={S.library.cleanupConfirm}
770 cancelLabel={S.library.cancel}
771 busy={cleanupMissing.isPending}
772 onConfirm={() => cleanupMissing.mutate(selectedSource.id)}
773 onCancel={() => setCleaning(false)}
774 />
775 )}
776 {/* 来源重抽:轻确认(不毁数据,只是费时费钱),无需打字解锁 */}
777 {reExtracting && selectedSource && (
778 <DangerConfirm
779 title={S.library.reExtractTitle}
780 hint={S.library.reExtractHint(
781 docs.data?.ready ?? 0,
782 selectedSource.name,
783 )}
784 confirmLabel={S.library.reExtractConfirm}
785 cancelLabel={S.library.cancel}
786 busy={reExtractSource.isPending}
787 onConfirm={() => reExtractSource.mutate(selectedSource.id)}
788 onCancel={() => setReExtracting(false)}
789 />
790 )}
791 {errorView && (
792 <ErrorModal
793 file={errorView.file}
794 kind={errorView.kind}
795 text={errorView.text}
796 onClose={() => setErrorView(null)}
797 />
798 )}
799 {dropsView && (
800 <DropsModal
801 file={dropsView.file}
802 rows={dropsView.rows}
803 onClose={() => setDropsView(null)}
804 />
805 )}
806 {/* 全库重建:打字级确认(清空图层不可逆) */}
807 {rebuilding && (
808 <DangerConfirm
809 title={S.library.rebuildTitle}
810 hint={S.library.rebuildHint(
811 kbReady,
812 kb.name,
813 )}
814 requireText={kb.name}
815 confirmLabel={S.library.rebuildConfirm}
816 cancelLabel={S.library.cancel}
817 busy={rebuildGraph.isPending}
818 onConfirm={() => rebuildGraph.mutate()}
819 onCancel={() => setRebuilding(false)}
820 />
821 )}
822 </div>
823 );
824}
825
826/** 选中来源的状态条:同步状态 / 上次同步 / History 切换 / Sync now / 设置。 */
827function SourceBar({
828 kbId,
829 source,
830 syncing,
831 historyOpen,
832 onToggleHistory,
833 onSync,
834 onEdit,
835 onCleanup,
836 onReExtract,
837 onToken,
838}: {
839 kbId: string;
840 source: SourceView;
841 syncing: boolean;
842 historyOpen: boolean;
843 onToggleHistory: () => void;
844 onSync: () => void;
845 onEdit: () => void;
846 onCleanup: () => void;
847 /** 缺省 = 无编辑权限,不渲染重抽入口 */
848 onReExtract?: () => void;
849 onToken: () => void;
850}) {
851 const isPull = SYNCING_KINDS.has(source.kind);
852 const isApi = source.kind === "api";
853 const busy = source.last_sync_status === "running" || source.last_sync_status === "queued";
854 // 历史数据的 config 可能是 jsonb null(缺省 Value::Null 落库所致)——防御性兜底
855 const cfg = source.config ?? {};
856 const configSummary =
857 cfg.feed_url ??
858 cfg.endpoint ??
859 cfg.repo ??
860 (cfg.urls ? `${cfg.urls.length} URLs` : "");
861
862 return (
863 <div className="glass rounded-xl mb-3">
864 <div className="px-4 py-2.5 flex items-center gap-3 text-xs">
865 {/* api 与拉取型同一状态语汇:点 + 状态 + 时刻 + 产出/错误;
866 端点是一次性集成信息,放 Token 弹窗,不占常驻条 */}
867 {(isPull || isApi) && (
868 <>
869 <span
870 className={`h-1.5 w-1.5 rounded-full shrink-0 ${SYNC_DOT[source.last_sync_status]}`}
871 />
872 <span className="text-neutral-300 whitespace-nowrap shrink-0">
873 {isApi
874 ? S.library.pushStatus[source.last_sync_status]
875 : S.library.syncStatus[source.last_sync_status]}
876 </span>
877 {source.last_sync_at && (
878 <span className="text-neutral-600 u-num whitespace-nowrap shrink-0">
879 {source.last_sync_at.slice(0, 16).replace("T", " ")}
880 </span>
881 )}
882 {source.last_sync_status === "ok" && source.last_sync_added > 0 && (
883 <span className="text-[var(--u-ok)]">
884 {S.library.lastSyncAdded(source.last_sync_added)}
885 </span>
886 )}
887 {source.last_sync_error && (
888 <span className="text-rose-400 truncate min-w-0" title={source.last_sync_error}>
889 {source.last_sync_error}
890 </span>
891 )}
892 {isPull && (
893 <>
894 <span className="text-neutral-600 truncate min-w-0">{configSummary}</span>
895 <span className="text-neutral-600 shrink-0 u-num">{scheduleLabel(source)}</span>
896 </>
897 )}
898 </>
899 )}
900 {!isPull && !isApi && (
901 <span className="text-neutral-600 truncate min-w-0">
902 {S.library.sourceKindHints[source.kind as "folder"] ?? ""}
903 </span>
904 )}
905 <div className="ml-auto flex items-center gap-2 shrink-0">
906 {/* 集成型来源(custom 拉取 / api 推送):接口文档随手可达 */}
907 {(source.kind === "custom" || source.kind === "api") && (
908 <Link
909 to="/docs/$slug"
910 params={{ slug: "ingest" }}
911 target="_blank"
912 title={S.library.ingestGuideTitle}
913 className="u-btn u-btn-ghost px-2 py-1"
914 >
915 <BookOpen size={12} />
916 </Link>
917 )}
918 {source.missing_count > 0 && (
919 <button
920 onClick={onCleanup}
921 className="u-btn u-btn-ghost px-2.5 py-1 text-xs !text-[var(--u-warn)]"
922 >
923 {S.library.cleanupMissing(source.missing_count)}
924 </button>
925 )}
926 {/* History 对拉取型与 api 推送型都开放:推送失败(格式错等)也记 run */}
927 {(isPull || source.kind === "api") && (
928 /* 激活态用反色(与弹窗类型 tab、图标选中同一语汇),一眼可辨 */
929 <button
930 onClick={onToggleHistory}
931 className={`u-btn px-2.5 py-1 text-xs flex items-center gap-1.5 ${
932 historyOpen ? "u-btn-primary" : "u-btn-ghost"
933 }`}
934 >
935 <HistoryIcon size={11} />
936 {S.library.syncHistory}
937 </button>
938 )}
939 {isPull && (
940 <button
941 onClick={onSync}
942 disabled={busy || syncing}
943 className="u-btn u-btn-ghost px-2.5 py-1 text-xs flex items-center gap-1.5"
944 >
945 <RefreshCw size={11} className={busy ? "animate-spin" : ""} />
946 {S.library.syncNow}
947 </button>
948 )}
949 {source.kind === "api" && (
950 <button
951 onClick={onToken}
952 className="u-btn u-btn-ghost px-2.5 py-1 text-xs flex items-center gap-1.5"
953 >
954 <KeyRound size={11} />
955 {S.library.viewToken}
956 </button>
957 )}
958 {/* 全量重抽本来源:所有类型都给(有文档就能重抽) */}
959 {onReExtract && source.doc_count > 0 && (
960 <button
961 onClick={onReExtract}
962 className="u-btn u-btn-ghost px-2.5 py-1 text-xs flex items-center gap-1.5"
963 >
964 <Waypoints size={11} />
965 {S.library.reExtractSource}
966 </button>
967 )}
968 <button
969 onClick={onEdit}
970 title={S.library.sourceSettings}
971 className="u-btn u-btn-ghost px-2 py-1"
972 >
973 <SettingsIcon size={12} />
974 </button>
975 </div>
976 </div>
977 </div>
978 );
979}
980
981/** 失败详情:完整原文,可复制。tooltip 装不下也拷不走,所以要弹窗。 */
982/** 抽取丢弃详情:抽出来了、被挡掉了,这里说清楚挡在哪、丢了多少。 */
983function DropsModal({
984 file,
985 rows,
986 onClose,
987}: {
988 file: string;
989 rows: ExtractionDrop[];
990 onClose: () => void;
991}) {
992 useEffect(() => {
993 const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();
994 document.addEventListener("keydown", onKey);
995 return () => document.removeEventListener("keydown", onKey);
996 }, [onClose]);
997
998 return (
999 <div
1000 className="fixed inset-0 z-50 grid place-items-center bg-black/60 backdrop-blur-sm"
1001 onMouseDown={(e) => {
1002 if (e.target === e.currentTarget) onClose();
1003 }}
1004 >
1005 <div className="glass-strong w-[36rem] max-w-[calc(100vw-2rem)] rounded-2xl shadow-2xl">
1006 <div className="px-5 pt-4 pb-3 border-b border-white/10">
1007 <div className="flex items-center justify-between">
1008 <h2 className="u-title text-[15px]">{S.library.dropsTitle}</h2>
1009 <button onClick={onClose} className="text-neutral-500 hover:text-neutral-200">
1010 <X size={15} />
1011 </button>
1012 </div>
1013 <p className="mt-1 text-xs text-neutral-500 truncate" title={file}>
1014 {file}
1015 </p>
1016 <p className="mt-1.5 text-xs text-neutral-500">{S.library.dropsNote}</p>
1017 </div>
1018 <div className="u-scroll max-h-80 overflow-y-auto px-5 py-3">
1019 {rows.map((r) => (
1020 <div
1021 key={`${r.reason}:${r.detail}`}
1022 className="border-b border-white/5 py-2.5 last:border-0"
1023 >
1024 <div className="flex items-baseline gap-2">
1025 <span className="text-sm text-neutral-200">
1026 {S.library.dropReason[r.reason] ?? r.reason}
1027 </span>
1028 <span className="u-num ml-auto text-xs text-neutral-500">×{r.count}</span>
1029 </div>
1030 <div className="mt-0.5 font-mono text-[11px] text-neutral-400 break-all">
1031 {r.detail}
1032 </div>
1033 {r.example && (
1034 <div className="mt-0.5 text-[11px] text-neutral-600 break-all">
1035 {S.library.dropsExample} {r.example}
1036 </div>
1037 )}
1038 </div>
1039 ))}
1040 </div>
1041 </div>
1042 </div>
1043 );
1044}
1045
1046function ErrorModal({
1047 file,
1048 kind,
1049 text,
1050 onClose,
1051}: {
1052 file: string;
1053 kind: string;
1054 text: string;
1055 onClose: () => void;
1056}) {
1057 useEffect(() => {
1058 const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();
1059 document.addEventListener("keydown", onKey);
1060 return () => document.removeEventListener("keydown", onKey);
1061 }, [onClose]);
1062
1063 return (
1064 <div
1065 className="fixed inset-0 z-50 grid place-items-center bg-black/60 backdrop-blur-sm"
1066 onMouseDown={(e) => {
1067 if (e.target === e.currentTarget) onClose();
1068 }}
1069 >
1070 <div className="glass-strong w-[36rem] max-w-[calc(100vw-2rem)] rounded-2xl shadow-2xl">
1071 <div className="px-5 pt-4 pb-3 border-b border-white/10">
1072 <div className="flex items-center justify-between">
1073 <h2 className="u-title text-[15px]">{S.library.errorTitle}</h2>
1074 <button onClick={onClose} className="text-neutral-500 hover:text-neutral-200">
1075 <X size={15} />
1076 </button>
1077 </div>
1078 <p className="mt-1 text-xs text-neutral-500 truncate" title={file}>
1079 {file} · {kind}
1080 </p>
1081 </div>
1082 <div className="px-5 py-4">
1083 <pre className="u-scroll max-h-72 overflow-auto rounded-lg border border-white/10 bg-white/[0.03] p-3 text-[12px] leading-relaxed text-neutral-300 whitespace-pre-wrap break-words">
1084 {text}
1085 </pre>
1086 </div>
1087 <div className="flex justify-end gap-2 px-5 py-3 border-t border-white/10">
1088 <button
1089 className="u-btn u-btn-ghost px-3.5 py-1.5 text-xs"
1090 onClick={() =>
1091 navigator.clipboard
1092 .writeText(text)
1093 .then(() => toast.success(S.library.errorCopied))
1094 .catch(() => {})
1095 }
1096 >
1097 {S.library.copyError}
1098 </button>
1099 <button className="u-btn u-btn-primary px-3.5 py-1.5 text-xs" onClick={onClose}>
1100 {S.library.close}
1101 </button>
1102 </div>
1103 </div>
1104 </div>
1105 );
1106}
1107
1108/** api 来源密钥:随时可查(Editor 专用端点),内置轮换。 */
1109function TokenModal({
1110 kbId,
1111 sourceId,
1112 onClose,
1113}: {
1114 kbId: string;
1115 sourceId: string;
1116 onClose: () => void;
1117}) {
1118 const queryClient = useQueryClient();
1119 const tokenQuery = useQuery({
1120 queryKey: ["sourceToken", kbId, sourceId],
1121 queryFn: () => api.sourceToken(kbId, sourceId),
1122 });
1123 const rotate = useMutation({
1124 mutationFn: () => api.rotateSourceToken(kbId, sourceId),
1125 onSuccess: (r) => {
1126 queryClient.setQueryData(["sourceToken", kbId, sourceId], { ingest_token: r.ingest_token });
1127 toast.success(S.toast.saved);
1128 },
1129 onError: (e) => toast.error((e as Error).message),
1130 });
1131 const token = tokenQuery.data?.ingest_token ?? null;
1132
1133 const copy = (text: string, msg: string) =>
1134 navigator.clipboard.writeText(text).then(() => toast.success(msg)).catch(() => {});
1135 const endpoint = `${location.origin}/api/v1/sources/${sourceId}/ingest`;
1136 return (
1137 <div
1138 className="fixed inset-0 z-50 grid place-items-center bg-black/60 backdrop-blur-sm"
1139 onMouseDown={(e) => {
1140 if (e.target === e.currentTarget) onClose();
1141 }}
1142 >
1143 <div className="glass-strong w-[32rem] max-w-[calc(100vw-2rem)] rounded-2xl shadow-2xl">
1144 <div className="flex items-center justify-between px-5 pt-4 pb-3 border-b border-white/10">
1145 <h2 className="u-title text-[15px] flex items-center gap-2">
1146 <KeyRound size={14} className="text-neutral-400" />
1147 {S.library.tokenTitle}
1148 </h2>
1149 <button onClick={onClose} className="text-neutral-500 hover:text-neutral-200">
1150 <X size={15} />
1151 </button>
1152 </div>
1153 <div className="px-5 py-4 space-y-3">
1154 {tokenQuery.isPending ? (
1155 <p className="text-sm text-neutral-500">{S.nav.loading}</p>
1156 ) : token ? (
1157 <>
1158 <button
1159 onClick={() => copy(token, S.library.tokenCopied)}
1160 title={S.library.copyEndpoint}
1161 className="w-full text-left font-mono text-[12.5px] text-neutral-200 bg-white/[0.05] border border-white/10 hover:border-white/25 rounded-lg px-3 py-2.5 break-all transition-colors"
1162 >
1163 {token}
1164 </button>
1165 <p className="text-[11px] leading-relaxed text-neutral-500">
1166 {S.library.tokenWarning}
1167 </p>
1168 <div>
1169 <p className="mb-1 text-[11px] text-neutral-500">{S.library.tokenUsage}</p>
1170 <button
1171 onClick={() => copy(endpoint, S.library.endpointCopied)}
1172 title={S.library.copyEndpoint}
1173 className="w-full text-left font-mono text-[11.5px] text-neutral-400 hover:text-neutral-200 bg-white/[0.03] border border-white/10 rounded-lg px-3 py-2 break-all transition-colors"
1174 >
1175 POST {endpoint}
1176 {"\n"}Authorization: Bearer &lt;token&gt;
1177 </button>
1178 </div>
1179 </>
1180 ) : (
1181 <p className="text-sm text-neutral-500">{S.library.noToken}</p>
1182 )}
1183 </div>
1184 <div className="flex justify-end gap-2 px-5 py-3 border-t border-white/10">
1185 <button
1186 className="u-btn u-btn-ghost px-3.5 py-1.5 text-xs flex items-center gap-1.5"
1187 disabled={rotate.isPending || tokenQuery.isPending}
1188 onClick={() => rotate.mutate()}
1189 >
1190 <RefreshCw size={11} className={rotate.isPending ? "animate-spin" : ""} />
1191 {token ? S.library.rotateToken : S.library.generateToken}
1192 </button>
1193 <button className="u-btn u-btn-primary px-3.5 py-1.5 text-xs" onClick={onClose}>
1194 {S.library.close}
1195 </button>
1196 </div>
1197 </div>
1198 </div>
1199 );
1200}
1201
1202/** History 视图:占据文件列表位置的同步运行记录(再点 History 切回)。 */
1203function RunsPanel({ kbId, sourceId }: { kbId: string; sourceId: string }) {
1204 const runs = useQuery({
1205 queryKey: ["sourceRuns", kbId, sourceId],
1206 queryFn: () => api.sourceRuns(kbId, sourceId),
1207 });
1208 const list = runs.data?.runs ?? [];
1209
1210 return (
1211 <div className="glass rounded-2xl">
1212 {runs.isLoading ? (
1213 <div className="py-20 text-center text-sm text-neutral-500">{S.nav.loading}</div>
1214 ) : list.length === 0 ? (
1215 <div className="py-20 text-center text-sm text-neutral-500">{S.library.noRuns}</div>
1216 ) : (
1217 <div className="px-4 py-2">
1218 {list.map((r) => (
1219 <div
1220 key={r.id}
1221 className="flex items-center gap-3 py-2 text-xs border-b border-white/5 last:border-0"
1222 >
1223 <span
1224 className={`h-1.5 w-1.5 rounded-full shrink-0 ${
1225 r.status === "ok"
1226 ? "bg-[var(--u-ok)]"
1227 : r.status === "failed"
1228 ? "bg-[var(--u-danger)]"
1229 : "bg-[var(--u-warn)] animate-pulse"
1230 }`}
1231 />
1232 <span className="u-num text-neutral-400 whitespace-nowrap shrink-0">
1233 {r.started_at.slice(0, 16).replace("T", " ")}
1234 </span>
1235 <span className="text-neutral-500 whitespace-nowrap shrink-0">
1236 {r.created_docs > 0 && S.library.runNew(r.created_docs)}
1237 {r.created_docs > 0 && r.updated_docs > 0 && " · "}
1238 {r.updated_docs > 0 && S.library.runUpdated(r.updated_docs)}
1239 {r.status === "ok" && r.created_docs === 0 && r.updated_docs === 0 && (
1240 <span className="text-neutral-600">{S.library.runNothing}</span>
1241 )}
1242 </span>
1243 {r.error && (
1244 <span className="text-rose-400 truncate min-w-0" title={r.error}>
1245 {r.error}
1246 </span>
1247 )}
1248 </div>
1249 ))}
1250 </div>
1251 )}
1252 </div>
1253 );
1254}
1255
1256/** 新建来源弹窗:类型 → 名称/图标 → 类型专属配置 → 同步周期。 */
1257function SourceModal({
1258 kbId,
1259 onDone,
1260}: {
1261 kbId: string;
1262 /** isApi=true 时父级紧接着打开密钥弹窗 */
1263 onDone: (id?: string, isApi?: boolean) => void;
1264}) {
1265 const [kind, setKind] = useState<
1266 | "folder"
1267 | "url"
1268 | "rss"
1269 | "custom"
1270 | "api"
1271 | "github_issues"
1272 | "jira_issues"
1273 >("folder");
1274 const [name, setName] = useState("");
1275 const [icon, setIcon] = useState<string | null>(null);
1276 const [urls, setUrls] = useState("");
1277 const [feedUrl, setFeedUrl] = useState("");
1278 const [endpoint, setEndpoint] = useState("");
1279 const [authHeader, setAuthHeader] = useState("");
1280 const [repo, setRepo] = useState("");
1281 const [jiraUrl, setJiraUrl] = useState("");
1282 const [jiraProject, setJiraProject] = useState("");
1283 // PR 在 GitHub 的模型里也是工单。默认不收——问「工单」要的是工单;
1284 // 但有些仓库的决策记录实际写在 PR 描述里,所以给个开关
1285 const [includePrs, setIncludePrs] = useState(false);
1286 const [schedule, setSchedule] = useState<ScheduleValue>({
1287 sync_interval_minutes: null,
1288 sync_cron: null,
1289 });
1290 // folder = 纯容器、api = 推送型:都没有同步日程
1291 const syncing =
1292 kind === "url" ||
1293 kind === "rss" ||
1294 kind === "custom" ||
1295 kind === "github_issues" ||
1296 kind === "jira_issues";
1297
1298 const create = useMutation({
1299 mutationFn: () => {
1300 const config =
1301 kind === "url"
1302 ? { urls: urls.split("\n").map((u) => u.trim()).filter(Boolean) }
1303 : kind === "rss"
1304 ? { feed_url: feedUrl.trim() }
1305 : kind === "custom"
1306 ? {
1307 endpoint: endpoint.trim(),
1308 ...(authHeader.trim() ? { auth_header: authHeader.trim() } : {}),
1309 }
1310 : kind === "github_issues"
1311 ? {
1312 repo: repo.trim(),
1313 ...(authHeader.trim() ? { auth_header: authHeader.trim() } : {}),
1314 ...(includePrs ? { include_pull_requests: true } : {}),
1315 }
1316 : kind === "jira_issues"
1317 ? {
1318 base_url: jiraUrl.trim(),
1319 project: jiraProject.trim(),
1320 ...(authHeader.trim() ? { auth_header: authHeader.trim() } : {}),
1321 }
1322 : {};
1323 return api.createSource(kbId, {
1324 kind,
1325 name: name.trim(),
1326 config,
1327 // 内置类型图标固定,只有 custom 允许自选
1328 icon: kind === "custom" ? icon : null,
1329 // folder/api 无同步语义:日程强制留空
1330 ...(syncing ? schedule : { sync_interval_minutes: null, sync_cron: null }),
1331 });
1332 },
1333 onSuccess: (data) => onDone(data.source.id, kind === "api"),
1334 });
1335
1336 const valid =
1337 name.trim() &&
1338 (kind === "url"
1339 ? urls.trim()
1340 : kind === "rss"
1341 ? feedUrl.trim()
1342 : kind === "custom"
1343 ? endpoint.trim()
1344 : true);
1345
1346 // 注意用 div 而非 label:label 会把 :hover/click 转发给内部第一个可标记控件
1347 //(button 也算),导致图标网格/日程选择器悬停时第一个按钮常亮
1348 const field = (label: string, node: React.ReactNode) => (
1349 <div className="mb-3">
1350 <div className="mb-1 text-[11px] font-medium text-neutral-500">{label}</div>
1351 {node}
1352 </div>
1353 );
1354
1355 return (
1356 <div
1357 className="fixed inset-0 z-50 grid place-items-center bg-black/60 backdrop-blur-sm"
1358 onMouseDown={(e) => {
1359 if (e.target === e.currentTarget) onDone();
1360 }}
1361 >
1362 <div className="glass-strong w-[30rem] max-w-[calc(100vw-2rem)] max-h-[calc(100vh-4rem)] overflow-y-auto u-scroll rounded-2xl shadow-2xl">
1363 <div className="flex items-center justify-between px-5 pt-4 pb-3 border-b border-white/10">
1364 <h2 className="u-title text-[15px]">{S.library.newSourceTitle}</h2>
1365 <button onClick={() => onDone()} className="text-neutral-500 hover:text-neutral-200">
1366 <X size={15} />
1367 </button>
1368 </div>
1369
1370 <div className="px-5 py-4">
1371 {/* 类型 */}
1372 <div className="flex gap-2 mb-2">
1373 {(
1374 [
1375 "folder",
1376 "url",
1377 "rss",
1378 "github_issues",
1379 "jira_issues",
1380 "api",
1381 "custom",
1382 ] as const
1383 ).map((k) => {
1384 const Icon = KIND_ICON[k];
1385 return (
1386 <button
1387 key={k}
1388 onClick={() => setKind(k)}
1389 className={`u-btn flex-1 px-3 py-2 text-xs flex items-center justify-center gap-1.5 ${
1390 kind === k ? "u-btn-primary" : "u-btn-ghost"
1391 }`}
1392 >
1393 <Icon size={12} />
1394 {S.library.sourceKinds[k]}
1395 </button>
1396 );
1397 })}
1398 </div>
1399 {/* 类型自解释:一行说明;接口细节移入内置文档,弹窗只留链接 */}
1400 <p className="mb-4 text-[11px] leading-relaxed text-neutral-500">
1401 {S.library.sourceKindHints[kind]}
1402 {kind === "custom" && (
1403 <>
1404 {" "}
1405 <Link
1406 to="/docs/$slug"
1407 params={{ slug: "ingest" }}
1408 target="_blank"
1409 className="u-link"
1410 >
1411 {S.library.ingestGuide}
1412 </Link>
1413 </>
1414 )}
1415 </p>
1416
1417 {field(
1418 S.library.sourceName,
1419 <input
1420 className="input-dark w-full px-3 py-2 text-sm"
1421 value={name}
1422 onChange={(e) => setName(e.target.value)}
1423 autoFocus
1424 />,
1425 )}
1426
1427 {/* 内置类型图标固定;只有 custom 开放图标选择 */}
1428 {kind === "custom" &&
1429 field(
1430 S.library.iconLabel,
1431 <div className="grid grid-cols-10 gap-1">
1432 {Object.entries(SOURCE_ICONS).map(([key, Icon]) => (
1433 <button
1434 key={key}
1435 onClick={() => setIcon(icon === key ? null : key)}
1436 title={key}
1437 className={`h-8 grid place-items-center rounded-lg transition-colors ${
1438 icon === key
1439 ? "bg-white text-black"
1440 : "text-neutral-400 hover:bg-white/[0.07] hover:text-neutral-200"
1441 }`}
1442 >
1443 <Icon size={14} />
1444 </button>
1445 ))}
1446 </div>,
1447 )}
1448
1449 {kind === "custom" && (
1450 <>
1451 {field(
1452 S.library.endpointField,
1453 <input
1454 className="input-dark w-full px-3 py-2 text-sm font-mono"
1455 placeholder="https://your-service/utopia-feed"
1456 value={endpoint}
1457 onChange={(e) => setEndpoint(e.target.value)}
1458 />,
1459 )}
1460 {field(
1461 S.library.authHeaderField,
1462 <input
1463 className="input-dark w-full px-3 py-2 text-sm font-mono"
1464 type="password"
1465 placeholder="Bearer sk-…"
1466 value={authHeader}
1467 onChange={(e) => setAuthHeader(e.target.value)}
1468 />,
1469 )}
1470 </>
1471 )}
1472
1473 {kind === "url" &&
1474 field(
1475 S.library.urlsField,
1476 <textarea
1477 className="input-dark w-full px-3 py-2 text-sm font-mono h-20 resize-y"
1478 value={urls}
1479 onChange={(e) => setUrls(e.target.value)}
1480 />,
1481 )}
1482 {kind === "rss" &&
1483 field(
1484 S.library.feedUrl,
1485 <input
1486 className="input-dark w-full px-3 py-2 text-sm font-mono"
1487 value={feedUrl}
1488 onChange={(e) => setFeedUrl(e.target.value)}
1489 />,
1490 )}
1491 {kind === "jira_issues" && (
1492 <>
1493 {field(
1494 S.library.jiraUrlField,
1495 <input
1496 className="input-dark w-full px-3 py-2 text-sm font-mono"
1497 placeholder="https://jira.example.com"
1498 value={jiraUrl}
1499 onChange={(e) => setJiraUrl(e.target.value)}
1500 />,
1501 )}
1502 {field(
1503 S.library.jiraProjectField,
1504 <input
1505 className="input-dark w-full px-3 py-2 text-sm font-mono"
1506 placeholder="KAFKA"
1507 value={jiraProject}
1508 onChange={(e) => setJiraProject(e.target.value)}
1509 />,
1510 )}
1511 {field(
1512 S.library.tokenField,
1513 <input
1514 className="input-dark w-full px-3 py-2 text-sm font-mono"
1515 type="password"
1516 placeholder="Basic dXNlcjp0b2tlbg=="
1517 value={authHeader}
1518 onChange={(e) => setAuthHeader(e.target.value)}
1519 />,
1520 )}
1521 </>
1522 )}
1523 {kind === "github_issues" && (
1524 <>
1525 {field(
1526 S.library.repoField,
1527 <input
1528 className="input-dark w-full px-3 py-2 text-sm font-mono"
1529 placeholder="owner/name"
1530 value={repo}
1531 onChange={(e) => setRepo(e.target.value)}
1532 />,
1533 )}
1534 {field(
1535 S.library.tokenField,
1536 <input
1537 className="input-dark w-full px-3 py-2 text-sm font-mono"
1538 type="password"
1539 placeholder="Bearer ghp_…"
1540 value={authHeader}
1541 onChange={(e) => setAuthHeader(e.target.value)}
1542 />,
1543 )}
1544 <label className="mb-4 flex items-center gap-2 text-[11px] text-neutral-400">
1545 <input
1546 type="checkbox"
1547 checked={includePrs}
1548 onChange={(e) => setIncludePrs(e.target.checked)}
1549 />
1550 {S.library.includePullRequests}
1551 </label>
1552 </>
1553 )}
1554
1555 {syncing && field(S.library.interval, <SchedulePicker onChange={setSchedule} />)}
1556
1557 {create.isError && (
1558 <p className="text-xs text-rose-400 mb-2">{(create.error as Error).message}</p>
1559 )}
1560 </div>
1561
1562 <div className="flex justify-end gap-2 px-5 py-3 border-t border-white/10">
1563 <button className="u-btn u-btn-ghost px-3.5 py-1.5 text-xs" onClick={() => onDone()}>
1564 {S.library.cancel}
1565 </button>
1566 <button
1567 className="u-btn u-btn-primary px-3.5 py-1.5 text-xs"
1568 disabled={!valid || create.isPending}
1569 onClick={() => create.mutate()}
1570 >
1571 {S.library.createSource}
1572 </button>
1573 </div>
1574 </div>
1575 </div>
1576 );
1577}
1578
1579/** 来源设置弹窗:改名/图标(仅 custom)/摄取配置/日程;类型不可改;底部 danger zone。 */
1580function SourceEditModal({
1581 kbId,
1582 source,
1583 onDone,
1584 onDelete,
1585}: {
1586 kbId: string;
1587 source: SourceView;
1588 onDone: () => void;
1589 onDelete: () => void;
1590}) {
1591 const kind = source.kind;
1592 const cfg = source.config ?? {};
1593 const [name, setName] = useState(source.name);
1594 const [icon, setIcon] = useState<string | null>(source.icon);
1595 const [urls, setUrls] = useState((cfg.urls ?? []).join("\n"));
1596 const [feedUrl, setFeedUrl] = useState(cfg.feed_url ?? "");
1597 const [endpoint, setEndpoint] = useState(cfg.endpoint ?? "");
1598 const [authHeader, setAuthHeader] = useState("");
1599 const [repo, setRepo] = useState(cfg.repo ?? "");
1600 const [includePrs, setIncludePrs] = useState(Boolean(cfg.include_pull_requests));
1601 const [confirmingDelete, setConfirmingDelete] = useState(false);
1602 const [schedule, setSchedule] = useState<ScheduleValue>({
1603 sync_interval_minutes: source.sync_interval_minutes,
1604 sync_cron: source.sync_cron,
1605 });
1606 const syncing = SYNCING_KINDS.has(kind);
1607 const KindIcon = KIND_ICON[kind as keyof typeof KIND_ICON] ?? Upload;
1608
1609 // 摄取配置是否有改动——有则展示"旧文档去留"说明
1610 const ingestChanged =
1611 (kind === "url" && urls.trim() !== (cfg.urls ?? []).join("\n").trim()) ||
1612 (kind === "rss" && feedUrl.trim() !== (cfg.feed_url ?? "")) ||
1613 (kind === "custom" && endpoint.trim() !== (cfg.endpoint ?? "")) ||
1614 // 换仓库或改收不收 PR,两者都会换掉这个来源里文档的集合
1615 (kind === "github_issues" &&
1616 (repo.trim() !== (cfg.repo ?? "") ||
1617 includePrs !== Boolean(cfg.include_pull_requests)));
1618
1619 const save = useMutation({
1620 mutationFn: () => {
1621 const config =
1622 kind === "url"
1623 ? { urls: urls.split("\n").map((u) => u.trim()).filter(Boolean) }
1624 : kind === "rss"
1625 ? { feed_url: feedUrl.trim() }
1626 : kind === "custom"
1627 ? {
1628 endpoint: endpoint.trim(),
1629 // 留空 = 后端保留库里原值(凭据只进不出)
1630 ...(authHeader.trim() ? { auth_header: authHeader.trim() } : {}),
1631 }
1632 : kind === "github_issues"
1633 ? {
1634 repo: repo.trim(),
1635 // 留空 = 后端保留库里原值(凭据只进不出)
1636 ...(authHeader.trim() ? { auth_header: authHeader.trim() } : {}),
1637 include_pull_requests: includePrs,
1638 }
1639 : undefined;
1640 return api.updateSource(kbId, source.id, {
1641 name: name.trim(),
1642 ...(kind === "custom" && icon ? { icon } : {}),
1643 ...(config ? { config } : {}),
1644 ...(syncing ? { schedule } : {}),
1645 });
1646 },
1647 onSuccess: () => onDone(),
1648 });
1649
1650 const valid =
1651 name.trim() &&
1652 (kind === "url"
1653 ? urls.trim()
1654 : kind === "rss"
1655 ? feedUrl.trim()
1656 : kind === "custom"
1657 ? endpoint.trim()
1658 : true);
1659
1660 // div 而非 label:label 会把 :hover/click 转发给第一个可标记控件
1661 const field = (label: string, node: React.ReactNode) => (
1662 <div className="mb-3">
1663 <div className="mb-1 text-[11px] font-medium text-neutral-500">{label}</div>
1664 {node}
1665 </div>
1666 );
1667
1668 return (
1669 <div
1670 className="fixed inset-0 z-50 grid place-items-center bg-black/60 backdrop-blur-sm"
1671 onMouseDown={(e) => {
1672 if (e.target === e.currentTarget) onDone();
1673 }}
1674 >
1675 <div className="glass-strong w-[30rem] max-w-[calc(100vw-2rem)] max-h-[calc(100vh-4rem)] overflow-y-auto u-scroll rounded-2xl shadow-2xl">
1676 <div className="flex items-center justify-between px-5 pt-4 pb-3 border-b border-white/10">
1677 <h2 className="u-title text-[15px]">{S.library.editSourceTitle}</h2>
1678 <button onClick={onDone} className="text-neutral-500 hover:text-neutral-200">
1679 <X size={15} />
1680 </button>
1681 </div>
1682
1683 <div className="px-5 py-4">
1684 {/* 类型只读:换类型 = 换身份,应新建来源 */}
1685 <div className="mb-4 flex items-center gap-2 text-xs text-neutral-400">
1686 <KindIcon size={13} className="text-neutral-500" />
1687 {S.library.sourceKinds[kind as keyof typeof S.library.sourceKinds] ?? kind}
1688 </div>
1689
1690 {field(
1691 S.library.sourceName,
1692 <input
1693 className="input-dark w-full px-3 py-2 text-sm"
1694 value={name}
1695 onChange={(e) => setName(e.target.value)}
1696 />,
1697 )}
1698
1699 {kind === "custom" &&
1700 field(
1701 S.library.iconLabel,
1702 <div className="grid grid-cols-10 gap-1">
1703 {Object.entries(SOURCE_ICONS).map(([key, Icon]) => (
1704 <button
1705 key={key}
1706 onClick={() => setIcon(icon === key ? null : key)}
1707 title={key}
1708 className={`h-8 grid place-items-center rounded-lg transition-colors ${
1709 icon === key
1710 ? "bg-white text-black"
1711 : "text-neutral-400 hover:bg-white/[0.07] hover:text-neutral-200"
1712 }`}
1713 >
1714 <Icon size={14} />
1715 </button>
1716 ))}
1717 </div>,
1718 )}
1719
1720 {kind === "url" &&
1721 field(
1722 S.library.urlsField,
1723 <textarea
1724 className="input-dark w-full px-3 py-2 text-sm font-mono h-20 resize-y"
1725 value={urls}
1726 onChange={(e) => setUrls(e.target.value)}
1727 />,
1728 )}
1729 {kind === "rss" &&
1730 field(
1731 S.library.feedUrl,
1732 <input
1733 className="input-dark w-full px-3 py-2 text-sm font-mono"
1734 value={feedUrl}
1735 onChange={(e) => setFeedUrl(e.target.value)}
1736 />,
1737 )}
1738 {kind === "github_issues" && (
1739 <>
1740 {field(
1741 S.library.repoField,
1742 <input
1743 className="input-dark w-full px-3 py-2 text-sm font-mono"
1744 placeholder="owner/name"
1745 value={repo}
1746 onChange={(e) => setRepo(e.target.value)}
1747 />,
1748 )}
1749 {field(
1750 S.library.tokenField,
1751 <input
1752 className="input-dark w-full px-3 py-2 text-sm font-mono"
1753 type="password"
1754 placeholder="Bearer ghp_…"
1755 value={authHeader}
1756 onChange={(e) => setAuthHeader(e.target.value)}
1757 />,
1758 )}
1759 <label className="mb-4 flex items-center gap-2 text-[11px] text-neutral-400">
1760 <input
1761 type="checkbox"
1762 checked={includePrs}
1763 onChange={(e) => setIncludePrs(e.target.checked)}
1764 />
1765 {S.library.includePullRequests}
1766 </label>
1767 </>
1768 )}
1769 {kind === "custom" && (
1770 <>
1771 {field(
1772 S.library.endpointField,
1773 <input
1774 className="input-dark w-full px-3 py-2 text-sm font-mono"
1775 value={endpoint}
1776 onChange={(e) => setEndpoint(e.target.value)}
1777 />,
1778 )}
1779 {field(
1780 S.library.authHeaderEditField,
1781 <input
1782 className="input-dark w-full px-3 py-2 text-sm font-mono"
1783 type="password"
1784 placeholder={S.library.authKeepHint}
1785 value={authHeader}
1786 onChange={(e) => setAuthHeader(e.target.value)}
1787 />,
1788 )}
1789 </>
1790 )}
1791
1792 {ingestChanged && (
1793 <p className="mb-3 text-[11px] leading-relaxed text-neutral-500">
1794 {S.library.editKeepNote}
1795 </p>
1796 )}
1797
1798 {syncing &&
1799 field(
1800 S.library.interval,
1801 <SchedulePicker
1802 initial={{
1803 sync_interval_minutes: source.sync_interval_minutes,
1804 sync_cron: source.sync_cron,
1805 }}
1806 onChange={setSchedule}
1807 />,
1808 )}
1809
1810 {save.isError && (
1811 <p className="text-xs text-rose-400 mb-2">{(save.error as Error).message}</p>
1812 )}
1813
1814 {/* Danger zone:删除来源(文档保留,落回 Uploads) */}
1815 <div className="mt-4 pt-3 border-t border-white/10">
1816 <div className="mb-1 text-[11px] font-medium text-neutral-500">
1817 {S.library.dangerZone}
1818 </div>
1819 <div className="flex items-center justify-between gap-3">
1820 <span className="text-[11px] text-neutral-600">{S.library.deleteSourceHint}</span>
1821 <button
1822 onClick={() => setConfirmingDelete(true)}
1823 className="u-btn px-3.5 py-1.5 text-xs font-semibold shrink-0"
1824 style={{ background: "var(--u-danger-solid)", color: "#ffffff" }}
1825 >
1826 {S.library.deleteSource}
1827 </button>
1828 </div>
1829 </div>
1830 </div>
1831
1832 <div className="flex justify-end gap-2 px-5 py-3 border-t border-white/10">
1833 <button className="u-btn u-btn-ghost px-3.5 py-1.5 text-xs" onClick={onDone}>
1834 {S.library.cancel}
1835 </button>
1836 <button
1837 className="u-btn u-btn-primary px-3.5 py-1.5 text-xs"
1838 disabled={!valid || save.isPending}
1839 onClick={() => save.mutate()}
1840 >
1841 {S.library.saveChanges}
1842 </button>
1843 </div>
1844 </div>
1845
1846 {confirmingDelete && (
1847 <DangerConfirm
1848 title={S.library.deleteSourceTitle}
1849 hint={S.library.deleteSourceBody(source.name)}
1850 requireText={source.name}
1851 confirmLabel={S.library.deleteSource}
1852 cancelLabel={S.library.cancel}
1853 onConfirm={onDelete}
1854 onCancel={() => setConfirmingDelete(false)}
1855 />
1856 )}
1857 </div>
1858 );
1859}
1860
1861function DocRow({
1862 doc,
1863 source,
1864 onDelete,
1865 onExtract,
1866 onReprocess,
1867 onShowError,
1868 drops,
1869 onShowDrops,
1870}: {
1871 doc: Doc;
1872 /** undefined = 不渲染来源列;null = Uploads(source_id 为空) */
1873 source?: SourceView | null;
1874 onDelete: () => void;
1875 onExtract: () => void;
1876 onReprocess: () => void;
1877 onShowError: (kind: string, text: string) => void;
1878 /** 这篇文档抽出来却没落地的事实;undefined = 一条都没有 */
1879 drops?: ExtractionDrop[];
1880 onShowDrops: (rows: ExtractionDrop[]) => void;
1881}) {
1882 const kbId = useKbId();
1883 const dropTotal = drops?.reduce((n, d) => n + d.count, 0) ?? 0;
1884 const statusText =
1885 S.library.status[doc.status as keyof typeof S.library.status] ?? doc.status;
1886 const graphText =
1887 S.library.graphStatus[doc.graph_status as keyof typeof S.library.graphStatus] ??
1888 doc.graph_status;
1889 const SrcIcon = source ? sourceIcon(source) : Upload;
1890 return (
1891 <tr className="border-b border-white/5 hover:bg-white/[0.03]">
1892 <td className="px-4 py-2.5 max-w-xs truncate" title={doc.filename}>
1893 <Link
1894 to="/kb/$kbId/doc/$docId"
1895 params={{ kbId, docId: doc.id }}
1896 search={{}}
1897 className="text-neutral-200 hover:text-[var(--u-accent)]"
1898 >
1899 {doc.filename}
1900 </Link>
1901 </td>
1902 {source !== undefined && (
1903 <td className="px-4 py-2.5">
1904 <span className="flex items-center gap-1.5 text-xs text-neutral-400">
1905 <SrcIcon size={12} className="shrink-0 text-neutral-500" />
1906 <span className="truncate max-w-28">{source?.name ?? S.library.uploads}</span>
1907 </span>
1908 </td>
1909 )}
1910 <td className="px-4 py-2.5">
1911 {/* 失败可点开看原文:tooltip 会截断、也没法复制 */}
1912 {doc.status === "failed" && doc.error ? (
1913 <button
1914 onClick={() => onShowError(S.library.errorParse, doc.error!)}
1915 className="align-middle"
1916 >
1917 <Chip tone="danger">{statusText}</Chip>
1918 </button>
1919 ) : (
1920 <Chip tone={STATUS_TONE[doc.status] ?? "neutral"}>{statusText}</Chip>
1921 )}
1922 {/* 解析管道失败:重跑 解析→索引→嵌入(解析器升级/瞬时故障重试) */}
1923 {doc.status === "failed" && (
1924 <button onClick={onReprocess} className="u-link ml-1.5 text-xs">
1925 {S.library.reprocess}
1926 </button>
1927 )}
1928 {doc.missing_since && (
1929 <span className="ml-1.5 inline-block" title={doc.missing_since.slice(0, 16).replace("T", " ")}>
1930 <Chip tone="neutral">{S.library.notInSource}</Chip>
1931 </span>
1932 )}
1933 </td>
1934 <td className="px-4 py-2.5">
1935 {doc.graph_status === "none" ? (
1936 <span className="text-xs text-neutral-600">{graphText}</span>
1937 ) : doc.graph_status === "failed" && doc.graph_error ? (
1938 <button
1939 onClick={() => onShowError(S.library.errorGraph, doc.graph_error!)}
1940 className="align-middle"
1941 >
1942 <Chip tone="danger">{graphText}</Chip>
1943 </button>
1944 ) : (
1945 <Chip tone={GRAPH_TONE[doc.graph_status] ?? "neutral"}>{graphText}</Chip>
1946 )}
1947 {/* 抽出来却没落地的事实。抽取成功不代表全须全尾,所以这个 chip 与
1948 graph_status 并列而不是替代它——"done" 和 "3 dropped" 同时为真 */}
1949 {dropTotal > 0 && drops && (
1950 <button onClick={() => onShowDrops(drops)} className="ml-1.5 align-middle">
1951 <Chip tone="warn">{S.library.dropsChip(dropTotal)}</Chip>
1952 </button>
1953 )}
1954 {/* done 也可重抽:本体(描述/新类)调整后强制全量重抽正是常规操作 */}
1955 {doc.status === "ready" && ["none", "failed", "done"].includes(doc.graph_status) && (
1956 <button onClick={onExtract} className="u-link ml-1.5 text-xs">
1957 {doc.graph_status === "done" ? S.library.reExtract : S.library.extract}
1958 </button>
1959 )}
1960 </td>
1961 <td className="px-4 py-2.5 text-neutral-400">{doc.chunk_count || "—"}</td>
1962 <td className="px-4 py-2.5 text-neutral-400">{formatSize(doc.size_bytes)}</td>
1963 <td className="px-4 py-2.5 text-right">
1964 <button onClick={onDelete} className="text-xs text-neutral-500 hover:text-rose-400">
1965 {S.library.delete}
1966 </button>
1967 </td>
1968 </tr>
1969 );
1970}
1971
1972function formatSize(bytes: number): string {
1973 if (bytes < 1024) return `${bytes} B`;
1974 if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;
1975 return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
1976}