Merge branch 'master' of http://192.168.0.200/knowledge-base-bj/deerflow-code into master-nj
Co-authored-by: Cursor <cursoragent@cursor.com> # Conflicts: # frontend-web/src/components/workspace/workspace-nav-chat-list.tsx # frontend-web/src/pages/WorkspaceRoutes.tsx # offline-backend-20260512/backend/app/gateway/app.py # offline-backend-20260512/backend/app/gateway/deps.py # offline-backend-20260512/backend/pyproject.toml
This commit is contained in:
commit
cf9fe58905
109 files changed
+18863
-982
No files matched your search
@@ -0,0 +1,514 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
import { apiFetch } from "@/core/api/fetch-client";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
|
||||
const BASE = () => `${getBackendBaseURL()}/api/assistant-knowledge`;
|
||||
|
||||
export interface AssistantKnowledgeBase {
|
||||
id: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
base_kind?: "global" | "custom";
|
||||
is_global?: boolean;
|
||||
status: string;
|
||||
source_count?: number;
|
||||
page_count?: number;
|
||||
entity_count?: number;
|
||||
relation_count?: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface AssistantWikiPage {
|
||||
id: string;
|
||||
base_id: string;
|
||||
slug: string;
|
||||
title: string;
|
||||
page_type: string;
|
||||
content_markdown: string;
|
||||
summary: string;
|
||||
current_revision_id?: string | null;
|
||||
updated_at: string;
|
||||
aliases?: string[];
|
||||
tags?: string[];
|
||||
category_path?: string[];
|
||||
parent_slug?: string;
|
||||
wiki_path?: string;
|
||||
in_links?: string[];
|
||||
out_links?: string[];
|
||||
source_refs?: string[];
|
||||
origins?: { mapping_id?: string; source_name: string; slug: string }[];
|
||||
matched_content?: string;
|
||||
matched_section?: {
|
||||
id?: string;
|
||||
section_index: number;
|
||||
heading?: string | null;
|
||||
content: string;
|
||||
score: number;
|
||||
source_chunk_id?: string | null;
|
||||
embedding_model?: string | null;
|
||||
embedding_fingerprint?: string | null;
|
||||
};
|
||||
}
|
||||
|
||||
export interface AssistantWikiRevision {
|
||||
id: string;
|
||||
page_id: string;
|
||||
revision_no: number;
|
||||
summary: string;
|
||||
content_markdown: string;
|
||||
change_type: string;
|
||||
created_by?: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface AssistantKnowledgeSource {
|
||||
id: string;
|
||||
base_id: string;
|
||||
source_type: "weknora" | "skill" | "local_file";
|
||||
source_name: string;
|
||||
source_key: string;
|
||||
status: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface AssistantImportJob {
|
||||
id: string;
|
||||
base_id: string;
|
||||
source_id: string;
|
||||
mirrored_global_base_id?: string;
|
||||
mirrored_global_job_id?: string;
|
||||
package_download_url?: string;
|
||||
trigger: string;
|
||||
status: string;
|
||||
phase: string;
|
||||
counts: Record<string, number>;
|
||||
last_error_message?: string | null;
|
||||
created_at: string;
|
||||
completed_at?: string | null;
|
||||
}
|
||||
|
||||
export interface LlmWikiExportPackageJob {
|
||||
id: string;
|
||||
mapping_id: string;
|
||||
status: string;
|
||||
phase: string;
|
||||
counts: Record<string, number>;
|
||||
package_download_url?: string;
|
||||
status_url?: string;
|
||||
error?: string | null;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
completed_at?: string | null;
|
||||
file_exists?: boolean;
|
||||
file_size_bytes?: number;
|
||||
}
|
||||
|
||||
async function readJson<T>(response: Response): Promise<T> {
|
||||
if (!response.ok) {
|
||||
const data = await response.json().catch(() => null);
|
||||
const detail =
|
||||
data && typeof data === "object" && "detail" in data
|
||||
? (data as { detail: unknown }).detail
|
||||
: `请求失败 (${response.status})`;
|
||||
throw new Error(
|
||||
typeof detail === "string" ? detail : JSON.stringify(detail),
|
||||
);
|
||||
}
|
||||
return (await response.json()) as T;
|
||||
}
|
||||
|
||||
function normalizeImportJob(job: AssistantImportJob): AssistantImportJob {
|
||||
const url = normalizeBackendUrl(job.package_download_url);
|
||||
return url ? { ...job, package_download_url: url } : job;
|
||||
}
|
||||
|
||||
function normalizeBackendUrl(
|
||||
url: string | undefined | null,
|
||||
): string | undefined {
|
||||
if (!url || /^https?:\/\//i.test(url)) return url || undefined;
|
||||
return `${getBackendBaseURL()}${url.startsWith("/") ? url : `/${url}`}`;
|
||||
}
|
||||
|
||||
function normalizeExportPackageJob(
|
||||
job: LlmWikiExportPackageJob,
|
||||
): LlmWikiExportPackageJob {
|
||||
return {
|
||||
...job,
|
||||
package_download_url: normalizeBackendUrl(job.package_download_url),
|
||||
status_url: normalizeBackendUrl(job.status_url),
|
||||
};
|
||||
}
|
||||
|
||||
export async function getAssistantKnowledgeBase() {
|
||||
const data = await readJson<{ base: AssistantKnowledgeBase | null }>(
|
||||
await apiFetch(`${BASE()}/base`),
|
||||
);
|
||||
return data.base;
|
||||
}
|
||||
|
||||
export async function getAssistantKnowledgeBaseById(baseId: string) {
|
||||
const data = await readJson<{ base: AssistantKnowledgeBase }>(
|
||||
await apiFetch(`${BASE()}/bases/${encodeURIComponent(baseId)}`),
|
||||
);
|
||||
return data.base;
|
||||
}
|
||||
|
||||
export async function listAssistantKnowledgeBases() {
|
||||
return (
|
||||
await readJson<{ bases: AssistantKnowledgeBase[] }>(
|
||||
await apiFetch(`${BASE()}/bases`),
|
||||
)
|
||||
).bases;
|
||||
}
|
||||
|
||||
export async function initializeAssistantKnowledgeBase(name = "知识梳理总库") {
|
||||
const data = await readJson<{ base: AssistantKnowledgeBase }>(
|
||||
await apiFetch(`${BASE()}/base/initialize`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name }),
|
||||
}),
|
||||
);
|
||||
return data.base;
|
||||
}
|
||||
|
||||
export async function createAssistantKnowledgeBase(input: {
|
||||
name: string;
|
||||
description?: string;
|
||||
}) {
|
||||
const data = await readJson<{ base: AssistantKnowledgeBase }>(
|
||||
await apiFetch(`${BASE()}/bases`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(input),
|
||||
}),
|
||||
);
|
||||
return data.base;
|
||||
}
|
||||
|
||||
export async function updateAssistantKnowledgeBase(input: {
|
||||
id: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
}) {
|
||||
const data = await readJson<{ base: AssistantKnowledgeBase }>(
|
||||
await apiFetch(`${BASE()}/bases/${encodeURIComponent(input.id)}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
name: input.name,
|
||||
description: input.description || "",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
return data.base;
|
||||
}
|
||||
|
||||
export async function deleteAssistantKnowledgeBase(id: string) {
|
||||
const response = await apiFetch(
|
||||
`${BASE()}/bases/${encodeURIComponent(id)}`,
|
||||
{ method: "DELETE" },
|
||||
);
|
||||
if (!response.ok) await readJson(response);
|
||||
}
|
||||
|
||||
function withBaseParam(baseId?: string | null) {
|
||||
const params = new URLSearchParams();
|
||||
if (baseId) params.set("base_id", baseId);
|
||||
return params;
|
||||
}
|
||||
|
||||
export async function listAssistantWikiPages(q = "", baseId?: string | null) {
|
||||
const params = withBaseParam(baseId);
|
||||
params.set("limit", "500");
|
||||
if (q.trim()) params.set("q", q.trim());
|
||||
const pages: AssistantWikiPage[] = [];
|
||||
let offset: number | null = 0;
|
||||
do {
|
||||
params.set("offset", String(offset));
|
||||
const batch: { pages: AssistantWikiPage[]; next_offset?: number | null } =
|
||||
await readJson(await apiFetch(`${BASE()}/wiki-pages?${params}`));
|
||||
pages.push(...batch.pages);
|
||||
offset = batch.next_offset ?? null;
|
||||
} while (offset !== null);
|
||||
return pages;
|
||||
}
|
||||
|
||||
export async function searchAssistantWiki(q: string, baseId: string) {
|
||||
return readJson<{
|
||||
results: (AssistantWikiPage & { score: number; retrieval_mode: string })[];
|
||||
retrieval_mode: string;
|
||||
}>(
|
||||
await apiFetch(
|
||||
`${BASE()}/search?${new URLSearchParams({ q, base_id: baseId })}`,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export async function listWikiTransfers(id: string, assistant: boolean) {
|
||||
const url = assistant
|
||||
? `${BASE()}/bases/${encodeURIComponent(id)}/export-package`
|
||||
: `${getBackendBaseURL()}/api/llmwiki/knowledge-bases/${encodeURIComponent(id)}/import-package`;
|
||||
return (
|
||||
await readJson<{ jobs: LlmWikiExportPackageJob[] }>(await apiFetch(url))
|
||||
).jobs.map(normalizeExportPackageJob);
|
||||
}
|
||||
|
||||
export async function createAssistantExportPackage(id: string) {
|
||||
return readJson<LlmWikiExportPackageJob>(
|
||||
await apiFetch(`${BASE()}/bases/${encodeURIComponent(id)}/export-package`, {
|
||||
method: "POST",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export async function importOrdinaryWikiPackage(id: string, file: File) {
|
||||
const body = new FormData();
|
||||
body.set("file", file);
|
||||
return readJson<LlmWikiExportPackageJob>(
|
||||
await apiFetch(
|
||||
`${getBackendBaseURL()}/api/llmwiki/knowledge-bases/${encodeURIComponent(id)}/import-package`,
|
||||
{ method: "POST", body },
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export async function listAssistantKnowledgeSources(baseId?: string | null) {
|
||||
const params = withBaseParam(baseId);
|
||||
return (
|
||||
await readJson<{ sources: AssistantKnowledgeSource[] }>(
|
||||
await apiFetch(`${BASE()}/sources?${params}`),
|
||||
)
|
||||
).sources;
|
||||
}
|
||||
|
||||
export async function listAssistantImportJobs(baseId?: string | null) {
|
||||
const params = withBaseParam(baseId);
|
||||
return (
|
||||
await readJson<{ jobs: AssistantImportJob[] }>(
|
||||
await apiFetch(`${BASE()}/import-jobs?${params}`),
|
||||
)
|
||||
).jobs.map(normalizeImportJob);
|
||||
}
|
||||
|
||||
export async function listAssistantWikiRevisions(
|
||||
slug: string,
|
||||
baseId?: string | null,
|
||||
) {
|
||||
const params = withBaseParam(baseId);
|
||||
return (
|
||||
await readJson<{ revisions: AssistantWikiRevision[] }>(
|
||||
await apiFetch(
|
||||
`${BASE()}/wiki-pages/${encodeURIComponent(slug)}/revisions?${params}`,
|
||||
),
|
||||
)
|
||||
).revisions;
|
||||
}
|
||||
|
||||
export async function rollbackAssistantWikiRevision(
|
||||
slug: string,
|
||||
revisionId: string,
|
||||
baseId?: string | null,
|
||||
) {
|
||||
const params = withBaseParam(baseId);
|
||||
return readJson<AssistantWikiRevision>(
|
||||
await apiFetch(
|
||||
`${BASE()}/wiki-pages/${encodeURIComponent(slug)}/revisions/${encodeURIComponent(revisionId)}/rollback?${params}`,
|
||||
{ method: "POST" },
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export async function exportLlmWikiToAssistant(
|
||||
mappingId: string,
|
||||
assistantBaseId?: string | null,
|
||||
) {
|
||||
return normalizeImportJob(
|
||||
await readJson<AssistantImportJob>(
|
||||
await apiFetch(
|
||||
`${getBackendBaseURL()}/api/llmwiki/knowledge-bases/${encodeURIComponent(mappingId)}/export-to-assistant`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ assistant_base_id: assistantBaseId || null }),
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export async function createLlmWikiExportPackage(mappingId: string) {
|
||||
return normalizeExportPackageJob(
|
||||
await readJson<LlmWikiExportPackageJob>(
|
||||
await apiFetch(
|
||||
`${getBackendBaseURL()}/api/llmwiki/knowledge-bases/${encodeURIComponent(mappingId)}/export-package`,
|
||||
{ method: "POST" },
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export async function listLlmWikiExportPackages(mappingId: string) {
|
||||
return (
|
||||
await readJson<{ jobs: LlmWikiExportPackageJob[] }>(
|
||||
await apiFetch(
|
||||
`${getBackendBaseURL()}/api/llmwiki/knowledge-bases/${encodeURIComponent(mappingId)}/export-package`,
|
||||
),
|
||||
)
|
||||
).jobs.map(normalizeExportPackageJob);
|
||||
}
|
||||
|
||||
export async function getLlmWikiExportPackageStatus(
|
||||
mappingId: string,
|
||||
jobId: string,
|
||||
) {
|
||||
return normalizeExportPackageJob(
|
||||
await readJson<LlmWikiExportPackageJob>(
|
||||
await apiFetch(
|
||||
`${getBackendBaseURL()}/api/llmwiki/knowledge-bases/${encodeURIComponent(mappingId)}/export-package/${encodeURIComponent(jobId)}`,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export async function reimportAssistantKnowledgeSource(sourceId: string) {
|
||||
return normalizeImportJob(
|
||||
await readJson<AssistantImportJob>(
|
||||
await apiFetch(
|
||||
`${BASE()}/sources/${encodeURIComponent(sourceId)}/reimport`,
|
||||
{
|
||||
method: "POST",
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export function getAssistantImportPackageUrl(jobId: string) {
|
||||
return `${BASE()}/import-jobs/${encodeURIComponent(jobId)}/package`;
|
||||
}
|
||||
|
||||
export async function uploadAssistantWeKnoraPackage(input: {
|
||||
file: File;
|
||||
assistantBaseId?: string | null;
|
||||
}) {
|
||||
const body = new FormData();
|
||||
body.set("file", input.file);
|
||||
if (input.assistantBaseId)
|
||||
body.set("assistant_base_id", input.assistantBaseId);
|
||||
return normalizeImportJob(
|
||||
await readJson<AssistantImportJob>(
|
||||
await apiFetch(`${BASE()}/imports/weknora-package`, {
|
||||
method: "POST",
|
||||
body,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export async function deleteAssistantKnowledgeSource(sourceId: string) {
|
||||
const response = await apiFetch(
|
||||
`${BASE()}/sources/${encodeURIComponent(sourceId)}`,
|
||||
{
|
||||
method: "DELETE",
|
||||
},
|
||||
);
|
||||
if (!response.ok) await readJson(response);
|
||||
}
|
||||
|
||||
const KEY = "assistant-knowledge";
|
||||
|
||||
export function useAssistantKnowledgeBase(baseId?: string | null) {
|
||||
return useQuery({
|
||||
queryKey: [KEY, "base", baseId ?? "global"],
|
||||
queryFn: () =>
|
||||
baseId
|
||||
? getAssistantKnowledgeBaseById(baseId)
|
||||
: getAssistantKnowledgeBase(),
|
||||
});
|
||||
}
|
||||
|
||||
export function useAssistantKnowledgeBases(enabled = true) {
|
||||
return useQuery({
|
||||
queryKey: [KEY, "bases"],
|
||||
queryFn: listAssistantKnowledgeBases,
|
||||
enabled,
|
||||
});
|
||||
}
|
||||
|
||||
export function useAssistantWikiPages(query = "", baseId?: string | null) {
|
||||
return useQuery({
|
||||
queryKey: [KEY, "pages", baseId ?? "global", query],
|
||||
queryFn: () => listAssistantWikiPages(query, baseId),
|
||||
});
|
||||
}
|
||||
|
||||
export function useAssistantKnowledgeSources(baseId?: string | null, enabled = true) {
|
||||
return useQuery({
|
||||
queryKey: [KEY, "sources", baseId ?? "global"],
|
||||
queryFn: () => listAssistantKnowledgeSources(baseId),
|
||||
enabled,
|
||||
});
|
||||
}
|
||||
|
||||
export function useAssistantImportJobs(baseId?: string | null) {
|
||||
return useQuery({
|
||||
queryKey: [KEY, "jobs", baseId ?? "global"],
|
||||
queryFn: () => listAssistantImportJobs(baseId),
|
||||
refetchInterval: (query) =>
|
||||
(query.state.data ?? []).some((job) =>
|
||||
["queued", "running"].includes(job.status),
|
||||
)
|
||||
? 3000
|
||||
: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function useAssistantKnowledgeActions() {
|
||||
const client = useQueryClient();
|
||||
const invalidate = () => client.invalidateQueries({ queryKey: [KEY] });
|
||||
return {
|
||||
initialize: useMutation({
|
||||
mutationFn: initializeAssistantKnowledgeBase,
|
||||
onSuccess: invalidate,
|
||||
}),
|
||||
createBase: useMutation({
|
||||
mutationFn: createAssistantKnowledgeBase,
|
||||
onSuccess: invalidate,
|
||||
}),
|
||||
updateBase: useMutation({
|
||||
mutationFn: updateAssistantKnowledgeBase,
|
||||
onSuccess: invalidate,
|
||||
}),
|
||||
deleteBase: useMutation({
|
||||
mutationFn: deleteAssistantKnowledgeBase,
|
||||
onSuccess: invalidate,
|
||||
}),
|
||||
uploadWeKnoraPackage: useMutation({
|
||||
mutationFn: uploadAssistantWeKnoraPackage,
|
||||
onSuccess: invalidate,
|
||||
}),
|
||||
reimportSource: useMutation({
|
||||
mutationFn: reimportAssistantKnowledgeSource,
|
||||
onSuccess: invalidate,
|
||||
}),
|
||||
deleteSource: useMutation({
|
||||
mutationFn: deleteAssistantKnowledgeSource,
|
||||
onSuccess: invalidate,
|
||||
}),
|
||||
rollback: useMutation({
|
||||
mutationFn: ({
|
||||
slug,
|
||||
revisionId,
|
||||
baseId,
|
||||
}: {
|
||||
slug: string;
|
||||
revisionId: string;
|
||||
baseId?: string | null;
|
||||
}) => rollbackAssistantWikiRevision(slug, revisionId, baseId),
|
||||
onSuccess: invalidate,
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
import { apiFetch } from "@/core/api/fetch-client";
|
||||
import { getCsrfToken } from "@/core/api/csrf";
|
||||
import { getAuthorizationHeaderValue } from "@/core/auth";
|
||||
import { useLiveAccount } from "@/core/auth/use-live-account";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
|
||||
@@ -29,7 +31,7 @@ export interface LlmWikiKnowledgeBase {
|
||||
remote_status: "available" | "missing";
|
||||
name: string;
|
||||
description: string;
|
||||
type: "document" | "faq";
|
||||
type: "document" | "faq" | "wiki";
|
||||
publication_status: "private" | "pending" | "published" | "rejected";
|
||||
owner_user_id?: string | null;
|
||||
is_owner: boolean;
|
||||
@@ -37,6 +39,12 @@ export interface LlmWikiKnowledgeBase {
|
||||
knowledge_count: number;
|
||||
chunk_count: number;
|
||||
processing_count: number;
|
||||
share_count?: number;
|
||||
is_processing?: boolean;
|
||||
is_temporary?: boolean;
|
||||
wiki_index_enabled?: boolean;
|
||||
external_search_enabled?: boolean;
|
||||
external_search_updated_at?: string | null;
|
||||
embedding_model_id?: string | null;
|
||||
vector_store_id?: string | null;
|
||||
vector_store_name?: string | null;
|
||||
@@ -44,19 +52,65 @@ export interface LlmWikiKnowledgeBase {
|
||||
vector_store_engine_type?: string | null;
|
||||
vector_store_status?: string | null;
|
||||
chunking_config?: Record<string, unknown>;
|
||||
image_processing_config?: Record<string, unknown>;
|
||||
indexing_strategy?: Record<string, boolean>;
|
||||
capabilities?: Record<string, boolean>;
|
||||
extract_config?: Record<string, unknown>;
|
||||
faq_config?: Record<string, unknown>;
|
||||
wiki_config?: Record<string, unknown>;
|
||||
question_generation_config?: Record<string, unknown>;
|
||||
auto_tag_config?: Record<string, unknown>;
|
||||
vlm_config?: Record<string, unknown>;
|
||||
asr_config?: Record<string, unknown>;
|
||||
summary_model_id?: string | null;
|
||||
storage_provider?: string | null;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
published_at?: string | null;
|
||||
remote_created_at?: string | null;
|
||||
remote_updated_at?: string | null;
|
||||
is_conversation_deposit?: boolean;
|
||||
}
|
||||
|
||||
export interface PublicLlmWikiKnowledgeBase extends LlmWikiKnowledgeBase {
|
||||
wiki: {
|
||||
status: "ready" | "empty" | "unavailable";
|
||||
page_count: number;
|
||||
loaded_page_count: number;
|
||||
stats_complete: boolean;
|
||||
page_type_counts: Record<string, number>;
|
||||
page_status_counts: Record<string, number>;
|
||||
index_mode: "explicit" | "generated" | "none" | "unknown";
|
||||
has_explicit_index: boolean;
|
||||
index_slug: string | null;
|
||||
default_slug: string | null;
|
||||
created_at: string | null;
|
||||
updated_at: string | null;
|
||||
embed_route: string;
|
||||
};
|
||||
local_index: {
|
||||
enabled: boolean;
|
||||
wiki_index_enabled: boolean;
|
||||
state: LlmWikiWikiIndexStatus["state"];
|
||||
fully_vectorized: boolean;
|
||||
retrieval_mode: "vector" | "wiki_api";
|
||||
remote_page_count: number;
|
||||
local_page_count: number;
|
||||
ready_page_count: number;
|
||||
failed_page_count: number;
|
||||
vector_count: number;
|
||||
last_started_at?: string | null;
|
||||
last_completed_at?: string | null;
|
||||
last_success_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
};
|
||||
}
|
||||
|
||||
export interface PublicLlmWikiKnowledgeBaseList {
|
||||
knowledge_bases: PublicLlmWikiKnowledgeBase[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface LlmWikiDocument {
|
||||
id: string;
|
||||
type?: string;
|
||||
@@ -115,6 +169,7 @@ export interface LlmWikiGraph {
|
||||
}
|
||||
|
||||
export interface LlmWikiWikiPage {
|
||||
page_metadata?: { tags?: string[]; [key: string]: unknown };
|
||||
id: string;
|
||||
slug: string;
|
||||
title: string;
|
||||
@@ -167,7 +222,14 @@ export interface LlmWikiWikiIndex {
|
||||
|
||||
export interface LlmWikiWikiIndexStatus {
|
||||
knowledge_base_id: string;
|
||||
state: "not_synced" | "idle" | "running" | "partial" | "failed" | "rebuilding" | "rebuild_required";
|
||||
state:
|
||||
| "not_synced"
|
||||
| "idle"
|
||||
| "running"
|
||||
| "partial"
|
||||
| "failed"
|
||||
| "rebuilding"
|
||||
| "rebuild_required";
|
||||
local_index_enabled: boolean;
|
||||
wiki_index_enabled: boolean;
|
||||
fully_vectorized: boolean;
|
||||
@@ -203,6 +265,25 @@ export interface LlmWikiWikiIndexStatus {
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface LocalWikiEncoderStatus {
|
||||
provider: string;
|
||||
model: string;
|
||||
dimensions?: number | null;
|
||||
state: "idle" | "starting" | "ready" | "failed";
|
||||
running: boolean;
|
||||
last_error?: string | null;
|
||||
started_at?: string | null;
|
||||
ready_at?: string | null;
|
||||
offline_only: boolean;
|
||||
model_path_configured: boolean;
|
||||
model_path_exists: boolean;
|
||||
model_files_ready: boolean;
|
||||
process_isolation: boolean;
|
||||
model_path: string;
|
||||
uploaded_files?: number;
|
||||
uploaded_bytes?: number;
|
||||
}
|
||||
|
||||
export interface LlmWikiSourceContext {
|
||||
knowledge_base_name?: string;
|
||||
document_title?: string;
|
||||
@@ -292,14 +373,16 @@ function userFacingKnowledgeMessage(value: string): string {
|
||||
async function readJson<T>(response: Response, context: string): Promise<T> {
|
||||
if (!response.ok) {
|
||||
const payload = await response.json().catch(() => null as unknown);
|
||||
const rawDetail = payload && typeof payload === "object" && "detail" in payload
|
||||
? (payload as { detail: unknown }).detail
|
||||
: null;
|
||||
const detail = rawDetail && typeof rawDetail === "object" && "message" in rawDetail
|
||||
? String((rawDetail as { message: unknown }).message)
|
||||
: rawDetail
|
||||
? String(rawDetail)
|
||||
: `${context}失败(${response.status})`;
|
||||
const rawDetail =
|
||||
payload && typeof payload === "object" && "detail" in payload
|
||||
? (payload as { detail: unknown }).detail
|
||||
: null;
|
||||
const detail =
|
||||
rawDetail && typeof rawDetail === "object" && "message" in rawDetail
|
||||
? String((rawDetail as { message: unknown }).message)
|
||||
: rawDetail
|
||||
? String(rawDetail)
|
||||
: `${context}失败(${response.status})`;
|
||||
throw new Error(userFacingKnowledgeMessage(detail));
|
||||
}
|
||||
if (response.status === 204) return undefined as T;
|
||||
@@ -307,10 +390,7 @@ async function readJson<T>(response: Response, context: string): Promise<T> {
|
||||
}
|
||||
|
||||
export async function getLlmWikiRuntime(): Promise<LlmWikiRuntime> {
|
||||
return readJson(
|
||||
await apiFetch(`${API()}/runtime`),
|
||||
"读取 LLMWiki 运行模式",
|
||||
);
|
||||
return readJson(await apiFetch(`${API()}/runtime`), "读取 LLMWiki 运行模式");
|
||||
}
|
||||
|
||||
export async function listLlmWikiKnowledgeBases(
|
||||
@@ -368,10 +448,10 @@ export async function getLlmWikiSourceContext(
|
||||
knowledge_base_id: knowledgeBaseId,
|
||||
chunk_id: chunkId,
|
||||
});
|
||||
const payload = await readJson<{ success: boolean; data: LlmWikiSourceContext }>(
|
||||
await apiFetch(`${API()}/sources/context?${params}`),
|
||||
"加载参考文献原文",
|
||||
);
|
||||
const payload = await readJson<{
|
||||
success: boolean;
|
||||
data: LlmWikiSourceContext;
|
||||
}>(await apiFetch(`${API()}/sources/context?${params}`), "加载参考文献原文");
|
||||
return payload.data;
|
||||
}
|
||||
|
||||
@@ -484,9 +564,13 @@ export async function getLlmWikiProtectedFileUrl(
|
||||
return `${PUBLIC_API()}/files/${encodeURIComponent(access.token)}`;
|
||||
}
|
||||
|
||||
export async function getLlmWikiGraph(knowledgeBaseId: string): Promise<LlmWikiGraph> {
|
||||
export async function getLlmWikiGraph(
|
||||
knowledgeBaseId: string,
|
||||
): Promise<LlmWikiGraph> {
|
||||
return readJson(
|
||||
await apiFetch(`${API()}/knowledge-bases/${encodeURIComponent(knowledgeBaseId)}/graph?limit=200`),
|
||||
await apiFetch(
|
||||
`${API()}/knowledge-bases/${encodeURIComponent(knowledgeBaseId)}/graph?limit=200`,
|
||||
),
|
||||
"读取知识图谱",
|
||||
);
|
||||
}
|
||||
@@ -497,7 +581,10 @@ export async function listLlmWikiWikiPages(
|
||||
pageSize: number,
|
||||
query = "",
|
||||
): Promise<LlmWikiWikiPageList> {
|
||||
const params = new URLSearchParams({ page: String(page), page_size: String(pageSize) });
|
||||
const params = new URLSearchParams({
|
||||
page: String(page),
|
||||
page_size: String(pageSize),
|
||||
});
|
||||
if (query.trim()) params.set("query", query.trim());
|
||||
return readJson(
|
||||
await apiFetch(
|
||||
@@ -543,6 +630,80 @@ export async function vectorizeLlmWikiKnowledgeBase(
|
||||
);
|
||||
}
|
||||
|
||||
export async function getLocalWikiEncoderStatus(): Promise<LocalWikiEncoderStatus> {
|
||||
return readJson(
|
||||
await apiFetch(`${API()}/local-encoder/status`),
|
||||
"读取本地编码器状态",
|
||||
);
|
||||
}
|
||||
|
||||
export async function startLocalWikiEncoder(): Promise<LocalWikiEncoderStatus> {
|
||||
return readJson(
|
||||
await apiFetch(`${API()}/local-encoder/start`, { method: "POST" }),
|
||||
"启动本地编码器",
|
||||
);
|
||||
}
|
||||
|
||||
export async function configureLocalWikiEncoder(
|
||||
modelPath: string,
|
||||
): Promise<LocalWikiEncoderStatus> {
|
||||
return readJson(
|
||||
await apiFetch(`${API()}/local-encoder/config`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ model_path: modelPath }),
|
||||
}),
|
||||
"保存本地编码器目录",
|
||||
);
|
||||
}
|
||||
|
||||
export async function uploadLocalWikiEncoder(
|
||||
files: File[],
|
||||
onProgress?: (percent: number) => void,
|
||||
): Promise<LocalWikiEncoderStatus> {
|
||||
const body = new FormData();
|
||||
for (const file of files) {
|
||||
const webkitPath = (file as File & { webkitRelativePath?: string }).webkitRelativePath || file.name;
|
||||
const parts = webkitPath.replace(/\\/g, "/").split("/").filter(Boolean);
|
||||
const relativePath = parts.length > 1 ? parts.slice(1).join("/") : parts[0];
|
||||
body.append("files", file, file.name);
|
||||
body.append("paths", relativePath);
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = new XMLHttpRequest();
|
||||
request.open("POST", `${API()}/local-encoder/upload`);
|
||||
request.withCredentials = true;
|
||||
const authorization = getAuthorizationHeaderValue();
|
||||
const csrf = getCsrfToken();
|
||||
if (authorization) request.setRequestHeader("Authorization", authorization);
|
||||
if (csrf) request.setRequestHeader("X-CSRF-Token", csrf);
|
||||
request.upload.onprogress = (event) => {
|
||||
if (event.lengthComputable && event.total > 0) {
|
||||
onProgress?.(Math.min(99, Math.round((event.loaded / event.total) * 100)));
|
||||
}
|
||||
};
|
||||
request.onerror = () => reject(new Error("上传本地编码器失败:网络连接中断"));
|
||||
request.onload = () => {
|
||||
let payload: unknown = null;
|
||||
try {
|
||||
payload = JSON.parse(request.responseText || "null");
|
||||
} catch {
|
||||
payload = null;
|
||||
}
|
||||
if (request.status < 200 || request.status >= 300) {
|
||||
const detail = payload && typeof payload === "object" && "detail" in payload
|
||||
? (payload as { detail: unknown }).detail
|
||||
: `请求失败 (${request.status})`;
|
||||
reject(new Error(typeof detail === "string" ? detail : JSON.stringify(detail)));
|
||||
return;
|
||||
}
|
||||
onProgress?.(100);
|
||||
resolve(payload as LocalWikiEncoderStatus);
|
||||
};
|
||||
request.send(body);
|
||||
});
|
||||
}
|
||||
|
||||
export async function exportLlmWikiWikiExcel(
|
||||
knowledgeBaseId: string,
|
||||
knowledgeBaseName = "LLMWiki",
|
||||
@@ -742,13 +903,23 @@ export async function getPublicLlmWikiKnowledgeBase(
|
||||
);
|
||||
}
|
||||
|
||||
export async function listPublicLlmWikiKnowledgeBases(): Promise<PublicLlmWikiKnowledgeBaseList> {
|
||||
return readJson(
|
||||
await apiFetch(`${PUBLIC_API()}/knowledge-bases`),
|
||||
"读取公开知识库列表",
|
||||
);
|
||||
}
|
||||
|
||||
export async function listPublicLlmWikiWikiPages(
|
||||
knowledgeBaseId: string,
|
||||
page: number,
|
||||
pageSize: number,
|
||||
query = "",
|
||||
): Promise<LlmWikiWikiPageList> {
|
||||
const params = new URLSearchParams({ page: String(page), page_size: String(pageSize) });
|
||||
const params = new URLSearchParams({
|
||||
page: String(page),
|
||||
page_size: String(pageSize),
|
||||
});
|
||||
if (query.trim()) params.set("query", query.trim());
|
||||
return readJson(
|
||||
await apiFetch(
|
||||
@@ -827,9 +998,7 @@ export async function resetLlmWikiSettings(): Promise<LlmWikiRuntime> {
|
||||
);
|
||||
}
|
||||
|
||||
export async function testLlmWikiConnection(
|
||||
apiBaseUrl: string,
|
||||
): Promise<void> {
|
||||
export async function testLlmWikiConnection(apiBaseUrl: string): Promise<void> {
|
||||
await readJson(
|
||||
await apiFetch(`${SETTINGS_API()}/test`, {
|
||||
method: "POST",
|
||||
@@ -854,10 +1023,7 @@ export function useLlmWikiRuntime() {
|
||||
});
|
||||
}
|
||||
|
||||
export function useLlmWikiKnowledgeBases(
|
||||
scope: LlmWikiScope,
|
||||
enabled = true,
|
||||
) {
|
||||
export function useLlmWikiKnowledgeBases(scope: LlmWikiScope, enabled = true) {
|
||||
const { userId } = useLiveAccount();
|
||||
return useQuery({
|
||||
queryKey: knowledgeBasesKey(userId, scope),
|
||||
@@ -873,7 +1039,13 @@ export function useAgentLlmWikiKnowledgeBases(
|
||||
) {
|
||||
const { userId } = useLiveAccount();
|
||||
return useQuery({
|
||||
queryKey: ["llmwiki", "agents", agentId, "knowledge-bases", userId ?? "anonymous"],
|
||||
queryKey: [
|
||||
"llmwiki",
|
||||
"agents",
|
||||
agentId,
|
||||
"knowledge-bases",
|
||||
userId ?? "anonymous",
|
||||
],
|
||||
queryFn: () => listAgentLlmWikiKnowledgeBases(agentId!),
|
||||
enabled: enabled && !!agentId,
|
||||
});
|
||||
@@ -885,7 +1057,12 @@ export function useLlmWikiKnowledgeBase(
|
||||
) {
|
||||
const { userId } = useLiveAccount();
|
||||
return useQuery({
|
||||
queryKey: ["llmwiki", "knowledge-base", knowledgeBaseId, userId ?? "anonymous"],
|
||||
queryKey: [
|
||||
"llmwiki",
|
||||
"knowledge-base",
|
||||
knowledgeBaseId,
|
||||
userId ?? "anonymous",
|
||||
],
|
||||
queryFn: () => getLlmWikiKnowledgeBase(knowledgeBaseId!),
|
||||
enabled: enabled && !!knowledgeBaseId,
|
||||
refetchInterval: 8_000,
|
||||
@@ -912,7 +1089,13 @@ export function useLlmWikiDocument(
|
||||
) {
|
||||
const { userId } = useLiveAccount();
|
||||
return useQuery({
|
||||
queryKey: ["llmwiki", "document", knowledgeBaseId, documentId, userId ?? "anonymous"],
|
||||
queryKey: [
|
||||
"llmwiki",
|
||||
"document",
|
||||
knowledgeBaseId,
|
||||
documentId,
|
||||
userId ?? "anonymous",
|
||||
],
|
||||
queryFn: () => getLlmWikiDocument(knowledgeBaseId!, documentId!),
|
||||
enabled: enabled && !!knowledgeBaseId && !!documentId,
|
||||
});
|
||||
@@ -927,13 +1110,25 @@ export function useLlmWikiDocumentChunks(
|
||||
) {
|
||||
const { userId } = useLiveAccount();
|
||||
return useQuery({
|
||||
queryKey: ["llmwiki", "document-chunks", knowledgeBaseId, documentId, page, pageSize, userId ?? "anonymous"],
|
||||
queryFn: () => listLlmWikiDocumentChunks(knowledgeBaseId!, documentId!, page, pageSize),
|
||||
queryKey: [
|
||||
"llmwiki",
|
||||
"document-chunks",
|
||||
knowledgeBaseId,
|
||||
documentId,
|
||||
page,
|
||||
pageSize,
|
||||
userId ?? "anonymous",
|
||||
],
|
||||
queryFn: () =>
|
||||
listLlmWikiDocumentChunks(knowledgeBaseId!, documentId!, page, pageSize),
|
||||
enabled: enabled && !!knowledgeBaseId && !!documentId,
|
||||
});
|
||||
}
|
||||
|
||||
export function useLlmWikiGraph(knowledgeBaseId: string | null, enabled = true) {
|
||||
export function useLlmWikiGraph(
|
||||
knowledgeBaseId: string | null,
|
||||
enabled = true,
|
||||
) {
|
||||
const { userId } = useLiveAccount();
|
||||
return useQuery({
|
||||
queryKey: ["llmwiki", "graph", knowledgeBaseId, userId ?? "anonymous"],
|
||||
@@ -951,8 +1146,17 @@ export function useLlmWikiWikiPages(
|
||||
) {
|
||||
const { userId } = useLiveAccount();
|
||||
return useQuery({
|
||||
queryKey: ["llmwiki", "wiki-pages", knowledgeBaseId, page, pageSize, query, userId ?? "anonymous"],
|
||||
queryFn: () => listLlmWikiWikiPages(knowledgeBaseId!, page, pageSize, query),
|
||||
queryKey: [
|
||||
"llmwiki",
|
||||
"wiki-pages",
|
||||
knowledgeBaseId,
|
||||
page,
|
||||
pageSize,
|
||||
query,
|
||||
userId ?? "anonymous",
|
||||
],
|
||||
queryFn: () =>
|
||||
listLlmWikiWikiPages(knowledgeBaseId!, page, pageSize, query),
|
||||
enabled: enabled && !!knowledgeBaseId,
|
||||
refetchInterval: 10_000,
|
||||
});
|
||||
@@ -965,7 +1169,13 @@ export function useLlmWikiWikiPage(
|
||||
) {
|
||||
const { userId } = useLiveAccount();
|
||||
return useQuery({
|
||||
queryKey: ["llmwiki", "wiki-page", knowledgeBaseId, slug, userId ?? "anonymous"],
|
||||
queryKey: [
|
||||
"llmwiki",
|
||||
"wiki-page",
|
||||
knowledgeBaseId,
|
||||
slug,
|
||||
userId ?? "anonymous",
|
||||
],
|
||||
queryFn: () => getLlmWikiWikiPage(knowledgeBaseId!, slug!),
|
||||
enabled: enabled && !!knowledgeBaseId && !!slug,
|
||||
});
|
||||
@@ -991,8 +1201,16 @@ export function usePublicLlmWikiWikiPages(
|
||||
enabled = true,
|
||||
) {
|
||||
return useQuery({
|
||||
queryKey: ["public-llmwiki", "wiki-pages", knowledgeBaseId, page, pageSize, query],
|
||||
queryFn: () => listPublicLlmWikiWikiPages(knowledgeBaseId!, page, pageSize, query),
|
||||
queryKey: [
|
||||
"public-llmwiki",
|
||||
"wiki-pages",
|
||||
knowledgeBaseId,
|
||||
page,
|
||||
pageSize,
|
||||
query,
|
||||
],
|
||||
queryFn: () =>
|
||||
listPublicLlmWikiWikiPages(knowledgeBaseId!, page, pageSize, query),
|
||||
enabled: enabled && !!knowledgeBaseId,
|
||||
staleTime: 60_000,
|
||||
});
|
||||
@@ -1029,7 +1247,12 @@ export function useLlmWikiWikiIndexStatus(
|
||||
) {
|
||||
const { userId } = useLiveAccount();
|
||||
return useQuery({
|
||||
queryKey: ["llmwiki", "wiki-index-status", knowledgeBaseId, userId ?? "anonymous"],
|
||||
queryKey: [
|
||||
"llmwiki",
|
||||
"wiki-index-status",
|
||||
knowledgeBaseId,
|
||||
userId ?? "anonymous",
|
||||
],
|
||||
queryFn: () => getLlmWikiWikiIndexStatus(knowledgeBaseId!),
|
||||
enabled: enabled && !!knowledgeBaseId,
|
||||
refetchInterval: (query) => {
|
||||
@@ -1058,8 +1281,14 @@ export function useLlmWikiActions() {
|
||||
onSuccess: invalidateKnowledge,
|
||||
}),
|
||||
update: useMutation({
|
||||
mutationFn: ({ id, ...input }: { id: string; name?: string; description?: string }) =>
|
||||
updateLlmWikiKnowledgeBase(id, input),
|
||||
mutationFn: ({
|
||||
id,
|
||||
...input
|
||||
}: {
|
||||
id: string;
|
||||
name?: string;
|
||||
description?: string;
|
||||
}) => updateLlmWikiKnowledgeBase(id, input),
|
||||
onSuccess: invalidateKnowledge,
|
||||
}),
|
||||
remove: useMutation({
|
||||
@@ -1077,8 +1306,15 @@ export function useLlmWikiActions() {
|
||||
onSuccess: invalidateKnowledge,
|
||||
}),
|
||||
createManual: useMutation({
|
||||
mutationFn: ({ id, title, content }: { id: string; title: string; content: string }) =>
|
||||
createManualLlmWikiDocument(id, { title, content }),
|
||||
mutationFn: ({
|
||||
id,
|
||||
title,
|
||||
content,
|
||||
}: {
|
||||
id: string;
|
||||
title: string;
|
||||
content: string;
|
||||
}) => createManualLlmWikiDocument(id, { title, content }),
|
||||
onSuccess: invalidateKnowledge,
|
||||
}),
|
||||
removeDocument: useMutation({
|
||||
@@ -1092,13 +1328,25 @@ export function useLlmWikiActions() {
|
||||
onSuccess: invalidateKnowledge,
|
||||
}),
|
||||
createWikiPage: useMutation({
|
||||
mutationFn: ({ id, input }: { id: string; input: LlmWikiWikiPageCreate }) =>
|
||||
createLlmWikiWikiPage(id, input),
|
||||
mutationFn: ({
|
||||
id,
|
||||
input,
|
||||
}: {
|
||||
id: string;
|
||||
input: LlmWikiWikiPageCreate;
|
||||
}) => createLlmWikiWikiPage(id, input),
|
||||
onSuccess: invalidateKnowledge,
|
||||
}),
|
||||
updateWikiPage: useMutation({
|
||||
mutationFn: ({ id, slug, input }: { id: string; slug: string; input: LlmWikiWikiPageUpdate }) =>
|
||||
updateLlmWikiWikiPage(id, slug, input),
|
||||
mutationFn: ({
|
||||
id,
|
||||
slug,
|
||||
input,
|
||||
}: {
|
||||
id: string;
|
||||
slug: string;
|
||||
input: LlmWikiWikiPageUpdate;
|
||||
}) => updateLlmWikiWikiPage(id, slug, input),
|
||||
onSuccess: invalidateKnowledge,
|
||||
}),
|
||||
removeWikiPage: useMutation({
|
||||
@@ -1128,8 +1376,14 @@ export function useLlmWikiSettingsActions() {
|
||||
await queryClient.invalidateQueries({ queryKey: ["llmwiki"] });
|
||||
};
|
||||
return {
|
||||
save: useMutation({ mutationFn: saveLlmWikiSettings, onSuccess: invalidate }),
|
||||
reset: useMutation({ mutationFn: resetLlmWikiSettings, onSuccess: invalidate }),
|
||||
save: useMutation({
|
||||
mutationFn: saveLlmWikiSettings,
|
||||
onSuccess: invalidate,
|
||||
}),
|
||||
reset: useMutation({
|
||||
mutationFn: resetLlmWikiSettings,
|
||||
onSuccess: invalidate,
|
||||
}),
|
||||
test: useMutation({ mutationFn: testLlmWikiConnection }),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
import { apiFetch } from "@/core/api/fetch-client";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
|
||||
const BASE = () => `${getBackendBaseURL()}/api/skill-knowledge`;
|
||||
|
||||
export type SkillKnowledgeTargetType = "weknora" | "assistant";
|
||||
export type SkillKnowledgeTargetMode =
|
||||
| "wiki"
|
||||
| "document"
|
||||
| "faq"
|
||||
| "conversation_archive"
|
||||
| "readonly_sidecar"
|
||||
| "assistant";
|
||||
|
||||
export interface SkillKnowledgeTarget {
|
||||
target_type: SkillKnowledgeTargetType;
|
||||
target_mode: SkillKnowledgeTargetMode;
|
||||
target_id: string;
|
||||
target_name: string;
|
||||
remote_business_key?: string | null;
|
||||
readonly?: boolean;
|
||||
}
|
||||
|
||||
export interface SkillKnowledgeBinding {
|
||||
id: string;
|
||||
skill_name: string;
|
||||
target_type: SkillKnowledgeTargetType;
|
||||
target_mode: SkillKnowledgeTargetMode;
|
||||
target_id: string;
|
||||
target_name: string;
|
||||
remote_business_key?: string | null;
|
||||
remote_refs?: Array<{
|
||||
provider: string;
|
||||
remote_kind: string;
|
||||
remote_id: string;
|
||||
slug?: string;
|
||||
}>;
|
||||
status: string;
|
||||
active: boolean;
|
||||
auto_sync_enabled: boolean;
|
||||
synced_digest?: string | null;
|
||||
last_synced_at?: string | null;
|
||||
last_error_message?: string | null;
|
||||
}
|
||||
|
||||
export interface SkillKnowledgeSyncItem {
|
||||
id: string;
|
||||
job_id: string;
|
||||
binding_id: string;
|
||||
skill_name: string;
|
||||
target_type: SkillKnowledgeTargetType;
|
||||
target_mode: SkillKnowledgeTargetMode;
|
||||
target_id: string;
|
||||
status: string;
|
||||
phase: string;
|
||||
progress: number;
|
||||
attempts: number;
|
||||
last_error_message?: string | null;
|
||||
}
|
||||
|
||||
export interface SkillKnowledgeJob {
|
||||
id: string;
|
||||
status: string;
|
||||
total_count: number;
|
||||
success_count: number;
|
||||
partial_failed_count: number;
|
||||
failed_count: number;
|
||||
review_mode: "required" | "auto_high_confidence" | "off";
|
||||
created_at: string;
|
||||
completed_at?: string | null;
|
||||
items?: SkillKnowledgeSyncItem[];
|
||||
}
|
||||
|
||||
export interface SkillKnowledgeReview {
|
||||
id: string;
|
||||
job_id: string;
|
||||
item_id: string;
|
||||
binding_id: string;
|
||||
object_type: "entity" | "relation" | "wiki" | "alignment";
|
||||
object_key: string;
|
||||
original: Record<string, unknown>;
|
||||
edited?: Record<string, unknown> | null;
|
||||
status: string;
|
||||
reason?: string | null;
|
||||
}
|
||||
|
||||
export interface SkillKnowledgeAutoSyncSettings {
|
||||
watch_enabled: boolean;
|
||||
schedule_enabled: boolean;
|
||||
schedule_cron: string;
|
||||
debounce_seconds: number;
|
||||
write_remote_enabled: boolean;
|
||||
review_mode: "required" | "auto_high_confidence" | "off";
|
||||
}
|
||||
|
||||
async function readJson<T>(response: Response): Promise<T> {
|
||||
if (!response.ok) {
|
||||
const data = await response.json().catch(() => null);
|
||||
const detail =
|
||||
data && typeof data === "object" && "detail" in data
|
||||
? JSON.stringify((data as { detail: unknown }).detail)
|
||||
: `请求失败 (${response.status})`;
|
||||
throw new Error(detail.replace(/^"|"$/g, ""));
|
||||
}
|
||||
return (await response.json()) as T;
|
||||
}
|
||||
|
||||
export async function listSkillKnowledgeBindings(
|
||||
skillNames?: string[],
|
||||
mineOnly = false,
|
||||
): Promise<SkillKnowledgeBinding[]> {
|
||||
const params = new URLSearchParams();
|
||||
for (const name of skillNames ?? []) params.append("skill_names", name);
|
||||
if (mineOnly) params.set("mine_only", "true");
|
||||
const response = await apiFetch(`${BASE()}/bindings?${params.toString()}`);
|
||||
return (await readJson<{ bindings: SkillKnowledgeBinding[] }>(response)).bindings;
|
||||
}
|
||||
|
||||
export async function createSkillKnowledgeJob(input: {
|
||||
skill_names: string[];
|
||||
targets: SkillKnowledgeTarget[];
|
||||
force?: boolean;
|
||||
review_mode?: "required" | "auto_high_confidence" | "off";
|
||||
}): Promise<SkillKnowledgeJob> {
|
||||
return readJson(
|
||||
await apiFetch(`${BASE()}/sync-jobs`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(input),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export async function listSkillKnowledgeJobs(mineOnly = false): Promise<SkillKnowledgeJob[]> {
|
||||
const params = mineOnly ? "?mine_only=true" : "";
|
||||
const response = await apiFetch(`${BASE()}/sync-jobs${params}`);
|
||||
return (await readJson<{ jobs: SkillKnowledgeJob[] }>(response)).jobs;
|
||||
}
|
||||
|
||||
export async function getSkillKnowledgeJob(id: string): Promise<SkillKnowledgeJob> {
|
||||
return readJson(await apiFetch(`${BASE()}/sync-jobs/${encodeURIComponent(id)}`));
|
||||
}
|
||||
|
||||
export async function listSkillKnowledgeReviews(): Promise<SkillKnowledgeReview[]> {
|
||||
const response = await apiFetch(`${BASE()}/reviews?status=pending`);
|
||||
return (await readJson<{ reviews: SkillKnowledgeReview[] }>(response)).reviews;
|
||||
}
|
||||
|
||||
export async function reviewSkillKnowledge(input: {
|
||||
review_ids: string[];
|
||||
action: "approve" | "reject";
|
||||
edits?: Record<string, Record<string, unknown>>;
|
||||
reason?: string;
|
||||
}) {
|
||||
return readJson<{ updated: number; resumed_item_ids: string[] }>(
|
||||
await apiFetch(`${BASE()}/reviews/actions`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(input),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export async function retrySkillKnowledgeItem(itemId: string) {
|
||||
return readJson<SkillKnowledgeSyncItem>(
|
||||
await apiFetch(`${BASE()}/sync-items/${encodeURIComponent(itemId)}/retry`, {
|
||||
method: "POST",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export async function detachSkillKnowledgeBinding(
|
||||
bindingId: string,
|
||||
deleteContributions: boolean,
|
||||
) {
|
||||
return readJson<SkillKnowledgeBinding>(
|
||||
await apiFetch(`${BASE()}/bindings/${encodeURIComponent(bindingId)}/detach`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ delete_contributions: deleteContributions }),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export async function resyncSkillKnowledgeBinding(bindingId: string) {
|
||||
return readJson<SkillKnowledgeJob>(
|
||||
await apiFetch(`${BASE()}/bindings/${encodeURIComponent(bindingId)}/resync`, {
|
||||
method: "POST",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export async function setSkillKnowledgeBindingAutoSync(
|
||||
bindingId: string,
|
||||
enabled: boolean,
|
||||
) {
|
||||
return readJson<SkillKnowledgeBinding>(
|
||||
await apiFetch(
|
||||
`${BASE()}/bindings/${encodeURIComponent(bindingId)}/${enabled ? "enable" : "disable"}-auto-sync`,
|
||||
{ method: "POST" },
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export async function getSkillKnowledgeAutoSyncSettings() {
|
||||
return readJson<SkillKnowledgeAutoSyncSettings>(
|
||||
await apiFetch(`${BASE()}/auto-sync-settings`),
|
||||
);
|
||||
}
|
||||
|
||||
export async function updateSkillKnowledgeAutoSyncSettings(
|
||||
input: Partial<SkillKnowledgeAutoSyncSettings>,
|
||||
) {
|
||||
return readJson<SkillKnowledgeAutoSyncSettings>(
|
||||
await apiFetch(`${BASE()}/auto-sync-settings`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(input),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const KEY = "skill-knowledge";
|
||||
|
||||
export function useSkillKnowledgeBindings(skillNames?: string[], mineOnly = false) {
|
||||
return useQuery({
|
||||
queryKey: [KEY, "bindings", mineOnly ? "mine" : "all", ...(skillNames ?? [])],
|
||||
queryFn: () => listSkillKnowledgeBindings(skillNames, mineOnly),
|
||||
refetchOnWindowFocus: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function useSkillKnowledgeJobs(mineOnly = false) {
|
||||
return useQuery({
|
||||
queryKey: [KEY, "jobs", mineOnly ? "mine" : "all"],
|
||||
queryFn: () => listSkillKnowledgeJobs(mineOnly),
|
||||
refetchInterval: (query) =>
|
||||
(query.state.data ?? []).some((job) => ["queued", "running"].includes(job.status))
|
||||
? 1500
|
||||
: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function useSkillKnowledgeReviews() {
|
||||
return useQuery({ queryKey: [KEY, "reviews"], queryFn: listSkillKnowledgeReviews });
|
||||
}
|
||||
|
||||
export function useSkillKnowledgeAutoSyncSettings() {
|
||||
return useQuery({
|
||||
queryKey: [KEY, "auto-sync-settings"],
|
||||
queryFn: getSkillKnowledgeAutoSyncSettings,
|
||||
});
|
||||
}
|
||||
|
||||
export function useSkillKnowledgeActions() {
|
||||
const client = useQueryClient();
|
||||
const invalidate = () => client.invalidateQueries({ queryKey: [KEY] });
|
||||
return {
|
||||
createJob: useMutation({ mutationFn: createSkillKnowledgeJob, onSuccess: invalidate }),
|
||||
review: useMutation({ mutationFn: reviewSkillKnowledge, onSuccess: invalidate }),
|
||||
retry: useMutation({ mutationFn: retrySkillKnowledgeItem, onSuccess: invalidate }),
|
||||
resync: useMutation({ mutationFn: resyncSkillKnowledgeBinding, onSuccess: invalidate }),
|
||||
setAutoSync: useMutation({
|
||||
mutationFn: ({ id, enabled }: { id: string; enabled: boolean }) =>
|
||||
setSkillKnowledgeBindingAutoSync(id, enabled),
|
||||
onSuccess: invalidate,
|
||||
}),
|
||||
updateAutoSyncSettings: useMutation({
|
||||
mutationFn: updateSkillKnowledgeAutoSyncSettings,
|
||||
onSuccess: invalidate,
|
||||
}),
|
||||
detach: useMutation({
|
||||
mutationFn: ({ id, deleteContributions }: { id: string; deleteContributions: boolean }) =>
|
||||
detachSkillKnowledgeBinding(id, deleteContributions),
|
||||
onSuccess: invalidate,
|
||||
}),
|
||||
};
|
||||
}
|
||||
+169
-53
@@ -1,6 +1,19 @@
|
||||
import { AlertCircle, Edit3, FileText, Loader2, RefreshCw, Trash2 } from "lucide-react";
|
||||
import {
|
||||
AlertCircle,
|
||||
Archive,
|
||||
Edit3,
|
||||
FileText,
|
||||
Loader2,
|
||||
RefreshCw,
|
||||
Trash2,
|
||||
} from "lucide-react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Navigate, useNavigate, useParams, useSearchParams } from "react-router-dom";
|
||||
import {
|
||||
Navigate,
|
||||
useNavigate,
|
||||
useParams,
|
||||
useSearchParams,
|
||||
} from "react-router-dom";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -14,6 +27,7 @@ import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { MarkdownCodeEditor } from "@/components/wiki/MarkdownCodeEditor";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
import { getStoredAuth } from "@/core/auth";
|
||||
import { buildWeKnoraWikiPagePath } from "@/core/llmwiki/source-links";
|
||||
import {
|
||||
createLlmWikiWeKnoraEmbedSession,
|
||||
@@ -34,7 +48,10 @@ type DeerFlowThemePayload = {
|
||||
|
||||
function cssVar(name: string, fallback = ""): string {
|
||||
if (typeof window === "undefined") return fallback;
|
||||
return getComputedStyle(document.documentElement).getPropertyValue(name).trim() || fallback;
|
||||
return (
|
||||
getComputedStyle(document.documentElement).getPropertyValue(name).trim() ||
|
||||
fallback
|
||||
);
|
||||
}
|
||||
|
||||
function collectThemePayload(): DeerFlowThemePayload {
|
||||
@@ -46,15 +63,27 @@ function collectThemePayload(): DeerFlowThemePayload {
|
||||
theme: isDark ? "dark" : "light",
|
||||
vars: {
|
||||
primary: cssVar("--primary", isDark ? "#2b81ff" : "#0062d9"),
|
||||
primaryForeground: cssVar("--button-foreground", cssVar("--primary-foreground", "#ffffff")),
|
||||
primaryForeground: cssVar(
|
||||
"--button-foreground",
|
||||
cssVar("--primary-foreground", "#ffffff"),
|
||||
),
|
||||
background: cssVar("--background", isDark ? "#0e172b" : "#ffffff"),
|
||||
foreground: cssVar("--foreground", isDark ? "#eff2f5" : "#202a3a"),
|
||||
card: cssVar("--card", isDark ? "#1a2539" : "#ffffff"),
|
||||
cardForeground: cssVar("--card-foreground", cssVar("--foreground", isDark ? "#eff2f5" : "#202a3a")),
|
||||
cardForeground: cssVar(
|
||||
"--card-foreground",
|
||||
cssVar("--foreground", isDark ? "#eff2f5" : "#202a3a"),
|
||||
),
|
||||
muted: cssVar("--muted", isDark ? "#232e40" : "#f3f5f8"),
|
||||
mutedForeground: cssVar("--muted-foreground", isDark ? "#8e9aa4" : "#7f7f7f"),
|
||||
mutedForeground: cssVar(
|
||||
"--muted-foreground",
|
||||
isDark ? "#8e9aa4" : "#7f7f7f",
|
||||
),
|
||||
border: cssVar("--border", isDark ? "rgba(255,255,255,0.12)" : "#dbdbdb"),
|
||||
popover: cssVar("--popover", cssVar("--card", isDark ? "#1a2539" : "#ffffff")),
|
||||
popover: cssVar(
|
||||
"--popover",
|
||||
cssVar("--card", isDark ? "#1a2539" : "#ffffff"),
|
||||
),
|
||||
destructive: cssVar("--destructive", "#d54941"),
|
||||
},
|
||||
};
|
||||
@@ -68,7 +97,8 @@ function postThemeToFrame(frame: HTMLIFrameElement | null) {
|
||||
try {
|
||||
const currentUrl = frame.contentWindow.location.href;
|
||||
if (!currentUrl || currentUrl === "about:blank") return;
|
||||
if (new URL(currentUrl, window.location.href).origin !== targetOrigin) return;
|
||||
if (new URL(currentUrl, window.location.href).origin !== targetOrigin)
|
||||
return;
|
||||
} catch {
|
||||
// Reading location throws once the iframe has reached the cross-origin backend.
|
||||
}
|
||||
@@ -89,7 +119,9 @@ function buildFrameUrl(framePath: string) {
|
||||
: framePath;
|
||||
return new URL(path, backendOrigin);
|
||||
}
|
||||
return new URL(`${backendBase || backendOrigin}/${framePath.replace(/^\/+/, "")}`);
|
||||
return new URL(
|
||||
`${backendBase || backendOrigin}/${framePath.replace(/^\/+/, "")}`,
|
||||
);
|
||||
}
|
||||
|
||||
export function WeKnoraKnowledgeDetailPage() {
|
||||
@@ -97,36 +129,57 @@ export function WeKnoraKnowledgeDetailPage() {
|
||||
knowledge_base_id: strategyKnowledgeBaseId,
|
||||
noteId: workspaceKnowledgeBaseId,
|
||||
} = useParams();
|
||||
const knowledgeBaseId = strategyKnowledgeBaseId ?? workspaceKnowledgeBaseId ?? "";
|
||||
const knowledgeBaseId =
|
||||
strategyKnowledgeBaseId ?? workspaceKnowledgeBaseId ?? "";
|
||||
const [searchParams] = useSearchParams();
|
||||
const navigate = useNavigate();
|
||||
const frameRef = useRef<HTMLIFrameElement>(null);
|
||||
const [frameSrc, setFrameSrc] = useState("");
|
||||
const [frameVersion, setFrameVersion] = useState(0);
|
||||
const [frameError, setFrameError] = useState<string | null>(null);
|
||||
const isAdmin = getStoredAuth()?.system_role === "admin";
|
||||
const runtime = useLlmWikiRuntime();
|
||||
const details = useLlmWikiKnowledgeBase(knowledgeBaseId || null, !!knowledgeBaseId);
|
||||
const details = useLlmWikiKnowledgeBase(
|
||||
knowledgeBaseId || null,
|
||||
!!knowledgeBaseId,
|
||||
);
|
||||
|
||||
const detailsReady = !!details.data;
|
||||
const requestedTab = searchParams.get("tab");
|
||||
const detailsWikiEnabled =
|
||||
details.data?.type === "wiki" ||
|
||||
details.data?.wiki_index_enabled === true ||
|
||||
details.data?.indexing_strategy?.wiki_enabled === true ||
|
||||
details.data?.capabilities?.wiki_enabled === true ||
|
||||
(details.data?.wiki_config &&
|
||||
Object.keys(details.data.wiki_config).length > 0);
|
||||
const preferredTab =
|
||||
requestedTab === "documents" || requestedTab === "wiki" || requestedTab === "graph"
|
||||
requestedTab === "documents" ||
|
||||
requestedTab === "wiki" ||
|
||||
requestedTab === "graph"
|
||||
? requestedTab
|
||||
: details.data?.indexing_strategy?.wiki_enabled
|
||||
: detailsWikiEnabled
|
||||
? "wiki"
|
||||
: "documents";
|
||||
const sourceChunkId = searchParams.get("sourceChunkId") || searchParams.get("chunkId") || "";
|
||||
const sourceChunkId =
|
||||
searchParams.get("sourceChunkId") || searchParams.get("chunkId") || "";
|
||||
const documentId = searchParams.get("documentId") || "";
|
||||
const wikiSlug = searchParams.get("wikiSlug") || "";
|
||||
const nativeWikiPageUrl = knowledgeBaseId && wikiSlug && preferredTab === "wiki"
|
||||
? buildWeKnoraWikiPagePath(knowledgeBaseId, wikiSlug)
|
||||
: "";
|
||||
const nativeWikiPageUrl =
|
||||
knowledgeBaseId && wikiSlug && preferredTab === "wiki"
|
||||
? buildWeKnoraWikiPagePath(knowledgeBaseId, wikiSlug)
|
||||
: "";
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
setFrameSrc("");
|
||||
setFrameError(null);
|
||||
if (nativeWikiPageUrl || !knowledgeBaseId || runtime.data?.provider !== "weknora" || !detailsReady) {
|
||||
if (
|
||||
nativeWikiPageUrl ||
|
||||
!knowledgeBaseId ||
|
||||
runtime.data?.provider !== "weknora" ||
|
||||
!detailsReady
|
||||
) {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
@@ -136,30 +189,47 @@ export function WeKnoraKnowledgeDetailPage() {
|
||||
const resolvedWikiSlug =
|
||||
wikiSlug ||
|
||||
(sourceChunkId
|
||||
? (await getLlmWikiSourceContext(knowledgeBaseId, sourceChunkId).catch(
|
||||
() => null,
|
||||
))?.wiki_page?.slug
|
||||
? (
|
||||
await getLlmWikiSourceContext(
|
||||
knowledgeBaseId,
|
||||
sourceChunkId,
|
||||
).catch(() => null)
|
||||
)?.wiki_page?.slug
|
||||
: "");
|
||||
const session = await createLlmWikiWeKnoraEmbedSession(knowledgeBaseId, preferredTab);
|
||||
if (cancelled) return;
|
||||
const framePath = session.frame_path || "";
|
||||
const nextUrl = buildFrameUrl(framePath);
|
||||
nextUrl.searchParams.set("theme", collectThemePayload().theme);
|
||||
if (sourceChunkId) nextUrl.searchParams.set("sourceChunkId", sourceChunkId);
|
||||
if (documentId) nextUrl.searchParams.set("documentId", documentId);
|
||||
if (resolvedWikiSlug) nextUrl.searchParams.set("wikiSlug", resolvedWikiSlug);
|
||||
setFrameSrc(nextUrl.toString());
|
||||
})()
|
||||
.catch((error: unknown) => {
|
||||
if (cancelled) return;
|
||||
const message = error instanceof Error ? error.message : "创建知识库详情会话失败";
|
||||
setFrameError(message);
|
||||
});
|
||||
const session = await createLlmWikiWeKnoraEmbedSession(
|
||||
knowledgeBaseId,
|
||||
preferredTab,
|
||||
);
|
||||
if (cancelled) return;
|
||||
const framePath = session.frame_path || "";
|
||||
const nextUrl = buildFrameUrl(framePath);
|
||||
nextUrl.searchParams.set("theme", collectThemePayload().theme);
|
||||
if (sourceChunkId)
|
||||
nextUrl.searchParams.set("sourceChunkId", sourceChunkId);
|
||||
if (documentId) nextUrl.searchParams.set("documentId", documentId);
|
||||
if (resolvedWikiSlug)
|
||||
nextUrl.searchParams.set("wikiSlug", resolvedWikiSlug);
|
||||
setFrameSrc(nextUrl.toString());
|
||||
})().catch((error: unknown) => {
|
||||
if (cancelled) return;
|
||||
const message =
|
||||
error instanceof Error ? error.message : "创建知识库详情会话失败";
|
||||
setFrameError(message);
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [detailsReady, documentId, knowledgeBaseId, nativeWikiPageUrl, preferredTab, runtime.data?.provider, sourceChunkId, wikiSlug]);
|
||||
}, [
|
||||
detailsReady,
|
||||
documentId,
|
||||
knowledgeBaseId,
|
||||
nativeWikiPageUrl,
|
||||
preferredTab,
|
||||
runtime.data?.provider,
|
||||
sourceChunkId,
|
||||
wikiSlug,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!frameSrc) return;
|
||||
@@ -192,7 +262,8 @@ export function WeKnoraKnowledgeDetailPage() {
|
||||
);
|
||||
}
|
||||
|
||||
if (runtime.data?.provider !== "weknora") return <Navigate to={LIST_PATH} replace />;
|
||||
if (runtime.data?.provider !== "weknora")
|
||||
return <Navigate to={LIST_PATH} replace />;
|
||||
|
||||
if (frameError) {
|
||||
return (
|
||||
@@ -201,7 +272,9 @@ export function WeKnoraKnowledgeDetailPage() {
|
||||
<AlertCircle className="size-6" />
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-base font-semibold text-foreground">无法打开知识库详情</div>
|
||||
<div className="text-base font-semibold text-foreground">
|
||||
无法打开知识库详情
|
||||
</div>
|
||||
<p className="mt-2 text-sm text-muted-foreground">{frameError}</p>
|
||||
</div>
|
||||
<Button variant="outline" onClick={() => navigate(LIST_PATH)}>
|
||||
@@ -218,7 +291,9 @@ export function WeKnoraKnowledgeDetailPage() {
|
||||
<AlertCircle className="size-6" />
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-base font-semibold text-foreground">无法打开知识库详情</div>
|
||||
<div className="text-base font-semibold text-foreground">
|
||||
无法打开知识库详情
|
||||
</div>
|
||||
<p className="mt-2 text-sm text-muted-foreground">
|
||||
当前账号没有访问权限,或知识服务资源已不存在。
|
||||
</p>
|
||||
@@ -230,10 +305,11 @@ export function WeKnoraKnowledgeDetailPage() {
|
||||
);
|
||||
}
|
||||
|
||||
const canWrite = details.data.can_write && !details.data.is_conversation_deposit;
|
||||
const canWrite =
|
||||
details.data.can_write && !details.data.is_conversation_deposit;
|
||||
const canEditCurrentWikiArticle =
|
||||
canWrite && !!details.data.indexing_strategy?.wiki_enabled && !!wikiSlug;
|
||||
const canManageWiki = canWrite && !!details.data.indexing_strategy?.wiki_enabled;
|
||||
canWrite && !!detailsWikiEnabled && !!wikiSlug;
|
||||
const canManageWiki = canWrite && !!detailsWikiEnabled;
|
||||
|
||||
return (
|
||||
<div className="flex h-full min-h-0 flex-col bg-background">
|
||||
@@ -246,19 +322,40 @@ export function WeKnoraKnowledgeDetailPage() {
|
||||
slug={wikiSlug}
|
||||
onChanged={() => setFrameVersion((value) => value + 1)}
|
||||
onDeleted={() => {
|
||||
navigate(`/page/workspace/knowledge/${encodeURIComponent(knowledgeBaseId)}?tab=wiki`, {
|
||||
replace: true,
|
||||
});
|
||||
navigate(
|
||||
`/page/workspace/knowledge/${encodeURIComponent(knowledgeBaseId)}?tab=wiki`,
|
||||
{
|
||||
replace: true,
|
||||
},
|
||||
);
|
||||
setFrameVersion((value) => value + 1);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
{isAdmin && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
navigate(
|
||||
`/page/workspace/knowledge/${encodeURIComponent(knowledgeBaseId)}/packages`,
|
||||
)
|
||||
}
|
||||
>
|
||||
<Archive className="mr-2 size-4" />
|
||||
数据包任务
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => navigate(`/page/workspace/knowledge/${encodeURIComponent(knowledgeBaseId)}/wiki`)}
|
||||
onClick={() =>
|
||||
navigate(
|
||||
`/page/workspace/knowledge/${encodeURIComponent(knowledgeBaseId)}/wiki`,
|
||||
)
|
||||
}
|
||||
>
|
||||
<FileText className="mr-2 size-4" />
|
||||
Wiki管理
|
||||
@@ -342,7 +439,12 @@ function CurrentWikiArticleActions({
|
||||
|
||||
const remove = async () => {
|
||||
if (!slug) return;
|
||||
if (!window.confirm(`确定删除文章「${detail.data?.title || slug}」吗?删除后不可恢复。`)) return;
|
||||
if (
|
||||
!window.confirm(
|
||||
`确定删除文章「${detail.data?.title || slug}」吗?删除后不可恢复。`,
|
||||
)
|
||||
)
|
||||
return;
|
||||
try {
|
||||
await actions.removeWikiPage.mutateAsync({ id: knowledgeBaseId, slug });
|
||||
toast.success("文章已删除");
|
||||
@@ -394,14 +496,18 @@ function CurrentWikiArticleActions({
|
||||
<label className="text-sm font-medium">标题</label>
|
||||
<Input
|
||||
value={draft.title}
|
||||
onChange={(event) => setDraft((prev) => ({ ...prev, title: event.target.value }))}
|
||||
onChange={(event) =>
|
||||
setDraft((prev) => ({ ...prev, title: event.target.value }))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-sm font-medium">摘要</label>
|
||||
<Textarea
|
||||
value={draft.summary}
|
||||
onChange={(event) => setDraft((prev) => ({ ...prev, summary: event.target.value }))}
|
||||
onChange={(event) =>
|
||||
setDraft((prev) => ({ ...prev, summary: event.target.value }))
|
||||
}
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
@@ -409,18 +515,28 @@ function CurrentWikiArticleActions({
|
||||
<label className="text-sm font-medium">正文</label>
|
||||
<MarkdownCodeEditor
|
||||
value={draft.content}
|
||||
onChange={(content) => setDraft((prev) => ({ ...prev, content }))}
|
||||
onChange={(content) =>
|
||||
setDraft((prev) => ({ ...prev, content }))
|
||||
}
|
||||
className="[&_.cm-editor]:min-h-[48vh]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-4 flex shrink-0 justify-end gap-2 border-t pt-3">
|
||||
<Button variant="outline" onClick={() => setOpen(false)} disabled={actions.updateWikiPage.isPending}>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setOpen(false)}
|
||||
disabled={actions.updateWikiPage.isPending}
|
||||
>
|
||||
取消
|
||||
</Button>
|
||||
<Button
|
||||
onClick={save}
|
||||
disabled={actions.updateWikiPage.isPending || !draft.title.trim() || !draft.content.trim()}
|
||||
disabled={
|
||||
actions.updateWikiPage.isPending ||
|
||||
!draft.title.trim() ||
|
||||
!draft.content.trim()
|
||||
}
|
||||
>
|
||||
{actions.updateWikiPage.isPending ? (
|
||||
<Loader2 className="mr-2 size-4 animate-spin" />
|
||||
|
||||
+215
-24
@@ -1,8 +1,11 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
BookOpen,
|
||||
BookOpenText,
|
||||
ChevronRight,
|
||||
Database,
|
||||
Cpu,
|
||||
Edit3,
|
||||
FileText,
|
||||
Globe2,
|
||||
Loader2,
|
||||
@@ -10,7 +13,9 @@ import {
|
||||
RefreshCw,
|
||||
Search,
|
||||
Settings2,
|
||||
Sparkles,
|
||||
Trash2,
|
||||
Upload,
|
||||
} from "lucide-react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
@@ -28,6 +33,7 @@ import {
|
||||
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";
|
||||
@@ -37,7 +43,11 @@ import {
|
||||
type LlmWikiSearchResponse,
|
||||
type LlmWikiSearchResult,
|
||||
type LlmWikiScope,
|
||||
configureLocalWikiEncoder,
|
||||
getLocalWikiEncoderStatus,
|
||||
searchLlmWiki,
|
||||
startLocalWikiEncoder,
|
||||
uploadLocalWikiEncoder,
|
||||
useLlmWikiActions,
|
||||
useLlmWikiKnowledgeBases,
|
||||
useLlmWikiSettings,
|
||||
@@ -83,7 +93,6 @@ function formatSearchTime(value?: string | null) {
|
||||
function resultPreview(result: LlmWikiSearchResult) {
|
||||
const text = (
|
||||
result.matched_sections?.map((section) => section.content).filter(Boolean).join("\n\n") ||
|
||||
result.summary ||
|
||||
result.content ||
|
||||
""
|
||||
);
|
||||
@@ -109,6 +118,7 @@ export function WeKnoraKnowledgeWorkspace() {
|
||||
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);
|
||||
@@ -119,12 +129,8 @@ export function WeKnoraKnowledgeWorkspace() {
|
||||
setSelectedSearchResult(null);
|
||||
}, [tab]);
|
||||
|
||||
const busy = actions.create.isPending || actions.remove.isPending || actions.publication.isPending;
|
||||
const busy = actions.create.isPending || actions.update.isPending || actions.remove.isPending || actions.publication.isPending;
|
||||
const openDetails = (item: LlmWikiKnowledgeBase) => {
|
||||
if (item.remote_status === "missing") {
|
||||
toast.error("该知识库已从知识服务删除,只能清理当前记录");
|
||||
return;
|
||||
}
|
||||
navigate(`${LIST_PATH}/${encodeURIComponent(item.id)}`);
|
||||
};
|
||||
|
||||
@@ -142,10 +148,7 @@ export function WeKnoraKnowledgeWorkspace() {
|
||||
};
|
||||
|
||||
const removeKnowledgeBase = async (item: LlmWikiKnowledgeBase) => {
|
||||
const warning = item.remote_status === "missing"
|
||||
? `知识库“${item.name}”已不在知识服务中。确定清理 cmzs 中的这条失效记录吗?`
|
||||
: `确定删除知识库“${item.name}”吗?知识服务中的文档和索引也会删除。`;
|
||||
if (!window.confirm(warning)) return;
|
||||
if (!window.confirm(`确定删除知识库“${item.name}”吗?知识服务中的文档和索引也会删除。`)) return;
|
||||
try {
|
||||
await actions.remove.mutateAsync(item.id);
|
||||
toast.success("知识库已删除");
|
||||
@@ -177,6 +180,11 @@ export function WeKnoraKnowledgeWorkspace() {
|
||||
<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" : ""}`} />刷新
|
||||
@@ -207,8 +215,8 @@ export function WeKnoraKnowledgeWorkspace() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
<TabsContent value="personal" className="mt-5"><KnowledgeGrid rows={knowledge.data ?? []} loading={knowledge.isLoading} error={knowledge.error} emptyText="还没有个人知识库,点击右上角创建。" busy={busy} onOpen={openDetails} 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} onPublish={togglePublication} onDelete={removeKnowledgeBase} /></TabsContent>
|
||||
<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>
|
||||
|
||||
@@ -301,6 +309,24 @@ export function WeKnoraKnowledgeWorkspace() {
|
||||
}}
|
||||
/>
|
||||
|
||||
{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);
|
||||
@@ -322,6 +348,7 @@ function KnowledgeGrid({
|
||||
emptyText,
|
||||
busy,
|
||||
onOpen,
|
||||
onEdit,
|
||||
onPublish,
|
||||
onDelete,
|
||||
}: {
|
||||
@@ -331,29 +358,27 @@ function KnowledgeGrid({
|
||||
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>;
|
||||
if (!rows.length) return <div className="flex h-64 items-center justify-center rounded-xl border border-dashed text-sm text-muted-foreground">{emptyText}</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">
|
||||
{rows.map((item) => (
|
||||
{visibleRows.map((item) => (
|
||||
<Card
|
||||
key={item.id}
|
||||
className={`group overflow-hidden rounded-2xl transition-all hover:-translate-y-0.5 hover:shadow-lg ${
|
||||
item.remote_status === "missing"
|
||||
? "border-amber-500/40 bg-amber-500/[0.03]"
|
||||
: "border-border/70 bg-card/95 hover:border-primary/30"
|
||||
}`}
|
||||
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" disabled={item.remote_status === "missing"} className="w-full text-left outline-none transition-colors enabled:hover:bg-muted/25 focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 disabled:cursor-default" onClick={() => onOpen(item)}>
|
||||
<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">{item.remote_status === "missing" ? <Badge variant="outline" className="border-amber-500/50 text-amber-700 dark:text-amber-300">远端已删除</Badge> : <Badge variant={item.publication_status === "published" ? "default" : "secondary"}>{publicationLabels[item.publication_status] ?? "仅自己"}</Badge>}{item.remote_status !== "missing" && 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 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>
|
||||
@@ -361,10 +386,11 @@ function KnowledgeGrid({
|
||||
<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">
|
||||
{item.remote_status === "missing" ? <span className="text-xs text-muted-foreground">知识服务资源不存在,可清理本地记录</span> : <Button size="sm" variant="outline" className="rounded-full" onClick={() => onOpen(item)}><FileText className="mr-2 size-4" />查看详情</Button>}
|
||||
{item.remote_status !== "missing" && 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>}
|
||||
<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.remote_status === "missing" ? `清理失效记录 ${item.name}` : `删除知识库 ${item.name}`} title={item.remote_status === "missing" ? "清理失效记录" : "删除知识库"} disabled={busy} onClick={() => void onDelete(item)}><Trash2 className="size-4" /></Button>}
|
||||
{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>
|
||||
@@ -373,6 +399,55 @@ function KnowledgeGrid({
|
||||
);
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -408,6 +483,122 @@ function CreateKnowledgeDialog({
|
||||
);
|
||||
}
|
||||
|
||||
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();
|
||||
|
||||
+221
@@ -0,0 +1,221 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
Archive,
|
||||
ArrowLeft,
|
||||
Download,
|
||||
HardDrive,
|
||||
Loader2,
|
||||
PackagePlus,
|
||||
RefreshCw,
|
||||
} from "lucide-react";
|
||||
import { Navigate, useNavigate, useParams } from "react-router-dom";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { KnowledgeProductNav } from "@/components/workspace/knowledge-product-nav";
|
||||
import { getStoredAuth } from "@/core/auth";
|
||||
import {
|
||||
createLlmWikiExportPackage,
|
||||
listLlmWikiExportPackages,
|
||||
} from "@/strategy-components/api/assistant-knowledge";
|
||||
import { useLlmWikiKnowledgeBase, useLlmWikiRuntime } from "@/strategy-components/api/llmwiki";
|
||||
import { WikiPackageTransfers } from "./WikiPackageTransfers";
|
||||
|
||||
const RUNNING = new Set(["queued", "running"]);
|
||||
const STATUS_LABEL: Record<string, string> = {
|
||||
queued: "排队中",
|
||||
running: "整理中",
|
||||
completed: "已完成",
|
||||
failed: "失败",
|
||||
};
|
||||
|
||||
function formatBytes(value?: number | null) {
|
||||
let current = Number(value || 0);
|
||||
if (!current) return "—";
|
||||
const units = ["B", "KB", "MB", "GB", "TB"];
|
||||
let unit = 0;
|
||||
while (current >= 1024 && unit < units.length - 1) {
|
||||
current /= 1024;
|
||||
unit += 1;
|
||||
}
|
||||
return `${current >= 10 || unit === 0 ? current.toFixed(0) : current.toFixed(1)} ${units[unit]}`;
|
||||
}
|
||||
|
||||
export default function WeKnoraPackageTransfersPage() {
|
||||
const { noteId = "" } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const queryClient = useQueryClient();
|
||||
const isAdmin = getStoredAuth()?.system_role === "admin";
|
||||
const runtime = useLlmWikiRuntime();
|
||||
const knowledge = useLlmWikiKnowledgeBase(noteId || null, !!noteId);
|
||||
const jobsKey = ["llmwiki-export-packages", noteId];
|
||||
const jobs = useQuery({
|
||||
queryKey: jobsKey,
|
||||
queryFn: () => listLlmWikiExportPackages(noteId),
|
||||
enabled: isAdmin && !!noteId && runtime.data?.provider === "weknora",
|
||||
refetchInterval: (query) =>
|
||||
query.state.data?.some((job) => RUNNING.has(job.status)) ? 3000 : false,
|
||||
});
|
||||
const createExport = useMutation({
|
||||
mutationFn: () => createLlmWikiExportPackage(noteId),
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: jobsKey });
|
||||
toast.success("已创建后台整理任务,完成后可在本页下载");
|
||||
},
|
||||
onError: (error) => toast.error(error.message),
|
||||
});
|
||||
if (!isAdmin) return <Navigate to="/page/workspace/knowledge" replace />;
|
||||
|
||||
return (
|
||||
<div className="flex size-full min-h-0 flex-col bg-muted/20">
|
||||
<KnowledgeProductNav />
|
||||
<main className="min-h-0 flex-1 overflow-auto px-5 py-6 lg:px-8">
|
||||
<div className="mx-auto max-w-6xl space-y-6">
|
||||
<header className="flex flex-wrap items-center justify-between gap-4">
|
||||
<div className="flex min-w-0 items-center gap-3">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() =>
|
||||
navigate(
|
||||
`/page/workspace/knowledge/${encodeURIComponent(noteId)}`,
|
||||
)
|
||||
}
|
||||
>
|
||||
<ArrowLeft className="size-5" />
|
||||
</Button>
|
||||
<div className="flex size-11 shrink-0 items-center justify-center rounded-xl bg-primary/10 text-primary">
|
||||
<Archive className="size-5" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<h1 className="truncate text-xl font-semibold">
|
||||
知识库数据包任务
|
||||
</h1>
|
||||
<p className="truncate text-sm text-muted-foreground">
|
||||
{knowledge.data?.name || "正在读取知识库"} ·
|
||||
大文件在后台整理,不占用详情页面
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => createExport.mutate()}
|
||||
disabled={createExport.isPending || !knowledge.data}
|
||||
>
|
||||
{createExport.isPending ? (
|
||||
<Loader2 className="mr-2 size-4 animate-spin" />
|
||||
) : (
|
||||
<PackagePlus className="mr-2 size-4" />
|
||||
)}
|
||||
新建导出任务
|
||||
</Button>
|
||||
</header>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex-row items-center justify-between space-y-0 border-b">
|
||||
<div>
|
||||
<CardTitle className="text-base">
|
||||
向量化数据包导出记录
|
||||
</CardTitle>
|
||||
<p className="mt-1 text-sm text-muted-foreground">
|
||||
每次生成独立记录;即使文件达到数
|
||||
GB,也只在后台落盘完成后提供下载。
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => void jobs.refetch()}
|
||||
disabled={jobs.isFetching}
|
||||
>
|
||||
<RefreshCw
|
||||
className={`mr-2 size-4 ${jobs.isFetching ? "animate-spin" : ""}`}
|
||||
/>
|
||||
刷新
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent className="p-0">
|
||||
{jobs.data?.map((job) => {
|
||||
const counts = job.counts || {};
|
||||
const ready =
|
||||
job.status === "completed" &&
|
||||
job.file_exists &&
|
||||
job.package_download_url;
|
||||
return (
|
||||
<div
|
||||
key={job.id}
|
||||
className="grid gap-4 border-b p-5 last:border-b-0 md:grid-cols-[auto_1fr_auto] md:items-center"
|
||||
>
|
||||
<div
|
||||
className={`flex size-10 items-center justify-center rounded-full ${job.status === "completed" ? "bg-emerald-100 text-emerald-700" : job.status === "failed" ? "bg-destructive/10 text-destructive" : "bg-amber-100 text-amber-700"}`}
|
||||
>
|
||||
{RUNNING.has(job.status) ? (
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
) : (
|
||||
<HardDrive className="size-4" />
|
||||
)}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="font-medium">
|
||||
任务 {job.id.slice(0, 8)}
|
||||
</span>
|
||||
<Badge variant="outline">
|
||||
{STATUS_LABEL[job.status] || job.status}
|
||||
</Badge>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{job.created_at
|
||||
? new Date(job.created_at).toLocaleString()
|
||||
: "—"}
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-2 flex flex-wrap gap-x-5 gap-y-1 text-sm text-muted-foreground">
|
||||
<span>
|
||||
Wiki {counts.wiki_page ?? counts.wiki_pages ?? 0}
|
||||
</span>
|
||||
<span>向量 {counts.vector ?? counts.vectors ?? 0}</span>
|
||||
<span>文件 {formatBytes(job.file_size_bytes)}</span>
|
||||
<span>阶段 {job.phase}</span>
|
||||
</div>
|
||||
{job.error && (
|
||||
<p className="mt-2 text-sm text-destructive">
|
||||
{job.error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{ready ? (
|
||||
<Button asChild variant="outline">
|
||||
<a href={job.package_download_url}>
|
||||
<Download className="mr-2 size-4" />
|
||||
下载数据包
|
||||
</a>
|
||||
</Button>
|
||||
) : (
|
||||
<Button variant="outline" disabled>
|
||||
{job.status === "failed" ? "整理失败" : "等待完成"}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{!jobs.isLoading && !jobs.data?.length && (
|
||||
<div className="px-6 py-14 text-center text-sm text-muted-foreground">
|
||||
暂无导出记录。点击右上角“新建导出任务”开始整理。
|
||||
</div>
|
||||
)}
|
||||
{jobs.isLoading && (
|
||||
<div className="flex items-center justify-center px-6 py-14 text-sm text-muted-foreground">
|
||||
<Loader2 className="mr-2 size-4 animate-spin" />
|
||||
加载导出记录
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<WikiPackageTransfers id={noteId} />
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+67
-8
@@ -52,8 +52,11 @@ import {
|
||||
usePublicLlmWikiWikiPages,
|
||||
} from "@/strategy-components/api/llmwiki";
|
||||
import { WikiProtectedImage } from "./WikiProtectedImage";
|
||||
import { WikiLibraryReader } from "./WikiLibraryReader";
|
||||
import { useAssistantKnowledgeBases, useAssistantKnowledgeSources } from "@/strategy-components/api/assistant-knowledge";
|
||||
|
||||
const LIST_PATH = "/page/workspace/knowledge";
|
||||
const GENERATED_PUBLIC_INDEX_SLUG = "__index__";
|
||||
|
||||
function cleanText(value?: string | null) {
|
||||
return (value || "").replace(/\r\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
|
||||
@@ -120,6 +123,10 @@ export function WeKnoraWikiPageView({
|
||||
const navigate = useNavigate();
|
||||
const publicBackground = usePublicBackground();
|
||||
const requestedWikiSlug = searchParams.get("wikiSlug")?.trim() || "";
|
||||
const assistantBases = useAssistantKnowledgeBases(!publicEmbed);
|
||||
const assistantSources = useAssistantKnowledgeSources(null, !publicEmbed);
|
||||
const globalBase = assistantBases.data?.find(base => base.is_global);
|
||||
const isDeposited = assistantSources.data?.some(source => source.source_key === noteId && source.status === "active");
|
||||
const privateKnowledgeBase = useLlmWikiKnowledgeBase(
|
||||
noteId || null,
|
||||
!!noteId && !publicEmbed,
|
||||
@@ -144,13 +151,40 @@ export function WeKnoraWikiPageView({
|
||||
!!noteId && publicEmbed,
|
||||
);
|
||||
const pages = publicEmbed ? publicPages : privatePages;
|
||||
const pagesList = useMemo(() => pages.data?.pages || [], [pages.data?.pages]);
|
||||
const indexPage = useMemo(
|
||||
() => (publicEmbed ? pagesList.find(isWikiIndexPage) : undefined),
|
||||
[pagesList, publicEmbed],
|
||||
const remotePagesList = useMemo(() => pages.data?.pages || [], [pages.data?.pages]);
|
||||
const explicitIndexPage = useMemo(
|
||||
() => (publicEmbed ? remotePagesList.find(isWikiIndexPage) : undefined),
|
||||
[publicEmbed, remotePagesList],
|
||||
);
|
||||
const generatedIndexPage = useMemo<LlmWikiWikiPage | undefined>(
|
||||
() => publicEmbed && remotePagesList.length > 0 && !explicitIndexPage
|
||||
? {
|
||||
id: "__generated_public_index__",
|
||||
slug: GENERATED_PUBLIC_INDEX_SLUG,
|
||||
title: "索引",
|
||||
page_type: "index",
|
||||
status: "generated",
|
||||
content: "# 索引\n\n知识库页面目录",
|
||||
summary: "",
|
||||
aliases: [],
|
||||
source_refs: [],
|
||||
in_links: [],
|
||||
out_links: [],
|
||||
version: 0,
|
||||
}
|
||||
: undefined,
|
||||
[explicitIndexPage, publicEmbed, remotePagesList.length],
|
||||
);
|
||||
const indexPage = explicitIndexPage || generatedIndexPage;
|
||||
const pagesList = useMemo(
|
||||
() => generatedIndexPage ? [generatedIndexPage, ...remotePagesList] : remotePagesList,
|
||||
[generatedIndexPage, remotePagesList],
|
||||
);
|
||||
const landingPage = useMemo(() => selectDefaultWikiPage(pagesList), [pagesList]);
|
||||
const wikiSlug = requestedWikiSlug || (publicEmbed ? landingPage?.slug || "" : "");
|
||||
const generatedIndexActive = generatedIndexPage?.slug === wikiSlug;
|
||||
const generatedIndexRequested =
|
||||
publicEmbed && wikiSlug === GENERATED_PUBLIC_INDEX_SLUG && !explicitIndexPage;
|
||||
const privatePage = useLlmWikiWikiPage(
|
||||
noteId || null,
|
||||
wikiSlug || null,
|
||||
@@ -159,7 +193,11 @@ export function WeKnoraWikiPageView({
|
||||
const publicPage = usePublicLlmWikiWikiPage(
|
||||
noteId || null,
|
||||
wikiSlug || null,
|
||||
!!noteId && !!wikiSlug && publicEmbed,
|
||||
!!noteId &&
|
||||
!!wikiSlug &&
|
||||
publicEmbed &&
|
||||
!generatedIndexActive &&
|
||||
!generatedIndexRequested,
|
||||
);
|
||||
const page = publicEmbed ? publicPage : privatePage;
|
||||
const publicWikiIndex = usePublicLlmWikiWikiIndex(
|
||||
@@ -170,7 +208,9 @@ export function WeKnoraWikiPageView({
|
||||
const [directoryQuery, setDirectoryQuery] = useState("");
|
||||
const [collapsedDirectories, setCollapsedDirectories] = useState<Set<string>>(() => new Set());
|
||||
const routedPage = (location.state as { wikiPage?: LlmWikiWikiPage } | null)?.wikiPage;
|
||||
const pageData = page.data || (routedPage?.slug === wikiSlug ? routedPage : undefined);
|
||||
const pageData = generatedIndexActive
|
||||
? generatedIndexPage
|
||||
: page.data || (routedPage?.slug === wikiSlug ? routedPage : undefined);
|
||||
const filteredPages = useMemo(
|
||||
() => filterWikiPagesWithAncestors(pagesList, directoryQuery),
|
||||
[directoryQuery, pagesList],
|
||||
@@ -345,6 +385,24 @@ export function WeKnoraWikiPageView({
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (publicEmbed && pages.error) {
|
||||
return (
|
||||
<div className="flex h-full flex-col items-center justify-center gap-4 px-6 text-center">
|
||||
<div className="flex size-12 items-center justify-center rounded-full bg-destructive/10 text-destructive">
|
||||
<BookOpenText className="size-6" />
|
||||
</div>
|
||||
<div>
|
||||
<div className="font-medium text-foreground">无法读取 Wiki 目录</div>
|
||||
<div className="mt-1 text-sm text-muted-foreground">
|
||||
{pages.error instanceof Error ? pages.error.message : "公开 Wiki 服务暂时不可用"}
|
||||
</div>
|
||||
</div>
|
||||
<Button onClick={() => void pages.refetch()}>
|
||||
<RefreshCw className="mr-2 size-4" />重试
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="flex h-full flex-col items-center justify-center gap-4 text-sm text-muted-foreground">
|
||||
{publicEmbed ? "该知识库暂无可展示的 Wiki 页面" : "当前链接缺少 Wiki 页面标识"}
|
||||
@@ -434,6 +492,7 @@ export function WeKnoraWikiPageView({
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{globalBase && isDeposited && <Button variant="outline" size="sm" onClick={() => navigate(`/page/workspace/knowledge/assistant?${new URLSearchParams({ base_id: globalBase.id, wikiSlug: pageData.slug })}`)}>在知识梳理中查看</Button>}
|
||||
<Button variant="outline" size="sm" onClick={() => void download("md")} disabled={downloading !== null}>
|
||||
{downloading === "md" ? <Loader2 className="size-4 animate-spin" /> : <Download className="size-4" />}
|
||||
下载 MD
|
||||
@@ -446,7 +505,7 @@ export function WeKnoraWikiPageView({
|
||||
</header>
|
||||
)}
|
||||
|
||||
<div className="flex min-h-0 flex-1 overflow-hidden">
|
||||
{!publicEmbed ? <WikiLibraryReader pages={pagesList} activePage={pageData} mappingId={noteId} onNavigate={slug => navigate(buildWeKnoraWikiPagePath(noteId, slug))} pageHref={slug => buildAppHashUrl(buildWeKnoraWikiPagePath(noteId, slug))} /> : <div className="flex min-h-0 flex-1 overflow-hidden">
|
||||
<aside className="flex w-64 shrink-0 flex-col border-r bg-background/90 lg:w-72">
|
||||
<div className="shrink-0 border-b px-3 py-3">
|
||||
<div className="flex items-center justify-between gap-3 px-1">
|
||||
@@ -531,7 +590,7 @@ export function WeKnoraWikiPageView({
|
||||
</section>
|
||||
</article>
|
||||
</main>
|
||||
</div>
|
||||
</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
+471
@@ -0,0 +1,471 @@
|
||||
import {
|
||||
BookOpenText,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
FileText,
|
||||
Folder,
|
||||
Link2,
|
||||
Network,
|
||||
Search,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { MarkdownContent } from "@/components/workspace/messages/markdown-content";
|
||||
import {
|
||||
buildWikiTree,
|
||||
filterWikiPagesWithAncestors,
|
||||
type WikiTreeNode,
|
||||
} from "@/core/llmwiki/wiki-tree";
|
||||
import {
|
||||
renderableWikiMarkdown,
|
||||
rewriteProtectedWikiImageSources,
|
||||
} from "@/core/llmwiki/wiki-page-markdown";
|
||||
import { reasoningPlugins } from "@/core/streamdown";
|
||||
import type { LlmWikiWikiPage } from "@/strategy-components/api/llmwiki";
|
||||
import { WikiProtectedImage } from "./WikiProtectedImage";
|
||||
|
||||
export type LibraryWikiPage = LlmWikiWikiPage & {
|
||||
tags?: string[];
|
||||
origins?: { mapping_id?: string; source_name: string; slug: string }[];
|
||||
};
|
||||
const TYPES: Record<string, string> = {
|
||||
index: "索引",
|
||||
summary: "摘要",
|
||||
entity: "实体",
|
||||
concept: "概念",
|
||||
synthesis: "综合分析",
|
||||
comparison: "对比分析",
|
||||
article: "文章",
|
||||
source: "资料",
|
||||
relation: "关系",
|
||||
};
|
||||
|
||||
export function WikiLibraryReader({
|
||||
pages,
|
||||
activePage,
|
||||
onNavigate,
|
||||
pageHref,
|
||||
mappingId,
|
||||
initiallyCollapseTree = false,
|
||||
}: {
|
||||
pages: LibraryWikiPage[];
|
||||
activePage: LibraryWikiPage | null;
|
||||
onNavigate: (slug: string) => void;
|
||||
pageHref: (slug: string) => string;
|
||||
mappingId?: string;
|
||||
initiallyCollapseTree?: boolean;
|
||||
}) {
|
||||
const [query, setQuery] = useState("");
|
||||
const [kind, setKind] = useState("");
|
||||
const [tag, setTag] = useState("");
|
||||
const [collapsed, setCollapsed] = useState<Set<string>>(new Set());
|
||||
const [graph, setGraph] = useState(false);
|
||||
const [directoryOpen, setDirectoryOpen] = useState(false);
|
||||
const initialTreeCollapseApplied = useRef(false);
|
||||
const navigate = (slug: string) => {
|
||||
onNavigate(slug);
|
||||
setDirectoryOpen(false);
|
||||
};
|
||||
const groups = useMemo(
|
||||
() => [...new Set(pages.map((p) => p.page_type))],
|
||||
[pages],
|
||||
);
|
||||
const tags = useMemo(
|
||||
() =>
|
||||
[
|
||||
...new Set(
|
||||
pages.flatMap((p) => [
|
||||
...(p.tags || p.page_metadata?.tags || []),
|
||||
...(p.aliases || []),
|
||||
]),
|
||||
),
|
||||
].sort(),
|
||||
[pages],
|
||||
);
|
||||
const tree = useMemo(
|
||||
() =>
|
||||
buildWikiTree(
|
||||
filterWikiPagesWithAncestors(
|
||||
pages.filter(
|
||||
(p) =>
|
||||
(!kind || p.page_type === kind) &&
|
||||
(!tag ||
|
||||
[
|
||||
...(p.tags || p.page_metadata?.tags || []),
|
||||
...(p.aliases || []),
|
||||
].includes(tag)),
|
||||
),
|
||||
query,
|
||||
),
|
||||
),
|
||||
[pages, kind, tag, query],
|
||||
);
|
||||
const bySlug = useMemo(() => new Map(pages.map((p) => [p.slug, p])), [pages]);
|
||||
useEffect(() => {
|
||||
const ancestors: string[] = [];
|
||||
const branches: string[] = [];
|
||||
const collectBranches = (nodes: WikiTreeNode[]) => {
|
||||
for (const node of nodes) {
|
||||
if (node.children.length) branches.push(node.key);
|
||||
collectBranches(node.children);
|
||||
}
|
||||
};
|
||||
const visit = (nodes: WikiTreeNode[], parents: string[]): boolean =>
|
||||
nodes.some((node) => {
|
||||
if (node.page?.slug === activePage?.slug) {
|
||||
ancestors.push(...parents);
|
||||
return true;
|
||||
}
|
||||
return visit(node.children, [...parents, node.key]);
|
||||
});
|
||||
collectBranches(tree.roots);
|
||||
visit(tree.roots, []);
|
||||
if (
|
||||
initiallyCollapseTree &&
|
||||
!initialTreeCollapseApplied.current &&
|
||||
tree.roots.length
|
||||
) {
|
||||
initialTreeCollapseApplied.current = true;
|
||||
setCollapsed(
|
||||
new Set(branches.filter((key) => !ancestors.includes(key))),
|
||||
);
|
||||
return;
|
||||
}
|
||||
setCollapsed(
|
||||
(current) =>
|
||||
new Set([...current].filter((key) => !ancestors.includes(key))),
|
||||
);
|
||||
}, [activePage?.slug, initiallyCollapseTree, tree]);
|
||||
const links = useMemo(() => {
|
||||
const outgoing = new Set(activePage?.out_links || []);
|
||||
for (const match of (activePage?.content || "").matchAll(
|
||||
/\[\[([^\]|]+)(?:\|[^\]]+)?\]\]/g,
|
||||
))
|
||||
outgoing.add(match[1].trim());
|
||||
const incoming = new Set(activePage?.in_links || []);
|
||||
for (const p of pages)
|
||||
if (
|
||||
p.slug !== activePage?.slug &&
|
||||
((p.out_links || []).includes(activePage?.slug || "") ||
|
||||
p.content?.includes(`[[${activePage?.slug}`))
|
||||
)
|
||||
incoming.add(p.slug);
|
||||
return {
|
||||
outgoing: [...outgoing].filter((s) => bySlug.has(s)),
|
||||
incoming: [...incoming].filter((s) => bySlug.has(s)),
|
||||
};
|
||||
}, [activePage, pages, bySlug]);
|
||||
const renderNode = (node: WikiTreeNode, depth = 0): React.ReactNode => {
|
||||
const active = activePage?.slug === node.page?.slug;
|
||||
const open = !!query || !collapsed.has(node.key);
|
||||
const toggle = () =>
|
||||
setCollapsed((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(node.key)) next.delete(node.key);
|
||||
else next.add(node.key);
|
||||
return next;
|
||||
});
|
||||
return (
|
||||
<div key={node.key}>
|
||||
<div
|
||||
style={{ paddingLeft: 8 + depth * 14 }}
|
||||
className={`flex items-center gap-1 rounded-lg pr-2 text-sm ${active ? "bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-200" : "text-muted-foreground hover:bg-muted"}`}
|
||||
>
|
||||
{node.children.length ? (
|
||||
<button
|
||||
aria-label={open ? "收起分类" : "展开分类"}
|
||||
onClick={toggle}
|
||||
className="p-1"
|
||||
>
|
||||
{open ? (
|
||||
<ChevronDown className="size-4" />
|
||||
) : (
|
||||
<ChevronRight className="size-4" />
|
||||
)}
|
||||
</button>
|
||||
) : (
|
||||
<span className="w-6" />
|
||||
)}
|
||||
<button
|
||||
onClick={() => (node.page ? navigate(node.page.slug) : toggle())}
|
||||
className="flex min-w-0 flex-1 items-center gap-2 py-2.5 text-left"
|
||||
aria-current={active ? "page" : undefined}
|
||||
>
|
||||
{node.page ? (
|
||||
<FileText className="size-4 shrink-0" />
|
||||
) : (
|
||||
<Folder className="size-4 shrink-0 text-amber-500" />
|
||||
)}
|
||||
<span className="truncate">{TYPES[node.label] || node.label}</span>
|
||||
</button>
|
||||
</div>
|
||||
{open && node.children.map((child) => renderNode(child, depth + 1))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
const renderLinks = (values: string[]) =>
|
||||
values.map((slug) => (
|
||||
<button
|
||||
key={slug}
|
||||
onClick={() => navigate(slug)}
|
||||
className="block w-full rounded-lg px-2 py-2 text-left text-sm text-primary hover:bg-muted"
|
||||
>
|
||||
<Link2 className="mr-2 inline size-3.5" />
|
||||
{bySlug.get(slug)?.title || slug}
|
||||
</button>
|
||||
));
|
||||
return (
|
||||
<div className="relative flex min-h-0 flex-1 overflow-hidden bg-muted/20">
|
||||
{directoryOpen && (
|
||||
<button
|
||||
aria-label="关闭 Wiki 目录"
|
||||
className="absolute inset-0 z-20 bg-black/30 md:hidden"
|
||||
onClick={() => setDirectoryOpen(false)}
|
||||
/>
|
||||
)}
|
||||
<aside
|
||||
className={`${directoryOpen ? "flex" : "hidden"} absolute inset-y-0 left-0 z-30 w-64 shrink-0 flex-col border-r bg-background md:static md:z-auto md:flex lg:w-72`}
|
||||
>
|
||||
<div className="space-y-3 border-b p-4">
|
||||
<div className="flex items-center gap-2 font-semibold">
|
||||
<BookOpenText className="size-4 text-emerald-600" />
|
||||
Wiki 目录
|
||||
<span className="ml-auto text-xs font-normal text-muted-foreground">
|
||||
{pages.length} 篇
|
||||
</span>
|
||||
<button
|
||||
className="md:hidden"
|
||||
aria-label="收起 Wiki 目录"
|
||||
onClick={() => setDirectoryOpen(false)}
|
||||
>
|
||||
<X className="size-4" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="relative">
|
||||
<Search className="absolute left-2 top-3 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
placeholder="搜索标题、分类或标签"
|
||||
className="pl-8"
|
||||
/>
|
||||
</div>
|
||||
<select
|
||||
aria-label="Wiki 分类"
|
||||
className="h-9 w-full rounded-md border bg-background px-2 text-sm"
|
||||
value={kind}
|
||||
onChange={(e) => setKind(e.target.value)}
|
||||
>
|
||||
<option value="">全部类型</option>
|
||||
{groups.map((k) => (
|
||||
<option key={k} value={k}>
|
||||
{TYPES[k] || k}({pages.filter((p) => p.page_type === k).length}
|
||||
)
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{tags.length > 0 && (
|
||||
<select
|
||||
aria-label="Wiki 标签"
|
||||
className="h-9 w-full rounded-md border bg-background px-2 text-sm"
|
||||
value={tag}
|
||||
onChange={(e) => setTag(e.target.value)}
|
||||
>
|
||||
<option value="">全部标签</option>
|
||||
{tags.map((t) => (
|
||||
<option key={t}>{t}</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
</div>
|
||||
<nav
|
||||
className="min-h-0 flex-1 overflow-auto p-2"
|
||||
aria-label="Wiki 目录"
|
||||
>
|
||||
{tree.roots.map((node) => renderNode(node))}
|
||||
{!tree.roots.length && (
|
||||
<p className="p-4 text-sm text-muted-foreground">暂无匹配页面</p>
|
||||
)}
|
||||
</nav>
|
||||
</aside>
|
||||
<main className="min-w-0 flex-1 overflow-auto p-3 md:p-5 lg:p-8">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="mb-3 md:hidden"
|
||||
onClick={() => setDirectoryOpen(true)}
|
||||
>
|
||||
<BookOpenText className="mr-2 size-4" />
|
||||
目录与分类({pages.length})
|
||||
</Button>
|
||||
{activePage ? (
|
||||
<article className="mx-auto max-w-5xl rounded-2xl border bg-background shadow-sm">
|
||||
<header className="space-y-3 border-b p-4 md:px-7 md:py-6">
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{(activePage.category_path || []).join(" / ") || "知识库 Wiki"}
|
||||
</div>
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<h1 className="text-2xl font-semibold tracking-tight">
|
||||
{activePage.title}
|
||||
</h1>
|
||||
<Badge variant="outline">
|
||||
{TYPES[activePage.page_type] || activePage.page_type}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{[
|
||||
...new Set([
|
||||
...(activePage.tags ||
|
||||
activePage.page_metadata?.tags ||
|
||||
[]),
|
||||
...(activePage.aliases || []),
|
||||
]),
|
||||
].map((t) => (
|
||||
<button
|
||||
key={t}
|
||||
onClick={() => {
|
||||
setTag(t);
|
||||
setDirectoryOpen(true);
|
||||
}}
|
||||
>
|
||||
<Badge variant="secondary">{t}</Badge>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{activePage.summary && (
|
||||
<p className="text-sm leading-7 text-muted-foreground">
|
||||
{activePage.summary}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-3 text-xs text-muted-foreground">
|
||||
{activePage.updated_at && (
|
||||
<span>
|
||||
更新于 {new Date(activePage.updated_at).toLocaleString()}
|
||||
</span>
|
||||
)}
|
||||
<span>
|
||||
{links.outgoing.length} 个引用 · {links.incoming.length}{" "}
|
||||
个反向链接
|
||||
</span>
|
||||
</div>
|
||||
</header>
|
||||
<section className="px-4 py-6 md:px-7 md:py-8 lg:px-10">
|
||||
<MarkdownContent
|
||||
content={rewriteProtectedWikiImageSources(
|
||||
renderableWikiMarkdown(
|
||||
activePage.title,
|
||||
activePage.content,
|
||||
mappingId || "assistant",
|
||||
(_id, slug) => pageHref(slug),
|
||||
pages,
|
||||
).replace(/^# [^\n]*(?:\n|$)/, ""),
|
||||
)}
|
||||
isLoading={false}
|
||||
remarkPlugins={reasoningPlugins.remarkPlugins}
|
||||
rehypePlugins={reasoningPlugins.rehypePlugins}
|
||||
components={
|
||||
mappingId
|
||||
? {
|
||||
img: (props) => (
|
||||
<WikiProtectedImage
|
||||
{...props}
|
||||
knowledgeBaseId={mappingId}
|
||||
/>
|
||||
),
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
linkClassName={(href) =>
|
||||
pages.some((p) => pageHref(p.slug) === href)
|
||||
? "wiki-content-link !text-primary border-b border-dashed"
|
||||
: undefined
|
||||
}
|
||||
onLinkClick={(event, href) => {
|
||||
const target = pages.find(
|
||||
(p) =>
|
||||
pageHref(p.slug) === href ||
|
||||
href === p.slug ||
|
||||
href === `/${p.slug}`,
|
||||
);
|
||||
if (target) {
|
||||
event.preventDefault();
|
||||
navigate(target.slug);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</section>
|
||||
<section className="border-t px-4 py-5 md:px-7">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setGraph(!graph)}
|
||||
>
|
||||
<Network className="mr-2 size-4" />
|
||||
{graph ? "收起关系图谱" : "查看关系图谱"}
|
||||
</Button>
|
||||
{graph && (
|
||||
<div className="my-4 grid grid-cols-3 items-center gap-3 rounded-xl bg-muted/40 p-4">
|
||||
<div>
|
||||
{renderLinks(links.incoming)}
|
||||
{!links.incoming.length && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
暂无反向链接
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="rounded-xl border border-primary/30 bg-primary/10 p-4 text-center text-sm font-medium">
|
||||
→ {activePage.title} →
|
||||
</div>
|
||||
<div>
|
||||
{renderLinks(links.outgoing)}
|
||||
{!links.outgoing.length && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
暂无引用
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="grid gap-5 sm:grid-cols-2">
|
||||
<div>
|
||||
<h3 className="my-2 text-sm font-medium">引用页面</h3>
|
||||
{renderLinks(links.outgoing)}
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="my-2 text-sm font-medium">被哪些页面引用</h3>
|
||||
{renderLinks(links.incoming)}
|
||||
</div>
|
||||
</div>
|
||||
{(activePage.origins || [])
|
||||
.filter(
|
||||
(o, index, all) =>
|
||||
o.mapping_id &&
|
||||
all.findIndex(
|
||||
(value) =>
|
||||
value.mapping_id === o.mapping_id &&
|
||||
value.slug === o.slug,
|
||||
) === index,
|
||||
)
|
||||
.map((o) => (
|
||||
<a
|
||||
key={`${o.mapping_id}:${o.slug}`}
|
||||
className="mt-3 block text-xs text-primary hover:underline"
|
||||
href={`#/page/workspace/knowledge/${encodeURIComponent(o.mapping_id!)}/wiki/view?wikiSlug=${encodeURIComponent(o.slug)}`}
|
||||
>
|
||||
查看普通知识库来源 · {o.source_name}
|
||||
</a>
|
||||
))}
|
||||
</section>
|
||||
</article>
|
||||
) : (
|
||||
<div className="py-20 text-center text-sm text-muted-foreground">
|
||||
选择一个 Wiki 页面开始阅读。完成向量化的数据会自动沉淀到知识梳理。
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { Download, Loader2, Upload } from "lucide-react";
|
||||
import { useRef } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import {
|
||||
createAssistantExportPackage,
|
||||
importOrdinaryWikiPackage,
|
||||
listWikiTransfers,
|
||||
} from "@/strategy-components/api/assistant-knowledge";
|
||||
|
||||
export function WikiPackageTransfers({
|
||||
id,
|
||||
assistant = false,
|
||||
}: {
|
||||
id: string;
|
||||
assistant?: boolean;
|
||||
}) {
|
||||
const input = useRef<HTMLInputElement>(null);
|
||||
const client = useQueryClient();
|
||||
const key = ["wiki-transfers", assistant, id];
|
||||
const jobs = useQuery({
|
||||
queryKey: key,
|
||||
queryFn: () => listWikiTransfers(id, assistant),
|
||||
refetchInterval: (q) =>
|
||||
q.state.data?.some((j) => ["queued", "running"].includes(j.status))
|
||||
? 3000
|
||||
: false,
|
||||
});
|
||||
const action = useMutation({
|
||||
mutationFn: (file?: File) =>
|
||||
assistant
|
||||
? createAssistantExportPackage(id)
|
||||
: importOrdinaryWikiPackage(id, file!),
|
||||
onSuccess: () => {
|
||||
void client.invalidateQueries({ queryKey: key });
|
||||
toast.success(
|
||||
assistant
|
||||
? "已创建导出记录,整理完成后可下载"
|
||||
: "文件已上传,后台正在校验并导入原有 Wiki 和向量",
|
||||
);
|
||||
},
|
||||
onError: (e) => toast.error(e.message),
|
||||
});
|
||||
return (
|
||||
<div className="space-y-3 rounded-xl border bg-card p-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<h3 className="text-sm font-semibold">
|
||||
{assistant ? "导出 Wiki 向量数据包" : "导入 Wiki 向量数据包"}
|
||||
</h3>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
{assistant
|
||||
? "保留正文、分类、标签、链接和原始向量;后台整理完成后下载。"
|
||||
: "选择助手知识库导出的文件,导入当前空库。模型一致时直接复用向量。"}
|
||||
</p>
|
||||
</div>
|
||||
<input
|
||||
type="file"
|
||||
accept=".jsonl,.ndjson"
|
||||
ref={input}
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
const f = e.target.files?.[0];
|
||||
if (f) action.mutate(f);
|
||||
e.target.value = "";
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={action.isPending}
|
||||
onClick={() =>
|
||||
assistant ? action.mutate(undefined) : input.current?.click()
|
||||
}
|
||||
>
|
||||
{action.isPending ? (
|
||||
<Loader2 className="mr-2 size-4 animate-spin" />
|
||||
) : assistant ? (
|
||||
<Download className="mr-2 size-4" />
|
||||
) : (
|
||||
<Upload className="mr-2 size-4" />
|
||||
)}
|
||||
{assistant ? "生成导出包" : "上传并导入"}
|
||||
</Button>
|
||||
</div>
|
||||
{jobs.error && (
|
||||
<p className="text-sm text-destructive">{jobs.error.message}</p>
|
||||
)}
|
||||
{jobs.data?.map((job) => (
|
||||
<div
|
||||
key={job.id}
|
||||
className="flex flex-wrap items-center gap-3 border-t pt-3 text-xs"
|
||||
>
|
||||
<Badge variant="outline">
|
||||
{{
|
||||
queued: "排队中",
|
||||
running: "处理中",
|
||||
failed: "失败",
|
||||
completed: "已完成",
|
||||
}[job.status] || job.status}
|
||||
</Badge>
|
||||
<span>
|
||||
{job.created_at && new Date(job.created_at).toLocaleString()}
|
||||
</span>
|
||||
<span>
|
||||
{job.counts?.wiki_page || 0} Wiki · {job.counts?.vector || 0} 向量
|
||||
</span>
|
||||
{job.file_size_bytes ? (
|
||||
<span>{(job.file_size_bytes / 1024 / 1024).toFixed(2)} MB</span>
|
||||
) : null}
|
||||
{job.error && <span className="text-destructive">{job.error}</span>}
|
||||
{assistant &&
|
||||
job.status === "completed" &&
|
||||
job.file_exists &&
|
||||
job.package_download_url && (
|
||||
<Button asChild size="sm" variant="outline" className="ml-auto">
|
||||
<a href={job.package_download_url}>下载</a>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user