feat(chat): 应用目录只配置成聚合应用

This commit is contained in:
sophie committed 2026-07-09 14:43:09 +08:00
1 parent 5bef77f86c
commit dab04d4c3e
28 files changed
+797 -138

No files matched your search

+16 -4
View File
@@ -19,8 +19,18 @@ from app.services.minio_service import minio_service
agents_bp = Blueprint('agents', __name__)
def _serialize_agent_row(agent: Agent) -> dict:
return serialize_agent_list_item(agent)
def _serialize_agent_row(agent: Agent, *, visible_agent_ids: set[int] | None = None) -> dict:
payload = serialize_agent_list_item(agent)
if not bool(getattr(agent, 'is_aggregate', False)):
return payload
from app.services.agent_directory import serialize_directory_members
members = serialize_directory_members(agent.id, active_only=True)
if visible_agent_ids is not None:
members = [member for member in members if int(member.get('id') or 0) in visible_agent_ids]
if members:
payload['directory_members'] = members
return payload
def _list_active_agents_for_user(user: User) -> list[Agent]:
@@ -46,7 +56,8 @@ def list_user_agents():
raise UnauthorizedError()
agents = _list_active_agents_for_user(user)
return jsonify([_serialize_agent_row(agent) for agent in sort_agent_rows(agents)])
visible_agent_ids = {agent.id for agent in agents}
return jsonify([_serialize_agent_row(agent, visible_agent_ids=visible_agent_ids) for agent in sort_agent_rows(agents)])
@agents_bp.route('/<int:agent_id>/guides', methods=['GET'])
def list_agent_guides(agent_id):
@@ -101,7 +112,8 @@ def list_public_agents():
.order_by(Agent.id.asc())
.all()
)
return jsonify([_serialize_agent_row(agent) for agent in sort_agent_rows(agents)])
visible_agent_ids = {agent.id for agent in agents}
return jsonify([_serialize_agent_row(agent, visible_agent_ids=visible_agent_ids) for agent in sort_agent_rows(agents)])
# 为了兼容本地无MinIO的环境,暴露一个静态文件读取接口
@agents_bp.route('/guides/files/<path:filename>', methods=['GET'])
+6
View File
@@ -1327,6 +1327,10 @@ def chat_completions():
agent_id = getattr(agent, 'id', None)
from types import SimpleNamespace
from app.services.agent_directory import serialize_directory_members
is_aggregate = bool(getattr(agent, 'is_aggregate', False))
directory_members = serialize_directory_members(agent_id, active_only=True) if is_aggregate else []
agent_proxy = SimpleNamespace(
id=agent_id,
name=getattr(agent, 'name', None),
@@ -1341,6 +1345,8 @@ def chat_completions():
capabilities=getattr(agent, 'capabilities', None),
bound_schedule_task_id=getattr(agent, 'bound_schedule_task_id', None),
handler_config=getattr(agent, 'handler_config', None),
is_aggregate=is_aggregate,
directory_members=directory_members,
)
user_proxy = SimpleNamespace(
id=user_id,
+2 -1
View File
@@ -6,7 +6,7 @@ backend/app/models/__init__.py
逻辑:Alembic / Flask-Migrate 通过本模块 import 注册全部表元数据;业务代码继续从此处导入模型类。
"""
from app.models.agent import Agent, AgentGuide, PermissionRequest
from app.models.agent import Agent, AgentDirectoryMember, AgentGuide, PermissionRequest
from app.models.base import Base, user_agent_permissions
from app.models.chat import ChatLog, ChatSession, Feedback, GeneralFeedback
from app.models.content import Announcement, FaqHotCandidate, QuickQuestion, ZlLanguage
@@ -66,6 +66,7 @@ __all__ = [
'ShippingTaskInventoryLink',
'ShippingInventoryMapping',
'AgentGuide',
'AgentDirectoryMember',
'TrainingRecord',
'MaintenanceDevice',
'MaintenanceRecord',
+26 -1
View File
@@ -11,7 +11,7 @@ from __future__ import annotations
from datetime import datetime
from typing import List, Optional
from sqlalchemy import DateTime, ForeignKey, Integer, JSON, String, Text
from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, JSON, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base, user_agent_permissions
@@ -36,6 +36,7 @@ class Agent(Base):
api_base_url: Mapped[Optional[str]] = mapped_column(String(255))
extra_config: Mapped[Optional[dict]] = mapped_column(JSON)
is_active: Mapped[bool] = mapped_column(default=True)
is_aggregate: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
# Agent Registry 结构化列(迭代 1;详见 docs/platform/agent_application_management.md §3.1)
@@ -90,6 +91,30 @@ class AgentGuide(Base):
agent: Mapped[Optional['Agent']] = relationship('Agent', foreign_keys=[agent_id])
class AgentDirectoryMember(Base):
"""
Directory-agent membership.
Purpose: lets an Agent act as a clickable directory entry while explicitly
listing the child Agents whose knowledge should be included by the upstream
aggregate Chatflow.
"""
__tablename__ = 'agent_directory_members'
__table_args__ = (
UniqueConstraint('directory_agent_id', 'member_agent_id', name='uq_agent_directory_member_pair'),
)
id: Mapped[int] = mapped_column(primary_key=True)
directory_agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id', ondelete='CASCADE'), index=True)
member_agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id', ondelete='CASCADE'), index=True)
sort_order: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
directory_agent: Mapped[Optional['Agent']] = relationship('Agent', foreign_keys=[directory_agent_id])
member_agent: Mapped[Optional['Agent']] = relationship('Agent', foreign_keys=[member_agent_id])
class PermissionRequest(Base):
"""
权限申请表
@@ -16,6 +16,7 @@ from app import db
from app.core.config.settings import Config
from app.core.errors import NotFoundError, ValidationError
from app.models import Agent, User
from app.services.agent_directory import normalize_directory_member_ids, replace_directory_members
from app.services.admin.training_exam_pdf_service import parse_training_question_bank_from_guide
from app.services.agent_registry.admin_payload import apply_agent_payload, validate_agent_payload
from app.services.agent_registry.catalog_loader import get_dify_required_providers
@@ -56,6 +57,9 @@ def create_agent(data: dict[str, Any]) -> dict:
apply_agent_payload(agent, normalized)
db.session.add(agent)
db.session.flush()
member_ids = data.get('directory_member_ids') if agent.is_aggregate else []
replace_directory_members(agent, normalize_directory_member_ids(member_ids, directory_agent_id=agent.id))
db.session.commit()
return {'id': agent.id}
@@ -94,12 +98,16 @@ def update_agent(agent_id: int, data: dict[str, Any]) -> None:
'bound_schedule_task_id': data.get('bound_schedule_task_id', agent.bound_schedule_task_id),
'handler_config': _pick_update_value(data, 'handler_config', agent.handler_config),
'extra_config': _pick_update_value(data, 'extra_config', agent.extra_config),
'is_aggregate': data.get('is_aggregate', agent.is_aggregate),
}
if data.get('dify_api_key'):
merged['dify_api_key'] = data['dify_api_key']
normalized = validate_agent_payload(merged, agent=agent, provided_fields=frozenset(data.keys()))
apply_agent_payload(agent, normalized)
if 'directory_member_ids' in data or 'is_aggregate' in data:
member_ids = data.get('directory_member_ids') if agent.is_aggregate else []
replace_directory_members(agent, normalize_directory_member_ids(member_ids, directory_agent_id=agent.id))
db.session.commit()
+108
View File
@@ -0,0 +1,108 @@
"""
backend/app/services/agent_directory.py
Purpose: manage directory-style Agents and expose their member metadata.
Dependencies: app.models Agent/AgentDirectoryMember, SQLAlchemy session.
Flow: Admin saves member IDs on an Agent; chat runtime serializes active members
into Dify inputs so an aggregate Chatflow can query the selected knowledge apps.
"""
from __future__ import annotations
from typing import Any
from app import db
from app.core.errors import ValidationError
from app.models import Agent, AgentDirectoryMember
def normalize_directory_member_ids(raw: Any, *, directory_agent_id: int | None = None) -> list[int]:
"""
Normalize Admin-provided directory member IDs.
AI trigger timing: call this whenever an Agent form payload includes the
directory_members field. It rejects non-numeric IDs, removes duplicates, and
prevents an Agent from being a member of itself.
"""
if raw in (None, ''):
return []
if not isinstance(raw, list):
raise ValidationError('directory_member_ids must be a list')
result: list[int] = []
seen: set[int] = set()
for item in raw:
try:
member_id = int(item)
except (TypeError, ValueError):
raise ValidationError('directory_member_ids must contain valid integers')
if member_id <= 0 or member_id in seen:
continue
if directory_agent_id and member_id == int(directory_agent_id):
raise ValidationError('A directory agent cannot include itself')
seen.add(member_id)
result.append(member_id)
return result
def replace_directory_members(agent: Agent, member_ids: list[int]) -> None:
"""
Replace directory membership for an Agent.
Core logic: validate all target Agents exist, delete previous rows, then
insert the new ordered set in the same transaction as the caller's save.
"""
normalized_ids = normalize_directory_member_ids(member_ids, directory_agent_id=agent.id)
db.session.query(AgentDirectoryMember).filter_by(directory_agent_id=agent.id).delete(synchronize_session=False)
if not normalized_ids:
return
existing_ids = {
row.id
for row in db.session.query(Agent.id).filter(Agent.id.in_(normalized_ids)).all()
}
missing_ids = [member_id for member_id in normalized_ids if member_id not in existing_ids]
if missing_ids:
raise ValidationError(f'Directory member agents not found: {missing_ids}')
for index, member_id in enumerate(normalized_ids):
db.session.add(AgentDirectoryMember(
directory_agent_id=agent.id,
member_agent_id=member_id,
sort_order=index,
))
def list_directory_member_agents(agent_id: int, *, active_only: bool = False) -> list[Agent]:
"""Return member Agent rows for a directory Agent in configured order."""
query = (
db.session.query(Agent)
.join(AgentDirectoryMember, AgentDirectoryMember.member_agent_id == Agent.id)
.filter(AgentDirectoryMember.directory_agent_id == agent_id)
.order_by(AgentDirectoryMember.sort_order.asc(), Agent.id.asc())
)
if active_only:
query = query.filter(Agent.is_active.is_(True))
return query.all()
def serialize_directory_member(agent: Agent) -> dict[str, Any]:
"""Serialize one member Agent for Admin and Dify runtime metadata."""
return {
'id': agent.id,
'name': agent.name,
'description': agent.description,
'icon_url': agent.icon_url,
'agent_code': agent.agent_code,
'dify_app_id': agent.dify_app_id,
'category': agent.category,
'sub_category': agent.sub_category,
}
def serialize_directory_members(agent_id: int, *, active_only: bool = False) -> list[dict[str, Any]]:
"""Serialize configured member Agents for a directory Agent."""
return [
serialize_directory_member(agent)
for agent in list_directory_member_agents(agent_id, active_only=active_only)
]
@@ -44,6 +44,7 @@ MIGRATED_EXTRA_REGISTRY_KEYS = frozenset({
'suggested_questions',
'capabilities',
'tool_run_progress',
'is_aggregate',
})
@@ -68,6 +69,13 @@ def _parse_is_active(raw: Any, *, default: bool) -> bool:
return coerce_manifest_boolean(raw, context='is_active')
def _parse_is_aggregate(raw: Any, *, default: bool) -> bool:
"""Admin is_aggregate 布尔归一化;只有为 true 时才保留目录成员配置。"""
if raw is None:
return default
return coerce_manifest_boolean(raw, context='is_aggregate')
def _parse_bound_schedule_task_id(raw: Any) -> int | None:
if raw is None or raw == '':
return None
@@ -231,12 +239,19 @@ def validate_agent_payload(
if 'is_active' in data
else is_active_default
)
is_aggregate_default = bool(getattr(agent, 'is_aggregate', False)) if agent else False
is_aggregate = (
_parse_is_aggregate(data.get('is_aggregate'), default=is_aggregate_default)
if 'is_aggregate' in data
else is_aggregate_default
)
return {
'name': _strip(data.get('name')),
'description': data.get('description'),
'icon_url': data.get('icon_url'),
'is_active': is_active,
'is_aggregate': is_aggregate,
'dify_app_id': dify_app_id or None,
'dify_api_key': _strip(data.get('dify_api_key')) or None,
'api_base_url': _strip(data.get('api_base_url')) or None,
@@ -269,7 +284,7 @@ def apply_agent_payload(agent: Agent, normalized: dict[str, Any]) -> None:
normalized: validate_agent_payload 的返回值。
"""
column_fields = (
'name', 'description', 'icon_url', 'is_active', 'dify_app_id', 'api_base_url', 'type',
'name', 'description', 'icon_url', 'is_active', 'is_aggregate', 'dify_app_id', 'api_base_url', 'type',
'agent_code', 'runtime_provider', 'conversation_mode', 'dify_app_type', 'iframe_url',
'category', 'sub_category', 'sort_order', 'welcome_message', 'suggested_questions_style',
'suggested_questions', 'capabilities', 'file_upload_policy', 'bound_schedule_task_id',
@@ -53,6 +53,7 @@ def serialize_registry_fields(agent: Agent | Any) -> dict[str, Any]:
'category': getattr(agent, 'category', None) or None,
'sub_category': getattr(agent, 'sub_category', None) or None,
'sort_order': int(getattr(agent, 'sort_order', 0) or 0),
'is_aggregate': bool(getattr(agent, 'is_aggregate', False)),
'welcome_message': getattr(agent, 'welcome_message', None),
'suggested_questions_style': getattr(agent, 'suggested_questions_style', None) or 'plain',
'suggested_questions': getattr(agent, 'suggested_questions', None) or [],
@@ -69,6 +70,7 @@ def serialize_registry_fields(agent: Agent | Any) -> dict[str, Any]:
def serialize_agent_for_admin(agent: Agent) -> dict[str, Any]:
"""Agent ORM → 管理端列表/详情 JSON(含 dify_api_key 供编辑表单密码框回填)。"""
registry = serialize_registry_fields(agent)
from app.services.agent_directory import serialize_directory_members
return {
'id': agent.id,
'name': agent.name,
@@ -81,6 +83,7 @@ def serialize_agent_for_admin(agent: Agent) -> dict[str, Any]:
'dify_api_key_masked': mask_dify_api_key(agent.dify_api_key),
'api_base_url': agent.api_base_url,
'extra_config': agent.extra_config if isinstance(agent.extra_config, dict) else {},
'directory_members': serialize_directory_members(agent.id) if bool(getattr(agent, 'is_aggregate', False)) else [],
**registry,
}
@@ -112,6 +112,29 @@ def _resolve_domain_summary(agent) -> str:
return '通用对话'
def _resolve_directory_members(agent) -> list[dict[str, Any]]:
"""
Return active child Agent metadata configured for a directory Agent.
AI trigger timing: aggregate Dify Chatflows read these values to decide
which child knowledge apps should be searched for the current turn.
"""
if not bool(getattr(agent, 'is_aggregate', False)):
return []
raw_members = getattr(agent, 'directory_members', None)
if isinstance(raw_members, list):
return [item for item in raw_members if isinstance(item, dict)]
agent_id = getattr(agent, 'id', None)
if not agent_id:
return []
try:
from app.services.agent_directory import serialize_directory_members
return serialize_directory_members(int(agent_id), active_only=True)
except Exception:
return []
def build_generic_runtime_context(
*,
session_id: str,
@@ -137,6 +160,14 @@ def build_generic_runtime_context(
Returns:
通用 agent_runtime_context 字典;session_id 为空时返回空 dict。
"""
directory_members = _resolve_directory_members(agent)
domain: dict[str, Any] = {
'type': 'generic',
'summary': _resolve_domain_summary(agent),
}
if directory_members:
domain['directory_members'] = directory_members
return build_agent_runtime_context(
agent_code=resolve_agent_code(agent),
scope=scope,
@@ -144,10 +175,7 @@ def build_generic_runtime_context(
request_id=request_id,
trigger_source=trigger_source,
locale=locale,
domain={
'type': 'generic',
'summary': _resolve_domain_summary(agent),
},
domain=domain,
)
@@ -182,7 +210,15 @@ def build_generic_dify_inputs(
locale=locale,
scope=scope,
)
return build_dify_inputs(runtime_context)
inputs = build_dify_inputs(runtime_context)
directory_members = _resolve_directory_members(agent)
if directory_members:
inputs['directory_member_agents'] = directory_members
inputs['directory_member_agent_ids'] = [item['id'] for item in directory_members if item.get('id')]
inputs['directory_member_dify_app_ids'] = [
item['dify_app_id'] for item in directory_members if item.get('dify_app_id')
]
return inputs
@register_context_adapter('generic')
@@ -39,6 +39,7 @@ def build_dify_inputs_for_context(ctx: ChatStreamContext) -> dict[str, Any]:
request_id=ctx.request_id,
trigger_source='frontend_chat',
adapter_hints=ctx.adapter_hints,
user_role=getattr(ctx.user, 'role', None),
)
+3 -3
View File
@@ -123,11 +123,11 @@ class DifyService:
if "keyword is required" in lower or re.search(r"\bstatus code 400\b", lower):
return "没有识别到要查询的设备编号或设备名称,请补充完整设备信息后再试。"
if re.search(r"\b(401|403)\b", lower) or "unauthorized" in lower or "invalid_auth" in lower:
return "设备维保查询服务暂时无法访问,请稍后重试或联系管理员检查工具授权。"
return "服务暂时无法访问,请稍后重试或联系管理员检查工具授权。"
if "ssrf" in lower or "blocked" in lower or "private or local network" in lower:
return "设备维保查询服务暂时无法访问,请联系管理员检查工具网络访问配置。"
return "服务暂时无法访问,请联系管理员检查工具网络访问配置。"
if "failed to invoke tool" in lower or "tool" in lower:
return "设备维保查询工具调用失败,请稍后重试;如持续失败请联系管理员。"
return "工具调用失败,请稍后重试;如持续失败请联系管理员。"
if "maximum context length" in lower or "input_tokens" in lower:
return "当前会话上下文过长,模型无法继续回答。请新建对话后重新查询。"
return "设备维保助手暂时无法完成查询,请稍后重试。"
@@ -0,0 +1,41 @@
"""add agent directory members
Revision ID: ff6a7b8c9d0e
Revises: b9c0d1e2f3a4
Create Date: 2026-07-09 00:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = 'ff6a7b8c9d0e'
down_revision = 'b9c0d1e2f3a4'
branch_labels = None
depends_on = None
def upgrade():
op.add_column('agents', sa.Column('is_aggregate', sa.Boolean(), nullable=False, server_default=sa.false()))
op.alter_column('agents', 'is_aggregate', server_default=None)
op.create_table(
'agent_directory_members',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('directory_agent_id', sa.Integer(), nullable=False),
sa.Column('member_agent_id', sa.Integer(), nullable=False),
sa.Column('sort_order', sa.Integer(), nullable=False, server_default='0'),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['directory_agent_id'], ['agents.id'], ondelete='CASCADE'),
sa.ForeignKeyConstraint(['member_agent_id'], ['agents.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('directory_agent_id', 'member_agent_id', name='uq_agent_directory_member_pair'),
)
op.create_index('ix_agent_directory_members_directory_agent_id', 'agent_directory_members', ['directory_agent_id'])
op.create_index('ix_agent_directory_members_member_agent_id', 'agent_directory_members', ['member_agent_id'])
def downgrade():
op.drop_index('ix_agent_directory_members_member_agent_id', table_name='agent_directory_members')
op.drop_index('ix_agent_directory_members_directory_agent_id', table_name='agent_directory_members')
op.drop_table('agent_directory_members')
op.drop_column('agents', 'is_aggregate')
+14
View File
@@ -396,3 +396,17 @@
1. 管理员能成功上传并管理应用的指南文件。
2. 客户端正确根据配置动态展示或隐藏入口。
3. 客户端能正常播放指南视频和预览 PDF 文档。
# Agent 目录聚合配置需求
## 目标
- 管理员可创建一个可点击的目录型 Agent,例如“知识库问答”或“研发赋能知识库”。
- 管理员需先把应用配置为“聚合应用”,才可在后台以多列勾选方式选择多个已有应用作为成员,例如“研发专利”“材质证明文档”等;非聚合应用不展示成员选择。
- 用户点击目录型 Agent 后仍进入普通聊天页;该 Agent 负责面向其成员应用的知识库做聚合问答。
## 范围
- 本期目录关系由 HXOPS 管理后台维护,保存为目录 Agent 与成员 Agent 的显式关系。
- 聚合/非聚合由 `agents.is_aggregate` 显式配置,切回非聚合时清空成员关系。
- 目录 Agent 本身仍配置一套聚合 Dify Chatflow;HXOPS 在发起聊天时向 Dify inputs 注入成员 Agent 元数据。
- 本期不在 HXOPS 后端并行调用多个子 Agent,不合并多个 Dify 回答;多路召回与答案融合由聚合 Chatflow 承担。
+10
View File
@@ -490,3 +490,13 @@
#### F-13 指南预览弹窗 (Client)
- **目标**:用户在聊天界面快速查阅指南。
- **功能点**:视频使用 HTML5 播放器,PDF 使用 `@vue-office/pdf` 渲染,支持 Tabs 切换多份指南。
# Agent 目录聚合
| 功能项 | 状态 | 说明 |
| --- | --- | --- |
| 聚合/非聚合显式配置 | 已实现 | 管理后台 Agent 表单提供“非聚合应用 / 聚合应用”并排选择;只有聚合应用展示成员勾选。 |
| 目录型 Agent 成员配置 | 已实现 | 管理后台 Agent 表单支持选择多个已有应用作为目录成员,保存到 `agent_directory_members`。 |
| 目录 Agent 可点击问答 | 已实现 | 目录本身仍是普通 Agent,用户点击后进入聊天页并走现有 SSE 链路。 |
| 目录展开/折叠与子应用点击 | 已实现 | Chat 侧边栏/移动端 Agent 切换器将目录渲染为树形节点;目录可点击,展开后成员应用也可点击并进入各自 Dify 问答。 |
| 聚合 Chatflow 上下文注入 | 已实现 | 聊天时向 Dify inputs 注入成员应用 ID、名称、Dify App ID 与分类等元数据。 |
| 多子 Agent 并行召回与答案融合 | 未纳入本期 | 当前由目录 Agent 对应的 Dify Chatflow 基于注入元数据完成聚合问答。 |
+30
View File
@@ -1048,3 +1048,33 @@ Dify
- 维修记录接口:`/api/maintenance/records`,支持查询详情、分页查询和新增。
- 前端新增 `features/maintenance` 业务域,包含台账 API、维修记录 API、类型定义和右侧固定面板组件。
- 聊天页仅当当前 Agent 名称为 `设备维保助手` 时显示底部管理按钮;查询继续走会话,配置类操作进入右侧固定面板。
# Agent 目录聚合技术方案
## 数据模型
- 新增 `agent_directory_members` 表,字段包含 `directory_agent_id`、`member_agent_id`、`sort_order`。
- 目录本身仍复用 `agents` 表;新增 `agents.is_aggregate` 显式标记聚合/非聚合,不新增独立应用类型。
## 运行时链路
1. 管理端保存 Agent 时提交 `is_aggregate`;仅当为 `true` 时提交并保留 `directory_member_ids`。
2. 后端写入目录成员关系,并在管理端列表返回 `directory_members`;切回非聚合时清空成员关系。
3. 用户点击目录 Agent 后沿用 `/api/chat/completions` SSE 链路。
4. `build_chat_dify_inputs` 为目录 Agent 注入:
- `directory_member_agents`
- `directory_member_agent_ids`
- `directory_member_dify_app_ids`
- `agent_runtime_context.domain.directory_members`
## 前端展示
- Agent 切换列表优先按目录成员关系渲染为树形节点。
- 目录 Agent 本身可点击,进入目录对应的聚合 Chatflow。
- 目录右侧提供展开/折叠按钮,展开后展示成员 Agent。
- 成员 Agent 仍按自身 `agent_id` 跳转,进入成员自己的 Dify 后端问答。
- 已作为目录成员出现的 Agent 不再在同一列表中重复作为普通节点展示。
## 边界
- 聚合问答由目录 Agent 自己的 Dify Chatflow 实现。
- HXOPS 当前只负责配置、权限、会话与上下文注入,不直接编排多个子 Agent 的回答。
@@ -76,7 +76,7 @@ const {
const tableHeaderColumns = computed(() => [
{ key: 'name', label: t('admin.agent.headers.name'), align: 'left' as const },
{ key: 'type', label: t('admin.agent.headers.type'), align: 'left' as const },
{ key: 'category', label: t('admin.agent.headers.category'), align: 'left' as const },
{ key: 'aggregation', label: t('admin.agent.headers.aggregation'), align: 'left' as const },
{ key: 'config', label: t('admin.agent.headers.config'), align: 'left' as const },
{ key: 'status', label: t('admin.agent.headers.status'), align: 'left' as const },
{ key: 'actions', label: t('admin.agent.headers.actions'), align: 'right' as const },
@@ -84,16 +84,14 @@ const tableHeaderColumns = computed(() => [
const formatAgentCode = (agent: AgentRow) => agent.agent_code || 'generic';
/** 分类主行:一级分类 */
const formatAgentCategoryPrimary = (agent: AgentRow) => {
const category = String(agent.category || '').trim();
return category || '—';
};
const formatAgentAggregationPrimary = (agent: AgentRow) => (
agent.is_aggregate ? t('admin.agent.directory.aggregateMode') : t('admin.agent.directory.normalMode')
);
/** 分类副行:二级分类 */
const formatAgentCategorySecondary = (agent: AgentRow) => {
const subCategory = String(agent.sub_category || '').trim();
return subCategory || '—';
const formatAgentAggregationSecondary = (agent: AgentRow) => {
const memberCount = Number(agent.directory_member_count || agent.directory_members?.length || 0);
if (agent.is_aggregate) return t('admin.agent.directory.memberCount', { count: memberCount });
return t('admin.agent.directory.normalListHint');
};
/** 配置列主行:Dify App ID 或 Iframe URL 摘要。 */
@@ -251,11 +249,15 @@ onMounted(() => {
</td>
<td class="px-4 py-4 align-middle">
<div class="agent-list-cell">
<p class="truncate text-sm text-secondary" :title="formatAgentCategoryPrimary(agent)">
{{ formatAgentCategoryPrimary(agent) }}
<p
class="truncate text-sm font-medium"
:class="agent.is_aggregate ? 'text-brand-700' : 'text-secondary'"
:title="formatAgentAggregationPrimary(agent)"
>
{{ formatAgentAggregationPrimary(agent) }}
</p>
<p class="truncate text-xs text-muted" :title="formatAgentCategorySecondary(agent)">
{{ formatAgentCategorySecondary(agent) }}
<p class="truncate text-xs text-muted" :title="formatAgentAggregationSecondary(agent)">
{{ formatAgentAggregationSecondary(agent) }}
</p>
</div>
</td>
@@ -348,6 +350,7 @@ onMounted(() => {
:content-profile-options="contentProfileOptions"
:runtime-providers="runtimeProviders"
:conversation-modes="conversationModes"
:agent-options="agents"
:sync-content-profile-from-intent-routes="syncContentProfileFromIntentRoutes"
@close="showFormDialog = false"
@save="saveAgentForm"
@@ -8,9 +8,9 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { ChevronDown, FileDown, Plus, Search, Trash2, X } from 'lucide-vue-next';
import { ChevronDown, FileDown, FolderTree, Plus, Search, Trash2, X } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
import type { AgentFormState, AgentGuideSummary } from '@/features/admin/types/agent.types';
import type { AgentFormState, AgentGuideSummary, AgentRow } from '@/features/admin/types/agent.types';
import type { ScheduleTask } from '@/shared/types/schedule.types';
import type { AgentTypeCatalogEntry, IntentRouteOption } from '../composables/useAgentsAdminRegistry';
import type { AdminContentProfileOption } from '@/features/admin/api/admin.api';
@@ -38,6 +38,7 @@ const props = defineProps<{
contentProfileOptions: AdminContentProfileOption[];
runtimeProviders: string[];
conversationModes: string[];
agentOptions: AgentRow[];
syncContentProfileFromIntentRoutes: (form: AgentFormState) => Promise<void>;
}>();
@@ -57,6 +58,7 @@ const { t } = useI18n();
const optionLabels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
const advancedOpen = ref(false);
const intentRouteSearch = ref('');
const directoryMemberSearch = ref('');
const showDifyFields = computed(() => props.form.runtime_provider === 'dify' || props.form.runtime_provider === 'hybrid');
const showIframeFields = computed(() => props.form.runtime_provider === 'iframe');
@@ -99,6 +101,49 @@ const filteredIntentRouteOptions = computed(() => {
));
});
const directoryMemberOptions = computed(() => {
const currentId = Number(props.form.id || 0);
const keyword = directoryMemberSearch.value.trim().toLowerCase();
return props.agentOptions
.filter((agent) => Number(agent.id) !== currentId)
.filter((agent) => {
if (!keyword) return true;
return [
agent.name,
agent.description,
agent.category,
agent.sub_category,
agent.agent_code,
].some((value) => String(value || '').toLowerCase().includes(keyword));
});
});
const selectedDirectoryMembers = computed(() => (
props.form.directory_member_ids
.map((id) => props.agentOptions.find((agent) => agent.id === id))
.filter(Boolean) as AgentRow[]
));
const setAggregateMode = (enabled: boolean) => {
props.form.is_aggregate = enabled;
if (!enabled) {
props.form.directory_member_ids = [];
directoryMemberSearch.value = '';
}
};
const toggleDirectoryMember = (agentId: number, checked: boolean) => {
const current = new Set(props.form.directory_member_ids);
if (checked) {
current.add(agentId);
} else {
current.delete(agentId);
}
props.form.directory_member_ids = props.agentOptions
.map((agent) => agent.id)
.filter((id) => current.has(id) && id !== props.form.id);
};
/**
* 切换 intent_route 勾选状态。
*/
@@ -153,6 +198,16 @@ watch(
},
);
watch(
() => props.form.is_aggregate,
(enabled) => {
if (!enabled) {
props.form.directory_member_ids = [];
directoryMemberSearch.value = '';
}
},
);
/**
* 用户切换应用类型时应用 Catalog 默认值。
*/
@@ -297,38 +352,86 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =
</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 class="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
<div>
<div class="flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-muted">
<FolderTree class="h-4 w-4" />
{{ t('admin.agent.directory.title') }}
</div>
<p class="mt-1 text-sm leading-6 text-secondary">{{ t('admin.agent.directory.subtitle') }}</p>
</div>
<span class="rounded-full bg-white px-3 py-1 text-xs font-medium text-secondary">
{{ t('admin.agent.directory.selectedCount', { count: selectedDirectoryMembers.length }) }}
</span>
</div>
<div class="mt-4 grid grid-cols-1 gap-3 md:grid-cols-2">
<button
type="button"
class="rounded-xl border px-4 py-3 text-left transition"
:class="!form.is_aggregate ? 'border-brand-500 bg-brand-50 text-brand-700' : 'border-default bg-white text-secondary hover:bg-surface-soft'"
@click="setAggregateMode(false)"
>
<span class="block text-sm font-semibold">{{ t('admin.agent.directory.normalMode') }}</span>
<span class="mt-1 block text-xs leading-5">{{ t('admin.agent.directory.normalModeHint') }}</span>
</button>
<button
type="button"
class="rounded-xl border px-4 py-3 text-left transition"
:class="form.is_aggregate ? 'border-brand-500 bg-brand-50 text-brand-700' : 'border-default bg-white text-secondary hover:bg-surface-soft'"
@click="setAggregateMode(true)"
>
<span class="block text-sm font-semibold">{{ t('admin.agent.directory.aggregateMode') }}</span>
<span class="mt-1 block text-xs leading-5">{{ t('admin.agent.directory.aggregateModeHint') }}</span>
</button>
</div>
<template v-if="form.is_aggregate">
<div class="mt-4 flex items-center gap-2 rounded-xl border border-default bg-white px-3 py-2">
<Search class="h-4 w-4 text-muted" />
<input
v-model="directoryMemberSearch"
type="search"
class="w-full bg-transparent text-sm outline-none"
:placeholder="t('admin.agent.directory.searchPlaceholder')"
/>
</div>
<div v-if="selectedDirectoryMembers.length" class="mt-3 flex flex-wrap gap-2">
<span
v-for="member in selectedDirectoryMembers"
:key="member.id"
class="inline-flex items-center gap-1 rounded-full bg-white px-2.5 py-1 text-xs text-secondary"
>
{{ member.name }}
<button type="button" @click="toggleDirectoryMember(member.id, false)">
<X class="h-3 w-3" />
</button>
</span>
</div>
<div class="mt-3 max-h-64 overflow-y-auto rounded-xl border border-default bg-white p-3">
<div v-if="directoryMemberOptions.length === 0" class="px-3 py-4 text-center text-sm text-muted">
{{ t('admin.agent.directory.emptyOptions') }}
</div>
<div v-else class="grid grid-cols-1 gap-2 sm:grid-cols-2 lg:grid-cols-3">
<label
v-for="agent in directoryMemberOptions"
:key="agent.id"
class="flex cursor-pointer items-center gap-2.5 rounded-lg border border-default px-3 py-2 text-sm hover:bg-surface-soft"
:class="form.directory_member_ids.includes(agent.id) ? 'border-brand-400 bg-brand-50' : 'bg-white'"
>
<input
type="checkbox"
class="shrink-0 accent-brand-600"
:checked="form.directory_member_ids.includes(agent.id)"
@change="toggleDirectoryMember(agent.id, ($event.target as HTMLInputElement).checked)"
/>
<span class="min-w-0 truncate font-medium text-primary">{{ agent.name }}</span>
</label>
</div>
</div>
</template>
</div>
<div
@@ -408,6 +408,7 @@ export function mapAgentRowToForm(
welcome_message: String(agent.welcome_message || ''),
is_active: agent.is_active,
is_aggregate: agent.is_aggregate === true,
category: String(agent.category || ''),
@@ -440,6 +441,9 @@ export function mapAgentRowToForm(
tool_run_progress_enabled: agent.capabilities?.task_progress === true,
schedule_task_id: agent.bound_schedule_task_id ?? null,
directory_member_ids: Array.isArray(agent.directory_members)
? agent.directory_members.map((item) => Number(item.id)).filter((id) => Number.isInteger(id) && id > 0)
: [],
};
@@ -518,6 +522,7 @@ export function buildAgentRegistryPayload(
description: form.description,
is_active: form.is_active,
is_aggregate: form.is_aggregate,
type: legacyType,
@@ -569,6 +574,7 @@ export function buildAgentRegistryPayload(
handler_config,
extra_config,
directory_member_ids: form.is_aggregate ? [...form.directory_member_ids] : [],
};
@@ -25,6 +25,7 @@ export interface AgentRow {
dify_api_key?: string;
dify_api_key_masked?: string;
is_active: boolean;
is_aggregate?: boolean;
description?: string;
type: 'api' | 'iframe';
agent_code?: string;
@@ -43,6 +44,18 @@ export interface AgentRow {
bound_schedule_task_id?: number | null;
handler_config?: Record<string, unknown> | null;
extra_config?: Record<string, unknown>;
directory_members?: AgentDirectoryMember[];
directory_member_count?: number;
}
export interface AgentDirectoryMember {
id: number;
name: string;
description?: string | null;
agent_code?: string | null;
dify_app_id?: string | null;
category?: string | null;
sub_category?: string | null;
}
export interface AgentSuggestedQuestionItem {
@@ -94,6 +107,7 @@ export interface AgentFormState {
suggested_questions_style: 'plain' | 'styled';
suggested_questions: AgentSuggestedQuestionItem[];
is_active: boolean;
is_aggregate: boolean;
category: string;
sub_category: string;
sort_order: number;
@@ -110,6 +124,7 @@ export interface AgentFormState {
training_summary_points_text: string;
training_summary_checklist_text: string;
training_question_bank: AgentTrainingQuestionFormItem[];
directory_member_ids: number[];
}
export const createEmptyTrainingQuestionForm = (): AgentTrainingQuestionFormItem => ({
@@ -139,6 +154,7 @@ export const createEmptyAgentForm = (
suggested_questions_style: 'plain',
suggested_questions: [],
is_active: true,
is_aggregate: false,
category: '',
sub_category: '',
sort_order: 0,
@@ -164,4 +180,5 @@ export const createEmptyAgentForm = (
training_summary_points_text: '',
training_summary_checklist_text: '',
training_question_bank: [],
directory_member_ids: [],
});
@@ -70,6 +70,16 @@ export function useChatAgent(options: UseChatAgentOptions) {
category?: string | null;
sub_category?: string | null;
sort_order?: number;
is_aggregate?: boolean;
directory_members?: Array<AgentRegistryFields & {
id: number;
name: string;
description?: string | null;
icon_url?: string;
category?: string | null;
sub_category?: string | null;
sort_order?: number;
}>;
}>>([]);
const showAgentPanel = ref(true);
const selectedKb = ref(DEFAULT_KB);
@@ -32,6 +32,8 @@ export interface WorkspaceAgent {
category?: string | null;
sub_category?: string | null;
sort_order?: number;
is_aggregate?: boolean;
directory_members?: WorkspaceAgent[];
}
export interface WorkspaceQuickQuestion {
+16 -2
View File
@@ -156,7 +156,8 @@
"category": "Category",
"config": "Configuration",
"status": "Status",
"actions": "Actions"
"actions": "Actions",
"aggregation": "Aggregation"
},
"fields": {
"name": "Name",
@@ -321,6 +322,20 @@
"questionSingleOptions": "Question {index} needs at least 2 valid options",
"questionAnswerRequired": "Please choose the correct answer for question {index}"
}
},
"directory": {
"title": "App aggregation",
"subtitle": "Set the Q&A scope for this app. A standard app uses only its own capabilities; an aggregate app acts as a directory entry and includes selected child apps in knowledge-base Q&A.",
"normalMode": "Standard app",
"normalModeHint": "Use only this app's own capabilities without child apps.",
"aggregateMode": "Aggregate app",
"aggregateModeHint": "Act as an expandable directory entry and include selected child apps in aggregate Q&A.",
"selectedCount": "{count} child apps selected",
"searchPlaceholder": "Search apps to include...",
"emptyOptions": "No apps available",
"uncategorized": "Uncategorized",
"memberCount": "{count} child apps",
"normalListHint": "This app only"
}
},
"question": {
@@ -794,7 +809,6 @@
"api_base_url": "API Base URL",
"agent_id": "Agent ID",
"agent_name": "Agent Name",
"real_name": "Real Name",
"conversation_id": "Conversation ID",
"attribution_parts": "Attribution Parts",
"session_id": "Session ID",
+16 -1
View File
@@ -156,7 +156,8 @@
"category": "หมวดหมู่",
"config": "การกำหนดค่า",
"status": "สถานะ",
"actions": "การกระทำ"
"actions": "การกระทำ",
"aggregation": "การรวมแอป"
},
"fields": {
"name": "ชื่อ",
@@ -321,6 +322,20 @@
"questionSingleOptions": "ข้อ {index} ต้องมีตัวเลือกที่ใช้ได้อย่างน้อย 2 ตัวเลือก",
"questionAnswerRequired": "กรุณาเลือกคำตอบที่ถูกต้องของข้อ {index}"
}
},
"directory": {
"title": "การตั้งค่าการรวมแอป",
"subtitle": "ตั้งค่าขอบเขตการถามตอบของแอปนี้ แอปทั่วไปใช้เฉพาะความสามารถของตัวเอง ส่วนแอปรวมจะเป็นรายการไดเรกทอรีและนำแอปลูกที่เลือกมาใช้ในถามตอบฐานความรู้",
"normalMode": "แอปทั่วไป",
"normalModeHint": "ใช้เฉพาะความสามารถของแอปนี้ โดยไม่เชื่อมโยงแอปลูก",
"aggregateMode": "แอปรวม",
"aggregateModeHint": "เป็นรายการไดเรกทอรีที่ขยายได้ และเลือกแอปลูกหลายรายการสำหรับถามตอบแบบรวม",
"selectedCount": "เลือกแอปลูกแล้ว {count} รายการ",
"searchPlaceholder": "ค้นหาแอปที่จะรวม...",
"emptyOptions": "ไม่มีแอปให้เลือก",
"uncategorized": "ไม่จัดหมวดหมู่",
"memberCount": "แอปลูก {count} รายการ",
"normalListHint": "เฉพาะแอปนี้"
}
},
"question": {
+16 -2
View File
@@ -157,7 +157,8 @@
"category": "分类",
"config": "配置",
"status": "状态",
"actions": "操作"
"actions": "操作",
"aggregation": "聚合配置"
},
"fields": {
"name": "名称",
@@ -322,6 +323,20 @@
"questionSingleOptions": "第 {index} 题至少需要 2 个有效选项",
"questionAnswerRequired": "第 {index} 题请选择正确答案"
}
},
"directory": {
"title": "应用聚合配置",
"subtitle": "设置当前应用的问答范围。普通应用只使用自身能力;聚合应用可作为目录入口,并把勾选的子应用纳入知识库问答范围。",
"normalMode": "普通应用",
"normalModeHint": "仅使用当前应用自身能力,不关联子应用。",
"aggregateMode": "聚合应用",
"aggregateModeHint": "作为可展开的目录入口,可勾选多个子应用参与聚合问答。",
"selectedCount": "已选子应用 {count} 个",
"searchPlaceholder": "搜索可归入目录的应用...",
"emptyOptions": "暂无可选择应用",
"uncategorized": "未分类",
"memberCount": "子应用 {count} 个",
"normalListHint": "仅当前应用"
}
},
"question": {
@@ -795,7 +810,6 @@
"api_base_url": "API 基础 URL",
"agent_id": "应用 ID",
"agent_name": "应用名称",
"real_name": "真实姓名",
"conversation_id": "会话 ID",
"attribution_parts": "归因片段",
"session_id": "会话 ID",
+16 -2
View File
@@ -156,7 +156,8 @@
"category": "分類",
"config": "配置",
"status": "狀態",
"actions": "操作"
"actions": "操作",
"aggregation": "聚合設定"
},
"fields": {
"name": "名稱",
@@ -321,6 +322,20 @@
"questionSingleOptions": "第 {index} 題至少需要 2 個有效選項",
"questionAnswerRequired": "第 {index} 題請選擇正確答案"
}
},
"directory": {
"title": "應用聚合設定",
"subtitle": "設定目前應用的問答範圍。普通應用只使用自身能力;聚合應用可作為目錄入口,並把勾選的子應用納入知識庫問答範圍。",
"normalMode": "普通應用",
"normalModeHint": "僅使用目前應用自身能力,不關聯子應用。",
"aggregateMode": "聚合應用",
"aggregateModeHint": "作為可展開的目錄入口,可勾選多個子應用參與聚合問答。",
"selectedCount": "已選子應用 {count} 個",
"searchPlaceholder": "搜尋可歸入目錄的應用...",
"emptyOptions": "暫無可選擇應用",
"uncategorized": "未分類",
"memberCount": "子應用 {count} 個",
"normalListHint": "僅目前應用"
}
},
"question": {
@@ -799,7 +814,6 @@
"api_base_url": "API 基礎 URL",
"agent_id": "應用 ID",
"agent_name": "應用名稱",
"real_name": "真實姓名",
"conversation_id": "會話 ID",
"attribution_parts": "歸因片段",
"session_id": "會話 ID",
@@ -1,16 +1,16 @@
/**
* shared/components/AgentCategoryList.vue
* 用途:按一级/二级分类展示可切换的 Agent 列表,支持搜索与折叠分组。
* 依赖:agent-category.utils、vue-i18n。
* 依赖:agent-category.utils、vue-i18n、lucide-vue-next。
* 逻辑: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 { ChevronDown, ChevronRight, FolderTree, Search } from 'lucide-vue-next';
import {
filterAgentsByQuery,
groupAgentsByCategory,
sortAgentsByCategory,
type AgentWithCategory,
} from '@/shared/utils/agent-category.utils';
@@ -33,121 +33,261 @@ const emit = defineEmits<{
const { t } = useI18n();
const searchQuery = ref('');
const collapsedCategories = ref<Set<string>>(new Set());
const collapsedDirectories = ref<Set<number>>(new Set());
const uncategorizedLabel = computed(() => t('chat.agentCategory.uncategorized'));
const directoryMemberIds = computed(() => {
const ids = new Set<number>();
for (const agent of props.agents) {
for (const member of agent.directory_members || []) {
ids.add(member.id);
}
}
return ids;
});
const filteredAgents = computed(() => filterAgentsByQuery(props.agents, searchQuery.value));
const categoryGroups = computed(() =>
groupAgentsByCategory(filteredAgents.value, uncategorizedLabel.value),
/**
* 判断是否为聚合目录 Agent(含 directory_members 或显式 is_aggregate)。
*/
const isAggregateAgent = (agent: AgentWithCategory) => (
agent.is_aggregate === true || (agent.directory_members || []).length > 0
);
/**
* 同步分类折叠态:新增分类默认展开,移除已不存在的折叠记录。
* 搜索时同时匹配目录自身与其成员名称/分类。
*/
const syncCollapsedState = () => {
const keys = new Set(categoryGroups.value.map((group) => group.category));
const next = new Set<string>();
for (const key of collapsedCategories.value) {
const matchesQuery = (agent: AgentWithCategory, query: string) => {
if (!query.trim()) return true;
return filterAgentsByQuery([agent], query).length > 0
|| (agent.directory_members || []).some((member) => filterAgentsByQuery([member], query).length > 0);
};
const filteredAgents = computed(() => {
const q = searchQuery.value.trim();
return props.agents.filter((agent) => {
if (directoryMemberIds.value.has(agent.id)) return false;
return matchesQuery(agent, q);
});
});
const aggregateAgents = computed(() => (
sortAgentsByCategory(filteredAgents.value.filter((agent) => isAggregateAgent(agent)))
));
const standardAgents = computed(() => (
sortAgentsByCategory(filteredAgents.value.filter((agent) => !isAggregateAgent(agent)))
));
const visibleAgentsCount = computed(() => aggregateAgents.value.length + standardAgents.value.length);
/**
* 同步折叠态:清理已消失目录,并在 defaultExpanded=false 时默认收起。
*/
const syncCollapsedDirectories = () => {
const keys = new Set(aggregateAgents.value.map((agent) => agent.id));
const next = new Set<number>();
for (const key of collapsedDirectories.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);
for (const agent of aggregateAgents.value) {
if (!next.has(agent.id)) next.add(agent.id);
}
}
collapsedCategories.value = next;
collapsedDirectories.value = next;
};
watch(categoryGroups, syncCollapsedState, { immediate: true });
watch(aggregateAgents, syncCollapsedDirectories, { immediate: true });
const toggleCategory = (category: string) => {
const next = new Set(collapsedCategories.value);
if (next.has(category)) {
next.delete(category);
/**
* 切换指定聚合目录的展开/折叠。
*/
const toggleDirectory = (agentId: number) => {
const next = new Set(collapsedDirectories.value);
if (next.has(agentId)) {
next.delete(agentId);
} else {
next.add(category);
next.add(agentId);
}
collapsedCategories.value = next;
collapsedDirectories.value = next;
};
const isCategoryCollapsed = (category: string) => collapsedCategories.value.has(category);
const isDirectoryCollapsed = (agentId: number) => collapsedDirectories.value.has(agentId);
const isActiveAgent = (agent: AgentWithCategory) => agent.id === props.activeAgentId;
/**
* 按当前搜索词过滤目录成员;目录名命中时展示全部成员。
*/
const visibleDirectoryMembers = (agent: AgentWithCategory) => {
const q = searchQuery.value.trim();
const members = agent.directory_members || [];
if (!q || filterAgentsByQuery([agent], q).length > 0) return members;
return members.filter((member) => filterAgentsByQuery([member], q).length > 0);
};
/**
* 选中 Agent;已激活则忽略,避免重复切换。
*/
const onSelect = (agent: AgentWithCategory) => {
if (isActiveAgent(agent)) return;
emit('select', agent);
};
/**
* 统一 Agent 行的激活/默认样式类。
* @param active - 是否为当前选中项
* @param dense - 是否为目录成员等更紧凑的行
*/
const agentRowClass = (active: boolean, dense = false) => {
const base = dense
? 'group relative flex w-full min-w-0 items-center gap-2 rounded-lg px-2 py-1.5 text-left text-[11px] font-medium transition-all duration-150'
: 'group relative flex w-full min-w-0 items-center gap-2 rounded-xl px-2.5 py-2 text-left text-xs font-medium transition-all duration-150';
if (active) {
return `${base} cursor-default bg-brand-50 text-brand-700 shadow-sm ring-1 ring-brand-100/80 dark:bg-brand-900/25 dark:text-brand-300 dark:ring-brand-800/40`;
}
return `${base} text-secondary hover:bg-surface hover:text-primary hover:shadow-sm`;
};
</script>
<template>
<div class="space-y-2">
<div class="space-y-2.5">
<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" />
<Search class="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted/80" />
<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"
class="w-full rounded-xl border border-subtle bg-surface py-2 pl-8 pr-2.5 text-xs text-primary shadow-sm placeholder:text-muted/70 transition-shadow focus:border-brand-300 focus:outline-none focus:ring-2 focus:ring-brand-400/25"
:placeholder="t('chat.agentCategory.searchPlaceholder')"
/>
</div>
<div v-if="categoryGroups.length === 0" class="py-2 text-center text-xs text-muted">
<div v-if="visibleAgentsCount === 0" class="rounded-xl bg-surface-soft/50 py-4 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)"
<div v-else class="max-h-72 space-y-2.5 overflow-y-auto pr-0.5 scrollbar-thin">
<!-- 聚合目录 -->
<div v-if="aggregateAgents.length" class="space-y-2">
<div
v-for="agent in aggregateAgents"
:key="agent.id"
class="overflow-hidden rounded-2xl border border-subtle bg-surface shadow-sm"
>
<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"
<div class="flex min-w-0 items-stretch">
<button
type="button"
class="flex w-7 shrink-0 items-center justify-center text-muted transition-colors hover:bg-surface-soft hover:text-brand-600"
:title="isDirectoryCollapsed(agent.id) ? t('chat.expandAgents') : t('chat.collapseAgents')"
@click.stop="toggleDirectory(agent.id)"
>
{{ 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 transition-colors"
<ChevronRight
v-if="isDirectoryCollapsed(agent.id)"
class="h-3 w-3 transition-transform"
/>
<ChevronDown v-else class="h-3 w-3" />
</button>
<button
type="button"
class="flex min-w-0 flex-1 items-center gap-1.5 py-1.5 pr-2.5 text-left transition-colors"
:class="isActiveAgent(agent)
? 'cursor-default bg-brand-50/80'
: 'hover:bg-surface-soft/80'"
:aria-current="isActiveAgent(agent) ? 'page' : undefined"
@click="onSelect(agent)"
>
<span
class="flex h-5 w-5 shrink-0 items-center justify-center rounded-md"
:class="isActiveAgent(agent)
? 'cursor-default bg-brand-50 text-brand-700 shadow-sm ring-1 ring-brand-100 dark:bg-brand-900/20 dark:text-brand-300 dark:ring-brand-800/50'
: 'text-secondary hover-surface-soft hover:shadow-sm'"
:aria-current="isActiveAgent(agent) ? 'page' : undefined"
@click="onSelect(agent)"
? 'bg-brand-100 text-brand-600 dark:bg-brand-900/40 dark:text-brand-300'
: 'bg-surface-strong text-brand-500'"
>
<FolderTree class="h-3 w-3" />
</span>
<span
class="min-w-0 truncate text-xs font-semibold tracking-tight"
:class="isActiveAgent(agent) ? 'text-brand-700 dark:text-brand-300' : 'text-primary'"
>
{{ agent.name }}
</span>
<span
v-if="visibleDirectoryMembers(agent).length"
class="ml-auto shrink-0 rounded px-1 py-px text-[10px] font-medium tabular-nums text-muted"
>
{{ visibleDirectoryMembers(agent).length }}
</span>
</button>
</div>
<div
v-show="!isDirectoryCollapsed(agent.id)"
class="border-t border-subtle bg-surface-soft/40 px-2 py-2"
>
<div class="grid grid-cols-2 gap-1">
<button
v-for="member in visibleDirectoryMembers(agent)"
:key="`${agent.id}-${member.id}`"
type="button"
:class="agentRowClass(isActiveAgent(member), true)"
:title="member.name"
:aria-current="isActiveAgent(member) ? 'page' : undefined"
@click="onSelect(member)"
>
<span
v-if="isActiveAgent(member)"
class="absolute inset-y-1 left-0 w-0.5 rounded-full bg-brand-500"
/>
<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})` }"
v-if="member.icon_url"
class="h-5 w-5 shrink-0 rounded-md bg-contain bg-center bg-no-repeat ring-1 ring-black/5"
:style="{ backgroundImage: `url(${member.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"
class="flex h-5 w-5 shrink-0 items-center justify-center rounded-md bg-brand-50 text-[10px] font-bold text-brand-600 ring-1 ring-brand-100/60 dark:bg-brand-900/30 dark:text-brand-300 dark:ring-brand-800/40"
>
{{ agent.name.charAt(0) }}
{{ member.name.charAt(0) }}
</div>
<span class="min-w-0 truncate">{{ agent.name }}</span>
<span class="min-w-0 truncate leading-tight">{{ member.name }}</span>
</button>
</div>
</template>
</div>
</div>
</section>
</div>
<!-- 普通智能体 -->
<div
v-if="standardAgents.length"
:class="[
aggregateAgents.length ? 'border-t border-subtle/80 pt-2.5' : '',
compact ? 'grid grid-cols-2 gap-1' : 'grid grid-cols-2 gap-1.5',
]"
>
<button
v-for="agent in standardAgents"
:key="agent.id"
type="button"
:class="agentRowClass(isActiveAgent(agent))"
:title="agent.name"
:aria-current="isActiveAgent(agent) ? 'page' : undefined"
@click="onSelect(agent)"
>
<span
v-if="isActiveAgent(agent)"
class="absolute inset-y-1.5 left-0 w-0.5 rounded-full bg-brand-500"
/>
<div
v-if="agent.icon_url"
class="h-5 w-5 shrink-0 rounded-md bg-contain bg-center bg-no-repeat ring-1 ring-black/5"
:style="{ backgroundImage: `url(${agent.icon_url})` }"
/>
<div
v-else
class="flex h-5 w-5 shrink-0 items-center justify-center rounded-md bg-brand-50 text-[10px] font-bold text-brand-600 ring-1 ring-brand-100/60 dark:bg-brand-900/30 dark:text-brand-300 dark:ring-brand-800/40"
>
{{ agent.name.charAt(0) }}
</div>
<span class="min-w-0 truncate leading-tight">{{ agent.name }}</span>
</button>
</div>
</div>
</div>
</template>
+2 -2
View File
@@ -783,8 +783,8 @@
}
.chat-agent-panel {
@apply mb-4 rounded-2xl border border-default p-3;
background-color: color-mix(in srgb, var(--bg-surface-soft) 85%, transparent);
@apply mb-4 rounded-2xl border border-subtle p-3 shadow-sm;
background-color: color-mix(in srgb, var(--bg-surface) 92%, var(--bg-surface-soft));
}
.chat-agent-panel--collapsed {
@@ -15,7 +15,18 @@ export interface AgentWithCategory extends AgentCategoryFields {
id: number;
name: string;
icon_url?: string;
description?: string;
description?: string | null;
is_aggregate?: boolean;
directory_members?: AgentDirectoryMemberRef[];
}
export interface AgentDirectoryMemberRef extends AgentCategoryFields {
id: number;
name: string;
icon_url?: string;
description?: string | null;
agent_code?: string | null;
dify_app_id?: string | null;
}
export interface AgentCategorySubGroup<T extends AgentWithCategory = AgentWithCategory> {