This commit is contained in:
吉鑫升 committed 2026-06-04 14:28:22 +08:00
commit 9704eff9f7
42 files changed
+1973 -10517

No files matched your search

+84 -2
View File
@@ -5,6 +5,7 @@ import type {
Agent,
AgentSelectorResponse,
CreateAgentRequest,
PaginatedAgents,
UpdateAgentRequest,
} from "./types";
@@ -23,13 +24,25 @@ 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;
}
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));
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 +51,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) {
@@ -152,6 +188,52 @@ export async function listPrivateAgents(password: string): Promise<Agent[]> {
return data.agents;
}
export interface ListPrivateAgentsParams {
password: string;
search?: string;
tagIds?: string[];
page?: number;
pageSize?: number;
}
/** 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,
}),
},
);
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,
+115 -16
View File
@@ -13,15 +13,42 @@ import {
getAgent,
getAgentSelector,
listAgents,
listAgentsPaginated,
listAllAgentsAdmin,
listPrivateAgents,
listPrivateAgentsPaginated,
reorderFeaturedAgents,
setAgentFeatured,
setAgentPrivate,
unfavoriteAgent,
updateAgent,
} from "./api";
import type { Agent, CreateAgentRequest, UpdateAgentRequest } from "./types";
import type {
Agent,
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 +59,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 +73,42 @@ 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[];
page: number;
pageSize: number;
enabled?: boolean;
}) {
const { scope, page, pageSize, enabled = true } = params;
const search = params.search ?? "";
const tagIds = params.tagIds ?? [];
const { data, isLoading, error } = useQuery({
queryKey: [
"agents",
"paginated",
scope,
search,
[...tagIds].sort(),
page,
pageSize,
],
queryFn: () =>
listAgentsPaginated({ scope, search, tagIds, 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
@@ -123,14 +180,8 @@ export function useToggleAgentFavorite() {
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,
@@ -196,6 +247,54 @@ 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[];
page: number;
pageSize: number;
enabled?: boolean;
},
) {
const { page, pageSize, enabled = true } = params;
const search = params.search ?? "";
const tagIds = params.tagIds ?? [];
const { data, isLoading, error, refetch } = useQuery({
queryKey: [
"agents",
"private-square",
password ?? "",
"paginated",
search,
[...tagIds].sort(),
page,
pageSize,
],
queryFn: () =>
listPrivateAgentsPaginated({
password: password!,
search,
tagIds,
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({
+8
View File
@@ -24,6 +24,14 @@ export interface AgentSelectorResponse {
agents: Agent[];
}
/** Pagination envelope returned by the server-side paginated agent listings. */
export interface PaginatedAgents {
agents: Agent[];
total: number;
page: number;
pageSize: number;
}
export interface CreateAgentRequest {
name: string;
description?: string;
@@ -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 });
@@ -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;
+8 -2
View File
@@ -27,6 +27,12 @@ import type { Skill, SkillState } from "./type";
import { loadAllSkillsAdmin, loadSkills } from ".";
// 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: { search?: string; tagIds?: string[] } = {}) {
const search = params.search ?? "";
const tagIds = params.tagIds ?? [];
@@ -35,7 +41,7 @@ export function useSkills(params: { search?: string; tagIds?: string[] } = {}) {
queryFn: () => loadSkills({ search, tagIds }),
placeholderData: keepPreviousData,
});
return { skills: data ?? [], isLoading, error };
return { skills: data ?? EMPTY_SKILLS, isLoading, error };
}
/**
@@ -50,7 +56,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) {
@@ -0,0 +1,59 @@
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 useUpdateUserPreferences() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: updateUserPreferences,
onSuccess: (data) => {
queryClient.setQueryData(QUERY_KEY, data);
},
});
}