Elffuss BraidHub

kikocis/utopia public

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