feat(agent): 增强 Agent 配置,新增结构化字段与聊天功能支持

This commit is contained in:
hugo committed 2026-07-07 11:10:32 +08:00
1 parent ac4262cd75
commit c8ce77199e
183 files changed
+11690 -2300

No files matched your search

@@ -94,6 +94,71 @@ export const deleteAdminDepartment = (id: number) =>
requestJson(`/api/admin/departments/${id}`, { method: 'DELETE', ...auth() });
// Agents
export interface AdminAgentRegistrySchema {
platform: {
runtime_providers: string[];
conversation_modes: string[];
dify_app_types: string[];
suggested_questions_styles: string[];
default_capabilities: Record<string, boolean>;
tool_run_progress_defaults: {
progress_type?: string;
poll_interval_seconds?: number;
lock_input_when_running?: boolean;
};
};
agent_types: Array<{
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>;
}>;
handler_config_schemas: Record<string, unknown>;
content_profile_keys: string[];
}
export const getAdminAgentRegistrySchema = () =>
requestJson<AdminAgentRegistrySchema>('/api/admin/agents/schema', auth());
export const inferAdminContentProfile = (intentRoutes: string[]) =>
requestJson<{ content_profile: string | null }>('/api/admin/agents/infer-content-profile', {
method: 'POST',
...jsonAuth(),
body: JSON.stringify({ intent_routes: intentRoutes }),
});
export const listAdminAgentTypeCatalog = () =>
getAdminAgentRegistrySchema().then((schema) => schema.agent_types);
export interface AdminIntentRouteOption {
key: string;
label: string;
description?: string;
category?: string;
enabled?: boolean;
sort_order?: number;
}
export const listAdminIntentRoutes = () =>
requestJson<AdminIntentRouteOption[]>('/api/admin/agents/intent-routes', auth());
export interface AdminContentProfileOption {
key: string;
label: string;
description?: string;
welcome_message?: string;
suggested_questions_style?: 'plain' | 'styled';
suggested_questions?: Array<{ question: string; group?: string }>;
}
export const listAdminContentProfiles = () =>
requestJson<AdminContentProfileOption[]>('/api/admin/agents/content-profiles', auth());
export const listAdminAgents = () => requestJson<any[]>('/api/admin/agents', auth());
export const createAdminAgent = (payload: Record<string, unknown>) =>
requestJson('/api/admin/agents', { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload) });
@@ -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>
@@ -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,
};
}
@@ -5,19 +5,43 @@
*/
import type { TrainingQuestionType } from '@/features/chat/training/training.types';
export type AgentRuntimeProvider = 'dify' | 'builtin' | 'hybrid' | 'iframe';
export type AgentConversationMode = 'chat' | 'task_chat' | 'embedded';
export interface AgentCapabilities {
streaming: boolean;
file_upload: boolean;
task_progress: boolean;
human_confirm: boolean;
source_citation: boolean;
guide: boolean;
erp_kb?: boolean;
}
export interface AgentRow {
id: number;
name: string;
dify_app_id: string;
dify_api_key: string;
dify_api_key_masked?: string;
is_active: boolean;
description?: string;
type: 'api' | 'iframe';
agent_code?: string;
runtime_provider?: AgentRuntimeProvider;
conversation_mode?: AgentConversationMode;
dify_app_type?: 'chatflow' | 'workflow';
api_base_url?: string;
extra_config?: Record<string, unknown>;
/** 表单编辑时的 iframe 地址辅助字段 */
iframe_url?: string;
welcome_message?: string | null;
suggested_questions_style?: 'plain' | 'styled';
suggested_questions?: AgentSuggestedQuestionItem[];
category?: string | null;
sub_category?: string | null;
sort_order?: number;
capabilities?: AgentCapabilities;
bound_schedule_task_id?: number | null;
handler_config?: Record<string, unknown> | null;
extra_config?: Record<string, unknown>;
}
export interface AgentSuggestedQuestionItem {
@@ -55,24 +79,30 @@ export interface AgentFormState {
id?: number;
name: string;
dify_app_id: string;
/** Write-only:表单输入新 key;编辑时留空表示保留服务端已有 key。 */
dify_api_key: string;
/** 编辑态展示已配置 key 的脱敏值(来自 API dify_api_key_masked)。 */
dify_api_key_masked: string;
description: string;
type: 'api' | 'iframe';
agent_code: string;
runtime_provider: AgentRuntimeProvider;
conversation_mode: AgentConversationMode;
dify_app_type: 'chatflow' | 'workflow';
api_base_url: string;
iframe_url: string;
welcome_message: string;
suggested_questions_style: 'plain' | 'styled';
suggested_questions: AgentSuggestedQuestionItem[];
is_active: boolean;
/** 一级分类,写入 extra_config.category */
category: string;
/** 二级分类,写入 extra_config.sub_category */
sub_category: string;
/** 排序权重,写入 extra_config.sort_order */
sort_order: number;
/** 是否启用 extra_config.capabilities 中的 tool_run_progress */
capabilities: AgentCapabilities;
intent_routes: string[];
content_profile: string;
bound_schedule_task_id: number | null;
tool_run_progress_enabled: boolean;
/** 对应 ScheduleTask.id,写入 extra_config.tool_run_progress.schedule_task_id */
schedule_task_id: number | null;
poll_interval_seconds: number;
lock_input_when_running: boolean;
@@ -92,21 +122,41 @@ export const createEmptyTrainingQuestionForm = (): AgentTrainingQuestionFormItem
answer: 'a',
});
export const createEmptyAgentForm = (): AgentFormState => ({
export const createEmptyAgentForm = (
defaultCapabilities?: Partial<AgentCapabilities>,
): AgentFormState => ({
name: '',
dify_app_id: '',
dify_api_key: '',
dify_api_key_masked: '',
description: '',
type: 'api',
agent_code: 'generic',
runtime_provider: 'dify',
conversation_mode: 'chat',
dify_app_type: 'chatflow',
api_base_url: '',
iframe_url: '',
welcome_message: '',
suggested_questions_style: 'plain',
suggested_questions: [],
is_active: true,
category: '',
sub_category: '',
sort_order: 0,
capabilities: {
streaming: true,
file_upload: false,
task_progress: false,
human_confirm: false,
source_citation: true,
guide: true,
erp_kb: false,
...defaultCapabilities,
},
intent_routes: [],
content_profile: '',
bound_schedule_task_id: null,
tool_run_progress_enabled: false,
schedule_task_id: null,
poll_interval_seconds: 2,
@@ -33,6 +33,7 @@ type ShippingApiStatusPayload = {
export type ShippingChatAgentOption = {
id: number;
name: string;
agent_code?: string;
};
function jsonPost(body?: unknown): RequestInit {
@@ -447,8 +448,8 @@ export async function generateWorkspaceShippingExcel(taskNo: string) {
return assertShippingOk(body);
}
/** 货代发货 Agent 显示名称,用于聊天路由与 Agent 匹配。 */
export const SHIPPING_NOTICE_AGENT_NAME = '货代发货通知 Agent';
/** 发货通知 Agent 应用类型标识(运行时识别)。 */
export const SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice';
export type {
ShippingBatchSummary,
@@ -14,6 +14,7 @@ import {
Mic,
Paperclip,
Send,
Square,
X,
} from 'lucide-vue-next';
import type { PendingAttachment } from '../types/shipping.types';
@@ -51,6 +52,7 @@ const props = defineProps<{
const emit = defineEmits<{
send: [];
stop: [];
'voice-click': [];
'remove-attachment': [id: string];
'local-files-selected': [event: Event];
@@ -386,6 +388,17 @@ watch(
</div>
<button
v-if="isThinking && !isUploadingAttachments"
type="button"
class="flex h-10 w-10 items-center justify-center rounded-full border border-rose-300 bg-rose-50 text-rose-600 shadow-sm transition-all duration-200 hover:scale-105 hover:bg-rose-100 active:scale-95"
:title="$t('chat.stopGenerating')"
:aria-label="$t('chat.stopGenerating')"
@click="emit('stop')"
>
<Square class="h-4 w-4 fill-current" />
</button>
<button
v-else
type="button"
:disabled="!canSendMessage"
class="flex h-10 w-10 items-center justify-center rounded-full border shadow-sm transition-all duration-200 disabled:cursor-not-allowed disabled:opacity-50"
@@ -394,7 +407,7 @@ watch(
: 'border-brand-500 bg-brand-500 text-white shadow-[0_0_0_4px_rgba(59,130,246,0.18)] hover:scale-105 hover:bg-brand-600 hover:shadow-[0_0_0_6px_rgba(59,130,246,0.24)] active:scale-95'"
@click="emit('send')"
>
<Loader2 v-if="isUploadingAttachments || isThinking" class="h-4 w-4 animate-spin" />
<Loader2 v-if="isUploadingAttachments" class="h-4 w-4 animate-spin" />
<Send v-else class="h-4 w-4" />
</button>
</div>
@@ -5,7 +5,7 @@
* 逻辑:由聊天页面传入当前 Agent、历史记录与用户可用 Agent;通过事件把新会话、切换 Agent、反馈等操作回传给页面。
*/
<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from 'vue';
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
import {
BookOpen,
Briefcase,
@@ -25,6 +25,7 @@ import {
} from 'lucide-vue-next';
import LocaleToggleButton from '@/shared/components/LocaleToggleButton.vue';
import AgentCategoryList from '@/shared/components/AgentCategoryList.vue';
import { isHrFocusedAgent, type AgentRegistryFields } from '@/shared/utils/agent-registry.utils';
import type { AgentWithCategory } from '@/shared/utils/agent-category.utils';
import type { DisplayHistoryItem } from '../types/chat.types';
@@ -33,9 +34,9 @@ export interface ChatSidebarAgent extends AgentWithCategory {}
const collapsed = defineModel<boolean>('collapsed', { required: true });
const agentPanelOpen = defineModel<boolean>('agentPanelOpen', { required: true });
const { currentUser } = defineProps<{
const props = defineProps<{
isOpen: boolean;
currentAgent: { name?: string } | null;
currentAgent: AgentRegistryFields | null;
currentAgentId: number;
agentDescription: string;
hasAgentGuides: boolean;
@@ -95,8 +96,10 @@ const onGoAdmin = () => {
emit('go-admin');
};
const agentAvatarLabel = computed(() => (isHrFocusedAgent(props.currentAgent) ? 'HR' : 'AI'));
const userInitial = (fallback: string) => {
const name = String(currentUser?.username ?? '').trim();
const name = String(props.currentUser?.username ?? '').trim();
return (name || fallback).charAt(0).toUpperCase();
};
</script>
@@ -143,7 +146,7 @@ const userInitial = (fallback: string) => {
<div class="flex items-center justify-between p-4">
<div class="flex w-full min-w-0 items-center gap-3">
<div class="flex h-8 w-8 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-sm font-bold text-white shadow-sm shadow-brand-500/25">
{{ currentAgent?.name === '人事规章' ? 'HR' : 'AI' }}
{{ agentAvatarLabel }}
</div>
<div class="group relative flex min-w-0 flex-1 flex-col justify-center">
<div class="flex items-center gap-2">
@@ -20,12 +20,16 @@ import LedgerConfigPanel from '@/features/maintenance/components/LedgerConfigPan
import MaintenanceRecordManagerPanel from '@/features/maintenance/components/MaintenanceRecordManagerPanel.vue';
import { useChatPageContext } from '@/features/chat/composables/chat.context';
import { matchesTrainingAgent } from '@/features/chat/training/trainingWorkspace.utils';
import { agentHasIntentUiProfile } from '@/shared/utils/agent-registry.utils';
const page = useChatPageContext();
const isTrainingAgentPage = computed(() => matchesTrainingAgent(page.currentAgent));
const isMaintenanceAgentPage = computed(() => {
const name = String(page.currentAgent?.name || '').trim();
return name === '设备维保助手' || (name.includes('设备维保') && name.includes('助手'));
const isMaintenanceAgentPage = computed(() => agentHasIntentUiProfile(page.currentAgent, 'maintenance'));
const embeddedIframeSrc = computed(() => {
const agent = page.currentAgent;
if (!agent) return undefined;
const url = agent.iframe_url;
return url ? String(url) : undefined;
});
const hideWelcomePanel = computed(() => isTrainingAgentPage.value);
const isTrainingWorkspaceExpanded = ref(false);
@@ -132,9 +136,9 @@ watch(() => page.currentAgentId, () => {
<p class="text-sm animate-pulse text-muted">{{ $t('chat.loadingAgent') }}</p>
</div>
<div v-else-if="page.currentAgent.type === 'iframe'" class="relative h-full w-full flex-1">
<div v-else-if="page.currentAgent.runtime_provider === 'iframe' || page.currentAgent.conversation_mode === 'embedded'" class="relative h-full w-full flex-1">
<iframe
:src="page.currentAgent.extra_config?.iframe_url"
:src="embeddedIframeSrc"
class="h-full w-full border-0 bg-surface"
allow="microphone; camera; clipboard-read; clipboard-write"
/>
@@ -227,6 +231,7 @@ watch(() => page.currentAgentId, () => {
:shipping-notice-picker-ref-holder="page.shippingNoticePickerRefHolder"
:get-kb-label="page.getKbLabel"
@send="page.handleSend()"
@stop="page.stopActiveGeneration()"
@voice-click="page.handleVoiceFeatureClick"
@remove-attachment="page.removeAttachment"
@local-files-selected="page.handleLocalFilesSelected"
@@ -85,6 +85,21 @@ const isResumableTask = (task: ShippingTaskSummary | ShippingTaskDetail) =>
const resolveWorkspaceActionButtons = (task: ShippingTaskSummary | ShippingTaskDetail): ShippingChatAction[] =>
resolveShippingWorkspaceActionButtons(task);
const rpaRuntimeMode = (task: ShippingTaskSummary | ShippingTaskDetail) =>
String(task.rpa_runtime?.mode || '').trim().toLowerCase();
const rpaRuntimeLabel = (task: ShippingTaskSummary | ShippingTaskDetail) => {
const mode = rpaRuntimeMode(task);
if (mode === 'mock') return t('chat.shippingNoticeUi.rpaModeMock');
if (mode === 'browser') return t('chat.shippingNoticeUi.rpaModeBrowser');
return String(task.rpa_runtime?.label || '').trim() || t('chat.shippingNoticeUi.rpaModeUnknown');
};
const rpaRuntimeBadgeClass = (task: ShippingTaskSummary | ShippingTaskDetail) =>
rpaRuntimeMode(task) === 'mock'
? 'border-amber-200 bg-amber-50 text-amber-700'
: 'border-emerald-200 bg-emerald-50 text-emerald-700';
/**
* 渲染工作台任务卡中的辅助动作按钮样式。
* 核心逻辑:把“聚焦当前任务 / 查询缺口明细”降级成轻量辅助入口,避免与后端主业务动作抢视觉权重。
@@ -503,7 +518,16 @@ const handleSwitchBatch = (batchNo: string) => {
<div class="mt-0.5 truncate text-xs text-muted">
{{ task.source_file_name || task.customer_name || t('chat.shippingNoticeUi.currentNotice') }}
</div>
<div class="mt-1 text-xs font-medium text-secondary">{{ taskStepHeadline(task) }}</div>
<div class="mt-1 flex flex-wrap items-center gap-1.5 text-xs font-medium text-secondary">
<span>{{ taskStepHeadline(task) }}</span>
<span
v-if="task.rpa_runtime"
class="rounded border px-1.5 py-0.5 text-[10px] font-bold leading-none"
:class="rpaRuntimeBadgeClass(task)"
>
{{ rpaRuntimeLabel(task) }}
</span>
</div>
</div>
<span class="rounded border px-2 py-1 text-[10px] font-bold" :class="resolveTaskStateMeta(task).className">
{{ resolveTaskStateMeta(task).text }}
@@ -8,6 +8,7 @@ import { getAuthHeaders } from '@/shared/utils/auth';
import { applyStreamErrorToMessage, type StreamErrorLabels } from '../utils/streamErrorMessage';
import type { ChatMessage, ChatRun, RetrieverResource } from '../types/chat.types';
import type { ShippingBatchUiState, ShippingTaskUiState } from '../types/shipping.api.types';
import { createStartChatTurn } from './useChatTurn';
export interface SendMessageLifecycleHooks {
onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void>;
@@ -300,9 +301,14 @@ export function useChat() {
activeRunId.value = runId;
};
/**
* 打开空白新会话视图:仅脱离当前流与视图绑定,不 abort 后台 SSE。
*
* 核心逻辑:与 loadConversationState 一致;旧 run 继续在 runs 中更新,并在侧栏显示为「生成中」。
*/
const createNewChatView = () => {
clearLikelyCompletedStreamTimer();
cancelActiveStream();
detachActiveStreamFromView();
viewId.value += 1;
messages.value = [];
conversationId.value = null;
@@ -310,6 +316,25 @@ export function useChat() {
activeRunId.value = null;
};
/**
* 用户显式点击「停止生成」时中止当前可见 run 的流式请求。
*
* 核心逻辑:优先 abort 活动视图绑定的 controller;若已 detach,则回退到 run 上保存的 controller。
*/
const stopActiveGeneration = () => {
clearLikelyCompletedStreamTimer();
const run = activeRunId.value != null
? runs.value.find((r) => r.runId === activeRunId.value)
: undefined;
const controller = activeStreamController.value ?? run?.abortController ?? null;
if (!controller) return;
controller.abort();
activeStreamController.value = null;
if (run && messages.value === run.messages) {
isThinking.value = false;
}
};
const loadConversationState = (id: string, nextMessages: ChatMessage[]) => {
clearLikelyCompletedStreamTimer();
detachActiveStreamFromView();
@@ -388,6 +413,18 @@ export function useChat() {
generic: t('chat.streamError.generic'),
});
const { startChatTurn } = createStartChatTurn({
messages,
isThinking,
conversationId,
viewId,
runs,
activeRunId,
activeStreamController,
streamErrorLabels,
formatStreamError,
});
const sendMessage = async (
query: string,
agentId: number,
@@ -420,6 +457,7 @@ export function useChat() {
conversationId: conversationId.value,
status: 'running',
createdAt: new Date().toISOString(),
abortController: controller,
};
runs.value.unshift(run);
if (runs.value.length > 30) runs.value = runs.value.slice(0, 30);
@@ -634,6 +672,9 @@ export function useChat() {
if (activeStreamController.value === controller) {
activeStreamController.value = null;
}
if (run.abortController === controller) {
delete run.abortController;
}
if (messages.value === runMessages) {
isThinking.value = false;
}
@@ -657,5 +698,7 @@ export function useChat() {
createNewChatView,
loadConversationState,
sendMessage,
startChatTurn,
stopActiveGeneration,
};
}
@@ -7,6 +7,11 @@ import { BusinessError } from '@/shared/api/client';
import { getUserAgent, listUserAgents } from '@/features/auth/api/user.api';
import { setLastChatAgentId } from '@/shared/utils/lastChatAgent';
import { sortAgentsByCategory } from '@/shared/utils/agent-category.utils';
import {
agentHasErpKb,
type AgentRegistryFields,
} from '@/shared/utils/agent-registry.utils';
import { matchesTrainingAgent } from '../training/trainingWorkspace.utils';
import type { ChatDeps } from './chat.deps';
import type { UseChatGuidesReturn } from './useChatGuides';
@@ -17,41 +22,9 @@ export type AgentSuggestedQuestionItem = {
const DEFAULT_KB = '企业知识库';
const ERP_KB = 'ERP知识库';
const ERP_KB_ENABLED_AGENT_NAMES = new Set(['固资管理']);
const TRAINING_AGENT_NAME_PATTERN = /(培训|考试|入职)/;
const isTrainingAgentName = (name: string) => TRAINING_AGENT_NAME_PATTERN.test(name);
const DEFAULT_AGENT_DESCRIPTIONS: Record<string, string> = {
人事规章: '我是你的7x24小时专属HR政策助手。无需手动检索文档,只需用日常说话的方式提问,我能从公司最新、最全的规章制度中,为你精准提取并总结答案。',
通用入口: '我是你的7x24小时专属AI数字人。无需手动检索文档,只需用日常说话的方式提问,我能从公司最新、最全的人事规章制度中,为你精准提取并总结答案。',
};
const DEFAULT_AGENT_SUGGESTED_QUESTIONS: Record<string, { style: 'plain' | 'styled'; questions: AgentSuggestedQuestionItem[] }> = {
人事规章: {
style: 'styled',
questions: [
{ question: '查询我有多少假期?', group: '考勤与休假' },
{ question: '如何进行请假?', group: '考勤与休假' },
{ question: '查公司法定节假日?', group: '考勤与休假' },
{ question: '新员工入职须知', group: '规章与日常' },
{ question: '怎么开具在职证明?', group: '规章与日常' },
{ question: '查公司薪酬及福利待遇怎么样?', group: '规章与日常' },
],
},
通用入口: {
style: 'plain',
questions: [
{ question: '新员工入职须知', group: '' },
{ question: '查询我有多少假期?', group: '' },
{ question: '如何进行请假?', group: '' },
{ question: '查公司法定节假日?', group: '' },
{ question: '查公司薪酬及福利待遇怎么样?', group: '' },
],
},
};
const TRAINING_AGENT_DESCRIPTION = '我是你的新人培训助手,会在同一个聊天页面内带你完成视频学习、知识点复盘、逐题考试和结果复盘。';
const TRAINING_AGENT_DESCRIPTION =
'我是你的新人培训助手,会在同一个聊天页面内带你完成视频学习、知识点复盘、逐题考试和结果复盘。';
const TRAINING_AGENT_QUESTIONS: AgentSuggestedQuestionItem[] = [
{ question: '开始新人培训', group: '培训流程' },
@@ -87,8 +60,8 @@ export function useChatAgent(options: UseChatAgentOptions) {
const { deps, currentAgentId, chatGuides } = options;
const { t, msg, router } = deps;
const currentAgent = ref<any>(null);
const userAgents = ref<Array<{
const currentAgent = ref<AgentRegistryFields | null>(null);
const userAgents = ref<Array<AgentRegistryFields & {
id: number;
name: string;
description: string;
@@ -108,8 +81,7 @@ export function useChatAgent(options: UseChatAgentOptions) {
return kb;
};
const currentAgentName = computed(() => String(currentAgent.value?.name || '').trim());
const canSelectErpKnowledgeBase = computed(() => ERP_KB_ENABLED_AGENT_NAMES.has(currentAgentName.value));
const canSelectErpKnowledgeBase = computed(() => agentHasErpKb(currentAgent.value));
const availableKbOptions = computed(() => (
canSelectErpKnowledgeBase.value
? kbOptions
@@ -118,7 +90,6 @@ export function useChatAgent(options: UseChatAgentOptions) {
const kbDropdownDisabled = computed(() => availableKbOptions.value.length <= 1);
watch(canSelectErpKnowledgeBase, (allowed) => {
// 固资管理默认先走企业知识库,用户可手动切换到 ERP 知识库。
if (allowed) {
selectedKb.value = DEFAULT_KB;
return;
@@ -129,26 +100,28 @@ export function useChatAgent(options: UseChatAgentOptions) {
}, { immediate: true });
const agentDescription = computed(() => {
const welcome = String(currentAgent.value?.welcome_message || '').trim();
if (welcome) return welcome;
const text = String(currentAgent.value?.description || '').trim();
if (!text && isTrainingAgentName(currentAgentName.value)) return TRAINING_AGENT_DESCRIPTION;
return text || DEFAULT_AGENT_DESCRIPTIONS[currentAgentName.value] || '';
if (!text && matchesTrainingAgent(currentAgent.value)) return TRAINING_AGENT_DESCRIPTION;
return text;
});
const suggestedQuestionsStyle = computed<'plain' | 'styled'>(() => {
const style = String(currentAgent.value?.extra_config?.suggested_questions_style || '').trim().toLowerCase();
const style = String(currentAgent.value?.suggested_questions_style || '').trim().toLowerCase();
if (style === 'styled') return 'styled';
if (style === 'plain') return 'plain';
if (isTrainingAgentName(currentAgentName.value)) return 'styled';
return DEFAULT_AGENT_SUGGESTED_QUESTIONS[currentAgentName.value]?.style || 'plain';
if (matchesTrainingAgent(currentAgent.value)) return 'styled';
return 'plain';
});
const agentSuggestedQuestions = computed<AgentSuggestedQuestionItem[]>(() => {
const configured = normalizeAgentSuggestedQuestions(
currentAgent.value?.suggested_questions ?? currentAgent.value?.extra_config?.suggested_questions,
currentAgent.value?.suggested_questions,
);
if (configured.length > 0) return configured;
if (isTrainingAgentName(currentAgentName.value)) return TRAINING_AGENT_QUESTIONS;
return DEFAULT_AGENT_SUGGESTED_QUESTIONS[currentAgentName.value]?.questions || [];
if (matchesTrainingAgent(currentAgent.value)) return TRAINING_AGENT_QUESTIONS;
return [];
});
const styledSuggestedQuestionSections = computed(() => {
@@ -191,7 +164,6 @@ export function useChatAgent(options: UseChatAgentOptions) {
? agents.filter((a: any) => (a.dify_app_type || 'chatflow') === 'chatflow')
: [];
userAgents.value = sortAgentsByCategory(filtered);
// [STEP 1] 有可切换智能体时默认展开面板;避免切换 Agent 后列表「消失」
showAgentPanel.value = userAgents.value.length > 0;
} catch {
userAgents.value = [];
@@ -77,6 +77,32 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
});
const attachmentPolicy = computed(() => {
const fileUploadAllowed = currentAgent.value?.capabilities?.file_upload;
if (fileUploadAllowed === false) {
return {
anyEnabled: false,
enabled: {
image: { local: false, remote: false },
document: { local: false, remote: false },
audio: { local: false, remote: false },
video: { local: false, remote: false },
custom: { local: false, remote: false },
},
sizeLimitMb: {
image: null,
audio: null,
video: null,
document: null,
custom: null,
},
canLocal: false,
canRemote: false,
accept: '',
allowedExts: null,
totalLimit: null,
};
}
const types: ChatUploadFileType[] = ['image', 'document', 'audio', 'video', 'custom'];
const enabled: Record<ChatUploadFileType, { local: boolean; remote: boolean; limit?: number }> = {
image: { local: false, remote: false },
@@ -9,7 +9,9 @@
*/
import { computed, type ComputedRef, type Ref } from 'vue';
import { getUserProfile } from '@/features/auth/api/user.api';
import { LEAVE_FEATURE_AGENT_NAMES, LEAVE_TYPES } from '../constants/leave';
import { canUseLeaveFeature as resolveLeaveFeatureEnabled } from '@/shared/utils/agent-registry.utils';
import type { AgentRegistryFields } from '@/shared/utils/agent-registry.utils';
import { LEAVE_TYPES } from '../constants/leave';
import {
createLeaveAgentPickerApi,
createLeaveFlowApi,
@@ -30,7 +32,7 @@ import type { ChatDeps } from './chat.deps';
export interface UseChatLeaveOptions {
deps: ChatDeps;
currentAgent: Ref<{ name?: string } | null>;
currentAgent: Ref<AgentRegistryFields | null>;
currentAgentId: ComputedRef<number>;
currentUser: Ref<Record<string, unknown> | null>;
currentUserDisplayName: ComputedRef<string>;
@@ -57,9 +59,7 @@ export function useChatLeave(options: UseChatLeaveOptions) {
loadHistory,
} = options;
const canUseLeaveFeature = computed(() =>
LEAVE_FEATURE_AGENT_NAMES.has(String(currentAgent.value?.name || '').trim()),
);
const canUseLeaveFeature = computed(() => resolveLeaveFeatureEnabled(currentAgent.value));
const { newLocalMessageId, saveLocalMessageToBackend } = createLeaveLocalMessageApi({
conversationId,
@@ -115,6 +115,8 @@ export function useChatPage() {
createNewChatView,
loadConversationState,
sendMessage,
startChatTurn,
stopActiveGeneration,
} = useChat();
const shippingActionBusy = computed(() => hasActiveRunningChatRun(
isThinking.value,
@@ -284,6 +286,7 @@ export function useChatPage() {
newLocalMessageId,
stripReasoningPrelude,
sendMessage,
startChatTurn,
buildFileSpecsForSend: attachmentApi.buildFileSpecsForSend,
loadConversation: (id, opts) => loadConversation(id, opts),
createNewChatView,
@@ -538,6 +541,7 @@ export function useChatPage() {
shouldRenderMessage: markdown.shouldRenderMessage,
canSendMessage: sendApi.canSendMessage,
handleSend: sendApi.handleSend,
stopActiveGeneration,
pushLocalAssistantMessage,
copyToClipboard: sendApi.copyToClipboard,
regenerate: sendApi.regenerate,
@@ -13,14 +13,14 @@ import {
type ComputedRef,
type Ref,
} from 'vue';
import { SHIPPING_NOTICE_AGENT_NAME } from '@/features/chat/api/shipping.api';
import { isShippingNoticeAgent as resolveShippingNoticeAgent } from '@/shared/utils/agent-registry.utils';
import type { AgentRegistryFields } from '@/shared/utils/agent-registry.utils';
import { hasActiveRunningChatRun } from '../shipping/shippingActionBusy';
import {
createShippingActionsRefresher,
createShippingConversationHelpers,
createShippingDecisionHandlers,
createShippingLocalMessages,
createShippingMappingFormHandlers,
createShippingMenuHandlers,
createShippingParseReviewHandlers,
@@ -49,8 +49,8 @@ import {
type ShippingTaskDetail,
type ShippingTaskSummary,
} from '@/features/chat/api/shipping.api';
import { buildShippingQueryShortageTurn } from '../shipping/shippingTurnActions';
import {
buildShortageDetailsMessage,
hasShortageLines,
isShippingShortageQueryIntent,
} from '../shipping/shippingShortageDetails';
@@ -62,7 +62,7 @@ import { listChatMessages } from '../api/chat.api';
export interface UseChatShippingOptions {
deps: ChatDeps;
currentAgent: Ref<{ name?: string } | null>;
currentAgent: Ref<AgentRegistryFields | null>;
currentAgentId: ComputedRef<number>;
messages: Ref<ChatMessage[]>;
conversationId: Ref<string | null>;
@@ -90,6 +90,7 @@ export interface UseChatShippingOptions {
context?: { task_id?: string; batch_no?: string; display_query?: string },
hooks?: { onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void> },
) => Promise<void>;
startChatTurn: (options: import('../types/chat-turn.types').StartChatTurnOptions) => Promise<boolean>;
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
loadConversation: (id: string, options?: { force?: boolean }) => Promise<void>;
createNewChatView: () => void;
@@ -154,6 +155,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
newLocalMessageId,
stripReasoningPrelude,
sendMessage,
startChatTurn,
buildFileSpecsForSend,
loadConversation,
createNewChatView,
@@ -165,7 +167,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
};
// ── 功能开关与 UI refs ────────────────────────────────────
const isShippingNoticeAgent = computed(() => currentAgent.value?.name === SHIPPING_NOTICE_AGENT_NAME);
const isShippingNoticeAgent = computed(() => resolveShippingNoticeAgent(currentAgent.value));
const isShippingActionBusy = computed(() => {
if (shippingActionBusy.value) return true;
return hasActiveRunningChatRun(isThinking.value, activeRunId.value, runs.value);
@@ -525,10 +527,23 @@ export function useChatShipping(options: UseChatShippingOptions) {
getActiveBatchTaskId,
});
const { pushShippingLocalUserMessage, pushShippingLocalAssistantMessage } = createShippingLocalMessages({
const {
openShippingInventoryMappingFormForTask,
applyShippingInventoryMappingForm,
reuploadShippingInventoryFromMappingForm,
} = createShippingMappingFormHandlers({
messages,
chatScrollContainer,
shippingInventorySchemaPreviewCache,
shippingInventoryPickerRef,
pendingShippingUploadTaskId,
resolvedShippingTaskId,
newLocalMessageId,
saveLocalMessageToBackend,
startChatTurn,
currentAgentId,
refreshShippingActions,
msg,
});
/**
@@ -573,10 +588,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
};
/**
* 在聊天流中输出确定性的缺口明细。
*
* 核心逻辑:追加一条本地用户意图消息和一条本地助手事实回复,不转发给 Dify,
* 避免大模型复述或重新计算预订单、料号与缺口数量。
* 在聊天流中输出确定性的缺口明细(Chat Turn SSE)。
*/
const queryShippingShortageDetails = async (taskNo?: string, displayText?: string) => {
const task = await resolveShippingTaskForShortageQuery(taskNo);
@@ -584,8 +596,19 @@ export function useChatShipping(options: UseChatShippingOptions) {
msg.warning(t('chat.shippingNoticeMissingTaskId'));
return true;
}
await pushShippingLocalUserMessage(displayText || t('chat.shippingNoticeUi.queryShortageDetails'));
await pushShippingLocalAssistantMessage(buildShortageDetailsMessage(task, t));
const normalizedTaskNo = String(task.task_no || '').trim().toUpperCase();
const turn = buildShippingQueryShortageTurn(
normalizedTaskNo,
displayText || t('chat.shippingNoticeUi.queryShortageDetails'),
);
await startChatTurn({
agentId: currentAgentId.value,
inputType: 'action',
displayText: turn.displayText,
actionType: turn.actionType,
payload: turn.payload,
refs: turn.refs,
});
return true;
};
@@ -599,36 +622,19 @@ export function useChatShipping(options: UseChatShippingOptions) {
sendMessage,
});
const {
openShippingInventoryMappingFormForTask,
applyShippingInventoryMappingForm,
reuploadShippingInventoryFromMappingForm,
} = createShippingMappingFormHandlers({
messages,
chatScrollContainer,
shippingInventorySchemaPreviewCache,
shippingInventoryPickerRef,
pendingShippingUploadTaskId,
resolvedShippingTaskId,
newLocalMessageId,
saveLocalMessageToBackend,
pushShippingLocalAssistantMessage,
refreshShippingActions,
msg,
});
const { executeShippingDecision, executeShippingManualUpload } = createShippingDecisionHandlers({
messages,
conversationId,
history,
isShippingNoticeAgent,
currentAgentId,
shippingInventorySchemaPreviewCache,
getActiveShippingTaskId,
newLocalMessageId,
saveLocalMessageToBackend,
getActiveShippingBatchNo: () => resolvedShippingBatchNo.value || shippingBatchNoFromQuery.value || '',
loadHistory,
openShippingInventoryMappingFormForTask,
refreshShippingActions,
startChatTurn,
msg,
t,
});
@@ -660,6 +666,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
useShippingSuggestedPrompt,
} = createShippingUploadHandlers({
conversationId,
currentAgentId,
attachments,
input,
shippingAutoFlowRequested,
@@ -676,9 +683,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
shippingInventorySelectionTaskId,
shippingInventorySchemaPreviewCache,
getActiveShippingTaskId,
sendShippingMenuMessage,
pushShippingLocalUserMessage,
pushShippingLocalAssistantMessage,
startChatTurn,
refreshShippingActions,
msg,
t,
@@ -686,10 +691,10 @@ export function useChatShipping(options: UseChatShippingOptions) {
const { handleShippingMenuAction, handleShippingActionClick } = createShippingMenuHandlers({
isThinking,
currentAgentId,
getActiveShippingTaskId,
getActiveShippingBatchNo: () => resolvedShippingBatchNo.value || shippingBatchNoFromQuery.value || '',
messages,
newLocalMessageId,
saveLocalMessageToBackend,
sendShippingMenuMessage,
openShippingInventoryMappingFormForTask,
openShippingInventoryPicker,
@@ -697,6 +702,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
executeShippingDecision,
executeShippingManualUpload,
refreshShippingActions,
startChatTurn,
msg,
t,
});
@@ -723,8 +729,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
buildFileSpecsForSend,
loadHistory,
sendShippingMenuMessage,
pushShippingLocalUserMessage,
pushShippingLocalAssistantMessage,
startChatTurn,
openShippingInventoryPicker,
executeShippingDecision,
executeShippingManualUpload,
@@ -0,0 +1,264 @@
/**
* features/chat/composables/useChatTurn.ts
* 用途:统一发起 Chat Turn(POST /api/chat/turns/stream),复用与 sendMessage 相同的 SSE 渲染链路。
* 依赖:chat-turn.types、useChat 的 shipping UI 同步、streamErrorMessage、auth headers。
* 逻辑:useChat 构造 startChatTurn 并导出;货代/请假等业务只构造 actionType + payload。
*/
import { type Ref } from 'vue';
import { getAuthHeaders } from '@/shared/utils/auth';
import { applyStreamErrorToMessage, type StreamErrorLabels } from '../utils/streamErrorMessage';
import type { StartChatTurnOptions } from '../types/chat-turn.types';
import type { ChatMessage, ChatRun } from '../types/chat.types';
import { applyShippingUiStateToMessage } from './useChat';
export interface CreateStartChatTurnOptions {
messages: Ref<ChatMessage[]>;
isThinking: Ref<boolean>;
conversationId: Ref<string | null>;
viewId: Ref<number>;
runs: Ref<ChatRun[]>;
activeRunId: Ref<number | null>;
activeStreamController: Ref<AbortController | null>;
streamErrorLabels: () => StreamErrorLabels;
formatStreamError: (message: unknown) => string;
}
/**
* 创建 startChatTurn 函数,供 useChat 与业务 handler 共用。
*/
export function createStartChatTurn(options: CreateStartChatTurnOptions) {
let runSeq = 0;
const normalizeStreamText = (text: string) => text.replace(/\\n/g, '\n');
const startChatTurn = async (turn: StartChatTurnOptions): Promise<boolean> => {
const displayText = String(turn.displayText || '').trim();
if (!displayText && !turn.silent) return false;
if (options.activeStreamController.value) {
options.activeStreamController.value.abort();
options.activeStreamController.value = null;
}
const controller = new AbortController();
options.activeStreamController.value = controller;
const runViewId = options.viewId.value;
const runMessages = options.messages.value;
const run: ChatRun = {
runId: ++runSeq,
agentId: turn.agentId,
viewId: runViewId,
query: displayText,
messages: runMessages,
conversationId: options.conversationId.value,
status: 'running',
createdAt: new Date().toISOString(),
abortController: controller,
};
options.runs.value.unshift(run);
if (options.runs.value.length > 30) {
options.runs.value = options.runs.value.slice(0, 30);
}
options.activeRunId.value = run.runId;
if (!turn.silent && displayText) {
runMessages.push({ role: 'user', content: displayText });
}
let botMsgIndex: number | null = null;
let hasTerminalEvent = false;
const ensureBotMessage = () => {
if (botMsgIndex === null) {
botMsgIndex = runMessages.push({
role: 'assistant',
content: '',
retriever_resources: [],
attribution_parts: [],
}) - 1;
}
return runMessages[botMsgIndex] || null;
};
options.isThinking.value = true;
const refs = turn.refs || {};
try {
const inputBody = {
type: turn.inputType,
display_text: displayText || turn.actionType,
action_type: turn.actionType,
payload: turn.payload || {},
};
const refsPayload = Object.keys(refs).length > 0 ? refs : undefined;
const hasFiles = Array.isArray(turn.files) && turn.files.length > 0;
let response: Response;
if (hasFiles) {
const form = new FormData();
form.append('agent_id', String(turn.agentId));
if (options.conversationId.value) {
form.append('conversation_id', options.conversationId.value);
}
form.append('input', JSON.stringify(inputBody));
if (refsPayload) {
form.append('context', JSON.stringify({ refs: refsPayload }));
}
turn.files!.forEach((file) => form.append('files', file));
response = await fetch('/api/chat/turns/stream', {
method: 'POST',
headers: { ...getAuthHeaders() },
signal: controller.signal,
body: form,
});
} else {
response = await fetch('/api/chat/turns/stream', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
signal: controller.signal,
body: JSON.stringify({
agent_id: turn.agentId,
conversation_id: options.conversationId.value,
input: inputBody,
context: {
refs: refsPayload,
},
}),
});
}
if (!response.ok) {
const err = await response.json().catch(() => ({}));
const envelope = err as { error?: { message?: string }; message?: string };
throw new Error(envelope.error?.message || envelope.message || `Request failed with status ${response.status}`);
}
const reader = response.body?.getReader();
const decoder = new TextDecoder();
if (!reader) throw new Error('No reader');
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
buffer = buffer.replace(/\r\n/g, '\n');
const frames = buffer.split('\n\n');
buffer = frames.pop() || '';
for (const frame of frames) {
const dataLines = frame
.split('\n')
.map((line) => line.trim())
.filter((line) => line.startsWith('data:'));
if (dataLines.length === 0) continue;
const payload = dataLines.map((line) => line.replace(/^data:\s?/, '')).join('\n');
if (!payload) continue;
try {
const data = JSON.parse(payload) as Record<string, unknown>;
if (data?.conversation_id) {
const cid = String(data.conversation_id);
if (!run.conversationId) run.conversationId = cid;
if (options.messages.value === runMessages) options.conversationId.value = cid;
}
const eventName = String(data.event || '');
if (eventName === 'shipping_ui_state' || eventName === 'ui_state.updated') {
const botMsg = ensureBotMessage();
if (botMsg) applyShippingUiStateToMessage(botMsg, data);
} else if (
eventName === 'message'
|| eventName === 'agent_message'
|| eventName === 'message.delta'
) {
const chunk = String(data.answer || data.content || '');
if (chunk) {
const botMsg = ensureBotMessage();
if (botMsg) botMsg.content += normalizeStreamText(chunk);
}
} else if (
eventName === 'message_end'
|| eventName === 'message.completed'
|| eventName === 'run.completed'
) {
if (eventName === 'run.completed') {
hasTerminalEvent = true;
run.status = 'done';
}
if (eventName === 'message_end' || eventName === 'message.completed') {
hasTerminalEvent = true;
run.status = 'done';
const botMsg = ensureBotMessage();
if (botMsg) {
const answer = normalizeStreamText(String(data.answer || data.content || ''));
if (answer) botMsg.content = answer;
const messageType = String(data.type || data.message_type || '').trim();
if (messageType) botMsg.type = messageType as ChatMessage['type'];
if (data.payload) botMsg.payload = data.payload;
if (data.chat_log_id != null) botMsg.chat_log_id = Number(data.chat_log_id);
if (botMsg.payload && typeof botMsg.payload === 'object' && (botMsg.payload as { shipping_actions_used?: boolean }).shipping_actions_used) {
botMsg.shipping_actions_used = true;
botMsg.shipping_actions = undefined;
}
}
}
} else if (eventName === 'run.failed' || eventName === 'error') {
hasTerminalEvent = true;
run.status = 'error';
const botMsg = ensureBotMessage();
if (botMsg) {
applyStreamErrorToMessage(botMsg, options.formatStreamError(data.message), options.streamErrorLabels());
}
}
} catch {
// ignore malformed SSE frames
}
}
}
if (!hasTerminalEvent) {
run.status = 'done';
}
return run.status === 'done';
} catch (error: unknown) {
if (!controller.signal.aborted) {
run.status = 'error';
const botMsg = ensureBotMessage();
if (botMsg) {
const message = error instanceof Error ? error.message : 'Network Issue';
applyStreamErrorToMessage(botMsg, message, options.streamErrorLabels());
}
}
} finally {
if (options.activeStreamController.value === controller) {
options.activeStreamController.value = null;
}
if (run.abortController === controller) {
delete run.abortController;
}
if (options.messages.value === runMessages) {
options.isThinking.value = false;
}
if (run.status === 'done' && botMsgIndex !== null) {
const botMsg = runMessages[botMsgIndex];
if (botMsg) {
await turn.hooks?.onAssistantMessageFinished?.(botMsg, runMessages);
}
}
return run.status === 'done';
}
};
return { startChatTurn };
}
/**
* useChatTurn 组合式入口;通常由 useChat 内部调用 createStartChatTurn。
*/
export function useChatTurn(options: CreateStartChatTurnOptions) {
const { startChatTurn } = createStartChatTurn(options);
return { startChatTurn };
}
@@ -1,12 +1,8 @@
/**
* features/chat/constants/leave.ts
* 请假功能常量:启用 Agent、假别编码、OA 跳转地址。
* 请假功能常量:假别编码、OA 跳转地址。
* 说明:Agent 门控已迁移至 shared/utils/agent-registry.utils(intent_routes)。
*/
/** 支持本地请假表单的 Agent 名称白名单 */
export const LEAVE_FEATURE_AGENT_NAMES = new Set(['通用入口', '人事规章']);
/** OA 系统基础地址(自动登录表单提交目标) */
export const OA_BASE_URL = 'http://192.168.100.221:8888';
export const OA_VERIFY_LOGIN_URL = `${OA_BASE_URL}/login/VerifyLogin.jsp`;
export const OA_LEAVE_APPLY_PATH = '/workflow/request/AddRequest.jsp?workflowid=652&isagent=0&beagenter=0&f_weaver_belongto_userid=';
@@ -15,7 +15,7 @@ export const SHIPPING_MENU_ACTION_SPECS: Record<
> = {
upload: { id: 'upload_inventory_file', label: '选择库存文件', message: '我要上传库存 Excel', variant: 'primary' },
paste: { id: 'paste_inventory_json', label: '粘贴库存', message: '我粘贴库存小表', variant: 'secondary' },
retry_rpa: { id: 'retry_rpa', label: '重试 RPA', message: '重试 RPA 导出库存', variant: 'secondary' },
retry_rpa: { id: 'retry_rpa', label: '重新获取库存', message: '重新获取库存', variant: 'secondary' },
confirm: { id: 'confirm', label: '确认', message: '确认', variant: 'primary' },
reparse: { id: 'reparse', label: '重新解析', message: '重新解析', variant: 'secondary' },
reject: { id: 'reject', label: '驳回', message: '驳回', variant: 'danger' },
@@ -147,7 +147,7 @@ export function createLeaveFlowApi(ctx: LeaveFlowContext) {
if (action !== 'start-leave-flow' || ctx.isThinking.value) return false;
event.preventDefault();
if (!ctx.canUseLeaveFeature.value) {
ctx.msg.warning('请在“通用入口”或“人事规章”入口使用请假功能');
ctx.msg.warning(ctx.t('chat.leaveFeatureAgentRequired'));
return true;
}
void startLocalLeaveFlow('我要请假');
@@ -1,29 +1,24 @@
/**
* 对话页:Agent tool_run_progress 能力轮询(文件检核等异步任务进度卡片)。
* 依赖:useToolRunProgress、toolRunProgressConfig、ChatMessage。
* 逻辑:仅当 chat_logs.run_id 已绑定(消息含 run_id 或 for-log 已解析到批次)时展示进度卡片;未绑定时不展示等待条,后台仍轮询 for-log。
* features/chat/page/useChatPageToolRun.ts
*
* 用途:对话页 Agent tool_run_progress 能力轮询(文件检核等异步任务进度卡片)。
* 依赖:useToolRunProgress、toolRunProgressConfig、agent-registry.utils、ChatMessage。
* 逻辑:仅当 chat_logs.run_id 已绑定(消息含 run_id 或 for-log 已解析到批次)时展示进度卡片。
*/
import { computed, nextTick, ref, watch } from 'vue';
import type { ToolRunProgress } from '../api/toolRunProgress.api';
import { getToolRunProgress } from '../api/toolRunProgress.api';
import type { ToolRunProgressConfig } from '../composables/useToolRunProgress';
import type { ChatMessage } from '../types/chat.types';
import type { Ref } from 'vue';
import { computed, nextTick, ref, watch, type Ref } from 'vue';
import {
agentHasTaskProgress,
resolveToolRunProgressView,
type AgentRegistryFields,
} from '@/shared/utils/agent-registry.utils';
import type { ToolRunProgress } from '../api/toolRunProgress.api';
import { getToolRunProgress } from '../api/toolRunProgress.api';
import type { ToolRunProgressConfig } from '../composables/useToolRunProgress';
import type { ChatMessage } from '../types/chat.types';
import {
assistantMessageHasError,
buildFileCheckDetailUrl,
buildFileCheckLogProgressUrl,
collectAssistantProgressTargets,
@@ -35,11 +30,8 @@ import {
resolveToolRunProgressOptions,
} from '../utils/toolRunProgressConfig';
export interface ChatPageToolRunContext {
currentAgent: Ref<{ id?: number; extra_config?: Record<string, unknown> } | null>;
currentAgent: Ref<AgentRegistryFields | null>;
conversationId: Ref<string | null>;
@@ -69,47 +61,41 @@ export function useChatPageToolRun(ctx: ChatPageToolRunContext) {
const rawToolRunConfig = computed(() => {
const extra = ctx.currentAgent.value?.extra_config || {};
const raw = extra.tool_run_progress;
return raw && typeof raw === 'object' ? (raw as ToolRunProgressConfig) : null;
});
const rawToolRunConfig = computed(() => resolveToolRunProgressView(ctx.currentAgent.value));
const toolRunProgressConfig = computed<ToolRunProgressConfig | null>(() => {
const agent = ctx.currentAgent.value;
if (!agent || !agentHasTaskProgress(agent)) return null;
const extra = ctx.currentAgent.value?.extra_config || {};
const cfg = resolveToolRunProgressView(agent) || {};
const handlerConfig = agent.handler_config && typeof agent.handler_config === 'object'
? agent.handler_config
: {};
const boundTaskId = agent.bound_schedule_task_id;
const pollRaw = Number(handlerConfig.poll_interval_seconds ?? cfg.poll_interval_seconds);
const pollInterval = Number.isFinite(pollRaw) && pollRaw > 0 ? pollRaw : undefined;
const lockRaw = handlerConfig.lock_input_when_running ?? cfg.lock_input_when_running;
const lockInput = typeof lockRaw === 'boolean' ? lockRaw : undefined;
const capabilities = Array.isArray(extra.capabilities)
? extra.capabilities.map((item: unknown) => String(item))
: [];
if (!capabilities.includes('tool_run_progress')) return null;
const cfg = rawToolRunConfig.value;
if (!cfg) return null;
const scheduleTaskId = boundTaskId ?? resolveScheduleTaskId(cfg);
if (!scheduleTaskId) return null;
return {
...cfg,
schedule_task_id: resolveScheduleTaskId(cfg),
schedule_task_id: scheduleTaskId,
poll_interval_seconds: pollInterval,
lock_input_when_running: lockInput,
};
});
const boundScheduleTaskId = computed(() => resolveScheduleTaskId(rawToolRunConfig.value));
const boundScheduleTaskId = computed(() => {
const agent = ctx.currentAgent.value;
const fromColumn = Number(agent?.bound_schedule_task_id);
if (Number.isFinite(fromColumn) && fromColumn > 0) return fromColumn;
return resolveScheduleTaskId(rawToolRunConfig.value);
});
const progressPollOptions = computed(() => resolveToolRunProgressOptions(rawToolRunConfig.value));
@@ -24,3 +24,4 @@ export * from './useChatShippingDecision';
export * from './useChatShippingMenuHandler';
export * from './useChatShippingUploadHandler';
export * from './useChatShippingSendHandler';
export * from './shippingTurnActions';
@@ -1,8 +1,11 @@
/**
* features/chat/shipping/shippingLocalMessages.ts
* 用途:发货聊天本地消息写入(不经 Dify SSE,直接 push 并落库)。
*
* @deprecated 货代业务动作已全部迁移至 Chat Turn(startChatTurn)。
* 本模块保留供历史引用,禁止在新代码中使用。
*
* 用途:发货聊天本地消息写入(不经 SSE,直接 push 并落库)。
* 依赖:chat.types、Vue Ref。
* 逻辑:useChatShipping 在菜单/决策拦截成功后写入本地 user/assistant 消息。
*/
import type { ChatMessage } from '../types/chat.types';
import type { Ref } from 'vue';
@@ -13,9 +16,7 @@ export interface ShippingLocalMessageContext {
saveLocalMessageToBackend: (msg: ChatMessage, userQuery?: string) => Promise<void>;
}
/**
* 创建本地 user/assistant 消息 push 函数。
*/
/** @deprecated 使用 startChatTurn 替代 */
export function createShippingLocalMessages(ctx: ShippingLocalMessageContext) {
const pushShippingLocalUserMessage = async (text: string) => {
const content = String(text || '').trim();
@@ -31,6 +32,7 @@ export function createShippingLocalMessages(ctx: ShippingLocalMessageContext) {
await ctx.saveLocalMessageToBackend(userMsg, content);
};
/** @deprecated 使用 startChatTurn 替代 */
const pushShippingLocalAssistantMessage = async (text: string) => {
const content = String(text || '').trim();
if (!content) return;
@@ -17,7 +17,7 @@ describe('shippingText', () => {
'目前任务已进入库存上传环节,您需要提供当前库存数据。请使用下方按钮选择以下任一方式:',
'',
'1. 📁 选择库存文件 — 在本对话中上传库存 Excel 文件',
'2. 🔄 重试 RPA — 让系统重新尝试从 RPA 导出库存快照',
'2. 🔄 重新获取库存 — 让系统重新获取库存快照',
'3. 📋 粘贴库存 — 直接粘贴库存小表内容',
'',
'请使用下方按钮继续操作。',
@@ -28,7 +28,7 @@ describe('shippingText', () => {
expect(result).toContain('当前卡点');
expect(result).not.toContain('1.');
expect(result).not.toContain('选择库存文件');
expect(result).not.toContain('重试 RPA');
expect(result).not.toContain('重新获取库存');
expect(result).not.toContain('粘贴库存');
expect(result).not.toContain('下方按钮');
});
@@ -70,7 +70,7 @@ describe('shippingText', () => {
const result = stripShippingActionListByButtons(
'已手动重新触发 RPA 库存导出,等待结果。若 6 分内无回调/无落盘文件,可手动重试,或上传库存 Excel。\n任务编号:SN-001',
[
{ label: '重试 RPA', message: '重试 RPA 导出库存' },
{ label: '重新获取库存', message: '重新获取库存' },
{ label: '选择库存文件', message: '我要上传库存 Excel' },
],
);
@@ -88,7 +88,7 @@ describe('shippingText', () => {
true,
);
expect(result).toContain('已重新触发 RPA 库存导出。');
expect(result).toContain('已重新触发库存获取。');
expect(result).not.toContain('手动第 2 次');
expect(result).not.toContain('第 2 次');
});
@@ -96,6 +96,6 @@ describe('shippingText', () => {
it('hides automatic retry count in runtime status text', () => {
const result = sanitizeShippingRuntimeStatusText('RPA 库存导出进行中(第 2/3 次)。');
expect(result).toBe('RPA 库存导出进行中。');
expect(result).toBe('库存获取进行中。');
});
});
@@ -36,22 +36,26 @@ const isPlainActionMenuLine = (line: string) =>
/**
* 规范化运行态提示文案,隐藏“第几次重试/尝试”这类面对业务用户价值较低的过程指标。
*
* 核心逻辑:仅收敛库存 RPA 相关状态短语,保留“已触发 / 已重新触发 / 进行中”这些对下一步决策有帮助的状态,
* 核心逻辑:仅收敛库存获取相关状态短语,保留“已触发 / 已重新触发 / 进行中”这些对下一步决策有帮助的状态,
* 不在前台暴露机械性的第 N 次计数。
*/
export function sanitizeShippingRuntimeStatusText(text: string): string {
return String(text || '')
.replace(
/已手动重新触发\s*RPA\s*库存导出\s*[((]\s*(?:手动第\s*\d+\s*次(?:尝试)?|第\s*\d+(?:\s*\/\s*\d+)?\s*次(?:尝试)?)\s*[))]\s*[。.]?/gi,
'已重新触发 RPA 库存导出。',
'已重新触发库存获取。',
)
.replace(
/已触发\s*RPA\s*库存导出\s*[((]\s*第\s*\d+(?:\s*\/\s*\d+)?\s*次(?:尝试)?\s*[))]\s*[。.]?/gi,
'已触发 RPA 库存导出。',
'已触发库存获取。',
)
.replace(
/RPA\s*库存导出进行中\s*[((]\s*第\s*\d+(?:\s*\/\s*\d+)?\s*次(?:尝试)?\s*[))]\s*[。.]?/gi,
'RPA 库存导出进行中。',
'库存获取进行中。',
)
.replace(
/库存获取进行中\s*[((]\s*第\s*\d+(?:\s*\/\s*\d+)?\s*次(?:尝试)?\s*[))]\s*[。.]?/gi,
'库存获取进行中。',
)
.replace(
/手动第\s*\d+\s*次尝试/gi,
@@ -175,7 +179,7 @@ export function stripShippingActionListByButtons(
.map((item) => normalizeActionComparableText(String(item || '')))
.filter((item) => item.length >= 2);
if (!normalizedActions.length) return source;
const hasRetryRpaAction = normalizedActions.some((action) => /重试.*rpa|rpa.*重试|重试库存抓取|重试库存导出/.test(action));
const hasRetryRpaAction = normalizedActions.some((action) => /重新获取库存|重试.*rpa|rpa.*重试|重试库存抓取|重试库存导出/.test(action));
const hasInventoryUploadAction = normalizedActions.some((action) => /选择库存文件|上传库存|库存excel|库存文件/.test(action));
if (hasRetryRpaAction && hasInventoryUploadAction) {
source = source
@@ -272,7 +276,7 @@ export function sanitizeShippingConversationText(text: string, enabled: boolean)
.replace(/\bdata\.库存表头预览\b/gi, '库存表头预览')
.replace(/\bmap_json\b/gi, '字段映射')
.replace(/\bsample_rows\b/gi, '样例行')
.replace(/\bretry_rpa\b/gi, '重试库存抓取')
.replace(/\bretry_rpa\b/gi, '重新获取库存')
.replace(/\bretry_upload\b/gi, '重试上传货代')
.replace(/\bstructured\b/gi, '结构化内容')
.replace(/\braw_text\b/gi, '通知原文');
@@ -0,0 +1,160 @@
/**
* features/chat/shipping/shippingTurnActions.ts
* 用途:将发货通知菜单/决策 action.id 映射为 Chat Turn action_type + payload。
* 依赖:constants/shipping。
* 逻辑:useChatShippingDecision 与 useChatShippingMenuHandler 调用本模块,不再直调 workspace API 插消息。
*/
import { SHIPPING_DECISION_ACTIONS } from '../constants/shipping';
export interface ShippingChatTurnSpec {
actionType: string;
payload: Record<string, unknown>;
}
/**
* 将发货 UI 动作 id 解析为平台 Chat Turn 规格。
* @param actionId - 状态机 action_buttons.id
* @param taskNo - 任务编号
* @param extra - 额外参数,如 confirm_inventory_source 的 source_code
* @returns Chat Turn 规格;无法映射时返回 null
*/
export function resolveShippingChatTurn(
actionId: string,
taskNo: string,
extra?: { sourceCode?: string },
): ShippingChatTurnSpec | null {
const normalizedTaskNo = String(taskNo || '').trim().toUpperCase();
if (!normalizedTaskNo) return null;
const id = String(actionId || '').trim();
if (!id) return null;
if (SHIPPING_DECISION_ACTIONS.has(id)) {
return {
actionType: 'shipping.submit_decision',
payload: { task_no: normalizedTaskNo, decision: id },
};
}
switch (id) {
case 'generate_excel':
return { actionType: 'shipping.generate_excel', payload: { task_no: normalizedTaskNo } };
case 'retry_upload':
return { actionType: 'shipping.retry_upload', payload: { task_no: normalizedTaskNo } };
case 'match_inventory':
return { actionType: 'shipping.match_inventory', payload: { task_no: normalizedTaskNo } };
case 'mark_manual_uploaded':
return { actionType: 'shipping.mark_manual_uploaded', payload: { task_no: normalizedTaskNo } };
case 'confirm_inventory_source': {
const sourceCode = String(extra?.sourceCode || '').trim().toUpperCase();
if (!sourceCode) return null;
return {
actionType: 'shipping.confirm_inventory_source',
payload: { task_no: normalizedTaskNo, source_code: sourceCode },
};
}
default:
return null;
}
}
/**
* 构造 submit_decision Chat Turn(文本/菜单决策共用)。
*/
export function buildShippingSubmitDecisionTurn(
taskNo: string,
decision: string,
): ShippingChatTurnSpec {
return {
actionType: 'shipping.submit_decision',
payload: {
task_no: String(taskNo || '').trim().toUpperCase(),
decision: String(decision || '').trim(),
},
};
}
/**
* 构造发货通知建批 Chat Turn(multipart 上传)。
*/
export function buildShippingCreateBatchTurn(
files: File[],
conversationId?: string | null,
): { actionType: string; displayText: string; payload: Record<string, unknown>; files: File[] } {
const count = files.length;
const displayText = count === 1
? `上传发货通知:${files[0]?.name || '附件'}`
: `上传 ${count} 份发货通知`;
return {
actionType: 'shipping.create_batch_from_notices',
displayText,
payload: {
conversation_id: conversationId || undefined,
file_count: count,
},
files,
};
}
/**
* 构造货代领域 refs,键名与 agent_runtime_context.refs 对齐。
*/
export function buildShippingTurnRefs(taskNo: string, batchNo?: string): Record<string, string> {
const refs: Record<string, string> = {};
const task = String(taskNo || '').trim().toUpperCase();
const batch = String(batchNo || '').trim();
if (task) refs.task_no = task;
if (batch) refs.batch_no = batch;
return refs;
}
export function buildShippingUploadInventoryTurn(taskNo: string, file: File) {
const task = String(taskNo || '').trim().toUpperCase();
return {
actionType: 'shipping.upload_inventory',
displayText: `上传库存文件:${file.name}`,
payload: { task_no: task },
files: [file],
refs: buildShippingTurnRefs(task),
};
}
export function buildShippingReplaceNoticeTurn(taskNo: string, file: File) {
const task = String(taskNo || '').trim().toUpperCase();
return {
actionType: 'shipping.replace_notice',
displayText: `重新上传发货通知:${file.name}`,
payload: { task_no: task },
files: [file],
refs: buildShippingTurnRefs(task),
};
}
export function buildShippingApplyMappingTurn(taskNo: string, mapping: Record<string, string>) {
const task = String(taskNo || '').trim().toUpperCase();
return {
actionType: 'shipping.apply_inventory_mapping',
displayText: `应用库存列映射(任务 ${task})`,
payload: { task_no: task, map_json: mapping },
refs: buildShippingTurnRefs(task),
};
}
export function buildShippingSwitchFocusTurn(batchNo: string, taskNo: string, displayText: string) {
const batch = String(batchNo || '').trim();
const task = String(taskNo || '').trim().toUpperCase();
return {
actionType: 'shipping.switch_batch_focus',
displayText,
payload: { batch_no: batch, task_no: task },
refs: buildShippingTurnRefs(task, batch),
};
}
export function buildShippingQueryShortageTurn(taskNo: string, displayText: string) {
const task = String(taskNo || '').trim().toUpperCase();
return {
actionType: 'shipping.query_shortage_details',
displayText,
payload: { task_no: task },
refs: buildShippingTurnRefs(task),
};
}
@@ -46,8 +46,8 @@ describe('shippingWorkspaceActions', () => {
action_buttons: [
{
id: 'retry_rpa',
label: '重试 RPA',
message: '重试 RPA',
label: '重新获取库存',
message: '重新获取库存',
variant: 'primary',
},
],
@@ -1,25 +1,22 @@
/**
* features/chat/shipping/useChatShippingDecision.spec.ts
* 用途:验证发货通知决策处理器的 silent 模式,避免纯 UI 操作追加本地聊天气泡。
* 依赖:vitest、vue refs、shipping.api、useChatShippingDecision。
* 逻辑:分别覆盖 silent 与普通决策路径,确保 silent 仅更新状态,不写入本地消息或后端消息存档。
* 用途:验证发货通知决策处理器经 Chat Turn 发起,silent 模式不追加用户气泡。
* 依赖:vitest、vue refs、useChatShippingDecision。
* 逻辑:mock startChatTurn,覆盖 silent/普通决策、显式 taskId 与 inventory_mapping 分支。
*/
import { computed, ref } from 'vue';
import { describe, expect, it, vi } from 'vitest';
import { describe, expect, it, vi, beforeEach } from 'vitest';
import { createShippingDecisionHandlers, type ShippingDecisionContext } from './useChatShippingDecision';
import type { ChatMessage } from '../types/chat.types';
const {
markWorkspaceShippingManualUploaded,
submitWorkspaceShippingDecision,
} = vi.hoisted(() => ({
markWorkspaceShippingManualUploaded: vi.fn(),
submitWorkspaceShippingDecision: vi.fn(),
}));
vi.mock('@/features/chat/api/shipping.api', () => ({
markWorkspaceShippingManualUploaded,
submitWorkspaceShippingDecision,
}));
const defaultStartChatTurn = vi.fn(async (options: {
hooks?: { onAssistantMessageFinished?: (msg: ChatMessage) => Promise<void> };
}) => {
await options?.hooks?.onAssistantMessageFinished?.(
{ role: 'assistant', content: 'mock assistant' },
);
return true;
});
const createContext = (
overrides: Partial<ShippingDecisionContext> = {},
@@ -28,13 +25,14 @@ const createContext = (
conversationId: ref('conv-001'),
history: ref([{ conversation_id: 'conv-001' }]),
isShippingNoticeAgent: computed(() => true),
currentAgentId: computed(() => 42),
shippingInventorySchemaPreviewCache: ref({}),
getActiveShippingTaskId: () => 'SN-FOCUS-001',
newLocalMessageId: vi.fn((prefix: string) => `${prefix}-local-id`),
saveLocalMessageToBackend: vi.fn(async () => undefined),
getActiveShippingBatchNo: () => 'BATCH-001',
loadHistory: vi.fn(async () => undefined),
openShippingInventoryMappingFormForTask: vi.fn(async () => true),
refreshShippingActions: vi.fn(async () => undefined),
startChatTurn: defaultStartChatTurn,
msg: {
warning: vi.fn(),
success: vi.fn(),
@@ -44,87 +42,102 @@ const createContext = (
});
describe('useChatShippingDecision', () => {
beforeEach(() => {
defaultStartChatTurn.mockClear();
});
it('does not append local chat messages when decision runs in silent mode', async () => {
submitWorkspaceShippingDecision.mockResolvedValue({
message: '已清除库存快照,请重新上传库存。',
data: {},
});
const ctx = createContext();
const { executeShippingDecision } = createShippingDecisionHandlers(ctx);
const ok = await executeShippingDecision('reparse_inventory', '重新上传库存', { silent: true });
expect(ok).toBe(true);
expect(submitWorkspaceShippingDecision).toHaveBeenCalledWith('SN-FOCUS-001', 'reparse_inventory');
expect(ctx.startChatTurn).toHaveBeenCalledWith(
expect.objectContaining({
inputType: 'action',
actionType: 'shipping.submit_decision',
payload: { task_no: 'SN-FOCUS-001', decision: 'reparse_inventory' },
silent: true,
}),
);
expect(ctx.messages.value).toEqual([]);
expect(ctx.saveLocalMessageToBackend).not.toHaveBeenCalled();
expect(ctx.refreshShippingActions).toHaveBeenCalledTimes(1);
});
it('keeps appending local chat messages for normal decisions', async () => {
submitWorkspaceShippingDecision.mockResolvedValue({
message: '已确认,请继续下一步。',
data: {},
});
it('delegates normal decisions to startChatTurn with display text', async () => {
const ctx = createContext();
const { executeShippingDecision } = createShippingDecisionHandlers(ctx);
const ok = await executeShippingDecision('confirm', '确认');
expect(ok).toBe(true);
expect(ctx.messages.value).toHaveLength(2);
expect(ctx.messages.value[0]?.role).toBe('user');
expect(ctx.messages.value[1]?.role).toBe('assistant');
expect(ctx.saveLocalMessageToBackend).toHaveBeenCalledTimes(2);
expect(ctx.startChatTurn).toHaveBeenCalledWith(
expect.objectContaining({
actionType: 'shipping.submit_decision',
displayText: expect.stringContaining('SN-FOCUS-001'),
payload: { task_no: 'SN-FOCUS-001', decision: 'confirm' },
}),
);
expect(ctx.refreshShippingActions).toHaveBeenCalledTimes(1);
});
it('does not show success toast for retry_rpa inside shipping agent workspace', async () => {
submitWorkspaceShippingDecision.mockResolvedValue({
message: '已加入 RPA 队列',
data: {},
});
const ctx = createContext();
const { executeShippingDecision } = createShippingDecisionHandlers(ctx);
const ok = await executeShippingDecision('retry_rpa', '重试 RPA');
const ok = await executeShippingDecision('retry_rpa', '重新获取库存');
expect(ok).toBe(true);
expect(submitWorkspaceShippingDecision).toHaveBeenCalledWith('SN-FOCUS-001', 'retry_rpa');
expect(ctx.startChatTurn).toHaveBeenCalledWith(
expect.objectContaining({
payload: { task_no: 'SN-FOCUS-001', decision: 'retry_rpa' },
}),
);
expect(ctx.msg.success).not.toHaveBeenCalled();
expect(ctx.refreshShippingActions).toHaveBeenCalledTimes(1);
});
it('prefers explicit taskId for workspace retry decisions', async () => {
submitWorkspaceShippingDecision.mockResolvedValue({
message: '已加入 RPA 队列',
data: {},
});
const ctx = createContext({
getActiveShippingTaskId: () => '',
});
const { executeShippingDecision } = createShippingDecisionHandlers(ctx);
const ok = await executeShippingDecision('retry_rpa', '重试 RPA', { taskId: 'sn-target-009' });
const ok = await executeShippingDecision('retry_rpa', '重新获取库存', { taskId: 'sn-target-009' });
expect(ok).toBe(true);
expect(submitWorkspaceShippingDecision).toHaveBeenCalledWith('SN-TARGET-009', 'retry_rpa');
expect(ctx.startChatTurn).toHaveBeenCalledWith(
expect.objectContaining({
payload: { task_no: 'SN-TARGET-009', decision: 'retry_rpa' },
}),
);
expect(ctx.msg.warning).not.toHaveBeenCalled();
});
it('submits confirm_inventory_mapping via submit_decision instead of auto_progress', async () => {
submitWorkspaceShippingDecision.mockResolvedValue({
status: 'running',
message: '库存字段对齐已确认,后台继续处理匹配与后续步骤。',
data: {},
});
it('submits confirm_inventory_mapping via submit_decision Chat Turn', async () => {
const ctx = createContext();
const { executeShippingDecision } = createShippingDecisionHandlers(ctx);
const ok = await executeShippingDecision('confirm_inventory_mapping', '确认');
expect(ok).toBe(true);
expect(submitWorkspaceShippingDecision).toHaveBeenCalledWith('SN-FOCUS-001', 'confirm_inventory_mapping');
expect(ctx.messages.value).toHaveLength(2);
expect(ctx.startChatTurn).toHaveBeenCalledWith(
expect.objectContaining({
actionType: 'shipping.submit_decision',
payload: { task_no: 'SN-FOCUS-001', decision: 'confirm_inventory_mapping' },
}),
);
});
it('returns false when startChatTurn reports failure', async () => {
const ctx = createContext({
startChatTurn: vi.fn(async () => false),
});
const { executeShippingDecision } = createShippingDecisionHandlers(ctx);
const ok = await executeShippingDecision('confirm', '确认');
expect(ok).toBe(false);
});
});
@@ -1,15 +1,12 @@
/**
* features/chat/shipping/useChatShippingDecision.ts
* 用途:封装人工决策提交与手工上传标记逻辑。
* 依赖:shipping.api、shippingDecisionFormat、chat.types。
* 逻辑:由 useChatShipping 调用本文件;本文件负责把 confirm/reject/reparse 等决策提交到后端,并生成聊天区本地消息。
* 用途:封装人工决策提交与手工上传标记逻辑,统一走 Chat Turn SSE。
* 依赖:shippingTurnActions、chat-turn.types、chat.types。
* 逻辑:由 useChatShipping 调用;所有决策/手工上传经 startChatTurn,不再 push 本地消息或直调 workspace API。
*/
import {
markWorkspaceShippingManualUploaded,
submitWorkspaceShippingDecision,
} from '@/features/chat/api/shipping.api';
import { formatShippingDecisionAssistantMessage } from './shippingDecisionFormat';
import { buildShippingSubmitDecisionTurn, buildShippingTurnRefs } from './shippingTurnActions';
import { reportShippingDebugEvent } from './shippingDebugReporter';
import type { StartChatTurnOptions } from '../types/chat-turn.types';
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
import type { ComputedRef, Ref } from 'vue';
@@ -18,13 +15,14 @@ export interface ShippingDecisionContext {
conversationId: Ref<string | null>;
history: Ref<ChatSessionItem[]>;
isShippingNoticeAgent: ComputedRef<boolean>;
currentAgentId: ComputedRef<number>;
shippingInventorySchemaPreviewCache: Ref<Record<string, unknown>>;
getActiveShippingTaskId: () => string;
newLocalMessageId: (prefix: string) => string;
saveLocalMessageToBackend: (msg: ChatMessage, userQuery?: string) => Promise<void>;
getActiveShippingBatchNo: () => string;
loadHistory: () => Promise<void>;
openShippingInventoryMappingFormForTask: (taskId: string) => Promise<boolean>;
refreshShippingActions: () => Promise<void>;
startChatTurn: (options: StartChatTurnOptions) => Promise<boolean>;
msg: { warning: (text: string) => void; success: (text: string) => void };
t: (key: string, params?: Record<string, unknown>) => string;
}
@@ -37,17 +35,15 @@ export interface ExecuteShippingDecisionOptions {
/**
* 创建发货通知决策处理器。
*
* 核心逻辑:根据决策类型调用对应后端接口;默认同步本地用户/助手消息,也支持 silent 模式仅更新状态机与按钮。
* 核心逻辑:构造 shipping.submit_decision Chat Turn,由平台 SSE 统一渲染 user/assistant 与 ChatLog。
* @param ctx - 决策处理上下文
* @returns 人工决策与手工上传确认处理函数
*/
export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
const manualUploadInFlightTaskIds = new Set<string>();
// #region debug-point D:decision-submit
const reportRetryRpaDebug = (hypothesisId: string, msg: string, data: Record<string, unknown>) =>
reportShippingDebugEvent('useChatShippingDecision.ts', hypothesisId, msg, data);
// #endregion
const syncHistoryIfNeeded = async () => {
if (!ctx.conversationId.value && ctx.history.value.length === 0) {
@@ -58,15 +54,27 @@ export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
}
};
const afterDecisionTurn = async (decision: string, taskId: string, assistantMsg?: ChatMessage) => {
if (decision === 'correct_inventory_mapping' && assistantMsg?.payload && typeof assistantMsg.payload === 'object') {
const toolResult = (assistantMsg.payload as { tool_result?: { data?: { schema_preview?: unknown } } }).tool_result;
const preview = toolResult?.data?.schema_preview;
const key = String(taskId || '').trim().toUpperCase();
if (key && preview && typeof preview === 'object') {
ctx.shippingInventorySchemaPreviewCache.value = {
...ctx.shippingInventorySchemaPreviewCache.value,
[key]: preview,
};
}
}
await syncHistoryIfNeeded();
void ctx.refreshShippingActions();
if (decision === 'correct_inventory_mapping') {
await ctx.openShippingInventoryMappingFormForTask(taskId);
}
};
/**
* 提交发货人工决策,并按需把结果落为本地聊天消息。
* 核心逻辑:优先使用 options.taskId 提交指定任务的决策;未显式传入时再回退到当前激活任务。
* 这样可避免工作台多任务场景在焦点刷新抖动时,把 retry_rpa 错投到空任务或直接中断。
* @param decision - 决策动作 ID,如 confirm、reparse_inventory
* @param displayText - 用户侧展示文案;未传时回退为 decision
* @param options.silent - 为 true 时只更新状态与按钮,不追加本地聊天消息
* @param options.taskId - 显式指定要提交决策的任务编号;工作台多票动作优先传入
* @returns 是否成功提交决策
* 提交发货人工决策,经 Chat Turn 统一 SSE 返回。
*/
const executeShippingDecision = async (
decision: string,
@@ -74,105 +82,35 @@ export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
options?: ExecuteShippingDecisionOptions,
) => {
const taskId = String(options?.taskId || ctx.getActiveShippingTaskId() || '').trim().toUpperCase();
// #region debug-point D:decision-entry
void reportRetryRpaDebug('D', 'executeShippingDecision entry', {
decision,
taskId,
conversationId: ctx.conversationId.value,
isShippingNoticeAgent: ctx.isShippingNoticeAgent.value,
silent: Boolean(options?.silent),
});
// #endregion
if (!taskId) {
// #region debug-point D:decision-missing-task
void reportRetryRpaDebug('D', 'executeShippingDecision missing taskId', {
decision,
conversationId: ctx.conversationId.value,
});
// #endregion
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
return false;
}
const userText = (displayText || decision).trim();
const turnSpec = buildShippingSubmitDecisionTurn(taskId, decision);
try {
// #region debug-point D:decision-before-submit
void reportRetryRpaDebug('D', 'executeShippingDecision before submit', {
decision,
taskId,
const ok = await ctx.startChatTurn({
agentId: ctx.currentAgentId.value,
inputType: 'action',
displayText: options?.silent ? userText : `${userText}\n任务编号:${taskId}`,
actionType: turnSpec.actionType,
payload: turnSpec.payload,
refs: buildShippingTurnRefs(taskId, ctx.getActiveShippingBatchNo()),
silent: options?.silent,
hooks: {
onAssistantMessageFinished: async (assistantMsg) => {
await afterDecisionTurn(decision, taskId, assistantMsg);
},
},
});
// #endregion
// 字段对齐确认必须走 submit_decision(confirm_inventory_mapping);
// auto_progress 在 align_review 只会再次返回同一检查点,造成点击确认后死循环。
const result = await submitWorkspaceShippingDecision(taskId, decision);
// #region debug-point D:decision-after-submit
void reportRetryRpaDebug('D', 'executeShippingDecision after submit', {
decision,
taskId,
message: String(result?.message || ''),
});
// #endregion
if (decision === 'correct_inventory_mapping') {
const preview = result?.data?.schema_preview;
const key = String(taskId || '').trim().toUpperCase();
if (key && preview && typeof preview === 'object') {
ctx.shippingInventorySchemaPreviewCache.value = {
...ctx.shippingInventorySchemaPreviewCache.value,
[key]: preview,
};
}
}
const userText = (displayText || decision).trim();
const assistantContent = formatShippingDecisionAssistantMessage(
decision,
result,
taskId,
ctx.t('chat.shippingNoticeDecisionDone'),
);
if (!options?.silent) {
const userMsg: ChatMessage = {
role: 'user',
type: 'text',
content: `${userText}\n任务编号:${taskId}`,
local_id: ctx.newLocalMessageId('shipping-user'),
local_only: true,
};
const assistantMsg: ChatMessage = {
role: 'assistant',
type: 'text',
content: assistantContent,
local_id: ctx.newLocalMessageId('shipping-assistant'),
local_only: true,
};
ctx.messages.value.push(userMsg, assistantMsg);
// #region debug-point D:decision-messages-appended
void reportRetryRpaDebug('D', 'executeShippingDecision appended local messages', {
decision,
taskId,
totalMessages: ctx.messages.value.length,
lastUserPreview: String(userMsg.content || '').slice(0, 80),
lastAssistantPreview: String(assistantContent || '').slice(0, 120),
});
// #endregion
await ctx.saveLocalMessageToBackend(userMsg, userText);
await ctx.saveLocalMessageToBackend(assistantMsg);
await syncHistoryIfNeeded();
}
// 工作台内的 shipping agent 决策以聊天气泡和任务卡刷新为主,避免 retry_rpa 再弹成功 toast 打断操作流。
if (result.message && !ctx.isShippingNoticeAgent.value) {
ctx.msg.success(result.message);
}
void ctx.refreshShippingActions();
if (decision === 'correct_inventory_mapping') {
await ctx.openShippingInventoryMappingFormForTask(taskId);
}
return true;
return ok;
} catch (e: unknown) {
// #region debug-point D:decision-catch
void reportRetryRpaDebug('D', 'executeShippingDecision caught error', {
decision,
taskId,
errorMessage: e instanceof Error ? e.message : String(e),
});
// #endregion
const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingNoticeUploadFailed');
ctx.msg.warning(errorMessage);
return false;
@@ -183,45 +121,29 @@ export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
const normalizedTaskId = String(taskId || '').trim().toUpperCase();
if (!normalizedTaskId || manualUploadInFlightTaskIds.has(normalizedTaskId)) return false;
manualUploadInFlightTaskIds.add(normalizedTaskId);
const userText = (displayText || '我已在货代系统完成上传').trim();
try {
const result = await markWorkspaceShippingManualUploaded(normalizedTaskId);
const userText = (displayText || '我已在货代系统完成上传').trim();
const assistantContent = String(
result.message || `好的,任务 ${normalizedTaskId} 已确认完成,无需再处理。`,
).trim();
const lastUserMessage = [...ctx.messages.value].reverse().find((item) => item.role === 'user');
const shouldAppendUser = String(lastUserMessage?.content || '').trim() !== userText;
const userMsg: ChatMessage = {
role: 'user',
type: 'text',
content: userText,
local_id: ctx.newLocalMessageId('shipping-user'),
local_only: true,
};
const assistantMsg: ChatMessage = {
role: 'assistant',
type: 'text',
content: assistantContent,
local_id: ctx.newLocalMessageId('shipping-assistant'),
local_only: true,
shipping_actions_used: true,
};
if (shouldAppendUser) {
ctx.messages.value.push(userMsg);
}
ctx.messages.value.push(assistantMsg);
ctx.messages.value.forEach((rawMsg) => {
const m = rawMsg as ChatMessage & { shipping_actions?: unknown };
if (m.role === 'assistant') {
m.shipping_actions = undefined;
}
const ok = await ctx.startChatTurn({
agentId: ctx.currentAgentId.value,
inputType: 'action',
displayText: userText,
actionType: 'shipping.mark_manual_uploaded',
payload: { task_no: normalizedTaskId },
refs: buildShippingTurnRefs(normalizedTaskId, ctx.getActiveShippingBatchNo()),
hooks: {
onAssistantMessageFinished: async (assistantMsg) => {
assistantMsg.shipping_actions_used = true;
assistantMsg.shipping_actions = undefined;
ctx.messages.value.forEach((rawMsg) => {
if (rawMsg.role === 'assistant') {
rawMsg.shipping_actions = undefined;
}
});
void ctx.refreshShippingActions();
},
},
});
if (shouldAppendUser) {
await ctx.saveLocalMessageToBackend(userMsg, userText);
}
await ctx.saveLocalMessageToBackend(assistantMsg);
void ctx.refreshShippingActions();
return true;
return ok;
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : '标记手工上传失败';
ctx.msg.warning(errorMessage);
@@ -5,11 +5,10 @@
* 逻辑:由 useChatShipping 调用本文件;本文件负责把 schema preview 渲染成聊天卡片,并把表单提交回后端映射接口。
*/
import { nextTick } from 'vue';
import {
applyWorkspaceShippingInventoryMapping,
getWorkspaceShippingTask,
} from '@/features/chat/api/shipping.api';
import { buildShippingFieldAlignmentText, getShippingInventoryMappingPayload } from './shippingMapping';
import { getWorkspaceShippingTask } from '@/features/chat/api/shipping.api';
import { buildShippingApplyMappingTurn } from './shippingTurnActions';
import { getShippingInventoryMappingPayload } from './shippingMapping';
import type { StartChatTurnOptions } from '../types/chat-turn.types';
import type { ChatMessage } from '../types/chat.types';
import type { ShippingInventoryMappingFormPayload } from '../types/shipping.types';
import type { Ref } from 'vue';
@@ -23,7 +22,8 @@ export interface ShippingMappingFormContext {
resolvedShippingTaskId: Ref<string>;
newLocalMessageId: (prefix: string) => string;
saveLocalMessageToBackend: (msg: ChatMessage, userQuery?: string) => Promise<void>;
pushShippingLocalAssistantMessage: (text: string) => Promise<void>;
startChatTurn: (options: StartChatTurnOptions) => Promise<boolean>;
currentAgentId: import('vue').ComputedRef<number>;
refreshShippingActions: () => Promise<void>;
msg: { warning: (text: string) => void };
}
@@ -133,18 +133,22 @@ export function createShippingMappingFormHandlers(ctx: ShippingMappingFormContex
}
payload.applying = true;
try {
const result = await applyWorkspaceShippingInventoryMapping(taskId, mapping);
const alignmentText = buildShippingFieldAlignmentText(result);
const hint = alignmentText || String(result.message || '').trim();
await ctx.pushShippingLocalAssistantMessage(
[
'映射已应用并解析库存。',
`任务编号:${taskId}`,
hint,
].filter(Boolean).join('\n'),
);
ctx.resolvedShippingTaskId.value = taskId;
void ctx.refreshShippingActions();
const turn = buildShippingApplyMappingTurn(taskId, mapping);
const ok = await ctx.startChatTurn({
agentId: ctx.currentAgentId.value,
inputType: 'form_submit',
displayText: turn.displayText,
actionType: turn.actionType,
payload: turn.payload,
refs: turn.refs,
hooks: {
onAssistantMessageFinished: async () => {
ctx.resolvedShippingTaskId.value = taskId;
void ctx.refreshShippingActions();
},
},
});
if (!ok) ctx.msg.warning('应用映射失败');
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : '应用映射失败';
ctx.msg.warning(errorMessage);
@@ -2,24 +2,18 @@
* features/chat/shipping/useChatShippingMenuHandler.spec.ts
* 用途:验证发货聊天动作菜单在工作台显式 taskId 场景下会命中指定任务,而不是误用当前激活任务。
* 依赖:vitest、vue refs、shipping.api、useChatShippingMenuHandler。
* 逻辑:覆盖工作台点击 `retry_rpa` 与 `generate_excel` 两类动作,锁死统一按钮分发时的任务归属。
* 逻辑:覆盖 retry_rpa、generate_excel 等动作,锁死 Chat Turn 分发时的任务归属。
*/
import { ref } from 'vue';
import { computed, ref } from 'vue';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { createShippingMenuHandlers, type ShippingMenuHandlerContext } from './useChatShippingMenuHandler';
const {
confirmWorkspaceShippingInventorySource,
generateWorkspaceShippingExcel,
getWorkspaceShippingTask,
matchWorkspaceShippingInventory,
retryWorkspaceShippingUpload,
} = vi.hoisted(() => ({
confirmWorkspaceShippingInventorySource: vi.fn(),
generateWorkspaceShippingExcel: vi.fn(),
getWorkspaceShippingTask: vi.fn(),
matchWorkspaceShippingInventory: vi.fn(),
retryWorkspaceShippingUpload: vi.fn(),
}));
const { downloadWorkspaceShippingExcelFile } = vi.hoisted(() => ({
@@ -28,10 +22,7 @@ const { downloadWorkspaceShippingExcelFile } = vi.hoisted(() => ({
vi.mock('@/features/chat/api/shipping.api', () => ({
confirmWorkspaceShippingInventorySource,
generateWorkspaceShippingExcel,
getWorkspaceShippingTask,
matchWorkspaceShippingInventory,
retryWorkspaceShippingUpload,
}));
vi.mock('./shippingDownload', () => ({
@@ -42,10 +33,10 @@ const createContext = (
overrides: Partial<ShippingMenuHandlerContext> = {},
): ShippingMenuHandlerContext => ({
isThinking: ref(false),
currentAgentId: computed(() => 42),
getActiveShippingTaskId: () => 'SN-ACTIVE-001',
getActiveShippingBatchNo: () => 'BATCH-001',
messages: ref([]),
newLocalMessageId: vi.fn((prefix: string) => `${prefix}-local-id`),
saveLocalMessageToBackend: vi.fn(async () => undefined),
sendShippingMenuMessage: vi.fn(async () => undefined),
openShippingInventoryMappingFormForTask: vi.fn(async () => true),
openShippingInventoryPicker: vi.fn((_taskId?: string) => true),
@@ -53,6 +44,7 @@ const createContext = (
executeShippingDecision: vi.fn(async () => true),
executeShippingManualUpload: vi.fn(async () => true),
refreshShippingActions: vi.fn(async () => undefined),
startChatTurn: vi.fn(async () => true),
msg: {
warning: vi.fn(),
info: vi.fn(),
@@ -64,10 +56,7 @@ const createContext = (
describe('useChatShippingMenuHandler', () => {
beforeEach(() => {
confirmWorkspaceShippingInventorySource.mockReset();
generateWorkspaceShippingExcel.mockReset();
getWorkspaceShippingTask.mockReset();
matchWorkspaceShippingInventory.mockReset();
retryWorkspaceShippingUpload.mockReset();
downloadWorkspaceShippingExcelFile.mockReset();
});
@@ -76,28 +65,24 @@ describe('useChatShippingMenuHandler', () => {
const { handleShippingMenuAction } = createShippingMenuHandlers(ctx);
await handleShippingMenuAction(
{ id: 'retry_rpa', label: '重试 RPA', message: '重试 RPA' },
{ id: 'retry_rpa', label: '重新获取库存', message: '重新获取库存' },
undefined,
{ taskId: 'sn-target-009' },
);
expect(ctx.executeShippingDecision).toHaveBeenCalledWith(
'retry_rpa',
'重试 RPA',
'重新获取库存',
{ taskId: 'SN-TARGET-009' },
);
expect(ctx.executeShippingDecision).not.toHaveBeenCalledWith(
'retry_rpa',
'重试 RPA',
'重新获取库存',
{ taskId: 'SN-ACTIVE-001' },
);
});
it('uses explicit taskId for generate_excel workspace actions', async () => {
generateWorkspaceShippingExcel.mockResolvedValue({
message: '发货文件已生成',
data: {},
});
it('uses explicit taskId for generate_excel via Chat Turn', async () => {
const ctx = createContext();
const { handleShippingMenuAction } = createShippingMenuHandlers(ctx);
@@ -107,9 +92,14 @@ describe('useChatShippingMenuHandler', () => {
{ taskId: 'sn-target-777' },
);
expect(generateWorkspaceShippingExcel).toHaveBeenCalledWith('SN-TARGET-777');
expect(ctx.messages.value[0]?.content).toContain('SN-TARGET-777');
expect(ctx.messages.value[1]?.content).toContain('SN-TARGET-777');
expect(ctx.startChatTurn).toHaveBeenCalledWith(
expect.objectContaining({
inputType: 'action',
actionType: 'shipping.generate_excel',
payload: { task_no: 'SN-TARGET-777' },
refs: expect.objectContaining({ task_no: 'SN-TARGET-777' }),
}),
);
});
it('passes explicit taskId into inventory picker actions', async () => {
@@ -1,30 +1,24 @@
/**
* features/chat/shipping/useChatShippingMenuHandler.ts
* 用途:分发聊天气泡动作按钮点击,连接 API、决策处理、下载和文件选择器。
* 依赖:shipping.api、shippingDownload、shipping 常量、chat.types。
* 逻辑:由 useChatShipping 调用本文件;本文件根据 action.id 决定触发后端接口、本地消息落库或前端 UI 行为。
* 用途:分发聊天气泡动作按钮点击;业务动作统一走 Chat Turn SSE。
* 依赖:shippingTurnActions、shipping.api(只读 task 详情)、shippingDownload、chat.types。
* 逻辑:可映射为 action_type 的按钮走 startChatTurn;纯 UI(下载/选文件/表单)仍走本地行为。
*/
import {
confirmWorkspaceShippingInventorySource,
generateWorkspaceShippingExcel,
getWorkspaceShippingTask,
matchWorkspaceShippingInventory,
retryWorkspaceShippingUpload,
type ShippingDecisionResponse,
type ShippingMatchLineResult,
} from '@/features/chat/api/shipping.api';
import { getWorkspaceShippingTask } from '@/features/chat/api/shipping.api';
import { SHIPPING_DECISION_ACTIONS } from '../constants/shipping';
import { downloadWorkspaceShippingExcelFile } from './shippingDownload';
import { buildShippingTurnRefs, resolveShippingChatTurn } from './shippingTurnActions';
import type { StartChatTurnOptions } from '../types/chat-turn.types';
import type { ChatMessage } from '../types/chat.types';
import type { ShippingActionButton, ShippingMatchResultPayload } from '../types/shipping.types';
import type { Ref } from 'vue';
import type { ShippingActionButton } from '../types/shipping.types';
import type { ComputedRef, Ref } from 'vue';
export interface ShippingMenuHandlerContext {
isThinking: Ref<boolean>;
currentAgentId: ComputedRef<number>;
getActiveShippingTaskId: () => string;
getActiveShippingBatchNo: () => string;
messages: Ref<ChatMessage[]>;
newLocalMessageId: (prefix: string) => string;
saveLocalMessageToBackend: (msg: ChatMessage, userQuery?: string) => Promise<void>;
sendShippingMenuMessage: (message: string) => Promise<void>;
openShippingInventoryMappingFormForTask: (taskId: string) => Promise<boolean>;
openShippingInventoryPicker: (taskId?: string) => boolean;
@@ -36,6 +30,7 @@ export interface ShippingMenuHandlerContext {
) => Promise<boolean>;
executeShippingManualUpload: (taskId: string, displayText?: string) => Promise<boolean>;
refreshShippingActions: () => Promise<void>;
startChatTurn: (options: StartChatTurnOptions) => Promise<boolean>;
msg: { warning: (text: string) => void; info: (text: string) => void };
t: (key: string) => string;
}
@@ -46,10 +41,6 @@ export interface HandleShippingMenuActionOptions {
/**
* 创建发货通知动作菜单处理器。
*
* 核心逻辑:按 action.id 分流到生成 Excel、库存匹配、人工决策、手工上传确认等前后端动作。
* @param ctx - 动作菜单上下文
* @returns 菜单动作与按钮点击处理函数
*/
export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
const normalizeInventorySourceText = (value: string) =>
@@ -96,29 +87,32 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
return String((matches[0] as { source_code?: unknown }).source_code || '').trim().toUpperCase();
};
const buildMatchResultPayload = (
const runShippingActionTurn = async (
action: ShippingActionButton | { id?: string; message: string; label?: string },
taskId: string,
result: ShippingDecisionResponse & { action_buttons?: Array<{ id: string; label: string; message: string; variant?: 'primary' | 'secondary' | 'danger'; source_code?: string }> },
): ShippingMatchResultPayload => {
const data = (result?.data && typeof result.data === 'object') ? result.data as Record<string, unknown> : {};
const lineResults = Array.isArray(data.line_results)
? data.line_results as ShippingMatchLineResult[]
: [];
const shortageRaw = data.shortage && typeof data.shortage === 'object'
? data.shortage as { lines?: ShippingMatchLineResult[] }
: null;
return {
taskId,
match_status: typeof data.match_status === 'string' ? data.match_status : null,
line_results: lineResults,
shortage_lines: Array.isArray(shortageRaw?.lines) ? shortageRaw.lines : [],
action_buttons: Array.isArray(result.action_buttons)
? result.action_buttons.map((action) => ({
...action,
variant: action.variant || 'secondary',
}))
: [],
};
extra?: { sourceCode?: string },
) => {
const actionId = String(action.id || '').trim();
const turnSpec = resolveShippingChatTurn(actionId, taskId, extra);
if (!turnSpec) return false;
const displayBase = String(action.message || actionId || '操作').trim();
const displayText = actionId === 'confirm_inventory_source'
? `${displayBase}\n任务编号:${taskId}`
: `${displayBase}(任务编号:${taskId})`;
await ctx.startChatTurn({
agentId: ctx.currentAgentId.value,
inputType: 'action',
displayText,
actionType: turnSpec.actionType,
payload: turnSpec.payload,
refs: buildShippingTurnRefs(taskId, ctx.getActiveShippingBatchNo()),
hooks: {
onAssistantMessageFinished: async () => {
void ctx.refreshShippingActions();
},
},
});
return true;
};
const handleShippingMenuAction = async (
@@ -129,6 +123,7 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
const explicitTaskId = String(options?.taskId || '').trim().toUpperCase();
const resolveTaskId = () => explicitTaskId || ctx.getActiveShippingTaskId();
if (ctx.isThinking.value) return;
if (action.id === 'refresh') {
await ctx.refreshShippingActions();
ctx.msg.info(ctx.t('chat.shippingNoticeRefreshDone'));
@@ -143,129 +138,61 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
try {
await downloadWorkspaceShippingExcelFile(taskId);
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : '下载 Excel 失败';
ctx.msg.warning(errorMessage);
ctx.msg.warning(e instanceof Error ? e.message : '下载 Excel 失败');
}
return;
}
if (action.id === 'generate_excel') {
const chatTurnActionIds = new Set([
'generate_excel',
'retry_upload',
'match_inventory',
'mark_manual_uploaded',
'confirm_inventory_source',
]);
if (action.id && chatTurnActionIds.has(action.id)) {
if (chatMsg?.shipping_actions_used) return;
if (chatMsg) chatMsg.shipping_actions_used = true;
const taskId = resolveTaskId();
if (!taskId) {
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
if (chatMsg) chatMsg.shipping_actions_used = false;
return;
}
try {
const result = await generateWorkspaceShippingExcel(taskId);
const userMsg: ChatMessage = {
role: 'user',
type: 'text',
content: `${action.message || '生成发货 Excel'}(任务编号:${taskId})`,
local_id: ctx.newLocalMessageId('shipping-user'),
local_only: true,
};
const assistantMsg: ChatMessage = {
role: 'assistant',
type: 'text',
content: [
String(result.message || '').trim(),
`任务编号:${taskId}`,
].filter(Boolean).join('\n'),
local_id: ctx.newLocalMessageId('shipping-assistant'),
local_only: true,
};
ctx.messages.value.push(userMsg, assistantMsg);
await ctx.saveLocalMessageToBackend(userMsg, action.message || '生成发货 Excel');
await ctx.saveLocalMessageToBackend(assistantMsg);
void ctx.refreshShippingActions();
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : '生成发货 Excel 失败';
ctx.msg.warning(errorMessage);
}
return;
}
if (action.id === 'retry_upload') {
if (chatMsg?.shipping_actions_used) return;
if (chatMsg) chatMsg.shipping_actions_used = true;
const taskId = resolveTaskId();
if (!taskId) {
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
return;
}
try {
const result = await retryWorkspaceShippingUpload(taskId);
const userText = action.message || ctx.t('chat.shippingNoticeRetryUploadAction');
const userMsg: ChatMessage = {
role: 'user',
type: 'text',
content: `${userText}\n任务编号:${taskId}`,
local_id: ctx.newLocalMessageId('shipping-user'),
local_only: true,
};
const assistantMsg: ChatMessage = {
role: 'assistant',
type: 'text',
content: String(result.message || ctx.t('chat.shippingNoticeRetryUploadQueued')).trim(),
local_id: ctx.newLocalMessageId('shipping-assistant'),
local_only: true,
};
ctx.messages.value.push(userMsg, assistantMsg);
await ctx.saveLocalMessageToBackend(userMsg, userText);
await ctx.saveLocalMessageToBackend(assistantMsg);
void ctx.refreshShippingActions();
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingNoticeRetryUploadFailed');
ctx.msg.warning(errorMessage);
}
return;
}
if (action.id === 'confirm_inventory_source') {
if (chatMsg?.shipping_actions_used) return;
if (chatMsg) chatMsg.shipping_actions_used = true;
const taskId = resolveTaskId();
if (!taskId) {
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
return;
}
try {
let sourceCode = String((action as { source_code?: unknown }).source_code || '').trim().toUpperCase();
if (!sourceCode) {
sourceCode = await resolveInventorySourceCodeFromContext(taskId);
let sourceCode = '';
if (action.id === 'confirm_inventory_source') {
sourceCode = String((action as { source_code?: unknown }).source_code || '').trim().toUpperCase();
if (!sourceCode) {
sourceCode = await resolveInventorySourceCodeFromContext(taskId);
}
if (!sourceCode) {
ctx.msg.warning('请直接输入要使用的库存源线索,例如 AWSDU、Dublin 或 Singapore。');
if (chatMsg) chatMsg.shipping_actions_used = false;
return;
}
}
if (!sourceCode) {
ctx.msg.warning('请直接输入要使用的库存源线索,例如 AWSDU、Dublin 或 Singapore。');
if (chatMsg) chatMsg.shipping_actions_used = false;
if (action.id === 'mark_manual_uploaded') {
await ctx.executeShippingManualUpload(taskId, '我已在货代系统完成上传');
return;
}
const result = await confirmWorkspaceShippingInventorySource(taskId, sourceCode);
const label = String(('label' in action ? action.label : '') || sourceCode).trim();
const userText = `确认库存查询来源:${label}`;
const userMsg: ChatMessage = {
role: 'user',
type: 'text',
content: `${userText}\n任务编号:${taskId}`,
local_id: ctx.newLocalMessageId('shipping-user'),
local_only: true,
};
const assistantMsg: ChatMessage = {
role: 'assistant',
type: 'text',
content: String(result.message || '').trim(),
local_id: ctx.newLocalMessageId('shipping-assistant'),
local_only: true,
};
ctx.messages.value.push(userMsg, assistantMsg);
await ctx.saveLocalMessageToBackend(userMsg, userText);
await ctx.saveLocalMessageToBackend(assistantMsg);
void ctx.refreshShippingActions();
const displayMessage = action.id === 'confirm_inventory_source'
? `确认库存查询来源:${label || sourceCode}`
: action.message;
await runShippingActionTurn(
{ ...action, message: displayMessage },
taskId,
sourceCode ? { sourceCode } : undefined,
);
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : '确认库存源失败';
ctx.msg.warning(errorMessage);
ctx.msg.warning(e instanceof Error ? e.message : '操作失败');
if (chatMsg) chatMsg.shipping_actions_used = false;
}
return;
}
if (action.id === 'retry_resolve_inventory_source') {
await ctx.refreshShippingActions();
ctx.msg.info('已重新刷新库存源状态');
@@ -288,55 +215,6 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
ctx.openShippingNoticePicker(resolveTaskId());
return;
}
if (action.id === 'match_inventory') {
if (chatMsg?.shipping_actions_used) return;
if (chatMsg) chatMsg.shipping_actions_used = true;
const taskId = resolveTaskId();
if (!taskId) {
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
return;
}
try {
const result = await matchWorkspaceShippingInventory(taskId);
const userMsg: ChatMessage = {
role: 'user',
type: 'text',
content: `${action.message || '匹配库存'}(任务编号:${taskId})`,
local_id: ctx.newLocalMessageId('shipping-user'),
local_only: true,
};
const assistantMsg: ChatMessage = {
role: 'assistant',
type: 'shipping-match-result',
content: String(result.message || '').trim(),
payload: buildMatchResultPayload(taskId, result),
local_id: ctx.newLocalMessageId('shipping-assistant'),
local_only: true,
};
ctx.messages.value.push(userMsg, assistantMsg);
await ctx.saveLocalMessageToBackend(userMsg, action.message || '匹配库存');
await ctx.saveLocalMessageToBackend(assistantMsg);
void ctx.refreshShippingActions();
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : '匹配库存失败';
ctx.msg.warning(errorMessage);
}
return;
}
if (action.id === 'mark_manual_uploaded') {
if (chatMsg?.shipping_actions_used) return;
if (chatMsg) {
chatMsg.shipping_actions_used = true;
chatMsg.shipping_actions = undefined;
}
const taskId = resolveTaskId();
if (!taskId) {
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
return;
}
await ctx.executeShippingManualUpload(taskId, '我已在货代系统完成上传');
return;
}
if (action.id === 'paste_inventory_json') {
ctx.msg.info(ctx.t('chat.shippingNoticePasteHint'));
return;
@@ -2,18 +2,14 @@
* features/chat/shipping/useChatShippingSendHandler.ts
* 用途:在聊天发送前拦截发货通知专属意图,如切票、决策文本、列映射和附件自动流程。
* 依赖:shipping.api、shippingIntents、shippingMenu、shippingMapping、shippingDownload、chat.types。
* 逻辑:由 useChatShipping 调用本文件;本文件优先消费 shipping 领域意图,只有未命中时才放行到默认 Dify 对话链路。
* 逻辑:业务动作经 Chat Turn / handleShippingMenuAction;纯 UI(下载/选文件/映射卡片)保留本地或客户端行为。
*/
import {
applyWorkspaceShippingInventoryMapping,
confirmWorkspaceShippingInventorySource,
generateWorkspaceShippingExcel,
getWorkspaceShippingBatch,
getWorkspaceShippingTask,
switchWorkspaceShippingBatchFocusTask,
} from '@/features/chat/api/shipping.api';
import { SHIPPING_DECISION_ACTIONS, SHIPPING_MENU_ACTION_SPECS } from '../constants/shipping';
import { buildShippingFieldAlignmentText } from './shippingMapping';
import { buildShippingApplyMappingTurn, buildShippingSwitchFocusTurn } from './shippingTurnActions';
import { downloadWorkspaceShippingExcelFile } from './shippingDownload';
import {
isShippingDownloadExcelIntent,
@@ -26,8 +22,9 @@ import {
import { resolveShippingDecisionFromText, resolveShippingNumericChoice } from './shippingMenu';
import { classifyShippingUploadFile } from './shippingUploadPrompt';
import { extractExt } from '../constants/shipping';
import type { StartChatTurnOptions } from '../types/chat-turn.types';
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
import type { ChatUploadFileSpec, PendingAttachment } from '../types/shipping.types';
import type { ChatUploadFileSpec, PendingAttachment, ShippingActionButton } from '../types/shipping.types';
import type { ComputedRef, Ref } from 'vue';
export interface ShippingSendHandlerContext {
@@ -57,12 +54,11 @@ export interface ShippingSendHandlerContext {
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
loadHistory: () => Promise<void>;
sendShippingMenuMessage: (message: string) => Promise<void>;
pushShippingLocalUserMessage: (text: string) => Promise<void>;
pushShippingLocalAssistantMessage: (text: string) => Promise<void>;
startChatTurn: (options: StartChatTurnOptions) => Promise<boolean>;
openShippingInventoryPicker: () => boolean;
executeShippingDecision: (decision: string, displayText?: string) => Promise<boolean>;
executeShippingManualUpload: (taskId: string, displayText?: string) => Promise<boolean>;
handleShippingMenuAction: (action: { id?: string; message: string }) => Promise<void>;
handleShippingMenuAction: (action: ShippingActionButton | { id?: string; message: string; label?: string; source_code?: string }) => Promise<void>;
handleShippingAutoUploadFile: (file: File) => Promise<void>;
handleShippingAutoUploadNoticeBatch: (files: File[]) => Promise<void>;
refreshShippingActions: () => Promise<void>;
@@ -116,16 +112,12 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
ctx.input.value = '';
ctx.attachments.value = [];
const label = String(hit?.display_name || sourceCode).trim();
await ctx.pushShippingLocalUserMessage(content.trim());
const result = await confirmWorkspaceShippingInventorySource(taskId, sourceCode);
await ctx.pushShippingLocalAssistantMessage(
[
String(result.message || '').trim(),
`已确认库存查询来源:${label}`,
`任务编号:${taskId}`,
].filter(Boolean).join('\n'),
);
void ctx.refreshShippingActions();
await ctx.handleShippingMenuAction({
id: 'confirm_inventory_source',
message: `确认库存查询来源:${label}`,
label,
source_code: sourceCode,
});
return true;
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : '确认库存源失败';
@@ -167,11 +159,21 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
ctx.msg.info(intent.mode === 'next' ? '已经是最后一票' : intent.mode === 'prev' ? '已经是第一票' : '已在当前任务');
return true;
}
await switchWorkspaceShippingBatchFocusTask(batchNo, targetTaskNo);
ctx.resolvedShippingTaskId.value = targetTaskNo;
await ctx.pushShippingLocalUserMessage(content.trim());
await ctx.pushShippingLocalAssistantMessage(`已切换到任务 ${targetTaskNo},请继续当前票处理。`);
void ctx.refreshShippingActions();
const turn = buildShippingSwitchFocusTurn(batchNo, targetTaskNo, content.trim());
await ctx.startChatTurn({
agentId: ctx.currentAgentId.value,
inputType: 'action',
displayText: turn.displayText,
actionType: turn.actionType,
payload: turn.payload,
refs: turn.refs,
hooks: {
onAssistantMessageFinished: async () => {
void ctx.refreshShippingActions();
},
},
});
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : '切换任务失败';
ctx.msg.warning(errorMessage);
@@ -203,8 +205,6 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
ctx.msg.warning('一次仅支持处理一个文件,将自动处理第一个');
}
try {
const prompt = trimmed || ctx.shippingSuggestedPrompt.value || '上传库存并进入字段对齐';
await ctx.pushShippingLocalUserMessage(prompt);
await ctx.handleShippingAutoUploadFile(first.file);
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : '文件处理失败';
@@ -295,23 +295,20 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
ctx.resolvedShippingTaskId.value = taskId;
if (typeof textOrEvent !== 'string') ctx.input.value = '';
ctx.attachments.value = [];
await ctx.pushShippingLocalUserMessage(content.trim());
try {
const result = await applyWorkspaceShippingInventoryMapping(taskId, mapping);
const alignmentText = buildShippingFieldAlignmentText(result);
const hint = alignmentText || String(result.message || '').trim();
await ctx.pushShippingLocalAssistantMessage(
[
`映射已应用:${Object.entries(mapping).map(([k, v]) => `${k}=${v}`).join(',')}`,
`任务编号:${taskId}`,
hint,
].filter(Boolean).join('\n'),
);
void ctx.refreshShippingActions();
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : '应用映射失败';
ctx.msg.warning(errorMessage);
}
const turn = buildShippingApplyMappingTurn(taskId, mapping);
await ctx.startChatTurn({
agentId: ctx.currentAgentId.value,
inputType: 'form_submit',
displayText: `${content.trim()}\n任务编号:${taskId}`,
actionType: turn.actionType,
payload: turn.payload,
refs: turn.refs,
hooks: {
onAssistantMessageFinished: async () => {
void ctx.refreshShippingActions();
},
},
});
return true;
}
}
@@ -340,20 +337,7 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
ctx.resolvedShippingTaskId.value = taskId;
if (typeof textOrEvent !== 'string') ctx.input.value = '';
ctx.attachments.value = [];
await ctx.pushShippingLocalUserMessage(content.trim());
try {
const result = await generateWorkspaceShippingExcel(taskId);
await ctx.pushShippingLocalAssistantMessage(
[
String(result.message || '').trim() || '已生成发货 Excel',
`任务编号:${taskId}`,
].filter(Boolean).join('\n'),
);
void ctx.refreshShippingActions();
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : '生成发货 Excel 失败';
ctx.msg.warning(errorMessage);
}
await ctx.handleShippingMenuAction({ id: 'generate_excel', message: content.trim() });
return true;
}
if (isShippingDownloadExcelIntent(content)) {
@@ -365,7 +349,6 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
ctx.resolvedShippingTaskId.value = taskId;
if (typeof textOrEvent !== 'string') ctx.input.value = '';
ctx.attachments.value = [];
await ctx.pushShippingLocalUserMessage(content.trim());
try {
await downloadWorkspaceShippingExcelFile(taskId);
} catch (e: unknown) {
@@ -2,38 +2,28 @@
* features/chat/shipping/useChatShippingUploadHandler.spec.ts
* 用途:验证发货通知上传 handler 在显式 taskId 场景下不会把库存/通知文件错投到当前激活任务。
* 依赖:vitest、vue refs、shipping.api、useChatShippingUploadHandler。
* 逻辑:覆盖库存/通知 picker 的任务锁定,以及 notice replace 在 pending task 锁定下命中指定任务。
* 逻辑:覆盖库存/通知 picker 的任务锁定,以及 Chat Turn 建批/覆盖路径。
*/
import { ref } from 'vue';
import { computed, ref } from 'vue';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
createShippingUploadHandlers,
type ShippingUploadHandlerContext,
} from './useChatShippingUploadHandler';
const {
createWorkspaceShippingBatchFromNotices,
createWorkspaceShippingTask,
replaceWorkspaceShippingTaskNotice,
uploadWorkspaceShippingInventory,
} = vi.hoisted(() => ({
createWorkspaceShippingBatchFromNotices: vi.fn(),
const { createWorkspaceShippingTask } = vi.hoisted(() => ({
createWorkspaceShippingTask: vi.fn(),
replaceWorkspaceShippingTaskNotice: vi.fn(),
uploadWorkspaceShippingInventory: vi.fn(),
}));
vi.mock('@/features/chat/api/shipping.api', () => ({
createWorkspaceShippingBatchFromNotices,
createWorkspaceShippingTask,
replaceWorkspaceShippingTaskNotice,
uploadWorkspaceShippingInventory,
}));
const createContext = (
overrides: Partial<ShippingUploadHandlerContext> = {},
): ShippingUploadHandlerContext => ({
conversationId: ref('conv-upload'),
currentAgentId: computed(() => 42),
attachments: ref([]),
input: ref(''),
shippingAutoFlowRequested: ref(false),
@@ -50,28 +40,16 @@ const createContext = (
shippingInventorySelectionTaskId: ref(''),
shippingInventorySchemaPreviewCache: ref({}),
getActiveShippingTaskId: () => 'SN-ACTIVE-001',
sendShippingMenuMessage: vi.fn(async () => undefined),
pushShippingLocalUserMessage: vi.fn(async () => undefined),
pushShippingLocalAssistantMessage: vi.fn(async () => undefined),
startChatTurn: vi.fn(async () => true),
refreshShippingActions: vi.fn(async () => undefined),
msg: { warning: vi.fn() },
t: (key: string, params?: Record<string, unknown>) => {
if (key === 'chat.shippingNoticeInventoryUploadStarted') {
return `开始上传库存:${String(params?.fileName || '')}`;
}
if (key === 'chat.shippingNoticeMissingTaskId') return '缺少任务编号';
if (key === 'chat.shippingNoticeUploadFailed') return '上传失败';
return key;
},
t: (key: string) => key,
...overrides,
});
describe('useChatShippingUploadHandler', () => {
beforeEach(() => {
createWorkspaceShippingBatchFromNotices.mockReset();
createWorkspaceShippingTask.mockReset();
replaceWorkspaceShippingTaskNotice.mockReset();
uploadWorkspaceShippingInventory.mockReset();
});
it('opens inventory picker for explicit taskId instead of current active task', () => {
@@ -88,11 +66,7 @@ describe('useChatShippingUploadHandler', () => {
expect(inventoryClick).toHaveBeenCalledTimes(1);
});
it('replaces notice on locked pending task instead of current active task', async () => {
replaceWorkspaceShippingTaskNotice.mockResolvedValue({
message: '已覆盖通知',
data: { orchestrator_started: true },
});
it('replaces notice on locked pending task via Chat Turn', async () => {
const ctx = createContext({
pendingShippingNoticeTaskId: ref('SN-TARGET-200'),
});
@@ -101,11 +75,34 @@ describe('useChatShippingUploadHandler', () => {
await handleShippingAutoUploadNoticeBatch([file]);
expect(replaceWorkspaceShippingTaskNotice).toHaveBeenCalledWith('SN-TARGET-200', file);
expect(replaceWorkspaceShippingTaskNotice).not.toHaveBeenCalledWith('SN-ACTIVE-001', file);
expect(ctx.startChatTurn).toHaveBeenCalledWith(
expect.objectContaining({
actionType: 'shipping.replace_notice',
files: [file],
}),
);
expect(ctx.pendingShippingNoticeTaskId.value).toBe('');
});
it('creates notice batch via Chat Turn instead of local assistant push', async () => {
const ctx = createContext({
getActiveShippingTaskId: () => '',
});
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([file]);
expect(ctx.startChatTurn).toHaveBeenCalledWith(
expect.objectContaining({
inputType: 'upload_followup',
actionType: 'shipping.create_batch_from_notices',
displayText: expect.stringContaining('notice.pdf'),
files: [file],
}),
);
});
it('does not open notice picker when both explicit taskId and active task are missing', () => {
const noticeClick = vi.fn();
const warning = vi.fn();
@@ -120,7 +117,7 @@ describe('useChatShippingUploadHandler', () => {
expect(ok).toBe(false);
expect(noticeClick).not.toHaveBeenCalled();
expect(warning).toHaveBeenCalledWith('缺少任务编号');
expect(warning).toHaveBeenCalled();
expect(ctx.pendingShippingNoticeTaskId.value).toBe('');
});
});
@@ -2,23 +2,24 @@
* features/chat/shipping/useChatShippingUploadHandler.ts
* 用途:处理发货通知与库存文件上传、批量建单和附件建议提示。
* 依赖:shipping.api、shippingUploadPrompt、shipping 常量、chat.types。
* 逻辑:由 useChatShipping 调用本文件;本文件识别附件类型后决定是创建任务/批次还是上传库存,并把结果同步到聊天上下文。
* 逻辑:发货通知建批/库存上传/单票覆盖均经 startChatTurn + multipart SSE。
*/
import { computed } from 'vue';
import {
createWorkspaceShippingBatchFromNotices,
createWorkspaceShippingTask,
replaceWorkspaceShippingTaskNotice,
uploadWorkspaceShippingInventory,
type ShippingTaskSummary,
} from '@/features/chat/api/shipping.api';
import { extractExt } from '../constants/shipping';
import { buildShippingInventoryUploadPrompt, classifyShippingUploadFile } from './shippingUploadPrompt';
import { buildShippingCreateBatchTurn, buildShippingReplaceNoticeTurn, buildShippingUploadInventoryTurn } from './shippingTurnActions';
import { classifyShippingUploadFile } from './shippingUploadPrompt';
import type { StartChatTurnOptions } from '../types/chat-turn.types';
import type { ChatMessage } from '../types/chat.types';
import type { PendingAttachment } from '../types/shipping.types';
import type { Ref } from 'vue';
import type { ComputedRef, Ref } from 'vue';
export interface ShippingUploadHandlerContext {
conversationId: Ref<string | null>;
currentAgentId: ComputedRef<number>;
attachments: Ref<PendingAttachment[]>;
input: Ref<string>;
shippingAutoFlowRequested: Ref<boolean>;
@@ -35,9 +36,7 @@ export interface ShippingUploadHandlerContext {
shippingInventorySelectionTaskId: Ref<string>;
shippingInventorySchemaPreviewCache: Ref<Record<string, unknown>>;
getActiveShippingTaskId: () => string;
sendShippingMenuMessage: (message: string) => Promise<void>;
pushShippingLocalUserMessage: (text: string) => Promise<void>;
pushShippingLocalAssistantMessage: (text: string) => Promise<void>;
startChatTurn: (options: StartChatTurnOptions) => Promise<boolean>;
refreshShippingActions: () => Promise<void>;
msg: { warning: (text: string) => void };
t: (key: string, params?: Record<string, unknown>) => string;
@@ -56,35 +55,41 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
ctx.shippingInventorySelectionTaskId.value = '';
};
const continueShippingInventoryUploadWithDify = async (
taskId: string,
result: Record<string, unknown> | null | undefined,
fileName?: string,
) => {
const key = String(taskId || '').trim().toUpperCase();
const schemaPreview = (result?.data as { schema_preview?: unknown } | undefined)?.schema_preview;
if (key && schemaPreview && typeof schemaPreview === 'object') {
ctx.shippingInventorySchemaPreviewCache.value = {
...ctx.shippingInventorySchemaPreviewCache.value,
[key]: schemaPreview,
};
}
ctx.resolvedShippingTaskId.value = taskId;
await ctx.sendShippingMenuMessage(buildShippingInventoryUploadPrompt(result, fileName));
const runInventoryUploadChatTurn = async (taskId: string, file: File) => {
const turn = buildShippingUploadInventoryTurn(taskId, file);
const ok = await ctx.startChatTurn({
agentId: ctx.currentAgentId.value,
inputType: 'upload_followup',
displayText: turn.displayText,
actionType: turn.actionType,
payload: turn.payload,
files: turn.files,
refs: turn.refs,
hooks: {
onAssistantMessageFinished: async (assistantMsg) => {
const payload = assistantMsg.payload && typeof assistantMsg.payload === 'object'
? assistantMsg.payload as { schema_preview?: unknown; task_no?: string }
: {};
const key = String(payload.task_no || taskId || '').trim().toUpperCase();
const preview = payload.schema_preview;
if (key && preview && typeof preview === 'object') {
ctx.shippingInventorySchemaPreviewCache.value = {
...ctx.shippingInventorySchemaPreviewCache.value,
[key]: preview,
};
}
syncBatchContextFromTurnMessage(assistantMsg);
void ctx.refreshShippingActions();
},
},
});
if (!ok) ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
return ok;
};
const uploadInventoryForTask = async (taskId: string, file: File) => {
ctx.resolvedShippingTaskId.value = taskId;
await ctx.pushShippingLocalUserMessage(ctx.t('chat.shippingNoticeInventoryUploadStarted', { fileName: file.name }));
const result = await uploadWorkspaceShippingInventory(taskId, file);
const batchNo = String(
((result as unknown as { data?: { batch_no?: string } }).data?.batch_no)
|| ((result as unknown as { data?: { batch?: { batch_no?: string } } }).data?.batch?.batch_no)
|| '',
).trim();
if (batchNo) ctx.resolvedShippingBatchNo.value = batchNo;
await continueShippingInventoryUploadWithDify(taskId, result as unknown as Record<string, unknown>, file.name);
void ctx.refreshShippingActions();
await runInventoryUploadChatTurn(taskId, file);
};
const selectShippingInventoryUploadTask = (taskId: string): boolean => {
@@ -119,6 +124,38 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
resetInventoryTaskSelection();
};
const syncBatchContextFromTurnMessage = (assistantMsg: ChatMessage) => {
const payload = assistantMsg.payload && typeof assistantMsg.payload === 'object'
? assistantMsg.payload as { batch_no?: string; task_no?: string; orchestrator_started?: boolean }
: {};
const batchNo = String(payload.batch_no || assistantMsg.shipping_ui_state?.batch_no || '').trim();
const taskId = String(payload.task_no || assistantMsg.shipping_ui_state?.task_no || '').trim();
if (batchNo) ctx.resolvedShippingBatchNo.value = batchNo;
if (taskId) ctx.resolvedShippingTaskId.value = taskId;
};
const runNoticeBatchChatTurn = async (files: File[]) => {
const turn = buildShippingCreateBatchTurn(files, ctx.conversationId.value);
const ok = await ctx.startChatTurn({
agentId: ctx.currentAgentId.value,
inputType: 'upload_followup',
displayText: turn.displayText,
actionType: turn.actionType,
payload: turn.payload,
files: turn.files,
hooks: {
onAssistantMessageFinished: async (assistantMsg) => {
syncBatchContextFromTurnMessage(assistantMsg);
void ctx.refreshShippingActions();
},
},
});
if (!ok) {
ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
}
return ok;
};
const syncBatchContextFromNoticeResponse = (result: Record<string, unknown> | null | undefined) => {
const batchNo = String(
(result?.batch_no as string | undefined)
@@ -138,24 +175,30 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
}
};
const runReplaceNoticeChatTurn = async (taskId: string, file: File) => {
const turn = buildShippingReplaceNoticeTurn(taskId, file);
const ok = await ctx.startChatTurn({
agentId: ctx.currentAgentId.value,
inputType: 'upload_followup',
displayText: turn.displayText,
actionType: turn.actionType,
payload: turn.payload,
files: turn.files,
refs: turn.refs,
hooks: {
onAssistantMessageFinished: async (assistantMsg) => {
syncBatchContextFromTurnMessage(assistantMsg);
void ctx.refreshShippingActions();
},
},
});
if (!ok) ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
return ok;
};
const handleReplaceNoticeForCurrentTask = async (taskId: string, file: File) => {
const result = await replaceWorkspaceShippingTaskNotice(taskId, file);
syncBatchContextFromNoticeResponse(result as unknown as Record<string, unknown>);
ctx.resolvedShippingTaskId.value = taskId;
const hint = String(result.message || '').trim();
const status = String((result as { status?: string }).status || '').trim();
const orchestratorStarted = Boolean(
(result.data as { orchestrator_started?: boolean } | undefined)?.orchestrator_started,
);
await ctx.pushShippingLocalAssistantMessage(
[
hint || `已重新上传发货通知并覆盖当前任务 ${taskId}`,
`任务编号:${taskId}`,
orchestratorStarted ? '后台已开始重新解析当前任务,请稍后查看进度自动刷新。' : '',
status === 'needs_human' ? '请根据提示重新上传清晰文件,或粘贴通知正文。' : '',
].filter(Boolean).join('\n'),
);
void ctx.refreshShippingActions();
await runReplaceNoticeChatTurn(taskId, file);
};
const handleShippingAutoUploadFile = async (file: File) => {
@@ -184,37 +227,7 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
await handleReplaceNoticeForCurrentTask(targetTaskId, file);
return;
}
const result = await createWorkspaceShippingBatchFromNotices(
[file],
String(ctx.conversationId.value || '').trim() || undefined,
);
syncBatchContextFromNoticeResponse(result as unknown as Record<string, unknown>);
const taskId = String(
((result.data as { focus_task?: { task_no?: string } } | undefined)?.focus_task?.task_no)
|| result.task_id
|| '',
).trim();
const batchNo = String(
result.batch_no
|| ((result.data as { batch?: { batch_no?: string } } | undefined)?.batch?.batch_no)
|| '',
).trim();
const hint = String(result.message || '').trim();
const status = String((result as { status?: string }).status || '').trim();
const orchestratorStarted = Boolean(
(result.data as { orchestrator_started?: boolean } | undefined)?.orchestrator_started,
);
const tail = status === 'needs_human' ? '请根据提示进行确认/驳回。' : '';
await ctx.pushShippingLocalAssistantMessage(
[
hint || `已处理发货通知附件:${file.name}`,
batchNo ? `批次编号:${batchNo}` : '',
taskId ? `任务编号:${taskId}` : '',
orchestratorStarted ? '后台已开始按票处理,请稍后查看进度自动刷新。' : '',
tail,
].filter(Boolean).join('\n'),
);
void ctx.refreshShippingActions();
await runNoticeBatchChatTurn([file]);
};
const handleShippingAutoUploadNoticeBatch = async (files: File[]) => {
@@ -228,50 +241,7 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
await handleReplaceNoticeForCurrentTask(activeTaskId, singleNoticeFile);
return;
}
const result = await createWorkspaceShippingBatchFromNotices(
noticeFiles,
String(ctx.conversationId.value || '').trim() || undefined,
);
syncBatchContextFromNoticeResponse(result as unknown as Record<string, unknown>);
const taskId = String(
((result.data as { focus_task?: { task_no?: string } } | undefined)?.focus_task?.task_no)
|| result.task_id
|| '',
).trim();
const batchNo = String(
result.batch_no
|| ((result.data as { batch?: { batch_no?: string } } | undefined)?.batch?.batch_no)
|| '',
).trim();
const batch = (result.data as {
batch?: { file_count?: number };
tasks?: Array<{ batch_index?: number; batch_total?: number }>;
} | undefined)?.batch;
const tasks = Array.isArray((result.data as { tasks?: unknown[] } | undefined)?.tasks)
? (result.data as { tasks: Array<{ batch_index?: number; batch_total?: number }> }).tasks
: [];
const focusTask = tasks[0];
const focusProgress = focusTask?.batch_index && focusTask?.batch_total
? `当前第 ${focusTask.batch_index}/${focusTask.batch_total} 票`
: '';
const fileCount = Number(batch?.file_count || noticeFiles.length || 0);
const hint = String(result.message || '').trim();
const status = String((result as { status?: string }).status || '').trim();
const orchestratorStarted = Boolean(
(result.data as { orchestrator_started?: boolean } | undefined)?.orchestrator_started,
);
const tail = status === 'needs_human' ? '请根据提示进行确认/驳回。' : '';
await ctx.pushShippingLocalAssistantMessage(
[
hint || `已处理 ${fileCount} 份发货通知附件`,
batchNo ? `批次编号:${batchNo}` : '',
taskId ? `当前任务:${taskId}` : '',
focusProgress,
orchestratorStarted ? `后台已开始按票拆分处理,本批 ${fileCount} 票会逐步更新状态。` : '',
tail,
].filter(Boolean).join('\n'),
);
void ctx.refreshShippingActions();
await runNoticeBatchChatTurn(noticeFiles);
};
const openShippingInventoryPicker = (taskId?: string): boolean => {
@@ -0,0 +1,33 @@
/**
* features/chat/training/trainingWorkspace.utils.test.ts
* 用途:锁定培训工作区 Agent 识别契约(content_profile / extra_config,非名称)。
*/
import { describe, expect, it } from 'vitest';
import { matchesTrainingAgent } from './trainingWorkspace.utils';
describe('matchesTrainingAgent', () => {
it('matches handler_config.content_profile=training', () => {
expect(matchesTrainingAgent({
name: '任意名称',
handler_config: { content_profile: 'training' },
})).toBe(true);
});
it('matches explicit extra_config training flags', () => {
expect(matchesTrainingAgent({
name: '普通 Agent',
extra_config: { training_workspace_enabled: true },
})).toBe(true);
});
it('does not match generic agent by name alone', () => {
expect(matchesTrainingAgent({ name: '新人培训助手' })).toBe(false);
});
it('respects training_workspace_enabled=false override', () => {
expect(matchesTrainingAgent({
handler_config: { content_profile: 'training' },
extra_config: { training_workspace_enabled: false },
})).toBe(false);
});
});
@@ -8,6 +8,10 @@ import type { TrainingContentConfig, TrainingQuestion, TrainingQuestionOption }
type TrainingAgentLike = {
name?: string | null;
handler_config?: {
content_profile?: string | null;
[key: string]: unknown;
} | null;
extra_config?: Record<string, unknown> | null;
} | null | undefined;
@@ -19,8 +23,28 @@ export type TrainingGuideLike = {
file_path?: string | null;
} | null | undefined;
const TRAINING_AGENT_NAME_PATTERN = /(培训|考试|入职)/;
const DEFAULT_PASS_SCORE = 90;
export const TRAINING_CONTENT_PROFILE = 'training';
/**
* 判断当前 Agent 是否应启用培训工作区。
* AI 触发时机:聊天页决定是否渲染培训主链时调用;优先 content_profile / extra_config,禁止名称启发式。
*/
export function matchesTrainingAgent(agent: TrainingAgentLike): boolean {
const extraConfig = agent?.extra_config || {};
if (extraConfig.training_workspace_enabled === false || extraConfig.training_workspace_enabled === 'false') {
return false;
}
const contentProfile = String(agent?.handler_config?.content_profile || '').trim();
if (contentProfile === TRAINING_CONTENT_PROFILE) {
return true;
}
const explicitFlags = [
extraConfig.training_workspace_enabled,
extraConfig.training_mode,
extraConfig.training_agent,
];
return explicitFlags.some((value) => value === true || value === 'true');
}
const asRecord = (value: unknown): Record<string, unknown> => (
value && typeof value === 'object' && !Array.isArray(value)
@@ -94,26 +118,7 @@ const normalizeQuestionBank = (
.filter((item): item is TrainingQuestion => Boolean(item));
};
/**
* 判断当前 Agent 是否应启用培训工作区。
* AI 触发时机:当聊天页需要决定是否渲染“视频 -> 总结 -> 答题”培训主链时使用,优先读取显式配置,避免误伤普通 Agent。
*/
export function matchesTrainingAgent(agent: TrainingAgentLike): boolean {
const extraConfig = agent?.extra_config || {};
if (extraConfig.training_workspace_enabled === false || extraConfig.training_workspace_enabled === 'false') {
return false;
}
const explicitFlags = [
extraConfig.training_workspace_enabled,
extraConfig.training_mode,
extraConfig.training_agent,
];
if (explicitFlags.some((value) => value === true || value === 'true')) {
return true;
}
const name = String(agent?.name || '').trim();
return TRAINING_AGENT_NAME_PATTERN.test(name);
}
const DEFAULT_PASS_SCORE = 90;
/**
* 解析培训视频地址。
@@ -0,0 +1,41 @@
/**
* features/chat/types/chat-turn.types.ts
* 用途:Chat Turn 平台层请求/响应类型定义。
* 依赖:无。
* 逻辑:useChatTurn 构造 POST /api/chat/turns/stream 请求体;refs 为不透明键值对,领域键名由各 Agent 自行约定。
*/
export type ChatTurnInputType = 'text' | 'action' | 'form_submit' | 'upload_followup';
/** 会话级业务锚点;货代常用 task_no/batch_no,其他 Agent 使用各自键名 */
export type ChatTurnRefs = Record<string, string>;
export interface StartChatTurnOptions {
agentId: number;
inputType: Extract<ChatTurnInputType, 'action' | 'form_submit' | 'upload_followup'>;
displayText: string;
actionType: string;
payload?: Record<string, unknown>;
refs?: ChatTurnRefs;
/** multipart 附件;与 JSON body 二选一,用于发货通知建批等 upload_followup */
files?: File[];
/** 为 true 时不追加 user 气泡(如 silent 决策),仍走 SSE 与 assistant 渲染 */
silent?: boolean;
hooks?: {
onAssistantMessageFinished?: (message: import('./chat.types').ChatMessage, runMessages: import('./chat.types').ChatMessage[]) => void | Promise<void>;
};
}
export interface ChatTurnStreamRequest {
agent_id: number;
conversation_id?: string | null;
input: {
type: ChatTurnInputType;
display_text: string;
action_type: string;
payload?: Record<string, unknown>;
};
context?: {
refs?: ChatTurnRefs;
};
}
@@ -61,6 +61,8 @@ export interface ChatRun {
conversationId: string | null;
status: ChatRunStatus;
createdAt: string;
/** 本轮 SSE 的 AbortController;detach 视图后仍可用于显式「停止生成」。 */
abortController?: AbortController;
}
export interface ChatSessionItem {
@@ -31,6 +31,7 @@ export interface ShippingTaskSummary {
step_payload?: Record<string, unknown> & {
current_step_progress?: ShippingCurrentStepProgress;
};
rpa_runtime?: ShippingRpaRuntime | null;
rpa_inventory_source?: Record<string, unknown> | null;
inventory_source_resolution?: Record<string, unknown> | null;
created_at?: string | null;
@@ -44,6 +45,12 @@ export interface ShippingTaskEvent {
created_at?: string | null;
}
export interface ShippingRpaRuntime {
mode?: 'browser' | 'mock' | string;
label?: string;
mock?: boolean;
}
export interface ShippingCurrentStepProgress {
step_key?: string;
step_title?: string;
@@ -16,7 +16,7 @@ import {
getWorkspaceShippingTask,
listShippingChatAgents,
listWorkspaceShippingTasks,
SHIPPING_NOTICE_AGENT_NAME,
SHIPPING_NOTICE_AGENT_CODE,
workspaceShippingExportUrl,
type ShippingCurrentStepProgress,
type ShippingTaskDetail,
@@ -159,7 +159,7 @@ const loadDetail = async (taskNo: string) => {
const resolveChatAgent = async () => {
try {
const agents = await listShippingChatAgents();
const found = agents.find((a) => a.name === SHIPPING_NOTICE_AGENT_NAME);
const found = agents.find((a) => String(a.agent_code || '').trim() === SHIPPING_NOTICE_AGENT_CODE);
if (found) chatAgentId.value = found.id;
} catch {
/* ignore */