feat(agent): 增强 Agent 配置,新增结构化字段与聊天功能支持
This commit is contained in:
1 parent
ac4262cd75
commit
c8ce77199e
183 files changed
+11690
-2300
No files matched your search
@@ -3,11 +3,10 @@
|
||||
*
|
||||
* 用途:管理控制台的应用管理页,提供应用列表、创建/编辑弹窗、测试与授权入口。
|
||||
* 依赖:useAgentsAdmin 业务编排、AgentFormModal/AgentTestModal/AgentPermissionModal 弹窗。
|
||||
* 逻辑:页面加载后拉取应用/用户/排程数据;主区域展示应用列表,新增和编辑通过弹窗表单完成。
|
||||
* 逻辑:页面加载后拉取应用/用户/排程数据;列表支持表头列宽拖拽并 localStorage 持久化。
|
||||
*/
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue';
|
||||
import { computed, ref, onMounted } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { Bot, Plus, SquarePen, Trash2, Users } from 'lucide-vue-next';
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
@@ -15,19 +14,19 @@ import AgentFormModal from './components/AgentFormModal.vue';
|
||||
import AgentPermissionModal from './components/AgentPermissionModal.vue';
|
||||
import AgentTestModal from './components/AgentTestModal.vue';
|
||||
import { useAgentsAdmin } from './composables/useAgentsAdmin';
|
||||
|
||||
const formatAgentCategory = (agent: { extra_config?: Record<string, unknown> }) => {
|
||||
const extra = agent.extra_config && typeof agent.extra_config === 'object' ? agent.extra_config : {};
|
||||
const category = String(extra.category || '').trim();
|
||||
const subCategory = String(extra.sub_category || '').trim();
|
||||
if (category && subCategory) return `${category} / ${subCategory}`;
|
||||
return category || subCategory || '—';
|
||||
};
|
||||
import { useAgentsTableColumnResize } from './composables/useAgentsTableColumnResize';
|
||||
import type { AgentRow } from '@/features/admin/types/agent.types';
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const {
|
||||
agents,
|
||||
typeCatalog,
|
||||
runtimeProviders,
|
||||
conversationModes,
|
||||
syncContentProfileFromIntentRoutes,
|
||||
intentRouteOptions,
|
||||
contentProfileOptions,
|
||||
scheduleTasks,
|
||||
trainingExamPdfGuides,
|
||||
activeUsers,
|
||||
@@ -67,6 +66,74 @@ const {
|
||||
confirmDelete,
|
||||
} = useAgentsAdmin();
|
||||
|
||||
const {
|
||||
columnWidths,
|
||||
tableMinWidth,
|
||||
startColumnResize,
|
||||
resetColumnWidths,
|
||||
} = useAgentsTableColumnResize();
|
||||
|
||||
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: '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 },
|
||||
]);
|
||||
|
||||
const formatAgentCode = (agent: AgentRow) => agent.agent_code || 'generic';
|
||||
|
||||
/** 分类主行:一级分类 */
|
||||
const formatAgentCategoryPrimary = (agent: AgentRow) => {
|
||||
const category = String(agent.category || '').trim();
|
||||
return category || '—';
|
||||
};
|
||||
|
||||
/** 分类副行:二级分类 */
|
||||
const formatAgentCategorySecondary = (agent: AgentRow) => {
|
||||
const subCategory = String(agent.sub_category || '').trim();
|
||||
return subCategory || '—';
|
||||
};
|
||||
|
||||
/** 配置列主行:Dify App ID 或 Iframe URL 摘要。 */
|
||||
const formatAgentConfigPrimary = (agent: AgentRow) => {
|
||||
if (agent.runtime_provider === 'iframe' || agent.type === 'iframe') {
|
||||
const url = String(agent.iframe_url || '').trim();
|
||||
return url || '—';
|
||||
}
|
||||
const appId = String(agent.dify_app_id || '').trim();
|
||||
return appId || '—';
|
||||
};
|
||||
|
||||
/** 配置列副行:配置类型说明。 */
|
||||
const formatAgentConfigSecondary = (agent: AgentRow) => {
|
||||
if (agent.runtime_provider === 'iframe' || agent.type === 'iframe') {
|
||||
return t('admin.agent.fields.types.iframe');
|
||||
}
|
||||
const appType = agent.dify_app_type === 'workflow' ? 'Workflow' : 'Chatflow';
|
||||
return `${t('admin.agent.fields.types.api')} · ${appType}`;
|
||||
};
|
||||
|
||||
/**
|
||||
* 列表「类型」列主文案:优先 Catalog 中文 label,否则 agent_code。
|
||||
*/
|
||||
const formatAgentTypeLabel = (agent: AgentRow) => {
|
||||
const code = formatAgentCode(agent);
|
||||
const entry = typeCatalog.value.find((item) => item.agent_code === code);
|
||||
return entry?.label || code;
|
||||
};
|
||||
|
||||
/**
|
||||
* 列表「类型」列副文案:runtime_provider 四语言展示。
|
||||
*/
|
||||
const formatRuntimeProviderLabel = (agent: AgentRow) => {
|
||||
const provider = agent.runtime_provider || (agent.type === 'iframe' ? 'iframe' : 'dify');
|
||||
const key = `admin.agent.fields.runtimeProviders.${provider}`;
|
||||
const translated = t(key);
|
||||
return translated === key ? provider : translated;
|
||||
};
|
||||
|
||||
const showFormDialog = ref(false);
|
||||
|
||||
/**
|
||||
@@ -124,23 +191,36 @@ onMounted(() => {
|
||||
<Bot class="w-12 h-12 mx-auto text-muted mb-3" />
|
||||
<p class="text-lg text-secondary">{{ t('admin.agent.noAgents') }}</p>
|
||||
</div>
|
||||
<table v-else class="admin-table table-fixed w-full">
|
||||
<table
|
||||
v-else
|
||||
class="admin-table agent-list-table table-fixed w-full"
|
||||
:style="{ minWidth: `${tableMinWidth}px` }"
|
||||
>
|
||||
<colgroup>
|
||||
<col class="w-64" />
|
||||
<col class="w-[4.5rem]" />
|
||||
<col class="w-36" />
|
||||
<col class="w-32" />
|
||||
<col class="w-[5.5rem]" />
|
||||
<col />
|
||||
<col
|
||||
v-for="(width, index) in columnWidths"
|
||||
:key="`col-${index}`"
|
||||
:style="{ width: `${width}px` }"
|
||||
/>
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="px-4 py-4 text-sm">{{ t('admin.agent.headers.name') }}</th>
|
||||
<th class="px-2 py-4 text-sm">{{ t('admin.agent.headers.type') }}</th>
|
||||
<th class="px-2 py-4 text-sm">{{ t('admin.agent.headers.category') }}</th>
|
||||
<th class="px-2 py-4 text-sm">{{ t('admin.agent.headers.config') }}</th>
|
||||
<th class="px-2 py-4 text-sm">{{ t('admin.agent.headers.status') }}</th>
|
||||
<th class="px-4 py-4 text-sm text-right">{{ t('admin.agent.headers.actions') }}</th>
|
||||
<th
|
||||
v-for="(column, index) in tableHeaderColumns"
|
||||
:key="column.key"
|
||||
class="relative px-4 py-3 text-xs"
|
||||
:class="column.align === 'right' ? 'text-right' : 'text-left'"
|
||||
>
|
||||
<span class="truncate pr-2">{{ column.label }}</span>
|
||||
<button
|
||||
v-if="index < tableHeaderColumns.length - 1"
|
||||
type="button"
|
||||
class="agent-col-resize-handle"
|
||||
:title="t('admin.agent.resizeColumn')"
|
||||
@mousedown.prevent="startColumnResize(index, $event)"
|
||||
@dblclick.prevent="resetColumnWidths"
|
||||
/>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -151,36 +231,59 @@ onMounted(() => {
|
||||
:class="{ 'bg-blue-50/50': selectedAgentId === agent.id }"
|
||||
@click="openEditDialog(agent)"
|
||||
>
|
||||
<td class="px-4 py-5 max-w-72">
|
||||
<div class="font-bold text-primary text-base truncate" :title="agent.name">{{ agent.name }}</div>
|
||||
<div class="section-desc mt-1 truncate" :title="agent.description">{{ agent.description }}</div>
|
||||
<td class="px-4 py-4 align-middle">
|
||||
<div class="agent-list-cell">
|
||||
<p class="truncate text-sm font-semibold text-primary" :title="agent.name">{{ agent.name }}</p>
|
||||
<p class="truncate text-xs text-muted" :title="agent.description || ''">
|
||||
{{ agent.description || '—' }}
|
||||
</p>
|
||||
</div>
|
||||
</td>
|
||||
<td class="px-2 py-5 whitespace-nowrap">
|
||||
<span class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium bg-surface-soft text-primary uppercase tracking-wide">
|
||||
{{ agent.type }}
|
||||
</span>
|
||||
<td class="px-4 py-4 align-middle">
|
||||
<div class="agent-list-cell">
|
||||
<p class="truncate text-sm text-primary" :title="formatAgentTypeLabel(agent)">
|
||||
{{ formatAgentTypeLabel(agent) }}
|
||||
</p>
|
||||
<p class="truncate text-xs text-muted" :title="formatRuntimeProviderLabel(agent)">
|
||||
{{ formatRuntimeProviderLabel(agent) }}
|
||||
</p>
|
||||
</div>
|
||||
</td>
|
||||
<td class="px-2 py-5 text-xs text-secondary max-w-36 truncate" :title="formatAgentCategory(agent)">
|
||||
{{ formatAgentCategory(agent) }}
|
||||
<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>
|
||||
<p class="truncate text-xs text-muted" :title="formatAgentCategorySecondary(agent)">
|
||||
{{ formatAgentCategorySecondary(agent) }}
|
||||
</p>
|
||||
</div>
|
||||
</td>
|
||||
<td class="px-2 py-5 font-mono text-xs text-muted max-w-32 truncate">
|
||||
<span v-if="agent.type === 'api'" class="truncate" :title="String(agent.dify_app_id)">
|
||||
<span class="text-muted">{{ t('admin.agent.idLabel') }}:</span> {{ agent.dify_app_id }}
|
||||
</span>
|
||||
<span v-else class="truncate block" :title="String(agent.extra_config?.iframe_url || '')">
|
||||
<span class="text-muted">{{ t('admin.agent.urlLabel') }}:</span> {{ agent.extra_config?.iframe_url }}
|
||||
</span>
|
||||
<td class="px-4 py-4 align-middle">
|
||||
<div class="agent-list-cell">
|
||||
<p
|
||||
class="truncate font-mono text-sm text-primary"
|
||||
:title="formatAgentConfigPrimary(agent)"
|
||||
>
|
||||
{{ formatAgentConfigPrimary(agent) }}
|
||||
</p>
|
||||
<p class="truncate text-xs text-muted">
|
||||
{{ formatAgentConfigSecondary(agent) }}
|
||||
</p>
|
||||
</div>
|
||||
</td>
|
||||
<td class="px-2 py-5 whitespace-nowrap">
|
||||
<span
|
||||
class="inline-flex shrink-0 items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border whitespace-nowrap"
|
||||
:class="agent.is_active ? 'bg-green-50 text-green-700 border-green-100' : 'bg-surface-soft text-secondary border-default'"
|
||||
>
|
||||
<span class="w-2 h-2 shrink-0 rounded-full" :class="agent.is_active ? 'bg-green-500' : 'bg-surface-strong'" />
|
||||
{{ agent.is_active ? t('admin.status.active') : t('admin.status.disabled') }}
|
||||
</span>
|
||||
<td class="px-4 py-4 align-middle">
|
||||
<div class="agent-list-cell">
|
||||
<span
|
||||
class="inline-flex w-fit items-center gap-1.5 rounded-full border px-2.5 py-0.5 text-xs font-medium"
|
||||
:class="agent.is_active ? 'border-green-100 bg-green-50 text-green-700' : 'border-default bg-surface-soft text-secondary'"
|
||||
>
|
||||
<span class="h-1.5 w-1.5 shrink-0 rounded-full" :class="agent.is_active ? 'bg-green-500' : 'bg-surface-strong'" />
|
||||
{{ agent.is_active ? t('admin.status.active') : t('admin.status.disabled') }}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
<td class="px-4 py-5 text-right whitespace-nowrap">
|
||||
<td class="px-4 py-4 align-middle text-right">
|
||||
<div class="inline-flex items-center justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
@@ -240,6 +343,12 @@ onMounted(() => {
|
||||
:form="form"
|
||||
:schedule-tasks="scheduleTasks"
|
||||
:training-exam-pdf-guides="trainingExamPdfGuides"
|
||||
:type-catalog="typeCatalog"
|
||||
:intent-route-options="intentRouteOptions"
|
||||
:content-profile-options="contentProfileOptions"
|
||||
:runtime-providers="runtimeProviders"
|
||||
:conversation-modes="conversationModes"
|
||||
:sync-content-profile-from-intent-routes="syncContentProfileFromIntentRoutes"
|
||||
@close="showFormDialog = false"
|
||||
@save="saveAgentForm"
|
||||
@add-suggested-question="addSuggestedQuestion"
|
||||
@@ -270,3 +379,36 @@ onMounted(() => {
|
||||
/>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.agent-list-table {
|
||||
table-layout: fixed;
|
||||
}
|
||||
|
||||
.agent-list-cell {
|
||||
display: flex;
|
||||
min-height: 2.5rem;
|
||||
min-width: 0;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
gap: 0.125rem;
|
||||
}
|
||||
|
||||
.agent-col-resize-handle {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
z-index: 1;
|
||||
width: 8px;
|
||||
height: 100%;
|
||||
cursor: col-resize;
|
||||
border: none;
|
||||
background: transparent;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.agent-col-resize-handle:hover,
|
||||
.agent-col-resize-handle:active {
|
||||
background-color: color-mix(in srgb, var(--border-default) 65%, transparent);
|
||||
}
|
||||
</style>
|
||||
@@ -7,13 +7,22 @@
|
||||
*/
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, watch } from 'vue';
|
||||
import { FileDown, Plus, Trash2, X } from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { AgentFormState, AgentGuideSummary } 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 {
|
||||
applyCatalogDefaultsToForm,
|
||||
applyContentProfileTemplate,
|
||||
catalogForcesTaskProgress,
|
||||
sortIntentRoutesByCatalog,
|
||||
} from '../composables/useAgentsAdminRegistry';
|
||||
import AgentToolRunProgressConfig from './AgentToolRunProgressConfig.vue';
|
||||
|
||||
defineProps<{
|
||||
const props = defineProps<{
|
||||
visible: boolean;
|
||||
isEditing: boolean;
|
||||
isSaving: boolean;
|
||||
@@ -21,6 +30,12 @@ defineProps<{
|
||||
form: AgentFormState;
|
||||
scheduleTasks: ScheduleTask[];
|
||||
trainingExamPdfGuides: AgentGuideSummary[];
|
||||
typeCatalog: AgentTypeCatalogEntry[];
|
||||
intentRouteOptions: IntentRouteOption[];
|
||||
contentProfileOptions: AdminContentProfileOption[];
|
||||
runtimeProviders: string[];
|
||||
conversationModes: string[];
|
||||
syncContentProfileFromIntentRoutes: (form: AgentFormState) => Promise<void>;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -38,6 +53,77 @@ const emit = defineEmits<{
|
||||
const { t } = useI18n();
|
||||
const optionLabels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
|
||||
|
||||
const showDifyFields = computed(() => props.form.runtime_provider === 'dify' || props.form.runtime_provider === 'hybrid');
|
||||
const showIframeFields = computed(() => props.form.runtime_provider === 'iframe');
|
||||
const showToolRunProgress = computed(() => (
|
||||
showDifyFields.value
|
||||
&& props.form.dify_app_type !== 'workflow'
|
||||
&& (props.form.capabilities.task_progress === true || props.form.tool_run_progress_enabled)
|
||||
));
|
||||
|
||||
const currentCatalogEntry = computed(() => (
|
||||
props.typeCatalog.find((item) => item.agent_code === props.form.agent_code)
|
||||
));
|
||||
|
||||
const taskProgressForced = computed(() => catalogForcesTaskProgress(currentCatalogEntry.value));
|
||||
|
||||
/**
|
||||
* 切换 intent_route 勾选状态。
|
||||
*/
|
||||
const toggleIntentRoute = (route: string, checked: boolean) => {
|
||||
const current = new Set(props.form.intent_routes);
|
||||
if (checked) {
|
||||
current.add(route);
|
||||
} else {
|
||||
current.delete(route);
|
||||
}
|
||||
props.form.intent_routes = sortIntentRoutesByCatalog(
|
||||
[...current],
|
||||
props.intentRouteOptions,
|
||||
);
|
||||
void props.syncContentProfileFromIntentRoutes(props.form);
|
||||
};
|
||||
|
||||
/**
|
||||
* 套用 content_profile 默认欢迎语与推荐问题。
|
||||
*/
|
||||
const applySelectedContentProfileTemplate = (force = false) => {
|
||||
const profile = String(props.form.content_profile || '').trim();
|
||||
if (!profile || profile === 'training') return;
|
||||
applyContentProfileTemplate(props.form, profile, props.contentProfileOptions, { force });
|
||||
};
|
||||
|
||||
/**
|
||||
* 启用培训工作区时同步 content_profile。
|
||||
*/
|
||||
const handleTrainingWorkspaceToggle = () => {
|
||||
if (props.form.training_workspace_enabled) {
|
||||
props.form.content_profile = 'training';
|
||||
} else if (props.form.content_profile === 'training') {
|
||||
props.form.content_profile = '';
|
||||
}
|
||||
};
|
||||
|
||||
watch(
|
||||
() => props.form.runtime_provider,
|
||||
(provider) => {
|
||||
props.form.type = provider === 'iframe' ? 'iframe' : 'api';
|
||||
if (provider === 'iframe') {
|
||||
props.form.conversation_mode = 'embedded';
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* 用户切换应用类型时应用 Catalog 默认值。
|
||||
*/
|
||||
const handleAgentCodeChange = () => {
|
||||
const entry = props.typeCatalog.find((item) => item.agent_code === props.form.agent_code);
|
||||
if (entry) {
|
||||
applyCatalogDefaultsToForm(props.form, entry);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 切换培训题型时同步修正表单结构。
|
||||
* 核心逻辑:判断题固定使用 true/false;单选题至少保留两个选项,并把答案回落到首个可用选项。
|
||||
@@ -89,14 +175,31 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.type') }}</label>
|
||||
<select v-model="form.type" class="w-full input-field text-sm">
|
||||
<option value="api">{{ t('admin.agent.fields.types.api') }}</option>
|
||||
<option value="iframe">{{ t('admin.agent.fields.types.iframe') }}</option>
|
||||
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.agentCode') }}</label>
|
||||
<select v-model="form.agent_code" class="w-full input-field text-sm" @change="handleAgentCodeChange">
|
||||
<option v-for="entry in typeCatalog" :key="entry.agent_code" :value="entry.agent_code">
|
||||
{{ entry.label }}
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.runtimeProvider') }}</label>
|
||||
<select v-model="form.runtime_provider" class="w-full input-field text-sm">
|
||||
<option v-for="provider in runtimeProviders" :key="provider" :value="provider">
|
||||
{{ t(`admin.agent.fields.runtimeProviders.${provider}`) }}
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.conversationMode') }}</label>
|
||||
<select v-model="form.conversation_mode" class="w-full input-field text-sm">
|
||||
<option v-for="mode in conversationModes" :key="mode" :value="mode">
|
||||
{{ t(`admin.agent.fields.conversationModes.${mode}`) }}
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<template v-if="form.type === 'api'">
|
||||
<template v-if="showDifyFields">
|
||||
<div class="space-y-2">
|
||||
<label class="text-xs font-bold text-muted uppercase tracking-wider">Dify应用类型</label>
|
||||
<select v-model="form.dify_app_type" class="w-full input-field text-sm">
|
||||
@@ -119,11 +222,19 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.apiKey') }}</label>
|
||||
<input v-model="form.dify_api_key" type="password" class="w-full input-field text-sm font-mono" />
|
||||
<input
|
||||
v-model="form.dify_api_key"
|
||||
type="password"
|
||||
class="w-full input-field text-sm font-mono"
|
||||
:placeholder="form.dify_api_key_masked
|
||||
? t('admin.agent.fields.apiKeyWriteOnlyPlaceholder', { masked: form.dify_api_key_masked })
|
||||
: t('admin.agent.fields.apiKeyCreatePlaceholder')"
|
||||
autocomplete="new-password"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template v-if="form.type === 'iframe'">
|
||||
<template v-if="showIframeFields">
|
||||
<div class="col-span-1 md:col-span-2 space-y-2">
|
||||
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.iframeUrl') }}</label>
|
||||
<input v-model="form.iframe_url" type="text" class="w-full input-field text-sm font-mono" placeholder="https://..." />
|
||||
@@ -140,6 +251,16 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="col-span-1 md:col-span-2 space-y-2">
|
||||
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.welcomeMessage') }}</label>
|
||||
<textarea
|
||||
v-model="form.welcome_message"
|
||||
rows="2"
|
||||
class="w-full input-field text-sm resize-y"
|
||||
:placeholder="t('admin.agent.fields.welcomeMessagePlaceholder')"
|
||||
/>
|
||||
</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">
|
||||
@@ -175,6 +296,81 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-span-1 md:col-span-2 rounded-2xl border border-default bg-surface-soft/40 p-4">
|
||||
<div class="mb-4">
|
||||
<div class="text-xs font-bold uppercase tracking-wider text-muted">{{ t('admin.agent.registry.title') }}</div>
|
||||
<p class="mt-1 text-sm leading-6 text-secondary">{{ t('admin.agent.registry.subtitle') }}</p>
|
||||
</div>
|
||||
|
||||
<div class="space-y-4">
|
||||
<div class="space-y-2">
|
||||
<label class="text-xs font-semibold text-secondary">{{ t('admin.agent.registry.intentRoutesLabel') }}</label>
|
||||
<div class="grid grid-cols-1 gap-2 sm:grid-cols-2">
|
||||
<label
|
||||
v-for="route in intentRouteOptions"
|
||||
:key="route.key"
|
||||
class="inline-flex items-start gap-2 rounded-xl border border-default bg-white px-3 py-2 text-sm text-secondary"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
class="mt-0.5 accent-brand-600"
|
||||
:checked="form.intent_routes.includes(route.key)"
|
||||
@change="toggleIntentRoute(route.key, ($event.target as HTMLInputElement).checked)"
|
||||
/>
|
||||
<span>
|
||||
<span class="font-medium text-primary">{{ route.label }}</span>
|
||||
<span v-if="route.description" class="mt-1 block text-xs leading-5 text-muted">
|
||||
{{ route.description }}
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
<p class="text-xs leading-5 text-muted">{{ t('admin.agent.registry.intentRoutesHint') }}</p>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2">
|
||||
<label class="text-xs font-semibold text-secondary">{{ t('admin.agent.registry.contentProfileLabel') }}</label>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<select v-model="form.content_profile" class="min-w-[12rem] flex-1 input-field text-sm">
|
||||
<option value="">{{ t('admin.agent.registry.contentProfileNone') }}</option>
|
||||
<option
|
||||
v-for="profile in contentProfileOptions"
|
||||
:key="profile.key"
|
||||
:value="profile.key"
|
||||
>
|
||||
{{ profile.label }}
|
||||
</option>
|
||||
</select>
|
||||
<button
|
||||
type="button"
|
||||
class="btn-secondary text-sm shrink-0"
|
||||
:disabled="!form.content_profile || form.content_profile === 'training'"
|
||||
@click="applySelectedContentProfileTemplate(false)"
|
||||
>
|
||||
{{ t('admin.agent.registry.applyContentProfileTemplate') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="btn-secondary text-sm shrink-0"
|
||||
:disabled="!form.content_profile || form.content_profile === 'training'"
|
||||
@click="applySelectedContentProfileTemplate(true)"
|
||||
>
|
||||
{{ t('admin.agent.registry.overwriteContentProfileTemplate') }}
|
||||
</button>
|
||||
</div>
|
||||
<p class="text-xs leading-5 text-muted">{{ t('admin.agent.registry.contentProfileHint') }}</p>
|
||||
</div>
|
||||
|
||||
<label class="inline-flex items-start gap-2 rounded-xl border border-default bg-white px-3 py-2 text-sm text-secondary">
|
||||
<input v-model="form.capabilities.erp_kb" type="checkbox" class="mt-0.5 accent-brand-600" />
|
||||
<span>
|
||||
<span class="font-medium text-primary">{{ t('admin.agent.registry.erpKb') }}</span>
|
||||
<span class="mt-1 block text-xs leading-5 text-muted">{{ t('admin.agent.registry.erpKbHint') }}</span>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-span-1 md:col-span-2 space-y-3">
|
||||
<div class="flex flex-wrap items-center justify-between gap-3">
|
||||
<label class="text-xs font-bold text-muted uppercase tracking-wider">常见问题</label>
|
||||
@@ -242,7 +438,12 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =
|
||||
<p class="mt-1 text-sm leading-6 text-secondary">{{ t('admin.agent.training.subtitle') }}</p>
|
||||
</div>
|
||||
<label class="inline-flex items-center gap-2 rounded-xl border border-default bg-white px-3 py-2 text-sm text-secondary">
|
||||
<input v-model="form.training_workspace_enabled" type="checkbox" class="accent-brand-600" />
|
||||
<input
|
||||
v-model="form.training_workspace_enabled"
|
||||
type="checkbox"
|
||||
class="accent-brand-600"
|
||||
@change="handleTrainingWorkspaceToggle"
|
||||
/>
|
||||
<span>{{ t('admin.agent.training.enable') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
@@ -448,9 +649,10 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =
|
||||
</div>
|
||||
|
||||
<AgentToolRunProgressConfig
|
||||
v-if="form.type === 'api' && form.dify_app_type !== 'workflow'"
|
||||
v-if="showToolRunProgress"
|
||||
:form="form"
|
||||
:schedule-tasks="scheduleTasks"
|
||||
:task-progress-forced="taskProgressForced"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+14
-6
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* features/admin/modules/agents/components/AgentToolRunProgressConfig.vue
|
||||
* 用途:应用管理表单中的 tool_run_progress 能力配置区块。
|
||||
* 用途:应用管理表单中的文件检核任务进度能力配置(Registry 列)。
|
||||
* 依赖:agent.types AgentFormState、schedule.types ScheduleTask、vue-i18n。
|
||||
* 逻辑:AgentsPage 在 API 集成类型下挂载本组件;schedule_task_id 写入 extra_config.tool_run_progress。
|
||||
* 逻辑:写入 bound_schedule_task_id、capabilities.task_progress 与 handler_config 轮询参数。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import type { AgentFormState } from '@/features/admin/types/agent.types';
|
||||
@@ -11,6 +11,8 @@ import type { ScheduleTask } from '@/shared/types/schedule.types';
|
||||
defineProps<{
|
||||
form: AgentFormState;
|
||||
scheduleTasks: ScheduleTask[];
|
||||
/** Catalog forced_capabilities.task_progress === true 时隐藏手动开关。 */
|
||||
taskProgressForced?: boolean;
|
||||
}>();
|
||||
</script>
|
||||
|
||||
@@ -21,22 +23,28 @@ defineProps<{
|
||||
<h4 class="text-sm font-semibold text-primary">{{ $t('admin.agent.toolRunProgress.title') }}</h4>
|
||||
<p class="mt-1 text-xs text-muted">{{ $t('admin.agent.toolRunProgress.subtitle') }}</p>
|
||||
</div>
|
||||
<label class="inline-flex items-center gap-2 text-sm text-secondary shrink-0">
|
||||
<input v-model="form.tool_run_progress_enabled" type="checkbox" class="admin-checkbox" />
|
||||
<label v-if="!taskProgressForced" class="inline-flex items-center gap-2 text-sm text-secondary shrink-0">
|
||||
<input
|
||||
v-model="form.tool_run_progress_enabled"
|
||||
type="checkbox"
|
||||
class="admin-checkbox"
|
||||
@change="form.capabilities.task_progress = form.tool_run_progress_enabled"
|
||||
/>
|
||||
<span>{{ $t('admin.agent.toolRunProgress.enable') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<template v-if="form.tool_run_progress_enabled">
|
||||
<template v-if="form.capabilities.task_progress === true || form.tool_run_progress_enabled">
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div class="space-y-2">
|
||||
<label class="text-xs font-bold text-muted uppercase tracking-wider">
|
||||
{{ $t('admin.agent.toolRunProgress.scheduleTaskId') }}
|
||||
</label>
|
||||
<select
|
||||
v-model="form.schedule_task_id"
|
||||
v-model="form.bound_schedule_task_id"
|
||||
class="w-full input-field text-sm"
|
||||
:disabled="scheduleTasks.length === 0"
|
||||
@change="form.schedule_task_id = form.bound_schedule_task_id"
|
||||
>
|
||||
<option :value="null">
|
||||
{{ scheduleTasks.length === 0
|
||||
|
||||
@@ -5,13 +5,17 @@
|
||||
* 从原 AdminView.vue 的 agents 相关 script 抽取,供 AgentsPage 使用。
|
||||
*/
|
||||
|
||||
import { ref } from 'vue';
|
||||
import { ref, computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import {
|
||||
createAdminAgent,
|
||||
deleteAdminAgent,
|
||||
getAdminAgentRegistrySchema,
|
||||
inferAdminContentProfile,
|
||||
importAdminAgentTrainingQuestionBankFromPdf,
|
||||
listAdminAgentGuides,
|
||||
listAdminContentProfiles,
|
||||
listAdminIntentRoutes,
|
||||
listAdminAgents,
|
||||
listAdminUsers,
|
||||
saveAdminAgentPermissions,
|
||||
@@ -24,32 +28,24 @@ import type { AdminUserRow } from '@/features/admin/types/admin.types';
|
||||
import type {
|
||||
AgentFormState,
|
||||
AgentRow,
|
||||
AgentSuggestedQuestionItem,
|
||||
AgentTestResult,
|
||||
AgentTrainingQuestionFormItem,
|
||||
AgentGuideSummary,
|
||||
} from '@/features/admin/types/agent.types';
|
||||
import { createEmptyAgentForm, createEmptyTrainingQuestionForm } from '@/features/admin/types/agent.types';
|
||||
import type { ScheduleTask } from '@/shared/types/schedule.types';
|
||||
import {
|
||||
applyCatalogDefaultsToForm,
|
||||
buildAgentRegistryPayload,
|
||||
mapAgentRowToForm,
|
||||
type AgentCapabilitiesDefaults,
|
||||
type AgentTypeCatalogEntry,
|
||||
type IntentRouteOption,
|
||||
} from './useAgentsAdminRegistry';
|
||||
import type { AdminAgentRegistrySchema, AdminContentProfileOption } from '@/features/admin/api/admin.api';
|
||||
|
||||
const TRAINING_OPTION_IDS = 'abcdefghijklmnopqrstuvwxyz'.split('');
|
||||
|
||||
const normalizeSuggestedQuestions = (value: unknown): AgentSuggestedQuestionItem[] => {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value
|
||||
.map((item) => {
|
||||
if (typeof item === 'string') {
|
||||
return { question: item.trim(), group: '' };
|
||||
}
|
||||
if (!item || typeof item !== 'object') return null;
|
||||
const question = String((item as Record<string, unknown>).question || (item as Record<string, unknown>).text || '').trim();
|
||||
const group = String((item as Record<string, unknown>).group || '').trim();
|
||||
if (!question) return null;
|
||||
return { question, group };
|
||||
})
|
||||
.filter((item): item is AgentSuggestedQuestionItem => !!item);
|
||||
};
|
||||
|
||||
const asRecord = (value: unknown): Record<string, unknown> => (
|
||||
value && typeof value === 'object' && !Array.isArray(value)
|
||||
? value as Record<string, unknown>
|
||||
@@ -213,85 +209,15 @@ const buildTrainingPdfImportMessages = (
|
||||
return { primary, notices };
|
||||
};
|
||||
|
||||
/**
|
||||
* 从 Agent extra_config 解析 tool_run_progress 表单字段。
|
||||
* 核心逻辑:capabilities 含 tool_run_progress 时视为启用;task_id 与 schedule_task_id 等价。
|
||||
*/
|
||||
const parseToolRunProgressFromExtra = (extra: Record<string, unknown> | undefined) => {
|
||||
const capabilities = Array.isArray(extra?.capabilities)
|
||||
? extra.capabilities.map((item) => String(item))
|
||||
: [];
|
||||
const enabled = capabilities.includes('tool_run_progress');
|
||||
const cfg = extra?.tool_run_progress && typeof extra.tool_run_progress === 'object'
|
||||
? (extra.tool_run_progress as Record<string, unknown>)
|
||||
: {};
|
||||
const rawTaskId = cfg.schedule_task_id ?? cfg.task_id;
|
||||
const parsedTaskId = rawTaskId != null && rawTaskId !== '' ? Number(rawTaskId) : null;
|
||||
const pollRaw = Number(cfg.poll_interval_seconds);
|
||||
return {
|
||||
tool_run_progress_enabled: enabled,
|
||||
schedule_task_id: Number.isFinite(parsedTaskId) && parsedTaskId! > 0 ? parsedTaskId : null,
|
||||
poll_interval_seconds: Number.isFinite(pollRaw) && pollRaw > 0 ? Math.min(pollRaw, 30) : 2,
|
||||
lock_input_when_running: cfg.lock_input_when_running !== false,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 将表单中的 tool_run_progress 字段写入 extra_config。
|
||||
* 核心逻辑:启用时追加 capabilities 并写入 schedule_task_id;禁用时移除能力声明。
|
||||
*/
|
||||
const applyToolRunProgressToExtra = (extraConfig: Record<string, unknown>, form: AgentFormState): void => {
|
||||
const capabilities = Array.isArray(extraConfig.capabilities)
|
||||
? extraConfig.capabilities.map((item) => String(item)).filter((item) => item !== 'tool_run_progress')
|
||||
: [];
|
||||
|
||||
if (form.tool_run_progress_enabled) {
|
||||
capabilities.push('tool_run_progress');
|
||||
extraConfig.capabilities = capabilities;
|
||||
extraConfig.tool_run_progress = {
|
||||
type: 'file_check',
|
||||
schedule_task_id: form.schedule_task_id,
|
||||
poll_interval_seconds: form.poll_interval_seconds,
|
||||
lock_input_when_running: form.lock_input_when_running,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
if (capabilities.length) {
|
||||
extraConfig.capabilities = capabilities;
|
||||
} else {
|
||||
delete extraConfig.capabilities;
|
||||
}
|
||||
delete extraConfig.tool_run_progress;
|
||||
};
|
||||
|
||||
/**
|
||||
* 将表单分类字段写入 extra_config(P1 轻量方案)。
|
||||
*/
|
||||
const applyAgentCategoryToExtra = (extraConfig: Record<string, unknown>, form: AgentFormState): void => {
|
||||
const category = String(form.category || '').trim();
|
||||
const subCategory = String(form.sub_category || '').trim();
|
||||
const sortRaw = Number(form.sort_order);
|
||||
const sortOrder = Number.isFinite(sortRaw) && sortRaw >= 0 ? Math.floor(sortRaw) : 0;
|
||||
|
||||
if (category) {
|
||||
extraConfig.category = category;
|
||||
} else {
|
||||
delete extraConfig.category;
|
||||
}
|
||||
if (subCategory) {
|
||||
extraConfig.sub_category = subCategory;
|
||||
} else {
|
||||
delete extraConfig.sub_category;
|
||||
}
|
||||
extraConfig.sort_order = sortOrder;
|
||||
};
|
||||
|
||||
export function useAgentsAdmin() {
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
|
||||
const agents = ref<AgentRow[]>([]);
|
||||
const registrySchema = ref<AdminAgentRegistrySchema | null>(null);
|
||||
const typeCatalog = ref<AgentTypeCatalogEntry[]>([]);
|
||||
const intentRouteOptions = ref<IntentRouteOption[]>([]);
|
||||
const contentProfileOptions = ref<AdminContentProfileOption[]>([]);
|
||||
const users = ref<AdminUserRow[]>([]);
|
||||
const scheduleTasks = ref<ScheduleTask[]>([]);
|
||||
const trainingExamPdfGuides = ref<AgentGuideSummary[]>([]);
|
||||
@@ -317,6 +243,55 @@ export function useAgentsAdmin() {
|
||||
|
||||
const activeUsers = () => users.value.filter((u) => u.status !== 'pending');
|
||||
|
||||
const defaultCapabilities = (): AgentCapabilitiesDefaults => {
|
||||
const caps = registrySchema.value?.platform.default_capabilities;
|
||||
return createEmptyAgentForm(caps as Partial<AgentCapabilitiesDefaults>).capabilities;
|
||||
};
|
||||
|
||||
const loadRegistrySchema = async (): Promise<void> => {
|
||||
try {
|
||||
registrySchema.value = await getAdminAgentRegistrySchema();
|
||||
typeCatalog.value = registrySchema.value.agent_types;
|
||||
} catch (e) {
|
||||
console.error('Error loading agent registry schema:', e);
|
||||
registrySchema.value = null;
|
||||
typeCatalog.value = [];
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 根据 intent_routes 调用后端推断 content_profile(Admin 表单建议)。
|
||||
*/
|
||||
const syncContentProfileFromIntentRoutes = async (targetForm: AgentFormState): Promise<void> => {
|
||||
if (targetForm.training_workspace_enabled || targetForm.content_profile === 'training') return;
|
||||
try {
|
||||
const result = await inferAdminContentProfile(targetForm.intent_routes);
|
||||
if (result.content_profile) {
|
||||
targetForm.content_profile = result.content_profile;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Error inferring content profile:', e);
|
||||
}
|
||||
};
|
||||
|
||||
const loadContentProfileOptions = async (): Promise<void> => {
|
||||
try {
|
||||
contentProfileOptions.value = await listAdminContentProfiles();
|
||||
} catch (e) {
|
||||
console.error('Error loading content profile catalog:', e);
|
||||
contentProfileOptions.value = [];
|
||||
}
|
||||
};
|
||||
|
||||
const loadIntentRouteOptions = async (): Promise<void> => {
|
||||
try {
|
||||
intentRouteOptions.value = await listAdminIntentRoutes();
|
||||
} catch (e) {
|
||||
console.error('Error loading intent route catalog:', e);
|
||||
intentRouteOptions.value = [];
|
||||
}
|
||||
};
|
||||
|
||||
const loadAgents = async (): Promise<void> => {
|
||||
try {
|
||||
agents.value = await listAdminAgents();
|
||||
@@ -362,13 +337,21 @@ export function useAgentsAdmin() {
|
||||
|
||||
const loadAll = async (): Promise<void> => {
|
||||
isLoading.value = true;
|
||||
await Promise.all([loadAgents(), loadUsers(), loadScheduleTasks()]);
|
||||
await Promise.all([
|
||||
loadRegistrySchema(),
|
||||
loadIntentRouteOptions(),
|
||||
loadContentProfileOptions(),
|
||||
loadAgents(),
|
||||
loadUsers(),
|
||||
loadScheduleTasks(),
|
||||
]);
|
||||
isLoading.value = false;
|
||||
};
|
||||
|
||||
const resetForm = (): void => {
|
||||
selectedAgentId.value = null;
|
||||
form.value = createEmptyAgentForm();
|
||||
form.value = createEmptyAgentForm(defaultCapabilities());
|
||||
applyCatalogDefaultsToForm(form.value, typeCatalog.value[0]);
|
||||
trainingExamPdfGuides.value = [];
|
||||
isEditing.value = false;
|
||||
};
|
||||
@@ -377,30 +360,15 @@ export function useAgentsAdmin() {
|
||||
const extra = (agent.extra_config && typeof agent.extra_config === 'object')
|
||||
? agent.extra_config
|
||||
: {};
|
||||
const toolRunProgress = parseToolRunProgressFromExtra(extra);
|
||||
const trainingConfig = parseTrainingConfigFromExtra(extra);
|
||||
selectedAgentId.value = agent.id;
|
||||
form.value = {
|
||||
id: agent.id,
|
||||
name: agent.name,
|
||||
dify_app_id: agent.dify_app_id,
|
||||
dify_api_key: agent.dify_api_key || '',
|
||||
description: agent.description || '',
|
||||
type: agent.type,
|
||||
dify_app_type: agent.extra_config?.dify_app_type === 'workflow' ? 'workflow' : 'chatflow',
|
||||
api_base_url: agent.api_base_url || '',
|
||||
iframe_url: String(agent.extra_config?.iframe_url || ''),
|
||||
suggested_questions_style: agent.extra_config?.suggested_questions_style === 'styled' ? 'styled' : 'plain',
|
||||
suggested_questions: normalizeSuggestedQuestions(agent.extra_config?.suggested_questions),
|
||||
is_active: agent.is_active,
|
||||
category: String(extra.category || ''),
|
||||
sub_category: String(extra.sub_category || ''),
|
||||
sort_order: Number(extra.sort_order) >= 0 && Number.isFinite(Number(extra.sort_order))
|
||||
? Math.floor(Number(extra.sort_order))
|
||||
: 0,
|
||||
...toolRunProgress,
|
||||
...mapAgentRowToForm(agent, defaultCapabilities()),
|
||||
...trainingConfig,
|
||||
};
|
||||
if (form.value.content_profile === 'training') {
|
||||
form.value.training_workspace_enabled = true;
|
||||
}
|
||||
isEditing.value = true;
|
||||
void loadTrainingExamPdfGuides(agent.id);
|
||||
};
|
||||
@@ -464,8 +432,11 @@ export function useAgentsAdmin() {
|
||||
}
|
||||
}
|
||||
}
|
||||
const supportsToolRunProgress = form.value.type === 'api' && form.value.dify_app_type !== 'workflow';
|
||||
if (supportsToolRunProgress && form.value.tool_run_progress_enabled && !form.value.schedule_task_id) {
|
||||
const supportsToolRunProgress = form.value.type === 'api'
|
||||
&& form.value.dify_app_type !== 'workflow'
|
||||
&& (form.value.capabilities.task_progress === true || form.value.tool_run_progress_enabled);
|
||||
const boundTaskId = form.value.bound_schedule_task_id ?? form.value.schedule_task_id;
|
||||
if (supportsToolRunProgress && !boundTaskId) {
|
||||
msg.warning(t('admin.agent.toolRunProgress.scheduleTaskRequired'));
|
||||
return false;
|
||||
}
|
||||
@@ -479,29 +450,6 @@ export function useAgentsAdmin() {
|
||||
? editingAgent.extra_config
|
||||
: {}),
|
||||
};
|
||||
if (form.value.type === 'iframe' && form.value.iframe_url) {
|
||||
extra_config.iframe_url = form.value.iframe_url;
|
||||
} else {
|
||||
delete extra_config.iframe_url;
|
||||
}
|
||||
if (form.value.type === 'api') {
|
||||
extra_config.dify_app_type = form.value.dify_app_type === 'workflow' ? 'workflow' : 'chatflow';
|
||||
} else {
|
||||
delete extra_config.dify_app_type;
|
||||
}
|
||||
extra_config.suggested_questions_style = form.value.suggested_questions_style === 'styled' ? 'styled' : 'plain';
|
||||
extra_config.suggested_questions = form.value.suggested_questions
|
||||
.map((item) => ({
|
||||
question: String(item.question || '').trim(),
|
||||
group: String(item.group || '').trim(),
|
||||
}))
|
||||
.filter((item) => item.question);
|
||||
if (supportsToolRunProgress) {
|
||||
applyToolRunProgressToExtra(extra_config, form.value);
|
||||
} else {
|
||||
applyToolRunProgressToExtra(extra_config, { ...form.value, tool_run_progress_enabled: false });
|
||||
}
|
||||
applyAgentCategoryToExtra(extra_config, form.value);
|
||||
extra_config.training_workspace_enabled = Boolean(form.value.training_workspace_enabled);
|
||||
if (hasTrainingConfigContent(form.value)) {
|
||||
extra_config.training_config = {
|
||||
@@ -514,17 +462,18 @@ export function useAgentsAdmin() {
|
||||
delete extra_config.training_config;
|
||||
}
|
||||
|
||||
const registryPayload = buildAgentRegistryPayload(form.value, {
|
||||
editingExtraConfig: extra_config,
|
||||
supportsToolRunProgress,
|
||||
trainingExtraPatch: {},
|
||||
typeCatalog: typeCatalog.value,
|
||||
});
|
||||
|
||||
try {
|
||||
const editingId = isEditing.value ? Number(form.value.id) : null;
|
||||
if (isEditing.value && form.value.id != null) {
|
||||
const payload: Record<string, unknown> = {
|
||||
name: form.value.name,
|
||||
dify_app_id: form.value.dify_app_id,
|
||||
description: form.value.description,
|
||||
type: form.value.type,
|
||||
api_base_url: form.value.api_base_url,
|
||||
extra_config,
|
||||
is_active: form.value.is_active,
|
||||
...registryPayload,
|
||||
};
|
||||
if (form.value.dify_api_key) {
|
||||
payload.dify_api_key = form.value.dify_api_key;
|
||||
@@ -533,13 +482,8 @@ export function useAgentsAdmin() {
|
||||
msg.success('应用更新成功');
|
||||
} else {
|
||||
await createAdminAgent({
|
||||
name: form.value.name,
|
||||
dify_app_id: form.value.dify_app_id,
|
||||
...registryPayload,
|
||||
dify_api_key: form.value.dify_api_key,
|
||||
description: form.value.description,
|
||||
type: form.value.type,
|
||||
api_base_url: form.value.api_base_url,
|
||||
extra_config,
|
||||
});
|
||||
msg.success('应用创建成功');
|
||||
}
|
||||
@@ -731,6 +675,13 @@ export function useAgentsAdmin() {
|
||||
|
||||
return {
|
||||
agents,
|
||||
typeCatalog,
|
||||
registrySchema,
|
||||
runtimeProviders: computed(() => registrySchema.value?.platform.runtime_providers ?? []),
|
||||
conversationModes: computed(() => registrySchema.value?.platform.conversation_modes ?? []),
|
||||
syncContentProfileFromIntentRoutes,
|
||||
intentRouteOptions,
|
||||
contentProfileOptions,
|
||||
users,
|
||||
scheduleTasks,
|
||||
trainingExamPdfGuides,
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* features/admin/modules/agents/composables/useAgentsAdminRegistry.test.ts
|
||||
*
|
||||
* 用途:锁定 Catalog 切换时 handler_config 表单清理与 payload 构造行为。
|
||||
* 依赖:Vitest、useAgentsAdminRegistry、agent.types。
|
||||
* 逻辑:从 generic 切到空 schema 类型后,intent_routes/content_profile 被清空且 handler_config 为 null。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { createEmptyAgentForm } from '@/features/admin/types/agent.types';
|
||||
import {
|
||||
applyCatalogDefaultsToForm,
|
||||
buildAgentRegistryPayload,
|
||||
pruneHandlerFormFieldsForCatalog,
|
||||
type AgentTypeCatalogEntry,
|
||||
} from './useAgentsAdminRegistry';
|
||||
|
||||
const genericCatalogEntry: AgentTypeCatalogEntry = {
|
||||
agent_code: 'generic',
|
||||
label: '通用问答 / 知识库',
|
||||
conversation_mode_default: 'chat',
|
||||
runtime_provider_default: 'dify',
|
||||
handler_config_schema: {
|
||||
intent_routes: { type: 'array', items: 'string' },
|
||||
content_profile: { type: 'string' },
|
||||
},
|
||||
};
|
||||
|
||||
const shippingCatalogEntry: AgentTypeCatalogEntry = {
|
||||
agent_code: 'shipping_notice',
|
||||
label: '货代发货通知',
|
||||
conversation_mode_default: 'task_chat',
|
||||
runtime_provider_default: 'hybrid',
|
||||
handler_config_schema: {},
|
||||
};
|
||||
|
||||
describe('useAgentsAdminRegistry catalog switch', () => {
|
||||
it('pruneHandlerFormFieldsForCatalog clears intent routes and content profile for empty schema', () => {
|
||||
const form = createEmptyAgentForm();
|
||||
form.agent_code = 'generic';
|
||||
form.intent_routes = ['text2sql'];
|
||||
form.content_profile = 'generic_entrance';
|
||||
|
||||
pruneHandlerFormFieldsForCatalog(form, shippingCatalogEntry);
|
||||
|
||||
expect(form.intent_routes).toEqual([]);
|
||||
expect(form.content_profile).toBe('');
|
||||
});
|
||||
|
||||
it('applyCatalogDefaultsToForm switching to shipping_notice yields null handler_config payload', () => {
|
||||
const form = createEmptyAgentForm();
|
||||
applyCatalogDefaultsToForm(form, genericCatalogEntry);
|
||||
form.intent_routes = ['text2sql'];
|
||||
form.content_profile = 'generic_entrance';
|
||||
form.name = 'Switch Bot';
|
||||
form.dify_app_id = 'app-switch';
|
||||
|
||||
applyCatalogDefaultsToForm(form, shippingCatalogEntry);
|
||||
|
||||
expect(form.agent_code).toBe('shipping_notice');
|
||||
expect(form.intent_routes).toEqual([]);
|
||||
expect(form.content_profile).toBe('');
|
||||
|
||||
const payload = buildAgentRegistryPayload(form, {
|
||||
supportsToolRunProgress: false,
|
||||
trainingExtraPatch: {},
|
||||
typeCatalog: [genericCatalogEntry, shippingCatalogEntry],
|
||||
});
|
||||
|
||||
expect(payload.handler_config).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,497 @@
|
||||
/**
|
||||
|
||||
* features/admin/modules/agents/composables/useAgentsAdminRegistry.ts
|
||||
|
||||
*
|
||||
|
||||
* 用途:Agent Registry 表单与 API 载荷映射(迭代 3 结构化列)。
|
||||
|
||||
* 依赖:agent.types、admin AgentTypeCatalog 条目。
|
||||
|
||||
* 逻辑:useAgentsAdmin 调用本模块构建 create/update payload 与表单回填。
|
||||
|
||||
*/
|
||||
|
||||
|
||||
|
||||
import type { AgentFormState, AgentRow } from '@/features/admin/types/agent.types';
|
||||
|
||||
import { createEmptyAgentForm } from '@/features/admin/types/agent.types';
|
||||
|
||||
import type { AdminContentProfileOption } from '@/features/admin/api/admin.api';
|
||||
|
||||
|
||||
|
||||
export interface AgentTypeCatalogEntry {
|
||||
|
||||
agent_code: string;
|
||||
|
||||
label: string;
|
||||
|
||||
conversation_mode_default: string;
|
||||
|
||||
runtime_provider_default: string;
|
||||
|
||||
runtime_handler?: string | null;
|
||||
|
||||
models?: string[];
|
||||
|
||||
required_fields?: string[];
|
||||
|
||||
forced_capabilities?: Record<string, boolean>;
|
||||
|
||||
handler_config_schema?: Record<string, unknown>;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
export type AgentCapabilitiesDefaults = AgentFormState['capabilities'];
|
||||
|
||||
|
||||
|
||||
/** Admin Intent route 选项(由后端 /api/admin/agents/intent-routes 提供)。 */
|
||||
|
||||
export interface IntentRouteOption {
|
||||
|
||||
key: string;
|
||||
|
||||
label: string;
|
||||
|
||||
description?: string;
|
||||
|
||||
category?: string;
|
||||
|
||||
enabled?: boolean;
|
||||
|
||||
sort_order?: number;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
const normalizeIntentRoutes = (raw: unknown): string[] => {
|
||||
|
||||
if (!Array.isArray(raw)) return [];
|
||||
|
||||
const seen = new Set<string>();
|
||||
|
||||
const result: string[] = [];
|
||||
|
||||
raw.forEach((item) => {
|
||||
|
||||
const route = String(item || '').trim();
|
||||
|
||||
if (!route || seen.has(route)) return;
|
||||
|
||||
seen.add(route);
|
||||
|
||||
result.push(route);
|
||||
|
||||
});
|
||||
|
||||
return result;
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 按后端 catalog 顺序重排已选 intent_routes。
|
||||
|
||||
*/
|
||||
|
||||
export function sortIntentRoutesByCatalog(
|
||||
|
||||
selected: string[],
|
||||
|
||||
options: IntentRouteOption[],
|
||||
|
||||
): string[] {
|
||||
|
||||
const selectedSet = new Set(selected);
|
||||
|
||||
return options.map((item) => item.key).filter((key) => selectedSet.has(key));
|
||||
|
||||
}
|
||||
|
||||
/** Catalog 是否强制开启 task_progress。 */
|
||||
export function catalogForcesTaskProgress(entry?: AgentTypeCatalogEntry): boolean {
|
||||
return entry?.forced_capabilities?.task_progress === true;
|
||||
}
|
||||
|
||||
/** Catalog 是否声明 bound_schedule_task_id 必填。 */
|
||||
export function catalogRequiresScheduleTask(entry?: AgentTypeCatalogEntry): boolean {
|
||||
return (entry?.required_fields || []).includes('bound_schedule_task_id');
|
||||
}
|
||||
|
||||
const handlerConfigSchemaFieldNames = (entry?: AgentTypeCatalogEntry): string[] => {
|
||||
const schema = entry?.handler_config_schema;
|
||||
if (!schema || typeof schema !== 'object') return [];
|
||||
return Object.keys(schema);
|
||||
};
|
||||
|
||||
/**
|
||||
* 切换 Catalog 后清理当前类型 handler_config_schema 不支持的表单字段。
|
||||
*/
|
||||
export function pruneHandlerFormFieldsForCatalog(
|
||||
form: AgentFormState,
|
||||
entry?: AgentTypeCatalogEntry,
|
||||
): void {
|
||||
const schemaFields = new Set(handlerConfigSchemaFieldNames(entry));
|
||||
if (!schemaFields.has('intent_routes')) {
|
||||
form.intent_routes = [];
|
||||
}
|
||||
if (!schemaFields.has('content_profile')) {
|
||||
form.content_profile = '';
|
||||
}
|
||||
if (!schemaFields.has('poll_interval_seconds')) {
|
||||
form.poll_interval_seconds = 2;
|
||||
}
|
||||
if (!schemaFields.has('lock_input_when_running')) {
|
||||
form.lock_input_when_running = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 合并 handler_config:仅写入当前 Catalog schema 声明的字段。
|
||||
*/
|
||||
function buildHandlerConfigPayload(
|
||||
form: AgentFormState,
|
||||
catalogEntry?: AgentTypeCatalogEntry,
|
||||
): Record<string, unknown> | null {
|
||||
|
||||
const schemaFields = handlerConfigSchemaFieldNames(catalogEntry);
|
||||
if (!schemaFields.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const handlerConfig: Record<string, unknown> = {};
|
||||
const schemaFieldSet = new Set(schemaFields);
|
||||
|
||||
if (schemaFieldSet.has('intent_routes') && form.intent_routes.length) {
|
||||
handlerConfig.intent_routes = [...form.intent_routes];
|
||||
}
|
||||
|
||||
const contentProfile = form.training_workspace_enabled
|
||||
? 'training'
|
||||
: String(form.content_profile || '').trim();
|
||||
if (schemaFieldSet.has('content_profile') && contentProfile) {
|
||||
handlerConfig.content_profile = contentProfile;
|
||||
}
|
||||
|
||||
const enableProgress = form.capabilities.task_progress === true || form.tool_run_progress_enabled;
|
||||
if (enableProgress) {
|
||||
if (schemaFieldSet.has('poll_interval_seconds')) {
|
||||
handlerConfig.poll_interval_seconds = form.poll_interval_seconds;
|
||||
}
|
||||
if (schemaFieldSet.has('lock_input_when_running')) {
|
||||
handlerConfig.lock_input_when_running = form.lock_input_when_running;
|
||||
}
|
||||
}
|
||||
|
||||
return Object.keys(handlerConfig).length ? handlerConfig : null;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 按 Catalog 默认值初始化新建表单。
|
||||
|
||||
*/
|
||||
|
||||
export function applyCatalogDefaultsToForm(
|
||||
|
||||
form: AgentFormState,
|
||||
|
||||
entry: AgentTypeCatalogEntry | undefined,
|
||||
|
||||
): void {
|
||||
|
||||
if (!entry) return;
|
||||
|
||||
form.agent_code = entry.agent_code;
|
||||
|
||||
form.runtime_provider = entry.runtime_provider_default as AgentFormState['runtime_provider'];
|
||||
|
||||
form.conversation_mode = entry.conversation_mode_default as AgentFormState['conversation_mode'];
|
||||
|
||||
form.type = form.runtime_provider === 'iframe' ? 'iframe' : 'api';
|
||||
|
||||
const forced = entry.forced_capabilities || {};
|
||||
if (forced.task_progress === true) {
|
||||
form.capabilities.task_progress = true;
|
||||
form.tool_run_progress_enabled = true;
|
||||
} else if (!catalogRequiresScheduleTask(entry)) {
|
||||
form.capabilities.task_progress = false;
|
||||
form.tool_run_progress_enabled = false;
|
||||
form.bound_schedule_task_id = null;
|
||||
}
|
||||
|
||||
pruneHandlerFormFieldsForCatalog(form, entry);
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* Admin 列表行 → 表单状态(只读结构化列;training 等实验字段由 useAgentsAdmin 处理 extra_config)。
|
||||
*/
|
||||
export function mapAgentRowToForm(
|
||||
agent: AgentRow,
|
||||
defaultCapabilities?: AgentCapabilitiesDefaults,
|
||||
): AgentFormState {
|
||||
const handlerConfig = agent.handler_config && typeof agent.handler_config === 'object'
|
||||
|
||||
? agent.handler_config
|
||||
|
||||
: {};
|
||||
|
||||
|
||||
|
||||
return {
|
||||
|
||||
...createEmptyAgentForm(defaultCapabilities),
|
||||
|
||||
id: agent.id,
|
||||
|
||||
name: agent.name,
|
||||
|
||||
dify_app_id: agent.dify_app_id || '',
|
||||
|
||||
dify_api_key: '',
|
||||
|
||||
dify_api_key_masked: String(agent.dify_api_key_masked || ''),
|
||||
|
||||
description: agent.description || '',
|
||||
|
||||
type: agent.runtime_provider === 'iframe' ? 'iframe' : (agent.type || 'api'),
|
||||
|
||||
agent_code: agent.agent_code || 'generic',
|
||||
|
||||
runtime_provider: agent.runtime_provider || 'dify',
|
||||
|
||||
conversation_mode: agent.conversation_mode || 'chat',
|
||||
|
||||
dify_app_type: agent.dify_app_type === 'workflow' ? 'workflow' : 'chatflow',
|
||||
|
||||
api_base_url: agent.api_base_url || '',
|
||||
|
||||
iframe_url: String(agent.iframe_url || ''),
|
||||
|
||||
suggested_questions_style: agent.suggested_questions_style === 'styled' ? 'styled' : 'plain',
|
||||
|
||||
suggested_questions: Array.isArray(agent.suggested_questions)
|
||||
|
||||
? agent.suggested_questions.map((item) => ({
|
||||
|
||||
question: String((item as { question?: string }).question || '').trim(),
|
||||
|
||||
group: String((item as { group?: string }).group || '').trim(),
|
||||
|
||||
})).filter((item) => item.question)
|
||||
|
||||
: [],
|
||||
|
||||
welcome_message: String(agent.welcome_message || ''),
|
||||
|
||||
is_active: agent.is_active,
|
||||
|
||||
category: String(agent.category || ''),
|
||||
|
||||
sub_category: String(agent.sub_category || ''),
|
||||
|
||||
sort_order: Number.isFinite(Number(agent.sort_order)) ? Math.floor(Number(agent.sort_order)) : 0,
|
||||
|
||||
capabilities: {
|
||||
|
||||
...(defaultCapabilities || createEmptyAgentForm().capabilities),
|
||||
|
||||
...(agent.capabilities || {}),
|
||||
|
||||
},
|
||||
|
||||
intent_routes: normalizeIntentRoutes(handlerConfig.intent_routes),
|
||||
|
||||
content_profile: String(handlerConfig.content_profile || '').trim(),
|
||||
|
||||
bound_schedule_task_id: agent.bound_schedule_task_id ?? null,
|
||||
|
||||
poll_interval_seconds: Number(handlerConfig.poll_interval_seconds) > 0
|
||||
|
||||
? Math.min(Number(handlerConfig.poll_interval_seconds), 30)
|
||||
|
||||
: 2,
|
||||
|
||||
lock_input_when_running: handlerConfig.lock_input_when_running !== false,
|
||||
|
||||
tool_run_progress_enabled: agent.capabilities?.task_progress === true,
|
||||
|
||||
schedule_task_id: agent.bound_schedule_task_id ?? null,
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 构建 Admin create/update API 载荷(结构化列 + training extra_config)。
|
||||
|
||||
*/
|
||||
|
||||
export function buildAgentRegistryPayload(
|
||||
|
||||
form: AgentFormState,
|
||||
|
||||
options: {
|
||||
|
||||
editingExtraConfig?: Record<string, unknown>;
|
||||
|
||||
supportsToolRunProgress: boolean;
|
||||
|
||||
trainingExtraPatch: Record<string, unknown>;
|
||||
|
||||
typeCatalog?: AgentTypeCatalogEntry[];
|
||||
|
||||
},
|
||||
|
||||
): Record<string, unknown> {
|
||||
|
||||
const extra_config: Record<string, unknown> = {
|
||||
|
||||
...(options.editingExtraConfig || {}),
|
||||
|
||||
...options.trainingExtraPatch,
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
const capabilities = { ...form.capabilities };
|
||||
|
||||
const enableTaskProgress = form.capabilities.task_progress === true
|
||||
|
||||
|| (options.supportsToolRunProgress && form.tool_run_progress_enabled);
|
||||
|
||||
if (enableTaskProgress) {
|
||||
|
||||
capabilities.task_progress = true;
|
||||
|
||||
} else {
|
||||
|
||||
capabilities.task_progress = false;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
const catalogEntry = options.typeCatalog?.find((item) => item.agent_code === form.agent_code);
|
||||
|
||||
const handler_config = buildHandlerConfigPayload(form, catalogEntry);
|
||||
|
||||
|
||||
|
||||
const runtimeProvider = form.runtime_provider;
|
||||
|
||||
const legacyType = runtimeProvider === 'iframe' ? 'iframe' : 'api';
|
||||
|
||||
|
||||
|
||||
return {
|
||||
|
||||
name: form.name,
|
||||
|
||||
description: form.description,
|
||||
|
||||
is_active: form.is_active,
|
||||
|
||||
type: legacyType,
|
||||
|
||||
agent_code: form.agent_code,
|
||||
|
||||
runtime_provider: runtimeProvider,
|
||||
|
||||
conversation_mode: form.conversation_mode,
|
||||
|
||||
dify_app_type: form.dify_app_type,
|
||||
|
||||
dify_app_id: form.dify_app_id,
|
||||
|
||||
api_base_url: form.api_base_url,
|
||||
|
||||
iframe_url: form.iframe_url,
|
||||
|
||||
welcome_message: form.welcome_message || null,
|
||||
|
||||
suggested_questions_style: form.suggested_questions_style,
|
||||
|
||||
suggested_questions: form.suggested_questions
|
||||
|
||||
.map((item) => ({
|
||||
|
||||
question: String(item.question || '').trim(),
|
||||
|
||||
group: String(item.group || '').trim(),
|
||||
|
||||
}))
|
||||
|
||||
.filter((item) => item.question),
|
||||
|
||||
category: form.category.trim() || null,
|
||||
|
||||
sub_category: form.sub_category.trim() || null,
|
||||
|
||||
sort_order: form.sort_order,
|
||||
|
||||
capabilities,
|
||||
|
||||
bound_schedule_task_id: form.capabilities.task_progress === true || form.tool_run_progress_enabled
|
||||
|
||||
? (form.bound_schedule_task_id ?? form.schedule_task_id)
|
||||
|
||||
: null,
|
||||
|
||||
handler_config,
|
||||
|
||||
extra_config,
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
export { normalizeIntentRoutes };
|
||||
|
||||
/**
|
||||
* 将 content_profile 默认欢迎语/推荐问题写入表单(force 时覆盖已有内容)。
|
||||
*/
|
||||
export function applyContentProfileTemplate(
|
||||
form: AgentFormState,
|
||||
profileKey: string,
|
||||
templates: AdminContentProfileOption[],
|
||||
options?: { force?: boolean },
|
||||
): boolean {
|
||||
const template = templates.find((item) => item.key === profileKey);
|
||||
if (!template?.welcome_message) return false;
|
||||
const force = options?.force === true;
|
||||
if (force || !String(form.welcome_message || '').trim()) {
|
||||
form.welcome_message = template.welcome_message;
|
||||
}
|
||||
const hasQuestions = form.suggested_questions.some((item) => String(item.question || '').trim());
|
||||
if (force || !hasQuestions) {
|
||||
form.suggested_questions_style = template.suggested_questions_style === 'styled' ? 'styled' : 'plain';
|
||||
form.suggested_questions = (template.suggested_questions ?? []).map((item) => ({
|
||||
question: String(item.question || '').trim(),
|
||||
group: String(item.group || '').trim(),
|
||||
})).filter((item) => item.question);
|
||||
}
|
||||
form.content_profile = profileKey;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
* features/admin/modules/agents/composables/useAgentsTableColumnResize.ts
|
||||
*
|
||||
* 用途:应用管理列表表头列宽拖拽伸缩,并持久化到 localStorage。
|
||||
* 依赖:Vue ref/computed。
|
||||
* 逻辑:AgentsPage 绑定 colgroup 宽度;除最后一列(操作)外均可拖右缘调整。
|
||||
*/
|
||||
|
||||
import { computed, onBeforeUnmount, ref } from 'vue';
|
||||
|
||||
const STORAGE_KEY = 'hxops.admin.agents.tableColumnWidths';
|
||||
|
||||
/** 名称 / 类型 / 分类 / 配置 / 状态 / 操作 */
|
||||
const DEFAULT_WIDTHS = [220, 168, 128, 140, 96, 220] as const;
|
||||
|
||||
const MIN_WIDTHS = [140, 120, 100, 120, 80, 200] as const;
|
||||
|
||||
const COLUMN_COUNT = DEFAULT_WIDTHS.length;
|
||||
|
||||
function loadWidths(): number[] {
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY);
|
||||
if (!raw) return [...DEFAULT_WIDTHS];
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (!Array.isArray(parsed) || parsed.length !== COLUMN_COUNT) return [...DEFAULT_WIDTHS];
|
||||
return parsed.map((value, index) => {
|
||||
const width = Number(value);
|
||||
const fallback = DEFAULT_WIDTHS[index] ?? 120;
|
||||
const min = MIN_WIDTHS[index] ?? 80;
|
||||
return Number.isFinite(width) ? Math.max(min, Math.round(width)) : fallback;
|
||||
});
|
||||
} catch {
|
||||
return [...DEFAULT_WIDTHS];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理应用列表列宽与拖拽伸缩。
|
||||
* @returns columnWidths、tableMinWidth、startColumnResize、resetColumnWidths
|
||||
*/
|
||||
export function useAgentsTableColumnResize() {
|
||||
const columnWidths = ref<number[]>(loadWidths());
|
||||
|
||||
const resizeState = ref<{
|
||||
index: number;
|
||||
startX: number;
|
||||
startWidth: number;
|
||||
} | null>(null);
|
||||
|
||||
const tableMinWidth = computed(() => (
|
||||
columnWidths.value.reduce((sum, width) => sum + width, 0)
|
||||
));
|
||||
|
||||
const persistWidths = (): void => {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(columnWidths.value));
|
||||
};
|
||||
|
||||
const onResizeMove = (event: MouseEvent): void => {
|
||||
if (!resizeState.value) return;
|
||||
const { index, startX, startWidth } = resizeState.value;
|
||||
const min = MIN_WIDTHS[index] ?? 80;
|
||||
const next = Math.max(min, startWidth + (event.clientX - startX));
|
||||
columnWidths.value = columnWidths.value.map((width, colIndex) => (
|
||||
colIndex === index ? next : width
|
||||
));
|
||||
};
|
||||
|
||||
const stopResize = (): void => {
|
||||
if (!resizeState.value) return;
|
||||
resizeState.value = null;
|
||||
persistWidths();
|
||||
document.removeEventListener('mousemove', onResizeMove);
|
||||
document.removeEventListener('mouseup', stopResize);
|
||||
document.body.style.cursor = '';
|
||||
document.body.style.userSelect = '';
|
||||
};
|
||||
|
||||
/**
|
||||
* 开始拖拽指定列的右缘以调整宽度。
|
||||
* @param index - 列索引(0-based);最后一列不提供手柄。
|
||||
*/
|
||||
const startColumnResize = (index: number, event: MouseEvent): void => {
|
||||
if (index < 0 || index >= COLUMN_COUNT - 1) return;
|
||||
resizeState.value = {
|
||||
index,
|
||||
startX: event.clientX,
|
||||
startWidth: columnWidths.value[index] ?? DEFAULT_WIDTHS[index] ?? 120,
|
||||
};
|
||||
document.addEventListener('mousemove', onResizeMove);
|
||||
document.addEventListener('mouseup', stopResize);
|
||||
document.body.style.cursor = 'col-resize';
|
||||
document.body.style.userSelect = 'none';
|
||||
};
|
||||
|
||||
/** 恢复默认列宽并清除 localStorage 缓存。 */
|
||||
const resetColumnWidths = (): void => {
|
||||
columnWidths.value = [...DEFAULT_WIDTHS];
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
};
|
||||
|
||||
onBeforeUnmount(stopResize);
|
||||
|
||||
return {
|
||||
columnWidths,
|
||||
tableMinWidth,
|
||||
startColumnResize,
|
||||
resetColumnWidths,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user