fix(chat): 智能体支持配置分级显示

This commit is contained in:
sophie committed 2026-06-25 17:37:48 +08:00
1 parent a451951e7a
commit 70d7435b5f
27 files changed
+637 -68

No files matched your search

+5 -10
View File
@@ -12,6 +12,7 @@ from app import db
from app.core.auth.jwt import get_current_user from app.core.auth.jwt import get_current_user
from app.core.errors import UnauthorizedError from app.core.errors import UnauthorizedError
from app.models import Agent, User, AgentGuide from app.models import Agent, User, AgentGuide
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
from app.services.minio_service import minio_service from app.services.minio_service import minio_service
# 定义 Blueprint,将在应用工厂中注册为 /api/agents # 定义 Blueprint,将在应用工厂中注册为 /api/agents
@@ -19,13 +20,7 @@ agents_bp = Blueprint('agents', __name__)
def _serialize_agent_row(row) -> dict: def _serialize_agent_row(row) -> dict:
return { return serialize_agent_list_item(row)
'id': row.id,
'name': row.name,
'description': row.description,
'icon_url': row.icon_url,
'dify_app_type': (row.extra_config or {}).get('dify_app_type') if hasattr(row, 'extra_config') else None,
}
@agents_bp.route('', methods=['GET']) @agents_bp.route('', methods=['GET'])
@@ -61,8 +56,8 @@ def list_user_agents():
if a.is_active if a.is_active
] ]
# 序列化为前端所需字段 # [STEP 1] 按 extra_config 分类字段排序后序列化
return jsonify([_serialize_agent_row(row) for row in agent_rows]) return jsonify([_serialize_agent_row(row) for row in sort_agent_rows(agent_rows)])
@agents_bp.route('/<int:agent_id>/guides', methods=['GET']) @agents_bp.route('/<int:agent_id>/guides', methods=['GET'])
def list_agent_guides(agent_id): def list_agent_guides(agent_id):
@@ -112,7 +107,7 @@ def list_public_agents():
.order_by(Agent.id.asc()) .order_by(Agent.id.asc())
.all() .all()
) )
return jsonify([_serialize_agent_row(row) for row in agent_rows]) return jsonify([_serialize_agent_row(row) for row in sort_agent_rows(agent_rows)])
# 为了兼容本地无MinIO的环境,暴露一个静态文件读取接口 # 为了兼容本地无MinIO的环境,暴露一个静态文件读取接口
@agents_bp.route('/guides/files/<path:filename>', methods=['GET']) @agents_bp.route('/guides/files/<path:filename>', methods=['GET'])
+7 -2
View File
@@ -9,6 +9,7 @@ from flask import Blueprint, request, jsonify, current_app
from app import db from app import db
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, Announcement, LoginAudit, WecomCallbackAudit, GeneralFeedback, ChatLog from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, Announcement, LoginAudit, WecomCallbackAudit, GeneralFeedback, ChatLog
from app.services.feedback_notify import send_feedback_group_notification from app.services.feedback_notify import send_feedback_group_notification
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
from app.core.auth.jwt import get_current_user as _auth_current_user from app.core.auth.jwt import get_current_user as _auth_current_user
@@ -1649,7 +1650,8 @@ def home():
if user.role == 'admin': if user.role == 'admin':
agent_rows = db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url, Agent.extra_config).filter(Agent.is_active.is_(True)).all() agent_rows = db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url, Agent.extra_config).filter(Agent.is_active.is_(True)).all()
else: else:
agent_rows = [{'id': agent.id, 'name': agent.name, 'description': agent.description, 'icon_url': agent.icon_url, 'extra_config': agent.extra_config} for agent in user.agents] agent_rows = [{'id': agent.id, 'name': agent.name, 'description': agent.description, 'icon_url': agent.icon_url, 'extra_config': agent.extra_config} for agent in user.agents if agent.is_active]
agent_rows = sort_agent_rows(agent_rows)
favorites = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id).all() favorites = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id).all()
favorite_ids = [f.agent_id for f in favorites] favorite_ids = [f.agent_id for f in favorites]
qqs = db.session.query(QuickQuestion).filter( qqs = db.session.query(QuickQuestion).filter(
@@ -1666,7 +1668,7 @@ def home():
agent = db.session.get(Agent, rel.agent_id) agent = db.session.get(Agent, rel.agent_id)
if agent: if agent:
embedded_agents.append({'id': agent.id, 'name': agent.name, 'iframe_url': agent.extra_config.get('iframe_url') if agent.extra_config else None}) embedded_agents.append({'id': agent.id, 'name': agent.name, 'iframe_url': agent.extra_config.get('iframe_url') if agent.extra_config else None})
return jsonify({'user': {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'language': user.language, 'theme_preference': user.theme_preference or 'system'}, 'agents': [{'id': a.id if hasattr(a, 'id') else a['id'], 'name': a.name if hasattr(a, 'name') else a['name'], 'description': a.description if hasattr(a, 'description') else a['description'], 'icon_url': a.icon_url if hasattr(a, 'icon_url') else a['icon_url'], 'dify_app_type': ((a.extra_config or {}).get('dify_app_type') if hasattr(a, 'extra_config') else (a.get('extra_config') or {}).get('dify_app_type')) or 'chatflow'} for a in agent_rows], 'favorite_agent_ids': favorite_ids, 'quick_questions': [{'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id} for q in qqs], 'embedded_agents': embedded_agents, 'layout': layout}) return jsonify({'user': {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'language': user.language, 'theme_preference': user.theme_preference or 'system'}, 'agents': [serialize_agent_list_item(a) for a in agent_rows], 'favorite_agent_ids': favorite_ids, 'quick_questions': [{'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id} for q in qqs], 'embedded_agents': embedded_agents, 'layout': layout})
try: try:
return _run_db_with_retry(_load_home_payload, label='user.home') return _run_db_with_retry(_load_home_payload, label='user.home')
except (OperationalError, DatabaseError) as exc: except (OperationalError, DatabaseError) as exc:
@@ -2137,12 +2139,15 @@ def get_agent_details(id):
if agent_type == 'api' and getattr(agent, 'dify_api_key', None): if agent_type == 'api' and getattr(agent, 'dify_api_key', None):
from app.services.dify import DifyService from app.services.dify import DifyService
try:
params = DifyService.get_app_parameters(agent) params = DifyService.get_app_parameters(agent)
if isinstance(params, dict): if isinstance(params, dict):
dify_parameters = { dify_parameters = {
'file_upload': params.get('file_upload') if isinstance(params.get('file_upload'), dict) else {}, 'file_upload': params.get('file_upload') if isinstance(params.get('file_upload'), dict) else {},
'system_parameters': params.get('system_parameters') if isinstance(params.get('system_parameters'), dict) else {}, 'system_parameters': params.get('system_parameters') if isinstance(params.get('system_parameters'), dict) else {},
} }
except Exception as exc:
current_app.logger.warning('[user.agents] dify parameters fetch failed agent_id=%s err=%s', id, exc)
return jsonify({ return jsonify({
'id': agent.id, 'id': agent.id,
+105
View File
@@ -0,0 +1,105 @@
"""
services/agent_category.py
用途:从 Agent.extra_config 解析 P1 分类字段(category / sub_category / sort_order),并提供排序与序列化。
依赖:无外部服务;由 api/agents、api/user 在返回列表时调用。
逻辑:分类信息暂存 extra_config,P2 可迁移至独立 agent_categories 表。
"""
from __future__ import annotations
from typing import Any
def parse_agent_category_meta(extra_config: dict | None) -> dict[str, Any]:
"""
从 extra_config 解析 Agent 分类元数据。
核心逻辑:category / sub_category 去首尾空白;sort_order 非法值回退为 0。
Args:
extra_config: Agent.extra_config JSON 字典,可为 None。
Returns:
含 category (str)、sub_category (str)、sort_order (int) 的字典。
"""
extra = extra_config if isinstance(extra_config, dict) else {}
category = str(extra.get('category') or '').strip()
sub_category = str(extra.get('sub_category') or '').strip()
sort_raw = extra.get('sort_order')
try:
sort_order = int(sort_raw) if sort_raw is not None and sort_raw != '' else 0
except (TypeError, ValueError):
sort_order = 0
return {
'category': category,
'sub_category': sub_category,
'sort_order': sort_order,
}
def _row_extra_config(row: Any) -> dict | None:
"""从 ORM 行或 dict 行读取 extra_config。"""
if hasattr(row, 'extra_config'):
return row.extra_config
if isinstance(row, dict):
return row.get('extra_config')
return None
def _row_id(row: Any) -> int:
"""从 ORM 行或 dict 行读取主键 id。"""
if hasattr(row, 'id'):
return int(row.id)
if isinstance(row, dict):
return int(row.get('id') or 0)
return 0
def agent_category_sort_key(row: Any) -> tuple:
"""
生成分类排序键:sort_order → category → sub_category → id。
核心逻辑:未配置 category 的 Agent 排在同 sort_order 下的末尾(用 \\uffff 占位)。
"""
meta = parse_agent_category_meta(_row_extra_config(row))
category_key = meta['category'] or '\uffff'
sub_key = meta['sub_category'] or '\uffff'
return (meta['sort_order'], category_key, sub_key, _row_id(row))
def sort_agent_rows(rows: list) -> list:
"""
按分类元数据对 Agent 行列表原地排序并返回。
"""
return sorted(rows, key=agent_category_sort_key)
def serialize_agent_category_fields(row: Any) -> dict[str, Any]:
"""
序列化分类相关 API 字段。
空字符串 category / sub_category 输出为 None,便于前端区分「未配置」。
"""
meta = parse_agent_category_meta(_row_extra_config(row))
return {
'category': meta['category'] or None,
'sub_category': meta['sub_category'] or None,
'sort_order': meta['sort_order'],
}
def serialize_agent_list_item(row: Any) -> dict[str, Any]:
"""
序列化用户可见 Agent 列表项(聊天侧栏、工作台首页共用)。
核心逻辑:合并基础字段、dify_app_type 与分类元数据。
"""
extra = _row_extra_config(row) or {}
name = row.name if hasattr(row, 'name') else row.get('name')
description = row.description if hasattr(row, 'description') else row.get('description')
icon_url = row.icon_url if hasattr(row, 'icon_url') else row.get('icon_url')
return {
'id': _row_id(row),
'name': name,
'description': description,
'icon_url': icon_url,
'dify_app_type': extra.get('dify_app_type') or 'chatflow',
**serialize_agent_category_fields(row),
}
@@ -16,6 +16,14 @@ import AgentPermissionModal from './components/AgentPermissionModal.vue';
import AgentTestModal from './components/AgentTestModal.vue'; import AgentTestModal from './components/AgentTestModal.vue';
import { useAgentsAdmin } from './composables/useAgentsAdmin'; import { useAgentsAdmin } from './composables/useAgentsAdmin';
const formatAgentCategory = (agent: { extra_config?: Record<string, unknown> }) => {
const extra = agent.extra_config && typeof agent.extra_config === 'object' ? agent.extra_config : {};
const category = String(extra.category || '').trim();
const subCategory = String(extra.sub_category || '').trim();
if (category && subCategory) return `${category} / ${subCategory}`;
return category || subCategory || '—';
};
const { t } = useI18n(); const { t } = useI18n();
const { const {
@@ -111,8 +119,9 @@ onMounted(() => {
</div> </div>
<table v-else class="admin-table table-fixed w-full"> <table v-else class="admin-table table-fixed w-full">
<colgroup> <colgroup>
<col class="w-72" /> <col class="w-64" />
<col class="w-[4.5rem]" /> <col class="w-[4.5rem]" />
<col class="w-36" />
<col class="w-32" /> <col class="w-32" />
<col class="w-[5.5rem]" /> <col class="w-[5.5rem]" />
<col /> <col />
@@ -121,6 +130,7 @@ onMounted(() => {
<tr> <tr>
<th class="px-4 py-4 text-sm">{{ t('admin.agent.headers.name') }}</th> <th class="px-4 py-4 text-sm">{{ t('admin.agent.headers.name') }}</th>
<th class="px-2 py-4 text-sm">{{ t('admin.agent.headers.type') }}</th> <th class="px-2 py-4 text-sm">{{ t('admin.agent.headers.type') }}</th>
<th class="px-2 py-4 text-sm">{{ t('admin.agent.headers.category') }}</th>
<th class="px-2 py-4 text-sm">{{ t('admin.agent.headers.config') }}</th> <th class="px-2 py-4 text-sm">{{ t('admin.agent.headers.config') }}</th>
<th class="px-2 py-4 text-sm">{{ t('admin.agent.headers.status') }}</th> <th class="px-2 py-4 text-sm">{{ t('admin.agent.headers.status') }}</th>
<th class="px-4 py-4 text-sm text-right">{{ t('admin.agent.headers.actions') }}</th> <th class="px-4 py-4 text-sm text-right">{{ t('admin.agent.headers.actions') }}</th>
@@ -143,6 +153,9 @@ onMounted(() => {
{{ agent.type }} {{ agent.type }}
</span> </span>
</td> </td>
<td class="px-2 py-5 text-xs text-secondary max-w-36 truncate" :title="formatAgentCategory(agent)">
{{ formatAgentCategory(agent) }}
</td>
<td class="px-2 py-5 font-mono text-xs text-muted max-w-32 truncate"> <td class="px-2 py-5 font-mono text-xs text-muted max-w-32 truncate">
<span v-if="agent.type === 'api'" class="truncate" :title="String(agent.dify_app_id)"> <span v-if="agent.type === 'api'" class="truncate" :title="String(agent.dify_app_id)">
<span class="text-muted">{{ t('admin.agent.idLabel') }}:</span> {{ agent.dify_app_id }} <span class="text-muted">{{ t('admin.agent.idLabel') }}:</span> {{ agent.dify_app_id }}
@@ -107,6 +107,41 @@ const { t } = useI18n();
/> />
</div> </div>
<div class="col-span-1 md:col-span-2 rounded-2xl border border-default bg-surface-soft/40 p-4">
<div class="mb-4 text-xs font-bold uppercase tracking-wider text-muted">{{ t('admin.agent.sections.category') }}</div>
<div class="grid grid-cols-1 gap-4 md:grid-cols-3">
<div class="space-y-2">
<label class="text-xs font-semibold text-secondary">{{ t('admin.agent.fields.category') }}</label>
<input
v-model="form.category"
type="text"
class="w-full input-field text-sm"
:placeholder="t('admin.agent.fields.categoryPlaceholder')"
/>
</div>
<div class="space-y-2">
<label class="text-xs font-semibold text-secondary">{{ t('admin.agent.fields.subCategory') }}</label>
<input
v-model="form.sub_category"
type="text"
class="w-full input-field text-sm"
:placeholder="t('admin.agent.fields.subCategoryPlaceholder')"
/>
</div>
<div class="space-y-2">
<label class="text-xs font-semibold text-secondary">{{ t('admin.agent.fields.sortOrder') }}</label>
<input
v-model.number="form.sort_order"
type="number"
min="0"
step="1"
class="w-full input-field text-sm"
:placeholder="t('admin.agent.fields.sortOrderPlaceholder')"
/>
</div>
</div>
</div>
<div class="col-span-1 md:col-span-2 space-y-3"> <div class="col-span-1 md:col-span-2 space-y-3">
<div class="flex flex-wrap items-center justify-between gap-3"> <div class="flex flex-wrap items-center justify-between gap-3">
<label class="text-xs font-bold text-muted uppercase tracking-wider">常见问题</label> <label class="text-xs font-bold text-muted uppercase tracking-wider">常见问题</label>
@@ -91,6 +91,28 @@ const applyToolRunProgressToExtra = (extraConfig: Record<string, unknown>, form:
delete extraConfig.tool_run_progress; delete extraConfig.tool_run_progress;
}; };
/**
* 将表单分类字段写入 extra_config(P1 轻量方案)。
*/
const applyAgentCategoryToExtra = (extraConfig: Record<string, unknown>, form: AgentFormState): void => {
const category = String(form.category || '').trim();
const subCategory = String(form.sub_category || '').trim();
const sortRaw = Number(form.sort_order);
const sortOrder = Number.isFinite(sortRaw) && sortRaw >= 0 ? Math.floor(sortRaw) : 0;
if (category) {
extraConfig.category = category;
} else {
delete extraConfig.category;
}
if (subCategory) {
extraConfig.sub_category = subCategory;
} else {
delete extraConfig.sub_category;
}
extraConfig.sort_order = sortOrder;
};
export function useAgentsAdmin() { export function useAgentsAdmin() {
const { t } = useI18n(); const { t } = useI18n();
const msg = useMessage(); const msg = useMessage();
@@ -177,6 +199,11 @@ export function useAgentsAdmin() {
suggested_questions_style: agent.extra_config?.suggested_questions_style === 'styled' ? 'styled' : 'plain', suggested_questions_style: agent.extra_config?.suggested_questions_style === 'styled' ? 'styled' : 'plain',
suggested_questions: normalizeSuggestedQuestions(agent.extra_config?.suggested_questions), suggested_questions: normalizeSuggestedQuestions(agent.extra_config?.suggested_questions),
is_active: agent.is_active, is_active: agent.is_active,
category: String(extra.category || ''),
sub_category: String(extra.sub_category || ''),
sort_order: Number(extra.sort_order) >= 0 && Number.isFinite(Number(extra.sort_order))
? Math.floor(Number(extra.sort_order))
: 0,
...toolRunProgress, ...toolRunProgress,
}; };
isEditing.value = true; isEditing.value = true;
@@ -252,6 +279,7 @@ export function useAgentsAdmin() {
} else { } else {
applyToolRunProgressToExtra(extra_config, { ...form.value, tool_run_progress_enabled: false }); applyToolRunProgressToExtra(extra_config, { ...form.value, tool_run_progress_enabled: false });
} }
applyAgentCategoryToExtra(extra_config, form.value);
try { try {
const editingId = isEditing.value ? Number(form.value.id) : null; const editingId = isEditing.value ? Number(form.value.id) : null;
@@ -46,6 +46,12 @@ export interface AgentFormState {
suggested_questions_style: 'plain' | 'styled'; suggested_questions_style: 'plain' | 'styled';
suggested_questions: AgentSuggestedQuestionItem[]; suggested_questions: AgentSuggestedQuestionItem[];
is_active: boolean; is_active: boolean;
/** 一级分类,写入 extra_config.category */
category: string;
/** 二级分类,写入 extra_config.sub_category */
sub_category: string;
/** 排序权重,写入 extra_config.sort_order */
sort_order: number;
/** 是否启用 extra_config.capabilities 中的 tool_run_progress */ /** 是否启用 extra_config.capabilities 中的 tool_run_progress */
tool_run_progress_enabled: boolean; tool_run_progress_enabled: boolean;
/** 对应 ScheduleTask.id,写入 extra_config.tool_run_progress.schedule_task_id */ /** 对应 ScheduleTask.id,写入 extra_config.tool_run_progress.schedule_task_id */
@@ -66,6 +72,9 @@ export const createEmptyAgentForm = (): AgentFormState => ({
suggested_questions_style: 'plain', suggested_questions_style: 'plain',
suggested_questions: [], suggested_questions: [],
is_active: true, is_active: true,
category: '',
sub_category: '',
sort_order: 0,
tool_run_progress_enabled: false, tool_run_progress_enabled: false,
schedule_task_id: null, schedule_task_id: null,
poll_interval_seconds: 2, poll_interval_seconds: 2,
@@ -5,11 +5,10 @@
<script setup lang="ts"> <script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from 'vue'; import { onBeforeUnmount, onMounted, ref } from 'vue';
import { BookOpen, History, LayoutGrid } from 'lucide-vue-next'; import { BookOpen, History, LayoutGrid } from 'lucide-vue-next';
import AgentCategoryList from '@/shared/components/AgentCategoryList.vue';
import type { AgentWithCategory } from '@/shared/utils/agent-category.utils';
export interface ChatMobileHeaderAgent { export interface ChatMobileHeaderAgent extends AgentWithCategory {}
id: number;
name: string;
}
defineProps<{ defineProps<{
agentName: string; agentName: string;
@@ -99,21 +98,12 @@ onBeforeUnmount(() => {
class="absolute right-4 top-12 z-50 w-72 rounded-2xl border border-default bg-surface p-3 shadow-xl" class="absolute right-4 top-12 z-50 w-72 rounded-2xl border border-default bg-surface p-3 shadow-xl"
> >
<div class="mb-2 text-xs font-medium text-muted">{{ $t('chat.agents') }}</div> <div class="mb-2 text-xs font-medium text-muted">{{ $t('chat.agents') }}</div>
<div class="grid grid-cols-2 gap-2"> <AgentCategoryList
<button v-if="userAgents.length > 0"
v-for="agent in userAgents" :agents="userAgents"
:key="agent.id" @select="onSwitchAgent"
type="button" />
class="flex flex-col items-center gap-1.5 rounded-xl px-2 py-3 text-center transition-colors hover-surface-soft" <div v-else class="py-3 text-center text-xs text-muted">{{ $t('chat.noOtherAgents') }}</div>
@click="onSwitchAgent(agent)"
>
<div class="flex h-9 w-9 items-center justify-center rounded-lg bg-brand-50 text-sm font-bold text-brand-600">
{{ agent.name.charAt(0) }}
</div>
<span class="w-full truncate text-xs font-medium text-secondary">{{ agent.name }}</span>
</button>
</div>
<div v-if="userAgents.length === 0" class="py-3 text-center text-xs text-muted">{{ $t('chat.noOtherAgents') }}</div>
</div> </div>
</header> </header>
</template> </template>
@@ -20,13 +20,11 @@ import {
X, X,
} from 'lucide-vue-next'; } from 'lucide-vue-next';
import LocaleToggleButton from '@/shared/components/LocaleToggleButton.vue'; import LocaleToggleButton from '@/shared/components/LocaleToggleButton.vue';
import AgentCategoryList from '@/shared/components/AgentCategoryList.vue';
import type { AgentWithCategory } from '@/shared/utils/agent-category.utils';
import type { DisplayHistoryItem } from '../types/chat.types'; import type { DisplayHistoryItem } from '../types/chat.types';
export interface ChatSidebarAgent { export interface ChatSidebarAgent extends AgentWithCategory {}
id: number;
name: string;
icon_url?: string;
}
const collapsed = defineModel<boolean>('collapsed', { required: true }); const collapsed = defineModel<boolean>('collapsed', { required: true });
const agentPanelOpen = defineModel<boolean>('agentPanelOpen', { required: true }); const agentPanelOpen = defineModel<boolean>('agentPanelOpen', { required: true });
@@ -227,29 +225,26 @@ const userInitial = (fallback: string) => {
</div> </div>
<div class="mt-auto flex flex-col p-4"> <div class="mt-auto flex flex-col p-4">
<div v-if="userAgents.length > 0 && agentPanelOpen" class="chat-agent-panel"> <div v-if="userAgents.length > 0" class="chat-agent-panel">
<div class="mb-2 flex items-center gap-1.5 text-xs font-semibold text-muted"> <div class="mb-2 flex items-center justify-between gap-2">
<div class="flex items-center gap-1.5 text-xs font-semibold text-muted">
<LayoutGrid class="h-3.5 w-3.5" /> {{ $t('chat.agents') }} <LayoutGrid class="h-3.5 w-3.5" /> {{ $t('chat.agents') }}
<span class="font-normal opacity-70">({{ userAgents.length }})</span>
</div> </div>
<div class="grid grid-cols-2 gap-x-2 gap-y-1.5">
<button <button
v-for="agent in userAgents"
:key="agent.id"
type="button" type="button"
class="grid w-full min-w-0 grid-cols-[1rem_1fr] items-center gap-1.5 rounded-xl px-2 py-2 text-left text-xs font-medium text-secondary transition-colors hover-surface-soft hover:shadow-sm" class="text-[10px] font-medium text-brand-600 hover:text-brand-700"
@click="emit('switch-agent', agent)" @click="agentPanelOpen = !agentPanelOpen"
> >
<div {{ agentPanelOpen ? $t('chat.collapseAgents') : $t('chat.expandAgents') }}
v-if="agent.icon_url"
class="h-4 w-4 shrink-0 rounded bg-contain bg-center bg-no-repeat"
:style="{ backgroundImage: `url(${agent.icon_url})` }"
/>
<div v-else class="flex h-4 w-4 shrink-0 items-center justify-center rounded bg-brand-100 text-[9px] font-bold text-brand-600">
{{ agent.name.charAt(0) }}
</div>
<span class="min-w-0 truncate">{{ agent.name }}</span>
</button> </button>
</div> </div>
<AgentCategoryList
v-show="agentPanelOpen"
:agents="userAgents"
compact
@select="emit('switch-agent', $event)"
/>
</div> </div>
<div ref="userMenuRef" class="relative flex items-center justify-between text-muted"> <div ref="userMenuRef" class="relative flex items-center justify-between text-muted">
@@ -6,6 +6,7 @@ import { computed, ref, watch, type ComputedRef } from 'vue';
import { BusinessError } from '@/shared/api/client'; import { BusinessError } from '@/shared/api/client';
import { getUserAgent, listUserAgents } from '@/features/auth/api/user.api'; import { getUserAgent, listUserAgents } from '@/features/auth/api/user.api';
import { setLastChatAgentId } from '@/shared/utils/lastChatAgent'; import { setLastChatAgentId } from '@/shared/utils/lastChatAgent';
import { sortAgentsByCategory } from '@/shared/utils/agent-category.utils';
import type { ChatDeps } from './chat.deps'; import type { ChatDeps } from './chat.deps';
import type { UseChatGuidesReturn } from './useChatGuides'; import type { UseChatGuidesReturn } from './useChatGuides';
@@ -75,7 +76,16 @@ export function useChatAgent(options: UseChatAgentOptions) {
const { t, msg, router } = deps; const { t, msg, router } = deps;
const currentAgent = ref<any>(null); const currentAgent = ref<any>(null);
const userAgents = ref<Array<{ id: number; name: string; description: string; icon_url?: string; dify_app_type?: 'chatflow' | 'workflow' }>>([]); const userAgents = ref<Array<{
id: number;
name: string;
description: string;
icon_url?: string;
dify_app_type?: 'chatflow' | 'workflow';
category?: string | null;
sub_category?: string | null;
sort_order?: number;
}>>([]);
const showAgentPanel = ref(true); const showAgentPanel = ref(true);
const selectedKb = ref(DEFAULT_KB); const selectedKb = ref(DEFAULT_KB);
const kbOptions = [DEFAULT_KB, ERP_KB]; const kbOptions = [DEFAULT_KB, ERP_KB];
@@ -162,12 +172,12 @@ export function useChatAgent(options: UseChatAgentOptions) {
const loadUserAgents = async () => { const loadUserAgents = async () => {
try { try {
const agents = await listUserAgents(); const agents = await listUserAgents();
userAgents.value = Array.isArray(agents) const filtered = Array.isArray(agents)
? agents.filter((a: any) => a.id !== currentAgentId.value && (a.dify_app_type || 'chatflow') === 'chatflow') ? agents.filter((a: any) => a.id !== currentAgentId.value && (a.dify_app_type || 'chatflow') === 'chatflow')
: []; : [];
if (userAgents.value.length === 0) { userAgents.value = sortAgentsByCategory(filtered);
showAgentPanel.value = false; // [STEP 1] 有可切换智能体时默认展开面板;避免切换 Agent 后列表「消失」
} showAgentPanel.value = userAgents.value.length > 0;
} catch { } catch {
userAgents.value = []; userAgents.value = [];
showAgentPanel.value = false; showAgentPanel.value = false;
@@ -16,6 +16,12 @@ import {
type WorkspaceUser, type WorkspaceUser,
} from '../types/workspace.types'; } from '../types/workspace.types';
import type { WorkspaceDeps } from './workspace.deps'; import type { WorkspaceDeps } from './workspace.deps';
import {
extractAgentCategories,
filterAgentsByQuery,
normalizeAgentCategoryFields,
sortAgentsByCategory,
} from '@/shared/utils/agent-category.utils';
interface HomeOptions { interface HomeOptions {
currentUser: Ref<WorkspaceUser | null>; currentUser: Ref<WorkspaceUser | null>;
@@ -41,6 +47,7 @@ export function useWorkspaceHome(deps: WorkspaceDeps, options: HomeOptions) {
{ id: 'all_agents', visible: true, collapsed: false, title: 'workspace.availableAgents' }, { id: 'all_agents', visible: true, collapsed: false, title: 'workspace.availableAgents' },
]); ]);
const searchQuery = ref(''); const searchQuery = ref('');
const selectedCategory = ref<string | null>(null);
const showAnnouncementModal = ref(false); const showAnnouncementModal = ref(false);
const selectedAnnouncement = ref<WorkspaceAnnouncement | null>(null); const selectedAnnouncement = ref<WorkspaceAnnouncement | null>(null);
const userReport = ref<unknown>(null); const userReport = ref<unknown>(null);
@@ -53,13 +60,18 @@ export function useWorkspaceHome(deps: WorkspaceDeps, options: HomeOptions) {
const favoriteAgents = computed(() => agents.value.filter((a) => favoriteAgentIds.value.includes(a.id))); const favoriteAgents = computed(() => agents.value.filter((a) => favoriteAgentIds.value.includes(a.id)));
const otherAgents = computed(() => { const chatflowAgents = computed(() =>
const chatflowAgents = agents.value.filter((a) => (a.dify_app_type || 'chatflow') === 'chatflow'); sortAgentsByCategory(agents.value.filter((a) => (a.dify_app_type || 'chatflow') === 'chatflow')),
if (!searchQuery.value.trim()) return chatflowAgents;
const q = searchQuery.value.toLowerCase();
return chatflowAgents.filter(
(a) => a.name.toLowerCase().includes(q) || a.description.toLowerCase().includes(q),
); );
const agentCategories = computed(() => extractAgentCategories(chatflowAgents.value));
const otherAgents = computed(() => {
let list = chatflowAgents.value;
if (selectedCategory.value) {
list = list.filter((a) => normalizeAgentCategoryFields(a).category === selectedCategory.value);
}
return filterAgentsByQuery(list, searchQuery.value);
}); });
const filteredQuickQuestions = computed(() => { const filteredQuickQuestions = computed(() => {
@@ -85,6 +97,7 @@ export function useWorkspaceHome(deps: WorkspaceDeps, options: HomeOptions) {
favoriteAgentIds.value = []; favoriteAgentIds.value = [];
embeddedAgents.value = []; embeddedAgents.value = [];
userReport.value = null; userReport.value = null;
selectedCategory.value = null;
}; };
const fetchHome = async () => { const fetchHome = async () => {
@@ -322,6 +335,8 @@ export function useWorkspaceHome(deps: WorkspaceDeps, options: HomeOptions) {
SECTION_TITLE_KEY_MAP, SECTION_TITLE_KEY_MAP,
layoutSections, layoutSections,
searchQuery, searchQuery,
selectedCategory,
agentCategories,
showAnnouncementModal, showAnnouncementModal,
selectedAnnouncement, selectedAnnouncement,
userReport, userReport,
@@ -161,6 +161,26 @@ const ws = inject(WORKSPACE_KEY)! as any;
<!-- Content: All Agents --> <!-- Content: All Agents -->
<div v-if="section.id === 'all_agents'"> <div v-if="section.id === 'all_agents'">
<div class="mb-4 flex flex-wrap gap-2">
<button
type="button"
class="rounded-full px-3 py-1.5 text-xs font-medium transition-colors"
:class="!ws.selectedCategory ? 'bg-brand-600 text-white' : 'bg-surface-soft text-secondary hover:bg-slate-100'"
@click="ws.selectedCategory = null"
>
{{ $t('workspace.agentCategory.all') }}
</button>
<button
v-for="category in ws.agentCategories"
:key="category"
type="button"
class="rounded-full px-3 py-1.5 text-xs font-medium transition-colors"
:class="ws.selectedCategory === category ? 'bg-brand-600 text-white' : 'bg-surface-soft text-secondary hover:bg-slate-100'"
@click="ws.selectedCategory = category"
>
{{ category }}
</button>
</div>
<div class="mb-6"> <div class="mb-6">
<input v-model="ws.searchQuery" type="text" :placeholder="$t('workspace.search')" class="input-field max-w-md shadow-sm" /> <input v-model="ws.searchQuery" type="text" :placeholder="$t('workspace.search')" class="input-field max-w-md shadow-sm" />
</div> </div>
@@ -29,6 +29,9 @@ export interface WorkspaceAgent {
description: string; description: string;
icon_url?: string; icon_url?: string;
dify_app_type?: 'chatflow' | 'workflow'; dify_app_type?: 'chatflow' | 'workflow';
category?: string | null;
sub_category?: string | null;
sort_order?: number;
} }
export interface WorkspaceQuickQuestion { export interface WorkspaceQuickQuestion {
+11 -1
View File
@@ -143,6 +143,7 @@
"headers": { "headers": {
"name": "Name", "name": "Name",
"type": "Type", "type": "Type",
"category": "Category",
"config": "Configuration", "config": "Configuration",
"status": "Status", "status": "Status",
"actions": "Actions" "actions": "Actions"
@@ -161,9 +162,18 @@
"baseUrlPlaceholder": "Default: Dify Config", "baseUrlPlaceholder": "Default: Dify Config",
"iframeUrl": "Iframe URL", "iframeUrl": "Iframe URL",
"description": "Description", "description": "Description",
"descPlaceholder": "Briefly describe what this agent does..." "descPlaceholder": "Briefly describe what this agent does...",
"category": "Primary category",
"categoryPlaceholder": "e.g. R&D Systems",
"subCategory": "Subcategory",
"subCategoryPlaceholder": "e.g. System Documents (optional)",
"sortOrder": "Sort order",
"sortOrderPlaceholder": "Lower numbers appear first (default 0)"
}, },
"confirmDelete": "Are you sure you want to delete this agent?", "confirmDelete": "Are you sure you want to delete this agent?",
"sections": {
"category": "Display category"
},
"manageAccess": "Manage Access", "manageAccess": "Manage Access",
"test": "Test", "test": "Test",
"delete": "Delete Agent", "delete": "Delete Agent",
+5
View File
@@ -164,6 +164,11 @@
"clearOneRecord": "Clear This Record", "clearOneRecord": "Clear This Record",
"agents": "Agents", "agents": "Agents",
"noOtherAgents": "No other agents", "noOtherAgents": "No other agents",
"agentCategory": {
"searchPlaceholder": "Search agents…",
"noResults": "No matching agents",
"uncategorized": "Knowledge Base Q&A"
},
"noAvailableAgents": "No available agents", "noAvailableAgents": "No available agents",
"collapseAgents": "Collapse agents", "collapseAgents": "Collapse agents",
"expandAgents": "Expand agents", "expandAgents": "Expand agents",
+4
View File
@@ -51,6 +51,10 @@
"favorites": "Favorites", "favorites": "Favorites",
"myAgents": "My Agents", "myAgents": "My Agents",
"availableAgents": "Available Agents", "availableAgents": "Available Agents",
"agentCategory": {
"all": "All",
"uncategorized": "Knowledge Base Q&A"
},
"noAgents": "No agents available", "noAgents": "No agents available",
"noPublicAgents": "No public agents available, please contact admin.", "noPublicAgents": "No public agents available, please contact admin.",
"requestPermission": "Request Access", "requestPermission": "Request Access",
+11 -1
View File
@@ -143,6 +143,7 @@
"headers": { "headers": {
"name": "ชื่อ", "name": "ชื่อ",
"type": "ประเภท", "type": "ประเภท",
"category": "หมวดหมู่",
"config": "การกำหนดค่า", "config": "การกำหนดค่า",
"status": "สถานะ", "status": "สถานะ",
"actions": "การกระทำ" "actions": "การกระทำ"
@@ -161,9 +162,18 @@
"baseUrlPlaceholder": "ค่าเริ่มต้น: ใช้การตั้งค่า Dify", "baseUrlPlaceholder": "ค่าเริ่มต้น: ใช้การตั้งค่า Dify",
"iframeUrl": "Iframe URL", "iframeUrl": "Iframe URL",
"description": "คำอธิบาย", "description": "คำอธิบาย",
"descPlaceholder": "อธิบายสั้นๆ เกี่ยวกับตัวแทนนี้..." "descPlaceholder": "อธิบายสั้นๆ เกี่ยวกับตัวแทนนี้...",
"category": "หมวดหมู่หลัก",
"categoryPlaceholder": "เช่น ระบบวิจัยและพัฒนา",
"subCategory": "หมวดหมู่ย่อย",
"subCategoryPlaceholder": "เช่น เอกสารระบบ (ไม่บังคับ)",
"sortOrder": "ลำดับการแสดง",
"sortOrderPlaceholder": "ตัวเลขน้อยแสดงก่อน (ค่าเริ่มต้น 0)"
}, },
"confirmDelete": "คุณแน่ใจหรือไม่ว่าต้องการลบตัวแทนนี้?", "confirmDelete": "คุณแน่ใจหรือไม่ว่าต้องการลบตัวแทนนี้?",
"sections": {
"category": "หมวดหมู่การแสดงผล"
},
"manageAccess": "จัดการสิทธิ์", "manageAccess": "จัดการสิทธิ์",
"test": "ทดสอบ", "test": "ทดสอบ",
"delete": "ลบแอป", "delete": "ลบแอป",
+5
View File
@@ -164,6 +164,11 @@
"clearOneRecord": "ลบรายการนี้", "clearOneRecord": "ลบรายการนี้",
"agents": "ตัวแทน", "agents": "ตัวแทน",
"noOtherAgents": "ไม่มีตัวแทนอื่น", "noOtherAgents": "ไม่มีตัวแทนอื่น",
"agentCategory": {
"searchPlaceholder": "ค้นหาตัวแทน…",
"noResults": "ไม่พบตัวแทนที่ตรงกัน",
"uncategorized": "ฐานความรู้ Q&A"
},
"noAvailableAgents": "ไม่มีตัวแทนที่ใช้ได้", "noAvailableAgents": "ไม่มีตัวแทนที่ใช้ได้",
"collapseAgents": "ย่อตัวแทน", "collapseAgents": "ย่อตัวแทน",
"expandAgents": "ขยายตัวแทน", "expandAgents": "ขยายตัวแทน",
+4
View File
@@ -51,6 +51,10 @@
"favorites": "รายการโปรด", "favorites": "รายการโปรด",
"myAgents": "ตัวแทนของฉัน", "myAgents": "ตัวแทนของฉัน",
"availableAgents": "ตัวแทนที่ใช้ได้", "availableAgents": "ตัวแทนที่ใช้ได้",
"agentCategory": {
"all": "ทั้งหมด",
"uncategorized": "ฐานความรู้ Q&A"
},
"noAgents": "ไม่มีตัวแทนที่ใช้ได้", "noAgents": "ไม่มีตัวแทนที่ใช้ได้",
"noFavorites": "ไม่มีรายการโปรด", "noFavorites": "ไม่มีรายการโปรด",
"noPublicAgents": "ไม่มีตัวแทนสาธารณะที่ใช้ได้ โปรดติดต่อผู้ดูแลระบบ", "noPublicAgents": "ไม่มีตัวแทนสาธารณะที่ใช้ได้ โปรดติดต่อผู้ดูแลระบบ",
+11 -1
View File
@@ -144,6 +144,7 @@
"headers": { "headers": {
"name": "名称", "name": "名称",
"type": "类型", "type": "类型",
"category": "分类",
"config": "配置", "config": "配置",
"status": "状态", "status": "状态",
"actions": "操作" "actions": "操作"
@@ -162,9 +163,18 @@
"baseUrlPlaceholder": "默认:使用 Dify 配置", "baseUrlPlaceholder": "默认:使用 Dify 配置",
"iframeUrl": "Iframe URL", "iframeUrl": "Iframe URL",
"description": "描述", "description": "描述",
"descPlaceholder": "简要描述该应用的功能..." "descPlaceholder": "简要描述该应用的功能...",
"category": "一级分类",
"categoryPlaceholder": "例如:研发体系",
"subCategory": "二级分类",
"subCategoryPlaceholder": "例如:体系文件(选填)",
"sortOrder": "排序权重",
"sortOrderPlaceholder": "数字越小越靠前,默认 0"
}, },
"confirmDelete": "确定要删除该应用吗?", "confirmDelete": "确定要删除该应用吗?",
"sections": {
"category": "展示分类"
},
"manageAccess": "管理权限", "manageAccess": "管理权限",
"test": "测试", "test": "测试",
"delete": "删除应用", "delete": "删除应用",
+5
View File
@@ -168,6 +168,11 @@
"clearOneRecord": "清除该记录", "clearOneRecord": "清除该记录",
"agents": "智能体", "agents": "智能体",
"noOtherAgents": "暂无其他智能体", "noOtherAgents": "暂无其他智能体",
"agentCategory": {
"searchPlaceholder": "搜索智能体…",
"noResults": "未找到匹配的智能体",
"uncategorized": "知识库问答"
},
"noAvailableAgents": "暂无可用智能体", "noAvailableAgents": "暂无可用智能体",
"collapseAgents": "收起智能体", "collapseAgents": "收起智能体",
"expandAgents": "展开智能体", "expandAgents": "展开智能体",
@@ -51,6 +51,10 @@
"favorites": "收藏应用", "favorites": "收藏应用",
"myAgents": "我的应用", "myAgents": "我的应用",
"availableAgents": "可用应用", "availableAgents": "可用应用",
"agentCategory": {
"all": "全部",
"uncategorized": "知识库问答"
},
"noAgents": "暂无可用应用", "noAgents": "暂无可用应用",
"noFavorites": "暂无收藏", "noFavorites": "暂无收藏",
"noPublicAgents": "暂无公开应用,请联系管理员。", "noPublicAgents": "暂无公开应用,请联系管理员。",
+11 -1
View File
@@ -143,6 +143,7 @@
"headers": { "headers": {
"name": "名稱", "name": "名稱",
"type": "類型", "type": "類型",
"category": "分類",
"config": "配置", "config": "配置",
"status": "狀態", "status": "狀態",
"actions": "操作" "actions": "操作"
@@ -161,9 +162,18 @@
"baseUrlPlaceholder": "預設:使用 Dify 配置", "baseUrlPlaceholder": "預設:使用 Dify 配置",
"iframeUrl": "Iframe URL", "iframeUrl": "Iframe URL",
"description": "描述", "description": "描述",
"descPlaceholder": "簡要描述該應用的功能..." "descPlaceholder": "簡要描述該應用的功能...",
"category": "一級分類",
"categoryPlaceholder": "例如:研發體系",
"subCategory": "二級分類",
"subCategoryPlaceholder": "例如:體系文件(選填)",
"sortOrder": "排序權重",
"sortOrderPlaceholder": "數字越小越靠前,預設 0"
}, },
"confirmDelete": "確定要刪除該應用嗎?", "confirmDelete": "確定要刪除該應用嗎?",
"sections": {
"category": "展示分類"
},
"manageAccess": "管理權限", "manageAccess": "管理權限",
"test": "測試", "test": "測試",
"delete": "刪除應用", "delete": "刪除應用",
+5
View File
@@ -164,6 +164,11 @@
"clearOneRecord": "清除此記錄", "clearOneRecord": "清除此記錄",
"agents": "智能體", "agents": "智能體",
"noOtherAgents": "暫無其他智能體", "noOtherAgents": "暫無其他智能體",
"agentCategory": {
"searchPlaceholder": "搜尋智能體…",
"noResults": "未找到符合的智能體",
"uncategorized": "知識庫問答"
},
"noAvailableAgents": "暫無可用智能體", "noAvailableAgents": "暫無可用智能體",
"collapseAgents": "收起智能體", "collapseAgents": "收起智能體",
"expandAgents": "展開智能體", "expandAgents": "展開智能體",
@@ -51,6 +51,10 @@
"favorites": "收藏應用", "favorites": "收藏應用",
"myAgents": "我的應用", "myAgents": "我的應用",
"availableAgents": "可用應用", "availableAgents": "可用應用",
"agentCategory": {
"all": "全部",
"uncategorized": "知識庫問答"
},
"noAgents": "暫無可用應用", "noAgents": "暫無可用應用",
"noFavorites": "暫無收藏", "noFavorites": "暫無收藏",
"noPublicAgents": "暫無公開應用,請聯繫管理員。", "noPublicAgents": "暫無公開應用,請聯繫管理員。",
@@ -0,0 +1,144 @@
/**
* shared/components/AgentCategoryList.vue
* 用途:按一级/二级分类展示可切换的 Agent 列表,支持搜索与折叠分组。
* 依赖:agent-category.utils、vue-i18n。
* 逻辑:ChatSidebar、ChatMobileHeader 等入口传入 agents 与 select 事件即可复用。
*/
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { ChevronDown, ChevronRight, Search } from 'lucide-vue-next';
import {
filterAgentsByQuery,
groupAgentsByCategory,
type AgentWithCategory,
} from '@/shared/utils/agent-category.utils';
const props = withDefaults(defineProps<{
agents: AgentWithCategory[];
compact?: boolean;
showSearch?: boolean;
defaultExpanded?: boolean;
}>(), {
compact: false,
showSearch: true,
defaultExpanded: true,
});
const emit = defineEmits<{
select: [agent: AgentWithCategory];
}>();
const { t } = useI18n();
const searchQuery = ref('');
const collapsedCategories = ref<Set<string>>(new Set());
const uncategorizedLabel = computed(() => t('chat.agentCategory.uncategorized'));
const filteredAgents = computed(() => filterAgentsByQuery(props.agents, searchQuery.value));
const categoryGroups = computed(() =>
groupAgentsByCategory(filteredAgents.value, uncategorizedLabel.value),
);
/**
* 同步分类折叠态:新增分类默认展开,移除已不存在的折叠记录。
*/
const syncCollapsedState = () => {
const keys = new Set(categoryGroups.value.map((group) => group.category));
const next = new Set<string>();
for (const key of collapsedCategories.value) {
if (keys.has(key)) next.add(key);
}
if (!props.defaultExpanded) {
for (const group of categoryGroups.value) {
if (!next.has(group.category)) next.add(group.category);
}
}
collapsedCategories.value = next;
};
watch(categoryGroups, syncCollapsedState, { immediate: true });
const toggleCategory = (category: string) => {
const next = new Set(collapsedCategories.value);
if (next.has(category)) {
next.delete(category);
} else {
next.add(category);
}
collapsedCategories.value = next;
};
const isCategoryCollapsed = (category: string) => collapsedCategories.value.has(category);
const onSelect = (agent: AgentWithCategory) => {
emit('select', agent);
};
</script>
<template>
<div class="space-y-2">
<div v-if="showSearch" class="relative">
<Search class="pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted" />
<input
v-model="searchQuery"
type="search"
class="w-full rounded-lg border border-default bg-surface py-1.5 pl-7 pr-2 text-xs text-primary placeholder:text-muted focus:border-brand-400 focus:outline-none focus:ring-1 focus:ring-brand-400"
:placeholder="t('chat.agentCategory.searchPlaceholder')"
/>
</div>
<div v-if="categoryGroups.length === 0" class="py-2 text-center text-xs text-muted">
{{ t('chat.agentCategory.noResults') }}
</div>
<div v-else class="max-h-48 space-y-2 overflow-y-auto scrollbar-thin">
<section v-for="group in categoryGroups" :key="group.category" class="space-y-1">
<button
type="button"
class="flex w-full items-center gap-1 rounded-md px-1 py-0.5 text-left text-[11px] font-semibold text-muted transition-colors hover:text-secondary"
@click="toggleCategory(group.category)"
>
<ChevronDown v-if="!isCategoryCollapsed(group.category)" class="h-3 w-3 shrink-0" />
<ChevronRight v-else class="h-3 w-3 shrink-0" />
<span class="min-w-0 flex-1 truncate">{{ group.category }}</span>
<span class="shrink-0 text-[10px] font-normal opacity-70">({{ group.agents.length }})</span>
</button>
<div v-show="!isCategoryCollapsed(group.category)" class="space-y-2 pl-1">
<template v-for="subGroup in group.subGroups" :key="`${group.category}-${subGroup.subCategory || '_'}`">
<div
v-if="subGroup.subCategory && group.subGroups.length > 1"
class="px-1 text-[10px] font-medium text-muted"
>
{{ subGroup.subCategory }}
</div>
<div :class="compact ? 'grid grid-cols-2 gap-x-2 gap-y-1.5' : 'grid grid-cols-2 gap-2'">
<button
v-for="agent in subGroup.agents"
:key="agent.id"
type="button"
class="grid w-full min-w-0 grid-cols-[1rem_1fr] items-center gap-1.5 rounded-xl px-2 py-2 text-left text-xs font-medium text-secondary transition-colors hover-surface-soft hover:shadow-sm"
@click="onSelect(agent)"
>
<div
v-if="agent.icon_url"
class="h-4 w-4 shrink-0 rounded bg-contain bg-center bg-no-repeat"
:style="{ backgroundImage: `url(${agent.icon_url})` }"
/>
<div
v-else
class="flex h-4 w-4 shrink-0 items-center justify-center rounded bg-brand-100 text-[9px] font-bold text-brand-600"
>
{{ agent.name.charAt(0) }}
</div>
<span class="min-w-0 truncate">{{ agent.name }}</span>
</button>
</div>
</template>
</div>
</section>
</div>
</div>
</template>
@@ -0,0 +1,126 @@
/**
* shared/utils/agent-category.utils.ts
* 用途:Agent P1 分类(extra_config.category / sub_category / sort_order)的解析、排序与分组。
* 依赖:无;供 Chat 侧栏、工作台、管理端列表复用。
* 逻辑:分类暂存 extra_config;P2 迁移独立表后本工具仅改数据来源。
*/
export interface AgentCategoryFields {
category?: string | null;
sub_category?: string | null;
sort_order?: number;
}
export interface AgentWithCategory extends AgentCategoryFields {
id: number;
name: string;
icon_url?: string;
description?: string;
}
export interface AgentCategorySubGroup<T extends AgentWithCategory = AgentWithCategory> {
subCategory: string;
agents: T[];
}
export interface AgentCategoryGroup<T extends AgentWithCategory = AgentWithCategory> {
category: string;
subGroups: AgentCategorySubGroup<T>[];
agents: T[];
}
const UNCATEGORIZED_KEY = '';
/**
* 规范化分类字段,去除空白并将 sort_order 转为非负整数。
*/
export function normalizeAgentCategoryFields(
agent: AgentCategoryFields,
): { category: string; subCategory: string; sortOrder: number } {
const category = String(agent.category || '').trim();
const subCategory = String(agent.sub_category || '').trim();
const raw = Number(agent.sort_order);
const sortOrder = Number.isFinite(raw) && raw >= 0 ? Math.floor(raw) : 0;
return { category, subCategory, sortOrder };
}
/**
* 按 sort_order → category → sub_category → name 排序 Agent 列表。
*/
export function sortAgentsByCategory<T extends AgentWithCategory>(agents: T[]): T[] {
return [...agents].sort((a, b) => {
const left = normalizeAgentCategoryFields(a);
const right = normalizeAgentCategoryFields(b);
if (left.sortOrder !== right.sortOrder) return left.sortOrder - right.sortOrder;
const catA = left.category || '\uffff';
const catB = right.category || '\uffff';
if (catA !== catB) return catA.localeCompare(catB, 'zh-CN');
const subA = left.subCategory || '\uffff';
const subB = right.subCategory || '\uffff';
if (subA !== subB) return subA.localeCompare(subB, 'zh-CN');
return a.name.localeCompare(b.name, 'zh-CN');
});
}
/**
* 将 Agent 列表按一级 category、二级 sub_category 分组。
* @param uncategorizedLabel - 未配置 category 时的默认分组名(i18n:知识库问答)
*/
export function groupAgentsByCategory<T extends AgentWithCategory>(
agents: T[],
uncategorizedLabel: string,
): AgentCategoryGroup<T>[] {
const sorted = sortAgentsByCategory(agents);
const categoryMap = new Map<string, AgentCategoryGroup<T>>();
for (const agent of sorted) {
const { category, subCategory } = normalizeAgentCategoryFields(agent);
const categoryKey = category || UNCATEGORIZED_KEY;
const displayCategory = category || uncategorizedLabel;
if (!categoryMap.has(categoryKey)) {
categoryMap.set(categoryKey, {
category: displayCategory,
subGroups: [],
agents: [],
});
}
const group = categoryMap.get(categoryKey)!;
group.agents.push(agent);
const subKey = subCategory || UNCATEGORIZED_KEY;
let subGroup = group.subGroups.find((item) => (item.subCategory || UNCATEGORIZED_KEY) === subKey);
if (!subGroup) {
subGroup = { subCategory, agents: [] };
group.subGroups.push(subGroup);
}
subGroup.agents.push(agent);
}
return Array.from(categoryMap.values());
}
/**
* 提取去重且已排序的一级分类名称(不含未分类)。
*/
export function extractAgentCategories<T extends AgentWithCategory>(agents: T[]): string[] {
const set = new Set<string>();
for (const agent of agents) {
const { category } = normalizeAgentCategoryFields(agent);
if (category) set.add(category);
}
return Array.from(set).sort((a, b) => a.localeCompare(b, 'zh-CN'));
}
/**
* 按关键词过滤 Agent(名称、一级/二级分类)。
*/
export function filterAgentsByQuery<T extends AgentWithCategory>(agents: T[], query: string): T[] {
const q = query.trim().toLowerCase();
if (!q) return agents;
return agents.filter((agent) => {
const { category, subCategory } = normalizeAgentCategoryFields(agent);
const haystack = [agent.name, category, subCategory].join(' ').toLowerCase();
return haystack.includes(q);
});
}