feat(schedule): 优化排程任务配置与进度契约处理逻辑

This commit is contained in:
hugo committed 2026-07-08 16:09:28 +08:00
1 parent d54f51ddc3
commit 99453aa52a
65 files changed
+2837 -487

No files matched your search

@@ -116,7 +116,9 @@ export interface AdminAgentRegistrySchema {
models?: string[];
required_fields?: string[];
forced_capabilities?: Record<string, boolean>;
default_capabilities?: Record<string, boolean>;
default_intent_routes?: string[];
progress_contract?: Record<string, unknown> | null;
handler_config_schema?: Record<string, unknown>;
}>;
handler_config_schemas: Record<string, unknown>;
@@ -33,6 +33,17 @@ export const importAdminSchedules = async (payload: any) => {
});
};
export interface PlatformJobOption {
key: string;
/** 前端 i18n key;下拉优先 $t(label_key),label 仅作 fallback */
label_key?: string | null;
label: string;
description?: string;
}
export const listAdminPlatformJobs = () =>
getJson<PlatformJobOption[]>('/api/admin/schedule/platform-jobs');
export const getAdminScheduleTaskConfig = (taskId: number) =>
getJson<{ data_source_type: string; config: Record<string, any> | null }>(`/api/admin/schedule-config/${taskId}`);
@@ -0,0 +1,91 @@
/**
* features/admin/modules/agents/components/AgentCapabilitiesConfig.vue
*
* 用途:应用管理表单中的 capabilities 能力开关面板。
* 依赖:agent.types AgentFormState、useAgentsAdminRegistry catalog 辅助函数、vue-i18n。
* 逻辑:AgentFormModal 挂载本组件;Catalog forced_capabilities 对应项只读展示。
*/
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type { AgentCapabilities, AgentFormState } from '@/features/admin/types/agent.types';
import {
catalogForcesCapability,
type AgentTypeCatalogEntry,
} from '../composables/useAgentsAdminRegistry';
const CAPABILITY_KEYS = [
'streaming',
'file_upload',
'task_progress',
'human_confirm',
'source_citation',
'guide',
'erp_kb',
] as const satisfies readonly (keyof AgentCapabilities)[];
const props = defineProps<{
form: AgentFormState;
catalogEntry?: AgentTypeCatalogEntry;
}>();
const { t } = useI18n();
const capabilityItems = computed(() => (
CAPABILITY_KEYS.map((key) => ({
key,
forced: catalogForcesCapability(props.catalogEntry, key),
label: t(`admin.agent.capabilities.${key}`),
hint: t(`admin.agent.capabilities.${key}Hint`),
}))
));
/**
* 切换 task_progress 时同步 tool_run_progress_enabled,供进度配置面板联动。
*/
const handleCapabilityChange = (key: keyof AgentCapabilities, checked: boolean) => {
props.form.capabilities[key] = checked;
if (key === 'task_progress') {
props.form.tool_run_progress_enabled = checked;
}
};
</script>
<template>
<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.capabilities.title') }}
</div>
<p class="mt-1 text-sm leading-6 text-secondary">
{{ t('admin.agent.capabilities.subtitle') }}
</p>
</div>
<div class="grid grid-cols-1 gap-3 md:grid-cols-2">
<label
v-for="item in capabilityItems"
:key="item.key"
class="inline-flex items-start gap-2 rounded-xl border border-default bg-white px-3 py-2 text-sm text-secondary"
:class="{ 'opacity-80': item.forced }"
>
<input
v-model="form.capabilities[item.key]"
type="checkbox"
class="mt-0.5 accent-brand-600"
:disabled="item.forced"
@change="item.key === 'task_progress'
? handleCapabilityChange('task_progress', ($event.target as HTMLInputElement).checked)
: undefined"
/>
<span>
<span class="font-medium text-primary">{{ item.label }}</span>
<span class="mt-1 block text-xs leading-5 text-muted">{{ item.hint }}</span>
<span v-if="item.forced" class="mt-1 block text-xs leading-5 text-amber-600">
{{ t('admin.agent.capabilities.forcedByCatalog') }}
</span>
</span>
</label>
</div>
</div>
</template>
@@ -17,9 +17,12 @@ import type { AdminContentProfileOption } from '@/features/admin/api/admin.api';
import {
applyCatalogDefaultsToForm,
applyContentProfileTemplate,
catalogForcesTaskProgress,
catalogHasHandlerConfigSchema,
catalogProgressRequiresScheduleTask,
catalogSupportsHandlerField,
sortIntentRoutesByCatalog,
} from '../composables/useAgentsAdminRegistry';
import AgentCapabilitiesConfig from './AgentCapabilitiesConfig.vue';
import AgentToolRunProgressConfig from './AgentToolRunProgressConfig.vue';
const props = defineProps<{
@@ -60,14 +63,17 @@ 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)
&& catalogProgressRequiresScheduleTask(currentCatalogEntry.value)
));
const currentCatalogEntry = computed(() => (
props.typeCatalog.find((item) => item.agent_code === props.form.agent_code)
));
const taskProgressForced = computed(() => catalogForcesTaskProgress(currentCatalogEntry.value));
const showIntentFastPathSection = computed(() => catalogHasHandlerConfigSchema(currentCatalogEntry.value));
const showIntentRoutes = computed(() => catalogSupportsHandlerField(currentCatalogEntry.value, 'intent_routes'));
const showContentProfile = computed(() => catalogSupportsHandlerField(currentCatalogEntry.value, 'content_profile'));
const requiresScheduleTask = computed(() => catalogProgressRequiresScheduleTask(currentCatalogEntry.value));
const selectedIntentRouteOptions = computed(() => (
props.form.intent_routes
@@ -259,10 +265,6 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =
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>
@@ -329,14 +331,17 @@ 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
v-if="showIntentFastPathSection"
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="rounded-xl border border-default bg-white">
<div v-if="showIntentRoutes" class="rounded-xl border border-default bg-white">
<button
type="button"
class="flex w-full items-center justify-between gap-3 px-4 py-3 text-left"
@@ -405,7 +410,7 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =
</div>
</div>
<div class="space-y-2">
<div v-if="showContentProfile" 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">
@@ -437,17 +442,14 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =
</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>
<AgentCapabilitiesConfig
:form="form"
:catalog-entry="currentCatalogEntry"
/>
<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>
@@ -729,7 +731,7 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =
v-if="showToolRunProgress"
:form="form"
:schedule-tasks="scheduleTasks"
:task-progress-forced="taskProgressForced"
:requires-schedule-task="requiresScheduleTask"
/>
</div>
</div>
@@ -1,83 +1,71 @@
/**
* features/admin/modules/agents/components/AgentToolRunProgressConfig.vue
* 用途:应用管理表单中的文件检核任务进度能力配置(Registry 列)。
* 依赖:agent.types AgentFormState、schedule.types ScheduleTask、vue-i18n。
* 逻辑:写入 bound_schedule_task_id、capabilities.task_progress 与 handler_config 轮询参数。
*/
<script setup lang="ts">
import type { AgentFormState } from '@/features/admin/types/agent.types';
import type { ScheduleTask } from '@/shared/types/schedule.types';
defineProps<{
form: AgentFormState;
scheduleTasks: ScheduleTask[];
/** Catalog forced_capabilities.task_progress === true 时隐藏手动开关。 */
taskProgressForced?: boolean;
}>();
</script>
<template>
<div class="col-span-1 md:col-span-2 rounded-2xl border border-default bg-surface-soft/40 p-5 space-y-4">
<div class="flex items-start justify-between gap-3">
<div>
<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 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.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.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
? $t('admin.agent.toolRunProgress.noScheduleTasks')
: $t('admin.agent.toolRunProgress.selectScheduleTask') }}
</option>
<option v-for="task in scheduleTasks" :key="task.id" :value="task.id">
{{ task.name }}
</option>
</select>
<p class="text-xs text-muted">{{ $t('admin.agent.toolRunProgress.scheduleTaskHint') }}</p>
</div>
<div class="space-y-2">
<label class="text-xs font-bold text-muted uppercase tracking-wider">
{{ $t('admin.agent.toolRunProgress.pollInterval') }}
</label>
<input
v-model.number="form.poll_interval_seconds"
type="number"
min="1"
max="30"
class="w-full input-field text-sm"
/>
</div>
<div class="md:col-span-2">
<label class="inline-flex items-center gap-2 text-sm text-secondary">
<input v-model="form.lock_input_when_running" type="checkbox" class="admin-checkbox" />
<span>{{ $t('admin.agent.toolRunProgress.lockInput') }}</span>
</label>
</div>
</div>
</template>
</div>
</template>
/**␍
* features/admin/modules/agents/components/AgentToolRunProgressConfig.vue␍
* 用途:应用管理表单中的任务进度关联配置(排程绑定、轮询间隔、运行期锁输入)。␍
* 依赖:agent.types AgentFormState、schedule.types ScheduleTask、vue-i18n。␍
* 逻辑:task_progress 能力开关由 AgentCapabilitiesConfig 维护;本组件只写 bound_schedule_task_id 与 handler_config 轮询参数。␍
*/␍
<script setup lang="ts">␍
import type { AgentFormState } from '@/features/admin/types/agent.types';␍
import type { ScheduleTask } from '@/shared/types/schedule.types';␍
␍
defineProps<{␍
form: AgentFormState;␍
scheduleTasks: ScheduleTask[];␍
/** file_check 等类型需绑定排程任务时才展示关联字段。 */␍
requiresScheduleTask?: boolean;␍
}>();␍
</script>␍
␍
<template>␍
<div class="col-span-1 md:col-span-2 rounded-2xl border border-default bg-surface-soft/40 p-5 space-y-4">␍
<div>␍
<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>␍
␍
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">␍
<div v-if="requiresScheduleTask" 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.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␍
? $t('admin.agent.toolRunProgress.noScheduleTasks')␍
: $t('admin.agent.toolRunProgress.selectScheduleTask') }}␍
</option>␍
<option v-for="task in scheduleTasks" :key="task.id" :value="task.id">␍
{{ task.name }}␍
</option>␍
</select>␍
<p class="text-xs text-muted">{{ $t('admin.agent.toolRunProgress.scheduleTaskHint') }}</p>␍
</div>␍
␍
<div v-if="requiresScheduleTask" class="space-y-2">␍
<label class="text-xs font-bold text-muted uppercase tracking-wider">␍
{{ $t('admin.agent.toolRunProgress.pollInterval') }}␍
</label>␍
<input␍
v-model.number="form.poll_interval_seconds"␍
type="number"␍
min="1"␍
max="30"␍
class="w-full input-field text-sm"␍
/>␍
</div>␍
␍
<div v-if="requiresScheduleTask" class="md:col-span-2">␍
<label class="inline-flex items-center gap-2 text-sm text-secondary">␍
<input v-model="form.lock_input_when_running" type="checkbox" class="admin-checkbox" />␍
<span>{{ $t('admin.agent.toolRunProgress.lockInput') }}</span>␍
</label>␍
</div>␍
</div>␍
</div>␍
</template>␍
␍
@@ -36,7 +36,9 @@ import { createEmptyAgentForm, createEmptyTrainingQuestionForm } from '@/feature
import type { ScheduleTask } from '@/shared/types/schedule.types';
import {
applyCatalogDefaultsToForm,
applyForcedCapabilitiesToForm,
buildAgentRegistryPayload,
catalogRequiresScheduleTask,
mapAgentRowToForm,
type AgentCapabilitiesDefaults,
type AgentTypeCatalogEntry,
@@ -366,6 +368,8 @@ export function useAgentsAdmin() {
...mapAgentRowToForm(agent, defaultCapabilities()),
...trainingConfig,
};
const catalogEntry = typeCatalog.value.find((item) => item.agent_code === form.value.agent_code);
applyForcedCapabilitiesToForm(form.value, catalogEntry);
if (form.value.content_profile === 'training') {
form.value.training_workspace_enabled = true;
}
@@ -432,11 +436,12 @@ export function useAgentsAdmin() {
}
}
}
const catalogEntry = typeCatalog.value.find((item) => item.agent_code === form.value.agent_code);
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) {
if (supportsToolRunProgress && catalogRequiresScheduleTask(catalogEntry) && !boundTaskId) {
msg.warning(t('admin.agent.toolRunProgress.scheduleTaskRequired'));
return false;
}
@@ -10,6 +10,10 @@ import { createEmptyAgentForm } from '@/features/admin/types/agent.types';
import {
applyCatalogDefaultsToForm,
buildAgentRegistryPayload,
catalogHasHandlerConfigSchema,
catalogHasProgress,
catalogProgressRequiresScheduleTask,
catalogSupportsHandlerField,
pruneHandlerFormFieldsForCatalog,
type AgentTypeCatalogEntry,
} from './useAgentsAdminRegistry';
@@ -30,9 +34,45 @@ const shippingCatalogEntry: AgentTypeCatalogEntry = {
label: '货代发货通知',
conversation_mode_default: 'task_chat',
runtime_provider_default: 'hybrid',
default_capabilities: {
file_upload: true,
task_progress: true,
},
forced_capabilities: {
file_upload: true,
task_progress: true,
human_confirm: true,
},
progress_contract: {
enabled: true,
data_source: { type: 'domain_state', domain: 'shipping_notice' },
update: { transport: 'sse', event: 'shipping_ui_state' },
binding: { type: 'conversation_context', requires_schedule_task: false },
presentation: { layout: 'workspace', visualization: 'stepper' },
},
handler_config_schema: {},
};
const fileCheckCatalogEntry: AgentTypeCatalogEntry = {
agent_code: 'file_check',
label: '文件检核',
conversation_mode_default: 'task_chat',
runtime_provider_default: 'dify',
forced_capabilities: { task_progress: true },
progress_contract: {
enabled: true,
data_source: { type: 'schedule_run' },
update: { transport: 'polling', interval_seconds: 2 },
binding: { type: 'chat_log_run', requires_schedule_task: true },
presentation: { layout: 'card', visualization: 'counter' },
},
required_fields: ['bound_schedule_task_id'],
handler_config_schema: {
poll_interval_seconds: { type: 'integer' },
lock_input_when_running: { type: 'boolean' },
},
};
const fixedAssetsCatalogEntry: AgentTypeCatalogEntry = {
agent_code: 'fixed_assets',
label: '固资管理',
@@ -71,6 +111,10 @@ describe('useAgentsAdminRegistry catalog switch', () => {
expect(form.agent_code).toBe('shipping_notice');
expect(form.intent_routes).toEqual([]);
expect(form.content_profile).toBe('');
expect(form.capabilities.file_upload).toBe(true);
expect(form.capabilities.task_progress).toBe(true);
expect(form.capabilities.human_confirm).toBe(true);
expect(form.capabilities.erp_kb).toBe(false);
const payload = buildAgentRegistryPayload(form, {
supportsToolRunProgress: false,
@@ -100,4 +144,45 @@ describe('useAgentsAdminRegistry catalog switch', () => {
expect(form.intent_routes).toEqual([]);
});
it('catalogHasHandlerConfigSchema reflects handler_config_schema presence', () => {
expect(catalogHasHandlerConfigSchema(genericCatalogEntry)).toBe(true);
expect(catalogHasHandlerConfigSchema(shippingCatalogEntry)).toBe(false);
expect(catalogSupportsHandlerField(genericCatalogEntry, 'intent_routes')).toBe(true);
expect(catalogSupportsHandlerField(shippingCatalogEntry, 'intent_routes')).toBe(false);
});
it('catalogProgressRequiresScheduleTask follows progress_contract binding', () => {
expect(catalogProgressRequiresScheduleTask(fileCheckCatalogEntry)).toBe(true);
expect(catalogProgressRequiresScheduleTask(shippingCatalogEntry)).toBe(false);
expect(catalogHasProgress(fileCheckCatalogEntry)).toBe(true);
expect(catalogHasProgress(genericCatalogEntry)).toBe(false);
});
it('buildAgentRegistryPayload nulls bound_schedule_task_id when contract does not require it', () => {
const form = createEmptyAgentForm();
applyCatalogDefaultsToForm(form, shippingCatalogEntry);
form.capabilities.task_progress = true;
form.bound_schedule_task_id = 42;
const payload = buildAgentRegistryPayload(form, {
supportsToolRunProgress: true,
trainingExtraPatch: {},
typeCatalog: [shippingCatalogEntry, fileCheckCatalogEntry],
});
expect(payload.bound_schedule_task_id).toBeNull();
});
it('applyCatalogDefaultsToForm clears stale schedule task when switching away from file_check', () => {
const form = createEmptyAgentForm();
applyCatalogDefaultsToForm(form, fileCheckCatalogEntry);
form.bound_schedule_task_id = 42;
form.schedule_task_id = 42;
applyCatalogDefaultsToForm(form, shippingCatalogEntry);
expect(form.bound_schedule_task_id).toBeNull();
expect(form.schedule_task_id).toBeNull();
});
});
@@ -40,12 +40,45 @@ export interface AgentTypeCatalogEntry {
required_fields?: string[];
default_capabilities?: Record<string, boolean>;
forced_capabilities?: Record<string, boolean>;
progress_contract?: ProgressContract | null;
handler_config_schema?: Record<string, unknown>;
}
export type ProgressDataSourceType = 'schedule_run' | 'domain_state' | 'job_queue' | 'external_callback';
export type ProgressTransport = 'polling' | 'sse' | 'manual_refresh';
export type ProgressBindingType = 'chat_log_run' | 'conversation_context' | 'domain_key';
export type ProgressLayout = 'card' | 'workspace' | 'inline' | 'drawer';
export type ProgressVisualization = 'counter' | 'stepper' | 'timeline' | 'percent' | 'hybrid';
export interface ProgressContract {
enabled?: boolean;
data_source?: {
type?: ProgressDataSourceType;
domain?: string;
};
update?: {
transport?: ProgressTransport;
event?: string;
interval_seconds?: number;
};
binding?: {
type?: ProgressBindingType;
keys?: string[];
fallback?: string;
requires_schedule_task?: boolean;
};
presentation?: {
layout?: ProgressLayout;
visualization?: ProgressVisualization;
};
}
export type AgentCapabilitiesDefaults = AgentFormState['capabilities'];
@@ -120,11 +153,50 @@ export function sortIntentRoutesByCatalog(
/** Catalog 是否强制开启 task_progress。 */
export function catalogForcesTaskProgress(entry?: AgentTypeCatalogEntry): boolean {
return entry?.forced_capabilities?.task_progress === true;
return catalogForcesCapability(entry, 'task_progress');
}
/** Catalog 是否声明 bound_schedule_task_id 必填。 */
/** Catalog 是否强制开启指定 capability。 */
export function catalogForcesCapability(
entry: AgentTypeCatalogEntry | undefined,
key: keyof AgentFormState['capabilities'],
): boolean {
return entry?.forced_capabilities?.[key] === true;
}
/**
* 将 Catalog forced_capabilities 合并到表单 capabilities。
*/
export function applyForcedCapabilitiesToForm(
form: AgentFormState,
entry?: AgentTypeCatalogEntry,
): void {
const forced = entry?.forced_capabilities || {};
Object.entries(forced).forEach(([key, value]) => {
if (!(key in form.capabilities)) return;
form.capabilities[key as keyof AgentFormState['capabilities']] = value === true;
});
if (forced.task_progress === true) {
form.tool_run_progress_enabled = true;
}
}
/** Catalog 是否声明 bound_schedule_task_id 必填(progress_contract 优先)。 */
export function catalogRequiresScheduleTask(entry?: AgentTypeCatalogEntry): boolean {
return catalogProgressRequiresScheduleTask(entry);
}
/** Catalog 是否启用 progress_contract。 */
export function catalogHasProgress(entry?: AgentTypeCatalogEntry): boolean {
return entry?.progress_contract?.enabled === true;
}
/** Catalog progress_contract 是否要求绑定排程任务。 */
export function catalogProgressRequiresScheduleTask(entry?: AgentTypeCatalogEntry): boolean {
const contract = entry?.progress_contract;
if (contract?.enabled === true && contract.binding?.requires_schedule_task === true) {
return true;
}
return (entry?.required_fields || []).includes('bound_schedule_task_id');
}
@@ -134,6 +206,36 @@ const handlerConfigSchemaFieldNames = (entry?: AgentTypeCatalogEntry): string[]
return Object.keys(schema);
};
/** 当前 Catalog 是否声明 handler_config_schema(非空)。 */
export function catalogHasHandlerConfigSchema(entry?: AgentTypeCatalogEntry): boolean {
return handlerConfigSchemaFieldNames(entry).length > 0;
}
/** 当前 Catalog handler_config_schema 是否包含指定字段。 */
export function catalogSupportsHandlerField(
entry: AgentTypeCatalogEntry | undefined,
field: string,
): boolean {
return handlerConfigSchemaFieldNames(entry).includes(field);
}
/**
* 将 Catalog default_capabilities 合并到表单(类型切换时的默认偏好,可被用户修改)。
*/
export function applyDefaultCapabilitiesToForm(
form: AgentFormState,
entry?: AgentTypeCatalogEntry,
): void {
const defaults = entry?.default_capabilities || {};
Object.entries(defaults).forEach(([key, value]) => {
if (!(key in form.capabilities)) return;
form.capabilities[key as keyof AgentFormState['capabilities']] = value === true;
});
if (defaults.task_progress === true) {
form.tool_run_progress_enabled = true;
}
}
/**
* 切换 Catalog 后清理当前类型 handler_config_schema 不支持的表单字段。
*/
@@ -222,14 +324,16 @@ export function applyCatalogDefaultsToForm(
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)) {
applyDefaultCapabilitiesToForm(form, entry);
applyForcedCapabilitiesToForm(form, entry);
if (!catalogForcesTaskProgress(entry) && !catalogProgressRequiresScheduleTask(entry)) {
form.capabilities.task_progress = false;
form.tool_run_progress_enabled = false;
}
// 切换到不需要排程绑定的进度类型时,清掉旧的 ScheduleTask 残留。
if (!catalogProgressRequiresScheduleTask(entry)) {
form.bound_schedule_task_id = null;
form.schedule_task_id = null;
}
pruneHandlerFormFieldsForCatalog(form, entry);
@@ -269,9 +373,7 @@ export function mapAgentRowToForm(
dify_app_id: agent.dify_app_id || '',
dify_api_key: '',
dify_api_key_masked: String(agent.dify_api_key_masked || ''),
dify_api_key: agent.dify_api_key || '',
description: agent.description || '',
@@ -457,7 +559,8 @@ export function buildAgentRegistryPayload(
capabilities,
bound_schedule_task_id: form.capabilities.task_progress === true || form.tool_run_progress_enabled
bound_schedule_task_id: catalogProgressRequiresScheduleTask(catalogEntry)
&& (form.capabilities.task_progress === true || form.tool_run_progress_enabled)
? (form.bound_schedule_task_id ?? form.schedule_task_id)
@@ -1,7 +1,9 @@
<script setup lang="ts">
/**
* features/admin/modules/schedules/components/ScheduleCreateEditModal.vue
* 定时任务创建/编辑弹窗。
* 用途:定时任务创建/编辑弹窗。
* 依赖:schedules.context、ScheduleCronDesigner。
* 逻辑:平台 Job 下拉展示由 registry 返回的 label_key 经 $t() 渲染,前端不维护 key→i18n 映射。
*/
import { ChevronDown, ChevronUp, Plus } from 'lucide-vue-next';
import { useScheduleCreateModalOpen, useSchedulesAdminContext } from '../composables/schedules.context';
@@ -68,8 +70,20 @@ const showCreateModal = useScheduleCreateModalOpen();
<div class="rounded-2xl border border-default bg-surface-soft/40 p-4">
<div class="mb-3 space-y-3">
<h4 class="text-base font-bold text-primary">{{ $t('admin.schedule.form.dataSourceConfig') }}</h4>
<div class="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
<div class="w-full sm:max-w-sm">
<div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
<div>
<label class="mb-1.5 block text-xs font-semibold uppercase tracking-wide text-muted">
{{ $t('admin.schedule.form.scheduleType') }}
</label>
<select
v-model="admin.scheduleCreateForm.schedule_type"
class="input-field w-full !text-sm !leading-5"
>
<option value="data_pipeline">{{ $t('admin.schedule.form.scheduleTypeDataPipeline') }}</option>
<option value="platform_job">{{ $t('admin.schedule.form.scheduleTypePlatformJob') }}</option>
</select>
</div>
<div v-if="admin.scheduleCreateForm.schedule_type === 'data_pipeline'">
<label class="mb-1.5 block text-xs font-semibold uppercase tracking-wide text-muted">
{{ $t('admin.schedule.form.dataSourceType') }}
</label>
@@ -79,49 +93,50 @@ const showCreateModal = useScheduleCreateModalOpen();
>
<option value="database">{{ $t('admin.schedule.form.databaseDirect') }}</option>
<option value="external_api">{{ $t('admin.schedule.form.externalApi') }}</option>
<option value="faq_hot_aggregate">{{ $t('admin.schedule.form.faqHotAggregate') }}</option>
</select>
</div>
<div
v-if="admin.scheduleCreateForm.data_source_type !== 'faq_hot_aggregate'"
class="flex flex-wrap items-center gap-2 sm:shrink-0"
>
<button
type="button"
class="btn-secondary btn-sm inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap disabled:cursor-not-allowed disabled:opacity-60"
:disabled="admin.scheduleTestLoading || !admin.scheduleEditingId"
@click="admin.handleTestScheduleSql"
<div v-else>
<label class="mb-1.5 block text-xs font-semibold uppercase tracking-wide text-muted">
{{ $t('admin.schedule.form.platformJob') }}
</label>
<select
v-model="admin.scheduleCreateForm.platform_api_path"
class="input-field w-full !text-sm !leading-5"
>
{{ admin.scheduleTestLoading ? $t('admin.schedule.form.querying') : $t('admin.schedule.form.testQuery') }}
</button>
<button
type="button"
class="btn-secondary btn-sm inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap"
@click="admin.scheduleConfigCollapsed = !admin.scheduleConfigCollapsed"
>
<ChevronDown v-if="admin.scheduleConfigCollapsed" class="h-3.5 w-3.5 shrink-0" />
<ChevronUp v-else class="h-3.5 w-3.5 shrink-0" />
{{ admin.scheduleConfigCollapsed ? $t('admin.schedule.form.expandConfig') : $t('admin.schedule.form.collapseConfig') }}
</button>
<option :value="null">{{ $t('admin.schedule.form.selectPlatformJob') }}</option>
<option v-for="job in admin.platformJobs" :key="job.key" :value="job.key">
{{ job.label_key ? $t(job.label_key) : job.label || job.key }}
</option>
</select>
</div>
</div>
<div
v-if="admin.scheduleCreateForm.schedule_type === 'data_pipeline'"
class="flex flex-wrap items-center gap-2 sm:shrink-0"
>
<button
type="button"
class="btn-secondary btn-sm inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap disabled:cursor-not-allowed disabled:opacity-60"
:disabled="admin.scheduleTestLoading || !admin.scheduleEditingId"
@click="admin.handleTestScheduleSql"
>
{{ admin.scheduleTestLoading ? $t('admin.schedule.form.querying') : $t('admin.schedule.form.testQuery') }}
</button>
<button
type="button"
class="btn-secondary btn-sm inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap"
@click="admin.scheduleConfigCollapsed = !admin.scheduleConfigCollapsed"
>
<ChevronDown v-if="admin.scheduleConfigCollapsed" class="h-3.5 w-3.5 shrink-0" />
<ChevronUp v-else class="h-3.5 w-3.5 shrink-0" />
{{ admin.scheduleConfigCollapsed ? $t('admin.schedule.form.expandConfig') : $t('admin.schedule.form.collapseConfig') }}
</button>
</div>
</div>
<div v-show="!admin.scheduleConfigCollapsed || admin.scheduleCreateForm.data_source_type === 'faq_hot_aggregate'" class="space-y-3">
<div
v-if="admin.scheduleCreateForm.data_source_type === 'faq_hot_aggregate'"
class="rounded-xl border border-amber-200 bg-amber-50/60 p-4 space-y-3"
>
<p class="text-sm text-amber-900">{{ $t('admin.schedule.form.faqHotAggregateHint') }}</p>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.faqHotAgentFilter') }}</label>
<select v-model="admin.scheduleCreateForm.dify_agent_id" class="input-field !text-sm !leading-5" :disabled="admin.agents.length === 0">
<option :value="null">{{ $t('admin.schedule.form.faqHotAllAgents') }}</option>
<option v-for="agent in admin.agents" :key="agent.id" :value="agent.id">{{ agent.name }}</option>
</select>
<p class="mt-1 text-xs text-muted">{{ $t('admin.schedule.form.faqHotAgentFilterHelp') }}</p>
</div>
</div>
<!-- 数据库直联模式 -->
<div
v-show="admin.scheduleCreateForm.schedule_type === 'data_pipeline' && !admin.scheduleConfigCollapsed"
class="space-y-3"
>
<template v-if="admin.scheduleCreateForm.data_source_type === 'database'">
<!-- 数据源配置 -->
<details class="rounded-xl border border-default bg-surface" open>
@@ -282,6 +297,40 @@ const showCreateModal = useScheduleCreateModalOpen();
</template>
</div>
<div
v-if="admin.scheduleCreateForm.schedule_type === 'platform_job'"
class="mt-3 space-y-3"
>
<div
v-if="admin.scheduleCreateForm.platform_api_path === 'faq-aggregate-hot'"
class="rounded-xl border border-amber-200 bg-amber-50/60 p-4 space-y-3"
>
<p class="text-sm text-amber-900">{{ $t('admin.schedule.form.faqHotAggregateHint') }}</p>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.faqHotAgentFilter') }}</label>
<select v-model="admin.scheduleCreateForm.dify_agent_id" class="input-field !text-sm !leading-5" :disabled="admin.agents.length === 0">
<option :value="null">{{ $t('admin.schedule.form.faqHotAllAgents') }}</option>
<option v-for="agent in admin.agents" :key="agent.id" :value="agent.id">{{ agent.name }}</option>
</select>
<p class="mt-1 text-xs text-muted">{{ $t('admin.schedule.form.faqHotAgentFilterHelp') }}</p>
</div>
</div>
<div
v-if="admin.scheduleCreateForm.platform_api_path === 'shipping-inventory-rpa'"
class="rounded-xl border border-blue-200 bg-blue-50/40 p-4 space-y-2"
>
<p class="text-sm text-blue-900">{{ $t('admin.schedule.form.shippingInventoryJobHint') }}</p>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.shippingInventoryJobParams') }}</label>
<textarea
v-model="admin.scheduleSqlEditForm.api_body_template"
class="w-full min-h-[80px] input-field p-3 text-xs leading-relaxed text-secondary font-mono resize-y"
:placeholder="$t('admin.schedule.form.shippingInventoryJobParamsPlaceholder')"
></textarea>
</div>
</div>
</div>
<div v-if="admin.scheduleTestResult" class="mt-4 rounded-2xl border border-emerald-200 bg-emerald-50/40 p-4">
<div class="mb-3 flex items-center justify-between">
<h4 class="text-sm font-bold text-emerald-900">{{ $t('admin.schedule.testRun.queryResult') }}</h4>
@@ -311,7 +360,7 @@ const showCreateModal = useScheduleCreateModalOpen();
</div>
</div>
<div v-if="admin.scheduleCreateForm.data_source_type !== 'faq_hot_aggregate'" class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div v-if="admin.scheduleCreateForm.schedule_type === 'data_pipeline'" class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div>
<label class="mb-2 block text-sm font-medium text-secondary">{{ $t('admin.schedule.form.agentLabel') }}</label>
<div class="relative">
@@ -330,7 +379,7 @@ const showCreateModal = useScheduleCreateModalOpen();
</div>
</div>
<div v-if="admin.scheduleCreateForm.data_source_type !== 'faq_hot_aggregate'" class="rounded-2xl border border-emerald-200 bg-emerald-50/40 p-4">
<div v-if="admin.scheduleCreateForm.schedule_type === 'data_pipeline'" class="rounded-2xl border border-emerald-200 bg-emerald-50/40 p-4">
<label class="flex items-center gap-2 text-sm font-semibold text-secondary">
<input v-model="admin.scheduleCreateForm.kb_sync_enabled" type="checkbox" class="h-4 w-4 rounded border-default text-emerald-600 focus:ring-emerald-300" />
{{ $t('admin.schedule.form.kbSyncEnabled') }}
@@ -127,7 +127,7 @@ const admin = useSchedulesAdminContext();
{{ $t('admin.schedule.actions.run') }}
</button>
<button
v-if="s.data_source_type !== 'external_api'"
v-if="s.schedule_type === 'data_pipeline' && s.data_source_type === 'database'"
class="inline-flex items-center gap-1 rounded-xl border border-violet-200 px-3 py-2 text-xs font-medium text-violet-700 transition-colors hover:bg-violet-50"
@click.stop="admin.openTestRunDialog(s)"
>
@@ -94,7 +94,7 @@ const admin = useSchedulesAdminContext();
<Rocket class="h-3 w-3" />
</button>
<button
v-if="s.data_source_type !== 'external_api'"
v-if="s.schedule_type === 'data_pipeline' && s.data_source_type === 'database'"
class="inline-flex items-center justify-center rounded-xl border border-violet-200 p-1.5 text-xs font-medium text-violet-700 transition-colors hover:bg-violet-50"
:title="$t('admin.schedule.actions.test')"
@click.stop="admin.openTestRunDialog(s)"
@@ -3,7 +3,7 @@
* 定时任务管理页共享 ref 与删除确认弹窗状态。
*/
import { ref } from 'vue';
import type { ScheduleRun, ScheduleTask, TestScheduleRunResult } from '@/features/admin/api/schedule.api';
import type { PlatformJobOption, ScheduleRun, ScheduleTask, TestScheduleRunResult } from '@/features/admin/api/schedule.api';
import type { AdminAgentOption, AdminUserRow } from '@/features/admin/types/admin.types';
import type { KbGroup } from '@/features/kb/api/kb.api';
import {
@@ -15,6 +15,7 @@ export function createScheduleAdminState() {
const agents = ref<AdminAgentOption[]>([]);
const users = ref<AdminUserRow[]>([]);
const kbGroups = ref<KbGroup[]>([]);
const platformJobs = ref<PlatformJobOption[]>([]);
const showDeleteConfirmDialog = ref(false);
const deleteConfirmTitle = ref('');
@@ -107,6 +108,7 @@ export function createScheduleAdminState() {
agents,
users,
kbGroups,
platformJobs,
showDeleteConfirmDialog,
deleteConfirmTitle,
deleteConfirmMessage,
@@ -27,7 +27,7 @@ import type { ScheduleAdminRuns } from './useScheduleAdminRuns';
export function useScheduleAdminForm(
state: ScheduleAdminState,
lookups: Pick<ScheduleAdminLookups, 'loadAgents' | 'loadUsers' | 'loadKbGroups'>,
lookups: Pick<ScheduleAdminLookups, 'loadAgents' | 'loadUsers' | 'loadKbGroups' | 'loadPlatformJobs'>,
list: Pick<ScheduleAdminList, 'loadSchedules'>,
runs: Pick<ScheduleAdminRuns, 'viewScheduleRuns'>,
t: ComposerTranslation,
@@ -107,7 +107,9 @@ export function useScheduleAdminForm(
result: Awaited<ReturnType<typeof getAdminScheduleTaskConfig>>,
): void => {
const cfg = result.config;
scheduleCreateForm.value.data_source_type = (result.data_source_type || 'database') as ScheduleCreateForm['data_source_type'];
if (scheduleCreateForm.value.schedule_type === 'data_pipeline') {
scheduleCreateForm.value.data_source_type = (result.data_source_type || 'database') as ScheduleCreateForm['data_source_type'];
}
if (!cfg) return;
scheduleSqlEditForm.value = {
base_fetch_sql: cfg.base_fetch_sql || '',
@@ -139,7 +141,12 @@ export function useScheduleAdminForm(
/** 后台拉取下拉与 SQL 配置;弹窗已打开后静默回填。 */
const loadScheduleEditModalData = async (taskId: number): Promise<void> => {
await Promise.all([lookups.loadAgents(), lookups.loadUsers(), lookups.loadKbGroups()]);
await Promise.all([
lookups.loadAgents(),
lookups.loadUsers(),
lookups.loadKbGroups(),
lookups.loadPlatformJobs(),
]);
syncScheduleOwnerQuery();
try {
const result = await getAdminScheduleTaskConfig(taskId);
@@ -156,7 +163,12 @@ export function useScheduleAdminForm(
resetScheduleCreateForm();
scheduleConfigCollapsed.value = true;
showScheduleCreateModal.value = true;
void Promise.all([lookups.loadAgents(), lookups.loadUsers(), lookups.loadKbGroups()]);
void Promise.all([
lookups.loadAgents(),
lookups.loadUsers(),
lookups.loadKbGroups(),
lookups.loadPlatformJobs(),
]);
};
/**
@@ -172,6 +184,11 @@ export function useScheduleAdminForm(
scheduleEditingId.value = task.id;
scheduleCreateForm.value = {
name: task.name || '',
schedule_type: (task.schedule_type === 'platform_job' ? 'platform_job' : 'data_pipeline') as ScheduleCreateForm['schedule_type'],
data_source_type: task.schedule_type === 'data_pipeline'
? ((task.data_source_type || 'database') as ScheduleCreateForm['data_source_type'])
: null,
platform_api_path: task.schedule_type === 'platform_job' ? (task.platform_api_path || null) : null,
dify_agent_id: task.dify_agent_id || null,
owner_user_id: task.owner_user_id || null,
wait_seconds: task.wait_seconds || 0,
@@ -180,7 +197,6 @@ export function useScheduleAdminForm(
kb_sync_enabled: !!task.kb_sync_enabled,
kb_group_id: task.kb_group_id || null,
enabled: !!task.enabled,
data_source_type: (task.data_source_type || 'database') as ScheduleCreateForm['data_source_type'],
};
scheduleSqlEditForm.value = createDefaultScheduleSqlEditForm();
scheduleTestResult.value = null;
@@ -278,18 +294,26 @@ export function useScheduleAdminForm(
return;
}
const dst = scheduleCreateForm.value.data_source_type;
const isFaqHot = dst === 'faq_hot_aggregate';
const hasAgent = !!scheduleCreateForm.value.dify_agent_id;
const hasSql = dst === 'database' && !!scheduleSqlEditForm.value.base_fetch_sql.trim();
const hasApi = dst === 'external_api' && !!scheduleSqlEditForm.value.api_url.trim();
if (!isFaqHot && !hasAgent && !hasSql && !hasApi) {
const form = scheduleCreateForm.value;
const isDataPipeline = form.schedule_type === 'data_pipeline';
const isPlatformJob = form.schedule_type === 'platform_job';
const isShippingRpa = isPlatformJob && form.platform_api_path === 'shipping-inventory-rpa';
const dst = form.data_source_type;
const hasAgent = !!form.dify_agent_id;
const hasSql = isDataPipeline && dst === 'database' && !!scheduleSqlEditForm.value.base_fetch_sql.trim();
const hasApi = isDataPipeline && dst === 'external_api' && !!scheduleSqlEditForm.value.api_url.trim();
if (isPlatformJob && !form.platform_api_path) {
msg.error(t('admin.schedule.msg.platformJobRequired'));
return;
}
if (isDataPipeline && !hasAgent && !hasSql && !hasApi) {
msg.error(t('admin.schedule.msg.configRequired'));
return;
}
let headerLabels: Record<string, string> = {};
if (!isFaqHot) {
if (isDataPipeline) {
try {
headerLabels = JSON.parse(scheduleSqlEditForm.value.header_labels_str || '{}');
} catch {
@@ -298,7 +322,7 @@ export function useScheduleAdminForm(
}
}
let apiHeaders: Record<string, string> = {};
if (dst === 'external_api') {
if (isDataPipeline && dst === 'external_api') {
try {
apiHeaders = JSON.parse(scheduleSqlEditForm.value.api_headers_str || '{}');
} catch {
@@ -308,30 +332,36 @@ export function useScheduleAdminForm(
}
let configPayload: Record<string, unknown> | undefined;
if (!isFaqHot) {
if (isDataPipeline) {
configPayload = buildScheduleConfigPayload(
scheduleSqlEditForm.value,
hasAgent,
headerLabels,
apiHeaders,
);
} else if (isShippingRpa && scheduleSqlEditForm.value.api_body_template.trim()) {
configPayload = {
api_body_template: scheduleSqlEditForm.value.api_body_template,
};
}
scheduleCreateSaving.value = true;
try {
const payload: Record<string, unknown> = {
name: scheduleCreateForm.value.name,
schedule_type: 'platform_app',
owner_user_id: scheduleCreateForm.value.owner_user_id,
name: form.name,
schedule_type: form.schedule_type,
owner_user_id: form.owner_user_id,
cron_expr: cronDesigner.cronExpr.value,
wait_seconds: Math.max(0, Number(scheduleCreateForm.value.wait_seconds || 0)),
dify_agent_id: scheduleCreateForm.value.dify_agent_id || undefined,
notify_user_ids_json: scheduleCreateForm.value.notify_enabled ? scheduleCreateForm.value.notify_user_ids_json : [],
notify_enabled: scheduleCreateForm.value.notify_enabled,
kb_sync_enabled: scheduleCreateForm.value.kb_sync_enabled,
kb_group_id: scheduleCreateForm.value.kb_sync_enabled ? scheduleCreateForm.value.kb_group_id : null,
enabled: scheduleCreateForm.value.enabled,
data_source_type: dst,
wait_seconds: Math.max(0, Number(form.wait_seconds || 0)),
dify_agent_id: form.dify_agent_id || undefined,
notify_user_ids_json: form.notify_enabled ? form.notify_user_ids_json : [],
notify_enabled: form.notify_enabled,
kb_sync_enabled: isDataPipeline ? form.kb_sync_enabled : false,
kb_group_id: isDataPipeline && form.kb_sync_enabled ? form.kb_group_id : null,
enabled: form.enabled,
...(isDataPipeline
? { data_source_type: dst, platform_api_path: null }
: { data_source_type: null, platform_api_path: form.platform_api_path }),
...(configPayload ? { config: configPayload } : {}),
};
let resultData: { id?: number; schedule?: { id?: number } } | null = null;
@@ -3,11 +3,12 @@
* 定时任务表单依赖的下拉数据:Agent、用户、知识库分组。
*/
import { listAdminAgents, listAdminUsers } from '@/features/admin/api/admin.api';
import { listAdminPlatformJobs } from '@/features/admin/api/schedule.api';
import { getKbGroups } from '@/features/kb/api/kb.api';
import type { ScheduleAdminState } from './schedule-admin.state';
export function useScheduleAdminLookups(state: ScheduleAdminState) {
const { agents, users, kbGroups } = state;
const { agents, users, kbGroups, platformJobs } = state;
const loadAgents = async (): Promise<void> => {
try {
@@ -36,10 +37,24 @@ export function useScheduleAdminLookups(state: ScheduleAdminState) {
}
};
/**
* 从后端 Job Registry 加载平台内置任务下拉选项。
* 核心逻辑:GET /api/admin/schedule/platform-jobs,与 registry 注册项保持同步。
*/
const loadPlatformJobs = async (): Promise<void> => {
try {
platformJobs.value = await listAdminPlatformJobs();
} catch (e) {
console.error('Failed to load platform jobs', e);
platformJobs.value = [];
}
};
return {
loadAgents,
loadUsers,
loadKbGroups,
loadPlatformJobs,
};
}
@@ -8,6 +8,18 @@
/** Cron 设计器模式 */
export type ScheduleCronDesignerMode = 'every_minutes' | 'hourly' | 'daily' | 'weekly';
/** 排程执行模式 */
export type ScheduleExecutionMode = 'data_pipeline' | 'platform_job';
/** data_pipeline 数据源类型 */
export type ScheduleDataSourceType = 'database' | 'external_api';
/** 平台内置 Job key(与后端 registry 一致,仅作类型提示) */
export type PlatformJobKey =
| 'shipping-inventory-rpa'
| 'faq-aggregate-hot'
| 'fixed-assets-snapshot';
/** Cron 可视化设计器状态 */
export interface ScheduleCronDesigner {
mode: ScheduleCronDesignerMode;
@@ -23,7 +35,9 @@ export interface ScheduleCronDesigner {
/** 创建/编辑定时任务主表单 */
export interface ScheduleCreateForm {
name: string;
data_source_type: 'database' | 'external_api' | 'faq_hot_aggregate';
schedule_type: ScheduleExecutionMode;
data_source_type: ScheduleDataSourceType | null;
platform_api_path: PlatformJobKey | string | null;
dify_agent_id: number | null;
owner_user_id: number | null;
wait_seconds: number;
@@ -86,7 +100,9 @@ export function createDefaultCronDesigner(): ScheduleCronDesigner {
export function createDefaultScheduleCreateForm(): ScheduleCreateForm {
return {
name: '',
schedule_type: 'data_pipeline',
data_source_type: 'database',
platform_api_path: null,
dify_agent_id: null,
owner_user_id: null,
wait_seconds: 300,
@@ -22,6 +22,7 @@ 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;
@@ -81,8 +82,6 @@ export interface AgentFormState {
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;
@@ -128,7 +127,6 @@ export const createEmptyAgentForm = (
name: '',
dify_app_id: '',
dify_api_key: '',
dify_api_key_masked: '',
description: '',
type: 'api',
agent_code: 'generic',
@@ -162,7 +162,7 @@ watch(() => page.currentAgentId, () => {
/>
<ShippingBatchProgressPanel
v-if="page.isShippingNoticeAgent && (page.shippingBatchSummary || page.activeShippingTaskDetail)"
v-if="page.showShippingProgressWorkspace && (page.shippingBatchSummary || page.activeShippingTaskDetail)"
:conversation-workspace="page.shippingConversationWorkspace"
:active-batch-no="page.activeShippingBatchNo"
:batch-summary="page.shippingBatchSummary"
@@ -313,7 +313,7 @@ watch(() => page.currentAgentId, () => {
/>
<ShippingBatchWorkspaceDrawer
v-if="page.isShippingNoticeAgent && (page.shippingConversationWorkspace || page.shippingBatchSummary)"
v-if="page.showShippingProgressWorkspace && (page.shippingConversationWorkspace || page.shippingBatchSummary)"
v-model:open="page.shippingWorkspaceOpen"
:conversation-workspace="page.shippingConversationWorkspace"
:active-batch-no="page.activeShippingBatchNo"
@@ -572,6 +572,7 @@ export function useChatPage() {
handleDeleteConfirm: dialogs.handleDeleteConfirm,
showChatRating,
isShippingNoticeAgent: shipping.isShippingNoticeAgent,
showShippingProgressWorkspace: shipping.showShippingProgressWorkspace,
shippingBatchSummary: shipping.shippingBatchSummary,
shippingConversationWorkspace: shipping.shippingConversationWorkspace,
activeShippingBatchNo: shipping.activeShippingBatchNo,
@@ -13,7 +13,7 @@ import {
type ComputedRef,
type Ref,
} from 'vue';
import { isShippingNoticeAgent as resolveShippingNoticeAgent } from '@/shared/utils/agent-registry.utils';
import { agentUsesWorkspaceStepperProgress, isShippingNoticeAgent as resolveShippingNoticeAgent } from '@/shared/utils/agent-registry.utils';
import type { AgentRegistryFields } from '@/shared/utils/agent-registry.utils';
import { hasActiveRunningChatRun } from '../shipping/shippingActionBusy';
@@ -168,6 +168,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
// ── 功能开关与 UI refs ────────────────────────────────────
const isShippingNoticeAgent = computed(() => resolveShippingNoticeAgent(currentAgent.value));
const showShippingProgressWorkspace = computed(() => agentUsesWorkspaceStepperProgress(currentAgent.value));
const isShippingActionBusy = computed(() => {
if (shippingActionBusy.value) return true;
return hasActiveRunningChatRun(isThinking.value, activeRunId.value, runs.value);
@@ -949,6 +950,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
return {
shippingBindSend,
isShippingNoticeAgent,
showShippingProgressWorkspace,
prepareMarkdownDisplayText,
shippingAutoFlowRequested,
shippingInventoryPickerRef,
@@ -9,7 +9,8 @@
import { computed, nextTick, ref, watch, type Ref } from 'vue';
import {
agentHasTaskProgress,
agentHasProgress,
agentUsesScheduleRunCounterProgress,
resolveToolRunProgressView,
type AgentRegistryFields,
} from '@/shared/utils/agent-registry.utils';
@@ -65,7 +66,7 @@ export function useChatPageToolRun(ctx: ChatPageToolRunContext) {
const toolRunProgressConfig = computed<ToolRunProgressConfig | null>(() => {
const agent = ctx.currentAgent.value;
if (!agent || !agentHasTaskProgress(agent)) return null;
if (!agent || !agentHasProgress(agent) || !agentUsesScheduleRunCounterProgress(agent)) return null;
const cfg = resolveToolRunProgressView(agent) || {};
const handlerConfig = agent.handler_config && typeof agent.handler_config === 'object'
+33 -2
View File
@@ -233,9 +233,28 @@
"lockInput": "Prevent sending new messages while a task is running",
"scheduleTaskRequired": "Please select a linked schedule first"
},
"capabilities": {
"title": "Runtime capabilities",
"subtitle": "Control streaming, file upload, task progress, human confirmation, citations, guides, and more at runtime",
"forcedByCatalog": "Fixed by the selected app type and cannot be turned off",
"streaming": "Streaming",
"streamingHint": "Stream chat responses via SSE; when off, wait for the full reply",
"file_upload": "File upload",
"file_uploadHint": "Show attachment upload in chat (local files / URLs)",
"task_progress": "Task progress",
"task_progressHint": "Show async task progress in chat (e.g. shipping flow, file checks)",
"human_confirm": "Human confirmation",
"human_confirmHint": "Enable steps that require explicit user confirmation",
"source_citation": "Source citation",
"source_citationHint": "Show knowledge-base citations in answers",
"guide": "Getting started guide",
"guideHint": "Show platform app guide / onboarding entry in chat",
"erp_kb": "ERP fixed-asset KB",
"erp_kbHint": "Default to enterprise KB and allow switching to ERP fixed-asset knowledge base"
},
"registry": {
"title": "Routing & Capabilities",
"subtitle": "Configure intent fast paths and ERP knowledge base without relying on agent name heuristics",
"title": "Intent fast path",
"subtitle": "When a specific intent matches, bypass the default chat flow and use a dedicated handler",
"intentRoutesLabel": "Intent routes",
"advancedTitle": "Advanced settings",
"intentRoutesNone": "No intent routes enabled",
@@ -938,6 +957,17 @@
"noUsers": "No users available",
"selectOwner": "Select an owner",
"dataSourceConfig": "Data source & execution config",
"scheduleType": "Execution mode",
"scheduleTypeDataPipeline": "Data pipeline task",
"scheduleTypePlatformJob": "Platform built-in task",
"platformJob": "Platform task",
"selectPlatformJob": "Select a platform task",
"platformJobShippingInventory": "Shipping inventory RPA",
"platformJobFaqHotAggregate": "FAQ hot aggregate",
"platformJobFixedAssetsSnapshot": "Fixed assets snapshot",
"shippingInventoryJobHint": "Writes batch inventory RPA export triggers on schedule; optional JSON to limit source_codes.",
"shippingInventoryJobParams": "Job parameters (optional)",
"shippingInventoryJobParamsPlaceholder": "{\"source_codes\": [\"BYAWSATL01\"]}",
"dataSourceType": "Data source type",
"databaseDirect": "Database",
"externalApi": "External API",
@@ -1102,6 +1132,7 @@
"testRunFailed": "Test run failed",
"testQueryFailed": "Test query failed",
"configRequired": "At least one of Dify Agent, SQL config, or external API is required.",
"platformJobRequired": "Please select a platform built-in task",
"headerLabelsJsonInvalid": "header_labels JSON format is invalid.",
"apiHeadersJsonInvalid": "API Headers JSON format is invalid.",
"runNowFailed": "Manual run failed",
+41 -2
View File
@@ -233,9 +233,28 @@
"lockInput": "ห้ามส่งข้อความใหม่ขณะงานกำลังทำงาน",
"scheduleTaskRequired": "โปรดเลือกตารางงานที่เชื่อมก่อน"
},
"capabilities": {
"title": "ความสามารถในการทำงาน",
"subtitle": "ควบคุมการสตรีม การอัปโหลดไฟล์ ความคืบหน้างาน การยืนยันจากผู้ใช้ การอ้างอิงแหล่งที่มา และคู่มือเริ่มต้นในแชท",
"forcedByCatalog": "ถูกกำหนดโดยประเภทแอปปัจจุบันและปิดไม่ได้",
"streaming": "สตรีมมิ่ง",
"streamingHint": "ตอบแชทแบบ SSE แบบสตรีม ปิดแล้วจะรอคำตอบเต็ม",
"file_upload": "อัปโหลดไฟล์",
"file_uploadHint": "แสดงปุ่มอัปโหลดไฟล์ในแชท (ไฟล์ในเครื่อง / URL)",
"task_progress": "ความคืบหน้างาน",
"task_progressHint": "แสดงความคืบหน้างานแบบอะซิงโครนัสในแชท (เช่น ขั้นตอนจัดส่ง การตรวจไฟล์)",
"human_confirm": "ยืนยันจากผู้ใช้",
"human_confirmHint": "เปิดขั้นตอนที่ต้องให้ผู้ใช้ยืนยันอย่างชัดเจน",
"source_citation": "อ้างอิงแหล่งที่มา",
"source_citationHint": "แสดงการอ้างอิงจาก knowledge base ในคำตอบ",
"guide": "คู่มือเริ่มต้น",
"guideHint": "แสดงทางเข้าคู่มือแอป / onboarding ในหน้าแชท",
"erp_kb": "ERP fixed-asset KB",
"erp_kbHint": "ใช้ enterprise KB เป็นค่าเริ่มต้นและสลับไปยัง ERP fixed-asset knowledge base ได้"
},
"registry": {
"title": "เส้นทางและความสามารถ",
"subtitle": "กำหนด fast path ของ intent และ ERP knowledge base โดยไม่พึ่งชื่อแอป",
"title": "Intent fast path",
"subtitle": "เมื่อตรงกับ intent ที่กำหนด จะข้าม flow แชทปกติและใช้ handler เฉพาะ",
"intentRoutesLabel": "Intent routes",
"advancedTitle": "การตั้งค่าขั้นสูง",
"intentRoutesNone": "ยังไม่ได้เปิดใช้ intent routes",
@@ -842,6 +861,25 @@
},
"schedule": {
"form": {
"scheduleType": "โหมดการทำงาน",
"scheduleTypeDataPipeline": "งานประมวลผลข้อมูล",
"scheduleTypePlatformJob": "งานในตัวแพลตฟอร์ม",
"platformJob": "งานแพลตฟอร์ม",
"selectPlatformJob": "เลือกงานแพลตฟอร์ม",
"platformJobShippingInventory": "Shipping inventory RPA",
"platformJobFaqHotAggregate": "FAQ hot aggregate",
"platformJobFixedAssetsSnapshot": "Fixed assets snapshot",
"shippingInventoryJobHint": "เขียน batch inventory RPA export trigger ตาม Cron; JSON ตัวเลือกจำกัด source_codes",
"shippingInventoryJobParams": "พารามิเตอร์ Job (ไม่บังคับ)",
"shippingInventoryJobParamsPlaceholder": "{\"source_codes\": [\"BYAWSATL01\"]}",
"dataSourceConfig": "แหล่งข้อมูลและการตั้งค่าการทำงาน",
"dataSourceType": "ประเภทแหล่งข้อมูล",
"databaseDirect": "ฐานข้อมูลโดยตรง",
"externalApi": "External API",
"faqHotAggregateHint": "รัน ChatLog hot-FAQ discovery ตาม Cron และเขียนลง faq_hot_candidates",
"faqHotAgentFilter": "จำกัด Agent (ไม่บังคับ)",
"faqHotAllAgents": "ทุก Agent",
"faqHotAgentFilterHelp": "เว้นว่างเพื่อรวมทุก Agent; เลือกหนึ่งรายการเพื่อจำกัด ChatLog",
"cronTitle": "ตั้งค่าเวลารัน",
"cronHint": "กำหนดปฏิทินและเวลาเพื่อสร้าง Cron อัตโนมัติ หรือสลับไปโหมดขั้นสูง Cron ใช้เขตเวลาของตารางเวลาปัจจุบัน",
"cronTimezoneHint": "Cron ใช้เขตเวลา {tz} เวลาที่แสดงตามโซนเวลาของเบราว์เซอร์",
@@ -961,6 +999,7 @@
"msg": {
"testRunFailed": "ทดสอบการทำงานล้มเหลว",
"configRequired": "ต้องกรอกอย่างน้อยหนึ่งรายการใน Dify Agent, SQL config หรือ external API",
"platformJobRequired": "โปรดเลือกงานในตัวแพลตฟอร์ม",
"headerLabelsJsonInvalid": "รูปแบบ JSON ของ header_labels ไม่ถูกต้อง",
"apiHeadersJsonInvalid": "รูปแบบ JSON ของ API Headers ไม่ถูกต้อง",
"runNowFailed": "การรันด้วยตนเองล้มเหลว",
+33 -2
View File
@@ -234,9 +234,28 @@
"lockInput": "任务执行期间禁止发送新消息",
"scheduleTaskRequired": "请先选择关联的排程任务"
},
"capabilities": {
"title": "运行能力",
"subtitle": "控制聊天页是否支持流式输出、附件上传、任务进度、人工确认、引用来源与新手指南等运行时能力",
"forcedByCatalog": "由当前应用类型固定,不可关闭",
"streaming": "流式输出",
"streamingHint": "开启后对话以 SSE 流式返回,关闭则等待完整响应",
"file_upload": "附件上传",
"file_uploadHint": "开启后聊天页显示附件上传入口(本地文件 / URL)",
"task_progress": "任务进度",
"task_progressHint": "开启后对话中展示异步任务进度(如发货流程、文件检核)",
"human_confirm": "人工确认",
"human_confirmHint": "开启后支持需要用户确认的关键步骤交互",
"source_citation": "引用来源",
"source_citationHint": "开启后在回答中展示知识库引用来源",
"guide": "新手指南",
"guideHint": "开启后聊天页展示平台应用说明 / 新手指南入口",
"erp_kb": "ERP 固资知识库",
"erp_kbHint": "启用后聊天页默认展示企业知识库,并允许切换到 ERP 固资知识库"
},
"registry": {
"title": "路由与能力",
"subtitle": "配置 Intent 快路径与 ERP 知识库等结构化能力,运行时不再依赖应用名称判断",
"title": "意图快路径",
"subtitle": "命中特定意图时绕过默认对话流,走专用处理器",
"intentRoutesLabel": "Intent 路由",
"advancedTitle": "高级配置",
"intentRoutesNone": "未启用 Intent 路由",
@@ -918,6 +937,17 @@
"noUsers": "暂无可用用户",
"selectOwner": "请选择所有者",
"dataSourceConfig": "数据源与执行配置",
"scheduleType": "执行模式",
"scheduleTypeDataPipeline": "数据处理任务",
"scheduleTypePlatformJob": "平台内置任务",
"platformJob": "平台任务",
"selectPlatformJob": "请选择平台任务",
"platformJobShippingInventory": "货代库存 RPA",
"platformJobFaqHotAggregate": "FAQ 热点聚合",
"platformJobFixedAssetsSnapshot": "固资快照",
"shippingInventoryJobHint": "按 Cron 批量写入库存 RPA 导出 trigger;可选 JSON 参数限定 source_codes。",
"shippingInventoryJobParams": "Job 参数(可选)",
"shippingInventoryJobParamsPlaceholder": "{\"source_codes\": [\"BYAWSATL01\"]}",
"dataSourceType": "数据源类型",
"databaseDirect": "数据库直联",
"externalApi": "外部API",
@@ -1082,6 +1112,7 @@
"testRunFailed": "测试执行失败",
"testQueryFailed": "测试查询失败",
"configRequired": "Dify Agent、SQL 配置或外部 API 至少填写一项,否则排程执行无任何效果",
"platformJobRequired": "请选择平台内置任务",
"headerLabelsJsonInvalid": "header_labels JSON 格式错误,请检查",
"apiHeadersJsonInvalid": "API Headers JSON 格式错误,请检查",
"runNowFailed": "手动执行失败",
+41 -2
View File
@@ -233,9 +233,28 @@
"lockInput": "任務執行期間禁止發送新訊息",
"scheduleTaskRequired": "請先選擇關聯的排程任務"
},
"capabilities": {
"title": "執行能力",
"subtitle": "控制聊天頁是否支援串流輸出、附件上傳、任務進度、人工確認、引用來源與新手指南等執行時能力",
"forcedByCatalog": "由目前應用類型固定,不可關閉",
"streaming": "串流輸出",
"streamingHint": "開啟後對話以 SSE 串流返回,關閉則等待完整回應",
"file_upload": "附件上傳",
"file_uploadHint": "開啟後聊天頁顯示附件上傳入口(本機檔案 / URL)",
"task_progress": "任務進度",
"task_progressHint": "開啟後對話中展示非同步任務進度(如發貨流程、檔案檢核)",
"human_confirm": "人工確認",
"human_confirmHint": "開啟後支援需要使用者確認的關鍵步驟互動",
"source_citation": "引用來源",
"source_citationHint": "開啟後在回答中展示知識庫引用來源",
"guide": "新手指南",
"guideHint": "開啟後聊天頁展示平台應用說明 / 新手指南入口",
"erp_kb": "ERP 固資知識庫",
"erp_kbHint": "啟用後聊天頁預設展示企業知識庫,並允許切換到 ERP 固資知識庫"
},
"registry": {
"title": "路由與能力",
"subtitle": "配置 Intent 快路徑與 ERP 知識庫等結構化能力,執行時不再依賴應用名稱判斷",
"title": "意圖快路徑",
"subtitle": "命中特定意圖時繞過預設對話流,走專用處理器",
"intentRoutesLabel": "Intent 路由",
"advancedTitle": "進階設定",
"intentRoutesNone": "未啟用 Intent 路由",
@@ -843,6 +862,25 @@
},
"schedule": {
"form": {
"scheduleType": "執行模式",
"scheduleTypeDataPipeline": "資料處理任務",
"scheduleTypePlatformJob": "平台內建任務",
"platformJob": "平台任務",
"selectPlatformJob": "請選擇平台任務",
"platformJobShippingInventory": "貨代庫存 RPA",
"platformJobFaqHotAggregate": "FAQ 熱點聚合",
"platformJobFixedAssetsSnapshot": "固資快照",
"shippingInventoryJobHint": "按 Cron 批量寫入庫存 RPA 匯出 trigger;可選 JSON 參數限定 source_codes。",
"shippingInventoryJobParams": "Job 參數(可選)",
"shippingInventoryJobParamsPlaceholder": "{\"source_codes\": [\"BYAWSATL01\"]}",
"dataSourceConfig": "資料來源與執行配置",
"dataSourceType": "資料來源類型",
"databaseDirect": "資料庫直連",
"externalApi": "外部 API",
"faqHotAggregateHint": "按 Cron 自動執行 ChatLog 熱點發現,結果寫入 faq_hot_candidates 表。",
"faqHotAgentFilter": "限定應用(可選)",
"faqHotAllAgents": "全部應用",
"faqHotAgentFilterHelp": "留空則聚合所有 Agent;選定後僅統計該應用的 ChatLog。",
"cronTitle": "執行時間設定",
"cronHint": "透過日曆與時刻配置自動產生 Cron,也可切換進階模式手動輸入。Cron 時刻按目前排程時區解讀。",
"cronTimezoneHint": "Cron 時刻按 {tz} 解讀,介面顯示為本地時間。",
@@ -962,6 +1000,7 @@
"msg": {
"testRunFailed": "測試執行失敗",
"configRequired": "Dify Agent、SQL 配置或外部 API 至少填寫一項,否則排程執行無任何效果",
"platformJobRequired": "請選擇平台內建任務",
"headerLabelsJsonInvalid": "header_labels JSON 格式錯誤,請檢查",
"apiHeadersJsonInvalid": "API Headers JSON 格式錯誤,請檢查",
"runNowFailed": "手動執行失敗",
+3 -2
View File
@@ -6,14 +6,15 @@ export interface ScheduleTask {
id: number;
schedule_no: string;
name: string;
schedule_type: string;
schedule_type: 'data_pipeline' | 'platform_job' | string;
owner_user_id: number;
owner_username?: string | null;
cron_expr: string;
schedule_timezone?: string | null;
wait_seconds: number;
dify_agent_id?: number | null;
data_source_type?: string;
platform_api_path?: string | null;
data_source_type?: 'database' | 'external_api' | null;
kb_sync_enabled?: boolean;
kb_group_id?: number | null;
notify_user_ids_json: number[];
@@ -7,13 +7,18 @@ import { describe, expect, it } from 'vitest';
import {
AGENT_CODE_SHIPPING_NOTICE,
agentHasIntentUiProfile,
agentHasProgress,
agentHasTaskProgress,
agentProgressRequiresScheduleTask,
agentUsesScheduleRunCounterProgress,
agentUsesWorkspaceStepperProgress,
canUseLeaveFeature,
isHrFocusedAgent,
isShippingNoticeAgent,
resolveAgentContentProfileKey,
resolveAgentCode,
resolveIntentRoutes,
resolveProgressContract,
} from './agent-registry.utils';
describe('agent-registry.utils', () => {
@@ -58,4 +63,31 @@ describe('agent-registry.utils', () => {
expect(agentHasIntentUiProfile({ intent_ui_profiles: ['maintenance'] }, 'maintenance')).toBe(true);
expect(agentHasIntentUiProfile({ intent_ui_profiles: [] }, 'maintenance')).toBe(false);
});
it('resolveProgressContract and helpers distinguish file_check vs shipping_notice', () => {
const fileCheckContract = {
enabled: true,
data_source: { type: 'schedule_run' as const },
presentation: { layout: 'card' as const, visualization: 'counter' as const },
binding: { requires_schedule_task: true },
};
const shippingContract = {
enabled: true,
data_source: { type: 'domain_state' as const, domain: 'shipping_notice' },
presentation: { layout: 'workspace' as const, visualization: 'stepper' as const },
binding: { requires_schedule_task: false },
};
const fileCheckAgent = { capabilities: { task_progress: true }, progress_contract: fileCheckContract };
const shippingAgent = { capabilities: { task_progress: true }, progress_contract: shippingContract };
expect(resolveProgressContract(fileCheckAgent)).toEqual(fileCheckContract);
expect(agentHasProgress(fileCheckAgent)).toBe(true);
expect(agentProgressRequiresScheduleTask(fileCheckAgent)).toBe(true);
expect(agentUsesScheduleRunCounterProgress(fileCheckAgent)).toBe(true);
expect(agentUsesWorkspaceStepperProgress(fileCheckAgent)).toBe(false);
expect(agentProgressRequiresScheduleTask(shippingAgent)).toBe(false);
expect(agentUsesWorkspaceStepperProgress(shippingAgent)).toBe(true);
expect(agentUsesScheduleRunCounterProgress(shippingAgent)).toBe(false);
});
});
@@ -27,6 +27,35 @@ export interface ToolRunProgressView {
lock_input_when_running?: boolean;
}
export type ProgressDataSourceType = 'schedule_run' | 'domain_state' | 'job_queue' | 'external_callback';
export type ProgressTransport = 'polling' | 'sse' | 'manual_refresh';
export type ProgressBindingType = 'chat_log_run' | 'conversation_context' | 'domain_key';
export type ProgressLayout = 'card' | 'workspace' | 'inline' | 'drawer';
export type ProgressVisualization = 'counter' | 'stepper' | 'timeline' | 'percent' | 'hybrid';
export interface ProgressContract {
enabled?: boolean;
data_source?: {
type?: ProgressDataSourceType;
domain?: string;
};
update?: {
transport?: ProgressTransport;
event?: string;
interval_seconds?: number;
};
binding?: {
type?: ProgressBindingType;
keys?: string[];
fallback?: string;
requires_schedule_task?: boolean;
};
presentation?: {
layout?: ProgressLayout;
visualization?: ProgressVisualization;
};
}
export interface AgentRegistryFields {
id?: number;
name?: string | null;
@@ -51,6 +80,7 @@ export interface AgentRegistryFields {
[key: string]: unknown;
} | null;
tool_run_progress?: ToolRunProgressView | null;
progress_contract?: ProgressContract | null;
intent_ui_profiles?: string[] | null;
leave_feature_enabled?: boolean | null;
hr_focused_avatar?: boolean | null;
@@ -123,10 +153,73 @@ export function agentHasIntentUiProfile(agent: AgentLike, profile: string): bool
return Array.isArray(profiles) && profiles.includes(normalized);
}
/** 是否声明异步任务进度(capabilities.task_progress === true)。 */
/** 是否声明异步任务进度能力(capabilities.task_progress === true)。 */
export function agentHasTaskProgress(agent: AgentLike): boolean {
return resolveAgentCapabilities(agent).task_progress === true;
}
/**
* 解析 progress_contract;优先 API 下发,缺失时返回 null。
*/
export function resolveProgressContract(agent: AgentLike): ProgressContract | null {
const contract = agent?.progress_contract;
if (!contract || typeof contract !== 'object' || contract.enabled !== true) {
return null;
}
return contract;
}
/** Agent 是否有可用进度契约(progress_contract.enabled === true)。 */
export function agentHasProgress(agent: AgentLike): boolean {
return resolveProgressContract(agent) !== null;
}
/** 进度数据源类型。 */
export function agentProgressDataSourceType(agent: AgentLike): ProgressDataSourceType | null {
return resolveProgressContract(agent)?.data_source?.type ?? null;
}
/** 进度更新传输方式。 */
export function agentProgressTransport(agent: AgentLike): ProgressTransport | null {
return resolveProgressContract(agent)?.update?.transport ?? null;
}
/** 进度展示布局。 */
export function agentProgressLayout(agent: AgentLike): ProgressLayout | null {
return resolveProgressContract(agent)?.presentation?.layout ?? null;
}
/** 进度可视化形态。 */
export function agentProgressVisualization(agent: AgentLike): ProgressVisualization | null {
return resolveProgressContract(agent)?.presentation?.visualization ?? null;
}
/** 进度契约是否要求绑定排程任务。 */
export function agentProgressRequiresScheduleTask(agent: AgentLike): boolean {
return resolveProgressContract(agent)?.binding?.requires_schedule_task === true;
}
/** 是否展示 workspace + stepper 形态的域状态进度(如货代发货)。 */
export function agentUsesWorkspaceStepperProgress(agent: AgentLike): boolean {
const contract = resolveProgressContract(agent);
if (!contract) return false;
return (
contract.presentation?.layout === 'workspace'
&& contract.presentation?.visualization === 'stepper'
&& contract.data_source?.type === 'domain_state'
);
}
/** 是否展示 schedule_run + counter 形态的轮询进度卡片(如文件检核)。 */
export function agentUsesScheduleRunCounterProgress(agent: AgentLike): boolean {
const contract = resolveProgressContract(agent);
if (!contract) return false;
return (
contract.data_source?.type === 'schedule_run'
&& contract.presentation?.visualization === 'counter'
&& contract.presentation?.layout === 'card'
);
}
/** 是否启用 ERP 固资知识库特化(capabilities.erp_kb)。 */
export function agentHasErpKb(agent: AgentLike): boolean {
return Boolean(resolveAgentCapabilities(agent).erp_kb);