Elffuss BraidHub

kikocis/utopia public

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