Elffuss BraidHub

kikocis/utopia public

95c87338cdc8 · 77.6 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 | "s3"
1274 | "azure_blob"
1275 | "gcs"
1276 >("folder");
1277 const [name, setName] = useState("");
1278 const [icon, setIcon] = useState<string | null>(null);
1279 const [urls, setUrls] = useState("");
1280 const [feedUrl, setFeedUrl] = useState("");
1281 const [endpoint, setEndpoint] = useState("");
1282 const [authHeader, setAuthHeader] = useState("");
1283 const [repo, setRepo] = useState("");
1284 const [jiraUrl, setJiraUrl] = useState("");
1285 const [jiraProject, setJiraProject] = useState("");
1286 const [s3Bucket, setS3Bucket] = useState("");
1287 const [s3Prefix, setS3Prefix] = useState("");
1288 const [s3Endpoint, setS3Endpoint] = useState("");
1289 const [s3Region, setS3Region] = useState("");
1290 const [s3Key, setS3Key] = useState("");
1291 const [s3Secret, setS3Secret] = useState("");
1292 const [azAccount, setAzAccount] = useState("");
1293 const [azKey, setAzKey] = useState("");
1294 const [gcsKey, setGcsKey] = useState("");
1295 // PR 在 GitHub 的模型里也是工单。默认不收——问「工单」要的是工单;
1296 // 但有些仓库的决策记录实际写在 PR 描述里,所以给个开关
1297 const [includePrs, setIncludePrs] = useState(false);
1298 const [schedule, setSchedule] = useState<ScheduleValue>({
1299 sync_interval_minutes: null,
1300 sync_cron: null,
1301 });
1302 // folder = 纯容器、api = 推送型:都没有同步日程
1303 const syncing =
1304 kind === "url" ||
1305 kind === "rss" ||
1306 kind === "custom" ||
1307 kind === "github_issues" ||
1308 kind === "jira_issues" ||
1309 kind === "s3" ||
1310 kind === "azure_blob" ||
1311 kind === "gcs";
1312
1313 const create = useMutation({
1314 mutationFn: () => {
1315 const config =
1316 kind === "url"
1317 ? { urls: urls.split("\n").map((u) => u.trim()).filter(Boolean) }
1318 : kind === "rss"
1319 ? { feed_url: feedUrl.trim() }
1320 : kind === "custom"
1321 ? {
1322 endpoint: endpoint.trim(),
1323 ...(authHeader.trim() ? { auth_header: authHeader.trim() } : {}),
1324 }
1325 : kind === "github_issues"
1326 ? {
1327 repo: repo.trim(),
1328 ...(authHeader.trim() ? { auth_header: authHeader.trim() } : {}),
1329 ...(includePrs ? { include_pull_requests: true } : {}),
1330 }
1331 : kind === "jira_issues"
1332 ? {
1333 base_url: jiraUrl.trim(),
1334 project: jiraProject.trim(),
1335 ...(authHeader.trim() ? { auth_header: authHeader.trim() } : {}),
1336 }
1337 : kind === "s3"
1338 ? {
1339 bucket: s3Bucket.trim(),
1340 ...(s3Prefix.trim() ? { prefix: s3Prefix.trim() } : {}),
1341 // 端点留空 = 公有云 S3;填了就是自建,后端据此走 path-style
1342 ...(s3Endpoint.trim() ? { endpoint: s3Endpoint.trim() } : {}),
1343 ...(s3Region.trim() ? { region: s3Region.trim() } : {}),
1344 ...(s3Key.trim() ? { access_key_id: s3Key.trim() } : {}),
1345 ...(s3Secret.trim() ? { secret_access_key: s3Secret.trim() } : {}),
1346 }
1347 : kind === "azure_blob"
1348 ? {
1349 bucket: s3Bucket.trim(),
1350 ...(s3Prefix.trim() ? { prefix: s3Prefix.trim() } : {}),
1351 ...(s3Endpoint.trim() ? { endpoint: s3Endpoint.trim() } : {}),
1352 ...(azAccount.trim() ? { account_name: azAccount.trim() } : {}),
1353 ...(azKey.trim() ? { account_key: azKey.trim() } : {}),
1354 }
1355 : kind === "gcs"
1356 ? {
1357 bucket: s3Bucket.trim(),
1358 ...(s3Prefix.trim() ? { prefix: s3Prefix.trim() } : {}),
1359 ...(s3Endpoint.trim() ? { endpoint: s3Endpoint.trim() } : {}),
1360 ...(gcsKey.trim()
1361 ? { service_account_key: gcsKey.trim() }
1362 : {}),
1363 }
1364 : {};
1365 return api.createSource(kbId, {
1366 kind,
1367 name: name.trim(),
1368 config,
1369 // 内置类型图标固定,只有 custom 允许自选
1370 icon: kind === "custom" ? icon : null,
1371 // folder/api 无同步语义:日程强制留空
1372 ...(syncing ? schedule : { sync_interval_minutes: null, sync_cron: null }),
1373 });
1374 },
1375 onSuccess: (data) => onDone(data.source.id, kind === "api"),
1376 });
1377
1378 const valid =
1379 name.trim() &&
1380 (kind === "url"
1381 ? urls.trim()
1382 : kind === "rss"
1383 ? feedUrl.trim()
1384 : kind === "custom"
1385 ? endpoint.trim()
1386 : kind === "s3" || kind === "azure_blob" || kind === "gcs"
1387 ? s3Bucket.trim()
1388 : true);
1389
1390 // 注意用 div 而非 label:label 会把 :hover/click 转发给内部第一个可标记控件
1391 //(button 也算),导致图标网格/日程选择器悬停时第一个按钮常亮
1392 const field = (label: string, node: React.ReactNode) => (
1393 <div className="mb-3">
1394 <div className="mb-1 text-[11px] font-medium text-neutral-500">{label}</div>
1395 {node}
1396 </div>
1397 );
1398
1399 return (
1400 <div
1401 className="fixed inset-0 z-50 grid place-items-center bg-black/60 backdrop-blur-sm"
1402 onMouseDown={(e) => {
1403 if (e.target === e.currentTarget) onDone();
1404 }}
1405 >
1406 <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">
1407 <div className="flex items-center justify-between px-5 pt-4 pb-3 border-b border-white/10">
1408 <h2 className="u-title text-[15px]">{S.library.newSourceTitle}</h2>
1409 <button onClick={() => onDone()} className="text-neutral-500 hover:text-neutral-200">
1410 <X size={15} />
1411 </button>
1412 </div>
1413
1414 <div className="px-5 py-4">
1415 {/* 类型 */}
1416 <div className="flex gap-2 mb-2">
1417 {(
1418 [
1419 "folder",
1420 "url",
1421 "rss",
1422 "github_issues",
1423 "jira_issues",
1424 "s3",
1425 "azure_blob",
1426 "gcs",
1427 "api",
1428 "custom",
1429 ] as const
1430 ).map((k) => {
1431 const Icon = KIND_ICON[k];
1432 return (
1433 <button
1434 key={k}
1435 onClick={() => setKind(k)}
1436 className={`u-btn flex-1 px-3 py-2 text-xs flex items-center justify-center gap-1.5 ${
1437 kind === k ? "u-btn-primary" : "u-btn-ghost"
1438 }`}
1439 >
1440 <Icon size={12} />
1441 {S.library.sourceKinds[k]}
1442 </button>
1443 );
1444 })}
1445 </div>
1446 {/* 类型自解释:一行说明;接口细节移入内置文档,弹窗只留链接 */}
1447 <p className="mb-4 text-[11px] leading-relaxed text-neutral-500">
1448 {S.library.sourceKindHints[kind]}
1449 {kind === "custom" && (
1450 <>
1451 {" "}
1452 <Link
1453 to="/docs/$slug"
1454 params={{ slug: "ingest" }}
1455 target="_blank"
1456 className="u-link"
1457 >
1458 {S.library.ingestGuide}
1459 </Link>
1460 </>
1461 )}
1462 </p>
1463
1464 {field(
1465 S.library.sourceName,
1466 <input
1467 className="input-dark w-full px-3 py-2 text-sm"
1468 value={name}
1469 onChange={(e) => setName(e.target.value)}
1470 autoFocus
1471 />,
1472 )}
1473
1474 {/* 内置类型图标固定;只有 custom 开放图标选择 */}
1475 {kind === "custom" &&
1476 field(
1477 S.library.iconLabel,
1478 <div className="grid grid-cols-10 gap-1">
1479 {Object.entries(SOURCE_ICONS).map(([key, Icon]) => (
1480 <button
1481 key={key}
1482 onClick={() => setIcon(icon === key ? null : key)}
1483 title={key}
1484 className={`h-8 grid place-items-center rounded-lg transition-colors ${
1485 icon === key
1486 ? "bg-white text-black"
1487 : "text-neutral-400 hover:bg-white/[0.07] hover:text-neutral-200"
1488 }`}
1489 >
1490 <Icon size={14} />
1491 </button>
1492 ))}
1493 </div>,
1494 )}
1495
1496 {kind === "custom" && (
1497 <>
1498 {field(
1499 S.library.endpointField,
1500 <input
1501 className="input-dark w-full px-3 py-2 text-sm font-mono"
1502 placeholder="https://your-service/utopia-feed"
1503 value={endpoint}
1504 onChange={(e) => setEndpoint(e.target.value)}
1505 />,
1506 )}
1507 {field(
1508 S.library.authHeaderField,
1509 <input
1510 className="input-dark w-full px-3 py-2 text-sm font-mono"
1511 type="password"
1512 placeholder="Bearer sk-…"
1513 value={authHeader}
1514 onChange={(e) => setAuthHeader(e.target.value)}
1515 />,
1516 )}
1517 </>
1518 )}
1519
1520 {kind === "url" &&
1521 field(
1522 S.library.urlsField,
1523 <textarea
1524 className="input-dark w-full px-3 py-2 text-sm font-mono h-20 resize-y"
1525 value={urls}
1526 onChange={(e) => setUrls(e.target.value)}
1527 />,
1528 )}
1529 {kind === "rss" &&
1530 field(
1531 S.library.feedUrl,
1532 <input
1533 className="input-dark w-full px-3 py-2 text-sm font-mono"
1534 value={feedUrl}
1535 onChange={(e) => setFeedUrl(e.target.value)}
1536 />,
1537 )}
1538 {kind === "jira_issues" && (
1539 <>
1540 {field(
1541 S.library.jiraUrlField,
1542 <input
1543 className="input-dark w-full px-3 py-2 text-sm font-mono"
1544 placeholder="https://jira.example.com"
1545 value={jiraUrl}
1546 onChange={(e) => setJiraUrl(e.target.value)}
1547 />,
1548 )}
1549 {field(
1550 S.library.jiraProjectField,
1551 <input
1552 className="input-dark w-full px-3 py-2 text-sm font-mono"
1553 placeholder="KAFKA"
1554 value={jiraProject}
1555 onChange={(e) => setJiraProject(e.target.value)}
1556 />,
1557 )}
1558 {field(
1559 S.library.tokenField,
1560 <input
1561 className="input-dark w-full px-3 py-2 text-sm font-mono"
1562 type="password"
1563 placeholder="Basic dXNlcjp0b2tlbg=="
1564 value={authHeader}
1565 onChange={(e) => setAuthHeader(e.target.value)}
1566 />,
1567 )}
1568 </>
1569 )}
1570 {(kind === "s3" || kind === "azure_blob" || kind === "gcs") && (
1571 <>
1572 {field(
1573 S.library.s3BucketField,
1574 <input
1575 className="input-dark w-full px-3 py-2 text-sm font-mono"
1576 placeholder="documents"
1577 value={s3Bucket}
1578 onChange={(e) => setS3Bucket(e.target.value)}
1579 />,
1580 )}
1581 {field(
1582 S.library.s3PrefixField,
1583 <input
1584 className="input-dark w-full px-3 py-2 text-sm font-mono"
1585 placeholder="reports/2026/"
1586 value={s3Prefix}
1587 onChange={(e) => setS3Prefix(e.target.value)}
1588 />,
1589 )}
1590 {field(
1591 S.library.s3EndpointField,
1592 <input
1593 className="input-dark w-full px-3 py-2 text-sm font-mono"
1594 placeholder="http://minio.internal:9000"
1595 value={s3Endpoint}
1596 onChange={(e) => setS3Endpoint(e.target.value)}
1597 />,
1598 )}
1599 {field(
1600 S.library.s3RegionField,
1601 <input
1602 className="input-dark w-full px-3 py-2 text-sm font-mono"
1603 placeholder="us-east-1"
1604 value={s3Region}
1605 onChange={(e) => setS3Region(e.target.value)}
1606 />,
1607 )}
1608 {kind === "s3" && (
1609 <>
1610 {field(
1611 S.library.s3KeyField,
1612 <input
1613 className="input-dark w-full px-3 py-2 text-sm font-mono"
1614 value={s3Key}
1615 onChange={(e) => setS3Key(e.target.value)}
1616 />,
1617 )}
1618 {field(
1619 S.library.s3SecretField,
1620 <input
1621 className="input-dark w-full px-3 py-2 text-sm font-mono"
1622 type="password"
1623 value={s3Secret}
1624 onChange={(e) => setS3Secret(e.target.value)}
1625 />,
1626 )}
1627 </>
1628 )}
1629 {kind === "azure_blob" && (
1630 <>
1631 {field(
1632 S.library.azAccountField,
1633 <input
1634 className="input-dark w-full px-3 py-2 text-sm font-mono"
1635 value={azAccount}
1636 onChange={(e) => setAzAccount(e.target.value)}
1637 />,
1638 )}
1639 {field(
1640 S.library.azKeyField,
1641 <input
1642 className="input-dark w-full px-3 py-2 text-sm font-mono"
1643 type="password"
1644 value={azKey}
1645 onChange={(e) => setAzKey(e.target.value)}
1646 />,
1647 )}
1648 </>
1649 )}
1650 {kind === "gcs" &&
1651 field(
1652 S.library.gcsKeyField,
1653 <textarea
1654 className="input-dark w-full px-3 py-2 text-sm font-mono h-24"
1655 placeholder='{"type":"service_account",...}'
1656 value={gcsKey}
1657 onChange={(e) => setGcsKey(e.target.value)}
1658 />,
1659 )}
1660 </>
1661 )}
1662 {kind === "github_issues" && (
1663 <>
1664 {field(
1665 S.library.repoField,
1666 <input
1667 className="input-dark w-full px-3 py-2 text-sm font-mono"
1668 placeholder="owner/name"
1669 value={repo}
1670 onChange={(e) => setRepo(e.target.value)}
1671 />,
1672 )}
1673 {field(
1674 S.library.tokenField,
1675 <input
1676 className="input-dark w-full px-3 py-2 text-sm font-mono"
1677 type="password"
1678 placeholder="Bearer ghp_…"
1679 value={authHeader}
1680 onChange={(e) => setAuthHeader(e.target.value)}
1681 />,
1682 )}
1683 <label className="mb-4 flex items-center gap-2 text-[11px] text-neutral-400">
1684 <input
1685 type="checkbox"
1686 checked={includePrs}
1687 onChange={(e) => setIncludePrs(e.target.checked)}
1688 />
1689 {S.library.includePullRequests}
1690 </label>
1691 </>
1692 )}
1693
1694 {syncing && field(S.library.interval, <SchedulePicker onChange={setSchedule} />)}
1695
1696 {create.isError && (
1697 <p className="text-xs text-rose-400 mb-2">{(create.error as Error).message}</p>
1698 )}
1699 </div>
1700
1701 <div className="flex justify-end gap-2 px-5 py-3 border-t border-white/10">
1702 <button className="u-btn u-btn-ghost px-3.5 py-1.5 text-xs" onClick={() => onDone()}>
1703 {S.library.cancel}
1704 </button>
1705 <button
1706 className="u-btn u-btn-primary px-3.5 py-1.5 text-xs"
1707 disabled={!valid || create.isPending}
1708 onClick={() => create.mutate()}
1709 >
1710 {S.library.createSource}
1711 </button>
1712 </div>
1713 </div>
1714 </div>
1715 );
1716}
1717
1718/** 来源设置弹窗:改名/图标(仅 custom)/摄取配置/日程;类型不可改;底部 danger zone。 */
1719function SourceEditModal({
1720 kbId,
1721 source,
1722 onDone,
1723 onDelete,
1724}: {
1725 kbId: string;
1726 source: SourceView;
1727 onDone: () => void;
1728 onDelete: () => void;
1729}) {
1730 const kind = source.kind;
1731 const cfg = source.config ?? {};
1732 const [name, setName] = useState(source.name);
1733 const [icon, setIcon] = useState<string | null>(source.icon);
1734 const [urls, setUrls] = useState((cfg.urls ?? []).join("\n"));
1735 const [feedUrl, setFeedUrl] = useState(cfg.feed_url ?? "");
1736 const [endpoint, setEndpoint] = useState(cfg.endpoint ?? "");
1737 const [authHeader, setAuthHeader] = useState("");
1738 const [repo, setRepo] = useState(cfg.repo ?? "");
1739 const [includePrs, setIncludePrs] = useState(Boolean(cfg.include_pull_requests));
1740 const [confirmingDelete, setConfirmingDelete] = useState(false);
1741 const [schedule, setSchedule] = useState<ScheduleValue>({
1742 sync_interval_minutes: source.sync_interval_minutes,
1743 sync_cron: source.sync_cron,
1744 });
1745 const syncing = SYNCING_KINDS.has(kind);
1746 const KindIcon = KIND_ICON[kind as keyof typeof KIND_ICON] ?? Upload;
1747
1748 // 摄取配置是否有改动——有则展示"旧文档去留"说明
1749 const ingestChanged =
1750 (kind === "url" && urls.trim() !== (cfg.urls ?? []).join("\n").trim()) ||
1751 (kind === "rss" && feedUrl.trim() !== (cfg.feed_url ?? "")) ||
1752 (kind === "custom" && endpoint.trim() !== (cfg.endpoint ?? "")) ||
1753 // 换仓库或改收不收 PR,两者都会换掉这个来源里文档的集合
1754 (kind === "github_issues" &&
1755 (repo.trim() !== (cfg.repo ?? "") ||
1756 includePrs !== Boolean(cfg.include_pull_requests)));
1757
1758 const save = useMutation({
1759 mutationFn: () => {
1760 const config =
1761 kind === "url"
1762 ? { urls: urls.split("\n").map((u) => u.trim()).filter(Boolean) }
1763 : kind === "rss"
1764 ? { feed_url: feedUrl.trim() }
1765 : kind === "custom"
1766 ? {
1767 endpoint: endpoint.trim(),
1768 // 留空 = 后端保留库里原值(凭据只进不出)
1769 ...(authHeader.trim() ? { auth_header: authHeader.trim() } : {}),
1770 }
1771 : kind === "github_issues"
1772 ? {
1773 repo: repo.trim(),
1774 // 留空 = 后端保留库里原值(凭据只进不出)
1775 ...(authHeader.trim() ? { auth_header: authHeader.trim() } : {}),
1776 include_pull_requests: includePrs,
1777 }
1778 : undefined;
1779 return api.updateSource(kbId, source.id, {
1780 name: name.trim(),
1781 ...(kind === "custom" && icon ? { icon } : {}),
1782 ...(config ? { config } : {}),
1783 ...(syncing ? { schedule } : {}),
1784 });
1785 },
1786 onSuccess: () => onDone(),
1787 });
1788
1789 const valid =
1790 name.trim() &&
1791 (kind === "url"
1792 ? urls.trim()
1793 : kind === "rss"
1794 ? feedUrl.trim()
1795 : kind === "custom"
1796 ? endpoint.trim()
1797 : true);
1798
1799 // div 而非 label:label 会把 :hover/click 转发给第一个可标记控件
1800 const field = (label: string, node: React.ReactNode) => (
1801 <div className="mb-3">
1802 <div className="mb-1 text-[11px] font-medium text-neutral-500">{label}</div>
1803 {node}
1804 </div>
1805 );
1806
1807 return (
1808 <div
1809 className="fixed inset-0 z-50 grid place-items-center bg-black/60 backdrop-blur-sm"
1810 onMouseDown={(e) => {
1811 if (e.target === e.currentTarget) onDone();
1812 }}
1813 >
1814 <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">
1815 <div className="flex items-center justify-between px-5 pt-4 pb-3 border-b border-white/10">
1816 <h2 className="u-title text-[15px]">{S.library.editSourceTitle}</h2>
1817 <button onClick={onDone} className="text-neutral-500 hover:text-neutral-200">
1818 <X size={15} />
1819 </button>
1820 </div>
1821
1822 <div className="px-5 py-4">
1823 {/* 类型只读:换类型 = 换身份,应新建来源 */}
1824 <div className="mb-4 flex items-center gap-2 text-xs text-neutral-400">
1825 <KindIcon size={13} className="text-neutral-500" />
1826 {S.library.sourceKinds[kind as keyof typeof S.library.sourceKinds] ?? kind}
1827 </div>
1828
1829 {field(
1830 S.library.sourceName,
1831 <input
1832 className="input-dark w-full px-3 py-2 text-sm"
1833 value={name}
1834 onChange={(e) => setName(e.target.value)}
1835 />,
1836 )}
1837
1838 {kind === "custom" &&
1839 field(
1840 S.library.iconLabel,
1841 <div className="grid grid-cols-10 gap-1">
1842 {Object.entries(SOURCE_ICONS).map(([key, Icon]) => (
1843 <button
1844 key={key}
1845 onClick={() => setIcon(icon === key ? null : key)}
1846 title={key}
1847 className={`h-8 grid place-items-center rounded-lg transition-colors ${
1848 icon === key
1849 ? "bg-white text-black"
1850 : "text-neutral-400 hover:bg-white/[0.07] hover:text-neutral-200"
1851 }`}
1852 >
1853 <Icon size={14} />
1854 </button>
1855 ))}
1856 </div>,
1857 )}
1858
1859 {kind === "url" &&
1860 field(
1861 S.library.urlsField,
1862 <textarea
1863 className="input-dark w-full px-3 py-2 text-sm font-mono h-20 resize-y"
1864 value={urls}
1865 onChange={(e) => setUrls(e.target.value)}
1866 />,
1867 )}
1868 {kind === "rss" &&
1869 field(
1870 S.library.feedUrl,
1871 <input
1872 className="input-dark w-full px-3 py-2 text-sm font-mono"
1873 value={feedUrl}
1874 onChange={(e) => setFeedUrl(e.target.value)}
1875 />,
1876 )}
1877 {kind === "github_issues" && (
1878 <>
1879 {field(
1880 S.library.repoField,
1881 <input
1882 className="input-dark w-full px-3 py-2 text-sm font-mono"
1883 placeholder="owner/name"
1884 value={repo}
1885 onChange={(e) => setRepo(e.target.value)}
1886 />,
1887 )}
1888 {field(
1889 S.library.tokenField,
1890 <input
1891 className="input-dark w-full px-3 py-2 text-sm font-mono"
1892 type="password"
1893 placeholder="Bearer ghp_…"
1894 value={authHeader}
1895 onChange={(e) => setAuthHeader(e.target.value)}
1896 />,
1897 )}
1898 <label className="mb-4 flex items-center gap-2 text-[11px] text-neutral-400">
1899 <input
1900 type="checkbox"
1901 checked={includePrs}
1902 onChange={(e) => setIncludePrs(e.target.checked)}
1903 />
1904 {S.library.includePullRequests}
1905 </label>
1906 </>
1907 )}
1908 {kind === "custom" && (
1909 <>
1910 {field(
1911 S.library.endpointField,
1912 <input
1913 className="input-dark w-full px-3 py-2 text-sm font-mono"
1914 value={endpoint}
1915 onChange={(e) => setEndpoint(e.target.value)}
1916 />,
1917 )}
1918 {field(
1919 S.library.authHeaderEditField,
1920 <input
1921 className="input-dark w-full px-3 py-2 text-sm font-mono"
1922 type="password"
1923 placeholder={S.library.authKeepHint}
1924 value={authHeader}
1925 onChange={(e) => setAuthHeader(e.target.value)}
1926 />,
1927 )}
1928 </>
1929 )}
1930
1931 {ingestChanged && (
1932 <p className="mb-3 text-[11px] leading-relaxed text-neutral-500">
1933 {S.library.editKeepNote}
1934 </p>
1935 )}
1936
1937 {syncing &&
1938 field(
1939 S.library.interval,
1940 <SchedulePicker
1941 initial={{
1942 sync_interval_minutes: source.sync_interval_minutes,
1943 sync_cron: source.sync_cron,
1944 }}
1945 onChange={setSchedule}
1946 />,
1947 )}
1948
1949 {save.isError && (
1950 <p className="text-xs text-rose-400 mb-2">{(save.error as Error).message}</p>
1951 )}
1952
1953 {/* Danger zone:删除来源(文档保留,落回 Uploads) */}
1954 <div className="mt-4 pt-3 border-t border-white/10">
1955 <div className="mb-1 text-[11px] font-medium text-neutral-500">
1956 {S.library.dangerZone}
1957 </div>
1958 <div className="flex items-center justify-between gap-3">
1959 <span className="text-[11px] text-neutral-600">{S.library.deleteSourceHint}</span>
1960 <button
1961 onClick={() => setConfirmingDelete(true)}
1962 className="u-btn px-3.5 py-1.5 text-xs font-semibold shrink-0"
1963 style={{ background: "var(--u-danger-solid)", color: "#ffffff" }}
1964 >
1965 {S.library.deleteSource}
1966 </button>
1967 </div>
1968 </div>
1969 </div>
1970
1971 <div className="flex justify-end gap-2 px-5 py-3 border-t border-white/10">
1972 <button className="u-btn u-btn-ghost px-3.5 py-1.5 text-xs" onClick={onDone}>
1973 {S.library.cancel}
1974 </button>
1975 <button
1976 className="u-btn u-btn-primary px-3.5 py-1.5 text-xs"
1977 disabled={!valid || save.isPending}
1978 onClick={() => save.mutate()}
1979 >
1980 {S.library.saveChanges}
1981 </button>
1982 </div>
1983 </div>
1984
1985 {confirmingDelete && (
1986 <DangerConfirm
1987 title={S.library.deleteSourceTitle}
1988 hint={S.library.deleteSourceBody(source.name)}
1989 requireText={source.name}
1990 confirmLabel={S.library.deleteSource}
1991 cancelLabel={S.library.cancel}
1992 onConfirm={onDelete}
1993 onCancel={() => setConfirmingDelete(false)}
1994 />
1995 )}
1996 </div>
1997 );
1998}
1999
2000function DocRow({
2001 doc,
2002 source,
2003 onDelete,
2004 onExtract,
2005 onReprocess,
2006 onShowError,
2007 drops,
2008 onShowDrops,
2009}: {
2010 doc: Doc;
2011 /** undefined = 不渲染来源列;null = Uploads(source_id 为空) */
2012 source?: SourceView | null;
2013 onDelete: () => void;
2014 onExtract: () => void;
2015 onReprocess: () => void;
2016 onShowError: (kind: string, text: string) => void;
2017 /** 这篇文档抽出来却没落地的事实;undefined = 一条都没有 */
2018 drops?: ExtractionDrop[];
2019 onShowDrops: (rows: ExtractionDrop[]) => void;
2020}) {
2021 const kbId = useKbId();
2022 const dropTotal = drops?.reduce((n, d) => n + d.count, 0) ?? 0;
2023 const statusText =
2024 S.library.status[doc.status as keyof typeof S.library.status] ?? doc.status;
2025 const graphText =
2026 S.library.graphStatus[doc.graph_status as keyof typeof S.library.graphStatus] ??
2027 doc.graph_status;
2028 const SrcIcon = source ? sourceIcon(source) : Upload;
2029 return (
2030 <tr className="border-b border-white/5 hover:bg-white/[0.03]">
2031 <td className="px-4 py-2.5 max-w-xs truncate" title={doc.filename}>
2032 <Link
2033 to="/kb/$kbId/doc/$docId"
2034 params={{ kbId, docId: doc.id }}
2035 search={{}}
2036 className="text-neutral-200 hover:text-[var(--u-accent)]"
2037 >
2038 {doc.filename}
2039 </Link>
2040 </td>
2041 {source !== undefined && (
2042 <td className="px-4 py-2.5">
2043 <span className="flex items-center gap-1.5 text-xs text-neutral-400">
2044 <SrcIcon size={12} className="shrink-0 text-neutral-500" />
2045 <span className="truncate max-w-28">{source?.name ?? S.library.uploads}</span>
2046 </span>
2047 </td>
2048 )}
2049 <td className="px-4 py-2.5">
2050 {/* 失败可点开看原文:tooltip 会截断、也没法复制 */}
2051 {doc.status === "failed" && doc.error ? (
2052 <button
2053 onClick={() => onShowError(S.library.errorParse, doc.error!)}
2054 className="align-middle"
2055 >
2056 <Chip tone="danger">{statusText}</Chip>
2057 </button>
2058 ) : (
2059 <Chip tone={STATUS_TONE[doc.status] ?? "neutral"}>{statusText}</Chip>
2060 )}
2061 {/* 解析管道失败:重跑 解析→索引→嵌入(解析器升级/瞬时故障重试) */}
2062 {doc.status === "failed" && (
2063 <button onClick={onReprocess} className="u-link ml-1.5 text-xs">
2064 {S.library.reprocess}
2065 </button>
2066 )}
2067 {doc.missing_since && (
2068 <span className="ml-1.5 inline-block" title={doc.missing_since.slice(0, 16).replace("T", " ")}>
2069 <Chip tone="neutral">{S.library.notInSource}</Chip>
2070 </span>
2071 )}
2072 </td>
2073 <td className="px-4 py-2.5">
2074 {doc.graph_status === "none" ? (
2075 <span className="text-xs text-neutral-600">{graphText}</span>
2076 ) : doc.graph_status === "failed" && doc.graph_error ? (
2077 <button
2078 onClick={() => onShowError(S.library.errorGraph, doc.graph_error!)}
2079 className="align-middle"
2080 >
2081 <Chip tone="danger">{graphText}</Chip>
2082 </button>
2083 ) : (
2084 <Chip tone={GRAPH_TONE[doc.graph_status] ?? "neutral"}>{graphText}</Chip>
2085 )}
2086 {/* 抽出来却没落地的事实。抽取成功不代表全须全尾,所以这个 chip 与
2087 graph_status 并列而不是替代它——"done" 和 "3 dropped" 同时为真 */}
2088 {dropTotal > 0 && drops && (
2089 <button onClick={() => onShowDrops(drops)} className="ml-1.5 align-middle">
2090 <Chip tone="warn">{S.library.dropsChip(dropTotal)}</Chip>
2091 </button>
2092 )}
2093 {/* done 也可重抽:本体(描述/新类)调整后强制全量重抽正是常规操作 */}
2094 {doc.status === "ready" && ["none", "failed", "done"].includes(doc.graph_status) && (
2095 <button onClick={onExtract} className="u-link ml-1.5 text-xs">
2096 {doc.graph_status === "done" ? S.library.reExtract : S.library.extract}
2097 </button>
2098 )}
2099 </td>
2100 <td className="px-4 py-2.5 text-neutral-400">{doc.chunk_count || "—"}</td>
2101 <td className="px-4 py-2.5 text-neutral-400">{formatSize(doc.size_bytes)}</td>
2102 <td className="px-4 py-2.5 text-right">
2103 <button onClick={onDelete} className="text-xs text-neutral-500 hover:text-rose-400">
2104 {S.library.delete}
2105 </button>
2106 </td>
2107 </tr>
2108 );
2109}
2110
2111function formatSize(bytes: number): string {
2112 if (bytes < 1024) return `${bytes} B`;
2113 if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;
2114 return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
2115}