Add managed tree categories for agents
Some checks failed
Lint / build (20) (push) Has been cancelled
Playwright Tests / test (push) Has been cancelled

This commit is contained in:
Your Name 2026-03-12 17:49:54 +08:00
parent 6936a2c203
commit c2a0568148
12 changed files with 556 additions and 142 deletions

View File

@ -230,6 +230,12 @@ type SiteSettings = {
rankingEnabled: boolean;
canvasEnabled: boolean;
agentEnabled: boolean;
agentCategoryTreeConfig: {
productCategories: string[];
audienceTags: string[];
usageScenarios: string[];
brands: string[];
};
realtimeCanvasEnabled: boolean;
aiDetailGenerationEnabled: boolean;
canvasDefaultModelId: string | null;
@ -620,6 +626,12 @@ export function AdminSettingsClient() {
rankingEnabled: true,
canvasEnabled: true,
agentEnabled: true,
agentCategoryTreeConfig: {
productCategories: [],
audienceTags: [],
usageScenarios: [],
brands: [],
},
realtimeCanvasEnabled: true,
aiDetailGenerationEnabled: false,
canvasDefaultModelId: null,
@ -692,6 +704,20 @@ export function AdminSettingsClient() {
rankingEnabled: siteSettingsData.rankingEnabled ?? true,
canvasEnabled: siteSettingsData.canvasEnabled ?? true,
agentEnabled: (siteSettingsData as any).agentEnabled ?? true,
agentCategoryTreeConfig: {
productCategories: Array.isArray((siteSettingsData as any).agentCategoryTreeConfig?.productCategories)
? (siteSettingsData as any).agentCategoryTreeConfig.productCategories
: [],
audienceTags: Array.isArray((siteSettingsData as any).agentCategoryTreeConfig?.audienceTags)
? (siteSettingsData as any).agentCategoryTreeConfig.audienceTags
: [],
usageScenarios: Array.isArray((siteSettingsData as any).agentCategoryTreeConfig?.usageScenarios)
? (siteSettingsData as any).agentCategoryTreeConfig.usageScenarios
: [],
brands: Array.isArray((siteSettingsData as any).agentCategoryTreeConfig?.brands)
? (siteSettingsData as any).agentCategoryTreeConfig.brands
: [],
},
realtimeCanvasEnabled: (siteSettingsData as any).realtimeCanvasEnabled ?? true,
aiDetailGenerationEnabled: siteSettingsData.aiDetailGenerationEnabled ?? false,
canvasDefaultModelId: siteSettingsData.canvasDefaultModelId || null,
@ -5308,6 +5334,103 @@ export function AdminSettingsClient() {
/>
</div>
{siteSettings.agentEnabled && (
<div className="rounded-lg border p-4 space-y-4">
<div>
<div className="font-medium">智能体树形分类配置</div>
<div className="text-xs text-muted-foreground mt-1">
固定四级分类:产品品类 / 人群标签 / 使用场景 / 品牌。用户创建和筛选智能体时统一从这里选择,不再支持自定义创建分类。
</div>
</div>
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
<div className="space-y-2">
<Label>一级分类:产品品类</Label>
<Textarea
value={siteSettings.agentCategoryTreeConfig.productCategories.join("\n")}
onChange={(event) =>
setSiteSettings({
...siteSettings,
agentCategoryTreeConfig: {
...siteSettings.agentCategoryTreeConfig,
productCategories: event.target.value
.split("\n")
.map((item) => item.trim())
.filter(Boolean),
},
})
}
rows={6}
placeholder={"例如:\n沙发\n床垫\n护肤品\n咖啡机"}
/>
</div>
<div className="space-y-2">
<Label>二级分类:人群标签</Label>
<Textarea
value={siteSettings.agentCategoryTreeConfig.audienceTags.join("\n")}
onChange={(event) =>
setSiteSettings({
...siteSettings,
agentCategoryTreeConfig: {
...siteSettings.agentCategoryTreeConfig,
audienceTags: event.target.value
.split("\n")
.map((item) => item.trim())
.filter(Boolean),
},
})
}
rows={6}
placeholder={"例如:\n宝妈\n年轻白领\n学生\n户外人群"}
/>
</div>
<div className="space-y-2">
<Label>三级分类:使用场景</Label>
<Textarea
value={siteSettings.agentCategoryTreeConfig.usageScenarios.join("\n")}
onChange={(event) =>
setSiteSettings({
...siteSettings,
agentCategoryTreeConfig: {
...siteSettings.agentCategoryTreeConfig,
usageScenarios: event.target.value
.split("\n")
.map((item) => item.trim())
.filter(Boolean),
},
})
}
rows={6}
placeholder={"例如:\n客厅\n卧室\n办公室\n户外露营"}
/>
</div>
<div className="space-y-2">
<Label>四级分类:品牌</Label>
<Textarea
value={siteSettings.agentCategoryTreeConfig.brands.join("\n")}
onChange={(event) =>
setSiteSettings({
...siteSettings,
agentCategoryTreeConfig: {
...siteSettings.agentCategoryTreeConfig,
brands: event.target.value
.split("\n")
.map((item) => item.trim())
.filter(Boolean),
},
})
}
rows={6}
placeholder={"例如:\n宜家\n华为\n兰蔻\n戴森"}
/>
</div>
</div>
</div>
)}
<div className="flex items-center justify-between rounded-lg border p-3">
<div className="space-y-0.5">
<Label htmlFor="realtimeCanvasEnabled">实时画布功能</Label>

View File

@ -22,23 +22,21 @@ const updateAgentSchema = z
name: z.string().trim().min(1).max(128).optional(),
type: z.enum(["image", "video"]).optional(),
visibility: z.enum(["public", "private"]).optional(),
categoryId: z.string().uuid().nullable().optional(),
newCategoryName: z.string().trim().min(1).max(64).optional(),
categoryPath: z
.object({
productCategory: z.string().trim().max(64).optional(),
audienceTag: z.string().trim().max(64).optional(),
usageScenario: z.string().trim().max(64).optional(),
brand: z.string().trim().max(64).optional(),
})
.nullable()
.optional(),
description: z.string().trim().max(2000).nullable().optional(),
defaultModelId: z.string().uuid().optional(),
defaultParams: z.record(z.string(), z.any()).nullable().optional(),
avatarAssetId: z.string().uuid().nullable().optional(),
slots: z.array(slotSchema).min(1).max(20).optional(),
status: z.enum(["active", "disabled", "hidden", "blocked"]).optional(),
})
.superRefine((value, ctx) => {
if (value.categoryId && value.newCategoryName) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "categoryId 和 newCategoryName 不能同时传入",
path: ["newCategoryName"],
});
}
});
export async function GET(
@ -93,8 +91,7 @@ export async function PUT(
name: data.name,
type: data.type,
visibility: data.visibility,
categoryId: data.categoryId ?? undefined,
newCategoryName: data.newCategoryName,
categoryPath: data.categoryPath ?? undefined,
description: data.description ?? undefined,
defaultModelId: data.defaultModelId,
defaultParams: data.defaultParams ?? undefined,

View File

@ -4,14 +4,16 @@ import { auth } from "@/app/(auth)/auth";
import { ChatSDKError } from "@/lib/errors";
import {
createAgentPreset,
getVisibleAgentCategories,
getVisibleAgentPresets,
} from "@/lib/db/queries";
const listQuerySchema = z.object({
scope: z.enum(["all", "public", "private"]).default("all"),
type: z.enum(["image", "video"]).optional(),
categoryId: z.string().uuid().optional(),
productCategory: z.string().trim().max(64).optional(),
audienceTag: z.string().trim().max(64).optional(),
usageScenario: z.string().trim().max(64).optional(),
brand: z.string().trim().max(64).optional(),
keyword: z.string().trim().max(128).optional(),
sort: z.enum(["latest", "hottest", "most_used"]).default("latest"),
});
@ -30,29 +32,19 @@ const createAgentSchema = z
name: z.string().trim().min(1).max(128),
type: z.enum(["image", "video"]),
visibility: z.enum(["public", "private"]).default("private"),
categoryId: z.string().uuid().optional(),
newCategoryName: z.string().trim().min(1).max(64).optional(),
categoryPath: z
.object({
productCategory: z.string().trim().max(64).optional(),
audienceTag: z.string().trim().max(64).optional(),
usageScenario: z.string().trim().max(64).optional(),
brand: z.string().trim().max(64).optional(),
})
.optional(),
description: z.string().trim().max(2000).optional(),
defaultModelId: z.string().uuid(),
defaultParams: z.record(z.string(), z.any()).optional(),
avatarAssetId: z.string().uuid().optional(),
slots: z.array(slotSchema).min(1).max(20),
})
.superRefine((value, ctx) => {
if (value.categoryId && value.newCategoryName) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "categoryId 和 newCategoryName 不能同时传入",
path: ["newCategoryName"],
});
}
if (value.visibility === "public" && !value.categoryId && !value.newCategoryName) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "公开智能体必须选择分类或新建分类",
path: ["categoryId"],
});
}
});
export async function GET(request: NextRequest) {
@ -66,32 +58,38 @@ export async function GET(request: NextRequest) {
const query = listQuerySchema.parse({
scope: searchParams.get("scope") || "all",
type: searchParams.get("type") || undefined,
categoryId: searchParams.get("categoryId") || undefined,
productCategory: searchParams.get("productCategory") || undefined,
audienceTag: searchParams.get("audienceTag") || undefined,
usageScenario: searchParams.get("usageScenario") || undefined,
brand: searchParams.get("brand") || undefined,
keyword: searchParams.get("keyword") || undefined,
sort: searchParams.get("sort") || "latest",
});
const [presets, categories] = await Promise.all([
getVisibleAgentPresets({
userId: session.user.id,
scope: query.scope,
type: query.type,
categoryId: query.categoryId,
keyword: query.keyword,
sort: query.sort,
}),
getVisibleAgentCategories({
userId: session.user.id,
scope: query.scope === "private" ? "private" : "all",
}),
]);
const presets = await getVisibleAgentPresets({
userId: session.user.id,
scope: query.scope,
type: query.type,
keyword: query.keyword,
sort: query.sort,
});
const filterByPath = (items: typeof presets) =>
items.filter((item) => {
const path = item.categoryPath || {};
if (query.productCategory && path.productCategory !== query.productCategory) return false;
if (query.audienceTag && path.audienceTag !== query.audienceTag) return false;
if (query.usageScenario && path.usageScenario !== query.usageScenario) return false;
if (query.brand && path.brand !== query.brand) return false;
return true;
});
return NextResponse.json({
success: true,
data: {
categories,
public: presets.filter((item) => item.visibility === "public"),
private: presets.filter((item) => item.visibility === "private"),
categories: [],
public: filterByPath(presets.filter((item) => item.visibility === "public")),
private: filterByPath(presets.filter((item) => item.visibility === "private")),
},
});
} catch (error) {
@ -126,8 +124,7 @@ export async function POST(request: NextRequest) {
name: data.name,
type: data.type,
visibility: data.visibility,
categoryId: data.categoryId,
newCategoryName: data.newCategoryName,
categoryPath: data.categoryPath,
description: data.description,
defaultModelId: data.defaultModelId,
defaultParams: data.defaultParams,

View File

@ -29,6 +29,7 @@ import {
normalizeOssImageMigrationConfig,
OSS_MIGRATION_CONFIG_KEY,
} from "@/lib/storage/migration-config";
import type { AgentCategoryTreeConfig } from "@/types/agent";
const HOME_VARIANT_KEY = "home_variant";
// Historically stored as "home_surprise_categories" but used for the featured gallery categories.
@ -42,6 +43,7 @@ const MEMBERSHIP_CONFIG_KEY = "membership_config";
const MEMBERSHIP_USER_OVERRIDES_KEY = "membership_user_plan_overrides";
const STORAGE_FAILOVER_CONFIG_KEY = "storage_failover_config";
const REALTIME_CANVAS_CONFIG_KEY = "realtime_canvas_config";
const AGENT_CATEGORY_TREE_CONFIG_KEY = "agent_category_tree_config";
function normalizeHomeVariant(value: unknown): "classic" | "lovart" {
return value === "lovart" ? "lovart" : "classic";
@ -156,6 +158,32 @@ function normalizeStorageFailoverConfig(value: unknown): {
};
}
function normalizeAgentCategoryTreeConfig(value: unknown): AgentCategoryTreeConfig {
const raw =
value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
const normalizeList = (input: unknown) => {
if (!Array.isArray(input)) return [] as string[];
return Array.from(
new Set(
input
.map((item) => String(item || "").trim())
.filter(Boolean)
.slice(0, 200)
)
);
};
return {
productCategories: normalizeList(raw.productCategories),
audienceTags: normalizeList(raw.audienceTags),
usageScenarios: normalizeList(raw.usageScenarios),
brands: normalizeList(raw.brands),
};
}
// GET /api/site-settings - 获取网站设置 (公开)
export async function GET() {
try {
@ -179,6 +207,7 @@ export async function GET() {
realtimeCanvasConfigSetting,
storageFailoverConfigSetting,
ossImageMigrationConfigSetting,
agentCategoryTreeConfigSetting,
] = await Promise.all([
db.select().from(siteSettings).limit(1).then(rows => rows[0]),
db
@ -277,6 +306,12 @@ export async function GET() {
.where(eq(systemSettings.key, OSS_MIGRATION_CONFIG_KEY))
.limit(1)
.then(rows => rows[0]),
db
.select()
.from(systemSettings)
.where(eq(systemSettings.key, AGENT_CATEGORY_TREE_CONFIG_KEY))
.limit(1)
.then(rows => rows[0]),
]);
const notification = notificationSetting?.value || { enabled: false, title: "", content: "" };
@ -312,6 +347,9 @@ export async function GET() {
const ossImageMigrationConfig = normalizeOssImageMigrationConfig(
ossImageMigrationConfigSetting?.value
);
const agentCategoryTreeConfig = normalizeAgentCategoryTreeConfig(
agentCategoryTreeConfigSetting?.value
);
// 如果没有设置记录,返回默认值
const baseSettings = settings || {
@ -337,6 +375,7 @@ export async function GET() {
rankingEnabled: true,
canvasEnabled: true,
agentEnabled: true,
agentCategoryTreeConfig: normalizeAgentCategoryTreeConfig(undefined),
realtimeCanvasEnabled: true,
realtimeCanvasServiceEnabled: true,
storageFailoverConfig,
@ -378,6 +417,7 @@ export async function GET() {
lovartComposerPreviewTexts,
lovartPromptTagVisibility,
contactConfig,
agentCategoryTreeConfig,
membershipConfig,
membershipUserOverrides,
pointsSystemConfig,
@ -426,6 +466,14 @@ const updateSchema = z.object({
rankingEnabled: z.boolean().optional(),
canvasEnabled: z.boolean().optional(),
agentEnabled: z.boolean().optional(),
agentCategoryTreeConfig: z
.object({
productCategories: z.array(z.string().trim().min(1).max(64)).max(200).optional(),
audienceTags: z.array(z.string().trim().min(1).max(64)).max(200).optional(),
usageScenarios: z.array(z.string().trim().min(1).max(64)).max(200).optional(),
brands: z.array(z.string().trim().min(1).max(64)).max(200).optional(),
})
.optional(),
realtimeCanvasEnabled: z.boolean().optional(),
aiDetailGenerationEnabled: z.boolean().optional(),
canvasDefaultModelId: z.string().nullable().optional(),
@ -501,6 +549,7 @@ export async function PUT(request: NextRequest) {
lovartComposerPreviewTexts,
lovartPromptTagVisibility,
contactConfig,
agentCategoryTreeConfig,
membershipConfig,
membershipUserOverrides,
pointsSystemConfig,
@ -665,6 +714,26 @@ export async function PUT(request: NextRequest) {
});
}
if (agentCategoryTreeConfig !== undefined) {
const normalized = normalizeAgentCategoryTreeConfig(agentCategoryTreeConfig);
await db
.insert(systemSettings)
.values({
key: AGENT_CATEGORY_TREE_CONFIG_KEY,
value: normalized,
updatedAt: new Date(),
updatedBy: session.user.id,
})
.onConflictDoUpdate({
target: systemSettings.key,
set: {
value: normalized,
updatedAt: new Date(),
updatedBy: session.user.id,
},
});
}
if (membershipConfig !== undefined) {
const normalized = normalizeMembershipConfig(membershipConfig);
await db
@ -829,6 +898,10 @@ export async function PUT(request: NextRequest) {
contactConfig !== undefined
? normalizeContactConfig(contactConfig)
: normalizeContactConfig(undefined),
agentCategoryTreeConfig:
agentCategoryTreeConfig !== undefined
? normalizeAgentCategoryTreeConfig(agentCategoryTreeConfig)
: normalizeAgentCategoryTreeConfig(undefined),
membershipConfig:
membershipConfig !== undefined
? normalizeMembershipConfig(membershipConfig)

View File

@ -40,6 +40,10 @@ export function AgentPresetCard({
day: "2-digit",
});
})();
const categoryBadges = [
preset.categoryPath?.productCategory,
preset.categoryPath?.audienceTag,
].filter(Boolean) as string[];
return (
<div
@ -75,11 +79,11 @@ export function AgentPresetCard({
<Badge variant="secondary" className="bg-white/90 text-black shadow-sm">
{preset.type === "video" ? "视频" : "生图"}
</Badge>
{preset.category?.name ? (
<Badge variant="secondary" className="bg-white/90 text-black shadow-sm">
{preset.category.name}
{categoryBadges.map((item) => (
<Badge key={item} variant="secondary" className="bg-white/90 text-black shadow-sm">
{item}
</Badge>
) : null}
))}
</div>
<div className="absolute right-2 top-2 flex items-center gap-1 opacity-0 transition-opacity group-hover:opacity-100">
{preset.visibility === "private" && onEdit ? (

View File

@ -26,7 +26,11 @@ import { ScrollArea } from "@/components/ui/scroll-area";
import { fetcher } from "@/lib/utils";
import { imageGenerationService } from "@/services/canvas";
import { agentService } from "@/services/agents";
import type { AgentCategory, AgentPreset, AgentPresetSlot } from "@/types/agent";
import type {
AgentCategoryTreeConfig,
AgentPreset,
AgentPresetSlot,
} from "@/types/agent";
type DialogSlotState = AgentPresetSlot & {
localReferenceAssets: Array<{
@ -39,17 +43,15 @@ type DialogSlotState = AgentPresetSlot & {
interface AgentPresetDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
categories: AgentCategory[];
categoryTreeConfig: AgentCategoryTreeConfig;
initialPreset?: AgentPreset | null;
onSaved?: (preset: AgentPreset) => void;
}
const NEW_CATEGORY_VALUE = "__new__";
export function AgentPresetDialog({
open,
onOpenChange,
categories,
categoryTreeConfig,
initialPreset,
onSaved,
}: AgentPresetDialogProps) {
@ -65,8 +67,17 @@ export function AgentPresetDialog({
const [name, setName] = useState("");
const [type, setType] = useState<"image" | "video">("image");
const [visibility, setVisibility] = useState<"public" | "private">("private");
const [categoryMode, setCategoryMode] = useState<string>("");
const [newCategoryName, setNewCategoryName] = useState("");
const [categoryPath, setCategoryPath] = useState<{
productCategory: string;
audienceTag: string;
usageScenario: string;
brand: string;
}>({
productCategory: "",
audienceTag: "",
usageScenario: "",
brand: "",
});
const [defaultModelId, setDefaultModelId] = useState("");
const [description, setDescription] = useState("");
const [avatarAssetId, setAvatarAssetId] = useState<string>("");
@ -131,8 +142,12 @@ export function AgentPresetDialog({
setName("");
setType("image");
setVisibility("private");
setCategoryMode("");
setNewCategoryName("");
setCategoryPath({
productCategory: "",
audienceTag: "",
usageScenario: "",
brand: "",
});
setDefaultModelId("");
setDescription("");
setAvatarAssetId("");
@ -162,8 +177,12 @@ export function AgentPresetDialog({
setName(initialPreset.name || "");
setType(initialPreset.type);
setVisibility(initialPreset.visibility);
setCategoryMode(initialPreset.category?.id || initialPreset.categoryId || "");
setNewCategoryName("");
setCategoryPath({
productCategory: String(initialPreset.categoryPath?.productCategory || ""),
audienceTag: String(initialPreset.categoryPath?.audienceTag || ""),
usageScenario: String(initialPreset.categoryPath?.usageScenario || ""),
brand: String(initialPreset.categoryPath?.brand || ""),
});
setDefaultModelId(initialPreset.defaultModelId || "");
setDescription(initialPreset.description || "");
setAvatarAssetId(initialPreset.avatarAssetId || "");
@ -301,10 +320,6 @@ export function AgentPresetDialog({
toast.error("请选择对应模型");
return;
}
if (visibility === "public" && !categoryMode && !newCategoryName.trim()) {
toast.error("公开智能体必须选择分类");
return;
}
if (slots.some((slot) => !slot.promptTemplate.trim())) {
toast.error("每个槽位都需要填写提示词");
return;
@ -316,10 +331,12 @@ export function AgentPresetDialog({
name: name.trim(),
type,
visibility,
categoryId:
categoryMode && categoryMode !== NEW_CATEGORY_VALUE ? categoryMode : undefined,
newCategoryName:
categoryMode === NEW_CATEGORY_VALUE ? newCategoryName.trim() : undefined,
categoryPath: {
productCategory: categoryPath.productCategory || undefined,
audienceTag: categoryPath.audienceTag || undefined,
usageScenario: categoryPath.usageScenario || undefined,
brand: categoryPath.brand || undefined,
},
description: description.trim() || undefined,
defaultModelId,
slots: slots.map((slot, index) => ({
@ -453,23 +470,28 @@ export function AgentPresetDialog({
</Select>
</div>
<div className="space-y-2">
<div className="text-sm font-medium">分类</div>
<Select value={categoryMode} onValueChange={setCategoryMode}>
<div className="text-sm font-medium">产品品类</div>
<Select
value={categoryPath.productCategory || "__none__"}
onValueChange={(value) =>
setCategoryPath((prev) => ({
...prev,
productCategory: value === "__none__" ? "" : value,
}))
}
>
<SelectTrigger>
<SelectValue placeholder="选择分类" />
<SelectValue placeholder="选择产品品类" />
</SelectTrigger>
<SelectContent>
{categories.map((category) => (
<SelectItem key={category.id} value={category.id}>
{category.name}
<SelectItem value="__none__">不选择</SelectItem>
{categoryTreeConfig.productCategories.map((item) => (
<SelectItem key={item} value={item}>
{item}
</SelectItem>
))}
<SelectItem value={NEW_CATEGORY_VALUE}>新建分类</SelectItem>
</SelectContent>
</Select>
<div className="text-xs text-muted-foreground">
如需创建分类,请先选择“新建分类”,再在下方填写分类名称。
</div>
</div>
<div className="space-y-2">
<div className="text-sm font-medium">对应模型</div>
@ -488,15 +510,80 @@ export function AgentPresetDialog({
</div>
</div>
{categoryMode === NEW_CATEGORY_VALUE ? (
<div className="grid grid-cols-1 gap-3 md:grid-cols-3">
<div className="space-y-2">
<div className="text-sm font-medium">新分类名称</div>
<Input
value={newCategoryName}
onChange={(event) => setNewCategoryName(event.target.value)}
/>
<div className="text-sm font-medium">人群标签</div>
<Select
value={categoryPath.audienceTag || "__none__"}
onValueChange={(value) =>
setCategoryPath((prev) => ({
...prev,
audienceTag: value === "__none__" ? "" : value,
}))
}
>
<SelectTrigger>
<SelectValue placeholder="选择人群标签" />
</SelectTrigger>
<SelectContent>
<SelectItem value="__none__">不选择</SelectItem>
{categoryTreeConfig.audienceTags.map((item) => (
<SelectItem key={item} value={item}>
{item}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
) : null}
<div className="space-y-2">
<div className="text-sm font-medium">使用场景</div>
<Select
value={categoryPath.usageScenario || "__none__"}
onValueChange={(value) =>
setCategoryPath((prev) => ({
...prev,
usageScenario: value === "__none__" ? "" : value,
}))
}
>
<SelectTrigger>
<SelectValue placeholder="选择使用场景" />
</SelectTrigger>
<SelectContent>
<SelectItem value="__none__">不选择</SelectItem>
{categoryTreeConfig.usageScenarios.map((item) => (
<SelectItem key={item} value={item}>
{item}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<div className="text-sm font-medium">品牌</div>
<Select
value={categoryPath.brand || "__none__"}
onValueChange={(value) =>
setCategoryPath((prev) => ({
...prev,
brand: value === "__none__" ? "" : value,
}))
}
>
<SelectTrigger>
<SelectValue placeholder="选择品牌" />
</SelectTrigger>
<SelectContent>
<SelectItem value="__none__">不选择</SelectItem>
{categoryTreeConfig.brands.map((item) => (
<SelectItem key={item} value={item}>
{item}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
<div className="space-y-2">
<div className="text-sm font-medium">描述</div>

View File

@ -4,12 +4,19 @@ import { useMemo, useState } from "react";
import useSWR from "swr";
import { Loader2, Plus, Sparkles } from "lucide-react";
import { toast } from "sonner";
import { fetcher } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ScrollArea } from "@/components/ui/scroll-area";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { agentService } from "@/services/agents";
import type { AgentPreset } from "@/types/agent";
import { AgentCategoryTabs } from "@/components/agents/AgentCategoryTabs";
import { AgentPresetCard } from "@/components/agents/AgentPresetCard";
import { AgentPresetDialog } from "@/components/agents/AgentPresetDialog";
@ -23,11 +30,24 @@ export function AgentPresetPanel({
onSelectPreset,
}: AgentPresetPanelProps) {
const [keyword, setKeyword] = useState("");
const [selectedCategoryId, setSelectedCategoryId] = useState<string | null>(null);
const [categoryFilters, setCategoryFilters] = useState({
productCategory: "",
audienceTag: "",
usageScenario: "",
brand: "",
});
const [showCreateDialog, setShowCreateDialog] = useState(false);
const [editingPreset, setEditingPreset] = useState<AgentPreset | null>(null);
const { data: siteSettingsData } = useSWR<{
agentCategoryTreeConfig?: {
productCategories?: string[];
audienceTags?: string[];
usageScenarios?: string[];
brands?: string[];
};
}>("/api/site-settings", fetcher);
const { data, isLoading, mutate } = useSWR(
["agent-presets", selectedCategoryId],
["agent-presets"],
async () => {
const result = await agentService.getPresets({
scope: "all",
@ -40,22 +60,39 @@ export function AgentPresetPanel({
}
);
const publicCategories = useMemo(
() => (data?.categories || []).filter((category) => category.scope !== "private"),
[data?.categories]
const categoryTreeConfig = useMemo(
() => ({
productCategories: siteSettingsData?.agentCategoryTreeConfig?.productCategories || [],
audienceTags: siteSettingsData?.agentCategoryTreeConfig?.audienceTags || [],
usageScenarios: siteSettingsData?.agentCategoryTreeConfig?.usageScenarios || [],
brands: siteSettingsData?.agentCategoryTreeConfig?.brands || [],
}),
[siteSettingsData?.agentCategoryTreeConfig]
);
const filteredPublicPresets = useMemo(() => {
return (data?.public || []).filter((preset) => {
const matchedCategory = !selectedCategoryId || preset.category?.id === selectedCategoryId;
const path = preset.categoryPath || {};
const matchedKeyword =
!keyword.trim() ||
preset.name.toLowerCase().includes(keyword.trim().toLowerCase()) ||
String(preset.category?.name || "")
[
path.productCategory,
path.audienceTag,
path.usageScenario,
path.brand,
]
.filter(Boolean)
.join(" ")
.toLowerCase()
.includes(keyword.trim().toLowerCase());
const matchedCategory =
(!categoryFilters.productCategory || path.productCategory === categoryFilters.productCategory) &&
(!categoryFilters.audienceTag || path.audienceTag === categoryFilters.audienceTag) &&
(!categoryFilters.usageScenario || path.usageScenario === categoryFilters.usageScenario) &&
(!categoryFilters.brand || path.brand === categoryFilters.brand);
return matchedCategory && matchedKeyword;
});
}, [data?.public, keyword, selectedCategoryId]);
}, [categoryFilters, data?.public, keyword]);
const filteredPrivatePresets = useMemo(() => {
return (data?.private || []).filter((preset) => {
const matchedKeyword =
@ -126,13 +163,94 @@ export function AgentPresetPanel({
<ScrollArea className="flex-1">
<div className="space-y-5 p-4">
<section className="space-y-3">
<div className="space-y-2">
<div className="space-y-3">
<div className="text-sm font-medium">公共智能体</div>
<AgentCategoryTabs
categories={publicCategories}
selectedCategoryId={selectedCategoryId}
onSelectCategory={setSelectedCategoryId}
/>
<div className="grid grid-cols-1 gap-2 md:grid-cols-2">
<Select
value={categoryFilters.productCategory || "__none__"}
onValueChange={(value) =>
setCategoryFilters((prev) => ({
...prev,
productCategory: value === "__none__" ? "" : value,
}))
}
>
<SelectTrigger>
<SelectValue placeholder="产品品类" />
</SelectTrigger>
<SelectContent>
<SelectItem value="__none__">全部产品品类</SelectItem>
{categoryTreeConfig.productCategories.map((item) => (
<SelectItem key={item} value={item}>
{item}
</SelectItem>
))}
</SelectContent>
</Select>
<Select
value={categoryFilters.audienceTag || "__none__"}
onValueChange={(value) =>
setCategoryFilters((prev) => ({
...prev,
audienceTag: value === "__none__" ? "" : value,
}))
}
>
<SelectTrigger>
<SelectValue placeholder="人群标签" />
</SelectTrigger>
<SelectContent>
<SelectItem value="__none__">全部人群标签</SelectItem>
{categoryTreeConfig.audienceTags.map((item) => (
<SelectItem key={item} value={item}>
{item}
</SelectItem>
))}
</SelectContent>
</Select>
<Select
value={categoryFilters.usageScenario || "__none__"}
onValueChange={(value) =>
setCategoryFilters((prev) => ({
...prev,
usageScenario: value === "__none__" ? "" : value,
}))
}
>
<SelectTrigger>
<SelectValue placeholder="使用场景" />
</SelectTrigger>
<SelectContent>
<SelectItem value="__none__">全部使用场景</SelectItem>
{categoryTreeConfig.usageScenarios.map((item) => (
<SelectItem key={item} value={item}>
{item}
</SelectItem>
))}
</SelectContent>
</Select>
<Select
value={categoryFilters.brand || "__none__"}
onValueChange={(value) =>
setCategoryFilters((prev) => ({
...prev,
brand: value === "__none__" ? "" : value,
}))
}
>
<SelectTrigger>
<SelectValue placeholder="品牌" />
</SelectTrigger>
<SelectContent>
<SelectItem value="__none__">全部品牌</SelectItem>
{categoryTreeConfig.brands.map((item) => (
<SelectItem key={item} value={item}>
{item}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
{isLoading ? (
<div className="flex items-center justify-center py-8">
@ -194,7 +312,7 @@ export function AgentPresetPanel({
}
setShowCreateDialog(true);
}}
categories={data?.categories || []}
categoryTreeConfig={categoryTreeConfig}
initialPreset={editingPreset}
onSaved={async (preset) => {
await mutate();

View File

@ -0,0 +1,2 @@
ALTER TABLE "AgentPreset"
ADD COLUMN IF NOT EXISTS "categoryPath" jsonb;

View File

@ -295,6 +295,13 @@
"when": 1773150000000,
"tag": "0055_add_agent_enabled_site_setting",
"breakpoints": true
},
{
"idx": 42,
"version": "7",
"when": 1773151800000,
"tag": "0056_add_agent_category_path",
"breakpoints": true
}
]
}

View File

@ -2473,8 +2473,12 @@ export async function createAgentPreset(params: {
name: string;
type: AgentPresetKind;
visibility: AgentPresetVisibility;
categoryId?: string | null;
newCategoryName?: string | null;
categoryPath?: {
productCategory?: string | null;
audienceTag?: string | null;
usageScenario?: string | null;
brand?: string | null;
} | null;
description?: string | null;
defaultModelId: string;
defaultParams?: Record<string, any> | null;
@ -2495,13 +2499,6 @@ export async function createAgentPreset(params: {
slots: params.slots,
});
const category = await resolveAgentCategory({
tx,
userId: params.userId,
visibility: params.visibility,
categoryId: params.categoryId,
newCategoryName: params.newCategoryName,
});
const requiredUploadCount = validatedSlots.some((slot) => slot.requireUpload !== false) ? 3 : 0;
const avatarAssetId = String(params.avatarAssetId || "").trim() || null;
if (avatarAssetId) {
@ -2519,7 +2516,8 @@ export async function createAgentPreset(params: {
name: params.name.trim(),
type: params.type,
visibility: params.visibility,
categoryId: category?.id || null,
categoryId: null,
categoryPath: params.categoryPath || null,
promptTemplate: validatedSlots[0]?.promptTemplate || "",
description: params.description || null,
defaultModelId: params.defaultModelId,
@ -2586,8 +2584,12 @@ export async function updateAgentPreset(params: {
name?: string;
type?: AgentPresetKind;
visibility?: AgentPresetVisibility;
categoryId?: string | null;
newCategoryName?: string | null;
categoryPath?: {
productCategory?: string | null;
audienceTag?: string | null;
usageScenario?: string | null;
brand?: string | null;
} | null;
description?: string | null;
defaultModelId?: string;
defaultParams?: Record<string, any> | null;
@ -2621,22 +2623,6 @@ export async function updateAgentPreset(params: {
.from(agentPresetSlot)
.where(eq(agentPresetSlot.presetId, params.id))
.orderBy(asc(agentPresetSlot.slotIndex), asc(agentPresetSlot.createdAt));
const shouldResolveCategory =
params.categoryId !== undefined ||
params.newCategoryName !== undefined ||
(nextVisibility === "public" && !existing.categoryId);
const category = shouldResolveCategory
? await resolveAgentCategory({
tx,
userId: params.userId,
visibility: nextVisibility,
categoryId:
params.categoryId === undefined ? existing.categoryId : params.categoryId,
newCategoryName: params.newCategoryName,
})
: null;
if (!nextDefaultModelId) {
throw new ChatSDKError(
"bad_request:database",
@ -2719,7 +2705,7 @@ export async function updateAgentPreset(params: {
if (params.name !== undefined) updateData.name = params.name.trim();
if (params.type !== undefined) updateData.type = params.type;
if (params.visibility !== undefined) updateData.visibility = params.visibility;
if (shouldResolveCategory) updateData.categoryId = category?.id || null;
if (params.categoryPath !== undefined) updateData.categoryPath = params.categoryPath || null;
if (params.description !== undefined) updateData.description = params.description || null;
if (params.defaultModelId !== undefined) {
updateData.defaultModelId = params.defaultModelId;
@ -2860,6 +2846,7 @@ export async function forkAgentPreset(params: {
type: source.type,
visibility: "private",
categoryId: source.categoryId,
categoryPath: source.categoryPath,
promptTemplate: source.promptTemplate,
description: source.description,
defaultModelId: source.defaultModelId,

View File

@ -530,6 +530,12 @@ export const agentPreset = pgTable("AgentPreset", {
categoryId: uuid("categoryId").references(() => agentPresetCategory.id, {
onDelete: "set null",
}),
categoryPath: jsonb("categoryPath").$type<{
productCategory?: string | null;
audienceTag?: string | null;
usageScenario?: string | null;
brand?: string | null;
}>(),
promptTemplate: text("promptTemplate").notNull().default(""),
description: text("description"),
defaultModelId: uuid("defaultModelId").references(() => aiModel.id, {

View File

@ -3,6 +3,20 @@ export type AgentPresetVisibility = "public" | "private";
export type AgentCategoryScope = "public" | "private" | "global";
export type AgentPresetStatus = "active" | "disabled" | "hidden" | "blocked";
export interface AgentCategoryPath {
productCategory?: string | null;
audienceTag?: string | null;
usageScenario?: string | null;
brand?: string | null;
}
export interface AgentCategoryTreeConfig {
productCategories: string[];
audienceTags: string[];
usageScenarios: string[];
brands: string[];
}
export interface AgentCategory {
id: string;
name: string;
@ -58,6 +72,7 @@ export interface AgentPreset {
type: AgentPresetType;
visibility: AgentPresetVisibility;
categoryId?: string | null;
categoryPath?: AgentCategoryPath | null;
promptTemplate: string;
description?: string | null;
defaultModelId?: string | null;
@ -130,8 +145,7 @@ export interface AgentCreatePayload {
name: string;
type: AgentPresetType;
visibility: AgentPresetVisibility;
categoryId?: string;
newCategoryName?: string;
categoryPath?: AgentCategoryPath | null;
description?: string;
defaultModelId: string;
defaultParams?: Record<string, any>;
@ -143,8 +157,7 @@ export interface AgentUpdatePayload {
name?: string;
type?: AgentPresetType;
visibility?: AgentPresetVisibility;
categoryId?: string | null;
newCategoryName?: string;
categoryPath?: AgentCategoryPath | null;
description?: string | null;
defaultModelId?: string;
defaultParams?: Record<string, any> | null;