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

+143 -103
View File
@@ -1,126 +1,109 @@
"""
backend/app/api/internal_jobs.py
用途:平台内置 Job 内部 API(POST /api/internal/jobs/<job_key>)。
依赖:job_registry、schedule_contract、scheduler_service。
逻辑:标准化 job key → registry 查 handler → 解析 ScheduleRun → 返回统一结构。
"""
from __future__ import annotations
import traceback
from datetime import datetime
from flask import Blueprint, jsonify, request
from app import db
from app.core.errors import AppError, NotFoundError, ValidationError
from app.models import ScheduleRun, ScheduleTask
from app.services.schedule import _run_generic_check_job
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
from app.core.errors import (
AppError,
ConflictError,
ForbiddenError,
NotFoundError,
ServiceUnavailableError,
UnauthorizedError,
ValidationError,
raise_for_status,
)
from app.services.schedule.job_registry import get_platform_job, run_platform_job
from app.services.schedule.schedule_contract import normalize_job_key
from app.services.schedule.scheduler_service import _generate_run_no
internal_jobs_bp = Blueprint('internal_jobs', __name__)
@internal_jobs_bp.route('/<name>', methods=['POST'])
def run_internal_job(name: str):
key = name.strip().lower()
data = request.get_json(silent=True) or {}
if key in {'fixed-assets-snapshot', 'fixed_assets_snapshot', 'fixedassets'}:
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
summary = FixedAssetsSnapshotService.sync_once(reason='internal_api', attempt=1)
row_count = int(summary.get('row_count') or 0)
return jsonify({
'summary': {
'total_count': row_count,
'success_count': row_count,
'failed_count': 0,
'skipped_count': 0,
},
'details': [summary],
'errors': [],
'step_logs': [
{
'step': 'fixed_assets_snapshot_sync',
'status': 'success',
'detail': {
'version': summary.get('current_version'),
'row_count': row_count,
},
}
],
})
if key in {'faq-aggregate-hot', 'faq_hot_aggregate', 'faq-hot-aggregate'}:
from app.services.hot_faq_aggregator import HotFaqAggregator
schedule_task_id = data.get('schedule_task_id')
agent_id = data.get('agent_id')
if schedule_task_id:
task = db.session.get(ScheduleTask, int(schedule_task_id))
if task and task.dify_agent_id:
agent_id = task.dify_agent_id
result = HotFaqAggregator.aggregate_hot_faq_candidates(
agent_id=int(agent_id) if agent_id else None,
dry_run=False,
def _assert_task_matches_job_key(task: ScheduleTask, job_key: str) -> None:
"""
校验 task 与 URL job key 一致,防止 schedule_task_id 指向错误 handler。
Raises:
ValidationError: 非 platform_job 或 platform_api_path 不匹配
"""
if task.schedule_type != 'platform_job':
raise ValidationError(f"schedule_task_id {task.id} is not a platform_job task")
task_key = normalize_job_key(task.platform_api_path)
if task_key != job_key:
raise ValidationError(
f"schedule_task_id {task.id} platform_api_path '{task.platform_api_path}' "
f"does not match job key '{job_key}'"
)
if not result.get('enabled'):
message = str(result.get('message') or 'FAQ_HOT_ENABLED is false')
return jsonify({
'summary': {'total_count': 0, 'success_count': 0, 'failed_count': 0, 'skipped_count': 1},
'details': [],
'errors': [message],
'step_logs': [{'step': 'faq_hot_aggregate', 'status': 'skipped', 'detail': {'message': message}}],
})
promoted = int(result.get('promoted_count') or 0)
skipped = int(result.get('skipped_count') or 0)
total = max(promoted + skipped, 1)
return jsonify({
'summary': {
'total_count': total,
'success_count': promoted,
'failed_count': 0,
'skipped_count': skipped,
},
'details': (result.get('candidates') or [])[:20],
'errors': [],
'step_logs': [{
'step': 'faq_hot_aggregate',
'status': 'success',
'detail': {
'scanned_logs': result.get('scanned_logs'),
'promoted_count': promoted,
'skipped_count': skipped,
},
}],
})
run_no = str(data.get('run_no') or '').strip()
def _resolve_schedule_task_and_run(job_key: str, data: dict) -> tuple[ScheduleTask, ScheduleRun]:
"""
解析或创建 ScheduleTask / ScheduleRun。
核心逻辑:优先 schedule_task_id(须匹配 job key);否则按 platform_api_path 匹配 job key。
run_no 查询限定 schedule_task_id,避免跨任务写入。
"""
schedule_task_id = data.get('schedule_task_id')
task = None
if schedule_task_id:
task = db.session.get(ScheduleTask, int(schedule_task_id))
if not task and key.isdigit():
task = db.session.get(ScheduleTask, int(key))
task = db.session.get(ScheduleTask, int(schedule_task_id)) if schedule_task_id else None
if task:
_assert_task_matches_job_key(task, job_key)
else:
task = (
ScheduleTask.query.filter(
ScheduleTask.platform_api_path == job_key,
ScheduleTask.schedule_type == 'platform_job',
)
.order_by(ScheduleTask.id.desc())
.first()
)
if not task:
task = ScheduleTask.query.filter(ScheduleTask.platform_api_path.ilike(f'%{key}%')).first()
if not task:
raise NotFoundError(f"No schedule task found for '{name}'")
raise NotFoundError(f"No schedule task found for platform job '{job_key}'")
run_no = str(data.get('run_no') or '').strip()
run = None
if run_no:
run = ScheduleRun.query.filter_by(run_no=run_no).first()
run = ScheduleRun.query.filter_by(run_no=run_no, schedule_task_id=task.id).first()
if not run:
foreign = ScheduleRun.query.filter_by(run_no=run_no).first()
if foreign and foreign.schedule_task_id != task.id:
raise ValidationError(
f"run_no '{run_no}' belongs to schedule_task_id {foreign.schedule_task_id}, "
f"not {task.id}"
)
if not run:
from app.services.schedule.scheduler_service import _generate_run_no
run = ScheduleRun(run_no=run_no or _generate_run_no(), schedule_task_id=task.id, trigger_type='api', started_at=datetime.utcnow(), status='running')
run = ScheduleRun(
run_no=run_no or _generate_run_no(),
schedule_task_id=task.id,
trigger_type='api',
started_at=datetime.utcnow(),
status='running',
)
db.session.add(run)
db.session.commit()
if not run.dify_execution_snapshot:
capture_dify_execution_snapshot(run, task)
db.session.commit()
try:
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = _run_generic_check_job(task, run)
except Exception as exc:
run.status = 'failed'
run.error_message = str(exc)
run.finished_at = datetime.utcnow()
db.session.commit()
raise AppError(code='SYSTEM.HTTP_ERROR', message=str(exc), http_status=500, details={'traceback': traceback.format_exc(), 'summary': {'total_count': 0, 'success_count': 0, 'failed_count': 0, 'skipped_count': 0}})
run.status = 'success' if failed_count == 0 else 'failed' if success_count == 0 else 'partial_failed'
return task, run
def _finalize_run(
run: ScheduleRun,
*,
total_count: int,
success_count: int,
failed_count: int,
skipped_count: int,
step_logs: list | None,
) -> None:
"""写入 run 汇总字段并 commit。"""
run.status = (
'success' if failed_count == 0
else 'failed' if success_count == 0
else 'partial_failed'
)
run.total_count = total_count
run.success_count = success_count
run.failed_count = failed_count
@@ -130,4 +113,61 @@ def run_internal_job(name: str):
run.duration_ms = int((run.finished_at - run.started_at).total_seconds() * 1000)
run.step_logs = step_logs if step_logs else None
db.session.commit()
return jsonify({'summary': {'total_count': total_count, 'success_count': success_count, 'failed_count': failed_count, 'skipped_count': skipped_count}, 'details': details, 'errors': errors, 'step_logs': step_logs})
@internal_jobs_bp.route('/<name>', methods=['POST'])
def run_internal_job(name: str):
"""
执行已注册平台 Job。
核心逻辑:标准化 job key → registry 查 handler → 解析 ScheduleRun → 返回统一结构。
"""
key = normalize_job_key(name)
data = request.get_json(silent=True) or {}
if not get_platform_job(key):
raise NotFoundError(f"Unknown platform job: {name}")
task, run = _resolve_schedule_task_and_run(key, data)
try:
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = run_platform_job(
key, task, run, data,
)
except Exception as exc:
run.status = 'failed'
run.error_message = str(exc)
run.finished_at = datetime.utcnow()
db.session.commit()
raise AppError(
code='SYSTEM.HTTP_ERROR',
message=str(exc),
http_status=500,
details={
'traceback': traceback.format_exc(),
'summary': {
'total_count': 0,
'success_count': 0,
'failed_count': 0,
'skipped_count': 0,
},
},
)
_finalize_run(
run,
total_count=total_count,
success_count=success_count,
failed_count=failed_count,
skipped_count=skipped_count,
step_logs=step_logs,
)
return jsonify({
'summary': {
'total_count': total_count,
'success_count': success_count,
'failed_count': failed_count,
'skipped_count': skipped_count,
},
'details': details,
'errors': errors,
'step_logs': step_logs,
})
+36 -7
View File
@@ -2,8 +2,8 @@
backend/app/api/schedule/config.py
用途:排程任务 SQL/数据源配置 API 与测试接口(薄路由层)。
依赖:schedule.blueprint、schedule.common、services/schedule/*。
逻辑:/schedule-config/* 路由。
依赖:schedule.blueprint、schedule.common、schedule_contract、services/schedule/*。
逻辑:/schedule-config/* 路由;配置更新仅允许 data_pipeline 任务修改 data_source_type。
"""
from __future__ import annotations
@@ -16,6 +16,11 @@ from app.core.auth.jwt import get_current_user
from app.core.decorators import require_admin
from app.core.errors import NotFoundError, ValidationError
from app.models import ScheduleTask, ScheduleTaskConfig
from app.services.schedule.schedule_contract import (
SCHEDULE_TYPE_DATA_PIPELINE,
apply_schedule_contract_to_payload,
platform_job_allows_config,
)
from app.services.schedule.sql_config import upsert_schedule_task_config
from app.services.schedule.sql_preview_service import preview_fetch_sql
from app.services.schedule.test_run_service import execute_test_run
@@ -37,22 +42,46 @@ def get_schedule_task_config(task_id: int):
@schedule_admin_bp.route('/schedule-config/<int:task_id>', methods=['PUT'])
@require_admin
def update_schedule_task_config(task_id: int):
"""更新排程 data_source_type 与 ScheduleTaskConfig。"""
"""
更新排程 data_source_type 与 ScheduleTaskConfig。
核心逻辑:仅 data_pipeline 允许改 data_source_type;platform_job 禁止经此接口绕过契约。
"""
task = db.session.get(ScheduleTask, task_id)
if not task:
raise NotFoundError('Not found')
data = request.get_json(silent=True) or {}
try:
if 'data_source_type' in data:
task.data_source_type = str(data['data_source_type'])
db.session.commit()
if task.schedule_type != SCHEDULE_TYPE_DATA_PIPELINE:
if 'data_source_type' in data:
raise ValidationError(
'data_source_type can only be updated for data_pipeline schedules; '
'use schedule task PATCH for platform_job'
)
elif 'data_source_type' in data:
contract = apply_schedule_contract_to_payload({
'schedule_type': task.schedule_type,
'data_source_type': data.get('data_source_type'),
'platform_api_path': task.platform_api_path,
})
task.data_source_type = contract['data_source_type']
config_data = data.get('config', data)
upsert_schedule_task_config(task_id, config_data)
if isinstance(config_data, dict) and config_data:
# platform_job 仅白名单任务(如 shipping-inventory-rpa)允许写 ScheduleTaskConfig
if task.schedule_type != SCHEDULE_TYPE_DATA_PIPELINE and not platform_job_allows_config(task.platform_api_path):
raise ValidationError(
f"platform_job '{task.platform_api_path}' does not accept ScheduleTaskConfig"
)
upsert_schedule_task_config(task_id, config_data, commit=False)
db.session.commit()
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
return jsonify({
'data_source_type': task.data_source_type,
'config': serialize_task_config(cfg_model) if cfg_model else None,
})
except ValidationError:
db.session.rollback()
raise
except Exception as exc:
db.session.rollback()
raise ValidationError(str(exc))
+107 -45
View File
@@ -17,10 +17,14 @@ from app.api.schedule.blueprint import schedule_admin_bp
from app.api.schedule.common import serialize_task_for_export
from app.core.auth.jwt import get_current_user
from app.core.decorators import require_admin
from app.core.errors import NotFoundError
from app.core.errors import NotFoundError, ValidationError
from app.models import ScheduleRun, ScheduleTask, ScheduleTaskConfig
from app.services.schedule.query_service import list_tasks, serialize_task
from app.services.schedule.import_service import import_schedules_from_payload
from app.services.schedule.schedule_contract import (
apply_schedule_contract_to_payload,
assert_schedule_config_writable,
)
from app.services.schedule.scheduler_service import create_task, update_task
from app.services.schedule.sql_config import upsert_schedule_task_config
@@ -32,6 +36,23 @@ def get_schedules():
return jsonify(list_tasks())
@schedule_admin_bp.route('/schedule/platform-jobs', methods=['GET'])
@require_admin
def get_platform_jobs():
"""返回 Job Registry 已注册平台任务列表,供前端下拉动态加载。"""
from app.services.schedule.job_registry import list_platform_jobs
return jsonify([
{
'key': job.key,
'label_key': job.label_key or None,
'label': job.label,
'description': job.description,
}
for job in list_platform_jobs()
])
@schedule_admin_bp.route('/schedules/<int:task_id>/export', methods=['GET'])
@require_admin
def export_schedule(task_id: int):
@@ -73,41 +94,59 @@ def post_schedule():
"""创建排程任务。"""
data = request.get_json(silent=True) or {}
user = get_current_user()
data_source_type = str(data.get('data_source_type') or 'database')
task = create_task(
name=str(data.get('name') or '').strip(),
schedule_type='platform_app',
owner_user_id=int(data.get('owner_user_id')),
cron_expr=str(data.get('cron_expr') or '').strip(),
schedule_timezone=data.get('schedule_timezone'),
wait_seconds=int(data.get('wait_seconds') or 0),
dify_agent_id=int(data.get('dify_agent_id')) if data.get('dify_agent_id') is not None else None,
platform_api_path=str(data.get('platform_api_path') or '').strip() or None,
notify_user_ids_json=data.get('notify_user_ids_json')
if isinstance(data.get('notify_user_ids_json'), list)
else [],
notify_enabled=bool(data.get('notify_enabled', True)),
enabled=bool(data.get('enabled', True)),
actor_id=getattr(user, 'id', None),
)
task.data_source_type = data_source_type
task.kb_sync_enabled = bool(data.get('kb_sync_enabled', False))
raw_kb_group_id = data.get('kb_group_id')
task.kb_group_id = int(raw_kb_group_id) if raw_kb_group_id not in (None, '', 0, '0') else None
if data_source_type == 'faq_hot_aggregate':
task.platform_api_path = 'faq-aggregate-hot'
else:
task.platform_api_path = f'/{task.id}'
db.session.commit()
db.session.refresh(task)
schedule_type = str(data.get('schedule_type') or 'data_pipeline')
data_source_type = data.get('data_source_type')
platform_api_path = data.get('platform_api_path')
config_data = data.get('config')
if config_data and data_source_type != 'faq_hot_aggregate':
upsert_schedule_task_config(task.id, config_data)
if not task.dify_agent_id:
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task.id).first()
if cfg_model and cfg_model.dify_system_prompt:
cfg_model.dify_system_prompt = None
db.session.commit()
if config_data is not None and not isinstance(config_data, dict):
raise ValidationError('config must be a JSON object')
if schedule_type.strip().lower() == 'data_pipeline' and data_source_type in (None, ''):
data_source_type = 'database'
try:
contract = apply_schedule_contract_to_payload({
'schedule_type': schedule_type,
'data_source_type': data_source_type,
'platform_api_path': platform_api_path,
})
assert_schedule_config_writable(
schedule_type=contract['schedule_type'],
platform_api_path=contract['platform_api_path'],
config=config_data,
)
task = create_task(
name=str(data.get('name') or '').strip(),
schedule_type=schedule_type,
owner_user_id=int(data.get('owner_user_id')),
cron_expr=str(data.get('cron_expr') or '').strip(),
schedule_timezone=data.get('schedule_timezone'),
wait_seconds=int(data.get('wait_seconds') or 0),
dify_agent_id=int(data.get('dify_agent_id')) if data.get('dify_agent_id') is not None else None,
platform_api_path=str(platform_api_path).strip() if platform_api_path else None,
data_source_type=str(data_source_type) if data_source_type is not None else None,
notify_user_ids_json=data.get('notify_user_ids_json')
if isinstance(data.get('notify_user_ids_json'), list)
else [],
notify_enabled=bool(data.get('notify_enabled', True)),
enabled=bool(data.get('enabled', True)),
kb_sync_enabled=bool(data.get('kb_sync_enabled', False)),
kb_group_id=int(data.get('kb_group_id')) if data.get('kb_group_id') not in (None, '', 0, '0') else None,
actor_id=getattr(user, 'id', None),
commit=not config_data,
)
except ValueError as exc:
raise ValidationError(str(exc))
if config_data:
try:
upsert_schedule_task_config(task.id, config_data, commit=False)
if not task.dify_agent_id:
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task.id).first()
if cfg_model and cfg_model.dify_system_prompt:
cfg_model.dify_system_prompt = None
db.session.commit()
except Exception:
db.session.rollback()
raise
db.session.refresh(task)
return jsonify(serialize_task(task)), 201
@@ -130,18 +169,41 @@ def patch_schedule(task_id: int):
raise NotFoundError('Not found')
data = request.get_json(silent=True) or {}
user = get_current_user()
if 'data_source_type' in data:
task.data_source_type = str(data['data_source_type'])
db.session.commit()
config_data = data.get('config')
if config_data:
upsert_schedule_task_config(task_id, config_data)
task = update_task(task, payload=data, actor_id=getattr(user, 'id', None))
if not task.dify_agent_id:
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
if cfg_model and cfg_model.dify_system_prompt:
cfg_model.dify_system_prompt = None
if config_data is not None and not isinstance(config_data, dict):
raise ValidationError('config must be a JSON object')
try:
# [STEP 1] 先校验契约与 config 写入权限,避免 update_task 已提交后 config 被拒产生半更新
contract = apply_schedule_contract_to_payload({
'schedule_type': data.get('schedule_type', task.schedule_type),
'data_source_type': data.get('data_source_type', task.data_source_type),
'platform_api_path': data.get('platform_api_path', task.platform_api_path),
})
assert_schedule_config_writable(
schedule_type=contract['schedule_type'],
platform_api_path=contract['platform_api_path'],
config=config_data,
)
task = update_task(
task,
payload=data,
actor_id=getattr(user, 'id', None),
commit=not config_data,
)
if config_data:
upsert_schedule_task_config(task_id, config_data, commit=False)
if not task.dify_agent_id:
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
if cfg_model and cfg_model.dify_system_prompt:
cfg_model.dify_system_prompt = None
if config_data:
db.session.commit()
except ValueError as exc:
db.session.rollback()
raise ValidationError(str(exc))
except Exception:
db.session.rollback()
raise
return jsonify(serialize_task(task))
+2 -2
View File
@@ -25,14 +25,14 @@ class ScheduleTask(Base):
id: Mapped[int] = mapped_column(primary_key=True)
schedule_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
name: Mapped[str] = mapped_column(String(128), index=True)
schedule_type: Mapped[str] = mapped_column(String(32), default='platform_app')
schedule_type: Mapped[str] = mapped_column(String(32), default='data_pipeline')
owner_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True)
cron_expr: Mapped[str] = mapped_column(String(64))
schedule_timezone: Mapped[str] = mapped_column(String(64), default='Asia/Shanghai', server_default=text("'Asia/Shanghai'"))
wait_seconds: Mapped[int] = mapped_column(Integer, default=0)
dify_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'), nullable=True, index=True)
platform_api_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
data_source_type: Mapped[str] = mapped_column(String(32), default='database')
data_source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
kb_sync_enabled: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false'))
kb_group_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_groups.id'), nullable=True, index=True)
notify_user_ids_json: Mapped[Optional[list]] = mapped_column(JSON, default=[])
@@ -20,6 +20,7 @@ from app.services.agent_registry.catalog_loader import (
)
from app.services.agent_registry.catalog_validation import (
apply_catalog_capabilities,
catalog_progress_requires_schedule_task,
default_capabilities_copy,
normalize_handler_config,
validate_required_fields,
@@ -176,6 +177,8 @@ def validate_agent_payload(
bound_schedule_task_id = data.get('bound_schedule_task_id', getattr(agent, 'bound_schedule_task_id', None) if agent else None)
bound_schedule_task_id = _parse_bound_schedule_task_id(bound_schedule_task_id)
if not catalog_progress_requires_schedule_task(agent_code):
bound_schedule_task_id = None
capabilities = _parse_capabilities(data.get('capabilities', getattr(agent, 'capabilities', None) if agent else None))
capabilities = apply_catalog_capabilities(agent_code, capabilities)
@@ -12,6 +12,7 @@ from typing import Any
from app.services.agent_registry.catalog_loader import (
build_agent_type_catalog,
get_agent_type_default_capabilities,
get_default_capabilities,
get_platform_config,
get_tool_run_progress_defaults,
@@ -41,7 +42,9 @@ def build_agent_registry_schema() -> dict[str, Any]:
agent_types.append({
**item,
'required_fields': list(entry.get('required_fields') or []),
'default_capabilities': get_agent_type_default_capabilities(str(code or '')),
'forced_capabilities': dict(entry.get('forced_capabilities') or {}),
'progress_contract': deepcopy_schema(entry.get('progress_contract')),
'default_intent_routes': list(entry.get('default_intent_routes') or []),
})
@@ -20,6 +20,17 @@ from app.services.agent_registry.catalog_bindings import RUNTIME_HANDLER_BINDING
_MANIFEST_PATH = Path(__file__).resolve().parent / 'data' / 'catalog_manifest.yaml'
_PROGRESS_DATA_SOURCES = frozenset({
'schedule_run',
'domain_state',
'job_queue',
'external_callback',
})
_PROGRESS_TRANSPORTS = frozenset({'polling', 'sse', 'manual_refresh'})
_PROGRESS_BINDINGS = frozenset({'chat_log_run', 'conversation_context', 'domain_key'})
_PROGRESS_LAYOUTS = frozenset({'card', 'workspace', 'inline', 'drawer'})
_PROGRESS_VISUALIZATIONS = frozenset({'counter', 'stepper', 'timeline', 'percent', 'hybrid'})
def coerce_manifest_boolean(value: Any, *, context: str = 'manifest') -> bool:
"""
@@ -128,6 +139,24 @@ def get_default_capabilities() -> dict[str, bool]:
return result
def get_agent_type_default_capabilities(agent_code: str) -> dict[str, bool]:
"""
合并 platform 与 agent_types 段 default_capabilities。
核心逻辑:平台默认为基础,类型级 default_capabilities 覆盖同名字段。
"""
merged = dict(get_default_capabilities())
entry = get_catalog_entry(agent_code) or {}
type_defaults = entry.get('default_capabilities') or {}
if isinstance(type_defaults, dict):
for key, value in type_defaults.items():
merged[str(key)] = coerce_manifest_boolean(
value,
context=f'agent_types.{agent_code}.default_capabilities.{key}',
)
return merged
def get_tool_run_progress_defaults() -> dict[str, Any]:
"""task_progress 视图默认值(含 progress_type);布尔/整数字段经 coercion。"""
platform = get_platform_config()
@@ -151,6 +180,134 @@ def get_tool_run_progress_defaults() -> dict[str, Any]:
}
def _enum_value(
value: Any,
*,
allowed: frozenset[str],
context: str,
default: str | None = None,
) -> str | None:
text = str(value or '').strip()
if not text:
return default
if text not in allowed:
raise ValidationError(f'{context} 取值无效: {text}')
return text
def normalize_progress_contract(raw: Any, *, context: str = 'progress_contract') -> dict[str, Any] | None:
"""
归一化通用进度契约。
核心逻辑:catalog 只声明通用 source/update/binding/presentation 维度,
不以 agent_code 作为进度类型。
"""
if raw in (None, False):
return None
if not isinstance(raw, dict):
raise ValidationError(f'{context} 必须为 JSON 对象')
enabled = coerce_manifest_boolean(raw.get('enabled', True), context=f'{context}.enabled')
if not enabled:
return {'enabled': False}
data_source_raw = raw.get('data_source') if isinstance(raw.get('data_source'), dict) else {}
update_raw = raw.get('update') if isinstance(raw.get('update'), dict) else {}
binding_raw = raw.get('binding') if isinstance(raw.get('binding'), dict) else {}
presentation_raw = raw.get('presentation') if isinstance(raw.get('presentation'), dict) else {}
data_source_type = _enum_value(
data_source_raw.get('type'),
allowed=_PROGRESS_DATA_SOURCES,
context=f'{context}.data_source.type',
)
if not data_source_type:
raise ValidationError(f'{context}.data_source.type 必填')
transport = _enum_value(
update_raw.get('transport'),
allowed=_PROGRESS_TRANSPORTS,
context=f'{context}.update.transport',
default='polling',
)
binding_type = _enum_value(
binding_raw.get('type'),
allowed=_PROGRESS_BINDINGS,
context=f'{context}.binding.type',
default='chat_log_run',
)
layout = _enum_value(
presentation_raw.get('layout'),
allowed=_PROGRESS_LAYOUTS,
context=f'{context}.presentation.layout',
default='card',
)
visualization = _enum_value(
presentation_raw.get('visualization'),
allowed=_PROGRESS_VISUALIZATIONS,
context=f'{context}.presentation.visualization',
default='counter',
)
interval_raw = update_raw.get('interval_seconds')
interval_seconds = None
if interval_raw is not None:
try:
interval_seconds = max(1, min(int(interval_raw), 30))
except (TypeError, ValueError):
raise ValidationError(f'{context}.update.interval_seconds 必须为整数')
keys_raw = binding_raw.get('keys')
keys = [
str(item or '').strip()
for item in keys_raw
if str(item or '').strip()
] if isinstance(keys_raw, list) else []
contract: dict[str, Any] = {
'enabled': True,
'data_source': {
'type': data_source_type,
},
'update': {
'transport': transport,
},
'binding': {
'type': binding_type,
'requires_schedule_task': coerce_manifest_boolean(
binding_raw.get('requires_schedule_task', False),
context=f'{context}.binding.requires_schedule_task',
),
},
'presentation': {
'layout': layout,
'visualization': visualization,
},
}
domain = str(data_source_raw.get('domain') or '').strip()
if domain:
contract['data_source']['domain'] = domain
event = str(update_raw.get('event') or '').strip()
if event:
contract['update']['event'] = event
if interval_seconds is not None:
contract['update']['interval_seconds'] = interval_seconds
fallback = str(binding_raw.get('fallback') or '').strip()
if fallback:
contract['binding']['fallback'] = fallback
if keys:
contract['binding']['keys'] = keys
# [STEP 组合校验] manifest 配错时 fail-fast,避免运行时静默失效。
if transport == 'sse' and not event:
raise ValidationError(f'{context}.update.transport=sse 时 update.event 必填')
if data_source_type == 'schedule_run' and contract['binding']['requires_schedule_task'] is not True:
raise ValidationError(
f'{context}.data_source.type=schedule_run 时 binding.requires_schedule_task 必须为 true',
)
return contract
@lru_cache(maxsize=1)
def build_agent_type_catalog() -> dict[str, dict[str, Any]]:
"""
@@ -169,6 +326,14 @@ def build_agent_type_catalog() -> dict[str, dict[str, Any]]:
continue
merged = deepcopy(entry)
merged['runtime_handler'] = RUNTIME_HANDLER_BINDINGS.get(str(code)) or None
if isinstance(merged.get('default_capabilities'), dict):
merged['default_capabilities'] = {
str(cap_key): coerce_manifest_boolean(
cap_value,
context=f'agent_types.{code}.default_capabilities.{cap_key}',
)
for cap_key, cap_value in merged['default_capabilities'].items()
}
if isinstance(merged.get('forced_capabilities'), dict):
merged['forced_capabilities'] = {
str(cap_key): coerce_manifest_boolean(
@@ -177,6 +342,10 @@ def build_agent_type_catalog() -> dict[str, dict[str, Any]]:
)
for cap_key, cap_value in merged['forced_capabilities'].items()
}
merged['progress_contract'] = normalize_progress_contract(
merged.get('progress_contract'),
context=f'agent_types.{code}.progress_contract',
)
catalog[str(code)] = merged
return catalog
@@ -42,22 +42,37 @@ def apply_catalog_capabilities(agent_code: str, capabilities: dict[str, bool]) -
return merged
def catalog_progress_requires_schedule_task(agent_code: str) -> bool:
"""
判断 Catalog progress_contract 是否要求绑定排程任务。
核心逻辑:优先读 progress_contract.binding.requires_schedule_task;
兼容 required_fields 中的 bound_schedule_task_id 声明。
"""
entry = get_catalog_entry(agent_code) or {}
progress = entry.get('progress_contract') if isinstance(entry.get('progress_contract'), dict) else {}
if progress.get('enabled') is True:
binding = progress.get('binding') if isinstance(progress.get('binding'), dict) else {}
if binding.get('requires_schedule_task') is True:
return True
required = entry.get('required_fields') or []
return isinstance(required, list) and 'bound_schedule_task_id' in required
def validate_required_fields(
agent_code: str,
*,
bound_schedule_task_id: int | None = None,
) -> None:
"""
校验 Catalog 声明的 required_fields。
校验 Catalog 声明的 required_fields 与 progress_contract.binding。
Raises:
ValidationError: 必填列缺失。
"""
entry = get_catalog_entry(agent_code) or {}
required = entry.get('required_fields') or []
if not isinstance(required, list):
if not catalog_progress_requires_schedule_task(agent_code):
return
if 'bound_schedule_task_id' in required and not bound_schedule_task_id:
if not bound_schedule_task_id:
raise ValidationError(f'agent_code={agent_code} 时 bound_schedule_task_id 必填')
@@ -58,7 +58,30 @@ agent_types:
- ShippingTask
- ShippingTaskEvent
required_fields: []
forced_capabilities: {}
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
keys:
- batch_no
- task_no
requires_schedule_task: false
presentation:
layout: workspace
visualization: stepper
handler_config_schema: {}
file_check:
label: 文件检核
@@ -70,6 +93,20 @@ agent_types:
- bound_schedule_task_id
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
fallback: chat_log_id
requires_schedule_task: true
presentation:
layout: card
visualization: counter
handler_config_schema:
poll_interval_seconds:
type: integer
@@ -2,7 +2,7 @@
backend/app/services/agent_registry/handlers/file_check.py
用途:文件检核 Agent Handler — 聊天流 turn 注册与 Dify 进度绑定。
依赖:file_check_tools.chat_turn_registry、agent_registry.handlers.registry。
依赖:file_check_tools.chat_turn_registry、agent_registry.handlers.registry、resolver。
逻辑:DifyChatExecutor 经 resolve_handler_for_agent_code 调用 prepare_stream 注册 hxops_turn_id。
"""
@@ -12,7 +12,16 @@ import uuid
from app.services.agent_registry.handlers.base import AgentHandler, ChatStreamContext
from app.services.agent_registry.handlers.registry import register_handler
from app.services.agent_registry.resolver import agent_declares_task_progress
from app.services.agent_registry.resolver import resolve_progress_contract
def _uses_schedule_run_progress(agent) -> bool:
"""progress_contract 声明 schedule_run 数据源时才注册检核 turn。"""
contract = resolve_progress_contract(agent)
if not contract:
return False
data_source = contract.get('data_source') if isinstance(contract.get('data_source'), dict) else {}
return data_source.get('type') == 'schedule_run'
@register_handler('file_check')
@@ -20,12 +29,12 @@ class FileCheckHandler(AgentHandler):
"""
文件检核业务 Handler。
核心逻辑:capabilities.task_progress === true 时在 Dify 流开始前注册 hxops_turn_id,
供检核进度轮询绑定 chat_log;capabilities 本身仅控制前端是否展示进度 UI。
核心逻辑:progress_contract.data_source=schedule_run 时在 Dify 流开始前注册 hxops_turn_id,
供检核进度轮询绑定 chat_log;capabilities.task_progress 仅作能力门禁。
"""
def prepare_stream(self, ctx: ChatStreamContext) -> ChatStreamContext:
if not agent_declares_task_progress(ctx.agent):
if not _uses_schedule_run_progress(ctx.agent):
return ctx
turn_id = uuid.uuid4().hex
@@ -15,6 +15,22 @@ from flask import current_app
from app.services.agent_registry.handlers.base import AgentHandler, ChatStreamContext
from app.services.agent_registry.handlers.registry import register_handler
from app.services.agent_registry.resolver import resolve_progress_contract
def _uses_shipping_ui_state_progress(agent) -> bool:
"""progress_contract 声明 domain_state + shipping_ui_state SSE 时才下发 UI State。"""
contract = resolve_progress_contract(agent)
if not contract:
return False
data_source = contract.get('data_source') if isinstance(contract.get('data_source'), dict) else {}
update = contract.get('update') if isinstance(contract.get('update'), dict) else {}
return (
data_source.get('type') == 'domain_state'
and data_source.get('domain') == 'shipping_notice'
and update.get('transport') == 'sse'
and update.get('event') == 'shipping_ui_state'
)
@register_handler('shipping_notice')
@@ -31,6 +47,9 @@ class ShippingNoticeHandler(AgentHandler):
核心逻辑:优先显式 task_id,其次 batch 焦点任务;失败时记录日志并返回 None。
"""
if not _uses_shipping_ui_state_progress(ctx.agent):
return None
task_id = str(ctx.shipping_task_id or '').strip()
batch_no = str(ctx.shipping_batch_no or '').strip()
if not task_id and not batch_no:
@@ -287,6 +287,40 @@ def agent_declares_task_progress(agent) -> bool:
return resolve_capabilities(agent).get('task_progress') is True
def resolve_progress_contract(agent) -> dict[str, Any] | None:
"""
解析 Agent 通用进度契约。
核心逻辑:读 catalog 中的 progress_contract;task_progress 门禁同时合并
Catalog forced_capabilities,避免存量行 capabilities 缺失导致进度 UI 消失。
"""
entry = get_catalog_entry(resolve_agent_code(agent)) or {}
forced = entry.get('forced_capabilities') if isinstance(entry.get('forced_capabilities'), dict) else {}
task_progress_enabled = (
agent_declares_task_progress(agent)
or forced.get('task_progress') is True
)
if not task_progress_enabled:
return None
contract = entry.get('progress_contract')
if not isinstance(contract, dict) or contract.get('enabled') is not True:
return None
import copy
return copy.deepcopy(contract)
def agent_has_progress(agent) -> bool:
"""判断 Agent 是否有可用通用进度契约。"""
return resolve_progress_contract(agent) is not None
def agent_progress_requires_schedule_task(agent) -> bool:
"""判断 Agent 进度契约是否需要绑定 ScheduleTask。"""
contract = resolve_progress_contract(agent)
binding = contract.get('binding') if isinstance(contract, dict) else None
return isinstance(binding, dict) and binding.get('requires_schedule_task') is True
def is_file_check_runtime_ready(agent) -> bool:
"""
判断 file_check 对话入口是否已完整配置(可注入 task_id、绑定 chat_log.run_id)。
@@ -299,7 +333,7 @@ def is_file_check_runtime_ready(agent) -> bool:
Returns:
能力声明且 task_id 列已配置时返回 True。
"""
if not agent_declares_task_progress(agent):
if not agent_progress_requires_schedule_task(agent):
return False
from app.services.file_check_tools.task_resolver import resolve_schedule_task_id_from_agent
@@ -12,10 +12,10 @@ from typing import Any
from app.models import Agent
from app.services.agent_registry.resolver import (
normalize_capabilities,
resolve_agent_code,
resolve_capabilities,
resolve_conversation_mode,
resolve_progress_contract,
resolve_runtime_provider,
)
@@ -43,6 +43,7 @@ def serialize_registry_fields(agent: Agent | Any) -> dict[str, Any]:
handler_config = getattr(agent, 'handler_config', None)
intent_meta = resolve_agent_intent_metadata(agent)
tool_run_progress = build_tool_run_progress_view(agent)
progress_contract = resolve_progress_contract(agent)
return {
'agent_code': resolve_agent_code(agent),
'runtime_provider': resolve_runtime_provider(agent),
@@ -60,12 +61,13 @@ def serialize_registry_fields(agent: Agent | Any) -> dict[str, Any]:
'bound_schedule_task_id': getattr(agent, 'bound_schedule_task_id', None),
'handler_config': handler_config if isinstance(handler_config, dict) else None,
'tool_run_progress': tool_run_progress,
'progress_contract': progress_contract,
**intent_meta,
}
def serialize_agent_for_admin(agent: Agent) -> dict[str, Any]:
"""Agent ORM → 管理端列表/详情 JSON(API Key 仅返回脱敏值,明文不可读)。"""
"""Agent ORM → 管理端列表/详情 JSON(含 dify_api_key 供编辑表单密码框回填)。"""
registry = serialize_registry_fields(agent)
return {
'id': agent.id,
@@ -75,6 +77,7 @@ def serialize_agent_for_admin(agent: Agent) -> dict[str, Any]:
'is_active': agent.is_active,
'type': agent.type,
'dify_app_id': agent.dify_app_id,
'dify_api_key': agent.dify_api_key,
'dify_api_key_masked': mask_dify_api_key(agent.dify_api_key),
'api_base_url': agent.api_base_url,
'extra_config': agent.extra_config if isinstance(agent.extra_config, dict) else {},
@@ -123,13 +126,18 @@ def serialize_agent_for_user_detail(
def build_tool_run_progress_view(agent: Agent) -> dict[str, Any] | None:
"""
从 Registry 列构建前端 tool_run_progress 视图(迁移期兼容 extra 读者)。
从 Registry 列构建前端 tool_run_progress 视图(schedule_run 进度兼容层)。
核心逻辑:capabilities.task_progress 为 true 且 bound_schedule_task_id 已注册时返回配置 dict。
核心逻辑:progress_contract.data_source.type=schedule_run 且 bound_schedule_task_id
已注册时返回配置 dict;domain_state 等其它进度类型不走本视图。
"""
caps = resolve_capabilities(agent)
if not caps.get('task_progress'):
contract = resolve_progress_contract(agent)
if not contract:
return None
data_source = contract.get('data_source') if isinstance(contract.get('data_source'), dict) else {}
if data_source.get('type') != 'schedule_run':
return None
task_id = getattr(agent, 'bound_schedule_task_id', None)
try:
schedule_task_id = int(task_id)
@@ -143,11 +151,12 @@ def build_tool_run_progress_view(agent: Agent) -> dict[str, Any] | None:
from app.services.agent_registry.resolver import resolve_agent_code
defaults = get_tool_run_progress_defaults()
update = contract.get('update') if isinstance(contract.get('update'), dict) else {}
cfg: dict[str, Any] = {
'type': str(defaults.get('progress_type') or resolve_agent_code(agent) or 'file_check'),
'schedule_task_id': schedule_task_id,
}
cfg['poll_interval_seconds'] = defaults.get('poll_interval_seconds', 2)
cfg['poll_interval_seconds'] = update.get('interval_seconds') or defaults.get('poll_interval_seconds', 2)
cfg['lock_input_when_running'] = defaults.get('lock_input_when_running', True)
if isinstance(handler_config, dict):
if handler_config.get('poll_interval_seconds') is not None:
+51 -19
View File
@@ -21,15 +21,21 @@ ScheduleExecutor = Callable[[ScheduleTask, ScheduleRun], ScheduleExecuteResult]
def normalize_platform_api_path(path: str | None) -> str:
"""
归一化 platform job key 或完整 URL。
核心逻辑:http(s) 完整 URL 原样返回(外部集成端点);
其余值统一委托 schedule_contract.normalize_job_key(契约层与执行层单一归一化入口)。
"""
value = str(path or "").strip()
if not value:
return ""
parsed = urlparse(value)
if parsed.scheme in {"http", "https"}:
return value
if not value.startswith("/"):
value = "/" + value
return value
from app.services.schedule.schedule_contract import normalize_job_key
return normalize_job_key(value)
def _build_srm_conn_str() -> str:
@@ -67,11 +73,38 @@ def _resolve_schedule_user(task: ScheduleTask) -> str:
return str(getattr(task.owner, "username", "") or task.owner_user_id or "schedule_system")
def _run_platform_job_in_process(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
进程内执行已注册平台 Job(无需 HTTP,也不依赖 INTERNAL_API_BASE_URL)。
核心逻辑:从 job_registry 按 platform_api_path 查 handler 直接调用。
"""
from app.services.schedule.job_registry import run_platform_job
key = normalize_platform_api_path(task.platform_api_path)
payload = {
"run_no": run.run_no,
"schedule_task_id": task.id,
"schedule_name": task.name,
"dify_agent_id": task.dify_agent_id,
}
run.api_request_json = payload
db.session.commit()
return run_platform_job(key, task, run, payload)
def _run_common_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
endpoint = normalize_platform_api_path(task.platform_api_path)
if not endpoint:
raise RuntimeError("platform_api_path is missing")
# [STEP 1] 普通 job key(非完整 URL)优先进程内直接调 registry,避免 HTTP 与 base URL 依赖
if not (endpoint.startswith("http://") or endpoint.startswith("https://")):
from app.services.schedule.job_registry import get_platform_job
if get_platform_job(endpoint):
return _run_platform_job_in_process(task, run)
# [STEP 2] 完整 URL(外部集成)仍走 HTTP;base URL 仅用于补全相对路径
base = str(current_app.config.get("INTERNAL_API_BASE_URL") or "").strip().rstrip("/")
if endpoint.startswith("http://") or endpoint.startswith("https://"):
url = endpoint
@@ -79,7 +112,9 @@ def _run_common_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecut
name = endpoint.lstrip("/")
url = f"{base}/api/internal/jobs/{name}"
else:
url = endpoint
raise RuntimeError(
f"platform_api_path '{endpoint}' is not a registered job and INTERNAL_API_BASE_URL is not configured"
)
payload = {
"run_no": run.run_no,
@@ -185,6 +220,10 @@ def _run_generic_check_job(task: ScheduleTask, run: ScheduleRun) -> ScheduleExec
_build_record_text,
)
dst = getattr(task, "data_source_type", None)
if dst not in ("database", "external_api"):
raise RuntimeError(f"Invalid data_source_type for data_pipeline: {dst!r}")
cfg = get_schedule_sql_config_by_task_id(task.id)
if not cfg:
return 0, 0, 0, 0, [], [], []
@@ -263,25 +302,18 @@ def _run_generic_check_job(task: ScheduleTask, run: ScheduleRun) -> ScheduleExec
def list_registered_api_paths() -> list[dict[str, str]]:
from app.models import ScheduleTask
results: list[dict[str, str]] = []
tasks = ScheduleTask.query.filter(ScheduleTask.platform_api_path.isnot(None)).all()
for t in tasks:
results.append({"value": t.platform_api_path, "label": t.name or str(t.id)})
return results
from app.services.schedule.job_registry import list_platform_jobs
return [{"value": job.key, "label": job.label} for job in list_platform_jobs()]
def resolve_schedule_executor(task: ScheduleTask) -> ScheduleExecutor:
dst = getattr(task, "data_source_type", None) or "database"
if dst == "faq_hot_aggregate":
from app.services.schedule.faq_hot_aggregate_job import run_faq_hot_aggregate_schedule
return run_faq_hot_aggregate_schedule
if dst == "shipping_inventory_rpa":
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
return run_shipping_inventory_rpa_schedule
if dst in ("database", "external_api"):
st = getattr(task, "schedule_type", None) or "data_pipeline"
if st == "data_pipeline":
return _run_generic_check_job
return _run_common_executor
if st == "platform_job":
return _run_common_executor
raise RuntimeError(f"Unsupported schedule_type: {st}")
_SCHEDULE_HEADER_REGISTRY: dict[str, tuple[list[str], dict[str, str]]] = {}
@@ -3,7 +3,7 @@ backend/app/services/schedule/faq_hot_aggregate_job.py
用途:排程管理触发的 FAQ 热点离线聚合执行器。
依赖:HotFaqAggregator、ScheduleTask、ScheduleRun。
逻辑:data_source_type=faq_hot_aggregate 时由 resolve_schedule_executor 调用。
逻辑:platform_api_path=faq-aggregate-hot 时由 job_registry 调用。
"""
from __future__ import annotations
@@ -0,0 +1,38 @@
"""
backend/app/services/schedule/fixed_assets_snapshot_job.py
用途:排程触发的固资快照同步执行器。
依赖:FixedAssetsSnapshotService、ScheduleTask、ScheduleRun。
逻辑:platform_api_path=fixed-assets-snapshot 时由 job_registry 调用。
"""
from __future__ import annotations
from typing import Any
from app.models import ScheduleRun, ScheduleTask
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
def run_fixed_assets_snapshot_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
执行固资快照同步(薄封装)。
核心逻辑:委托 FixedAssetsSnapshotService.sync_once,结果写入 step_logs。
"""
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
summary = FixedAssetsSnapshotService.sync_once(reason="schedule", attempt=1)
row_count = int(summary.get("row_count") or 0)
step_logs: list[dict[str, Any]] = [
{
"step": "fixed_assets_snapshot_sync",
"status": "success",
"detail": {
"version": summary.get("current_version"),
"row_count": row_count,
"schedule_task_id": task.id,
},
}
]
return row_count, row_count, 0, 0, [summary], [], step_logs
+50 -34
View File
@@ -2,8 +2,8 @@
backend/app/services/schedule/import_service.py
用途:排程任务 JSON 批量导入(upsert by schedule_no)。
依赖:models、scheduler_service、sql_config。
逻辑:由 api/schedule/tasks.py import 路由调用。
依赖:models、scheduler_service、schedule_contract、sql_config。
逻辑:由 api/schedule/tasks.py import 路由调用;导入时自动迁移旧语义。
"""
from __future__ import annotations
@@ -12,6 +12,11 @@ from typing import Any
from app import db
from app.core.errors import ValidationError
from app.models import ScheduleTask
from app.services.schedule.schedule_contract import (
apply_schedule_contract_to_payload,
assert_schedule_config_writable,
migrate_legacy_schedule_payload,
)
from app.services.schedule.scheduler_service import create_task, update_task
from app.services.schedule.sql_config import upsert_schedule_task_config
@@ -38,67 +43,78 @@ def import_schedules_from_payload(schedules: list[Any], *, actor_id: int | None)
skipped += 1
continue
try:
name = str(item.get('name') or '').strip()
cron_expr = str(item.get('cron_expr') or '').strip()
owner_user_id = int(item.get('owner_user_id'))
migrated = migrate_legacy_schedule_payload(item)
name = str(migrated.get('name') or '').strip()
cron_expr = str(migrated.get('cron_expr') or '').strip()
owner_user_id = int(migrated.get('owner_user_id'))
if not name or not cron_expr:
raise ValueError('name or cron_expr missing')
contract = apply_schedule_contract_to_payload({
'schedule_type': migrated.get('schedule_type'),
'data_source_type': migrated.get('data_source_type'),
'platform_api_path': migrated.get('platform_api_path'),
})
cfg = migrated.get('config') if isinstance(migrated.get('config'), dict) else None
assert_schedule_config_writable(
schedule_type=contract['schedule_type'],
platform_api_path=contract['platform_api_path'],
config=cfg,
)
existing = None
schedule_no = str(item.get('schedule_no') or '').strip()
schedule_no = str(migrated.get('schedule_no') or '').strip()
if schedule_no:
existing = db.session.query(ScheduleTask).filter_by(schedule_no=schedule_no).first()
task_payload = {
'name': name,
'schedule_type': str(item.get('schedule_type') or 'platform_app'),
'schedule_type': contract['schedule_type'],
'owner_user_id': owner_user_id,
'cron_expr': cron_expr,
'schedule_timezone': item.get('schedule_timezone'),
'wait_seconds': int(item.get('wait_seconds') or 0),
'dify_agent_id': item.get('dify_agent_id'),
'platform_api_path': item.get('platform_api_path'),
'notify_user_ids_json': item.get('notify_user_ids_json')
if isinstance(item.get('notify_user_ids_json'), list)
'schedule_timezone': migrated.get('schedule_timezone'),
'wait_seconds': int(migrated.get('wait_seconds') or 0),
'dify_agent_id': migrated.get('dify_agent_id'),
'platform_api_path': contract['platform_api_path'],
'data_source_type': contract['data_source_type'],
'notify_user_ids_json': migrated.get('notify_user_ids_json')
if isinstance(migrated.get('notify_user_ids_json'), list)
else [],
'notify_enabled': bool(item.get('notify_enabled', True)),
'enabled': bool(item.get('enabled', True)),
'data_source_type': str(item.get('data_source_type') or 'database'),
'kb_sync_enabled': bool(item.get('kb_sync_enabled', False)),
'kb_group_id': item.get('kb_group_id'),
'notify_enabled': bool(migrated.get('notify_enabled', True)),
'enabled': bool(migrated.get('enabled', True)),
'kb_sync_enabled': bool(migrated.get('kb_sync_enabled', False)),
'kb_group_id': migrated.get('kb_group_id'),
}
cfg = item.get('config') if isinstance(item.get('config'), dict) else None
if existing:
update_task(existing, payload=task_payload, actor_id=actor_id)
existing.data_source_type = task_payload['data_source_type']
update_task(existing, payload=task_payload, actor_id=actor_id, commit=False)
if cfg:
upsert_schedule_task_config(existing.id, cfg)
upsert_schedule_task_config(existing.id, cfg, commit=False)
else:
task = create_task(
name=name,
schedule_type=task_payload['schedule_type'],
schedule_type=contract['schedule_type'],
owner_user_id=owner_user_id,
cron_expr=cron_expr,
schedule_timezone=task_payload['schedule_timezone'],
wait_seconds=task_payload['wait_seconds'],
dify_agent_id=task_payload['dify_agent_id'],
platform_api_path=task_payload['platform_api_path'],
platform_api_path=contract['platform_api_path'],
data_source_type=contract['data_source_type'],
notify_user_ids_json=task_payload['notify_user_ids_json'],
notify_enabled=task_payload['notify_enabled'],
enabled=task_payload['enabled'],
kb_sync_enabled=task_payload['kb_sync_enabled'],
kb_group_id=(
int(task_payload['kb_group_id'])
if task_payload.get('kb_group_id') not in (None, '', 0, '0')
else None
),
actor_id=actor_id,
commit=False,
)
task.data_source_type = task_payload['data_source_type']
task.kb_sync_enabled = task_payload['kb_sync_enabled']
task.kb_group_id = (
int(task_payload['kb_group_id'])
if task_payload.get('kb_group_id') not in (None, '', 0, '0')
else None
)
db.session.commit()
if cfg:
upsert_schedule_task_config(task.id, cfg)
upsert_schedule_task_config(task.id, cfg, commit=False)
db.session.commit()
imported += 1
except Exception as exc:
db.session.rollback()
errors.append(str(exc))
skipped += 1
db.session.commit()
return {'ok': True, 'imported': imported, 'skipped': skipped, 'errors': errors[:20]}
@@ -0,0 +1,119 @@
"""
backend/app/services/schedule/job_registry.py
用途:平台内置排程 Job Registry(key → handler)。
依赖:shipping_inventory_rpa_job、faq_hot_aggregate_job、fixed_assets_snapshot_job。
逻辑:internal_jobs API 与 platform_job 排程通过 platform_api_path 引用已注册 key。
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Callable
from app.models import ScheduleRun, ScheduleTask
from app.services.schedule.schedule_contract import normalize_job_key
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
PlatformJobHandler = Callable[[ScheduleTask, ScheduleRun], ScheduleExecuteResult]
_REGISTRY: dict[str, "PlatformJobDefinition"] = {}
@dataclass(frozen=True)
class PlatformJobDefinition:
"""平台内置 Job 元数据与执行 handler。"""
key: str
label: str
handler: PlatformJobHandler
description: str = ""
# 前端 i18n key(如 admin.schedule.form.platformJobShippingInventory);
# 前端下拉优先 $t(label_key),label 仅作 fallback/debug。
label_key: str = ""
def register_platform_job(definition: PlatformJobDefinition) -> None:
"""注册平台 Job;重复 key 覆盖(便于热重载测试)。"""
key = normalize_job_key(definition.key)
if not key:
raise ValueError("platform job key is required")
_REGISTRY[key] = PlatformJobDefinition(
key=key,
label=definition.label,
handler=definition.handler,
description=definition.description,
label_key=definition.label_key,
)
def get_platform_job(key: str) -> PlatformJobDefinition | None:
"""按 key 查询已注册 Job。"""
return _REGISTRY.get(normalize_job_key(key))
def list_platform_jobs() -> list[PlatformJobDefinition]:
"""返回全部已注册 Job(按 key 排序)。"""
return [_REGISTRY[k] for k in sorted(_REGISTRY)]
def is_registered_platform_job(key: str) -> bool:
"""判断 key 是否已注册。"""
return normalize_job_key(key) in _REGISTRY
def run_platform_job(
key: str,
task: ScheduleTask,
run: ScheduleRun,
payload: dict[str, Any] | None = None,
) -> ScheduleExecuteResult:
"""
执行已注册平台 Job。
Args:
key: platform_api_path job key
task: 排程任务
run: 执行批次
payload: internal API 请求体(部分 handler 可读 agent_id 等)
Returns:
ScheduleExecuteResult 七元组
Raises:
KeyError: 未注册 key
"""
definition = get_platform_job(key)
if not definition:
raise KeyError(f"Unknown platform job: {key}")
_ = payload # 预留扩展;FAQ 等从 task 读取 dify_agent_id
return definition.handler(task, run)
def _register_builtin_platform_jobs() -> None:
"""模块加载时注册内置平台 Job。"""
from app.services.schedule.faq_hot_aggregate_job import run_faq_hot_aggregate_schedule
from app.services.schedule.fixed_assets_snapshot_job import run_fixed_assets_snapshot_schedule
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
register_platform_job(PlatformJobDefinition(
key="shipping-inventory-rpa",
label="货代库存 RPA",
label_key="admin.schedule.form.platformJobShippingInventory",
handler=run_shipping_inventory_rpa_schedule,
description="批量写入库存 RPA export trigger,由 freight_rpa_worker 异步导出。",
))
register_platform_job(PlatformJobDefinition(
key="faq-aggregate-hot",
label="FAQ 热点聚合",
label_key="admin.schedule.form.platformJobFaqHotAggregate",
handler=run_faq_hot_aggregate_schedule,
description="ChatLog 热点发现,结果写入 faq_hot_candidates。",
))
register_platform_job(PlatformJobDefinition(
key="fixed-assets-snapshot",
label="固资快照",
label_key="admin.schedule.form.platformJobFixedAssetsSnapshot",
handler=run_fixed_assets_snapshot_schedule,
description="同步 PLM 固资快照至本地 manifest。",
))
_register_builtin_platform_jobs()
@@ -0,0 +1,202 @@
"""
backend/app/services/schedule/schedule_contract.py
用途:排程三层语义校验与旧数据迁移(schedule_type / data_source_type / platform_api_path)。
依赖:job_registry.get_platform_job。
逻辑:scheduler_service、api/schedule/tasks、import_service 创建/更新/导入前调用。
"""
from __future__ import annotations
from typing import Any
SCHEDULE_TYPE_DATA_PIPELINE = "data_pipeline"
SCHEDULE_TYPE_PLATFORM_JOB = "platform_job"
DATA_SOURCE_DATABASE = "database"
DATA_SOURCE_EXTERNAL_API = "external_api"
VALID_SCHEDULE_TYPES = frozenset({SCHEDULE_TYPE_DATA_PIPELINE, SCHEDULE_TYPE_PLATFORM_JOB})
VALID_DATA_PIPELINE_SOURCES = frozenset({DATA_SOURCE_DATABASE, DATA_SOURCE_EXTERNAL_API})
LEGACY_SCHEDULE_TYPES = frozenset({"platform_app", "dify_app"})
LEGACY_DATA_SOURCE_TO_PLATFORM_JOB = {
"shipping_inventory_rpa": "shipping-inventory-rpa",
"faq_hot_aggregate": "faq-aggregate-hot",
}
# 允许写 ScheduleTaskConfig 的 platform_job(其余平台任务仅存 cron + job key,禁配置)
PLATFORM_JOBS_ALLOWING_CONFIG = frozenset({"shipping-inventory-rpa"})
def platform_job_allows_config(key: str | None) -> bool:
"""判断该 platform_job 是否允许写 ScheduleTaskConfig。"""
return normalize_job_key(key) in PLATFORM_JOBS_ALLOWING_CONFIG
def assert_schedule_config_writable(
*,
schedule_type: str,
platform_api_path: str | None,
config: dict[str, Any] | None,
) -> None:
"""
携带 config 时校验是否允许写入 ScheduleTaskConfig。
Raises:
ValueError: 非白名单 platform_job 携带 config
"""
if not config or not isinstance(config, dict):
return
st = str(schedule_type or "").strip().lower()
if st == SCHEDULE_TYPE_DATA_PIPELINE:
return
if st == SCHEDULE_TYPE_PLATFORM_JOB and platform_job_allows_config(platform_api_path):
return
key = normalize_job_key(platform_api_path) or "unknown"
raise ValueError(f"platform_job '{key}' does not accept ScheduleTaskConfig")
def normalize_job_key(value: str | None) -> str:
"""
归一化 platform job key。
核心逻辑:小写、去 query/hash、去首尾斜杠;历史数据可能存完整路径或 URL
(如 /api/internal/jobs/faq-aggregate-hot、http://host/api/internal/jobs/foo),
统一取最后一段;下划线转连字符。
"""
raw = str(value or "").strip().lower()
raw = raw.split("?", 1)[0].split("#", 1)[0]
raw = raw.strip("/")
if "/" in raw:
raw = raw.rsplit("/", 1)[-1]
return raw.replace("_", "-")
def _is_registered_platform_job(key: str) -> bool:
"""查询 job_registry 判断 key 是否已注册(懒加载避免循环 import)。"""
if not key:
return False
from app.services.schedule.job_registry import get_platform_job
return get_platform_job(key) is not None
def normalize_schedule_type(value: str | None, *, default: str = SCHEDULE_TYPE_DATA_PIPELINE) -> str:
"""
宽松解析 schedule_type;未知值回退 default。
仅用于 legacy 迁移兜底;创建/更新校验请用 validate_schedule_fields(对未知值报错)。
"""
raw = str(value or "").strip().lower()
if raw in VALID_SCHEDULE_TYPES:
return raw
return default
def normalize_data_source_type(value: str | None) -> str | None:
"""解析 data_pipeline 数据源;空值返回 None。"""
if value is None:
return None
raw = str(value).strip().lower()
if not raw:
return None
if raw in VALID_DATA_PIPELINE_SOURCES:
return raw
raise ValueError(f"Invalid data_source_type: {value!r}")
def migrate_legacy_schedule_payload(payload: dict[str, Any]) -> dict[str, Any]:
"""
导入/导出 JSON 旧语义自动迁移。
核心逻辑:旧 data_source_type 平台任务别名 → platform_job + job key;旧 platform_app → data_pipeline。
"""
out = dict(payload)
dst = str(out.get("data_source_type") or "").strip().lower()
st = str(out.get("schedule_type") or "").strip().lower()
path = normalize_job_key(str(out.get("platform_api_path") or ""))
if dst in LEGACY_DATA_SOURCE_TO_PLATFORM_JOB:
out["schedule_type"] = SCHEDULE_TYPE_PLATFORM_JOB
out["platform_api_path"] = LEGACY_DATA_SOURCE_TO_PLATFORM_JOB[dst]
out["data_source_type"] = None
return out
if _is_registered_platform_job(path):
out["schedule_type"] = SCHEDULE_TYPE_PLATFORM_JOB
out["platform_api_path"] = path
out["data_source_type"] = None
return out
if st in LEGACY_SCHEDULE_TYPES and dst in VALID_DATA_PIPELINE_SOURCES:
out["schedule_type"] = SCHEDULE_TYPE_DATA_PIPELINE
out["platform_api_path"] = None
return out
if st in LEGACY_SCHEDULE_TYPES and not dst:
if path:
out["schedule_type"] = SCHEDULE_TYPE_PLATFORM_JOB
out["platform_api_path"] = path
out["data_source_type"] = None
else:
out["schedule_type"] = SCHEDULE_TYPE_DATA_PIPELINE
out["data_source_type"] = DATA_SOURCE_DATABASE
out["platform_api_path"] = None
return out
def validate_schedule_fields(
*,
schedule_type: str,
data_source_type: str | None,
platform_api_path: str | None,
) -> tuple[str, str | None, str | None]:
"""
校验并归一化三层字段组合。
Args:
schedule_type: data_pipeline | platform_job
data_source_type: 仅 data_pipeline 必填
platform_api_path: 仅 platform_job 必填且须已注册
Returns:
(schedule_type, data_source_type, platform_api_path)
Raises:
ValueError: schedule_type 未知、字段组合非法或未注册 job key
"""
st = str(schedule_type or "").strip().lower()
if st not in VALID_SCHEDULE_TYPES:
raise ValueError(
f"Invalid schedule_type: {schedule_type!r} (expected data_pipeline | platform_job)"
)
path = normalize_job_key(platform_api_path) or None
if st == SCHEDULE_TYPE_DATA_PIPELINE:
dst = normalize_data_source_type(data_source_type)
if not dst:
raise ValueError("data_source_type is required for data_pipeline (database | external_api)")
return st, dst, None
if st == SCHEDULE_TYPE_PLATFORM_JOB:
if not path:
raise ValueError("platform_api_path is required for platform_job")
from app.services.schedule.job_registry import get_platform_job
if not get_platform_job(path):
raise ValueError(f"Unknown platform job key: {path}")
return st, None, path
raise ValueError(f"Unsupported schedule_type: {schedule_type}")
def apply_schedule_contract_to_payload(payload: dict[str, Any]) -> dict[str, Any]:
"""迁移旧字段后校验,返回可写入 ORM 的字段子集。"""
migrated = migrate_legacy_schedule_payload(payload)
st, dst, path = validate_schedule_fields(
schedule_type=str(migrated.get("schedule_type") or SCHEDULE_TYPE_DATA_PIPELINE),
data_source_type=migrated.get("data_source_type"),
platform_api_path=migrated.get("platform_api_path"),
)
return {
"schedule_type": st,
"data_source_type": dst,
"platform_api_path": path,
}
@@ -10,11 +10,11 @@ from flask import current_app
from app import db
from app.models import ScheduleRun, ScheduleTask, User
from app.services.schedule import normalize_platform_api_path, resolve_schedule_executor, resolve_schedule_header
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
from app.services.schedule.excel_service import export_schedule_result_excel
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
from app.services.schedule.cron_util import normalize_cron_expr
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
from app.services.schedule.excel_service import export_schedule_result_excel
from app.services.schedule import resolve_schedule_executor, resolve_schedule_header
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
from app.services.schedule.timezone_util import compute_next_run_at, normalize_schedule_timezone, utc_now_naive
_worker_started = False
@@ -165,22 +165,36 @@ def create_task(
wait_seconds: int,
dify_agent_id: int | None,
platform_api_path: str | None,
data_source_type: str | None,
notify_user_ids_json: list[int] | None,
notify_enabled: bool,
enabled: bool,
kb_sync_enabled: bool = False,
kb_group_id: int | None = None,
actor_id: int | None,
commit: bool = True,
) -> ScheduleTask:
from app.services.schedule.schedule_contract import apply_schedule_contract_to_payload
cron_expr = normalize_cron_expr(cron_expr)
contract = apply_schedule_contract_to_payload({
'schedule_type': schedule_type,
'data_source_type': data_source_type,
'platform_api_path': platform_api_path,
})
task = ScheduleTask(
schedule_no=_generate_schedule_no(),
name=name,
schedule_type="platform_app",
schedule_type=contract['schedule_type'],
owner_user_id=owner_user_id,
cron_expr=cron_expr,
schedule_timezone=normalize_schedule_timezone(schedule_timezone),
wait_seconds=max(0, int(wait_seconds or 0)),
dify_agent_id=dify_agent_id,
platform_api_path=normalize_platform_api_path(platform_api_path) or None,
platform_api_path=contract['platform_api_path'],
data_source_type=contract['data_source_type'],
kb_sync_enabled=bool(kb_sync_enabled),
kb_group_id=kb_group_id,
notify_user_ids_json=notify_user_ids_json or [],
notify_enabled=bool(notify_enabled),
enabled=bool(enabled),
@@ -192,11 +206,22 @@ def create_task(
if task.next_run_at is None:
task.enabled = False
db.session.add(task)
db.session.commit()
if commit:
db.session.commit()
else:
db.session.flush()
return task
def update_task(task: ScheduleTask, *, payload: dict[str, Any], actor_id: int | None) -> ScheduleTask:
def update_task(
task: ScheduleTask,
*,
payload: dict[str, Any],
actor_id: int | None,
commit: bool = True,
) -> ScheduleTask:
from app.services.schedule.schedule_contract import apply_schedule_contract_to_payload
for key in [
"name",
"owner_user_id",
@@ -215,8 +240,6 @@ def update_task(task: ScheduleTask, *, payload: dict[str, Any], actor_id: int |
else:
value = payload[key]
setattr(task, key, value)
if "platform_api_path" in payload:
task.platform_api_path = normalize_platform_api_path(payload.get("platform_api_path")) or None
if "notify_user_ids_json" in payload and isinstance(payload.get("notify_user_ids_json"), list):
task.notify_user_ids_json = payload.get("notify_user_ids_json")
if "kb_sync_enabled" in payload:
@@ -225,12 +248,15 @@ def update_task(task: ScheduleTask, *, payload: dict[str, Any], actor_id: int |
raw_group_id = payload.get("kb_group_id")
task.kb_group_id = int(raw_group_id) if raw_group_id not in (None, "", 0, "0") else None
if not normalize_platform_api_path(task.platform_api_path):
dst = str(getattr(task, "data_source_type", None) or "database")
if dst != "faq_hot_aggregate":
raise ValueError("platform_api_path is required for platform_app")
task.platform_api_path = "faq-aggregate-hot"
task.schedule_type = "platform_app"
if any(k in payload for k in ("schedule_type", "data_source_type", "platform_api_path")):
contract = apply_schedule_contract_to_payload({
"schedule_type": payload.get("schedule_type", task.schedule_type),
"data_source_type": payload.get("data_source_type", task.data_source_type),
"platform_api_path": payload.get("platform_api_path", task.platform_api_path),
})
task.schedule_type = contract["schedule_type"]
task.data_source_type = contract["data_source_type"]
task.platform_api_path = contract["platform_api_path"]
if task.enabled and task.cron_expr:
task.schedule_timezone = normalize_schedule_timezone(getattr(task, "schedule_timezone", None))
@@ -239,7 +265,8 @@ def update_task(task: ScheduleTask, *, payload: dict[str, Any], actor_id: int |
task.next_run_at = None
task.updated_by = actor_id
db.session.commit()
if commit:
db.session.commit()
return task
@@ -3,7 +3,7 @@ backend/app/services/schedule/shipping_inventory_rpa_job.py
用途:排程触发货代库存 RPA 批量导出(各 Warehouse 一次登录多导出)。
依赖:inventory_sources、rpa.write_inventory_export_batch_trigger、ScheduleTask/ScheduleRun。
逻辑:data_source_type=shipping_inventory_rpa 时由 resolve_schedule_executor 调用。
逻辑:platform_api_path=shipping-inventory-rpa 时由 job_registry 调用。
"""
from __future__ import annotations
+25 -8
View File
@@ -159,16 +159,27 @@ def _config_from_model(cfg_model: Any) -> ScheduleSqlConfig:
def get_schedule_sql_config(name: str) -> ScheduleSqlConfig | None:
"""
按 task id 或 platform job key 精确查找 ScheduleSqlConfig。
核心逻辑:数字 name 走主键;否则归一化后与 platform_api_path 精确匹配(禁止模糊 ilike)。
Args:
name: 数字 task id,或 platform_api_path job key。
Returns:
找到则返回配置,否则 None。
"""
from app import db
from app.models import ScheduleTask, ScheduleTaskConfig
from app.services.schedule.schedule_contract import normalize_job_key
key = name.strip().lower()
raw = name.strip()
job_key = normalize_job_key(raw)
task = None
if key.isdigit():
task = db.session.get(ScheduleTask, int(key))
if not task:
if raw.isdigit():
task = db.session.get(ScheduleTask, int(raw))
if not task and job_key:
task = ScheduleTask.query.filter(
ScheduleTask.platform_api_path.ilike(f"%{key}%")
ScheduleTask.platform_api_path == job_key,
ScheduleTask.schedule_type == 'platform_job',
).first()
if not task:
return None
@@ -201,7 +212,12 @@ def get_all_schedule_sql_configs() -> dict[str, ScheduleSqlConfig]:
return results
def upsert_schedule_task_config(task_id: int, data: dict[str, Any]) -> ScheduleSqlConfig:
def upsert_schedule_task_config(
task_id: int,
data: dict[str, Any],
*,
commit: bool = True,
) -> ScheduleSqlConfig:
from app import db
from app.models import ScheduleTask, ScheduleTaskConfig
@@ -238,6 +254,7 @@ def upsert_schedule_task_config(task_id: int, data: dict[str, Any]) -> ScheduleS
elif k == "dify_system_prompt":
setattr(cfg_model, k, str(v) if v is not None else None)
db.session.commit()
db.session.refresh(cfg_model)
if commit:
db.session.commit()
db.session.refresh(cfg_model)
return _config_from_model(cfg_model)
@@ -0,0 +1,135 @@
"""schedule_type platform_job split
Revision ID: b9c0d1e2f3a4
Revises: a8b9c0d1e2f3
Create Date: 2026-07-08
用途:激活 schedule_type 执行模式;data_source_type 仅 data_pipeline;platform_job 用 platform_api_path。
"""
from alembic import op
import sqlalchemy as sa
revision = 'b9c0d1e2f3a4'
down_revision = 'a8b9c0d1e2f3'
branch_labels = None
depends_on = None
def upgrade():
with op.batch_alter_table('schedule_tasks', schema=None) as batch_op:
batch_op.alter_column(
'data_source_type',
existing_type=sa.String(length=32),
nullable=True,
server_default=None,
)
batch_op.alter_column(
'schedule_type',
existing_type=sa.String(length=32),
server_default='data_pipeline',
)
op.execute("""
UPDATE schedule_tasks
SET schedule_type = 'platform_job',
platform_api_path = 'shipping-inventory-rpa',
data_source_type = NULL
WHERE data_source_type = 'shipping_inventory_rpa'
""")
op.execute("""
UPDATE schedule_tasks
SET schedule_type = 'platform_job',
platform_api_path = 'faq-aggregate-hot',
data_source_type = NULL
WHERE data_source_type = 'faq_hot_aggregate'
""")
op.execute("""
UPDATE schedule_tasks
SET schedule_type = 'platform_job',
data_source_type = NULL,
platform_api_path = LTRIM(RTRIM(REPLACE(REPLACE(platform_api_path, '/', ''), '\\', '')))
WHERE LTRIM(RTRIM(REPLACE(REPLACE(platform_api_path, '/', ''), '\\', ''))) IN (
'faq-aggregate-hot', 'fixed-assets-snapshot', 'shipping-inventory-rpa'
)
AND schedule_type IN ('platform_app', 'dify_app')
""")
# 兜底:历史 platform_api_path 可能存完整路径/URL(如 /api/internal/jobs/foo),
# 精确匹配失败时按包含关系归一到对应 job key。
op.execute("""
UPDATE schedule_tasks
SET schedule_type = 'platform_job',
platform_api_path = 'faq-aggregate-hot',
data_source_type = NULL
WHERE schedule_type IN ('platform_app', 'dify_app')
AND REPLACE(LOWER(platform_api_path), '_', '-') LIKE '%faq-aggregate-hot%'
""")
op.execute("""
UPDATE schedule_tasks
SET schedule_type = 'platform_job',
platform_api_path = 'shipping-inventory-rpa',
data_source_type = NULL
WHERE schedule_type IN ('platform_app', 'dify_app')
AND REPLACE(LOWER(platform_api_path), '_', '-') LIKE '%shipping-inventory-rpa%'
""")
op.execute("""
UPDATE schedule_tasks
SET schedule_type = 'platform_job',
platform_api_path = 'fixed-assets-snapshot',
data_source_type = NULL
WHERE schedule_type IN ('platform_app', 'dify_app')
AND REPLACE(LOWER(platform_api_path), '_', '-') LIKE '%fixed-assets-snapshot%'
""")
op.execute("""
UPDATE schedule_tasks
SET schedule_type = 'data_pipeline',
platform_api_path = NULL
WHERE schedule_type IN ('platform_app', 'dify_app')
AND data_source_type IN ('database', 'external_api')
""")
op.execute("""
UPDATE schedule_tasks
SET platform_api_path = TRIM(BOTH '/' FROM platform_api_path)
WHERE platform_api_path IS NOT NULL
AND platform_api_path LIKE '/%'
""")
def downgrade():
op.execute("""
UPDATE schedule_tasks
SET schedule_type = 'platform_app',
data_source_type = 'shipping_inventory_rpa',
platform_api_path = 'shipping-inventory-rpa'
WHERE schedule_type = 'platform_job'
AND platform_api_path = 'shipping-inventory-rpa'
""")
op.execute("""
UPDATE schedule_tasks
SET schedule_type = 'platform_app',
data_source_type = 'faq_hot_aggregate',
platform_api_path = 'faq-aggregate-hot'
WHERE schedule_type = 'platform_job'
AND platform_api_path = 'faq-aggregate-hot'
""")
# fixed-assets-snapshot 等其余 platform_job 统一回落旧语义(platform_app + database),
# 避免 data_source_type 改回 NOT NULL 后残留 NULL 行导致约束失败。
op.execute("""
UPDATE schedule_tasks
SET schedule_type = 'platform_app',
data_source_type = 'database'
WHERE schedule_type = 'platform_job'
AND (data_source_type IS NULL OR data_source_type = '')
""")
with op.batch_alter_table('schedule_tasks', schema=None) as batch_op:
batch_op.alter_column(
'data_source_type',
existing_type=sa.String(length=32),
nullable=False,
server_default='database',
)
batch_op.alter_column(
'schedule_type',
existing_type=sa.String(length=32),
server_default='platform_app',
)
+1 -1
View File
@@ -27,7 +27,7 @@ def test_agent_lifecycle(client, admin_headers):
assert len(agents) == 1
assert agents[0]['name'] == "Test Agent"
assert agents[0]['description'] == "Initial Description"
assert 'dify_api_key' not in agents[0]
assert agents[0]['dify_api_key'] == "key-123"
assert agents[0]['dify_api_key_masked']
# 3. Update Agent
+1 -1
View File
@@ -89,7 +89,7 @@ def test_agent_crud(client):
agents = parse_api_data(res.get_json())
assert len(agents) == 1
assert agents[0]['name'] == 'Test Agent'
assert 'dify_api_key' not in agents[0]
assert agents[0]['dify_api_key'] == 'sk-test-key'
# Update
res = client.put(f'/api/admin/agents/{agent_id}', json={
@@ -133,6 +133,19 @@ def test_validate_omitted_handler_config_preserves_existing(app):
assert normalized['handler_config']['intent_routes'] == ['text2sql']
def test_validate_shipping_notice_clears_bound_schedule_task_id():
normalized = validate_agent_payload({
'name': 'Shipping Bot',
'agent_code': 'shipping_notice',
'runtime_provider': 'hybrid',
'conversation_mode': 'task_chat',
'dify_app_id': 'app-ship',
'bound_schedule_task_id': 42,
'capabilities': {'task_progress': True},
})
assert normalized['bound_schedule_task_id'] is None
def test_strip_migrated_extra_registry_keys_preserves_training(app):
with app.app_context():
agent = Agent(
@@ -23,12 +23,26 @@ def test_build_agent_registry_schema_includes_platform_enums():
def test_build_agent_registry_schema_agent_types_include_validation_rules():
"""agent_types 每条应含 required_fields 与 forced_capabilities。"""
"""agent_types 每条应含 required_fields、default_capabilities、forced_capabilities 与 progress_contract。"""
schema = build_agent_registry_schema()
by_code = {item['agent_code']: item for item in schema['agent_types']}
assert by_code['file_check']['required_fields'] == ['bound_schedule_task_id']
assert by_code['file_check']['forced_capabilities']['task_progress'] is True
assert by_code['generic']['required_fields'] == []
file_check_contract = by_code['file_check']['progress_contract']
assert file_check_contract['data_source']['type'] == 'schedule_run'
assert file_check_contract['binding']['requires_schedule_task'] is True
shipping = by_code['shipping_notice']
assert shipping['default_capabilities']['file_upload'] is True
assert shipping['default_capabilities']['task_progress'] is True
assert shipping['forced_capabilities'] == {
'file_upload': True,
'task_progress': True,
'human_confirm': True,
}
assert shipping['progress_contract']['presentation']['layout'] == 'workspace'
assert shipping['progress_contract']['binding']['requires_schedule_task'] is False
assert 'erp_kb' not in shipping['forced_capabilities']
def test_build_agent_registry_schema_handler_config_schemas():
@@ -12,7 +12,9 @@ from app.core.errors import ValidationError
from app.services.agent_registry.catalog_loader import (
clear_catalog_cache,
coerce_manifest_boolean,
get_agent_type_default_capabilities,
get_default_capabilities,
normalize_progress_contract,
)
@@ -46,6 +48,53 @@ def test_get_default_capabilities_uses_manifest_boolean_coercion(monkeypatch):
assert caps['task_progress'] is False
def test_get_agent_type_default_capabilities_merges_platform_and_type_defaults():
"""agent_types.default_capabilities 应覆盖 platform 同名字段。"""
clear_catalog_cache()
caps = get_agent_type_default_capabilities('shipping_notice')
assert caps['streaming'] is True
assert caps['file_upload'] is True
assert caps['task_progress'] is True
assert caps['erp_kb'] is False
def test_normalize_progress_contract_file_check_shape():
contract = normalize_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'},
})
assert contract is not None
assert contract['data_source']['type'] == 'schedule_run'
assert contract['binding']['requires_schedule_task'] is True
def test_normalize_progress_contract_sse_requires_event():
"""transport=sse 但缺 event 时应 fail-fast,避免运行时静默不发进度。"""
with pytest.raises(ValidationError, match='update.event'):
normalize_progress_contract({
'enabled': True,
'data_source': {'type': 'domain_state', 'domain': 'shipping_notice'},
'update': {'transport': 'sse'},
'binding': {'type': 'conversation_context'},
'presentation': {'layout': 'workspace', 'visualization': 'stepper'},
})
def test_normalize_progress_contract_schedule_run_requires_schedule_task_binding():
"""schedule_run 数据源必须声明 binding.requires_schedule_task=true。"""
with pytest.raises(ValidationError, match='requires_schedule_task'):
normalize_progress_contract({
'enabled': True,
'data_source': {'type': 'schedule_run'},
'update': {'transport': 'polling'},
'binding': {'type': 'chat_log_run', 'requires_schedule_task': False},
'presentation': {'layout': 'card', 'visualization': 'counter'},
})
def test_get_tool_run_progress_defaults_coerces_boolean_string(monkeypatch):
from app.services.agent_registry import catalog_loader
from app.services.agent_registry.catalog_loader import get_tool_run_progress_defaults
@@ -16,6 +16,7 @@ from app.services.agent_registry.catalog import AGENT_TYPE_CATALOG, clear_catalo
from app.services.agent_registry.catalog_loader import list_agent_type_codes
from app.services.agent_registry.catalog_validation import (
apply_catalog_capabilities,
catalog_progress_requires_schedule_task,
normalize_handler_config,
validate_required_fields,
)
@@ -110,6 +111,11 @@ def test_normalize_handler_config_rejects_invalid_boolean_string():
normalize_handler_config('file_check', {'lock_input_when_running': 'maybe'})
def test_catalog_progress_requires_schedule_task_follows_contract():
assert catalog_progress_requires_schedule_task('file_check') is True
assert catalog_progress_requires_schedule_task('shipping_notice') is False
def test_normalize_handler_config_empty_schema_rejects_any_field():
"""空 handler_config_schema 表示不允许任何 handler_config 字段。"""
with pytest.raises(ValidationError, match='不允许配置 handler_config'):
+48 -1
View File
@@ -13,6 +13,8 @@ from app.services.agent_registry.resolver import (
agent_declares_task_progress,
agent_has_erp_kb,
agent_has_intent_route,
agent_has_progress,
agent_progress_requires_schedule_task,
is_file_check_runtime_ready,
normalize_capabilities,
resolve_agent_code,
@@ -20,6 +22,7 @@ from app.services.agent_registry.resolver import (
resolve_conversation_mode,
resolve_handler_key,
resolve_intent_routes,
resolve_progress_contract,
resolve_runtime_provider,
)
from app.services.file_check_tools.task_resolver import resolve_schedule_task_id_from_agent
@@ -184,7 +187,7 @@ def test_agent_declares_task_progress_reads_registry_columns():
def test_is_file_check_runtime_ready_requires_bound_task_id():
"""完整 file_check 入口须 capabilities.task_progress 与 bound_schedule_task_id。"""
"""完整 file_check 入口须 progress_contract 要求排程且 bound_schedule_task_id 已配置。"""
ready = _agent(
agent_code='file_check',
capabilities={'task_progress': True},
@@ -196,3 +199,47 @@ def test_is_file_check_runtime_ready_requires_bound_task_id():
)
assert is_file_check_runtime_ready(ready) is True
assert is_file_check_runtime_ready(misconfigured) is False
def test_resolve_progress_contract_reads_catalog_for_file_check():
agent = _agent(agent_code='file_check', capabilities={'task_progress': True})
contract = resolve_progress_contract(agent)
assert contract is not None
assert contract['data_source']['type'] == 'schedule_run'
assert contract['presentation']['visualization'] == 'counter'
def test_resolve_progress_contract_reads_catalog_for_shipping_notice():
agent = _agent(agent_code='shipping_notice', capabilities={'task_progress': True})
contract = resolve_progress_contract(agent)
assert contract is not None
assert contract['data_source']['type'] == 'domain_state'
assert contract['update']['event'] == 'shipping_ui_state'
def test_agent_has_progress_merges_catalog_forced_capabilities():
"""capabilities 列缺失时,Catalog forced_capabilities.task_progress 也应放行 contract。"""
assert agent_has_progress(_agent(agent_code='file_check')) is True
assert agent_has_progress(_agent(agent_code='file_check', capabilities={'task_progress': True})) is True
assert agent_has_progress(_agent(agent_code='generic')) is False
def test_resolve_progress_contract_shipping_notice_without_capabilities_column():
"""存量 shipping_notice 行 capabilities.task_progress 缺失/false 时仍应返回 contract。"""
missing = _agent(agent_code='shipping_notice', capabilities=None)
stale_false = _agent(agent_code='shipping_notice', capabilities={'task_progress': False})
for agent in (missing, stale_false):
contract = resolve_progress_contract(agent)
assert contract is not None
assert contract['update']['event'] == 'shipping_ui_state'
def test_agent_progress_requires_schedule_task_only_for_file_check():
assert agent_progress_requires_schedule_task(_agent(
agent_code='file_check',
capabilities={'task_progress': True},
)) is True
assert agent_progress_requires_schedule_task(_agent(
agent_code='shipping_notice',
capabilities={'task_progress': True},
)) is False
@@ -6,7 +6,12 @@ tests/test_agent_registry_serialization.py
from types import SimpleNamespace
from app.services.agent_registry.serialization import mask_dify_api_key, serialize_agent_for_admin
from app.services.agent_registry.serialization import (
build_tool_run_progress_view,
mask_dify_api_key,
serialize_agent_for_admin,
serialize_registry_fields,
)
def test_mask_dify_api_key():
@@ -15,7 +20,7 @@ def test_mask_dify_api_key():
assert mask_dify_api_key('sk-abcdefghijklmnop') == 'sk-a****mnop'
def test_serialize_agent_for_admin_does_not_expose_plain_api_key():
def test_serialize_agent_for_admin_includes_api_key_for_admin_edit():
agent = SimpleNamespace(
id=1,
name='Bot',
@@ -44,5 +49,38 @@ def test_serialize_agent_for_admin_does_not_expose_plain_api_key():
handler_config=None,
)
payload = serialize_agent_for_admin(agent)
assert 'dify_api_key' not in payload
assert payload['dify_api_key'] == agent.dify_api_key
assert payload['dify_api_key_masked'] == mask_dify_api_key(agent.dify_api_key)
def test_serialize_registry_fields_includes_progress_contract():
file_check = SimpleNamespace(
agent_code='file_check',
runtime_provider='dify',
conversation_mode='task_chat',
capabilities={'task_progress': True},
bound_schedule_task_id=42,
handler_config={'poll_interval_seconds': 2, 'lock_input_when_running': True},
dify_app_type='chatflow',
iframe_url=None,
category=None,
sub_category=None,
sort_order=0,
welcome_message=None,
suggested_questions_style='plain',
suggested_questions=[],
file_upload_policy=None,
)
payload = serialize_registry_fields(file_check)
assert payload['progress_contract']['data_source']['type'] == 'schedule_run'
assert payload['tool_run_progress']['schedule_task_id'] == 42
def test_build_tool_run_progress_view_skips_domain_state_contract():
shipping = SimpleNamespace(
agent_code='shipping_notice',
capabilities={'task_progress': True},
bound_schedule_task_id=99,
handler_config=None,
)
assert build_tool_run_progress_view(shipping) is None
+8 -6
View File
@@ -49,11 +49,12 @@ def _mk_check_task(owner_id: int, *, enabled=True):
task = ScheduleTask(
schedule_no='CHK-ROHS-001',
name='RoHS 自动检核',
schedule_type='platform_app',
schedule_type='data_pipeline',
data_source_type='database',
owner_user_id=owner_id,
cron_expr='0 * * * *',
wait_seconds=5,
platform_api_path='/1',
platform_api_path=None,
enabled=enabled,
)
db.session.add(task)
@@ -65,11 +66,12 @@ def _mk_other_check_task(owner_id: int):
task = ScheduleTask(
schedule_no='CHK-GENERAL-001',
name='通用检核',
schedule_type='platform_app',
schedule_type='data_pipeline',
data_source_type='database',
owner_user_id=owner_id,
cron_expr='0 * * * *',
wait_seconds=5,
platform_api_path='/general-check',
platform_api_path=None,
enabled=True,
)
db.session.add(task)
@@ -512,7 +514,7 @@ def test_file_check_tool_running_conflict_is_per_task(app, client, monkeypatch):
second_task = ScheduleTask(
schedule_no='CHK-ROHS-002',
name='RoHS 文件检核备用',
schedule_type='platform_app',
schedule_type='data_pipeline',
owner_user_id=admin.id,
cron_expr='0 * * * *',
wait_seconds=5,
@@ -609,7 +611,7 @@ def test_workspace_file_check_active_run_filters_by_task_id(app, client):
task_b = ScheduleTask(
schedule_no='CHK-ROHS-002',
name='RoHS 文件检核 B',
schedule_type='platform_app',
schedule_type='data_pipeline',
owner_user_id=admin.id,
cron_expr='0 * * * *',
wait_seconds=5,
@@ -0,0 +1,138 @@
"""internal_jobs API registry 集成测试。"""
import json
from app.models import ScheduleRun, ScheduleTask, User
def test_internal_job_shipping_inventory_rpa_writes_trigger(client, app, tmp_path):
"""POST /api/internal/jobs/shipping-inventory-rpa 应写入 batch trigger。"""
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
with app.app_context():
from app import db
user = User(username="internal_job_user", email="internal_job_user@example.com")
db.session.add(user)
db.session.flush()
task = ScheduleTask(
schedule_no="SCH-IJ-001",
name="货代库存每日导出",
schedule_type="platform_job",
platform_api_path="shipping-inventory-rpa",
data_source_type=None,
owner_user_id=user.id,
cron_expr="0 3 * * *",
enabled=True,
)
db.session.add(task)
db.session.flush()
run = ScheduleRun(
run_no="RUN20260708030000",
schedule_task_id=task.id,
status="running",
)
db.session.add(run)
db.session.commit()
run_no = run.run_no
task_id = task.id
resp = client.post(
"/api/internal/jobs/shipping-inventory-rpa",
data=json.dumps({"run_no": run_no, "schedule_task_id": task_id}),
content_type="application/json",
)
assert resp.status_code == 200
body = resp.get_json()
assert body["summary"]["success_count"] >= 1
assert list(trigger_dir.glob("inventory_export_batch_*.json"))
def test_internal_job_unknown_key_returns_404(client):
"""未注册 job key 应返回 404。"""
resp = client.post(
"/api/internal/jobs/not-registered-job",
data=json.dumps({}),
content_type="application/json",
)
assert resp.status_code == 404
def test_internal_job_rejects_mismatched_schedule_task_id(client, app):
"""schedule_task_id 与 URL job key 不匹配应 400。"""
with app.app_context():
from app import db
user = User(username="ij_mismatch_user", email="ij_mismatch_user@example.com")
db.session.add(user)
db.session.flush()
task = ScheduleTask(
schedule_no="SCH-IJ-MISMATCH",
name="固资快照",
schedule_type="platform_job",
platform_api_path="fixed-assets-snapshot",
data_source_type=None,
owner_user_id=user.id,
cron_expr="0 3 * * *",
enabled=True,
)
db.session.add(task)
db.session.commit()
task_id = task.id
resp = client.post(
"/api/internal/jobs/shipping-inventory-rpa",
data=json.dumps({"schedule_task_id": task_id}),
content_type="application/json",
)
assert resp.status_code == 400
def test_internal_job_rejects_foreign_run_no(client, app):
"""run_no 属于其他任务时应 400。"""
with app.app_context():
from app import db
user = User(username="ij_run_user", email="ij_run_user@example.com")
db.session.add(user)
db.session.flush()
task_a = ScheduleTask(
schedule_no="SCH-IJ-A",
name="shipping task",
schedule_type="platform_job",
platform_api_path="shipping-inventory-rpa",
data_source_type=None,
owner_user_id=user.id,
cron_expr="0 3 * * *",
enabled=True,
)
task_b = ScheduleTask(
schedule_no="SCH-IJ-B",
name="faq task",
schedule_type="platform_job",
platform_api_path="faq-aggregate-hot",
data_source_type=None,
owner_user_id=user.id,
cron_expr="0 4 * * *",
enabled=True,
)
db.session.add_all([task_a, task_b])
db.session.flush()
run = ScheduleRun(
run_no="RUN-FOREIGN-001",
schedule_task_id=task_b.id,
status="running",
)
db.session.add(run)
db.session.commit()
task_a_id = task_a.id
run_no = run.run_no
resp = client.post(
"/api/internal/jobs/shipping-inventory-rpa",
data=json.dumps({"schedule_task_id": task_a_id, "run_no": run_no}),
content_type="application/json",
)
assert resp.status_code == 400
+79 -10
View File
@@ -1,12 +1,30 @@
import pytest
from app import db
from app.core.auth.jwt import issue_local_access_token
from app.models import Agent, ScheduleRun, ScheduleTask, User
def _mk_admin():
admin = User(username='admin', email='admin@example.com', role='admin', status='active')
admin.set_password('x')
db.session.add(admin)
return admin
@pytest.fixture
def admin_jwt_headers(app):
"""创建 admin 用户并签发 Bearer JWT。"""
with app.app_context():
user = db.session.query(User).filter_by(username='admin').first()
if not user:
user = User(
username='admin',
email='admin@example.com',
role='admin',
status='active',
)
user.set_password('admin')
db.session.add(user)
db.session.commit()
token = issue_local_access_token(user)
return {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json',
}
def _mk_user(name: str, email: str):
@@ -16,9 +34,8 @@ def _mk_user(name: str, email: str):
return user
def test_schedule_crud_and_workspace_visibility(app, client, admin_headers):
def test_schedule_crud_and_workspace_visibility(app, client, admin_jwt_headers):
with app.app_context():
_mk_admin()
owner = _mk_user('owner_u', 'owner@example.com')
notify = _mk_user('notify_u', 'notify@example.com')
other = _mk_user('other_u', 'other@example.com')
@@ -31,9 +48,10 @@ def test_schedule_crud_and_workspace_visibility(app, client, admin_headers):
other_id = other.id
agent_id = agent.id
create_res = client.post('/api/admin/schedules', headers=admin_headers, json={
create_res = client.post('/api/admin/schedules', headers=admin_jwt_headers, json={
'name': 'rohs-schedule',
'schedule_type': 'dify_app',
'schedule_type': 'data_pipeline',
'data_source_type': 'database',
'owner_user_id': owner_id,
'cron_expr': '0 */30 * * *',
'wait_seconds': 5,
@@ -46,7 +64,7 @@ def test_schedule_crud_and_workspace_visibility(app, client, admin_headers):
task = create_res.get_json()
task_id = task['id']
list_res = client.get('/api/admin/schedules', headers=admin_headers)
list_res = client.get('/api/admin/schedules', headers=admin_jwt_headers)
assert list_res.status_code == 200
assert any(x['id'] == task_id for x in list_res.get_json())
@@ -85,3 +103,54 @@ def test_schedule_crud_and_workspace_visibility(app, client, admin_headers):
denied = client.get(f'/api/workspace/schedule-runs/{run_id}', headers=other_headers)
assert denied.status_code == 403
def test_post_schedule_defaults_data_source_type_to_database(app, client, admin_jwt_headers):
"""兼容旧客户端:data_pipeline 不传 data_source_type 时应默认 database 而非 400。"""
with app.app_context():
owner = _mk_user('legacy_owner_u', 'legacy_owner@example.com')
db.session.commit()
owner_id = owner.id
res = client.post('/api/admin/schedules', headers=admin_jwt_headers, json={
'name': 'legacy-minimal-schedule',
'owner_user_id': owner_id,
'cron_expr': '0 3 * * *',
})
assert res.status_code == 201
body = res.get_json()
assert body['schedule_type'] == 'data_pipeline'
assert body['data_source_type'] == 'database'
def test_post_and_patch_schedule_reject_non_object_config(app, client, admin_jwt_headers):
"""POST/PATCH config 传非 JSON 对象(数组/字符串)应 400,而非 500。"""
with app.app_context():
owner = _mk_user('cfg_type_owner_u', 'cfg_type_owner@example.com')
db.session.commit()
owner_id = owner.id
post_res = client.post('/api/admin/schedules', headers=admin_jwt_headers, json={
'name': 'bad-config-schedule',
'schedule_type': 'data_pipeline',
'data_source_type': 'database',
'owner_user_id': owner_id,
'cron_expr': '0 3 * * *',
'config': ['not-an-object'],
})
assert post_res.status_code == 400
create_res = client.post('/api/admin/schedules', headers=admin_jwt_headers, json={
'name': 'good-schedule',
'schedule_type': 'data_pipeline',
'data_source_type': 'database',
'owner_user_id': owner_id,
'cron_expr': '0 3 * * *',
})
assert create_res.status_code == 201
task_id = create_res.get_json()['id']
patch_res = client.patch(f'/api/admin/schedules/{task_id}', headers=admin_jwt_headers, json={
'config': 'not-an-object',
})
assert patch_res.status_code == 400
+289
View File
@@ -0,0 +1,289 @@
"""排程 Job Registry 与 executor 分发测试。"""
import pytest
from app import db
from app.core.auth.jwt import issue_local_access_token
from app.models import ScheduleTask, User
from app.services.schedule import _run_common_executor, _run_generic_check_job, resolve_schedule_executor
from app.services.schedule.job_registry import get_platform_job, list_platform_jobs, run_platform_job
from app.services.schedule.schedule_contract import migrate_legacy_schedule_payload, normalize_job_key
@pytest.fixture
def admin_jwt_headers(app):
"""创建 admin 用户并签发 Bearer JWT。"""
with app.app_context():
user = db.session.query(User).filter_by(username='admin').first()
if not user:
user = User(
username='admin',
email='admin@example.com',
role='admin',
status='active',
)
user.set_password('admin')
db.session.add(user)
db.session.commit()
token = issue_local_access_token(user)
return {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json',
}
def test_platform_jobs_registered():
"""内置 platform job 应已注册。"""
keys = {job.key for job in list_platform_jobs()}
assert "shipping-inventory-rpa" in keys
assert "faq-aggregate-hot" in keys
assert "fixed-assets-snapshot" in keys
assert get_platform_job("shipping-inventory-rpa") is not None
def test_unknown_platform_job_raises():
"""未注册 key 应无法 resolve。"""
assert get_platform_job("not-a-real-job") is None
def test_resolve_schedule_executor_dispatch():
"""schedule_type 决定 executor 分发。"""
pipeline_task = ScheduleTask(schedule_type="data_pipeline", data_source_type="database")
platform_task = ScheduleTask(schedule_type="platform_job", platform_api_path="faq-aggregate-hot")
assert resolve_schedule_executor(pipeline_task) is _run_generic_check_job
assert resolve_schedule_executor(platform_task) is _run_common_executor
with pytest.raises(RuntimeError, match="Unsupported schedule_type"):
resolve_schedule_executor(ScheduleTask(schedule_type="legacy_type"))
def test_normalize_job_key_extracts_last_segment_from_full_path():
"""历史数据存完整内部路径或 URL 时,应提取最后一段作为 job key。"""
assert normalize_job_key('/api/internal/jobs/faq-aggregate-hot') == 'faq-aggregate-hot'
assert normalize_job_key('http://hxops.local/api/internal/jobs/shipping-inventory-rpa') == 'shipping-inventory-rpa'
assert normalize_job_key('/api/internal/jobs/fixed_assets_snapshot?token=x') == 'fixed-assets-snapshot'
assert normalize_job_key('faq_aggregate_hot') == 'faq-aggregate-hot'
assert normalize_job_key(None) == ''
def test_normalize_platform_api_path_delegates_to_job_key():
"""执行层归一化应与契约层 normalize_job_key 一致;完整 URL 原样透传。"""
from app.services.schedule import normalize_platform_api_path
assert normalize_platform_api_path('/api/internal/jobs/faq-aggregate-hot') == 'faq-aggregate-hot'
assert normalize_platform_api_path('faq_aggregate_hot') == 'faq-aggregate-hot'
assert normalize_platform_api_path('http://external.host/hook') == 'http://external.host/hook'
assert normalize_platform_api_path(None) == ''
def test_migrate_legacy_full_path_platform_api_path():
"""旧 platform_app + 完整路径 platform_api_path 应迁移为 platform_job。"""
migrated = migrate_legacy_schedule_payload({
"schedule_type": "platform_app",
"platform_api_path": "/api/internal/jobs/fixed-assets-snapshot",
})
assert migrated["schedule_type"] == "platform_job"
assert migrated["platform_api_path"] == "fixed-assets-snapshot"
assert migrated["data_source_type"] is None
def test_migrate_legacy_shipping_inventory_rpa():
"""旧 shipping_inventory_rpa 语义应迁移为 platform_job。"""
migrated = migrate_legacy_schedule_payload({
"schedule_type": "platform_app",
"data_source_type": "shipping_inventory_rpa",
"platform_api_path": "/123",
})
assert migrated["schedule_type"] == "platform_job"
assert migrated["platform_api_path"] == "shipping-inventory-rpa"
assert migrated["data_source_type"] is None
def test_migrate_legacy_faq_hot_aggregate():
"""旧 faq_hot_aggregate 语义应迁移为 platform_job。"""
migrated = migrate_legacy_schedule_payload({
"data_source_type": "faq_hot_aggregate",
})
assert migrated["schedule_type"] == "platform_job"
assert migrated["platform_api_path"] == "faq-aggregate-hot"
assert migrated["data_source_type"] is None
def test_migrate_legacy_database_pipeline():
"""旧 platform_app + database 应迁移为 data_pipeline。"""
migrated = migrate_legacy_schedule_payload({
"schedule_type": "platform_app",
"data_source_type": "database",
"platform_api_path": "/42",
})
assert migrated["schedule_type"] == "data_pipeline"
assert migrated["platform_api_path"] is None
assert migrated["data_source_type"] == "database"
def test_run_platform_job_unknown_key(app):
"""run_platform_job 对未知 key 应抛 KeyError。"""
with app.app_context():
user = User(username="registry_user", email="registry_user@example.com")
from app import db
db.session.add(user)
db.session.flush()
task = ScheduleTask(
schedule_no="SCH-REG-001",
name="test",
schedule_type="platform_job",
platform_api_path="shipping-inventory-rpa",
owner_user_id=user.id,
cron_expr="0 3 * * *",
)
from app.models import ScheduleRun
run = ScheduleRun(run_no="RUN-REG-001", schedule_task_id=1, status="running")
with pytest.raises(KeyError):
run_platform_job("unknown-job-key", task, run, {})
def test_common_executor_in_process_without_base_url(app, monkeypatch):
"""已注册 job key 在无 INTERNAL_API_BASE_URL 时应进程内执行,不走 HTTP。"""
with app.app_context():
from app import db
from app.models import ScheduleRun
app.config["INTERNAL_API_BASE_URL"] = ""
user = User(username="inproc_exec_user", email="inproc_exec_user@example.com")
db.session.add(user)
db.session.flush()
task = ScheduleTask(
schedule_no="SCH-INPROC-001",
name="in-process job",
schedule_type="platform_job",
platform_api_path="faq-aggregate-hot",
data_source_type=None,
owner_user_id=user.id,
cron_expr="0 3 * * *",
)
db.session.add(task)
db.session.flush()
run = ScheduleRun(run_no="RUN-INPROC-001", schedule_task_id=task.id, status="running")
db.session.add(run)
db.session.commit()
called: dict[str, str] = {}
def _fake_run_platform_job(key, t, r, payload=None):
called["key"] = key
return 1, 1, 0, 0, [{"ok": True}], [], [{"step": "in_process", "status": "success"}]
monkeypatch.setattr(
"app.services.schedule.job_registry.run_platform_job",
_fake_run_platform_job,
)
total, success, failed, skipped, details, errors, logs = _run_common_executor(task, run)
assert called["key"] == "faq-aggregate-hot"
assert total == 1 and success == 1
assert any(log.get("step") == "in_process" for log in logs)
def test_get_platform_jobs_api(client, admin_jwt_headers):
"""GET /api/admin/schedule/platform-jobs 应返回 registry 列表及 label_key。"""
res = client.get("/api/admin/schedule/platform-jobs", headers=admin_jwt_headers)
assert res.status_code == 200
body = res.get_json()
keys = {item["key"] for item in body}
assert "shipping-inventory-rpa" in keys
assert "faq-aggregate-hot" in keys
assert all("label" in item for item in body)
# 内置 job 应返回稳定 i18n key,供前端 $t(label_key) 渲染
by_key = {item["key"]: item for item in body}
assert by_key["shipping-inventory-rpa"]["label_key"] == "admin.schedule.form.platformJobShippingInventory"
assert by_key["faq-aggregate-hot"]["label_key"] == "admin.schedule.form.platformJobFaqHotAggregate"
assert by_key["fixed-assets-snapshot"]["label_key"] == "admin.schedule.form.platformJobFixedAssetsSnapshot"
def test_schedule_config_rejects_data_source_type_for_platform_job(client, admin_jwt_headers, app):
"""platform_job 经 schedule-config PUT 改 data_source_type 应被拒绝。"""
with app.app_context():
from app import db
user = User(username="cfg_platform_user", email="cfg_platform_user@example.com")
db.session.add(user)
db.session.flush()
task = ScheduleTask(
schedule_no="SCH-CFG-001",
name="platform cfg guard",
schedule_type="platform_job",
platform_api_path="fixed-assets-snapshot",
data_source_type=None,
owner_user_id=user.id,
cron_expr="0 3 * * *",
)
db.session.add(task)
db.session.commit()
task_id = task.id
res = client.put(
f"/api/admin/schedule-config/{task_id}",
headers=admin_jwt_headers,
json={"data_source_type": "database"},
)
assert res.status_code == 400
def test_post_platform_job_rejects_illegal_config(client, admin_jwt_headers, app):
"""创建 platform_job 携带非白名单 config 应 400。"""
with app.app_context():
user = User(username="post_cfg_user", email="post_cfg_user@example.com")
db.session.add(user)
db.session.commit()
owner_id = user.id
res = client.post(
"/api/admin/schedules",
headers=admin_jwt_headers,
json={
"name": "faq with config",
"schedule_type": "platform_job",
"platform_api_path": "faq-aggregate-hot",
"owner_user_id": owner_id,
"cron_expr": "0 3 * * *",
"config": {"api_body_template": "{}"},
},
)
assert res.status_code == 400
def test_patch_platform_job_rejects_illegal_config_without_partial_update(client, admin_jwt_headers, app):
"""PATCH 携带非法 config 应 400,且任务主字段不被半更新。"""
with app.app_context():
user = User(username="patch_cfg_user", email="patch_cfg_user@example.com")
db.session.add(user)
db.session.flush()
task = ScheduleTask(
schedule_no="SCH-PATCH-CFG-001",
name="before patch",
schedule_type="platform_job",
platform_api_path="fixed-assets-snapshot",
data_source_type=None,
owner_user_id=user.id,
cron_expr="0 3 * * *",
)
db.session.add(task)
db.session.commit()
task_id = task.id
res = client.patch(
f"/api/admin/schedules/{task_id}",
headers=admin_jwt_headers,
json={
"name": "after patch",
"config": {"api_body_template": "{}"},
},
)
assert res.status_code == 400
with app.app_context():
refreshed = db.session.get(ScheduleTask, task_id)
assert refreshed.name == "before patch"
@@ -19,9 +19,11 @@ def test_shipping_inventory_rpa_schedule_writes_batch_trigger(app, tmp_path):
task = ScheduleTask(
schedule_no="SCH-INV-001",
name="货代库存每日导出",
schedule_type="platform_job",
platform_api_path="shipping-inventory-rpa",
data_source_type=None,
owner_user_id=user.id,
cron_expr="0 3 * * *",
data_source_type="shipping_inventory_rpa",
enabled=True,
)
db.session.add(task)
+2 -1
View File
@@ -2761,7 +2761,8 @@ API 层
- **multi_select**:worker `_fill_dsv_multi_select` 支持多选控件(非仅取第一个值)
- Worker:`scripts/rpa/freight_rpa_worker.py` → `_handle_inventory_batch_trigger`
- 回调:`POST /api/shipping-notice/rpa/inventory-batch-ready`
- 定时排程:`data_source_type=shipping_inventory_rpa`,建议 cron `0 3 * * *`(Asia/Shanghai)
- 定时排程:`schedule_type=platform_job`,`platform_api_path=shipping-inventory-rpa`,`data_source_type=null`;建议 cron `0 3 * * *`(Asia/Shanghai)
- 排程语义:`data_source_type` 仅用于 `schedule_type=data_pipeline`(`database` | `external_api`);平台任务通过 Job Registry 注册,由 `platform_api_path` 引用 job key
### 5.4 审计字段
+1 -1
View File
@@ -59,7 +59,7 @@
| 库存 RPA 源 JSON 配置 | 已实现 | `backend/config/shipping_inventory_sources.json`,新增 Warehouse 只改 JSON |
| 库存快照 TTL 复用 | 已实现 | `inventory_snapshot_store`,按需任务优先复用未过期快照 |
| 库存 RPA 批量导出(DSV/Crane 一次登录) | 已实现 | `inventory_export_batch` trigger + worker + `/rpa/inventory-batch-ready` |
| 库存每日定时导出排程 | 已实现 | `data_source_type=shipping_inventory_rpa`,cron 建议 `0 3 * * *` |
| 库存每日定时导出排程 | 已实现 | `schedule_type=platform_job` + `platform_api_path=shipping-inventory-rpa`,cron 建议 `0 3 * * *` |
| 产品原型 | 已文档化 | 见 [docs/prototype/shipping_notice_agent_prototype.md](prototype/shipping_notice_agent_prototype.md) |
### Agent 应用管理(platform)
@@ -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);