636 lines
36 KiB
TypeScript
636 lines
36 KiB
TypeScript
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
|
import {
|
|
BookOpen,
|
|
BookOpenText,
|
|
ChevronRight,
|
|
Database,
|
|
Cpu,
|
|
Edit3,
|
|
FileText,
|
|
Globe2,
|
|
Loader2,
|
|
Plus,
|
|
RefreshCw,
|
|
Search,
|
|
Settings2,
|
|
Sparkles,
|
|
Trash2,
|
|
Upload,
|
|
} from "lucide-react";
|
|
import { useEffect, useMemo, useState } from "react";
|
|
import { useNavigate } from "react-router-dom";
|
|
import { toast } from "sonner";
|
|
|
|
import { Badge } from "@/components/ui/badge";
|
|
import { Button } from "@/components/ui/button";
|
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
|
import {
|
|
Dialog,
|
|
DialogContent,
|
|
DialogDescription,
|
|
DialogFooter,
|
|
DialogHeader,
|
|
DialogTitle,
|
|
} from "@/components/ui/dialog";
|
|
import { Input } from "@/components/ui/input";
|
|
import { Progress } from "@/components/ui/progress";
|
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
|
import { Textarea } from "@/components/ui/textarea";
|
|
import { getStoredAuth } from "@/core/auth";
|
|
import { WeKnoraSourceDrawer } from "@/strategy-components/components/resource-management/llmwiki/WeKnoraSourceDrawer";
|
|
import {
|
|
type LlmWikiKnowledgeBase,
|
|
type LlmWikiSearchResponse,
|
|
type LlmWikiSearchResult,
|
|
type LlmWikiScope,
|
|
configureLocalWikiEncoder,
|
|
getLocalWikiEncoderStatus,
|
|
searchLlmWiki,
|
|
startLocalWikiEncoder,
|
|
uploadLocalWikiEncoder,
|
|
useLlmWikiActions,
|
|
useLlmWikiKnowledgeBases,
|
|
useLlmWikiSettings,
|
|
useLlmWikiSettingsActions,
|
|
} from "@/strategy-components/api/llmwiki";
|
|
|
|
type WorkspaceTab = "personal" | "public" | "settings";
|
|
const LIST_PATH = "/page/workspace/knowledge";
|
|
|
|
const publicationLabels: Record<string, string> = {
|
|
private: "仅自己",
|
|
pending: "仅自己",
|
|
published: "已公开",
|
|
rejected: "仅自己",
|
|
};
|
|
|
|
function messageOf(error: unknown): string {
|
|
return error instanceof Error ? error.message : "操作失败,请稍后重试";
|
|
}
|
|
|
|
function searchModeLabel(mode: LlmWikiSearchResponse["mode"]) {
|
|
if (mode === "vector") return "本地 Wiki 向量检索";
|
|
if (mode === "mixed") return "Wiki 混合检索";
|
|
return "Wiki 接口检索";
|
|
}
|
|
|
|
function wikiPageTypeLabel(value?: string) {
|
|
const normalized = (value || "").trim().toLowerCase();
|
|
if (normalized === "directory") return "目录页";
|
|
if (normalized === "overview") return "概览页";
|
|
if (normalized === "article") return "文章页";
|
|
return value?.trim() || "Wiki 页面";
|
|
}
|
|
|
|
function formatSearchTime(value?: string | null) {
|
|
if (!value) return "";
|
|
const date = new Date(value);
|
|
return Number.isNaN(date.getTime())
|
|
? value
|
|
: date.toLocaleString("zh-CN", { hour12: false });
|
|
}
|
|
|
|
function resultPreview(result: LlmWikiSearchResult) {
|
|
const text = (
|
|
result.matched_sections?.map((section) => section.content).filter(Boolean).join("\n\n") ||
|
|
result.content ||
|
|
""
|
|
);
|
|
return text
|
|
.replace(/^---[\s\S]*?---\s*/m, "")
|
|
.replace(/```[\s\S]*?```/g, " ")
|
|
.replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1")
|
|
.replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
|
|
.replace(/\[\[[^\]\s|]+[|\s]+([^\]]+)\]\]/g, "$1")
|
|
.replace(/\[\[([^\]]+)\]\]/g, "$1")
|
|
.replace(/^#{1,6}\s+/gm, "")
|
|
.replace(/^\s*[-*+]\s+/gm, "")
|
|
.replace(/[>*_`~|]/g, " ")
|
|
.replace(/\s+/g, " ")
|
|
.trim();
|
|
}
|
|
|
|
export function WeKnoraKnowledgeWorkspace() {
|
|
const navigate = useNavigate();
|
|
const isAdmin = getStoredAuth()?.system_role === "admin";
|
|
const [tab, setTab] = useState<WorkspaceTab>("personal");
|
|
const scope: LlmWikiScope = tab === "public" ? "public" : "personal";
|
|
const knowledge = useLlmWikiKnowledgeBases(scope, tab !== "settings");
|
|
const actions = useLlmWikiActions();
|
|
const [createOpen, setCreateOpen] = useState(false);
|
|
const [editingKnowledge, setEditingKnowledge] = useState<LlmWikiKnowledgeBase | null>(null);
|
|
const [searchText, setSearchText] = useState("");
|
|
const [searching, setSearching] = useState(false);
|
|
const [searchResponse, setSearchResponse] = useState<LlmWikiSearchResponse | null>(null);
|
|
const [selectedSearchResult, setSelectedSearchResult] = useState<LlmWikiSearchResult | null>(null);
|
|
|
|
useEffect(() => {
|
|
setSearchResponse(null);
|
|
setSelectedSearchResult(null);
|
|
}, [tab]);
|
|
|
|
const busy = actions.create.isPending || actions.update.isPending || actions.remove.isPending || actions.publication.isPending;
|
|
const openDetails = (item: LlmWikiKnowledgeBase) => {
|
|
navigate(`${LIST_PATH}/${encodeURIComponent(item.id)}`);
|
|
};
|
|
|
|
const runSearch = async () => {
|
|
const query = searchText.trim();
|
|
if (!query) return;
|
|
setSearching(true);
|
|
try {
|
|
setSearchResponse(await searchLlmWiki({ query, scope }));
|
|
} catch (error) {
|
|
toast.error(messageOf(error));
|
|
} finally {
|
|
setSearching(false);
|
|
}
|
|
};
|
|
|
|
const removeKnowledgeBase = async (item: LlmWikiKnowledgeBase) => {
|
|
if (!window.confirm(`确定删除知识库“${item.name}”吗?知识服务中的文档和索引也会删除。`)) return;
|
|
try {
|
|
await actions.remove.mutateAsync(item.id);
|
|
toast.success("知识库已删除");
|
|
} catch (error) {
|
|
toast.error(messageOf(error));
|
|
}
|
|
};
|
|
|
|
const togglePublication = async (item: LlmWikiKnowledgeBase) => {
|
|
const publish = item.publication_status !== "published";
|
|
try {
|
|
await actions.publication.mutateAsync({ id: item.id, publish });
|
|
toast.success(publish ? "知识库已发布到公共 LLMWiki" : "知识库已取消公开");
|
|
} catch (error) {
|
|
toast.error(messageOf(error));
|
|
}
|
|
};
|
|
|
|
return (
|
|
<div className="flex h-full min-h-0 flex-col bg-background">
|
|
<div className="border-b bg-gradient-to-r from-primary/8 via-card to-card px-6 py-5">
|
|
<div className="mx-auto flex max-w-[1500px] flex-wrap items-center justify-between gap-4">
|
|
<div>
|
|
<div className="flex items-center gap-2">
|
|
<Database className="size-5 text-primary" />
|
|
<h1 className="text-xl font-semibold">知识库管理</h1>
|
|
<Badge variant="secondary">知识服务</Badge>
|
|
</div>
|
|
<p className="mt-1 text-sm text-muted-foreground">由知识服务负责解析与检索,用户、权限和发布范围由 cmzs 管理。</p>
|
|
</div>
|
|
<div className="flex items-center gap-2 rounded-full border bg-background/80 p-1 shadow-sm backdrop-blur">
|
|
{tab !== "settings" && (
|
|
<Button variant="ghost" size="sm" className="rounded-full" onClick={() => navigate("/page/workspace/skills?tab=knowledge")}>
|
|
<Sparkles className="mr-2 size-4" />从技能归纳
|
|
</Button>
|
|
)}
|
|
{tab !== "settings" && (
|
|
<Button variant="ghost" size="sm" className="rounded-full" onClick={() => knowledge.refetch()} disabled={knowledge.isFetching}>
|
|
<RefreshCw className={`mr-2 size-4 ${knowledge.isFetching ? "animate-spin" : ""}`} />刷新
|
|
</Button>
|
|
)}
|
|
{tab === "personal" && <Button size="sm" className="rounded-full px-4 shadow-sm" onClick={() => setCreateOpen(true)}><Plus className="mr-2 size-4" />新建知识库</Button>}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="min-h-0 flex-1 overflow-auto px-6 py-5">
|
|
<div className="mx-auto max-w-[1500px]">
|
|
<Tabs value={tab} onValueChange={(value) => setTab(value as WorkspaceTab)}>
|
|
<div className="flex flex-wrap items-center justify-between gap-3 rounded-2xl border bg-card/80 p-3 shadow-sm">
|
|
<TabsList className="rounded-xl bg-muted/70">
|
|
<TabsTrigger value="personal"><BookOpen className="mr-2 size-4" />我的知识库</TabsTrigger>
|
|
<TabsTrigger value="public"><Globe2 className="mr-2 size-4" />公共 LLMWiki</TabsTrigger>
|
|
{isAdmin && <TabsTrigger value="settings"><Settings2 className="mr-2 size-4" />连接配置</TabsTrigger>}
|
|
</TabsList>
|
|
{tab !== "settings" && (
|
|
<div className="flex w-full max-w-xl items-center gap-2 rounded-xl border bg-background/80 p-1 shadow-sm sm:w-auto">
|
|
<div className="relative min-w-0 flex-1 sm:w-80">
|
|
<Search className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
|
|
<Input value={searchText} onChange={(event) => setSearchText(event.target.value)} onKeyDown={(event) => event.key === "Enter" && void runSearch()} placeholder={tab === "public" ? "检索公共 Wiki 文档" : "检索我的 Wiki 文档"} className="border-0 bg-transparent pl-9 shadow-none focus-visible:ring-0" />
|
|
</div>
|
|
<Button variant="secondary" className="rounded-lg px-4" onClick={() => void runSearch()} disabled={searching || !searchText.trim()}>{searching ? <Loader2 className="size-4 animate-spin" /> : "检索 Wiki"}</Button>
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
<TabsContent value="personal" className="mt-5"><KnowledgeGrid rows={knowledge.data ?? []} loading={knowledge.isLoading} error={knowledge.error} emptyText="还没有个人知识库,点击右上角创建。" busy={busy} onOpen={openDetails} onEdit={setEditingKnowledge} onPublish={togglePublication} onDelete={removeKnowledgeBase} /></TabsContent>
|
|
<TabsContent value="public" className="mt-5"><KnowledgeGrid rows={knowledge.data ?? []} loading={knowledge.isLoading} error={knowledge.error} emptyText="公共 LLMWiki 暂无已发布知识库。" busy={busy} onOpen={openDetails} onEdit={setEditingKnowledge} onPublish={togglePublication} onDelete={removeKnowledgeBase} /></TabsContent>
|
|
{isAdmin && <TabsContent value="settings" className="mt-5"><ConnectionSettings /></TabsContent>}
|
|
</Tabs>
|
|
|
|
{searchResponse && tab !== "settings" && (
|
|
<Card className="mt-5 overflow-hidden border-emerald-200/70 bg-gradient-to-br from-emerald-50/70 via-card to-card shadow-sm dark:border-emerald-900/60 dark:from-emerald-950/20">
|
|
<CardHeader className="border-b border-emerald-200/60 pb-4 dark:border-emerald-900/50">
|
|
<div className="flex flex-wrap items-start justify-between gap-3">
|
|
<div className="flex min-w-0 items-start gap-3">
|
|
<div className="flex size-10 shrink-0 items-center justify-center rounded-xl bg-emerald-600 text-white shadow-sm shadow-emerald-600/20">
|
|
<BookOpenText className="size-5" />
|
|
</div>
|
|
<div className="min-w-0">
|
|
<CardTitle className="flex flex-wrap items-center gap-2 text-base">
|
|
Wiki 文档检索
|
|
<Badge className="border-emerald-200 bg-emerald-100 text-emerald-800 hover:bg-emerald-100 dark:border-emerald-800 dark:bg-emerald-950 dark:text-emerald-200">
|
|
{searchResponse.results.length} 个 Wiki 页面
|
|
</Badge>
|
|
</CardTitle>
|
|
<CardDescription className="mt-1.5 leading-5">
|
|
本次直接检索知识库生成的 Wiki 页面,不检索上传原文或原文分块。
|
|
</CardDescription>
|
|
</div>
|
|
</div>
|
|
<Badge variant="outline" className="shrink-0 bg-background/80 text-emerald-700 dark:text-emerald-300">
|
|
{searchModeLabel(searchResponse.mode)}
|
|
</Badge>
|
|
</div>
|
|
</CardHeader>
|
|
<CardContent className="space-y-3 p-4">
|
|
{searchResponse.results.length === 0 ? (
|
|
<div className="flex min-h-36 flex-col items-center justify-center rounded-xl border border-dashed bg-background/70 px-6 text-center">
|
|
<BookOpenText className="mb-3 size-8 text-muted-foreground/60" />
|
|
<div className="text-sm font-medium">已完成 Wiki 文档检索,暂未命中相关页面</div>
|
|
<div className="mt-1 text-xs text-muted-foreground">可以缩短关键词或换一个主题后重试。</div>
|
|
</div>
|
|
) : searchResponse.results.map((result) => {
|
|
const heading = result.matched_heading || result.matched_sections?.find((section) => section.heading)?.heading;
|
|
const updatedAt = formatSearchTime(result.updated_at);
|
|
return (
|
|
<button
|
|
type="button"
|
|
key={`${result.knowledge_base_id}:${result.wiki_slug || result.id}`}
|
|
className="group w-full rounded-xl border bg-background/90 p-4 text-left shadow-sm transition hover:-translate-y-0.5 hover:border-emerald-300 hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-500/40"
|
|
onClick={() => setSelectedSearchResult(result)}
|
|
>
|
|
<div className="flex items-start gap-3">
|
|
<div className="mt-0.5 flex size-9 shrink-0 items-center justify-center rounded-lg bg-emerald-100 text-emerald-700 dark:bg-emerald-950 dark:text-emerald-300">
|
|
<BookOpenText className="size-4.5" />
|
|
</div>
|
|
<div className="min-w-0 flex-1">
|
|
<div className="flex flex-wrap items-center gap-2">
|
|
<Badge variant="secondary" className="bg-emerald-50 text-emerald-700 dark:bg-emerald-950 dark:text-emerald-300">Wiki 文档</Badge>
|
|
<Badge variant="outline">{wikiPageTypeLabel(result.page_type)}</Badge>
|
|
<span className="truncate text-xs text-muted-foreground">{result.knowledge_base_name}</span>
|
|
</div>
|
|
<div className="mt-2 line-clamp-2 text-[15px] font-semibold leading-6 text-foreground">{result.title || "未命名 Wiki 页面"}</div>
|
|
{heading && <div className="mt-1 text-xs font-medium text-emerald-700 dark:text-emerald-300">命中章节:{heading}</div>}
|
|
<p className="mt-2 line-clamp-3 whitespace-pre-wrap text-sm leading-6 text-muted-foreground">{resultPreview(result)}</p>
|
|
<div className="mt-3 flex flex-wrap items-center justify-between gap-2 border-t pt-3 text-xs text-muted-foreground">
|
|
<div className="flex flex-wrap items-center gap-x-3 gap-y-1">
|
|
<span>相关度 {Math.round(Math.max(0, result.score || 0) * 100)}%</span>
|
|
{updatedAt && <span>更新于 {updatedAt}</span>}
|
|
</div>
|
|
<span className="inline-flex items-center font-medium text-emerald-700 transition group-hover:translate-x-0.5 dark:text-emerald-300">
|
|
抽屉查看完整 Wiki <ChevronRight className="ml-1 size-3.5" />
|
|
</span>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</button>
|
|
);
|
|
})}
|
|
</CardContent>
|
|
</Card>
|
|
)}
|
|
</div>
|
|
</div>
|
|
|
|
<WeKnoraSourceDrawer
|
|
open={selectedSearchResult !== null}
|
|
target={selectedSearchResult ? {
|
|
knowledgeBaseId: selectedSearchResult.knowledge_base_id,
|
|
wikiSlug: selectedSearchResult.wiki_slug,
|
|
tab: "wiki",
|
|
} : null}
|
|
title={selectedSearchResult?.title}
|
|
quote={selectedSearchResult ? resultPreview(selectedSearchResult) : ""}
|
|
onOpenChange={(open) => {
|
|
if (!open) setSelectedSearchResult(null);
|
|
}}
|
|
/>
|
|
|
|
{editingKnowledge && (
|
|
<EditKnowledgeDialog
|
|
key={editingKnowledge.id}
|
|
knowledgeBase={editingKnowledge}
|
|
pending={actions.update.isPending}
|
|
onClose={() => setEditingKnowledge(null)}
|
|
onSave={async (input) => {
|
|
try {
|
|
await actions.update.mutateAsync({ id: editingKnowledge.id, ...input });
|
|
setEditingKnowledge(null);
|
|
toast.success("知识库信息已保存");
|
|
} catch (error) {
|
|
toast.error(messageOf(error));
|
|
}
|
|
}}
|
|
/>
|
|
)}
|
|
|
|
<CreateKnowledgeDialog open={createOpen} pending={actions.create.isPending} onOpenChange={setCreateOpen} onCreate={async (input) => {
|
|
try {
|
|
const created = await actions.create.mutateAsync(input);
|
|
setCreateOpen(false);
|
|
navigate(`${LIST_PATH}/${encodeURIComponent(created.id)}`);
|
|
toast.success("知识库已创建");
|
|
} catch (error) {
|
|
toast.error(messageOf(error));
|
|
}
|
|
}} />
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function KnowledgeGrid({
|
|
rows,
|
|
loading,
|
|
error,
|
|
emptyText,
|
|
busy,
|
|
onOpen,
|
|
onEdit,
|
|
onPublish,
|
|
onDelete,
|
|
}: {
|
|
rows: LlmWikiKnowledgeBase[];
|
|
loading: boolean;
|
|
error: unknown;
|
|
emptyText: string;
|
|
busy: boolean;
|
|
onOpen: (item: LlmWikiKnowledgeBase) => void;
|
|
onEdit: (item: LlmWikiKnowledgeBase) => void;
|
|
onPublish: (item: LlmWikiKnowledgeBase) => void;
|
|
onDelete: (item: LlmWikiKnowledgeBase) => void;
|
|
}) {
|
|
if (loading) return <div className="flex h-64 items-center justify-center text-muted-foreground"><Loader2 className="mr-2 size-5 animate-spin" />正在读取知识库</div>;
|
|
if (error) return <div className="rounded-lg border border-destructive/30 bg-destructive/5 p-6 text-sm text-destructive">{messageOf(error)}</div>;
|
|
const visibleRows = rows.filter((item) => item.remote_status !== "missing");
|
|
if (!visibleRows.length) return <div className="flex h-64 items-center justify-center rounded-xl border border-dashed text-sm text-muted-foreground">{emptyText}</div>;
|
|
return (
|
|
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
|
|
{visibleRows.map((item) => (
|
|
<Card
|
|
key={item.id}
|
|
className="group overflow-hidden rounded-2xl border-border/70 bg-card/95 transition-all hover:-translate-y-0.5 hover:border-primary/30 hover:shadow-lg"
|
|
>
|
|
<div className={`h-1 ${item.publication_status === "published" ? "bg-primary" : "bg-muted"}`} />
|
|
<button type="button" className="w-full text-left outline-none transition-colors hover:bg-muted/25 focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2" onClick={() => onOpen(item)}>
|
|
<CardHeader className="pb-3 pt-5">
|
|
<div className="flex items-start justify-between gap-3">
|
|
<div className="min-w-0"><CardTitle className="truncate text-base">{item.name}</CardTitle><CardDescription className="mt-1 line-clamp-2 min-h-10">{item.description || "暂无描述"}</CardDescription></div>
|
|
<div className="flex shrink-0 flex-col items-end gap-1.5"><Badge variant={item.publication_status === "published" ? "default" : "secondary"}>{publicationLabels[item.publication_status] ?? "仅自己"}</Badge>{item.indexing_strategy?.wiki_enabled && <Badge className="bg-violet-100 text-violet-700 hover:bg-violet-100 dark:bg-violet-950 dark:text-violet-300">Wiki</Badge>}</div>
|
|
</div>
|
|
</CardHeader>
|
|
<div className="px-6 pb-4"><div className="grid grid-cols-3 gap-2 rounded-xl border bg-muted/35 p-3 text-center text-xs"><div><div className="text-base font-semibold text-foreground">{item.knowledge_count}</div><span className="text-muted-foreground">文档</span></div><div><div className="text-base font-semibold text-foreground">{item.chunk_count}</div><span className="text-muted-foreground">分块</span></div><div><div className="text-base font-semibold text-foreground">{item.processing_count}</div><span className="text-muted-foreground">处理中</span></div></div></div>
|
|
</button>
|
|
<CardContent className="border-t bg-muted/20 px-6 py-4">
|
|
<div className="flex items-center justify-between gap-3">
|
|
<div className="flex min-w-0 flex-wrap items-center gap-2">
|
|
<Button size="sm" variant="outline" className="rounded-full" onClick={() => onOpen(item)}><FileText className="mr-2 size-4" />查看详情</Button>
|
|
{item.can_write && !item.is_conversation_deposit && <Button size="sm" variant="outline" className="rounded-full" disabled={busy} onClick={() => onEdit(item)} aria-label={`编辑知识库 ${item.name}`}><Edit3 className="mr-2 size-4" />编辑</Button>}
|
|
{item.is_owner && !item.is_conversation_deposit && <Button size="sm" variant="secondary" className="rounded-full" disabled={busy} onClick={() => void onPublish(item)}>{item.publication_status === "published" ? "取消公开" : "发布公共库"}</Button>}
|
|
</div>
|
|
{item.can_write && !item.is_conversation_deposit && <Button size="icon" variant="ghost" className="size-8 shrink-0 rounded-full text-destructive hover:bg-destructive/10 hover:text-destructive" aria-label={`删除知识库 ${item.name}`} title="删除知识库" disabled={busy} onClick={() => void onDelete(item)}><Trash2 className="size-4" /></Button>}
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
))}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function EditKnowledgeDialog({
|
|
knowledgeBase,
|
|
pending,
|
|
onClose,
|
|
onSave,
|
|
}: {
|
|
knowledgeBase: LlmWikiKnowledgeBase;
|
|
pending: boolean;
|
|
onClose: () => void;
|
|
onSave: (input: { name: string; description: string }) => Promise<void>;
|
|
}) {
|
|
const [name, setName] = useState(knowledgeBase.name);
|
|
const [description, setDescription] = useState(knowledgeBase.description);
|
|
|
|
return (
|
|
<Dialog open onOpenChange={(open) => { if (!open && !pending) onClose(); }}>
|
|
<DialogContent>
|
|
<form onSubmit={(event) => {
|
|
event.preventDefault();
|
|
if (!pending && name.trim()) {
|
|
void onSave({ name: name.trim(), description: description.trim() });
|
|
}
|
|
}}>
|
|
<DialogHeader>
|
|
<DialogTitle>编辑知识库</DialogTitle>
|
|
<DialogDescription>修改知识库名称和描述,保存后同步到知识服务。</DialogDescription>
|
|
</DialogHeader>
|
|
<div className="space-y-4 py-4">
|
|
<div className="space-y-2">
|
|
<label className="text-sm font-medium" htmlFor="llmwiki-edit-name">名称</label>
|
|
<Input id="llmwiki-edit-name" value={name} onChange={(event) => setName(event.target.value)} maxLength={255} required disabled={pending} />
|
|
</div>
|
|
<div className="space-y-2">
|
|
<label className="text-sm font-medium" htmlFor="llmwiki-edit-description">描述</label>
|
|
<Textarea id="llmwiki-edit-description" value={description} onChange={(event) => setDescription(event.target.value)} rows={4} maxLength={2048} disabled={pending} />
|
|
</div>
|
|
</div>
|
|
<DialogFooter>
|
|
<Button type="button" variant="outline" onClick={onClose} disabled={pending}>取消</Button>
|
|
<Button type="submit" disabled={pending || !name.trim()}>
|
|
{pending && <Loader2 className="mr-2 size-4 animate-spin" />}保存
|
|
</Button>
|
|
</DialogFooter>
|
|
</form>
|
|
</DialogContent>
|
|
</Dialog>
|
|
);
|
|
}
|
|
|
|
function CreateKnowledgeDialog({
|
|
open,
|
|
pending,
|
|
onOpenChange,
|
|
onCreate,
|
|
}: {
|
|
open: boolean;
|
|
pending: boolean;
|
|
onOpenChange: (value: boolean) => void;
|
|
onCreate: (input: { name: string; description: string; type: "document" | "faq"; wiki_enabled: boolean }) => Promise<void>;
|
|
}) {
|
|
const [name, setName] = useState("");
|
|
const [description, setDescription] = useState("");
|
|
const [wikiEnabled, setWikiEnabled] = useState(true);
|
|
useEffect(() => {
|
|
if (!open) { setName(""); setDescription(""); setWikiEnabled(true); }
|
|
}, [open]);
|
|
return (
|
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
|
<DialogContent>
|
|
<DialogHeader><DialogTitle>新建个人知识库</DialogTitle><DialogDescription>选择知识库模式;模型、切块和存储策略仍由知识服务管理。</DialogDescription></DialogHeader>
|
|
<div className="space-y-4 py-2">
|
|
<div className="space-y-2"><label className="text-sm font-medium" htmlFor="llmwiki-name">名称</label><Input id="llmwiki-name" value={name} onChange={(event) => setName(event.target.value)} maxLength={255} /></div>
|
|
<div className="space-y-2"><label className="text-sm font-medium" htmlFor="llmwiki-description">描述</label><Textarea id="llmwiki-description" value={description} onChange={(event) => setDescription(event.target.value)} rows={4} maxLength={2048} /></div>
|
|
<div className="space-y-2"><div className="text-sm font-medium">知识库模式</div><div className="grid gap-3 sm:grid-cols-2">
|
|
<button type="button" className={`rounded-xl border p-4 text-left transition-colors ${wikiEnabled ? "border-primary bg-primary/5 ring-1 ring-primary" : "hover:bg-muted/40"}`} onClick={() => setWikiEnabled(true)}><div className="flex items-center gap-2 text-sm font-semibold"><BookOpen className="size-4 text-violet-500" />Wiki 知识库</div><p className="mt-2 text-xs leading-5 text-muted-foreground">自动综合资料,生成 Wiki 页面和页面关系图谱。</p></button>
|
|
<button type="button" className={`rounded-xl border p-4 text-left transition-colors ${!wikiEnabled ? "border-primary bg-primary/5 ring-1 ring-primary" : "hover:bg-muted/40"}`} onClick={() => setWikiEnabled(false)}><div className="flex items-center gap-2 text-sm font-semibold"><FileText className="size-4 text-blue-500" />标准知识库</div><p className="mt-2 text-xs leading-5 text-muted-foreground">仅进行文档解析、切块与向量/关键词索引。</p></button>
|
|
</div></div>
|
|
</div>
|
|
<DialogFooter><Button variant="outline" onClick={() => onOpenChange(false)}>取消</Button><Button disabled={pending || !name.trim()} onClick={() => void onCreate({ name: name.trim(), description: description.trim(), type: "document", wiki_enabled: wikiEnabled })}>{pending && <Loader2 className="mr-2 size-4 animate-spin" />}创建</Button></DialogFooter>
|
|
</DialogContent>
|
|
</Dialog>
|
|
);
|
|
}
|
|
|
|
export function LocalEncoderSettingsCard() {
|
|
const queryClient = useQueryClient();
|
|
const encoder = useQuery({
|
|
queryKey: ["llmwiki-local-encoder"],
|
|
queryFn: getLocalWikiEncoderStatus,
|
|
retry: false,
|
|
refetchInterval: (query) => query.state.data?.state === "starting" ? 1000 : false,
|
|
});
|
|
const [modelPath, setModelPath] = useState("");
|
|
const [files, setFiles] = useState<File[]>([]);
|
|
const [uploadProgress, setUploadProgress] = useState(0);
|
|
|
|
useEffect(() => {
|
|
if (encoder.data?.model_path) setModelPath(encoder.data.model_path);
|
|
}, [encoder.data?.model_path]);
|
|
|
|
const applyStatus = (status: Awaited<ReturnType<typeof getLocalWikiEncoderStatus>>) => {
|
|
queryClient.setQueryData(["llmwiki-local-encoder"], status);
|
|
setModelPath(status.model_path || "");
|
|
};
|
|
const configure = useMutation({
|
|
mutationFn: () => configureLocalWikiEncoder(modelPath.trim()),
|
|
onSuccess: (status) => { applyStatus(status); toast.success("编码器目录已保存"); },
|
|
onError: (error) => toast.error(messageOf(error)),
|
|
});
|
|
const upload = useMutation({
|
|
mutationFn: () => uploadLocalWikiEncoder(files, setUploadProgress),
|
|
onMutate: () => setUploadProgress(0),
|
|
onSuccess: (status) => {
|
|
applyStatus(status);
|
|
setFiles([]);
|
|
toast.success(`已保存 ${status.uploaded_files ?? 0} 个模型文件`);
|
|
},
|
|
onError: (error) => toast.error(messageOf(error)),
|
|
});
|
|
const start = useMutation({
|
|
mutationFn: startLocalWikiEncoder,
|
|
onSuccess: (status) => {
|
|
applyStatus(status);
|
|
toast.success(status.state === "ready" ? "本地编码器已就绪" : "本地编码器正在独立启动");
|
|
},
|
|
onError: (error) => toast.error(messageOf(error)),
|
|
});
|
|
const status = encoder.data;
|
|
const selectedBytes = files.reduce((sum, file) => sum + file.size, 0);
|
|
const formatSize = (value: number) => value >= 1024 ** 3
|
|
? `${(value / 1024 ** 3).toFixed(2)} GB`
|
|
: `${(value / 1024 ** 2).toFixed(1)} MB`;
|
|
|
|
return (
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle className="flex items-center gap-2 text-base"><Cpu className="size-5" />DeerFlow 本地编码器</CardTitle>
|
|
<CardDescription>仅管理员可见。配置服务器上已有的 BGE-M3 目录,或直接上传完整离线模型目录;编码器作为独立进程启动,不影响 DeerFlow 其他服务。</CardDescription>
|
|
</CardHeader>
|
|
<CardContent className="space-y-5">
|
|
<div className="flex flex-wrap items-center gap-2 text-sm">
|
|
<Badge variant={status?.state === "failed" ? "destructive" : status?.state === "ready" ? "default" : "secondary"}>
|
|
{status?.state === "ready" ? "已就绪" : status?.state === "starting" ? "启动中" : status?.state === "failed" ? "启动失败" : "未启动"}
|
|
</Badge>
|
|
<span className="text-muted-foreground">{status ? `${status.model} · ${status.dimensions || "自动探测"} 维 · ${status.process_isolation ? "独立进程" : "主进程"}` : "正在读取状态"}</span>
|
|
{status?.model_files_ready && <Badge variant="outline">模型文件已就绪</Badge>}
|
|
</div>
|
|
{encoder.error && <p className="text-sm text-destructive">{messageOf(encoder.error)}</p>}
|
|
{status?.last_error && <p className="rounded-lg border border-destructive/30 bg-destructive/5 p-3 text-xs text-destructive">{status.last_error}</p>}
|
|
|
|
<div className="space-y-2">
|
|
<label className="text-sm font-medium" htmlFor="local-encoder-path">使用服务器已有目录</label>
|
|
<div className="flex flex-col gap-2 sm:flex-row">
|
|
<Input id="local-encoder-path" value={modelPath} onChange={(event) => setModelPath(event.target.value)} placeholder="例如 /opt/deerflow/models/bge-m3" />
|
|
<Button variant="outline" disabled={!modelPath.trim() || configure.isPending} onClick={() => configure.mutate()}>
|
|
{configure.isPending && <Loader2 className="mr-2 size-4 animate-spin" />}保存目录
|
|
</Button>
|
|
</div>
|
|
<p className="text-xs text-muted-foreground">目录内需包含 <code>onnx/model.onnx</code>(推荐)或根目录 <code>model.onnx</code>。</p>
|
|
</div>
|
|
|
|
<div className="space-y-2 rounded-xl border border-dashed p-4">
|
|
<div className="flex items-center gap-2 text-sm font-medium"><Upload className="size-4" />从当前电脑上传模型目录</div>
|
|
<Input
|
|
type="file"
|
|
multiple
|
|
{...{ webkitdirectory: "" }}
|
|
onChange={(event) => setFiles(Array.from(event.currentTarget.files ?? []))}
|
|
/>
|
|
{upload.isPending && (
|
|
<div className="space-y-1">
|
|
<Progress value={uploadProgress} />
|
|
<p className="text-right text-xs text-muted-foreground">上传进度 {uploadProgress}%</p>
|
|
</div>
|
|
)}
|
|
<div className="flex flex-wrap items-center justify-between gap-3">
|
|
<p className="text-xs text-muted-foreground">
|
|
{files.length ? `已选择 ${files.length} 个文件,共 ${formatSize(selectedBytes)}` : "请选择完整 BGE-M3 目录。大文件会落到运行目录,不写入源码仓库。"}
|
|
</p>
|
|
<Button disabled={!files.length || upload.isPending} onClick={() => upload.mutate()}>
|
|
{upload.isPending ? <Loader2 className="mr-2 size-4 animate-spin" /> : <Upload className="mr-2 size-4" />}
|
|
{upload.isPending ? "正在上传,请勿关闭页面" : "上传并设为当前模型"}
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="flex flex-wrap gap-2">
|
|
<Button disabled={!status?.model_files_ready || start.isPending || status?.state === "starting" || status?.state === "ready"} onClick={() => start.mutate()}>
|
|
{(start.isPending || status?.state === "starting") && <Loader2 className="mr-2 size-4 animate-spin" />}
|
|
{status?.state === "ready" ? "编码器已启动" : status?.state === "failed" ? "重新启动" : "一键启动编码器"}
|
|
</Button>
|
|
<Button variant="ghost" disabled={encoder.isFetching} onClick={() => void encoder.refetch()}>
|
|
<RefreshCw className={`mr-2 size-4 ${encoder.isFetching ? "animate-spin" : ""}`} />刷新状态
|
|
</Button>
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
);
|
|
}
|
|
|
|
export function ConnectionSettings() {
|
|
const settings = useLlmWikiSettings(true);
|
|
const actions = useLlmWikiSettingsActions();
|
|
const [apiUrl, setApiUrl] = useState("");
|
|
const [webUrl, setWebUrl] = useState("");
|
|
|
|
useEffect(() => {
|
|
if (!settings.data) return;
|
|
setApiUrl(settings.data.api_base_url || settings.data.file_api_base_url || "");
|
|
setWebUrl(settings.data.web_base_url || settings.data.file_web_base_url || "");
|
|
}, [settings.data]);
|
|
|
|
const status = useMemo(() => settings.data?.effective_provider === "weknora" ? "知识服务模式" : "原 LLMWiki 模式", [settings.data]);
|
|
if (settings.isLoading) return <div className="flex h-52 items-center justify-center"><Loader2 className="size-5 animate-spin" /></div>;
|
|
if (settings.error) return <div className="rounded-lg border border-destructive/30 p-5 text-sm text-destructive">{messageOf(settings.error)}</div>;
|
|
return (
|
|
<Card className="max-w-3xl">
|
|
<CardHeader><CardTitle className="flex items-center gap-2 text-base"><Settings2 className="size-5" />知识服务连接</CardTitle><CardDescription>这里只管理 cmzs 到知识服务的连接地址。数据库、Redis、模型、存储和解析器仍在服务端配置中维护。</CardDescription></CardHeader>
|
|
<CardContent className="space-y-5">
|
|
<div className="flex flex-wrap gap-2 text-sm"><Badge>{status}</Badge><Badge variant="secondary">服务端代理鉴权</Badge>{settings.data?.override_enabled && <Badge variant="outline">页面配置覆盖中</Badge>}</div>
|
|
<div className="space-y-2"><label className="text-sm font-medium" htmlFor="weknora-api-url">知识服务 API 地址</label><Input id="weknora-api-url" value={apiUrl} onChange={(event) => setApiUrl(event.target.value)} placeholder="http://knowledge-service:8080" /><p className="text-xs text-muted-foreground">非空启用知识服务;保存为空会切回原 LLMWiki。</p></div>
|
|
<div className="space-y-2"><label className="text-sm font-medium" htmlFor="weknora-web-url">知识服务管理地址(可选)</label><Input id="weknora-web-url" value={webUrl} onChange={(event) => setWebUrl(event.target.value)} placeholder="https://knowledge-admin.example.com" /></div>
|
|
<div className="rounded-lg border border-amber-500/30 bg-amber-500/5 p-3 text-xs text-muted-foreground">配置文件地址:{settings.data?.file_api_base_url || "未配置"}。页面只配置地址;免登录详情页所需的管理员账号/密码只从后端 config.yaml 或环境变量读取,不在前端保存。</div>
|
|
<div className="flex flex-wrap gap-2">
|
|
<Button variant="outline" disabled={!apiUrl.trim() || actions.test.isPending} onClick={async () => { try { await actions.test.mutateAsync(apiUrl.trim()); toast.success("知识服务连接正常"); } catch (error) { toast.error(messageOf(error)); } }}>{actions.test.isPending && <Loader2 className="mr-2 size-4 animate-spin" />}测试连接</Button>
|
|
<Button disabled={actions.save.isPending} onClick={async () => { try { await actions.save.mutateAsync({ override_enabled: true, api_base_url: apiUrl.trim(), web_base_url: webUrl.trim() }); toast.success(apiUrl.trim() ? "已启用知识服务模式" : "已切换到原 LLMWiki 模式"); } catch (error) { toast.error(messageOf(error)); } }}>{actions.save.isPending && <Loader2 className="mr-2 size-4 animate-spin" />}保存页面配置</Button>
|
|
<Button variant="secondary" disabled={actions.reset.isPending} onClick={async () => { try { await actions.reset.mutateAsync(); toast.success("已恢复 config.yaml 配置"); } catch (error) { toast.error(messageOf(error)); } }}>恢复配置文件</Button>
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
);
|
|
}
|
|
|
|
export default WeKnoraKnowledgeWorkspace;
|