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

# Conflicts:
#	offline-backend-20260512/backend/config.yaml
This commit is contained in:
xuhd committed 2026-06-09 15:43:40 +08:00
commit bd0eceda61
267 files changed
+41209 -14541

No files matched your search

+281
View File
@@ -35,6 +35,144 @@ export interface AdminMemoryResponse {
buckets: AdminMemoryBucket[];
}
export interface AdminUserQaItem {
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 AdminUserQaPageResponse {
user_id: string;
page: number;
page_size: number;
total: number;
items: AdminUserQaItem[];
}
export interface AdminLeaderboardUser {
user_id: string;
email: string;
system_role: string;
thread_count: number;
run_count: number;
qa_count: number;
llm_call_count: number;
tool_call_count: number;
skill_call_count: number;
total_tokens: number;
input_tokens: number;
output_tokens: number;
last_active_at: string;
}
export interface AdminLeaderboardSkill {
name: string;
call_count: number;
user_count: number;
success_count: number;
error_count: number;
avg_duration_ms: number;
last_used_at: string;
}
export interface AdminLeaderboardDimension {
name: string;
count: number;
user_count: number;
success_count: number;
error_count: number;
total_tokens: number;
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;
questions: number;
tokens: number;
users: number;
}
export interface AdminLeaderboardOverview {
total_users: number;
active_users: number;
total_threads: number;
total_runs: number;
total_questions: number;
total_tokens: number;
total_skill_calls: number;
total_tool_calls: number;
error_runs: number;
}
export interface AdminLeaderboardResponse {
range_days: number;
since: string;
until: string;
status?: "ready" | "running" | "refreshing";
generated_at?: string;
message?: string;
overview: AdminLeaderboardOverview;
users_by_activity: AdminLeaderboardUser[];
users_by_questions: AdminLeaderboardUser[];
users_by_tokens: AdminLeaderboardUser[];
skills: AdminLeaderboardSkill[];
tools: AdminLeaderboardSkill[];
models: AdminLeaderboardDimension[];
agents: AdminLeaderboardDimension[];
run_statuses: AdminLeaderboardDimension[];
recent_questions: AdminLeaderboardQuestion[];
frequent_questions: AdminLeaderboardQuestion[];
trends: AdminLeaderboardTrendPoint[];
}
export interface AdminUserAnalyticsResponse {
range_days: number;
since: string;
until: string;
user: AdminLeaderboardUser;
overview: AdminLeaderboardOverview;
skills: AdminLeaderboardSkill[];
tools: AdminLeaderboardSkill[];
models: AdminLeaderboardDimension[];
agents: AdminLeaderboardDimension[];
run_statuses: AdminLeaderboardDimension[];
recent_questions: AdminLeaderboardQuestion[];
trends: AdminLeaderboardTrendPoint[];
}
export interface AdminLeaderboardReportResponse {
report: string;
generated_at: string;
cached?: boolean;
model_name?: string | null;
}
export type AdminLeaderboardReportStreamEvent =
| { event: "meta"; data: { cached?: boolean; model_name?: string | null } }
| { event: "cached"; data: { report: string; generated_at?: string | null; model_name?: string | null } }
| { event: "thinking"; data: { chunk: string } }
| { event: "text"; data: { chunk: string } }
| { event: "done"; data: { cached?: boolean; generated_at?: string | null; model_name?: string | null; report?: string } }
| { event: "error"; data: { message: string } };
const base = () => `${getBackendBaseURL()}/api/admin/users`;
async function parse<T>(res: Response, what: string): Promise<T> {
@@ -64,6 +202,22 @@ export async function listUserThreadMessages(
);
}
export async function listUserQa(
userId: string,
params: { page?: number; pageSize?: number; q?: string } = {},
): Promise<AdminUserQaPageResponse> {
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(`${base()}/${encodeURIComponent(userId)}/qa?${search}`),
"Failed to load user Q&A",
);
}
export async function getUserMemory(
userId: string,
): Promise<AdminMemoryResponse> {
@@ -73,6 +227,133 @@ export async function getUserMemory(
);
}
export async function getUserLeaderboard(
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?${params}`),
"Failed to load leaderboard",
);
}
export async function getUserAnalytics(
userId: string,
range: { since: string; until: string; days?: number },
limit = 20,
): Promise<AdminUserAnalyticsResponse> {
const params = new URLSearchParams({
days: String(range.days ?? 30),
since: range.since,
until: range.until,
limit: String(limit),
});
return parse(
await apiFetch(`${base()}/${encodeURIComponent(userId)}/analytics?${params}`),
"Failed to load user analytics",
);
}
export async function generateUserLeaderboardReport(
range: { since: string; until: string; days?: number },
limit = 30,
modelName?: string,
): Promise<AdminLeaderboardReportResponse> {
const params = new URLSearchParams({
days: String(range.days ?? 30),
since: range.since,
until: range.until,
limit: String(limit),
});
if (modelName) params.set("model_name", modelName);
return parse(
await apiFetch(`${base()}/leaderboard/report?${params}`, {
method: "POST",
}),
"Failed to generate leaderboard report",
);
}
function parseSseFrame(frame: string): AdminLeaderboardReportStreamEvent | null {
let event = "message";
const dataLines: string[] = [];
for (const rawLine of frame.split(/\r?\n/)) {
const line = rawLine.trimEnd();
if (!line || line.startsWith(":")) continue;
if (line.startsWith("event:")) {
event = line.slice("event:".length).trim();
} else if (line.startsWith("data:")) {
dataLines.push(line.slice("data:".length).trimStart());
}
}
if (!dataLines.length) return null;
const data = JSON.parse(dataLines.join("\n")) as AdminLeaderboardReportStreamEvent["data"];
return { event, data } as AdminLeaderboardReportStreamEvent;
}
export async function streamUserLeaderboardReport({
range,
limit = 30,
modelName,
signal,
onEvent,
}: {
range: { since: string; until: string; days?: number };
limit?: number;
modelName?: string;
signal?: AbortSignal;
onEvent: (event: AdminLeaderboardReportStreamEvent) => void;
}) {
const params = new URLSearchParams({
days: String(range.days ?? 30),
since: range.since,
until: range.until,
limit: String(limit),
});
if (modelName) params.set("model_name", modelName);
const response = await apiFetch(`${base()}/leaderboard/report/stream?${params}`, {
method: "POST",
signal,
});
if (!response.ok) {
const err = (await response.json().catch(() => ({}))) as { detail?: string };
throw new Error(err.detail ?? `Failed to stream leaderboard report (HTTP ${response.status})`);
}
if (!response.body) {
throw new Error("当前浏览器不支持流式报告读取");
}
const reader = response.body.getReader();
const decoder = new TextDecoder("utf-8");
let buffer = "";
for (;;) {
const { done, value } = await reader.read();
buffer += decoder.decode(value ?? new Uint8Array(), { stream: !done });
const frames = buffer.split(/\r?\n\r?\n/);
buffer = frames.pop() ?? "";
for (const frame of frames) {
const parsed = parseSseFrame(frame);
if (parsed) onEvent(parsed);
}
if (done) break;
}
const tail = buffer.trim();
if (tail) {
const parsed = parseSseFrame(tail);
if (parsed) onEvent(parsed);
}
}
export async function addAdminMemoryEntry(
userId: string,
content: string,
+65
View File
@@ -5,7 +5,11 @@ import {
addAdminV1Fact,
deleteAdminMemoryEntry,
deleteAdminV1Fact,
generateUserLeaderboardReport,
getUserMemory,
getUserAnalytics,
getUserLeaderboard,
listUserQa,
listUserThreadMessages,
listUserThreads,
replaceAdminMemoryEntry,
@@ -13,6 +17,56 @@ import {
updateAdminV1Section,
} from "./api";
export function useUserLeaderboard(
range: {
since: string;
until: string;
days?: number;
},
limit = 20,
) {
return useQuery({
queryKey: [
"admin-activity",
"leaderboard",
range.since,
range.until,
limit,
],
queryFn: () => getUserLeaderboard(range, limit),
refetchInterval: (query) => {
const status = query.state.data?.status;
return status === "running" || status === "refreshing" ? 3000 : false;
},
});
}
export function useUserAnalytics(
userId: string | null,
range: { since: string; until: string; days?: number },
limit = 20,
) {
return useQuery({
queryKey: ["admin-activity", "analytics", userId, range.since, range.until, limit],
queryFn: () => getUserAnalytics(userId!, range, limit),
enabled: !!userId,
});
}
export function useGenerateUserLeaderboardReport() {
return useMutation({
mutationFn: ({
range,
limit,
modelName,
}: {
range: { since: string; until: string; days?: number };
limit?: number;
modelName?: string;
}) => generateUserLeaderboardReport(range, limit ?? 30, modelName),
});
}
/** Threads owned by a given user. Disabled until a user is picked. */
export function useUserThreads(userId: string | null) {
return useQuery({
@@ -22,6 +76,17 @@ export function useUserThreads(userId: string | null) {
});
}
export function useUserQa(
userId: string | null,
params: { page: number; pageSize: number; q?: string },
) {
return useQuery({
queryKey: ["admin-activity", "qa", userId, params.page, params.pageSize, params.q ?? ""],
queryFn: () => listUserQa(userId!, params),
enabled: !!userId,
});
}
/** Messages of a given thread. Disabled until a thread is picked. */
export function useUserThreadMessages(
userId: string | null,
+122 -15
View File
@@ -2,11 +2,13 @@ import { getBackendBaseURL } from "@/core/config";
import { apiFetch } from "@/core/api";
import type {
Agent,
AgentSelectorResponse,
CreateAgentRequest,
UpdateAgentRequest,
} from "./types";
Agent,
AgentSelectorResponse,
AgentSort,
CreateAgentRequest,
PaginatedAgents,
UpdateAgentRequest,
} from "./types";
const BACKEND_UNAVAILABLE_STATUSES = new Set([502, 503, 504]);
@@ -23,13 +25,27 @@ export class AgentNameCheckError extends Error {
export interface ListAgentsParams {
search?: string;
tagIds?: string[];
}
/** 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;
}
export async function listAgents(params: ListAgentsParams = {}): Promise<Agent[]> {
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);
const query = qs.toString();
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();
}
export async function listAgents(params: ListAgentsParams = {}): Promise<Agent[]> {
const query = buildAgentsQuery(params);
const res = await apiFetch(
`${getBackendBaseURL()}/api/agents${query ? `?${query}` : ""}`,
);
@@ -38,6 +54,29 @@ export async function listAgents(params: ListAgentsParams = {}): Promise<Agent[]
return data.agents;
}
/** Like {@link listAgents} but returns the pagination envelope (total/page). */
export async function listAgentsPaginated(
params: ListAgentsParams = {},
): Promise<PaginatedAgents> {
const query = buildAgentsQuery(params);
const res = await apiFetch(
`${getBackendBaseURL()}/api/agents${query ? `?${query}` : ""}`,
);
if (!res.ok) throw new Error(`Failed to load agents: ${res.statusText}`);
const data = (await res.json()) as {
agents: Agent[];
total?: number;
page?: number;
page_size?: number;
};
return {
agents: data.agents,
total: data.total ?? data.agents.length,
page: data.page ?? params.page ?? 1,
pageSize: data.page_size ?? params.pageSize ?? data.agents.length,
};
}
export async function listAllAgentsAdmin(): Promise<Agent[]> {
const res = await apiFetch(`${getBackendBaseURL()}/api/agents?admin=true`);
if (!res.ok) {
@@ -90,13 +129,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",
});
@@ -106,15 +145,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 reorderFeaturedAgents(agentIds: string[]): Promise<void> {
const res = await apiFetch(
@@ -152,6 +211,54 @@ 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;
}
/** Paginated private-square listing (password-gated). */
export async function listPrivateAgentsPaginated(
params: ListPrivateAgentsParams,
): Promise<PaginatedAgents> {
const res = await apiFetch(
`${getBackendBaseURL()}/api/agents/private-square/list`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
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,
}),
},
);
if (!res.ok) {
const err = (await res.json().catch(() => ({}))) as { detail?: string };
throw new Error(
err.detail ?? `Failed to load private agents: ${res.statusText}`,
);
}
const data = (await res.json()) as {
agents: Agent[];
total?: number;
page?: number;
page_size?: number;
};
return {
agents: data.agents,
total: data.total ?? data.agents.length,
page: data.page ?? params.page ?? 1,
pageSize: data.page_size ?? params.pageSize ?? data.agents.length,
};
}
export async function setAgentPrivate(
id: string,
isPrivate: boolean,
+165 -36
View File
@@ -3,25 +3,55 @@ import {
useMutation,
useQuery,
useQueryClient,
} from "@tanstack/react-query";
import {
} from "@tanstack/react-query";
import {
adminSyncAgentSkills,
createAgent,
deleteAgent,
favoriteAgent,
getAgent,
getAgentSelector,
listAgents,
listAllAgentsAdmin,
listPrivateAgents,
reorderFeaturedAgents,
setAgentFeatured,
setAgentPrivate,
unfavoriteAgent,
updateAgent,
} from "./api";
import type { Agent, CreateAgentRequest, UpdateAgentRequest } from "./types";
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``)
* or the paginated ``{ agents, total, ... }`` envelope. Mutators patch both. */
type CachedAgents = Agent[] | PaginatedAgents | undefined;
function isPaginated(value: CachedAgents): value is PaginatedAgents {
return !!value && !Array.isArray(value) && Array.isArray(value.agents);
}
/** Apply ``map`` to every agent inside whatever listing shape is cached. */
function mapCachedAgents(
queryClient: ReturnType<typeof useQueryClient>,
map: (a: Agent) => Agent,
) {
queryClient.setQueriesData<CachedAgents>({ queryKey: ["agents"] }, (old) => {
if (Array.isArray(old)) return old.map(map);
if (isPaginated(old)) return { ...old, agents: old.agents.map(map) };
return old;
});
}
/** Patch an updated agent into every cached agent listing immediately so
* cards re-render before the background refetch finishes. Without this the
@@ -32,13 +62,7 @@ function applyAgentToCache(
queryClient: ReturnType<typeof useQueryClient>,
next: Agent,
) {
queryClient.setQueriesData<Agent[] | undefined>(
{ queryKey: ["agents"] },
(old) => {
if (!Array.isArray(old)) return old;
return old.map((a) => (a.id === next.id ? { ...a, ...next } : a));
},
);
mapCachedAgents(queryClient, (a) => (a.id === next.id ? { ...a, ...next } : a));
}
export function useAgents(params: { search?: string; tagIds?: string[] } = {}) {
@@ -52,6 +76,45 @@ export function useAgents(params: { search?: string; tagIds?: string[] } = {}) {
return { agents: data ?? [], isLoading, error };
}
/** 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({
queryKey: [
"agents",
"paginated",
scope,
search,
[...tagIds].sort(),
sort,
page,
pageSize,
],
queryFn: () =>
listAgentsPaginated({ scope, search, tagIds, sort, page, pageSize }),
enabled,
placeholderData: keepPreviousData,
});
return {
agents: data?.agents ?? [],
total: data?.total ?? 0,
isLoading,
error,
};
}
/**
* Admin-only listing — returns every agent including unpublished agents owned
* by other users and private-square entries. Caller must be ``system_role
@@ -117,20 +180,14 @@ 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 }) =>
favorite ? favoriteAgent(id) : unfavoriteAgent(id),
onMutate: ({ id, favorite }) => {
queryClient.setQueriesData<Agent[] | undefined>(
{ queryKey: ["agents"] },
(old) =>
Array.isArray(old)
? old.map((a) =>
a.id === id ? { ...a, is_favorite: favorite } : a,
)
: old,
mapCachedAgents(queryClient, (a) =>
a.id === id ? { ...a, is_favorite: favorite } : a,
);
queryClient.setQueryData<Agent | undefined>(["agents", id], (old) =>
old ? { ...old, is_favorite: favorite } : old,
@@ -139,10 +196,30 @@ export function useToggleAgentFavorite() {
onSettled: () => {
void queryClient.invalidateQueries({ queryKey: ["agents"] });
},
});
}
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(),
@@ -153,9 +230,9 @@ export function useAgentSelector() {
isLoading,
error,
};
}
function invalidateAgentQueries(queryClient: ReturnType<typeof useQueryClient>) {
}
function invalidateAgentQueries(queryClient: ReturnType<typeof useQueryClient>) {
void queryClient.invalidateQueries({ queryKey: ["agents"] });
}
@@ -196,6 +273,58 @@ export function usePrivateAgents(password: string | null) {
return { agents: data ?? [], isLoading, error, refetch };
}
/** Paginated variant of {@link usePrivateAgents} — one page of the
* 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({
queryKey: [
"agents",
"private-square",
password ?? "",
"paginated",
search,
[...tagIds].sort(),
sort,
page,
pageSize,
],
queryFn: () =>
listPrivateAgentsPaginated({
password: password!,
search,
tagIds,
sort,
page,
pageSize,
}),
enabled: !!password && enabled,
staleTime: 30_000,
retry: false,
placeholderData: keepPreviousData,
});
return {
agents: data?.agents ?? [],
total: data?.total ?? 0,
isLoading,
error,
refetch,
};
}
export function useSetAgentPrivate() {
const queryClient = useQueryClient();
return useMutation({
+15 -4
View File
@@ -1,6 +1,6 @@
import type { Tag } from "@/core/tags";
export interface Agent {
export interface Agent {
id: string;
name: string;
description: string;
@@ -17,11 +17,22 @@ export interface Agent {
tags?: Tag[];
featured_order?: number | null;
/** Whether the current user has favorited (收藏) this agent. */
is_favorite?: boolean;
}
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[];
}
export interface AgentSelectorResponse {
/** Pagination envelope returned by the server-side paginated agent listings. */
export interface PaginatedAgents {
agents: Agent[];
total: number;
page: number;
pageSize: number;
}
export interface CreateAgentRequest {
+37 -6
View File
@@ -1,4 +1,8 @@
import { getAuthorizationHeaderValue } from "@/core/auth";
import {
clearStoredAuth,
getAuthorizationHeaderValue,
getStoredAuth,
} from "@/core/auth";
import { withCsrfHeaders } from "./csrf";
function withAuthHeaders(headers?: HeadersInit): Headers {
@@ -8,13 +12,40 @@ function withAuthHeaders(headers?: HeadersInit): Headers {
next.set("Authorization", authHeader);
}
return next;
}
export function apiFetch(input: RequestInfo | URL, init?: RequestInit) {
return fetch(input, {
}
function requestUrl(input: RequestInfo | URL): string {
if (typeof input === "string") return input;
if (input instanceof URL) return input.href;
return (input as Request).url ?? "";
}
export async function apiFetch(input: RequestInfo | URL, init?: RequestInit) {
const response = await fetch(input, {
...init,
credentials: init?.credentials ?? "include",
headers: withAuthHeaders(init?.headers),
});
// Session is considered lost ONLY when the backend actually answers 401.
// (Previously a stray localStorage change could log the user out client-side
// even though the session was still valid.) Auth endpoints are excluded so a
// failed/transient login attempt never wipes state, and we only act when we
// believed we were logged in — avoiding redirect loops on the login page.
if (response.status === 401) {
const url = requestUrl(input);
const isAuthEndpoint = url.includes("/api/v1/auth/");
if (!isAuthEndpoint && getStoredAuth()) {
clearStoredAuth();
if (
typeof window !== "undefined" &&
!window.location.hash.startsWith("#/login")
) {
window.location.replace("#/login");
}
}
}
return response;
}
+2
View File
@@ -9,6 +9,8 @@ export interface UserListItem {
system_role: "admin" | "user";
skill_count: number;
agent_count: number;
/** 问答次数:用户提问的次数(一次提问算一次)。 */
qa_count: number;
}
export async function listAllUsers(): Promise<UserListItem[]> {
+7 -35
View File
@@ -6,13 +6,7 @@ import { toast } from "sonner";
import { getStoredAuth } from "@/core/auth";
const AUTH_STORAGE_KEY = "deerflow.auth";
// 防抖窗口:跨标签页登录/重写 auth 常常在极短时间内连发多个 storage 事件
// (例如先写 token、再写用户信息)。等它"落定"再判断,避免抖动期的中间态
// (短暂 null / 半写状态)误触发动作。
const SETTLE_DELAY_MS = 1200;
// 提示 toast 的稳定 id —— 同一次身份变化只保留一条,避免连发事件刷屏。
const IDENTITY_TOAST_ID = "auth-identity-changed";
function readUserId(): string | null {
@@ -20,23 +14,8 @@ function readUserId(): string | null {
}
/**
* Mount once at the app root. Watches `localStorage["deerflow.auth"]` for
* cross-tab changes.
*
* 背景:`deerflow.auth` 在同源所有标签页之间共享。某个标签页登录/重写它时,
* 其它标签页仍持有旧用户的内存态(会话列表、thread id、以及多智能体会商这类
* 纯内存的页面状态),与新 token 不一致,可能在"新对话"等操作上 404。
*
* 旧实现:只要检测到 user_id 变化就 `window.location.reload()`。这会把**正在
* 使用的标签页**(例如正在跑多智能体会商第二步的那个)整页刷新,内存态全丢、
* 步骤回到第一步 —— 用户复制链接到新标签页打开(新标签页可能以不同/默认用户
* 重新登录并改写共享 auth)就会触发,体验很差。
*
* 现实现(方案 1,收敛粗暴刷新):
* - **真·退出登录**(auth 变为 null)→ 仍然跳登录页并刷新(本就该重新登录)。
* - **出现不同的非空用户**(另一个标签页登录成别的身份)→ **不再自动整页刷新**,
* 改为弹一条常驻提示,把"是否刷新同步"的决定权交给用户,避免冲掉正在进行的工作。
* - 防抖 + 落定后二次校验,过滤掉同用户重写 / 抖动中间态带来的误触发。
* Mount once at the app root. Watches localStorage auth changes from other
* tabs and lets the user decide when to refresh on account switches.
*/
export function AuthSyncWatcher() {
const lastUserIdRef = useRef<string | null>(readUserId());
@@ -44,26 +23,18 @@ export function AuthSyncWatcher() {
useEffect(() => {
let settleTimer: ReturnType<typeof setTimeout> | null = null;
// storage 事件落定后再判断当前的真实身份并决定动作。
function evaluateSettledIdentity() {
const nextUserId = readUserId();
if (nextUserId === lastUserIdRef.current) {
// 同用户重写,或抖动后又回到原身份 —— 无需任何动作。
return;
}
lastUserIdRef.current = nextUserId;
if (nextUserId === null) {
// 另一个标签页退出登录(或清空了 auth)→ 本标签页也该回到登录页。
lastUserIdRef.current = null;
window.location.replace("#/login");
window.location.reload();
return;
}
// 出现了不同的非空用户。共享 auth 已被改成别的身份,继续在本标签页发请求
// 可能 404 / 鉴权失败,但**不**强制刷新 —— 用户可能正在本标签页干活
// (如多智能体会商),由用户自己决定何时刷新同步。
lastUserIdRef.current = nextUserId;
toast.warning("检测到账号在其它标签页发生变化", {
id: IDENTITY_TOAST_ID,
description: "当前标签页仍是原会话。如需与新账号同步,请刷新页面。",
@@ -76,8 +47,9 @@ export function AuthSyncWatcher() {
}
function handleStorage(event: StorageEvent) {
// 只关心 auth 键的变化;event.key === null 表示 localStorage 被整体清空。
if (event.key !== null && event.key !== AUTH_STORAGE_KEY) {
// Ignore unrelated keys and localStorage.clear(). Backend session loss is
// handled centrally through 401 responses.
if (event.key !== AUTH_STORAGE_KEY) {
return;
}
if (settleTimer) {
+1 -1
View File
@@ -5,7 +5,7 @@ const CONSUMER_URL = import.meta.env.VITE_AIPI_CONSUMER_URL || "";
export const TOOLS_TOKEN_STORAGE_KEY = "tools_token";
export const EXTERNAL_USER_ID_STORAGE_KEY = "userId";
export const EXTERNAL_USER_INFO_STORAGE_KEY = "userInfo";
export const GENERAL_QA_ROUTE = "/page/strategy/qa/general";
export const GENERAL_QA_ROUTE = "/page/workspace/chats/new";
type UserDetailResponse = {
data?: {
@@ -9,6 +9,12 @@ export interface CustomPrompt {
title: string;
content: string;
sort_order?: number;
/**
* Optional association to a single agent. ``null``/absent = global (shown for
* every agent); otherwise the prompt only surfaces when that agent is
* selected.
*/
agent_id?: string | null;
created_at?: string | null;
updated_at?: string | null;
}
@@ -27,6 +33,7 @@ async function listUserPrompts(): Promise<CustomPrompt[]> {
async function createUserPrompt(input: {
title: string;
content: string;
agent_id?: string | null;
}): Promise<CustomPrompt> {
const res = await apiFetch(baseUrl(), {
method: "POST",
@@ -42,7 +49,7 @@ async function createUserPrompt(input: {
async function updateUserPrompt(
id: string,
input: { title?: string; content?: string },
input: { title?: string; content?: string; agent_id?: string | null },
): Promise<CustomPrompt> {
const res = await apiFetch(`${baseUrl()}/${encodeURIComponent(id)}`, {
method: "PUT",
@@ -93,7 +100,7 @@ export function useUpdateCustomPrompt() {
input,
}: {
id: string;
input: { title?: string; content?: string };
input: { title?: string; content?: string; agent_id?: string | null };
}) => updateUserPrompt(id, input),
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: QUERY_KEY });
@@ -82,6 +82,10 @@ export const enUS: Translations = {
inputBox: {
placeholder: "How can I assist you today?",
editQuestion: "Edit question",
deleteMessage: "Delete question and answer",
deleteMessageConfirmTitle: "Delete this question and its answer?",
deleteMessageConfirmDescription:
"The question and its answer will both be removed. This cannot be undone.",
createSkillPrompt:
"We're going to build a new skill step by step with `skill-creator`. To start, what do you want this skill to do?",
addAttachments: "Add attachments",
@@ -472,6 +476,8 @@ export const enUS: Translations = {
badgeArchivedTitle: "Archived — recoverable from the archive drawer",
badgePinned: "Pinned",
badgePinnedTitle: "Pinned — the curator will never auto-archive this skill",
badgeFeatured: "Top",
badgeFeaturedTitle: "Pinned to the top of the list",
badgeSourceAgent: "Agent-created",
badgeSourceAgentTitle: "Auto-generated by an agent during a conversation",
badgeSourceUpload: "Uploaded",
@@ -490,6 +496,10 @@ export const enUS: Translations = {
unpinAction: "Unpin",
pinSuccess: "Pinned",
unpinSuccess: "Unpinned",
featureAction: "Pin to top",
unfeatureAction: "Unpin from top",
featureSuccess: "Pinned to top",
unfeatureSuccess: "Unpinned from top",
deleteAction: "Delete skill",
deleteConfirm:
"Delete skill \"{name}\"? This cannot be undone and the skill will be removed from any agent that referenced it.",
@@ -79,6 +79,9 @@ export interface Translations {
inputBox: {
placeholder: string;
editQuestion: string;
deleteMessage: string;
deleteMessageConfirmTitle: string;
deleteMessageConfirmDescription: string;
createSkillPrompt: string;
addAttachments: string;
mode: string;
@@ -406,6 +409,8 @@ export interface Translations {
badgeArchivedTitle: string;
badgePinned: string;
badgePinnedTitle: string;
badgeFeatured: string;
badgeFeaturedTitle: string;
badgeSourceAgent: string;
badgeSourceAgentTitle: string;
badgeSourceUpload: string;
@@ -424,6 +429,10 @@ export interface Translations {
unpinAction: string;
pinSuccess: string;
unpinSuccess: string;
featureAction: string;
unfeatureAction: string;
featureSuccess: string;
unfeatureSuccess: string;
deleteAction: string;
deleteConfirm: string;
deleteSuccess: string;
+10 -1
View File
@@ -1,4 +1,4 @@
import {
import {
CompassIcon,
GraduationCapIcon,
ImageIcon,
@@ -82,6 +82,9 @@ export const zhCN: Translations = {
inputBox: {
placeholder: "今天我能为你做些什么?",
editQuestion: "编辑问题",
deleteMessage: "删除提问及回答",
deleteMessageConfirmTitle: "删除该提问及其回答?",
deleteMessageConfirmDescription: "该提问及对应的回答都会被删除,且无法恢复。",
createSkillPrompt:
"我们一起用 skill-creator 技能来创建一个技能吧。先问问我希望这个技能能做什么。",
addAttachments: "添加附件",
@@ -453,6 +456,8 @@ export const zhCN: Translations = {
badgeArchivedTitle: "已被归档,可在归档抽屉中恢复",
badgePinned: "钉选",
badgePinnedTitle: "已钉选,策展程序不会自动归档此技能",
badgeFeatured: "置顶",
badgeFeaturedTitle: "已置顶,固定显示在列表顶部",
badgeSourceAgent: "Agent 创建",
badgeSourceAgentTitle: "在对话中由 Agent 自动生成",
badgeSourceUpload: "用户上传",
@@ -471,6 +476,10 @@ export const zhCN: Translations = {
unpinAction: "取消钉选",
pinSuccess: "已钉选",
unpinSuccess: "已取消钉选",
featureAction: "置顶",
unfeatureAction: "取消置顶",
featureSuccess: "已置顶",
unfeatureSuccess: "已取消置顶",
deleteAction: "删除技能",
deleteConfirm: "确认删除技能 “{name}”?该操作不可恢复,且会从引用它的所有智能体中自动移除。",
deleteSuccess: "技能已删除",
@@ -54,15 +54,13 @@ export const sidebarMenuItems: MenuItem[] = [
icon: HelpCircle,
children: [
{ id: "general-qa", label: "通用问答", icon: CircleHelp, path: "/page/workspace/chats/new" },
{ id: "expert-qa", label: "专家问答", icon: Brain, path: "/page/strategy/qa/expert-qa" },
// 「圆桌规划」入口暂时隐藏 —— 功能仍在 /page/roundtable/planning,只是不在侧边栏出现。
// 需要重新开放时取消注释即可。
// {
// id: "qa-roundtable",
// label: "圆桌规划",
// icon: Bot,
// path: "/page/roundtable/planning",
// },
{
id: "multi-agent-roundtable",
label: "多智能体会商",
icon: Users,
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-research", label: "课题研究", icon: FileText, path: "/page/canvas/ai-writing" },
@@ -0,0 +1,141 @@
import { apiFetch } from "@/core/api";
import { getBackendBaseURL } from "@/core/config";
// Share codes share the same alphabet/shape as conversation shares, so reuse the
// extractor instead of duplicating the regex.
export { extractShareCode } from "@/core/thread-shares/api";
/**
* Roundtable-draft share modes:
* - `import` — recipient (a logged-in user) copies the 会商 draft into their own
* account and can keep working on the copy.
* - `view` — a public, read-only page anyone can open without logging in; it
* renders the draft's Step 3 result report (方案总览 HTML).
*/
export type DraftShareMode = "import" | "view";
export interface DraftShare {
share_code: string;
owner_user_id: string;
draft_id: string;
revoked: boolean;
mode: DraftShareMode;
created_at: string | null;
}
/** One sub-agent's final delivery from the Step 2 roundtable. */
export interface PublicDraftSeatDelivery {
sender: string;
content: string;
}
/** Read-only roundtable-result snapshot returned by the public view-share endpoint. */
export interface PublicDraftShareSnapshot {
share_code: string;
title: string;
mode: string;
/** 总控最终结论 (markdown). */
consensus_text: string;
/** 各席位最终交付. */
seat_deliveries: PublicDraftSeatDelivery[];
/** Self-contained Step 3 result report HTML (empty when no report exists). */
html: string;
summary: string | null;
generated_at: string | null;
has_report: boolean;
created_at: string | null;
}
export interface DraftSharePreview {
share_code: string;
shared_by: string;
title: string;
}
export interface DraftImportResult {
imported: number;
skipped: number;
draft_id: string | null;
}
const baseUrl = () => `${getBackendBaseURL()}/api/roundtable-draft-shares`;
async function parseError(response: Response, fallback: string): Promise<Error> {
const data = (await response.json().catch(() => ({}))) as { detail?: unknown };
const detail = data.detail;
const message =
typeof detail === "string" && detail
? detail
: `${fallback} (HTTP ${response.status})`;
return new Error(message);
}
/** Create (or reuse) a share code for one roundtable draft in the given mode. */
export async function createDraftShare(
draftId: string,
mode: DraftShareMode = "import",
): Promise<DraftShare> {
const response = await apiFetch(baseUrl(), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ draft_id: draftId, mode }),
});
if (!response.ok) throw await parseError(response, "创建分享失败");
return response.json() as Promise<DraftShare>;
}
/** List the current user's own roundtable-draft share links. */
export async function listDraftShares(): Promise<DraftShare[]> {
const response = await apiFetch(baseUrl());
if (!response.ok) throw await parseError(response, "加载分享列表失败");
const json = (await response.json()) as { shares: DraftShare[] };
return json.shares;
}
/** Revoke a share link so it can no longer be previewed, imported, or viewed. */
export async function revokeDraftShare(shareCode: string): Promise<void> {
const response = await apiFetch(`${baseUrl()}/${encodeURIComponent(shareCode)}`, {
method: "DELETE",
});
if (!response.ok) throw await parseError(response, "撤销分享失败");
}
/** Preview a share link before importing it. */
export async function previewDraftShare(shareCode: string): Promise<DraftSharePreview> {
const response = await apiFetch(
`${baseUrl()}/${encodeURIComponent(shareCode)}/preview`,
);
if (!response.ok) throw await parseError(response, "无法读取该分享");
return response.json() as Promise<DraftSharePreview>;
}
/** Import the roundtable draft behind a share link into the current account. */
export async function importDraftShare(shareCode: string): Promise<DraftImportResult> {
const response = await apiFetch(
`${baseUrl()}/${encodeURIComponent(shareCode)}/import`,
{ method: "POST" },
);
if (!response.ok) throw await parseError(response, "导入失败");
return response.json() as Promise<DraftImportResult>;
}
/**
* Fetch the public read-only snapshot of a `view`-mode roundtable share.
*
* Uses a plain `fetch` (no auth header) — the `/api/public/` endpoint is
* intentionally world-readable so anyone with the link can open it.
*/
export async function getPublicDraftShareSnapshot(
shareCode: string,
): Promise<PublicDraftShareSnapshot> {
const response = await fetch(
`${getBackendBaseURL()}/api/public/roundtable-shares/${encodeURIComponent(shareCode)}`,
);
if (!response.ok) throw await parseError(response, "无法打开该分享");
return response.json() as Promise<PublicDraftShareSnapshot>;
}
/** Build the shareable public URL for a `view`-mode roundtable share code. */
export function buildPublicDraftShareUrl(shareCode: string): string {
// The app uses HashRouter, so the public viewer lives at `#/roundtable-share/<code>`.
return `${window.location.origin}${window.location.pathname}#/roundtable-share/${shareCode}`;
}
@@ -0,0 +1,61 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
createDraftShare,
importDraftShare,
listDraftShares,
previewDraftShare,
revokeDraftShare,
type DraftShareMode,
} from "./api";
export function useDraftShares(enabled = true) {
return useQuery({
queryKey: ["roundtable-draft-shares"],
queryFn: listDraftShares,
enabled,
});
}
export function useCreateDraftShare() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({
draftId,
mode = "import",
}: {
draftId: string;
mode?: DraftShareMode;
}) => createDraftShare(draftId, mode),
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: ["roundtable-draft-shares"] });
},
});
}
export function useRevokeDraftShare() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (shareCode: string) => revokeDraftShare(shareCode),
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: ["roundtable-draft-shares"] });
},
});
}
export function usePreviewDraftShare() {
return useMutation({
mutationFn: (shareCode: string) => previewDraftShare(shareCode),
});
}
export function useImportDraftShare() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (shareCode: string) => importDraftShare(shareCode),
onSuccess: () => {
// Imported drafts show up in the user's roundtable history sidebar.
void queryClient.invalidateQueries({ queryKey: ["roundtable-drafts"] });
},
});
}
@@ -26,6 +26,14 @@ export type HtmlPageConfig = {
export type ScheduledTaskExecutionContext = {
require_markdown?: boolean;
/**
* The unified "必须生成 HTML" switch. The task form no longer splits "普通任务 /
* HTML 页面" into separate kinds — instead ``require_html`` and
* ``require_markdown`` are two independent toggles that may both be on. Legacy
* tasks created under the old two-tab UI still carry ``task_kind`` and are
* treated as HTML tasks by the backend for backward compatibility.
*/
require_html?: boolean;
task_kind?: ScheduledTaskKind;
html_config?: HtmlPageConfig;
[key: string]: unknown;
+7
View File
@@ -55,6 +55,13 @@ export interface LocalSettings {
* app sizes text/spacing in rem, the whole UI scales proportionally.
*/
fontScale: number;
/**
* Per-user override for the skill / agent list display mode (card vs list).
* `undefined` = follow the admin-configured system default. Set when the
* user flips the card/list toggle on the skills or agents page.
*/
skillViewMode?: "card" | "list";
agentViewMode?: "card" | "list";
};
context: Omit<
AgentThreadContext,
+20
View File
@@ -6,12 +6,14 @@ import type { Skill, SkillDisplayConfig, SkillState } from "./type";
export interface ListSkillsParams {
search?: string;
tagIds?: string[];
sort?: "time_desc" | "time_asc" | "activity_desc" | "activity_asc" | "usage_desc" | "usage_asc" | "name_asc" | "name_desc";
}
export async function loadSkills(params: ListSkillsParams = {}) {
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.sort) qs.set("sort", params.sort);
const query = qs.toString();
const skills = await apiFetch(
`${getBackendBaseURL()}/api/skills${query ? `?${query}` : ""}`,
@@ -296,6 +298,24 @@ export async function setSkillPinned(
return response.json() as Promise<Skill>;
}
export async function setSkillFeatured(
skillName: string,
featured: boolean,
): Promise<Skill> {
const response = await apiFetch(
`${getBackendBaseURL()}/api/skills/custom/${encodeURIComponent(skillName)}/featured`,
{
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ featured }),
},
);
if (!response.ok) {
throw await parseDetailedError(response, "Failed to update skill featured state");
}
return response.json() as Promise<Skill>;
}
export interface SkillContentResponse {
name: string;
category: string;
+25 -5
View File
@@ -19,23 +19,32 @@ import {
setSkillDetail,
setSkillDisplay,
setSkillPinned,
setSkillFeatured,
setSkillPublished,
setSkillState,
validateSkillUpload,
} from "./api";
import type { ListSkillsParams } from "./api";
import type { Skill, SkillState } from "./type";
import { loadAllSkillsAdmin, loadSkills } from ".";
export function useSkills(params: { search?: string; tagIds?: string[] } = {}) {
// Stable empty fallback. Returning `data ?? []` inline would hand out a fresh
// array reference on every render while the query is loading/errored, which
// makes downstream `useMemo([skills])` / `useEffect([skills])` consumers churn
// forever (observed as a "Maximum update depth exceeded" loop on NewAgentPage).
const EMPTY_SKILLS: Skill[] = [];
export function useSkills(params: ListSkillsParams = {}) {
const search = params.search ?? "";
const tagIds = params.tagIds ?? [];
const sort = params.sort ?? "time_desc";
const { data, isLoading, error } = useQuery({
queryKey: ["skills", search, [...tagIds].sort()],
queryFn: () => loadSkills({ search, tagIds }),
queryKey: ["skills", search, [...tagIds].sort(), sort],
queryFn: () => loadSkills({ search, tagIds, sort }),
placeholderData: keepPreviousData,
});
return { skills: data ?? [], isLoading, error };
return { skills: data ?? EMPTY_SKILLS, isLoading, error };
}
/**
@@ -50,7 +59,7 @@ export function useAllSkillsAdmin(enabled: boolean) {
enabled,
staleTime: 30_000,
});
return { skills: data ?? [], isLoading, error };
return { skills: data ?? EMPTY_SKILLS, isLoading, error };
}
export function useSkillContent(skillName: string | null) {
@@ -193,6 +202,17 @@ export function useSetSkillPinned() {
});
}
export function useSetSkillFeatured() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ skillName, featured }: { skillName: string; featured: boolean }) =>
setSkillFeatured(skillName, featured),
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: ["skills"] });
},
});
}
export function useDuplicateSkill() {
const queryClient = useQueryClient();
return useMutation({
+3
View File
@@ -60,9 +60,12 @@ export interface Skill {
// so stale / archived skills appear in dedicated drawers instead.
state?: SkillState;
pinned?: boolean;
// 置顶 —— 仅影响列表排序,与 pinned(防自动归档)正交。
featured?: boolean;
// Provenance — distinguishes skills created by an agent during a chat
// (``agent``) from skills the user uploaded / authored manually (``upload``).
source?: SkillSource;
created_at?: string | null;
last_activity_at?: string | null;
use_count?: number;
view_count?: number;
@@ -61,6 +61,22 @@ export interface CitationDisplayUpdate {
cleanup_words?: string[];
}
export interface LeaderboardSettings {
exclude_user_ids: string[];
include_scheduled: boolean;
include_admins: boolean;
include_failed: boolean;
cleanup_system_questions: boolean;
}
export interface LeaderboardSettingsUpdate {
exclude_user_ids?: string[];
include_scheduled?: boolean;
include_admins?: boolean;
include_failed?: boolean;
cleanup_system_questions?: boolean;
}
export async function loadPrivateSquareStatus(): Promise<PrivateSquareStatus> {
const response = await apiFetch(
`${getBackendBaseURL()}/api/system-settings/private-square`,
@@ -74,13 +90,18 @@ export async function loadPrivateSquareStatus(): Promise<PrivateSquareStatus> {
}
export type ThemeMode = "light" | "dark";
export type ViewMode = "card" | "list";
export interface AppearanceSettings {
default_theme: ThemeMode;
default_skill_view: ViewMode;
default_agent_view: ViewMode;
}
export interface AppearanceUpdate {
default_theme?: ThemeMode;
default_skill_view?: ViewMode;
default_agent_view?: ViewMode;
}
export async function loadAppearanceSettings(): Promise<AppearanceSettings> {
@@ -127,6 +148,36 @@ export async function loadCitationDisplaySettings(): Promise<CitationDisplaySett
return (await response.json()) as CitationDisplaySettings;
}
export async function loadLeaderboardSettings(): Promise<LeaderboardSettings> {
const response = await apiFetch(
`${getBackendBaseURL()}/api/system-settings/leaderboard`,
);
if (!response.ok) {
throw new Error(`Failed to load leaderboard settings: ${response.status}`);
}
return (await response.json()) as LeaderboardSettings;
}
export async function updateLeaderboardSettings(
body: LeaderboardSettingsUpdate,
): Promise<LeaderboardSettings> {
const response = await apiFetch(
`${getBackendBaseURL()}/api/system-settings/leaderboard`,
{
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
},
);
if (!response.ok) {
const detail = await response
.json()
.catch(() => ({ detail: "Failed to update leaderboard settings" }));
throw new Error(detail.detail ?? "Failed to update leaderboard settings");
}
return (await response.json()) as LeaderboardSettings;
}
export async function updateCitationDisplaySettings(
body: CitationDisplayUpdate,
): Promise<CitationDisplaySettings> {
@@ -147,6 +198,22 @@ export async function updateCitationDisplaySettings(
return (await response.json()) as CitationDisplaySettings;
}
export interface LogSystemSettings {
enabled: boolean;
url: string;
label: string;
}
export async function loadLogSystemSettings(): Promise<LogSystemSettings> {
const response = await apiFetch(
`${getBackendBaseURL()}/api/system-settings/log-system`,
);
if (!response.ok) {
throw new Error(`Failed to load log system settings: ${response.status}`);
}
return (await response.json()) as LogSystemSettings;
}
export async function updatePrivateSquareSettings(
body: PrivateSquareUpdate,
): Promise<PrivateSquareStatus> {
@@ -1,24 +1,31 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useLocalSettings } from "@/core/settings";
import {
loadAppearanceSettings,
loadCitationDisplaySettings,
loadLeaderboardSettings,
loadPrivateSquareStatus,
loadPromptPrefixSettings,
updateAppearanceSettings,
updateCitationDisplaySettings,
updateLeaderboardSettings,
updatePrivateSquareSettings,
updatePromptPrefixSettings,
type AppearanceUpdate,
type CitationDisplayUpdate,
type LeaderboardSettingsUpdate,
type PrivateSquareUpdate,
type PromptPrefixUpdate,
type ViewMode,
} from "./api";
const PROMPT_PREFIX_KEY = ["systemSettings", "promptPrefix"] as const;
const PRIVATE_SQUARE_KEY = ["systemSettings", "privateSquare"] as const;
const APPEARANCE_KEY = ["systemSettings", "appearance"] as const;
const CITATION_DISPLAY_KEY = ["systemSettings", "citationDisplay"] as const;
const LEADERBOARD_KEY = ["systemSettings", "leaderboard"] as const;
export function usePromptPrefixSettings() {
return useQuery({
@@ -82,6 +89,31 @@ export function useUpdateAppearanceSettings() {
});
}
/**
* Effective card/list display mode for the skill or agent list. A user's own
* choice (persisted in local settings) wins; otherwise the admin-configured
* system default applies; otherwise a built-in fallback (skills → list,
* agents → card, matching the historical layout of each page). `setMode`
* persists the user's override locally.
*/
export function useViewMode(
kind: "skill" | "agent",
): [ViewMode, (mode: ViewMode) => void] {
const [settings, setSettings] = useLocalSettings();
const { data: appearance } = useAppearanceSettings();
const overrideKey = kind === "skill" ? "skillViewMode" : "agentViewMode";
const userOverride = settings.display[overrideKey];
const adminDefault =
kind === "skill"
? appearance?.default_skill_view
: appearance?.default_agent_view;
const fallback: ViewMode = kind === "skill" ? "list" : "card";
const mode: ViewMode = userOverride ?? adminDefault ?? fallback;
const setMode = (next: ViewMode) =>
setSettings("display", { [overrideKey]: next });
return [mode, setMode];
}
export function useCitationDisplaySettings() {
return useQuery({
queryKey: CITATION_DISPLAY_KEY,
@@ -102,3 +134,25 @@ export function useUpdateCitationDisplaySettings() {
},
});
}
export function useLeaderboardSettings() {
return useQuery({
queryKey: LEADERBOARD_KEY,
queryFn: () => loadLeaderboardSettings(),
staleTime: 60_000,
refetchOnWindowFocus: false,
retry: false,
});
}
export function useUpdateLeaderboardSettings() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (body: LeaderboardSettingsUpdate) =>
updateLeaderboardSettings(body),
onSuccess: (data) => {
queryClient.setQueryData(LEADERBOARD_KEY, data);
queryClient.invalidateQueries({ queryKey: ["admin-activity", "leaderboard"] });
},
});
}
+49 -6
View File
@@ -350,12 +350,12 @@ export function useThreadStream({
// agent thread URL — otherwise fall back to the global new chat.
const hash = typeof window !== "undefined" ? window.location.hash : "";
const agentMatch = hash.match(/#\/page\/workspace\/agents\/([^/]+)\//);
const iframeMatch = hash.match(/#\/page\/workspace\/chats_iframe\//);
const target = agentMatch
? `/page/workspace/agents/${agentMatch[1]}/chats/new`
: iframeMatch
? "/page/workspace/chats_iframe/new"
: "/page/workspace/chats/new";
const iframeMatch = hash.match(/#\/page\/workspace\/chats_iframe\//);
const target = agentMatch
? `/page/workspace/agents/${agentMatch[1]}/chats/new`
: iframeMatch
? "/page/workspace/chats_iframe/new"
: "/page/workspace/chats/new";
// First navigate to a safe URL so the post-reload page lands on a
// valid route. Then full-reload so TanStack Query cache, context
// providers and any other state captured under the previous user's
@@ -810,6 +810,49 @@ export function useDeleteThread() {
});
}
/**
* Delete a conversation turn (a user question together with its answer) from a
* thread. Hits the Gateway endpoint that removes the question and every
* following message up to the next question from the latest checkpoint, and
* returns the ids that were actually removed. The live `useStream` cache is not
* auto-refreshed by this call — callers hide the returned ids locally (see
* `MessageList`) so the removal shows immediately; a reload then reads the
* persisted, already-trimmed state.
*/
export function useDeleteMessage() {
return useMutation({
mutationFn: async ({
threadId,
messageId,
}: {
threadId: string;
messageId: string;
}): Promise<string[]> => {
const response = await apiFetch(
`${getBackendBaseURL()}/api/threads/${encodeURIComponent(
threadId,
)}/messages/${encodeURIComponent(messageId)}`,
{
method: "DELETE",
},
);
if (!response.ok) {
const error = await response
.json()
.catch(() => ({ detail: "删除消息失败。" }));
throw new Error(error.detail ?? "删除消息失败。");
}
const body = (await response.json().catch(() => ({}))) as {
deleted_ids?: string[];
};
// Fall back to the requested id so the caller can always hide something.
return body.deleted_ids?.length ? body.deleted_ids : [messageId];
},
});
}
export function useRenameThread() {
const queryClient = useQueryClient();
const apiClient = getAPIClient();
@@ -0,0 +1,85 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { apiFetch } from "@/core/api";
import { getBackendBaseURL } from "@/core/config";
/** Per-user UI preferences, bound to the account (stored server-side). */
export interface UserPreferences {
/**
* When true, the chat input hides the admin-configured prompt-prefix switch
* and never applies the prefix — the user uses only their own prompts.
*/
hide_admin_prompt_prefix: boolean;
}
const QUERY_KEY = ["user-preferences"] as const;
const DEFAULT_PREFS: UserPreferences = { hide_admin_prompt_prefix: false };
const baseUrl = () => `${getBackendBaseURL()}/api/user-preferences`;
async function getUserPreferences(): Promise<UserPreferences> {
const res = await apiFetch(baseUrl());
if (!res.ok) throw new Error(`Failed to load preferences: ${res.statusText}`);
const data = (await res.json()) as Partial<UserPreferences>;
return { hide_admin_prompt_prefix: !!data.hide_admin_prompt_prefix };
}
async function updateUserPreferences(
input: Partial<UserPreferences>,
): Promise<UserPreferences> {
const res = await apiFetch(baseUrl(), {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(input),
});
if (!res.ok) {
const err = (await res.json().catch(() => ({}))) as { detail?: string };
throw new Error(err.detail ?? `Failed to update preferences: ${res.statusText}`);
}
const data = (await res.json()) as Partial<UserPreferences>;
return { hide_admin_prompt_prefix: !!data.hide_admin_prompt_prefix };
}
/** Reactive current-user preferences (server-backed, follows the account). */
export function useUserPreferences(): UserPreferences {
const { data } = useQuery({
queryKey: QUERY_KEY,
queryFn: getUserPreferences,
});
return data ?? DEFAULT_PREFS;
}
export function useUserPreferencesQuery() {
return useQuery({
queryKey: QUERY_KEY,
queryFn: getUserPreferences,
});
}
export function useUpdateUserPreferences() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: updateUserPreferences,
// Optimistically flip the cached preference so the switch — and every
// surface that reacts to it (e.g. the chat input's admin prompt-prefix
// toggle) — updates instantly instead of waiting for the round-trip,
// which made the toggle look like it "didn't take effect / didn't refresh".
onMutate: async (input) => {
await queryClient.cancelQueries({ queryKey: QUERY_KEY });
const previous = queryClient.getQueryData<UserPreferences>(QUERY_KEY);
queryClient.setQueryData<UserPreferences>(QUERY_KEY, (old) => ({
...(old ?? DEFAULT_PREFS),
...input,
}));
return { previous };
},
onError: (_err, _input, context) => {
// Roll back to the pre-toggle value if the server rejected the change.
if (context?.previous) {
queryClient.setQueryData(QUERY_KEY, context.previous);
}
},
onSuccess: (data) => {
queryClient.setQueryData(QUERY_KEY, data);
},
});
}
+5 -4
View File
@@ -94,10 +94,11 @@ const extensionMap: Record<string, string> = {
ini: "ini",
env: "dotenv",
// Markdown & Docs
md: "markdown",
mdx: "mdx",
rst: "rst",
// Markdown & Docs
md: "markdown",
mdx: "mdx",
mmd: "mermaid",
rst: "rst",
// SQL
sql: "sql",
+196 -10
View File
@@ -1,10 +1,196 @@
export function extractTitleFromMarkdown(markdown: string) {
if (markdown.startsWith("# ")) {
let title = markdown.split("\n")[0]!.trim();
if (title.startsWith("# ")) {
title = title.slice(2).trim();
}
return title;
}
return undefined;
}
export function extractTitleFromMarkdown(markdown: string) {
if (markdown.startsWith("# ")) {
let title = markdown.split("\n")[0]!.trim();
if (title.startsWith("# ")) {
title = title.slice(2).trim();
}
return title;
}
return undefined;
}
export type MarkdownHeadingAnchor = {
level: number;
text: string;
id: string;
};
export type MarkdownAnchorResolver = {
headings: MarkdownHeadingAnchor[];
getHeadingId: (level: number, text: string) => string | undefined;
resolveHref: (href: string | undefined, label?: string) => string | null | undefined;
};
const HEADING_RE = /^(#{1,6})\s+(.+?)\s*#*\s*$/;
const PROTOCOL_RE = /^[a-z][a-z\d+.-]*:/i;
function stripInlineMarkdown(value: string): string {
return value
.replace(/!\[([^\]]*)\]\([^)]+\)/g, "$1")
.replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
.replace(/[`*_~]/g, "")
.replace(/<[^>]+>/g, "")
.trim();
}
export function markdownSlug(value: string): string {
const cleaned = stripInlineMarkdown(value)
.normalize("NFKC")
.toLowerCase()
.replace(/[^\p{L}\p{N}\s._-]+/gu, "")
.trim()
.replace(/[\s._-]+/g, "-")
.replace(/^-+|-+$/g, "");
return cleaned || "section";
}
function decodeLinkPart(value: string): string {
try {
return decodeURIComponent(value);
} catch {
return value;
}
}
/** True for hrefs that point to an anchor within the current document (`#section`). */
export function isInPageAnchor(href: string | undefined | null): href is string {
return !!href && href.startsWith("#") && !href.startsWith("#reference-");
}
function escapeAttrValue(value: string): string {
return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
}
/**
* Scrolls to an in-page anchor by id without mutating `window.location.hash`.
*
* The app runs under a HashRouter, so letting an `<a href="#...">` click change
* the hash would be interpreted as a route change and 404. We resolve the target
* element ourselves and scroll to it instead. Scoped to the nearest
* `[data-markdown-anchor-root]` so headings in other messages don't collide.
*/
export function scrollToInPageAnchor(anchor: HTMLElement, href: string | undefined | null): void {
if (!isInPageAnchor(href)) return;
const id = decodeLinkPart(href.slice(1)).trim();
if (!id) return;
const scope = anchor.closest<HTMLElement>("[data-markdown-anchor-root]");
const selector = `[id="${escapeAttrValue(id)}"]`;
const target =
(scope?.querySelector<HTMLElement>(selector) ?? null) ??
document.getElementById(id) ??
document.querySelector<HTMLElement>(selector);
target?.scrollIntoView({ behavior: "smooth", block: "start" });
}
function normalizeLookupKey(value: string): string {
return markdownSlug(decodeLinkPart(value).replace(/^#+/, ""));
}
function isExternalOrSpecialHref(href: string): boolean {
if (href.startsWith("//")) return true;
if (PROTOCOL_RE.test(href)) return true;
return href.startsWith("/") || href.startsWith("?");
}
function candidateTextFromHref(href: string): string {
const withoutQuery = href.split(/[?#]/)[0] ?? href;
const lastSegment = withoutQuery.split("/").filter(Boolean).pop() ?? withoutQuery;
return decodeLinkPart(lastSegment).replace(/\.(md|markdown)$/i, "");
}
/**
* Injects a small runtime script into generated HTML so that clicking an
* in-page anchor (`<a href="#section">`) scrolls within the iframe instead of
* navigating it. The preview iframe loads from a sandboxed `blob:` URL, where a
* fragment navigation blanks the frame; intercepting the click avoids that.
*/
export function injectInPageAnchorHandler(html: string): string {
const script = `<script>(function(){
function decode(v){try{return decodeURIComponent(v);}catch(e){return v;}}
function bySelector(id){
if(!document.querySelector)return null;
var esc=window.CSS&&CSS.escape?CSS.escape(id):id.replace(/["\\\\]/g,"\\\\$&");
try{return document.querySelector("#"+esc+",[name=\\""+esc+"\\"]");}catch(e){return null;}
}
document.addEventListener("click",function(e){
var el=e.target;
while(el&&el.tagName!=="A"){el=el.parentElement;}
if(!el)return;
var href=el.getAttribute("href");
if(!href||href.charAt(0)!=="#"||href.length<2)return;
e.preventDefault();
var id=decode(href.slice(1));
var raw=href.slice(1);
var target=
document.getElementById(id)||
document.getElementById(raw)||
document.getElementsByName(id)[0]||
document.getElementsByName(raw)[0]||
bySelector(id)||
bySelector(raw);
if(target){target.scrollIntoView({behavior:"smooth",block:"start"});}
},true);
})();</script>`;
if (/<\/body>/i.test(html)) {
return html.replace(/<\/body>/i, `${script}</body>`);
}
return html + script;
}
export function createMarkdownAnchorResolver(markdown: string): MarkdownAnchorResolver {
const headings: MarkdownHeadingAnchor[] = [];
const idsByLookup = new Map<string, string>();
const seen = new Map<string, number>();
let inFence = false;
for (const rawLine of markdown.split(/\r?\n/)) {
const line = rawLine.trim();
if (/^(```|~~~)/.test(line)) {
inFence = !inFence;
continue;
}
if (inFence) continue;
const match = HEADING_RE.exec(rawLine);
if (!match) continue;
const level = match[1]!.length;
const text = stripInlineMarkdown(match[2]!);
const baseId = markdownSlug(text);
const count = seen.get(baseId) ?? 0;
seen.set(baseId, count + 1);
const id = count === 0 ? baseId : `${baseId}-${count}`;
headings.push({ level, text, id });
idsByLookup.set(normalizeLookupKey(text), id);
idsByLookup.set(normalizeLookupKey(id), id);
}
return {
headings,
getHeadingId: (level: number, text: string) => {
void level;
return idsByLookup.get(normalizeLookupKey(text));
},
resolveHref: (href: string | undefined, label?: string) => {
if (!href) return href;
const trimmed = href.trim();
if (!trimmed || isExternalOrSpecialHref(trimmed)) return href;
const hash = trimmed.includes("#") ? trimmed.slice(trimmed.indexOf("#") + 1) : "";
const candidates = [
hash,
trimmed.startsWith("#") ? trimmed.slice(1) : "",
candidateTextFromHref(trimmed),
label ?? "",
].filter(Boolean);
for (const candidate of candidates) {
const id = idsByLookup.get(normalizeLookupKey(candidate));
if (id) return `#${id}`;
}
return trimmed.startsWith("#") ? null : null;
},
};
}
+75
View File
@@ -0,0 +1,75 @@
import { getFileName } from "./files";
let mermaidInitialized = false;
export function isMermaidFile(filepath: string): boolean {
return /\.mmd$/i.test(filepath);
}
export function getMermaidImageFileName(filepath: string, extension = "svg"): string {
return getFileName(filepath).replace(/\.mmd$/i, `.${extension}`);
}
async function getMermaidModule() {
const mod = await import("mermaid");
const mermaid = mod.default;
if (!mermaidInitialized) {
mermaid.initialize({
startOnLoad: false,
securityLevel: "strict",
});
mermaidInitialized = true;
}
return mermaid;
}
export async function renderMermaidToSvg(source: string): Promise<string> {
const text = source.trim();
if (!text) {
throw new Error("Mermaid 内容为空,无法生成图片");
}
const mermaid = await getMermaidModule();
const renderId = `mermaid-preview-${Math.random().toString(36).slice(2, 10)}`;
const host = document.createElement("div");
host.style.position = "fixed";
host.style.left = "-10000px";
host.style.top = "-10000px";
host.style.pointerEvents = "none";
host.style.opacity = "0";
document.body.appendChild(host);
try {
const { svg, bindFunctions } = await mermaid.render(renderId, text);
host.innerHTML = svg;
bindFunctions?.(host);
return host.innerHTML;
} finally {
host.remove();
}
}
export async function openMermaidSvgInNewTab(source: string): Promise<void> {
const svg = await renderMermaidToSvg(source);
const blob = new Blob([svg], { type: "image/svg+xml;charset=utf-8" });
const objectUrl = URL.createObjectURL(blob);
const win = window.open(objectUrl, "_blank", "noopener,noreferrer");
if (win) {
win.opener = null;
}
window.setTimeout(() => URL.revokeObjectURL(objectUrl), 120_000);
}
export async function downloadMermaidSvgFile(source: string, filepath: string): Promise<void> {
const svg = await renderMermaidToSvg(source);
const blob = new Blob([svg], { type: "image/svg+xml;charset=utf-8" });
const objectUrl = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = objectUrl;
a.download = getMermaidImageFileName(filepath);
a.rel = "noopener";
document.body.appendChild(a);
a.click();
a.remove();
window.setTimeout(() => URL.revokeObjectURL(objectUrl), 30_000);
}