Merge branch 'dev' into hugo-shipping-notice

This commit is contained in:
hugo committed 2026-07-09 14:46:30 +08:00
commit c778f40fbc
35 files changed
+996 -164

No files matched your search

@@ -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,12 +8,16 @@
<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';
import {
DEFAULT_TRAINING_EMPLOYEE_CHAT_QUESTIONS,
DEFAULT_TRAINING_HR_CHAT_QUESTIONS,
} from '@/features/chat/training/trainingChatQuestions';
import {
applyCatalogDefaultsToForm,
applyContentProfileTemplate,
@@ -38,6 +42,7 @@ const props = defineProps<{
contentProfileOptions: AdminContentProfileOption[];
runtimeProviders: string[];
conversationModes: string[];
agentOptions: AgentRow[];
syncContentProfileFromIntentRoutes: (form: AgentFormState) => Promise<void>;
}>();
@@ -57,6 +62,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 +105,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 勾选状态。
*/
@@ -138,6 +187,12 @@ const applySelectedContentProfileTemplate = (force = false) => {
const handleTrainingWorkspaceToggle = () => {
if (props.form.training_workspace_enabled) {
props.form.content_profile = 'training';
if (!props.form.training_employee_chat_questions_text.trim()) {
props.form.training_employee_chat_questions_text = DEFAULT_TRAINING_EMPLOYEE_CHAT_QUESTIONS.join('\n');
}
if (!props.form.training_hr_chat_questions_text.trim()) {
props.form.training_hr_chat_questions_text = DEFAULT_TRAINING_HR_CHAT_QUESTIONS.join('\n');
}
} else if (props.form.content_profile === 'training') {
props.form.content_profile = '';
}
@@ -153,6 +208,16 @@ watch(
},
);
watch(
() => props.form.is_aggregate,
(enabled) => {
if (!enabled) {
props.form.directory_member_ids = [];
directoryMemberSearch.value = '';
}
},
);
/**
* 用户切换应用类型时应用 Catalog 默认值。
*/
@@ -297,38 +362,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
@@ -565,6 +678,29 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =
</div>
</div>
<div class="mt-4 grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="space-y-2">
<label class="text-xs font-semibold text-secondary">{{ t('admin.agent.training.employeeChatQuestions') }}</label>
<textarea
v-model="form.training_employee_chat_questions_text"
rows="6"
class="w-full input-field text-sm"
:placeholder="t('admin.agent.training.employeeChatQuestionsPlaceholder')"
/>
<p class="text-xs leading-5 text-muted">{{ t('admin.agent.training.employeeChatQuestionsHint') }}</p>
</div>
<div class="space-y-2">
<label class="text-xs font-semibold text-secondary">{{ t('admin.agent.training.hrChatQuestions') }}</label>
<textarea
v-model="form.training_hr_chat_questions_text"
rows="6"
class="w-full input-field text-sm"
:placeholder="t('admin.agent.training.hrChatQuestionsPlaceholder')"
/>
<p class="text-xs leading-5 text-muted">{{ t('admin.agent.training.hrChatQuestionsHint') }}</p>
</div>
</div>
<div class="mt-5 space-y-3">
<div class="flex flex-wrap items-center justify-between gap-3">
<div>
@@ -24,6 +24,9 @@ import {
} from '@/features/admin/api/admin.api';
import { listAdminSchedules } from '@/features/admin/api/schedule.api';
import { useMessage } from '@/shared/composables/useMessage';
import {
resolveTrainingRoleChatQuestions,
} from '@/features/chat/training/trainingChatQuestions';
import type { AdminUserRow } from '@/features/admin/types/admin.types';
import type {
AgentFormState,
@@ -115,21 +118,30 @@ const parseTrainingConfigFromExtra = (extra: Record<string, unknown> | undefined
const hasTrainingContent = questionBank.length > 0
|| Boolean(toMultilineText(merged.summary_points ?? merged.summaryPoints))
|| Boolean(toMultilineText(merged.summary_checklist ?? merged.summaryChecklist));
const workspaceEnabled =
extra?.training_workspace_enabled === true
|| extra?.training_workspace_enabled === 'true'
|| extra?.training_mode === true
|| extra?.training_mode === 'true'
|| extra?.training_agent === true
|| extra?.training_agent === 'true'
|| hasTrainingContent;
const employeeQuestions = resolveTrainingRoleChatQuestions(extra, 'employee');
const hrQuestions = resolveTrainingRoleChatQuestions(extra, 'hr');
return {
training_workspace_enabled:
extra?.training_workspace_enabled === true
|| extra?.training_workspace_enabled === 'true'
|| extra?.training_mode === true
|| extra?.training_mode === 'true'
|| extra?.training_agent === true
|| extra?.training_agent === 'true'
|| hasTrainingContent,
training_workspace_enabled: workspaceEnabled,
training_pass_score: Number.isFinite(Number(merged.pass_score ?? merged.passScore))
? Math.max(0, Math.min(100, Math.round(Number(merged.pass_score ?? merged.passScore))))
: 90,
training_summary_points_text: toMultilineText(merged.summary_points ?? merged.summaryPoints),
training_summary_checklist_text: toMultilineText(merged.summary_checklist ?? merged.summaryChecklist),
training_employee_chat_questions_text: employeeQuestions.configured || workspaceEnabled
? toMultilineText(employeeQuestions.questions)
: '',
training_hr_chat_questions_text: hrQuestions.configured || workspaceEnabled
? toMultilineText(hrQuestions.questions)
: '',
training_question_bank: questionBank,
};
};
@@ -170,6 +182,8 @@ const hasTrainingConfigContent = (form: AgentFormState) => (
form.training_workspace_enabled
|| Boolean(form.training_summary_points_text.trim())
|| Boolean(form.training_summary_checklist_text.trim())
|| Boolean(form.training_employee_chat_questions_text.trim())
|| Boolean(form.training_hr_chat_questions_text.trim())
|| form.training_question_bank.length > 0
);
@@ -461,6 +475,8 @@ export function useAgentsAdmin() {
pass_score: Math.max(0, Math.min(100, Math.round(Number(form.value.training_pass_score) || 90))),
summary_points: splitMultilineText(form.value.training_summary_points_text),
summary_checklist: splitMultilineText(form.value.training_summary_checklist_text),
employee_chat_suggested_questions: splitMultilineText(form.value.training_employee_chat_questions_text),
hr_chat_suggested_questions: splitMultilineText(form.value.training_hr_chat_questions_text),
question_bank: form.value.training_question_bank.map((question, index) => buildTrainingQuestionPayload(question, index)),
};
} else {
@@ -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;
@@ -109,7 +123,10 @@ export interface AgentFormState {
training_pass_score: number;
training_summary_points_text: string;
training_summary_checklist_text: string;
training_employee_chat_questions_text: string;
training_hr_chat_questions_text: string;
training_question_bank: AgentTrainingQuestionFormItem[];
directory_member_ids: number[];
}
export const createEmptyTrainingQuestionForm = (): AgentTrainingQuestionFormItem => ({
@@ -139,6 +156,7 @@ export const createEmptyAgentForm = (
suggested_questions_style: 'plain',
suggested_questions: [],
is_active: true,
is_aggregate: false,
category: '',
sub_category: '',
sort_order: 0,
@@ -163,5 +181,8 @@ export const createEmptyAgentForm = (
training_pass_score: 90,
training_summary_points_text: '',
training_summary_checklist_text: '',
training_employee_chat_questions_text: '',
training_hr_chat_questions_text: '',
training_question_bank: [],
directory_member_ids: [],
});
@@ -26,6 +26,7 @@ const {
suggestedQuestionsStyle: 'plain' | 'styled';
styledSections: WelcomeQuestionSection[];
suggestedQuestions: WelcomeQuestionItem[];
hideWelcomeTitle?: boolean;
showThinkingBubble: boolean;
isThinking: boolean;
showChatRating: boolean;
@@ -104,6 +105,7 @@ const isLatestAssistantMessage = (items: ChatMessage[], index: number) => {
:suggested-questions-style="suggestedQuestionsStyle"
:styled-sections="styledSections"
:suggested-questions="suggestedQuestions"
:hide-title="hideWelcomeTitle"
@select-question="emit('select-question', $event)"
/>
@@ -45,7 +45,8 @@ const embeddedIframeSrc = computed(() => {
return url ? String(url) : undefined;
});
const canManageMaintenance = computed(() => ['admin', 'maintenance_manager'].includes(String(page.currentUser?.role || '')));
const hideWelcomePanel = computed(() => isTrainingAgentPage.value);
const hideWelcomePanel = computed(() => false);
const hideWelcomeTitle = computed(() => isTrainingAgentPage.value);
const isTrainingWorkspaceExpanded = ref(false);
const maintenancePanel = ref<'ledger' | 'record' | null>(null);
const maintenanceEditRecord = ref<MaintenanceRecord | null>(null);
@@ -243,6 +244,7 @@ watch(() => page.currentAgentId, () => {
:tool-run-progress-title="page.toolRunProgressTitle"
:show-scroll-to-bottom="page.showScrollToBottom"
:hide-welcome-panel="hideWelcomePanel"
:hide-welcome-title="hideWelcomeTitle"
:pin-messages-to-bottom="!isTrainingAgentPage"
:scroll-container-holder="page.scrollContainerHolder"
@copy="page.copyToClipboard($event.message, $event.index)"
@@ -23,6 +23,7 @@ const props = defineProps<{
suggestedQuestionsStyle: 'plain' | 'styled';
styledSections: WelcomeQuestionSection[];
suggestedQuestions: WelcomeQuestionItem[];
hideTitle?: boolean;
}>();
const emit = defineEmits<{
@@ -32,18 +33,19 @@ const emit = defineEmits<{
const { t } = useI18n();
const displayAgentName = computed(() => props.agentName || t('chat.assistantLabel'));
const shouldShowTitle = computed(() => !props.hideTitle);
</script>
<template>
<div class="flex h-full min-h-0 w-full flex-col items-center px-4 pb-2 pt-2 md:pb-3">
<template v-if="suggestedQuestionsStyle === 'styled' && styledSections.length > 0">
<h2 class="mb-8 mt-12 shrink-0 text-center text-2xl font-bold text-primary md:mt-16 md:text-3xl">
<h2 v-if="shouldShowTitle" class="mb-8 mt-12 shrink-0 text-center text-2xl font-bold text-primary md:mt-16 md:text-3xl">
<span>{{ $t('chat.welcomeAgentTitlePrefix') }}</span>
<span class="mx-1 text-brand-600">{{ displayAgentName }}</span>
<span>{{ $t('chat.welcomeAgentTitleSuffix') }}</span>
</h2>
<div class="min-h-0 w-full flex-1 overflow-y-auto pb-2">
<div class="min-h-0 w-full flex-1 overflow-y-auto pb-2" :class="shouldShowTitle ? '' : 'pt-4 md:pt-8'">
<div class="mx-auto grid w-full max-w-4xl grid-cols-1 gap-4 md:grid-cols-2">
<div
v-for="(section, sectionIndex) in styledSections"
@@ -74,13 +76,13 @@ const displayAgentName = computed(() => props.agentName || t('chat.assistantLabe
</template>
<template v-else-if="suggestedQuestions.length > 0">
<h2 class="mb-8 mt-12 shrink-0 text-center text-2xl font-bold text-primary md:mt-16 md:text-3xl">
<h2 v-if="shouldShowTitle" class="mb-8 mt-12 shrink-0 text-center text-2xl font-bold text-primary md:mt-16 md:text-3xl">
<span>{{ $t('chat.welcomeAgentTitlePrefix') }}</span>
<span class="mx-1 text-brand-600">{{ displayAgentName }}</span>
<span>{{ $t('chat.welcomeAgentTitleSuffix') }}</span>
</h2>
<div class="min-h-0 w-full flex-1 overflow-y-auto pb-2">
<div class="min-h-0 w-full flex-1 overflow-y-auto pb-2" :class="shouldShowTitle ? '' : 'pt-6 md:pt-10'">
<div class="mx-auto mt-2 flex w-full max-w-3xl flex-wrap justify-center gap-3">
<button
v-for="(item, index) in suggestedQuestions"
@@ -96,7 +98,7 @@ const displayAgentName = computed(() => props.agentName || t('chat.assistantLabe
</template>
<template v-else>
<h2 class="mt-12 text-center text-2xl font-bold text-primary md:mt-16 md:text-3xl">
<h2 v-if="shouldShowTitle" class="mt-12 text-center text-2xl font-bold text-primary md:mt-16 md:text-3xl">
<span>{{ $t('chat.welcomeAgentTitlePrefix') }}</span>
<span class="mx-1 text-brand-600">{{ displayAgentName }}</span>
<span>{{ $t('chat.welcomeAgentTitleSuffix') }}</span>
@@ -3,7 +3,7 @@
* features/chat/components/TrainingWorkspacePanel.vue
* 用途:在培训 Agent 的聊天页顶部提供“员工培训 + 培训管理”一体化工作区。
* 依赖:useTrainingWorkspace、lucide 图标、聊天页 currentAgent/currentUser。
* 逻辑:只在培训 Agent 下渲染;员工角色默认直达展开工作区,管理角色保留问答视图,培训答题不再走聊天链路。
* 逻辑:只在培训 Agent 下渲染;普通员工首次进入默认展开工作区,但新建/切换会话后保持收起,避免聊天过程中被自动展开打断。
*/
import { computed, reactive, ref, watch, type ShallowUnwrapRef } from 'vue';
import { useI18n } from 'vue-i18n';
@@ -123,7 +123,8 @@ watch(
() => props.newSessionTick,
(tick, prevTick) => {
if (!tick || tick === prevTick) return;
userExpandedOverride.value = null;
// [STEP 1] 新建对话或切换会话后统一收起工作区,避免聊天中因视图重建被自动展开。
userExpandedOverride.value = false;
applyDefaultExpandedState();
},
);
@@ -12,6 +12,7 @@ import {
type AgentRegistryFields,
} from '@/shared/utils/agent-registry.utils';
import { matchesTrainingAgent } from '../training/trainingWorkspace.utils';
import { resolveTrainingRoleChatQuestions } from '../training/trainingChatQuestions';
import type { ChatDeps } from './chat.deps';
import type { UseChatGuidesReturn } from './useChatGuides';
@@ -26,13 +27,6 @@ const ERP_KB = 'ERP知识库';
const TRAINING_AGENT_DESCRIPTION =
'我是你的新人培训助手,会在同一个聊天页面内带你完成视频学习、知识点复盘、逐题考试和结果复盘。';
const TRAINING_AGENT_QUESTIONS: AgentSuggestedQuestionItem[] = [
{ question: '这次员工培训主要学习什么内容?', group: '培训问答' },
{ question: '员工培训的通过规则是什么?', group: '培训问答' },
{ question: '这次培训的试题范围有哪些?', group: '培训问答' },
{ question: '培训记录会如何统计?', group: '培训问答' },
];
const normalizeAgentSuggestedQuestions = (value: unknown): AgentSuggestedQuestionItem[] => {
if (!Array.isArray(value)) return [];
return value
@@ -53,11 +47,12 @@ const normalizeAgentSuggestedQuestions = (value: unknown): AgentSuggestedQuestio
export interface UseChatAgentOptions {
deps: ChatDeps;
currentAgentId: ComputedRef<number>;
currentUser: ComputedRef<Record<string, unknown> | null>;
chatGuides: Pick<UseChatGuidesReturn, 'loadGuides' | 'clearGuides'>;
}
export function useChatAgent(options: UseChatAgentOptions) {
const { deps, currentAgentId, chatGuides } = options;
const { deps, currentAgentId, currentUser, chatGuides } = options;
const { t, msg, router } = deps;
const currentAgent = ref<AgentRegistryFields | null>(null);
@@ -70,6 +65,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);
@@ -88,6 +93,10 @@ export function useChatAgent(options: UseChatAgentOptions) {
: kbOptions.filter((option) => option !== ERP_KB)
));
const kbDropdownDisabled = computed(() => availableKbOptions.value.length <= 1);
const isTrainingAdminViewer = computed(() => Boolean(
(currentUser.value as { feature_permissions?: { training_hr_manage?: boolean } } | null)
?.feature_permissions?.training_hr_manage,
));
watch(canSelectErpKnowledgeBase, (allowed) => {
if (allowed) {
@@ -119,8 +128,18 @@ export function useChatAgent(options: UseChatAgentOptions) {
const configured = normalizeAgentSuggestedQuestions(
currentAgent.value?.suggested_questions,
);
if (matchesTrainingAgent(currentAgent.value)) {
const roleQuestions = resolveTrainingRoleChatQuestions(
currentAgent.value?.extra_config,
isTrainingAdminViewer.value ? 'hr' : 'employee',
);
if (roleQuestions.configured) {
return roleQuestions.questions.map((question) => ({ question, group: '' }));
}
if (configured.length > 0) return configured;
return roleQuestions.questions.map((question) => ({ question, group: '' }));
}
if (configured.length > 0) return configured;
if (matchesTrainingAgent(currentAgent.value)) return TRAINING_AGENT_QUESTIONS;
return [];
});
@@ -149,7 +149,7 @@ export function useChatPage() {
};
const chatGuides = useChatGuides({ currentAgentId });
const agent = useChatAgent({ deps, currentAgentId, chatGuides });
const agent = useChatAgent({ deps, currentAgentId, currentUser: computed(() => currentUser.value), chatGuides });
const attachmentApi = useChatAttachments({
deps,
currentAgentId,
@@ -0,0 +1,79 @@
/**
* features/chat/training/trainingChatQuestions.ts
* 用途:统一维护员工培训 Agent 的员工版 / HR 版聊天常见问题默认值与解析逻辑。
* 依赖:被 Admin 后台培训配置表单与 Chat 欢迎区共同引用,避免默认问题与字段名出现多份散落副本。
* 逻辑:优先读取 extra_config.training_config 中的角色化问题列表;未配置时回退到内置示例,显式保存空数组时尊重为空。
*/
export type TrainingChatQuestionRole = 'employee' | 'hr';
const TRAINING_ROLE_QUESTION_KEYS: Record<TrainingChatQuestionRole, string[]> = {
employee: ['employee_chat_suggested_questions', 'learner_chat_suggested_questions'],
hr: ['hr_chat_suggested_questions', 'admin_chat_suggested_questions'],
};
export const DEFAULT_TRAINING_EMPLOYEE_CHAT_QUESTIONS = [
'这次员工培训主要学习什么内容?',
'完成培训需要经过哪些步骤?',
'员工培训的通过规则是什么?',
'开始考试前需要注意什么?',
];
export const DEFAULT_TRAINING_HR_CHAT_QUESTIONS = [
'现在有多少人参加了培训?',
'当前培训通过率是多少?',
'哪些员工还没有完成培训?',
'我想查看本月培训成绩统计',
];
const asRecord = (value: unknown): Record<string, unknown> => (
value && typeof value === 'object' && !Array.isArray(value)
? value as Record<string, unknown>
: {}
);
const cloneQuestions = (questions: string[]) => questions.map((item) => String(item || '').trim()).filter(Boolean);
/**
* 归一化后台保存的常见问题数组。
* AI 触发时机:培训配置允许 string[] 与 { question }[] 混存时,需要统一还原成纯文本列表供表单和聊天欢迎区复用。
*/
const normalizeTrainingChatQuestionList = (value: unknown): string[] => {
if (!Array.isArray(value)) return [];
return value
.map((item) => {
if (typeof item === 'string') return item.trim();
if (!item || typeof item !== 'object') return '';
return String((item as Record<string, unknown>).question || (item as Record<string, unknown>).text || '').trim();
})
.filter(Boolean);
};
const getDefaultQuestions = (role: TrainingChatQuestionRole) => (
role === 'hr'
? cloneQuestions(DEFAULT_TRAINING_HR_CHAT_QUESTIONS)
: cloneQuestions(DEFAULT_TRAINING_EMPLOYEE_CHAT_QUESTIONS)
);
/**
* 读取培训配置中的角色化聊天常见问题。
* AI 触发时机:员工培训 Agent 需要按当前用户角色切换欢迎区问题时,必须先判断后台是否显式配置该角色问题,再决定是否回退默认示例。
*/
export const resolveTrainingRoleChatQuestions = (
extraConfig: unknown,
role: TrainingChatQuestionRole,
): { configured: boolean; questions: string[] } => {
const trainingConfig = asRecord(asRecord(extraConfig).training_config);
const keys = TRAINING_ROLE_QUESTION_KEYS[role];
const matchedKey = keys.find((key) => Object.prototype.hasOwnProperty.call(trainingConfig, key));
if (!matchedKey) {
return {
configured: false,
questions: getDefaultQuestions(role),
};
}
return {
configured: true,
questions: normalizeTrainingChatQuestionList(trainingConfig[matchedKey]),
};
};
@@ -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 {
+22 -2
View File
@@ -156,7 +156,8 @@
"category": "Category",
"config": "Configuration",
"status": "Status",
"actions": "Actions"
"actions": "Actions",
"aggregation": "Aggregation"
},
"fields": {
"name": "Name",
@@ -282,6 +283,12 @@
"summaryPointsPlaceholder": "One item per line, for example: Salary is paid on the 15th of each month",
"summaryChecklist": "Must know before the exam",
"summaryChecklistPlaceholder": "One item per line, for example: Scores below 90 require a retake",
"employeeChatQuestions": "Employee chat questions",
"employeeChatQuestionsPlaceholder": "One question per line, for example: What are the passing rules for this training?",
"employeeChatQuestionsHint": "When a normal employee opens the employee training chat page, these questions are shown first.",
"hrChatQuestions": "HR chat questions",
"hrChatQuestionsPlaceholder": "One question per line, for example: Which employees have not completed the training yet?",
"hrChatQuestionsHint": "When a user with training management permission opens the employee training chat page, these questions are shown first.",
"questionBank": "Question bank",
"questionHint": "Supports single choice and true or false questions. Employees will use the updated bank immediately after saving.",
"emptyQuestionBank": "No question bank configured yet. The employee view will fall back to the default bank.",
@@ -321,6 +328,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 +815,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",
+22 -1
View File
@@ -156,7 +156,8 @@
"category": "หมวดหมู่",
"config": "การกำหนดค่า",
"status": "สถานะ",
"actions": "การกระทำ"
"actions": "การกระทำ",
"aggregation": "การรวมแอป"
},
"fields": {
"name": "ชื่อ",
@@ -282,6 +283,12 @@
"summaryPointsPlaceholder": "หนึ่งบรรทัดต่อหนึ่งข้อ เช่น เงินเดือนจ่ายทุกวันที่ 15",
"summaryChecklist": "สิ่งที่ต้องรู้ก่อนสอบ",
"summaryChecklistPlaceholder": "หนึ่งบรรทัดต่อหนึ่งข้อ เช่น คะแนนต่ำกว่า 90 ต้องสอบใหม่",
"employeeChatQuestions": "คำถามแนะนำสำหรับพนักงาน",
"employeeChatQuestionsPlaceholder": "หนึ่งคำถามต่อหนึ่งบรรทัด เช่น เกณฑ์ผ่านของการอบรมนี้คืออะไร?",
"employeeChatQuestionsHint": "เมื่อพนักงานทั่วไปเปิดหน้าแชตการอบรมพนักงาน ระบบจะแสดงคำถามชุดนี้ก่อน",
"hrChatQuestions": "คำถามแนะนำสำหรับ HR",
"hrChatQuestionsPlaceholder": "หนึ่งคำถามต่อหนึ่งบรรทัด เช่น ยังมีพนักงานคนใดที่ยังไม่จบการอบรมบ้าง?",
"hrChatQuestionsHint": "เมื่อผู้ใช้ที่มีสิทธิ์จัดการอบรมเปิดหน้าแชตการอบรมพนักงาน ระบบจะแสดงคำถามชุดนี้ก่อน",
"questionBank": "คลังข้อสอบ",
"questionHint": "รองรับข้อสอบแบบปรนัยและถูกหรือผิด หลังบันทึกแล้วพนักงานจะใช้ชุดข้อสอบใหม่นี้ทันที",
"emptyQuestionBank": "ยังไม่ได้ตั้งค่าคลังข้อสอบ ฝั่งพนักงานจะใช้คลังข้อสอบเริ่มต้นแทน",
@@ -321,6 +328,20 @@
"questionSingleOptions": "ข้อ {index} ต้องมีตัวเลือกที่ใช้ได้อย่างน้อย 2 ตัวเลือก",
"questionAnswerRequired": "กรุณาเลือกคำตอบที่ถูกต้องของข้อ {index}"
}
},
"directory": {
"title": "การตั้งค่าการรวมแอป",
"subtitle": "ตั้งค่าขอบเขตการถามตอบของแอปนี้ แอปทั่วไปใช้เฉพาะความสามารถของตัวเอง ส่วนแอปรวมจะเป็นรายการไดเรกทอรีและนำแอปลูกที่เลือกมาใช้ในถามตอบฐานความรู้",
"normalMode": "แอปทั่วไป",
"normalModeHint": "ใช้เฉพาะความสามารถของแอปนี้ โดยไม่เชื่อมโยงแอปลูก",
"aggregateMode": "แอปรวม",
"aggregateModeHint": "เป็นรายการไดเรกทอรีที่ขยายได้ และเลือกแอปลูกหลายรายการสำหรับถามตอบแบบรวม",
"selectedCount": "เลือกแอปลูกแล้ว {count} รายการ",
"searchPlaceholder": "ค้นหาแอปที่จะรวม...",
"emptyOptions": "ไม่มีแอปให้เลือก",
"uncategorized": "ไม่จัดหมวดหมู่",
"memberCount": "แอปลูก {count} รายการ",
"normalListHint": "เฉพาะแอปนี้"
}
},
"question": {
+22 -2
View File
@@ -157,7 +157,8 @@
"category": "分类",
"config": "配置",
"status": "状态",
"actions": "操作"
"actions": "操作",
"aggregation": "聚合配置"
},
"fields": {
"name": "名称",
@@ -283,6 +284,12 @@
"summaryPointsPlaceholder": "每行一条,例如:工资每月 15 号发放",
"summaryChecklist": "考前必知",
"summaryChecklistPlaceholder": "每行一条,例如:低于 90 分必须重新考试",
"employeeChatQuestions": "员工聊天常见问题",
"employeeChatQuestionsPlaceholder": "每行一个问题,例如:员工培训的通过规则是什么?",
"employeeChatQuestionsHint": "普通员工进入员工培训聊天页时,会优先看到这里配置的常见问题。",
"hrChatQuestions": "HR聊天常见问题",
"hrChatQuestionsPlaceholder": "每行一个问题,例如:哪些员工还没有完成培训?",
"hrChatQuestionsHint": "拥有培训管理权限的 HR 进入员工培训聊天页时,会优先看到这里配置的常见问题。",
"questionBank": "题库",
"questionHint": "支持单选题和判断题;保存后员工考试会即时使用新的题库。",
"emptyQuestionBank": "暂未配置题库,员工端会回退到默认题库。",
@@ -322,6 +329,20 @@
"questionSingleOptions": "第 {index} 题至少需要 2 个有效选项",
"questionAnswerRequired": "第 {index} 题请选择正确答案"
}
},
"directory": {
"title": "应用聚合配置",
"subtitle": "设置当前应用的问答范围。普通应用只使用自身能力;聚合应用可作为目录入口,并把勾选的子应用纳入知识库问答范围。",
"normalMode": "普通应用",
"normalModeHint": "仅使用当前应用自身能力,不关联子应用。",
"aggregateMode": "聚合应用",
"aggregateModeHint": "作为可展开的目录入口,可勾选多个子应用参与聚合问答。",
"selectedCount": "已选子应用 {count} 个",
"searchPlaceholder": "搜索可归入目录的应用...",
"emptyOptions": "暂无可选择应用",
"uncategorized": "未分类",
"memberCount": "子应用 {count} 个",
"normalListHint": "仅当前应用"
}
},
"question": {
@@ -795,7 +816,6 @@
"api_base_url": "API 基础 URL",
"agent_id": "应用 ID",
"agent_name": "应用名称",
"real_name": "真实姓名",
"conversation_id": "会话 ID",
"attribution_parts": "归因片段",
"session_id": "会话 ID",
+22 -2
View File
@@ -156,7 +156,8 @@
"category": "分類",
"config": "配置",
"status": "狀態",
"actions": "操作"
"actions": "操作",
"aggregation": "聚合設定"
},
"fields": {
"name": "名稱",
@@ -282,6 +283,12 @@
"summaryPointsPlaceholder": "每行一條,例如:工資每月 15 號發放",
"summaryChecklist": "考前必知",
"summaryChecklistPlaceholder": "每行一條,例如:低於 90 分必須重新考試",
"employeeChatQuestions": "員工聊天常見問題",
"employeeChatQuestionsPlaceholder": "每行一個問題,例如:員工培訓的通過規則是什麼?",
"employeeChatQuestionsHint": "普通員工進入員工培訓聊天頁時,會優先看到這裡配置的常見問題。",
"hrChatQuestions": "HR聊天常見問題",
"hrChatQuestionsPlaceholder": "每行一個問題,例如:哪些員工還沒有完成培訓?",
"hrChatQuestionsHint": "擁有培訓管理權限的 HR 進入員工培訓聊天頁時,會優先看到這裡配置的常見問題。",
"questionBank": "題庫",
"questionHint": "支援單選題和判斷題;保存後員工考試會即時使用新的題庫。",
"emptyQuestionBank": "暫未配置題庫,員工端會回退到預設題庫。",
@@ -321,6 +328,20 @@
"questionSingleOptions": "第 {index} 題至少需要 2 個有效選項",
"questionAnswerRequired": "第 {index} 題請選擇正確答案"
}
},
"directory": {
"title": "應用聚合設定",
"subtitle": "設定目前應用的問答範圍。普通應用只使用自身能力;聚合應用可作為目錄入口,並把勾選的子應用納入知識庫問答範圍。",
"normalMode": "普通應用",
"normalModeHint": "僅使用目前應用自身能力,不關聯子應用。",
"aggregateMode": "聚合應用",
"aggregateModeHint": "作為可展開的目錄入口,可勾選多個子應用參與聚合問答。",
"selectedCount": "已選子應用 {count} 個",
"searchPlaceholder": "搜尋可歸入目錄的應用...",
"emptyOptions": "暫無可選擇應用",
"uncategorized": "未分類",
"memberCount": "子應用 {count} 個",
"normalListHint": "僅目前應用"
}
},
"question": {
@@ -799,7 +820,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> {