Merge remote-tracking branch 'origin/master' into xuhd

# Conflicts:
#	frontend-web/.env.production
#	frontend-web/.env.sit
#	frontend-web/package.json
#	offline-backend-20260512/backend/config.yaml
This commit is contained in:
xuhd committed 2026-06-11 14:19:01 +08:00
commit 1668c1da87
177 files changed
+21030 -2738

No files matched your search

+26
View File
@@ -247,6 +247,32 @@ export async function getUserLeaderboard(
);
}
/**
* Force a synchronous rebuild of *today's* leaderboard snapshot so the latest
* real-time records are included, then return the leaderboard for `range`.
*/
export async function refreshTodayLeaderboard(
range: {
since: string;
until: string;
days?: number;
},
limit = 20,
): Promise<AdminLeaderboardResponse> {
const params = new URLSearchParams({
days: String(range.days ?? 30),
since: range.since,
until: range.until,
limit: String(limit),
});
return parse(
await apiFetch(`${base()}/leaderboard/refresh-today?${params}`, {
method: "POST",
}),
"Failed to refresh today's leaderboard",
);
}
export async function getUserAnalytics(
userId: string,
range: { since: string; until: string; days?: number },
+31
View File
@@ -9,6 +9,7 @@ import {
getUserMemory,
getUserAnalytics,
getUserLeaderboard,
refreshTodayLeaderboard,
listUserQa,
listUserThreadMessages,
listUserThreads,
@@ -41,6 +42,36 @@ export function useUserLeaderboard(
});
}
/**
* Force-rebuild today's snapshot, then prime + invalidate the matching
* leaderboard query so the page shows the freshly recomputed numbers.
*/
export function useRefreshTodayLeaderboard() {
const qc = useQueryClient();
return useMutation({
mutationFn: ({
range,
limit = 20,
}: {
range: { since: string; until: string; days?: number };
limit?: number;
}) => refreshTodayLeaderboard(range, limit),
onSuccess: (data, variables) => {
qc.setQueryData(
[
"admin-activity",
"leaderboard",
variables.range.since,
variables.range.until,
variables.limit ?? 20,
],
data,
);
qc.invalidateQueries({ queryKey: ["admin-activity", "leaderboard"] });
},
});
}
export function useUserAnalytics(
userId: string | null,
range: { since: string; until: string; days?: number },
+62 -56
View File
@@ -2,13 +2,13 @@ import { getBackendBaseURL } from "@/core/config";
import { apiFetch } from "@/core/api";
import type {
Agent,
AgentSelectorResponse,
AgentSort,
CreateAgentRequest,
PaginatedAgents,
UpdateAgentRequest,
} from "./types";
Agent,
AgentSelectorResponse,
AgentSort,
CreateAgentRequest,
PaginatedAgents,
UpdateAgentRequest,
} from "./types";
const BACKEND_UNAVAILABLE_STATUSES = new Set([502, 503, 504]);
@@ -28,21 +28,24 @@ export interface ListAgentsParams {
/** Pagination scope. Omit for the legacy combined-visibility list. */
scope?: "mine" | "square";
/** 1-based page index. Providing this (or scope) enables server-side pagination. */
page?: number;
pageSize?: number;
sort?: AgentSort;
}
page?: number;
pageSize?: number;
sort?: AgentSort;
/** Keep only agents published by this user id (the card's publisher). */
owner?: string;
}
function buildAgentsQuery(params: ListAgentsParams): string {
const qs = new URLSearchParams();
if (params.search) qs.set("search", params.search);
for (const id of params.tagIds ?? []) qs.append("tag_ids", id);
if (params.scope) qs.set("scope", params.scope);
if (params.page != null) qs.set("page", String(params.page));
if (params.pageSize != null) qs.set("page_size", String(params.pageSize));
if (params.sort) qs.set("sort", params.sort);
return qs.toString();
}
if (params.page != null) qs.set("page", String(params.page));
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);
return qs.toString();
}
export async function listAgents(params: ListAgentsParams = {}): Promise<Agent[]> {
const query = buildAgentsQuery(params);
@@ -129,13 +132,13 @@ export async function deleteAgent(id: string): Promise<void> {
if (!res.ok) throw new Error(`Failed to delete agent: ${res.statusText}`);
}
export async function getAgentSelector(): Promise<AgentSelectorResponse> {
export async function getAgentSelector(): Promise<AgentSelectorResponse> {
const res = await apiFetch(`${getBackendBaseURL()}/api/agents/selector`);
if (!res.ok) throw new Error(`Failed to load agent selector: ${res.statusText}`);
return res.json() as Promise<AgentSelectorResponse>;
}
export async function favoriteAgent(id: string): Promise<void> {
}
export async function favoriteAgent(id: string): Promise<void> {
const res = await apiFetch(`${getBackendBaseURL()}/api/agents/${id}/favorite`, {
method: "POST",
});
@@ -145,35 +148,35 @@ export async function favoriteAgent(id: string): Promise<void> {
}
}
export async function unfavoriteAgent(id: string): Promise<void> {
export async function unfavoriteAgent(id: string): Promise<void> {
const res = await apiFetch(`${getBackendBaseURL()}/api/agents/${id}/favorite`, {
method: "DELETE",
});
if (!res.ok) {
const err = (await res.json().catch(() => ({}))) as { detail?: string };
throw new Error(err.detail ?? `Failed to unfavorite agent: ${res.statusText}`);
}
}
export async function pinAgent(id: string): Promise<void> {
const res = await apiFetch(`${getBackendBaseURL()}/api/agents/${id}/pin`, {
method: "POST",
});
if (!res.ok) {
const err = (await res.json().catch(() => ({}))) as { detail?: string };
throw new Error(err.detail ?? `Failed to pin agent: ${res.statusText}`);
}
}
export async function unpinAgent(id: string): Promise<void> {
const res = await apiFetch(`${getBackendBaseURL()}/api/agents/${id}/pin`, {
method: "DELETE",
});
if (!res.ok) {
const err = (await res.json().catch(() => ({}))) as { detail?: string };
throw new Error(err.detail ?? `Failed to unpin agent: ${res.statusText}`);
}
}
}
}
export async function pinAgent(id: string): Promise<void> {
const res = await apiFetch(`${getBackendBaseURL()}/api/agents/${id}/pin`, {
method: "POST",
});
if (!res.ok) {
const err = (await res.json().catch(() => ({}))) as { detail?: string };
throw new Error(err.detail ?? `Failed to pin agent: ${res.statusText}`);
}
}
export async function unpinAgent(id: string): Promise<void> {
const res = await apiFetch(`${getBackendBaseURL()}/api/agents/${id}/pin`, {
method: "DELETE",
});
if (!res.ok) {
const err = (await res.json().catch(() => ({}))) as { detail?: string };
throw new Error(err.detail ?? `Failed to unpin agent: ${res.statusText}`);
}
}
export async function reorderFeaturedAgents(agentIds: string[]): Promise<void> {
const res = await apiFetch(
@@ -211,14 +214,16 @@ export async function listPrivateAgents(password: string): Promise<Agent[]> {
return data.agents;
}
export interface ListPrivateAgentsParams {
password: string;
search?: string;
tagIds?: string[];
page?: number;
pageSize?: number;
sort?: AgentSort;
}
export interface ListPrivateAgentsParams {
password: string;
search?: string;
tagIds?: string[];
page?: number;
pageSize?: number;
sort?: AgentSort;
/** Keep only agents published by this user id (the card's publisher). */
owner?: string;
}
/** Paginated private-square listing (password-gated). */
export async function listPrivateAgentsPaginated(
@@ -232,11 +237,12 @@ export async function listPrivateAgentsPaginated(
body: JSON.stringify({
password: params.password,
search: params.search || undefined,
tag_ids: params.tagIds && params.tagIds.length ? params.tagIds : undefined,
page: params.page,
page_size: params.pageSize,
sort: params.sort,
}),
tag_ids: params.tagIds && params.tagIds.length ? params.tagIds : undefined,
page: params.page,
page_size: params.pageSize,
sort: params.sort,
owner: params.owner || undefined,
}),
},
);
if (!res.ok) {
+119 -98
View File
@@ -3,34 +3,34 @@ import {
useMutation,
useQuery,
useQueryClient,
} from "@tanstack/react-query";
import {
} from "@tanstack/react-query";
import {
adminSyncAgentSkills,
createAgent,
deleteAgent,
favoriteAgent,
getAgent,
getAgentSelector,
listAgents,
listAgentsPaginated,
listAllAgentsAdmin,
listPrivateAgents,
listPrivateAgentsPaginated,
pinAgent,
reorderFeaturedAgents,
setAgentFeatured,
setAgentPrivate,
unfavoriteAgent,
unpinAgent,
updateAgent,
} from "./api";
import type {
Agent,
AgentSort,
CreateAgentRequest,
PaginatedAgents,
UpdateAgentRequest,
listAgents,
listAgentsPaginated,
listAllAgentsAdmin,
listPrivateAgents,
listPrivateAgentsPaginated,
pinAgent,
reorderFeaturedAgents,
setAgentFeatured,
setAgentPrivate,
unfavoriteAgent,
unpinAgent,
updateAgent,
} from "./api";
import type {
Agent,
AgentSort,
CreateAgentRequest,
PaginatedAgents,
UpdateAgentRequest,
} from "./types";
/** A cached agent listing is either a plain ``Agent[]`` (legacy ``useAgents``)
@@ -79,31 +79,43 @@ export function useAgents(params: { search?: string; tagIds?: string[] } = {}) {
/** Server-side paginated agent listing for one gallery tab (scope). Returns
* the page of agents plus the total count for the "共 N 个" header. */
export function useAgentsPaginated(params: {
scope: "mine" | "square";
search?: string;
tagIds?: string[];
sort?: AgentSort;
page: number;
pageSize: number;
enabled?: boolean;
}) {
const { scope, page, pageSize, enabled = true } = params;
const search = params.search ?? "";
const tagIds = params.tagIds ?? [];
const sort = params.sort ?? "time_desc";
const { data, isLoading, error } = useQuery({
scope: "mine" | "square";
search?: string;
tagIds?: string[];
sort?: AgentSort;
page: number;
pageSize: number;
enabled?: boolean;
/** Keep only agents published by this user id (the card's publisher). */
owner?: 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 { data, isLoading, isFetching, error } = useQuery({
queryKey: [
"agents",
"paginated",
scope,
search,
[...tagIds].sort(),
sort,
page,
pageSize,
],
queryFn: () =>
listAgentsPaginated({ scope, search, tagIds, sort, page, pageSize }),
scope,
search,
[...tagIds].sort(),
sort,
page,
pageSize,
owner,
],
queryFn: () =>
listAgentsPaginated({
scope,
search,
tagIds,
sort,
page,
pageSize,
owner: owner || undefined,
}),
enabled,
placeholderData: keepPreviousData,
});
@@ -111,6 +123,9 @@ export function useAgentsPaginated(params: {
agents: data?.agents ?? [],
total: data?.total ?? 0,
isLoading,
// keepPreviousData keeps isLoading false on subsequent searches; expose
// isFetching so callers can show a "searching" indicator on every query.
isFetching,
error,
};
}
@@ -180,7 +195,7 @@ export function useDeleteAgent() {
/** Toggle a user's favorite (收藏) on an agent, with an optimistic flip of
* ``is_favorite`` across every cached agent listing + detail so the star
* reacts instantly before the round-trip completes. */
export function useToggleAgentFavorite() {
export function useToggleAgentFavorite() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ id, favorite }: { id: string; favorite: boolean }) =>
@@ -196,30 +211,30 @@ export function useToggleAgentFavorite() {
onSettled: () => {
void queryClient.invalidateQueries({ queryKey: ["agents"] });
},
});
}
export function useToggleAgentPin() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ id, pinned }: { id: string; pinned: boolean }) =>
pinned ? pinAgent(id) : unpinAgent(id),
onMutate: ({ id, pinned }) => {
mapCachedAgents(queryClient, (a) =>
a.id === id ? { ...a, is_pinned: pinned } : a,
);
queryClient.setQueryData<Agent | undefined>(["agents", id], (old) =>
old ? { ...old, is_pinned: pinned } : old,
);
},
onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: ["agents"] });
await queryClient.refetchQueries({ queryKey: ["agents"], type: "active" });
},
});
}
export function useAgentSelector() {
});
}
export function useToggleAgentPin() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ id, pinned }: { id: string; pinned: boolean }) =>
pinned ? pinAgent(id) : unpinAgent(id),
onMutate: ({ id, pinned }) => {
mapCachedAgents(queryClient, (a) =>
a.id === id ? { ...a, is_pinned: pinned } : a,
);
queryClient.setQueryData<Agent | undefined>(["agents", id], (old) =>
old ? { ...old, is_pinned: pinned } : old,
);
},
onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: ["agents"] });
await queryClient.refetchQueries({ queryKey: ["agents"], type: "active" });
},
});
}
export function useAgentSelector() {
const { data, isLoading, error } = useQuery({
queryKey: ["agents", "selector"],
queryFn: () => getAgentSelector(),
@@ -230,9 +245,9 @@ export function useAgentSelector() {
isLoading,
error,
};
}
function invalidateAgentQueries(queryClient: ReturnType<typeof useQueryClient>) {
}
function invalidateAgentQueries(queryClient: ReturnType<typeof useQueryClient>) {
void queryClient.invalidateQueries({ queryKey: ["agents"] });
}
@@ -277,39 +292,44 @@ export function usePrivateAgents(password: string | null) {
* password-gated private square plus the total count. */
export function usePrivateAgentsPaginated(
password: string | null,
params: {
search?: string;
tagIds?: string[];
sort?: AgentSort;
page: number;
pageSize: number;
enabled?: boolean;
},
) {
const { page, pageSize, enabled = true } = params;
const search = params.search ?? "";
const tagIds = params.tagIds ?? [];
const sort = params.sort ?? "time_desc";
const { data, isLoading, error, refetch } = useQuery({
params: {
search?: string;
tagIds?: string[];
sort?: AgentSort;
page: number;
pageSize: number;
enabled?: boolean;
/** Keep only agents published by this user id (the card's publisher). */
owner?: string;
},
) {
const { page, pageSize, enabled = true } = params;
const search = params.search ?? "";
const tagIds = params.tagIds ?? [];
const sort = params.sort ?? "time_desc";
const owner = params.owner ?? "";
const { data, isLoading, isFetching, error, refetch } = useQuery({
queryKey: [
"agents",
"private-square",
password ?? "",
"paginated",
search,
[...tagIds].sort(),
sort,
page,
pageSize,
"paginated",
search,
[...tagIds].sort(),
sort,
page,
pageSize,
owner,
],
queryFn: () =>
listPrivateAgentsPaginated({
password: password!,
search,
tagIds,
sort,
page,
pageSize,
password: password!,
search,
tagIds,
sort,
page,
pageSize,
owner: owner || undefined,
}),
enabled: !!password && enabled,
staleTime: 30_000,
@@ -320,6 +340,7 @@ export function usePrivateAgentsPaginated(
agents: data?.agents ?? [],
total: data?.total ?? 0,
isLoading,
isFetching,
error,
refetch,
};
+12 -10
View File
@@ -1,10 +1,12 @@
import type { Tag } from "@/core/tags";
export interface Agent {
export interface Agent {
id: string;
name: string;
description: string;
user_id: string | null;
/** Publisher username (email local part); null for built-in agents. */
owner_username?: string | null;
published: boolean;
is_private: boolean;
builtin: boolean;
@@ -17,15 +19,15 @@ export interface Agent {
tags?: Tag[];
featured_order?: number | null;
/** Whether the current user has favorited (收藏) this agent. */
is_favorite?: boolean;
is_pinned?: boolean;
}
export type AgentSort = "time_desc" | "time_asc" | "updated_desc" | "updated_asc" | "name_asc" | "name_desc";
export interface AgentSelectorResponse {
agents: Agent[];
}
is_favorite?: boolean;
is_pinned?: boolean;
}
export type AgentSort = "time_desc" | "time_asc" | "updated_desc" | "updated_asc" | "name_asc" | "name_desc";
export interface AgentSelectorResponse {
agents: Agent[];
}
/** Pagination envelope returned by the server-side paginated agent listings. */
export interface PaginatedAgents {
@@ -25,6 +25,10 @@ export const enUS: Translations = {
edit: "Edit",
rename: "Rename",
share: "Share",
pin: "Pin",
unpin: "Unpin",
favorite: "Favorite",
unfavorite: "Unfavorite",
openInNewWindow: "Open in new window",
close: "Close",
more: "More",
@@ -255,6 +259,14 @@ export const enUS: Translations = {
// Chats
chats: {
searchChats: "Search chats",
pinnedSection: "Pinned",
allChats: "All",
favorites: "Favorites",
onlyFavorites: "Favorites only",
prevPage: "Previous",
nextPage: "Next",
noChats: "No conversations yet",
noFavorites: "No favorited conversations yet",
},
// Conversation sharing
@@ -586,6 +598,14 @@ export const enUS: Translations = {
targetCategoryLabel: "Install to",
categoryCustom: "Custom skill",
categoryPublic: "Built-in (admin)",
nameZhStepTitle: "Set Chinese name",
nameZhStepHint:
"Skill '{name}' is installed. You can give it a Chinese display name, or let the model generate a default one (leave blank to use the English name).",
nameZhPlaceholder: "Enter a Chinese name (optional)",
nameZhGenerate: "AI generate",
nameZhSkip: "Skip",
nameZhGenerated: "Chinese name generated",
nameZhSaved: "Chinese name saved",
},
},
skillEvolution: {
@@ -26,6 +26,10 @@ export interface Translations {
edit: string;
rename: string;
share: string;
pin: string;
unpin: string;
favorite: string;
unfavorite: string;
openInNewWindow: string;
close: string;
more: string;
@@ -198,6 +202,14 @@ export interface Translations {
// Chats
chats: {
searchChats: string;
pinnedSection: string;
allChats: string;
favorites: string;
onlyFavorites: string;
prevPage: string;
nextPage: string;
noChats: string;
noFavorites: string;
};
// Conversation sharing
@@ -511,6 +523,13 @@ export interface Translations {
targetCategoryLabel: string;
categoryCustom: string;
categoryPublic: string;
nameZhStepTitle: string;
nameZhStepHint: string;
nameZhPlaceholder: string;
nameZhGenerate: string;
nameZhSkip: string;
nameZhGenerated: string;
nameZhSaved: string;
};
};
skillEvolution: {
@@ -25,6 +25,10 @@ export const zhCN: Translations = {
edit: "编辑",
rename: "重命名",
share: "分享",
pin: "置顶",
unpin: "取消置顶",
favorite: "收藏",
unfavorite: "取消收藏",
openInNewWindow: "在新窗口打开",
close: "关闭",
more: "更多",
@@ -242,6 +246,14 @@ export const zhCN: Translations = {
// Chats
chats: {
searchChats: "搜索对话",
pinnedSection: "置顶",
allChats: "全部",
favorites: "收藏",
onlyFavorites: "只看收藏",
prevPage: "上一页",
nextPage: "下一页",
noChats: "暂无对话",
noFavorites: "暂无收藏的对话",
},
// Conversation sharing
@@ -559,6 +571,14 @@ export const zhCN: Translations = {
targetCategoryLabel: `安装到`,
categoryCustom: `自定义技能`,
categoryPublic: `内置技能(管理员)`,
nameZhStepTitle: "设置中文名",
nameZhStepHint:
"技能 “{name}” 已安装。你可以为它填写一个中文名,或让大模型自动生成一个默认中文名(留空则使用英文名)。",
nameZhPlaceholder: "请输入中文名(可留空)",
nameZhGenerate: "AI 生成",
nameZhSkip: "跳过",
nameZhGenerated: "已生成中文名称",
nameZhSaved: "已保存中文名",
},
},
skillEvolution: {
+226
View File
@@ -0,0 +1,226 @@
import { apiFetch } from "@/core/api";
import { getBackendBaseURL } from "@/core/config";
import type {
BatchIngestPayload,
BatchIngestResult,
GraphExportResult,
IngestThreadPayload,
KnowledgeListParams,
KnowledgeListResponse,
KnowledgeNote,
KnowledgeSearchItem,
VaultPage,
WikilinkResolutionMap,
} from "./types";
const baseUrl = () => `${getBackendBaseURL()}/api/knowledge`;
async function parseResponse<T>(response: Response): Promise<T> {
if (!response.ok) {
const error = await response
.json()
.catch(() => ({ detail: "Request failed" }));
const detail = error.detail;
if (typeof detail === "string") throw new Error(detail);
throw new Error("请求失败");
}
return response.json() as Promise<T>;
}
export async function listKnowledgeNotes(params: KnowledgeListParams = {}) {
const qs = new URLSearchParams();
if (params.keyword) qs.set("keyword", params.keyword);
if (params.tag) qs.set("tag", params.tag);
if (params.source_type) qs.set("source_type", params.source_type);
if (params.status) qs.set("status", params.status);
qs.set("limit", String(params.limit ?? 20));
qs.set("offset", String(params.offset ?? 0));
return parseResponse<KnowledgeListResponse>(
await apiFetch(`${baseUrl()}/notes?${qs.toString()}`),
);
}
export async function getKnowledgeNote(noteId: string) {
return parseResponse<KnowledgeNote>(
await apiFetch(`${baseUrl()}/notes/${encodeURIComponent(noteId)}`),
);
}
export async function createKnowledgeNote(data: {
title: string;
content_md: string;
summary?: string | null;
tags?: string[];
status?: string;
}) {
const res = await parseResponse<{ note: KnowledgeNote }>(
await apiFetch(`${baseUrl()}/notes`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
}),
);
return res.note;
}
export async function updateKnowledgeNote(
noteId: string,
data: Partial<{
title: string;
content_md: string;
summary: string | null;
tags: string[];
status: string;
}>,
) {
return parseResponse<KnowledgeNote>(
await apiFetch(`${baseUrl()}/notes/${encodeURIComponent(noteId)}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
}),
);
}
export async function deleteKnowledgeNote(noteId: string, hard = false) {
return parseResponse<{ ok: boolean; note_id: string }>(
await apiFetch(
`${baseUrl()}/notes/${encodeURIComponent(noteId)}${hard ? "?hard=true" : ""}`,
{ method: "DELETE" },
),
);
}
export async function searchKnowledge(query: string, limit = 8) {
const res = await parseResponse<{ items: KnowledgeSearchItem[] }>(
await apiFetch(`${baseUrl()}/search`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ query, mode: "keyword", limit }),
}),
);
return res.items;
}
export async function ingestThread(threadId: string, payload: IngestThreadPayload = {}) {
return parseResponse<{
note?: KnowledgeNote;
created?: boolean;
queued?: boolean;
}>(
await apiFetch(`${baseUrl()}/ingest/thread/${encodeURIComponent(threadId)}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
}),
);
}
export async function ingestThreadsBatch(payload: BatchIngestPayload = {}) {
return parseResponse<BatchIngestResult>(
await apiFetch(`${baseUrl()}/ingest/threads/batch`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
}),
);
}
/** Resolve `[[wikilink]]` targets to note ids / vault pages. */
export async function resolveWikilinks(targets: string[]) {
const res = await parseResponse<{ resolved: WikilinkResolutionMap }>(
await apiFetch(`${baseUrl()}/resolve`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ targets }),
}),
);
return res.resolved;
}
/** Resolve every `[[wikilink]]` inside a note's body in one call. */
export async function resolveNoteWikilinks(noteId: string) {
const res = await parseResponse<{ resolved: WikilinkResolutionMap }>(
await apiFetch(
`${baseUrl()}/notes/${encodeURIComponent(noteId)}/wikilinks`,
),
);
return res.resolved;
}
/** Fetch a raw vault meta/hub Markdown page (no DB note) by its path. */
export async function fetchVaultPage(path: string) {
return parseResponse<VaultPage>(
await apiFetch(`${baseUrl()}/vault-page?path=${encodeURIComponent(path)}`),
);
}
export async function exportKnowledgeGraph() {
return parseResponse<GraphExportResult>(
await apiFetch(`${baseUrl()}/export/graph`, { method: "POST" }),
);
}
/** Absolute URL of a served wiki-export file (for iframe / download). */
export function knowledgeExportFileUrl(filename: string) {
return `${baseUrl()}/export/files/${encodeURIComponent(filename)}`;
}
// --- phase 2/3/4 ---
export interface KnowledgeVersion {
id: string;
note_id: string;
title: string;
summary?: string | null;
content_md: string;
status: string;
tags: string[];
edited_by?: string | null;
created_at?: string | null;
}
export async function listNoteVersions(noteId: string) {
const res = await parseResponse<{ items: KnowledgeVersion[] }>(
await apiFetch(`${baseUrl()}/notes/${encodeURIComponent(noteId)}/versions`),
);
return res.items;
}
export interface DuplicateGroup {
primary: { id: string; title: string | null };
duplicates: Array<{ id: string; title: string | null; score: number }>;
}
export async function listDuplicates() {
const res = await parseResponse<{ groups: DuplicateGroup[] }>(
await apiFetch(`${baseUrl()}/duplicates`),
);
return res.groups;
}
export async function mergeKnowledgeNotes(primaryId: string, duplicateIds: string[]) {
return parseResponse<{ note: KnowledgeNote }>(
await apiFetch(`${baseUrl()}/merge`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ primary_id: primaryId, duplicate_ids: duplicateIds }),
}),
);
}
export async function reindexKnowledge() {
return parseResponse<{ reindexed: number; embedding_enabled: number }>(
await apiFetch(`${baseUrl()}/reindex`, { method: "POST" }),
);
}
export interface KnowledgeGraph {
nodes: Array<{ id: string; type: string; label: string; category?: string | null }>;
edges: Array<{ id: string; source: string; target: string; label: string; weight: number }>;
}
export async function getKnowledgeGraph() {
return parseResponse<KnowledgeGraph>(await apiFetch(`${baseUrl()}/graph`));
}
+125
View File
@@ -0,0 +1,125 @@
import {
keepPreviousData,
useMutation,
useQuery,
useQueryClient,
} from "@tanstack/react-query";
import {
createKnowledgeNote,
deleteKnowledgeNote,
exportKnowledgeGraph,
fetchVaultPage,
getKnowledgeNote,
ingestThread,
ingestThreadsBatch,
listDuplicates,
listKnowledgeNotes,
mergeKnowledgeNotes,
resolveNoteWikilinks,
searchKnowledge,
updateKnowledgeNote,
} from "./api";
import type { KnowledgeListParams } from "./types";
const ROOT_KEY = ["knowledge"] as const;
export function useKnowledgeNotes(params: KnowledgeListParams = {}) {
return useQuery({
queryKey: [...ROOT_KEY, "list", params],
queryFn: () => listKnowledgeNotes(params),
placeholderData: keepPreviousData,
refetchOnWindowFocus: false,
});
}
export function useKnowledgeNote(noteId: string | undefined) {
return useQuery({
queryKey: [...ROOT_KEY, "note", noteId],
queryFn: () => getKnowledgeNote(noteId as string),
enabled: !!noteId,
refetchOnWindowFocus: false,
});
}
export function useNoteWikilinks(noteId: string | undefined) {
return useQuery({
queryKey: [...ROOT_KEY, "wikilinks", noteId],
queryFn: () => resolveNoteWikilinks(noteId as string),
enabled: !!noteId,
refetchOnWindowFocus: false,
});
}
export function useVaultPage(path: string | undefined) {
return useQuery({
queryKey: [...ROOT_KEY, "vault-page", path],
queryFn: () => fetchVaultPage(path as string),
enabled: !!path,
refetchOnWindowFocus: false,
});
}
export function useKnowledgeSearch(query: string, enabled: boolean) {
return useQuery({
queryKey: [...ROOT_KEY, "search", query],
queryFn: () => searchKnowledge(query),
enabled: enabled && query.trim().length > 0,
placeholderData: keepPreviousData,
refetchOnWindowFocus: false,
});
}
export function useKnowledgeActions() {
const queryClient = useQueryClient();
const invalidate = () =>
queryClient.invalidateQueries({ queryKey: ROOT_KEY });
return {
create: useMutation({ mutationFn: createKnowledgeNote, onSuccess: invalidate }),
update: useMutation({
mutationFn: ({
noteId,
data,
}: {
noteId: string;
data: Parameters<typeof updateKnowledgeNote>[1];
}) => updateKnowledgeNote(noteId, data),
onSuccess: invalidate,
}),
remove: useMutation({
mutationFn: ({ noteId, hard }: { noteId: string; hard?: boolean }) =>
deleteKnowledgeNote(noteId, hard),
onSuccess: invalidate,
}),
ingestThread: useMutation({
mutationFn: ({
threadId,
payload,
}: {
threadId: string;
payload?: Parameters<typeof ingestThread>[1];
}) => ingestThread(threadId, payload),
onSuccess: invalidate,
}),
batchIngest: useMutation({
mutationFn: ingestThreadsBatch,
onSuccess: invalidate,
}),
exportGraph: useMutation({ mutationFn: exportKnowledgeGraph }),
merge: useMutation({
mutationFn: ({ primaryId, duplicateIds }: { primaryId: string; duplicateIds: string[] }) =>
mergeKnowledgeNotes(primaryId, duplicateIds),
onSuccess: invalidate,
}),
};
}
export function useKnowledgeDuplicates(enabled: boolean) {
return useQuery({
queryKey: [...ROOT_KEY, "duplicates"],
queryFn: listDuplicates,
enabled,
refetchOnWindowFocus: false,
});
}
+144
View File
@@ -0,0 +1,144 @@
export type KnowledgeStatus = "draft" | "approved" | "archived";
export type KnowledgeSourceType =
| "thread"
| "search"
| "tool"
| "file"
| "manual"
| "report";
export interface KnowledgeSource {
id: string;
note_id: string;
source_type: string;
thread_id?: string | null;
message_id?: string | null;
tool_name?: string | null;
title?: string | null;
url?: string | null;
snippet?: string | null;
created_at?: string | null;
}
export interface KnowledgeEntity {
name: string;
entity_type?: string | null;
}
export interface KnowledgeNote {
id: string;
title: string;
summary?: string | null;
content_md: string;
vault_path?: string | null;
source_type: string;
source_id?: string | null;
status: KnowledgeStatus;
confidence?: number;
created_by?: string | null;
updated_by?: string | null;
created_by_name?: string | null;
updated_by_name?: string | null;
created_at?: string | null;
updated_at?: string | null;
tags: string[];
entities?: KnowledgeEntity[];
sources?: KnowledgeSource[];
}
export interface KnowledgeListResponse {
items: KnowledgeNote[];
total: number;
}
export interface KnowledgeListParams {
keyword?: string;
tag?: string;
source_type?: string;
status?: string;
limit?: number;
offset?: number;
}
export type WikilinkKind = "note" | "vault" | "missing";
export interface WikilinkResolution {
target: string;
normalized?: string;
kind: WikilinkKind;
exists: boolean;
note_id?: string;
vault_path?: string;
title?: string;
}
/** Map of original `[[target]]` string → its resolution. */
export type WikilinkResolutionMap = Record<string, WikilinkResolution>;
export interface VaultPage {
path: string;
title: string;
content_md: string;
}
export interface KnowledgeSearchItem {
note_id: string;
chunk_id?: string | null;
title?: string | null;
summary?: string | null;
snippet?: string | null;
score: number;
tags: string[];
source_type?: string | null;
updated_at?: string | null;
}
export interface IngestThreadPayload {
mode?: "summary" | "full";
title?: string | null;
status?: KnowledgeStatus;
tags?: string[];
include_sources?: boolean;
/** When true the backend sediments asynchronously and returns immediately. */
background?: boolean;
/** Optional model override for knowledge extraction (null = configured default). */
model_name?: string | null;
}
export interface BatchIngestPayload {
limit?: number;
offset?: number;
status?: KnowledgeStatus;
include_sources?: boolean;
skip_existing?: boolean;
mode?: "summary" | "full";
/** Optional model override for knowledge extraction (null = configured default). */
model_name?: string | null;
}
export interface BatchIngestResult {
ok: boolean;
processed: number;
created: number;
skipped: number;
failed: number;
/** Notes that fell back to rule-based extraction because the model failed. */
llm_fallback?: number;
items: Array<{
thread_id: string;
note_id: string | null;
status: string;
llm_fallback?: boolean;
}>;
}
export interface GraphExportResult {
ok: boolean;
files: {
graph_json: string;
graph_html: string;
graph_graphml: string;
cypher: string;
};
stats: { nodes: number; edges: number };
}
@@ -9,6 +9,7 @@
*/
import type { ElementType } from "react";
import {
BookOpen,
Bot,
Brain,
CalendarClock,
@@ -21,20 +22,20 @@ import {
Grid3X3,
HelpCircle,
History,
Layers,
Layout,
Library,
List,
ListChecks,
ListTodo,
MessageSquareCode,
MessageSquarePlus,
Network,
NotebookPen,
Plus,
Settings,
ShieldCheck,
Sparkles,
Target,
Trophy,
Users,
} from "lucide-react";
@@ -61,8 +62,13 @@ export const sidebarMenuItems: MenuItem[] = [
path: "/page/strategy/qa/multi-agent-roundtable",
},
// { id: "expert-qa", label: "专家问答", icon: Brain, path: "/page/strategy/qa/expert-qa" },
{ id: "qa-zzjc", label: "zzjc支持", icon: Bot },
{ id: "qa-zzxd", label: "zzXD应用", icon: Layout },
{
id: "qa-zzjc",
label: "zzjc支持",
icon: Bot,
path: "/page/strategy/agents/6bf/chats/new",
},
{ id: "qa-zzxd", label: "zzXD应用", icon: Layout, path: "/page/strategy/agents/10d69686718349688e58a8790cb61024/chats/new", },
{ id: "qa-research", label: "课题研究", icon: FileText, path: "/page/canvas/ai-writing" },
],
},
@@ -209,10 +215,16 @@ export const sidebarMenuItems: MenuItem[] = [
{ id: "mgmt-agents", label: "智能体管理", icon: Bot, path: "/page/strategy/agents" },
{
id: "mgmt-business-chain-mapping",
label: "业务链条管理",
label: "配置管理",
icon: Network,
path: "/page/strategy/business-chain-mapping",
},
{
id: "mgmt-business-chains",
label: "业务链条配置",
icon: Layers,
path: "/page/strategy/business-chains",
},
{ id: "mgmt-skills", label: "技能管理", icon: Sparkles, path: "/page/strategy/skills" },
{ id: "mgmt-memory", label: "记忆管理", icon: Brain, path: "/page/strategy/memory" },
{
@@ -221,27 +233,6 @@ export const sidebarMenuItems: MenuItem[] = [
icon: ListChecks,
path: "/page/strategy/scheduled/tasks",
},
{
id: "mgmt-recommended-questions",
label: "推荐问题配置",
icon: MessageSquarePlus,
path: "/page/strategy/settings/recommended-questions",
adminOnly: true,
},
{
id: "mgmt-prompt-prefix",
label: "问答前缀配置",
icon: MessageSquareCode,
path: "/page/strategy/settings/prompt-prefix",
adminOnly: true,
},
{
id: "mgmt-private-square",
label: "私密广场配置",
icon: ShieldCheck,
path: "/page/strategy/settings/private-square",
adminOnly: true,
},
{
id: "mgmt-llm-metrics",
label: "大模型调用统计",
@@ -256,6 +247,13 @@ export const sidebarMenuItems: MenuItem[] = [
path: "/page/strategy/admin/users",
adminOnly: true,
},
{
id: "mgmt-user-leaderboard",
label: "用户排行榜",
icon: Trophy,
path: "/page/strategy/admin/user-leaderboard",
adminOnly: true,
},
{
id: "mgmt-admin-scheduled-tasks",
label: "定时任务管理",
@@ -283,6 +281,12 @@ export const sidebarMenuItems: MenuItem[] = [
icon: Network,
path: "/page/strategy/resource-management/resource-network-actor",
},
{
id: "resource-knowledge-native",
label: "知识库",
icon: BookOpen,
path: "/page/workspace/knowledge",
},
{
id: "resource-knowledge-base",
label: "知识库资源管理",
@@ -306,6 +310,7 @@ export const defaultExpandedIds: ReadonlySet<string> = new Set([
"light-app-note-management",
"task-management",
"xk-center-task",
"comprehensive-management",
]);
/** 按 admin 角色过滤菜单:非 admin 不展示 ``adminOnly: true`` 的项及其子项 */
+72
View File
@@ -430,6 +430,78 @@ export async function saveSkillFile(
return response.json() as Promise<SkillFileSaveResponse>;
}
export interface SkillNameZhResponse {
name: string;
name_zh: string | null;
}
export interface GenerateMissingSkillNameZhResponse {
generated: SkillNameZhResponse[];
failed: string[];
skipped: number;
/** Representative model error when some skills failed due to the LLM. */
model_error?: string | null;
}
/**
* Set a skill's Chinese display name. An empty string clears it (falls back to
* the English name).
*/
export async function setSkillNameZh(
skillName: string,
nameZh: string,
): Promise<SkillNameZhResponse> {
const response = await apiFetch(
`${getBackendBaseURL()}/api/skills/${encodeURIComponent(skillName)}/name-zh`,
{
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name_zh: nameZh }),
},
);
if (!response.ok) {
throw await parseDetailedError(response, "Failed to set skill Chinese name");
}
return response.json() as Promise<SkillNameZhResponse>;
}
/** Ask the LLM to generate and persist a Chinese name for a single skill. */
export async function generateSkillNameZh(
skillName: string,
modelName?: string | null,
): Promise<SkillNameZhResponse> {
const response = await apiFetch(
`${getBackendBaseURL()}/api/skills/${encodeURIComponent(skillName)}/name-zh/generate`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ model_name: modelName ?? null }),
},
);
if (!response.ok) {
throw await parseDetailedError(response, "Failed to generate skill Chinese name");
}
return response.json() as Promise<SkillNameZhResponse>;
}
/** One-click (admin): generate Chinese names for every skill that lacks one. */
export async function generateMissingSkillNameZh(
modelName?: string | null,
): Promise<GenerateMissingSkillNameZhResponse> {
const response = await apiFetch(
`${getBackendBaseURL()}/api/skills/name-zh/generate-missing`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ model_name: modelName ?? null }),
},
);
if (!response.ok) {
throw await parseDetailedError(response, "Failed to bulk-generate skill Chinese names");
}
return response.json() as Promise<GenerateMissingSkillNameZhResponse>;
}
export interface SetSkillDetailResponse {
name: string;
detail: string | null;
+37
View File
@@ -9,6 +9,8 @@ import {
deleteCustomSkill,
duplicateSkill,
enableSkill,
generateMissingSkillNameZh,
generateSkillNameZh,
getSkill,
getSkillContent,
getSkillFileContent,
@@ -17,6 +19,7 @@ import {
reconcileCustomSkills,
saveSkillFile,
setSkillDetail,
setSkillNameZh,
setSkillDisplay,
setSkillPinned,
setSkillFeatured,
@@ -90,6 +93,40 @@ export function useSetSkillDetail() {
});
}
export function useSetSkillNameZh() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ skillName, nameZh }: { skillName: string; nameZh: string }) =>
setSkillNameZh(skillName, nameZh),
onSuccess: (_data, { skillName }) => {
void queryClient.invalidateQueries({ queryKey: ["skills"] });
void queryClient.invalidateQueries({ queryKey: ["skill", skillName] });
},
});
}
export function useGenerateSkillNameZh() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ skillName, modelName }: { skillName: string; modelName?: string | null }) =>
generateSkillNameZh(skillName, modelName),
onSuccess: (_data, { skillName }) => {
void queryClient.invalidateQueries({ queryKey: ["skills"] });
void queryClient.invalidateQueries({ queryKey: ["skill", skillName] });
},
});
}
export function useGenerateMissingSkillNameZh() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (modelName?: string | null) => generateMissingSkillNameZh(modelName),
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: ["skills"] });
},
});
}
export function useSetSkillDisplay() {
const queryClient = useQueryClient();
return useMutation({
+5
View File
@@ -42,6 +42,8 @@ export interface SkillDisplayConfig extends Omit<SkillDisplayResultSetConfig, "k
export interface Skill {
name: string;
// 用户配置或大模型生成的中文名称;为空时界面回退到使用英文 name。
name_zh?: string | null;
description: string;
category: string;
license: string;
@@ -49,6 +51,9 @@ export interface Skill {
// Multitenancy fields — owner_user_id is null for built-in / public skills.
// ``builtin`` mirrors that nullness for explicit branching on the UI side.
owner_user_id?: string | null;
// Publisher username (email local part) resolved from owner_user_id by the
// backend. Null for built-in / public skills with no human owner.
owner_username?: string | null;
published?: boolean;
builtin?: boolean;
// Long-form detail/introduction authored by the skill owner or an admin.
+116 -36
View File
@@ -621,15 +621,15 @@ export function useThreadStream({
lockThreadRagMode(threadId);
}
const mergedContext = {
...context,
...extraContext,
};
await thread.submit(
{
messages: [
{
const mergedContext = {
...context,
...extraContext,
};
await thread.submit(
{
messages: [
{
type: "human",
content: [
{
@@ -647,33 +647,33 @@ export function useThreadStream({
},
],
},
{
threadId: threadId,
streamSubgraphs: true,
streamResumable: true,
config: {
recursion_limit: 1000,
},
context: {
...mergedContext,
thinking_enabled: mergedContext.mode !== "flash",
is_plan_mode:
mergedContext.mode === "pro" || mergedContext.mode === "ultra",
subagent_enabled: mergedContext.mode === "ultra",
reasoning_effort:
mergedContext.reasoning_effort ??
(mergedContext.mode === "ultra"
? "high"
: mergedContext.mode === "pro"
? "medium"
: mergedContext.mode === "thinking"
? "low"
: undefined),
memory_injection_enabled:
mergedContext.memory_injection_enabled ?? true,
rag_mode_enabled: ragModeEnabled,
thread_id: threadId,
},
{
threadId: threadId,
streamSubgraphs: true,
streamResumable: true,
config: {
recursion_limit: 1000,
},
context: {
...mergedContext,
thinking_enabled: mergedContext.mode !== "flash",
is_plan_mode:
mergedContext.mode === "pro" || mergedContext.mode === "ultra",
subagent_enabled: mergedContext.mode === "ultra",
reasoning_effort:
mergedContext.reasoning_effort ??
(mergedContext.mode === "ultra"
? "high"
: mergedContext.mode === "pro"
? "medium"
: mergedContext.mode === "thinking"
? "low"
: undefined),
memory_injection_enabled:
mergedContext.memory_injection_enabled ?? true,
rag_mode_enabled: ragModeEnabled,
thread_id: threadId,
},
},
);
void queryClient.invalidateQueries({ queryKey: ["threads", "search"] });
@@ -853,6 +853,86 @@ export function useDeleteMessage() {
});
}
/**
* Merge metadata into a conversation's record via the Gateway
* `PATCH /api/threads/{id}` route. Used to persist per-conversation flags such
* as `is_pinned` (置顶) and `is_favorite` (收藏) — a conversation belongs to a
* single user, so these live directly on the thread metadata (no join table).
* Updates the `["threads", "search"]` cache optimistically so the UI reflects
* the toggle immediately, mirroring `useRenameThread`.
*/
export function useUpdateThreadMetadata() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({
threadId,
metadata,
}: {
threadId: string;
metadata: Record<string, unknown>;
}) => {
const response = await apiFetch(
`${getBackendBaseURL()}/api/threads/${encodeURIComponent(threadId)}`,
{
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ metadata }),
},
);
if (!response.ok) {
const error = await response
.json()
.catch(() => ({ detail: "更新对话失败。" }));
throw new Error(error.detail ?? "更新对话失败。");
}
},
onSuccess(_, { threadId, metadata }) {
queryClient.setQueriesData(
{
queryKey: ["threads", "search"],
exact: false,
},
(oldData: Array<AgentThread> | undefined) => {
if (oldData == null) {
return oldData;
}
return oldData.map((t) =>
t.thread_id === threadId
? {
...t,
metadata: {
...(t.metadata as Record<string, unknown> | null),
...metadata,
},
}
: t,
);
},
);
},
});
}
/** Toggle a conversation's pinned (置顶) flag. */
export function useToggleThreadPin() {
const { mutate, ...rest } = useUpdateThreadMetadata();
return {
...rest,
toggle: (threadId: string, pinned: boolean) =>
mutate({ threadId, metadata: { is_pinned: pinned } }),
};
}
/** Toggle a conversation's favorite (收藏) flag. */
export function useToggleThreadFavorite() {
const { mutate, ...rest } = useUpdateThreadMetadata();
return {
...rest,
toggle: (threadId: string, favorite: boolean) =>
mutate({ threadId, metadata: { is_favorite: favorite } }),
};
}
export function useRenameThread() {
const queryClient = useQueryClient();
const apiClient = getAPIClient();
+5 -3
View File
@@ -18,9 +18,11 @@ export interface AgentThreadContext extends Record<string, unknown> {
reasoning_effort?: "minimal" | "low" | "medium" | "high";
writing_mode?: boolean;
writing_artifact_path?: string;
memory_injection_enabled?: boolean;
rag_mode_enabled?: boolean;
agent_id?: string;
memory_injection_enabled?: boolean;
rag_mode_enabled?: boolean;
/** Per-conversation switch for knowledge-base RAG injection (phase 2). */
knowledge_rag_enabled?: boolean;
agent_id?: string;
/** @deprecated kept for reading legacy thread metadata; prefer agent_id */
agent_name?: string;
}
+22
View File
@@ -81,6 +81,28 @@ export function titleOfThread(thread: AgentThread, fallback = "Untitled") {
return fallback;
}
export function isThreadPinned(thread: AgentThread): boolean {
return (thread.metadata as Record<string, unknown> | null)?.is_pinned === true;
}
export function isThreadFavorite(thread: AgentThread): boolean {
return (thread.metadata as Record<string, unknown> | null)?.is_favorite === true;
}
/**
* Stable sort that lifts pinned (置顶) threads to the top while preserving the
* incoming order (typically `updated_at` desc) within both the pinned and the
* unpinned group.
*/
export function sortThreadsPinnedFirst(threads: AgentThread[]): AgentThread[] {
const pinned: AgentThread[] = [];
const rest: AgentThread[] = [];
for (const thread of threads) {
(isThreadPinned(thread) ? pinned : rest).push(thread);
}
return [...pinned, ...rest];
}
export function sanitizeThreadTitleForDisplay(title: string | null | undefined) {
if (!title) return "Untitled";
+47
View File
@@ -0,0 +1,47 @@
import { apiFetch } from "@/core/api";
import { getBackendBaseURL } from "@/core/config";
export interface UserQaItem {
run_id: string;
thread_id: string;
thread_title: string;
assistant_id: string;
status: string;
model_name: string;
question: string;
answer: string;
total_tokens: number;
created_at: string;
updated_at: string;
}
export interface UserQaPageResponse {
user_id: string;
page: number;
page_size: number;
total: number;
items: UserQaItem[];
}
async function parse<T>(res: Response, what: string): Promise<T> {
if (!res.ok) {
const err = (await res.json().catch(() => ({}))) as { detail?: string };
throw new Error(err.detail ?? `${what} (HTTP ${res.status})`);
}
return res.json() as Promise<T>;
}
export async function listMyQa(
params: { page?: number; pageSize?: number; q?: string } = {},
): Promise<UserQaPageResponse> {
const search = new URLSearchParams({
page: String(params.page ?? 1),
page_size: String(params.pageSize ?? 20),
});
const query = (params.q ?? "").trim();
if (query) search.set("q", query);
return parse(
await apiFetch(`${getBackendBaseURL()}/api/users/me/qa?${search}`),
"Failed to load my Q&A",
);
}