Merge branch 'ji' into dhk-1
Resolve column_additions_mysql.sql conflict: keep square_id columns from master and roundtable_drafts.task_id from dhk-1. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
commit
bcc3d617a0
142 files changed
+14953
-2383
No files matched your search
@@ -93,15 +93,6 @@ export interface AdminLeaderboardDimension {
|
||||
last_seen_at: string;
|
||||
}
|
||||
|
||||
export interface AdminLeaderboardQuestion {
|
||||
text: string;
|
||||
user_id: string;
|
||||
email: string;
|
||||
thread_id: string;
|
||||
run_id: string;
|
||||
asked_at: string;
|
||||
}
|
||||
|
||||
export interface AdminLeaderboardTrendPoint {
|
||||
date: string;
|
||||
runs: number;
|
||||
@@ -138,8 +129,6 @@ export interface AdminLeaderboardResponse {
|
||||
models: AdminLeaderboardDimension[];
|
||||
agents: AdminLeaderboardDimension[];
|
||||
run_statuses: AdminLeaderboardDimension[];
|
||||
recent_questions: AdminLeaderboardQuestion[];
|
||||
frequent_questions: AdminLeaderboardQuestion[];
|
||||
trends: AdminLeaderboardTrendPoint[];
|
||||
}
|
||||
|
||||
@@ -154,7 +143,6 @@ export interface AdminUserAnalyticsResponse {
|
||||
models: AdminLeaderboardDimension[];
|
||||
agents: AdminLeaderboardDimension[];
|
||||
run_statuses: AdminLeaderboardDimension[];
|
||||
recent_questions: AdminLeaderboardQuestion[];
|
||||
trends: AdminLeaderboardTrendPoint[];
|
||||
}
|
||||
|
||||
|
||||
@@ -33,6 +33,8 @@ export interface ListAgentsParams {
|
||||
sort?: AgentSort;
|
||||
/** Keep only agents published by this user id (the card's publisher). */
|
||||
owner?: string;
|
||||
/** Keep only agents filed under this publish square (发布广场). */
|
||||
square?: string;
|
||||
}
|
||||
|
||||
function buildAgentsQuery(params: ListAgentsParams): string {
|
||||
@@ -44,6 +46,7 @@ function buildAgentsQuery(params: ListAgentsParams): string {
|
||||
if (params.pageSize != null) qs.set("page_size", String(params.pageSize));
|
||||
if (params.sort) qs.set("sort", params.sort);
|
||||
if (params.owner) qs.set("owner", params.owner);
|
||||
if (params.square) qs.set("square", params.square);
|
||||
return qs.toString();
|
||||
}
|
||||
|
||||
|
||||
@@ -88,12 +88,15 @@ export function useAgentsPaginated(params: {
|
||||
enabled?: boolean;
|
||||
/** Keep only agents published by this user id (the card's publisher). */
|
||||
owner?: string;
|
||||
/** Keep only agents filed under this publish square (发布广场). */
|
||||
square?: string;
|
||||
}) {
|
||||
const { scope, page, pageSize, enabled = true } = params;
|
||||
const search = params.search ?? "";
|
||||
const tagIds = params.tagIds ?? [];
|
||||
const sort = params.sort ?? "time_desc";
|
||||
const owner = params.owner ?? "";
|
||||
const square = params.square ?? "";
|
||||
const { data, isLoading, isFetching, error } = useQuery({
|
||||
queryKey: [
|
||||
"agents",
|
||||
@@ -105,6 +108,7 @@ export function useAgentsPaginated(params: {
|
||||
page,
|
||||
pageSize,
|
||||
owner,
|
||||
square,
|
||||
],
|
||||
queryFn: () =>
|
||||
listAgentsPaginated({
|
||||
@@ -115,6 +119,7 @@ export function useAgentsPaginated(params: {
|
||||
page,
|
||||
pageSize,
|
||||
owner: owner || undefined,
|
||||
square: square || undefined,
|
||||
}),
|
||||
enabled,
|
||||
placeholderData: keepPreviousData,
|
||||
|
||||
@@ -1,5 +1,38 @@
|
||||
import type { Tag } from "@/core/tags";
|
||||
|
||||
/**
|
||||
* A recommended question shown on the agent chat home / sidebar. `title` is the
|
||||
* short chip label; `prompt` is the full message sent when clicked. Legacy
|
||||
* agents stored questions as bare strings — use {@link normalizeAgentQuestions}
|
||||
* to read either shape.
|
||||
*/
|
||||
export interface AgentQuestion {
|
||||
title: string;
|
||||
prompt: string;
|
||||
}
|
||||
|
||||
/** Coerce the raw `common_questions` payload (legacy `string[]` or the new
|
||||
* `{title, prompt}[]`) into a uniform, non-empty `AgentQuestion[]`. */
|
||||
export function normalizeAgentQuestions(
|
||||
raw: (string | AgentQuestion)[] | null | undefined,
|
||||
): AgentQuestion[] {
|
||||
if (!raw) return [];
|
||||
const out: AgentQuestion[] = [];
|
||||
for (const item of raw) {
|
||||
if (typeof item === "string") {
|
||||
const text = item.trim();
|
||||
if (!text) continue;
|
||||
out.push({ title: text.length <= 40 ? text : `${text.slice(0, 40)}…`, prompt: text });
|
||||
continue;
|
||||
}
|
||||
const prompt = (item?.prompt ?? "").trim();
|
||||
const title = (item?.title ?? "").trim() || prompt;
|
||||
if (!prompt && !title) continue;
|
||||
out.push({ title: title || prompt, prompt: prompt || title });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export interface Agent {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -9,6 +42,8 @@ export interface Agent {
|
||||
owner_username?: string | null;
|
||||
published: boolean;
|
||||
is_private: boolean;
|
||||
/** Publish square (发布广场) the agent is filed under. "" = the default square. */
|
||||
square_id?: string;
|
||||
builtin: boolean;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
@@ -16,6 +51,10 @@ export interface Agent {
|
||||
model?: string | null;
|
||||
tool_groups?: string[] | null;
|
||||
skills?: string[] | null;
|
||||
/** Recommended questions (常用问题) shown on the agent chat home / sidebar.
|
||||
* New agents store `{title, prompt}`; legacy agents may still return `string[]`.
|
||||
* Read via {@link normalizeAgentQuestions}. */
|
||||
common_questions?: (string | AgentQuestion)[] | null;
|
||||
tags?: Tag[];
|
||||
featured_order?: number | null;
|
||||
/** Whether the current user has favorited (收藏) this agent. */
|
||||
@@ -43,9 +82,11 @@ export interface CreateAgentRequest {
|
||||
soul?: string;
|
||||
published?: boolean;
|
||||
is_private?: boolean;
|
||||
square_id?: string;
|
||||
skills?: string[] | null;
|
||||
model?: string | null;
|
||||
tool_groups?: string[] | null;
|
||||
common_questions?: AgentQuestion[] | null;
|
||||
}
|
||||
|
||||
export interface UpdateAgentRequest {
|
||||
@@ -54,7 +95,9 @@ export interface UpdateAgentRequest {
|
||||
soul?: string | null;
|
||||
published?: boolean | null;
|
||||
is_private?: boolean | null;
|
||||
square_id?: string | null;
|
||||
skills?: string[] | null;
|
||||
model?: string | null;
|
||||
tool_groups?: string[] | null;
|
||||
common_questions?: AgentQuestion[] | null;
|
||||
}
|
||||
@@ -69,7 +69,7 @@ export function getLangGraphBaseURL(isMock?: boolean) {
|
||||
}
|
||||
}
|
||||
|
||||
/** 笔记本外部系统后端 API 地址,通过 VITE_AIPI_BACKENP_URL 配置。 */
|
||||
/** 空间外部系统后端 API 地址,通过 VITE_AIPI_BACKENP_URL 配置。 */
|
||||
export function getNotebookApiBaseURL(): string {
|
||||
if (env.NEXT_PUBLIC_NOTEBOOK_API_BASE_URL) {
|
||||
return env.NEXT_PUBLIC_NOTEBOOK_API_BASE_URL.replace(/\/+$/, "");
|
||||
|
||||
@@ -17,8 +17,15 @@ export async function getCuratorConfig(): Promise<CuratorConfig> {
|
||||
return response.json() as Promise<CuratorConfig>;
|
||||
}
|
||||
|
||||
export interface CuratorConfigUpdatePayload {
|
||||
interval_hours: number;
|
||||
stale_after_days: number;
|
||||
archive_after_days: number;
|
||||
model_name: string | null;
|
||||
}
|
||||
|
||||
export async function updateCuratorConfig(
|
||||
payload: CuratorConfig,
|
||||
payload: CuratorConfigUpdatePayload,
|
||||
): Promise<CuratorConfig> {
|
||||
const response = await apiFetch(`${getBackendBaseURL()}/api/curator/config`, {
|
||||
method: "PUT",
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
runCurator,
|
||||
updateCuratorConfig,
|
||||
} from "./api";
|
||||
import type { CuratorConfigUpdatePayload } from "./api";
|
||||
import type { CuratorConfig } from "./types";
|
||||
|
||||
// All curator-related queries are per-user data (status / config / logs all
|
||||
@@ -51,7 +52,7 @@ export function useUpdateCuratorConfig() {
|
||||
const queryClient = useQueryClient();
|
||||
const keys = useCuratorKeys();
|
||||
return useMutation({
|
||||
mutationFn: (payload: CuratorConfig) => updateCuratorConfig(payload),
|
||||
mutationFn: (payload: CuratorConfigUpdatePayload) => updateCuratorConfig(payload),
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: keys.config });
|
||||
void queryClient.invalidateQueries({ queryKey: keys.status });
|
||||
|
||||
@@ -127,6 +127,30 @@ export async function ingestThreadsBatch(payload: BatchIngestPayload = {}) {
|
||||
);
|
||||
}
|
||||
|
||||
export interface IngestFileResult {
|
||||
note: KnowledgeNote;
|
||||
created: boolean;
|
||||
notes: KnowledgeNote[];
|
||||
llm_fallback: boolean;
|
||||
}
|
||||
|
||||
/** Import a file (md/txt/pdf/word/ppt/excel) into the KB as wiki note(s). */
|
||||
export async function ingestKnowledgeFile(
|
||||
file: File,
|
||||
opts: { title?: string; tags?: string; status?: string; model_name?: string | null } = {},
|
||||
) {
|
||||
const form = new FormData();
|
||||
form.append("file", file);
|
||||
if (opts.title) form.append("title", opts.title);
|
||||
if (opts.tags) form.append("tags", opts.tags);
|
||||
if (opts.status) form.append("status", opts.status);
|
||||
if (opts.model_name) form.append("model_name", opts.model_name);
|
||||
// No Content-Type header — the browser sets the multipart boundary itself.
|
||||
return parseResponse<IngestFileResult>(
|
||||
await apiFetch(`${baseUrl()}/ingest/file`, { method: "POST", body: form }),
|
||||
);
|
||||
}
|
||||
|
||||
/** Resolve `[[wikilink]]` targets to note ids / vault pages. */
|
||||
export async function resolveWikilinks(targets: string[]) {
|
||||
const res = await parseResponse<{ resolved: WikilinkResolutionMap }>(
|
||||
|
||||
@@ -10,7 +10,9 @@ import {
|
||||
deleteKnowledgeNote,
|
||||
exportKnowledgeGraph,
|
||||
fetchVaultPage,
|
||||
getKnowledgeGraph,
|
||||
getKnowledgeNote,
|
||||
ingestKnowledgeFile,
|
||||
ingestThread,
|
||||
ingestThreadsBatch,
|
||||
listDuplicates,
|
||||
@@ -70,6 +72,14 @@ export function useKnowledgeSearch(query: string, enabled: boolean) {
|
||||
});
|
||||
}
|
||||
|
||||
export function useKnowledgeGraph() {
|
||||
return useQuery({
|
||||
queryKey: [...ROOT_KEY, "graph"],
|
||||
queryFn: getKnowledgeGraph,
|
||||
refetchOnWindowFocus: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function useKnowledgeActions() {
|
||||
const queryClient = useQueryClient();
|
||||
const invalidate = () =>
|
||||
@@ -106,6 +116,16 @@ export function useKnowledgeActions() {
|
||||
mutationFn: ingestThreadsBatch,
|
||||
onSuccess: invalidate,
|
||||
}),
|
||||
ingestFile: useMutation({
|
||||
mutationFn: ({
|
||||
file,
|
||||
opts,
|
||||
}: {
|
||||
file: File;
|
||||
opts?: Parameters<typeof ingestKnowledgeFile>[1];
|
||||
}) => ingestKnowledgeFile(file, opts),
|
||||
onSuccess: invalidate,
|
||||
}),
|
||||
exportGraph: useMutation({ mutationFn: exportKnowledgeGraph }),
|
||||
merge: useMutation({
|
||||
mutationFn: ({ primaryId, duplicateIds }: { primaryId: string; duplicateIds: string[] }) =>
|
||||
|
||||
@@ -434,7 +434,17 @@ export function findToolCallResult(
|
||||
}
|
||||
|
||||
export function isHiddenFromUIMessage(message: Message) {
|
||||
return message.additional_kwargs?.hide_from_ui === true;
|
||||
if (message.additional_kwargs?.hide_from_ui === true) {
|
||||
return true;
|
||||
}
|
||||
// Conversation-summary messages are context for the model only — never shown
|
||||
// to the user. New summaries are injected transiently (never persisted), but
|
||||
// threads compacted by older builds still carry a persisted `name: "summary"`
|
||||
// HumanMessage, so hide those too.
|
||||
if (message.name === "summary") {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -7,6 +7,8 @@ export interface ListSkillsParams {
|
||||
search?: string;
|
||||
tagIds?: string[];
|
||||
sort?: "time_desc" | "time_asc" | "activity_desc" | "activity_asc" | "usage_desc" | "usage_asc" | "name_asc" | "name_desc";
|
||||
/** Keep only skills filed under this publish square (发布广场). */
|
||||
square?: string;
|
||||
}
|
||||
|
||||
export async function loadSkills(params: ListSkillsParams = {}) {
|
||||
@@ -14,6 +16,7 @@ export async function loadSkills(params: ListSkillsParams = {}) {
|
||||
if (params.search) qs.set("search", params.search);
|
||||
for (const id of params.tagIds ?? []) qs.append("tag_ids", id);
|
||||
if (params.sort) qs.set("sort", params.sort);
|
||||
if (params.square) qs.set("square", params.square);
|
||||
const query = qs.toString();
|
||||
const skills = await apiFetch(
|
||||
`${getBackendBaseURL()}/api/skills${query ? `?${query}` : ""}`,
|
||||
@@ -242,18 +245,22 @@ export interface SetSkillPublishedResponse {
|
||||
name: string;
|
||||
owner_user_id: string | null;
|
||||
published: boolean;
|
||||
square_id?: string;
|
||||
}
|
||||
|
||||
export async function setSkillPublished(
|
||||
skillName: string,
|
||||
published: boolean,
|
||||
squareId?: string,
|
||||
): Promise<SetSkillPublishedResponse> {
|
||||
const response = await apiFetch(
|
||||
`${getBackendBaseURL()}/api/skills/custom/${encodeURIComponent(skillName)}/published`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ published }),
|
||||
body: JSON.stringify(
|
||||
squareId != null ? { published, square_id: squareId } : { published },
|
||||
),
|
||||
},
|
||||
);
|
||||
if (!response.ok) {
|
||||
|
||||
@@ -203,10 +203,12 @@ export function useSetSkillPublished() {
|
||||
mutationFn: ({
|
||||
skillName,
|
||||
published,
|
||||
squareId,
|
||||
}: {
|
||||
skillName: string;
|
||||
published: boolean;
|
||||
}) => setSkillPublished(skillName, published),
|
||||
squareId?: string;
|
||||
}) => setSkillPublished(skillName, published, squareId),
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ["skills"] });
|
||||
// Unpublishing triggers the backend cascade that strips this skill
|
||||
|
||||
@@ -55,6 +55,8 @@ export interface Skill {
|
||||
// backend. Null for built-in / public skills with no human owner.
|
||||
owner_username?: string | null;
|
||||
published?: boolean;
|
||||
/** Publish square (发布广场) the skill is filed under once published. "" = default square. */
|
||||
square_id?: string;
|
||||
builtin?: boolean;
|
||||
// Long-form detail/introduction authored by the skill owner or an admin.
|
||||
// Distinct from ``description`` (parsed from SKILL.md); supports Markdown.
|
||||
|
||||
@@ -20,14 +20,16 @@ export async function fetchStudioToken(email: string): Promise<string> {
|
||||
return token;
|
||||
}
|
||||
|
||||
export async function fetchStudioNotebooks(token: string): Promise<StudioNotebook[]> {
|
||||
export async function fetchStudioNotebooks(
|
||||
token: string,
|
||||
): Promise<StudioNotebook[]> {
|
||||
const apiBase = base();
|
||||
if (!apiBase) throw new Error("VITE_AIPI_FRONTEND_URL 未配置");
|
||||
|
||||
const res = await fetch(`${apiBase}/api/v1/searchspaces`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
if (!res.ok) throw new Error(`获取笔记本列表失败:${res.status}`);
|
||||
if (!res.ok) throw new Error(`获取空间列表失败:${res.status}`);
|
||||
return res.json() as Promise<StudioNotebook[]>;
|
||||
}
|
||||
|
||||
@@ -62,13 +64,23 @@ export async function uploadSourceText(
|
||||
if (!apiBase) throw new Error("VITE_AIPI_FRONTEND_URL 未配置");
|
||||
const res = await fetch(`${apiBase}/api/v1/documents/textupload`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
|
||||
body: JSON.stringify({ search_space_id: notebookId, content, title: title || "粘贴的文字" }),
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
search_space_id: notebookId,
|
||||
content,
|
||||
title: title || "粘贴的文字",
|
||||
}),
|
||||
});
|
||||
if (!res.ok) throw new Error(`上传失败:${res.status}`);
|
||||
}
|
||||
|
||||
export async function deleteSearchSpace(id: number, token: string): Promise<void> {
|
||||
export async function deleteSearchSpace(
|
||||
id: number,
|
||||
token: string,
|
||||
): Promise<void> {
|
||||
const apiBase = base();
|
||||
if (!apiBase) throw new Error("VITE_AIPI_FRONTEND_URL 未配置");
|
||||
const res = await fetch(`${apiBase}/api/v1/searchspaces/${id}`, {
|
||||
@@ -78,12 +90,19 @@ export async function deleteSearchSpace(id: number, token: string): Promise<void
|
||||
if (!res.ok) throw new Error(`删除失败:${res.status}`);
|
||||
}
|
||||
|
||||
export async function renameSearchSpace(id: number, name: string, token: string): Promise<void> {
|
||||
export async function renameSearchSpace(
|
||||
id: number,
|
||||
name: string,
|
||||
token: string,
|
||||
): Promise<void> {
|
||||
const apiBase = base();
|
||||
if (!apiBase) throw new Error("VITE_AIPI_FRONTEND_URL 未配置");
|
||||
const res = await fetch(`${apiBase}/api/v1/searchspaces/${id}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify({ name }),
|
||||
});
|
||||
if (!res.ok) throw new Error(`重命名失败:${res.status}`);
|
||||
|
||||
@@ -4,11 +4,15 @@ import { useStream } from "@langchain/langgraph-sdk/react";
|
||||
|
||||
import { getStoredAuth } from "@/core/auth";
|
||||
import { getAPIClient } from "@/core/api";
|
||||
import { fetchNotebookSources, fetchStudioNotebooks, fetchStudioToken } from "./api";
|
||||
import {
|
||||
fetchNotebookSources,
|
||||
fetchStudioNotebooks,
|
||||
fetchStudioToken,
|
||||
} from "./api";
|
||||
import type { AgentThreadState } from "@/core/threads/types";
|
||||
import type { SourceItem, StudioNotebook } from "./types";
|
||||
|
||||
export function useStudioNotebooks(): {
|
||||
export function useStudioNotebooks(enabled = true): {
|
||||
notebooks: StudioNotebook[];
|
||||
isLoading: boolean;
|
||||
isError: boolean;
|
||||
@@ -19,17 +23,22 @@ export function useStudioNotebooks(): {
|
||||
const tokenQuery = useQuery({
|
||||
queryKey: ["studio", "token", email],
|
||||
queryFn: () => fetchStudioToken(email),
|
||||
enabled: Boolean(email),
|
||||
enabled: enabled && Boolean(email),
|
||||
staleTime: 5 * 60 * 1000,
|
||||
retry: 1,
|
||||
// 账号不存在(404/422)是永久错误,重试无意义,立即让 isError 落地
|
||||
retry: false,
|
||||
refetchOnWindowFocus: false,
|
||||
});
|
||||
|
||||
const notebooksQuery = useQuery({
|
||||
queryKey: ["studio", "notebooks", tokenQuery.data],
|
||||
queryFn: () => fetchStudioNotebooks(tokenQuery.data!),
|
||||
enabled: Boolean(tokenQuery.data),
|
||||
staleTime: 60 * 1000,
|
||||
enabled: enabled && Boolean(tokenQuery.data),
|
||||
// 空间列表不会高频变动;新建/删除路径已通过 invalidateQueries 主动失效
|
||||
// (见 workspace-nav-studio.tsx),不需要短 staleTime + windowFocus 双兜底。
|
||||
staleTime: 10 * 60 * 1000,
|
||||
retry: 1,
|
||||
refetchOnWindowFocus: false,
|
||||
});
|
||||
|
||||
return {
|
||||
@@ -71,7 +80,8 @@ export function useNotebookChat(
|
||||
queryFn: () => fetchStudioToken(email),
|
||||
enabled: Boolean(email),
|
||||
staleTime: 5 * 60 * 1000,
|
||||
retry: 1,
|
||||
retry: false,
|
||||
refetchOnWindowFocus: false,
|
||||
});
|
||||
|
||||
const thread = useStream<AgentThreadState>({
|
||||
@@ -99,7 +109,9 @@ export function useNotebookChat(
|
||||
const sourceIds =
|
||||
selectedSourceIds.length > 0
|
||||
? toDocIds(selectedSourceIds)
|
||||
: sources.map((s) => s.document?.id).filter((id): id is number => id !== undefined);
|
||||
: sources
|
||||
.map((s) => s.document?.id)
|
||||
.filter((id): id is number => id !== undefined);
|
||||
|
||||
await thread.submit(
|
||||
{ messages: [{ type: "human", content: text }] },
|
||||
@@ -118,36 +130,52 @@ export function useNotebookChat(
|
||||
);
|
||||
};
|
||||
|
||||
return { thread, messages: thread.messages, isStreaming: thread.isLoading, send, threadId, setThreadId };
|
||||
return {
|
||||
thread,
|
||||
messages: thread.messages,
|
||||
isStreaming: thread.isLoading,
|
||||
send,
|
||||
threadId,
|
||||
setThreadId,
|
||||
};
|
||||
}
|
||||
|
||||
export function useNotebookSources(notebookId: number | null): {
|
||||
export function useNotebookSources(
|
||||
notebookId: number | null,
|
||||
overrideToken?: string,
|
||||
): {
|
||||
sources: SourceItem[];
|
||||
isLoading: boolean;
|
||||
isError: boolean;
|
||||
} {
|
||||
const email = getStoredAuth()?.email ?? "";
|
||||
|
||||
// 复用与 useStudioNotebooks 相同的 token query key,命中缓存不重复请求
|
||||
// 若外部直接提供 user_token(如 notebook-token 接口返回的),跳过 getTokenByEmail
|
||||
const tokenQuery = useQuery({
|
||||
queryKey: ["studio", "token", email],
|
||||
queryFn: () => fetchStudioToken(email),
|
||||
enabled: Boolean(email),
|
||||
enabled: !overrideToken && Boolean(email),
|
||||
staleTime: 5 * 60 * 1000,
|
||||
retry: 1,
|
||||
retry: false,
|
||||
refetchOnWindowFocus: false,
|
||||
});
|
||||
|
||||
const resolvedToken = overrideToken ?? tokenQuery.data;
|
||||
|
||||
const sourcesQuery = useQuery({
|
||||
queryKey: ["studio", "sources", notebookId],
|
||||
queryFn: () => fetchNotebookSources(notebookId!, tokenQuery.data!),
|
||||
enabled: notebookId !== null && Boolean(tokenQuery.data),
|
||||
staleTime: 60 * 1000,
|
||||
queryKey: ["studio", "sources", notebookId, overrideToken ?? "default"],
|
||||
queryFn: () => fetchNotebookSources(notebookId!, resolvedToken!),
|
||||
enabled: notebookId !== null && Boolean(resolvedToken),
|
||||
// 笔记文档列表低频变动;增删时调用方应主动 invalidateQueries(["studio", "sources"]) 失效。
|
||||
staleTime: 5 * 60 * 1000,
|
||||
retry: 1,
|
||||
refetchOnWindowFocus: false,
|
||||
});
|
||||
|
||||
return {
|
||||
sources: sourcesQuery.data ?? [],
|
||||
isLoading: tokenQuery.isLoading || sourcesQuery.isLoading,
|
||||
isError: tokenQuery.isError || sourcesQuery.isError,
|
||||
isLoading:
|
||||
(!overrideToken && tokenQuery.isLoading) || sourcesQuery.isLoading,
|
||||
isError: (!overrideToken && tokenQuery.isError) || sourcesQuery.isError,
|
||||
};
|
||||
}
|
||||
@@ -89,6 +89,52 @@ export async function loadPrivateSquareStatus(): Promise<PrivateSquareStatus> {
|
||||
return (await response.json()) as PrivateSquareStatus;
|
||||
}
|
||||
|
||||
export interface PublishSquare {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
export interface PublishSquaresSettings {
|
||||
squares: PublishSquare[];
|
||||
default_square_id: string;
|
||||
}
|
||||
|
||||
export interface PublishSquaresUpdate {
|
||||
squares?: PublishSquare[];
|
||||
default_square_id?: string;
|
||||
}
|
||||
|
||||
export async function loadPublishSquares(): Promise<PublishSquaresSettings> {
|
||||
const response = await apiFetch(
|
||||
`${getBackendBaseURL()}/api/system-settings/publish-squares`,
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to load publish squares: ${response.status}`);
|
||||
}
|
||||
return (await response.json()) as PublishSquaresSettings;
|
||||
}
|
||||
|
||||
export async function updatePublishSquares(
|
||||
body: PublishSquaresUpdate,
|
||||
): Promise<PublishSquaresSettings> {
|
||||
const response = await apiFetch(
|
||||
`${getBackendBaseURL()}/api/system-settings/publish-squares`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
},
|
||||
);
|
||||
if (!response.ok) {
|
||||
const detail = await response
|
||||
.json()
|
||||
.catch(() => ({ detail: "Failed to update publish squares" }));
|
||||
throw new Error(detail.detail ?? "Failed to update publish squares");
|
||||
}
|
||||
return (await response.json()) as PublishSquaresSettings;
|
||||
}
|
||||
|
||||
export type ThemeMode = "light" | "dark";
|
||||
export type ViewMode = "card" | "list";
|
||||
|
||||
|
||||
@@ -8,21 +8,25 @@ import {
|
||||
loadLeaderboardSettings,
|
||||
loadPrivateSquareStatus,
|
||||
loadPromptPrefixSettings,
|
||||
loadPublishSquares,
|
||||
updateAppearanceSettings,
|
||||
updateCitationDisplaySettings,
|
||||
updateLeaderboardSettings,
|
||||
updatePrivateSquareSettings,
|
||||
updatePromptPrefixSettings,
|
||||
updatePublishSquares,
|
||||
type AppearanceUpdate,
|
||||
type CitationDisplayUpdate,
|
||||
type LeaderboardSettingsUpdate,
|
||||
type PrivateSquareUpdate,
|
||||
type PromptPrefixUpdate,
|
||||
type PublishSquaresUpdate,
|
||||
type ViewMode,
|
||||
} from "./api";
|
||||
|
||||
const PROMPT_PREFIX_KEY = ["systemSettings", "promptPrefix"] as const;
|
||||
const PRIVATE_SQUARE_KEY = ["systemSettings", "privateSquare"] as const;
|
||||
const PUBLISH_SQUARES_KEY = ["systemSettings", "publishSquares"] as const;
|
||||
const APPEARANCE_KEY = ["systemSettings", "appearance"] as const;
|
||||
const CITATION_DISPLAY_KEY = ["systemSettings", "citationDisplay"] as const;
|
||||
const LEADERBOARD_KEY = ["systemSettings", "leaderboard"] as const;
|
||||
@@ -67,6 +71,31 @@ export function useUpdatePrivateSquareSettings() {
|
||||
});
|
||||
}
|
||||
|
||||
/** The configured publish squares (发布广场). Readable by any logged-in user —
|
||||
* the gallery sub-tabs and the publish-flow square picker both need it. */
|
||||
export function usePublishSquares() {
|
||||
return useQuery({
|
||||
queryKey: PUBLISH_SQUARES_KEY,
|
||||
queryFn: () => loadPublishSquares(),
|
||||
staleTime: 60_000,
|
||||
refetchOnWindowFocus: false,
|
||||
retry: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdatePublishSquares() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (body: PublishSquaresUpdate) => updatePublishSquares(body),
|
||||
onSuccess: (data) => {
|
||||
queryClient.setQueryData(PUBLISH_SQUARES_KEY, data);
|
||||
// Squares changing can re-bucket gallery tabs; refresh agent/skill lists.
|
||||
queryClient.invalidateQueries({ queryKey: ["agents"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["skills"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useAppearanceSettings() {
|
||||
return useQuery({
|
||||
queryKey: APPEARANCE_KEY,
|
||||
|
||||
Reference in new issue
Block a user