Elffuss BraidHub

kikocis/utopia public

da80a58c3af3 · 63.7 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 } from "../kb";
18import { toast } from "../toast";
19import { Chip, type ChipTone, DangerConfirm, Loading, Pager, pageSlice } 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/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 // 切换文件夹回到第一页、清空过滤、退出历史视图
331 useEffect(() => {
332 setPage(0);
333 setFilter("");
334 setShowHistory(false);
335 }, [selection]);
336 // 过滤词变化回到第一页
337 useEffect(() => setPage(0), [filter]);
338
339 // 状态变化经 SSE 事件流推送(useKbEvents 挂在 Shell),无需轮询
340 const docs = useQuery({
341 queryKey: ["documents", kb?.id],
342 queryFn: () => api.documents(kb!.id),
343 enabled: !!kb,
344 });
345 const sources = useQuery({
346 queryKey: ["sources", kb?.id],
347 queryFn: () => api.sources(kb!.id),
348 enabled: !!kb,
349 });
350 // 整库一次取回后按文档分组:抽取丢弃的行数很小,好过每行发一个请求
351 const drops = useQuery({
352 queryKey: ["extraction-drops", kb?.id],
353 queryFn: () => api.extractionDrops(kb!.id),
354 enabled: !!kb,
355 });
356 const dropsByDoc = useMemo(() => {
357 const m = new Map<string, ExtractionDrop[]>();
358 for (const d of drops.data?.drops ?? []) {
359 const list = m.get(d.document_id);
360 if (list) list.push(d);
361 else m.set(d.document_id, [d]);
362 }
363 return m;
364 }, [drops.data]);
365
366 const invalidate = () => {
367 queryClient.invalidateQueries({ queryKey: ["documents", kb?.id] });
368 queryClient.invalidateQueries({ queryKey: ["sources", kb?.id] });
369 // 重抽会重写这篇文档的丢弃信号,跟着文档一起失效
370 queryClient.invalidateQueries({ queryKey: ["extraction-drops", kb?.id] });
371 };
372
373 const upload = useMutation({
374 // 选中 folder 来源时,上传直接归入该文件夹
375 mutationFn: (files: FileList | File[]) => {
376 const folder = sources.data?.sources.find(
377 (s) => s.id === selection && s.kind === "folder",
378 );
379 return api.upload(kb!.id, Array.from(files), folder?.id);
380 },
381 onSuccess: invalidate,
382 });
383 const remove = useMutation({ mutationFn: (id: string) => api.deleteDocument(id), onSuccess: invalidate });
384 const extract = useMutation({ mutationFn: (id: string) => api.extractDocument(id), onSuccess: invalidate });
385 const reprocess = useMutation({
386 mutationFn: (id: string) => api.reprocessDocument(id),
387 onSuccess: invalidate,
388 });
389 // 本库角色:门控"重建图谱"入口(KB admin 起步,与 API 端一致)
390 const kbDetail = useQuery({
391 queryKey: ["kbOne", kb?.id],
392 queryFn: () => api.kbDetail(kb!.id),
393 enabled: !!kb,
394 });
395 const myRole = kbDetail.data?.my_role ?? "";
396 const canEdit = ["editor", "admin", "owner"].includes(myRole);
397 const canRebuild = ["admin", "owner"].includes(myRole);
398
399 const reExtractSource = useMutation({
400 mutationFn: (sourceId: string) => api.reExtractSource(kb!.id, sourceId),
401 onSuccess: (r) => {
402 toast.success(S.library.queuedDocs(r.queued));
403 setReExtracting(false);
404 invalidate();
405 },
406 onError: (e) => toast.error((e as Error).message),
407 });
408 const rebuildGraph = useMutation({
409 mutationFn: () => api.rebuildGraph(kb!.id),
410 onSuccess: (r) => {
411 toast.success(S.library.rebuildDone(r.entities_removed, r.facts_removed, r.queued));
412 setRebuilding(false);
413 invalidate();
414 },
415 onError: (e) => toast.error((e as Error).message),
416 });
417 const syncNow = useMutation({
418 mutationFn: (sourceId: string) => api.syncSource(kb!.id, sourceId),
419 onSuccess: invalidate,
420 });
421 const removeSource = useMutation({
422 mutationFn: (sourceId: string) => api.deleteSource(kb!.id, sourceId),
423 onSuccess: () => {
424 setSelection("all");
425 invalidate();
426 },
427 });
428 const cleanupMissing = useMutation({
429 mutationFn: (sourceId: string) => api.cleanupMissing(kb!.id, sourceId),
430 onSuccess: () => {
431 setCleaning(false);
432 invalidate();
433 },
434 });
435
436 // 只有手动语义的目的地可上传:All/Uploads/folder。拉取型来源(url/rss/api/custom)
437 // 由同步填充,手动塞文件会在下次同步时变成"来源里不存在"的孤儿
438 const canUpload =
439 selection === "all" ||
440 selection === "uploads" ||
441 sources.data?.sources.find((s) => s.id === selection)?.kind === "folder";
442
443 const onDrop = useCallback(
444 (e: React.DragEvent) => {
445 e.preventDefault();
446 setDragging(false);
447 if (!canUpload) return;
448 if (e.dataTransfer.files.length && kb) upload.mutate(e.dataTransfer.files);
449 },
450 [kb, upload, canUpload],
451 );
452
453 if (!kb) return <Loading>{S.nav.loading}</Loading>;
454
455 const allDocs = docs.data ?? [];
456 const sourceList = sources.data?.sources ?? [];
457 const visibleDocs =
458 selection === "all"
459 ? allDocs
460 : selection === "uploads"
461 ? allDocs.filter((d) => !d.source_id)
462 : allDocs.filter((d) => d.source_id === selection);
463 const selectedSource = sourceList.find((s) => s.id === selection);
464
465 const query = filter.trim().toLowerCase();
466 const filteredDocs = query
467 ? visibleDocs.filter((d) => d.filename.toLowerCase().includes(query))
468 : visibleDocs;
469
470 const { rows: pagedDocs, safe: safePage } = pageSlice(filteredDocs, page, PAGE_SIZE);
471
472 return (
473 <div className="h-full flex">
474 <SourcesRail
475 kbId={kb.id}
476 active={selection}
477 onSelect={setSelection}
478 onAdd={() => setAdding(true)}
479 />
480
481 {/* 文档区(scrollbar-gutter 常驻:视图切换时滚动条出没不再引起水平抖动) */}
482 <div
483 className="flex-1 min-w-0 overflow-y-auto u-scroll px-8 py-6 [scrollbar-gutter:stable]"
484 onDragOver={(e) => {
485 e.preventDefault();
486 if (canUpload) setDragging(true);
487 }}
488 onDragLeave={() => setDragging(false)}
489 onDrop={onDrop}
490 >
491 {/* 工作页居左:与 Review/Ontology 同规——左缘随栏起步,切页不跳 */}
492 <div className="max-w-4xl">
493 <div className="flex items-center justify-between mb-4">
494 <h1 className="u-title text-lg">
495 {selectedSource?.name ??
496 (selection === "uploads" ? S.library.uploads : S.library.title)}
497 </h1>
498 <div className="flex items-center gap-2">
499 {/* 历史视图下过滤框只藏不撤(invisible 保留占位),标题行高度不塌、不抖 */}
500 <div className={`relative ${showHistory ? "invisible" : ""}`}>
501 <Search
502 size={13}
503 className="absolute left-2.5 top-1/2 -translate-y-1/2 text-neutral-500 pointer-events-none"
504 />
505 <input
506 className="input-dark w-52 pl-8 pr-7 py-1.5 text-[13px]"
507 placeholder={S.library.filterPlaceholder}
508 value={filter}
509 onChange={(e) => setFilter(e.target.value)}
510 onKeyDown={(e) => e.key === "Escape" && setFilter("")}
511 />
512 {filter && (
513 <button
514 onClick={() => setFilter("")}
515 className="absolute right-2 top-1/2 -translate-y-1/2 text-neutral-500 hover:text-neutral-200"
516 >
517 <X size={12} />
518 </button>
519 )}
520 </div>
521 {/* 全库重建:清算语义,仅 KB admin;放在 All documents 视图 */}
522 {selection === "all" && canRebuild && (
523 <button
524 onClick={() => setRebuilding(true)}
525 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)]"
526 >
527 <RefreshCw size={12} />
528 {S.library.rebuild}
529 </button>
530 )}
531 {canUpload && (
532 <button
533 onClick={() => fileInput.current?.click()}
534 className="u-btn u-btn-ghost px-3 py-1.5 text-xs flex items-center gap-1.5 shrink-0"
535 >
536 <Upload size={12} />
537 {S.library.upload}
538 </button>
539 )}
540 </div>
541 <input
542 ref={fileInput}
543 type="file"
544 multiple
545 hidden
546 accept=".pdf,.docx,.xlsx,.xls,.ods,.pptx,.md,.txt,.html,.htm,.csv,.tsv,.json,.yaml,.yml,.xml,.log"
547 onChange={(e) => e.target.files?.length && upload.mutate(e.target.files)}
548 />
549 </div>
550
551 {selectedSource && (
552 <SourceBar
553 kbId={kb.id}
554 source={selectedSource}
555 syncing={syncNow.isPending}
556 historyOpen={showHistory}
557 onToggleHistory={() => setShowHistory((v) => !v)}
558 onSync={() => syncNow.mutate(selectedSource.id)}
559 onEdit={() => setEditing(true)}
560 onCleanup={() => setCleaning(true)}
561 onReExtract={canEdit ? () => setReExtracting(true) : undefined}
562 onToken={() => setTokenReveal({ sourceId: selectedSource.id })}
563 />
564 )}
565
566 {/* 抽取进度:当前视图内聚合 graph_status,SSE 推动实时走条 */}
567 {(() => {
568 const pending = visibleDocs.filter((d) =>
569 ["queued", "extracting"].includes(d.graph_status),
570 ).length;
571 if (pending === 0) return null;
572 const total = visibleDocs.filter((d) => d.graph_status !== "none").length;
573 const done = total - pending;
574 return (
575 <div className="mb-3 glass rounded-xl px-4 py-2.5">
576 <div className="flex items-center justify-between text-xs text-neutral-400 mb-1.5">
577 <span>{S.library.extractProgress(done, total)}</span>
578 <span className="u-num text-neutral-600">
579 {Math.round((done / Math.max(total, 1)) * 100)}%
580 </span>
581 </div>
582 <div className="h-1 rounded-full bg-white/[0.06] overflow-hidden">
583 <div
584 className="h-full bg-[var(--u-warn)] transition-[width] duration-500"
585 style={{ width: `${(done / Math.max(total, 1)) * 100}%` }}
586 />
587 </div>
588 </div>
589 );
590 })()}
591
592 {upload.isPending && (
593 <div className="mb-3 text-sm text-[var(--u-warn)]">{S.library.uploading}</div>
594 )}
595 {upload.isError && (
596 <div className="mb-3 text-sm text-rose-400">
597 {S.library.uploadFailed}: {String((upload.error as Error).message)}
598 </div>
599 )}
600
601 {showHistory && selectedSource ? (
602 <RunsPanel kbId={kb.id} sourceId={selectedSource.id} />
603 ) : (
604 <>
605 <div className={`glass rounded-2xl glass-hover ${dragging ? "u-highlight" : ""}`}>
606 {filteredDocs.length ? (
607 <table className="w-full text-sm">
608 <thead>
609 <tr className="text-left text-xs text-neutral-500 border-b border-white/10">
610 <th className="px-4 py-2.5 font-medium">{S.library.colFile}</th>
611 {selection === "all" && (
612 <th className="px-4 py-2.5 font-medium">{S.library.colSource}</th>
613 )}
614 <th className="px-4 py-2.5 font-medium">{S.library.colStatus}</th>
615 <th className="px-4 py-2.5 font-medium">{S.library.colGraph}</th>
616 <th className="px-4 py-2.5 font-medium">{S.library.colChunks}</th>
617 <th className="px-4 py-2.5 font-medium">{S.library.colSize}</th>
618 <th className="px-4 py-2.5"></th>
619 </tr>
620 </thead>
621 <tbody>
622 {pagedDocs.map((d) => (
623 <DocRow
624 key={d.id}
625 doc={d}
626 source={
627 selection === "all"
628 ? (sourceList.find((s) => s.id === d.source_id) ?? null)
629 : undefined
630 }
631 onDelete={() => remove.mutate(d.id)}
632 onExtract={() => extract.mutate(d.id)}
633 onReprocess={() => reprocess.mutate(d.id)}
634 onShowError={(kind, text) =>
635 setErrorView({ file: d.filename, kind, text })
636 }
637 drops={dropsByDoc.get(d.id)}
638 onShowDrops={(rows) => setDropsView({ file: d.filename, rows })}
639 />
640 ))}
641 </tbody>
642 </table>
643 ) : query && visibleDocs.length ? (
644 <div className="py-20 text-center text-sm text-neutral-500">
645 {S.library.filterNoMatch}
646 </div>
647 ) : (
648 <div className="py-20 text-center text-sm text-neutral-500">
649 {canUpload ? (
650 <>
651 {S.library.dropHint}
652 <div className="mt-2 text-xs text-neutral-600">{S.library.formats}</div>
653 </>
654 ) : (
655 S.library.emptyPull
656 )}
657 </div>
658 )}
659 </div>
660
661 <Pager
662 total={filteredDocs.length}
663 pageSize={PAGE_SIZE}
664 page={safePage}
665 onPage={setPage}
666 />
667 </>
668 )}
669 </div>
670 </div>
671
672 {adding && (
673 <SourceModal
674 kbId={kb.id}
675 onDone={(id, isApi) => {
676 setAdding(false);
677 if (id) setSelection(id);
678 // api 来源建好直接打开密钥弹窗(onboarding:端点 + 密钥一步拿全)
679 if (id && isApi) setTokenReveal({ sourceId: id });
680 invalidate();
681 }}
682 />
683 )}
684 {tokenReveal && (
685 <TokenModal
686 kbId={kb.id}
687 sourceId={tokenReveal.sourceId}
688 onClose={() => setTokenReveal(null)}
689 />
690 )}
691 {editing && selectedSource && (
692 <SourceEditModal
693 kbId={kb.id}
694 source={selectedSource}
695 onDone={() => {
696 setEditing(false);
697 invalidate();
698 }}
699 onDelete={() => {
700 setEditing(false);
701 removeSource.mutate(selectedSource.id);
702 }}
703 />
704 )}
705 {cleaning && selectedSource && (
706 <DangerConfirm
707 title={S.library.cleanupTitle}
708 hint={S.library.cleanupHint(selectedSource.missing_count, selectedSource.name)}
709 confirmLabel={S.library.cleanupConfirm}
710 cancelLabel={S.library.cancel}
711 busy={cleanupMissing.isPending}
712 onConfirm={() => cleanupMissing.mutate(selectedSource.id)}
713 onCancel={() => setCleaning(false)}
714 />
715 )}
716 {/* 来源重抽:轻确认(不毁数据,只是费时费钱),无需打字解锁 */}
717 {reExtracting && selectedSource && (
718 <DangerConfirm
719 title={S.library.reExtractTitle}
720 hint={S.library.reExtractHint(
721 allDocs.filter((d) => d.source_id === selectedSource.id && d.status === "ready").length,
722 selectedSource.name,
723 )}
724 confirmLabel={S.library.reExtractConfirm}
725 cancelLabel={S.library.cancel}
726 busy={reExtractSource.isPending}
727 onConfirm={() => reExtractSource.mutate(selectedSource.id)}
728 onCancel={() => setReExtracting(false)}
729 />
730 )}
731 {errorView && (
732 <ErrorModal
733 file={errorView.file}
734 kind={errorView.kind}
735 text={errorView.text}
736 onClose={() => setErrorView(null)}
737 />
738 )}
739 {dropsView && (
740 <DropsModal
741 file={dropsView.file}
742 rows={dropsView.rows}
743 onClose={() => setDropsView(null)}
744 />
745 )}
746 {/* 全库重建:打字级确认(清空图层不可逆) */}
747 {rebuilding && (
748 <DangerConfirm
749 title={S.library.rebuildTitle}
750 hint={S.library.rebuildHint(
751 allDocs.filter((d) => d.status === "ready").length,
752 kb.name,
753 )}
754 requireText={kb.name}
755 confirmLabel={S.library.rebuildConfirm}
756 cancelLabel={S.library.cancel}
757 busy={rebuildGraph.isPending}
758 onConfirm={() => rebuildGraph.mutate()}
759 onCancel={() => setRebuilding(false)}
760 />
761 )}
762 </div>
763 );
764}
765
766/** 选中来源的状态条:同步状态 / 上次同步 / History 切换 / Sync now / 设置。 */
767function SourceBar({
768 kbId,
769 source,
770 syncing,
771 historyOpen,
772 onToggleHistory,
773 onSync,
774 onEdit,
775 onCleanup,
776 onReExtract,
777 onToken,
778}: {
779 kbId: string;
780 source: SourceView;
781 syncing: boolean;
782 historyOpen: boolean;
783 onToggleHistory: () => void;
784 onSync: () => void;
785 onEdit: () => void;
786 onCleanup: () => void;
787 /** 缺省 = 无编辑权限,不渲染重抽入口 */
788 onReExtract?: () => void;
789 onToken: () => void;
790}) {
791 const isPull = SYNCING_KINDS.has(source.kind);
792 const isApi = source.kind === "api";
793 const busy = source.last_sync_status === "running" || source.last_sync_status === "queued";
794 // 历史数据的 config 可能是 jsonb null(缺省 Value::Null 落库所致)——防御性兜底
795 const cfg = source.config ?? {};
796 const configSummary =
797 cfg.feed_url ?? cfg.endpoint ?? (cfg.urls ? `${cfg.urls.length} URLs` : "");
798
799 return (
800 <div className="glass rounded-xl mb-3">
801 <div className="px-4 py-2.5 flex items-center gap-3 text-xs">
802 {/* api 与拉取型同一状态语汇:点 + 状态 + 时刻 + 产出/错误;
803 端点是一次性集成信息,放 Token 弹窗,不占常驻条 */}
804 {(isPull || isApi) && (
805 <>
806 <span
807 className={`h-1.5 w-1.5 rounded-full shrink-0 ${SYNC_DOT[source.last_sync_status]}`}
808 />
809 <span className="text-neutral-300 whitespace-nowrap shrink-0">
810 {isApi
811 ? S.library.pushStatus[source.last_sync_status]
812 : S.library.syncStatus[source.last_sync_status]}
813 </span>
814 {source.last_sync_at && (
815 <span className="text-neutral-600 u-num whitespace-nowrap shrink-0">
816 {source.last_sync_at.slice(0, 16).replace("T", " ")}
817 </span>
818 )}
819 {source.last_sync_status === "ok" && source.last_sync_added > 0 && (
820 <span className="text-[var(--u-ok)]">
821 {S.library.lastSyncAdded(source.last_sync_added)}
822 </span>
823 )}
824 {source.last_sync_error && (
825 <span className="text-rose-400 truncate min-w-0" title={source.last_sync_error}>
826 {source.last_sync_error}
827 </span>
828 )}
829 {isPull && (
830 <>
831 <span className="text-neutral-600 truncate min-w-0">{configSummary}</span>
832 <span className="text-neutral-600 shrink-0 u-num">{scheduleLabel(source)}</span>
833 </>
834 )}
835 </>
836 )}
837 {!isPull && !isApi && (
838 <span className="text-neutral-600 truncate min-w-0">
839 {S.library.sourceKindHints[source.kind as "folder"] ?? ""}
840 </span>
841 )}
842 <div className="ml-auto flex items-center gap-2 shrink-0">
843 {/* 集成型来源(custom 拉取 / api 推送):接口文档随手可达 */}
844 {(source.kind === "custom" || source.kind === "api") && (
845 <Link
846 to="/docs/$slug"
847 params={{ slug: "ingest" }}
848 target="_blank"
849 title={S.library.ingestGuideTitle}
850 className="u-btn u-btn-ghost px-2 py-1"
851 >
852 <BookOpen size={12} />
853 </Link>
854 )}
855 {source.missing_count > 0 && (
856 <button
857 onClick={onCleanup}
858 className="u-btn u-btn-ghost px-2.5 py-1 text-xs !text-[var(--u-warn)]"
859 >
860 {S.library.cleanupMissing(source.missing_count)}
861 </button>
862 )}
863 {/* History 对拉取型与 api 推送型都开放:推送失败(格式错等)也记 run */}
864 {(isPull || source.kind === "api") && (
865 /* 激活态用反色(与弹窗类型 tab、图标选中同一语汇),一眼可辨 */
866 <button
867 onClick={onToggleHistory}
868 className={`u-btn px-2.5 py-1 text-xs flex items-center gap-1.5 ${
869 historyOpen ? "u-btn-primary" : "u-btn-ghost"
870 }`}
871 >
872 <HistoryIcon size={11} />
873 {S.library.syncHistory}
874 </button>
875 )}
876 {isPull && (
877 <button
878 onClick={onSync}
879 disabled={busy || syncing}
880 className="u-btn u-btn-ghost px-2.5 py-1 text-xs flex items-center gap-1.5"
881 >
882 <RefreshCw size={11} className={busy ? "animate-spin" : ""} />
883 {S.library.syncNow}
884 </button>
885 )}
886 {source.kind === "api" && (
887 <button
888 onClick={onToken}
889 className="u-btn u-btn-ghost px-2.5 py-1 text-xs flex items-center gap-1.5"
890 >
891 <KeyRound size={11} />
892 {S.library.viewToken}
893 </button>
894 )}
895 {/* 全量重抽本来源:所有类型都给(有文档就能重抽) */}
896 {onReExtract && source.doc_count > 0 && (
897 <button
898 onClick={onReExtract}
899 className="u-btn u-btn-ghost px-2.5 py-1 text-xs flex items-center gap-1.5"
900 >
901 <Waypoints size={11} />
902 {S.library.reExtractSource}
903 </button>
904 )}
905 <button
906 onClick={onEdit}
907 title={S.library.sourceSettings}
908 className="u-btn u-btn-ghost px-2 py-1"
909 >
910 <SettingsIcon size={12} />
911 </button>
912 </div>
913 </div>
914 </div>
915 );
916}
917
918/** 失败详情:完整原文,可复制。tooltip 装不下也拷不走,所以要弹窗。 */
919/** 抽取丢弃详情:抽出来了、被挡掉了,这里说清楚挡在哪、丢了多少。 */
920function DropsModal({
921 file,
922 rows,
923 onClose,
924}: {
925 file: string;
926 rows: ExtractionDrop[];
927 onClose: () => void;
928}) {
929 useEffect(() => {
930 const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();
931 document.addEventListener("keydown", onKey);
932 return () => document.removeEventListener("keydown", onKey);
933 }, [onClose]);
934
935 return (
936 <div
937 className="fixed inset-0 z-50 grid place-items-center bg-black/60 backdrop-blur-sm"
938 onMouseDown={(e) => {
939 if (e.target === e.currentTarget) onClose();
940 }}
941 >
942 <div className="glass-strong w-[36rem] max-w-[calc(100vw-2rem)] rounded-2xl shadow-2xl">
943 <div className="px-5 pt-4 pb-3 border-b border-white/10">
944 <div className="flex items-center justify-between">
945 <h2 className="u-title text-[15px]">{S.library.dropsTitle}</h2>
946 <button onClick={onClose} className="text-neutral-500 hover:text-neutral-200">
947 <X size={15} />
948 </button>
949 </div>
950 <p className="mt-1 text-xs text-neutral-500 truncate" title={file}>
951 {file}
952 </p>
953 <p className="mt-1.5 text-xs text-neutral-500">{S.library.dropsNote}</p>
954 </div>
955 <div className="u-scroll max-h-80 overflow-y-auto px-5 py-3">
956 {rows.map((r) => (
957 <div
958 key={`${r.reason}:${r.detail}`}
959 className="border-b border-white/5 py-2.5 last:border-0"
960 >
961 <div className="flex items-baseline gap-2">
962 <span className="text-sm text-neutral-200">
963 {S.library.dropReason[r.reason] ?? r.reason}
964 </span>
965 <span className="u-num ml-auto text-xs text-neutral-500">×{r.count}</span>
966 </div>
967 <div className="mt-0.5 font-mono text-[11px] text-neutral-400 break-all">
968 {r.detail}
969 </div>
970 {r.example && (
971 <div className="mt-0.5 text-[11px] text-neutral-600 break-all">
972 {S.library.dropsExample} {r.example}
973 </div>
974 )}
975 </div>
976 ))}
977 </div>
978 </div>
979 </div>
980 );
981}
982
983function ErrorModal({
984 file,
985 kind,
986 text,
987 onClose,
988}: {
989 file: string;
990 kind: string;
991 text: string;
992 onClose: () => void;
993}) {
994 useEffect(() => {
995 const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();
996 document.addEventListener("keydown", onKey);
997 return () => document.removeEventListener("keydown", onKey);
998 }, [onClose]);
999
1000 return (
1001 <div
1002 className="fixed inset-0 z-50 grid place-items-center bg-black/60 backdrop-blur-sm"
1003 onMouseDown={(e) => {
1004 if (e.target === e.currentTarget) onClose();
1005 }}
1006 >
1007 <div className="glass-strong w-[36rem] max-w-[calc(100vw-2rem)] rounded-2xl shadow-2xl">
1008 <div className="px-5 pt-4 pb-3 border-b border-white/10">
1009 <div className="flex items-center justify-between">
1010 <h2 className="u-title text-[15px]">{S.library.errorTitle}</h2>
1011 <button onClick={onClose} className="text-neutral-500 hover:text-neutral-200">
1012 <X size={15} />
1013 </button>
1014 </div>
1015 <p className="mt-1 text-xs text-neutral-500 truncate" title={file}>
1016 {file} · {kind}
1017 </p>
1018 </div>
1019 <div className="px-5 py-4">
1020 <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">
1021 {text}
1022 </pre>
1023 </div>
1024 <div className="flex justify-end gap-2 px-5 py-3 border-t border-white/10">
1025 <button
1026 className="u-btn u-btn-ghost px-3.5 py-1.5 text-xs"
1027 onClick={() =>
1028 navigator.clipboard
1029 .writeText(text)
1030 .then(() => toast.success(S.library.errorCopied))
1031 .catch(() => {})
1032 }
1033 >
1034 {S.library.copyError}
1035 </button>
1036 <button className="u-btn u-btn-primary px-3.5 py-1.5 text-xs" onClick={onClose}>
1037 {S.library.close}
1038 </button>
1039 </div>
1040 </div>
1041 </div>
1042 );
1043}
1044
1045/** api 来源密钥:随时可查(Editor 专用端点),内置轮换。 */
1046function TokenModal({
1047 kbId,
1048 sourceId,
1049 onClose,
1050}: {
1051 kbId: string;
1052 sourceId: string;
1053 onClose: () => void;
1054}) {
1055 const queryClient = useQueryClient();
1056 const tokenQuery = useQuery({
1057 queryKey: ["sourceToken", kbId, sourceId],
1058 queryFn: () => api.sourceToken(kbId, sourceId),
1059 });
1060 const rotate = useMutation({
1061 mutationFn: () => api.rotateSourceToken(kbId, sourceId),
1062 onSuccess: (r) => {
1063 queryClient.setQueryData(["sourceToken", kbId, sourceId], { ingest_token: r.ingest_token });
1064 toast.success(S.toast.saved);
1065 },
1066 onError: (e) => toast.error((e as Error).message),
1067 });
1068 const token = tokenQuery.data?.ingest_token ?? null;
1069
1070 const copy = (text: string, msg: string) =>
1071 navigator.clipboard.writeText(text).then(() => toast.success(msg)).catch(() => {});
1072 const endpoint = `${location.origin}/api/v1/sources/${sourceId}/ingest`;
1073 return (
1074 <div
1075 className="fixed inset-0 z-50 grid place-items-center bg-black/60 backdrop-blur-sm"
1076 onMouseDown={(e) => {
1077 if (e.target === e.currentTarget) onClose();
1078 }}
1079 >
1080 <div className="glass-strong w-[32rem] max-w-[calc(100vw-2rem)] rounded-2xl shadow-2xl">
1081 <div className="flex items-center justify-between px-5 pt-4 pb-3 border-b border-white/10">
1082 <h2 className="u-title text-[15px] flex items-center gap-2">
1083 <KeyRound size={14} className="text-neutral-400" />
1084 {S.library.tokenTitle}
1085 </h2>
1086 <button onClick={onClose} className="text-neutral-500 hover:text-neutral-200">
1087 <X size={15} />
1088 </button>
1089 </div>
1090 <div className="px-5 py-4 space-y-3">
1091 {tokenQuery.isPending ? (
1092 <p className="text-sm text-neutral-500">{S.nav.loading}</p>
1093 ) : token ? (
1094 <>
1095 <button
1096 onClick={() => copy(token, S.library.tokenCopied)}
1097 title={S.library.copyEndpoint}
1098 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"
1099 >
1100 {token}
1101 </button>
1102 <p className="text-[11px] leading-relaxed text-neutral-500">
1103 {S.library.tokenWarning}
1104 </p>
1105 <div>
1106 <p className="mb-1 text-[11px] text-neutral-500">{S.library.tokenUsage}</p>
1107 <button
1108 onClick={() => copy(endpoint, S.library.endpointCopied)}
1109 title={S.library.copyEndpoint}
1110 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"
1111 >
1112 POST {endpoint}
1113 {"\n"}Authorization: Bearer &lt;token&gt;
1114 </button>
1115 </div>
1116 </>
1117 ) : (
1118 <p className="text-sm text-neutral-500">{S.library.noToken}</p>
1119 )}
1120 </div>
1121 <div className="flex justify-end gap-2 px-5 py-3 border-t border-white/10">
1122 <button
1123 className="u-btn u-btn-ghost px-3.5 py-1.5 text-xs flex items-center gap-1.5"
1124 disabled={rotate.isPending || tokenQuery.isPending}
1125 onClick={() => rotate.mutate()}
1126 >
1127 <RefreshCw size={11} className={rotate.isPending ? "animate-spin" : ""} />
1128 {token ? S.library.rotateToken : S.library.generateToken}
1129 </button>
1130 <button className="u-btn u-btn-primary px-3.5 py-1.5 text-xs" onClick={onClose}>
1131 {S.library.close}
1132 </button>
1133 </div>
1134 </div>
1135 </div>
1136 );
1137}
1138
1139/** History 视图:占据文件列表位置的同步运行记录(再点 History 切回)。 */
1140function RunsPanel({ kbId, sourceId }: { kbId: string; sourceId: string }) {
1141 const runs = useQuery({
1142 queryKey: ["sourceRuns", kbId, sourceId],
1143 queryFn: () => api.sourceRuns(kbId, sourceId),
1144 });
1145 const list = runs.data?.runs ?? [];
1146
1147 return (
1148 <div className="glass rounded-2xl">
1149 {runs.isLoading ? (
1150 <div className="py-20 text-center text-sm text-neutral-500">{S.nav.loading}</div>
1151 ) : list.length === 0 ? (
1152 <div className="py-20 text-center text-sm text-neutral-500">{S.library.noRuns}</div>
1153 ) : (
1154 <div className="px-4 py-2">
1155 {list.map((r) => (
1156 <div
1157 key={r.id}
1158 className="flex items-center gap-3 py-2 text-xs border-b border-white/5 last:border-0"
1159 >
1160 <span
1161 className={`h-1.5 w-1.5 rounded-full shrink-0 ${
1162 r.status === "ok"
1163 ? "bg-[var(--u-ok)]"
1164 : r.status === "failed"
1165 ? "bg-[var(--u-danger)]"
1166 : "bg-[var(--u-warn)] animate-pulse"
1167 }`}
1168 />
1169 <span className="u-num text-neutral-400 whitespace-nowrap shrink-0">
1170 {r.started_at.slice(0, 16).replace("T", " ")}
1171 </span>
1172 <span className="text-neutral-500 whitespace-nowrap shrink-0">
1173 {r.created_docs > 0 && S.library.runNew(r.created_docs)}
1174 {r.created_docs > 0 && r.updated_docs > 0 && " · "}
1175 {r.updated_docs > 0 && S.library.runUpdated(r.updated_docs)}
1176 {r.status === "ok" && r.created_docs === 0 && r.updated_docs === 0 && (
1177 <span className="text-neutral-600">{S.library.runNothing}</span>
1178 )}
1179 </span>
1180 {r.error && (
1181 <span className="text-rose-400 truncate min-w-0" title={r.error}>
1182 {r.error}
1183 </span>
1184 )}
1185 </div>
1186 ))}
1187 </div>
1188 )}
1189 </div>
1190 );
1191}
1192
1193/** 新建来源弹窗:类型 → 名称/图标 → 类型专属配置 → 同步周期。 */
1194function SourceModal({
1195 kbId,
1196 onDone,
1197}: {
1198 kbId: string;
1199 /** isApi=true 时父级紧接着打开密钥弹窗 */
1200 onDone: (id?: string, isApi?: boolean) => void;
1201}) {
1202 const [kind, setKind] = useState<"folder" | "url" | "rss" | "custom" | "api">("folder");
1203 const [name, setName] = useState("");
1204 const [icon, setIcon] = useState<string | null>(null);
1205 const [urls, setUrls] = useState("");
1206 const [feedUrl, setFeedUrl] = useState("");
1207 const [endpoint, setEndpoint] = useState("");
1208 const [authHeader, setAuthHeader] = useState("");
1209 const [schedule, setSchedule] = useState<ScheduleValue>({
1210 sync_interval_minutes: null,
1211 sync_cron: null,
1212 });
1213 // folder = 纯容器、api = 推送型:都没有同步日程
1214 const syncing = kind === "url" || kind === "rss" || kind === "custom";
1215
1216 const create = useMutation({
1217 mutationFn: () => {
1218 const config =
1219 kind === "url"
1220 ? { urls: urls.split("\n").map((u) => u.trim()).filter(Boolean) }
1221 : kind === "rss"
1222 ? { feed_url: feedUrl.trim() }
1223 : kind === "custom"
1224 ? {
1225 endpoint: endpoint.trim(),
1226 ...(authHeader.trim() ? { auth_header: authHeader.trim() } : {}),
1227 }
1228 : {};
1229 return api.createSource(kbId, {
1230 kind,
1231 name: name.trim(),
1232 config,
1233 // 内置类型图标固定,只有 custom 允许自选
1234 icon: kind === "custom" ? icon : null,
1235 // folder/api 无同步语义:日程强制留空
1236 ...(syncing ? schedule : { sync_interval_minutes: null, sync_cron: null }),
1237 });
1238 },
1239 onSuccess: (data) => onDone(data.source.id, kind === "api"),
1240 });
1241
1242 const valid =
1243 name.trim() &&
1244 (kind === "url"
1245 ? urls.trim()
1246 : kind === "rss"
1247 ? feedUrl.trim()
1248 : kind === "custom"
1249 ? endpoint.trim()
1250 : true);
1251
1252 // 注意用 div 而非 label:label 会把 :hover/click 转发给内部第一个可标记控件
1253 //(button 也算),导致图标网格/日程选择器悬停时第一个按钮常亮
1254 const field = (label: string, node: React.ReactNode) => (
1255 <div className="mb-3">
1256 <div className="mb-1 text-[11px] font-medium text-neutral-500">{label}</div>
1257 {node}
1258 </div>
1259 );
1260
1261 return (
1262 <div
1263 className="fixed inset-0 z-50 grid place-items-center bg-black/60 backdrop-blur-sm"
1264 onMouseDown={(e) => {
1265 if (e.target === e.currentTarget) onDone();
1266 }}
1267 >
1268 <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">
1269 <div className="flex items-center justify-between px-5 pt-4 pb-3 border-b border-white/10">
1270 <h2 className="u-title text-[15px]">{S.library.newSourceTitle}</h2>
1271 <button onClick={() => onDone()} className="text-neutral-500 hover:text-neutral-200">
1272 <X size={15} />
1273 </button>
1274 </div>
1275
1276 <div className="px-5 py-4">
1277 {/* 类型 */}
1278 <div className="flex gap-2 mb-2">
1279 {(["folder", "url", "rss", "api", "custom"] as const).map((k) => {
1280 const Icon = KIND_ICON[k];
1281 return (
1282 <button
1283 key={k}
1284 onClick={() => setKind(k)}
1285 className={`u-btn flex-1 px-3 py-2 text-xs flex items-center justify-center gap-1.5 ${
1286 kind === k ? "u-btn-primary" : "u-btn-ghost"
1287 }`}
1288 >
1289 <Icon size={12} />
1290 {S.library.sourceKinds[k]}
1291 </button>
1292 );
1293 })}
1294 </div>
1295 {/* 类型自解释:一行说明;接口细节移入内置文档,弹窗只留链接 */}
1296 <p className="mb-4 text-[11px] leading-relaxed text-neutral-500">
1297 {S.library.sourceKindHints[kind]}
1298 {kind === "custom" && (
1299 <>
1300 {" "}
1301 <Link
1302 to="/docs/$slug"
1303 params={{ slug: "ingest" }}
1304 target="_blank"
1305 className="u-link"
1306 >
1307 {S.library.ingestGuide}
1308 </Link>
1309 </>
1310 )}
1311 </p>
1312
1313 {field(
1314 S.library.sourceName,
1315 <input
1316 className="input-dark w-full px-3 py-2 text-sm"
1317 value={name}
1318 onChange={(e) => setName(e.target.value)}
1319 autoFocus
1320 />,
1321 )}
1322
1323 {/* 内置类型图标固定;只有 custom 开放图标选择 */}
1324 {kind === "custom" &&
1325 field(
1326 S.library.iconLabel,
1327 <div className="grid grid-cols-10 gap-1">
1328 {Object.entries(SOURCE_ICONS).map(([key, Icon]) => (
1329 <button
1330 key={key}
1331 onClick={() => setIcon(icon === key ? null : key)}
1332 title={key}
1333 className={`h-8 grid place-items-center rounded-lg transition-colors ${
1334 icon === key
1335 ? "bg-white text-black"
1336 : "text-neutral-400 hover:bg-white/[0.07] hover:text-neutral-200"
1337 }`}
1338 >
1339 <Icon size={14} />
1340 </button>
1341 ))}
1342 </div>,
1343 )}
1344
1345 {kind === "custom" && (
1346 <>
1347 {field(
1348 S.library.endpointField,
1349 <input
1350 className="input-dark w-full px-3 py-2 text-sm font-mono"
1351 placeholder="https://your-service/utopia-feed"
1352 value={endpoint}
1353 onChange={(e) => setEndpoint(e.target.value)}
1354 />,
1355 )}
1356 {field(
1357 S.library.authHeaderField,
1358 <input
1359 className="input-dark w-full px-3 py-2 text-sm font-mono"
1360 type="password"
1361 placeholder="Bearer sk-…"
1362 value={authHeader}
1363 onChange={(e) => setAuthHeader(e.target.value)}
1364 />,
1365 )}
1366 </>
1367 )}
1368
1369 {kind === "url" &&
1370 field(
1371 S.library.urlsField,
1372 <textarea
1373 className="input-dark w-full px-3 py-2 text-sm font-mono h-20 resize-y"
1374 value={urls}
1375 onChange={(e) => setUrls(e.target.value)}
1376 />,
1377 )}
1378 {kind === "rss" &&
1379 field(
1380 S.library.feedUrl,
1381 <input
1382 className="input-dark w-full px-3 py-2 text-sm font-mono"
1383 value={feedUrl}
1384 onChange={(e) => setFeedUrl(e.target.value)}
1385 />,
1386 )}
1387
1388 {syncing && field(S.library.interval, <SchedulePicker onChange={setSchedule} />)}
1389
1390 {create.isError && (
1391 <p className="text-xs text-rose-400 mb-2">{(create.error as Error).message}</p>
1392 )}
1393 </div>
1394
1395 <div className="flex justify-end gap-2 px-5 py-3 border-t border-white/10">
1396 <button className="u-btn u-btn-ghost px-3.5 py-1.5 text-xs" onClick={() => onDone()}>
1397 {S.library.cancel}
1398 </button>
1399 <button
1400 className="u-btn u-btn-primary px-3.5 py-1.5 text-xs"
1401 disabled={!valid || create.isPending}
1402 onClick={() => create.mutate()}
1403 >
1404 {S.library.createSource}
1405 </button>
1406 </div>
1407 </div>
1408 </div>
1409 );
1410}
1411
1412/** 来源设置弹窗:改名/图标(仅 custom)/摄取配置/日程;类型不可改;底部 danger zone。 */
1413function SourceEditModal({
1414 kbId,
1415 source,
1416 onDone,
1417 onDelete,
1418}: {
1419 kbId: string;
1420 source: SourceView;
1421 onDone: () => void;
1422 onDelete: () => void;
1423}) {
1424 const kind = source.kind;
1425 const cfg = source.config ?? {};
1426 const [name, setName] = useState(source.name);
1427 const [icon, setIcon] = useState<string | null>(source.icon);
1428 const [urls, setUrls] = useState((cfg.urls ?? []).join("\n"));
1429 const [feedUrl, setFeedUrl] = useState(cfg.feed_url ?? "");
1430 const [endpoint, setEndpoint] = useState(cfg.endpoint ?? "");
1431 const [authHeader, setAuthHeader] = useState("");
1432 const [confirmingDelete, setConfirmingDelete] = useState(false);
1433 const [schedule, setSchedule] = useState<ScheduleValue>({
1434 sync_interval_minutes: source.sync_interval_minutes,
1435 sync_cron: source.sync_cron,
1436 });
1437 const syncing = SYNCING_KINDS.has(kind);
1438 const KindIcon = KIND_ICON[kind as keyof typeof KIND_ICON] ?? Upload;
1439
1440 // 摄取配置是否有改动——有则展示"旧文档去留"说明
1441 const ingestChanged =
1442 (kind === "url" && urls.trim() !== (cfg.urls ?? []).join("\n").trim()) ||
1443 (kind === "rss" && feedUrl.trim() !== (cfg.feed_url ?? "")) ||
1444 (kind === "custom" && endpoint.trim() !== (cfg.endpoint ?? ""));
1445
1446 const save = useMutation({
1447 mutationFn: () => {
1448 const config =
1449 kind === "url"
1450 ? { urls: urls.split("\n").map((u) => u.trim()).filter(Boolean) }
1451 : kind === "rss"
1452 ? { feed_url: feedUrl.trim() }
1453 : kind === "custom"
1454 ? {
1455 endpoint: endpoint.trim(),
1456 // 留空 = 后端保留库里原值(凭据只进不出)
1457 ...(authHeader.trim() ? { auth_header: authHeader.trim() } : {}),
1458 }
1459 : undefined;
1460 return api.updateSource(kbId, source.id, {
1461 name: name.trim(),
1462 ...(kind === "custom" && icon ? { icon } : {}),
1463 ...(config ? { config } : {}),
1464 ...(syncing ? { schedule } : {}),
1465 });
1466 },
1467 onSuccess: () => onDone(),
1468 });
1469
1470 const valid =
1471 name.trim() &&
1472 (kind === "url"
1473 ? urls.trim()
1474 : kind === "rss"
1475 ? feedUrl.trim()
1476 : kind === "custom"
1477 ? endpoint.trim()
1478 : true);
1479
1480 // div 而非 label:label 会把 :hover/click 转发给第一个可标记控件
1481 const field = (label: string, node: React.ReactNode) => (
1482 <div className="mb-3">
1483 <div className="mb-1 text-[11px] font-medium text-neutral-500">{label}</div>
1484 {node}
1485 </div>
1486 );
1487
1488 return (
1489 <div
1490 className="fixed inset-0 z-50 grid place-items-center bg-black/60 backdrop-blur-sm"
1491 onMouseDown={(e) => {
1492 if (e.target === e.currentTarget) onDone();
1493 }}
1494 >
1495 <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">
1496 <div className="flex items-center justify-between px-5 pt-4 pb-3 border-b border-white/10">
1497 <h2 className="u-title text-[15px]">{S.library.editSourceTitle}</h2>
1498 <button onClick={onDone} className="text-neutral-500 hover:text-neutral-200">
1499 <X size={15} />
1500 </button>
1501 </div>
1502
1503 <div className="px-5 py-4">
1504 {/* 类型只读:换类型 = 换身份,应新建来源 */}
1505 <div className="mb-4 flex items-center gap-2 text-xs text-neutral-400">
1506 <KindIcon size={13} className="text-neutral-500" />
1507 {S.library.sourceKinds[kind as keyof typeof S.library.sourceKinds] ?? kind}
1508 </div>
1509
1510 {field(
1511 S.library.sourceName,
1512 <input
1513 className="input-dark w-full px-3 py-2 text-sm"
1514 value={name}
1515 onChange={(e) => setName(e.target.value)}
1516 />,
1517 )}
1518
1519 {kind === "custom" &&
1520 field(
1521 S.library.iconLabel,
1522 <div className="grid grid-cols-10 gap-1">
1523 {Object.entries(SOURCE_ICONS).map(([key, Icon]) => (
1524 <button
1525 key={key}
1526 onClick={() => setIcon(icon === key ? null : key)}
1527 title={key}
1528 className={`h-8 grid place-items-center rounded-lg transition-colors ${
1529 icon === key
1530 ? "bg-white text-black"
1531 : "text-neutral-400 hover:bg-white/[0.07] hover:text-neutral-200"
1532 }`}
1533 >
1534 <Icon size={14} />
1535 </button>
1536 ))}
1537 </div>,
1538 )}
1539
1540 {kind === "url" &&
1541 field(
1542 S.library.urlsField,
1543 <textarea
1544 className="input-dark w-full px-3 py-2 text-sm font-mono h-20 resize-y"
1545 value={urls}
1546 onChange={(e) => setUrls(e.target.value)}
1547 />,
1548 )}
1549 {kind === "rss" &&
1550 field(
1551 S.library.feedUrl,
1552 <input
1553 className="input-dark w-full px-3 py-2 text-sm font-mono"
1554 value={feedUrl}
1555 onChange={(e) => setFeedUrl(e.target.value)}
1556 />,
1557 )}
1558 {kind === "custom" && (
1559 <>
1560 {field(
1561 S.library.endpointField,
1562 <input
1563 className="input-dark w-full px-3 py-2 text-sm font-mono"
1564 value={endpoint}
1565 onChange={(e) => setEndpoint(e.target.value)}
1566 />,
1567 )}
1568 {field(
1569 S.library.authHeaderEditField,
1570 <input
1571 className="input-dark w-full px-3 py-2 text-sm font-mono"
1572 type="password"
1573 placeholder={S.library.authKeepHint}
1574 value={authHeader}
1575 onChange={(e) => setAuthHeader(e.target.value)}
1576 />,
1577 )}
1578 </>
1579 )}
1580
1581 {ingestChanged && (
1582 <p className="mb-3 text-[11px] leading-relaxed text-neutral-500">
1583 {S.library.editKeepNote}
1584 </p>
1585 )}
1586
1587 {syncing &&
1588 field(
1589 S.library.interval,
1590 <SchedulePicker
1591 initial={{
1592 sync_interval_minutes: source.sync_interval_minutes,
1593 sync_cron: source.sync_cron,
1594 }}
1595 onChange={setSchedule}
1596 />,
1597 )}
1598
1599 {save.isError && (
1600 <p className="text-xs text-rose-400 mb-2">{(save.error as Error).message}</p>
1601 )}
1602
1603 {/* Danger zone:删除来源(文档保留,落回 Uploads) */}
1604 <div className="mt-4 pt-3 border-t border-white/10">
1605 <div className="mb-1 text-[11px] font-medium text-neutral-500">
1606 {S.library.dangerZone}
1607 </div>
1608 <div className="flex items-center justify-between gap-3">
1609 <span className="text-[11px] text-neutral-600">{S.library.deleteSourceHint}</span>
1610 <button
1611 onClick={() => setConfirmingDelete(true)}
1612 className="u-btn px-3.5 py-1.5 text-xs font-semibold shrink-0"
1613 style={{ background: "var(--u-danger-solid)", color: "#ffffff" }}
1614 >
1615 {S.library.deleteSource}
1616 </button>
1617 </div>
1618 </div>
1619 </div>
1620
1621 <div className="flex justify-end gap-2 px-5 py-3 border-t border-white/10">
1622 <button className="u-btn u-btn-ghost px-3.5 py-1.5 text-xs" onClick={onDone}>
1623 {S.library.cancel}
1624 </button>
1625 <button
1626 className="u-btn u-btn-primary px-3.5 py-1.5 text-xs"
1627 disabled={!valid || save.isPending}
1628 onClick={() => save.mutate()}
1629 >
1630 {S.library.saveChanges}
1631 </button>
1632 </div>
1633 </div>
1634
1635 {confirmingDelete && (
1636 <DangerConfirm
1637 title={S.library.deleteSourceTitle}
1638 hint={S.library.deleteSourceBody(source.name)}
1639 requireText={source.name}
1640 confirmLabel={S.library.deleteSource}
1641 cancelLabel={S.library.cancel}
1642 onConfirm={onDelete}
1643 onCancel={() => setConfirmingDelete(false)}
1644 />
1645 )}
1646 </div>
1647 );
1648}
1649
1650function DocRow({
1651 doc,
1652 source,
1653 onDelete,
1654 onExtract,
1655 onReprocess,
1656 onShowError,
1657 drops,
1658 onShowDrops,
1659}: {
1660 doc: Doc;
1661 /** undefined = 不渲染来源列;null = Uploads(source_id 为空) */
1662 source?: SourceView | null;
1663 onDelete: () => void;
1664 onExtract: () => void;
1665 onReprocess: () => void;
1666 onShowError: (kind: string, text: string) => void;
1667 /** 这篇文档抽出来却没落地的事实;undefined = 一条都没有 */
1668 drops?: ExtractionDrop[];
1669 onShowDrops: (rows: ExtractionDrop[]) => void;
1670}) {
1671 const dropTotal = drops?.reduce((n, d) => n + d.count, 0) ?? 0;
1672 const statusText =
1673 S.library.status[doc.status as keyof typeof S.library.status] ?? doc.status;
1674 const graphText =
1675 S.library.graphStatus[doc.graph_status as keyof typeof S.library.graphStatus] ??
1676 doc.graph_status;
1677 const SrcIcon = source ? sourceIcon(source) : Upload;
1678 return (
1679 <tr className="border-b border-white/5 hover:bg-white/[0.03]">
1680 <td className="px-4 py-2.5 max-w-xs truncate" title={doc.filename}>
1681 <Link
1682 to="/doc/$docId"
1683 params={{ docId: doc.id }}
1684 search={{}}
1685 className="text-neutral-200 hover:text-[var(--u-accent)]"
1686 >
1687 {doc.filename}
1688 </Link>
1689 </td>
1690 {source !== undefined && (
1691 <td className="px-4 py-2.5">
1692 <span className="flex items-center gap-1.5 text-xs text-neutral-400">
1693 <SrcIcon size={12} className="shrink-0 text-neutral-500" />
1694 <span className="truncate max-w-28">{source?.name ?? S.library.uploads}</span>
1695 </span>
1696 </td>
1697 )}
1698 <td className="px-4 py-2.5">
1699 {/* 失败可点开看原文:tooltip 会截断、也没法复制 */}
1700 {doc.status === "failed" && doc.error ? (
1701 <button
1702 onClick={() => onShowError(S.library.errorParse, doc.error!)}
1703 className="align-middle"
1704 >
1705 <Chip tone="danger">{statusText}</Chip>
1706 </button>
1707 ) : (
1708 <Chip tone={STATUS_TONE[doc.status] ?? "neutral"}>{statusText}</Chip>
1709 )}
1710 {/* 解析管道失败:重跑 解析→索引→嵌入(解析器升级/瞬时故障重试) */}
1711 {doc.status === "failed" && (
1712 <button onClick={onReprocess} className="u-link ml-1.5 text-xs">
1713 {S.library.reprocess}
1714 </button>
1715 )}
1716 {doc.missing_since && (
1717 <span className="ml-1.5 inline-block" title={doc.missing_since.slice(0, 16).replace("T", " ")}>
1718 <Chip tone="neutral">{S.library.notInSource}</Chip>
1719 </span>
1720 )}
1721 </td>
1722 <td className="px-4 py-2.5">
1723 {doc.graph_status === "none" ? (
1724 <span className="text-xs text-neutral-600">{graphText}</span>
1725 ) : doc.graph_status === "failed" && doc.graph_error ? (
1726 <button
1727 onClick={() => onShowError(S.library.errorGraph, doc.graph_error!)}
1728 className="align-middle"
1729 >
1730 <Chip tone="danger">{graphText}</Chip>
1731 </button>
1732 ) : (
1733 <Chip tone={GRAPH_TONE[doc.graph_status] ?? "neutral"}>{graphText}</Chip>
1734 )}
1735 {/* 抽出来却没落地的事实。抽取成功不代表全须全尾,所以这个 chip 与
1736 graph_status 并列而不是替代它——"done" 和 "3 dropped" 同时为真 */}
1737 {dropTotal > 0 && drops && (
1738 <button onClick={() => onShowDrops(drops)} className="ml-1.5 align-middle">
1739 <Chip tone="warn">{S.library.dropsChip(dropTotal)}</Chip>
1740 </button>
1741 )}
1742 {/* done 也可重抽:本体(描述/新类)调整后强制全量重抽正是常规操作 */}
1743 {doc.status === "ready" && ["none", "failed", "done"].includes(doc.graph_status) && (
1744 <button onClick={onExtract} className="u-link ml-1.5 text-xs">
1745 {doc.graph_status === "done" ? S.library.reExtract : S.library.extract}
1746 </button>
1747 )}
1748 </td>
1749 <td className="px-4 py-2.5 text-neutral-400">{doc.chunk_count || "—"}</td>
1750 <td className="px-4 py-2.5 text-neutral-400">{formatSize(doc.size_bytes)}</td>
1751 <td className="px-4 py-2.5 text-right">
1752 <button onClick={onDelete} className="text-xs text-neutral-500 hover:text-rose-400">
1753 {S.library.delete}
1754 </button>
1755 </td>
1756 </tr>
1757 );
1758}
1759
1760function formatSize(bytes: number): string {
1761 if (bytes < 1024) return `${bytes} B`;
1762 if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;
1763 return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
1764}