sync update from LAN repo (source dhk-1 @ 3e87be55)
This commit is contained in:
1 parent
ab6068a7c1
commit
42f2a26fa8
1482 files changed
+227759
-9584
No files matched your search
@@ -1,8 +1,14 @@
|
||||
import { Bell, ChevronDown, User } from "lucide-react";
|
||||
import { Bell, ChevronDown, ListTree, User } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { useLocation, useNavigate } from "react-router-dom";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import "@/components/page-sdebar.css";
|
||||
import {
|
||||
CompactShortcutButtons,
|
||||
@@ -41,10 +47,6 @@ const iconButtonClass = (isDark: boolean, isPaleLightTheme: boolean, isCustomThe
|
||||
: "text-white hover:bg-[var(--brand-950)] active:bg-[#8a0618]",
|
||||
);
|
||||
|
||||
// 深色顶栏菜单左右分组(设计稿:左 问答中心/任务管理/应用中心,右 综合管理/资源管理)
|
||||
const LEFT_MENU_IDS = ["qa-center", "task-management", "light-app-center"];
|
||||
const RIGHT_MENU_IDS = ["comprehensive-management", "resource-management"];
|
||||
|
||||
type HeaderProps = {
|
||||
collapsed?: boolean;
|
||||
};
|
||||
@@ -86,7 +88,7 @@ const Header = ({ collapsed }: HeaderProps) => {
|
||||
const { pathname } = useLocation();
|
||||
const liveAccount = useLiveAccount();
|
||||
const auth = getStoredAuth();
|
||||
const isAdmin = auth?.system_role === "admin";
|
||||
const isAdmin = !auth || auth.system_role === "admin";
|
||||
const visibleMenuItems = useSidebarMenuItems(!!isAdmin);
|
||||
const desensitizeText = useDisplayDesensitizer();
|
||||
const { data: myPosition } = useMyPosition();
|
||||
@@ -122,8 +124,11 @@ const Header = ({ collapsed }: HeaderProps) => {
|
||||
|
||||
const thirdSubNavItems = getActiveThirdLevelItems(visibleMenuItems, pathname);
|
||||
|
||||
const leftMenuItems = visibleMenuItems.filter((i) => LEFT_MENU_IDS.includes(i.id));
|
||||
const rightMenuItems = visibleMenuItems.filter((i) => RIGHT_MENU_IDS.includes(i.id));
|
||||
// 深色顶栏围绕中间标题分成左右两组。直接按菜单管理后的一级顺序均分,确保被升为
|
||||
// 一级或重新排序的节点仍会显示;默认 5 项时仍保持左 3 / 右 2 的原布局。
|
||||
const topMenuSplitIndex = Math.ceil(visibleMenuItems.length / 2);
|
||||
const leftMenuItems = visibleMenuItems.slice(0, topMenuSplitIndex);
|
||||
const rightMenuItems = visibleMenuItems.slice(topMenuSplitIndex);
|
||||
|
||||
const handleNavItemClick = (item: MenuItem) => {
|
||||
const path = item.path ?? findFirstRoutePath(item.children);
|
||||
@@ -209,54 +214,64 @@ const Header = ({ collapsed }: HeaderProps) => {
|
||||
aria-hidden
|
||||
/>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
className={cn(
|
||||
"h-8 gap-2 rounded-sm px-2",
|
||||
isCustomTheme
|
||||
? "text-[var(--navigation-foreground)] hover:bg-white/20 active:bg-white/30"
|
||||
: isDark
|
||||
? "text-slate-200 hover:bg-slate-800/50"
|
||||
: isPaleLightTheme
|
||||
? "text-[var(--foreground)] hover:bg-white/55 active:bg-white/75"
|
||||
: "text-white hover:bg-[var(--brand-950)] active:bg-[#8a0618]",
|
||||
)}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"flex size-8 shrink-0 items-center justify-center rounded-sm",
|
||||
isCustomTheme
|
||||
? "bg-white/25"
|
||||
: isDark
|
||||
? "bg-gradient-to-br from-blue-500 to-cyan-400"
|
||||
: "bg-white",
|
||||
)}
|
||||
>
|
||||
<User
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
className={cn(
|
||||
"size-4",
|
||||
isDark && !isCustomTheme ? "text-white" : "text-[var(--brand-900)]",
|
||||
"h-8 gap-2 rounded-sm px-2",
|
||||
isCustomTheme
|
||||
? "text-[var(--navigation-foreground)] hover:bg-white/20 active:bg-white/30"
|
||||
: isDark
|
||||
? "text-slate-200 hover:bg-slate-800/50"
|
||||
: isPaleLightTheme
|
||||
? "text-[var(--foreground)] hover:bg-white/55 active:bg-white/75"
|
||||
: "text-white hover:bg-[var(--brand-950)] active:bg-[#8a0618]",
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<div className="hidden text-left sm:block">
|
||||
<p className={cn("text-sm leading-tight font-medium", headerTextClass)}>
|
||||
{displayName}
|
||||
</p>
|
||||
{positionName && (
|
||||
<p className={cn("text-[11px] leading-tight", isCustomTheme ? "text-[var(--navigation-foreground)]/75" : isPaleLightTheme ? "text-[var(--muted-foreground)]" : "text-white/70")}>
|
||||
{positionName}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<ChevronDown
|
||||
className={cn(
|
||||
"size-4 shrink-0",
|
||||
isCustomTheme ? "text-[var(--navigation-foreground)]/80" : isDark ? "text-slate-500" : isPaleLightTheme ? "text-[var(--muted-foreground)]" : "text-white/80",
|
||||
)}
|
||||
/>
|
||||
</Button>
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"flex size-8 shrink-0 items-center justify-center rounded-sm",
|
||||
isCustomTheme
|
||||
? "bg-white/25"
|
||||
: isDark
|
||||
? "bg-gradient-to-br from-blue-500 to-cyan-400"
|
||||
: "bg-white",
|
||||
)}
|
||||
>
|
||||
<User
|
||||
className={cn(
|
||||
"size-4",
|
||||
isDark && !isCustomTheme ? "text-white" : "text-[var(--brand-900)]",
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<div className="hidden text-left sm:block">
|
||||
<p className={cn("text-sm leading-tight font-medium", headerTextClass)}>
|
||||
{displayName}
|
||||
</p>
|
||||
{positionName && (
|
||||
<p className={cn("text-[11px] leading-tight", isCustomTheme ? "text-[var(--navigation-foreground)]/75" : isPaleLightTheme ? "text-[var(--muted-foreground)]" : "text-white/70")}>
|
||||
{positionName}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<ChevronDown
|
||||
className={cn(
|
||||
"size-4 shrink-0",
|
||||
isCustomTheme ? "text-[var(--navigation-foreground)]/80" : isDark ? "text-slate-500" : isPaleLightTheme ? "text-[var(--muted-foreground)]" : "text-white/80",
|
||||
)}
|
||||
/>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" sideOffset={8} className="min-w-48">
|
||||
<DropdownMenuItem onClick={() => navigate("/page/strategy/admin/menu-management")}>
|
||||
<ListTree className="size-4" />
|
||||
{isAdmin ? "默认菜单管理" : "我的菜单"}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</>
|
||||
);
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
// Node's type-stripping test runner requires the explicit TypeScript suffix.
|
||||
// @ts-expect-error The application compiler intentionally uses extensionless imports.
|
||||
import { ANSWER_FEEDBACK_BATCH_SIZE, batchAnswerFeedbackMessageIds } from "./answer-feedback-batching.ts";
|
||||
|
||||
test("deduplicates ids and keeps each request within the backend limit", () => {
|
||||
const ids = Array.from({ length: 405 }, (_, index) => `message-${index}`);
|
||||
const batches = batchAnswerFeedbackMessageIds([
|
||||
ids[0]!,
|
||||
...ids,
|
||||
ids[404]!,
|
||||
]);
|
||||
|
||||
assert.deepEqual(
|
||||
batches.map((batch) => batch.length),
|
||||
[ANSWER_FEEDBACK_BATCH_SIZE, ANSWER_FEEDBACK_BATCH_SIZE, 5],
|
||||
);
|
||||
assert.equal(batches[0]?.[0], "message-0");
|
||||
assert.equal(batches[2]?.[4], "message-404");
|
||||
});
|
||||
|
||||
test("returns no request batch when there are no message ids", () => {
|
||||
assert.deepEqual(batchAnswerFeedbackMessageIds([]), []);
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
export const ANSWER_FEEDBACK_BATCH_SIZE = 200;
|
||||
|
||||
/** Preserve display order while deduplicating and respecting the API limit. */
|
||||
export function batchAnswerFeedbackMessageIds(messageIds: string[]): string[][] {
|
||||
const uniqueIds = [...new Set(messageIds.filter(Boolean))];
|
||||
const chunks: string[][] = [];
|
||||
for (
|
||||
let index = 0;
|
||||
index < uniqueIds.length;
|
||||
index += ANSWER_FEEDBACK_BATCH_SIZE
|
||||
) {
|
||||
chunks.push(uniqueIds.slice(index, index + ANSWER_FEEDBACK_BATCH_SIZE));
|
||||
}
|
||||
return chunks;
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
/**
|
||||
* Assistant-answer feedback API and React Query hooks.
|
||||
*
|
||||
* Feedback is addressed by the visible assistant message id. The gateway
|
||||
* resolves that id to its authoritative run and agent, so callers never need
|
||||
* to infer a run id from streaming state.
|
||||
*/
|
||||
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
import { apiFetch } from "@/core/api/fetch-client";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
|
||||
import { batchAnswerFeedbackMessageIds } from "./answer-feedback-batching";
|
||||
|
||||
export const ANSWER_FEEDBACK_REASONS = [
|
||||
"incorrect_or_incomplete",
|
||||
"unmet_expectations",
|
||||
"slow_or_problematic",
|
||||
"style_or_tone",
|
||||
"safety_or_legal",
|
||||
"other",
|
||||
] as const;
|
||||
|
||||
export type AnswerFeedbackReason = (typeof ANSWER_FEEDBACK_REASONS)[number];
|
||||
export type AnswerFeedbackRating = 1 | -1;
|
||||
|
||||
export interface AnswerFeedback {
|
||||
feedback_id: string;
|
||||
run_id: string;
|
||||
thread_id: string;
|
||||
user_id: string | null;
|
||||
message_id: string;
|
||||
agent_id: string;
|
||||
rating: AnswerFeedbackRating;
|
||||
reasons: AnswerFeedbackReason[];
|
||||
detail: string | null;
|
||||
/** Legacy free-text field retained by the backend for old feedback rows. */
|
||||
comment: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface AnswerFeedbackContext {
|
||||
thread_id: string;
|
||||
message_id: string;
|
||||
run_id: string;
|
||||
agent_id: string;
|
||||
feedback: AnswerFeedback | null;
|
||||
}
|
||||
|
||||
export interface UpsertAnswerFeedbackInput {
|
||||
rating: AnswerFeedbackRating;
|
||||
reasons?: AnswerFeedbackReason[];
|
||||
detail?: string | null;
|
||||
}
|
||||
|
||||
export type FeedbackScoreConfidenceLevel =
|
||||
| "none"
|
||||
| "low"
|
||||
| "medium"
|
||||
| "high";
|
||||
|
||||
export interface FeedbackScoreBand {
|
||||
key: "excellent" | "good" | "needs_attention" | "poor" | string;
|
||||
label: string;
|
||||
min: number;
|
||||
max: number;
|
||||
}
|
||||
|
||||
export interface FeedbackDimensionScore {
|
||||
weight: number;
|
||||
score: number | null;
|
||||
evidence_count: number;
|
||||
positive_count: number;
|
||||
negative_count: number;
|
||||
mapped_reasons: AnswerFeedbackReason[];
|
||||
}
|
||||
|
||||
export type FeedbackDimensionKey =
|
||||
| "correctness"
|
||||
| "completeness"
|
||||
| "evidence_grounding"
|
||||
| "relevance"
|
||||
| "actionability";
|
||||
|
||||
export interface FeedbackReasonBreakdown {
|
||||
count: number;
|
||||
rate: number;
|
||||
}
|
||||
|
||||
export interface AgentFeedbackScore {
|
||||
agent_id: string;
|
||||
score: number | null;
|
||||
score_band: FeedbackScoreBand;
|
||||
/** Statistical confidence N / (N + 10), in the range 0..1. */
|
||||
confidence: number;
|
||||
confidence_level: FeedbackScoreConfidenceLevel;
|
||||
sample_count: number;
|
||||
positive_count: number;
|
||||
negative_count: number;
|
||||
task_success_rate: number | null;
|
||||
task_score: number | null;
|
||||
dimensions: Record<FeedbackDimensionKey, FeedbackDimensionScore>;
|
||||
reason_breakdown: Partial<
|
||||
Record<AnswerFeedbackReason, FeedbackReasonBreakdown>
|
||||
>;
|
||||
prior: Record<string, number>;
|
||||
formula: Record<string, string>;
|
||||
}
|
||||
|
||||
const feedbackContextKey = (threadId: string, messageId: string) =>
|
||||
["answer-feedback", "context", threadId, messageId] as const;
|
||||
|
||||
const feedbackContextsPrefix = (threadId: string) =>
|
||||
["answer-feedback", "contexts", threadId] as const;
|
||||
|
||||
const feedbackContextsKey = (threadId: string, messageIds: string[]) =>
|
||||
[...feedbackContextsPrefix(threadId), messageIds] as const;
|
||||
|
||||
const feedbackScoreKey = (agentId: string) =>
|
||||
["answer-feedback", "agent-score", agentId] as const;
|
||||
|
||||
function messageFeedbackBase(threadId: string, messageId: string) {
|
||||
return `${getBackendBaseURL()}/api/threads/${encodeURIComponent(
|
||||
threadId,
|
||||
)}/messages/${encodeURIComponent(messageId)}`;
|
||||
}
|
||||
|
||||
async function readJson<T>(response: Response, fallback: string): Promise<T> {
|
||||
if (!response.ok) {
|
||||
const body = (await response.json().catch(() => null)) as {
|
||||
detail?: unknown;
|
||||
} | null;
|
||||
throw new Error(
|
||||
typeof body?.detail === "string"
|
||||
? body.detail
|
||||
: `${fallback} (${response.status})`,
|
||||
);
|
||||
}
|
||||
return (await response.json()) as T;
|
||||
}
|
||||
|
||||
export async function getAnswerFeedbackContext(
|
||||
threadId: string,
|
||||
messageId: string,
|
||||
): Promise<AnswerFeedbackContext | null> {
|
||||
const response = await apiFetch(
|
||||
`${messageFeedbackBase(threadId, messageId)}/feedback-context`,
|
||||
);
|
||||
// Older conversations may predate run-event journaling. They simply do not
|
||||
// expose a feedback action rather than surfacing an error in the chat.
|
||||
if (response.status === 404) return null;
|
||||
return readJson<AnswerFeedbackContext>(
|
||||
response,
|
||||
"Unable to load answer feedback",
|
||||
);
|
||||
}
|
||||
|
||||
interface AnswerFeedbackContextsResponse {
|
||||
contexts: AnswerFeedbackContext[];
|
||||
unresolved_message_ids: string[];
|
||||
}
|
||||
|
||||
export type AnswerFeedbackContextMap = Record<string, AnswerFeedbackContext>;
|
||||
|
||||
/**
|
||||
* Hydrate a conversation's visible feedback in bounded batches. The API limit
|
||||
* is 200 message ids; chunking keeps long histories O(N/200), never O(N).
|
||||
*/
|
||||
export async function getAnswerFeedbackContexts(
|
||||
threadId: string,
|
||||
messageIds: string[],
|
||||
): Promise<AnswerFeedbackContextMap> {
|
||||
const chunks = batchAnswerFeedbackMessageIds(messageIds);
|
||||
if (chunks.length === 0) return {};
|
||||
const responses = await Promise.all(
|
||||
chunks.map(async (ids) => {
|
||||
const response = await apiFetch(
|
||||
`${getBackendBaseURL()}/api/threads/${encodeURIComponent(
|
||||
threadId,
|
||||
)}/feedback-contexts`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ message_ids: ids }),
|
||||
},
|
||||
);
|
||||
return readJson<AnswerFeedbackContextsResponse>(
|
||||
response,
|
||||
"Unable to load answer feedback",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const result: AnswerFeedbackContextMap = {};
|
||||
for (const response of responses) {
|
||||
for (const context of response.contexts ?? []) {
|
||||
result[context.message_id] = context;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function upsertAnswerFeedback(
|
||||
threadId: string,
|
||||
messageId: string,
|
||||
input: UpsertAnswerFeedbackInput,
|
||||
): Promise<AnswerFeedback> {
|
||||
const response = await apiFetch(
|
||||
`${messageFeedbackBase(threadId, messageId)}/feedback`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(input),
|
||||
},
|
||||
);
|
||||
return readJson<AnswerFeedback>(response, "Unable to save answer feedback");
|
||||
}
|
||||
|
||||
export async function deleteAnswerFeedback(
|
||||
threadId: string,
|
||||
messageId: string,
|
||||
): Promise<void> {
|
||||
const response = await apiFetch(
|
||||
`${messageFeedbackBase(threadId, messageId)}/feedback`,
|
||||
{ method: "DELETE" },
|
||||
);
|
||||
if (!response.ok && response.status !== 404) {
|
||||
await readJson(response, "Unable to delete answer feedback");
|
||||
}
|
||||
}
|
||||
|
||||
export async function getAgentFeedbackScore(
|
||||
agentId: string,
|
||||
): Promise<AgentFeedbackScore> {
|
||||
const response = await apiFetch(
|
||||
`${getBackendBaseURL()}/api/agents/${encodeURIComponent(
|
||||
agentId,
|
||||
)}/feedback-score`,
|
||||
);
|
||||
return readJson<AgentFeedbackScore>(
|
||||
response,
|
||||
"Unable to load agent feedback score",
|
||||
);
|
||||
}
|
||||
|
||||
export function useAnswerFeedbackContext(
|
||||
threadId: string,
|
||||
messageId: string,
|
||||
enabled = true,
|
||||
) {
|
||||
return useQuery({
|
||||
queryKey: feedbackContextKey(threadId, messageId),
|
||||
queryFn: () => getAnswerFeedbackContext(threadId, messageId),
|
||||
enabled: enabled && Boolean(threadId) && Boolean(messageId),
|
||||
staleTime: 30_000,
|
||||
refetchOnWindowFocus: false,
|
||||
retry: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function useAnswerFeedbackContexts(
|
||||
threadId: string,
|
||||
messageIds: string[],
|
||||
enabled = true,
|
||||
) {
|
||||
return useQuery({
|
||||
queryKey: feedbackContextsKey(threadId, messageIds),
|
||||
queryFn: () => getAnswerFeedbackContexts(threadId, messageIds),
|
||||
enabled: enabled && Boolean(threadId) && messageIds.length > 0,
|
||||
staleTime: 30_000,
|
||||
// Each completed turn produces a new message-id set. Retire superseded
|
||||
// batch maps promptly so a long-running chat does not accumulate them.
|
||||
gcTime: 60_000,
|
||||
refetchOnWindowFocus: false,
|
||||
retry: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpsertAnswerFeedback() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: ({
|
||||
threadId,
|
||||
messageId,
|
||||
input,
|
||||
}: {
|
||||
threadId: string;
|
||||
messageId: string;
|
||||
input: UpsertAnswerFeedbackInput;
|
||||
}) => upsertAnswerFeedback(threadId, messageId, input),
|
||||
onSuccess: (feedback, variables) => {
|
||||
queryClient.setQueryData<AnswerFeedbackContext | null>(
|
||||
feedbackContextKey(variables.threadId, variables.messageId),
|
||||
(current) =>
|
||||
current
|
||||
? { ...current, agent_id: feedback.agent_id, feedback }
|
||||
: {
|
||||
thread_id: feedback.thread_id,
|
||||
message_id: feedback.message_id,
|
||||
run_id: feedback.run_id,
|
||||
agent_id: feedback.agent_id,
|
||||
feedback,
|
||||
},
|
||||
);
|
||||
queryClient.setQueriesData<AnswerFeedbackContextMap>(
|
||||
{
|
||||
queryKey: feedbackContextsPrefix(variables.threadId),
|
||||
exact: false,
|
||||
},
|
||||
(current) => {
|
||||
if (!current) return current;
|
||||
const previous = current[variables.messageId];
|
||||
return {
|
||||
...current,
|
||||
[variables.messageId]: previous
|
||||
? { ...previous, agent_id: feedback.agent_id, feedback }
|
||||
: {
|
||||
thread_id: feedback.thread_id,
|
||||
message_id: feedback.message_id,
|
||||
run_id: feedback.run_id,
|
||||
agent_id: feedback.agent_id,
|
||||
feedback,
|
||||
},
|
||||
};
|
||||
},
|
||||
);
|
||||
if (feedback.agent_id) {
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: feedbackScoreKey(feedback.agent_id),
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useAgentFeedbackScore(agentId: string | null | undefined) {
|
||||
return useQuery({
|
||||
queryKey: feedbackScoreKey(agentId ?? ""),
|
||||
queryFn: () => getAgentFeedbackScore(agentId!),
|
||||
enabled: Boolean(agentId),
|
||||
staleTime: 30_000,
|
||||
refetchOnWindowFocus: false,
|
||||
retry: false,
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,10 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
useInfiniteQuery,
|
||||
useMutation,
|
||||
useQuery,
|
||||
useQueryClient,
|
||||
} from "@tanstack/react-query";
|
||||
import { useEffect } from "react";
|
||||
|
||||
import { apiFetch } from "@/core/api/fetch-client";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
@@ -27,7 +33,8 @@ export interface AssistantWikiPage {
|
||||
slug: string;
|
||||
title: string;
|
||||
page_type: string;
|
||||
content_markdown: string;
|
||||
/** Omitted by the lightweight directory endpoint; present on page detail. */
|
||||
content_markdown?: string;
|
||||
summary: string;
|
||||
current_revision_id?: string | null;
|
||||
updated_at: string;
|
||||
@@ -67,7 +74,7 @@ export interface AssistantWikiRevision {
|
||||
export interface AssistantKnowledgeSource {
|
||||
id: string;
|
||||
base_id: string;
|
||||
source_type: "weknora" | "skill" | "local_file";
|
||||
source_type: "weknora" | "skill" | "file";
|
||||
source_name: string;
|
||||
source_key: string;
|
||||
status: string;
|
||||
@@ -221,26 +228,71 @@ function withBaseParam(baseId?: string | null) {
|
||||
return params;
|
||||
}
|
||||
|
||||
export async function listAssistantWikiPages(q = "", baseId?: string | null) {
|
||||
const params = withBaseParam(baseId);
|
||||
params.set("limit", "500");
|
||||
if (q.trim()) params.set("q", q.trim());
|
||||
export async function listAssistantWikiPages(
|
||||
q = "",
|
||||
baseId?: string | null,
|
||||
includeContent = true,
|
||||
) {
|
||||
const pages: AssistantWikiPage[] = [];
|
||||
let offset: number | null = 0;
|
||||
do {
|
||||
params.set("offset", String(offset));
|
||||
const batch: { pages: AssistantWikiPage[]; next_offset?: number | null } =
|
||||
await readJson(await apiFetch(`${BASE()}/wiki-pages?${params}`));
|
||||
const batch = await listAssistantWikiPageBatch(
|
||||
q,
|
||||
baseId,
|
||||
includeContent,
|
||||
offset,
|
||||
);
|
||||
pages.push(...batch.pages);
|
||||
offset = batch.next_offset ?? null;
|
||||
} while (offset !== null);
|
||||
return pages;
|
||||
}
|
||||
|
||||
export type AssistantKnowledgeRetrievalMode =
|
||||
| "empty"
|
||||
| "keyword"
|
||||
| "overview"
|
||||
| "vector";
|
||||
|
||||
type AssistantWikiPageBatch = {
|
||||
pages: AssistantWikiPage[];
|
||||
next_offset?: number | null;
|
||||
};
|
||||
|
||||
async function listAssistantWikiPageBatch(
|
||||
q = "",
|
||||
baseId?: string | null,
|
||||
includeContent = true,
|
||||
offset = 0,
|
||||
): 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}`),
|
||||
);
|
||||
}
|
||||
|
||||
export async function getAssistantWikiPage(
|
||||
slug: string,
|
||||
baseId: string,
|
||||
) {
|
||||
const params = withBaseParam(baseId);
|
||||
const safeSlug = slug.split("/").map(encodeURIComponent).join("/");
|
||||
return readJson<AssistantWikiPage>(
|
||||
await apiFetch(`${BASE()}/wiki-pages/${safeSlug}?${params}`),
|
||||
);
|
||||
}
|
||||
|
||||
export async function searchAssistantWiki(q: string, baseId: string) {
|
||||
return readJson<{
|
||||
results: (AssistantWikiPage & { score: number; retrieval_mode: string })[];
|
||||
retrieval_mode: string;
|
||||
results: (AssistantWikiPage & {
|
||||
score: number;
|
||||
retrieval_mode: Exclude<AssistantKnowledgeRetrievalMode, "empty">;
|
||||
})[];
|
||||
retrieval_mode: AssistantKnowledgeRetrievalMode;
|
||||
}>(
|
||||
await apiFetch(
|
||||
`${BASE()}/search?${new URLSearchParams({ q, base_id: baseId })}`,
|
||||
@@ -447,13 +499,60 @@ export function useAssistantKnowledgeBases(enabled = true) {
|
||||
queryKey: [KEY, "bases"],
|
||||
queryFn: listAssistantKnowledgeBases,
|
||||
enabled,
|
||||
staleTime: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useAssistantWikiPages(query = "", baseId?: string | null) {
|
||||
export function useAssistantWikiPages(
|
||||
query = "",
|
||||
baseId?: string | null,
|
||||
options: { includeContent?: boolean; enabled?: boolean } = {},
|
||||
) {
|
||||
const includeContent = options.includeContent ?? true;
|
||||
const enabled = (options.enabled ?? true) && !!baseId;
|
||||
const result = useInfiniteQuery({
|
||||
queryKey: [KEY, "pages", baseId ?? "global", query, includeContent],
|
||||
queryFn: ({ pageParam }) =>
|
||||
listAssistantWikiPageBatch(
|
||||
query,
|
||||
baseId,
|
||||
includeContent,
|
||||
pageParam,
|
||||
),
|
||||
initialPageParam: 0,
|
||||
getNextPageParam: (lastPage) => lastPage.next_offset ?? undefined,
|
||||
enabled,
|
||||
});
|
||||
|
||||
// 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) {
|
||||
void result.fetchNextPage();
|
||||
}
|
||||
}, [
|
||||
enabled,
|
||||
result.fetchNextPage,
|
||||
result.hasNextPage,
|
||||
result.isFetchingNextPage,
|
||||
]);
|
||||
|
||||
return {
|
||||
...result,
|
||||
data: result.data?.pages.flatMap((batch) => batch.pages),
|
||||
};
|
||||
}
|
||||
|
||||
export function useAssistantWikiPage(
|
||||
slug?: string | null,
|
||||
baseId?: string | null,
|
||||
enabled = true,
|
||||
) {
|
||||
return useQuery({
|
||||
queryKey: [KEY, "pages", baseId ?? "global", query],
|
||||
queryFn: () => listAssistantWikiPages(query, baseId),
|
||||
queryKey: [KEY, "page", baseId, slug],
|
||||
queryFn: () => getAssistantWikiPage(slug!, baseId!),
|
||||
enabled: enabled && !!baseId && !!slug,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -465,10 +564,14 @@ export function useAssistantKnowledgeSources(baseId?: string | null, enabled = t
|
||||
});
|
||||
}
|
||||
|
||||
export function useAssistantImportJobs(baseId?: string | null) {
|
||||
export function useAssistantImportJobs(
|
||||
baseId?: string | null,
|
||||
enabled = true,
|
||||
) {
|
||||
return useQuery({
|
||||
queryKey: [KEY, "jobs", baseId ?? "global"],
|
||||
queryFn: () => listAssistantImportJobs(baseId),
|
||||
enabled: enabled && !!baseId,
|
||||
refetchInterval: (query) =>
|
||||
(query.state.data ?? []).some((job) =>
|
||||
["queued", "running"].includes(job.status),
|
||||
@@ -492,7 +595,20 @@ export function useAssistantKnowledgeActions() {
|
||||
}),
|
||||
updateBase: useMutation({
|
||||
mutationFn: updateAssistantKnowledgeBase,
|
||||
onSuccess: invalidate,
|
||||
onSuccess: (updated) => {
|
||||
client.setQueryData<AssistantKnowledgeBase[]>(
|
||||
[KEY, "bases"],
|
||||
(current) =>
|
||||
current?.map((base) =>
|
||||
base.id === updated.id ? { ...base, ...updated } : base,
|
||||
),
|
||||
);
|
||||
client.setQueriesData<AssistantKnowledgeBase>(
|
||||
{ queryKey: [KEY, "base"] },
|
||||
(current) =>
|
||||
current?.id === updated.id ? { ...current, ...updated } : current,
|
||||
);
|
||||
},
|
||||
}),
|
||||
deleteBase: useMutation({
|
||||
mutationFn: deleteAssistantKnowledgeBase,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
import { apiFetch } from "@/core/api/fetch-client";
|
||||
import { getAccountIdentityKey, getStoredAuth } from "@/core/auth";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
import { OptType, writeYLog } from "@/core/log/y-log";
|
||||
import {
|
||||
@@ -20,6 +21,24 @@ interface ServerCompactOverride {
|
||||
menu_type?: string | null;
|
||||
}
|
||||
|
||||
interface ServerCompactMenuOverrideConfig {
|
||||
overrides?: ServerCompactOverride[];
|
||||
default_overrides?: ServerCompactOverride[];
|
||||
user_overrides?: ServerCompactOverride[];
|
||||
has_user_override?: boolean;
|
||||
editable_scope?: "default" | "user";
|
||||
menu_type?: string;
|
||||
}
|
||||
|
||||
export interface CompactMenuOverrideConfig {
|
||||
overrides: CompactMenuOverride[];
|
||||
defaultOverrides: CompactMenuOverride[];
|
||||
userOverrides: CompactMenuOverride[];
|
||||
hasUserOverride: boolean;
|
||||
editableScope: "default" | "user";
|
||||
menuType: CompactMenuType;
|
||||
}
|
||||
|
||||
function toOverride(s: ServerCompactOverride): CompactMenuOverride {
|
||||
const placement =
|
||||
s.placement === "settings" || s.placement === "toolbox"
|
||||
@@ -54,22 +73,38 @@ async function readJson<T>(res: Response, ctx: string): Promise<T> {
|
||||
return (await res.json()) as T;
|
||||
}
|
||||
|
||||
function toConfig(
|
||||
data: ServerCompactMenuOverrideConfig,
|
||||
requestedType: CompactMenuType,
|
||||
): CompactMenuOverrideConfig {
|
||||
const auth = getStoredAuth();
|
||||
const fallbackScope = !auth || auth.system_role === "admin" ? "default" : "user";
|
||||
return {
|
||||
overrides: (data.overrides ?? []).map(toOverride),
|
||||
defaultOverrides: (data.default_overrides ?? data.overrides ?? []).map(toOverride),
|
||||
userOverrides: (data.user_overrides ?? []).map(toOverride),
|
||||
hasUserOverride: data.has_user_override ?? false,
|
||||
editableScope: data.editable_scope ?? fallbackScope,
|
||||
menuType: data.menu_type === "B" ? "B" : requestedType,
|
||||
};
|
||||
}
|
||||
|
||||
export async function listCompactMenuOverrides(
|
||||
menuType: CompactMenuType = getRuntimeCompactMenuType(),
|
||||
): Promise<CompactMenuOverride[]> {
|
||||
): Promise<CompactMenuOverrideConfig> {
|
||||
// 旧页面 / 未配置 VITE_COMPACT_MENU_TYPE 时不带参数,后端按类型 A 返回原来的数据。
|
||||
const url = isDefaultCompactMenuType(menuType)
|
||||
? BASE()
|
||||
: `${BASE()}?menu_type=${encodeURIComponent(menuType)}`;
|
||||
const res = await apiFetch(url, { method: "GET" });
|
||||
const data = await readJson<{ overrides: ServerCompactOverride[] }>(res, "list compact menu overrides");
|
||||
return (data.overrides ?? []).map(toOverride);
|
||||
const data = await readJson<ServerCompactMenuOverrideConfig>(res, "list compact menu overrides");
|
||||
return toConfig(data, menuType);
|
||||
}
|
||||
|
||||
export async function replaceCompactMenuOverrides(
|
||||
overrides: CompactMenuOverride[],
|
||||
menuType: CompactMenuType = getRuntimeCompactMenuType(),
|
||||
): Promise<CompactMenuOverride[]> {
|
||||
): Promise<CompactMenuOverrideConfig> {
|
||||
const body: { overrides: ServerCompactOverride[]; menu_type?: CompactMenuType } = {
|
||||
overrides: overrides.map(toBody),
|
||||
};
|
||||
@@ -81,14 +116,14 @@ export async function replaceCompactMenuOverrides(
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const data = await readJson<{ overrides: ServerCompactOverride[] }>(res, "save compact menu overrides");
|
||||
const saved = (data.overrides ?? []).map(toOverride);
|
||||
const data = await readJson<ServerCompactMenuOverrideConfig>(res, "save compact menu overrides");
|
||||
const saved = toConfig(data, menuType);
|
||||
writeYLog({
|
||||
optType: OptType.edit,
|
||||
optDetail: `CM助手-简介-菜单管理-保存-类型${menuType}`,
|
||||
url: "/api/compact-menu-overrides",
|
||||
reqParam: { menuType, overrides },
|
||||
returnParam: saved,
|
||||
returnParam: saved.overrides,
|
||||
});
|
||||
return saved;
|
||||
}
|
||||
@@ -97,8 +132,9 @@ const COMPACT_MENU_OVERRIDES_KEY = "compact-menu-overrides";
|
||||
|
||||
export function useCompactMenuOverrides(menuType?: CompactMenuType) {
|
||||
const type = menuType ?? getRuntimeCompactMenuType();
|
||||
const accountKey = getAccountIdentityKey() ?? "anonymous";
|
||||
return useQuery({
|
||||
queryKey: [COMPACT_MENU_OVERRIDES_KEY, type],
|
||||
queryKey: [COMPACT_MENU_OVERRIDES_KEY, type, accountKey],
|
||||
queryFn: () => listCompactMenuOverrides(type),
|
||||
// 菜单管理常在另一个标签页操作。简洁模式页面重新挂载或获得焦点时必须
|
||||
// 立即读取最新配置,否则新放入右侧工具箱的项目会被旧缓存隐藏一分钟。
|
||||
@@ -111,10 +147,14 @@ export function useCompactMenuOverrides(menuType?: CompactMenuType) {
|
||||
export function useCompactMenuOverrideActions(menuType?: CompactMenuType) {
|
||||
const queryClient = useQueryClient();
|
||||
const type = menuType ?? getRuntimeCompactMenuType();
|
||||
const accountKey = getAccountIdentityKey() ?? "anonymous";
|
||||
return {
|
||||
save: useMutation({
|
||||
mutationFn: (overrides: CompactMenuOverride[]) => replaceCompactMenuOverrides(overrides, type),
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: [COMPACT_MENU_OVERRIDES_KEY, type] }),
|
||||
onSuccess: () =>
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: [COMPACT_MENU_OVERRIDES_KEY, type, accountKey],
|
||||
}),
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
useMutation,
|
||||
useQuery,
|
||||
useQueryClient,
|
||||
type QueryClient,
|
||||
} from "@tanstack/react-query";
|
||||
|
||||
import { apiFetch } from "@/core/api/fetch-client";
|
||||
@@ -335,6 +336,10 @@ export async function updateSession(
|
||||
title?: string;
|
||||
status?: "collecting" | "awaiting_report";
|
||||
collectorMaterials?: Record<string, unknown>[];
|
||||
planOutline?: boolean;
|
||||
modelName?: string | null;
|
||||
force?: boolean;
|
||||
customOutline?: string;
|
||||
},
|
||||
): Promise<DeepResearchSession> {
|
||||
const res = await apiFetch(`${BASE()}/sessions/${id}`, {
|
||||
@@ -349,11 +354,42 @@ export async function updateSession(
|
||||
collectorMaterials: patch.collectorMaterials,
|
||||
}
|
||||
: {}),
|
||||
...(patch.planOutline ? { planOutline: true } : {}),
|
||||
...(patch.modelName ? { modelName: patch.modelName } : {}),
|
||||
...(patch.force ? { force: true } : {}),
|
||||
...(patch.customOutline !== undefined ? { customOutline: patch.customOutline } : {}),
|
||||
}),
|
||||
});
|
||||
return normalizeSession(await readJson<WireRecord>(res, "updateSession"));
|
||||
}
|
||||
|
||||
export async function planIntentOutline(
|
||||
sessionId: string,
|
||||
opts?: {
|
||||
modelName?: string | null;
|
||||
collectorMaterials?: Record<string, unknown>[];
|
||||
force?: boolean;
|
||||
},
|
||||
): Promise<{ outline: string; source: string; reused: boolean }> {
|
||||
// Use the existing session PATCH. A dedicated POST /intent-outline is easy
|
||||
// to miss when uvicorn --reload watches the file but does not recycle the worker.
|
||||
const session = await updateSession(sessionId, {
|
||||
planOutline: true,
|
||||
modelName: opts?.modelName,
|
||||
collectorMaterials: opts?.collectorMaterials,
|
||||
force: opts?.force,
|
||||
});
|
||||
const outline = String(session.config?.custom_outline ?? "").trim();
|
||||
if (!outline) {
|
||||
throw new Error("未能根据课题生成报告结构,请手动填写或直接开始撰写。");
|
||||
}
|
||||
return {
|
||||
outline,
|
||||
source: "intent",
|
||||
reused: false,
|
||||
};
|
||||
}
|
||||
|
||||
export async function deleteSession(id: string): Promise<void> {
|
||||
const res = await apiFetch(`${BASE()}/sessions/${id}`, { method: "DELETE" });
|
||||
if (!res.ok && res.status !== 204) {
|
||||
@@ -495,6 +531,25 @@ const DIAGNOSTIC_EVENT_TYPES = new Set([
|
||||
"report_reset",
|
||||
]);
|
||||
|
||||
const MAX_STREAM_RECONNECTS = 12;
|
||||
const STREAM_RETRY_BASE_MS = 800;
|
||||
const FATAL_STREAM_STATUSES = new Set([401, 403, 404]);
|
||||
|
||||
function sleep(ms: number, signal: AbortSignal): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
if (signal.aborted) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
const timer = globalThis.setTimeout(resolve, ms);
|
||||
const onAbort = () => {
|
||||
globalThis.clearTimeout(timer);
|
||||
resolve();
|
||||
};
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Print backend diagnostics in the browser console.
|
||||
*
|
||||
@@ -547,7 +602,10 @@ export interface StreamJobHandlers {
|
||||
* Stream job progress events via SSE.
|
||||
*
|
||||
* Returns an unsubscribe function (call on unmount / job change).
|
||||
* Uses ?after=<seq> cursor for reconnect-safe replay.
|
||||
* Uses ?after=<seq> cursor for reconnect-safe replay. Idle harvest /
|
||||
* thinking used to send zero bytes, so production proxies dropped the
|
||||
* stream and this client treated that as a hard failure. Reconnect
|
||||
* until a terminal job_status arrives or the caller unsubscribes.
|
||||
*/
|
||||
export function streamJob(
|
||||
jobId: string,
|
||||
@@ -555,67 +613,105 @@ export function streamJob(
|
||||
afterSeq = 0,
|
||||
): () => void {
|
||||
const controller = new AbortController();
|
||||
let cursor = afterSeq;
|
||||
let terminal = false;
|
||||
|
||||
const emitReconnectWarning = (attempt: number) => {
|
||||
handlers.onEvent({
|
||||
seq: 0,
|
||||
liveId: `stream-reconnect:${jobId}:${attempt}`,
|
||||
sessionId: "",
|
||||
jobId,
|
||||
type: "warning",
|
||||
phase: "writing",
|
||||
payload: {
|
||||
code: "stream_reconnecting",
|
||||
message: "进度连接中断,正在自动重连…",
|
||||
recoverable: true,
|
||||
attempt,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
const res = await apiFetch(
|
||||
`${BASE()}/jobs/${encodeURIComponent(jobId)}/stream?after=${afterSeq}`,
|
||||
{ method: "GET", signal: controller.signal },
|
||||
);
|
||||
if (!res.ok || !res.body) {
|
||||
const detail = `stream failed (${res.status})`;
|
||||
console.error("[深度研究] stream_open_failed", { jobId, afterSeq, status: res.status });
|
||||
handlers.onError?.(detail);
|
||||
return;
|
||||
}
|
||||
const reader = res.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = "";
|
||||
let attempt = 0;
|
||||
while (!controller.signal.aborted && !terminal) {
|
||||
try {
|
||||
const res = await apiFetch(
|
||||
`${BASE()}/jobs/${encodeURIComponent(jobId)}/stream?after=${cursor}`,
|
||||
{ method: "GET", signal: controller.signal },
|
||||
);
|
||||
if (FATAL_STREAM_STATUSES.has(res.status)) {
|
||||
const detail = `stream failed (${res.status})`;
|
||||
console.error("[深度研究] stream_open_failed", { jobId, afterSeq: cursor, status: res.status });
|
||||
handlers.onError?.(detail);
|
||||
return;
|
||||
}
|
||||
if (!res.ok || !res.body) {
|
||||
throw new Error(`stream failed (${res.status})`);
|
||||
}
|
||||
attempt = 0;
|
||||
const reader = res.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = "";
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
// Normalize CRLF so the parser works with both the Gateway's SSE
|
||||
// formatter and proxies that rewrite line endings.
|
||||
buffer += decoder.decode(value, { stream: true }).replace(/\r\n/g, "\n");
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
// Normalize CRLF so the parser works with both the Gateway's SSE
|
||||
// formatter and proxies that rewrite line endings.
|
||||
buffer += decoder.decode(value, { stream: true }).replace(/\r\n/g, "\n");
|
||||
|
||||
// SSE frames are separated by double-newlines; each frame has
|
||||
// `event: <name>` and `data: <json>` lines.
|
||||
const frames = buffer.split("\n\n");
|
||||
buffer = frames.pop() ?? "";
|
||||
// SSE frames are separated by double-newlines; each frame has
|
||||
// `event: <name>` and `data: <json>` lines. Comment pings (`: ping`)
|
||||
// keep proxies from dropping an idle harvest and are ignored here.
|
||||
const frames = buffer.split("\n\n");
|
||||
buffer = frames.pop() ?? "";
|
||||
|
||||
for (const frame of frames) {
|
||||
const dataLine = frame
|
||||
.split("\n")
|
||||
.find((l) => l.startsWith("data:"));
|
||||
if (!dataLine) continue;
|
||||
const json = dataLine.slice("data:".length).trim();
|
||||
if (!json) continue;
|
||||
let event: ProgressEvent;
|
||||
try {
|
||||
event = JSON.parse(json);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
logDeepResearchDiagnostic(event);
|
||||
handlers.onEvent(event);
|
||||
for (const frame of frames) {
|
||||
const dataLine = frame
|
||||
.split("\n")
|
||||
.find((l) => l.startsWith("data:"));
|
||||
if (!dataLine) continue;
|
||||
const json = dataLine.slice("data:".length).trim();
|
||||
if (!json) continue;
|
||||
let event: ProgressEvent;
|
||||
try {
|
||||
event = JSON.parse(json);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
if (typeof event.seq === "number" && event.seq > cursor) {
|
||||
cursor = event.seq;
|
||||
}
|
||||
logDeepResearchDiagnostic(event);
|
||||
handlers.onEvent(event);
|
||||
|
||||
// Check for terminal status in the payload.
|
||||
const payloadStatus = event.payload?.status as string | undefined;
|
||||
if (
|
||||
event.type === "job_status" &&
|
||||
payloadStatus &&
|
||||
isTerminalJobStatus(payloadStatus as JobStatus)
|
||||
) {
|
||||
handlers.onTerminal?.(payloadStatus);
|
||||
const payloadStatus = event.payload?.status as string | undefined;
|
||||
if (
|
||||
event.type === "job_status" &&
|
||||
payloadStatus &&
|
||||
isTerminalJobStatus(payloadStatus as JobStatus)
|
||||
) {
|
||||
terminal = true;
|
||||
handlers.onTerminal?.(payloadStatus);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
if (!controller.signal.aborted) {
|
||||
const detail = err instanceof Error ? err.message : String(err);
|
||||
console.error("[深度研究] stream_disconnected", { jobId, afterSeq, detail, error: err });
|
||||
handlers.onError?.(detail);
|
||||
if (terminal || controller.signal.aborted) return;
|
||||
throw new Error("stream ended before terminal");
|
||||
} catch (err) {
|
||||
if (controller.signal.aborted || terminal) return;
|
||||
attempt += 1;
|
||||
if (attempt > MAX_STREAM_RECONNECTS) {
|
||||
const detail = err instanceof Error ? err.message : String(err);
|
||||
console.error("[深度研究] stream_disconnected", { jobId, afterSeq: cursor, detail, error: err });
|
||||
handlers.onError?.(detail);
|
||||
return;
|
||||
}
|
||||
console.warn("[深度研究] stream_reconnecting", { jobId, afterSeq: cursor, attempt, error: err });
|
||||
emitReconnectWarning(attempt);
|
||||
await sleep(Math.min(8000, STREAM_RETRY_BASE_MS * 2 ** (attempt - 1)), controller.signal);
|
||||
}
|
||||
}
|
||||
})();
|
||||
@@ -1082,6 +1178,38 @@ export const DEEP_RESEARCH_MESSAGES_KEY = "deep-research-messages";
|
||||
export const DEEP_RESEARCH_CAPABILITIES_KEY = "deep-research-capabilities";
|
||||
export const DEEP_RESEARCH_REPORT_VARIANTS_KEY = "deep-research-report-variants";
|
||||
|
||||
type SessionListPage = {
|
||||
items: DeepResearchSession[];
|
||||
total: number;
|
||||
limit: number;
|
||||
offset: number;
|
||||
};
|
||||
|
||||
/** Keep the history rail in sync with the open session after an inline write. */
|
||||
export function patchCachedResearchSession(
|
||||
queryClient: QueryClient,
|
||||
sessionId: string,
|
||||
patch: Partial<DeepResearchSession>,
|
||||
) {
|
||||
queryClient.setQueryData<DeepResearchSession>(
|
||||
[DEEP_RESEARCH_SESSION_KEY, sessionId],
|
||||
(current) => (current ? { ...current, ...patch } : current),
|
||||
);
|
||||
queryClient.setQueriesData<SessionListPage>(
|
||||
{ queryKey: [DEEP_RESEARCH_SESSIONS_KEY] },
|
||||
(current) => {
|
||||
if (!current?.items) return current;
|
||||
let changed = false;
|
||||
const items = current.items.map((item) => {
|
||||
if (item.id !== sessionId) return item;
|
||||
changed = true;
|
||||
return { ...item, ...patch };
|
||||
});
|
||||
return changed ? { ...current, items } : current;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export function useResearchSessions(limit = 50) {
|
||||
return useQuery({
|
||||
queryKey: [DEEP_RESEARCH_SESSIONS_KEY, limit],
|
||||
@@ -1163,9 +1291,28 @@ export function useResearchActions() {
|
||||
collectorMaterials?: Record<string, unknown>[];
|
||||
forceNoMaterials?: boolean;
|
||||
}) => startJob(sessionId, { entry, config, query, title, collectorMaterials, forceNoMaterials }),
|
||||
onSuccess: (_result, { sessionId }) => {
|
||||
onSuccess: (result, { sessionId }) => {
|
||||
// Bind the write stream immediately. Waiting for GET /session makes
|
||||
// 「开始撰写」 look frozen on a slow server: the card stays up, SSE
|
||||
// never attaches, and the job can finish collecting materials with
|
||||
// no visible progress.
|
||||
queryClient.setQueryData<DeepResearchSession>(
|
||||
[DEEP_RESEARCH_SESSION_KEY, sessionId],
|
||||
(current) => (
|
||||
current
|
||||
? {
|
||||
...current,
|
||||
status: "running",
|
||||
activeJobId: result.jobId,
|
||||
error: undefined,
|
||||
}
|
||||
: current
|
||||
),
|
||||
);
|
||||
queryClient.invalidateQueries({ queryKey: [DEEP_RESEARCH_SESSIONS_KEY] });
|
||||
queryClient.invalidateQueries({ queryKey: [DEEP_RESEARCH_SESSION_KEY, sessionId] });
|
||||
// Do not refetch the session row immediately. On a slow server the
|
||||
// GET can still see awaiting_report and overwrite this optimistic
|
||||
// running state, which disconnects the write stream.
|
||||
},
|
||||
}),
|
||||
updateStatus: useMutation({
|
||||
@@ -1173,11 +1320,30 @@ export function useResearchActions() {
|
||||
sessionId,
|
||||
status,
|
||||
collectorMaterials,
|
||||
customOutline,
|
||||
}: {
|
||||
sessionId: string;
|
||||
status: "collecting" | "awaiting_report";
|
||||
collectorMaterials?: Record<string, unknown>[];
|
||||
}) => updateSession(sessionId, { status, collectorMaterials }),
|
||||
customOutline?: string;
|
||||
}) => updateSession(sessionId, { status, collectorMaterials, customOutline }),
|
||||
onSuccess: (_result, { sessionId }) => {
|
||||
queryClient.invalidateQueries({ queryKey: [DEEP_RESEARCH_SESSIONS_KEY] });
|
||||
queryClient.invalidateQueries({ queryKey: [DEEP_RESEARCH_SESSION_KEY, sessionId] });
|
||||
},
|
||||
}),
|
||||
planIntentOutline: useMutation({
|
||||
mutationFn: ({
|
||||
sessionId,
|
||||
modelName,
|
||||
collectorMaterials,
|
||||
force,
|
||||
}: {
|
||||
sessionId: string;
|
||||
modelName?: string | null;
|
||||
collectorMaterials?: Record<string, unknown>[];
|
||||
force?: boolean;
|
||||
}) => planIntentOutline(sessionId, { modelName, collectorMaterials, force }),
|
||||
onSuccess: (_result, { sessionId }) => {
|
||||
queryClient.invalidateQueries({ queryKey: [DEEP_RESEARCH_SESSIONS_KEY] });
|
||||
queryClient.invalidateQueries({ queryKey: [DEEP_RESEARCH_SESSION_KEY, sessionId] });
|
||||
|
||||
@@ -0,0 +1,372 @@
|
||||
"use client";
|
||||
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
import { apiFetch } from "@/core/api/fetch-client";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
|
||||
const BASE = () => `${getBackendBaseURL()}/api/gongwen-documents`;
|
||||
|
||||
export type GongwenDocumentStatus = "checking" | "review_required" | "verified" | "repaired" | "failed";
|
||||
export type GongwenDocumentSource = "upload" | "generated";
|
||||
|
||||
export interface GongwenIssue {
|
||||
ruleId: string;
|
||||
severity: "P0" | "P1" | "P2";
|
||||
category: string;
|
||||
name: string;
|
||||
location: string;
|
||||
paragraphIndex?: number | null;
|
||||
message: string;
|
||||
expected: string;
|
||||
actual: string;
|
||||
standardRef: string;
|
||||
autoFixable: boolean;
|
||||
}
|
||||
|
||||
export interface GongwenReview {
|
||||
engine: string;
|
||||
documentType: string;
|
||||
issues: GongwenIssue[];
|
||||
summary?: Record<string, unknown> | null;
|
||||
}
|
||||
|
||||
export interface GongwenDocumentVersion {
|
||||
id: string;
|
||||
documentId: string;
|
||||
versionNo: number;
|
||||
kind: "original" | "generated" | "repaired" | "markdown";
|
||||
fileName: string;
|
||||
contentType: string;
|
||||
sizeBytes: number;
|
||||
sha256: string;
|
||||
review?: GongwenReview | null;
|
||||
createdAt?: string;
|
||||
}
|
||||
|
||||
export interface GongwenDocument {
|
||||
id: string;
|
||||
title: string;
|
||||
documentType: string;
|
||||
source: GongwenDocumentSource;
|
||||
status: GongwenDocumentStatus;
|
||||
templateKey?: string | null;
|
||||
researchSessionId?: string | null;
|
||||
originalVersionId?: string | null;
|
||||
latestVersionId?: string | null;
|
||||
issueCounts: Record<"P0" | "P1" | "P2", number>;
|
||||
error?: string | null;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
versions?: GongwenDocumentVersion[];
|
||||
}
|
||||
|
||||
export interface GongwenTemplate {
|
||||
key: string;
|
||||
name: string;
|
||||
category: string;
|
||||
description: string;
|
||||
scope: "builtin" | "organization" | "personal";
|
||||
active: boolean;
|
||||
outline: string[];
|
||||
questions: string[];
|
||||
engineType?: string;
|
||||
sourceFileName?: string | null;
|
||||
createdAt?: string;
|
||||
}
|
||||
|
||||
export interface GongwenDraftPlan {
|
||||
intent: string;
|
||||
reason: string;
|
||||
template: GongwenTemplate;
|
||||
}
|
||||
|
||||
export interface GongwenDraftAnswer {
|
||||
question: string;
|
||||
answer: string;
|
||||
}
|
||||
|
||||
export interface GongwenDraftContent {
|
||||
title: string;
|
||||
markdown: string;
|
||||
templateKey: string;
|
||||
usedFallback: boolean;
|
||||
}
|
||||
|
||||
export interface GongwenPreview {
|
||||
paragraphs: Array<{ index: number; text: string }>;
|
||||
review?: GongwenReview | null;
|
||||
}
|
||||
|
||||
async function readJson<T>(response: Response, action: string): Promise<T> {
|
||||
if (!response.ok) {
|
||||
let detail = `${action} 失败(${response.status})`;
|
||||
try {
|
||||
const body = await response.json() as { detail?: unknown };
|
||||
if (typeof body.detail === "string") detail = body.detail;
|
||||
} catch {
|
||||
// Keep the fallback error.
|
||||
}
|
||||
throw new Error(detail);
|
||||
}
|
||||
return response.json() as Promise<T>;
|
||||
}
|
||||
|
||||
export async function listGongwenTemplates(): Promise<GongwenTemplate[]> {
|
||||
const response = await apiFetch(`${BASE()}/templates`);
|
||||
const data = await readJson<{ items?: GongwenTemplate[] }>(response, "读取模板");
|
||||
return data.items ?? [];
|
||||
}
|
||||
|
||||
export async function createGongwenTemplate(input: {
|
||||
name: string;
|
||||
description?: string;
|
||||
category?: string;
|
||||
outline: string[];
|
||||
questions?: string[];
|
||||
engineType?: string;
|
||||
}): Promise<GongwenTemplate> {
|
||||
const response = await apiFetch(`${BASE()}/templates`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
name: input.name,
|
||||
description: input.description ?? "",
|
||||
category: input.category ?? "我的模板",
|
||||
outline: input.outline,
|
||||
questions: input.questions ?? [],
|
||||
engine_type: input.engineType ?? "notice",
|
||||
}),
|
||||
});
|
||||
return readJson<GongwenTemplate>(response, "创建模板");
|
||||
}
|
||||
|
||||
export async function uploadGongwenTemplate(input: {
|
||||
file: File;
|
||||
name?: string;
|
||||
description?: string;
|
||||
category?: string;
|
||||
engineType?: string;
|
||||
}): Promise<GongwenTemplate> {
|
||||
const body = new FormData();
|
||||
body.set("file", input.file);
|
||||
if (input.name) body.set("name", input.name);
|
||||
if (input.description) body.set("description", input.description);
|
||||
body.set("category", input.category ?? "我的模板");
|
||||
body.set("engine_type", input.engineType ?? "notice");
|
||||
const response = await apiFetch(`${BASE()}/templates/upload`, { method: "POST", body });
|
||||
return readJson<GongwenTemplate>(response, "上传模板");
|
||||
}
|
||||
|
||||
export async function listGongwenDocuments(filters?: { source?: string; status?: string }): Promise<GongwenDocument[]> {
|
||||
const query = new URLSearchParams();
|
||||
if (filters?.source) query.set("source", filters.source);
|
||||
if (filters?.status) query.set("status", filters.status);
|
||||
const response = await apiFetch(`${BASE()}/documents?${query.toString()}`);
|
||||
const data = await readJson<{ items?: GongwenDocument[] }>(response, "读取公文文库");
|
||||
return data.items ?? [];
|
||||
}
|
||||
|
||||
export async function getGongwenDocument(id: string): Promise<GongwenDocument> {
|
||||
const response = await apiFetch(`${BASE()}/documents/${encodeURIComponent(id)}`);
|
||||
return readJson<GongwenDocument>(response, "读取文档详情");
|
||||
}
|
||||
|
||||
export async function uploadGongwenDocument(input: {
|
||||
file: File;
|
||||
documentType?: string;
|
||||
templateKey?: string;
|
||||
}): Promise<GongwenDocument> {
|
||||
const body = new FormData();
|
||||
body.set("file", input.file);
|
||||
body.set("document_type", input.documentType || "auto");
|
||||
if (input.templateKey) body.set("template_key", input.templateKey);
|
||||
const response = await apiFetch(`${BASE()}/documents/upload`, { method: "POST", body });
|
||||
return readJson<GongwenDocument>(response, "上传并校审");
|
||||
}
|
||||
|
||||
export async function importGongwenThreadArtifact(input: {
|
||||
threadId: string;
|
||||
artifactPath: string;
|
||||
source: "upload" | "generated" | "repaired";
|
||||
parentArtifactPath?: string;
|
||||
title?: string;
|
||||
documentType?: string;
|
||||
templateKey?: string;
|
||||
}): Promise<GongwenDocument> {
|
||||
const response = await apiFetch(`${BASE()}/documents/import-thread-artifact`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
thread_id: input.threadId,
|
||||
artifact_path: input.artifactPath,
|
||||
source: input.source,
|
||||
parent_artifact_path: input.parentArtifactPath,
|
||||
title: input.title,
|
||||
document_type: input.documentType ?? "auto",
|
||||
template_key: input.templateKey,
|
||||
}),
|
||||
});
|
||||
return readJson<GongwenDocument>(response, "归档公文");
|
||||
}
|
||||
|
||||
export async function planGongwenDraft(input: { intent: string; templateKey?: string }): Promise<GongwenDraftPlan> {
|
||||
const response = await apiFetch(`${BASE()}/drafts/plan`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ intent: input.intent, template_key: input.templateKey }),
|
||||
});
|
||||
return readJson<GongwenDraftPlan>(response, "规划公文结构");
|
||||
}
|
||||
|
||||
export async function writeGongwenDraft(input: {
|
||||
intent: string;
|
||||
templateKey: string;
|
||||
answers: GongwenDraftAnswer[];
|
||||
titleHint?: string;
|
||||
modelName?: string;
|
||||
}): Promise<GongwenDraftContent> {
|
||||
const response = await apiFetch(`${BASE()}/drafts/write`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
intent: input.intent,
|
||||
template_key: input.templateKey,
|
||||
answers: input.answers,
|
||||
title_hint: input.titleHint,
|
||||
model_name: input.modelName,
|
||||
}),
|
||||
});
|
||||
return readJson<GongwenDraftContent>(response, "起草公文");
|
||||
}
|
||||
|
||||
export interface GongwenDocumentElements {
|
||||
orgName?: string;
|
||||
docNumber?: string;
|
||||
signer?: string;
|
||||
cc?: string;
|
||||
printer?: string;
|
||||
printDate?: string;
|
||||
pageNumber?: boolean;
|
||||
}
|
||||
|
||||
export async function generateGongwenDocument(input: {
|
||||
title: string;
|
||||
documentType: string;
|
||||
content: string;
|
||||
templateKey?: string;
|
||||
researchSessionId?: string;
|
||||
elements?: GongwenDocumentElements;
|
||||
}): Promise<GongwenDocument> {
|
||||
const response = await apiFetch(`${BASE()}/documents/generate`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
title: input.title,
|
||||
document_type: input.documentType,
|
||||
content: input.content,
|
||||
template_key: input.templateKey,
|
||||
research_session_id: input.researchSessionId,
|
||||
elements: input.elements
|
||||
? {
|
||||
org_name: input.elements.orgName ?? "",
|
||||
doc_number: input.elements.docNumber ?? "",
|
||||
signer: input.elements.signer ?? "",
|
||||
cc: input.elements.cc ?? "",
|
||||
printer: input.elements.printer ?? "",
|
||||
print_date: input.elements.printDate ?? "",
|
||||
page_number: input.elements.pageNumber ?? false,
|
||||
}
|
||||
: undefined,
|
||||
}),
|
||||
});
|
||||
return readJson<GongwenDocument>(response, "生成公文");
|
||||
}
|
||||
|
||||
export async function repairGongwenDocument(id: string): Promise<GongwenDocument> {
|
||||
const response = await apiFetch(`${BASE()}/documents/${encodeURIComponent(id)}/repair`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
return readJson<GongwenDocument>(response, "格式修复");
|
||||
}
|
||||
|
||||
export async function getGongwenPreview(documentId: string, versionId: string): Promise<GongwenPreview> {
|
||||
const response = await apiFetch(
|
||||
`${BASE()}/documents/${encodeURIComponent(documentId)}/versions/${encodeURIComponent(versionId)}/preview`,
|
||||
);
|
||||
return readJson<GongwenPreview>(response, "读取审校预览");
|
||||
}
|
||||
|
||||
export async function downloadGongwenVersion(documentId: string, version: GongwenDocumentVersion): Promise<void> {
|
||||
const response = await apiFetch(
|
||||
`${BASE()}/documents/${encodeURIComponent(documentId)}/versions/${encodeURIComponent(version.id)}/download`,
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error(`下载文件失败(${response.status})`);
|
||||
}
|
||||
const url = URL.createObjectURL(await response.blob());
|
||||
const anchor = document.createElement("a");
|
||||
anchor.href = url;
|
||||
anchor.download = version.fileName;
|
||||
document.body.appendChild(anchor);
|
||||
anchor.click();
|
||||
anchor.remove();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
export async function downloadGongwenTemplate(template: GongwenTemplate): Promise<void> {
|
||||
const response = await apiFetch(`${BASE()}/templates/${encodeURIComponent(template.key)}/download`);
|
||||
if (!response.ok) {
|
||||
throw new Error(`下载模板失败(${response.status})`);
|
||||
}
|
||||
const url = URL.createObjectURL(await response.blob());
|
||||
const anchor = document.createElement("a");
|
||||
anchor.href = url;
|
||||
anchor.download = `${template.name}—标准空白模板.docx`;
|
||||
document.body.appendChild(anchor);
|
||||
anchor.click();
|
||||
anchor.remove();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
export function useGongwenTemplates() {
|
||||
return useQuery({ queryKey: ["gongwen", "templates"], queryFn: listGongwenTemplates, staleTime: 5 * 60_000 });
|
||||
}
|
||||
|
||||
export function useGongwenDocuments(filters?: { source?: string; status?: string }) {
|
||||
return useQuery({
|
||||
queryKey: ["gongwen", "documents", filters?.source ?? "", filters?.status ?? ""],
|
||||
queryFn: () => listGongwenDocuments(filters),
|
||||
});
|
||||
}
|
||||
|
||||
export function useGongwenDocument(documentId: string | null) {
|
||||
return useQuery({
|
||||
queryKey: ["gongwen", "document", documentId],
|
||||
queryFn: () => getGongwenDocument(documentId as string),
|
||||
enabled: Boolean(documentId),
|
||||
});
|
||||
}
|
||||
|
||||
export function useGongwenPreview(documentId: string | null, versionId: string | null) {
|
||||
return useQuery({
|
||||
queryKey: ["gongwen", "preview", documentId, versionId],
|
||||
queryFn: () => getGongwenPreview(documentId as string, versionId as string),
|
||||
enabled: Boolean(documentId && versionId),
|
||||
});
|
||||
}
|
||||
|
||||
export function useGongwenActions() {
|
||||
const client = useQueryClient();
|
||||
const invalidate = async () => {
|
||||
await client.invalidateQueries({ queryKey: ["gongwen", "documents"] });
|
||||
await client.invalidateQueries({ queryKey: ["gongwen", "document"] });
|
||||
};
|
||||
return {
|
||||
upload: useMutation({ mutationFn: uploadGongwenDocument, onSuccess: invalidate }),
|
||||
generate: useMutation({ mutationFn: generateGongwenDocument, onSuccess: invalidate }),
|
||||
repair: useMutation({ mutationFn: repairGongwenDocument, onSuccess: invalidate }),
|
||||
};
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
import { apiFetch } from "@/core/api/fetch-client";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
import { OptType, writeYLog } from "@/core/log/y-log";
|
||||
import type { Tag } from "@/core/tags";
|
||||
import { parseThemeMap, stringifyThemeMap } from "@/strategy-components/lib/light-app";
|
||||
|
||||
export type LightAppType = "window_open" | "iframe";
|
||||
@@ -48,6 +49,7 @@ export interface LightApp {
|
||||
sortOrder: number;
|
||||
createdAt: string | null;
|
||||
updatedAt: string | null;
|
||||
tags: Tag[];
|
||||
}
|
||||
|
||||
export interface LightAppInput {
|
||||
@@ -67,6 +69,8 @@ export interface ListLightAppsParams {
|
||||
mountLocation?: string;
|
||||
enabledOnly?: boolean;
|
||||
search?: string;
|
||||
/** OR-match: keep apps that carry any of these light_app tag ids. */
|
||||
tagIds?: string[];
|
||||
}
|
||||
|
||||
const BASE = () => `${getBackendBaseURL()}/api/light-apps`;
|
||||
@@ -92,6 +96,7 @@ interface ServerApp {
|
||||
sort_order: number;
|
||||
created_at: string | null;
|
||||
updated_at: string | null;
|
||||
tags?: Tag[];
|
||||
}
|
||||
|
||||
function toApp(s: ServerApp): LightApp {
|
||||
@@ -119,6 +124,7 @@ function toApp(s: ServerApp): LightApp {
|
||||
sortOrder: s.sort_order ?? 0,
|
||||
createdAt: s.created_at ?? null,
|
||||
updatedAt: s.updated_at ?? null,
|
||||
tags: s.tags ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -154,6 +160,7 @@ export async function listLightApps(params: ListLightAppsParams = {}): Promise<L
|
||||
if (params.mountLocation) qs.set("mount_location", params.mountLocation);
|
||||
if (params.enabledOnly) qs.set("enabled_only", "true");
|
||||
if (params.search) qs.set("search", params.search);
|
||||
for (const id of params.tagIds ?? []) qs.append("tag_ids", id);
|
||||
const query = qs.toString();
|
||||
const res = await apiFetch(`${BASE()}${query ? `?${query}` : ""}`, { method: "GET" });
|
||||
const data = await readJson<{ apps: ServerApp[] }>(res, "list light apps");
|
||||
@@ -242,6 +249,7 @@ export function useLightApps(params: ListLightAppsParams = {}) {
|
||||
params.mountLocation ?? "",
|
||||
params.enabledOnly ?? false,
|
||||
params.search ?? "",
|
||||
(params.tagIds ?? []).join(","),
|
||||
],
|
||||
queryFn: () => listLightApps(params),
|
||||
placeholderData: keepPreviousData,
|
||||
|
||||
@@ -5,8 +5,11 @@ import { getCsrfToken } from "@/core/api/csrf";
|
||||
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 { userFacingKnowledgeMessage } from "@/lib/knowledge-message";
|
||||
|
||||
export type { LlmWikiRetrievalMode } from "@/core/llmwiki/retrieval-debug";
|
||||
|
||||
const API = () => `${getBackendBaseURL()}/api/llmwiki`;
|
||||
const PUBLIC_API = () => `${getBackendBaseURL()}/api/public/llmwiki`;
|
||||
const SETTINGS_API = () => `${getBackendBaseURL()}/api/system-settings/llmwiki`;
|
||||
@@ -27,11 +30,30 @@ export interface LlmWikiSettings extends LlmWikiRuntime {
|
||||
effective_provider: LlmWikiProvider;
|
||||
}
|
||||
|
||||
export interface LlmWikiWikiInstructions {
|
||||
content_instructions: string;
|
||||
extraction_instructions: string;
|
||||
}
|
||||
|
||||
export interface LlmWikiWikiConfig extends Record<string, unknown> {
|
||||
synthesis_model_id?: string;
|
||||
extraction_granularity?: "focused" | "standard" | "exhaustive";
|
||||
content_instructions?: string;
|
||||
extraction_instructions?: string;
|
||||
}
|
||||
|
||||
export interface LlmWikiKnowledgeBase {
|
||||
id: string;
|
||||
remote_status: "available" | "missing";
|
||||
name: string;
|
||||
description: string;
|
||||
test_questions: string[];
|
||||
test_questions_customized?: boolean;
|
||||
retrieval_settings: {
|
||||
entity_expansion_enabled: boolean;
|
||||
max_related_terms: number;
|
||||
statistics_enabled: boolean;
|
||||
};
|
||||
type: "document" | "faq" | "wiki";
|
||||
publication_status: "private" | "pending" | "published" | "rejected";
|
||||
owner_user_id?: string | null;
|
||||
@@ -58,7 +80,7 @@ export interface LlmWikiKnowledgeBase {
|
||||
capabilities?: Record<string, boolean>;
|
||||
extract_config?: Record<string, unknown>;
|
||||
faq_config?: Record<string, unknown>;
|
||||
wiki_config?: Record<string, unknown>;
|
||||
wiki_config?: LlmWikiWikiConfig;
|
||||
question_generation_config?: Record<string, unknown>;
|
||||
auto_tag_config?: Record<string, unknown>;
|
||||
vlm_config?: Record<string, unknown>;
|
||||
@@ -73,6 +95,21 @@ export interface LlmWikiKnowledgeBase {
|
||||
is_conversation_deposit?: boolean;
|
||||
}
|
||||
|
||||
export interface LlmWikiEmbeddingModel {
|
||||
id: string;
|
||||
name: string;
|
||||
provider?: string | null;
|
||||
model_name?: string | null;
|
||||
status?: string | null;
|
||||
is_default: boolean;
|
||||
available: boolean;
|
||||
}
|
||||
|
||||
export interface LlmWikiEmbeddingModelsResponse {
|
||||
models: LlmWikiEmbeddingModel[];
|
||||
default_model_id?: string | null;
|
||||
}
|
||||
|
||||
export interface PublicLlmWikiKnowledgeBase extends LlmWikiKnowledgeBase {
|
||||
wiki: {
|
||||
status: "ready" | "empty" | "unavailable";
|
||||
@@ -94,7 +131,7 @@ export interface PublicLlmWikiKnowledgeBase extends LlmWikiKnowledgeBase {
|
||||
wiki_index_enabled: boolean;
|
||||
state: LlmWikiWikiIndexStatus["state"];
|
||||
fully_vectorized: boolean;
|
||||
retrieval_mode: "vector" | "wiki_api";
|
||||
retrieval_mode: LlmWikiRetrievalMode;
|
||||
remote_page_count: number;
|
||||
local_page_count: number;
|
||||
ready_page_count: number;
|
||||
@@ -137,6 +174,7 @@ export interface LlmWikiDocument {
|
||||
export interface LlmWikiChunk {
|
||||
id: string;
|
||||
content: string;
|
||||
snippet?: string;
|
||||
chunk_index: number;
|
||||
is_enabled: boolean;
|
||||
status?: number | string | null;
|
||||
@@ -223,6 +261,7 @@ export interface LlmWikiWikiIndex {
|
||||
|
||||
export interface LlmWikiWikiIndexStatus {
|
||||
knowledge_base_id: string;
|
||||
active_sync_id?: string | null;
|
||||
state:
|
||||
| "not_synced"
|
||||
| "idle"
|
||||
@@ -234,7 +273,7 @@ export interface LlmWikiWikiIndexStatus {
|
||||
local_index_enabled: boolean;
|
||||
wiki_index_enabled: boolean;
|
||||
fully_vectorized: boolean;
|
||||
retrieval_mode: "vector" | "wiki_api";
|
||||
retrieval_mode: LlmWikiRetrievalMode;
|
||||
local_page_count?: number;
|
||||
ready_page_count?: number;
|
||||
failed_page_count?: number;
|
||||
@@ -242,6 +281,9 @@ export interface LlmWikiWikiIndexStatus {
|
||||
last_error?: string | null;
|
||||
last_started_at?: string | null;
|
||||
last_completed_at?: string | null;
|
||||
last_sync?: LlmWikiIncrementalSyncSummary | null;
|
||||
/** Compatibility with stores that expose their persisted field directly. */
|
||||
last_sync_result?: LlmWikiIncrementalSyncSummary | null;
|
||||
progress?: {
|
||||
total_pages: number;
|
||||
processed_pages: number;
|
||||
@@ -266,8 +308,33 @@ export interface LlmWikiWikiIndexStatus {
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface LlmWikiIncrementalSyncSummary {
|
||||
sync_id: string;
|
||||
mode: "incremental" | "full";
|
||||
status: "accepted" | "running" | "completed" | "partial" | "failed" | string;
|
||||
remote_pages: number | null;
|
||||
added_pages: number | null;
|
||||
updated_pages: number | null;
|
||||
skipped_pages: number | null;
|
||||
deleted_pages: number | null;
|
||||
failed_pages: number | null;
|
||||
started_at?: string | null;
|
||||
completed_at?: string | null;
|
||||
}
|
||||
|
||||
export interface LlmWikiIncrementalSyncAccepted {
|
||||
job_id: string;
|
||||
status: "accepted";
|
||||
mode: "incremental";
|
||||
knowledge_base_id: string;
|
||||
status_url: string;
|
||||
}
|
||||
|
||||
export interface LocalWikiEncoderStatus {
|
||||
provider: string;
|
||||
configured_provider?: string | null;
|
||||
mode?: "configured" | "local";
|
||||
using_local?: boolean;
|
||||
model: string;
|
||||
dimensions?: number | null;
|
||||
state: "idle" | "starting" | "ready" | "failed";
|
||||
@@ -321,13 +388,15 @@ export interface LlmWikiSearchResult {
|
||||
score: number;
|
||||
}>;
|
||||
score: number;
|
||||
channel_score?: number | null;
|
||||
url: string;
|
||||
retrieval_mode?: "vector" | "wiki_api";
|
||||
retrieval_mode?: LlmWikiRetrievalMode;
|
||||
matched_queries?: string[];
|
||||
}
|
||||
|
||||
export interface LlmWikiSearchResponse {
|
||||
query: string;
|
||||
mode: "vector" | "wiki_api" | "mixed";
|
||||
mode: LlmWikiRetrievalMode;
|
||||
results: LlmWikiSearchResult[];
|
||||
knowledge_base_count: number;
|
||||
partial: boolean;
|
||||
@@ -335,6 +404,56 @@ export interface LlmWikiSearchResponse {
|
||||
fallback_knowledge_base_ids: string[];
|
||||
}
|
||||
|
||||
export interface LlmWikiRetrievalDebugRequest {
|
||||
query: string;
|
||||
knowledge_base_ids: string[];
|
||||
assistant_knowledge_base_ids: string[];
|
||||
}
|
||||
|
||||
export interface LlmWikiRetrievalDebugResult extends Record<string, unknown> {
|
||||
rank?: number;
|
||||
id?: string | null;
|
||||
kind?: string;
|
||||
knowledge_base_id?: string | null;
|
||||
knowledge_base_name?: string | null;
|
||||
title?: string | null;
|
||||
wiki_slug?: string | null;
|
||||
page_type?: string | null;
|
||||
matched_heading?: string | null;
|
||||
retrieval_mode?: LlmWikiRetrievalMode | string;
|
||||
rank_score?: number | null;
|
||||
rank_score_semantics?: string | null;
|
||||
provider_score?: number | null;
|
||||
score?: number | null;
|
||||
channel_score?: number | null;
|
||||
vector_score?: number | null;
|
||||
graph_score?: number | null;
|
||||
graph_hop?: number | null;
|
||||
graph_path?: Array<string | Record<string, unknown>>;
|
||||
snippet?: string;
|
||||
content?: string;
|
||||
url?: string;
|
||||
}
|
||||
|
||||
/** The debug endpoint is intentionally forward-compatible with new trace fields. */
|
||||
export interface LlmWikiRetrievalDebugResponse extends Record<string, unknown> {
|
||||
retrieval_trace_id?: string;
|
||||
query?: string;
|
||||
selected_spaces?: Array<Record<string, unknown>>;
|
||||
authorized_space_count?: number;
|
||||
mode?: LlmWikiRetrievalMode | string;
|
||||
source_count?: number;
|
||||
partial?: boolean;
|
||||
warnings?: string[];
|
||||
fallback_reason?: string | null;
|
||||
fallback_knowledge_base_ids?: string[];
|
||||
diagnostics?: Record<string, unknown>;
|
||||
timings_ms?: Record<string, unknown>;
|
||||
results?: LlmWikiRetrievalDebugResult[];
|
||||
zero_result_reason?: string | null;
|
||||
capabilities?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface LlmWikiWeKnoraEmbedSession {
|
||||
frame_path: string;
|
||||
expires_in: number;
|
||||
@@ -424,6 +543,17 @@ export async function getLlmWikiKnowledgeBase(
|
||||
);
|
||||
}
|
||||
|
||||
export async function listLlmWikiEmbeddingModels(): Promise<LlmWikiEmbeddingModelsResponse> {
|
||||
const payload = await readJson<LlmWikiEmbeddingModelsResponse>(
|
||||
await apiFetch(`${API()}/embedding-models`),
|
||||
"读取知识服务向量模型",
|
||||
);
|
||||
return {
|
||||
models: payload.models ?? [],
|
||||
default_model_id: payload.default_model_id ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export async function createLlmWikiWeKnoraEmbedSession(
|
||||
id: string,
|
||||
tab: "documents" | "wiki" | "graph",
|
||||
@@ -457,6 +587,8 @@ export async function createLlmWikiKnowledgeBase(input: {
|
||||
description: string;
|
||||
type: "document" | "faq";
|
||||
wiki_enabled?: boolean;
|
||||
embedding_model_id?: string;
|
||||
wiki_config?: LlmWikiWikiInstructions;
|
||||
}): Promise<LlmWikiKnowledgeBase> {
|
||||
return readJson(
|
||||
await apiFetch(`${API()}/knowledge-bases`, {
|
||||
@@ -470,7 +602,13 @@ export async function createLlmWikiKnowledgeBase(input: {
|
||||
|
||||
export async function updateLlmWikiKnowledgeBase(
|
||||
id: string,
|
||||
input: { name?: string; description?: string },
|
||||
input: {
|
||||
name?: string;
|
||||
description?: string;
|
||||
test_questions?: string[];
|
||||
retrieval_settings?: LlmWikiKnowledgeBase["retrieval_settings"];
|
||||
wiki_config?: LlmWikiWikiInstructions;
|
||||
},
|
||||
): Promise<LlmWikiKnowledgeBase> {
|
||||
return readJson(
|
||||
await apiFetch(`${API()}/knowledge-bases/${encodeURIComponent(id)}`, {
|
||||
@@ -482,6 +620,85 @@ export async function updateLlmWikiKnowledgeBase(
|
||||
);
|
||||
}
|
||||
|
||||
export interface LlmWikiRetrievalReference {
|
||||
reference_id: string;
|
||||
title?: string;
|
||||
knowledge_base_id: string;
|
||||
knowledge_base_name?: string;
|
||||
wiki_page_id?: string;
|
||||
wiki_slug?: string;
|
||||
url?: string;
|
||||
snippet?: string;
|
||||
}
|
||||
|
||||
export interface LlmWikiStatisticsItem {
|
||||
id: string;
|
||||
title: string;
|
||||
published_at?: string | null;
|
||||
date_source?: string | null;
|
||||
url?: string | null;
|
||||
document_id?: string | null;
|
||||
chunk_id?: string | null;
|
||||
knowledge_base_id: string;
|
||||
knowledge_base_name?: string;
|
||||
wiki_page_id?: string;
|
||||
wiki_slug?: string;
|
||||
wiki_page_title?: string;
|
||||
}
|
||||
|
||||
export interface LlmWikiKnowledgeBaseRetrievalDebugResponse {
|
||||
request_id: string;
|
||||
query: string;
|
||||
mode: string;
|
||||
query_plan: {
|
||||
subject_terms: string[];
|
||||
date_from?: string | null;
|
||||
date_to?: string | null;
|
||||
entity_expansion_enabled: boolean;
|
||||
expanded_terms: Array<{ term: string; relation: string; from_page: string }>;
|
||||
executed_queries: string[];
|
||||
};
|
||||
statistics?: {
|
||||
requested: boolean;
|
||||
unit: "source_document" | "wiki_page";
|
||||
unit_label: string;
|
||||
subject_terms: string[];
|
||||
date_from?: string | null;
|
||||
date_to?: string | null;
|
||||
matched_count: number;
|
||||
undated_excluded_count: number;
|
||||
items: LlmWikiStatisticsItem[];
|
||||
} | null;
|
||||
results: LlmWikiSearchResult[];
|
||||
references: LlmWikiRetrievalReference[];
|
||||
partial: boolean;
|
||||
warnings: string[];
|
||||
diagnostics: Array<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
export async function debugLlmWikiKnowledgeBaseRetrieval(
|
||||
knowledgeBaseId: string,
|
||||
input: {
|
||||
query: string;
|
||||
date_from?: string;
|
||||
date_to?: string;
|
||||
top_k?: number;
|
||||
expand_entities?: boolean;
|
||||
},
|
||||
): Promise<LlmWikiKnowledgeBaseRetrievalDebugResponse> {
|
||||
return readJson(
|
||||
await apiFetch(
|
||||
`${API()}/knowledge-bases/${encodeURIComponent(knowledgeBaseId)}/retrieval-debug`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(input),
|
||||
},
|
||||
),
|
||||
"调试知识库检索",
|
||||
);
|
||||
}
|
||||
|
||||
export async function deleteLlmWikiKnowledgeBase(id: string): Promise<void> {
|
||||
await readJson<void>(
|
||||
await apiFetch(`${API()}/knowledge-bases/${encodeURIComponent(id)}`, {
|
||||
@@ -606,10 +823,11 @@ export async function getLlmWikiWikiPage(
|
||||
|
||||
export async function getLlmWikiWikiIndexStatus(
|
||||
knowledgeBaseId: string,
|
||||
includePages = true,
|
||||
): Promise<LlmWikiWikiIndexStatus> {
|
||||
return readJson(
|
||||
await apiFetch(
|
||||
`${API()}/knowledge-bases/${encodeURIComponent(knowledgeBaseId)}/wiki-index-status`,
|
||||
`${API()}/knowledge-bases/${encodeURIComponent(knowledgeBaseId)}/wiki-index-status${includePages ? "" : "?include_pages=false"}`,
|
||||
),
|
||||
"读取 Wiki 向量化状态",
|
||||
);
|
||||
@@ -627,6 +845,18 @@ export async function vectorizeLlmWikiKnowledgeBase(
|
||||
);
|
||||
}
|
||||
|
||||
export async function syncLlmWikiKnowledgeBaseIncrementally(
|
||||
knowledgeBaseId: string,
|
||||
): Promise<LlmWikiIncrementalSyncAccepted> {
|
||||
return readJson(
|
||||
await apiFetch(
|
||||
`${API()}/knowledge-bases/${encodeURIComponent(knowledgeBaseId)}/sync`,
|
||||
{ method: "POST" },
|
||||
),
|
||||
"增量同步知识库",
|
||||
);
|
||||
}
|
||||
|
||||
export async function getLocalWikiEncoderStatus(): Promise<LocalWikiEncoderStatus> {
|
||||
return readJson(
|
||||
await apiFetch(`${API()}/local-encoder/status`),
|
||||
@@ -654,6 +884,13 @@ export async function configureLocalWikiEncoder(
|
||||
);
|
||||
}
|
||||
|
||||
export async function restoreConfiguredWikiEncoder(): Promise<LocalWikiEncoderStatus> {
|
||||
return readJson(
|
||||
await apiFetch(`${API()}/local-encoder/use-configured`, { method: "POST" }),
|
||||
"恢复配置文件编码器",
|
||||
);
|
||||
}
|
||||
|
||||
export async function uploadLocalWikiEncoder(
|
||||
files: File[],
|
||||
onProgress?: (percent: number) => void,
|
||||
@@ -688,10 +925,15 @@ export async function uploadLocalWikiEncoder(
|
||||
payload = null;
|
||||
}
|
||||
if (request.status < 200 || request.status >= 300) {
|
||||
const detail = payload && typeof payload === "object" && "detail" in payload
|
||||
const rawDetail = payload && typeof payload === "object" && "detail" in payload
|
||||
? (payload as { detail: unknown }).detail
|
||||
: `请求失败 (${request.status})`;
|
||||
reject(new Error(typeof detail === "string" ? detail : JSON.stringify(detail)));
|
||||
const detail = rawDetail && typeof rawDetail === "object" && "message" in rawDetail
|
||||
? String((rawDetail as { message: unknown }).message)
|
||||
: typeof rawDetail === "string"
|
||||
? rawDetail
|
||||
: JSON.stringify(rawDetail);
|
||||
reject(new Error(userFacingKnowledgeMessage(detail)));
|
||||
return;
|
||||
}
|
||||
onProgress?.(100);
|
||||
@@ -891,6 +1133,19 @@ export async function searchLlmWiki(input: {
|
||||
);
|
||||
}
|
||||
|
||||
export async function debugLlmWikiRetrieval(
|
||||
input: LlmWikiRetrievalDebugRequest,
|
||||
): Promise<LlmWikiRetrievalDebugResponse> {
|
||||
return readJson<LlmWikiRetrievalDebugResponse>(
|
||||
await apiFetch(`${API()}/retrieval-debug`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(input),
|
||||
}),
|
||||
"调试知识库检索",
|
||||
);
|
||||
}
|
||||
|
||||
export async function getPublicLlmWikiKnowledgeBase(
|
||||
id: string,
|
||||
): Promise<LlmWikiKnowledgeBase> {
|
||||
@@ -1026,7 +1281,13 @@ export function useLlmWikiKnowledgeBases(scope: LlmWikiScope, enabled = true) {
|
||||
queryKey: knowledgeBasesKey(userId, scope),
|
||||
queryFn: () => listLlmWikiKnowledgeBases(scope),
|
||||
enabled,
|
||||
refetchInterval: 15_000,
|
||||
staleTime: 30_000,
|
||||
refetchInterval: (query) =>
|
||||
(query.state.data ?? []).some(
|
||||
(item) => item.is_processing || item.processing_count > 0,
|
||||
)
|
||||
? 15_000
|
||||
: false,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1241,18 +1502,25 @@ export function usePublicLlmWikiWikiIndex(
|
||||
export function useLlmWikiWikiIndexStatus(
|
||||
knowledgeBaseId: string | null,
|
||||
enabled = true,
|
||||
options: {
|
||||
includePages?: boolean;
|
||||
fastPolling?: boolean;
|
||||
} = {},
|
||||
) {
|
||||
const { userId } = useLiveAccount();
|
||||
const includePages = options.includePages ?? true;
|
||||
return useQuery({
|
||||
queryKey: [
|
||||
"llmwiki",
|
||||
"wiki-index-status",
|
||||
knowledgeBaseId,
|
||||
userId ?? "anonymous",
|
||||
includePages ? "with-pages" : "summary-only",
|
||||
],
|
||||
queryFn: () => getLlmWikiWikiIndexStatus(knowledgeBaseId!),
|
||||
queryFn: () => getLlmWikiWikiIndexStatus(knowledgeBaseId!, includePages),
|
||||
enabled: enabled && !!knowledgeBaseId,
|
||||
refetchInterval: (query) => {
|
||||
if (options.fastPolling) return 1_500;
|
||||
const state = query.state.data?.state;
|
||||
return state === "running" || state === "rebuilding" ? 2_000 : 10_000;
|
||||
},
|
||||
@@ -1268,6 +1536,17 @@ export function useLlmWikiSettings(enabled = true) {
|
||||
});
|
||||
}
|
||||
|
||||
export function useLlmWikiEmbeddingModels(enabled = true) {
|
||||
const { userId } = useLiveAccount();
|
||||
return useQuery({
|
||||
queryKey: ["llmwiki", "embedding-models", userId ?? "anonymous"],
|
||||
queryFn: listLlmWikiEmbeddingModels,
|
||||
enabled,
|
||||
staleTime: 60_000,
|
||||
refetchOnMount: "always",
|
||||
});
|
||||
}
|
||||
|
||||
export function useLlmWikiActions() {
|
||||
const queryClient = useQueryClient();
|
||||
const invalidateKnowledge = () =>
|
||||
@@ -1285,8 +1564,27 @@ export function useLlmWikiActions() {
|
||||
id: string;
|
||||
name?: string;
|
||||
description?: string;
|
||||
test_questions?: string[];
|
||||
retrieval_settings?: LlmWikiKnowledgeBase["retrieval_settings"];
|
||||
wiki_config?: LlmWikiWikiInstructions;
|
||||
}) => updateLlmWikiKnowledgeBase(id, input),
|
||||
onSuccess: invalidateKnowledge,
|
||||
// Renaming a base only changes the base record. Writing the mutation
|
||||
// result through avoids making the edit dialog wait for the unrelated
|
||||
// documents, Wiki pages, graph, and settings requests under `llmwiki`.
|
||||
onSuccess: (updated) => {
|
||||
queryClient.setQueriesData<LlmWikiKnowledgeBase[]>(
|
||||
{ queryKey: ["llmwiki", "knowledge-bases"] },
|
||||
(current) =>
|
||||
current?.map((base) =>
|
||||
base.id === updated.id ? { ...base, ...updated } : base,
|
||||
),
|
||||
);
|
||||
queryClient.setQueriesData<LlmWikiKnowledgeBase>(
|
||||
{ queryKey: ["llmwiki", "knowledge-base", updated.id] },
|
||||
(current) =>
|
||||
current?.id === updated.id ? { ...current, ...updated } : current,
|
||||
);
|
||||
},
|
||||
}),
|
||||
remove: useMutation({
|
||||
mutationFn: deleteLlmWikiKnowledgeBase,
|
||||
@@ -1355,6 +1653,14 @@ export function useLlmWikiActions() {
|
||||
mutationFn: ({ id }: { id: string }) => vectorizeLlmWikiKnowledgeBase(id),
|
||||
onSuccess: invalidateKnowledge,
|
||||
}),
|
||||
syncIncremental: useMutation({
|
||||
mutationFn: ({ id }: { id: string }) =>
|
||||
syncLlmWikiKnowledgeBaseIncrementally(id),
|
||||
onSuccess: (_result, { id }) =>
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["llmwiki", "wiki-index-status", id],
|
||||
}),
|
||||
}),
|
||||
exportWikiExcel: useMutation({
|
||||
mutationFn: ({ id, name }: { id: string; name?: string }) =>
|
||||
exportLlmWikiWikiExcel(id, name),
|
||||
|
||||
@@ -2,13 +2,15 @@
|
||||
* 菜单覆盖层(菜单管理)API 客户端 + React Query hooks。
|
||||
*
|
||||
* 后端:`/api/menu-overrides`(见 app/gateway/routers/menu_overrides.py)。
|
||||
* 全局共享、无用户隔离;读对所有登录用户开放(侧边栏要用),写仅 admin(整体替换)。
|
||||
* 管理员维护默认菜单,普通用户维护自己的菜单快照;后端返回当前账号的生效配置,
|
||||
* 并让个人快照中尚不存在的新节点继续继承管理员默认值。
|
||||
* snake_case ⇄ camelCase 在此边界收敛。
|
||||
*/
|
||||
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
import { apiFetch } from "@/core/api/fetch-client";
|
||||
import { getAccountIdentityKey, getStoredAuth } from "@/core/auth";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
import { OptType, writeYLog } from "@/core/log/y-log";
|
||||
import type { MenuOverride } from "@/core/page-layout/menu-overrides";
|
||||
@@ -23,6 +25,30 @@ interface ServerOverride {
|
||||
disabled: boolean;
|
||||
}
|
||||
|
||||
interface ServerMenuOverrideConfig {
|
||||
overrides?: ServerOverride[];
|
||||
default_overrides?: ServerOverride[];
|
||||
user_overrides?: ServerOverride[];
|
||||
has_user_override?: boolean;
|
||||
editable_scope?: "default" | "user";
|
||||
}
|
||||
|
||||
interface ServerMenuHierarchyNode {
|
||||
node_id: string;
|
||||
parent_id: string | null;
|
||||
}
|
||||
|
||||
export interface MenuOverrideConfig {
|
||||
/** 当前账号最终生效的覆盖项。侧边栏只消费这一层。 */
|
||||
overrides: MenuOverride[];
|
||||
/** 管理员维护的默认覆盖项。 */
|
||||
defaultOverrides: MenuOverride[];
|
||||
/** 当前普通用户已保存的完整菜单快照;管理员恒为空。 */
|
||||
userOverrides: MenuOverride[];
|
||||
hasUserOverride: boolean;
|
||||
editableScope: "default" | "user";
|
||||
}
|
||||
|
||||
function toOverride(s: ServerOverride): MenuOverride {
|
||||
return {
|
||||
nodeId: s.node_id,
|
||||
@@ -55,26 +81,58 @@ async function readJson<T>(res: Response, ctx: string): Promise<T> {
|
||||
return (await res.json()) as T;
|
||||
}
|
||||
|
||||
export async function listMenuOverrides(): Promise<MenuOverride[]> {
|
||||
const res = await apiFetch(BASE(), { method: "GET" });
|
||||
const data = await readJson<{ overrides: ServerOverride[] }>(res, "list menu overrides");
|
||||
return (data.overrides ?? []).map(toOverride);
|
||||
function toConfig(data: ServerMenuOverrideConfig): MenuOverrideConfig {
|
||||
const effective = (data.overrides ?? []).map(toOverride);
|
||||
const auth = getStoredAuth();
|
||||
// Auth-disabled deployments have no stored account and historically expose
|
||||
// the shared administrator configuration.
|
||||
const fallbackScope = !auth || auth.system_role === "admin" ? "default" : "user";
|
||||
return {
|
||||
overrides: effective,
|
||||
// 兼容滚动升级期间的旧后端:旧响应只有 overrides,视作默认配置。
|
||||
defaultOverrides: (data.default_overrides ?? data.overrides ?? []).map(toOverride),
|
||||
userOverrides: (data.user_overrides ?? []).map(toOverride),
|
||||
hasUserOverride: data.has_user_override ?? false,
|
||||
editableScope: data.editable_scope ?? fallbackScope,
|
||||
};
|
||||
}
|
||||
|
||||
export async function replaceMenuOverrides(overrides: MenuOverride[]): Promise<MenuOverride[]> {
|
||||
export async function listMenuOverrides(): Promise<MenuOverrideConfig> {
|
||||
const res = await apiFetch(BASE(), { method: "GET" });
|
||||
const data = await readJson<ServerMenuOverrideConfig>(res, "list menu overrides");
|
||||
return toConfig(data);
|
||||
}
|
||||
|
||||
export interface MenuOverrideSaveInput {
|
||||
overrides: MenuOverride[];
|
||||
/** Complete effective parent graph; the backend uses it only to validate depth. */
|
||||
hierarchy: MenuOverride[];
|
||||
}
|
||||
|
||||
export async function replaceMenuOverrides({
|
||||
overrides,
|
||||
hierarchy,
|
||||
}: MenuOverrideSaveInput): Promise<MenuOverrideConfig> {
|
||||
const hierarchyBody: ServerMenuHierarchyNode[] = hierarchy.map((item) => ({
|
||||
node_id: item.nodeId,
|
||||
parent_id: item.parentId ?? null,
|
||||
}));
|
||||
const res = await apiFetch(BASE(), {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ overrides: overrides.map(toBody) }),
|
||||
body: JSON.stringify({
|
||||
overrides: overrides.map(toBody),
|
||||
hierarchy: hierarchyBody,
|
||||
}),
|
||||
});
|
||||
const data = await readJson<{ overrides: ServerOverride[] }>(res, "save menu overrides");
|
||||
const saved = (data.overrides ?? []).map(toOverride);
|
||||
const data = await readJson<ServerMenuOverrideConfig>(res, "save menu overrides");
|
||||
const saved = toConfig(data);
|
||||
writeYLog({
|
||||
optType: OptType.edit,
|
||||
optDetail: "CM助手-全量-菜单管理-保存",
|
||||
url: "/api/menu-overrides",
|
||||
reqParam: { overrides },
|
||||
returnParam: saved,
|
||||
returnParam: saved.overrides,
|
||||
});
|
||||
return saved;
|
||||
}
|
||||
@@ -84,20 +142,26 @@ export async function replaceMenuOverrides(overrides: MenuOverride[]): Promise<M
|
||||
const MENU_OVERRIDES_KEY = "menu-overrides";
|
||||
|
||||
export function useMenuOverrides() {
|
||||
const accountKey = getAccountIdentityKey() ?? "anonymous";
|
||||
return useQuery({
|
||||
queryKey: [MENU_OVERRIDES_KEY],
|
||||
queryKey: [MENU_OVERRIDES_KEY, accountKey],
|
||||
queryFn: listMenuOverrides,
|
||||
refetchOnWindowFocus: false,
|
||||
staleTime: 60_000,
|
||||
// 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,
|
||||
});
|
||||
}
|
||||
|
||||
export function useMenuOverrideActions() {
|
||||
const queryClient = useQueryClient();
|
||||
const accountKey = getAccountIdentityKey() ?? "anonymous";
|
||||
return {
|
||||
save: useMutation({
|
||||
mutationFn: replaceMenuOverrides,
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: [MENU_OVERRIDES_KEY] }),
|
||||
onSuccess: () =>
|
||||
queryClient.invalidateQueries({ queryKey: [MENU_OVERRIDES_KEY, accountKey] }),
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -10,6 +10,13 @@ import {
|
||||
X,
|
||||
} from 'lucide-react';
|
||||
import { Dialog, DialogPlugin, Select, Slider } from 'tdesign-react';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from '@/components/ui/sheet';
|
||||
import { useTheme } from '@/contexts/ThemeContext';
|
||||
import { ChatMessage, EmptyChatState, QAAvatar, QAComposer, QASingleRagTrace, QAThinkingRound, QAThinkingTrace, RetrievalThinkingTrace, SingleRagAnswer, TypingIndicator } from './QACommon';
|
||||
import GeneralQAHeader from './GeneralQAHeader';
|
||||
@@ -114,6 +121,7 @@ const GeneralQA: React.FC<{
|
||||
const [weknoraDrawer, setWeknoraDrawer] = useState<{
|
||||
target: WeKnoraSourceTarget;
|
||||
title: string;
|
||||
quote: string;
|
||||
} | null>(null);
|
||||
const [editingMessageId, setEditingMessageId] = useState<string | null>(null);
|
||||
const [editingThinking, setEditingThinking] = useState('');
|
||||
@@ -2364,74 +2372,71 @@ const GeneralQA: React.FC<{
|
||||
</div>
|
||||
)}
|
||||
|
||||
{selectedCitation && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-4">
|
||||
<div
|
||||
className="absolute inset-0 bg-black/45 backdrop-blur-[1px]"
|
||||
onClick={() => setSelectedCitation(null)}
|
||||
/>
|
||||
<div className={`relative w-full max-w-xl rounded-2xl border shadow-2xl p-5 ${isDark
|
||||
? 'bg-slate-900 border-slate-700 text-slate-100'
|
||||
: 'bg-white border-gray-200 text-gray-900'
|
||||
}`}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setSelectedCitation(null)}
|
||||
className={`absolute top-3 right-3 p-1.5 rounded-lg transition-all ${isDark ? 'hover:bg-slate-700 text-slate-300' : 'hover:bg-gray-100 text-gray-500'
|
||||
}`}
|
||||
title="关闭"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
|
||||
<div className="pr-9">
|
||||
<h3 className="text-base font-semibold">{selectedCitation.title || '引用内容'}</h3>
|
||||
<div className={`mt-2 text-xs space-y-1 ${isDark ? 'text-slate-400' : 'text-gray-500'}`}>
|
||||
<div>来源:{selectedCitation.source || selectedCitation.type || '未知来源'}</div>
|
||||
<div>时间:{selectedCitation.time || '未知'}</div>
|
||||
<Sheet
|
||||
open={!!selectedCitation}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setSelectedCitation(null);
|
||||
}}
|
||||
>
|
||||
<SheetContent
|
||||
side="right"
|
||||
className="w-[min(92vw,760px)] gap-0 overflow-hidden p-0 sm:max-w-none"
|
||||
>
|
||||
<SheetHeader className="shrink-0 border-b px-5 py-4 pr-12 text-left">
|
||||
<SheetTitle className="text-base leading-relaxed">
|
||||
{selectedCitation?.title || '引用内容'}
|
||||
</SheetTitle>
|
||||
<SheetDescription className="space-y-1 text-xs">
|
||||
<span className="block">来源:{selectedCitation?.source || selectedCitation?.type || '未知来源'}</span>
|
||||
<span className="block">时间:{selectedCitation?.time || '未知'}</span>
|
||||
</SheetDescription>
|
||||
</SheetHeader>
|
||||
{selectedCitation && (
|
||||
<div className={`min-h-0 flex-1 overflow-y-auto p-4 sm:p-6 ${isDark ? 'bg-slate-950/60' : 'bg-gray-50/70'}`}>
|
||||
<div className="mx-auto max-w-3xl space-y-4">
|
||||
{(selectedCitation.url || resolveWeKnoraSourceTarget(selectedCitation)) && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const weknoraTarget = resolveWeKnoraSourceTarget(selectedCitation);
|
||||
if (weknoraTarget) {
|
||||
setWeknoraDrawer({
|
||||
target: weknoraTarget,
|
||||
title: selectedCitation.title || '参考文献原文',
|
||||
quote: selectedCitation.content || selectedCitation.snippet || '',
|
||||
});
|
||||
setSelectedCitation(null);
|
||||
} else {
|
||||
void openKnowledgeSource(selectedCitation);
|
||||
}
|
||||
}}
|
||||
className={`inline-flex items-center gap-2 rounded-lg border px-3 py-1.5 text-sm transition-all ${isDark
|
||||
? 'border-slate-600 bg-slate-900 text-slate-200 hover:bg-slate-800'
|
||||
: 'border-gray-300 bg-white text-gray-700 hover:bg-gray-50'
|
||||
}`}
|
||||
title="打开原始链接"
|
||||
>
|
||||
<ExternalLink className="w-4 h-4" />
|
||||
查看原文链接
|
||||
</button>
|
||||
)}
|
||||
<article className={`rounded-xl border p-4 text-sm leading-7 whitespace-pre-wrap shadow-sm ${isDark
|
||||
? 'border-slate-700 bg-slate-900 text-slate-200'
|
||||
: 'border-gray-200 bg-white text-gray-700'
|
||||
}`}>
|
||||
{selectedCitation.content || selectedCitation.snippet || '暂无引用内容'}
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{(selectedCitation.url || resolveWeKnoraSourceTarget(selectedCitation)) && (
|
||||
<div className="mt-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const weknoraTarget = resolveWeKnoraSourceTarget(selectedCitation);
|
||||
if (weknoraTarget) {
|
||||
setWeknoraDrawer({
|
||||
target: weknoraTarget,
|
||||
title: selectedCitation.title || '参考文献原文',
|
||||
});
|
||||
setSelectedCitation(null);
|
||||
} else {
|
||||
void openKnowledgeSource(selectedCitation);
|
||||
}
|
||||
}}
|
||||
className={`inline-flex items-center gap-2 px-3 py-1.5 rounded-lg border text-sm transition-all ${isDark
|
||||
? 'border-slate-600 text-slate-200 hover:bg-slate-800'
|
||||
: 'border-gray-300 text-gray-700 hover:bg-gray-50'
|
||||
}`}
|
||||
title="打开原始链接"
|
||||
>
|
||||
<ExternalLink className="w-4 h-4" />
|
||||
查看原文链接
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={`mt-4 rounded-xl p-3 text-sm leading-relaxed max-h-[500px] overflow-auto pr-[10px] whitespace-pre-wrap ${isDark ? 'bg-slate-800/70 text-slate-200' : 'bg-gray-50 text-gray-700'
|
||||
}`}>
|
||||
{selectedCitation.content || selectedCitation.snippet || '暂无引用内容'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
)}
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
|
||||
<WeKnoraSourceDrawer
|
||||
open={!!weknoraDrawer}
|
||||
target={weknoraDrawer?.target ?? null}
|
||||
title={weknoraDrawer?.title}
|
||||
quote={weknoraDrawer?.quote}
|
||||
onOpenChange={(nextOpen) => {
|
||||
if (!nextOpen) setWeknoraDrawer(null);
|
||||
}}
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Dialog, Textarea } from 'tdesign-react';
|
||||
import { Textarea } from 'tdesign-react';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from '@/components/ui/sheet';
|
||||
import {
|
||||
Bookmark,
|
||||
BrainCircuit,
|
||||
@@ -256,14 +263,17 @@ export function ChatMessage<T extends QACommonMessage>({
|
||||
const [weknoraDrawer, setWeknoraDrawer] = useState<{
|
||||
target: WeKnoraSourceTarget;
|
||||
title: string;
|
||||
quote: string;
|
||||
} | null>(null);
|
||||
const showDialog = (item: SourceItem) => {
|
||||
console.log('item', item)
|
||||
const weknoraTarget = resolveWeKnoraSourceTarget(item);
|
||||
if (weknoraTarget) {
|
||||
setWeknoraDrawer({ target: weknoraTarget, title: item.title || '参考文献原文' });
|
||||
} else if (item.url) {
|
||||
openKnowledgeSource(item);
|
||||
setWeknoraDrawer({
|
||||
target: weknoraTarget,
|
||||
title: item.title || '参考文献原文',
|
||||
quote: item.content || item.snippet || '',
|
||||
});
|
||||
} else {
|
||||
setListData(item);
|
||||
setVisible(true);
|
||||
@@ -355,28 +365,33 @@ export function ChatMessage<T extends QACommonMessage>({
|
||||
</div>
|
||||
</CollapsibleSection>
|
||||
)}
|
||||
<Dialog
|
||||
visible={visible}
|
||||
onClose={() => setVisible(false)}
|
||||
header="提示"
|
||||
footer={null}
|
||||
>
|
||||
<div>
|
||||
<div className="pr-9">
|
||||
<h3 className="text-base font-semibold">{listData.title || '引用内容'}</h3>
|
||||
<div className={`mt-2 text-xs space-y-1 ${isDark ? 'text-slate-400' : 'text-gray-500'}`}>
|
||||
<div>来源:{listData.source || '未知来源'}</div>
|
||||
<div>时间:{listData.time || '未知'}</div>
|
||||
</div>
|
||||
</div>
|
||||
{(listData.url || resolveWeKnoraSourceTarget(listData)) && (
|
||||
<div className="mt-4">
|
||||
<Sheet open={visible} onOpenChange={setVisible}>
|
||||
<SheetContent
|
||||
side="right"
|
||||
className="w-[min(92vw,760px)] gap-0 overflow-hidden p-0 sm:max-w-none"
|
||||
>
|
||||
<SheetHeader className="shrink-0 border-b px-5 py-4 pr-12 text-left">
|
||||
<SheetTitle className="text-base leading-relaxed">
|
||||
{listData.title || '引用内容'}
|
||||
</SheetTitle>
|
||||
<SheetDescription className="space-y-1 text-xs">
|
||||
<span className="block">来源:{listData.source || '未知来源'}</span>
|
||||
<span className="block">时间:{listData.time || '未知'}</span>
|
||||
</SheetDescription>
|
||||
</SheetHeader>
|
||||
<div className={`min-h-0 flex-1 overflow-y-auto p-4 sm:p-6 ${isDark ? 'bg-slate-950/60' : 'bg-gray-50/70'}`}>
|
||||
<div className="mx-auto max-w-3xl space-y-4">
|
||||
{(listData.url || resolveWeKnoraSourceTarget(listData)) && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const weknoraTarget = resolveWeKnoraSourceTarget(listData);
|
||||
if (weknoraTarget) {
|
||||
setWeknoraDrawer({ target: weknoraTarget, title: listData.title || '参考文献原文' });
|
||||
setWeknoraDrawer({
|
||||
target: weknoraTarget,
|
||||
title: listData.title || '参考文献原文',
|
||||
quote: listData.content || listData.snippet || '',
|
||||
});
|
||||
setVisible(false);
|
||||
} else {
|
||||
void openKnowledgeSource(listData);
|
||||
@@ -391,18 +406,22 @@ export function ChatMessage<T extends QACommonMessage>({
|
||||
<ExternalLink className="w-4 h-4" />
|
||||
查看原文链接
|
||||
</button>
|
||||
)}
|
||||
<article className={`rounded-xl border p-4 text-sm leading-7 whitespace-pre-wrap shadow-sm ${isDark
|
||||
? 'border-slate-700 bg-slate-900 text-slate-200'
|
||||
: 'border-gray-200 bg-white text-gray-700'
|
||||
}`}>
|
||||
{listData.content || listData.snippet || '暂无引用内容'}
|
||||
</article>
|
||||
</div>
|
||||
)}
|
||||
<div className={`mt-4 rounded-xl p-3 text-sm leading-relaxed whitespace-pre-wrap ${isDark ? 'bg-slate-800/70 text-slate-200' : 'bg-gray-50 text-gray-700'
|
||||
}`}>
|
||||
{listData.content || '暂无引用内容'}
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
<WeKnoraSourceDrawer
|
||||
open={!!weknoraDrawer}
|
||||
target={weknoraDrawer?.target ?? null}
|
||||
title={weknoraDrawer?.title}
|
||||
quote={weknoraDrawer?.quote}
|
||||
onOpenChange={(nextOpen) => {
|
||||
if (!nextOpen) setWeknoraDrawer(null);
|
||||
}}
|
||||
@@ -620,27 +639,31 @@ const RetrievalList: React.FC<RetrievalListProps> = ({ items }) => {
|
||||
}
|
||||
</div>
|
||||
))}
|
||||
<Dialog
|
||||
visible={visible}
|
||||
onClose={() => setVisible(false)}
|
||||
header="提示"
|
||||
footer={null}
|
||||
>
|
||||
<div>
|
||||
<div className="pr-9">
|
||||
<h3 className="text-base font-semibold">{listData.title}</h3>
|
||||
<div className={`mt-2 text-xs space-y-1 ${isDark ? 'text-slate-400' : 'text-gray-500'}`}>
|
||||
{listData.time && <span>时间:{listData.time || '未知'}</span>}
|
||||
{listData.platform && <span className="ml-[10px]">平台:{listData.platform || '未知'}</span>}
|
||||
{listData.comment_count && <span className="ml-[10px]">评论数:{listData.comment_count || '未知'}</span>}
|
||||
</div>
|
||||
<Sheet open={visible} onOpenChange={setVisible}>
|
||||
<SheetContent
|
||||
side="right"
|
||||
className="w-[min(92vw,760px)] gap-0 overflow-hidden p-0 sm:max-w-none"
|
||||
>
|
||||
<SheetHeader className="shrink-0 border-b px-5 py-4 pr-12 text-left">
|
||||
<SheetTitle className="text-base leading-relaxed">
|
||||
{listData.title || '检索结果'}
|
||||
</SheetTitle>
|
||||
<SheetDescription className="flex flex-wrap items-center gap-2 text-xs">
|
||||
{listData.time && <span>时间:{listData.time}</span>}
|
||||
{listData.platform && <span>平台:{listData.platform}</span>}
|
||||
{listData.comment_count && <span>评论数:{listData.comment_count}</span>}
|
||||
</SheetDescription>
|
||||
</SheetHeader>
|
||||
<div className={`min-h-0 flex-1 overflow-y-auto p-4 sm:p-6 ${isDark ? 'bg-slate-950/60' : 'bg-gray-50/70'}`}>
|
||||
<article className={`mx-auto max-w-3xl rounded-xl border p-4 text-sm leading-7 whitespace-pre-wrap shadow-sm ${isDark
|
||||
? 'border-slate-700 bg-slate-900 text-slate-200'
|
||||
: 'border-gray-200 bg-white text-gray-700'
|
||||
}`}>
|
||||
{listData.content || '暂无引用内容'}
|
||||
</article>
|
||||
</div>
|
||||
<div className={`mt-4 rounded-xl p-3 text-sm leading-relaxed whitespace-pre-wrap ${isDark ? 'bg-slate-800/70 text-slate-200' : 'bg-gray-50 text-gray-700'
|
||||
}`}>
|
||||
{listData.content || '暂无引用内容'}
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
+354
@@ -0,0 +1,354 @@
|
||||
import { CircleAlert, CircleCheck, Loader2, RefreshCw } from "lucide-react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import {
|
||||
type LlmWikiIncrementalSyncSummary,
|
||||
useLlmWikiActions,
|
||||
useLlmWikiWikiIndexStatus,
|
||||
} from "@/strategy-components/api/llmwiki";
|
||||
|
||||
const RUNNING_STATES = new Set(["accepted", "running", "rebuilding"]);
|
||||
const TERMINAL_STATES = new Set(["completed", "partial", "failed"]);
|
||||
|
||||
function isRunningState(value?: string | null) {
|
||||
return RUNNING_STATES.has(String(value || "").toLowerCase());
|
||||
}
|
||||
|
||||
function countText(value?: number | null) {
|
||||
return typeof value === "number" && Number.isFinite(value)
|
||||
? String(value)
|
||||
: "—";
|
||||
}
|
||||
|
||||
function formatTime(value?: string | null) {
|
||||
if (!value) return "";
|
||||
const date = new Date(value);
|
||||
return Number.isNaN(date.getTime())
|
||||
? value
|
||||
: date.toLocaleString("zh-CN", { hour12: false });
|
||||
}
|
||||
|
||||
function statusLabel(value?: string | null) {
|
||||
const normalized = String(value || "").toLowerCase();
|
||||
if (normalized === "accepted") return "等待执行";
|
||||
if (normalized === "running") return "同步中";
|
||||
if (normalized === "rebuilding") return "同步中";
|
||||
if (normalized === "completed" || normalized === "idle") return "已完成";
|
||||
if (normalized === "partial") return "部分完成";
|
||||
if (normalized === "failed") return "同步失败";
|
||||
if (normalized === "not_synced") return "尚未同步";
|
||||
return value || "等待同步";
|
||||
}
|
||||
|
||||
function resultMessage(summary?: LlmWikiIncrementalSyncSummary | null) {
|
||||
if (!summary) return "增量同步已结束,请查看最新知识库内容。";
|
||||
return [
|
||||
`新增 ${countText(summary.added_pages)}`,
|
||||
`修改 ${countText(summary.updated_pages)}`,
|
||||
`跳过 ${countText(summary.skipped_pages)}`,
|
||||
`失败 ${countText(summary.failed_pages)}`,
|
||||
].join(",");
|
||||
}
|
||||
|
||||
export function WeKnoraIncrementalSync({
|
||||
knowledgeBaseId,
|
||||
disabled = false,
|
||||
}: {
|
||||
knowledgeBaseId: string;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
const queryClient = useQueryClient();
|
||||
const actions = useLlmWikiActions();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [watching, setWatching] = useState(false);
|
||||
const syncStatus = useLlmWikiWikiIndexStatus(
|
||||
knowledgeBaseId || null,
|
||||
!!knowledgeBaseId,
|
||||
{ includePages: false, fastPolling: watching },
|
||||
);
|
||||
const baselineSyncId = useRef<string | null>(null);
|
||||
const observedRunning = useRef(false);
|
||||
const launchLocked = useRef(false);
|
||||
|
||||
const lastSync =
|
||||
syncStatus.data?.last_sync ?? syncStatus.data?.last_sync_result;
|
||||
const indexRunning = isRunningState(syncStatus.data?.state);
|
||||
const summaryRunning = isRunningState(lastSync?.status);
|
||||
const serverRunning = indexRunning || summaryRunning;
|
||||
const summaryIsCurrent =
|
||||
!watching || (!!lastSync?.sync_id && lastSync.sync_id !== baselineSyncId.current);
|
||||
const summaryBelongsToActiveRun =
|
||||
!serverRunning ||
|
||||
summaryRunning ||
|
||||
(!!syncStatus.data?.active_sync_id &&
|
||||
lastSync?.sync_id === syncStatus.data.active_sync_id);
|
||||
const displayedSummary =
|
||||
summaryIsCurrent &&
|
||||
summaryBelongsToActiveRun &&
|
||||
lastSync?.mode === "incremental"
|
||||
? lastSync
|
||||
: null;
|
||||
const busy = actions.syncIncremental.isPending || watching || serverRunning;
|
||||
const progress = syncStatus.data?.progress;
|
||||
const progressValue = serverRunning
|
||||
? progress?.completion_percent ?? 0
|
||||
: watching
|
||||
? 0
|
||||
: progress?.completion_percent ?? (displayedSummary ? 100 : 0);
|
||||
|
||||
const refreshKnowledgeViews = () => {
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: ["llmwiki", "knowledge-base", knowledgeBaseId],
|
||||
});
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: ["llmwiki", "wiki-pages", knowledgeBaseId],
|
||||
});
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: ["llmwiki", "wiki-page", knowledgeBaseId],
|
||||
});
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: ["public-llmwiki", "knowledge-base", knowledgeBaseId],
|
||||
});
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: ["public-llmwiki", "wiki-pages", knowledgeBaseId],
|
||||
});
|
||||
};
|
||||
|
||||
const startSync = async () => {
|
||||
setOpen(true);
|
||||
if (
|
||||
launchLocked.current ||
|
||||
watching ||
|
||||
serverRunning ||
|
||||
actions.syncIncremental.isPending
|
||||
) {
|
||||
return;
|
||||
}
|
||||
launchLocked.current = true;
|
||||
baselineSyncId.current = lastSync?.sync_id ?? null;
|
||||
observedRunning.current = false;
|
||||
try {
|
||||
await actions.syncIncremental.mutateAsync({ id: knowledgeBaseId });
|
||||
setWatching(true);
|
||||
toast.success("已启动当前知识库的增量同步");
|
||||
void syncStatus.refetch();
|
||||
} catch (error) {
|
||||
launchLocked.current = false;
|
||||
const message = error instanceof Error ? error.message : "启动增量同步失败";
|
||||
toast.error(message);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!watching) return;
|
||||
const currentLastSync =
|
||||
syncStatus.data?.last_sync ?? syncStatus.data?.last_sync_result;
|
||||
const currentlyRunning =
|
||||
isRunningState(syncStatus.data?.state) ||
|
||||
isRunningState(currentLastSync?.status);
|
||||
if (currentlyRunning) {
|
||||
observedRunning.current = true;
|
||||
return;
|
||||
}
|
||||
const hasNewSummary =
|
||||
!!currentLastSync?.sync_id &&
|
||||
currentLastSync.sync_id !== baselineSyncId.current;
|
||||
const terminalSummary = TERMINAL_STATES.has(
|
||||
String(currentLastSync?.status || "").toLowerCase(),
|
||||
);
|
||||
const terminalIndexState = ["idle", "partial", "failed"].includes(
|
||||
String(syncStatus.data?.state || "").toLowerCase(),
|
||||
);
|
||||
if (
|
||||
(hasNewSummary && terminalSummary) ||
|
||||
(observedRunning.current && terminalIndexState)
|
||||
) {
|
||||
launchLocked.current = false;
|
||||
setWatching(false);
|
||||
refreshKnowledgeViews();
|
||||
if (
|
||||
currentLastSync?.status === "failed" ||
|
||||
syncStatus.data?.state === "failed"
|
||||
) {
|
||||
toast.error(syncStatus.data?.last_error || "知识库增量同步失败");
|
||||
} else if (currentLastSync?.status === "partial") {
|
||||
toast.warning(`增量同步部分完成:${resultMessage(currentLastSync)}`);
|
||||
} else {
|
||||
toast.success(`增量同步完成:${resultMessage(currentLastSync)}`);
|
||||
}
|
||||
}
|
||||
}, [knowledgeBaseId, queryClient, syncStatus.data, watching]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!watching) return;
|
||||
const timeout = window.setTimeout(() => {
|
||||
launchLocked.current = false;
|
||||
setWatching(false);
|
||||
toast.warning("同步耗时较长,任务仍会在后台继续,可稍后查看同步结果");
|
||||
}, 10 * 60 * 1_000);
|
||||
return () => window.clearTimeout(timeout);
|
||||
}, [watching]);
|
||||
|
||||
const currentStatus =
|
||||
watching && !serverRunning
|
||||
? "accepted"
|
||||
: serverRunning
|
||||
? indexRunning
|
||||
? syncStatus.data?.state
|
||||
: lastSync?.status || "running"
|
||||
: displayedSummary?.status || syncStatus.data?.state;
|
||||
const resultIconFailed =
|
||||
displayedSummary?.status === "failed" ||
|
||||
displayedSummary?.status === "partial";
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={disabled || !knowledgeBaseId || actions.syncIncremental.isPending}
|
||||
onClick={() => void startSync()}
|
||||
title="只更新新增和已修改的 Wiki 内容,未变化内容会跳过"
|
||||
>
|
||||
{busy ? (
|
||||
<Loader2 className="mr-2 size-4 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw className="mr-2 size-4" />
|
||||
)}
|
||||
{busy ? "增量同步中" : "增量同步"}
|
||||
</Button>
|
||||
{displayedSummary && !serverRunning && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => setOpen(true)}
|
||||
aria-label="查看上次增量同步结果"
|
||||
title="查看上次增量同步结果"
|
||||
>
|
||||
{resultIconFailed ? (
|
||||
<CircleAlert className="size-4 text-amber-600" />
|
||||
) : (
|
||||
<CircleCheck className="size-4 text-emerald-600" />
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogContent className="sm:max-w-xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>当前知识库增量同步</DialogTitle>
|
||||
<DialogDescription>
|
||||
只为新增或内容已修改的 Wiki 页面更新镜像与向量;未变化页面直接跳过,不执行整库重建。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 py-2">
|
||||
<div className="rounded-xl border bg-muted/20 p-4">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-2 text-sm font-medium">
|
||||
{busy && <Loader2 className="size-4 animate-spin text-primary" />}
|
||||
同步状态
|
||||
</div>
|
||||
<Badge
|
||||
variant={
|
||||
currentStatus === "failed" || currentStatus === "partial"
|
||||
? "destructive"
|
||||
: "secondary"
|
||||
}
|
||||
>
|
||||
{statusLabel(currentStatus)}
|
||||
</Badge>
|
||||
</div>
|
||||
{(busy || progress) && (
|
||||
<>
|
||||
<Progress value={progressValue} className="mt-3 h-2" />
|
||||
<div className="mt-2 flex justify-between text-xs text-muted-foreground">
|
||||
<span>
|
||||
{serverRunning
|
||||
? `已检查 ${progress?.processed_pages ?? 0}/${progress?.total_pages ?? 0} 页`
|
||||
: watching
|
||||
? "正在等待服务端开始任务"
|
||||
: "最近一次同步进度"}
|
||||
</span>
|
||||
<span className="tabular-nums">{progressValue}%</span>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{displayedSummary ? (
|
||||
<>
|
||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
|
||||
{[
|
||||
["新增", displayedSummary.added_pages, "text-emerald-600"],
|
||||
["修改", displayedSummary.updated_pages, "text-blue-600"],
|
||||
["跳过", displayedSummary.skipped_pages, "text-muted-foreground"],
|
||||
["失败", displayedSummary.failed_pages, "text-destructive"],
|
||||
].map(([label, value, color]) => (
|
||||
<div key={String(label)} className="rounded-xl border bg-card p-3 text-center">
|
||||
<div className={`text-2xl font-semibold tabular-nums ${color}`}>
|
||||
{countText(value as number | null)}
|
||||
</div>
|
||||
<div className="mt-1 text-xs text-muted-foreground">{label}页面</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted-foreground">
|
||||
<span>远端页面 {countText(displayedSummary.remote_pages)}</span>
|
||||
<span>已删除 {countText(displayedSummary.deleted_pages)}</span>
|
||||
{formatTime(displayedSummary.started_at) && (
|
||||
<span>开始于 {formatTime(displayedSummary.started_at)}</span>
|
||||
)}
|
||||
{formatTime(displayedSummary.completed_at) && (
|
||||
<span>完成于 {formatTime(displayedSummary.completed_at)}</span>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="rounded-xl border border-dashed px-4 py-5 text-center text-sm text-muted-foreground">
|
||||
{busy
|
||||
? "服务端接单后会在这里显示本轮新增、修改、跳过和失败数量。"
|
||||
: "尚无可展示的增量同步记录。"}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{syncStatus.data?.last_error && (
|
||||
<div className="rounded-lg border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive">
|
||||
{syncStatus.data.last_error}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => setOpen(false)}>
|
||||
关闭
|
||||
</Button>
|
||||
{!busy && (
|
||||
<Button type="button" onClick={() => void startSync()}>
|
||||
<RefreshCw className="mr-2 size-4" />
|
||||
{displayedSummary ? "再次增量同步" : "开始增量同步"}
|
||||
</Button>
|
||||
)}
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
+19
-4
@@ -5,6 +5,7 @@ import {
|
||||
FileText,
|
||||
Loader2,
|
||||
RefreshCw,
|
||||
Search,
|
||||
Trash2,
|
||||
} from "lucide-react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
@@ -38,6 +39,7 @@ import {
|
||||
useLlmWikiWikiPage,
|
||||
useLlmWikiRuntime,
|
||||
} from "@/strategy-components/api/llmwiki";
|
||||
import { WeKnoraIncrementalSync } from "@/strategy-components/components/resource-management/llmwiki/WeKnoraIncrementalSync";
|
||||
|
||||
const LIST_PATH = "/page/workspace/knowledge";
|
||||
|
||||
@@ -319,11 +321,14 @@ export function WeKnoraKnowledgeDetailPage() {
|
||||
details.data.can_write && !details.data.is_conversation_deposit;
|
||||
const canEditCurrentWikiArticle =
|
||||
canWrite && !!detailsWikiEnabled && !!wikiSlug;
|
||||
const canManageWiki = canWrite && !!detailsWikiEnabled;
|
||||
// A new/empty WeKnora base does not always expose wiki_enabled until its
|
||||
// first document has been processed. Manual Wiki management is still a
|
||||
// valid writable-base operation and must remain reachable in that state.
|
||||
const canManageWiki = canWrite;
|
||||
|
||||
return (
|
||||
<div className="flex h-full min-h-0 flex-col bg-background">
|
||||
{detailsWikiEnabled && (
|
||||
{(detailsWikiEnabled || canManageWiki) && (
|
||||
<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 && (
|
||||
@@ -344,7 +349,17 @@ export function WeKnoraKnowledgeDetailPage() {
|
||||
)}
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<Button size="sm" variant="outline" onClick={() => navigate(`/page/workspace/knowledge/${encodeURIComponent(knowledgeBaseId)}/wiki/view`)}>查看 Wiki 索引</Button>
|
||||
{isAdmin && (
|
||||
<Button size="sm" variant="outline" onClick={() => navigate(`/page/workspace/knowledge/${encodeURIComponent(knowledgeBaseId)}/retrieval-debug`)}>
|
||||
<Search className="mr-2 size-4" />检索测试
|
||||
</Button>
|
||||
)}
|
||||
{canManageWiki && (
|
||||
<WeKnoraIncrementalSync knowledgeBaseId={knowledgeBaseId} />
|
||||
)}
|
||||
{detailsWikiEnabled && (
|
||||
<Button size="sm" variant="outline" onClick={() => navigate(`/page/workspace/knowledge/${encodeURIComponent(knowledgeBaseId)}/wiki/view`)}>查看 Wiki 索引</Button>
|
||||
)}
|
||||
{isAdmin && (
|
||||
<Button
|
||||
size="sm"
|
||||
@@ -356,7 +371,7 @@ export function WeKnoraKnowledgeDetailPage() {
|
||||
}
|
||||
>
|
||||
<Archive className="mr-2 size-4" />
|
||||
数据包任务
|
||||
导入 / 导出数据包
|
||||
</Button>
|
||||
)}
|
||||
{canManageWiki && <Button
|
||||
|
||||
+316
-31
@@ -34,21 +34,36 @@ import {
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { getStoredAuth } from "@/core/auth";
|
||||
import {
|
||||
formatRetrievalScore,
|
||||
retrievalChannelScores,
|
||||
retrievalModeLabel,
|
||||
} from "@/core/llmwiki/retrieval-debug";
|
||||
import { WeKnoraSourceDrawer } from "@/strategy-components/components/resource-management/llmwiki/WeKnoraSourceDrawer";
|
||||
import {
|
||||
type LlmWikiKnowledgeBase,
|
||||
type LlmWikiSearchResponse,
|
||||
type LlmWikiSearchResult,
|
||||
type LlmWikiScope,
|
||||
type LlmWikiWikiInstructions,
|
||||
configureLocalWikiEncoder,
|
||||
getLocalWikiEncoderStatus,
|
||||
searchLlmWiki,
|
||||
startLocalWikiEncoder,
|
||||
uploadLocalWikiEncoder,
|
||||
restoreConfiguredWikiEncoder,
|
||||
useLlmWikiActions,
|
||||
useLlmWikiEmbeddingModels,
|
||||
useLlmWikiKnowledgeBases,
|
||||
useLlmWikiSettings,
|
||||
useLlmWikiSettingsActions,
|
||||
@@ -56,6 +71,7 @@ import {
|
||||
|
||||
type WorkspaceTab = "personal" | "public" | "settings";
|
||||
const LIST_PATH = "/page/workspace/knowledge";
|
||||
const WIKI_INSTRUCTION_MAX_LENGTH = 8000;
|
||||
|
||||
const publicationLabels: Record<string, string> = {
|
||||
private: "仅自己",
|
||||
@@ -68,10 +84,12 @@ function messageOf(error: unknown): string {
|
||||
return error instanceof Error ? error.message : "操作失败,请稍后重试";
|
||||
}
|
||||
|
||||
function searchModeLabel(mode: LlmWikiSearchResponse["mode"]) {
|
||||
if (mode === "vector") return "本地 Wiki 向量检索";
|
||||
if (mode === "mixed") return "Wiki 混合检索";
|
||||
return "Wiki 接口检索";
|
||||
function encoderProviderLabel(provider?: string | null): string {
|
||||
const normalized = provider?.trim().toLowerCase();
|
||||
if (normalized === "local") return "本地 BGE-M3";
|
||||
if (normalized === "openai") return "OpenAI";
|
||||
if (normalized === "openai_compatible") return "OpenAI 兼容服务";
|
||||
return provider?.trim() || "未配置";
|
||||
}
|
||||
|
||||
function wikiPageTypeLabel(value?: string) {
|
||||
@@ -215,8 +233,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} onEdit={setEditingKnowledge} onPublish={togglePublication} onDelete={removeKnowledgeBase} /></TabsContent>
|
||||
<TabsContent value="public" className="mt-5"><KnowledgeGrid rows={knowledge.data ?? []} loading={knowledge.isLoading} error={knowledge.error} emptyText="公共 LLMWiki 暂无已发布知识库。" busy={busy} onOpen={openDetails} onEdit={setEditingKnowledge} onPublish={togglePublication} onDelete={removeKnowledgeBase} /></TabsContent>
|
||||
<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>
|
||||
{isAdmin && <TabsContent value="settings" className="mt-5"><ConnectionSettings /></TabsContent>}
|
||||
</Tabs>
|
||||
|
||||
@@ -241,7 +259,7 @@ export function WeKnoraKnowledgeWorkspace() {
|
||||
</div>
|
||||
</div>
|
||||
<Badge variant="outline" className="shrink-0 bg-background/80 text-emerald-700 dark:text-emerald-300">
|
||||
{searchModeLabel(searchResponse.mode)}
|
||||
{retrievalModeLabel(searchResponse.mode)}
|
||||
</Badge>
|
||||
</div>
|
||||
</CardHeader>
|
||||
@@ -270,6 +288,7 @@ export function WeKnoraKnowledgeWorkspace() {
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Badge variant="secondary" className="bg-emerald-50 text-emerald-700 dark:bg-emerald-950 dark:text-emerald-300">Wiki 文档</Badge>
|
||||
<Badge variant="outline">{wikiPageTypeLabel(result.page_type)}</Badge>
|
||||
{result.retrieval_mode && <Badge variant="outline">{retrievalModeLabel(result.retrieval_mode)}</Badge>}
|
||||
<span className="truncate text-xs text-muted-foreground">{result.knowledge_base_name}</span>
|
||||
</div>
|
||||
<div className="mt-2 line-clamp-2 text-[15px] font-semibold leading-6 text-foreground">{result.title || "未命名 Wiki 页面"}</div>
|
||||
@@ -277,7 +296,10 @@ export function WeKnoraKnowledgeWorkspace() {
|
||||
<p className="mt-2 line-clamp-3 whitespace-pre-wrap text-sm leading-6 text-muted-foreground">{resultPreview(result)}</p>
|
||||
<div className="mt-3 flex flex-wrap items-center justify-between gap-2 border-t pt-3 text-xs text-muted-foreground">
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-1">
|
||||
<span>相关度 {Math.round(Math.max(0, result.score || 0) * 100)}%</span>
|
||||
<span>融合排序分 {formatRetrievalScore(result.score)}</span>
|
||||
{retrievalChannelScores(result).map((score) => (
|
||||
<span key={score.label}>{score.label} {formatRetrievalScore(score.value)}</span>
|
||||
))}
|
||||
{updatedAt && <span>更新于 {updatedAt}</span>}
|
||||
</div>
|
||||
<span className="inline-flex items-center font-medium text-emerald-700 transition group-hover:translate-x-0.5 dark:text-emerald-300">
|
||||
@@ -348,6 +370,7 @@ function KnowledgeGrid({
|
||||
emptyText,
|
||||
busy,
|
||||
onOpen,
|
||||
onTest,
|
||||
onEdit,
|
||||
onPublish,
|
||||
onDelete,
|
||||
@@ -358,6 +381,7 @@ function KnowledgeGrid({
|
||||
emptyText: string;
|
||||
busy: boolean;
|
||||
onOpen: (item: LlmWikiKnowledgeBase) => void;
|
||||
onTest?: (item: LlmWikiKnowledgeBase) => void;
|
||||
onEdit: (item: LlmWikiKnowledgeBase) => void;
|
||||
onPublish: (item: LlmWikiKnowledgeBase) => void;
|
||||
onDelete: (item: LlmWikiKnowledgeBase) => void;
|
||||
@@ -387,6 +411,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>
|
||||
{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>}
|
||||
</div>
|
||||
@@ -408,23 +433,62 @@ function EditKnowledgeDialog({
|
||||
knowledgeBase: LlmWikiKnowledgeBase;
|
||||
pending: boolean;
|
||||
onClose: () => void;
|
||||
onSave: (input: { name: string; description: string }) => Promise<void>;
|
||||
onSave: (input: {
|
||||
name: string;
|
||||
description: string;
|
||||
test_questions?: string[];
|
||||
retrieval_settings: LlmWikiKnowledgeBase["retrieval_settings"];
|
||||
wiki_config?: LlmWikiWikiInstructions;
|
||||
}) => Promise<void>;
|
||||
}) {
|
||||
const [name, setName] = useState(knowledgeBase.name);
|
||||
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;
|
||||
|
||||
return (
|
||||
<Dialog open onOpenChange={(open) => { if (!open && !pending) onClose(); }}>
|
||||
<DialogContent>
|
||||
<DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-2xl">
|
||||
<form onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
if (!pending && name.trim()) {
|
||||
void onSave({ name: name.trim(), description: description.trim() });
|
||||
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(),
|
||||
}
|
||||
: undefined,
|
||||
});
|
||||
}
|
||||
}}>
|
||||
<DialogHeader>
|
||||
<DialogTitle>编辑知识库</DialogTitle>
|
||||
<DialogDescription>修改知识库名称和描述,保存后同步到知识服务。</DialogDescription>
|
||||
<DialogDescription>维护知识库说明、测试问题、检索方式和 Wiki 抽取要求。抽取要求会用于此后上传或重新解析的文档。</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="space-y-2">
|
||||
@@ -434,7 +498,42 @@ function EditKnowledgeDialog({
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium" htmlFor="llmwiki-edit-description">描述</label>
|
||||
<Textarea id="llmwiki-edit-description" value={description} onChange={(event) => setDescription(event.target.value)} rows={4} maxLength={2048} disabled={pending} />
|
||||
<p className="text-xs text-muted-foreground">问“这个知识库讲了什么”时会把此说明与实际命中的 Wiki 正文一起提供给回答模型。</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium" htmlFor="llmwiki-edit-questions">默认测试问题</label>
|
||||
<Textarea id="llmwiki-edit-questions" value={questionsText} onChange={(event) => { setQuestionsText(event.target.value); setQuestionsDirty(true); }} rows={6} maxLength={6000} disabled={pending} placeholder="每行一个问题,最多 12 个" />
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{knowledgeBase.test_questions_customized
|
||||
? "用户选择此知识库后,这些自定义问题会显示为可点击的测试问题。"
|
||||
: "这是系统自动问题;不编辑时会自动跟随知识库新名称更新。"}
|
||||
</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>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={onClose} disabled={pending}>取消</Button>
|
||||
@@ -457,18 +556,61 @@ function CreateKnowledgeDialog({
|
||||
open: boolean;
|
||||
pending: boolean;
|
||||
onOpenChange: (value: boolean) => void;
|
||||
onCreate: (input: { name: string; description: string; type: "document" | "faq"; wiki_enabled: boolean }) => Promise<void>;
|
||||
onCreate: (input: {
|
||||
name: string;
|
||||
description: string;
|
||||
type: "document" | "faq";
|
||||
wiki_enabled: boolean;
|
||||
embedding_model_id: string;
|
||||
wiki_config?: LlmWikiWikiInstructions;
|
||||
}) => 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 embeddingModels = useLlmWikiEmbeddingModels(open);
|
||||
const availableEmbeddingModels = useMemo(
|
||||
() => (embeddingModels.data?.models ?? []).filter((model) => model.available !== false),
|
||||
[embeddingModels.data?.models],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) { setName(""); setDescription(""); setWikiEnabled(true); }
|
||||
if (!open) {
|
||||
setName("");
|
||||
setDescription("");
|
||||
setWikiEnabled(true);
|
||||
setEmbeddingModelId("");
|
||||
setContentInstructions("");
|
||||
setExtractionInstructions("");
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !embeddingModels.data || availableEmbeddingModels.length === 0) return;
|
||||
if (availableEmbeddingModels.some((model) => model.id === embeddingModelId)) return;
|
||||
const defaultId = embeddingModels.data.default_model_id;
|
||||
setEmbeddingModelId(
|
||||
availableEmbeddingModels.some((model) => model.id === defaultId)
|
||||
? defaultId!
|
||||
: availableEmbeddingModels[0]!.id,
|
||||
);
|
||||
}, [availableEmbeddingModels, embeddingModelId, embeddingModels.data, open]);
|
||||
|
||||
const modelLabel = (model: (typeof availableEmbeddingModels)[number]) => {
|
||||
const provider = model.provider?.trim();
|
||||
const implementation = model.model_name?.trim();
|
||||
const suffix = [provider, implementation].filter(Boolean).join(" · ");
|
||||
return suffix ? `${model.name}(${suffix})` : model.name;
|
||||
};
|
||||
const modelSelectionUnavailable = embeddingModels.isLoading || embeddingModels.isError || !embeddingModelId;
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent>
|
||||
<DialogHeader><DialogTitle>新建个人知识库</DialogTitle><DialogDescription>选择知识库模式;模型、切块和存储策略仍由知识服务管理。</DialogDescription></DialogHeader>
|
||||
<DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-2xl">
|
||||
<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>
|
||||
@@ -476,13 +618,119 @@ function CreateKnowledgeDialog({
|
||||
<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}
|
||||
/>
|
||||
)}
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium" htmlFor="llmwiki-embedding-model">原文向量模型</label>
|
||||
{embeddingModels.isLoading ? (
|
||||
<div className="flex h-9 items-center rounded-md border px-3 text-sm text-muted-foreground"><Loader2 className="mr-2 size-4 animate-spin" />正在读取知识服务模型</div>
|
||||
) : embeddingModels.isError ? (
|
||||
<div className="rounded-lg border border-destructive/30 bg-destructive/5 p-3 text-xs text-destructive">
|
||||
<p>模型读取失败:{messageOf(embeddingModels.error)}</p>
|
||||
<Button type="button" variant="ghost" size="sm" className="mt-1 h-7 px-2" onClick={() => void embeddingModels.refetch()}>重新读取</Button>
|
||||
</div>
|
||||
) : availableEmbeddingModels.length ? (
|
||||
<Select value={embeddingModelId} onValueChange={setEmbeddingModelId} disabled={pending}>
|
||||
<SelectTrigger id="llmwiki-embedding-model" className="w-full"><SelectValue placeholder="请选择向量模型" /></SelectTrigger>
|
||||
<SelectContent position="popper">
|
||||
{availableEmbeddingModels.map((model) => (
|
||||
<SelectItem key={model.id} value={model.id}>
|
||||
{modelLabel(model)}{model.is_default ? " · 默认" : ""}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
) : (
|
||||
<div className="rounded-lg border border-amber-500/30 bg-amber-500/5 p-3 text-xs text-muted-foreground">知识服务中没有可用的 Embedding 模型,请先在知识服务中启用本地或 OpenAI 兼容向量模型。</div>
|
||||
)}
|
||||
<p className="text-xs leading-5 text-muted-foreground">该模型由知识服务(WeKnora)对上传原文和分块进行向量化,并在创建时绑定到新库。它与 DeerFlow 的“Wiki 镜像编码器”是两套独立配置;选择 OpenAI 兼容模型时,无需再配置本地 BGE-M3。需要跨知识库检索时,请为相关知识库保持相同或兼容的向量模型。</p>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter><Button variant="outline" onClick={() => onOpenChange(false)}>取消</Button><Button disabled={pending || !name.trim()} onClick={() => void onCreate({ name: name.trim(), description: description.trim(), type: "document", wiki_enabled: wikiEnabled })}>{pending && <Loader2 className="mr-2 size-4 animate-spin" />}创建</Button></DialogFooter>
|
||||
<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>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function WikiInstructionFields({
|
||||
idPrefix,
|
||||
contentInstructions,
|
||||
extractionInstructions,
|
||||
onContentInstructionsChange,
|
||||
onExtractionInstructionsChange,
|
||||
disabled,
|
||||
}: {
|
||||
idPrefix: string;
|
||||
contentInstructions: string;
|
||||
extractionInstructions: string;
|
||||
onContentInstructionsChange: (value: string) => void;
|
||||
onExtractionInstructionsChange: (value: string) => void;
|
||||
disabled: boolean;
|
||||
}) {
|
||||
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 自动抽取与页面生成。
|
||||
</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}
|
||||
</span>
|
||||
</div>
|
||||
<Textarea
|
||||
id={`${idPrefix}-content-instructions`}
|
||||
value={contentInstructions}
|
||||
onChange={(event) => onContentInstructionsChange(event.target.value)}
|
||||
rows={3}
|
||||
maxLength={WIKI_INSTRUCTION_MAX_LENGTH}
|
||||
disabled={disabled}
|
||||
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>
|
||||
</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>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function LocalEncoderSettingsCard() {
|
||||
const queryClient = useQueryClient();
|
||||
const encoder = useQuery({
|
||||
@@ -501,11 +749,12 @@ export function LocalEncoderSettingsCard() {
|
||||
|
||||
const applyStatus = (status: Awaited<ReturnType<typeof getLocalWikiEncoderStatus>>) => {
|
||||
queryClient.setQueryData(["llmwiki-local-encoder"], status);
|
||||
void queryClient.invalidateQueries({ queryKey: ["llmwiki", "wiki-index-status"] });
|
||||
setModelPath(status.model_path || "");
|
||||
};
|
||||
const configure = useMutation({
|
||||
mutationFn: () => configureLocalWikiEncoder(modelPath.trim()),
|
||||
onSuccess: (status) => { applyStatus(status); toast.success("编码器目录已保存"); },
|
||||
onSuccess: (status) => { applyStatus(status); toast.success("已切换到本地 Wiki 编码器并保存目录"); },
|
||||
onError: (error) => toast.error(messageOf(error)),
|
||||
});
|
||||
const upload = useMutation({
|
||||
@@ -514,7 +763,7 @@ export function LocalEncoderSettingsCard() {
|
||||
onSuccess: (status) => {
|
||||
applyStatus(status);
|
||||
setFiles([]);
|
||||
toast.success(`已保存 ${status.uploaded_files ?? 0} 个模型文件`);
|
||||
toast.success(`已保存 ${status.uploaded_files ?? 0} 个模型文件,并切换到本地 Wiki 编码器`);
|
||||
},
|
||||
onError: (error) => toast.error(messageOf(error)),
|
||||
});
|
||||
@@ -526,7 +775,17 @@ export function LocalEncoderSettingsCard() {
|
||||
},
|
||||
onError: (error) => toast.error(messageOf(error)),
|
||||
});
|
||||
const restoreConfigured = useMutation({
|
||||
mutationFn: restoreConfiguredWikiEncoder,
|
||||
onSuccess: (nextStatus) => {
|
||||
applyStatus(nextStatus);
|
||||
toast.success(`已恢复 config.yaml 编码器:${encoderProviderLabel(nextStatus.provider)}`);
|
||||
},
|
||||
onError: (error) => toast.error(messageOf(error)),
|
||||
});
|
||||
const status = encoder.data;
|
||||
const usingLocal = status?.using_local ?? status?.provider === "local";
|
||||
const localOverrideActive = status?.mode === "local";
|
||||
const selectedBytes = files.reduce((sum, file) => sum + file.size, 0);
|
||||
const formatSize = (value: number) => value >= 1024 ** 3
|
||||
? `${(value / 1024 ** 3).toFixed(2)} GB`
|
||||
@@ -535,29 +794,49 @@ export function LocalEncoderSettingsCard() {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-base"><Cpu className="size-5" />DeerFlow 本地编码器</CardTitle>
|
||||
<CardDescription>仅管理员可见。配置服务器上已有的 BGE-M3 目录,或直接上传完整离线模型目录;编码器作为独立进程启动,不影响 DeerFlow 其他服务。</CardDescription>
|
||||
<CardTitle className="flex items-center gap-2 text-base"><Cpu className="size-5" />DeerFlow Wiki 镜像编码器</CardTitle>
|
||||
<CardDescription>仅管理员可见。这里负责 DeerFlow 内部 Wiki 页面镜像的向量检索,不会决定知识服务对上传原文使用哪个模型。原文向量模型在“新建知识库”时选择。</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-5">
|
||||
<div className="flex flex-wrap items-center gap-2 text-sm">
|
||||
<Badge variant={status?.state === "failed" ? "destructive" : status?.state === "ready" ? "default" : "secondary"}>
|
||||
{status?.state === "ready" ? "已就绪" : status?.state === "starting" ? "启动中" : status?.state === "failed" ? "启动失败" : "未启动"}
|
||||
<Badge variant={encoder.isError || (usingLocal && status?.state === "failed") ? "destructive" : usingLocal && status?.state === "ready" ? "default" : "secondary"}>
|
||||
{encoder.isError
|
||||
? "状态读取失败"
|
||||
: encoder.isLoading
|
||||
? "读取中"
|
||||
: !usingLocal
|
||||
? "配置编码器生效中"
|
||||
: status?.state === "ready"
|
||||
? "本地编码器已就绪"
|
||||
: status?.state === "starting"
|
||||
? "本地编码器启动中"
|
||||
: status?.state === "failed"
|
||||
? "本地编码器启动失败"
|
||||
: "本地编码器未启动"}
|
||||
</Badge>
|
||||
<span className="text-muted-foreground">{status ? `${status.model} · ${status.dimensions || "自动探测"} 维 · ${status.process_isolation ? "独立进程" : "主进程"}` : "正在读取状态"}</span>
|
||||
{status?.model_files_ready && <Badge variant="outline">模型文件已就绪</Badge>}
|
||||
{status && <Badge variant="outline">当前 provider:{encoderProviderLabel(status.provider)}</Badge>}
|
||||
{status && <Badge variant="outline">{localOverrideActive ? "页面本地覆盖" : "config.yaml 配置"}</Badge>}
|
||||
<span className="text-muted-foreground">
|
||||
{status
|
||||
? usingLocal
|
||||
? `${status.model} · ${status.dimensions || "自动探测"} 维 · ${status.process_isolation ? "独立进程" : "主进程"}`
|
||||
: `由 config.yaml 的 ${encoderProviderLabel(status.configured_provider || status.provider)} provider 提供向量服务,无需启动本地模型`
|
||||
: "正在读取状态"}
|
||||
</span>
|
||||
{usingLocal && status?.model_files_ready && <Badge variant="outline">模型文件已就绪</Badge>}
|
||||
</div>
|
||||
{encoder.error && <p className="text-sm text-destructive">{messageOf(encoder.error)}</p>}
|
||||
{status?.last_error && <p className="rounded-lg border border-destructive/30 bg-destructive/5 p-3 text-xs text-destructive">{status.last_error}</p>}
|
||||
{usingLocal && status?.last_error && <p className="rounded-lg border border-destructive/30 bg-destructive/5 p-3 text-xs text-destructive">{status.last_error}</p>}
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium" htmlFor="local-encoder-path">使用服务器已有目录</label>
|
||||
<label className="text-sm font-medium" htmlFor="local-encoder-path">切换到服务器本地模型目录</label>
|
||||
<div className="flex flex-col gap-2 sm:flex-row">
|
||||
<Input id="local-encoder-path" value={modelPath} onChange={(event) => setModelPath(event.target.value)} placeholder="例如 /opt/deerflow/models/bge-m3" />
|
||||
<Button variant="outline" disabled={!modelPath.trim() || configure.isPending} onClick={() => configure.mutate()}>
|
||||
{configure.isPending && <Loader2 className="mr-2 size-4 animate-spin" />}保存目录
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">目录内需包含 <code>onnx/model.onnx</code>(推荐)或根目录 <code>model.onnx</code>。</p>
|
||||
<p className="text-xs text-muted-foreground">目录内需包含 <code>onnx/model.onnx</code>(推荐)或根目录 <code>model.onnx</code>。保存后会立即把 Wiki 镜像编码器切换为 local 并热重建,无需修改配置文件或重启服务。</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 rounded-xl border border-dashed p-4">
|
||||
@@ -576,7 +855,7 @@ export function LocalEncoderSettingsCard() {
|
||||
)}
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{files.length ? `已选择 ${files.length} 个文件,共 ${formatSize(selectedBytes)}` : "请选择完整 BGE-M3 目录。大文件会落到运行目录,不写入源码仓库。"}
|
||||
{files.length ? `已选择 ${files.length} 个文件,共 ${formatSize(selectedBytes)}` : "请选择完整 BGE-M3 目录。上传完成后会自动切换到 local;大文件会落到运行目录,不写入源码仓库。"}
|
||||
</p>
|
||||
<Button disabled={!files.length || upload.isPending} onClick={() => upload.mutate()}>
|
||||
{upload.isPending ? <Loader2 className="mr-2 size-4 animate-spin" /> : <Upload className="mr-2 size-4" />}
|
||||
@@ -586,10 +865,16 @@ export function LocalEncoderSettingsCard() {
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button disabled={!status?.model_files_ready || start.isPending || status?.state === "starting" || status?.state === "ready"} onClick={() => start.mutate()}>
|
||||
<Button disabled={!usingLocal || !status?.model_files_ready || start.isPending || status?.state === "starting" || status?.state === "ready"} onClick={() => start.mutate()}>
|
||||
{(start.isPending || status?.state === "starting") && <Loader2 className="mr-2 size-4 animate-spin" />}
|
||||
{status?.state === "ready" ? "编码器已启动" : status?.state === "failed" ? "重新启动" : "一键启动编码器"}
|
||||
{!usingLocal ? "当前无需启动本地模型" : status?.state === "ready" ? "编码器已启动" : status?.state === "failed" ? "重新启动" : "一键启动编码器"}
|
||||
</Button>
|
||||
{localOverrideActive && (
|
||||
<Button variant="secondary" disabled={restoreConfigured.isPending} onClick={() => restoreConfigured.mutate()}>
|
||||
{restoreConfigured.isPending && <Loader2 className="mr-2 size-4 animate-spin" />}
|
||||
恢复 config.yaml 编码器
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="ghost" disabled={encoder.isFetching} onClick={() => void encoder.refetch()}>
|
||||
<RefreshCw className={`mr-2 size-4 ${encoder.isFetching ? "animate-spin" : ""}`} />刷新状态
|
||||
</Button>
|
||||
|
||||
+16
-9
@@ -59,6 +59,8 @@ export default function WeKnoraPackageTransfersPage() {
|
||||
refetchInterval: (query) =>
|
||||
query.state.data?.some((job) => RUNNING.has(job.status)) ? 3000 : false,
|
||||
});
|
||||
const exportActive =
|
||||
jobs.data?.some((job) => RUNNING.has(job.status)) ?? false;
|
||||
const createExport = useMutation({
|
||||
mutationFn: () => createLlmWikiExportPackage(noteId),
|
||||
onSuccess: () => {
|
||||
@@ -92,36 +94,42 @@ export default function WeKnoraPackageTransfersPage() {
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<h1 className="truncate text-xl font-semibold">
|
||||
知识库数据包任务
|
||||
导入 / 导出知识库数据包
|
||||
</h1>
|
||||
<p className="truncate text-sm text-muted-foreground">
|
||||
{knowledge.data?.name || "正在读取知识库"} ·
|
||||
大文件在后台整理,不占用详情页面
|
||||
数据包任务在后台处理,无需停留本页
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => createExport.mutate()}
|
||||
disabled={createExport.isPending || !knowledge.data}
|
||||
disabled={
|
||||
createExport.isPending || exportActive || !knowledge.data
|
||||
}
|
||||
>
|
||||
{createExport.isPending ? (
|
||||
{createExport.isPending || exportActive ? (
|
||||
<Loader2 className="mr-2 size-4 animate-spin" />
|
||||
) : (
|
||||
<PackagePlus className="mr-2 size-4" />
|
||||
)}
|
||||
新建导出任务
|
||||
{createExport.isPending || exportActive
|
||||
? "数据包生成中"
|
||||
: "新建导出任务"}
|
||||
</Button>
|
||||
</header>
|
||||
|
||||
<WikiPackageTransfers id={noteId} />
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex-row items-center justify-between space-y-0 border-b">
|
||||
<div>
|
||||
<CardTitle className="text-base">
|
||||
向量化数据包导出记录
|
||||
Wiki 与向量数据包导出记录
|
||||
</CardTitle>
|
||||
<p className="mt-1 text-sm text-muted-foreground">
|
||||
每次生成独立记录;即使文件达到数
|
||||
GB,也只在后台落盘完成后提供下载。
|
||||
导出生成后的 Wiki、向量和关联元数据,供普通知识库或助手知识库导入;
|
||||
不包含原始文档文件。大文件在后台整理完成后提供下载。
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
@@ -214,7 +222,6 @@ export default function WeKnoraPackageTransfersPage() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<WikiPackageTransfers id={noteId} />
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
import { ArrowLeft, BookOpenText, Braces, ExternalLink, Loader2, Search } from "lucide-react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import {
|
||||
debugLlmWikiKnowledgeBaseRetrieval,
|
||||
type LlmWikiKnowledgeBaseRetrievalDebugResponse,
|
||||
type LlmWikiSearchResult,
|
||||
useLlmWikiKnowledgeBase,
|
||||
} from "@/strategy-components/api/llmwiki";
|
||||
import { WeKnoraSourceDrawer } from "@/strategy-components/components/resource-management/llmwiki/WeKnoraSourceDrawer";
|
||||
|
||||
function errorMessage(error: unknown) {
|
||||
return error instanceof Error ? error.message : "检索失败";
|
||||
}
|
||||
|
||||
export default function WeKnoraRetrievalDebugPage() {
|
||||
const { noteId = "" } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const base = useLlmWikiKnowledgeBase(noteId || null, !!noteId);
|
||||
const [query, setQuery] = useState("帮我统计本月关于赖清德的新闻有多少条,并列出具体新闻");
|
||||
const [dateFrom, setDateFrom] = useState("");
|
||||
const [dateTo, setDateTo] = useState("");
|
||||
const [expandEntities, setExpandEntities] = useState(true);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [response, setResponse] = useState<LlmWikiKnowledgeBaseRetrievalDebugResponse | null>(null);
|
||||
const [selected, setSelected] = useState<LlmWikiSearchResult | null>(null);
|
||||
|
||||
const resultBySlug = useMemo(() => {
|
||||
const index = new Map<string, LlmWikiSearchResult>();
|
||||
for (const item of response?.results ?? []) index.set(item.wiki_slug || item.id, item);
|
||||
return index;
|
||||
}, [response]);
|
||||
|
||||
const run = async () => {
|
||||
if (!query.trim() || !noteId) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
setResponse(await debugLlmWikiKnowledgeBaseRetrieval(noteId, {
|
||||
query: query.trim(),
|
||||
date_from: dateFrom || undefined,
|
||||
date_to: dateTo || undefined,
|
||||
expand_entities: expandEntities,
|
||||
top_k: 50,
|
||||
}));
|
||||
} catch (error) {
|
||||
toast.error(errorMessage(error));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex h-full min-h-0 flex-col bg-background">
|
||||
<div className="border-b px-5 py-4">
|
||||
<div className="mx-auto flex max-w-[1500px] items-center gap-3">
|
||||
<Button variant="ghost" size="icon" onClick={() => navigate(`/page/workspace/knowledge/${encodeURIComponent(noteId)}`)}><ArrowLeft className="size-4" /></Button>
|
||||
<div className="min-w-0 flex-1">
|
||||
<h1 className="truncate text-lg font-semibold">检索测试 · {base.data?.name || "知识库"}</h1>
|
||||
<p className="mt-0.5 text-xs text-muted-foreground">本页调用问答使用的真实检索链路;F12 → Network 可查看 retrieval-debug 接口的查询计划、统计值和全部参考文献。</p>
|
||||
</div>
|
||||
<Badge variant="outline"><Braces className="mr-1 size-3" />可审计接口</Badge>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-auto px-5 py-5">
|
||||
<div className="mx-auto grid max-w-[1500px] gap-5 xl:grid-cols-[420px_minmax(0,1fr)]">
|
||||
<Card className="h-fit xl:sticky xl:top-0">
|
||||
<CardHeader><CardTitle className="text-base">输入问题</CardTitle></CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<Textarea value={query} onChange={(event) => setQuery(event.target.value)} rows={7} placeholder="例如:9月1日到9月15日有多少新闻与赖清德有关?列出明细并总结。" />
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div><label className="mb-1.5 block text-xs text-muted-foreground">开始日期(可选)</label><Input type="date" value={dateFrom} onChange={(event) => setDateFrom(event.target.value)} /></div>
|
||||
<div><label className="mb-1.5 block text-xs text-muted-foreground">结束日期(可选)</label><Input type="date" value={dateTo} onChange={(event) => setDateTo(event.target.value)} /></div>
|
||||
</div>
|
||||
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={expandEntities} onChange={(event) => setExpandEntities(event.target.checked)} />扩展 Wiki 别名和一跳关联实体</label>
|
||||
<Button className="w-full" onClick={() => void run()} disabled={loading || !query.trim()}>{loading ? <Loader2 className="mr-2 size-4 animate-spin" /> : <Search className="mr-2 size-4" />}执行真实检索</Button>
|
||||
{base.data?.test_questions?.length ? <div className="border-t pt-4"><div className="mb-2 text-xs font-medium text-muted-foreground">该库测试问题</div><div className="space-y-2">{base.data.test_questions.map((item) => <button type="button" key={item} onClick={() => setQuery(item)} className="block w-full rounded-lg border px-3 py-2 text-left text-xs leading-5 hover:bg-muted/60">{item}</button>)}</div></div> : null}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="space-y-5">
|
||||
{!response ? <div className="flex min-h-80 flex-col items-center justify-center rounded-2xl border border-dashed text-center text-muted-foreground"><BookOpenText className="mb-3 size-10 opacity-50" /><div className="text-sm font-medium">执行一次检索后,这里会显示扩展词、精确统计和参考文献</div></div> : (
|
||||
<>
|
||||
<Card><CardContent className="grid gap-4 p-5 sm:grid-cols-3"><div><div className="text-xs text-muted-foreground">统计口径</div><div className="mt-1 text-lg font-semibold">{response.statistics?.unit_label || "未启用"}</div></div><div><div className="text-xs text-muted-foreground">命中数量</div><div className="mt-1 text-2xl font-semibold text-primary">{response.statistics?.matched_count ?? response.results.length}</div></div><div><div className="text-xs text-muted-foreground">无日期而排除</div><div className="mt-1 text-lg font-semibold">{response.statistics?.undated_excluded_count ?? 0}</div></div></CardContent></Card>
|
||||
|
||||
<Card><CardHeader><CardTitle className="text-base">查询计划</CardTitle></CardHeader><CardContent className="space-y-3 text-sm"><div><span className="text-muted-foreground">识别对象:</span>{response.query_plan.subject_terms.join("、") || "未识别"}</div><div><span className="text-muted-foreground">日期范围:</span>{response.query_plan.date_from || "不限"} ~ {response.query_plan.date_to || "不限"}</div><div className="flex flex-wrap gap-2"><span className="text-muted-foreground">关联扩展:</span>{response.query_plan.expanded_terms.length ? response.query_plan.expanded_terms.map((item) => <Badge key={`${item.term}:${item.from_page}`} variant="secondary" title={`来自 ${item.from_page} · ${item.relation}`}>{item.term}</Badge>) : "无"}</div><div className="break-all text-xs text-muted-foreground">request_id: {response.request_id}</div></CardContent></Card>
|
||||
|
||||
<Card><CardHeader><CardTitle className="text-base">统计明细({response.statistics?.items.length ?? 0})</CardTitle></CardHeader><CardContent className="space-y-2">{response.statistics?.items.length ? response.statistics.items.map((item) => <button type="button" key={`${item.id}:${item.wiki_slug}`} onClick={() => { const result = resultBySlug.get(item.wiki_slug || ""); if (result) setSelected(result); }} className="flex w-full items-start justify-between gap-3 rounded-xl border p-3 text-left hover:bg-muted/40"><div className="min-w-0"><div className="font-medium">{item.title}</div><div className="mt-1 text-xs text-muted-foreground">{item.published_at || "日期未知"} · {item.knowledge_base_name}{item.wiki_page_title ? ` · Wiki: ${item.wiki_page_title}` : ""}</div></div>{item.url ? <ExternalLink className="mt-1 size-4 shrink-0 text-muted-foreground" /> : null}</button>) : <div className="py-8 text-center text-sm text-muted-foreground">当前统计条件没有命中可计数的数据。</div>}</CardContent></Card>
|
||||
|
||||
<Card><CardHeader><CardTitle className="text-base">参考文献({response.references.length})</CardTitle></CardHeader><CardContent className="space-y-2">{response.references.map((item) => <button type="button" key={item.reference_id} onClick={() => { const result = resultBySlug.get(item.wiki_slug || ""); if (result) setSelected(result); }} className="block w-full rounded-xl border p-3 text-left hover:bg-muted/40"><div className="font-medium">{item.title || "未命名参考文献"}</div><p className="mt-1 line-clamp-3 text-xs leading-5 text-muted-foreground">{item.snippet}</p><div className="mt-2 text-[11px] text-muted-foreground">{item.reference_id}</div></button>)}</CardContent></Card>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<WeKnoraSourceDrawer open={selected !== null} target={selected ? { knowledgeBaseId: selected.knowledge_base_id, wikiSlug: selected.wiki_slug, tab: "wiki" } : null} title={selected?.title} quote={selected?.content || ""} onOpenChange={(open) => { if (!open) setSelected(null); }} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+217
-4
@@ -1,5 +1,9 @@
|
||||
import {
|
||||
ArrowLeft,
|
||||
BookOpenText,
|
||||
ChevronDown,
|
||||
ChevronUp,
|
||||
CornerUpLeft,
|
||||
Download,
|
||||
FileDown,
|
||||
FileText,
|
||||
@@ -26,6 +30,10 @@ import {
|
||||
parseWeKnoraPreviewUrl,
|
||||
type WeKnoraSourceTarget,
|
||||
} from "@/core/llmwiki/source-links";
|
||||
import {
|
||||
cleanRetrievedChunkText,
|
||||
resolveRetrievedChunkExcerpt,
|
||||
} from "@/core/llmwiki/source-excerpt";
|
||||
import { SpreadsheetPreview } from "@/components/workspace/artifacts/spreadsheet-preview";
|
||||
import { MarkdownContent } from "@/components/workspace/messages/markdown-content";
|
||||
import { cn } from "@/lib/utils";
|
||||
@@ -56,6 +64,12 @@ type SourceContextResponse = {
|
||||
success?: boolean;
|
||||
data?: {
|
||||
document_id?: string;
|
||||
focus_chunk_id?: string;
|
||||
chunks?: Array<{
|
||||
id?: string;
|
||||
content?: string;
|
||||
is_focus?: boolean;
|
||||
}>;
|
||||
wiki_page?: {
|
||||
slug?: string;
|
||||
} | null;
|
||||
@@ -65,6 +79,13 @@ type SourceContextResponse = {
|
||||
type DetailTarget = WeKnoraSourceTarget & {
|
||||
documentId?: string;
|
||||
wikiSlug?: string;
|
||||
retrievedExcerpt?: string;
|
||||
};
|
||||
|
||||
type WikiNavigationEntry = {
|
||||
knowledgeBaseId: string;
|
||||
slug: string;
|
||||
title: string;
|
||||
};
|
||||
|
||||
type PreviewState =
|
||||
@@ -82,6 +103,7 @@ type CachedSourceDetail = {
|
||||
wikiPage: LlmWikiWikiPage | null;
|
||||
preview: PreviewState;
|
||||
previewError: string;
|
||||
retrievedExcerpt: string;
|
||||
};
|
||||
|
||||
const sourceDetailCache = new Map<string, CachedSourceDetail>();
|
||||
@@ -146,6 +168,7 @@ async function resolveTargetDetail(target: WeKnoraSourceTarget): Promise<DetailT
|
||||
...target,
|
||||
documentId: documentId || target.documentId,
|
||||
wikiSlug: wikiSlug || target.wikiSlug,
|
||||
retrievedExcerpt: resolveRetrievedChunkExcerpt(payload.data),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -533,12 +556,14 @@ export function WeKnoraSourceDrawer({
|
||||
target,
|
||||
title,
|
||||
quote = "",
|
||||
collapseRetrievedExcerptByDefault = false,
|
||||
onOpenChange,
|
||||
}: {
|
||||
open: boolean;
|
||||
target: WeKnoraSourceTarget | null;
|
||||
title?: string;
|
||||
quote?: string;
|
||||
collapseRetrievedExcerptByDefault?: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}) {
|
||||
const [loading, setLoading] = useState(false);
|
||||
@@ -552,7 +577,13 @@ export function WeKnoraSourceDrawer({
|
||||
const [downloading, setDownloading] = useState(false);
|
||||
const [wikiDownload, setWikiDownload] = useState<"md" | "word" | null>(null);
|
||||
const [resolvedDocumentId, setResolvedDocumentId] = useState("");
|
||||
const [retrievedExcerpt, setRetrievedExcerpt] = useState("");
|
||||
const [retrievedExcerptExpanded, setRetrievedExcerptExpanded] = useState(
|
||||
!collapseRetrievedExcerptByDefault,
|
||||
);
|
||||
const [wikiHistory, setWikiHistory] = useState<WikiNavigationEntry[]>([]);
|
||||
const wikiNavigationRequestRef = useRef(0);
|
||||
const contentScrollRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const targetKey = useMemo(() => {
|
||||
if (!target) return "";
|
||||
@@ -565,6 +596,11 @@ export function WeKnoraSourceDrawer({
|
||||
].join("|");
|
||||
}, [quote, target]);
|
||||
|
||||
useEffect(() => {
|
||||
setWikiHistory([]);
|
||||
setRetrievedExcerptExpanded(!collapseRetrievedExcerptByDefault);
|
||||
}, [collapseRetrievedExcerptByDefault, open, targetKey]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !target) {
|
||||
setError(null);
|
||||
@@ -576,6 +612,7 @@ export function WeKnoraSourceDrawer({
|
||||
setPreview({ kind: "none" });
|
||||
setFullscreen(false);
|
||||
setResolvedDocumentId("");
|
||||
setRetrievedExcerpt("");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -587,6 +624,7 @@ export function WeKnoraSourceDrawer({
|
||||
setWikiPage(cached.wikiPage);
|
||||
setPreview(cached.preview);
|
||||
setPreviewError(cached.previewError);
|
||||
setRetrievedExcerpt(cached.retrievedExcerpt);
|
||||
setLoading(false);
|
||||
setPreviewLoading(false);
|
||||
return;
|
||||
@@ -599,12 +637,17 @@ export function WeKnoraSourceDrawer({
|
||||
setPreviewError("");
|
||||
setPreviewLoading(false);
|
||||
setPreview({ kind: "none" });
|
||||
setRetrievedExcerpt(cleanRetrievedChunkText(quote));
|
||||
|
||||
void (async () => {
|
||||
const detailTarget = await resolveTargetDetail(target);
|
||||
const loadedRetrievedExcerpt =
|
||||
cleanRetrievedChunkText(detailTarget.retrievedExcerpt) ||
|
||||
cleanRetrievedChunkText(quote);
|
||||
const isWikiTarget = Boolean(detailTarget.wikiSlug);
|
||||
const previewDocumentId = isWikiTarget ? "" : detailTarget.documentId || "";
|
||||
if (!cancelled) setResolvedDocumentId(previewDocumentId);
|
||||
if (!cancelled) setRetrievedExcerpt(loadedRetrievedExcerpt);
|
||||
const tasks: Promise<void>[] = [];
|
||||
let loadedDocument: LlmWikiDocument | null = null;
|
||||
let loadedWikiPage: LlmWikiWikiPage | null = null;
|
||||
@@ -679,6 +722,7 @@ export function WeKnoraSourceDrawer({
|
||||
wikiPage: loadedWikiPage,
|
||||
preview: loadedPreview,
|
||||
previewError: loadedPreviewError,
|
||||
retrievedExcerpt: loadedRetrievedExcerpt,
|
||||
});
|
||||
})()
|
||||
.catch((err: unknown) => {
|
||||
@@ -722,8 +766,21 @@ export function WeKnoraSourceDrawer({
|
||||
? buildWeKnoraWikiPagePath(target.knowledgeBaseId, resolvedWikiSlug)
|
||||
: "";
|
||||
|
||||
const openWikiPageInDrawer = async (linkedTarget: WeKnoraSourceTarget) => {
|
||||
const openWikiPageInDrawer = async (
|
||||
linkedTarget: WeKnoraSourceTarget,
|
||||
historyMode: "push" | "back" = "push",
|
||||
) => {
|
||||
if (!linkedTarget.wikiSlug) return;
|
||||
const currentSlug = wikiPage?.slug || target?.wikiSlug || "";
|
||||
if (linkedTarget.wikiSlug === currentSlug) return;
|
||||
const currentEntry = currentSlug
|
||||
? {
|
||||
knowledgeBaseId:
|
||||
target?.knowledgeBaseId || linkedTarget.knowledgeBaseId,
|
||||
slug: currentSlug,
|
||||
title: resolvedTitle,
|
||||
}
|
||||
: null;
|
||||
const requestId = ++wikiNavigationRequestRef.current;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
@@ -738,6 +795,15 @@ export function WeKnoraSourceDrawer({
|
||||
setResolvedDocumentId("");
|
||||
setPreview({ kind: "none" });
|
||||
setPreviewError("");
|
||||
setRetrievedExcerpt("");
|
||||
setWikiHistory((previous) =>
|
||||
historyMode === "back"
|
||||
? previous.slice(0, -1)
|
||||
: currentEntry
|
||||
? [...previous, currentEntry]
|
||||
: previous,
|
||||
);
|
||||
contentScrollRef.current?.scrollTo({ top: 0 });
|
||||
}
|
||||
} catch (error) {
|
||||
if (requestId === wikiNavigationRequestRef.current) {
|
||||
@@ -748,6 +814,9 @@ export function WeKnoraSourceDrawer({
|
||||
}
|
||||
};
|
||||
|
||||
const previousWikiPage = wikiHistory.at(-1) ?? null;
|
||||
const parentWikiSlug = wikiPage?.parent_slug?.trim() || "";
|
||||
|
||||
const downloadOriginal = async () => {
|
||||
if (!target || !resolvedDocumentId) return;
|
||||
setDownloading(true);
|
||||
@@ -864,6 +933,59 @@ export function WeKnoraSourceDrawer({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{wikiPage && (previousWikiPage || parentWikiSlug) && (
|
||||
<nav
|
||||
aria-label="Wiki 页面导航"
|
||||
className="flex shrink-0 flex-wrap items-center gap-2 border-b bg-muted/25 px-5 py-2.5"
|
||||
>
|
||||
{previousWikiPage && (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={loading}
|
||||
title={`返回:${previousWikiPage.title || previousWikiPage.slug}`}
|
||||
onClick={() =>
|
||||
void openWikiPageInDrawer(
|
||||
{
|
||||
knowledgeBaseId: previousWikiPage.knowledgeBaseId,
|
||||
wikiSlug: previousWikiPage.slug,
|
||||
tab: "wiki",
|
||||
},
|
||||
"back",
|
||||
)
|
||||
}
|
||||
>
|
||||
<ArrowLeft className="size-4" />
|
||||
上一页
|
||||
</Button>
|
||||
)}
|
||||
{parentWikiSlug && (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={loading}
|
||||
title={`返回上一级:${parentWikiSlug}`}
|
||||
onClick={() =>
|
||||
target &&
|
||||
void openWikiPageInDrawer({
|
||||
knowledgeBaseId: target.knowledgeBaseId,
|
||||
wikiSlug: parentWikiSlug,
|
||||
tab: "wiki",
|
||||
})
|
||||
}
|
||||
>
|
||||
<CornerUpLeft className="size-4" />
|
||||
上一级
|
||||
</Button>
|
||||
)}
|
||||
<span className="text-muted-foreground min-w-0 truncate text-xs">
|
||||
当前:{resolvedTitle}
|
||||
</span>
|
||||
</nav>
|
||||
)}
|
||||
|
||||
{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" />
|
||||
@@ -872,13 +994,104 @@ export function WeKnoraSourceDrawer({
|
||||
)}
|
||||
|
||||
{error && !loading && (
|
||||
<div className="flex min-h-0 flex-1 items-center justify-center px-8 text-center text-sm text-destructive">
|
||||
{error}
|
||||
<div className="min-h-0 flex-1 overflow-auto p-5">
|
||||
<div className="rounded-lg border border-destructive/30 bg-destructive/5 px-4 py-3 text-sm text-destructive">
|
||||
完整内容加载失败:{error}
|
||||
</div>
|
||||
{retrievedExcerpt && (
|
||||
<section className="mt-4 overflow-hidden rounded-xl border border-amber-200/80 bg-amber-50/60 dark:border-amber-800/70 dark:bg-amber-950/20">
|
||||
{collapseRetrievedExcerptByDefault ? (
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={retrievedExcerptExpanded}
|
||||
className="flex w-full items-center justify-between gap-3 px-4 py-3 text-left text-sm font-semibold text-amber-900 transition hover:bg-amber-100/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-amber-500/40 dark:text-amber-200 dark:hover:bg-amber-950/40"
|
||||
onClick={() =>
|
||||
setRetrievedExcerptExpanded((value) => !value)
|
||||
}
|
||||
>
|
||||
<span className="flex items-center gap-2">
|
||||
<BookOpenText className="size-4" />
|
||||
已保留本次检索命中内容
|
||||
</span>
|
||||
<span className="inline-flex items-center gap-1 text-xs font-normal">
|
||||
{retrievedExcerptExpanded ? "收起切片" : "展开切片"}
|
||||
{retrievedExcerptExpanded ? (
|
||||
<ChevronUp className="size-3.5" />
|
||||
) : (
|
||||
<ChevronDown className="size-3.5" />
|
||||
)}
|
||||
</span>
|
||||
</button>
|
||||
) : (
|
||||
<div className="flex items-center gap-2 px-4 pt-4 text-sm font-semibold text-amber-900 dark:text-amber-200">
|
||||
<BookOpenText className="size-4" />
|
||||
已保留本次检索命中内容
|
||||
</div>
|
||||
)}
|
||||
{retrievedExcerptExpanded && (
|
||||
<article className="m-4 mt-2 rounded-lg border border-amber-200/80 bg-background px-4 py-3 shadow-sm dark:border-amber-800/70">
|
||||
<MarkdownContent
|
||||
className="max-w-none text-sm leading-7"
|
||||
content={retrievedExcerpt}
|
||||
isLoading={false}
|
||||
remarkPlugins={reasoningPlugins.remarkPlugins}
|
||||
rehypePlugins={reasoningPlugins.rehypePlugins}
|
||||
/>
|
||||
</article>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && !error && (
|
||||
<div className="min-h-0 flex-1 overflow-auto">
|
||||
<div ref={contentScrollRef} className="min-h-0 flex-1 overflow-auto">
|
||||
{retrievedExcerpt && (
|
||||
<section className="border-b bg-amber-50/60 px-5 py-4 dark:bg-amber-950/20">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-2 text-sm font-semibold text-amber-900 dark:text-amber-200">
|
||||
<BookOpenText className="size-4" />
|
||||
本次检索命中切片
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-xs text-amber-800/75 dark:text-amber-300/75">
|
||||
下方为
|
||||
{collapseRetrievedExcerptByDefault ? " Wiki" : "文档"}
|
||||
完整内容
|
||||
</span>
|
||||
{collapseRetrievedExcerptByDefault && (
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={retrievedExcerptExpanded}
|
||||
className="inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium text-amber-900 transition hover:bg-amber-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-500/40 dark:text-amber-200 dark:hover:bg-amber-950/60"
|
||||
onClick={() =>
|
||||
setRetrievedExcerptExpanded((value) => !value)
|
||||
}
|
||||
>
|
||||
{retrievedExcerptExpanded ? "收起切片" : "展开切片"}
|
||||
{retrievedExcerptExpanded ? (
|
||||
<ChevronUp className="size-3.5" />
|
||||
) : (
|
||||
<ChevronDown className="size-3.5" />
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{retrievedExcerptExpanded && (
|
||||
<article className="mt-2 max-h-72 overflow-y-auto rounded-lg border border-amber-200/80 bg-background px-4 py-3 shadow-sm dark:border-amber-800/70">
|
||||
<MarkdownContent
|
||||
className="max-w-none text-sm leading-7"
|
||||
content={retrievedExcerpt}
|
||||
isLoading={false}
|
||||
remarkPlugins={reasoningPlugins.remarkPlugins}
|
||||
rehypePlugins={reasoningPlugins.rehypePlugins}
|
||||
/>
|
||||
</article>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
|
||||
{summary && (
|
||||
<section className="border-b px-5 py-4">
|
||||
<div className="mb-2 text-sm font-medium text-foreground">摘要</div>
|
||||
|
||||
+57
-35
@@ -1,4 +1,4 @@
|
||||
import { ArrowLeft, ChevronDown, ChevronRight, Cpu, Download, FilePlus2, FileText, Folder, Loader2, RefreshCw, Save, Search, Trash2 } from "lucide-react";
|
||||
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 { Navigate, useNavigate, useParams } from "react-router-dom";
|
||||
import { toast } from "sonner";
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
useLlmWikiWikiPage,
|
||||
useLlmWikiWikiPages,
|
||||
} from "@/strategy-components/api/llmwiki";
|
||||
import { WeKnoraIncrementalSync } from "@/strategy-components/components/resource-management/llmwiki/WeKnoraIncrementalSync";
|
||||
|
||||
const LIST_PATH = "/page/workspace/knowledge";
|
||||
|
||||
@@ -581,17 +582,6 @@ export function WeKnoraWikiManagementPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const vectorize = async () => {
|
||||
if (!canWrite) return;
|
||||
try {
|
||||
await actions.vectorizeWiki.mutateAsync({ id: noteId });
|
||||
toast.success("已提交整库 Wiki 向量化任务");
|
||||
await indexStatus.refetch();
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "触发向量化失败");
|
||||
}
|
||||
};
|
||||
|
||||
const exportExcel = async () => {
|
||||
try {
|
||||
await actions.exportWikiExcel.mutateAsync({ id: noteId, name: title });
|
||||
@@ -601,13 +591,19 @@ export function WeKnoraWikiManagementPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const vectorStatusText = !indexStatus.data?.local_index_enabled
|
||||
? "本地向量未启用,检索使用 Wiki 接口"
|
||||
: indexStatus.data.fully_vectorized
|
||||
? `整库已向量化(${indexStatus.data.vector_count ?? 0} 个向量章节)`
|
||||
: indexStatus.data.state === "running" || indexStatus.data.state === "rebuilding"
|
||||
? "整库向量化进行中,完成前检索使用 Wiki 接口"
|
||||
: "整库尚未完成向量化,检索使用 Wiki 接口";
|
||||
const vectorStatusText = indexStatus.isLoading
|
||||
? "正在读取 Wiki 镜像向量状态"
|
||||
: indexStatus.isError
|
||||
? `Wiki 镜像向量状态读取失败:${indexStatus.error instanceof Error ? indexStatus.error.message : "请稍后重试"}`
|
||||
: !indexStatus.data?.local_index_enabled
|
||||
? "Wiki 镜像向量未启用,检索使用 Wiki 接口"
|
||||
: indexStatus.data.fully_vectorized
|
||||
? `Wiki 镜像已更新(${indexStatus.data.vector_count ?? 0} 个向量章节)`
|
||||
: indexStatus.data.state === "running" || indexStatus.data.state === "rebuilding"
|
||||
? "增量同步进行中,完成前检索使用 Wiki 接口"
|
||||
: indexStatus.data.last_error
|
||||
? `Wiki 镜像同步失败:${indexStatus.data.last_error}`
|
||||
: "Wiki 镜像尚未完成首次同步,检索使用 Wiki 接口";
|
||||
|
||||
return (
|
||||
<div className="flex h-full min-h-0 flex-col bg-background">
|
||||
@@ -622,19 +618,7 @@ 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">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => void vectorize()}
|
||||
disabled={!canWrite || actions.vectorizeWiki.isPending || indexStatus.data?.state === "running" || indexStatus.data?.state === "rebuilding"}
|
||||
>
|
||||
{actions.vectorizeWiki.isPending || indexStatus.data?.state === "running" || indexStatus.data?.state === "rebuilding" ? (
|
||||
<Loader2 className="mr-2 size-4 animate-spin" />
|
||||
) : (
|
||||
<Cpu className="mr-2 size-4" />
|
||||
)}
|
||||
手动向量化
|
||||
</Button>
|
||||
<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
|
||||
@@ -652,11 +636,22 @@ export function WeKnoraWikiManagementPage() {
|
||||
<main className="grid min-h-0 flex-1 grid-cols-[320px_1fr] overflow-hidden">
|
||||
<aside className="flex min-h-0 flex-col border-r bg-muted/20">
|
||||
<div className="border-b p-3">
|
||||
{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 && (
|
||||
<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 && (
|
||||
<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">
|
||||
向量化进度
|
||||
同步 / 向量化进度
|
||||
{!indexStatus.data.local_index_enabled && <Badge variant="outline" className="text-[10px]">当前未启用</Badge>}
|
||||
</span>
|
||||
<span className="tabular-nums text-muted-foreground">
|
||||
@@ -691,6 +686,14 @@ export function WeKnoraWikiManagementPage() {
|
||||
<Loader2 className="mr-2 size-4 animate-spin" />
|
||||
加载文章
|
||||
</div>
|
||||
) : pages.isError && pagesList.length === 0 ? (
|
||||
<div className="flex h-40 flex-col items-center justify-center gap-2 px-3 text-center text-sm text-muted-foreground">
|
||||
<span>Wiki 目录暂时读取失败,不影响手工新建文章</span>
|
||||
<Button type="button" variant="outline" size="sm" onClick={() => void pages.refetch()}>
|
||||
<RefreshCw className="mr-2 size-3.5" />
|
||||
重试读取
|
||||
</Button>
|
||||
</div>
|
||||
) : filteredPages.length === 0 ? (
|
||||
<div className="flex h-32 items-center justify-center text-sm text-muted-foreground">
|
||||
{query.trim() ? "没有匹配的 Wiki 文章" : "暂无 Wiki 文章"}
|
||||
@@ -704,8 +707,27 @@ export function WeKnoraWikiManagementPage() {
|
||||
</aside>
|
||||
<section className="flex min-h-0 flex-col overflow-hidden">
|
||||
{!creating && !selectedSlug ? (
|
||||
<div className="flex flex-1 items-center justify-center text-sm text-muted-foreground">
|
||||
选择左侧文章,或点击新建文章
|
||||
<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">
|
||||
<FilePlus2 className="mx-auto size-9 text-muted-foreground/60" />
|
||||
<div className="mt-4 text-sm font-medium text-foreground">
|
||||
{pagesList.length === 0 ? "还没有 Wiki 文章" : "请选择一篇 Wiki 文章"}
|
||||
</div>
|
||||
<p className="mt-2 text-sm leading-6 text-muted-foreground">
|
||||
{pagesList.length === 0
|
||||
? "没有上传文件也可以直接创建 Wiki 内容。"
|
||||
: "从左侧目录选择文章进行编辑,或继续新建文章。"}
|
||||
</p>
|
||||
{canWrite && (
|
||||
<Button className="mt-5" size="sm" onClick={startCreate}>
|
||||
<FilePlus2 className="mr-2 size-4" />
|
||||
{pagesList.length === 0 ? "新建第一篇文章" : "新建文章"}
|
||||
</Button>
|
||||
)}
|
||||
{!canWrite && (
|
||||
<p className="mt-4 text-xs text-muted-foreground">当前知识库为只读,无法新建文章。</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
) : detail.isLoading && !creating ? (
|
||||
<div className="flex flex-1 items-center justify-center text-sm text-muted-foreground">
|
||||
|
||||
+100
-12
@@ -1,9 +1,11 @@
|
||||
import {
|
||||
Archive,
|
||||
ArrowLeft,
|
||||
BookOpenText,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
Download,
|
||||
FilePlus2,
|
||||
FileText,
|
||||
Folder,
|
||||
Loader2,
|
||||
@@ -18,6 +20,7 @@ import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { MarkdownContent } from "@/components/workspace/messages/markdown-content";
|
||||
import { useAssistantKnowledgeAccess } from "@/core/llmwiki/assistant-knowledge-access";
|
||||
import {
|
||||
buildAppHashUrl,
|
||||
buildPublicKnowledgeWikiPath,
|
||||
@@ -121,10 +124,13 @@ export function WeKnoraWikiPageView({
|
||||
const [searchParams] = useSearchParams();
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const assistantAccess = useAssistantKnowledgeAccess({ enabled: !publicEmbed });
|
||||
const isAdmin = assistantAccess.isAdmin;
|
||||
const publicBackground = usePublicBackground();
|
||||
const requestedWikiSlug = searchParams.get("wikiSlug")?.trim() || "";
|
||||
const assistantBases = useAssistantKnowledgeBases(!publicEmbed);
|
||||
const assistantSources = useAssistantKnowledgeSources(null, !publicEmbed);
|
||||
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(
|
||||
@@ -136,6 +142,10 @@ export function WeKnoraWikiPageView({
|
||||
!!noteId && publicEmbed,
|
||||
);
|
||||
const knowledgeBase = publicEmbed ? publicKnowledgeBase : privateKnowledgeBase;
|
||||
const canManageWiki =
|
||||
!publicEmbed &&
|
||||
knowledgeBase.data?.can_write === true &&
|
||||
knowledgeBase.data?.is_conversation_deposit !== true;
|
||||
const privatePages = useLlmWikiWikiPages(
|
||||
noteId || null,
|
||||
1,
|
||||
@@ -397,18 +407,81 @@ export function WeKnoraWikiPageView({
|
||||
{pages.error instanceof Error ? pages.error.message : "公开 Wiki 服务暂时不可用"}
|
||||
</div>
|
||||
</div>
|
||||
<Button onClick={() => void pages.refetch()}>
|
||||
<RefreshCw className="mr-2 size-4" />重试
|
||||
</Button>
|
||||
<div className="flex flex-wrap justify-center gap-2">
|
||||
{canManageWiki && (
|
||||
<Button
|
||||
onClick={() =>
|
||||
navigate(`${LIST_PATH}/${encodeURIComponent(noteId)}/wiki`)
|
||||
}
|
||||
>
|
||||
<FilePlus2 className="mr-2 size-4" />
|
||||
进入 Wiki 管理
|
||||
</Button>
|
||||
)}
|
||||
<Button variant={canManageWiki ? "outline" : "default"} onClick={() => void pages.refetch()}>
|
||||
<RefreshCw className="mr-2 size-4" />重试
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="flex h-full flex-col items-center justify-center gap-4 text-sm text-muted-foreground">
|
||||
该知识库暂无可展示的 Wiki 页面
|
||||
{!publicEmbed && (
|
||||
<><Button variant="outline" onClick={() => navigate(LIST_PATH)}>返回知识库</Button><Button onClick={() => navigate(`${LIST_PATH}/${encodeURIComponent(noteId)}?view=weknora`)}>进入知识库管理,导入资料</Button></>
|
||||
)}
|
||||
<div className="flex h-full items-center justify-center bg-background px-6">
|
||||
<div className="w-full max-w-xl rounded-2xl border border-dashed bg-card px-6 py-10 text-center shadow-sm">
|
||||
<div className="mx-auto flex size-12 items-center justify-center rounded-full bg-emerald-100 text-emerald-700 dark:bg-emerald-950 dark:text-emerald-300">
|
||||
<BookOpenText className="size-6" />
|
||||
</div>
|
||||
<div className="mt-4 font-medium text-foreground">该知识库还没有 Wiki 页面</div>
|
||||
<p className="mt-2 text-sm leading-6 text-muted-foreground">
|
||||
{canManageWiki
|
||||
? "无需先上传文件:可以直接进入 Wiki 管理手工新建文章,也可以先导入资料后自动生成 Wiki。"
|
||||
: publicEmbed
|
||||
? "当前没有可公开阅读的 Wiki 页面,请稍后再试。"
|
||||
: "当前没有可阅读的 Wiki 页面;如需新增内容,请联系有写权限的管理员。"}
|
||||
</p>
|
||||
{!publicEmbed && (
|
||||
<div className="mt-6 flex flex-wrap justify-center gap-2">
|
||||
{canManageWiki && (
|
||||
<Button
|
||||
onClick={() =>
|
||||
navigate(
|
||||
`${LIST_PATH}/${encodeURIComponent(noteId)}/wiki`,
|
||||
)
|
||||
}
|
||||
>
|
||||
<FilePlus2 className="mr-2 size-4" />
|
||||
进入 Wiki 管理,新建文章
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
navigate(
|
||||
`${LIST_PATH}/${encodeURIComponent(noteId)}?view=weknora`,
|
||||
)
|
||||
}
|
||||
>
|
||||
导入资料
|
||||
</Button>
|
||||
{isAdmin && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
navigate(
|
||||
`${LIST_PATH}/${encodeURIComponent(noteId)}/packages`,
|
||||
)
|
||||
}
|
||||
>
|
||||
<Archive className="mr-2 size-4" />
|
||||
导入 JSONL 数据包
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="ghost" onClick={() => navigate(LIST_PATH)}>
|
||||
返回知识库
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -491,9 +564,24 @@ export function WeKnoraWikiPageView({
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<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={() => navigate(`${LIST_PATH}/${encodeURIComponent(noteId)}?view=weknora`)}>知识库管理</Button>
|
||||
{globalBase && isDeposited && <Button variant="outline" size="sm" onClick={() => navigate(`/page/workspace/knowledge/assistant?${new URLSearchParams({ base_id: globalBase.id, wikiSlug: pageData.slug })}`)}>在知识梳理中查看</Button>}
|
||||
{isAdmin && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
navigate(
|
||||
`${LIST_PATH}/${encodeURIComponent(noteId)}/packages`,
|
||||
)
|
||||
}
|
||||
>
|
||||
<Archive className="mr-2 size-4" />
|
||||
导入 / 导出数据包
|
||||
</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>}
|
||||
<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
|
||||
|
||||
+119
-58
@@ -5,6 +5,7 @@ import {
|
||||
FileText,
|
||||
Folder,
|
||||
Link2,
|
||||
Loader2,
|
||||
Network,
|
||||
Search,
|
||||
X,
|
||||
@@ -50,6 +51,9 @@ export function WikiLibraryReader({
|
||||
pageHref,
|
||||
mappingId,
|
||||
initiallyCollapseTree = false,
|
||||
activePageLoading = false,
|
||||
activePageError,
|
||||
onRetryActivePage,
|
||||
}: {
|
||||
pages: LibraryWikiPage[];
|
||||
activePage: LibraryWikiPage | null;
|
||||
@@ -57,6 +61,9 @@ export function WikiLibraryReader({
|
||||
pageHref: (slug: string) => string;
|
||||
mappingId?: string;
|
||||
initiallyCollapseTree?: boolean;
|
||||
activePageLoading?: boolean;
|
||||
activePageError?: string | null;
|
||||
onRetryActivePage?: () => void;
|
||||
}) {
|
||||
const [query, setQuery] = useState("");
|
||||
const [kind, setKind] = useState("");
|
||||
@@ -65,6 +72,7 @@ export function WikiLibraryReader({
|
||||
const [graph, setGraph] = useState(false);
|
||||
const [directoryOpen, setDirectoryOpen] = useState(false);
|
||||
const initialTreeCollapseApplied = useRef(false);
|
||||
const knownTreeBranches = useRef<Set<string>>(new Set());
|
||||
const navigate = (slug: string) => {
|
||||
onNavigate(slug);
|
||||
setDirectoryOpen(false);
|
||||
@@ -104,6 +112,15 @@ export function WikiLibraryReader({
|
||||
[pages, kind, tag, query],
|
||||
);
|
||||
const bySlug = useMemo(() => new Map(pages.map((p) => [p.slug, p])), [pages]);
|
||||
const initialOpenBranches = useMemo(
|
||||
() =>
|
||||
new Set(
|
||||
activePage?.slug
|
||||
? tree.parentKeysBySlug.get(activePage.slug) || []
|
||||
: [],
|
||||
),
|
||||
[activePage?.slug, tree],
|
||||
);
|
||||
useEffect(() => {
|
||||
const ancestors: string[] = [];
|
||||
const branches: string[] = [];
|
||||
@@ -123,21 +140,21 @@ export function WikiLibraryReader({
|
||||
});
|
||||
collectBranches(tree.roots);
|
||||
visit(tree.roots, []);
|
||||
if (
|
||||
initiallyCollapseTree &&
|
||||
!initialTreeCollapseApplied.current &&
|
||||
tree.roots.length
|
||||
) {
|
||||
initialTreeCollapseApplied.current = true;
|
||||
setCollapsed(
|
||||
new Set(branches.filter((key) => !ancestors.includes(key))),
|
||||
);
|
||||
return;
|
||||
}
|
||||
setCollapsed(
|
||||
(current) =>
|
||||
new Set([...current].filter((key) => !ancestors.includes(key))),
|
||||
);
|
||||
const ancestorSet = new Set(ancestors);
|
||||
setCollapsed((current) => {
|
||||
const next = new Set(current);
|
||||
if (initiallyCollapseTree) {
|
||||
for (const key of branches) {
|
||||
if (!knownTreeBranches.current.has(key) && !ancestorSet.has(key)) {
|
||||
next.add(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const key of ancestors) next.delete(key);
|
||||
return next;
|
||||
});
|
||||
for (const key of branches) knownTreeBranches.current.add(key);
|
||||
if (tree.roots.length) initialTreeCollapseApplied.current = true;
|
||||
}, [activePage?.slug, initiallyCollapseTree, tree]);
|
||||
const links = useMemo(() => {
|
||||
const outgoing = new Set(activePage?.out_links || []);
|
||||
@@ -160,7 +177,17 @@ export function WikiLibraryReader({
|
||||
}, [activePage, pages, bySlug]);
|
||||
const renderNode = (node: WikiTreeNode, depth = 0): React.ReactNode => {
|
||||
const active = activePage?.slug === node.page?.slug;
|
||||
const open = !!query || !collapsed.has(node.key);
|
||||
const awaitingInitialCollapse =
|
||||
initiallyCollapseTree && !initialTreeCollapseApplied.current;
|
||||
const awaitingNewBranchCollapse =
|
||||
initiallyCollapseTree &&
|
||||
node.children.length > 0 &&
|
||||
!knownTreeBranches.current.has(node.key);
|
||||
const open =
|
||||
!!query ||
|
||||
(awaitingInitialCollapse || awaitingNewBranchCollapse
|
||||
? initialOpenBranches.has(node.key)
|
||||
: !collapsed.has(node.key));
|
||||
const toggle = () =>
|
||||
setCollapsed((current) => {
|
||||
const next = new Set(current);
|
||||
@@ -353,49 +380,67 @@ export function WikiLibraryReader({
|
||||
</div>
|
||||
</header>
|
||||
<section className="px-4 py-6 md:px-7 md:py-8 lg:px-10">
|
||||
<MarkdownContent
|
||||
content={rewriteProtectedWikiImageSources(
|
||||
renderableWikiMarkdown(
|
||||
activePage.title,
|
||||
activePage.content,
|
||||
mappingId || "assistant",
|
||||
(_id, slug) => pageHref(slug),
|
||||
pages,
|
||||
).replace(/^# [^\n]*(?:\n|$)/, ""),
|
||||
)}
|
||||
isLoading={false}
|
||||
remarkPlugins={reasoningPlugins.remarkPlugins}
|
||||
rehypePlugins={reasoningPlugins.rehypePlugins}
|
||||
components={
|
||||
mappingId
|
||||
? {
|
||||
img: (props) => (
|
||||
<WikiProtectedImage
|
||||
{...props}
|
||||
knowledgeBaseId={mappingId}
|
||||
/>
|
||||
),
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
linkClassName={(href) =>
|
||||
pages.some((p) => pageHref(p.slug) === href)
|
||||
? "wiki-content-link !text-primary border-b border-dashed"
|
||||
: undefined
|
||||
}
|
||||
onLinkClick={(event, href) => {
|
||||
const target = pages.find(
|
||||
(p) =>
|
||||
pageHref(p.slug) === href ||
|
||||
href === p.slug ||
|
||||
href === `/${p.slug}`,
|
||||
);
|
||||
if (target) {
|
||||
event.preventDefault();
|
||||
navigate(target.slug);
|
||||
{activePageLoading ? (
|
||||
<div className="flex min-h-40 items-center justify-center gap-2 text-sm text-muted-foreground">
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
正在加载正文…
|
||||
</div>
|
||||
) : activePageError ? (
|
||||
<div className="flex min-h-40 flex-col items-center justify-center gap-3 text-center">
|
||||
<p className="text-sm text-destructive">
|
||||
正文加载失败:{activePageError}
|
||||
</p>
|
||||
{onRetryActivePage && (
|
||||
<Button size="sm" variant="outline" onClick={onRetryActivePage}>
|
||||
重试
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<MarkdownContent
|
||||
content={rewriteProtectedWikiImageSources(
|
||||
renderableWikiMarkdown(
|
||||
activePage.title,
|
||||
activePage.content,
|
||||
mappingId || "assistant",
|
||||
(_id, slug) => pageHref(slug),
|
||||
pages,
|
||||
).replace(/^# [^\n]*(?:\n|$)/, ""),
|
||||
)}
|
||||
isLoading={false}
|
||||
remarkPlugins={reasoningPlugins.remarkPlugins}
|
||||
rehypePlugins={reasoningPlugins.rehypePlugins}
|
||||
components={
|
||||
mappingId
|
||||
? {
|
||||
img: (props) => (
|
||||
<WikiProtectedImage
|
||||
{...props}
|
||||
knowledgeBaseId={mappingId}
|
||||
/>
|
||||
),
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
}}
|
||||
/>
|
||||
linkClassName={(href) =>
|
||||
pages.some((p) => pageHref(p.slug) === href)
|
||||
? "wiki-content-link !text-primary border-b border-dashed"
|
||||
: undefined
|
||||
}
|
||||
onLinkClick={(event, href) => {
|
||||
const target = pages.find(
|
||||
(p) =>
|
||||
pageHref(p.slug) === href ||
|
||||
href === p.slug ||
|
||||
href === `/${p.slug}`,
|
||||
);
|
||||
if (target) {
|
||||
event.preventDefault();
|
||||
navigate(target.slug);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
<section className="border-t px-4 py-5 md:px-7">
|
||||
<Button
|
||||
@@ -460,6 +505,22 @@ export function WikiLibraryReader({
|
||||
))}
|
||||
</section>
|
||||
</article>
|
||||
) : activePageLoading ? (
|
||||
<div className="flex min-h-40 items-center justify-center gap-2 py-20 text-sm text-muted-foreground">
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
正在加载正文…
|
||||
</div>
|
||||
) : activePageError ? (
|
||||
<div className="flex min-h-40 flex-col items-center justify-center gap-3 py-20 text-center">
|
||||
<p className="text-sm text-destructive">
|
||||
正文加载失败:{activePageError}
|
||||
</p>
|
||||
{onRetryActivePage && (
|
||||
<Button size="sm" variant="outline" onClick={onRetryActivePage}>
|
||||
重试
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="py-20 text-center text-sm text-muted-foreground">
|
||||
选择一个 Wiki 页面开始阅读。完成向量化的数据会自动沉淀到知识梳理。
|
||||
|
||||
+15
-5
@@ -29,6 +29,9 @@ export function WikiPackageTransfers({
|
||||
? 3000
|
||||
: false,
|
||||
});
|
||||
const hasActiveJob =
|
||||
jobs.data?.some((job) => ["queued", "running"].includes(job.status)) ??
|
||||
false;
|
||||
const action = useMutation({
|
||||
mutationFn: (file?: File) =>
|
||||
assistant
|
||||
@@ -54,36 +57,43 @@ export function WikiPackageTransfers({
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
{assistant
|
||||
? "保留正文、分类、标签、链接和原始向量;后台整理完成后下载。"
|
||||
: "选择助手知识库导出的文件,导入当前空库。模型一致时直接复用向量。"}
|
||||
: "兼容普通知识库和助手知识库导出的 JSONL 数据包;导入当前空库时直接还原 Wiki 与向量,不调用大模型,也不会恢复原始文档。"}
|
||||
</p>
|
||||
</div>
|
||||
<input
|
||||
type="file"
|
||||
accept=".jsonl,.ndjson"
|
||||
ref={input}
|
||||
disabled={action.isPending || hasActiveJob}
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
const f = e.target.files?.[0];
|
||||
if (f) action.mutate(f);
|
||||
if (f && !action.isPending && !hasActiveJob) action.mutate(f);
|
||||
e.target.value = "";
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={action.isPending}
|
||||
disabled={action.isPending || hasActiveJob}
|
||||
onClick={() =>
|
||||
assistant ? action.mutate(undefined) : input.current?.click()
|
||||
}
|
||||
>
|
||||
{action.isPending ? (
|
||||
{action.isPending || hasActiveJob ? (
|
||||
<Loader2 className="mr-2 size-4 animate-spin" />
|
||||
) : assistant ? (
|
||||
<Download className="mr-2 size-4" />
|
||||
) : (
|
||||
<Upload className="mr-2 size-4" />
|
||||
)}
|
||||
{assistant ? "生成导出包" : "上传并导入"}
|
||||
{action.isPending || hasActiveJob
|
||||
? assistant
|
||||
? "数据包生成中"
|
||||
: "数据包导入中"
|
||||
: assistant
|
||||
? "生成导出包"
|
||||
: "上传并导入"}
|
||||
</Button>
|
||||
</div>
|
||||
{jobs.error && (
|
||||
|
||||
+1
-1
@@ -27,7 +27,7 @@ import { titleOfThread } from "@/core/threads/utils";
|
||||
import { desensitize } from "@/lib/desensitize";
|
||||
import { cn } from "@/lib/utils";
|
||||
import AgentChatPage from "@/pages/AgentChatPage";
|
||||
import { ChatRuntime } from "@/pages/WorkspaceRoutes";
|
||||
import { ChatRuntime } from "@/components/workspace/chat-runtime";
|
||||
|
||||
/** 左列表顶部的业务名标识(3qfx 显示「三情分析」,agentfx 用固定名)。 */
|
||||
const AGENTFX_BUSINESS_NAME = "智能体分析";
|
||||
|
||||
+182
@@ -0,0 +1,182 @@
|
||||
/**
|
||||
* b5-1「任务分析」单智能体工作区。
|
||||
*
|
||||
* 详情由本系统的 task-deeplink-details 保存;会话列表按 ``taskId + b5-1``
|
||||
* 专用索引读取,因而不会混入普通聊天或其它任务深链的聊天记录。
|
||||
*/
|
||||
|
||||
import { useEffect, useMemo } from "react";
|
||||
import { Outlet, useLocation, useNavigate, useParams } from "react-router-dom";
|
||||
import { Loader2, MessageSquare, PlusSquare } from "lucide-react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { B5_1_GOPATH, readB51TaskDetail } from "@/core/auth/b5-1-deeplink";
|
||||
import { readTaskContext } from "@/core/auth/task-purpose";
|
||||
import { useTaskDeeplinkThreads } from "@/core/threads/use-task-deeplink-threads";
|
||||
import { titleOfThread } from "@/core/threads/utils";
|
||||
import { ChatRuntime } from "@/components/workspace/chat-runtime";
|
||||
import { desensitize } from "@/lib/desensitize";
|
||||
import { cn } from "@/lib/utils";
|
||||
import AgentChatPage from "@/pages/AgentChatPage";
|
||||
|
||||
const TASK_ANALYSIS_NAME = "任务分析";
|
||||
|
||||
function useChatsBase(taskBase: string): { taskId: string; agentId: 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` };
|
||||
}
|
||||
|
||||
function TaskDetailHeader() {
|
||||
const detail = useMemo(() => readB51TaskDetail(), []);
|
||||
const name = desensitize((detail?.taskName ?? "").trim());
|
||||
const brief = desensitize(
|
||||
((detail?.taskContent ?? "").trim() || (detail?.overview ?? "").trim()),
|
||||
);
|
||||
if (!name && !brief) return null;
|
||||
return (
|
||||
<div className="mb-3 rounded-md border border-[var(--card-border)] bg-background/70 p-2.5 shadow-sm dark:border-[#2b8ffe]/40 dark:bg-[#0b2546]/70">
|
||||
<div className="text-muted-foreground mb-1 text-[11px] font-medium">当前任务</div>
|
||||
{name && (
|
||||
<div className="text-foreground line-clamp-2 text-sm font-semibold leading-snug" title={name}>
|
||||
{name}
|
||||
</div>
|
||||
)}
|
||||
{brief && (
|
||||
<div className="text-muted-foreground mt-1 line-clamp-3 text-xs leading-relaxed" title={brief}>
|
||||
{brief}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function parseThreadId(pathname: string, chatsBase: string): string | null {
|
||||
if (!pathname.startsWith(chatsBase)) return null;
|
||||
const segment = pathname.slice(chatsBase.length).replace(/^\/+/, "").split("/")[0];
|
||||
return segment && segment !== "new" ? segment : null;
|
||||
}
|
||||
|
||||
function TaskConversationsList({
|
||||
taskId,
|
||||
chatsBase,
|
||||
}: {
|
||||
taskId: string;
|
||||
chatsBase: string;
|
||||
}) {
|
||||
const { pathname } = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const { threads, isLoading } = useTaskDeeplinkThreads(taskId, B5_1_GOPATH);
|
||||
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="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)]" />
|
||||
<span className="text-foreground text-sm font-semibold tracking-wide">{TASK_ANALYSIS_NAME}</span>
|
||||
</div>
|
||||
<TaskDetailHeader />
|
||||
<div className="mb-2 min-w-0">
|
||||
<div className="text-foreground text-sm font-semibold">任务对话</div>
|
||||
<div className="text-muted-foreground mt-0.5 text-xs tabular-nums">
|
||||
{isLoading ? "同步中" : `${threads.length} 个会话`}
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
className="h-9 w-full bg-[var(--color-main)] text-white shadow-sm hover:bg-[var(--brand-950)]"
|
||||
onClick={() => navigate(`${chatsBase}/new`)}
|
||||
>
|
||||
<PlusSquare className="h-4 w-4" /> 新建对话
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-y-auto p-2">
|
||||
{isLoading ? (
|
||||
<div className="text-muted-foreground rounded-md border border-dashed p-3 text-center text-sm dark:border-[#1b477e]/60">
|
||||
加载中…
|
||||
</div>
|
||||
) : threads.length === 0 ? (
|
||||
<div className="text-muted-foreground rounded-md border border-dashed p-3 text-center text-sm dark:border-[#1b477e]/60">
|
||||
暂无对话
|
||||
</div>
|
||||
) : (
|
||||
threads.map((thread) => (
|
||||
<button
|
||||
key={thread.thread_id}
|
||||
onClick={() => navigate(`${chatsBase}/${thread.thread_id}`)}
|
||||
className={cn(
|
||||
"group relative flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left text-sm transition-colors",
|
||||
"hover:bg-[var(--bg-color)] dark:hover:bg-[#0d2a4d]/85",
|
||||
thread.thread_id === currentThreadId &&
|
||||
"bg-[var(--bg-color)] font-medium text-[var(--color-main)] shadow-sm dark:bg-[#0d2a4d] dark:text-[#9fe3ff]",
|
||||
)}
|
||||
title={desensitize(titleOfThread(thread, "新对话"))}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
"absolute inset-y-2 left-0 w-0.5 rounded-full bg-transparent transition-colors",
|
||||
thread.thread_id === currentThreadId && "bg-[var(--color-main)] dark:bg-[#64cdf5]",
|
||||
)}
|
||||
/>
|
||||
<MessageSquare className="text-muted-foreground group-hover:text-foreground h-3.5 w-3.5 shrink-0" />
|
||||
<span className="truncate">{desensitize(titleOfThread(thread, "新对话"))}</span>
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function TaskAnalysisWorkspace({ taskBase }: { taskBase: string }) {
|
||||
const { taskId, 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} />
|
||||
<div className="relative min-h-0 min-w-0 flex-1">
|
||||
<Outlet />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function TaskAnalysisIndexResolver({ taskBase }: { taskBase: string }) {
|
||||
const { taskId, chatsBase } = useChatsBase(taskBase);
|
||||
const navigate = useNavigate();
|
||||
const { isLoading, hasThreads, latestThreadId } = useTaskDeeplinkThreads(taskId, B5_1_GOPATH);
|
||||
|
||||
useEffect(() => {
|
||||
if (isLoading) return;
|
||||
if (hasThreads && latestThreadId) {
|
||||
navigate(`${chatsBase}/${latestThreadId}`, { replace: true });
|
||||
} else {
|
||||
navigate(`${chatsBase}/new`, { replace: true, state: { taskAutoStart: true } });
|
||||
}
|
||||
}, [isLoading, hasThreads, latestThreadId, chatsBase, navigate]);
|
||||
|
||||
return (
|
||||
<div className="text-muted-foreground flex size-full items-center justify-center">
|
||||
<Loader2 className="h-5 w-5 animate-spin" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function TaskAnalysisChat({ taskBase }: { taskBase: string }) {
|
||||
const { agent_id } = useParams<{ agent_id: string }>();
|
||||
return (
|
||||
<ChatRuntime>
|
||||
<AgentChatPage
|
||||
chatBasePath={`${taskBase}/agent/${agent_id}/chats`}
|
||||
taskBind
|
||||
taskGoPath={B5_1_GOPATH}
|
||||
/>
|
||||
</ChatRuntime>
|
||||
);
|
||||
}
|
||||
+38
-13
@@ -2,7 +2,7 @@
|
||||
* 任务深链的「任务工作区」:一个任务挂多个对话(1:N)。三种业务共用本布局:
|
||||
* - rwfx(任务FX,完整版):左对话列表 + 任务操作(编辑/下一步/清除记录)+ 跳转三情分析按钮;
|
||||
* 右侧问答带「目的树闸门」(AgentChatPage taskGate)。
|
||||
* - 3qfx(三情分析)/ xdfx(行动分析)(``lite`` 精简版):只有左对话列表(按 taskId + agentId 隔离),
|
||||
* - 3qfx(三情分析)/ xdfx(行动分析)(``lite`` 精简版):只有左对话列表(按深链 taskId + goPath 隔离),
|
||||
* 无任务操作、无闸门;新建对话进问答页后,右上角「开始回答」按钮手动发出任务开场信息(AgentChatPage taskBind)。
|
||||
* xdfx 额外在左上「当前任务」卡片下展示「行动详情」(行动名称/叙事,来自行动详情接口)。
|
||||
*
|
||||
@@ -42,12 +42,12 @@ import {
|
||||
type ActionDetail,
|
||||
} from "@/core/auth/task-deeplink";
|
||||
import { TASK_BUSINESSES, type TaskBusiness } from "@/core/auth/task-buttons";
|
||||
import { useTaskThreads } from "@/core/threads/use-task-threads";
|
||||
import { useTaskDeeplinkThreads } from "@/core/threads/use-task-deeplink-threads";
|
||||
import { titleOfThread } from "@/core/threads/utils";
|
||||
import { desensitize } from "@/lib/desensitize";
|
||||
import { cn } from "@/lib/utils";
|
||||
import AgentChatPage from "@/pages/AgentChatPage";
|
||||
import { ChatRuntime } from "@/pages/WorkspaceRoutes";
|
||||
import { ChatRuntime } from "@/components/workspace/chat-runtime";
|
||||
import { TaskJumpBar } from "@/strategy-components/components/task-components/TaskJumpBar";
|
||||
import { RwfxSqGateProvider } from "@/strategy-components/components/task-components/rwfx-sq-gate";
|
||||
|
||||
@@ -169,14 +169,15 @@ function parseThreadId(pathname: string, chatsBase: string): string | null {
|
||||
*/
|
||||
function TaskConversationsList({
|
||||
taskId,
|
||||
agentId,
|
||||
recordTaskId,
|
||||
actionId,
|
||||
chatsBase,
|
||||
business,
|
||||
lite,
|
||||
}: {
|
||||
taskId: string;
|
||||
agentId: string;
|
||||
/** 原始深链 URL 的 taskId;xdfx 下即行动 id。 */
|
||||
recordTaskId: string;
|
||||
/** xdfx:按「行动id」划分聊天记录;其它业务为 ""。 */
|
||||
actionId: string;
|
||||
chatsBase: string;
|
||||
@@ -185,7 +186,7 @@ function TaskConversationsList({
|
||||
}) {
|
||||
const { pathname } = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const { threads, isLoading } = useTaskThreads(taskId, agentId, actionId);
|
||||
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 ?? "");
|
||||
|
||||
@@ -425,13 +426,14 @@ export function TaskFxWorkspace({
|
||||
business: TaskBusiness;
|
||||
lite?: boolean;
|
||||
}) {
|
||||
const { taskId, agentId, actionId, chatsBase } = useChatsBase(taskBase);
|
||||
const { taskId, actionId, chatsBase } = useChatsBase(taskBase);
|
||||
const recordTaskId = business === "xdfx" ? (actionId || taskId) : taskId;
|
||||
const content = (
|
||||
<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}
|
||||
agentId={agentId}
|
||||
recordTaskId={recordTaskId}
|
||||
actionId={actionId}
|
||||
chatsBase={chatsBase}
|
||||
business={business}
|
||||
@@ -453,10 +455,20 @@ export function TaskFxWorkspace({
|
||||
}
|
||||
|
||||
/** chats 索引:有历史对话 → 跳最新;否则 → 跳 new(rwfx 走闸门 / 3qfx/xdfx 直接带开场信息)。 */
|
||||
export function TaskFxIndexResolver({ taskBase }: { taskBase: string }) {
|
||||
const { taskId, agentId, actionId, chatsBase } = useChatsBase(taskBase);
|
||||
export function TaskFxIndexResolver({
|
||||
taskBase,
|
||||
business,
|
||||
}: {
|
||||
taskBase: string;
|
||||
business: TaskBusiness;
|
||||
}) {
|
||||
const { taskId, actionId, chatsBase } = useChatsBase(taskBase);
|
||||
const navigate = useNavigate();
|
||||
const { isLoading, hasThreads, latestThreadId } = useTaskThreads(taskId, agentId, actionId);
|
||||
const recordTaskId = business === "xdfx" ? (actionId || taskId) : taskId;
|
||||
const { isLoading, hasThreads, latestThreadId } = useTaskDeeplinkThreads(
|
||||
recordTaskId,
|
||||
business,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (isLoading) return;
|
||||
@@ -482,9 +494,11 @@ export function TaskFxIndexResolver({ taskBase }: { taskBase: string }) {
|
||||
*/
|
||||
export function TaskFxChat({
|
||||
taskBase,
|
||||
business,
|
||||
autoStartWhenPurposeEmpty,
|
||||
}: {
|
||||
taskBase: string;
|
||||
business: TaskBusiness;
|
||||
autoStartWhenPurposeEmpty?: boolean;
|
||||
}) {
|
||||
const { agent_id } = useParams<{ agent_id: string }>();
|
||||
@@ -493,6 +507,7 @@ export function TaskFxChat({
|
||||
<AgentChatPage
|
||||
chatBasePath={`${taskBase}/agent/${agent_id}/chats`}
|
||||
taskGate
|
||||
taskGoPath={business}
|
||||
autoStartWhenPurposeEmpty={autoStartWhenPurposeEmpty}
|
||||
/>
|
||||
</ChatRuntime>
|
||||
@@ -500,11 +515,21 @@ export function TaskFxChat({
|
||||
}
|
||||
|
||||
/** 右侧对话宿主(3qfx/xdfx):AgentChatPage taskBind → 仅 1:N 绑定,新建对话进问答页,右上角「开始回答」按钮手动发出开场信息。 */
|
||||
export function TaskBindChat({ taskBase }: { taskBase: string }) {
|
||||
export function TaskBindChat({
|
||||
taskBase,
|
||||
business,
|
||||
}: {
|
||||
taskBase: string;
|
||||
business: TaskBusiness;
|
||||
}) {
|
||||
const { agent_id } = useParams<{ agent_id: string }>();
|
||||
return (
|
||||
<ChatRuntime>
|
||||
<AgentChatPage chatBasePath={`${taskBase}/agent/${agent_id}/chats`} taskBind />
|
||||
<AgentChatPage
|
||||
chatBasePath={`${taskBase}/agent/${agent_id}/chats`}
|
||||
taskBind
|
||||
taskGoPath={business}
|
||||
/>
|
||||
</ChatRuntime>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user