sync update from LAN repo (source dhk-1 @ 3b1ec5b4)
This commit is contained in:
1 parent
da6521b6cb
commit
264e2200d6
995 files changed
+148105
-13399
No files matched your search
@@ -18,7 +18,7 @@ import {
|
||||
import { NotificationDialog } from "@/components/workspace/notification-dialog";
|
||||
import { getStoredAuth } from "@/core/auth";
|
||||
import { useLiveAccount } from "@/core/auth/use-live-account";
|
||||
import { getHeaderBrandAsset, getHeaderBrandFallback } from "@/core/branding/brand-assets";
|
||||
import { AppBrandImage } from "@/core/branding/app-brand-image";
|
||||
import { isWujieEnv } from "@/core/embed/wujie";
|
||||
import { readRuntimeEnv } from "@/env";
|
||||
import { useUnreadCount } from "@/core/notifications";
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
} from "@/core/page-layout/sidebar-menu";
|
||||
import { useSidebarMenuItems } from "@/core/page-layout/use-sidebar-menu";
|
||||
import { useDisplayDesensitizer } from "@/core/sensitive-words/use-display-desensitizer";
|
||||
import { useAppSystemName } from "@/core/system-settings/hooks";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import { useTheme } from "../contexts/ThemeContext";
|
||||
@@ -71,17 +72,7 @@ const Header = ({ collapsed }: HeaderProps) => {
|
||||
const darkLogoPosition =
|
||||
readRuntimeEnv("VITE_DARK_LOGO_POSITION") === "left" ? "left" : "center";
|
||||
const isDarkLogoOnLeft = darkLogoPosition === "left";
|
||||
const brandTheme = theme;
|
||||
const configuredBrandLogo = getHeaderBrandAsset(brandTheme);
|
||||
const fallbackBrandLogo = getHeaderBrandFallback(brandTheme);
|
||||
const [failedBrandLogo, setFailedBrandLogo] = useState<string | null>(null);
|
||||
const brandLogo =
|
||||
failedBrandLogo === configuredBrandLogo ? fallbackBrandLogo : configuredBrandLogo;
|
||||
const handleBrandLogoError = () => {
|
||||
if (brandLogo !== fallbackBrandLogo) {
|
||||
setFailedBrandLogo(brandLogo);
|
||||
}
|
||||
};
|
||||
const systemName = useAppSystemName("CM业务中心");
|
||||
const [notificationOpen, setNotificationOpen] = useState(false);
|
||||
const { data: unreadCount = 0 } = useUnreadCount();
|
||||
const navigate = useNavigate();
|
||||
@@ -296,12 +287,9 @@ const Header = ({ collapsed }: HeaderProps) => {
|
||||
className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-blue-950/55"
|
||||
title="系统 Logo"
|
||||
>
|
||||
<img
|
||||
src={brandLogo}
|
||||
alt=""
|
||||
aria-hidden="true"
|
||||
<AppBrandImage
|
||||
theme={theme}
|
||||
className="h-[35px] w-[35px] object-contain"
|
||||
onError={handleBrandLogoError}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
@@ -318,16 +306,13 @@ const Header = ({ collapsed }: HeaderProps) => {
|
||||
{/* 中:系统 logo + 名称,落在背景图发光基座上。 */}
|
||||
<div className="header-center-title">
|
||||
{darkLogoPosition === "center" && (
|
||||
<img
|
||||
src={brandLogo}
|
||||
alt=""
|
||||
aria-hidden="true"
|
||||
<AppBrandImage
|
||||
theme={theme}
|
||||
className="header-center-title__logo"
|
||||
onError={handleBrandLogoError}
|
||||
/>
|
||||
)}
|
||||
<span className="header-center-title__label">
|
||||
{desensitizeText("CM业务中心")}
|
||||
{desensitizeText(systemName)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
@@ -352,16 +337,13 @@ const Header = ({ collapsed }: HeaderProps) => {
|
||||
<div className="flex h-full min-w-0 flex-1 items-center">
|
||||
<div className="flex flex-shrink-0 items-center gap-2 pr-1">
|
||||
<div className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-lg bg-white/20">
|
||||
<img
|
||||
src={brandLogo}
|
||||
alt=""
|
||||
aria-hidden="true"
|
||||
<AppBrandImage
|
||||
theme={theme}
|
||||
className="h-[35px] w-[35px] object-contain"
|
||||
onError={handleBrandLogoError}
|
||||
/>
|
||||
</div>
|
||||
<span className={cn("whitespace-nowrap text-lg font-semibold", headerTextClass)}>
|
||||
{desensitizeText("CM业务中心")}
|
||||
{desensitizeText(systemName)}
|
||||
</span>
|
||||
</div>
|
||||
<nav className="light-topnav" aria-label="一级菜单">
|
||||
@@ -388,17 +370,14 @@ const Header = ({ collapsed }: HeaderProps) => {
|
||||
: "bg-white/20",
|
||||
)}
|
||||
>
|
||||
<img
|
||||
src={brandLogo}
|
||||
alt=""
|
||||
aria-hidden="true"
|
||||
<AppBrandImage
|
||||
theme={theme}
|
||||
className="h-7 w-7 object-contain"
|
||||
onError={handleBrandLogoError}
|
||||
/>
|
||||
</div>
|
||||
{!collapsed && (
|
||||
<span className={cn("text-sm font-semibold", headerTextClass)}>
|
||||
{desensitizeText("CM业务中心")}
|
||||
{desensitizeText(systemName)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
import {
|
||||
getAssistantWikiPage,
|
||||
listAssistantKnowledgeBases,
|
||||
listAssistantWikiPages,
|
||||
} from "./assistant-knowledge";
|
||||
|
||||
test("directory pagination terminates when the backend repeats an offset", async (t) => {
|
||||
const offsets: string[] = [];
|
||||
t.mock.method(globalThis, "fetch", async (input: RequestInfo | URL) => {
|
||||
const url = new URL(String(input), "http://localhost");
|
||||
offsets.push(url.searchParams.get("offset")!);
|
||||
assert.equal(url.searchParams.get("include_content"), "false");
|
||||
return Response.json({ pages: [{ id: "page-1", slug: "wiki/one" }], next_offset: 500 });
|
||||
});
|
||||
|
||||
await assert.rejects(listAssistantWikiPages("", "base-1", false), /目录分页异常/);
|
||||
assert.deepEqual(offsets, ["0", "500"]);
|
||||
});
|
||||
|
||||
test("directory pagination rejects an empty batch that advertises more pages", async (t) => {
|
||||
const fetch = t.mock.method(globalThis, "fetch", async () =>
|
||||
Response.json({ pages: [], next_offset: 500 }),
|
||||
);
|
||||
|
||||
await assert.rejects(listAssistantWikiPages("", "base-1", false), /目录分页异常/);
|
||||
assert.equal(fetch.mock.callCount(), 1);
|
||||
});
|
||||
|
||||
test("directory pagination preserves every completed batch", async (t) => {
|
||||
t.mock.method(globalThis, "fetch", async (input: RequestInfo | URL) => {
|
||||
const offset = new URL(String(input), "http://localhost").searchParams.get("offset");
|
||||
return Response.json(offset === "0"
|
||||
? { pages: [{ id: "index", slug: "index" }], next_offset: 500 }
|
||||
: { pages: [{ id: "article", slug: "wiki/article" }], next_offset: null });
|
||||
});
|
||||
|
||||
assert.deepEqual((await listAssistantWikiPages("", "base-1", false)).map((page) => page.id), ["index", "article"]);
|
||||
});
|
||||
|
||||
test("leaving a library aborts its article request", async (t) => {
|
||||
const controller = new AbortController();
|
||||
let requestSignal: AbortSignal | undefined;
|
||||
t.mock.method(globalThis, "fetch", async (_input: RequestInfo | URL, init?: RequestInit) => {
|
||||
requestSignal = init?.signal ?? undefined;
|
||||
return new Promise<Response>((_resolve, reject) => {
|
||||
requestSignal!.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError")), { once: true });
|
||||
});
|
||||
});
|
||||
|
||||
const pending = getAssistantWikiPage("wiki/one", "base-1", controller.signal);
|
||||
controller.abort();
|
||||
await assert.rejects(pending, { name: "AbortError" });
|
||||
assert.equal(requestSignal?.aborted, true);
|
||||
});
|
||||
|
||||
test("failed library reads surface the backend error instead of an empty library", async (t) => {
|
||||
t.mock.method(globalThis, "fetch", async () =>
|
||||
Response.json({ detail: "助手知识库存储不可用" }, { status: 503 }),
|
||||
);
|
||||
|
||||
await assert.rejects(listAssistantKnowledgeBases(), /助手知识库存储不可用/);
|
||||
});
|
||||
@@ -4,10 +4,11 @@ import {
|
||||
useQuery,
|
||||
useQueryClient,
|
||||
} from "@tanstack/react-query";
|
||||
import { useEffect } from "react";
|
||||
import { useEffect, useMemo } from "react";
|
||||
|
||||
import { apiFetch } from "@/core/api/fetch-client";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
import { withKnowledgeRequestTimeout } from "@/core/llmwiki/request-timeout";
|
||||
import { userFacingKnowledgeMessage } from "@/lib/knowledge-message";
|
||||
|
||||
const BASE = () => `${getBackendBaseURL()}/api/assistant-knowledge`;
|
||||
@@ -149,26 +150,30 @@ function normalizeExportPackageJob(
|
||||
};
|
||||
}
|
||||
|
||||
export async function getAssistantKnowledgeBase() {
|
||||
const data = await readJson<{ base: AssistantKnowledgeBase | null }>(
|
||||
await apiFetch(`${BASE()}/base`),
|
||||
);
|
||||
return data.base;
|
||||
export async function getAssistantKnowledgeBase(signal?: AbortSignal) {
|
||||
return withKnowledgeRequestTimeout(async (requestSignal) => {
|
||||
const data = await readJson<{ base: AssistantKnowledgeBase | null }>(
|
||||
await apiFetch(`${BASE()}/base`, { signal: requestSignal }),
|
||||
);
|
||||
return data.base;
|
||||
}, { signal });
|
||||
}
|
||||
|
||||
export async function getAssistantKnowledgeBaseById(baseId: string) {
|
||||
const data = await readJson<{ base: AssistantKnowledgeBase }>(
|
||||
await apiFetch(`${BASE()}/bases/${encodeURIComponent(baseId)}`),
|
||||
);
|
||||
return data.base;
|
||||
export async function getAssistantKnowledgeBaseById(baseId: string, signal?: AbortSignal) {
|
||||
return withKnowledgeRequestTimeout(async (requestSignal) => {
|
||||
const data = await readJson<{ base: AssistantKnowledgeBase }>(
|
||||
await apiFetch(`${BASE()}/bases/${encodeURIComponent(baseId)}`, { signal: requestSignal }),
|
||||
);
|
||||
return data.base;
|
||||
}, { signal });
|
||||
}
|
||||
|
||||
export async function listAssistantKnowledgeBases() {
|
||||
return (
|
||||
export async function listAssistantKnowledgeBases(signal?: AbortSignal) {
|
||||
return withKnowledgeRequestTimeout(async (requestSignal) => (
|
||||
await readJson<{ bases: AssistantKnowledgeBase[] }>(
|
||||
await apiFetch(`${BASE()}/bases`),
|
||||
await apiFetch(`${BASE()}/bases`, { signal: requestSignal }),
|
||||
)
|
||||
).bases;
|
||||
).bases, { signal });
|
||||
}
|
||||
|
||||
export async function initializeAssistantKnowledgeBase(name = "知识梳理总库") {
|
||||
@@ -264,30 +269,39 @@ async function listAssistantWikiPageBatch(
|
||||
baseId?: string | null,
|
||||
includeContent = true,
|
||||
offset = 0,
|
||||
signal?: AbortSignal,
|
||||
): Promise<AssistantWikiPageBatch> {
|
||||
const params = withBaseParam(baseId);
|
||||
params.set("limit", "500");
|
||||
params.set("include_content", String(includeContent));
|
||||
params.set("offset", String(offset));
|
||||
if (q.trim()) params.set("q", q.trim());
|
||||
return readJson<AssistantWikiPageBatch>(
|
||||
await apiFetch(`${BASE()}/wiki-pages?${params}`),
|
||||
);
|
||||
const batch = await withKnowledgeRequestTimeout(async (requestSignal) =>
|
||||
readJson<AssistantWikiPageBatch>(
|
||||
await apiFetch(`${BASE()}/wiki-pages?${params}`, { signal: requestSignal }),
|
||||
), { signal });
|
||||
if (batch.next_offset != null &&
|
||||
(!Number.isInteger(batch.next_offset) || batch.next_offset <= offset || !batch.pages.length)) {
|
||||
throw new Error("Wiki 目录分页异常,请刷新重试");
|
||||
}
|
||||
return batch;
|
||||
}
|
||||
|
||||
export async function getAssistantWikiPage(
|
||||
slug: string,
|
||||
baseId: string,
|
||||
signal?: AbortSignal,
|
||||
) {
|
||||
const params = withBaseParam(baseId);
|
||||
const safeSlug = slug.split("/").map(encodeURIComponent).join("/");
|
||||
return readJson<AssistantWikiPage>(
|
||||
await apiFetch(`${BASE()}/wiki-pages/${safeSlug}?${params}`),
|
||||
);
|
||||
return withKnowledgeRequestTimeout(async (requestSignal) =>
|
||||
readJson<AssistantWikiPage>(
|
||||
await apiFetch(`${BASE()}/wiki-pages/${safeSlug}?${params}`, { signal: requestSignal }),
|
||||
), { signal });
|
||||
}
|
||||
|
||||
export async function searchAssistantWiki(q: string, baseId: string) {
|
||||
return readJson<{
|
||||
return withKnowledgeRequestTimeout(async (signal) => readJson<{
|
||||
results: (AssistantWikiPage & {
|
||||
score: number;
|
||||
retrieval_mode: Exclude<AssistantKnowledgeRetrievalMode, "empty">;
|
||||
@@ -296,8 +310,9 @@ export async function searchAssistantWiki(q: string, baseId: string) {
|
||||
}>(
|
||||
await apiFetch(
|
||||
`${BASE()}/search?${new URLSearchParams({ q, base_id: baseId })}`,
|
||||
{ signal },
|
||||
),
|
||||
);
|
||||
));
|
||||
}
|
||||
|
||||
export async function listWikiTransfers(id: string, assistant: boolean) {
|
||||
@@ -328,22 +343,22 @@ export async function importOrdinaryWikiPackage(id: string, file: File) {
|
||||
);
|
||||
}
|
||||
|
||||
export async function listAssistantKnowledgeSources(baseId?: string | null) {
|
||||
export async function listAssistantKnowledgeSources(baseId?: string | null, signal?: AbortSignal) {
|
||||
const params = withBaseParam(baseId);
|
||||
return (
|
||||
return withKnowledgeRequestTimeout(async (requestSignal) => (
|
||||
await readJson<{ sources: AssistantKnowledgeSource[] }>(
|
||||
await apiFetch(`${BASE()}/sources?${params}`),
|
||||
await apiFetch(`${BASE()}/sources?${params}`, { signal: requestSignal }),
|
||||
)
|
||||
).sources;
|
||||
).sources, { signal });
|
||||
}
|
||||
|
||||
export async function listAssistantImportJobs(baseId?: string | null) {
|
||||
export async function listAssistantImportJobs(baseId?: string | null, signal?: AbortSignal) {
|
||||
const params = withBaseParam(baseId);
|
||||
return (
|
||||
return withKnowledgeRequestTimeout(async (requestSignal) => (
|
||||
await readJson<{ jobs: AssistantImportJob[] }>(
|
||||
await apiFetch(`${BASE()}/import-jobs?${params}`),
|
||||
await apiFetch(`${BASE()}/import-jobs?${params}`, { signal: requestSignal }),
|
||||
)
|
||||
).jobs.map(normalizeImportJob);
|
||||
).jobs.map(normalizeImportJob), { signal });
|
||||
}
|
||||
|
||||
export async function listAssistantWikiRevisions(
|
||||
@@ -487,19 +502,21 @@ const KEY = "assistant-knowledge";
|
||||
export function useAssistantKnowledgeBase(baseId?: string | null) {
|
||||
return useQuery({
|
||||
queryKey: [KEY, "base", baseId ?? "global"],
|
||||
queryFn: () =>
|
||||
queryFn: ({ signal }) =>
|
||||
baseId
|
||||
? getAssistantKnowledgeBaseById(baseId)
|
||||
: getAssistantKnowledgeBase(),
|
||||
? getAssistantKnowledgeBaseById(baseId, signal)
|
||||
: getAssistantKnowledgeBase(signal),
|
||||
retry: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function useAssistantKnowledgeBases(enabled = true) {
|
||||
return useQuery({
|
||||
queryKey: [KEY, "bases"],
|
||||
queryFn: listAssistantKnowledgeBases,
|
||||
queryFn: ({ signal }) => listAssistantKnowledgeBases(signal),
|
||||
enabled,
|
||||
staleTime: 30_000,
|
||||
retry: false,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -512,35 +529,45 @@ export function useAssistantWikiPages(
|
||||
const enabled = (options.enabled ?? true) && !!baseId;
|
||||
const result = useInfiniteQuery({
|
||||
queryKey: [KEY, "pages", baseId ?? "global", query, includeContent],
|
||||
queryFn: ({ pageParam }) =>
|
||||
queryFn: ({ pageParam, signal }) =>
|
||||
listAssistantWikiPageBatch(
|
||||
query,
|
||||
baseId,
|
||||
includeContent,
|
||||
pageParam,
|
||||
signal,
|
||||
),
|
||||
initialPageParam: 0,
|
||||
getNextPageParam: (lastPage) => lastPage.next_offset ?? undefined,
|
||||
enabled,
|
||||
staleTime: 30_000,
|
||||
retry: false,
|
||||
refetchOnWindowFocus: false,
|
||||
});
|
||||
|
||||
// Resolve the first 500 lightweight directory entries immediately so the
|
||||
// active article can load, then fill the rest of a very large directory in
|
||||
// the background instead of blocking the whole reader on serial pagination.
|
||||
useEffect(() => {
|
||||
if (enabled && result.hasNextPage && !result.isFetchingNextPage) {
|
||||
if (enabled && result.hasNextPage && !result.isFetching && !result.isError) {
|
||||
void result.fetchNextPage();
|
||||
}
|
||||
}, [
|
||||
enabled,
|
||||
result.fetchNextPage,
|
||||
result.hasNextPage,
|
||||
result.isFetchingNextPage,
|
||||
result.isFetching,
|
||||
result.isError,
|
||||
]);
|
||||
|
||||
const pages = useMemo(
|
||||
() => result.data?.pages.flatMap((batch) => batch.pages),
|
||||
[result.data],
|
||||
);
|
||||
|
||||
return {
|
||||
...result,
|
||||
data: result.data?.pages.flatMap((batch) => batch.pages),
|
||||
data: pages,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -551,16 +578,20 @@ export function useAssistantWikiPage(
|
||||
) {
|
||||
return useQuery({
|
||||
queryKey: [KEY, "page", baseId, slug],
|
||||
queryFn: () => getAssistantWikiPage(slug!, baseId!),
|
||||
queryFn: ({ signal }) => getAssistantWikiPage(slug!, baseId!, signal),
|
||||
enabled: enabled && !!baseId && !!slug,
|
||||
staleTime: 30_000,
|
||||
retry: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function useAssistantKnowledgeSources(baseId?: string | null, enabled = true) {
|
||||
return useQuery({
|
||||
queryKey: [KEY, "sources", baseId ?? "global"],
|
||||
queryFn: () => listAssistantKnowledgeSources(baseId),
|
||||
queryFn: ({ signal }) => listAssistantKnowledgeSources(baseId, signal),
|
||||
enabled,
|
||||
staleTime: 30_000,
|
||||
retry: false,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -570,8 +601,9 @@ export function useAssistantImportJobs(
|
||||
) {
|
||||
return useQuery({
|
||||
queryKey: [KEY, "jobs", baseId ?? "global"],
|
||||
queryFn: () => listAssistantImportJobs(baseId),
|
||||
queryFn: ({ signal }) => listAssistantImportJobs(baseId, signal),
|
||||
enabled: enabled && !!baseId,
|
||||
retry: false,
|
||||
refetchInterval: (query) =>
|
||||
(query.state.data ?? []).some((job) =>
|
||||
["queued", "running"].includes(job.status),
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* 全局业务映射(业务码 → 智能体 / 业务链)API 客户端。
|
||||
*
|
||||
* 后端:`/api/business-mapping`(见 app/gateway/routers/business_mapping.py)。
|
||||
* 全局共享、无用户隔离;只读列表 + 更新 agent / chain 两列(业务行由后端 seed 固定)。
|
||||
* 全局共享、无用户隔离;内置业务行由后端 seed 固定,管理员也可以创建自定义类型配置。
|
||||
* snake_case ⇄ camelCase 在此边界收敛,调用方保持干净。
|
||||
*/
|
||||
|
||||
@@ -13,6 +13,10 @@ import { OptType, writeYLog } from "@/core/log/y-log";
|
||||
export interface BusinessMapping {
|
||||
businessCode: string;
|
||||
label: string;
|
||||
/** 页面筛选用的业务分类,仅为「内置」或「自定义类型」。 */
|
||||
mappingType: string;
|
||||
/** 自定义行的 businessCode 同时是登录深链的 goPath。 */
|
||||
isCustom: boolean;
|
||||
agentId: string | null;
|
||||
agentName: string | null;
|
||||
chainId: string | null;
|
||||
@@ -28,11 +32,18 @@ export interface BusinessMappingPatch {
|
||||
chainTitle?: string | null;
|
||||
}
|
||||
|
||||
export interface CreateBusinessMappingInput {
|
||||
/** 登录 URL 的 `goPath`,同时作为页面显示名称。 */
|
||||
name: string;
|
||||
}
|
||||
|
||||
const BASE = () => `${getBackendBaseURL()}/api/business-mapping`;
|
||||
|
||||
interface ServerMapping {
|
||||
business_code: string;
|
||||
label: string;
|
||||
mapping_type?: string;
|
||||
is_custom?: boolean;
|
||||
agent_id: string | null;
|
||||
agent_name: string | null;
|
||||
chain_id: string | null;
|
||||
@@ -44,6 +55,8 @@ function toMapping(s: ServerMapping): BusinessMapping {
|
||||
return {
|
||||
businessCode: s.business_code,
|
||||
label: s.label ?? "",
|
||||
mappingType: s.is_custom ? "自定义类型" : "内置",
|
||||
isCustom: s.is_custom === true,
|
||||
agentId: s.agent_id ?? null,
|
||||
agentName: s.agent_name ?? null,
|
||||
chainId: s.chain_id ?? null,
|
||||
@@ -101,3 +114,24 @@ export async function updateBusinessMapping(
|
||||
});
|
||||
return mapping;
|
||||
}
|
||||
|
||||
/** 新增一个管理员自定义配置;名称也是登录使用的 goPath。 */
|
||||
export async function createBusinessMapping(
|
||||
input: CreateBusinessMappingInput,
|
||||
): Promise<BusinessMapping> {
|
||||
const res = await apiFetch(BASE(), {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name: input.name }),
|
||||
});
|
||||
const data = await readJson<ServerMapping>(res, "create business mapping");
|
||||
const mapping = toMapping(data);
|
||||
writeYLog({
|
||||
optType: OptType.create,
|
||||
optDetail: "CM助手-全量-业务映射-新增自定义配置",
|
||||
url: "/api/business-mapping",
|
||||
reqParam: input,
|
||||
returnParam: mapping,
|
||||
});
|
||||
return mapping;
|
||||
}
|
||||
@@ -18,6 +18,7 @@ interface ServerCompactOverride {
|
||||
placement: "sidebar" | "settings" | "toolbox";
|
||||
sort_order: number;
|
||||
label: string | null;
|
||||
disabled?: boolean;
|
||||
menu_type?: string | null;
|
||||
}
|
||||
|
||||
@@ -49,6 +50,7 @@ function toOverride(s: ServerCompactOverride): CompactMenuOverride {
|
||||
placement,
|
||||
sortOrder: s.sort_order ?? 0,
|
||||
label: s.label ?? null,
|
||||
disabled: s.disabled ?? false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -58,6 +60,7 @@ function toBody(o: CompactMenuOverride): ServerCompactOverride {
|
||||
placement: o.placement,
|
||||
sort_order: o.sortOrder,
|
||||
label: o.label ?? null,
|
||||
disabled: o.disabled,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,421 @@
|
||||
/**
|
||||
* HTML 模板管理(模板管理页)API 客户端 + React Query hooks。
|
||||
*
|
||||
* 后端:`/api/html-templates`(见 app/gateway/routers/html_templates.py,存储为
|
||||
* harness 层 `deerflow.runtime.scheduler.template_store` 文件型存储,内置 27 个
|
||||
* 模板启动 seed)。读对所有登录用户开放,写仅 admin。snake_case ⇄ camelCase
|
||||
* 在此边界收敛。
|
||||
*/
|
||||
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
import { apiFetch } from "@/core/api/fetch-client";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
import { OptType, writeYLog } from "@/core/log/y-log";
|
||||
|
||||
const BASE = () => `${getBackendBaseURL()}/api/html-templates`;
|
||||
|
||||
/** 一条模板元信息(前端视图模型)。 */
|
||||
export interface HtmlTemplateMeta {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
/** 内置模板(不可删除,可编辑/上传覆盖/重置回随包原版)。 */
|
||||
builtin: boolean;
|
||||
/** true = 支持「JSON 转换填充」;false = 只展示。 */
|
||||
convertible: boolean;
|
||||
/** "structured" = 结构化模板(骨架+runtime+data.json,支持「编辑数据」持久化);缺省 single。 */
|
||||
kind?: "single" | "structured";
|
||||
/** 正文大小(字节;结构化模板为各组成文件之和)。 */
|
||||
size?: number;
|
||||
createdAt?: string | null;
|
||||
updatedAt?: string | null;
|
||||
}
|
||||
|
||||
interface ServerMeta {
|
||||
id: string;
|
||||
name: string;
|
||||
description?: string | null;
|
||||
builtin?: boolean;
|
||||
convertible?: boolean;
|
||||
kind?: string | null;
|
||||
size?: number | null;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
}
|
||||
|
||||
function toMeta(s: ServerMeta): HtmlTemplateMeta {
|
||||
return {
|
||||
id: s.id,
|
||||
name: s.name ?? s.id,
|
||||
description: s.description ?? "",
|
||||
builtin: !!s.builtin,
|
||||
convertible: !!s.convertible,
|
||||
kind: s.kind === "structured" ? "structured" : "single",
|
||||
size: s.size ?? undefined,
|
||||
createdAt: s.created_at ?? null,
|
||||
updatedAt: s.updated_at ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
async function readJson<T>(res: Response, ctx: string): Promise<T> {
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => null as unknown);
|
||||
const detail =
|
||||
data && typeof data === "object" && "detail" in data
|
||||
? String((data as { detail: unknown }).detail)
|
||||
: `${ctx} failed (${res.status})`;
|
||||
throw new Error(detail);
|
||||
}
|
||||
return (await res.json()) as T;
|
||||
}
|
||||
|
||||
// ── API ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function listHtmlTemplates(): Promise<HtmlTemplateMeta[]> {
|
||||
const res = await apiFetch(BASE(), { method: "GET" });
|
||||
const data = await readJson<{ templates: ServerMeta[] }>(res, "list html templates");
|
||||
const templates = (data.templates ?? []).map(toMeta);
|
||||
writeYLog({
|
||||
optType: OptType.search,
|
||||
optDetail: "CM助手-全量-模板管理-列表",
|
||||
url: "/api/html-templates",
|
||||
returnParam: templates,
|
||||
});
|
||||
return templates;
|
||||
}
|
||||
|
||||
/**
|
||||
* 模板内容。默认返回可预览的完整文档(结构化模板 = 默认数据组合产物);
|
||||
* `raw: true` 返回正文原文(结构化模板 = 带 `__PAGE_*` 标记的骨架,编辑用)。
|
||||
*/
|
||||
export async function getHtmlTemplateContent(
|
||||
templateId: string,
|
||||
opts?: { raw?: boolean },
|
||||
): Promise<string> {
|
||||
const suffix = opts?.raw ? "?raw=1" : "";
|
||||
const res = await apiFetch(
|
||||
`${BASE()}/${encodeURIComponent(templateId)}/content${suffix}`,
|
||||
{ method: "GET" },
|
||||
);
|
||||
const data = await readJson<{ html: string }>(res, "get html template content");
|
||||
return data.html ?? "";
|
||||
}
|
||||
|
||||
/** 结构化模板的一个数据模块(DATA 顶层键)及其中文显示名。 */
|
||||
export interface HtmlTemplateModuleInfo {
|
||||
key: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
/** 结构化模板的默认数据 + MANIFEST + 模块中文名(管理页「编辑数据」用)。 */
|
||||
export async function getHtmlTemplateData(
|
||||
templateId: string,
|
||||
): Promise<{
|
||||
data: Record<string, unknown>;
|
||||
manifest: Record<string, unknown>;
|
||||
modules: HtmlTemplateModuleInfo[];
|
||||
}> {
|
||||
const res = await apiFetch(`${BASE()}/${encodeURIComponent(templateId)}/data`, {
|
||||
method: "GET",
|
||||
});
|
||||
const payload = await readJson<{
|
||||
data: Record<string, unknown>;
|
||||
manifest?: Record<string, unknown> | null;
|
||||
modules?: { key: string; label?: string }[] | null;
|
||||
}>(res, "get html template data");
|
||||
return {
|
||||
data: payload.data ?? {},
|
||||
manifest: payload.manifest ?? {},
|
||||
modules: (payload.modules ?? []).map((m) => ({
|
||||
key: m.key,
|
||||
label: m.label || m.key,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
/** 字段目录的一条字段(fields.json × 当前可见性 × 抽取锁定)。 */
|
||||
export interface HtmlTemplateFieldInfo {
|
||||
label: string;
|
||||
pages: string[];
|
||||
description: string;
|
||||
visible: boolean;
|
||||
/** 是否接受定时任务抽取数据更新(默认 true;关闭后该字段保持模板现有数据)。 */
|
||||
extract: boolean;
|
||||
/** false = 布局分区(无独立数据键),抽取开关无意义。 */
|
||||
hasKey: boolean;
|
||||
}
|
||||
|
||||
/** 自定义模块(挂在指定页面底部的 AI 生成 HTML 片段,存于 manifest)。 */
|
||||
export interface HtmlTemplateCustomModule {
|
||||
编号?: string;
|
||||
页面: string;
|
||||
标题?: string;
|
||||
html: string;
|
||||
}
|
||||
|
||||
export interface HtmlTemplatePageOption {
|
||||
key: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
/** 字段目录 + 页面清单 + 自定义模块列表(「字段与模块」页签数据源)。 */
|
||||
export async function getHtmlTemplateFields(templateId: string): Promise<{
|
||||
fields: HtmlTemplateFieldInfo[];
|
||||
pages: HtmlTemplatePageOption[];
|
||||
customModules: HtmlTemplateCustomModule[];
|
||||
}> {
|
||||
const res = await apiFetch(`${BASE()}/${encodeURIComponent(templateId)}/fields`, {
|
||||
method: "GET",
|
||||
});
|
||||
const data = await readJson<{
|
||||
fields?: (Omit<HtmlTemplateFieldInfo, "extract" | "hasKey"> & {
|
||||
extract?: boolean | null;
|
||||
has_key?: boolean | null;
|
||||
})[] | null;
|
||||
pages?: HtmlTemplatePageOption[] | null;
|
||||
custom_modules?: HtmlTemplateCustomModule[] | null;
|
||||
}>(res, "get html template fields");
|
||||
return {
|
||||
fields: (data.fields ?? []).map((f) => ({
|
||||
...f,
|
||||
extract: f.extract !== false,
|
||||
// 兼容旧缓存缺 has_key 的响应:缺失按有键处理(宁可多开不可全禁)。
|
||||
hasKey: f.has_key !== false,
|
||||
})),
|
||||
pages: data.pages ?? [],
|
||||
customModules: data.custom_modules ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
/** 整体替换字段隐藏名单(可选一并替换抽取锁定名单;未列出的字段全部显示/接受抽取)。 */
|
||||
export async function updateHtmlTemplateFieldVisibility(
|
||||
templateId: string,
|
||||
hidden: string[],
|
||||
extractLocked?: string[],
|
||||
): Promise<HtmlTemplateMeta> {
|
||||
const res = await apiFetch(`${BASE()}/${encodeURIComponent(templateId)}/fields`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
hidden,
|
||||
...(extractLocked !== undefined ? { extract_locked: extractLocked } : {}),
|
||||
}),
|
||||
});
|
||||
return toMeta(await readJson<ServerMeta>(res, "update html template fields"));
|
||||
}
|
||||
|
||||
/** 自定义模块列表整体替换(后端逐条消毒后入库)。 */
|
||||
export async function updateHtmlTemplateCustomModules(
|
||||
templateId: string,
|
||||
modules: HtmlTemplateCustomModule[],
|
||||
): Promise<HtmlTemplateMeta> {
|
||||
const res = await apiFetch(`${BASE()}/${encodeURIComponent(templateId)}/custom-modules`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ modules }),
|
||||
});
|
||||
return toMeta(await readJson<ServerMeta>(res, "update html template custom modules"));
|
||||
}
|
||||
|
||||
/** 按自然语言描述调用模型生成自定义模块 HTML 片段(已消毒,未入库)。 */
|
||||
export async function generateHtmlTemplateCustomModule(
|
||||
templateId: string,
|
||||
input: { page: string; title?: string; description: string; modelName?: string },
|
||||
): Promise<string> {
|
||||
const res = await apiFetch(
|
||||
`${BASE()}/${encodeURIComponent(templateId)}/custom-modules/generate`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
page: input.page,
|
||||
title: input.title ?? "",
|
||||
description: input.description,
|
||||
model_name: input.modelName ?? null,
|
||||
}),
|
||||
},
|
||||
);
|
||||
const data = await readJson<{ html: string }>(res, "generate custom module");
|
||||
return data.html ?? "";
|
||||
}
|
||||
|
||||
/** 整体替换结构化模板的默认数据(manifest 给出时一并持久化 manifest.json)。 */
|
||||
export async function updateHtmlTemplateData(
|
||||
templateId: string,
|
||||
data: Record<string, unknown>,
|
||||
manifest?: Record<string, unknown>,
|
||||
): Promise<HtmlTemplateMeta> {
|
||||
const res = await apiFetch(`${BASE()}/${encodeURIComponent(templateId)}/data`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
data,
|
||||
...(manifest !== undefined ? { manifest } : {}),
|
||||
}),
|
||||
});
|
||||
return toMeta(await readJson<ServerMeta>(res, "update html template data"));
|
||||
}
|
||||
|
||||
export async function createHtmlTemplate(input: {
|
||||
templateId: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
html: string;
|
||||
}): Promise<HtmlTemplateMeta> {
|
||||
const res = await apiFetch(BASE(), {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
template_id: input.templateId,
|
||||
name: input.name,
|
||||
description: input.description ?? "",
|
||||
html: input.html,
|
||||
}),
|
||||
});
|
||||
return toMeta(await readJson<ServerMeta>(res, "create html template"));
|
||||
}
|
||||
|
||||
export async function updateHtmlTemplate(
|
||||
templateId: string,
|
||||
patch: { name?: string; description?: string; html?: string },
|
||||
): Promise<HtmlTemplateMeta> {
|
||||
const res = await apiFetch(`${BASE()}/${encodeURIComponent(templateId)}`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
...(patch.name !== undefined ? { name: patch.name } : {}),
|
||||
...(patch.description !== undefined ? { description: patch.description } : {}),
|
||||
...(patch.html !== undefined ? { html: patch.html } : {}),
|
||||
}),
|
||||
});
|
||||
return toMeta(await readJson<ServerMeta>(res, "update html template"));
|
||||
}
|
||||
|
||||
export async function deleteHtmlTemplate(templateId: string): Promise<void> {
|
||||
const res = await apiFetch(`${BASE()}/${encodeURIComponent(templateId)}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
await readJson<{ ok: boolean }>(res, "delete html template");
|
||||
}
|
||||
|
||||
export async function resetHtmlTemplate(templateId: string): Promise<HtmlTemplateMeta> {
|
||||
const res = await apiFetch(`${BASE()}/${encodeURIComponent(templateId)}/reset`, {
|
||||
method: "POST",
|
||||
});
|
||||
return toMeta(await readJson<ServerMeta>(res, "reset html template"));
|
||||
}
|
||||
|
||||
// ── React Query hooks ───────────────────────────────────────────────────────
|
||||
|
||||
export const HTML_TEMPLATES_KEY = "html-templates";
|
||||
const TEMPLATE_CONTENT_KEY = "html-template-content";
|
||||
const TEMPLATE_DATA_KEY = "html-template-data";
|
||||
const TEMPLATE_FIELDS_KEY = "html-template-fields";
|
||||
|
||||
/** 失效模板相关的全部查询(列表/内容/数据/字段)——任何写操作后调用。 */
|
||||
export function invalidateHtmlTemplateCaches(queryClient: {
|
||||
invalidateQueries: (filter: { queryKey: unknown[] }) => Promise<unknown>;
|
||||
}): Promise<unknown> {
|
||||
return Promise.all(
|
||||
[HTML_TEMPLATES_KEY, TEMPLATE_CONTENT_KEY, TEMPLATE_DATA_KEY, TEMPLATE_FIELDS_KEY].map(
|
||||
(key) => queryClient.invalidateQueries({ queryKey: [key] }),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export function useHtmlTemplatesAdmin(enabled = true) {
|
||||
return useQuery({
|
||||
queryKey: [HTML_TEMPLATES_KEY],
|
||||
queryFn: listHtmlTemplates,
|
||||
enabled,
|
||||
refetchOnWindowFocus: false,
|
||||
staleTime: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
/** 可预览的完整文档(结构化模板为默认数据组合产物)。 */
|
||||
export function useHtmlTemplateContent(templateId: string | null) {
|
||||
return useQuery({
|
||||
queryKey: [TEMPLATE_CONTENT_KEY, templateId, "doc"],
|
||||
queryFn: () => getHtmlTemplateContent(templateId as string),
|
||||
enabled: !!templateId,
|
||||
refetchOnWindowFocus: false,
|
||||
staleTime: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
/** 正文原文(结构化模板 = 带 `__PAGE_*` 标记的骨架,编辑用)。 */
|
||||
export function useHtmlTemplateRawContent(templateId: string | null, enabled = true) {
|
||||
return useQuery({
|
||||
queryKey: [TEMPLATE_CONTENT_KEY, templateId, "raw"],
|
||||
queryFn: () => getHtmlTemplateContent(templateId as string, { raw: true }),
|
||||
enabled: !!templateId && enabled,
|
||||
refetchOnWindowFocus: false,
|
||||
staleTime: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
/** 结构化模板的默认数据(仅 kind=structured 时启用)。 */
|
||||
export function useHtmlTemplateData(templateId: string | null, enabled = true) {
|
||||
return useQuery({
|
||||
queryKey: [TEMPLATE_DATA_KEY, templateId],
|
||||
queryFn: () => getHtmlTemplateData(templateId as string),
|
||||
enabled: !!templateId && enabled,
|
||||
refetchOnWindowFocus: false,
|
||||
staleTime: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
/** 字段目录 + 页面清单 + 自定义模块(「字段与模块」页签)。 */
|
||||
export function useHtmlTemplateFields(templateId: string | null, enabled = true) {
|
||||
return useQuery({
|
||||
queryKey: [TEMPLATE_FIELDS_KEY, templateId],
|
||||
queryFn: () => getHtmlTemplateFields(templateId as string),
|
||||
enabled: !!templateId && enabled,
|
||||
refetchOnWindowFocus: false,
|
||||
staleTime: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
export function generateCustomModuleDirect(
|
||||
templateId: string,
|
||||
input: { page: string; title?: string; description: string; modelName?: string },
|
||||
): Promise<string> {
|
||||
return generateHtmlTemplateCustomModule(templateId, input);
|
||||
}
|
||||
|
||||
export function useHtmlTemplateActions() {
|
||||
const queryClient = useQueryClient();
|
||||
const invalidate = () => {
|
||||
void invalidateHtmlTemplateCaches(queryClient);
|
||||
};
|
||||
return {
|
||||
create: useMutation({ mutationFn: createHtmlTemplate, onSuccess: invalidate }),
|
||||
update: useMutation({
|
||||
mutationFn: (vars: {
|
||||
id: string;
|
||||
patch: { name?: string; description?: string; html?: string };
|
||||
}) => updateHtmlTemplate(vars.id, vars.patch),
|
||||
onSuccess: invalidate,
|
||||
}),
|
||||
updateData: useMutation({
|
||||
mutationFn: (vars: {
|
||||
id: string;
|
||||
data: Record<string, unknown>;
|
||||
manifest?: Record<string, unknown>;
|
||||
}) => updateHtmlTemplateData(vars.id, vars.data, vars.manifest),
|
||||
onSuccess: invalidate,
|
||||
}),
|
||||
remove: useMutation({ mutationFn: deleteHtmlTemplate, onSuccess: invalidate }),
|
||||
reset: useMutation({ mutationFn: resetHtmlTemplate, onSuccess: invalidate }),
|
||||
};
|
||||
}
|
||||
|
||||
/** 正文字节数的人类可读格式。 */
|
||||
export function formatTemplateSize(bytes?: number): string {
|
||||
if (!bytes || bytes <= 0) return "—";
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
||||
return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
import { apiFetch } from "@/core/api";
|
||||
import { useLiveAccount } from "@/core/auth/use-live-account";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
import {
|
||||
KNOWLEDGE_RESEARCH_ANONYMOUS_SCOPE,
|
||||
knowledgeResearchLibraryQueryKey,
|
||||
knowledgeResearchPublicationQueryKey,
|
||||
knowledgeResearchSessionQueryKey,
|
||||
} from "@/core/llmwiki/knowledge-research";
|
||||
|
||||
export type KnowledgeResearchPublication = {
|
||||
id: string;
|
||||
sessionId?: string;
|
||||
wikiSlug: string;
|
||||
title: string;
|
||||
savedHash: string;
|
||||
savedAt?: string;
|
||||
updatedAt?: string;
|
||||
ownedByCurrentUser: boolean;
|
||||
canContinue: boolean;
|
||||
canWrite: boolean;
|
||||
contentMarkdown?: string;
|
||||
};
|
||||
|
||||
export type KnowledgeResearchSession = {
|
||||
id: string;
|
||||
threadId: string;
|
||||
title: string;
|
||||
draftMarkdown: string;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
canWrite: boolean;
|
||||
publication: KnowledgeResearchPublication | null;
|
||||
};
|
||||
|
||||
export type KnowledgeResearchLibrary = {
|
||||
sessions: KnowledgeResearchSession[];
|
||||
publications: KnowledgeResearchPublication[];
|
||||
};
|
||||
|
||||
type WireRecord = Record<string, unknown>;
|
||||
|
||||
function asRecord(value: unknown): WireRecord {
|
||||
return value && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as WireRecord)
|
||||
: {};
|
||||
}
|
||||
|
||||
function pick<T>(row: WireRecord, camel: string, snake: string): T | undefined {
|
||||
return (row[camel] ?? row[snake]) as T | undefined;
|
||||
}
|
||||
|
||||
function normalizePublication(value: unknown): KnowledgeResearchPublication | null {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
||||
const row = asRecord(value);
|
||||
const id = String(
|
||||
row.id ?? pick(row, "publicationId", "publication_id") ?? "",
|
||||
);
|
||||
const sessionId = String(pick(row, "sessionId", "session_id") ?? "");
|
||||
const wikiSlug = String(pick(row, "wikiSlug", "wiki_slug") ?? "");
|
||||
if (!id || !wikiSlug) return null;
|
||||
return {
|
||||
id,
|
||||
...(sessionId ? { sessionId } : {}),
|
||||
wikiSlug,
|
||||
title: String(row.title ?? "未命名研究"),
|
||||
savedHash: String(pick(row, "savedHash", "saved_hash") ?? ""),
|
||||
savedAt: pick(row, "savedAt", "saved_at"),
|
||||
updatedAt: pick(row, "updatedAt", "updated_at"),
|
||||
ownedByCurrentUser: Boolean(
|
||||
pick(row, "ownedByCurrentUser", "owned_by_current_user"),
|
||||
),
|
||||
canContinue: Boolean(pick(row, "canContinue", "can_continue")),
|
||||
canWrite: Boolean(pick(row, "canWrite", "can_write")),
|
||||
contentMarkdown: pick(row, "contentMarkdown", "content_markdown"),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeSession(value: unknown): KnowledgeResearchSession {
|
||||
const row = asRecord(value);
|
||||
return {
|
||||
id: String(row.id ?? ""),
|
||||
threadId: String(pick(row, "threadId", "thread_id") ?? ""),
|
||||
title: String(row.title ?? "未命名问答"),
|
||||
draftMarkdown: String(
|
||||
pick(row, "draftMarkdown", "draft_markdown") ?? "",
|
||||
),
|
||||
createdAt: pick(row, "createdAt", "created_at"),
|
||||
updatedAt: pick(row, "updatedAt", "updated_at"),
|
||||
canWrite: Boolean(pick(row, "canWrite", "can_write")),
|
||||
publication: normalizePublication(row.publication),
|
||||
};
|
||||
}
|
||||
|
||||
async function readJson<T>(response: Response, action: string): Promise<T> {
|
||||
if (!response.ok) {
|
||||
const body = (await response.json().catch(() => ({}))) as {
|
||||
detail?: unknown;
|
||||
};
|
||||
const detail = body.detail;
|
||||
const detailMessage =
|
||||
detail && typeof detail === "object" && !Array.isArray(detail)
|
||||
? (detail as { message?: unknown }).message
|
||||
: undefined;
|
||||
throw new Error(
|
||||
typeof detail === "string"
|
||||
? detail
|
||||
: typeof detailMessage === "string"
|
||||
? detailMessage
|
||||
: `${action}失败(${response.status})`,
|
||||
);
|
||||
}
|
||||
return response.json() as Promise<T>;
|
||||
}
|
||||
|
||||
function researchBase(knowledgeBaseId: string): string {
|
||||
return `${getBackendBaseURL()}/api/llmwiki/knowledge-bases/${encodeURIComponent(knowledgeBaseId)}/research`;
|
||||
}
|
||||
|
||||
export async function listKnowledgeResearch(
|
||||
knowledgeBaseId: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<KnowledgeResearchLibrary> {
|
||||
const data = await readJson<WireRecord>(
|
||||
await apiFetch(`${researchBase(knowledgeBaseId)}/sessions`, { signal }),
|
||||
"读取深度研究",
|
||||
);
|
||||
return {
|
||||
sessions: Array.isArray(data.sessions)
|
||||
? data.sessions.map(normalizeSession).filter((item) => item.id)
|
||||
: [],
|
||||
publications: Array.isArray(data.publications)
|
||||
? data.publications
|
||||
.map(normalizePublication)
|
||||
.filter((item): item is KnowledgeResearchPublication => item !== null)
|
||||
: [],
|
||||
};
|
||||
}
|
||||
|
||||
export async function createKnowledgeResearchSession(
|
||||
knowledgeBaseId: string,
|
||||
question: string,
|
||||
): Promise<KnowledgeResearchSession> {
|
||||
const data = await readJson<WireRecord>(
|
||||
await apiFetch(`${researchBase(knowledgeBaseId)}/sessions`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ question }),
|
||||
}),
|
||||
"创建知识库问答",
|
||||
);
|
||||
return normalizeSession(data);
|
||||
}
|
||||
|
||||
export async function getKnowledgeResearchSession(
|
||||
knowledgeBaseId: string,
|
||||
sessionId: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<KnowledgeResearchSession> {
|
||||
const data = await readJson<WireRecord>(
|
||||
await apiFetch(
|
||||
`${researchBase(knowledgeBaseId)}/sessions/${encodeURIComponent(sessionId)}`,
|
||||
{ signal },
|
||||
),
|
||||
"读取知识库问答",
|
||||
);
|
||||
return normalizeSession(data);
|
||||
}
|
||||
|
||||
export async function updateKnowledgeResearchSession(
|
||||
knowledgeBaseId: string,
|
||||
sessionId: string,
|
||||
patch: { title?: string; draftMarkdown?: string },
|
||||
): Promise<KnowledgeResearchSession> {
|
||||
const data = await readJson<WireRecord>(
|
||||
await apiFetch(
|
||||
`${researchBase(knowledgeBaseId)}/sessions/${encodeURIComponent(sessionId)}`,
|
||||
{
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
...(patch.title !== undefined ? { title: patch.title } : {}),
|
||||
...(patch.draftMarkdown !== undefined
|
||||
? { draft_markdown: patch.draftMarkdown }
|
||||
: {}),
|
||||
}),
|
||||
},
|
||||
),
|
||||
"更新 Markdown 草稿",
|
||||
);
|
||||
return normalizeSession(data);
|
||||
}
|
||||
|
||||
export async function publishKnowledgeResearchSession(
|
||||
knowledgeBaseId: string,
|
||||
sessionId: string,
|
||||
input: { title: string; expectedSavedHash?: string | null },
|
||||
): Promise<KnowledgeResearchSession> {
|
||||
const data = await readJson<WireRecord>(
|
||||
await apiFetch(
|
||||
`${researchBase(knowledgeBaseId)}/sessions/${encodeURIComponent(sessionId)}/publication`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
title: input.title,
|
||||
expected_saved_hash: input.expectedSavedHash ?? null,
|
||||
}),
|
||||
},
|
||||
),
|
||||
"保存到 Wiki",
|
||||
);
|
||||
// The endpoint returns the updated session so the caller gets the new hash.
|
||||
return normalizeSession(data);
|
||||
}
|
||||
|
||||
export async function getKnowledgeResearchPublication(
|
||||
knowledgeBaseId: string,
|
||||
publicationId: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<KnowledgeResearchPublication> {
|
||||
const data = await readJson<WireRecord>(
|
||||
await apiFetch(
|
||||
`${researchBase(knowledgeBaseId)}/publications/${encodeURIComponent(publicationId)}`,
|
||||
{ signal },
|
||||
),
|
||||
"读取 Markdown 文档",
|
||||
);
|
||||
const normalized = normalizePublication(data);
|
||||
if (!normalized) throw new Error("Markdown 文档数据无效");
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function useKnowledgeResearchLibrary(
|
||||
knowledgeBaseId: string | null,
|
||||
) {
|
||||
const { userId } = useLiveAccount();
|
||||
const userScope = userId ?? KNOWLEDGE_RESEARCH_ANONYMOUS_SCOPE;
|
||||
return useQuery({
|
||||
queryKey: knowledgeResearchLibraryQueryKey(
|
||||
userScope,
|
||||
knowledgeBaseId ?? "",
|
||||
),
|
||||
queryFn: ({ signal }) => listKnowledgeResearch(knowledgeBaseId!, signal),
|
||||
enabled: !!knowledgeBaseId,
|
||||
});
|
||||
}
|
||||
|
||||
export function useKnowledgeResearchSession(
|
||||
knowledgeBaseId: string | null,
|
||||
sessionId: string | null,
|
||||
) {
|
||||
const { userId } = useLiveAccount();
|
||||
const userScope = userId ?? KNOWLEDGE_RESEARCH_ANONYMOUS_SCOPE;
|
||||
return useQuery({
|
||||
queryKey: knowledgeResearchSessionQueryKey(
|
||||
userScope,
|
||||
knowledgeBaseId ?? "",
|
||||
sessionId,
|
||||
),
|
||||
queryFn: ({ signal }) =>
|
||||
getKnowledgeResearchSession(knowledgeBaseId!, sessionId!, signal),
|
||||
enabled: !!knowledgeBaseId && !!sessionId,
|
||||
});
|
||||
}
|
||||
|
||||
export function useKnowledgeResearchPublication(
|
||||
knowledgeBaseId: string | null,
|
||||
publicationId: string | null,
|
||||
enabled = true,
|
||||
) {
|
||||
const { userId } = useLiveAccount();
|
||||
const userScope = userId ?? KNOWLEDGE_RESEARCH_ANONYMOUS_SCOPE;
|
||||
return useQuery({
|
||||
queryKey: knowledgeResearchPublicationQueryKey(
|
||||
userScope,
|
||||
knowledgeBaseId ?? "",
|
||||
publicationId,
|
||||
),
|
||||
queryFn: ({ signal }) =>
|
||||
getKnowledgeResearchPublication(knowledgeBaseId!, publicationId!, signal),
|
||||
enabled: enabled && !!knowledgeBaseId && !!publicationId,
|
||||
});
|
||||
}
|
||||
|
||||
export function useKnowledgeResearchActions(knowledgeBaseId: string) {
|
||||
const client = useQueryClient();
|
||||
const { userId } = useLiveAccount();
|
||||
const userScope = userId ?? KNOWLEDGE_RESEARCH_ANONYMOUS_SCOPE;
|
||||
const updateCaches = (session: KnowledgeResearchSession) => {
|
||||
client.setQueryData(
|
||||
knowledgeResearchSessionQueryKey(
|
||||
userScope,
|
||||
knowledgeBaseId,
|
||||
session.id,
|
||||
),
|
||||
session,
|
||||
);
|
||||
void client.invalidateQueries({
|
||||
queryKey: knowledgeResearchLibraryQueryKey(userScope, knowledgeBaseId),
|
||||
});
|
||||
if (session.publication)
|
||||
void client.invalidateQueries({
|
||||
queryKey: knowledgeResearchPublicationQueryKey(
|
||||
userScope,
|
||||
knowledgeBaseId,
|
||||
session.publication.id,
|
||||
),
|
||||
});
|
||||
};
|
||||
return {
|
||||
create: useMutation({
|
||||
mutationKey: [
|
||||
...knowledgeResearchLibraryQueryKey(userScope, knowledgeBaseId),
|
||||
"create",
|
||||
],
|
||||
mutationFn: (question: string) =>
|
||||
createKnowledgeResearchSession(knowledgeBaseId, question),
|
||||
onSuccess: updateCaches,
|
||||
}),
|
||||
update: useMutation({
|
||||
mutationKey: [
|
||||
...knowledgeResearchLibraryQueryKey(userScope, knowledgeBaseId),
|
||||
"update",
|
||||
],
|
||||
mutationFn: ({
|
||||
sessionId,
|
||||
patch,
|
||||
}: {
|
||||
sessionId: string;
|
||||
patch: { title?: string; draftMarkdown?: string };
|
||||
}) => updateKnowledgeResearchSession(knowledgeBaseId, sessionId, patch),
|
||||
onSuccess: updateCaches,
|
||||
}),
|
||||
publish: useMutation({
|
||||
mutationKey: [
|
||||
...knowledgeResearchLibraryQueryKey(userScope, knowledgeBaseId),
|
||||
"publish",
|
||||
],
|
||||
mutationFn: ({
|
||||
sessionId,
|
||||
title,
|
||||
expectedSavedHash,
|
||||
}: {
|
||||
sessionId: string;
|
||||
title: string;
|
||||
expectedSavedHash?: string | null;
|
||||
}) =>
|
||||
publishKnowledgeResearchSession(knowledgeBaseId, sessionId, {
|
||||
title,
|
||||
expectedSavedHash,
|
||||
}),
|
||||
onSuccess: updateCaches,
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -52,6 +52,13 @@ export interface LightApp {
|
||||
tags: Tag[];
|
||||
}
|
||||
|
||||
export interface LightAppSidebarItem {
|
||||
appId: string;
|
||||
name: string;
|
||||
mountLocation: string | null;
|
||||
sortOrder: number;
|
||||
}
|
||||
|
||||
export interface LightAppInput {
|
||||
name: string;
|
||||
description?: string | null;
|
||||
@@ -175,6 +182,24 @@ export async function listLightApps(params: ListLightAppsParams = {}): Promise<L
|
||||
return apps;
|
||||
}
|
||||
|
||||
export async function listSidebarLightApps(): Promise<LightAppSidebarItem[]> {
|
||||
const res = await apiFetch(`${BASE()}/sidebar`, { method: "GET" });
|
||||
const data = await readJson<{
|
||||
apps?: Array<{
|
||||
app_id: string;
|
||||
name: string;
|
||||
mount_location?: string | null;
|
||||
sort_order?: number;
|
||||
}>;
|
||||
}>(res, "list sidebar light apps");
|
||||
return (data.apps ?? []).map((app) => ({
|
||||
appId: app.app_id,
|
||||
name: app.name,
|
||||
mountLocation: app.mount_location ?? null,
|
||||
sortOrder: app.sort_order ?? 0,
|
||||
}));
|
||||
}
|
||||
|
||||
export async function getLightApp(appId: string): Promise<LightApp> {
|
||||
const res = await apiFetch(`${BASE()}/${encodeURIComponent(appId)}`, { method: "GET" });
|
||||
const app = toApp(await readJson<ServerApp>(res, "get light app"));
|
||||
@@ -240,6 +265,15 @@ export async function deleteLightApp(appId: string): Promise<void> {
|
||||
|
||||
const LIGHT_APPS_KEY = "light-apps";
|
||||
|
||||
export function useSidebarLightApps() {
|
||||
return useQuery({
|
||||
queryKey: [LIGHT_APPS_KEY, "sidebar"],
|
||||
queryFn: listSidebarLightApps,
|
||||
staleTime: 60_000,
|
||||
refetchOnWindowFocus: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function useLightApps(params: ListLightAppsParams = {}) {
|
||||
return useQuery({
|
||||
queryKey: [
|
||||
@@ -254,6 +288,7 @@ export function useLightApps(params: ListLightAppsParams = {}) {
|
||||
queryFn: () => listLightApps(params),
|
||||
placeholderData: keepPreviousData,
|
||||
refetchOnWindowFocus: false,
|
||||
staleTime: 60_000,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import { getAuthorizationHeaderValue } from "@/core/auth";
|
||||
import { useLiveAccount } from "@/core/auth/use-live-account";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
import type { LlmWikiRetrievalMode } from "@/core/llmwiki/retrieval-debug";
|
||||
import { withKnowledgeRequestTimeout } from "@/core/llmwiki/request-timeout";
|
||||
import { userFacingKnowledgeMessage } from "@/lib/knowledge-message";
|
||||
|
||||
export type { LlmWikiRetrievalMode } from "@/core/llmwiki/retrieval-debug";
|
||||
@@ -31,20 +32,35 @@ export interface LlmWikiSettings extends LlmWikiRuntime {
|
||||
}
|
||||
|
||||
export interface LlmWikiWikiInstructions {
|
||||
content_instructions: string;
|
||||
extraction_instructions: string;
|
||||
content_instructions?: string;
|
||||
extraction_instructions?: string;
|
||||
parent_directories?: string[];
|
||||
directory_paths?: string[][];
|
||||
focus_instructions?: string;
|
||||
}
|
||||
|
||||
export interface LlmWikiWikiConfig extends Record<string, unknown> {
|
||||
synthesis_model_id?: string;
|
||||
extraction_granularity?: "focused" | "standard" | "exhaustive";
|
||||
content_instructions?: string;
|
||||
extraction_instructions?: string;
|
||||
content_instructions?: string | null;
|
||||
extraction_instructions?: string | null;
|
||||
parent_directories?: string[] | null;
|
||||
directory_paths?: string[][] | null;
|
||||
focus_instructions?: string | null;
|
||||
wiki_config_schema_version?: number | null;
|
||||
wiki_config_revision?: number | null;
|
||||
applied_revision?: number | null;
|
||||
applied_result_id?: string | null;
|
||||
apply_status?: "active" | "error" | "not_applicable";
|
||||
apply_error?: string | null;
|
||||
directory_prompt_coverage?: "full" | "partial" | "none";
|
||||
directory_prompt_covered_nodes?: number;
|
||||
directory_prompt_total_nodes?: number;
|
||||
}
|
||||
|
||||
export interface LlmWikiKnowledgeBase {
|
||||
id: string;
|
||||
remote_status: "available" | "missing";
|
||||
remote_status: "available" | "cached" | "missing";
|
||||
name: string;
|
||||
description: string;
|
||||
test_questions: string[];
|
||||
@@ -93,6 +109,16 @@ export interface LlmWikiKnowledgeBase {
|
||||
remote_created_at?: string | null;
|
||||
remote_updated_at?: string | null;
|
||||
is_conversation_deposit?: boolean;
|
||||
wiki_generation_managed?: boolean | null;
|
||||
}
|
||||
|
||||
export interface LlmWikiKnowledgeBaseCreateInput {
|
||||
name: string;
|
||||
description: string;
|
||||
type: "document" | "faq";
|
||||
wiki_enabled?: boolean;
|
||||
embedding_model_id?: string;
|
||||
wiki_config?: LlmWikiWikiInstructions;
|
||||
}
|
||||
|
||||
export interface LlmWikiEmbeddingModel {
|
||||
@@ -353,6 +379,8 @@ export interface LocalWikiEncoderStatus {
|
||||
}
|
||||
|
||||
export interface LlmWikiSourceContext {
|
||||
knowledge_base_id?: string;
|
||||
document_id?: string;
|
||||
knowledge_base_name?: string;
|
||||
document_title?: string;
|
||||
document_file_name?: string;
|
||||
@@ -505,21 +533,25 @@ async function readJson<T>(response: Response, context: string): Promise<T> {
|
||||
return (await response.json()) as T;
|
||||
}
|
||||
|
||||
export async function getLlmWikiRuntime(): Promise<LlmWikiRuntime> {
|
||||
return readJson(await apiFetch(`${API()}/runtime`), "读取 LLMWiki 运行模式");
|
||||
export async function getLlmWikiRuntime(signal?: AbortSignal): Promise<LlmWikiRuntime> {
|
||||
return withKnowledgeRequestTimeout(
|
||||
async (requestSignal) => readJson(await apiFetch(`${API()}/runtime`, { signal: requestSignal }), "读取 LLMWiki 运行模式"),
|
||||
{ signal },
|
||||
);
|
||||
}
|
||||
|
||||
export async function listLlmWikiKnowledgeBases(
|
||||
scope: LlmWikiScope,
|
||||
options: { signal?: AbortSignal; refresh?: boolean } = {},
|
||||
): Promise<LlmWikiKnowledgeBase[]> {
|
||||
const response = await apiFetch(
|
||||
`${API()}/knowledge-bases?scope=${encodeURIComponent(scope)}`,
|
||||
);
|
||||
const payload = await readJson<{ knowledge_bases: LlmWikiKnowledgeBase[] }>(
|
||||
response,
|
||||
"读取知识库",
|
||||
);
|
||||
return payload.knowledge_bases ?? [];
|
||||
return withKnowledgeRequestTimeout(async (signal) => {
|
||||
const response = await apiFetch(
|
||||
`${API()}/knowledge-bases?scope=${encodeURIComponent(scope)}${options.refresh ? "&refresh=true" : ""}`,
|
||||
{ signal },
|
||||
);
|
||||
const payload = await readJson<{ knowledge_bases: LlmWikiKnowledgeBase[] }>(response, "读取知识库");
|
||||
return payload.knowledge_bases ?? [];
|
||||
}, options);
|
||||
}
|
||||
|
||||
export async function listAgentLlmWikiKnowledgeBases(
|
||||
@@ -536,10 +568,14 @@ export async function listAgentLlmWikiKnowledgeBases(
|
||||
|
||||
export async function getLlmWikiKnowledgeBase(
|
||||
id: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<LlmWikiKnowledgeBase> {
|
||||
return readJson(
|
||||
await apiFetch(`${API()}/knowledge-bases/${encodeURIComponent(id)}`),
|
||||
"读取知识库详情",
|
||||
return withKnowledgeRequestTimeout(
|
||||
async (requestSignal) => readJson(
|
||||
await apiFetch(`${API()}/knowledge-bases/${encodeURIComponent(id)}`, { signal: requestSignal }),
|
||||
"读取知识库详情",
|
||||
),
|
||||
{ signal },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -557,39 +593,50 @@ export async function listLlmWikiEmbeddingModels(): Promise<LlmWikiEmbeddingMode
|
||||
export async function createLlmWikiWeKnoraEmbedSession(
|
||||
id: string,
|
||||
tab: "documents" | "wiki" | "graph",
|
||||
signal?: AbortSignal,
|
||||
): Promise<LlmWikiWeKnoraEmbedSession> {
|
||||
return readJson(
|
||||
await apiFetch(
|
||||
`${API()}/knowledge-bases/${encodeURIComponent(id)}/weknora/session?tab=${encodeURIComponent(tab)}`,
|
||||
{ method: "POST" },
|
||||
return withKnowledgeRequestTimeout(
|
||||
async (requestSignal) => readJson(
|
||||
await apiFetch(
|
||||
`${API()}/knowledge-bases/${encodeURIComponent(id)}/weknora/session?tab=${encodeURIComponent(tab)}`,
|
||||
{ method: "POST", signal: requestSignal },
|
||||
),
|
||||
"创建知识库详情会话",
|
||||
),
|
||||
"创建知识库详情会话",
|
||||
{ signal },
|
||||
);
|
||||
}
|
||||
|
||||
export async function resolveLlmWikiSourceKnowledgeBase(knowledgeBaseId: string): Promise<string> {
|
||||
const params = new URLSearchParams({ knowledge_base_id: knowledgeBaseId });
|
||||
const payload = await readJson<{ knowledge_base_id: string }>(
|
||||
await apiFetch(`${API()}/sources/resolve?${params}`),
|
||||
"定位检索文件所属知识库",
|
||||
);
|
||||
return payload.knowledge_base_id;
|
||||
}
|
||||
|
||||
export async function getLlmWikiSourceContext(
|
||||
knowledgeBaseId: string,
|
||||
chunkId: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<LlmWikiSourceContext> {
|
||||
const params = new URLSearchParams({
|
||||
knowledge_base_id: knowledgeBaseId,
|
||||
chunk_id: chunkId,
|
||||
});
|
||||
const payload = await readJson<{
|
||||
success: boolean;
|
||||
data: LlmWikiSourceContext;
|
||||
}>(await apiFetch(`${API()}/sources/context?${params}`), "加载参考文献原文");
|
||||
const payload = await withKnowledgeRequestTimeout(async (requestSignal) => readJson<{
|
||||
success: boolean;
|
||||
data: LlmWikiSourceContext;
|
||||
}>(await apiFetch(`${API()}/sources/context?${params}`, { signal: requestSignal }), "加载参考文献原文"),
|
||||
{ signal },
|
||||
);
|
||||
return payload.data;
|
||||
}
|
||||
|
||||
export async function createLlmWikiKnowledgeBase(input: {
|
||||
name: string;
|
||||
description: string;
|
||||
type: "document" | "faq";
|
||||
wiki_enabled?: boolean;
|
||||
embedding_model_id?: string;
|
||||
wiki_config?: LlmWikiWikiInstructions;
|
||||
}): Promise<LlmWikiKnowledgeBase> {
|
||||
export async function createLlmWikiKnowledgeBase(
|
||||
input: LlmWikiKnowledgeBaseCreateInput,
|
||||
): Promise<LlmWikiKnowledgeBase> {
|
||||
return readJson(
|
||||
await apiFetch(`${API()}/knowledge-bases`, {
|
||||
method: "POST",
|
||||
@@ -794,31 +841,35 @@ export async function listLlmWikiWikiPages(
|
||||
page: number,
|
||||
pageSize: number,
|
||||
query = "",
|
||||
signal?: AbortSignal,
|
||||
): Promise<LlmWikiWikiPageList> {
|
||||
const params = new URLSearchParams({
|
||||
page: String(page),
|
||||
page_size: String(pageSize),
|
||||
});
|
||||
if (query.trim()) params.set("query", query.trim());
|
||||
return readJson(
|
||||
return withKnowledgeRequestTimeout(async (requestSignal) => readJson(
|
||||
await apiFetch(
|
||||
`${API()}/knowledge-bases/${encodeURIComponent(knowledgeBaseId)}/wiki/pages?${params.toString()}`,
|
||||
{ signal: requestSignal },
|
||||
),
|
||||
"读取 Wiki 页面",
|
||||
);
|
||||
), { signal });
|
||||
}
|
||||
|
||||
export async function getLlmWikiWikiPage(
|
||||
knowledgeBaseId: string,
|
||||
slug: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<LlmWikiWikiPage> {
|
||||
const safeSlug = slug.split("/").map(encodeURIComponent).join("/");
|
||||
return readJson(
|
||||
return withKnowledgeRequestTimeout(async (requestSignal) => readJson(
|
||||
await apiFetch(
|
||||
`${API()}/knowledge-bases/${encodeURIComponent(knowledgeBaseId)}/wiki/pages/${safeSlug}`,
|
||||
{ signal: requestSignal },
|
||||
),
|
||||
"读取 Wiki 页面详情",
|
||||
);
|
||||
), { signal });
|
||||
}
|
||||
|
||||
export async function getLlmWikiWikiIndexStatus(
|
||||
@@ -1269,26 +1320,37 @@ const knowledgeBasesKey = (userId: string | null, scope: LlmWikiScope) =>
|
||||
export function useLlmWikiRuntime() {
|
||||
return useQuery({
|
||||
queryKey: runtimeKey,
|
||||
queryFn: getLlmWikiRuntime,
|
||||
queryFn: ({ signal }) => getLlmWikiRuntime(signal),
|
||||
staleTime: 30_000,
|
||||
retry: 1,
|
||||
retry: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function useLlmWikiKnowledgeBases(scope: LlmWikiScope, enabled = true) {
|
||||
const { userId } = useLiveAccount();
|
||||
return useQuery({
|
||||
const queryClient = useQueryClient();
|
||||
const query = useQuery({
|
||||
queryKey: knowledgeBasesKey(userId, scope),
|
||||
queryFn: () => listLlmWikiKnowledgeBases(scope),
|
||||
// The local directory response has no document/chunk statistics. Fetch the
|
||||
// upstream snapshot on normal loads too, including after invalidation.
|
||||
queryFn: ({ signal }) => listLlmWikiKnowledgeBases(scope, { signal, refresh: true }),
|
||||
enabled,
|
||||
staleTime: 30_000,
|
||||
refetchInterval: (query) =>
|
||||
(query.state.data ?? []).some(
|
||||
(item) => item.is_processing || item.processing_count > 0,
|
||||
)
|
||||
? 15_000
|
||||
: false,
|
||||
retry: false,
|
||||
});
|
||||
return {
|
||||
...query,
|
||||
refresh: async () => {
|
||||
const queryKey = knowledgeBasesKey(userId, scope);
|
||||
await queryClient.cancelQueries({ queryKey, exact: true });
|
||||
return queryClient.fetchQuery({
|
||||
queryKey,
|
||||
queryFn: ({ signal }) => listLlmWikiKnowledgeBases(scope, { signal, refresh: true }),
|
||||
staleTime: 0,
|
||||
retry: false,
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function useAgentLlmWikiKnowledgeBases(
|
||||
@@ -1312,6 +1374,7 @@ export function useAgentLlmWikiKnowledgeBases(
|
||||
export function useLlmWikiKnowledgeBase(
|
||||
knowledgeBaseId: string | null,
|
||||
enabled = true,
|
||||
options: { pollInterval?: number | false } = {},
|
||||
) {
|
||||
const { userId } = useLiveAccount();
|
||||
return useQuery({
|
||||
@@ -1321,9 +1384,14 @@ export function useLlmWikiKnowledgeBase(
|
||||
knowledgeBaseId,
|
||||
userId ?? "anonymous",
|
||||
],
|
||||
queryFn: () => getLlmWikiKnowledgeBase(knowledgeBaseId!),
|
||||
queryFn: ({ signal }) => getLlmWikiKnowledgeBase(knowledgeBaseId!, signal),
|
||||
enabled: enabled && !!knowledgeBaseId,
|
||||
refetchInterval: 8_000,
|
||||
staleTime: 30_000,
|
||||
retry: false,
|
||||
refetchInterval: (query) =>
|
||||
options.pollInterval ?? (query.state.data?.is_processing || (query.state.data?.processing_count ?? 0) > 0
|
||||
? 8_000
|
||||
: false),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1401,6 +1469,7 @@ export function useLlmWikiWikiPages(
|
||||
pageSize = 50,
|
||||
query = "",
|
||||
enabled = true,
|
||||
options: { pollInterval?: number | false } = {},
|
||||
) {
|
||||
const { userId } = useLiveAccount();
|
||||
return useQuery({
|
||||
@@ -1413,10 +1482,12 @@ export function useLlmWikiWikiPages(
|
||||
query,
|
||||
userId ?? "anonymous",
|
||||
],
|
||||
queryFn: () =>
|
||||
listLlmWikiWikiPages(knowledgeBaseId!, page, pageSize, query),
|
||||
queryFn: ({ signal }) =>
|
||||
listLlmWikiWikiPages(knowledgeBaseId!, page, pageSize, query, signal),
|
||||
enabled: enabled && !!knowledgeBaseId,
|
||||
refetchInterval: 10_000,
|
||||
retry: false,
|
||||
staleTime: 30_000,
|
||||
refetchInterval: options.pollInterval ?? 10_000,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1434,8 +1505,10 @@ export function useLlmWikiWikiPage(
|
||||
slug,
|
||||
userId ?? "anonymous",
|
||||
],
|
||||
queryFn: () => getLlmWikiWikiPage(knowledgeBaseId!, slug!),
|
||||
queryFn: ({ signal }) => getLlmWikiWikiPage(knowledgeBaseId!, slug!, signal),
|
||||
enabled: enabled && !!knowledgeBaseId && !!slug,
|
||||
staleTime: 30_000,
|
||||
retry: false,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -146,11 +146,11 @@ export function useMenuOverrides() {
|
||||
return useQuery({
|
||||
queryKey: [MENU_OVERRIDES_KEY, accountKey],
|
||||
queryFn: listMenuOverrides,
|
||||
// An administrator may add a default menu from another tab. Refreshing on
|
||||
// mount/focus lets that new node flow into an existing personal snapshot.
|
||||
refetchOnMount: "always",
|
||||
refetchOnWindowFocus: "always",
|
||||
staleTime: 0,
|
||||
// Menu defaults change rarely and writes invalidate this shared cache.
|
||||
// Avoid re-reading the same global + personal rows on every route mount.
|
||||
refetchOnMount: false,
|
||||
refetchOnWindowFocus: false,
|
||||
staleTime: 60_000,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+60
-75
@@ -4,6 +4,7 @@ import {
|
||||
Edit3,
|
||||
FileText,
|
||||
Loader2,
|
||||
Microscope,
|
||||
RefreshCw,
|
||||
Search,
|
||||
Trash2,
|
||||
@@ -18,7 +19,6 @@ import {
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useOrdinaryKnowledgeLanding } from "@/components/workspace/knowledge-product-nav";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
@@ -30,7 +30,10 @@ import { Textarea } from "@/components/ui/textarea";
|
||||
import { MarkdownCodeEditor } from "@/components/wiki/MarkdownCodeEditor";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
import { getStoredAuth } from "@/core/auth";
|
||||
import { defaultEmbeddedKnowledgeTab } from "@/core/llmwiki/knowledge-base-navigation";
|
||||
import { buildWeKnoraWikiPagePath } from "@/core/llmwiki/source-links";
|
||||
import { resolveWeKnoraFrameUrl } from "@/core/llmwiki/weknora-frame-url";
|
||||
import { useOrdinaryKnowledgeRetrievalSettings } from "@/core/system-settings/hooks";
|
||||
import {
|
||||
createLlmWikiWeKnoraEmbedSession,
|
||||
getLlmWikiSourceContext,
|
||||
@@ -108,22 +111,11 @@ function postThemeToFrame(frame: HTMLIFrameElement | null) {
|
||||
frame.contentWindow.postMessage(collectThemePayload(), targetOrigin);
|
||||
}
|
||||
|
||||
const WEKNORA_BACKEND_PREFIX = "/deerflow";
|
||||
|
||||
function buildFrameUrl(framePath: string) {
|
||||
const backendBase = getBackendBaseURL().replace(/\/+$/, "");
|
||||
const backendOrigin = backendBase
|
||||
? new URL(backendBase, window.location.origin).origin
|
||||
: window.location.origin;
|
||||
if (/^https?:\/\//i.test(framePath)) return new URL(framePath);
|
||||
if (framePath.startsWith("/")) {
|
||||
const path = !framePath.startsWith(`${WEKNORA_BACKEND_PREFIX}/`)
|
||||
? `${WEKNORA_BACKEND_PREFIX}${framePath}`
|
||||
: framePath;
|
||||
return new URL(path, backendOrigin);
|
||||
}
|
||||
return new URL(
|
||||
`${backendBase || backendOrigin}/${framePath.replace(/^\/+/, "")}`,
|
||||
return resolveWeKnoraFrameUrl(
|
||||
framePath,
|
||||
getBackendBaseURL(),
|
||||
window.location.origin,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -139,17 +131,29 @@ export function WeKnoraKnowledgeDetailPage() {
|
||||
const frameRef = useRef<HTMLIFrameElement>(null);
|
||||
const [frameSrc, setFrameSrc] = useState("");
|
||||
const [frameVersion, setFrameVersion] = useState(0);
|
||||
const [sessionAttempt, setSessionAttempt] = useState(0);
|
||||
const [frameError, setFrameError] = useState<string | null>(null);
|
||||
const isAdmin = getStoredAuth()?.system_role === "admin";
|
||||
const runtime = useLlmWikiRuntime();
|
||||
const landing = useOrdinaryKnowledgeLanding();
|
||||
const requestedTab = searchParams.get("tab");
|
||||
const explicitTab = requestedTab === "documents" || requestedTab === "wiki" || requestedTab === "graph" ? requestedTab : null;
|
||||
const sourceChunkId = searchParams.get("sourceChunkId") || searchParams.get("chunkId") || "";
|
||||
const documentId = searchParams.get("documentId") || "";
|
||||
const wikiSlug = searchParams.get("wikiSlug") || "";
|
||||
const nativeWikiPageUrl = knowledgeBaseId && wikiSlug && (!explicitTab || explicitTab === "wiki")
|
||||
? buildWeKnoraWikiPagePath(knowledgeBaseId, wikiSlug)
|
||||
: "";
|
||||
const details = useLlmWikiKnowledgeBase(
|
||||
knowledgeBaseId || null,
|
||||
!!knowledgeBaseId,
|
||||
!!knowledgeBaseId && !nativeWikiPageUrl,
|
||||
);
|
||||
const knowledgeManagementSettings = useOrdinaryKnowledgeRetrievalSettings(
|
||||
isAdmin || details.data?.can_write === true,
|
||||
);
|
||||
const advancedManagementEnabled =
|
||||
knowledgeManagementSettings.data?.advanced_management_enabled === true;
|
||||
|
||||
const detailsReady = !!details.data;
|
||||
const requestedTab = searchParams.get("tab");
|
||||
const detailsWikiEnabled =
|
||||
details.data?.type === "wiki" ||
|
||||
details.data?.wiki_index_enabled === true ||
|
||||
@@ -157,34 +161,19 @@ export function WeKnoraKnowledgeDetailPage() {
|
||||
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
|
||||
: detailsWikiEnabled
|
||||
? "wiki"
|
||||
: "documents";
|
||||
const sourceChunkId =
|
||||
searchParams.get("sourceChunkId") || searchParams.get("chunkId") || "";
|
||||
const documentId = searchParams.get("documentId") || "";
|
||||
const wikiSlug = searchParams.get("wikiSlug") || "";
|
||||
const defaultEntry = searchParams.get("view") !== "weknora" && !requestedTab && !wikiSlug && !sourceChunkId && !documentId;
|
||||
const showNativeIndex = defaultEntry && (landing.data ?? "wiki") === "wiki" && !!detailsWikiEnabled;
|
||||
const nativeWikiPageUrl =
|
||||
knowledgeBaseId && wikiSlug && preferredTab === "wiki"
|
||||
? buildWeKnoraWikiPagePath(knowledgeBaseId, wikiSlug)
|
||||
: "";
|
||||
const preferredTab = defaultEmbeddedKnowledgeTab(explicitTab);
|
||||
const sessionReady = !!(explicitTab || detailsReady);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const controller = new AbortController();
|
||||
setFrameSrc("");
|
||||
setFrameError(null);
|
||||
if (
|
||||
nativeWikiPageUrl || landing.isLoading || showNativeIndex ||
|
||||
nativeWikiPageUrl ||
|
||||
!knowledgeBaseId ||
|
||||
runtime.data?.provider !== "weknora" ||
|
||||
!detailsReady
|
||||
!sessionReady
|
||||
) {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
@@ -192,22 +181,17 @@ export function WeKnoraKnowledgeDetailPage() {
|
||||
}
|
||||
|
||||
void (async () => {
|
||||
const resolvedWikiSlug =
|
||||
wikiSlug ||
|
||||
(sourceChunkId
|
||||
? (
|
||||
await getLlmWikiSourceContext(
|
||||
knowledgeBaseId,
|
||||
sourceChunkId,
|
||||
).catch(() => null)
|
||||
)?.wiki_page?.slug
|
||||
: "");
|
||||
const session = await createLlmWikiWeKnoraEmbedSession(
|
||||
knowledgeBaseId,
|
||||
preferredTab,
|
||||
);
|
||||
// Source lookup and cookie/session setup are independent requests.
|
||||
const [session, context] = await Promise.all([
|
||||
createLlmWikiWeKnoraEmbedSession(knowledgeBaseId, preferredTab, controller.signal),
|
||||
!wikiSlug && sourceChunkId
|
||||
? getLlmWikiSourceContext(knowledgeBaseId, sourceChunkId, controller.signal).catch(() => null)
|
||||
: Promise.resolve(null),
|
||||
]);
|
||||
if (cancelled) return;
|
||||
const resolvedWikiSlug = wikiSlug || context?.wiki_page?.slug || "";
|
||||
const framePath = session.frame_path || "";
|
||||
if (!framePath) throw new Error("知识库会话未返回页面地址,请重试");
|
||||
const nextUrl = buildFrameUrl(framePath);
|
||||
nextUrl.searchParams.set("theme", collectThemePayload().theme);
|
||||
if (sourceChunkId)
|
||||
@@ -225,14 +209,14 @@ export function WeKnoraKnowledgeDetailPage() {
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
controller.abort();
|
||||
};
|
||||
}, [
|
||||
detailsReady,
|
||||
sessionReady,
|
||||
sessionAttempt,
|
||||
documentId,
|
||||
knowledgeBaseId,
|
||||
nativeWikiPageUrl,
|
||||
landing.isLoading,
|
||||
showNativeIndex,
|
||||
preferredTab,
|
||||
runtime.data?.provider,
|
||||
sourceChunkId,
|
||||
@@ -261,7 +245,7 @@ export function WeKnoraKnowledgeDetailPage() {
|
||||
return <Navigate to={nativeWikiPageUrl} replace />;
|
||||
}
|
||||
|
||||
if (runtime.isLoading || details.isLoading || landing.isLoading) {
|
||||
if (runtime.isLoading || (details.isLoading && !frameSrc)) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center text-sm text-muted-foreground">
|
||||
<Loader2 className="mr-2 size-5 animate-spin" />
|
||||
@@ -270,10 +254,6 @@ export function WeKnoraKnowledgeDetailPage() {
|
||||
);
|
||||
}
|
||||
|
||||
if (showNativeIndex) {
|
||||
return <Navigate to={`/page/workspace/knowledge/${encodeURIComponent(knowledgeBaseId)}/wiki/view`} replace />;
|
||||
}
|
||||
|
||||
if (runtime.data?.provider !== "weknora")
|
||||
return <Navigate to={LIST_PATH} replace />;
|
||||
|
||||
@@ -289,14 +269,15 @@ export function WeKnoraKnowledgeDetailPage() {
|
||||
</div>
|
||||
<p className="mt-2 text-sm text-muted-foreground">{frameError}</p>
|
||||
</div>
|
||||
<Button variant="outline" onClick={() => navigate(LIST_PATH)}>
|
||||
返回知识库
|
||||
</Button>
|
||||
<div className="flex gap-2">
|
||||
<Button onClick={() => setSessionAttempt((value) => value + 1)}>重新加载</Button>
|
||||
<Button variant="outline" onClick={() => navigate(LIST_PATH)}>返回知识库</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (details.error || !details.data) {
|
||||
if ((details.error || !details.data) && !frameSrc) {
|
||||
return (
|
||||
<div className="flex h-full flex-col items-center justify-center gap-4 bg-background px-6 text-center">
|
||||
<div className="flex size-12 items-center justify-center rounded-full bg-destructive/10 text-destructive">
|
||||
@@ -307,18 +288,19 @@ export function WeKnoraKnowledgeDetailPage() {
|
||||
无法打开知识库详情
|
||||
</div>
|
||||
<p className="mt-2 text-sm text-muted-foreground">
|
||||
当前账号没有访问权限,或知识服务资源已不存在。
|
||||
{details.error?.message || "当前账号没有访问权限,或知识服务资源已不存在。"}
|
||||
</p>
|
||||
</div>
|
||||
<Button variant="outline" onClick={() => navigate(LIST_PATH)}>
|
||||
返回知识库
|
||||
</Button>
|
||||
<div className="flex gap-2">
|
||||
<Button disabled={details.isFetching} onClick={() => void details.refetch()}>重新加载</Button>
|
||||
<Button variant="outline" onClick={() => navigate(LIST_PATH)}>返回知识库</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const canWrite =
|
||||
details.data.can_write && !details.data.is_conversation_deposit;
|
||||
details.data?.can_write && !details.data.is_conversation_deposit;
|
||||
const canEditCurrentWikiArticle =
|
||||
canWrite && !!detailsWikiEnabled && !!wikiSlug;
|
||||
// A new/empty WeKnora base does not always expose wiki_enabled until its
|
||||
@@ -328,7 +310,7 @@ export function WeKnoraKnowledgeDetailPage() {
|
||||
|
||||
return (
|
||||
<div className="flex h-full min-h-0 flex-col bg-background">
|
||||
{(detailsWikiEnabled || canManageWiki) && (
|
||||
{details.data && (
|
||||
<div className="flex min-h-12 shrink-0 flex-wrap items-center justify-between gap-2 border-b px-4 py-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
{canEditCurrentWikiArticle && (
|
||||
@@ -349,18 +331,21 @@ export function WeKnoraKnowledgeDetailPage() {
|
||||
)}
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
{isAdmin && (
|
||||
<Button size="sm" variant="outline" onClick={() => navigate(`/page/workspace/knowledge/${encodeURIComponent(knowledgeBaseId)}/research`)}>
|
||||
<Microscope className="mr-2 size-4" />深度研究
|
||||
</Button>
|
||||
{isAdmin && advancedManagementEnabled && (
|
||||
<Button size="sm" variant="outline" onClick={() => navigate(`/page/workspace/knowledge/${encodeURIComponent(knowledgeBaseId)}/retrieval-debug`)}>
|
||||
<Search className="mr-2 size-4" />检索测试
|
||||
</Button>
|
||||
)}
|
||||
{canManageWiki && (
|
||||
{canManageWiki && advancedManagementEnabled && (
|
||||
<WeKnoraIncrementalSync knowledgeBaseId={knowledgeBaseId} />
|
||||
)}
|
||||
{detailsWikiEnabled && (
|
||||
<Button size="sm" variant="outline" onClick={() => navigate(`/page/workspace/knowledge/${encodeURIComponent(knowledgeBaseId)}/wiki/view`)}>查看 Wiki 索引</Button>
|
||||
)}
|
||||
{isAdmin && (
|
||||
{isAdmin && advancedManagementEnabled && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
@@ -389,7 +374,7 @@ export function WeKnoraKnowledgeDetailPage() {
|
||||
<iframe
|
||||
key={`${frameSrc}:${frameVersion}`}
|
||||
ref={frameRef}
|
||||
title={`${details.data.name || "知识库"} 详情`}
|
||||
title={`${details.data?.name || "知识库"} 详情`}
|
||||
src={frameSrc}
|
||||
className="h-full min-h-0 w-full flex-1 border-0 bg-background"
|
||||
referrerPolicy="no-referrer"
|
||||
|
||||
+419
-115
@@ -1,14 +1,18 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
AlertCircle,
|
||||
BookOpen,
|
||||
BookOpenText,
|
||||
ChevronRight,
|
||||
Database,
|
||||
Cpu,
|
||||
Download,
|
||||
Edit3,
|
||||
FileText,
|
||||
FolderTree,
|
||||
Globe2,
|
||||
Loader2,
|
||||
Microscope,
|
||||
Plus,
|
||||
RefreshCw,
|
||||
Search,
|
||||
@@ -44,6 +48,18 @@ import {
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { getStoredAuth } from "@/core/auth";
|
||||
import { useOrdinaryKnowledgeRetrievalSettings } from "@/core/system-settings/hooks";
|
||||
import {
|
||||
formatWikiDirectoryPaths,
|
||||
type WikiDirectoryTreeNode,
|
||||
validateWikiDirectoryTree,
|
||||
WIKI_DIRECTORY_MAX_DEPTH,
|
||||
WIKI_DIRECTORY_MAX_NODES,
|
||||
WIKI_DIRECTORY_MAX_NORMALIZED_LENGTH,
|
||||
WIKI_DIRECTORY_TEMPLATE_CONTENT,
|
||||
WIKI_DIRECTORY_TEMPLATE_FILENAME,
|
||||
} from "@/core/llmwiki/directory-tree";
|
||||
import { buildWikiKnowledgeBaseCreateInput } from "@/core/llmwiki/knowledge-base-form";
|
||||
import {
|
||||
formatRetrievalScore,
|
||||
retrievalChannelScores,
|
||||
@@ -52,6 +68,7 @@ import {
|
||||
import { WeKnoraSourceDrawer } from "@/strategy-components/components/resource-management/llmwiki/WeKnoraSourceDrawer";
|
||||
import {
|
||||
type LlmWikiKnowledgeBase,
|
||||
type LlmWikiKnowledgeBaseCreateInput,
|
||||
type LlmWikiSearchResponse,
|
||||
type LlmWikiSearchResult,
|
||||
type LlmWikiScope,
|
||||
@@ -71,7 +88,8 @@ import {
|
||||
|
||||
type WorkspaceTab = "personal" | "public" | "settings";
|
||||
const LIST_PATH = "/page/workspace/knowledge";
|
||||
const WIKI_INSTRUCTION_MAX_LENGTH = 8000;
|
||||
const WIKI_INSTRUCTION_MAX_LENGTH = 4000;
|
||||
const WIKI_FOCUS_INSTRUCTION_MAX_LENGTH = 2000;
|
||||
|
||||
const publicationLabels: Record<string, string> = {
|
||||
private: "仅自己",
|
||||
@@ -84,6 +102,20 @@ function messageOf(error: unknown): string {
|
||||
return error instanceof Error ? error.message : "操作失败,请稍后重试";
|
||||
}
|
||||
|
||||
function codePointLength(value: string): number {
|
||||
return Array.from(value).length;
|
||||
}
|
||||
|
||||
function isWikiKnowledgeBase(knowledgeBase: LlmWikiKnowledgeBase): boolean {
|
||||
if (typeof knowledgeBase.wiki_generation_managed === "boolean") {
|
||||
return knowledgeBase.wiki_generation_managed;
|
||||
}
|
||||
return knowledgeBase.type === "wiki" ||
|
||||
knowledgeBase.indexing_strategy?.wiki_enabled === true ||
|
||||
knowledgeBase.capabilities?.wiki_enabled === true ||
|
||||
knowledgeBase.wiki_config?.wiki_config_revision != null;
|
||||
}
|
||||
|
||||
function encoderProviderLabel(provider?: string | null): string {
|
||||
const normalized = provider?.trim().toLowerCase();
|
||||
if (normalized === "local") return "本地 BGE-M3";
|
||||
@@ -131,6 +163,10 @@ function resultPreview(result: LlmWikiSearchResult) {
|
||||
export function WeKnoraKnowledgeWorkspace() {
|
||||
const navigate = useNavigate();
|
||||
const isAdmin = getStoredAuth()?.system_role === "admin";
|
||||
const knowledgeManagementSettings =
|
||||
useOrdinaryKnowledgeRetrievalSettings(isAdmin);
|
||||
const advancedManagementEnabled =
|
||||
knowledgeManagementSettings.data?.advanced_management_enabled === true;
|
||||
const [tab, setTab] = useState<WorkspaceTab>("personal");
|
||||
const scope: LlmWikiScope = tab === "public" ? "public" : "personal";
|
||||
const knowledge = useLlmWikiKnowledgeBases(scope, tab !== "settings");
|
||||
@@ -148,6 +184,14 @@ export function WeKnoraKnowledgeWorkspace() {
|
||||
}, [tab]);
|
||||
|
||||
const busy = actions.create.isPending || actions.update.isPending || actions.remove.isPending || actions.publication.isPending;
|
||||
const setCreateDialogOpen = (open: boolean) => {
|
||||
if (open) actions.create.reset();
|
||||
setCreateOpen(open);
|
||||
};
|
||||
const openKnowledgeEditor = (item: LlmWikiKnowledgeBase) => {
|
||||
actions.update.reset();
|
||||
setEditingKnowledge(item);
|
||||
};
|
||||
const openDetails = (item: LlmWikiKnowledgeBase) => {
|
||||
navigate(`${LIST_PATH}/${encodeURIComponent(item.id)}`);
|
||||
};
|
||||
@@ -204,11 +248,11 @@ export function WeKnoraKnowledgeWorkspace() {
|
||||
</Button>
|
||||
)}
|
||||
{tab !== "settings" && (
|
||||
<Button variant="ghost" size="sm" className="rounded-full" onClick={() => knowledge.refetch()} disabled={knowledge.isFetching}>
|
||||
<Button variant="ghost" size="sm" className="rounded-full" onClick={() => void knowledge.refresh().catch((error) => toast.error(messageOf(error)))} disabled={knowledge.isFetching}>
|
||||
<RefreshCw className={`mr-2 size-4 ${knowledge.isFetching ? "animate-spin" : ""}`} />刷新
|
||||
</Button>
|
||||
)}
|
||||
{tab === "personal" && <Button size="sm" className="rounded-full px-4 shadow-sm" onClick={() => setCreateOpen(true)}><Plus className="mr-2 size-4" />新建知识库</Button>}
|
||||
{tab === "personal" && <Button size="sm" className="rounded-full px-4 shadow-sm" onClick={() => setCreateDialogOpen(true)}><Plus className="mr-2 size-4" />新建知识库</Button>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -233,8 +277,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} onTest={isAdmin ? (item) => navigate(`${LIST_PATH}/${encodeURIComponent(item.id)}/retrieval-debug`) : undefined} 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} onTest={isAdmin ? (item) => navigate(`${LIST_PATH}/${encodeURIComponent(item.id)}/retrieval-debug`) : undefined} onEdit={setEditingKnowledge} 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} onResearch={(item) => navigate(`${LIST_PATH}/${encodeURIComponent(item.id)}/research`)} onTest={isAdmin && advancedManagementEnabled ? (item) => navigate(`${LIST_PATH}/${encodeURIComponent(item.id)}/retrieval-debug`) : undefined} onEdit={openKnowledgeEditor} 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} onResearch={(item) => navigate(`${LIST_PATH}/${encodeURIComponent(item.id)}/research`)} onTest={isAdmin && advancedManagementEnabled ? (item) => navigate(`${LIST_PATH}/${encodeURIComponent(item.id)}/retrieval-debug`) : undefined} onEdit={openKnowledgeEditor} onPublish={togglePublication} onDelete={removeKnowledgeBase} /></TabsContent>
|
||||
{isAdmin && <TabsContent value="settings" className="mt-5"><ConnectionSettings /></TabsContent>}
|
||||
</Tabs>
|
||||
|
||||
@@ -336,7 +380,11 @@ export function WeKnoraKnowledgeWorkspace() {
|
||||
key={editingKnowledge.id}
|
||||
knowledgeBase={editingKnowledge}
|
||||
pending={actions.update.isPending}
|
||||
onClose={() => setEditingKnowledge(null)}
|
||||
error={actions.update.error}
|
||||
onClose={() => {
|
||||
actions.update.reset();
|
||||
setEditingKnowledge(null);
|
||||
}}
|
||||
onSave={async (input) => {
|
||||
try {
|
||||
await actions.update.mutateAsync({ id: editingKnowledge.id, ...input });
|
||||
@@ -349,7 +397,7 @@ export function WeKnoraKnowledgeWorkspace() {
|
||||
/>
|
||||
)}
|
||||
|
||||
<CreateKnowledgeDialog open={createOpen} pending={actions.create.isPending} onOpenChange={setCreateOpen} onCreate={async (input) => {
|
||||
<CreateKnowledgeDialog open={createOpen} pending={actions.create.isPending} error={actions.create.error} onOpenChange={setCreateDialogOpen} onCreate={async (input) => {
|
||||
try {
|
||||
const created = await actions.create.mutateAsync(input);
|
||||
setCreateOpen(false);
|
||||
@@ -363,6 +411,66 @@ export function WeKnoraKnowledgeWorkspace() {
|
||||
);
|
||||
}
|
||||
|
||||
function WikiConfigurationStatus({
|
||||
knowledgeBase,
|
||||
detailed = false,
|
||||
}: {
|
||||
knowledgeBase: LlmWikiKnowledgeBase;
|
||||
detailed?: boolean;
|
||||
}) {
|
||||
if (!isWikiKnowledgeBase(knowledgeBase)) return null;
|
||||
const config = knowledgeBase.wiki_config;
|
||||
const status = config?.apply_status;
|
||||
const revision = config?.wiki_config_revision;
|
||||
const appliedRevision = config?.applied_revision;
|
||||
const coverage = config?.directory_prompt_coverage;
|
||||
const coveredNodes = config?.directory_prompt_covered_nodes ?? 0;
|
||||
const totalNodes = config?.directory_prompt_total_nodes ?? 0;
|
||||
const hasError = status === "error" || Boolean(config?.apply_error);
|
||||
const label = hasError
|
||||
? "生成配置应用失败"
|
||||
: status === "active"
|
||||
? "生成配置已生效"
|
||||
: knowledgeBase.wiki_generation_managed === null
|
||||
? "生成配置待确认"
|
||||
: "Wiki 配置";
|
||||
const badgeClass = hasError
|
||||
? "border-destructive/30 bg-destructive/10 text-destructive hover:bg-destructive/10"
|
||||
: status === "active"
|
||||
? "border-emerald-200 bg-emerald-100 text-emerald-800 hover:bg-emerald-100 dark:border-emerald-800 dark:bg-emerald-950 dark:text-emerald-200"
|
||||
: "border-amber-200 bg-amber-100 text-amber-800 hover:bg-amber-100 dark:border-amber-800 dark:bg-amber-950 dark:text-amber-200";
|
||||
|
||||
if (!detailed) {
|
||||
return status || hasError || knowledgeBase.wiki_generation_managed === null
|
||||
? <Badge variant="outline" className={badgeClass}>{label}</Badge>
|
||||
: null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`rounded-xl border p-3 ${hasError ? "border-destructive/30 bg-destructive/5" : "bg-muted/25"}`}>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Badge variant="outline" className={badgeClass}>{label}</Badge>
|
||||
{revision != null && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
配置版本 {revision}{appliedRevision != null ? ` · 已应用版本 ${appliedRevision}` : ""}
|
||||
</span>
|
||||
)}
|
||||
{totalNodes > 0 && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
参考目录提示 {coverage === "full" ? "已全部写入" : coverage === "partial" ? "已部分写入" : "未写入"} {coveredNodes}/{totalNodes}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{config?.apply_error && (
|
||||
<p className="mt-2 text-xs leading-5 text-destructive" role="alert">{config.apply_error}</p>
|
||||
)}
|
||||
{status === "active" && (
|
||||
<p className="mt-2 text-xs leading-5 text-muted-foreground">当前表单显示的是数据库中已保存并生效的生成配置;修改只影响后续上传或重新解析的文档。</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function KnowledgeGrid({
|
||||
rows,
|
||||
loading,
|
||||
@@ -370,6 +478,7 @@ function KnowledgeGrid({
|
||||
emptyText,
|
||||
busy,
|
||||
onOpen,
|
||||
onResearch,
|
||||
onTest,
|
||||
onEdit,
|
||||
onPublish,
|
||||
@@ -381,6 +490,7 @@ function KnowledgeGrid({
|
||||
emptyText: string;
|
||||
busy: boolean;
|
||||
onOpen: (item: LlmWikiKnowledgeBase) => void;
|
||||
onResearch: (item: LlmWikiKnowledgeBase) => void;
|
||||
onTest?: (item: LlmWikiKnowledgeBase) => void;
|
||||
onEdit: (item: LlmWikiKnowledgeBase) => void;
|
||||
onPublish: (item: LlmWikiKnowledgeBase) => void;
|
||||
@@ -402,7 +512,7 @@ function KnowledgeGrid({
|
||||
<CardHeader className="pb-3 pt-5">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0"><CardTitle className="truncate text-base">{item.name}</CardTitle><CardDescription className="mt-1 line-clamp-2 min-h-10">{item.description || "暂无描述"}</CardDescription></div>
|
||||
<div className="flex shrink-0 flex-col items-end gap-1.5"><Badge variant={item.publication_status === "published" ? "default" : "secondary"}>{publicationLabels[item.publication_status] ?? "仅自己"}</Badge>{item.indexing_strategy?.wiki_enabled && <Badge className="bg-violet-100 text-violet-700 hover:bg-violet-100 dark:bg-violet-950 dark:text-violet-300">Wiki</Badge>}</div>
|
||||
<div className="flex shrink-0 flex-col items-end gap-1.5"><Badge variant={item.publication_status === "published" ? "default" : "secondary"}>{publicationLabels[item.publication_status] ?? "仅自己"}</Badge>{isWikiKnowledgeBase(item) && <Badge className="bg-violet-100 text-violet-700 hover:bg-violet-100 dark:bg-violet-950 dark:text-violet-300">Wiki</Badge>}<WikiConfigurationStatus knowledgeBase={item} /></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>
|
||||
@@ -411,6 +521,7 @@ function KnowledgeGrid({
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-2">
|
||||
<Button size="sm" variant="outline" className="rounded-full" onClick={() => onOpen(item)}><FileText className="mr-2 size-4" />查看详情</Button>
|
||||
<Button size="sm" variant="outline" className="rounded-full" onClick={() => onResearch(item)}><Microscope className="mr-2 size-4" />深度研究</Button>
|
||||
{onTest && <Button size="sm" variant="outline" className="rounded-full" onClick={() => onTest(item)}><Search 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>}
|
||||
@@ -427,17 +538,18 @@ function KnowledgeGrid({
|
||||
function EditKnowledgeDialog({
|
||||
knowledgeBase,
|
||||
pending,
|
||||
error,
|
||||
onClose,
|
||||
onSave,
|
||||
}: {
|
||||
knowledgeBase: LlmWikiKnowledgeBase;
|
||||
pending: boolean;
|
||||
error: unknown;
|
||||
onClose: () => void;
|
||||
onSave: (input: {
|
||||
name: string;
|
||||
description: string;
|
||||
test_questions?: string[];
|
||||
retrieval_settings: LlmWikiKnowledgeBase["retrieval_settings"];
|
||||
wiki_config?: LlmWikiWikiInstructions;
|
||||
}) => Promise<void>;
|
||||
}) {
|
||||
@@ -445,42 +557,49 @@ function EditKnowledgeDialog({
|
||||
const [description, setDescription] = useState(knowledgeBase.description);
|
||||
const [questionsText, setQuestionsText] = useState((knowledgeBase.test_questions ?? []).join("\n"));
|
||||
const [questionsDirty, setQuestionsDirty] = useState(false);
|
||||
const [entityExpansion, setEntityExpansion] = useState(knowledgeBase.retrieval_settings?.entity_expansion_enabled ?? true);
|
||||
const [statisticsEnabled, setStatisticsEnabled] = useState(knowledgeBase.retrieval_settings?.statistics_enabled ?? true);
|
||||
const [maxRelatedTerms, setMaxRelatedTerms] = useState(knowledgeBase.retrieval_settings?.max_related_terms ?? 6);
|
||||
const [contentInstructions, setContentInstructions] = useState(
|
||||
knowledgeBase.wiki_config?.content_instructions ?? "",
|
||||
);
|
||||
const [extractionInstructions, setExtractionInstructions] = useState(
|
||||
knowledgeBase.wiki_config?.extraction_instructions ?? "",
|
||||
);
|
||||
const wikiEnabled =
|
||||
knowledgeBase.type === "wiki" ||
|
||||
knowledgeBase.wiki_index_enabled === true ||
|
||||
knowledgeBase.indexing_strategy?.wiki_enabled === true ||
|
||||
knowledgeBase.capabilities?.wiki_enabled === true;
|
||||
const [directoryTreeText, setDirectoryTreeText] = useState(
|
||||
formatWikiDirectoryPaths(
|
||||
knowledgeBase.wiki_config?.directory_paths ??
|
||||
(knowledgeBase.wiki_config?.parent_directories ?? []).map((name) => [name]),
|
||||
),
|
||||
);
|
||||
const [focusInstructions, setFocusInstructions] = useState(
|
||||
knowledgeBase.wiki_config?.focus_instructions ?? "",
|
||||
);
|
||||
const directoryTreeValidation = useMemo(
|
||||
() => validateWikiDirectoryTree(directoryTreeText),
|
||||
[directoryTreeText],
|
||||
);
|
||||
const instructionLengthInvalid =
|
||||
codePointLength(contentInstructions) > WIKI_INSTRUCTION_MAX_LENGTH ||
|
||||
codePointLength(extractionInstructions) > WIKI_INSTRUCTION_MAX_LENGTH ||
|
||||
codePointLength(focusInstructions) > WIKI_FOCUS_INSTRUCTION_MAX_LENGTH;
|
||||
const wikiEnabled = isWikiKnowledgeBase(knowledgeBase);
|
||||
|
||||
return (
|
||||
<Dialog open onOpenChange={(open) => { if (!open && !pending) onClose(); }}>
|
||||
<DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-2xl">
|
||||
<DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-3xl">
|
||||
<form onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
if (!pending && name.trim()) {
|
||||
if (!pending && name.trim() && directoryTreeValidation.errors.length === 0 && !instructionLengthInvalid) {
|
||||
void onSave({
|
||||
name: name.trim(),
|
||||
description: description.trim(),
|
||||
...(questionsDirty
|
||||
? { test_questions: questionsText.split("\n").map((item) => item.trim()).filter(Boolean).slice(0, 12) }
|
||||
: {}),
|
||||
retrieval_settings: {
|
||||
entity_expansion_enabled: entityExpansion,
|
||||
max_related_terms: Math.max(0, Math.min(12, maxRelatedTerms)),
|
||||
statistics_enabled: statisticsEnabled,
|
||||
},
|
||||
wiki_config: wikiEnabled
|
||||
? {
|
||||
content_instructions: contentInstructions.trim(),
|
||||
extraction_instructions: extractionInstructions.trim(),
|
||||
directory_paths: directoryTreeValidation.directoryPaths,
|
||||
focus_instructions: focusInstructions.trim(),
|
||||
}
|
||||
: undefined,
|
||||
});
|
||||
@@ -509,36 +628,34 @@ function EditKnowledgeDialog({
|
||||
: "这是系统自动问题;不编辑时会自动跟随知识库新名称更新。"}
|
||||
</p>
|
||||
</div>
|
||||
<div className="rounded-xl border bg-muted/20 p-4">
|
||||
<div className="text-sm font-medium">扩展与统计检索</div>
|
||||
<label className="mt-3 flex items-center gap-2 text-sm">
|
||||
<input type="checkbox" checked={entityExpansion} onChange={(event) => setEntityExpansion(event.target.checked)} disabled={pending} />
|
||||
沿 Wiki 别名和关联链接扩展一跳检索
|
||||
</label>
|
||||
<label className="mt-2 flex items-center gap-2 text-sm">
|
||||
<input type="checkbox" checked={statisticsEnabled} onChange={(event) => setStatisticsEnabled(event.target.checked)} disabled={pending} />
|
||||
支持日期过滤、数量统计和新闻/来源明细
|
||||
</label>
|
||||
<div className="mt-3 flex items-center gap-3">
|
||||
<label className="text-sm" htmlFor="llmwiki-related-limit">最多扩展词</label>
|
||||
<Input id="llmwiki-related-limit" type="number" min={0} max={12} className="h-8 w-24" value={maxRelatedTerms} onChange={(event) => setMaxRelatedTerms(Number(event.target.value) || 0)} disabled={pending || !entityExpansion} />
|
||||
</div>
|
||||
</div>
|
||||
{wikiEnabled && (
|
||||
<WikiInstructionFields
|
||||
idPrefix="llmwiki-edit"
|
||||
contentInstructions={contentInstructions}
|
||||
extractionInstructions={extractionInstructions}
|
||||
onContentInstructionsChange={setContentInstructions}
|
||||
onExtractionInstructionsChange={setExtractionInstructions}
|
||||
disabled={pending}
|
||||
/>
|
||||
<div className="space-y-3">
|
||||
<WikiConfigurationStatus knowledgeBase={knowledgeBase} detailed />
|
||||
<WikiInstructionFields
|
||||
idPrefix="llmwiki-edit"
|
||||
contentInstructions={contentInstructions}
|
||||
extractionInstructions={extractionInstructions}
|
||||
directoryTreeText={directoryTreeText}
|
||||
focusInstructions={focusInstructions}
|
||||
onContentInstructionsChange={setContentInstructions}
|
||||
onExtractionInstructionsChange={setExtractionInstructions}
|
||||
onDirectoryTreeTextChange={setDirectoryTreeText}
|
||||
onFocusInstructionsChange={setFocusInstructions}
|
||||
disabled={pending}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{Boolean(error) && (
|
||||
<div className="flex gap-2 rounded-lg border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive" role="alert">
|
||||
<AlertCircle className="mt-0.5 size-4 shrink-0" />
|
||||
<span>保存失败:{messageOf(error)}</span>
|
||||
</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 type="submit" disabled={pending || !name.trim() || directoryTreeValidation.errors.length > 0 || instructionLengthInvalid}>
|
||||
{pending && <Loader2 className="mr-2 size-4 animate-spin" />}{pending ? "保存中" : "保存"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
@@ -550,27 +667,23 @@ function EditKnowledgeDialog({
|
||||
function CreateKnowledgeDialog({
|
||||
open,
|
||||
pending,
|
||||
error,
|
||||
onOpenChange,
|
||||
onCreate,
|
||||
}: {
|
||||
open: boolean;
|
||||
pending: boolean;
|
||||
error: unknown;
|
||||
onOpenChange: (value: boolean) => void;
|
||||
onCreate: (input: {
|
||||
name: string;
|
||||
description: string;
|
||||
type: "document" | "faq";
|
||||
wiki_enabled: boolean;
|
||||
embedding_model_id: string;
|
||||
wiki_config?: LlmWikiWikiInstructions;
|
||||
}) => Promise<void>;
|
||||
onCreate: (input: LlmWikiKnowledgeBaseCreateInput) => Promise<void>;
|
||||
}) {
|
||||
const [name, setName] = useState("");
|
||||
const [description, setDescription] = useState("");
|
||||
const [wikiEnabled, setWikiEnabled] = useState(true);
|
||||
const [embeddingModelId, setEmbeddingModelId] = useState("");
|
||||
const [contentInstructions, setContentInstructions] = useState("");
|
||||
const [extractionInstructions, setExtractionInstructions] = useState("");
|
||||
const [directoryTreeText, setDirectoryTreeText] = useState("");
|
||||
const [focusInstructions, setFocusInstructions] = useState("");
|
||||
const embeddingModels = useLlmWikiEmbeddingModels(open);
|
||||
const availableEmbeddingModels = useMemo(
|
||||
() => (embeddingModels.data?.models ?? []).filter((model) => model.available !== false),
|
||||
@@ -581,10 +694,11 @@ function CreateKnowledgeDialog({
|
||||
if (!open) {
|
||||
setName("");
|
||||
setDescription("");
|
||||
setWikiEnabled(true);
|
||||
setEmbeddingModelId("");
|
||||
setContentInstructions("");
|
||||
setExtractionInstructions("");
|
||||
setDirectoryTreeText("");
|
||||
setFocusInstructions("");
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
@@ -606,28 +720,34 @@ function CreateKnowledgeDialog({
|
||||
return suffix ? `${model.name}(${suffix})` : model.name;
|
||||
};
|
||||
const modelSelectionUnavailable = embeddingModels.isLoading || embeddingModels.isError || !embeddingModelId;
|
||||
const directoryTreeValidation = useMemo(
|
||||
() => validateWikiDirectoryTree(directoryTreeText),
|
||||
[directoryTreeText],
|
||||
);
|
||||
const instructionLengthInvalid =
|
||||
codePointLength(contentInstructions) > WIKI_INSTRUCTION_MAX_LENGTH ||
|
||||
codePointLength(extractionInstructions) > WIKI_INSTRUCTION_MAX_LENGTH ||
|
||||
codePointLength(focusInstructions) > WIKI_FOCUS_INSTRUCTION_MAX_LENGTH;
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-2xl">
|
||||
<DialogHeader><DialogTitle>新建个人知识库</DialogTitle><DialogDescription>选择知识库模式、原文向量模型,并按需指定 Wiki 自动生成和提取要求。</DialogDescription></DialogHeader>
|
||||
<DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-3xl">
|
||||
<DialogHeader><DialogTitle>新建个人知识库</DialogTitle><DialogDescription>上传的原文会同时用于分片检索和 Wiki 生成;请选择原文向量模型,并可按需提供参考目录和提取重点。</DialogDescription></DialogHeader>
|
||||
<div className="space-y-4 py-2">
|
||||
<div className="space-y-2"><label className="text-sm font-medium" htmlFor="llmwiki-name">名称</label><Input id="llmwiki-name" value={name} onChange={(event) => setName(event.target.value)} maxLength={255} /></div>
|
||||
<div className="space-y-2"><label className="text-sm font-medium" htmlFor="llmwiki-description">描述</label><Textarea id="llmwiki-description" value={description} onChange={(event) => setDescription(event.target.value)} rows={4} maxLength={2048} /></div>
|
||||
<div className="space-y-2"><div className="text-sm font-medium">知识库模式</div><div className="grid gap-3 sm:grid-cols-2">
|
||||
<button type="button" className={`rounded-xl border p-4 text-left transition-colors ${wikiEnabled ? "border-primary bg-primary/5 ring-1 ring-primary" : "hover:bg-muted/40"}`} onClick={() => setWikiEnabled(true)}><div className="flex items-center gap-2 text-sm font-semibold"><BookOpen className="size-4 text-violet-500" />Wiki 知识库</div><p className="mt-2 text-xs leading-5 text-muted-foreground">自动综合资料,生成 Wiki 页面和页面关系图谱。</p></button>
|
||||
<button type="button" className={`rounded-xl border p-4 text-left transition-colors ${!wikiEnabled ? "border-primary bg-primary/5 ring-1 ring-primary" : "hover:bg-muted/40"}`} onClick={() => setWikiEnabled(false)}><div className="flex items-center gap-2 text-sm font-semibold"><FileText className="size-4 text-blue-500" />标准知识库</div><p className="mt-2 text-xs leading-5 text-muted-foreground">仅进行文档解析、切块与向量/关键词索引。</p></button>
|
||||
</div></div>
|
||||
{wikiEnabled && (
|
||||
<WikiInstructionFields
|
||||
idPrefix="llmwiki-create"
|
||||
contentInstructions={contentInstructions}
|
||||
extractionInstructions={extractionInstructions}
|
||||
onContentInstructionsChange={setContentInstructions}
|
||||
onExtractionInstructionsChange={setExtractionInstructions}
|
||||
disabled={pending}
|
||||
/>
|
||||
)}
|
||||
<WikiInstructionFields
|
||||
idPrefix="llmwiki-create"
|
||||
contentInstructions={contentInstructions}
|
||||
extractionInstructions={extractionInstructions}
|
||||
directoryTreeText={directoryTreeText}
|
||||
focusInstructions={focusInstructions}
|
||||
onContentInstructionsChange={setContentInstructions}
|
||||
onExtractionInstructionsChange={setExtractionInstructions}
|
||||
onDirectoryTreeTextChange={setDirectoryTreeText}
|
||||
onFocusInstructionsChange={setFocusInstructions}
|
||||
disabled={pending}
|
||||
/>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium" htmlFor="llmwiki-embedding-model">原文向量模型</label>
|
||||
{embeddingModels.isLoading ? (
|
||||
@@ -653,80 +773,264 @@ function CreateKnowledgeDialog({
|
||||
)}
|
||||
<p className="text-xs leading-5 text-muted-foreground">该模型由知识服务(WeKnora)对上传原文和分块进行向量化,并在创建时绑定到新库。它与 DeerFlow 的“Wiki 镜像编码器”是两套独立配置;选择 OpenAI 兼容模型时,无需再配置本地 BGE-M3。需要跨知识库检索时,请为相关知识库保持相同或兼容的向量模型。</p>
|
||||
</div>
|
||||
{Boolean(error) && (
|
||||
<div className="flex gap-2 rounded-lg border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive" role="alert">
|
||||
<AlertCircle className="mt-0.5 size-4 shrink-0" />
|
||||
<span>创建失败:{messageOf(error)}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<DialogFooter><Button variant="outline" onClick={() => onOpenChange(false)}>取消</Button><Button disabled={pending || !name.trim() || modelSelectionUnavailable} onClick={() => void onCreate({ name: name.trim(), description: description.trim(), type: "document", wiki_enabled: wikiEnabled, embedding_model_id: embeddingModelId, wiki_config: wikiEnabled ? { content_instructions: contentInstructions.trim(), extraction_instructions: extractionInstructions.trim() } : undefined })}>{pending && <Loader2 className="mr-2 size-4 animate-spin" />}创建</Button></DialogFooter>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={pending}>取消</Button>
|
||||
<Button
|
||||
disabled={pending || !name.trim() || modelSelectionUnavailable || directoryTreeValidation.errors.length > 0 || instructionLengthInvalid}
|
||||
onClick={() => void onCreate(buildWikiKnowledgeBaseCreateInput({
|
||||
name,
|
||||
description,
|
||||
embeddingModelId,
|
||||
wikiConfig: {
|
||||
content_instructions: contentInstructions.trim(),
|
||||
extraction_instructions: extractionInstructions.trim(),
|
||||
directory_paths: directoryTreeValidation.directoryPaths,
|
||||
focus_instructions: focusInstructions.trim(),
|
||||
},
|
||||
}))}
|
||||
>
|
||||
{pending && <Loader2 className="mr-2 size-4 animate-spin" />}{pending ? "创建中" : "创建"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function WikiDirectoryTreePreview({ nodes, depth = 0 }: { nodes: WikiDirectoryTreeNode[]; depth?: number }) {
|
||||
return (
|
||||
<ul className={depth > 0 ? "ml-3 border-l border-border/70 pl-3" : "space-y-1"}>
|
||||
{nodes.map((node) => (
|
||||
<li key={JSON.stringify(node.path)} className="py-0.5">
|
||||
<div className="flex items-center gap-2 text-xs leading-5">
|
||||
<FolderTree className="size-3.5 shrink-0 text-violet-500" />
|
||||
<span className="break-all">{node.name}</span>
|
||||
<span className="shrink-0 text-[10px] text-muted-foreground">{node.path.length} 级</span>
|
||||
</div>
|
||||
{node.children.length > 0 && <WikiDirectoryTreePreview nodes={node.children} depth={depth + 1} />}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
function WikiInstructionFields({
|
||||
idPrefix,
|
||||
contentInstructions,
|
||||
extractionInstructions,
|
||||
directoryTreeText,
|
||||
focusInstructions,
|
||||
onContentInstructionsChange,
|
||||
onExtractionInstructionsChange,
|
||||
onDirectoryTreeTextChange,
|
||||
onFocusInstructionsChange,
|
||||
disabled,
|
||||
}: {
|
||||
idPrefix: string;
|
||||
contentInstructions: string;
|
||||
extractionInstructions: string;
|
||||
directoryTreeText: string;
|
||||
focusInstructions: string;
|
||||
onContentInstructionsChange: (value: string) => void;
|
||||
onExtractionInstructionsChange: (value: string) => void;
|
||||
onDirectoryTreeTextChange: (value: string) => void;
|
||||
onFocusInstructionsChange: (value: string) => void;
|
||||
disabled: boolean;
|
||||
}) {
|
||||
const [advancedOpen, setAdvancedOpen] = useState(
|
||||
Boolean(contentInstructions.trim() || extractionInstructions.trim()),
|
||||
);
|
||||
const directoryTreeValidation = useMemo(
|
||||
() => validateWikiDirectoryTree(directoryTreeText),
|
||||
[directoryTreeText],
|
||||
);
|
||||
const focusLength = codePointLength(focusInstructions);
|
||||
const contentLength = codePointLength(contentInstructions);
|
||||
const extractionLength = codePointLength(extractionInstructions);
|
||||
|
||||
const importDirectoryTree = async (file?: File) => {
|
||||
if (!file) return;
|
||||
if (!/\.(?:txt|md)$/i.test(file.name)) {
|
||||
toast.error("仅支持上传 .txt 或 .md 目录文件");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
onDirectoryTreeTextChange(await file.text());
|
||||
} catch {
|
||||
toast.error("读取目录文件失败,请重新选择");
|
||||
}
|
||||
};
|
||||
|
||||
const downloadDirectoryTemplate = () => {
|
||||
const objectUrl = URL.createObjectURL(
|
||||
new Blob([WIKI_DIRECTORY_TEMPLATE_CONTENT], { type: "text/markdown;charset=utf-8" }),
|
||||
);
|
||||
const anchor = document.createElement("a");
|
||||
anchor.href = objectUrl;
|
||||
anchor.download = WIKI_DIRECTORY_TEMPLATE_FILENAME;
|
||||
document.body.appendChild(anchor);
|
||||
anchor.click();
|
||||
anchor.remove();
|
||||
window.setTimeout(() => URL.revokeObjectURL(objectUrl), 10_000);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4 rounded-xl border bg-violet-500/5 p-4">
|
||||
<div>
|
||||
<div className="text-sm font-semibold">Wiki 生成与抽取要求</div>
|
||||
<p className="mt-1 text-xs leading-5 text-muted-foreground">
|
||||
两项均可选。要求保存在 WeKnora 知识库配置中,并用于后续文档的 Wiki 自动抽取与页面生成。
|
||||
参考目录和重点要求均可留空。全部留空时沿用原来的自动 Wiki 生成方式。
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<label className="text-sm font-medium" htmlFor={`${idPrefix}-content-instructions`}>
|
||||
Wiki 内容生成要求
|
||||
</label>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{contentInstructions.length}/{WIKI_INSTRUCTION_MAX_LENGTH}
|
||||
|
||||
<section className="space-y-3 rounded-xl border bg-background/85 p-4" aria-labelledby={`${idPrefix}-directory-title`}>
|
||||
<div className="flex flex-wrap items-start justify-between gap-2">
|
||||
<div>
|
||||
<h3 id={`${idPrefix}-directory-title`} className="text-sm font-semibold">提供参考目录(选填)</h3>
|
||||
<p className="mt-1 text-xs leading-5 text-muted-foreground">先下载示例文件,按需修改参考目录的名称和层级,再选择文件导入。支持 Markdown 标题或每级 2 个空格的缩进文本,最多 {WIKI_DIRECTORY_MAX_DEPTH} 级。</p>
|
||||
</div>
|
||||
<Badge variant="outline" className={directoryTreeValidation.errors.length ? "border-destructive/30 text-destructive" : ""}>
|
||||
{directoryTreeValidation.nodeCount}/{WIKI_DIRECTORY_MAX_NODES} 个节点
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="grid gap-3 lg:grid-cols-[minmax(0,1.25fr)_minmax(220px,0.75fr)]">
|
||||
<div className="space-y-2">
|
||||
<label className="sr-only" htmlFor={`${idPrefix}-directory-tree`}>参考目录</label>
|
||||
<Textarea
|
||||
id={`${idPrefix}-directory-tree`}
|
||||
value={directoryTreeText}
|
||||
onChange={(event) => onDirectoryTreeTextChange(event.target.value)}
|
||||
rows={8}
|
||||
disabled={disabled}
|
||||
aria-invalid={directoryTreeValidation.errors.length > 0}
|
||||
placeholder={"# 政策法规\n## 国内政策\n### 2026 年\n## 国际规则\n# 操作指南\n## 申报流程\n\n也可用每级 2 个空格缩进。"}
|
||||
/>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button type="button" variant="outline" size="sm" disabled={disabled} onClick={downloadDirectoryTemplate}>
|
||||
<Download className="mr-1.5 size-4" />
|
||||
下载参考目录示例
|
||||
</Button>
|
||||
<Input
|
||||
type="file"
|
||||
accept=".txt,.md,text/plain,text/markdown"
|
||||
disabled={disabled}
|
||||
className="h-9 max-w-sm cursor-pointer text-xs"
|
||||
aria-label="导入参考目录文件"
|
||||
onChange={(event) => {
|
||||
const file = event.currentTarget.files?.[0];
|
||||
event.currentTarget.value = "";
|
||||
void importDirectoryTree(file);
|
||||
}}
|
||||
/>
|
||||
{directoryTreeText && (
|
||||
<Button type="button" variant="ghost" size="sm" disabled={disabled} onClick={() => onDirectoryTreeTextChange("")}>
|
||||
清空参考目录
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs leading-5 text-muted-foreground">
|
||||
示例文件名为“{WIKI_DIRECTORY_TEMPLATE_FILENAME}”。下载后可直接编辑并上传;选择文件只会填入当前表单,点击保存或创建后才会生效。
|
||||
</p>
|
||||
<p className="text-xs leading-5 text-muted-foreground">
|
||||
规范长度 {directoryTreeValidation.normalizedLength}/{WIKI_DIRECTORY_MAX_NORMALIZED_LENGTH}。普通逐行文本会按一级目录处理;不能混用 Markdown 和缩进格式。
|
||||
</p>
|
||||
{directoryTreeValidation.errors.length > 0 && (
|
||||
<div className="space-y-1 rounded-lg border border-destructive/25 bg-destructive/5 p-2.5 text-xs text-destructive" role="alert">
|
||||
{directoryTreeValidation.errors.slice(0, 5).map((validationError) => <p key={validationError}>{validationError}</p>)}
|
||||
{directoryTreeValidation.errors.length > 5 && <p>另有 {directoryTreeValidation.errors.length - 5} 项格式问题</p>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="min-h-40 rounded-lg border bg-muted/20 p-3">
|
||||
<div className="mb-2 flex items-center gap-2 text-xs font-medium">
|
||||
<FolderTree className="size-4 text-violet-500" />参考目录预览
|
||||
</div>
|
||||
{directoryTreeValidation.tree.length > 0 ? (
|
||||
<div className="max-h-64 overflow-auto pr-1"><WikiDirectoryTreePreview nodes={directoryTreeValidation.tree} /></div>
|
||||
) : (
|
||||
<div className="flex min-h-28 items-center justify-center text-center text-xs leading-5 text-muted-foreground">输入参考目录后在这里实时预览层级。</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs leading-5 text-muted-foreground">
|
||||
参考目录只用于帮助系统理解期望的信息组织方式。系统会结合实际资料新增、合并或调整目录,不会强制逐项套用,也不会创建没有资料支撑的目录。清空后不再向后续生成提供这份参考,不会撤销已有页面或目录。
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section className="space-y-2 rounded-xl border bg-background/85 p-4" aria-labelledby={`${idPrefix}-focus-title`}>
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<h3 id={`${idPrefix}-focus-title`} className="text-sm font-semibold">按要求突出重点(选填)</h3>
|
||||
<span className={focusLength > WIKI_FOCUS_INSTRUCTION_MAX_LENGTH ? "text-xs text-destructive" : "text-xs text-muted-foreground"}>
|
||||
{focusLength}/{WIKI_FOCUS_INSTRUCTION_MAX_LENGTH}
|
||||
</span>
|
||||
</div>
|
||||
<Textarea
|
||||
id={`${idPrefix}-content-instructions`}
|
||||
value={contentInstructions}
|
||||
onChange={(event) => onContentInstructionsChange(event.target.value)}
|
||||
rows={3}
|
||||
maxLength={WIKI_INSTRUCTION_MAX_LENGTH}
|
||||
id={`${idPrefix}-focus-instructions`}
|
||||
value={focusInstructions}
|
||||
onChange={(event) => onFocusInstructionsChange(event.target.value)}
|
||||
rows={4}
|
||||
disabled={disabled}
|
||||
placeholder="例如:使用正式中文,先给结论再展开依据;保留关键数字、时间和来源,不写空泛表述。"
|
||||
aria-invalid={focusLength > WIKI_FOCUS_INSTRUCTION_MAX_LENGTH}
|
||||
placeholder="例如:重点提取政策适用对象、申请条件、时间期限、审批部门和例外情形;涉及不同年份时优先说明最新规则,并保留历史差异。"
|
||||
/>
|
||||
<p className="text-xs leading-5 text-muted-foreground">
|
||||
控制自动生成 Wiki 页面时的语言、结构、详略和表达侧重。
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<label className="text-sm font-medium" htmlFor={`${idPrefix}-extraction-instructions`}>
|
||||
Wiki 提取重点
|
||||
</label>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{extractionInstructions.length}/{WIKI_INSTRUCTION_MAX_LENGTH}
|
||||
</span>
|
||||
{focusLength > WIKI_FOCUS_INSTRUCTION_MAX_LENGTH && <p className="text-xs text-destructive" role="alert">重点要求不能超过 {WIKI_FOCUS_INSTRUCTION_MAX_LENGTH} 个字符。</p>}
|
||||
<p className="text-xs leading-5 text-muted-foreground">重点要求决定优先组织和提取哪些内容,不会降低事实与来源要求,也不会覆盖下方高级指令。</p>
|
||||
</section>
|
||||
|
||||
<details
|
||||
className="rounded-xl border bg-background/70"
|
||||
open={advancedOpen}
|
||||
onToggle={(event) => setAdvancedOpen(event.currentTarget.open)}
|
||||
>
|
||||
<summary className="cursor-pointer px-4 py-3 text-sm font-medium">高级设置:内容生成与信息抽取指令</summary>
|
||||
<div className="space-y-4 border-t p-4">
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<label className="text-sm font-medium" htmlFor={`${idPrefix}-content-instructions`}>Wiki 内容生成要求</label>
|
||||
<span className={contentLength > WIKI_INSTRUCTION_MAX_LENGTH ? "text-xs text-destructive" : "text-xs text-muted-foreground"}>{contentLength}/{WIKI_INSTRUCTION_MAX_LENGTH}</span>
|
||||
</div>
|
||||
<Textarea
|
||||
id={`${idPrefix}-content-instructions`}
|
||||
value={contentInstructions}
|
||||
onChange={(event) => onContentInstructionsChange(event.target.value)}
|
||||
rows={3}
|
||||
disabled={disabled}
|
||||
aria-invalid={contentLength > WIKI_INSTRUCTION_MAX_LENGTH}
|
||||
placeholder="例如:使用正式中文,先给结论再展开依据;保留关键数字、时间和来源,不写空泛表述。"
|
||||
/>
|
||||
{contentLength > WIKI_INSTRUCTION_MAX_LENGTH && <p className="text-xs text-destructive" role="alert">内容生成要求不能超过 {WIKI_INSTRUCTION_MAX_LENGTH} 个字符。</p>}
|
||||
<p className="text-xs leading-5 text-muted-foreground">控制自动生成 Wiki 页面时的语言、结构、详略和表达侧重。</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<label className="text-sm font-medium" htmlFor={`${idPrefix}-extraction-instructions`}>Wiki 信息抽取要求</label>
|
||||
<span className={extractionLength > WIKI_INSTRUCTION_MAX_LENGTH ? "text-xs text-destructive" : "text-xs text-muted-foreground"}>{extractionLength}/{WIKI_INSTRUCTION_MAX_LENGTH}</span>
|
||||
</div>
|
||||
<Textarea
|
||||
id={`${idPrefix}-extraction-instructions`}
|
||||
value={extractionInstructions}
|
||||
onChange={(event) => onExtractionInstructionsChange(event.target.value)}
|
||||
rows={3}
|
||||
disabled={disabled}
|
||||
aria-invalid={extractionLength > WIKI_INSTRUCTION_MAX_LENGTH}
|
||||
placeholder="例如:重点提取人物、组织、关键事件、时间线及相互关系;忽略仅被顺带提及的通用技术名词。"
|
||||
/>
|
||||
{extractionLength > WIKI_INSTRUCTION_MAX_LENGTH && <p className="text-xs text-destructive" role="alert">信息抽取要求不能超过 {WIKI_INSTRUCTION_MAX_LENGTH} 个字符。</p>}
|
||||
<p className="text-xs leading-5 text-muted-foreground">指定候选主题、实体和概念的领域要求;不会覆盖知识服务的引用、去重和格式约束。</p>
|
||||
</div>
|
||||
</div>
|
||||
<Textarea
|
||||
id={`${idPrefix}-extraction-instructions`}
|
||||
value={extractionInstructions}
|
||||
onChange={(event) => onExtractionInstructionsChange(event.target.value)}
|
||||
rows={3}
|
||||
maxLength={WIKI_INSTRUCTION_MAX_LENGTH}
|
||||
disabled={disabled}
|
||||
placeholder="例如:重点提取人物、组织、关键事件、时间线及相互关系;忽略仅被顺带提及的通用技术名词。"
|
||||
/>
|
||||
<p className="text-xs leading-5 text-muted-foreground">
|
||||
指定候选主题、实体和概念的领域重点;不会覆盖 WeKnora 的引用、去重和格式约束。
|
||||
</p>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<p className="text-xs leading-5 text-muted-foreground">
|
||||
保存后的配置用于后续上传和重新解析;已有 Wiki 内容不会自动重写,需要在文档详情中显式重新解析。
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
+25
-3
@@ -17,6 +17,7 @@ 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 { useOrdinaryKnowledgeRetrievalSettings } from "@/core/system-settings/hooks";
|
||||
import {
|
||||
createLlmWikiExportPackage,
|
||||
listLlmWikiExportPackages,
|
||||
@@ -49,13 +50,24 @@ export default function WeKnoraPackageTransfersPage() {
|
||||
const navigate = useNavigate();
|
||||
const queryClient = useQueryClient();
|
||||
const isAdmin = getStoredAuth()?.system_role === "admin";
|
||||
const managementSettings =
|
||||
useOrdinaryKnowledgeRetrievalSettings(isAdmin);
|
||||
const advancedManagementEnabled =
|
||||
managementSettings.data?.advanced_management_enabled === true;
|
||||
const runtime = useLlmWikiRuntime();
|
||||
const knowledge = useLlmWikiKnowledgeBase(noteId || null, !!noteId);
|
||||
const knowledge = useLlmWikiKnowledgeBase(
|
||||
noteId || null,
|
||||
!!noteId && isAdmin && advancedManagementEnabled,
|
||||
);
|
||||
const jobsKey = ["llmwiki-export-packages", noteId];
|
||||
const jobs = useQuery({
|
||||
queryKey: jobsKey,
|
||||
queryFn: () => listLlmWikiExportPackages(noteId),
|
||||
enabled: isAdmin && !!noteId && runtime.data?.provider === "weknora",
|
||||
enabled:
|
||||
isAdmin &&
|
||||
advancedManagementEnabled &&
|
||||
!!noteId &&
|
||||
runtime.data?.provider === "weknora",
|
||||
refetchInterval: (query) =>
|
||||
query.state.data?.some((job) => RUNNING.has(job.status)) ? 3000 : false,
|
||||
});
|
||||
@@ -70,6 +82,16 @@ export default function WeKnoraPackageTransfersPage() {
|
||||
onError: (error) => toast.error(error.message),
|
||||
});
|
||||
if (!isAdmin) return <Navigate to="/page/workspace/knowledge" replace />;
|
||||
if (managementSettings.isLoading) {
|
||||
return (
|
||||
<div className="flex size-full items-center justify-center text-sm text-muted-foreground">
|
||||
<Loader2 className="mr-2 size-5 animate-spin" />加载知识库设置
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (!advancedManagementEnabled) {
|
||||
return <Navigate to="/page/workspace/knowledge" replace />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex size-full min-h-0 flex-col bg-muted/20">
|
||||
@@ -128,7 +150,7 @@ export default function WeKnoraPackageTransfersPage() {
|
||||
Wiki 与向量数据包导出记录
|
||||
</CardTitle>
|
||||
<p className="mt-1 text-sm text-muted-foreground">
|
||||
导出生成后的 Wiki、向量和关联元数据,供普通知识库或助手知识库导入;
|
||||
导出生成后的 Wiki、向量和关联元数据,供兼容的知识库导入;
|
||||
不包含原始文档文件。大文件在后台整理完成后提供下载。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
+24
-2
@@ -1,6 +1,6 @@
|
||||
import { ArrowLeft, BookOpenText, Braces, ExternalLink, Loader2, Search } from "lucide-react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
import { Navigate, useNavigate, useParams } from "react-router-dom";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
@@ -8,6 +8,8 @@ import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { getStoredAuth } from "@/core/auth";
|
||||
import { useOrdinaryKnowledgeRetrievalSettings } from "@/core/system-settings/hooks";
|
||||
import {
|
||||
debugLlmWikiKnowledgeBaseRetrieval,
|
||||
type LlmWikiKnowledgeBaseRetrievalDebugResponse,
|
||||
@@ -23,7 +25,15 @@ function errorMessage(error: unknown) {
|
||||
export default function WeKnoraRetrievalDebugPage() {
|
||||
const { noteId = "" } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const base = useLlmWikiKnowledgeBase(noteId || null, !!noteId);
|
||||
const isAdmin = getStoredAuth()?.system_role === "admin";
|
||||
const managementSettings =
|
||||
useOrdinaryKnowledgeRetrievalSettings(isAdmin);
|
||||
const advancedManagementEnabled =
|
||||
managementSettings.data?.advanced_management_enabled === true;
|
||||
const base = useLlmWikiKnowledgeBase(
|
||||
noteId || null,
|
||||
!!noteId && isAdmin && advancedManagementEnabled,
|
||||
);
|
||||
const [query, setQuery] = useState("帮我统计本月关于赖清德的新闻有多少条,并列出具体新闻");
|
||||
const [dateFrom, setDateFrom] = useState("");
|
||||
const [dateTo, setDateTo] = useState("");
|
||||
@@ -38,6 +48,18 @@ export default function WeKnoraRetrievalDebugPage() {
|
||||
return index;
|
||||
}, [response]);
|
||||
|
||||
if (!isAdmin) return <Navigate to="/page/workspace/knowledge" replace />;
|
||||
if (managementSettings.isLoading) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center text-sm text-muted-foreground">
|
||||
<Loader2 className="mr-2 size-5 animate-spin" />加载知识库设置
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (!advancedManagementEnabled) {
|
||||
return <Navigate to="/page/workspace/knowledge" replace />;
|
||||
}
|
||||
|
||||
const run = async () => {
|
||||
if (!query.trim() || !noteId) return;
|
||||
setLoading(true);
|
||||
|
||||
+34
-19
@@ -30,6 +30,10 @@ import {
|
||||
parseWeKnoraPreviewUrl,
|
||||
type WeKnoraSourceTarget,
|
||||
} from "@/core/llmwiki/source-links";
|
||||
import {
|
||||
mergeSourceContextTarget,
|
||||
sourceTargetNeedsContext,
|
||||
} from "@/core/llmwiki/source-detail-target";
|
||||
import {
|
||||
cleanRetrievedChunkText,
|
||||
resolveRetrievedChunkExcerpt,
|
||||
@@ -143,12 +147,18 @@ async function getAvailableWikiPage(
|
||||
}
|
||||
|
||||
async function resolveTargetDetail(target: WeKnoraSourceTarget): Promise<DetailTarget> {
|
||||
if (target.wikiSlug || !target.chunkId) {
|
||||
return target;
|
||||
if (!sourceTargetNeedsContext(target)) {
|
||||
return target.tab === "documents"
|
||||
? { ...target, wikiSlug: undefined }
|
||||
: target;
|
||||
}
|
||||
const chunkId = target.chunkId;
|
||||
if (!chunkId) {
|
||||
throw new Error("当前引用缺少检索片段标识,无法定位详情");
|
||||
}
|
||||
const params = new URLSearchParams({
|
||||
knowledge_base_id: target.knowledgeBaseId,
|
||||
chunk_id: target.chunkId,
|
||||
chunk_id: chunkId,
|
||||
});
|
||||
const response = await apiFetch(
|
||||
`${getBackendBaseURL()}/api/llmwiki/sources/context?${params}`,
|
||||
@@ -158,18 +168,17 @@ async function resolveTargetDetail(target: WeKnoraSourceTarget): Promise<DetailT
|
||||
if (target.documentId) return target;
|
||||
throw new Error("无法定位当前引用详情");
|
||||
}
|
||||
const documentId = payload.data?.document_id?.trim();
|
||||
const wikiSlug = payload.data?.wiki_page?.slug?.trim();
|
||||
if (!documentId && !wikiSlug) {
|
||||
if (target.documentId) return target;
|
||||
throw new Error("当前引用缺少 Wiki 页面或文档标识,无法打开详情");
|
||||
}
|
||||
return {
|
||||
...target,
|
||||
documentId: documentId || target.documentId,
|
||||
wikiSlug: wikiSlug || target.wikiSlug,
|
||||
const resolved = mergeSourceContextTarget(target, {
|
||||
documentId: payload.data?.document_id?.trim(),
|
||||
wikiSlug: payload.data?.wiki_page?.slug?.trim(),
|
||||
retrievedExcerpt: resolveRetrievedChunkExcerpt(payload.data),
|
||||
};
|
||||
});
|
||||
if (resolved) return resolved;
|
||||
throw new Error(
|
||||
target.tab === "documents"
|
||||
? "当前引用缺少原始文档标识,无法打开详情"
|
||||
: "当前引用缺少 Wiki 页面或文档标识,无法打开详情",
|
||||
);
|
||||
}
|
||||
|
||||
function formatDate(value?: string | null) {
|
||||
@@ -765,6 +774,10 @@ export function WeKnoraSourceDrawer({
|
||||
const wikiWorkspacePath = target && resolvedWikiSlug
|
||||
? buildWeKnoraWikiPagePath(target.knowledgeBaseId, resolvedWikiSlug)
|
||||
: "";
|
||||
const isWikiSource =
|
||||
Boolean(wikiPage) ||
|
||||
(target?.tab !== "documents" &&
|
||||
Boolean(target?.wikiSlug || target?.tab === "wiki"));
|
||||
|
||||
const openWikiPageInDrawer = async (
|
||||
linkedTarget: WeKnoraSourceTarget,
|
||||
@@ -869,7 +882,9 @@ export function WeKnoraSourceDrawer({
|
||||
)}
|
||||
>
|
||||
<SheetTitle className="sr-only">{resolvedTitle}</SheetTitle>
|
||||
<SheetDescription className="sr-only">知识库 Wiki 页面详情</SheetDescription>
|
||||
<SheetDescription className="sr-only">
|
||||
{isWikiSource ? "知识库 Wiki 页面详情" : "知识库原始文档详情"}
|
||||
</SheetDescription>
|
||||
<div className="relative flex h-full min-h-0 flex-col bg-background">
|
||||
<div className="shrink-0 border-b px-5 py-4 pr-12">
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
@@ -989,7 +1004,7 @@ export function WeKnoraSourceDrawer({
|
||||
{loading && (
|
||||
<div className="flex min-h-0 flex-1 items-center justify-center text-sm text-muted-foreground">
|
||||
<Loader2 className="mr-2 size-5 animate-spin" />
|
||||
正在加载完整 Wiki 文档
|
||||
{isWikiSource ? "正在加载完整 Wiki 文档" : "正在加载原始文档"}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1055,9 +1070,9 @@ export function WeKnoraSourceDrawer({
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-xs text-amber-800/75 dark:text-amber-300/75">
|
||||
下方为
|
||||
{collapseRetrievedExcerptByDefault ? " Wiki" : "文档"}
|
||||
完整内容
|
||||
{isWikiSource
|
||||
? "下方为 Wiki 完整内容"
|
||||
: "下方为原始文档完整内容"}
|
||||
</span>
|
||||
{collapseRetrievedExcerptByDefault && (
|
||||
<button
|
||||
|
||||
+134
-91
@@ -1,5 +1,5 @@
|
||||
import { ArrowLeft, ChevronDown, ChevronRight, Download, FilePlus2, FileText, Folder, Loader2, RefreshCw, Save, Search, Trash2 } from "lucide-react";
|
||||
import { type Dispatch, type SetStateAction, useEffect, useMemo, useState } from "react";
|
||||
import { type Dispatch, type SetStateAction, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Navigate, useNavigate, useParams } from "react-router-dom";
|
||||
import { toast } from "sonner";
|
||||
|
||||
@@ -9,6 +9,8 @@ import { Input } from "@/components/ui/input";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { MarkdownCodeEditor } from "@/components/wiki/MarkdownCodeEditor";
|
||||
import { selectDefaultWikiPage } from "@/core/llmwiki/wiki-tree";
|
||||
import { useOrdinaryKnowledgeRetrievalSettings } from "@/core/system-settings/hooks";
|
||||
import {
|
||||
type LlmWikiWikiPage,
|
||||
useLlmWikiActions,
|
||||
@@ -291,17 +293,33 @@ export function WeKnoraWikiManagementPage() {
|
||||
const { noteId = "" } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const runtime = useLlmWikiRuntime();
|
||||
const knowledgeManagementSettings =
|
||||
useOrdinaryKnowledgeRetrievalSettings();
|
||||
const advancedManagementEnabled =
|
||||
knowledgeManagementSettings.data?.advanced_management_enabled === true;
|
||||
const details = useLlmWikiKnowledgeBase(noteId || null, !!noteId);
|
||||
const actions = useLlmWikiActions();
|
||||
const initialSelection = useRef("");
|
||||
const [query, setQuery] = useState("");
|
||||
const [selectedSlug, setSelectedSlug] = useState("");
|
||||
const [creating, setCreating] = useState(false);
|
||||
const [metadataOpen, setMetadataOpen] = useState(false);
|
||||
const [draft, setDraft] = useState<Draft>(() => emptyDraft());
|
||||
const [expandedDirectories, setExpandedDirectories] = useState<Set<string>>(() => new Set());
|
||||
|
||||
const canWrite = !!details.data?.can_write && !details.data?.is_conversation_deposit;
|
||||
const pages = useLlmWikiWikiPages(noteId || null, 1, 500, "", !!noteId);
|
||||
const indexStatus = useLlmWikiWikiIndexStatus(noteId || null, !!noteId);
|
||||
const pages = useLlmWikiWikiPages(
|
||||
noteId || null,
|
||||
1,
|
||||
500,
|
||||
"",
|
||||
!!noteId,
|
||||
{ pollInterval: false },
|
||||
);
|
||||
const indexStatus = useLlmWikiWikiIndexStatus(
|
||||
noteId || null,
|
||||
!!noteId && advancedManagementEnabled,
|
||||
);
|
||||
const detail = useLlmWikiWikiPage(
|
||||
noteId || null,
|
||||
selectedSlug || null,
|
||||
@@ -327,6 +345,19 @@ export function WeKnoraWikiManagementPage() {
|
||||
|
||||
const title = details.data?.name || "Wiki 文档管理";
|
||||
const pagesList = useMemo(() => pages.data?.pages ?? [], [pages.data?.pages]);
|
||||
useEffect(() => {
|
||||
if (initialSelection.current === noteId) return;
|
||||
if (creating || selectedSlug) {
|
||||
initialSelection.current = noteId;
|
||||
return;
|
||||
}
|
||||
const initialPage = selectDefaultWikiPage(pagesList);
|
||||
if (initialPage) {
|
||||
initialSelection.current = noteId;
|
||||
setSelectedSlug(initialPage.slug);
|
||||
}
|
||||
}, [creating, selectedSlug, pagesList, noteId]);
|
||||
|
||||
const filteredPages = useMemo(() => filterWikiPagesWithAncestors(pagesList, query), [pagesList, query]);
|
||||
const wikiTree = useMemo(() => buildWikiTree(filteredPages), [filteredPages]);
|
||||
const moveOptions = useMemo(
|
||||
@@ -374,12 +405,14 @@ export function WeKnoraWikiManagementPage() {
|
||||
}
|
||||
|
||||
const startCreate = () => {
|
||||
setMetadataOpen(true);
|
||||
setCreating(true);
|
||||
setSelectedSlug("");
|
||||
setDraft(emptyDraft());
|
||||
};
|
||||
|
||||
const selectPage = (slug: string) => {
|
||||
setMetadataOpen(false);
|
||||
setCreating(false);
|
||||
setSelectedSlug(slug);
|
||||
};
|
||||
@@ -394,6 +427,7 @@ export function WeKnoraWikiManagementPage() {
|
||||
};
|
||||
|
||||
const renderVectorBadge = (page: WikiPageListItem) => {
|
||||
if (!advancedManagementEnabled) return null;
|
||||
const item = pageIndexBySlug.get(page.slug);
|
||||
if (item?.last_error || item?.index_status === "failed" || item?.index_status === "stale") {
|
||||
return <Badge variant="destructive" className="ml-auto shrink-0 text-[10px]" title={item?.last_error || "向量化失败"}>失败</Badge>;
|
||||
@@ -591,7 +625,9 @@ export function WeKnoraWikiManagementPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const vectorStatusText = indexStatus.isLoading
|
||||
const vectorStatusText = !advancedManagementEnabled
|
||||
? "Wiki 文档新增、编辑与删除"
|
||||
: indexStatus.isLoading
|
||||
? "正在读取 Wiki 镜像向量状态"
|
||||
: indexStatus.isError
|
||||
? `Wiki 镜像向量状态读取失败:${indexStatus.error instanceof Error ? indexStatus.error.message : "请稍后重试"}`
|
||||
@@ -610,7 +646,7 @@ export function WeKnoraWikiManagementPage() {
|
||||
<header className="flex min-h-14 shrink-0 flex-wrap items-center justify-between gap-3 border-b px-4 py-2">
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<Button size="icon-sm" variant="ghost" onClick={() => navigate(`/page/workspace/knowledge/${encodeURIComponent(noteId)}?tab=wiki`)}>
|
||||
<Button size="icon-sm" variant="ghost" onClick={() => navigate(`/page/workspace/knowledge/${encodeURIComponent(noteId)}?tab=documents`)}>
|
||||
<ArrowLeft className="size-4" />
|
||||
</Button>
|
||||
<h1 className="truncate text-base font-semibold text-foreground">{title}</h1>
|
||||
@@ -618,7 +654,9 @@ export function WeKnoraWikiManagementPage() {
|
||||
<p className="ml-9 mt-0.5 text-xs text-muted-foreground">Wiki 文档新增、编辑、删除 · {vectorStatusText}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<WeKnoraIncrementalSync knowledgeBaseId={noteId} disabled={!canWrite} />
|
||||
{advancedManagementEnabled && (
|
||||
<WeKnoraIncrementalSync knowledgeBaseId={noteId} disabled={!canWrite} />
|
||||
)}
|
||||
<Button variant="outline" size="sm" onClick={() => void exportExcel()} disabled={actions.exportWikiExcel.isPending}>
|
||||
{actions.exportWikiExcel.isPending ? <Loader2 className="mr-2 size-4 animate-spin" /> : <Download className="mr-2 size-4" />}
|
||||
导出 Excel
|
||||
@@ -633,21 +671,21 @@ export function WeKnoraWikiManagementPage() {
|
||||
</Button>
|
||||
</div>
|
||||
</header>
|
||||
<main className="grid min-h-0 flex-1 grid-cols-[320px_1fr] overflow-hidden">
|
||||
<main className="grid min-h-0 flex-1 grid-cols-[320px_minmax(0,1fr)] overflow-hidden">
|
||||
<aside className="flex min-h-0 flex-col border-r bg-muted/20">
|
||||
<div className="border-b p-3">
|
||||
{indexStatus.isLoading && (
|
||||
{advancedManagementEnabled && indexStatus.isLoading && (
|
||||
<div className="mb-3 flex items-center rounded-lg border bg-background p-3 text-xs text-muted-foreground">
|
||||
<Loader2 className="mr-2 size-4 animate-spin" />正在读取 Wiki 镜像向量状态
|
||||
</div>
|
||||
)}
|
||||
{indexStatus.isError && (
|
||||
{advancedManagementEnabled && indexStatus.isError && (
|
||||
<div className="mb-3 rounded-lg border border-destructive/30 bg-destructive/5 p-3 text-xs text-destructive">
|
||||
<p>Wiki 镜像向量状态读取失败:{indexStatus.error instanceof Error ? indexStatus.error.message : "请稍后重试"}</p>
|
||||
<Button type="button" variant="ghost" size="sm" className="mt-1 h-7 px-2" onClick={() => void indexStatus.refetch()}>重新读取</Button>
|
||||
</div>
|
||||
)}
|
||||
{indexStatus.data && (
|
||||
{advancedManagementEnabled && indexStatus.data && (
|
||||
<div className="mb-3 rounded-lg border bg-background p-3">
|
||||
<div className="flex items-center justify-between gap-2 text-xs">
|
||||
<span className="flex items-center gap-2 font-medium">
|
||||
@@ -705,7 +743,7 @@ export function WeKnoraWikiManagementPage() {
|
||||
)}
|
||||
</div>
|
||||
</aside>
|
||||
<section className="flex min-h-0 flex-col overflow-hidden">
|
||||
<section className="flex min-w-0 min-h-0 flex-col overflow-hidden">
|
||||
{!creating && !selectedSlug ? (
|
||||
<div className="flex flex-1 items-center justify-center px-6">
|
||||
<div className="max-w-md rounded-2xl border border-dashed bg-muted/15 px-8 py-10 text-center">
|
||||
@@ -739,8 +777,8 @@ export function WeKnoraWikiManagementPage() {
|
||||
<div className="flex shrink-0 items-center justify-between gap-3 border-b px-4 py-3">
|
||||
<div className="min-w-0">
|
||||
<div className="truncate text-sm font-medium">{creating ? "新建文章" : draft.title || selectedSlug}</div>
|
||||
<div className="truncate text-xs text-muted-foreground">{creating ? "创建后写入知识库 Wiki" : draft.slug}</div>
|
||||
{(draft.pageType || draft.status || draft.parentSlug || draft.aliasesText || draft.categoryPathText) && (
|
||||
{metadataOpen && <div className="truncate text-xs text-muted-foreground">{creating ? "创建后写入知识库 Wiki" : draft.slug}</div>}
|
||||
{metadataOpen && (draft.pageType || draft.status || draft.parentSlug || draft.aliasesText || draft.categoryPathText) && (
|
||||
<div className="mt-1 flex flex-wrap gap-1">
|
||||
{[draft.pageType, draft.status, draft.parentSlug, ...splitDirectory(draft.categoryPathText), ...splitTags(draft.aliasesText)]
|
||||
.filter(Boolean)
|
||||
@@ -775,84 +813,89 @@ export function WeKnoraWikiManagementPage() {
|
||||
</div>
|
||||
</div>
|
||||
<div className="min-h-0 flex-1 space-y-4 overflow-auto p-4">
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<label className="space-y-1.5">
|
||||
<span className="text-sm font-medium">Slug</span>
|
||||
<Input
|
||||
value={draft.slug}
|
||||
disabled={!creating}
|
||||
onChange={(event) => setDraft((prev) => ({ ...prev, slug: event.target.value }))}
|
||||
placeholder="例如 entity/flow-json"
|
||||
/>
|
||||
</label>
|
||||
<label className="space-y-1.5">
|
||||
<span className="text-sm font-medium">标题</span>
|
||||
<Input
|
||||
value={draft.title}
|
||||
onChange={(event) => setDraft((prev) => ({ ...prev, title: event.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
<label className="space-y-1.5">
|
||||
<span className="text-sm font-medium">类型</span>
|
||||
<Input
|
||||
value={draft.pageType}
|
||||
onChange={(event) => setDraft((prev) => ({ ...prev, pageType: event.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
<label className="space-y-1.5">
|
||||
<span className="text-sm font-medium">状态</span>
|
||||
<Input
|
||||
value={draft.status}
|
||||
onChange={(event) => setDraft((prev) => ({ ...prev, status: event.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
<label className="space-y-1.5 md:col-span-2">
|
||||
<span className="text-sm font-medium">移动到</span>
|
||||
<select
|
||||
value={moveOptions.some((option) => option.value === currentMoveTarget) ? currentMoveTarget : "root:"}
|
||||
onChange={(event) => applyMoveTarget(event.target.value, setDraft)}
|
||||
className="border-input bg-background ring-offset-background placeholder:text-muted-foreground focus-visible:ring-ring h-10 w-full rounded-md border px-3 py-2 text-sm focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
{moveOptions.map((option) => (
|
||||
<option key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="space-y-1.5">
|
||||
<span className="text-sm font-medium">目录路径</span>
|
||||
<Input
|
||||
value={draft.categoryPathText}
|
||||
onChange={(event) => setDraft((prev) => ({ ...prev, categoryPathText: event.target.value }))}
|
||||
placeholder="例如 政要/日本/内阁"
|
||||
/>
|
||||
</label>
|
||||
<label className="space-y-1.5">
|
||||
<span className="text-sm font-medium">父级 slug</span>
|
||||
<Input
|
||||
value={draft.parentSlug}
|
||||
onChange={(event) => setDraft((prev) => ({ ...prev, parentSlug: event.target.value }))}
|
||||
placeholder="可选,例如 entity/japan"
|
||||
/>
|
||||
</label>
|
||||
<label className="space-y-1.5">
|
||||
<span className="text-sm font-medium">别名</span>
|
||||
<Input
|
||||
value={draft.aliasesText}
|
||||
onChange={(event) => setDraft((prev) => ({ ...prev, aliasesText: event.target.value }))}
|
||||
placeholder="多个别名用逗号分隔"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<label className="block space-y-1.5">
|
||||
<span className="text-sm font-medium">摘要</span>
|
||||
<Textarea
|
||||
value={draft.summary}
|
||||
rows={3}
|
||||
onChange={(event) => setDraft((prev) => ({ ...prev, summary: event.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
<details open={metadataOpen} onToggle={(event) => setMetadataOpen(event.currentTarget.open)} className="rounded-lg border">
|
||||
<summary className="cursor-pointer px-3 py-2 text-sm font-medium">文章属性与摘要</summary>
|
||||
<div className="space-y-4 border-t p-3">
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<label className="space-y-1.5">
|
||||
<span className="text-sm font-medium">Slug</span>
|
||||
<Input
|
||||
value={draft.slug}
|
||||
disabled={!creating}
|
||||
onChange={(event) => setDraft((prev) => ({ ...prev, slug: event.target.value }))}
|
||||
placeholder="例如 entity/flow-json"
|
||||
/>
|
||||
</label>
|
||||
<label className="space-y-1.5">
|
||||
<span className="text-sm font-medium">标题</span>
|
||||
<Input
|
||||
value={draft.title}
|
||||
onChange={(event) => setDraft((prev) => ({ ...prev, title: event.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
<label className="space-y-1.5">
|
||||
<span className="text-sm font-medium">类型</span>
|
||||
<Input
|
||||
value={draft.pageType}
|
||||
onChange={(event) => setDraft((prev) => ({ ...prev, pageType: event.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
<label className="space-y-1.5">
|
||||
<span className="text-sm font-medium">状态</span>
|
||||
<Input
|
||||
value={draft.status}
|
||||
onChange={(event) => setDraft((prev) => ({ ...prev, status: event.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
<label className="space-y-1.5 md:col-span-2">
|
||||
<span className="text-sm font-medium">移动到</span>
|
||||
<select
|
||||
value={moveOptions.some((option) => option.value === currentMoveTarget) ? currentMoveTarget : "root:"}
|
||||
onChange={(event) => applyMoveTarget(event.target.value, setDraft)}
|
||||
className="border-input bg-background ring-offset-background placeholder:text-muted-foreground focus-visible:ring-ring h-10 w-full rounded-md border px-3 py-2 text-sm focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
{moveOptions.map((option) => (
|
||||
<option key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="space-y-1.5">
|
||||
<span className="text-sm font-medium">目录路径</span>
|
||||
<Input
|
||||
value={draft.categoryPathText}
|
||||
onChange={(event) => setDraft((prev) => ({ ...prev, categoryPathText: event.target.value }))}
|
||||
placeholder="例如 政要/日本/内阁"
|
||||
/>
|
||||
</label>
|
||||
<label className="space-y-1.5">
|
||||
<span className="text-sm font-medium">父级 slug</span>
|
||||
<Input
|
||||
value={draft.parentSlug}
|
||||
onChange={(event) => setDraft((prev) => ({ ...prev, parentSlug: event.target.value }))}
|
||||
placeholder="可选,例如 entity/japan"
|
||||
/>
|
||||
</label>
|
||||
<label className="space-y-1.5">
|
||||
<span className="text-sm font-medium">别名</span>
|
||||
<Input
|
||||
value={draft.aliasesText}
|
||||
onChange={(event) => setDraft((prev) => ({ ...prev, aliasesText: event.target.value }))}
|
||||
placeholder="多个别名用逗号分隔"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<label className="block space-y-1.5">
|
||||
<span className="text-sm font-medium">摘要</span>
|
||||
<Textarea
|
||||
value={draft.summary}
|
||||
rows={3}
|
||||
onChange={(event) => setDraft((prev) => ({ ...prev, summary: event.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</details>
|
||||
<label className="block space-y-1.5">
|
||||
<span className="text-sm font-medium">正文</span>
|
||||
<MarkdownCodeEditor
|
||||
|
||||
+75
-10
@@ -21,6 +21,7 @@ import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { MarkdownContent } from "@/components/workspace/messages/markdown-content";
|
||||
import { useAssistantKnowledgeAccess } from "@/core/llmwiki/assistant-knowledge-access";
|
||||
import { ASSISTANT_KNOWLEDGE_UI_VISIBLE } from "@/core/llmwiki/assistant-knowledge-ui";
|
||||
import {
|
||||
buildAppHashUrl,
|
||||
buildPublicKnowledgeWikiPath,
|
||||
@@ -36,6 +37,7 @@ import {
|
||||
import { usePublicBackground } from "@/core/embed/background";
|
||||
import { reasoningPlugins } from "@/core/streamdown";
|
||||
import { markdownToDocxBlob } from "@/core/scheduled-tasks/markdown-docx";
|
||||
import { useOrdinaryKnowledgeRetrievalSettings } from "@/core/system-settings/hooks";
|
||||
import {
|
||||
exportableWikiMarkdown,
|
||||
renderableWikiMarkdown,
|
||||
@@ -56,7 +58,10 @@ import {
|
||||
} from "@/strategy-components/api/llmwiki";
|
||||
import { WikiProtectedImage } from "./WikiProtectedImage";
|
||||
import { WikiLibraryReader } from "./WikiLibraryReader";
|
||||
import { useAssistantKnowledgeBases, useAssistantKnowledgeSources } from "@/strategy-components/api/assistant-knowledge";
|
||||
import {
|
||||
listAssistantKnowledgeBases,
|
||||
listAssistantKnowledgeSources,
|
||||
} from "@/strategy-components/api/assistant-knowledge";
|
||||
|
||||
const LIST_PATH = "/page/workspace/knowledge";
|
||||
const GENERATED_PUBLIC_INDEX_SLUG = "__index__";
|
||||
@@ -126,16 +131,16 @@ export function WeKnoraWikiPageView({
|
||||
const navigate = useNavigate();
|
||||
const assistantAccess = useAssistantKnowledgeAccess({ enabled: !publicEmbed });
|
||||
const isAdmin = assistantAccess.isAdmin;
|
||||
const knowledgeManagementSettings =
|
||||
useOrdinaryKnowledgeRetrievalSettings(!publicEmbed && isAdmin);
|
||||
const advancedManagementEnabled =
|
||||
knowledgeManagementSettings.data?.advanced_management_enabled === true;
|
||||
const publicBackground = usePublicBackground();
|
||||
const requestedWikiSlug = searchParams.get("wikiSlug")?.trim() || "";
|
||||
const assistantKnowledgeEnabled = !publicEmbed && assistantAccess.canAccess;
|
||||
const assistantBases = useAssistantKnowledgeBases(assistantKnowledgeEnabled);
|
||||
const assistantSources = useAssistantKnowledgeSources(null, assistantKnowledgeEnabled);
|
||||
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,
|
||||
{ pollInterval: false },
|
||||
);
|
||||
const publicKnowledgeBase = usePublicLlmWikiKnowledgeBase(
|
||||
noteId || null,
|
||||
@@ -152,6 +157,7 @@ export function WeKnoraWikiPageView({
|
||||
500,
|
||||
"",
|
||||
!!noteId && !publicEmbed,
|
||||
{ pollInterval: false },
|
||||
);
|
||||
const publicPages = usePublicLlmWikiWikiPages(
|
||||
noteId || null,
|
||||
@@ -215,6 +221,8 @@ export function WeKnoraWikiPageView({
|
||||
!!noteId && publicEmbed && !!indexPage && wikiSlug === indexPage.slug,
|
||||
);
|
||||
const [downloading, setDownloading] = useState<"md" | "word" | null>(null);
|
||||
const [openingAssistant, setOpeningAssistant] = useState(false);
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const [directoryQuery, setDirectoryQuery] = useState("");
|
||||
const [collapsedDirectories, setCollapsedDirectories] = useState<Set<string>>(() => new Set());
|
||||
const routedPage = (location.state as { wikiPage?: LlmWikiWikiPage } | null)?.wikiPage;
|
||||
@@ -283,6 +291,57 @@ export function WeKnoraWikiPageView({
|
||||
? wikiLinkMarkdown(exportableWikiMarkdown(title, summary, content), noteId)
|
||||
: "";
|
||||
|
||||
const refresh = async () => {
|
||||
if (refreshing) return;
|
||||
setRefreshing(true);
|
||||
try {
|
||||
const results = await Promise.all([
|
||||
knowledgeBase.refetch(),
|
||||
pages.refetch(),
|
||||
...(!generatedIndexActive && !generatedIndexRequested && wikiSlug
|
||||
? [page.refetch()]
|
||||
: []),
|
||||
...(publicEmbed && indexPage && wikiSlug === indexPage.slug
|
||||
? [publicWikiIndex.refetch()]
|
||||
: []),
|
||||
]);
|
||||
const failed = results.find((result) => result.isError);
|
||||
if (failed) {
|
||||
toast.error(failed.error instanceof Error ? failed.error.message : "刷新 Wiki 页面失败,请重试");
|
||||
}
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "刷新 Wiki 页面失败,请重试");
|
||||
} finally {
|
||||
setRefreshing(false);
|
||||
}
|
||||
};
|
||||
|
||||
const openAssistantKnowledge = async () => {
|
||||
if (openingAssistant || !assistantAccess.canAccess || !pageData) return;
|
||||
setOpeningAssistant(true);
|
||||
try {
|
||||
// This lookup only supports a secondary navigation action. Keep both
|
||||
// catalogues off the reader's initial load and fetch them concurrently.
|
||||
const [bases, sources] = await Promise.all([
|
||||
listAssistantKnowledgeBases(),
|
||||
listAssistantKnowledgeSources(),
|
||||
]);
|
||||
const globalBase = bases.find((base) => base.is_global);
|
||||
const deposited = sources.some(
|
||||
(source) => source.source_key === noteId && source.status === "active",
|
||||
);
|
||||
if (!globalBase || !deposited) {
|
||||
toast.info("该知识库尚未归纳到助手知识库");
|
||||
return;
|
||||
}
|
||||
navigate(`/page/workspace/knowledge/assistant?${new URLSearchParams({ base_id: globalBase.id, wikiSlug: pageData.slug })}`);
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "读取助手知识库失败,请重试");
|
||||
} finally {
|
||||
setOpeningAssistant(false);
|
||||
}
|
||||
};
|
||||
|
||||
const download = async (format: "md" | "word") => {
|
||||
if (!exportMarkdown) return;
|
||||
setDownloading(format);
|
||||
@@ -463,7 +522,7 @@ export function WeKnoraWikiPageView({
|
||||
>
|
||||
导入资料
|
||||
</Button>
|
||||
{isAdmin && (
|
||||
{isAdmin && advancedManagementEnabled && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
@@ -543,6 +602,9 @@ export function WeKnoraWikiPageView({
|
||||
<Badge variant="outline" className="shrink-0 border-emerald-200 text-emerald-700 dark:border-emerald-800 dark:text-emerald-300">
|
||||
公开 Wiki
|
||||
</Badge>
|
||||
<Button variant="ghost" size="icon-sm" onClick={() => void refresh()} disabled={refreshing} aria-label="刷新 Wiki">
|
||||
<RefreshCw className={`size-4 ${refreshing ? "animate-spin" : ""}`} />
|
||||
</Button>
|
||||
</header>
|
||||
) : (
|
||||
<header className="flex shrink-0 flex-wrap items-center justify-between gap-3 border-b bg-background px-4 py-3 shadow-sm sm:px-6">
|
||||
@@ -565,9 +627,12 @@ export function WeKnoraWikiPageView({
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{isAdmin && <Button variant="outline" size="sm" onClick={() => navigate(`${LIST_PATH}/${encodeURIComponent(noteId)}/retrieval-debug`)}><Search className="mr-2 size-4" />检索测试</Button>}
|
||||
<Button variant="outline" size="sm" onClick={() => void refresh()} disabled={refreshing}>
|
||||
<RefreshCw className={`mr-2 size-4 ${refreshing ? "animate-spin" : ""}`} />刷新
|
||||
</Button>
|
||||
{isAdmin && advancedManagementEnabled && <Button variant="outline" size="sm" onClick={() => navigate(`${LIST_PATH}/${encodeURIComponent(noteId)}/retrieval-debug`)}><Search className="mr-2 size-4" />检索测试</Button>}
|
||||
<Button variant="outline" size="sm" onClick={() => navigate(`${LIST_PATH}/${encodeURIComponent(noteId)}?view=weknora`)}>知识库管理</Button>
|
||||
{isAdmin && (
|
||||
{isAdmin && advancedManagementEnabled && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
@@ -581,7 +646,7 @@ export function WeKnoraWikiPageView({
|
||||
导入 / 导出数据包
|
||||
</Button>
|
||||
)}
|
||||
{assistantAccess.canAccess && globalBase && isDeposited && <Button variant="outline" size="sm" onClick={() => navigate(`/page/workspace/knowledge/assistant?${new URLSearchParams({ base_id: globalBase.id, wikiSlug: pageData.slug })}`)}>在知识梳理中查看</Button>}
|
||||
{ASSISTANT_KNOWLEDGE_UI_VISIBLE && assistantAccess.canAccess && <Button variant="outline" size="sm" onClick={() => void openAssistantKnowledge()} disabled={openingAssistant}>{openingAssistant && <Loader2 className="mr-2 size-4 animate-spin" />}在知识梳理中查看</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
|
||||
|
||||
+1
-1
@@ -523,7 +523,7 @@ export function WikiLibraryReader({
|
||||
</div>
|
||||
) : (
|
||||
<div className="py-20 text-center text-sm text-muted-foreground">
|
||||
选择一个 Wiki 页面开始阅读。完成向量化的数据会自动沉淀到知识梳理。
|
||||
选择一个 Wiki 页面开始阅读。完成向量化后即可用于知识检索。
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
|
||||
+1
-1
@@ -57,7 +57,7 @@ export function WikiPackageTransfers({
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
{assistant
|
||||
? "保留正文、分类、标签、链接和原始向量;后台整理完成后下载。"
|
||||
: "兼容普通知识库和助手知识库导出的 JSONL 数据包;导入当前空库时直接还原 Wiki 与向量,不调用大模型,也不会恢复原始文档。"}
|
||||
: "兼容知识库导出的 JSONL 数据包;导入当前空库时直接还原 Wiki 与向量,不调用大模型,也不会恢复原始文档。"}
|
||||
</p>
|
||||
</div>
|
||||
<input
|
||||
|
||||
+1
-1
@@ -99,7 +99,7 @@ function TaskConversationsList({
|
||||
const currentThreadId = useMemo(() => parseThreadId(pathname, chatsBase), [pathname, chatsBase]);
|
||||
|
||||
return (
|
||||
<div className="bg-background/85 border-border/70 flex w-64 shrink-0 flex-col border-r shadow-[12px_0_30px_-30px_rgba(15,23,42,0.45)] backdrop-blur-xl dark:border-[#1b477e]/70 dark:bg-[#061b35]/82">
|
||||
<div className="bg-background border-border/70 flex w-64 shrink-0 flex-col border-r shadow-[12px_0_30px_-30px_rgba(15,23,42,0.45)] dark:border-[#1b477e]/70 dark:bg-[#061b35]">
|
||||
<div className="border-border/70 border-b p-3 dark:border-[#1b477e]/70">
|
||||
{/* 左上角标明当前是哪个分析页面 */}
|
||||
<div className="mb-3 flex items-center gap-2">
|
||||
|
||||
+24
-8
@@ -21,13 +21,23 @@ import AgentChatPage from "@/pages/AgentChatPage";
|
||||
|
||||
const TASK_ANALYSIS_NAME = "任务分析";
|
||||
|
||||
function useChatsBase(taskBase: string): { taskId: string; agentId: string; chatsBase: string } {
|
||||
function useChatsBase(taskBase: string): {
|
||||
taskId: string;
|
||||
agentId: string;
|
||||
taskType: string;
|
||||
chatsBase: string;
|
||||
} {
|
||||
const { agent_id } = useParams<{ agent_id: string }>();
|
||||
const agentId = agent_id ?? "";
|
||||
const context = readTaskContext();
|
||||
const detail = readB51TaskDetail();
|
||||
const taskId = context?.goPath === B5_1_GOPATH ? context.taskId : (detail?.id ?? "");
|
||||
return { taskId, agentId, chatsBase: `${taskBase}/agent/${agentId}/chats` };
|
||||
// 聊天记录按 taskId + ?type= 分区;上下文丢失时从详情快照兜底恢复。
|
||||
const taskType =
|
||||
context?.goPath === B5_1_GOPATH
|
||||
? (context.taskType ?? "")
|
||||
: (detail?.taskType ?? "");
|
||||
return { taskId, agentId, taskType, chatsBase: `${taskBase}/agent/${agentId}/chats` };
|
||||
}
|
||||
|
||||
function TaskDetailHeader() {
|
||||
@@ -62,18 +72,20 @@ function parseThreadId(pathname: string, chatsBase: string): string | null {
|
||||
|
||||
function TaskConversationsList({
|
||||
taskId,
|
||||
taskType,
|
||||
chatsBase,
|
||||
}: {
|
||||
taskId: string;
|
||||
taskType: string;
|
||||
chatsBase: string;
|
||||
}) {
|
||||
const { pathname } = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const { threads, isLoading } = useTaskDeeplinkThreads(taskId, B5_1_GOPATH);
|
||||
const { threads, isLoading } = useTaskDeeplinkThreads(taskId, B5_1_GOPATH, taskType);
|
||||
const currentThreadId = useMemo(() => parseThreadId(pathname, chatsBase), [pathname, chatsBase]);
|
||||
|
||||
return (
|
||||
<div className="bg-background/85 border-border/70 flex w-64 shrink-0 flex-col border-r shadow-[12px_0_30px_-30px_rgba(15,23,42,0.45)] backdrop-blur-xl dark:border-[#1b477e]/70 dark:bg-[#061b35]/82">
|
||||
<div className="bg-background border-border/70 flex w-64 shrink-0 flex-col border-r shadow-[12px_0_30px_-30px_rgba(15,23,42,0.45)] dark:border-[#1b477e]/70 dark:bg-[#061b35]">
|
||||
<div className="border-border/70 border-b p-3 dark:border-[#1b477e]/70">
|
||||
<div className="mb-3 flex items-center gap-2">
|
||||
<span className="h-4 w-1 rounded-full bg-[var(--color-main)]" />
|
||||
@@ -134,11 +146,11 @@ function TaskConversationsList({
|
||||
}
|
||||
|
||||
export function TaskAnalysisWorkspace({ taskBase }: { taskBase: string }) {
|
||||
const { taskId, chatsBase } = useChatsBase(taskBase);
|
||||
const { taskId, taskType, chatsBase } = useChatsBase(taskBase);
|
||||
return (
|
||||
<div className="flex size-full min-h-0 flex-col overflow-hidden">
|
||||
<div className="flex min-h-0 flex-1 overflow-hidden">
|
||||
<TaskConversationsList taskId={taskId} chatsBase={chatsBase} />
|
||||
<TaskConversationsList taskId={taskId} taskType={taskType} chatsBase={chatsBase} />
|
||||
<div className="relative min-h-0 min-w-0 flex-1">
|
||||
<Outlet />
|
||||
</div>
|
||||
@@ -148,9 +160,13 @@ export function TaskAnalysisWorkspace({ taskBase }: { taskBase: string }) {
|
||||
}
|
||||
|
||||
export function TaskAnalysisIndexResolver({ taskBase }: { taskBase: string }) {
|
||||
const { taskId, chatsBase } = useChatsBase(taskBase);
|
||||
const { taskId, taskType, chatsBase } = useChatsBase(taskBase);
|
||||
const navigate = useNavigate();
|
||||
const { isLoading, hasThreads, latestThreadId } = useTaskDeeplinkThreads(taskId, B5_1_GOPATH);
|
||||
const { isLoading, hasThreads, latestThreadId } = useTaskDeeplinkThreads(
|
||||
taskId,
|
||||
B5_1_GOPATH,
|
||||
taskType,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (isLoading) return;
|
||||
|
||||
@@ -188,10 +188,11 @@ function TaskConversationsList({
|
||||
const navigate = useNavigate();
|
||||
const { threads, isLoading } = useTaskDeeplinkThreads(recordTaskId, business);
|
||||
const currentThreadId = useMemo(() => parseThreadId(pathname, chatsBase), [pathname, chatsBase]);
|
||||
const businessName = desensitize(TASK_BUSINESSES.find((b) => b.code === business)?.name ?? "");
|
||||
// 左上角业务标题用配置名直出,不走脱敏(种子/后台曾把「三情*」替换成 3qfx 业务码)。
|
||||
const businessName = TASK_BUSINESSES.find((b) => b.code === business)?.name ?? "";
|
||||
|
||||
return (
|
||||
<div className="bg-background/85 border-border/70 flex w-64 shrink-0 flex-col border-r shadow-[12px_0_30px_-30px_rgba(15,23,42,0.45)] backdrop-blur-xl dark:border-[#1b477e]/70 dark:bg-[#061b35]/82">
|
||||
<div className="bg-background border-border/70 flex w-64 shrink-0 flex-col border-r shadow-[12px_0_30px_-30px_rgba(15,23,42,0.45)] dark:border-[#1b477e]/70 dark:bg-[#061b35]">
|
||||
<div className="border-border/70 border-b p-3 dark:border-[#1b477e]/70">
|
||||
{/* 左上角标明当前是哪个分析页面 */}
|
||||
<div className="mb-3 flex items-center gap-2">
|
||||
|
||||
@@ -122,7 +122,7 @@ export function TaskJumpBar({
|
||||
<>
|
||||
{menuButtons.length > 0 && <TaskSideJumpMenu buttons={menuButtons} onRun={handleRun} />}
|
||||
{barButtons.length > 0 && (
|
||||
<div className="border-border/70 bg-background/90 flex shrink-0 flex-wrap items-center justify-end gap-3 border-t px-5 py-3 backdrop-blur-xl dark:border-[#1b477e]/70 dark:bg-[#061b35]/85">
|
||||
<div className="border-border/70 bg-background flex shrink-0 flex-wrap items-center justify-end gap-3 border-t px-5 py-3 dark:border-[#1b477e]/70 dark:bg-[#061b35]">
|
||||
{barButtons.map((btn) => (
|
||||
<TaskJumpButton
|
||||
key={btn.id}
|
||||
@@ -203,7 +203,7 @@ function TaskSideJumpMenu({
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="absolute right-0 top-1/2 overflow-hidden rounded-l-2xl rounded-r-none bg-white/95 py-1.5 shadow-[0_18px_45px_rgba(15,23,42,0.16)] backdrop-blur-2xl dark:bg-[#061b35]/90 dark:shadow-[0_18px_45px_rgba(0,0,0,0.35)]"
|
||||
className="absolute right-0 top-1/2 overflow-hidden rounded-l-2xl rounded-r-none bg-white py-1.5 shadow-[0_18px_45px_rgba(15,23,42,0.16)] dark:bg-[#061b35] dark:shadow-[0_18px_45px_rgba(0,0,0,0.35)]"
|
||||
style={{
|
||||
width: menuWidth,
|
||||
transform: `translateY(-50%) translateX(${open ? 0 : menuWidth - collapsedWidth}px)`,
|
||||
|
||||
+1
-1
@@ -89,7 +89,7 @@ export function TaskReportImportCard({
|
||||
}, [onImported, taskId, validation]);
|
||||
|
||||
return (
|
||||
<div className="border-border/70 bg-background/85 mx-auto w-full max-w-[760px] rounded-xl border p-4 shadow-sm backdrop-blur-xl dark:border-[#1b477e]/70 dark:bg-[#061b35]/82">
|
||||
<div className="border-border/70 bg-background mx-auto w-full max-w-[760px] rounded-xl border p-4 shadow-sm dark:border-[#1b477e]/70 dark:bg-[#061b35]">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="bg-[var(--color-main)]/10 text-[var(--color-main)] mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-lg">
|
||||
<Database className="h-4.5 w-4.5" />
|
||||
|
||||
@@ -403,7 +403,7 @@ const MOCK_ROUTES: Array<{ match: string; dataset: MockDataset }> = [
|
||||
//
|
||||
// consumer 接口 `{VITE_AIPI_CONSUMER_URL}/taskAnalyseSearch/cop-task-detail` 外网可能不可达,
|
||||
// 可用假数据模拟登录深链(?taskId=&goPath=)效果。返回结构与真实接口一致:
|
||||
// `{ code, message, data: { id, overview, taskDirection, taskName, taskContent } }`
|
||||
// `{ code, message, data: { id, overview, taskDirection, taskName, taskContent, taskType } }`
|
||||
//
|
||||
// 启停由 `VITE_MOCK_COP_TASK_DETAIL` 控制(默认真实数据,=true 时走假数据),
|
||||
// 见 `utils/request.ts` 的请求拦截器。
|
||||
@@ -416,6 +416,8 @@ interface CopTaskDetailSeed {
|
||||
taskContent: string;
|
||||
overview: string;
|
||||
taskDirection: string;
|
||||
/** 字典码:1 打击 / 2 塑势 / 3 防御。 */
|
||||
taskType: number;
|
||||
}
|
||||
|
||||
/** 任务详情假数据池(按 taskId 取模选一条,让不同 taskId 呈现不同任务)。 */
|
||||
@@ -426,6 +428,7 @@ const COP_TASK_DETAIL_SEEDS: CopTaskDetailSeed[] = [
|
||||
'围绕"暑期文旅消费季"全网讨论,分析公众情绪走向、核心关切与潜在争议点,识别需重点引导的群体,并给出传播策略建议。',
|
||||
overview: '暑期文旅消费季相关讨论的情绪与倾向分析。',
|
||||
taskDirection: '王磊',
|
||||
taskType: 1,
|
||||
},
|
||||
{
|
||||
taskName: '居民阶梯电价调整公众情绪研判',
|
||||
@@ -433,6 +436,7 @@ const COP_TASK_DETAIL_SEEDS: CopTaskDetailSeed[] = [
|
||||
'针对居民阶梯电价调整方案,梳理公众主要担忧(用电成本、公平性),判断情绪峰值节点与高敏群体,形成分群体沟通要点。',
|
||||
overview: '阶梯电价调整的公众情绪研判。',
|
||||
taskDirection: '李婷',
|
||||
taskType: 2,
|
||||
},
|
||||
{
|
||||
taskName: '城市更新片区舆论引导任务',
|
||||
@@ -440,6 +444,7 @@ const COP_TASK_DETAIL_SEEDS: CopTaskDetailSeed[] = [
|
||||
'对老城区改造涉及的拆迁、安置等敏感议题进行情绪与诉求拆解,识别居民、商户等不同立场,制定差异化回应策略。',
|
||||
overview: '城市更新片区敏感议题的舆论引导分析。',
|
||||
taskDirection: '张伟',
|
||||
taskType: 3,
|
||||
},
|
||||
];
|
||||
|
||||
@@ -462,10 +467,77 @@ function buildCopTaskDetailBody(taskId: string) {
|
||||
taskDirection: seed.taskDirection,
|
||||
taskName: seed.taskName,
|
||||
taskContent: seed.taskContent,
|
||||
taskType: seed.taskType,
|
||||
cbwName: "暑期文旅传播网",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const XDFX_ACTION_DETAIL_ROUTE = "/task-action/actionDetail";
|
||||
const XDFX_NARRATIVE_ROUTE = "/mainnets/narratives-by-name";
|
||||
|
||||
/** xdfx 深链两条 consumer 接口:行动结构、传播网简介。 */
|
||||
export function matchXdfxConsumerMock(url?: string): boolean {
|
||||
return !!url && (url.includes(XDFX_ACTION_DETAIL_ROUTE) || url.includes(XDFX_NARRATIVE_ROUTE));
|
||||
}
|
||||
|
||||
function readQueryValue(
|
||||
config: { url?: string; params?: Record<string, unknown> },
|
||||
key: string,
|
||||
): string {
|
||||
const fromParams = config.params?.[key];
|
||||
if (fromParams != null && fromParams !== "") return String(fromParams);
|
||||
if (config.url) {
|
||||
const match = config.url.match(new RegExp(`[?&]${key}=([^&]+)`));
|
||||
if (match) return decodeURIComponent(match[1]);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function buildXdfxActionDetailBody(actionId: string) {
|
||||
return {
|
||||
state: 200,
|
||||
msg: "操作成功",
|
||||
data: {
|
||||
actionId: actionId || "9001",
|
||||
purpose: null,
|
||||
actor: null,
|
||||
expectedBehavior: null,
|
||||
drivingFactor: null,
|
||||
narrationList: null,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function buildXdfxNarrativeBody(cbwName: string) {
|
||||
const name = cbwName || "未命名传播网";
|
||||
return {
|
||||
state: 200,
|
||||
msg: "操作成功",
|
||||
data: { summary: `「${name}」主要讨论暑期文旅消费,本地假数据。` },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 本地假数据:不发真实请求。控制台打印实际 URL 和参数,方便核对 actionId / cbwName。
|
||||
* purpose 为 null 时,行为体、预期行为、驱动因素、叙事也是 null,用户消息不展示这些行。
|
||||
* 仍会请求传播网简介。
|
||||
*/
|
||||
export function xdfxConsumerMockAdapter(config: {
|
||||
url?: string;
|
||||
params?: Record<string, unknown>;
|
||||
}): Promise<{ data: unknown; status: number; statusText: string; headers: Record<string, unknown>; config: unknown }> {
|
||||
const actionId = readQueryValue(config, "actionId");
|
||||
const cbwName = readQueryValue(config, "cbwName");
|
||||
const narrative = !!config.url?.includes(XDFX_NARRATIVE_ROUTE);
|
||||
console.info("[xdfx mock] 未发真实请求", {
|
||||
url: config.url,
|
||||
params: narrative ? { cbwName } : { actionId },
|
||||
});
|
||||
const body = narrative ? buildXdfxNarrativeBody(cbwName) : buildXdfxActionDetailBody(actionId);
|
||||
return Promise.resolve({ data: body, status: 200, statusText: "OK", headers: {}, config });
|
||||
}
|
||||
|
||||
/** 判断某请求 url 是否是 cop-task-detail。 */
|
||||
export function matchCopTaskDetailMock(url?: string): boolean {
|
||||
return !!url && url.includes(COP_TASK_DETAIL_ROUTE);
|
||||
|
||||
@@ -211,6 +211,26 @@ function replaceAccessTokenParam(url: string, accessToken: string): { url: strin
|
||||
return { url: nextUrl, replaced };
|
||||
}
|
||||
|
||||
/**
|
||||
* 把已解析的路由参数拼到地址上。只追加调用方传入的参数,不额外注入 access_token。
|
||||
* 智能体「对话」跳转用这个;轻应用仍走 {@link buildLightAppUrl}。
|
||||
*/
|
||||
export function appendResolvedRouteParams(
|
||||
url: string,
|
||||
routeParams: Array<Pick<LightAppRouteParam, "key" | "paramType" | "source" | "customValue" | "themeValue">> | null | undefined,
|
||||
userInfo: Record<string, unknown> = readUserInfo(),
|
||||
theme?: AppThemeColor,
|
||||
): string {
|
||||
const pairs = (routeParams ?? [])
|
||||
.filter((param) => (param.key ?? "").trim())
|
||||
.map((param) => {
|
||||
const key = (param.key ?? "").trim();
|
||||
const value = resolveRouteParamValue(param as LightAppRouteParam, userInfo, theme);
|
||||
return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
|
||||
});
|
||||
return appendQueryPairs(url, pairs);
|
||||
}
|
||||
|
||||
export function buildLightAppUrl(
|
||||
app: Pick<LightApp, "url" | "routeParams">,
|
||||
userInfo: Record<string, unknown> = readUserInfo(),
|
||||
|
||||
Reference in new issue
Block a user