Elffuss BraidHub

kikocis/utopia public

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