feat: 笔记本 Studio 模块 — RAG 聊天、引用弹窗、侧边栏工作室
- 新增 Studio 笔记本列表页与详情页(RAG 流式聊天、历史线程切换) - 修复 streamSubgraphs: true 使 AI 流式消息正常展示 - 引用圆圈 [[cite:N]] 渲染 + 点击弹窗显示文档 chunk 内容 - 侧边栏「工作室」区域支持折叠/展开,笔记本过滤 is_owner=true - 后端 lead_agent 支持 notebook_source_ids / notebook_token 参数 - 线程 metadata 改为 thread_type=notebook,侧边栏过滤同步 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
1 parent
d738c13e9e
commit
ff8eb930f7
17 files changed
+1325
-12
No files matched your search
@@ -69,6 +69,14 @@ export function getLangGraphBaseURL(isMock?: boolean) {
|
||||
}
|
||||
}
|
||||
|
||||
/** 笔记本外部系统(Studio)API 基础地址,通过 VITE_NOTEBOOK_API_BASE_URL 配置。 */
|
||||
export function getNotebookApiBaseURL(): string {
|
||||
if (env.NEXT_PUBLIC_NOTEBOOK_API_BASE_URL) {
|
||||
return env.NEXT_PUBLIC_NOTEBOOK_API_BASE_URL.replace(/\/+$/, "");
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/** 轻应用「新建笔记」系列接口的基础地址(与 DeerFlow Gateway 分离)。 */
|
||||
export function getNoteApiBaseURL(): string {
|
||||
if (env.NEXT_PUBLIC_NOTE_API_BASE_URL) {
|
||||
|
||||
@@ -3,6 +3,55 @@ import { useMemo } from "react";
|
||||
import { visit } from "unist-util-visit";
|
||||
import type { BuildVisitor } from "unist-util-visit";
|
||||
|
||||
const CITE_RE = /\[\[cite:(\d+)\]\]/g;
|
||||
|
||||
export function rehypeCitations(sources: Array<{ id: number; title: string }>) {
|
||||
const sourceMap = new Map(sources.map((s) => [s.id, s.title]));
|
||||
|
||||
return (tree: Root) => {
|
||||
visit(tree, "text", (node, index, parent) => {
|
||||
if (!CITE_RE.test(node.value)) return;
|
||||
CITE_RE.lastIndex = 0;
|
||||
|
||||
const newNodes: ElementContent[] = [];
|
||||
const citeCounter = new Map<number, number>();
|
||||
let citeIndex = 0;
|
||||
let last = 0;
|
||||
let match: RegExpExecArray | null;
|
||||
|
||||
while ((match = CITE_RE.exec(node.value)) !== null) {
|
||||
if (match.index > last) {
|
||||
newNodes.push({ type: "text", value: node.value.slice(last, match.index) });
|
||||
}
|
||||
const docId = Number(match[1]);
|
||||
if (!citeCounter.has(docId)) citeCounter.set(docId, ++citeIndex);
|
||||
const num = citeCounter.get(docId)!;
|
||||
const title = sourceMap.get(docId) ?? `来源 ${docId}`;
|
||||
|
||||
newNodes.push({
|
||||
type: "element",
|
||||
tagName: "sup",
|
||||
properties: {
|
||||
title,
|
||||
"data-chunk-id": String(docId),
|
||||
style:
|
||||
"display:inline-flex;align-items:center;justify-content:center;width:1rem;height:1rem;border-radius:9999px;background:hsl(var(--primary));color:hsl(var(--primary-foreground));font-size:10px;font-weight:700;margin-left:1px;cursor:pointer;vertical-align:super;",
|
||||
},
|
||||
children: [{ type: "text", value: String(num) }],
|
||||
});
|
||||
last = match.index + match[0].length;
|
||||
}
|
||||
if (last < node.value.length) {
|
||||
newNodes.push({ type: "text", value: node.value.slice(last) });
|
||||
}
|
||||
if (parent && index !== undefined && newNodes.length > 0) {
|
||||
(parent.children as ElementContent[]).splice(index, 1, ...newNodes);
|
||||
return index + newNodes.length;
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
const CJK_TEXT_RE =
|
||||
/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
|
||||
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import { getNotebookApiBaseURL } from "@/core/config";
|
||||
import type { SourceItem, StudioNotebook } from "./types";
|
||||
|
||||
function base(): string {
|
||||
return getNotebookApiBaseURL();
|
||||
}
|
||||
|
||||
export async function fetchStudioToken(email: string): Promise<string> {
|
||||
const apiBase = base();
|
||||
if (!apiBase) throw new Error("VITE_NOTEBOOK_API_BASE_URL 未配置");
|
||||
|
||||
const res = await fetch(
|
||||
`${apiBase}/api/getTokenByEmail?email=${encodeURIComponent(email)}`,
|
||||
);
|
||||
if (!res.ok) throw new Error(`获取 Token 失败:${res.status}`);
|
||||
|
||||
const data = (await res.json()) as { token?: string } | string;
|
||||
const token = typeof data === "string" ? data : data?.token;
|
||||
if (!token) throw new Error("接口未返回有效 token");
|
||||
return token;
|
||||
}
|
||||
|
||||
export async function fetchStudioNotebooks(token: string): Promise<StudioNotebook[]> {
|
||||
const apiBase = base();
|
||||
if (!apiBase) throw new Error("VITE_NOTEBOOK_API_BASE_URL 未配置");
|
||||
|
||||
const res = await fetch(`${apiBase}/api/v1/searchspaces`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
if (!res.ok) throw new Error(`获取笔记本列表失败:${res.status}`);
|
||||
return res.json() as Promise<StudioNotebook[]>;
|
||||
}
|
||||
|
||||
export async function createSearchSpace(
|
||||
name: string,
|
||||
token: string,
|
||||
): Promise<void> {
|
||||
const apiBase = base();
|
||||
if (!apiBase) throw new Error("VITE_NOTEBOOK_API_BASE_URL 未配置");
|
||||
|
||||
const res = await fetch(`${apiBase}/api/v1/searchspaces`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify({ name, description: "", citations_enabled: true }),
|
||||
});
|
||||
if (!res.ok) throw new Error(`创建失败:${res.status}`);
|
||||
}
|
||||
|
||||
export interface ChunkRead {
|
||||
id: number;
|
||||
content: string;
|
||||
document_id: number;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface DocumentWithChunks {
|
||||
id: number;
|
||||
title: string;
|
||||
document_type: string;
|
||||
file_type: string;
|
||||
chunks: ChunkRead[];
|
||||
}
|
||||
|
||||
export async function fetchDocumentByChunk(
|
||||
chunkId: number,
|
||||
token: string,
|
||||
): Promise<DocumentWithChunks> {
|
||||
const apiBase = base();
|
||||
if (!apiBase) throw new Error("VITE_NOTEBOOK_API_BASE_URL 未配置");
|
||||
|
||||
const res = await fetch(`${apiBase}/api/v1/documents/by-chunk/${chunkId}`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
if (!res.ok) throw new Error(`获取文档失败:${res.status}`);
|
||||
return res.json() as Promise<DocumentWithChunks>;
|
||||
}
|
||||
|
||||
export async function fetchNotebookSources(
|
||||
notebookId: number,
|
||||
token: string,
|
||||
): Promise<SourceItem[]> {
|
||||
const apiBase = base();
|
||||
if (!apiBase) throw new Error("VITE_NOTEBOOK_API_BASE_URL 未配置");
|
||||
|
||||
const res = await fetch(
|
||||
`${apiBase}/api/v1/source/search-space/${notebookId}?limit=100`,
|
||||
{ headers: { Authorization: `Bearer ${token}` } },
|
||||
);
|
||||
if (!res.ok) throw new Error(`获取来源失败:${res.status}`);
|
||||
return res.json() as Promise<SourceItem[]>;
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import { useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useStream } from "@langchain/langgraph-sdk/react";
|
||||
|
||||
import { getStoredAuth } from "@/core/auth";
|
||||
import { getAPIClient } from "@/core/api";
|
||||
import { fetchNotebookSources, fetchStudioNotebooks, fetchStudioToken } from "./api";
|
||||
import type { AgentThreadState } from "@/core/threads/types";
|
||||
import type { SourceItem, StudioNotebook } from "./types";
|
||||
|
||||
export function useStudioNotebooks(): {
|
||||
notebooks: StudioNotebook[];
|
||||
isLoading: boolean;
|
||||
isError: boolean;
|
||||
} {
|
||||
const email = getStoredAuth()?.email ?? "";
|
||||
|
||||
const tokenQuery = useQuery({
|
||||
queryKey: ["studio", "token", email],
|
||||
queryFn: () => fetchStudioToken(email),
|
||||
enabled: Boolean(email),
|
||||
staleTime: 5 * 60 * 1000,
|
||||
retry: 1,
|
||||
});
|
||||
|
||||
const notebooksQuery = useQuery({
|
||||
queryKey: ["studio", "notebooks", tokenQuery.data],
|
||||
queryFn: () => fetchStudioNotebooks(tokenQuery.data!),
|
||||
enabled: Boolean(tokenQuery.data),
|
||||
staleTime: 60 * 1000,
|
||||
retry: 1,
|
||||
});
|
||||
|
||||
return {
|
||||
notebooks: (notebooksQuery.data ?? []).filter((nb) => nb.is_owner),
|
||||
isLoading: tokenQuery.isLoading || notebooksQuery.isLoading,
|
||||
isError: tokenQuery.isError || notebooksQuery.isError,
|
||||
};
|
||||
}
|
||||
|
||||
export function useNotebookThreads(notebookId: number | null) {
|
||||
const client = getAPIClient();
|
||||
return useQuery({
|
||||
queryKey: ["notebook-threads", notebookId],
|
||||
queryFn: () =>
|
||||
client.threads.search({
|
||||
metadata: { thread_type: "notebook", note_id: notebookId },
|
||||
limit: 20,
|
||||
sortBy: "updated_at",
|
||||
sortOrder: "desc",
|
||||
}),
|
||||
enabled: notebookId !== null,
|
||||
staleTime: 30 * 1000,
|
||||
refetchOnWindowFocus: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function useNotebookChat(
|
||||
notebookId: number,
|
||||
sources: SourceItem[],
|
||||
modelName?: string,
|
||||
initialThreadId?: string,
|
||||
) {
|
||||
const [threadId, setThreadId] = useState<string | undefined>(initialThreadId);
|
||||
|
||||
const email = getStoredAuth()?.email ?? "";
|
||||
const { data: token } = useQuery({
|
||||
queryKey: ["studio", "token", email],
|
||||
queryFn: () => fetchStudioToken(email),
|
||||
enabled: Boolean(email),
|
||||
staleTime: 5 * 60 * 1000,
|
||||
retry: 1,
|
||||
});
|
||||
|
||||
const thread = useStream<AgentThreadState>({
|
||||
client: getAPIClient(),
|
||||
assistantId: "lead_agent",
|
||||
threadId,
|
||||
fetchStateHistory: { limit: 1 },
|
||||
onCreated(meta) {
|
||||
setThreadId(meta.thread_id);
|
||||
void getAPIClient()
|
||||
.threads.update(meta.thread_id, {
|
||||
metadata: { thread_type: "notebook", note_id: notebookId },
|
||||
})
|
||||
.catch(() => ({}));
|
||||
},
|
||||
});
|
||||
|
||||
const send = async (text: string, selectedSourceIds: number[]) => {
|
||||
if (thread.isLoading || !token) return;
|
||||
const sourceIds =
|
||||
selectedSourceIds.length > 0
|
||||
? selectedSourceIds
|
||||
: sources.map((s) => s.id).filter(Boolean);
|
||||
|
||||
await thread.submit(
|
||||
{ messages: [{ type: "human", content: text }] },
|
||||
{
|
||||
threadId,
|
||||
streamSubgraphs: true,
|
||||
config: {
|
||||
configurable: {
|
||||
notebook_search_space_id: notebookId,
|
||||
notebook_source_ids: sourceIds,
|
||||
notebook_token: token,
|
||||
...(modelName ? { model_name: modelName } : {}),
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
return { thread, messages: thread.messages, isStreaming: thread.isLoading, send, threadId, setThreadId };
|
||||
}
|
||||
|
||||
export function useNotebookSources(notebookId: number | null): {
|
||||
sources: SourceItem[];
|
||||
isLoading: boolean;
|
||||
isError: boolean;
|
||||
} {
|
||||
const email = getStoredAuth()?.email ?? "";
|
||||
|
||||
// 复用与 useStudioNotebooks 相同的 token query key,命中缓存不重复请求
|
||||
const tokenQuery = useQuery({
|
||||
queryKey: ["studio", "token", email],
|
||||
queryFn: () => fetchStudioToken(email),
|
||||
enabled: Boolean(email),
|
||||
staleTime: 5 * 60 * 1000,
|
||||
retry: 1,
|
||||
});
|
||||
|
||||
const sourcesQuery = useQuery({
|
||||
queryKey: ["studio", "sources", notebookId],
|
||||
queryFn: () => fetchNotebookSources(notebookId!, tokenQuery.data!),
|
||||
enabled: notebookId !== null && Boolean(tokenQuery.data),
|
||||
staleTime: 60 * 1000,
|
||||
retry: 1,
|
||||
});
|
||||
|
||||
return {
|
||||
sources: sourcesQuery.data ?? [],
|
||||
isLoading: tokenQuery.isLoading || sourcesQuery.isLoading,
|
||||
isError: tokenQuery.isError || sourcesQuery.isError,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
export interface StudioTokenResponse {
|
||||
token: string;
|
||||
}
|
||||
|
||||
export interface DocumentRead {
|
||||
id: number;
|
||||
title: string;
|
||||
document_type: string;
|
||||
file_type: string | null;
|
||||
created_at: string | null;
|
||||
}
|
||||
|
||||
export interface SourceItem {
|
||||
id: number;
|
||||
search_space_id: number;
|
||||
source_type: string;
|
||||
title: string | null;
|
||||
status: string | null;
|
||||
created_at: string;
|
||||
document: DocumentRead | null;
|
||||
}
|
||||
|
||||
export interface StudioNotebook {
|
||||
id: number;
|
||||
name: string;
|
||||
description: string;
|
||||
user_id: string;
|
||||
owner_email: string;
|
||||
member_count: number;
|
||||
source_count: number;
|
||||
is_shared: boolean;
|
||||
is_owner: boolean;
|
||||
membership_role: string;
|
||||
created_at: string;
|
||||
avatar_url: string | null;
|
||||
}
|
||||
@@ -596,7 +596,9 @@ export function useThreads(
|
||||
offset += response.length;
|
||||
}
|
||||
|
||||
return threads;
|
||||
return threads.filter(
|
||||
(t) => (t.metadata as Record<string, unknown> | null)?.thread_type !== "notebook",
|
||||
);
|
||||
},
|
||||
refetchOnWindowFocus: false,
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user