Merge branch 'dev' of https://gitee.com/justop/hxops into dev

This commit is contained in:
sophie committed 2026-07-06 15:20:40 +08:00
commit fa8f6990a7
113 files changed
+19714 -9259

No files matched your search

+2
View File
@@ -27,6 +27,7 @@ def register_blueprints(app: Flask) -> None:
from app.api.maintenance import maintenance_bp
from app.api.speech import speech_bp
from app.api.training import training_admin_bp, training_user_bp
from app.api.agent_runtime_context_tools import agent_runtime_context_bp
# [STEP 2] 已分包骨架(Wave 3:kb、schedule 等)
from app.api.kb import knowledge_base_bp
@@ -55,6 +56,7 @@ def register_blueprints(app: Flask) -> None:
app.register_blueprint(maintenance_bp, url_prefix='/api/maintenance')
app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice')
app.register_blueprint(file_check_bp, url_prefix='/api/file-check')
app.register_blueprint(agent_runtime_context_bp, url_prefix='/api/agent-runtime-context')
app.register_blueprint(maintenance_tool_bp, url_prefix='/api/maintenance')
app.register_blueprint(speech_bp, url_prefix='/api/speech')
app.register_blueprint(training_admin_bp, url_prefix='/api/admin')
@@ -0,0 +1,107 @@
"""
backend/app/api/agent_runtime_context_tools.py
用途:暴露 agent_runtime_context 只读 Tool API,供 Dify Chatflow 解析 HXOPS 上下文。
依赖:app.core.errors、agent_runtime_context.parser/openapi_spec、shipping_notice.tool_api_url。
逻辑:OpenAPI 文档接口放行;parse 工具复用 Authorization Bearer / X-Integration-Key 鉴权,不推进业务状态。
"""
from __future__ import annotations
from flask import Blueprint, current_app, jsonify, request
from app.core.errors import AppError, ServiceUnavailableError, UnauthorizedError
from app.services.agent_runtime_context.openapi_spec import build_agent_runtime_context_openapi_spec
from app.services.agent_runtime_context.parser import parse_agent_runtime_context
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
agent_runtime_context_bp = Blueprint("agent_runtime_context_tools", __name__)
def _require_tool_auth() -> None:
"""
校验 agent_runtime_context Tool API 鉴权 Header。
【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;Dify 请求 parse 工具时由 before_request 自动触发。
核心逻辑:只接受 Authorization Bearer 或 X-Integration-Key,复用 INTEGRATION_API_KEY 作为平台工具密钥。
Raises:
ServiceUnavailableError: 未配置 INTEGRATION_API_KEY。
UnauthorizedError: 缺少或传入错误鉴权。
"""
configured = str(current_app.config.get("INTEGRATION_API_KEY") or "").strip()
if not configured:
raise ServiceUnavailableError("INTEGRATION_API_KEY is not configured", code="missing_auth")
bearer = str(request.headers.get("Authorization") or "").strip()
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
if configured in {token, integration_key}:
return
if not token and not integration_key:
raise UnauthorizedError("missing_auth")
raise UnauthorizedError("invalid_auth")
def _tool_error_code(exc: AppError) -> str:
"""
归一化 Tool API 错误码。
核心逻辑:保持与 shipping/file-check Tool API 的 ok:false 响应风格一致,便于 Dify 侧统一处理。
Args:
exc: 业务异常。
Returns:
Tool 侧错误码。
"""
message = str(exc.message or "").strip()
if message in {"missing_auth", "invalid_auth"}:
return message
if exc.code == "AUTH.UNAUTHORIZED":
return "invalid_auth"
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
return "missing_auth"
return exc.code
@agent_runtime_context_bp.errorhandler(AppError)
def _handle_tool_app_error(exc: AppError):
"""把业务异常统一转成 Tool 侧约定的 JSON 结构。"""
return jsonify({"ok": False, "error_code": _tool_error_code(exc), "message": exc.message}), exc.http_status
@agent_runtime_context_bp.before_request
def _verify_tool_access():
"""
对上下文解析 Tool 做统一 Header 鉴权。
核心逻辑:OpenAPI 导入文档无需鉴权;parse 工具必须携带平台 Tool Key。
"""
if request.path.endswith("/openapi.json"):
return None
_require_tool_auth()
return None
@agent_runtime_context_bp.route("/tools/openapi.json", methods=["GET"])
def openapi_spec():
"""返回 Dify 导入用的 OpenAPI JSON 文档。"""
return jsonify(build_agent_runtime_context_openapi_spec(resolve_tool_api_base_url()))
@agent_runtime_context_bp.route("/tools/parse", methods=["POST"])
def parse_context_tool():
"""
解析 agent_runtime_context 的白名单字段。
【AI 触发时机】:Dify 需要读取 HXOPS session/task/batch/run_purpose/state_hint 等上下文字段时调用;
不用于推进业务状态。
"""
payload = request.get_json(silent=True) or {}
return jsonify(
parse_agent_runtime_context(
payload.get("agent_runtime_context"),
payload.get("paths"),
)
)
+51 -19
View File
@@ -20,6 +20,7 @@ import requests
from flask import Blueprint, request, Response, stream_with_context, jsonify, g, current_app, has_request_context
from sqlalchemy import func, desc, or_, exists, and_
from openpyxl import load_workbook
from app.services.agent_runtime_context.dify_inputs import build_chat_dify_inputs
from app.services.dify import DifyService
from app.core.config.settings import Config
from app.services.integration_api import IntegrationApiService
@@ -48,6 +49,25 @@ def _can_use_leave_feature(agent_proxy) -> bool:
PLM_PREVIEW_SHARE_ROOT = (os.getenv('PLM_PREVIEW_SHARE_ROOT') or '\\\\192.168.0.11\\dss\\dssroot\\').strip()
def _build_chat_adapter_hints(*, shipping_task_id: str | None = None, shipping_batch_no: str | None = None) -> dict | None:
"""
构建聊天入口分发给领域 adapter 的提示字典。
核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task/batch 提示,
统一收敛到 adapter_hints 这个不透明容器里,避免平台函数签名泄漏领域字段。
"""
task_id = str(shipping_task_id or '').strip()
batch_no = str(shipping_batch_no or '').strip()
if not task_id and not batch_no:
return None
return {
'shipping_notice': {
'task_id': task_id or None,
'batch_no': batch_no or None,
}
}
def _should_reset_provider_conversation_for_asset_query(query: str, agent_proxy) -> bool:
"""
判断固资管理里的当前问题是否应当切断上游 Dify 会话上下文。
@@ -1386,7 +1406,25 @@ def chat_completions():
raise ValidationError('This route does not support attachments')
generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
elif leave_supported:
generator = DifyService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, request_id=request_id, session_id=session.session_id, files=normalized_files)
generator = DifyService.stream_chat(
query,
user_proxy.id,
agent_proxy,
external_conversation_id,
request_id=request_id,
session_id=session.session_id,
files=normalized_files,
inputs=build_chat_dify_inputs(
agent_proxy,
session_id=session.session_id,
request_id=request_id,
trigger_source="frontend_chat",
adapter_hints=_build_chat_adapter_hints(
shipping_task_id=shipping_task_id,
shipping_batch_no=shipping_batch_no,
),
),
)
elif kb_type == 'ERP知识库':
from app.services.text2sql import Text2SQLService
if normalized_files:
@@ -1399,23 +1437,26 @@ def chat_completions():
raise ValidationError('This route does not support attachments')
generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
else:
dify_inputs: dict[str, object] | None = None
hxops_turn_id: str | None = None
from app.services.file_check_tools.agent_resolver import (
agent_declares_file_check_progress,
is_file_check_chat_agent,
)
from app.services.file_check_tools.dify_inputs import build_file_check_dify_inputs
from app.services.shipping_notice.dify_inputs import (
build_dify_chat_inputs as build_shipping_notice_dify_inputs,
is_shipping_notice_chat_agent,
)
declares_file_check = agent_declares_file_check_progress(agent_proxy)
is_file_check_agent = is_file_check_chat_agent(agent_proxy)
is_shipping_agent = is_shipping_notice_chat_agent(agent_proxy)
dify_inputs = build_chat_dify_inputs(
agent_proxy,
session_id=session.session_id,
request_id=request_id,
trigger_source="frontend_chat",
adapter_hints=_build_chat_adapter_hints(
shipping_task_id=shipping_task_id,
shipping_batch_no=shipping_batch_no,
),
)
if declares_file_check or is_file_check_agent:
# [STEP 1] 先校验 task_id,避免 Dify Chatflow 缺参时长连接挂死
dify_inputs = build_file_check_dify_inputs(agent_proxy, required=True)
# [STEP 1] file_check 的 task_id 校验已在统一 dify_inputs 分发入口完成;这里只保留 turn 注册
if is_file_check_agent:
hxops_turn_id = uuid.uuid4().hex
from app.services.file_check_tools.chat_turn_registry import register_file_check_chat_turn
@@ -1427,15 +1468,6 @@ def chat_completions():
agent_id=agent_proxy.id,
query=query,
)
elif is_shipping_agent:
# [STEP 2] 发货通知 Chatflow 依赖会话级 task/batch 上下文稳定定位当前任务
dify_inputs = build_shipping_notice_dify_inputs(
session.session_id,
task_id=shipping_task_id,
batch_no=shipping_batch_no,
trigger_source="frontend_chat",
request_id=request_id,
)
generator = DifyService.stream_chat(
query,
user_proxy.id,
+6 -1
View File
@@ -33,6 +33,7 @@ from app.services.shipping_notice.query_service import (
serialize_task_summary,
task_export_error_message,
)
from app.services.shipping_notice.tool_common import switch_batch_focus
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
shipping_notice_bp = Blueprint("shipping_notice", __name__)
@@ -314,7 +315,11 @@ def tool_switch_focus_task():
task = get_task_in_batch(batch_no, task_no)
if not task:
raise NotFoundError("task not found in batch")
batch.current_focus_task_no = task.task_no
switch_batch_focus(
batch,
task,
source="tool_api",
)
db.session.commit()
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'task_no': task.task_no, 'message': f'已切换当前任务到 {task.task_no}', 'data': {'batch': serialize_batch_summary(batch), 'focus_task': serialize_task_summary(task)}})
+12 -1
View File
@@ -37,7 +37,18 @@ def serialize_file_judgement(payload: dict) -> dict:
judgement = response_summary.get('file_judgement')
if not isinstance(judgement, dict):
judgement = {}
return {'qualified_count': int(judgement.get('qualified_count') or 0), 'unqualified_count': int(judgement.get('unqualified_count') or 0), 'manual_count': int(judgement.get('manual_count') or 0), 'dify_error_count': int(judgement.get('dify_error_count') or 0), 'invalid_result_count': int(judgement.get('invalid_result_count') or 0)}
return {
'qualified_count': int(judgement.get('qualified_count') or 0),
'unqualified_count': int(judgement.get('unqualified_count') or 0),
'manual_count': int(judgement.get('manual_count') or 0),
'dify_error_count': int(judgement.get('dify_error_count') or 0),
'invalid_result_count': int(judgement.get('invalid_result_count') or 0),
'business_manual_count': int(judgement.get('business_manual_count') or 0),
'system_error_count': int(judgement.get('system_error_count') or 0),
'dify_timeout_count': int(judgement.get('dify_timeout_count') or 0),
'invalid_output_count': int(judgement.get('invalid_output_count') or 0),
'attachment_error_count': int(judgement.get('attachment_error_count') or 0),
}
def serialize_current_step(payload: dict) -> dict | None:
response_summary = payload.get('response_summary_json') if isinstance(payload.get('response_summary_json'), dict) else {}
+134 -73
View File
@@ -2,16 +2,19 @@
backend/app/api/workspace/shipping_notice.py
用途:HXOPS 工作台与聊天前端使用的发货通知用户态 API。
依赖:app.core.auth.jwt、app.core.errors、shipping_notice.query_service / tools / notice_upload。
依赖:app.core.auth.jwt、app.core.errors、shipping_notice.query_service / tools / notice_upload / ui_state。
逻辑:薄路由层鉴权与参数校验;register_blueprints 经 workspace 包注册。
"""
from __future__ import annotations
from flask import Blueprint, jsonify, request, send_file
import uuid
from flask import Blueprint, g, jsonify, request, send_file
from app import db
from app.core.auth.jwt import get_current_user
from app.core.errors import AppError, NotFoundError, UnauthorizedError, ValidationError
from app.core.response import ok
from app.models import ShippingBatch, ShippingTask
from app.services.shipping_notice.chat_actions import build_chat_actions_payload
from app.services.shipping_notice.constants import (
@@ -20,6 +23,7 @@ from app.services.shipping_notice.constants import (
CP_NOTICE_TEXT_EXTRACTION_FAILED,
MAP_JSON,
)
from app.services.shipping_notice.tool_common import switch_batch_focus
from app.services.shipping_notice.query_service import (
EXPORT_MIME_TYPE,
get_batch_for_user,
@@ -35,6 +39,7 @@ from app.services.shipping_notice.query_service import (
serialize_task_summary,
task_export_error_message,
)
from app.services.shipping_notice.ui_state import build_batch_ui_state, build_task_ui_state
workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__)
@@ -53,6 +58,11 @@ def _require_user():
return user
def _ok(payload: dict):
"""返回带 request_id 的成功 envelope,供工作台读接口复用。"""
return ok(payload, request_id=getattr(g, 'request_id', None))
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET'])
def workspace_shipping_tasks():
"""列出当前用户可见的发货任务,可按批次与处理状态过滤。"""
@@ -73,10 +83,7 @@ def workspace_shipping_batches():
def workspace_shipping_conversation_batch_workspace(conversation_id: str):
"""返回一个 Agent 会话下的多批次执行工作台快照。"""
user = _require_user()
batches = ShippingBatch.query.filter(ShippingBatch.conversation_id == str(conversation_id or "").strip()).filter(
(ShippingBatch.user_id == user.id) | (ShippingBatch.user_id.is_(None))
).all()
return jsonify(get_conversation_batch_workspace(conversation_id, user.id))
return _ok(get_conversation_batch_workspace(conversation_id, user.id))
@workspace_shipping_notice_bp.route('/shipping-batches/create-from-notices', methods=['POST'])
def workspace_create_shipping_batch_from_notices():
@@ -90,29 +97,37 @@ def workspace_create_shipping_batch_from_notices():
if not uploads:
raise ValidationError('files is required')
from app.services.shipping_notice import tools as shipping_tools
from app.services.shipping_notice.notice_upload import extract_notice_text, guess_source_type, max_notice_chars, save_task_notice_upload
from app.services.shipping_notice.notice_upload import (
build_notice_file_summary,
cleanup_temp_notice_uploads,
intake_temp_notice_uploads,
)
conversation_id = str(request.form.get('conversation_id') or '').strip()
notice_items: list[dict] = []
for upload in uploads:
raw = upload.read() or b''
filename = upload.filename or 'notice'
source_type = guess_source_type(filename)
text = ''
warnings: list[str] = []
try:
temp_task_no = f'TMP-{len(notice_items) + 1}'
saved_path = save_task_notice_upload(temp_task_no, filename, raw)
text, meta = extract_notice_text(saved_path)
warnings = list(meta.get('warnings') or []) if isinstance(meta, dict) else []
except Exception as exc:
warnings = [f'notice_extract_failed:{exc}']
if text:
limit = max_notice_chars()
if len(text) > limit:
text = text[:limit]
warnings.append(f'notice_text_truncated:{limit}')
notice_items.append({'source_type': source_type, 'source_file_name': filename, 'source_file_type': str(getattr(upload, 'mimetype', '') or '').strip() or None, 'raw_text': text, 'warnings': warnings})
payload = {'user_id': user.id, 'conversation_id': conversation_id or None, 'file_count': len(notice_items), 'notice_items': notice_items, 'defer_parse': True}
temp_request_id = str(getattr(g, 'request_id', None) or uuid.uuid4().hex)
try:
accepted, rejected = intake_temp_notice_uploads(temp_request_id, uploads)
finally:
cleanup_temp_notice_uploads(temp_request_id)
file_summary = build_notice_file_summary(
total_files=len(uploads),
accepted=accepted,
rejected=rejected,
)
notice_items = [item.to_notice_item() for item in accepted]
if not notice_items:
raise ValidationError(
'all uploaded files failed extraction or contained no parseable text',
details={'rejected_files': file_summary['rejected_files'], 'file_summary': file_summary},
)
payload = {
'user_id': user.id,
'conversation_id': conversation_id or None,
'file_count': len(notice_items),
'notice_items': notice_items,
'defer_parse': True,
}
created = shipping_tools.create_batch_tasks(payload)
data = created.get('data') if isinstance(created, dict) else None
batch_data = data.get('batch') if isinstance(data, dict) else None
@@ -133,17 +148,37 @@ def workspace_create_shipping_batch_from_notices():
base_message = str(created.get('message') or '').strip()
if orchestrator_started:
created['message'] = f'{base_message},后台已开始逐票处理。' if base_message else '后台已开始逐票处理。'
return jsonify(created)
created['file_summary'] = file_summary
return _ok(created)
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>', methods=['GET'])
def workspace_shipping_batch_detail(batch_no: str):
"""返回批次详情、批次内任务列表和当前焦点任务。"""
"""
返回批次详情与聚合 UI State。
核心逻辑:工作台详情页与独立 `/ui-state` 端点共享同一份批次状态构建结果,
避免批次摘要、焦点任务和任务卡片在不同接口里各自推导造成漂移。
"""
user = _require_user()
batch = get_batch_for_user(batch_no, user.id)
if not batch:
raise NotFoundError('Not found')
focus_task = get_focus_task_for_batch(batch_no, user.id)
return jsonify({**serialize_batch_summary(batch), 'tasks': list_tasks_for_batch(batch_no, user.id), 'focus_task': serialize_task_summary(focus_task) if focus_task else None})
return _ok(build_batch_ui_state(batch))
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/ui-state', methods=['GET'])
def workspace_shipping_batch_ui_state(batch_no: str):
"""
返回批次级 UI State。
核心逻辑:供右侧工作台、步骤条与批次任务卡统一读取同源状态,
保持与批次详情接口返回的 `focus_task_ui_state/tasks[].ui_state` 完全一致。
"""
user = _require_user()
batch = get_batch_for_user(batch_no, user.id)
if not batch:
raise NotFoundError('Not found')
return _ok(build_batch_ui_state(batch))
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/tasks', methods=['GET'])
def workspace_shipping_batch_tasks(batch_no: str):
@@ -175,12 +210,19 @@ def workspace_switch_shipping_batch_focus_task(batch_no: str):
raise NotFoundError('Not found')
data = request.get_json(silent=True) or {}
task_no = str(data.get('task_no') or data.get('target_task_no') or '').strip()
comment = str(data.get('comment') or '').strip()
if not task_no:
raise ValidationError('task_no is required')
task = get_task_for_user(task_no, user.id)
if not task or task.batch_id != batch.id:
raise NotFoundError('Task not found in batch')
batch.current_focus_task_no = task.task_no
switch_batch_focus(
batch,
task,
source='workspace_api',
comment=comment or None,
extra={'actor_user_id': user.id},
)
db.session.commit()
return jsonify({'batch': serialize_batch_summary(batch), 'focus_task': serialize_task_summary(task)})
@@ -210,8 +252,11 @@ def workspace_create_shipping_task_from_notice():
if not upload:
raise ValidationError('file is required')
from app.services.shipping_notice import tools as shipping_tools
from app.services.shipping_notice.notice_upload import extract_notice_text, guess_source_type, max_notice_chars, save_task_notice_upload
source_type = guess_source_type(upload.filename or '')
from app.services.shipping_notice.notice_upload import guess_source_type, intake_notice_attachment, notice_source_file_type
filename = upload.filename or 'notice'
raw = upload.read() or b''
source_file_type = notice_source_file_type(upload)
source_type = guess_source_type(filename)
conversation_id = str(request.form.get('conversation_id') or '').strip()
payload = {'user_id': user.id, 'source_type': source_type}
if conversation_id:
@@ -220,29 +265,25 @@ def workspace_create_shipping_task_from_notice():
task_id = str(created.get('task_id') or '').strip()
if not task_id:
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='failed to create task', http_status=500)
raw = upload.read() or b''
saved_path = save_task_notice_upload(task_id, upload.filename or 'notice', raw)
text, meta = extract_notice_text(saved_path)
if not text:
intake = intake_notice_attachment(
filename=filename,
raw=raw,
source_file_type=source_file_type,
storage='task',
task_no=task_id,
)
if not intake.accepted:
from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint
return jsonify({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': {'filename': upload.filename or '', **meta}}, 'human_options': ['reparse', 'reject'], 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED, 'action_buttons': action_buttons_for_checkpoint(CP_NOTICE_TEXT_EXTRACTION_FAILED)})
if text:
limit = max_notice_chars()
if len(text) > limit:
text = text[:limit]
meta.setdefault('warnings', []).append(f'notice_text_truncated:{limit}')
task = ShippingTask.query.filter_by(task_no=task_id).first()
if task:
task.raw_content = text
db.session.commit()
return jsonify({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'human_options': ['reparse', 'reject'], 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED, 'action_buttons': action_buttons_for_checkpoint(CP_NOTICE_TEXT_EXTRACTION_FAILED)})
task = ShippingTask.query.filter_by(task_no=task_id).first()
if task:
task.source_file_name = str(upload.filename or '').strip() or task.source_file_name
task.source_file_type = str(getattr(upload, 'mimetype', '') or '').strip() or task.source_file_type
task.raw_content = intake.text
task.source_file_name = intake.filename or task.source_file_name
task.source_file_type = intake.source_file_type or task.source_file_type
db.session.commit()
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
orchestrator_started = start_task_orchestrator(task_id)
return jsonify({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task) if task else {'task_no': task_id}, 'notice_upload': {'filename': upload.filename or '', **meta}, 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}})
return jsonify({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task) if task else {'task_no': task_id}, 'notice_upload': intake.to_notice_upload_meta(), 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}})
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/replace-notice', methods=['POST'])
def workspace_replace_shipping_task_notice(task_no: str):
@@ -255,38 +296,58 @@ def workspace_replace_shipping_task_notice(task_no: str):
if not upload:
raise ValidationError('file is required')
from app.services.shipping_notice import task_workflow
from app.services.shipping_notice.notice_upload import extract_notice_text, guess_source_type, max_notice_chars, save_task_notice_upload
raw = upload.read() or b''
filename = upload.filename or 'notice'
saved_path = save_task_notice_upload(task.task_no, filename, raw)
text, meta = extract_notice_text(saved_path)
warnings = list(meta.get('warnings') or []) if isinstance(meta, dict) else []
if text:
limit = max_notice_chars()
if len(text) > limit:
text = text[:limit]
warnings.append(f'notice_text_truncated:{limit}')
task.source_type = guess_source_type(filename) or task.source_type
from app.services.shipping_notice.notice_upload import intake_notice_attachment, notice_source_file_type
intake = intake_notice_attachment(
filename=upload.filename or 'notice',
raw=upload.read() or b'',
source_file_type=notice_source_file_type(upload),
storage='task',
task_no=task.task_no,
)
task.source_type = intake.source_type or task.source_type
result = task_workflow.replace_task_notice(
task,
raw_text=text,
source_file_name=filename,
source_file_type=str(getattr(upload, 'mimetype', '') or '').strip(),
warnings=warnings,
raw_text=intake.text,
source_file_name=intake.filename,
source_file_type=intake.source_file_type,
warnings=list(intake.warnings),
)
data = result.setdefault('data', {})
if isinstance(data, dict):
data['notice_upload'] = {'filename': filename, **(meta if isinstance(meta, dict) else {})}
return jsonify(result)
data['notice_upload'] = intake.to_notice_upload_meta()
return _ok(result)
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>', methods=['GET'])
def workspace_shipping_task_detail(task_no: str):
"""返回指定任务的详情快照。"""
"""
返回指定任务的详情快照与内嵌 UI State。
核心逻辑:详情接口直接内嵌 `ui_state`,让页面首屏读取任务详情时即可拿到
checkpoint / action_buttons / steps,减少前端二次推导与竞态刷新。
"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
return jsonify(serialize_task_detail(task))
return _ok({
**serialize_task_detail(task),
'ui_state': build_task_ui_state(task),
})
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/ui-state', methods=['GET'])
def workspace_shipping_task_ui_state(task_no: str):
"""
返回单票任务 UI State。
核心逻辑:Chat 顶部步骤条、动作按钮和工作台详情统一复用这里的状态机投影,
避免不同前端入口重复拼装按钮集合。
"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
return _ok(build_task_ui_state(task))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/chat-actions', methods=['GET'])
def workspace_shipping_task_chat_actions(task_no: str):
@@ -365,7 +426,7 @@ def workspace_submit_shipping_decision(task_no: str):
if not decision:
raise ValidationError('decision is required')
from app.services.shipping_notice import tools as shipping_tools
payload = {'task_id': task.task_no, 'decision': decision, AUTO_CHAIN_FALLBACK: True}
payload = {'task_id': task.task_no, 'decision': decision, AUTO_CHAIN_FALLBACK: True, 'event_source': 'workspace_api'}
comment = str(data.get('comment') or '').strip()
if comment:
payload['comment'] = comment
+15 -8
View File
@@ -8,7 +8,7 @@ backend/app/core/config/settings.py
import os
from pathlib import Path
from dotenv import load_dotenv
from dotenv import dotenv_values
_BACKEND_DIR = Path(__file__).resolve().parents[3]
@@ -36,18 +36,25 @@ def _load_environment_files() -> str:
4. system environment variables (always highest, never overridden)
"""
env_name = _normalize_env_name(os.getenv('ENV_NAME') or os.getenv('FLASK_ENV'))
preserved_env = dict(os.environ)
merged_values: dict[str, str] = {}
shared_file = _ROOT_DIR / '.env.shared'
if shared_file.exists():
load_dotenv(shared_file, override=False)
merged_values.update({k: v for k, v in dotenv_values(shared_file).items() if v is not None})
env_file = _ROOT_DIR / f'.env.{env_name}'
if env_file.exists():
load_dotenv(env_file, override=True)
merged_values.update({k: v for k, v in dotenv_values(env_file).items() if v is not None})
if env_name == 'dev':
local_file = _ROOT_DIR / '.env.local'
if local_file.exists():
load_dotenv(local_file, override=True)
merged_values.update({k: v for k, v in dotenv_values(local_file).items() if v is not None})
for key, value in merged_values.items():
if key not in preserved_env:
os.environ[key] = value
return env_name
@@ -145,11 +152,8 @@ class Config:
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED = (
os.getenv('SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED', 'true').lower() == 'true'
)
SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS = int(
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS') or '1'
)
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS') or '120'
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS') or '360'
)
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM = os.getenv('SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM', 'false').lower() == 'true'
SHIPPING_NOTICE_AUTO_MATCH_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_MATCH_ENABLED', 'true').lower() == 'true'
@@ -187,6 +191,9 @@ class Config:
FREIGHT_RPA_UPLOAD_TRIGGER_DIR = _data_path(
"FREIGHT_RPA_UPLOAD_TRIGGER_DIR", "shipping_notice", "freight_rpa", "upload_triggers"
)
FREIGHT_RPA_BROWSER_PROFILE_DIR = _data_path(
"FREIGHT_RPA_BROWSER_PROFILE_DIR", "shipping_notice", "freight_rpa", "browser_profile"
)
FREIGHT_SHIPMENT_TEMPLATE_PATH = _backend_path(
"FREIGHT_SHIPMENT_TEMPLATE_PATH", "templates", "freight_shipment_upload.xlsx"
)
@@ -0,0 +1,37 @@
"""
backend/app/services/agent_runtime_context/__init__.py
用途:聚合导出 HXOPS Agent Runtime Context 平台协议能力与通用构建器。
依赖:builder、schema、generic adapter、reference。
逻辑:业务 adapter 从本包导入平台协议与构建器;聊天分发入口单独从 `dify_inputs.py` 直接导入,避免包初始化时反向拉起业务 adapter 形成循环依赖。
"""
from app.services.agent_runtime_context.adapters.generic import (
build_generic_runtime_context,
resolve_agent_code,
)
from app.services.agent_runtime_context.builder import (
build_agent_runtime_context,
build_dify_inputs,
serialize_for_dify,
)
from app.services.agent_runtime_context.reference import (
build_object_ref,
build_reference_context,
)
from app.services.agent_runtime_context.schema import (
AGENT_RUNTIME_CONTEXT_INPUT,
AGENT_RUNTIME_CONTEXT_SCHEMA_VERSION,
)
__all__ = [
"AGENT_RUNTIME_CONTEXT_INPUT",
"AGENT_RUNTIME_CONTEXT_SCHEMA_VERSION",
"build_agent_runtime_context",
"build_dify_inputs",
"build_generic_runtime_context",
"build_object_ref",
"build_reference_context",
"resolve_agent_code",
"serialize_for_dify",
]
@@ -0,0 +1,130 @@
"""
backend/app/services/agent_runtime_context/adapters/generic.py
用途:为未接入专用业务 adapter 的 Dify Agent 构建最小可用的 agent_runtime_context。
依赖:agent_runtime_context.builder、标准库 typing。
逻辑:由平台级 dify_inputs 分发入口调用;当 Agent 既不是 shipping_notice 也不是 file_check 时,
使用本模块生成通用会话快照,让 Dify Start 节点也能稳定拿到 platform/session 上下文。
"""
from __future__ import annotations
from typing import Any
from app.services.agent_runtime_context.builder import (
build_agent_runtime_context,
build_dify_inputs,
)
def _agent_extra_config(agent) -> dict[str, Any]:
"""读取 Agent.extra_config;非字典时回退为空,避免通用适配器因脏配置报错。"""
extra_config = getattr(agent, "extra_config", None)
return extra_config if isinstance(extra_config, dict) else {}
def resolve_agent_code(agent) -> str:
"""
解析通用 Agent 的稳定 code。
核心逻辑:优先读取 extra_config.agent_code;未配置或为空时回退为 generic,
让知识库/普通问答类 Agent 也能在 Runtime 中暴露稳定标识。
Args:
agent: 当前对话 Agent 记录或代理对象。
Returns:
Agent code 字符串;缺省为 generic。
"""
agent_code = str(_agent_extra_config(agent).get("agent_code") or "").strip()
return agent_code or "generic"
def _resolve_domain_summary(agent) -> str:
"""按优先级提取通用摘要,避免无业务状态 Agent 的 domain.summary 为空。"""
extra_config = _agent_extra_config(agent)
runtime_context_summary = str(extra_config.get("runtime_context_summary") or "").strip()
if runtime_context_summary:
return runtime_context_summary
agent_description = str(getattr(agent, "description", None) or "").strip()
if agent_description:
return agent_description
return "通用对话"
def build_generic_runtime_context(
*,
session_id: str,
agent,
request_id: str | None = None,
trigger_source: str | None = "frontend_chat",
locale: str | None = None,
scope: str = "chat_turn",
) -> dict[str, Any]:
"""
为通用 Dify Agent 构建最小 Runtime Context。
核心逻辑:仅注入 platform/session 锚点与 generic domain 摘要,
不附带 refs/reference_context,适用于纯 Q&A 或知识库类 Agent。
Args:
session_id: HXOPS 会话 ID;为空时返回空 dict。
agent: 当前对话 Agent,读取 extra_config.agent_code/runtime_context_summary。
request_id: 本次请求追踪 ID。
trigger_source: 触发来源,默认 frontend_chat。
locale: 用户语言。
scope: 上下文作用域,默认 chat_turn。
Returns:
通用 agent_runtime_context 字典;session_id 为空时返回空 dict。
"""
return build_agent_runtime_context(
agent_code=resolve_agent_code(agent),
scope=scope,
session_id=session_id,
request_id=request_id,
trigger_source=trigger_source,
locale=locale,
domain={
"type": "generic",
"summary": _resolve_domain_summary(agent),
},
)
def build_generic_dify_inputs(
*,
session_id: str,
agent,
request_id: str | None = None,
trigger_source: str | None = "frontend_chat",
locale: str | None = None,
scope: str = "chat_turn",
) -> dict[str, str]:
"""
构建通用 Agent 的 Dify Start inputs。
核心逻辑:统一把最小 Runtime Context 序列化到 agent_runtime_context,
让未接入专用 adapter 的 Agent 也能消费平台会话快照。
Args:
session_id: HXOPS 会话 ID。
agent: 当前对话 Agent。
request_id: 本次请求追踪 ID。
trigger_source: 触发来源。
locale: 用户语言。
scope: 上下文作用域。
Returns:
仅含 agent_runtime_context 的 inputs;session_id 为空时返回空 dict。
"""
runtime_context = build_generic_runtime_context(
session_id=session_id,
agent=agent,
request_id=request_id,
trigger_source=trigger_source,
locale=locale,
scope=scope,
)
return build_dify_inputs(runtime_context)
@@ -0,0 +1,186 @@
"""
backend/app/services/agent_runtime_context/builder.py
用途:构建并序列化 HXOPS 平台统一的 agent_runtime_context。
依赖:schema 协议常量、policy 裁剪策略、json/uuid/time 标准库。
逻辑:聊天入口或业务 adapter 调用本模块生成每次 Runtime 调用前的现场 snapshot,再作为 Dify Start 变量注入。
"""
from __future__ import annotations
import json
import time
from typing import Any
from uuid import uuid4
from app.services.agent_runtime_context.policy import (
MAX_CONTEXT_JSON_CHARS,
normalize_domain,
normalize_reference_context,
normalize_refs,
)
from app.services.agent_runtime_context.schema import (
AGENT_RUNTIME_CONTEXT_INPUT,
AGENT_RUNTIME_CONTEXT_SCHEMA_VERSION,
AgentRuntimeContext,
)
def generate_context_id() -> str:
"""
生成单次 Runtime 上下文编号。
核心逻辑:使用毫秒时间戳与短 UUID,便于日志检索且不暴露业务编号。
Returns:
形如 ctx_20260702094300000_ab12cd34 的上下文编号。
"""
timestamp_ms = int(time.time() * 1000)
return f"ctx_{timestamp_ms}_{uuid4().hex[:8]}"
def _normalize_platform(
*,
session_id: str,
parent_session_id: str | None = None,
request_id: str | None = None,
trigger_source: str | None = None,
locale: str | None = None,
) -> dict[str, str]:
"""
构建平台侧上下文片段。
核心逻辑:session_id 为必填锚点,其余字段有值才输出,避免空字段误导 Runtime。
Args:
session_id: HXOPS ChatSession.session_id。
parent_session_id: 后台 run 所属的用户主会话;缺省时等于 session_id。
request_id: 本次请求追踪 ID。
trigger_source: 触发来源,如 frontend_chat/backend_orchestrator。
locale: 用户语言。
Returns:
平台上下文字典。
"""
normalized_session_id = str(session_id or "").strip()
platform = {"session_id": normalized_session_id}
normalized_parent = str(parent_session_id or "").strip()
if normalized_parent:
platform["parent_session_id"] = normalized_parent
elif normalized_session_id:
platform["parent_session_id"] = normalized_session_id
normalized_request_id = str(request_id or "").strip()
normalized_trigger_source = str(trigger_source or "").strip()
normalized_locale = str(locale or "").strip()
if normalized_request_id:
platform["request_id"] = normalized_request_id
if normalized_trigger_source:
platform["trigger_source"] = normalized_trigger_source
if normalized_locale:
platform["locale"] = normalized_locale
return platform
def build_agent_runtime_context(
*,
agent_code: str = "generic",
scope: str = "chat_turn",
session_id: str,
parent_session_id: str | None = None,
request_id: str | None = None,
trigger_source: str | None = None,
locale: str | None = None,
refs: dict[str, Any] | None = None,
domain: dict[str, Any] | None = None,
reference_context: dict[str, Any] | None = None,
context_id: str | None = None,
) -> AgentRuntimeContext:
"""
构建单次 Runtime 调用的上下文 snapshot。
核心逻辑:校验 session 锚点,填充平台字段,裁剪 refs/domain/reference_context,并生成 context_id 供审计追踪。
Args:
agent_code: 稳定 Agent 标识,禁止使用展示名称。
scope: 上下文作用域,如 chat_turn/task_run。
session_id: HXOPS 本地会话 ID。
parent_session_id: 后台任务所属主会话 ID。
request_id: 本次请求 ID。
trigger_source: 触发来源。
locale: 用户语言。
refs: 业务对象锚点字典。
domain: 业务域摘要与状态提示。
reference_context: 短期指代治理上下文。
context_id: 外部指定的上下文编号;通常留空自动生成。
Returns:
agent_runtime_context 字典;session_id 为空时返回空 dict。
"""
normalized_session_id = str(session_id or "").strip()
if not normalized_session_id:
return {}
context: AgentRuntimeContext = {
"schema_version": AGENT_RUNTIME_CONTEXT_SCHEMA_VERSION,
"context_id": str(context_id or "").strip() or generate_context_id(),
"agent_code": str(agent_code or "generic").strip() or "generic",
"scope": str(scope or "chat_turn").strip() or "chat_turn",
"platform": _normalize_platform(
session_id=normalized_session_id,
parent_session_id=parent_session_id,
request_id=request_id,
trigger_source=trigger_source,
locale=locale,
),
"refs": normalize_refs(refs),
}
normalized_domain = normalize_domain(domain)
if normalized_domain:
context["domain"] = normalized_domain
normalized_reference_context = normalize_reference_context(reference_context)
if normalized_reference_context:
context["reference_context"] = normalized_reference_context
return context
def serialize_for_dify(context: dict[str, Any]) -> str:
"""
将上下文序列化为 Dify Start 节点可稳定接收的 JSON 字符串。
核心逻辑:使用紧凑 JSON,超过平台限制时抛 ValueError,避免悄悄截断成非法 JSON。
Args:
context: agent_runtime_context 字典。
Returns:
UTF-8 JSON 字符串。
Raises:
ValueError: 上下文序列化后超过长度上限。
"""
payload = json.dumps(context or {}, ensure_ascii=False, separators=(",", ":"))
if len(payload) > MAX_CONTEXT_JSON_CHARS:
raise ValueError("agent_runtime_context exceeds max serialized length")
return payload
def build_dify_inputs(
context: dict[str, Any],
) -> dict[str, Any]:
"""
构建传给 Dify 的 inputs。
核心逻辑:统一只输出 agent_runtime_context JSON 字符串,避免 Start 协议出现多套上下文字段。
Args:
context: agent_runtime_context 字典。
Returns:
Dify inputs 字典。
"""
if not context:
return {}
return {AGENT_RUNTIME_CONTEXT_INPUT: serialize_for_dify(context)}
@@ -0,0 +1,80 @@
"""
backend/app/services/agent_runtime_context/dify_inputs.py
用途:提供聊天入口构建 Dify inputs 的统一分发入口。
依赖:generic adapter、file_check_tools.dify_inputs、shipping_notice.dify_inputs。
逻辑:chat.py 在调用 DifyService.stream_chat 前只调用本模块;本模块按 Agent 类型分发到
shipping_notice / file_check / generic adapter,平台层只暴露会话级公共参数,领域提示由 adapter_hints 透传。
"""
from __future__ import annotations
from typing import Any
from app.services.agent_runtime_context.adapters.generic import build_generic_dify_inputs
from app.services.file_check_tools.agent_resolver import (
agent_declares_file_check_progress,
is_file_check_chat_agent,
)
from app.services.file_check_tools.dify_inputs import build_file_check_dify_inputs
from app.services.shipping_notice.dify_inputs import (
build_dify_chat_inputs as build_shipping_notice_dify_inputs,
is_shipping_notice_chat_agent,
)
def build_chat_dify_inputs(
agent,
*,
session_id: str,
request_id: str | None = None,
trigger_source: str | None = "frontend_chat",
locale: str | None = None,
adapter_hints: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""
统一构建聊天 Dify inputs。
核心逻辑:优先命中 shipping_notice 专用 adapter;其次复用 file_check 既有 task_id 注入;
其余 Agent 一律走 generic adapter,让所有 Dify Chatflow 至少拿到 platform/session 快照。
业务域专用提示不出现在平台签名中,而是由 adapter_hints 交给对应 adapter 自行消费。
Args:
agent: 当前对话 Agent。
session_id: HXOPS 会话 ID;为空时直接返回空 dict。
request_id: 本次请求追踪 ID。
trigger_source: 触发来源,默认 frontend_chat。
locale: 用户语言。
adapter_hints: 领域 adapter 可选读取的提示字典;平台层不感知其内部业务字段。
Returns:
Dify inputs 字典;session_id 为空时返回空 dict。
"""
normalized_session_id = str(session_id or "").strip()
if not normalized_session_id:
return {}
normalized_adapter_hints = adapter_hints if isinstance(adapter_hints, dict) else {}
if is_shipping_notice_chat_agent(agent):
shipping_hints = normalized_adapter_hints.get("shipping_notice")
shipping_hints = shipping_hints if isinstance(shipping_hints, dict) else {}
return build_shipping_notice_dify_inputs(
normalized_session_id,
task_id=shipping_hints.get("task_id"),
batch_no=shipping_hints.get("batch_no"),
trigger_source=trigger_source,
request_id=request_id,
locale=locale,
)
if agent_declares_file_check_progress(agent) or is_file_check_chat_agent(agent):
return build_file_check_dify_inputs(agent, required=True)
return build_generic_dify_inputs(
session_id=normalized_session_id,
agent=agent,
request_id=request_id,
trigger_source=trigger_source,
locale=locale,
)
@@ -0,0 +1,115 @@
"""
backend/app/services/agent_runtime_context/openapi_spec.py
用途:构建 agent_runtime_context Tool API 的 OpenAPI 3.0 文档,供 Dify 导入。
依赖:parser.ALLOWED_PARSE_PATHS。
逻辑:api/agent_runtime_context_tools.py 调用本模块生成 JSON 文档,Dify 通过 parse 工具安全读取上下文字段。
"""
from __future__ import annotations
from typing import Any
from app.services.agent_runtime_context.parser import ALLOWED_PARSE_PATHS, MAX_PARSE_PATHS
def build_agent_runtime_context_openapi_spec(base_url: str) -> dict[str, Any]:
"""
构建 Dify 导入用 OpenAPI 文档。
核心逻辑:仅暴露 parse_agent_runtime_context 一个只读工具,不包含任何业务推进接口。
Args:
base_url: HXOPS 后端公开 Base URL。
Returns:
OpenAPI 3.0 字典。
"""
server = str(base_url or "").strip().rstrip("/")
if not server.endswith("/api/agent-runtime-context"):
server = f"{server}/api/agent-runtime-context" if server else "/api/agent-runtime-context"
return {
"openapi": "3.0.0",
"info": {
"title": "HXOPS Agent Runtime Context Tools",
"version": "1.0.0",
"description": (
"HXOPS 平台运行态上下文只读解析工具。"
"Dify 应在需要读取 session、task、batch、run purpose、state_hint 或模糊指代线索时调用本工具;"
"遇到“继续”“刚才那个”“上一个失败的”等表达时,应优先读取 reference_context。"
"若只需要 focus id、last action 或 failure reason,可优先读取 reference_context 的细粒度字段,减少上下文判断分支。"
"若 reference_context 返回多个 candidates(多候选),不要猜测,应追问用户或调用业务 Tool 再确认。"
"reference_context 与 state_hint 都只是提示,不是业务事实源,也不能替代 HXOPS 状态机。"
"推进业务状态必须调用对应业务 Tool,不能依据上下文直接宣布完成、上传成功或任务关闭。"
"鉴权:Authorization Bearer 或 X-Integration-Key。"
),
},
"servers": [{"url": server}],
"paths": {
"/tools/parse": {
"post": {
"operationId": "parse_agent_runtime_context",
"summary": "解析 HXOPS agent_runtime_context 中的白名单字段",
"description": (
"只读解析工具;agent_runtime_context 应为 Dify Start 节点中的 JSON 字符串。"
f"paths 最多 {MAX_PARSE_PATHS} 个,且必须属于 allowed_paths。"
"推荐优先读取 reference_context.focus_object.id、reference_context.last_action_target.action、"
"reference_context.last_failed_target.reason 等细粒度字段,降低提示词中的对象拆解成本。"
"模糊指代建议优先读取 reference_context;若拿到多个 candidates(多候选),必须追问或回到业务 Tool 校验,禁止自行猜测推进。"
"reference_context/state_hint 仅用于理解当前现场,不能替代状态机事实,更不能据此直接推进业务或宣布完成。"
),
"parameters": [],
"requestBody": {
"required": True,
"content": {
"application/json": {
"schema": {
"type": "object",
"required": ["agent_runtime_context", "paths"],
"properties": {
"agent_runtime_context": {
"type": "string",
"description": (
"Dify Start 变量 agent_runtime_context 的 JSON 字符串。"
"其中 reference_context 仅用于辅助理解当前现场,不可替代 HXOPS 业务事实源。"
),
},
"paths": {
"type": "array",
"description": "需要读取的字段路径。",
"maxItems": MAX_PARSE_PATHS,
"items": {
"type": "string",
"enum": sorted(ALLOWED_PARSE_PATHS),
},
},
},
}
}
},
},
"responses": {
"200": {
"description": "Parse response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"status": {"type": "string", "enum": ["ok"]},
"data": {"type": "object", "additionalProperties": True},
"missing": {
"type": "array",
"items": {"type": "string"},
},
},
}
}
},
}
},
}
}
},
}
@@ -0,0 +1,204 @@
"""
backend/app/services/agent_runtime_context/parser.py
用途:解析 Dify 传回的 agent_runtime_context JSON 字符串,并按白名单路径取值。
依赖:json 标准库、agent_runtime_context.schema/policy、AppError 体系。
逻辑:Tool API 调用本模块只读解析上下文;不执行表达式、不访问数据库、不推进任何业务状态。
"""
from __future__ import annotations
import json
from typing import Any
from app.core.errors import ValidationError
from app.services.agent_runtime_context.policy import MAX_CONTEXT_JSON_CHARS
from app.services.agent_runtime_context.schema import AGENT_RUNTIME_CONTEXT_SCHEMA_VERSION
MAX_PARSE_PATHS = 20
ALLOWED_PARSE_PATHS: frozenset[str] = frozenset(
{
"schema_version",
"context_id",
"agent_code",
"scope",
"platform.session_id",
"platform.parent_session_id",
"platform.request_id",
"platform.locale",
"platform.trigger_source",
"refs.batch_no",
"refs.task_no",
"refs.run_purpose",
"refs.file_name",
"refs.schedule_task_id",
"domain.type",
"domain.summary",
"domain.state_hint.batch_no",
"domain.state_hint.focus_task_no",
"domain.state_hint.current_step",
"domain.state_hint.status",
"domain.state_hint.review_status",
"domain.state_hint.match_status",
"domain.state_hint.pending_human_reason",
"domain.state_hint.upload_status",
"reference_context.recent_activity_summary",
"reference_context.focus_object",
"reference_context.focus_object.type",
"reference_context.focus_object.id",
"reference_context.last_action_target",
"reference_context.last_action_target.action",
"reference_context.last_action_target.id",
"reference_context.last_failed_target",
"reference_context.last_failed_target.reason",
"reference_context.last_failed_target.id",
"reference_context.candidates",
}
)
def _normalize_context(raw_context: str | dict[str, Any]) -> dict[str, Any]:
"""
解析并校验 agent_runtime_context。
核心逻辑:优先支持 Dify Paragraph 传入的 JSON 字符串,也兼容测试/内部调用传 object。
Args:
raw_context: JSON 字符串或上下文字典。
Returns:
agent_runtime_context 字典。
Raises:
ValidationError: 空上下文、超长、JSON 非法或协议版本不匹配。
"""
if isinstance(raw_context, dict):
context = raw_context
else:
serialized = str(raw_context or "").strip()
if not serialized:
raise ValidationError("agent_runtime_context_required")
if len(serialized) > MAX_CONTEXT_JSON_CHARS:
raise ValidationError(
"agent_runtime_context_too_large",
details={"max_chars": MAX_CONTEXT_JSON_CHARS},
)
try:
context = json.loads(serialized)
except json.JSONDecodeError as exc:
raise ValidationError("agent_runtime_context_invalid_json", details={"error": str(exc)}) from exc
if not isinstance(context, dict):
raise ValidationError("agent_runtime_context_must_be_object")
schema_version = str(context.get("schema_version") or "").strip()
if schema_version != AGENT_RUNTIME_CONTEXT_SCHEMA_VERSION:
raise ValidationError(
"agent_runtime_context_schema_version_unsupported",
details={
"expected": AGENT_RUNTIME_CONTEXT_SCHEMA_VERSION,
"actual": schema_version,
},
)
return context
def _normalize_paths(paths: Any) -> list[str]:
"""
校验并规范化字段路径列表。
核心逻辑:限制路径数量且只允许白名单字段,避免 Dify 读取未授权内部上下文片段。
Args:
paths: 请求中的 paths 字段。
Returns:
去重后的路径列表。
Raises:
ValidationError: paths 非列表、为空、超限或包含非白名单路径。
"""
if not isinstance(paths, list) or not paths:
raise ValidationError("paths_required")
if len(paths) > MAX_PARSE_PATHS:
raise ValidationError("paths_too_many", details={"max_paths": MAX_PARSE_PATHS})
normalized: list[str] = []
seen: set[str] = set()
rejected: list[str] = []
for item in paths:
path = str(item or "").strip()
if not path:
continue
if path not in ALLOWED_PARSE_PATHS:
rejected.append(path)
continue
if path not in seen:
normalized.append(path)
seen.add(path)
if rejected:
raise ValidationError("paths_not_allowed", details={"paths": rejected})
if not normalized:
raise ValidationError("paths_required")
return normalized
def _get_path_value(context: dict[str, Any], path: str) -> tuple[bool, Any]:
"""
按点路径从上下文读取值。
核心逻辑:只做 dict key 逐层访问,不支持数组下标、通配符或表达式。
Args:
context: agent_runtime_context 字典。
path: 白名单字段路径。
Returns:
(是否存在, 值)。
"""
cursor: Any = context
for part in path.split("."):
if not isinstance(cursor, dict) or part not in cursor:
return False, None
cursor = cursor[part]
return True, cursor
def parse_agent_runtime_context(raw_context: str | dict[str, Any], paths: Any) -> dict[str, Any]:
"""
解析 agent_runtime_context 并返回指定字段。
【AI 触发时机】:Dify 画布需要读取当前 HXOPS 会话、任务、批次、执行目的或状态提示时调用;
不用于推进任务状态,推进必须调用对应业务 Tool。
核心逻辑:校验协议版本与路径白名单,逐路径读取字段,缺失字段放入 missing。
Args:
raw_context: Dify Start 变量中的 agent_runtime_context JSON 字符串。
paths: 需要读取的白名单路径列表。
Returns:
{"status": "ok", "data": {...}, "missing": [...]}。
Raises:
ValidationError: 请求体、上下文或路径非法。
"""
context = _normalize_context(raw_context)
normalized_paths = _normalize_paths(paths)
data: dict[str, Any] = {}
missing: list[str] = []
for path in normalized_paths:
exists, value = _get_path_value(context, path)
if exists:
data[path] = value
else:
missing.append(path)
return {"status": "ok", "data": data, "missing": missing}
__all__ = [
"ALLOWED_PARSE_PATHS",
"MAX_PARSE_PATHS",
"parse_agent_runtime_context",
]
@@ -0,0 +1,103 @@
"""
backend/app/services/agent_runtime_context/policy.py
用途:集中管理 agent_runtime_context 的长度、字段与安全裁剪策略。
依赖:schema 中的平台协议常量;不访问数据库或业务服务。
逻辑:builder 在输出给 Dify 前调用本模块,确保上下文短小、稳定且不会把大段历史塞进 Runtime。
"""
from __future__ import annotations
from typing import Any
MAX_CONTEXT_JSON_CHARS = 8192
MAX_DOMAIN_SUMMARY_CHARS = 500
MAX_RECENT_ACTIVITY_SUMMARY_CHARS = 500
MAX_REF_VALUE_CHARS = 200
MAX_REFS = 30
def truncate_text(value: Any, max_chars: int) -> str:
"""
将任意输入规范化为短文本。
核心逻辑:strip 后按字符数截断,避免上下文摘要或 ref 值撑爆 Dify Start 变量。
Args:
value: 待规范化的文本或可转字符串对象。
max_chars: 最大保留字符数。
Returns:
规范化后的字符串;空值返回空字符串。
"""
normalized = str(value or "").strip()
if max_chars <= 0 or len(normalized) <= max_chars:
return normalized
return normalized[:max_chars]
def normalize_refs(refs: dict[str, Any] | None) -> dict[str, str]:
"""
规范化业务对象锚点。
核心逻辑:保留首个有效 key/value,裁剪 value 长度,并限制总数量,防止业务 adapter 注入过长对象。
Args:
refs: 业务 adapter 传入的 refs 字典。
Returns:
字段名和值均为非空字符串的 refs 字典。
"""
normalized: dict[str, str] = {}
for raw_key, raw_value in (refs or {}).items():
key = str(raw_key or "").strip()
value = truncate_text(raw_value, MAX_REF_VALUE_CHARS)
if not key or not value or key in normalized:
continue
normalized[key] = value
if len(normalized) >= MAX_REFS:
break
return normalized
def normalize_domain(domain: dict[str, Any] | None) -> dict[str, Any]:
"""
规范化领域上下文。
核心逻辑:只裁剪已知长文本字段,其余结构保持给业务 adapter 自主表达。
Args:
domain: 业务域上下文片段。
Returns:
裁剪后的领域上下文字典。
"""
if not domain:
return {}
normalized = dict(domain)
if "summary" in normalized:
normalized["summary"] = truncate_text(normalized.get("summary"), MAX_DOMAIN_SUMMARY_CHARS)
return normalized
def normalize_reference_context(reference_context: dict[str, Any] | None) -> dict[str, Any]:
"""
规范化短期指代上下文。
核心逻辑:限制 recent_activity_summary 长度,保留 focus/candidates 等结构化候选。
Args:
reference_context: 指代治理上下文。
Returns:
裁剪后的 reference_context 字典。
"""
if not reference_context:
return {}
normalized = dict(reference_context)
if "recent_activity_summary" in normalized:
normalized["recent_activity_summary"] = truncate_text(
normalized.get("recent_activity_summary"),
MAX_RECENT_ACTIVITY_SUMMARY_CHARS,
)
return normalized
@@ -0,0 +1,157 @@
"""
backend/app/services/agent_runtime_context/reference.py
用途:构建平台级 reference_context,给外部 Runtime 提供短期指代解析线索。
依赖:agent_runtime_context.policy、schema;不依赖具体业务模型。
逻辑:业务 adapter 先把 focus/last_action/candidates 等抽象成对象引用,再由本模块统一裁剪、去重和限流。
"""
from __future__ import annotations
from typing import Any
from app.services.agent_runtime_context.policy import MAX_REF_VALUE_CHARS, normalize_reference_context, truncate_text
from app.services.agent_runtime_context.schema import ReferenceContext
MAX_REFERENCE_OBJECT_TYPE_CHARS = 64
MAX_REFERENCE_KEY_CHARS = 64
MAX_REFERENCE_CANDIDATES = 5
def build_object_ref(type_: str, id_: str, **extra: Any) -> dict[str, str]:
"""
构建 reference_context 中的对象引用。
核心逻辑:统一输出 type/id,并裁剪 action/reason/label 等扩展字段,避免业务 adapter 各自拼装不同口径。
Args:
type_: 对象类型,如 task/batch。
id_: 对象稳定标识,如 SN-001。
**extra: 可选扩展字段,例如 action/reason/label。
Returns:
规范化后的对象引用;type 或 id 为空时返回空 dict。
"""
normalized_type = truncate_text(type_, MAX_REFERENCE_OBJECT_TYPE_CHARS)
normalized_id = truncate_text(id_, MAX_REF_VALUE_CHARS)
if not normalized_type or not normalized_id:
return {}
object_ref: dict[str, str] = {
"type": normalized_type,
"id": normalized_id,
}
for raw_key, raw_value in extra.items():
key = truncate_text(raw_key, MAX_REFERENCE_KEY_CHARS)
if not key or key in object_ref or raw_value is None:
continue
value = truncate_text(raw_value, MAX_REF_VALUE_CHARS)
if not value:
continue
object_ref[key] = value
return object_ref
def _normalize_object_ref(value: dict[str, Any] | None) -> dict[str, str]:
"""
规范化单个对象引用。
核心逻辑:兼容业务 adapter 传入的普通 dict,统一转成 build_object_ref 输出结构。
Args:
value: 原始对象引用。
Returns:
规范化后的对象引用;非法输入返回空 dict。
"""
if not isinstance(value, dict):
return {}
extra = {key: item for key, item in value.items() if key not in {"type", "type_", "id"}}
return build_object_ref(
str(value.get("type") or value.get("type_") or ""),
str(value.get("id") or ""),
**extra,
)
def _normalize_candidates(candidates: list[dict[str, Any]] | None) -> list[dict[str, str]]:
"""
规范化候选对象列表。
核心逻辑:只保留前几个有效候选,按 type/id 去重,避免把整批对象全塞给 Dify。
Args:
candidates: 候选对象引用列表。
Returns:
去重并限量后的候选列表。
"""
normalized: list[dict[str, str]] = []
seen: set[tuple[str, str]] = set()
for item in candidates or []:
candidate = _normalize_object_ref(item)
if not candidate:
continue
dedupe_key = (candidate["type"], candidate["id"])
if dedupe_key in seen:
continue
normalized.append(candidate)
seen.add(dedupe_key)
if len(normalized) >= MAX_REFERENCE_CANDIDATES:
break
return normalized
def build_reference_context(
*,
recent_activity_summary: str | None = None,
focus_object: dict[str, Any] | None = None,
last_action_target: dict[str, Any] | None = None,
last_failed_target: dict[str, Any] | None = None,
candidates: list[dict[str, Any]] | None = None,
) -> ReferenceContext:
"""
构建平台统一的 reference_context。
核心逻辑:收敛业务 adapter 提供的短期指代线索,限制候选数量并裁剪摘要长度,保证输出小而稳定。
Args:
recent_activity_summary: 最近活动摘要。
focus_object: 当前焦点对象。
last_action_target: 最近一次动作作用对象。
last_failed_target: 最近一次失败/异常对象。
candidates: 模糊指代候选对象列表。
Returns:
规范化后的 reference_context;所有字段都为空时返回空 dict。
"""
reference_context: ReferenceContext = {}
summary = str(recent_activity_summary or "").strip()
if summary:
reference_context["recent_activity_summary"] = summary
normalized_focus = _normalize_object_ref(focus_object)
if normalized_focus:
reference_context["focus_object"] = normalized_focus
normalized_last_action = _normalize_object_ref(last_action_target)
if normalized_last_action:
reference_context["last_action_target"] = normalized_last_action
normalized_last_failed = _normalize_object_ref(last_failed_target)
if normalized_last_failed:
reference_context["last_failed_target"] = normalized_last_failed
normalized_candidates = _normalize_candidates(candidates)
if normalized_candidates:
reference_context["candidates"] = normalized_candidates
return normalize_reference_context(reference_context)
__all__ = [
"MAX_REFERENCE_CANDIDATES",
"build_object_ref",
"build_reference_context",
]
@@ -0,0 +1,75 @@
"""
backend/app/services/agent_runtime_context/schema.py
用途:定义 HXOPS 传递给外部 Agent Runtime 的统一上下文协议常量与类型。
依赖:typing 标准库;不依赖具体业务域,避免平台协议与 shipping/file-check 强耦合。
逻辑:builder/policy/parser 等模块引用本文件的字段名和类型,业务 adapter 只填充 refs/domain 差异。
"""
from __future__ import annotations
from typing import Any, Literal, TypedDict
AGENT_RUNTIME_CONTEXT_INPUT = "agent_runtime_context"
AGENT_RUNTIME_CONTEXT_SCHEMA_VERSION = "1"
AgentCode = Literal["generic", "shipping_notice", "file_check"]
ContextScope = Literal["chat_turn", "task_run", "batch_summary"]
class PlatformContext(TypedDict, total=False):
"""
描述 HXOPS 平台侧会话与请求锚点。
核心逻辑:只放平台身份与请求追踪字段,业务状态放入 refs/domain。
"""
session_id: str
parent_session_id: str
request_id: str
locale: str
trigger_source: str
class DomainContext(TypedDict, total=False):
"""
描述业务域运行态摘要。
核心逻辑:由各业务 adapter 填充 summary/state_hint,供 Dify 理解现场但不替代 HXOPS 状态机。
"""
type: str
summary: str
state_hint: dict[str, Any]
available_actions_hint: list[dict[str, Any]]
class ReferenceContext(TypedDict, total=False):
"""
描述模糊指代解析所需的短期上下文。
核心逻辑:承载 recent_activity_summary/focus_object 等摘要,不传全量 ChatLog。
"""
recent_activity_summary: str
focus_object: dict[str, Any]
last_action_target: dict[str, Any]
last_failed_target: dict[str, Any]
candidates: list[dict[str, Any]]
class AgentRuntimeContext(TypedDict, total=False):
"""
HXOPS Agent Runtime Context 协议对象。
核心逻辑:每次调用外部 Runtime 前重新生成 snapshot,Dify/其他 Runtime 只读取,不作为业务事实源。
"""
schema_version: str
context_id: str
agent_code: str
scope: str
platform: PlatformContext
refs: dict[str, str]
domain: DomainContext
reference_context: ReferenceContext
@@ -1,77 +0,0 @@
"""
backend/app/services/chat/hxops_context.py
用途:构建 HXOPS -> Dify 的平台统一上下文注入协议。
依赖:无业务域依赖,仅提供平台级上下文结构与 refs 规范化工具。
逻辑:由聊天入口、后台编排器或各 Agent 适配层调用本模块,统一生成 hxops_context,
避免各业务目录重复定义 Dify Start 输入协议。
"""
from __future__ import annotations
from typing import Any
HXOPS_CONTEXT_INPUT = "hxops_context"
HXOPS_CONTEXT_SCHEMA_VERSION = "1"
def build_ref(field: str, value: str | None) -> dict[str, str] | None:
"""构建单个业务对象引用;缺值时返回 None。"""
normalized_field = str(field or "").strip()
normalized_value = str(value or "").strip()
if not normalized_field or not normalized_value:
return None
return {"field": normalized_field, "value": normalized_value}
def build_hxops_context(
*,
session_id: str,
request_id: str | None = None,
trigger_source: str | None = None,
locale: str | None = None,
refs: list[dict[str, str] | None] | None = None,
) -> dict[str, Any]:
"""
构建平台统一的 hxops_context。
设计约束:
- 只注入平台基础信息与当前已知对象锚点
- 不注入 query/files 等 Dify 原生输入
- 不注入 checkpoint/stage 等运行态状态
"""
normalized_session_id = str(session_id or "").strip()
if not normalized_session_id:
return {}
request_payload: dict[str, str] = {}
normalized_request_id = str(request_id or "").strip()
normalized_trigger_source = str(trigger_source or "").strip()
normalized_locale = str(locale or "").strip()
if normalized_request_id:
request_payload["id"] = normalized_request_id
if normalized_trigger_source:
request_payload["trigger_source"] = normalized_trigger_source
if normalized_locale:
request_payload["locale"] = normalized_locale
normalized_refs: list[dict[str, str]] = []
seen_fields: set[str] = set()
for item in refs or []:
if not item:
continue
field = str(item.get("field") or "").strip()
value = str(item.get("value") or "").strip()
if not field or not value or field in seen_fields:
continue
normalized_refs.append({"field": field, "value": value})
seen_fields.add(field)
payload: dict[str, Any] = {
"schema_version": HXOPS_CONTEXT_SCHEMA_VERSION,
"session": {"id": normalized_session_id},
"request": request_payload,
"refs": normalized_refs,
}
return payload
+232 -63
View File
@@ -324,6 +324,116 @@ class DifyService:
}
return data
@staticmethod
def _classify_workflow_request_exception(exc: Exception) -> tuple[str, bool]:
"""
将 Workflow HTTP/网络异常归类为 error_type,并判断是否可重试。
502/503/504 与连接/读超时视为可恢复;400/401/403 不重试。
"""
if isinstance(exc, requests.exceptions.ConnectTimeout):
return "connect_timeout", True
if isinstance(exc, requests.exceptions.ReadTimeout):
return "read_timeout", True
if isinstance(exc, requests.exceptions.ConnectionError):
return "connection_error", True
if isinstance(exc, requests.exceptions.HTTPError):
status = int(getattr(getattr(exc, "response", None), "status_code", 0) or 0)
if status in (502, 503, 504):
return f"http_{status}", True
if status in (400, 401, 403):
return f"http_{status}", False
return f"http_{status}", False
return "request_error", False
@staticmethod
def _attach_workflow_reliability_meta(
result: dict[str, Any],
*,
poll_used: bool = False,
retry_count: int = 0,
error_type: str | None = None,
workflow_run_id: str | None = None,
) -> dict[str, Any]:
"""在 Dify Workflow 响应上附加网关侧可靠性元信息(poll/重试/错误类型)。"""
out = dict(result) if isinstance(result, dict) else {}
if workflow_run_id and not out.get("workflow_run_id"):
out["workflow_run_id"] = workflow_run_id
out["_workflow_poll_used"] = bool(poll_used)
out["_workflow_retry_count"] = max(0, int(retry_count))
if error_type:
out["_workflow_error_type"] = error_type
return out
@staticmethod
def _consume_workflow_stream(
*,
url: str,
headers: dict[str, str],
payload: dict[str, Any],
timeout: tuple[int, int],
state: dict[str, Any],
) -> dict[str, Any]:
"""
执行一次 Workflow streaming POST 并消费 SSE 直至 workflow_finished。
state 在解析过程中写入 workflow_run_id / result,供断连后补偿使用。
"""
result: dict[str, Any] = {}
with requests.post(url, headers=headers, json=payload, stream=True, timeout=timeout) as resp:
if not resp.ok:
body = resp.text[:2000]
if current_app:
current_app.logger.error(
"[workflow-streaming] dify error status=%s url=%s body=%s",
resp.status_code, url, body,
)
resp.raise_for_status()
for line in resp.iter_lines(decode_unicode=True):
if not line:
continue
if not line.startswith("data:"):
continue
raw = line[len("data:"):].strip()
if not raw:
continue
try:
evt = json.loads(raw)
except json.JSONDecodeError:
continue
event_type = evt.get("event", "")
if event_type == "workflow_started":
run_id = (evt.get("data") or {}).get("workflow_run_id")
state["workflow_run_id"] = run_id
if current_app:
current_app.logger.info(
"[workflow-streaming] started run_id=%s",
run_id,
)
elif event_type == "workflow_finished":
result = evt.get("data") or {}
state["result"] = result
if current_app:
current_app.logger.info(
"[workflow-streaming] finished status=%s error=%s",
result.get("status"),
result.get("error"),
)
elif event_type == "error":
err_msg = evt.get("message") or str(evt)
if current_app:
current_app.logger.error(
"[workflow-streaming] dify stream error: %s",
err_msg,
)
raise RuntimeError(f"Dify workflow error: {err_msg}")
return result
@staticmethod
def run_workflow_streaming(
*,
@@ -332,6 +442,10 @@ class DifyService:
user: str = "system",
timeout: tuple[int, int] = (5, 300),
) -> dict[str, Any]:
"""
调用 Dify Workflow(streaming),并在断连/超时时优先 poll 补偿结果。
对可恢复网络错误最多重试 1 次;返回体附带 _workflow_* 可靠性元信息。
"""
base_url = agent.api_base_url if getattr(agent, "api_base_url", None) else Config.DIFY_API_BASE
url = DifyService._build_workflow_url(base_url)
@@ -344,6 +458,12 @@ class DifyService:
"response_mode": "streaming",
"user": str(user or "system"),
}
max_wait = timeout[1] if isinstance(timeout, tuple) else 300
max_attempts = 2
retry_count = 0
poll_used = False
last_error_type: str | None = None
last_workflow_run_id: str | None = None
if current_app:
current_app.logger.info(
@@ -354,86 +474,135 @@ class DifyService:
)
result: dict[str, Any] = {}
workflow_run_id: str | None = None
stream_state: dict[str, Any] = {"workflow_run_id": None, "result": {}}
try:
with requests.post(url, headers=headers, json=payload, stream=True, timeout=timeout) as resp:
if not resp.ok:
body = resp.text[:2000]
for attempt in range(max_attempts):
try:
result = DifyService._consume_workflow_stream(
url=url,
headers=headers,
payload=payload,
timeout=timeout,
state=stream_state,
)
workflow_run_id = stream_state.get("workflow_run_id")
if workflow_run_id:
last_workflow_run_id = workflow_run_id
# [STEP] 连接正常结束但未收到 workflow_finished 时,用 poll 补偿最终结果
if not result and workflow_run_id:
poll_used = True
if current_app:
current_app.logger.error(
"[workflow-streaming] dify error status=%s url=%s body=%s",
resp.status_code, url, body,
current_app.logger.warning(
"[workflow-streaming] stream closed without finished event, polling run_id=%s",
workflow_run_id,
)
resp.raise_for_status()
result = DifyService._poll_workflow_result(
agent=agent,
workflow_run_id=workflow_run_id,
max_wait=max_wait,
)
poll_error_type = None if result else "poll_timeout"
return DifyService._attach_workflow_reliability_meta(
result,
poll_used=True,
retry_count=retry_count,
error_type=poll_error_type or "stream_closed_early",
workflow_run_id=workflow_run_id,
)
for line in resp.iter_lines(decode_unicode=True):
if not line:
continue
if not line.startswith("data:"):
continue
raw = line[len("data:"):].strip()
if not raw:
continue
try:
evt = json.loads(raw)
except json.JSONDecodeError:
continue
event_type = evt.get("event", "")
if event_type == "workflow_started":
workflow_run_id = (evt.get("data") or {}).get("workflow_run_id")
if current_app:
current_app.logger.info(
"[workflow-streaming] started run_id=%s",
workflow_run_id,
)
elif event_type == "workflow_finished":
result = evt.get("data") or {}
if current_app:
current_app.logger.info(
"[workflow-streaming] finished status=%s error=%s",
result.get("status"),
result.get("error"),
)
elif event_type == "error":
err_msg = evt.get("message") or str(evt)
if current_app:
current_app.logger.error(
"[workflow-streaming] dify stream error: %s",
err_msg,
)
raise RuntimeError(f"Dify workflow error: {err_msg}")
except requests.exceptions.RequestException as exc:
if result:
if current_app:
current_app.logger.info(
"[workflow-streaming] connection dropped but result already captured",
"[workflow-streaming] attempt=%s finished run_id=%s retry_count=%s",
attempt + 1,
workflow_run_id,
retry_count,
)
elif workflow_run_id:
return DifyService._attach_workflow_reliability_meta(
result,
poll_used=False,
retry_count=retry_count,
workflow_run_id=workflow_run_id,
)
except requests.exceptions.RequestException as exc:
error_type, retryable = DifyService._classify_workflow_request_exception(exc)
last_error_type = error_type
workflow_run_id = stream_state.get("workflow_run_id")
partial_result = stream_state.get("result") or {}
if workflow_run_id:
last_workflow_run_id = workflow_run_id
if current_app:
current_app.logger.warning(
"[workflow-streaming] connection dropped, polling result for run_id=%s",
"[workflow-streaming] attempt=%s error_type=%s retryable=%s run_id=%s err=%s",
attempt + 1,
error_type,
retryable,
workflow_run_id,
exc,
)
result = DifyService._poll_workflow_result(
agent=agent,
workflow_run_id=workflow_run_id,
max_wait=timeout[1] if isinstance(timeout, tuple) else 300,
)
else:
if partial_result:
if current_app:
current_app.logger.info(
"[workflow-streaming] connection dropped but result already captured run_id=%s",
workflow_run_id,
)
return DifyService._attach_workflow_reliability_meta(
partial_result,
poll_used=False,
retry_count=retry_count,
error_type=error_type,
workflow_run_id=workflow_run_id,
)
if workflow_run_id:
poll_used = True
if current_app:
current_app.logger.warning(
"[workflow-streaming] polling after disconnect run_id=%s error_type=%s",
workflow_run_id,
error_type,
)
result = DifyService._poll_workflow_result(
agent=agent,
workflow_run_id=workflow_run_id,
max_wait=max_wait,
)
poll_error_type = None if result else "poll_timeout"
return DifyService._attach_workflow_reliability_meta(
result,
poll_used=True,
retry_count=retry_count,
error_type=poll_error_type or error_type,
workflow_run_id=workflow_run_id,
)
if retryable and attempt < max_attempts - 1:
retry_count += 1
if current_app:
current_app.logger.info(
"[workflow-streaming] retrying attempt=%s error_type=%s",
attempt + 2,
error_type,
)
continue
if current_app:
current_app.logger.error(
"[workflow-streaming] request error (no run_id): %s",
"[workflow-streaming] request failed (no run_id) error_type=%s err=%s",
error_type,
exc,
)
raise
return result if isinstance(result, dict) else {}
return DifyService._attach_workflow_reliability_meta(
result if isinstance(result, dict) else {},
poll_used=poll_used,
retry_count=retry_count,
error_type=last_error_type,
workflow_run_id=last_workflow_run_id,
)
@staticmethod
def _poll_workflow_result(
+259 -16
View File
@@ -7,12 +7,180 @@ backend/app/services/file_check.py
"""
from __future__ import annotations
import re
from typing import Any
import requests
from app.services.dify import DifyService
VALID_FILE_CHECK_RESULTS = {"合格", "不合格", "人工判定"}
MANUAL_REASON_BUSINESS_UNCERTAIN = "business_uncertain"
MANUAL_REASON_DIFY_TIMEOUT = "dify_timeout"
MANUAL_REASON_POLL_TIMEOUT = "poll_timeout"
MANUAL_REASON_DIFY_FAILED = "dify_failed"
MANUAL_REASON_INVALID_OUTPUT = "invalid_workflow_output"
MANUAL_REASON_ATTACHMENT_FAILED = "attachment_read_failed"
MANUAL_REASON_NO_DIFY_AGENT = "no_dify_agent"
SYSTEM_MANUAL_REASON_TYPES = {
MANUAL_REASON_DIFY_TIMEOUT,
MANUAL_REASON_POLL_TIMEOUT,
MANUAL_REASON_DIFY_FAILED,
MANUAL_REASON_INVALID_OUTPUT,
MANUAL_REASON_ATTACHMENT_FAILED,
}
_GATEWAY_TIMEOUT_ERROR_TYPES = {
"read_timeout",
"connect_timeout",
"connection_error",
"stream_closed_early",
}
_ATTACHMENT_FAIL_PATTERN = re.compile(
r"附件.{0,8}读取失败|读取附件失败|无法读取附件|attachment.{0,12}read.{0,8}fail|attachment_read_failed",
re.IGNORECASE,
)
def _extract_workflow_reliability_meta(workflow_result: dict[str, Any] | None) -> dict[str, Any]:
"""从 Dify Workflow 原始响应提取网关侧可靠性元信息。"""
data = workflow_result if isinstance(workflow_result, dict) else {}
workflow_run_id = data.get("workflow_run_id") or data.get("id")
return {
"workflow_run_id": workflow_run_id,
"poll_used": bool(data.get("_workflow_poll_used")),
"retry_count": int(data.get("_workflow_retry_count") or 0),
"error_type": data.get("_workflow_error_type"),
}
def _classify_evaluate_exception(exc: Exception) -> tuple[str, bool]:
"""将 evaluate 层异常映射为 error_type 与是否可重试。"""
if isinstance(exc, requests.exceptions.RequestException):
return DifyService._classify_workflow_request_exception(exc)
return "evaluate_error", False
def _gateway_error_to_manual_reason(error_type: str | None) -> str:
"""将网关 error_type 映射为 manual_reason_type。"""
normalized = str(error_type or "").strip().lower()
if normalized == "poll_timeout":
return MANUAL_REASON_POLL_TIMEOUT
if normalized in _GATEWAY_TIMEOUT_ERROR_TYPES:
return MANUAL_REASON_DIFY_TIMEOUT
return MANUAL_REASON_DIFY_FAILED
def _detect_attachment_read_failure(*texts: str | None) -> bool:
"""根据 Dify 返回文案判断是否附件读取失败。"""
combined = " ".join(str(t or "") for t in texts if t)
if not combined.strip():
return False
if _ATTACHMENT_FAIL_PATTERN.search(combined):
return True
lowered = combined.lower()
return "attachment_read_failed" in lowered or "附件读取失败" in combined
def user_action_hint_for_manual_reason(manual_reason_type: str | None) -> str | None:
"""按 manual_reason_type 返回给业务人员的操作建议。"""
hints = {
MANUAL_REASON_BUSINESS_UNCERTAIN: "AI 无法给出明确结论,请人工复核材料后至 SRM 审核或驳回",
MANUAL_REASON_DIFY_TIMEOUT: "系统调用 Dify 超时,请稍后重试或联系运维排查网络/代理",
MANUAL_REASON_POLL_TIMEOUT: "系统补偿查询 Dify 结果超时,请稍后重试或凭 workflow_run_id 对账",
MANUAL_REASON_DIFY_FAILED: "Dify Workflow 执行失败,请查看 dify_message 或联系运维",
MANUAL_REASON_INVALID_OUTPUT: "Dify 返回格式不符合约定,请检查 Workflow 输出节点",
MANUAL_REASON_ATTACHMENT_FAILED: "附件读取失败,请检查 SRM 附件链接或文件是否可访问",
MANUAL_REASON_NO_DIFY_AGENT: "未配置 Dify Agent,请在排程管理中绑定后重新检核",
}
if not manual_reason_type:
return None
return hints.get(manual_reason_type)
def build_manual_classification(
manual_reason_type: str | None,
*,
is_system_error: bool | None = None,
) -> dict[str, Any]:
"""构建 manual_reason_type / is_system_error / user_action_hint 三元组。"""
reason = str(manual_reason_type or "").strip() or None
system = (
bool(is_system_error)
if is_system_error is not None
else bool(reason and reason in SYSTEM_MANUAL_REASON_TYPES)
)
return {
"manual_reason_type": reason,
"is_system_error": system,
"user_action_hint": user_action_hint_for_manual_reason(reason),
}
def build_no_dify_agent_result() -> dict[str, Any]:
"""未配置 Dify Agent 时的标准判定结果。"""
classification = build_manual_classification(MANUAL_REASON_NO_DIFY_AGENT, is_system_error=False)
return {
"dify_result": "人工判定",
"dify_message": "未配置 Agent ID,跳过 Dify",
**classification,
}
def increment_judgement_stats(
stats: dict[str, Any],
*,
dify_result: str,
manual_reason_type: str | None = None,
is_system_error: bool = False,
) -> None:
"""
按单条判定结果累加批次 judgement 统计。
manual_count 仍表示所有「人工判定」条数;新增字段区分业务与系统原因。
"""
result = str(dify_result or "").strip()
if result == "合格":
stats["qualified_count"] = int(stats.get("qualified_count") or 0) + 1
return
if result == "不合格":
stats["unqualified_count"] = int(stats.get("unqualified_count") or 0) + 1
return
stats["manual_count"] = int(stats.get("manual_count") or 0) + 1
reason = str(manual_reason_type or "").strip()
if reason == MANUAL_REASON_BUSINESS_UNCERTAIN:
stats["business_manual_count"] = int(stats.get("business_manual_count") or 0) + 1
if is_system_error:
stats["system_error_count"] = int(stats.get("system_error_count") or 0) + 1
stats["dify_error_count"] = int(stats.get("dify_error_count") or 0) + 1
if reason in (MANUAL_REASON_DIFY_TIMEOUT, MANUAL_REASON_POLL_TIMEOUT):
stats["dify_timeout_count"] = int(stats.get("dify_timeout_count") or 0) + 1
if reason == MANUAL_REASON_INVALID_OUTPUT:
stats["invalid_output_count"] = int(stats.get("invalid_output_count") or 0) + 1
stats["invalid_result_count"] = int(stats.get("invalid_result_count") or 0) + 1
if reason == MANUAL_REASON_ATTACHMENT_FAILED:
stats["attachment_error_count"] = int(stats.get("attachment_error_count") or 0) + 1
def empty_judgement_stats() -> dict[str, int]:
"""文件检核批次 judgement 统计初始值。"""
return {
"qualified_count": 0,
"unqualified_count": 0,
"manual_count": 0,
"dify_error_count": 0,
"invalid_result_count": 0,
"business_manual_count": 0,
"system_error_count": 0,
"dify_timeout_count": 0,
"invalid_output_count": 0,
"attachment_error_count": 0,
}
class FileCheckService:
"""文件检核 Dify Workflow 调用与结果规范化。"""
@@ -44,7 +212,7 @@ class FileCheckService:
timeout: HTTP 超时 (connect, read) 秒。
Returns:
含 dify_result、dify_message、workflow_run_id 等字段的 dict。
含 dify_result、dify_message、workflow_run_id 及可靠性/分类元信息的 dict。
"""
inputs: dict[str, Any] = {
"run_no": run_no,
@@ -63,12 +231,20 @@ class FileCheckService:
timeout=timeout,
)
except Exception as exc:
error_type, retryable = _classify_evaluate_exception(exc)
manual_reason = _gateway_error_to_manual_reason(error_type)
classification = build_manual_classification(manual_reason, is_system_error=True)
return {
"dify_result": "人工判定",
"dify_message": f"Dify执行失败:{exc}",
"provider": cls.PROVIDER,
"workflow_run_id": None,
"error": str(exc),
"error_type": error_type,
"retryable": retryable,
"retry_count": 0,
"poll_used": False,
**classification,
}
normalized = cls.normalize_workflow_result(workflow_result)
@@ -77,40 +253,107 @@ class FileCheckService:
@staticmethod
def normalize_workflow_result(workflow_result: dict[str, Any] | None) -> dict[str, Any]:
"""将 Dify Workflow 输出规范为合格/不合格/人工判定。"""
"""将 Dify Workflow 输出规范为合格/不合格/人工判定,并附加分类与可靠性元信息。"""
data = workflow_result if isinstance(workflow_result, dict) else {}
outputs = (data.get("outputs") or {}).get("output") or data.get("outputs") or data
output_data = outputs if isinstance(outputs, dict) else {}
reliability = _extract_workflow_reliability_meta(data)
outputs_container = data.get("outputs")
if isinstance(outputs_container, dict):
nested = outputs_container.get("output")
output_data = nested if isinstance(nested, dict) else outputs_container
else:
output_data = {}
dify_result = str(output_data.get("dify_result") or output_data.get("result") or "").strip()
dify_message = str(output_data.get("dify_message") or output_data.get("message") or "").strip()
workflow_run_id = data.get("workflow_run_id") if isinstance(data, dict) else None
workflow_run_id = reliability.get("workflow_run_id")
status = data.get("status") if isinstance(data, dict) else None
error = data.get("error") if isinstance(data, dict) else None
gateway_error_type = reliability.get("error_type")
reliability_fields = {
"workflow_run_id": workflow_run_id,
"poll_used": reliability.get("poll_used"),
"retry_count": reliability.get("retry_count"),
"error_type": gateway_error_type,
"retryable": None,
}
def _with_classification(payload: dict[str, Any], manual_reason_type: str) -> dict[str, Any]:
classification = build_manual_classification(manual_reason_type)
return {**payload, **reliability_fields, **classification}
if _detect_attachment_read_failure(dify_message, str(error or ""), str(output_data.get("error") or "")):
return _with_classification(
{
"dify_result": "人工判定",
"dify_message": dify_message or f"Dify执行失败:{error or '附件读取失败'}",
"error": str(error or "attachment_read_failed"),
"raw_outputs": output_data,
},
MANUAL_REASON_ATTACHMENT_FAILED,
)
if not output_data and not dify_result and gateway_error_type == "poll_timeout":
return _with_classification(
{
"dify_result": "人工判定",
"dify_message": "Dify执行失败:poll 超时未获取最终结果",
"error": "poll_timeout",
"raw_outputs": output_data,
},
MANUAL_REASON_POLL_TIMEOUT,
)
if gateway_error_type in _GATEWAY_TIMEOUT_ERROR_TYPES and not output_data and not dify_result:
return _with_classification(
{
"dify_result": "人工判定",
"dify_message": f"Dify执行失败:{gateway_error_type}",
"error": str(gateway_error_type),
"raw_outputs": output_data,
},
MANUAL_REASON_DIFY_TIMEOUT,
)
if status == "failed" or (error and not output_data):
return {
"dify_result": "人工判定",
"dify_message": f"Dify执行失败:{error or f'status={status}'}",
"workflow_run_id": workflow_run_id,
"error": str(error or ""),
"raw_outputs": output_data,
}
return _with_classification(
{
"dify_result": "人工判定",
"dify_message": f"Dify执行失败:{error or f'status={status}'}",
"error": str(error or ""),
"raw_outputs": output_data,
},
MANUAL_REASON_DIFY_FAILED,
)
if dify_result not in VALID_FILE_CHECK_RESULTS:
bad_value = dify_result or "空"
extra = f" | {dify_message}" if dify_message else ""
return _with_classification(
{
"dify_result": "人工判定",
"dify_message": f"返回值异常:{bad_value}{extra}",
"error": None,
"raw_outputs": output_data,
},
MANUAL_REASON_INVALID_OUTPUT,
)
if dify_result == "人工判定":
return {
"dify_result": "人工判定",
"dify_message": f"返回值异常:{bad_value}{extra}",
"workflow_run_id": workflow_run_id,
"dify_result": dify_result,
"dify_message": dify_message,
"error": None,
"raw_outputs": output_data,
**reliability_fields,
**build_manual_classification(MANUAL_REASON_BUSINESS_UNCERTAIN, is_system_error=False),
}
return {
"dify_result": dify_result,
"dify_message": dify_message,
"workflow_run_id": workflow_run_id,
"error": None,
"raw_outputs": output_data,
**reliability_fields,
"manual_reason_type": None,
"is_system_error": False,
"user_action_hint": None,
}
+13 -1
View File
@@ -32,7 +32,19 @@ def export_schedule_result_excel(
header_labels = header_labels or {}
detail_alias_order = detail_alias_order or []
exec_result_order = ["dify_result", "dify_message", "writeback_srm", "writeback_err"]
exec_result_order = [
"dify_result",
"dify_message",
"workflow_run_id",
"dify_error_type",
"dify_retry_count",
"dify_poll_used",
"manual_reason_type",
"is_system_error",
"user_action_hint",
"writeback_srm",
"writeback_err",
]
sql_headers: list[str] = []
detail_headers: list[str] = []
+46 -24
View File
@@ -5,7 +5,7 @@ from typing import Any, Callable
from flask import current_app, has_app_context
from app.services.file_check import FileCheckService
from app.services.file_check import FileCheckService, build_no_dify_agent_result, empty_judgement_stats, increment_judgement_stats
try:
import pyodbc # type: ignore
@@ -187,13 +187,7 @@ def _run_check_job_loop(
success_count = 0
failed_count = 0
skipped_count = 0
judgement_stats = {
"qualified_count": 0,
"unqualified_count": 0,
"manual_count": 0,
"dify_error_count": 0,
"invalid_result_count": 0,
}
judgement_stats = empty_judgement_stats()
current_step: dict[str, Any] | None = None
all_errors: list[str] = []
@@ -302,6 +296,13 @@ def _run_check_job_loop(
dify_ok = False
dify_result = "人工判定"
dify_message = ""
workflow_run_id = None
dify_error_type = None
dify_retry_count = 0
dify_poll_used = False
manual_reason_type = None
is_system_error = False
user_action_hint = None
try:
if use_dify:
@@ -337,21 +338,20 @@ def _run_check_job_loop(
dify_error = dify_res.get("error") if isinstance(dify_res, dict) else None
workflow_run_id = dify_res.get("workflow_run_id") if isinstance(dify_res, dict) else None
dify_error_type = dify_res.get("error_type") if isinstance(dify_res, dict) else None
dify_retry_count = dify_res.get("retry_count") if isinstance(dify_res, dict) else None
dify_poll_used = dify_res.get("poll_used") if isinstance(dify_res, dict) else None
manual_reason_type = dify_res.get("manual_reason_type") if isinstance(dify_res, dict) else None
is_system_error = bool(dify_res.get("is_system_error")) if isinstance(dify_res, dict) else False
user_action_hint = dify_res.get("user_action_hint") if isinstance(dify_res, dict) else None
dify_result, dify_message = _derive_dify_result_and_message(dify_res if isinstance(dify_res, dict) else {})
dify_ok = True
if dify_result == "合格":
judgement_stats["qualified_count"] += 1
elif dify_result == "不合格":
judgement_stats["unqualified_count"] += 1
else:
judgement_stats["manual_count"] += 1
if dify_error:
judgement_stats["dify_error_count"] += 1
raw_outputs = dify_res.get("raw_outputs") if isinstance(dify_res, dict) else None
if dify_result == "人工判定" and isinstance(raw_outputs, dict) and not dify_error:
raw_result = str(raw_outputs.get("dify_result") or raw_outputs.get("result") or "").strip()
if raw_result and raw_result not in {"合格", "不合格", "人工判定"}:
judgement_stats["invalid_result_count"] += 1
increment_judgement_stats(
judgement_stats,
dify_result=dify_result,
manual_reason_type=manual_reason_type,
is_system_error=is_system_error,
)
if current_app:
current_app.logger.info(
@@ -370,13 +370,28 @@ def _run_check_job_loop(
"dify_message": _truncate_str(dify_message),
"workflow_run_id": workflow_run_id,
"error": dify_error,
"error_type": dify_error_type,
"retry_count": dify_retry_count,
"poll_used": dify_poll_used,
"manual_reason_type": manual_reason_type,
"is_system_error": is_system_error,
"user_action_hint": user_action_hint,
},
}))
else:
dify_result = "人工判定"
dify_message = "未配置 Agent ID,跳过 Dify"
no_agent = build_no_dify_agent_result()
dify_result = no_agent["dify_result"]
dify_message = no_agent["dify_message"]
manual_reason_type = no_agent["manual_reason_type"]
is_system_error = no_agent["is_system_error"]
user_action_hint = no_agent["user_action_hint"]
dify_ok = True
judgement_stats["manual_count"] += 1
increment_judgement_stats(
judgement_stats,
dify_result=dify_result,
manual_reason_type=manual_reason_type,
is_system_error=is_system_error,
)
wb_sql = writeback_sql
wb_params = (run_no, dify_result, dify_message, str(row_id_value))
@@ -391,6 +406,13 @@ def _run_check_job_loop(
item.update({
"dify_result": dify_result,
"dify_message": dify_message,
"workflow_run_id": workflow_run_id,
"dify_error_type": dify_error_type,
"dify_retry_count": dify_retry_count,
"dify_poll_used": dify_poll_used,
"manual_reason_type": manual_reason_type,
"is_system_error": is_system_error,
"user_action_hint": user_action_hint,
"writeback_srm": True,
"writeback_err": item.get("writeback_err"),
})
@@ -19,7 +19,13 @@ from app.services.shipping_notice.queue_service import enqueue_shipping_notice_j
from app.services.shipping_notice.dify_executor import run_shipping_parse_via_dify
from app.services.shipping_notice.query_service import get_batch_by_no, get_task_by_ref, list_sorted_batch_tasks
from app.services.shipping_notice.task_workflow import recompute_batch_summary
from app.services.shipping_notice.tool_common import auto_progress_enabled, cfg_bool, cfg_int, log_task_event
from app.services.shipping_notice.tool_common import (
auto_progress_enabled,
cfg_bool,
cfg_int,
log_task_event,
switch_batch_focus,
)
from app.services.shipping_notice.tools import auto_progress, submit_decision
_RUNNING_BATCHES: set[str] = set()
@@ -97,7 +103,13 @@ def _refresh_batch_focus(task_no: str) -> None:
task = get_task_by_ref(task_no)
if not task or not task.batch:
return
task.batch.current_focus_task_no = task.task_no
switch_batch_focus(
task.batch,
task,
source="backend_orchestrator",
event_type="focus_auto_switched",
emit_when_unchanged=False,
)
recompute_batch_summary(task.batch)
db.session.commit()
@@ -2,8 +2,8 @@
services/shipping_notice/chat_actions.py
用途:发货通知状态机旧模块名的向后兼容 re-export 入口。
依赖:state_machine(ACTION_SPECS、CHECKPOINT_REGISTRY、apply_task_transition 等)。
逻辑:历史代码 import chat_actions;新代码应直接引用 state_machine.py,不再暴露已删除的 /chat-actions 读模型。
依赖:state_machine(ACTION_SPECS、CHECKPOINT_REGISTRY、apply_task_transition 等)、ui_state。
逻辑:历史代码 import chat_actions;新代码应直接引用 state_machine.py / ui_state.py,本模块仅保留兼容导出。
"""
from app.services.shipping_notice.state_machine import (
@@ -28,36 +28,38 @@ from app.services.shipping_notice.state_machine import (
upload_req_options_for_task,
validate_registry,
)
from app.services.shipping_notice.ui_state import build_task_ui_state
# Legacy alias
CHECKPOINT_OPTIONS = CHECKPOINT_REGISTRY
def build_chat_actions_payload(task):
def build_chat_actions_payload(task) -> dict:
"""
Build the legacy chat-actions API payload for one shipping task.
构建聊天气泡侧动作按钮兼容 payload。
AI trigger: use this when the workspace chat panel needs the current checkpoint
and clickable action buttons for an existing ShippingTask. The payload keeps the
historical `task_id` field as `task.task_no` so older frontend code can consume it.
核心逻辑:复用统一 UI State 读模型,只抽取聊天侧需要的 checkpoint/action_buttons/summary,
避免 workspace 路由继续依赖已删除的旧读模型实现。
Args:
task: ShippingTask 模型实例。
Returns:
包含 task_no、checkpoint、action_buttons 与摘要的字典。
"""
ui_state = resolve_task_ui_state(task)
action_buttons = (
inventory_source_action_buttons(task)
if ui_state.checkpoint == CP_INVENTORY_SOURCE_REVIEW
else ui_state.action_buttons
)
state = build_task_ui_state(task)
return {
"task_id": task.task_no,
"task_no": task.task_no,
"checkpoint": ui_state.checkpoint,
"human_options": ui_state.human_options or [],
"action_buttons": action_buttons,
"process_status": task.process_status,
"review_status": task.review_status,
"pending_human_reason": task.pending_human_reason,
"match_status": task.match_status,
"updated_at": task.updated_at.isoformat() if task.updated_at else None,
"task_no": state.get("task_no"),
"batch_no": state.get("batch_no"),
"checkpoint": state.get("checkpoint"),
"process_status": state.get("process_status"),
"review_status": state.get("review_status"),
"pending_human_reason": state.get("pending_human_reason"),
"match_status": state.get("match_status"),
"current_step": state.get("current_step"),
"summary": state.get("summary"),
"action_buttons": state.get("action_buttons") or [],
"updated_at": state.get("updated_at"),
}
__all__ = [
@@ -41,8 +41,9 @@ from app.services.shipping_notice.inventory_upload import (
from app.services.shipping_notice.inventory_workflow import ensure_inventory
from app.services.shipping_notice.i18n import resolve_lang, t
from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition, resolve_task_ui_state
from app.services.shipping_notice.tool_common import (
log_task_action_event,
log_task_event,
merge_tool_payload,
payload_wants_auto_chain_fallback,
@@ -79,12 +80,19 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
decision = str(payload.get("decision") or "").strip().lower()
comment = str(payload.get("comment") or "").strip()
lang = resolve_lang(payload)
event_source = str(payload.get("event_source") or "").strip() or "decision_workflow"
# [STEP 1] 先处理终止型决策。
# reject / close 会直接结束当前任务,不再继续进入库存或出货链路。
if decision == "reject":
apply_task_transition(task, TaskTransition.REJECTED)
log_task_event(task, "decision_rejected", {"comment": comment})
log_task_action_event(
task,
"decision_rejected",
action="reject",
source=event_source,
comment=comment,
)
db.session.commit()
return tool_response(
status="ok",
@@ -95,7 +103,13 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
if decision in {"close", "closed"}:
apply_task_transition(task, TaskTransition.CLOSED)
log_task_event(task, "decision_closed", {"comment": comment})
log_task_action_event(
task,
"decision_closed",
action="close",
source=event_source,
comment=comment,
)
db.session.commit()
return tool_response(
status="ok",
@@ -128,7 +142,13 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
task.match_status = None
task.shortage_json = None
task.line_results_json = None
log_task_event(task, "parse_confirmed", {"comment": comment})
log_task_action_event(
task,
"parse_confirmed",
action="confirm",
source=event_source,
comment=comment,
)
db.session.commit()
if (not task.inventory_lines_json) and (not has_uploaded_task_inventory(task.task_no)):
orchestrator_started = start_task_orchestrator(task.task_no)
@@ -153,7 +173,13 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
if match_completed(task):
apply_task_transition(task, TaskTransition.CONFIRM_MATCHED)
log_task_event(task, "decision_confirmed", {"comment": comment})
log_task_action_event(
task,
"decision_confirmed",
action="confirm",
source=event_source,
comment=comment,
)
db.session.commit()
return tool_response(
status="ok",
@@ -212,7 +238,13 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
task.match_status = None
task.shortage_json = None
task.line_results_json = None
log_task_event(task, "decision_rematch", {"comment": comment})
log_task_action_event(
task,
"decision_rematch",
action="rematch",
source=event_source,
comment=comment,
)
db.session.commit()
orchestrator_started = start_task_orchestrator(task.task_no)
return tool_response(
@@ -239,15 +271,18 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
apply_task_transition(task, TaskTransition.ALIGN_REVIEW_HOLD)
db.session.commit()
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
return inventory_mapping_checkpoint_response(
task,
column_meta=meta,
extra_data={
"warnings": [
t("workflow.decision.mapping_missing_reservation_warning", lang=lang),
],
},
lang=lang or None,
warning = t("workflow.decision.mapping_missing_reservation_warning", lang=lang)
ui = resolve_task_ui_state(task)
return tool_response(
status="needs_human",
task=task,
message=warning,
data=serialize_task_for_tool(task),
checkpoint=ui.checkpoint,
human_options=ui.human_options,
next_required_action=t("workflow.decision.mapping_correction_next", lang=lang),
forbidden_next_tools=["match_inventory"],
stop_agent_turn=True,
)
headers = meta.get("headers") if isinstance(meta.get("headers"), list) else []
field_mapping = meta.get("field_mapping") if isinstance(meta.get("field_mapping"), dict) else None
@@ -269,9 +304,19 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
task,
"inventory_mapping_confirmed",
{
"comment": comment,
"confirmed_by_task_no": task.task_no,
"inventory_file_no": inv_file.inventory_file_no,
**{
"comment": comment,
"confirmed_by_task_no": task.task_no,
"inventory_file_no": inv_file.inventory_file_no,
},
**{
"action": "confirm_inventory_mapping",
"source": event_source,
"target_type": "task",
"target_id": task.task_no,
"batch_no": task.batch.batch_no if task.batch else "",
"conversation_id": task.conversation_id or "",
},
},
)
for link in inv_file.links or []:
@@ -285,13 +330,29 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
linked_task,
"inventory_mapping_confirmed",
{
"comment": comment,
"confirmed_by_task_no": task.task_no,
"inventory_file_no": inv_file.inventory_file_no,
**{
"comment": comment,
"confirmed_by_task_no": task.task_no,
"inventory_file_no": inv_file.inventory_file_no,
},
**{
"action": "confirm_inventory_mapping",
"source": event_source,
"target_type": "task",
"target_id": linked_task.task_no,
"batch_no": linked_task.batch.batch_no if linked_task.batch else "",
"conversation_id": linked_task.conversation_id or "",
},
},
)
else:
log_task_event(task, "inventory_mapping_confirmed", {"comment": comment})
log_task_action_event(
task,
"inventory_mapping_confirmed",
action="confirm_inventory_mapping",
source=event_source,
comment=comment,
)
db.session.commit()
orchestrator_started = (
start_inventory_file_linked_tasks(inv_file)
@@ -385,7 +446,14 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
task.line_results_json = None
task.inventory_lines_json = None
task.error_message = None
log_task_event(task, "notice_reparse_requested", {"comment": comment, "source": "dify_required"})
log_task_action_event(
task,
"notice_reparse_requested",
action="reparse",
source=event_source,
comment=comment,
extra={"reparse_mode": "dify_required"},
)
db.session.commit()
orchestrator_started = start_task_orchestrator(task.task_no)
return tool_response(
@@ -28,7 +28,8 @@ def build_single_task_parse_prompt(task_no: str, *, batch_no: str | None = None)
"""
构造后台排程器发给 Dify 的用户意图短句。
后台任务号与批次号通过 hxops_context.refs 注入,不能拼入 query,避免 Dify 预处理把 SB-/流程指令误判为切换任务。
后台任务号与批次号通过 agent_runtime_context.refs 注入,不能拼入 query,
避免 Dify 预处理把 SB-/流程指令误判为切换任务。
"""
return "解析当前发货通知任务"
@@ -2,9 +2,9 @@
services/shipping_notice/dify_inputs.py
用途:识别发货通知 Dify Chatflow Agent,并构建会话级 Dify inputs。
依赖:agent_resolver、models.ShippingBatch/ShippingTask、chat.hxops_context。
依赖:agent_runtime_context 平台协议、agent_resolver、models.ShippingBatch/ShippingTask、shipping_notice.runtime_context。
逻辑:由 api/chat 在调用 DifyService.stream_chat 前引用;本模块按会话号解析当前批次/任务焦点,
仅补充货代发货场景可识别的 refs,再委托平台级上下文构造器生成 hxops_context。
仅输出 agent_runtime_context JSON 字符串,供 Dify 画布统一读取平台运行态快照。
"""
from __future__ import annotations
@@ -12,8 +12,10 @@ from __future__ import annotations
from typing import Any
from app.models import ShippingBatch, ShippingTask
from app.services.chat.hxops_context import HXOPS_CONTEXT_INPUT, build_hxops_context, build_ref
from app.services.agent_runtime_context.builder import serialize_for_dify
from app.services.agent_runtime_context.schema import AGENT_RUNTIME_CONTEXT_INPUT
from app.services.shipping_notice.agent_resolver import CHAT_AGENT_NAME
from app.services.shipping_notice.runtime_context import build_shipping_runtime_context
def is_shipping_notice_chat_agent(agent) -> bool:
@@ -45,12 +47,26 @@ def _task_by_task_no(task_id: str) -> ShippingTask | None:
return ShippingTask.query.filter_by(task_no=normalized).first()
def _build_hxops_refs(*, task: str, batch: str) -> list[dict[str, str]]:
"""构建货代发货 Agent 当前已知业务对象锚点。"""
return [
build_ref("task", task),
build_ref("batch", batch),
]
def _focus_task_row(focus_task: str, explicit_task_row: ShippingTask | None) -> ShippingTask | None:
"""
解析当前显式焦点任务行。
核心逻辑:优先复用已查出的显式 task;若焦点来自 batch.current_focus_task_no,再按 task_no 查询,
但不在无焦点时回退到最近任务,避免多票批次串单。
Args:
focus_task: 已解析出的焦点任务号。
explicit_task_row: task_id 显式传入时查询到的任务。
Returns:
当前焦点任务;无法明确识别时返回 None。
"""
normalized = str(focus_task or "").strip().upper()
if not normalized:
return None
if explicit_task_row and str(explicit_task_row.task_no or "").strip().upper() == normalized:
return explicit_task_row
return ShippingTask.query.filter_by(task_no=normalized).first()
def build_dify_chat_inputs(
@@ -66,7 +82,7 @@ def build_dify_chat_inputs(
构建发货通知 Dify Chatflow inputs。
OpenAPI 工具已在 Dify 侧配置 Server URL 与 Authorization / X-Integration-Key,
无需再注入 HXOPS_TOOLS_API_BASE;这里只补会话级上下文,供 Dify 画布通过 refs 稳定定位当前 task/batch。
无需再注入 HXOPS_TOOLS_API_BASE;这里仅注入 agent_runtime_context,避免新旧上下文字段并存导致画布协议漂移。
"""
conv_id = str(conversation_id or "").strip()
if not conv_id:
@@ -93,13 +109,18 @@ def build_dify_chat_inputs(
):
focus_batch = str(explicit_task_row.batch.batch_no or "").strip().upper()
hxops_context = build_hxops_context(
runtime_context = build_shipping_runtime_context(
session_id=conv_id,
request_id=request_id,
task=_focus_task_row(focus_task, explicit_task_row),
batch=batch or getattr(explicit_task_row, "batch", None),
trigger_source=trigger_source,
request_id=request_id,
locale=locale,
refs=_build_hxops_refs(task=focus_task, batch=focus_batch),
scope="task_run" if trigger_source == "backend_orchestrator" else "chat_turn",
run_purpose="parse_notice" if trigger_source == "backend_orchestrator" else "chat_turn",
)
if not hxops_context:
if not runtime_context:
return {}
return {HXOPS_CONTEXT_INPUT: hxops_context}
return {
AGENT_RUNTIME_CONTEXT_INPUT: serialize_for_dify(runtime_context),
}
+5 -1
View File
@@ -462,4 +462,8 @@ def resolve_lang(payload: dict[str, Any] | None = None) -> str:
def t(key: str, *, lang: str | None = None) -> str:
"""按语言键查找 i18n 文案;未命中时回退 zh 或原 key。"""
resolved = normalize_lang(lang) if lang else "zh"
return _MESSAGES.get(resolved, {}).get(key) or _MESSAGES["zh"].get(key) or key
if key in _MESSAGES.get(resolved, {}):
return _MESSAGES[resolved][key]
if key in _MESSAGES["zh"]:
return _MESSAGES["zh"][key]
return key
@@ -58,6 +58,70 @@ def latest_task_event(task: ShippingTask, event_type: str) -> ShippingTaskEvent
)
def _inventory_rpa_attempt_label(*, attempt_no: int, max_attempts: int, manual_retry_round: bool) -> str:
"""
生成库存 RPA 尝试轮次文案。
【AI 触发时机】:需要把当前 RPA 处于单次自动尝试、多次自动尝试或手动重试轮次解释给用户时调用。
核心逻辑:手动 retry_rpa 始终强调“手动第 N 次”;自动模式在 max_attempts=1 时不再输出“1/1”,
避免 Dify 误解为系统还会继续自动重试。
"""
if manual_retry_round:
return f"手动第 {attempt_no} 次尝试"
if max_attempts <= 1:
return "当前配置为单次自动尝试"
return f"第 {attempt_no}/{max_attempts} 次尝试"
def _inventory_rpa_running_prefix(*, attempt_no: int, max_attempts: int) -> str:
"""生成库存 RPA 运行中的简短前缀,单次模式不暴露 1/1 计数。"""
if max_attempts <= 1:
return "RPA 库存导出进行中。"
return f"RPA 库存导出进行中(第 {attempt_no}/{max_attempts} 次)。"
def _inventory_rpa_triggered_prefix(*, attempt_no: int, max_attempts: int, manual_retry_round: bool) -> str:
"""生成库存 RPA 触发成功后的摘要文案,区分自动单次、自动多次与人工重试。"""
if manual_retry_round:
return f"已手动重新触发 RPA 库存导出(手动第 {attempt_no} 次)。"
if max_attempts <= 1:
return "已触发 RPA 库存导出。"
return f"已触发 RPA 库存导出(第 {attempt_no}/{max_attempts} 次)。"
def _inventory_rpa_exhausted_message(attempts: int) -> str:
"""生成库存 RPA 已耗尽时的用户文案;单次模式明确提示“已尝试一次”。"""
if max_rpa_inventory_attempts() <= 1:
return "已尝试 1 次仍无法通过 RPA 获取库存,请手动上传货代库存 Excel 继续。"
return f"已尝试 {attempts} 次仍无法通过 RPA 获取库存,请手动上传货代库存 Excel 继续。"
def _inventory_rpa_running_message(*, attempt_no: int, max_attempts: int) -> str:
"""
生成库存 RPA 等待中的用户提示。
【AI 触发时机】:任务已进入 RPA 等待窗口、前端或工具再次查询状态时调用。
核心逻辑:前台只展示“仍在进行中”和下一步建议,不暴露 elapsed/timeout/retry_after 等秒级内部阈值。
"""
prefix = _inventory_rpa_running_prefix(attempt_no=attempt_no, max_attempts=max_attempts)
return f"{prefix}请稍后刷新状态;若长时间无结果,可改为上传库存 Excel。"
def _inventory_rpa_triggered_message(*, attempt_no: int, max_attempts: int, manual_retry_round: bool) -> str:
"""
生成库存 RPA 刚触发成功后的用户提示。
【AI 触发时机】:成功写出 trigger、准备把 running 状态回传给前端或 Agent 时调用。
核心逻辑:保留“已触发/已重新触发”状态提示,但不把 timeout 秒数暴露给业务用户。
"""
prefix = _inventory_rpa_triggered_prefix(
attempt_no=attempt_no,
max_attempts=max_attempts,
manual_retry_round=manual_retry_round,
)
return f"{prefix}若长时间无结果,可手动重试,或上传库存 Excel。"
def inventory_rpa_wait_seconds(task: ShippingTask) -> tuple[int | None, int | None, int | None]:
"""
返回库存 RPA 当前等待耗时、超时时间和剩余秒数。
@@ -231,10 +295,9 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
return tool_response(
status="running",
task_id=task.task_no,
message=(
f"RPA 库存导出进行中(第 {max(attempts, 1)}/{max_attempts} 次)。"
f"已等待 {elapsed}s / 超时 {timeout_seconds}s。"
f"请稍后再试(建议 {remaining}s 后)。"
message=_inventory_rpa_running_message(
attempt_no=max(attempts, 1),
max_attempts=max_attempts,
),
data={
**serialize_task_for_tool(task),
@@ -249,7 +312,7 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
)
last_failed = latest_task_event(task, "inventory_rpa_failed")
if not last_failed or (last_failed.created_at < last_trigger.created_at):
task.error_message = f"RPA 库存导出超时(>{timeout_seconds}s)"
task.error_message = "RPA 库存导出等待超时"
log_task_event(
task,
"inventory_rpa_failed",
@@ -262,7 +325,8 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
db.session.flush()
# [STEP 2] 处理重试上限与已落盘文件两种捷径。
# 已达到最大次数时直接转人工;若目录里已有最新库存文件,则优先吃掉落盘结果而不是再触发一次 RPA。
# 单次模式下,只有“上一轮已经失败/超时”时才允许在这里转人工;首次成功写出 trigger 后必须进入等待窗口。
# 若目录里已有最新库存文件,则优先吃掉落盘结果而不是再触发一次 RPA。
attempts = inventory_rpa_attempts(task)
max_attempts = max_rpa_inventory_attempts()
if attempts >= max_attempts and not task.inventory_lines_json and not manual_retry_round:
@@ -273,7 +337,7 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
return tool_response(
status="needs_human",
task=task,
message=f"已尝试 {attempts} 次仍无法通过 RPA 获取库存,请手动上传货代库存 Excel 继续。",
message=_inventory_rpa_exhausted_message(attempts),
data=serialize_task_for_tool(task),
)
@@ -313,10 +377,10 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
if manual_retry_round
else "已触发 RPA 库存导出,等待结果"
)
progress_detail = (
f"手动第 {attempt_no} 次尝试"
if manual_retry_round
else f"第 {attempt_no}/{max_attempts} 次尝试"
progress_detail = _inventory_rpa_attempt_label(
attempt_no=attempt_no,
max_attempts=max_attempts,
manual_retry_round=manual_retry_round,
)
set_task_step_progress(
task,
@@ -336,28 +400,15 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
{"trigger": trigger, "attempt": attempt_no, "manual_retry_round": manual_retry_round},
)
if attempt_no >= max_attempts and not task.inventory_lines_json and not manual_retry_round:
apply_task_transition(task, TaskTransition.RPA_EXHAUSTED)
task.error_message = "已多次尝试仍无法通过 RPA 获取库存"
log_task_event(task, "inventory_rpa_exhausted", {"attempts": attempt_no})
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message=f"已尝试 {attempt_no} 次仍无法通过 RPA 获取库存,请手动上传货代库存 Excel 继续。",
data=serialize_task_for_tool(task),
)
response_prefix = (
f"已手动重新触发 RPA 库存导出(手动第 {attempt_no} 次)。"
if manual_retry_round
else f"已触发 RPA 库存导出(第 {attempt_no}/{max_attempts} 次)。"
)
db.session.commit()
return tool_response(
status="running",
task_id=task.task_no,
message=f"{response_prefix}若 {timeout_seconds}s 内无回调/无落盘文件,可手动重试,或上传库存 Excel。",
message=_inventory_rpa_triggered_message(
attempt_no=attempt_no,
max_attempts=max_attempts,
manual_retry_round=manual_retry_round,
),
data={
**serialize_task_for_tool(task),
"rpa": {
@@ -417,7 +468,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
return tool_response(
status="needs_human",
task=task,
message=f"已尝试 {attempts} 次仍无法通过 RPA 获取库存,请手动上传货代库存 Excel 继续。",
message=_inventory_rpa_exhausted_message(attempts),
data=serialize_task_for_tool(task),
)
@@ -1,9 +1,10 @@
"""
services/shipping_notice/notice_upload.py
用途:管理发货通知附件上传、文本抽取、OCR/文档解析与文件落盘。
用途:管理发货通知附件上传、文本抽取、截断与统一接入结果模型。
依赖:edkb_system 的 PDF/Docx/CSV/OCR 技能、export._storage_root、Flask current_app 配置。
逻辑:由 workspace_shipping_notice 和 task_workflow 上游入口调用本文件,把原始附件转成可解析文本后交给 extract/task_workflow;批量上传的预检临时文件也在这里统一落盘和清理。
逻辑:workspace 单票建单、批量建单、重新上传三条入口均经 intake_notice_attachment / intake_temp_notice_uploads
收敛抽取与失败分流;下游 extract/task_workflow 只消费 NoticeIntakeResult。
"""
from __future__ import annotations
@@ -11,10 +12,11 @@ from __future__ import annotations
import base64
import re
import shutil
from dataclasses import dataclass, field
from email import policy
from email.parser import BytesParser
from pathlib import Path
from typing import Any
from typing import Any, Literal, Sequence
from flask import current_app
@@ -228,3 +230,237 @@ def max_notice_chars() -> int:
except Exception:
value = 0
return value if value > 0 else 200000
EMPTY_TEXT_REJECT_MESSAGE = "notice text is empty after extraction"
@dataclass(frozen=True)
class NoticeIntakeResult:
"""
发货通知附件统一接入结果。
三条工作台入口(单票建单 / 批量建单 / 重新上传)共用本模型,避免抽取、截断与失败分流行为漂移。
"""
filename: str
source_type: str
source_file_type: str | None
text: str
warnings: list[str] = field(default_factory=list)
meta: dict[str, Any] = field(default_factory=dict)
status: Literal["accepted", "empty_text", "extract_failed"] = "empty_text"
saved_path: Path | None = None
@property
def accepted(self) -> bool:
"""抽取成功且正文非空。"""
return self.status == "accepted"
def to_notice_item(self) -> dict[str, Any]:
"""批量建单 notice_items 载荷项。"""
return {
"source_type": self.source_type,
"source_file_name": self.filename,
"source_file_type": self.source_file_type,
"raw_text": self.text,
"warnings": list(self.warnings),
}
def to_accepted_file_summary(self) -> dict[str, Any]:
"""批量预检 accepted_files 摘要项。"""
return {
"filename": self.filename,
"source_type": self.source_type,
"source_file_type": self.source_file_type,
"text_length": len(self.text),
"warnings": list(self.warnings),
}
def to_rejected_file_summary(self) -> dict[str, Any]:
"""批量预检 rejected_files 摘要项。"""
return {
"filename": self.filename,
"source_type": self.source_type,
"source_file_type": self.source_file_type,
"reason": "empty_text",
"message": EMPTY_TEXT_REJECT_MESSAGE,
"warnings": list(self.warnings),
}
def to_notice_upload_meta(self) -> dict[str, Any]:
"""API data.notice_upload 响应字段。"""
payload = dict(self.meta) if isinstance(self.meta, dict) else {}
payload["filename"] = self.filename
payload["warnings"] = list(self.warnings)
return payload
def notice_source_file_type(upload: Any) -> str | None:
"""从 Flask/Werkzeug 上传对象提取 MIME type;为空时返回 None。"""
return str(getattr(upload, "mimetype", "") or "").strip() or None
def truncate_notice_text(text: str, warnings: list[str] | None = None) -> tuple[str, list[str]]:
"""
按配置上限截断发货通知正文,并追加统一 warning 标记。
Args:
text: 抽取后的原始正文。
warnings: 已有 warnings,截断时会追加 notice_text_truncated 项。
Returns:
tuple[str, list[str]]: (截断后正文, 更新后的 warnings)。
"""
ws = list(warnings or [])
limit = max_notice_chars()
if len(text) > limit:
text = text[:limit]
ws.append(f"notice_text_truncated:{limit}")
return text, ws
def intake_notice_attachment(
*,
filename: str,
raw: bytes,
source_file_type: str | None = None,
storage: Literal["task", "temp"] = "task",
task_no: str | None = None,
temp_request_id: str | None = None,
temp_index: int = 1,
) -> NoticeIntakeResult:
"""
单份发货通知附件的统一接入:落盘 → 抽取 → 截断 → 失败分流。
核心逻辑:三条工作台入口均调用本函数,保证 empty_text / extract_failed 与 warnings 语义一致。
Args:
filename: 原始文件名。
raw: 文件字节流。
source_file_type: MIME type,可为空。
storage: task 为任务级持久化目录;temp 为批量预检临时目录。
task_no: storage=task 时必填。
temp_request_id: storage=temp 时必填。
temp_index: storage=temp 时文件序号,避免同名覆盖。
Returns:
NoticeIntakeResult: 含 accepted / empty_text / extract_failed 状态与截断后正文。
"""
name = str(filename or "").strip() or "notice"
source_type = guess_source_type(name)
saved_path: Path | None = None
text = ""
meta: dict[str, Any] = {}
warnings: list[str] = []
status: Literal["accepted", "empty_text", "extract_failed"] = "empty_text"
try:
if storage == "task":
if not task_no:
raise ValueError("task_no is required for task storage")
saved_path = save_task_notice_upload(task_no, name, raw or b"")
else:
if not temp_request_id:
raise ValueError("temp_request_id is required for temp storage")
saved_path = save_temp_notice_upload(temp_request_id, temp_index, name, raw or b"")
text, meta = extract_notice_text(saved_path)
warnings = list(meta.get("warnings") or []) if isinstance(meta, dict) else []
except Exception as exc:
warnings = [f"notice_extract_failed:{exc}"]
status = "extract_failed"
return NoticeIntakeResult(
filename=name,
source_type=source_type,
source_file_type=source_file_type,
text="",
warnings=warnings,
meta=meta if isinstance(meta, dict) else {},
status=status,
saved_path=saved_path,
)
if not str(text or "").strip():
return NoticeIntakeResult(
filename=name,
source_type=source_type,
source_file_type=source_file_type,
text="",
warnings=warnings,
meta=meta if isinstance(meta, dict) else {},
status="empty_text",
saved_path=saved_path,
)
text, warnings = truncate_notice_text(text, warnings)
return NoticeIntakeResult(
filename=name,
source_type=source_type,
source_file_type=source_file_type,
text=text,
warnings=warnings,
meta=meta if isinstance(meta, dict) else {},
status="accepted",
saved_path=saved_path,
)
def intake_temp_notice_uploads(
temp_request_id: str,
uploads: Sequence[Any],
) -> tuple[list[NoticeIntakeResult], list[NoticeIntakeResult]]:
"""
批量建单入口:逐份附件接入并在 finally 外由调用方清理临时目录。
Args:
temp_request_id: 请求级临时目录 ID。
uploads: Flask request.files 中的上传对象序列。
Returns:
tuple[list, list]: (accepted 结果列表, rejected 结果列表)。
"""
accepted: list[NoticeIntakeResult] = []
rejected: list[NoticeIntakeResult] = []
for index, upload in enumerate(uploads, start=1):
raw = upload.read() or b""
result = intake_notice_attachment(
filename=upload.filename or "notice",
raw=raw,
source_file_type=notice_source_file_type(upload),
storage="temp",
temp_request_id=temp_request_id,
temp_index=index,
)
if result.accepted:
accepted.append(result)
else:
rejected.append(result)
return accepted, rejected
def build_notice_file_summary(
*,
total_files: int,
accepted: Sequence[NoticeIntakeResult],
rejected: Sequence[NoticeIntakeResult],
) -> dict[str, Any]:
"""
构建批量上传预检摘要,供前端回显与测试断言。
Args:
total_files: 请求内附件总数。
accepted: 接入成功的结果列表。
rejected: 接入失败的结果列表。
Returns:
dict: total/accepted/rejected 计数与文件明细。
"""
accepted_files = [item.to_accepted_file_summary() for item in accepted]
rejected_files = [item.to_rejected_file_summary() for item in rejected]
return {
"total_files": total_files,
"accepted_count": len(accepted_files),
"rejected_count": len(rejected_files),
"accepted_files": accepted_files,
"rejected_files": rejected_files,
}
@@ -30,6 +30,7 @@ def _post_op(
properties: dict[str, Any],
*,
required: list[str] | None = None,
description: str | None = None,
) -> dict[str, Any]:
schema: dict[str, Any] = {"type": "object", "properties": properties}
if required:
@@ -38,7 +39,7 @@ def _post_op(
"post": {
"operationId": operation_id,
"summary": summary,
"description": summary,
"description": str(description or summary),
"parameters": [],
"requestBody": {
"required": True,
@@ -83,8 +84,13 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
"货代发货通知 Agent Tool API。仅导出适合 Dify AI 编排层使用的工具:"
"通知理解、字段修订、库存映射建议、人工确认收口与状态查询;"
"不包含由后台任务统一续跑的主推进工具,也不包含 RPA 回调。"
"推进类 Tool 的统一约束如下:必须依赖 HXOPS 状态机校验,必须基于唯一 task_id 推进;"
"模糊指代不能直接推进,必须先通过 reference_context、get_task_status 或其他 HXOPS Tool 解析到唯一任务。"
"submit_decision、match_inventory、generate_shipment_excel、upload_to_freight、retry_task、confirm_inventory_source"
" 这类推进动作都必须根据 HXOPS Tool 返回结果解释,不能脱离 Tool 返回自行编造状态。"
"若 Tool 返回 needs_human 或 failed,不得自行改写成完成、成功上传或已处理完毕。"
"如果响应包含 action_buttons,Dify 只解释当前状态、业务原因和影响,"
"不要在自然语言正文里列出按钮清单或“推荐下一步”动作列表;"
"不要在自然语言正文列出按钮清单或“推荐下一步”动作列表;"
"可点击按钮由宿主系统根据 action_buttons 统一渲染。"
"鉴权:Authorization Bearer 或 X-Integration-Key。"
),
@@ -201,6 +207,14 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
"comment": _str_prop("备注(可选)"),
},
required=["decision"],
description=(
"人工复核决策入口。必须先定位到唯一 task_id 才能推进;若 conversation_id 对应多个任务,必须先追问或调用状态查询工具确认,"
"禁止用模糊指代直接推进。"
"本 Tool 的返回结果以 HXOPS 状态机为准,Dify 必须根据实际返回的 status、checkpoint、forbidden_next_tools、"
"human_options 或 action_buttons 解释当前现场。"
"若返回 needs_human 或 failed,不得自行宣布完成、不得改写为成功,也不要在正文列出按钮清单;"
"按钮由 HXOPS 前端渲染。"
),
),
"/tools/get_task_status": _post_op(
"get_task_status",
@@ -391,14 +391,16 @@ def serialize_batch_summary(batch: ShippingBatch) -> dict[str, Any]:
}
def serialize_conversation_batch_workspace(batch: ShippingBatch, user_id: int) -> dict[str, Any]:
"""序列化会话工作台中的单个批次,包含批次摘要、任务列表与焦点任务。"""
focus_task = get_focus_task_for_batch(batch.batch_no, user_id)
return {
**serialize_batch_summary(batch),
"tasks": list_batch_task_summaries(batch),
"focus_task": serialize_task_summary(focus_task) if focus_task else None,
}
def serialize_conversation_batch_workspace(batch: ShippingBatch) -> dict[str, Any]:
"""
序列化会话工作台中的单个批次。
核心逻辑:直接复用批次级 UI State 构建器,确保会话级工作台与批次详情页的
`tasks[].ui_state / focus_task_ui_state / action_buttons` 完全同源,避免按钮来源漂移。
"""
from app.services.shipping_notice.ui_state import build_batch_ui_state
return build_batch_ui_state(batch)
def get_conversation_batch_workspace(conversation_id: str, user_id: int) -> dict[str, Any]:
@@ -417,7 +419,7 @@ def get_conversation_batch_workspace(conversation_id: str, user_id: int) -> dict
"conversation_id": value,
"summary": compute_conversation_workspace_summary(ordered_batches),
"batches": [
serialize_conversation_batch_workspace(batch, user_id)
serialize_conversation_batch_workspace(batch)
for batch in ordered_batches
],
}
@@ -0,0 +1,311 @@
"""
backend/app/services/shipping_notice/reference_context.py
用途:从发货通知批次/任务/事件构建 shipping_notice 专用 reference_context。
依赖:models.ShippingBatch/ShippingTask/ShippingTaskEvent、agent_runtime_context.reference。
逻辑:runtime_context 在调用 Dify 前经本模块提炼当前 focus、最近动作、最近失败和候选对象,避免把全量事件流水直接暴露给 Runtime。
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
from typing import Any
from app.models import ShippingBatch, ShippingTask, ShippingTaskEvent
from app.services.agent_runtime_context.reference import build_object_ref, build_reference_context
MAX_REFERENCE_EVENT_SCAN = 8
MAX_REFERENCE_SUMMARY_CANDIDATES = 2
@dataclass(frozen=True)
class _ActionEventMeta:
"""定义 reference builder 可识别动作事件的语义与优先级。"""
action: str
summary_template: str
priority: int
_ACTION_EVENT_MAP: dict[str, _ActionEventMeta] = {
"parse_confirmed": _ActionEventMeta("confirm_parse", "用户已确认 {task_no} 解析", 40),
"decision_confirmed": _ActionEventMeta("confirm_matched", "用户已确认 {task_no} 当前结果", 40),
"decision_rematch": _ActionEventMeta("rematch", "用户已要求重新匹配 {task_no}", 40),
"notice_reparse_requested": _ActionEventMeta("reparse", "用户已要求重新解析 {task_no}", 40),
"decision_rejected": _ActionEventMeta("reject", "用户已驳回 {task_no}", 40),
"focus_switched": _ActionEventMeta("switch_focus", "用户已切换 focus 到 {task_no}", 35),
"focus_auto_switched": _ActionEventMeta("auto_focus", "系统自动聚焦到 {task_no}", 10),
"inventory_mapping_confirmed": _ActionEventMeta("confirm_inventory_mapping", "用户已确认 {task_no} 库存映射", 30),
"inventory_source_confirmed": _ActionEventMeta("confirm_inventory_source", "用户已确认 {task_no} 库存源", 30),
}
def _clean_text(value: Any) -> str:
"""将任意值规范化为去空白字符串。"""
return str(value or "").strip()
def _task_no(task: ShippingTask | None) -> str:
"""提取任务号并统一成大写。"""
return _clean_text(getattr(task, "task_no", None)).upper()
def _task_recency_key(task: ShippingTask) -> tuple[datetime, int]:
"""
构造任务最近性排序键。
核心逻辑:优先按 updated_at,其次 created_at 与主键排序,保证最近失败/最近动作关联稳定可复现。
"""
updated_at = getattr(task, "updated_at", None) or getattr(task, "created_at", None) or datetime.min
return updated_at, int(getattr(task, "id", 0) or 0)
def _collect_batch_tasks(batch: ShippingBatch | None, focus_task: ShippingTask | None) -> list[ShippingTask]:
"""
汇总当前 reference_context 可见的任务集合。
核心逻辑:优先读取当前批次任务;若 focus_task 尚未包含则补入,避免后台单票 run 丢失最近失败/焦点判断。
"""
tasks: list[ShippingTask] = []
seen: set[str] = set()
for task in list(getattr(batch, "tasks", None) or []):
task_no = _task_no(task)
if not task_no or task_no in seen:
continue
tasks.append(task)
seen.add(task_no)
focus_task_no = _task_no(focus_task)
if focus_task is not None and focus_task_no and focus_task_no not in seen:
tasks.append(focus_task)
return sorted(tasks, key=_task_recency_key, reverse=True)
def _recent_events(tasks: list[ShippingTask]) -> list[ShippingTaskEvent]:
"""
查询最近关键事件。
核心逻辑:只取当前批次/任务的最近少量事件,用于推断最后动作,不把全量事件流水塞进上下文。
"""
task_ids = [int(task.id) for task in tasks if getattr(task, "id", None) is not None]
if not task_ids:
return []
return (
ShippingTaskEvent.query.filter(ShippingTaskEvent.task_id.in_(task_ids))
.order_by(ShippingTaskEvent.created_at.desc(), ShippingTaskEvent.id.desc())
.limit(MAX_REFERENCE_EVENT_SCAN)
.all()
)
def _task_failure_descriptor(task: ShippingTask | None) -> dict[str, str] | None:
"""
提取任务失败/异常摘要。
核心逻辑:把 HXOPS 内部状态机信号收敛成 Dify 可理解的 shortage/rejected/upload_failed 等短标签。
"""
task_no = _task_no(task)
if not task_no:
return None
process_status = _clean_text(getattr(task, "process_status", None)).lower()
review_status = _clean_text(getattr(task, "review_status", None)).lower()
match_status = _clean_text(getattr(task, "match_status", None)).lower()
pending_reason = _clean_text(getattr(task, "pending_human_reason", None)).lower()
upload_status = _clean_text(getattr(task, "upload_status", None)).lower()
if match_status == "shortage" or pending_reason == "shortage" or getattr(task, "shortage_json", None):
return {
"reason": "shortage",
"label": "异常:库存不足",
"summary": f"{task_no} 库存匹配失败",
}
if process_status == "rejected" or review_status == "rejected":
return {
"reason": "rejected",
"label": "已驳回",
"summary": f"{task_no} 已被驳回",
}
if process_status == "upload_failed" or upload_status == "failed" or pending_reason == "upload_rpa_failed":
return {
"reason": "upload_failed",
"label": "异常:上传失败",
"summary": f"{task_no} 上传失败",
}
if _clean_text(getattr(task, "error_message", None)):
return {
"reason": "error",
"label": "异常:处理失败",
"summary": f"{task_no} 处理失败",
}
return None
def _last_action_target(
*,
events: list[ShippingTaskEvent],
task_by_id: dict[int, ShippingTask],
) -> tuple[dict[str, str], str]:
"""
根据最近事件提取最后动作对象。
核心逻辑:只识别对指代解析价值高的人工动作事件,如 confirm/rematch/reparse,避免把系统内部流水误当“用户刚才那个”。
"""
best_match: tuple[int, dict[str, str], str] | None = None
for event in events:
event_type = _clean_text(getattr(event, "event_type", None))
meta = _ACTION_EVENT_MAP.get(event_type)
if not meta:
continue
detail = getattr(event, "detail_json", None)
task_no = ""
source = ""
if isinstance(detail, dict):
task_no = _clean_text(detail.get("target_id")).upper()
source = _clean_text(detail.get("source")).lower()
if not task_no:
task = task_by_id.get(int(getattr(event, "task_id", 0) or 0))
task_no = _task_no(task)
if not task_no:
continue
priority = meta.priority
if source in {"workspace_api", "tool_api"}:
priority += 5
candidate_ref = build_object_ref("task", task_no, action=meta.action)
candidate_summary = meta.summary_template.format(task_no=task_no)
if best_match is None or priority > best_match[0]:
best_match = (priority, candidate_ref, candidate_summary)
if best_match is None:
return {}, ""
return best_match[1], best_match[2]
def _last_failed_target(tasks: list[ShippingTask]) -> tuple[dict[str, str], str]:
"""
提取最近失败或异常的目标对象。
核心逻辑:优先按任务最近更新时间选择一个失败任务,供“上一个失败的”之类模糊指代使用。
"""
for task in tasks:
failure = _task_failure_descriptor(task)
task_no = _task_no(task)
if not failure or not task_no:
continue
return (
build_object_ref("task", task_no, reason=failure["reason"], label=failure["label"]),
failure["summary"],
)
return {}, ""
def _candidate_refs(tasks: list[ShippingTask], focus_task_no: str) -> list[dict[str, str]]:
"""
生成模糊指代候选对象列表。
核心逻辑:仅暴露少量异常/失败任务,如 shortage/rejected/upload_failed,避免把整批任务全部透传给 Dify。
"""
candidates: list[dict[str, str]] = []
seen: set[str] = set()
for task in tasks:
task_no = _task_no(task)
failure = _task_failure_descriptor(task)
if not task_no or not failure:
continue
if focus_task_no and task_no == focus_task_no:
continue
if task_no in seen:
continue
candidates.append(build_object_ref("task", task_no, label=failure["label"]))
seen.add(task_no)
return candidates
def _build_recent_activity_summary(
*,
batch: ShippingBatch | None,
focus_task_no: str,
last_action_summary: str,
last_failed_summary: str,
candidates: list[dict[str, str]],
) -> str:
"""
组装 recent_activity_summary 短摘要。
核心逻辑:优先描述最近动作、当前 focus 和最近失败,再补少量候选摘要,帮助 Dify 理解“继续/刚才那个/上一个失败的”。
"""
pieces: list[str] = []
if last_action_summary:
pieces.append(last_action_summary)
if focus_task_no:
pieces.append(f"当前 focus 为 {focus_task_no}")
elif _clean_text(getattr(batch, "batch_no", None)):
pieces.append(f"当前批次为 {_clean_text(batch.batch_no).upper()}")
if last_failed_summary:
pieces.append(last_failed_summary)
if len(candidates) > 1:
candidate_labels = "、".join(
f"{item['id']}({item.get('label') or '候选'})"
for item in candidates[:MAX_REFERENCE_SUMMARY_CANDIDATES]
if item.get("id")
)
if candidate_labels:
pieces.append(f"候选对象:{candidate_labels}")
return (";".join(pieces) + "。") if pieces else ""
def build_shipping_reference_context(
*,
batch: ShippingBatch | None,
focus_task: ShippingTask | None,
) -> dict[str, Any]:
"""
构建发货通知 Agent 专用 reference_context。
【AI 触发时机】:当用户在 HXOPS 已做确认、重匹配、切票等动作后,又在对话里说“继续”“刚才那个”“上一个失败的”时,
Dify 需要优先读取这份上下文理解当前现场,但不能直接据此推进业务状态。
核心逻辑:读取 batch.current_focus_task_no、任务状态和最近少量事件,提炼 focus_object / last_action_target /
last_failed_target / candidates / recent_activity_summary 五类短期线索;不输出全量任务详情或完整事件日志。
Args:
batch: 当前批次;可为空。
focus_task: 当前焦点任务;可为空。
Returns:
shipping_notice 领域的 reference_context;没有有效线索时返回空 dict。
"""
tasks = _collect_batch_tasks(batch, focus_task)
focus_task_no = _task_no(focus_task)
if not focus_task_no and batch and _clean_text(getattr(batch, "current_focus_task_no", None)):
focus_task_no = _clean_text(batch.current_focus_task_no).upper()
if not tasks and not focus_task_no:
return {}
events = _recent_events(tasks)
task_by_id = {int(task.id): task for task in tasks if getattr(task, "id", None) is not None}
last_action_target, last_action_summary = _last_action_target(events=events, task_by_id=task_by_id)
last_failed_target, last_failed_summary = _last_failed_target(tasks)
candidates = _candidate_refs(tasks, focus_task_no)
focus_object = build_object_ref("task", focus_task_no) if focus_task_no else {}
recent_activity_summary = _build_recent_activity_summary(
batch=batch,
focus_task_no=focus_task_no,
last_action_summary=last_action_summary,
last_failed_summary=last_failed_summary,
candidates=candidates,
)
return build_reference_context(
recent_activity_summary=recent_activity_summary or None,
focus_object=focus_object or None,
last_action_target=last_action_target or None,
last_failed_target=last_failed_target or None,
candidates=candidates or None,
)
__all__ = ["build_shipping_reference_context"]
@@ -1,7 +1,7 @@
"""
services/shipping_notice/rpa_attempts.py
用途:统计任务的 RPA 库存导出与货代上传重试次数,并给出默认上限。
用途:统计任务的 RPA 库存导出与货代上传重试次数,并返回统一上限。
依赖:ShippingTask、ShippingTaskEvent 模型与事件查询逻辑。
逻辑:由 inventory_rpa_workflow、fulfillment_workflow 等模块调用本文件,决定是否还能继续触发 RPA 重试。
"""
@@ -13,7 +13,7 @@ from datetime import datetime
from app.models import ShippingTask, ShippingTaskEvent
DEFAULT_RPA_INVENTORY_MAX_ATTEMPTS = 1
FIXED_RPA_INVENTORY_MAX_ATTEMPTS = 1
DEFAULT_RPA_UPLOAD_MAX_ATTEMPTS = 3
_INVENTORY_SUCCESS_EVENTS = {
@@ -87,15 +87,8 @@ def upload_rpa_attempts(task: ShippingTask | None) -> int:
def max_rpa_inventory_attempts() -> int:
"""RPA 库存导出最大重试次数(环境变量 SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS)。"""
value = os.getenv("SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS")
if value is None or not str(value).strip():
return DEFAULT_RPA_INVENTORY_MAX_ATTEMPTS
try:
parsed = int(value)
except (TypeError, ValueError):
return DEFAULT_RPA_INVENTORY_MAX_ATTEMPTS
return max(parsed, 1)
"""RPA 库存导出固定只允许自动尝试一次;再次尝试必须由用户显式点击 retry_rpa。"""
return FIXED_RPA_INVENTORY_MAX_ATTEMPTS
def max_rpa_upload_attempts() -> int:
@@ -0,0 +1,239 @@
"""
backend/app/services/shipping_notice/runtime_context.py
用途:构建货代发货通知 Agent 的 agent_runtime_context 领域适配层。
依赖:models.ShippingBatch/ShippingTask、agent_runtime_context.builder。
逻辑:dify_inputs 与后台编排器在调用 Dify 前通过本模块生成最新业务现场,
Dify 只消费 snapshot,任务推进仍以 HXOPS 状态机和 Tool API 为准。
"""
from __future__ import annotations
from typing import Any
from app.models import ShippingBatch, ShippingTask
from app.services.agent_runtime_context.builder import build_agent_runtime_context
from app.services.shipping_notice.reference_context import build_shipping_reference_context
SHIPPING_NOTICE_AGENT_CODE = "shipping_notice"
def _clean_text(value: Any) -> str:
"""
将模型字段规范化为短文本。
核心逻辑:统一处理 None/空白字符串,避免 domain/state_hint 中混入空值。
Args:
value: 待规范化字段。
Returns:
去除首尾空白后的字符串。
"""
return str(value or "").strip()
def _batch_no(batch: ShippingBatch | None, task: ShippingTask | None) -> str:
"""
获取当前上下文的批次号。
核心逻辑:优先使用显式 batch;缺失时从 task.batch 补齐,避免后台单票 run 丢失批次锚点。
Args:
batch: 当前批次。
task: 当前任务。
Returns:
批次号;无法识别时返回空字符串。
"""
if batch and _clean_text(getattr(batch, "batch_no", None)):
return _clean_text(batch.batch_no).upper()
task_batch = getattr(task, "batch", None)
if task_batch and _clean_text(getattr(task_batch, "batch_no", None)):
return _clean_text(task_batch.batch_no).upper()
return ""
def _task_no(task: ShippingTask | None) -> str:
"""
获取当前上下文的任务号。
核心逻辑:只使用已解析出的显式任务对象,不按会话猜测最近任务,避免多票串单。
Args:
task: 当前任务。
Returns:
任务号;缺失时返回空字符串。
"""
return _clean_text(getattr(task, "task_no", None)).upper()
def _build_refs(
*,
task: ShippingTask | None,
batch: ShippingBatch | None,
run_purpose: str | None,
) -> dict[str, str]:
"""
构建新版 agent_runtime_context.refs。
核心逻辑:使用稳定业务字段名 task_no/batch_no/run_purpose/file_name,区别于旧 hxops_context 的 task/batch。
Args:
task: 当前任务。
batch: 当前批次。
run_purpose: 本次 Dify run 的目的。
Returns:
非空业务锚点字典。
"""
refs: dict[str, str] = {}
task_no = _task_no(task)
batch_no = _batch_no(batch, task)
file_name = _clean_text(getattr(task, "source_file_name", None))
normalized_run_purpose = _clean_text(run_purpose)
if task_no:
refs["task_no"] = task_no
if batch_no:
refs["batch_no"] = batch_no
if normalized_run_purpose:
refs["run_purpose"] = normalized_run_purpose
if file_name:
refs["file_name"] = file_name
return refs
def _build_state_hint(task: ShippingTask | None, batch: ShippingBatch | None) -> dict[str, Any]:
"""
构建发货通知运行态提示。
核心逻辑:只放 Dify 判断流程所需的状态摘要;真正能否推进仍由 HXOPS Tool/状态机校验。
Args:
task: 当前任务。
batch: 当前批次。
Returns:
状态提示字典。
"""
state_hint: dict[str, Any] = {}
task_no = _task_no(task)
if task_no:
state_hint["focus_task_no"] = task_no
elif batch and _clean_text(getattr(batch, "current_focus_task_no", None)):
state_hint["focus_task_no"] = _clean_text(batch.current_focus_task_no).upper()
if task is not None:
for attr, key in (
("current_step", "current_step"),
("process_status", "status"),
("review_status", "review_status"),
("match_status", "match_status"),
("pending_human_reason", "pending_human_reason"),
("upload_status", "upload_status"),
):
value = _clean_text(getattr(task, attr, None))
if value:
state_hint[key] = value
batch_no = _batch_no(batch, task)
if batch_no:
state_hint["batch_no"] = batch_no
return state_hint
def _build_summary(
*,
task: ShippingTask | None,
batch: ShippingBatch | None,
run_purpose: str | None,
) -> str:
"""
构建给 Dify 阅读的短摘要。
核心逻辑:用自然语言说明当前 run 的任务、批次、文件和状态,避免 Dify 依赖 conversation memory 猜现场。
Args:
task: 当前任务。
batch: 当前批次。
run_purpose: 本次 Dify run 的目的。
Returns:
200 字以内的现场摘要。
"""
pieces: list[str] = []
task_no = _task_no(task)
batch_no = _batch_no(batch, task)
file_name = _clean_text(getattr(task, "source_file_name", None))
status = _clean_text(getattr(task, "process_status", None))
current_step = _clean_text(getattr(task, "current_step", None))
normalized_run_purpose = _clean_text(run_purpose)
if task_no:
pieces.append(f"当前任务 {task_no}")
if batch_no:
pieces.append(f"属于批次 {batch_no}")
if file_name:
pieces.append(f"来源文件 {file_name}")
if normalized_run_purpose:
pieces.append(f"本次执行目的为 {normalized_run_purpose}")
if status:
pieces.append(f"当前状态 {status}")
if current_step:
pieces.append(f"当前步骤 {current_step}")
if not pieces:
return "当前为货代发货通知 Agent 会话,尚未解析出明确任务或批次锚点。"
return ",".join(pieces) + "。"
def build_shipping_runtime_context(
*,
session_id: str,
task: ShippingTask | None = None,
batch: ShippingBatch | None = None,
trigger_source: str | None = None,
request_id: str | None = None,
locale: str | None = None,
scope: str = "task_run",
run_purpose: str | None = None,
) -> dict[str, Any]:
"""
构建货代发货通知 Agent 的 agent_runtime_context。
核心逻辑:以 HXOPS DB 中的 task/batch 为事实源,生成 refs/domain.state_hint/reference_context snapshot,
供 Dify 每次 run 显式识别现场。
Args:
session_id: HXOPS 本地 ChatSession.session_id。
task: 当前显式任务;禁止在本函数内按会话猜测。
batch: 当前批次。
trigger_source: 触发来源,如 frontend_chat/backend_orchestrator。
request_id: 本次请求 ID。
locale: 用户语言。
scope: 上下文作用域。
run_purpose: 本次 Dify run 的目的,如 parse_notice。
Returns:
agent_runtime_context 字典;session_id 为空时返回空 dict。
"""
domain = {
"type": SHIPPING_NOTICE_AGENT_CODE,
"summary": _build_summary(task=task, batch=batch, run_purpose=run_purpose),
"state_hint": _build_state_hint(task, batch),
"available_actions_hint": [],
}
reference_context = build_shipping_reference_context(
batch=batch,
focus_task=task,
)
return build_agent_runtime_context(
agent_code=SHIPPING_NOTICE_AGENT_CODE,
scope=scope,
session_id=session_id,
request_id=request_id,
trigger_source=trigger_source,
locale=locale,
refs=_build_refs(task=task, batch=batch, run_purpose=run_purpose),
domain=domain,
reference_context=reference_context,
)
@@ -15,7 +15,7 @@ import uuid
from flask import current_app
from app import db
from app.models import ShippingTask, ShippingTaskEvent
from app.models import ShippingBatch, ShippingTask, ShippingTaskEvent
from app.services.shipping_notice.constants import AUTO_CHAIN_FALLBACK
@@ -56,7 +56,7 @@ def auto_rpa_inventory_enabled() -> bool:
def rpa_inventory_timeout_seconds() -> int:
"""RPA 库存导出等待超时秒数。"""
return cfg_int("SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS", 120, min_value=5)
return cfg_int("SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS", 360, min_value=5)
def auto_mapping_allow_llm() -> bool:
@@ -181,6 +181,58 @@ def generate_task_no() -> str:
return f"SN-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
def _clean_event_value(value: Any) -> str:
"""把事件详情值规范化为短字符串;空值返回空字符串。"""
return str(value or "").strip()
def _task_batch_no(task: ShippingTask | None) -> str:
"""从任务关系中提取批次号。"""
batch = getattr(task, "batch", None)
return _clean_event_value(getattr(batch, "batch_no", None))
def build_task_action_event_detail(
task: ShippingTask,
*,
action: str,
source: str,
comment: str | None = None,
extra: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""
构建任务动作类事件详情。
核心逻辑:统一补齐 action/source/target/batch/conversation 等字段,保证 reference_context 后续可以稳定消费本地动作事件。
Args:
task: 动作作用的目标任务。
action: 规范化动作名,如 confirm/reject/rematch/reparse/switch_focus。
source: 触发来源,如 workspace_api/tool_api/backend_orchestrator。
comment: 用户附带备注。
extra: 其他扩展字段,例如 previous_focus_task_no。
Returns:
标准化的事件 detail_json。
"""
detail: dict[str, Any] = {
"action": _clean_event_value(action),
"source": _clean_event_value(source),
"target_type": "task",
"target_id": _clean_event_value(getattr(task, "task_no", None)),
"batch_no": _task_batch_no(task),
"conversation_id": _clean_event_value(getattr(task, "conversation_id", None)),
}
normalized_comment = _clean_event_value(comment)
if normalized_comment:
detail["comment"] = normalized_comment
for key, value in (extra or {}).items():
if value is None:
continue
detail[key] = value
return detail
def log_task_event(task: ShippingTask, event_type: str, detail: dict[str, Any] | None = None) -> None:
"""写入 ShippingTaskEvent 审计记录(task 尚未 flush 时自动 flush)。"""
if task.id is None:
@@ -190,3 +242,81 @@ def log_task_event(task: ShippingTask, event_type: str, detail: dict[str, Any] |
event_type=event_type,
detail_json=detail or {},
))
def log_task_action_event(
task: ShippingTask,
event_type: str,
*,
action: str,
source: str,
comment: str | None = None,
extra: dict[str, Any] | None = None,
) -> None:
"""
写入标准化任务动作事件。
核心逻辑:在原始 event_type 之外,统一补足 reference_context 所需的动作元数据,避免各入口散落拼接。
"""
log_task_event(
task,
event_type,
build_task_action_event_detail(
task,
action=action,
source=source,
comment=comment,
extra=extra,
),
)
def switch_batch_focus(
batch: ShippingBatch,
task: ShippingTask,
*,
source: str,
event_type: str = "focus_switched",
comment: str | None = None,
emit_when_unchanged: bool = True,
extra: dict[str, Any] | None = None,
) -> bool:
"""
切换批次焦点任务并写入标准事件。
核心逻辑:统一处理 current_focus_task_no 更新与 focus 切换事件,供 workspace/tool/orchestrator 复用。
Args:
batch: 所属批次。
task: 新焦点任务。
source: 触发来源,如 workspace_api/tool_api/backend_orchestrator。
event_type: 事件名;用户态默认 focus_switched,系统自动切票可传 focus_auto_switched。
comment: 用户备注。
emit_when_unchanged: 焦点未变化时是否仍记事件。
extra: 附加字段。
Returns:
是否实际发生焦点变化。
"""
previous_focus_task_no = _clean_event_value(getattr(batch, "current_focus_task_no", None))
next_focus_task_no = _clean_event_value(getattr(task, "task_no", None))
changed = previous_focus_task_no != next_focus_task_no
batch.current_focus_task_no = next_focus_task_no or None
if changed or emit_when_unchanged:
detail_extra = {
"previous_focus_task_no": previous_focus_task_no or None,
"next_focus_task_no": next_focus_task_no or None,
"changed": changed,
}
if extra:
detail_extra.update(extra)
log_task_action_event(
task,
event_type,
action="switch_focus",
source=source,
comment=comment,
extra=detail_extra,
)
return changed
@@ -87,13 +87,18 @@ _PENDING_REASON_LABELS: dict[str, str] = {
def user_facing_task_stage(task: ShippingTask) -> str:
"""Short Chinese label for chat / get_task_status — no snake_case codes."""
ui = resolve_task_ui_state(task)
if ui.checkpoint and ui.checkpoint in _CHECKPOINT_LABELS:
return _CHECKPOINT_LABELS[ui.checkpoint]
"""
Short Chinese label for chat / get_task_status — no snake_case codes.
核心逻辑:优先返回更具体的 pending_human_reason 标签,避免 `rpa_pending`
这类细粒度状态被通用 checkpoint(如“待上传或获取库存”)覆盖。
"""
reason = str(task.pending_human_reason or "").strip()
if reason in _PENDING_REASON_LABELS:
return _PENDING_REASON_LABELS[reason]
ui = resolve_task_ui_state(task)
if ui.checkpoint and ui.checkpoint in _CHECKPOINT_LABELS:
return _CHECKPOINT_LABELS[ui.checkpoint]
process = str(task.process_status or "").strip()
return _PROCESS_STATUS_LABELS.get(process, "处理中")
@@ -0,0 +1,122 @@
"""
backend/tests/test_agent_runtime_context_builder.py
用途:验证 agent_runtime_context 平台协议构建、序列化与 reference builder 行为。
依赖:agent_runtime_context.builder/policy/reference。
逻辑:覆盖平台上下文字段、refs 规范化、Dify JSON 字符串输入与 reference_context 裁剪规则。
"""
import json
import pytest
from app.services.agent_runtime_context import AGENT_RUNTIME_CONTEXT_INPUT
from app.services.agent_runtime_context.builder import (
build_agent_runtime_context,
build_dify_inputs,
serialize_for_dify,
)
from app.services.agent_runtime_context.policy import (
MAX_CONTEXT_JSON_CHARS,
MAX_DOMAIN_SUMMARY_CHARS,
MAX_RECENT_ACTIVITY_SUMMARY_CHARS,
)
from app.services.agent_runtime_context.reference import (
MAX_REFERENCE_CANDIDATES,
build_object_ref,
build_reference_context,
)
def test_build_agent_runtime_context_normalizes_core_fields():
"""新版上下文应输出稳定协议字段并裁剪重复/空 refs。"""
context = build_agent_runtime_context(
agent_code="shipping_notice",
scope="task_run",
session_id=" conv-001 ",
request_id=" req-001 ",
trigger_source=" frontend_chat ",
locale=" zh-CN ",
refs={"task_no": " SN-001 ", "batch_no": "SB-001", "empty": ""},
domain={"type": "shipping_notice", "summary": "当前处理 SN-001"},
)
assert context["schema_version"] == "1"
assert context["context_id"].startswith("ctx_")
assert context["agent_code"] == "shipping_notice"
assert context["scope"] == "task_run"
assert context["platform"] == {
"session_id": "conv-001",
"parent_session_id": "conv-001",
"request_id": "req-001",
"trigger_source": "frontend_chat",
"locale": "zh-CN",
}
assert context["refs"] == {"task_no": "SN-001", "batch_no": "SB-001"}
assert context["domain"]["summary"] == "当前处理 SN-001"
def test_serialize_for_dify_outputs_json_string():
"""Dify Start 节点应接收 JSON 字符串而不是 object。"""
context = build_agent_runtime_context(
agent_code="file_check",
scope="chat_turn",
session_id="conv-file-check-001",
refs={"schedule_task_id": 123},
)
inputs = build_dify_inputs(context)
serialized = inputs[AGENT_RUNTIME_CONTEXT_INPUT]
assert isinstance(serialized, str)
assert json.loads(serialized)["refs"] == {"schedule_task_id": "123"}
def test_policy_truncates_domain_summary_before_serialization():
"""超长领域摘要应先被裁剪,避免把历史流水塞进 Runtime。"""
long_summary = "A" * (MAX_DOMAIN_SUMMARY_CHARS + 50)
context = build_agent_runtime_context(
session_id="conv-long-summary-001",
domain={"type": "generic", "summary": long_summary},
)
assert len(context["domain"]["summary"]) == MAX_DOMAIN_SUMMARY_CHARS
def test_build_reference_context_normalizes_objects_candidates_and_summary():
"""reference_context builder 应统一裁剪摘要、规范对象引用并限制候选数量。"""
reference_context = build_reference_context(
recent_activity_summary="A" * (MAX_RECENT_ACTIVITY_SUMMARY_CHARS + 32),
focus_object=build_object_ref("task", "SN-FOCUS-001"),
last_action_target={"type": "task", "id": "SN-ACTION-001", "action": "confirm"},
candidates=[
{"type": "task", "id": f"SN-CAND-{index:03d}", "label": f"候选 {index}"}
for index in range(MAX_REFERENCE_CANDIDATES + 3)
],
)
assert len(reference_context["recent_activity_summary"]) == MAX_RECENT_ACTIVITY_SUMMARY_CHARS
assert reference_context["focus_object"] == {"type": "task", "id": "SN-FOCUS-001"}
assert reference_context["last_action_target"] == {
"type": "task",
"id": "SN-ACTION-001",
"action": "confirm",
}
assert len(reference_context["candidates"]) == MAX_REFERENCE_CANDIDATES
def test_serialize_for_dify_rejects_oversized_context():
"""序列化后超过总长度上限时应显式失败,避免输出非法截断 JSON。"""
context = {
"schema_version": "1",
"context_id": "ctx-too-large",
"agent_code": "generic",
"scope": "chat_turn",
"platform": {"session_id": "conv-too-large"},
"refs": {},
"payload": "X" * (MAX_CONTEXT_JSON_CHARS + 1),
}
with pytest.raises(ValueError):
serialize_for_dify(context)
@@ -0,0 +1,188 @@
"""
backend/tests/test_agent_runtime_context_generic_adapter.py
用途:验证 generic adapter 与统一 Dify inputs 分发入口的兜底行为。
依赖:agent_runtime_context.adapters.generic、agent_runtime_context.dify_inputs、pytest。
逻辑:覆盖通用 Agent 的最小 runtime_context 序列化,以及 shipping/file_check/generic 三类分发路径。
"""
from __future__ import annotations
import json
from types import SimpleNamespace
import app.services.agent_runtime_context.dify_inputs as dify_inputs_module
from app.services.agent_runtime_context import AGENT_RUNTIME_CONTEXT_INPUT
from app.services.agent_runtime_context.adapters.generic import (
build_generic_dify_inputs,
resolve_agent_code,
)
from app.services.agent_runtime_context.dify_inputs import build_chat_dify_inputs
def test_resolve_agent_code_reads_extra_config_or_falls_back_to_generic():
"""通用 adapter 应优先读取 extra_config.agent_code,缺省时回退为 generic。"""
configured_agent = SimpleNamespace(extra_config={"agent_code": "kb_faq_agent"})
default_agent = SimpleNamespace(extra_config={})
assert resolve_agent_code(configured_agent) == "kb_faq_agent"
assert resolve_agent_code(default_agent) == "generic"
def test_build_generic_dify_inputs_outputs_only_agent_runtime_context_json():
"""generic adapter 应只输出 agent_runtime_context,且其内容必须可解析。"""
agent = SimpleNamespace(
description="知识库常见问题问答",
extra_config={
"agent_code": "kb_faq_agent",
"runtime_context_summary": "知识库问答助手",
},
)
inputs = build_generic_dify_inputs(
session_id="conv-generic-001",
agent=agent,
request_id="req-generic-001",
trigger_source="frontend_chat",
)
assert set(inputs.keys()) == {AGENT_RUNTIME_CONTEXT_INPUT}
payload = json.loads(inputs[AGENT_RUNTIME_CONTEXT_INPUT])
assert payload["agent_code"] == "kb_faq_agent"
assert payload["platform"]["session_id"] == "conv-generic-001"
assert payload["platform"]["request_id"] == "req-generic-001"
assert payload["domain"] == {
"type": "generic",
"summary": "知识库问答助手",
}
def test_build_chat_dify_inputs_dispatches_shipping_adapter(monkeypatch):
"""shipping Agent 应从 adapter_hints 读取业务提示,而不是暴露平台级 task/batch 参数。"""
agent = SimpleNamespace(name="货代发货通知 Agent", extra_config={})
monkeypatch.setattr(dify_inputs_module, "is_shipping_notice_chat_agent", lambda _: True)
monkeypatch.setattr(dify_inputs_module, "agent_declares_file_check_progress", lambda _: False)
monkeypatch.setattr(dify_inputs_module, "is_file_check_chat_agent", lambda _: False)
monkeypatch.setattr(
dify_inputs_module,
"build_shipping_notice_dify_inputs",
lambda conversation_id, **kwargs: {
"adapter": "shipping",
"conversation_id": conversation_id,
"task_id": kwargs.get("task_id"),
"batch_no": kwargs.get("batch_no"),
},
)
inputs = build_chat_dify_inputs(
agent,
session_id="conv-shipping-001",
adapter_hints={
"shipping_notice": {
"task_id": "SN-001",
"batch_no": "BATCH-001",
}
},
)
assert inputs == {
"adapter": "shipping",
"conversation_id": "conv-shipping-001",
"task_id": "SN-001",
"batch_no": "BATCH-001",
}
def test_build_chat_dify_inputs_dispatches_file_check_adapter(monkeypatch):
"""file_check Agent 应继续沿用 task_id 专用 inputs,不自动混入 generic 上下文。"""
agent = SimpleNamespace(name="文件检核 Agent", extra_config={})
monkeypatch.setattr(dify_inputs_module, "is_shipping_notice_chat_agent", lambda _: False)
monkeypatch.setattr(dify_inputs_module, "agent_declares_file_check_progress", lambda _: True)
monkeypatch.setattr(dify_inputs_module, "is_file_check_chat_agent", lambda _: False)
monkeypatch.setattr(
dify_inputs_module,
"build_file_check_dify_inputs",
lambda current_agent, required: {
"adapter": "file_check",
"agent_name": current_agent.name,
"required": required,
},
)
inputs = build_chat_dify_inputs(agent, session_id="conv-file-check-001")
assert inputs == {
"adapter": "file_check",
"agent_name": "文件检核 Agent",
"required": True,
}
def test_build_chat_dify_inputs_falls_back_to_generic_adapter(monkeypatch):
"""未命中专用 adapter 的 Agent 应统一走 generic 兜底。"""
agent = SimpleNamespace(name="知识库问答 Agent", extra_config={})
monkeypatch.setattr(dify_inputs_module, "is_shipping_notice_chat_agent", lambda _: False)
monkeypatch.setattr(dify_inputs_module, "agent_declares_file_check_progress", lambda _: False)
monkeypatch.setattr(dify_inputs_module, "is_file_check_chat_agent", lambda _: False)
monkeypatch.setattr(
dify_inputs_module,
"build_generic_dify_inputs",
lambda **kwargs: {
"adapter": "generic",
"session_id": kwargs["session_id"],
},
)
inputs = build_chat_dify_inputs(agent, session_id="conv-generic-002")
assert inputs == {
"adapter": "generic",
"session_id": "conv-generic-002",
}
def test_build_chat_dify_inputs_ignores_invalid_shipping_hints(monkeypatch):
"""shipping hints 非字典时应安全回退为空,避免平台入口依赖脏业务结构。"""
agent = SimpleNamespace(name="货代发货通知 Agent", extra_config={})
monkeypatch.setattr(dify_inputs_module, "is_shipping_notice_chat_agent", lambda _: True)
monkeypatch.setattr(dify_inputs_module, "agent_declares_file_check_progress", lambda _: False)
monkeypatch.setattr(dify_inputs_module, "is_file_check_chat_agent", lambda _: False)
monkeypatch.setattr(
dify_inputs_module,
"build_shipping_notice_dify_inputs",
lambda conversation_id, **kwargs: {
"conversation_id": conversation_id,
"task_id": kwargs.get("task_id"),
"batch_no": kwargs.get("batch_no"),
},
)
inputs = build_chat_dify_inputs(
agent,
session_id="conv-shipping-002",
adapter_hints={"shipping_notice": "invalid"},
)
assert inputs == {
"conversation_id": "conv-shipping-002",
"task_id": None,
"batch_no": None,
}
def test_build_chat_dify_inputs_returns_empty_when_session_id_missing(monkeypatch):
"""统一分发入口在缺少 session_id 时应直接返回空 dict。"""
agent = SimpleNamespace(name="任意 Agent", extra_config={})
monkeypatch.setattr(
dify_inputs_module,
"is_shipping_notice_chat_agent",
lambda _: (_ for _ in ()).throw(AssertionError("should not dispatch when session_id is empty")),
)
assert build_chat_dify_inputs(agent, session_id=" ") == {}
@@ -0,0 +1,179 @@
"""
backend/tests/test_agent_runtime_context_tools.py
用途:验证 agent_runtime_context Tool API 的鉴权、白名单解析和 OpenAPI 文档。
依赖:Flask 测试 client、agent_runtime_context.builder。
逻辑:模拟 Dify 使用 X-Integration-Key 调用 parse 工具,确保只能读取允许字段且不会执行任意路径。
"""
from __future__ import annotations
import json
from pathlib import Path
from app.services.agent_runtime_context.builder import build_agent_runtime_context, serialize_for_dify
def _headers(app) -> dict[str, str]:
"""
构建 Tool API 测试鉴权 Header。
核心逻辑:复用平台 INTEGRATION_API_KEY,贴近 Dify OpenAPI Tool 的实际调用方式。
Args:
app: Flask 测试应用。
Returns:
请求 Header 字典。
"""
app.config["INTEGRATION_API_KEY"] = "test-integration-key"
return {
"Content-Type": "application/json",
"X-Integration-Key": "test-integration-key",
}
def _serialized_context() -> str:
"""
构建测试用 agent_runtime_context JSON 字符串。
核心逻辑:覆盖 platform、refs、domain.state_hint 三类常用路径。
Returns:
JSON 字符串。
"""
context = build_agent_runtime_context(
agent_code="shipping_notice",
scope="task_run",
session_id="conv-parse-001",
request_id="req-parse-001",
trigger_source="backend_orchestrator",
refs={
"task_no": "SN-PARSE-001",
"batch_no": "SB-PARSE-001",
"run_purpose": "parse_notice",
},
domain={
"type": "shipping_notice",
"summary": "当前任务 SN-PARSE-001 属于批次 SB-PARSE-001。",
"state_hint": {
"focus_task_no": "SN-PARSE-001",
"status": "created",
},
},
reference_context={
"recent_activity_summary": "用户已确认 SN-PARSE-000 解析;当前 focus 为 SN-PARSE-001。",
"focus_object": {"type": "task", "id": "SN-PARSE-001"},
"last_action_target": {"type": "task", "id": "SN-PARSE-000", "action": "confirm_parse"},
"last_failed_target": {"type": "task", "id": "SN-PARSE-002", "reason": "shortage"},
"candidates": [{"type": "task", "id": "SN-PARSE-002", "label": "异常:库存不足"}],
},
)
return serialize_for_dify(context)
def test_parse_agent_runtime_context_tool_returns_allowed_paths(app, client):
"""Dify 传入 JSON 字符串与白名单路径时,应返回 data/missing。"""
res = client.post(
"/api/agent-runtime-context/tools/parse",
headers=_headers(app),
json={
"agent_runtime_context": _serialized_context(),
"paths": [
"platform.session_id",
"refs.task_no",
"refs.batch_no",
"domain.state_hint.status",
"reference_context.focus_object",
"reference_context.last_action_target",
"reference_context.focus_object.id",
"reference_context.last_action_target.action",
"reference_context.last_failed_target.reason",
"refs.file_name",
],
},
)
assert res.status_code == 200
body = res.get_json()
assert body["status"] == "ok"
assert body["data"]["platform.session_id"] == "conv-parse-001"
assert body["data"]["refs.task_no"] == "SN-PARSE-001"
assert body["data"]["refs.batch_no"] == "SB-PARSE-001"
assert body["data"]["domain.state_hint.status"] == "created"
assert body["data"]["reference_context.focus_object"] == {"type": "task", "id": "SN-PARSE-001"}
assert body["data"]["reference_context.last_action_target"] == {
"type": "task",
"id": "SN-PARSE-000",
"action": "confirm_parse",
}
assert body["data"]["reference_context.focus_object.id"] == "SN-PARSE-001"
assert body["data"]["reference_context.last_action_target.action"] == "confirm_parse"
assert body["data"]["reference_context.last_failed_target.reason"] == "shortage"
assert body["missing"] == ["refs.file_name"]
def test_parse_agent_runtime_context_tool_rejects_disallowed_paths(app, client):
"""非白名单路径应被拒绝,防止 Dify 读取任意上下文片段。"""
res = client.post(
"/api/agent-runtime-context/tools/parse",
headers=_headers(app),
json={
"agent_runtime_context": _serialized_context(),
"paths": ["platform.session_id", "domain.state_hint.secret"],
},
)
assert res.status_code == 400
body = res.get_json()
assert body["ok"] is False
assert body["message"] == "paths_not_allowed"
def test_parse_agent_runtime_context_tool_requires_auth(app, client):
"""parse 工具必须携带平台集成密钥。"""
app.config["INTEGRATION_API_KEY"] = "test-integration-key"
res = client.post(
"/api/agent-runtime-context/tools/parse",
json={"agent_runtime_context": _serialized_context(), "paths": ["platform.session_id"]},
)
assert res.status_code == 401
body = res.get_json()
assert body["ok"] is False
assert body["error_code"] == "missing_auth"
def test_agent_runtime_context_openapi_is_public(app, client):
"""OpenAPI 文档应允许 Dify/开发者无鉴权导入。"""
res = client.get("/api/agent-runtime-context/tools/openapi.json")
assert res.status_code == 200
body = res.get_json()
assert body["openapi"] == "3.0.0"
assert "/tools/parse" in body["paths"]
assert body["paths"]["/tools/parse"]["post"]["operationId"] == "parse_agent_runtime_context"
spec_text = str(body)
assert "reference_context" in spec_text
assert "多候选" in spec_text
assert "追问" in spec_text
assert "state_hint" in spec_text
assert "状态机" in spec_text
assert "不能依据上下文直接宣布完成" in spec_text
def test_agent_runtime_context_static_openapi_contains_reference_contract():
"""静态 OpenAPI 快照应锁定 reference_context 的消费约束,避免导入文件与动态 spec 漂移。"""
spec_path = Path(__file__).resolve().parents[2] / "docs" / "openapi" / "agent_runtime_context_tools.dify.json"
spec = json.loads(spec_path.read_text(encoding="utf-8"))
assert spec["openapi"] == "3.0.0"
assert "/tools/parse" in spec["paths"]
spec_text = str(spec)
assert "reference_context" in spec_text
assert "多候选" in spec_text
assert "追问" in spec_text
assert "state_hint" in spec_text
assert "状态机" in spec_text
assert "不能依据上下文直接宣布完成" in spec_text
@@ -0,0 +1,273 @@
"""
tests/test_dify_workflow_reliability.py
用途:覆盖 Dify Workflow streaming 断连补偿、重试与可靠性元信息。
"""
from __future__ import annotations
import json
from types import SimpleNamespace
import pytest
import requests
from app.services.dify import DifyService
from app.services.file_check import FileCheckService
class _Agent:
id = 1
dify_api_key = "secret"
api_base_url = "http://dify.example/v1"
def _sse_lines(*events: dict) -> list[bytes]:
return [f"data: {json.dumps(evt, ensure_ascii=False)}".encode("utf-8") for evt in events]
def _mock_stream_response(monkeypatch, *, status_code: int = 200, lines: list[bytes] | None = None, exc: Exception | None = None):
calls = {"count": 0}
class _Resp:
def __init__(self):
self.ok = status_code < 400
self.status_code = status_code
self.text = "upstream error"
def __enter__(self):
return self
def __exit__(self, *args):
return False
def raise_for_status(self):
if not self.ok:
resp = requests.Response()
resp.status_code = self.status_code
raise requests.HTTPError(response=resp)
def iter_lines(self, decode_unicode=True):
for line in lines or []:
yield line.decode("utf-8") if decode_unicode else line
if exc is not None:
raise exc
def _post(*args, **kwargs):
calls["count"] += 1
return _Resp()
monkeypatch.setattr("app.services.dify.requests.post", _post)
return calls
def test_workflow_streaming_normal_finished(monkeypatch):
lines = _sse_lines(
{"event": "workflow_started", "data": {"workflow_run_id": "wf-ok"}},
{
"event": "workflow_finished",
"data": {
"status": "succeeded",
"workflow_run_id": "wf-ok",
"outputs": {"output": {"dify_result": "合格", "dify_message": "ok"}},
},
},
)
_mock_stream_response(monkeypatch, lines=lines)
result = DifyService.run_workflow_streaming(agent=_Agent(), inputs={"record": "x"})
assert result["status"] == "succeeded"
assert result["workflow_run_id"] == "wf-ok"
assert result["_workflow_poll_used"] is False
assert result["_workflow_retry_count"] == 0
def test_workflow_streaming_read_timeout_polls_success(monkeypatch):
lines = _sse_lines({"event": "workflow_started", "data": {"workflow_run_id": "wf-poll"}})
_mock_stream_response(
monkeypatch,
lines=lines,
exc=requests.exceptions.ReadTimeout("read timed out"),
)
def _poll(**kwargs):
return {
"id": "wf-poll",
"status": "succeeded",
"outputs": {"output": {"dify_result": "不合格", "dify_message": "from poll"}},
}
monkeypatch.setattr(DifyService, "_poll_workflow_result", staticmethod(lambda **kwargs: _poll(**kwargs)))
result = DifyService.run_workflow_streaming(agent=_Agent(), inputs={"record": "x"}, timeout=(5, 60))
assert result["status"] == "succeeded"
assert result["_workflow_poll_used"] is True
assert result["_workflow_retry_count"] == 0
assert result["_workflow_error_type"] == "read_timeout"
def test_workflow_streaming_503_retries_then_success(monkeypatch):
calls = {"count": 0}
def _post(*args, **kwargs):
calls["count"] += 1
if calls["count"] == 1:
resp = requests.Response()
resp.status_code = 503
raise requests.HTTPError(response=resp)
lines = _sse_lines(
{"event": "workflow_started", "data": {"workflow_run_id": "wf-retry"}},
{"event": "workflow_finished", "data": {"status": "succeeded", "workflow_run_id": "wf-retry"}},
)
class _Resp:
ok = True
status_code = 200
def __enter__(self):
return self
def __exit__(self, *args):
return False
def raise_for_status(self):
return None
def iter_lines(self, decode_unicode=True):
for line in lines:
yield line.decode("utf-8")
return _Resp()
monkeypatch.setattr("app.services.dify.requests.post", _post)
result = DifyService.run_workflow_streaming(agent=_Agent(), inputs={"record": "x"})
assert calls["count"] == 2
assert result["status"] == "succeeded"
assert result["_workflow_retry_count"] == 1
assert result["_workflow_poll_used"] is False
def test_workflow_streaming_401_does_not_retry(monkeypatch):
calls = {"count": 0}
def _post(*args, **kwargs):
calls["count"] += 1
resp = requests.Response()
resp.status_code = 401
raise requests.HTTPError(response=resp)
monkeypatch.setattr("app.services.dify.requests.post", _post)
with pytest.raises(requests.HTTPError):
DifyService.run_workflow_streaming(agent=_Agent(), inputs={"record": "x"})
assert calls["count"] == 1
def test_workflow_streaming_poll_timeout_sets_error_type(monkeypatch):
lines = _sse_lines({"event": "workflow_started", "data": {"workflow_run_id": "wf-timeout"}})
_mock_stream_response(
monkeypatch,
lines=lines,
exc=requests.exceptions.ReadTimeout("read timed out"),
)
monkeypatch.setattr(DifyService, "_poll_workflow_result", staticmethod(lambda **kwargs: {}))
result = DifyService.run_workflow_streaming(agent=_Agent(), inputs={"record": "x"})
assert not result.get("status")
assert result["_workflow_poll_used"] is True
assert result["_workflow_error_type"] == "poll_timeout"
assert result.get("workflow_run_id") == "wf-timeout"
def test_workflow_streaming_clean_close_without_finished_polls(monkeypatch):
"""仅收到 workflow_started、连接正常关闭且无异常时,应 poll 补偿。"""
lines = _sse_lines({"event": "workflow_started", "data": {"workflow_run_id": "wf-clean-close"}})
_mock_stream_response(monkeypatch, lines=lines)
def _poll(**kwargs):
return {
"id": "wf-clean-close",
"status": "succeeded",
"outputs": {"output": {"dify_result": "合格", "dify_message": "from poll after clean close"}},
}
monkeypatch.setattr(DifyService, "_poll_workflow_result", staticmethod(lambda **kwargs: _poll(**kwargs)))
result = DifyService.run_workflow_streaming(agent=_Agent(), inputs={"record": "x"})
assert result["status"] == "succeeded"
assert result["_workflow_poll_used"] is True
assert result.get("workflow_run_id") == "wf-clean-close"
def test_srm_loop_without_dify_agent_does_not_crash(app, monkeypatch):
from app.services.schedule.srm_service import _run_check_job_loop
writebacks = []
with app.app_context():
total, success, failed, skipped, details, errors, _step_logs = _run_check_job_loop(
conn_str="",
run_no="RUN-NO-AGENT",
agent=None,
user="tester",
wait_seconds=5,
run_id=None,
fetch_fn=lambda _conn: [{"id": "R1"}],
build_record_fn=lambda _conn, item, row_id: ("record text", None),
writeback_fn=lambda _conn, **kwargs: writebacks.append(kwargs),
row_id_key="id",
log_prefix="row",
)
assert total == 1
assert success == 1
assert failed == 0
assert details[0]["dify_message"] == "未配置 Agent ID,跳过 Dify"
assert details[0]["workflow_run_id"] is None
assert details[0]["dify_retry_count"] == 0
assert details[0]["dify_poll_used"] is False
assert writebacks
def test_file_check_evaluate_passes_reliability_meta(monkeypatch):
def _streaming(**kwargs):
return {
"status": "succeeded",
"workflow_run_id": "wf-meta",
"outputs": {"output": {"dify_result": "合格", "dify_message": "ok"}},
"_workflow_poll_used": True,
"_workflow_retry_count": 1,
"_workflow_error_type": "read_timeout",
}
monkeypatch.setattr("app.services.file_check.DifyService.run_workflow_streaming", _streaming)
payload = FileCheckService.evaluate(agent=_Agent(), run_no="RUN-1", record="Pb: 100ppm")
assert payload["dify_result"] == "合格"
assert payload["workflow_run_id"] == "wf-meta"
assert payload["poll_used"] is True
assert payload["retry_count"] == 1
assert payload["error_type"] == "read_timeout"
def test_file_check_evaluate_exception_includes_error_type(monkeypatch):
def _boom(**kwargs):
resp = requests.Response()
resp.status_code = 403
raise requests.HTTPError(response=resp)
monkeypatch.setattr("app.services.file_check.DifyService.run_workflow_streaming", _boom)
payload = FileCheckService.evaluate(agent=_Agent(), run_no="RUN-1", record="Pb: 100ppm")
assert payload["dify_result"] == "人工判定"
assert payload["error_type"] == "http_403"
assert payload["retryable"] is False
assert payload["poll_used"] is False
@@ -0,0 +1,216 @@
"""
tests/test_file_check_error_classification.py
用途:覆盖文件检核「业务人工判定」与「系统异常」分类。
"""
from __future__ import annotations
import pytest
import requests
from app.services.file_check import (
MANUAL_REASON_ATTACHMENT_FAILED,
MANUAL_REASON_BUSINESS_UNCERTAIN,
MANUAL_REASON_DIFY_FAILED,
MANUAL_REASON_INVALID_OUTPUT,
MANUAL_REASON_NO_DIFY_AGENT,
MANUAL_REASON_POLL_TIMEOUT,
MANUAL_REASON_DIFY_TIMEOUT,
FileCheckService,
build_no_dify_agent_result,
increment_judgement_stats,
)
def test_business_uncertain_classification():
payload = FileCheckService.normalize_workflow_result({
"status": "succeeded",
"workflow_run_id": "wf-biz",
"outputs": {"output": {"dify_result": "人工判定", "dify_message": "报告签章不清晰"}},
})
assert payload["dify_result"] == "人工判定"
assert payload["manual_reason_type"] == MANUAL_REASON_BUSINESS_UNCERTAIN
assert payload["is_system_error"] is False
assert payload["user_action_hint"]
def test_poll_timeout_classification():
payload = FileCheckService.normalize_workflow_result({
"workflow_run_id": "wf-poll",
"_workflow_poll_used": True,
"_workflow_error_type": "poll_timeout",
})
assert payload["dify_result"] == "人工判定"
assert payload["manual_reason_type"] == MANUAL_REASON_POLL_TIMEOUT
assert payload["is_system_error"] is True
def test_dify_timeout_classification():
payload = FileCheckService.normalize_workflow_result({
"workflow_run_id": "wf-read",
"_workflow_error_type": "read_timeout",
})
assert payload["manual_reason_type"] == MANUAL_REASON_DIFY_TIMEOUT
assert payload["is_system_error"] is True
def test_workflow_failed_classification():
payload = FileCheckService.normalize_workflow_result({
"status": "failed",
"error": "workflow timeout",
"workflow_run_id": "wf-fail",
})
assert payload["manual_reason_type"] == MANUAL_REASON_DIFY_FAILED
assert payload["is_system_error"] is True
def test_invalid_output_classification():
payload = FileCheckService.normalize_workflow_result({
"status": "succeeded",
"outputs": {"dify_result": "OK", "dify_message": "bad enum"},
"workflow_run_id": "wf-invalid",
})
assert payload["manual_reason_type"] == MANUAL_REASON_INVALID_OUTPUT
assert payload["is_system_error"] is True
def test_attachment_read_failed_classification():
payload = FileCheckService.normalize_workflow_result({
"status": "succeeded",
"outputs": {
"output": {
"dify_result": "人工判定",
"dify_message": "附件读取失败:无法下载供应商 PDF",
},
},
"workflow_run_id": "wf-att",
})
assert payload["manual_reason_type"] == MANUAL_REASON_ATTACHMENT_FAILED
assert payload["is_system_error"] is True
def test_no_dify_agent_classification():
payload = build_no_dify_agent_result()
assert payload["manual_reason_type"] == MANUAL_REASON_NO_DIFY_AGENT
assert payload["is_system_error"] is False
def test_evaluate_http_error_classified_as_system(monkeypatch):
class _Agent:
id = 1
def _boom(**kwargs):
resp = requests.Response()
resp.status_code = 503
raise requests.HTTPError(response=resp)
monkeypatch.setattr("app.services.file_check.DifyService.run_workflow_streaming", _boom)
payload = FileCheckService.evaluate(agent=_Agent(), run_no="RUN-1", record="Pb")
assert payload["manual_reason_type"] == MANUAL_REASON_DIFY_FAILED
assert payload["is_system_error"] is True
def test_increment_judgement_stats_splits_business_and_system():
stats = {
"qualified_count": 0,
"unqualified_count": 0,
"manual_count": 0,
"dify_error_count": 0,
"invalid_result_count": 0,
"business_manual_count": 0,
"system_error_count": 0,
"dify_timeout_count": 0,
"invalid_output_count": 0,
"attachment_error_count": 0,
}
increment_judgement_stats(
stats,
dify_result="人工判定",
manual_reason_type=MANUAL_REASON_BUSINESS_UNCERTAIN,
is_system_error=False,
)
increment_judgement_stats(
stats,
dify_result="人工判定",
manual_reason_type=MANUAL_REASON_POLL_TIMEOUT,
is_system_error=True,
)
increment_judgement_stats(
stats,
dify_result="人工判定",
manual_reason_type=MANUAL_REASON_ATTACHMENT_FAILED,
is_system_error=True,
)
assert stats["manual_count"] == 3
assert stats["business_manual_count"] == 1
assert stats["system_error_count"] == 2
assert stats["dify_timeout_count"] == 1
assert stats["attachment_error_count"] == 1
def test_srm_loop_records_manual_reason_on_system_error(app, monkeypatch):
from app.services.schedule.srm_service import _run_check_job_loop
class _Agent:
id = 1
dify_api_key = "secret"
def _evaluate(**kwargs):
return {
"dify_result": "人工判定",
"dify_message": "Dify执行失败:poll 超时未获取最终结果",
"workflow_run_id": "wf-timeout",
"error": "poll_timeout",
"error_type": "poll_timeout",
"poll_used": True,
"retry_count": 0,
"manual_reason_type": MANUAL_REASON_POLL_TIMEOUT,
"is_system_error": True,
"user_action_hint": "系统补偿查询 Dify 结果超时,请稍后重试或凭 workflow_run_id 对账",
"provider": "dify_workflow",
}
monkeypatch.setattr("app.services.schedule.srm_service.FileCheckService.evaluate", _evaluate)
with app.app_context():
total, success, failed, skipped, details, errors, _logs = _run_check_job_loop(
conn_str="",
run_no="RUN-CLS",
agent=_Agent(),
user="tester",
wait_seconds=5,
run_id=None,
fetch_fn=lambda _conn: [{"id": "R1"}],
build_record_fn=lambda _conn, item, row_id: ("record text", None),
writeback_fn=lambda _conn, **kwargs: None,
row_id_key="id",
log_prefix="row",
)
assert total == 1
assert success == 1
assert details[0]["manual_reason_type"] == MANUAL_REASON_POLL_TIMEOUT
assert details[0]["is_system_error"] is True
assert details[0]["user_action_hint"]
def test_serialize_file_judgement_includes_split_counts():
from app.api.workspace.file_check import serialize_file_judgement
payload = serialize_file_judgement({
"response_summary_json": {
"file_judgement": {
"qualified_count": 2,
"unqualified_count": 1,
"manual_count": 4,
"business_manual_count": 1,
"system_error_count": 3,
"dify_timeout_count": 2,
"invalid_output_count": 1,
"attachment_error_count": 1,
},
},
})
assert payload["business_manual_count"] == 1
assert payload["system_error_count"] == 3
assert payload["dify_timeout_count"] == 2
assert payload["attachment_error_count"] == 1
+5
View File
@@ -86,6 +86,8 @@ def test_file_check_service_normalizes_failed_workflow():
assert payload['dify_result'] == '人工判定'
assert 'Dify执行失败' in payload['dify_message']
assert payload['workflow_run_id'] == 'wf-2'
assert payload['manual_reason_type'] == 'dify_failed'
assert payload['is_system_error'] is True
def test_file_check_service_evaluate_degrades_on_dify_error(monkeypatch):
@@ -130,6 +132,8 @@ def test_file_check_loop_splits_processing_and_judgement_counts(app, monkeypatch
'dify_message': 'Dify执行失败:workflow timeout',
'workflow_run_id': 'wf-failed',
'error': 'workflow timeout',
'manual_reason_type': 'dify_failed',
'is_system_error': True,
}
writebacks = []
@@ -169,6 +173,7 @@ def test_file_check_loop_splits_processing_and_judgement_counts(app, monkeypatch
assert errors == []
assert judgement['manual_count'] == 1
assert judgement['dify_error_count'] == 1
assert judgement['system_error_count'] == 1
assert (run.response_summary_json or {}).get('current_step', {}).get('step') == 'completed'
assert any(log['step'] == 'call_dify' and log['status'] == 'success' for log in step_logs)
File diff suppressed because it is too large. Load diff
+142
View File
@@ -0,0 +1,142 @@
"""
tests/test_notice_intake.py
用途:验证发货通知附件统一接入服务的抽取、截断与失败分流语义。
依赖:notice_upload.intake_notice_attachment、truncate_notice_text。
逻辑:保证单票/批量/重传三条入口共用同一 intake 结果模型,避免行为漂移。
"""
from __future__ import annotations
from io import BytesIO
def test_truncate_notice_text_appends_warning(app):
"""正文超长时应截断并追加 notice_text_truncated warning。"""
from app.services.shipping_notice.notice_upload import truncate_notice_text
with app.app_context():
app.config["SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS"] = 10
text, warnings = truncate_notice_text("abcdefghijklmnop", [])
assert text == "abcdefghij"
assert warnings == ["notice_text_truncated:10"]
def test_intake_notice_attachment_accepts_txt(app, tmp_path):
"""任务级接入应落盘、抽取并标记 accepted。"""
from app.services.shipping_notice.notice_upload import intake_notice_attachment
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path)
with app.app_context():
result = intake_notice_attachment(
filename="notice-a.txt",
raw="客户:ACME\nA001 x 10".encode("utf-8"),
source_file_type="text/plain",
storage="task",
task_no="SN-INTAKE-001",
)
assert result.accepted is True
assert result.status == "accepted"
assert "A001" in result.text
assert result.to_notice_item()["source_file_name"] == "notice-a.txt"
assert result.to_notice_upload_meta()["filename"] == "notice-a.txt"
assert result.saved_path is not None
assert result.saved_path.exists()
def test_intake_notice_attachment_empty_text_is_rejected(app, tmp_path, monkeypatch):
"""抽取空文本时应标记 empty_text,供批量入口分流到 rejected_files。"""
from app.services.shipping_notice import notice_upload
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path)
monkeypatch.setattr(
notice_upload,
"extract_notice_text",
lambda saved_path: ("", {"warnings": ["ocr_empty"], "file_type": "pdf"}),
)
with app.app_context():
result = notice_upload.intake_notice_attachment(
filename="scan.pdf",
raw=b"%PDF-1.4",
source_file_type="application/pdf",
storage="temp",
temp_request_id="req-empty",
temp_index=1,
)
assert result.accepted is False
assert result.status == "empty_text"
rejected = result.to_rejected_file_summary()
assert rejected["reason"] == "empty_text"
assert rejected["warnings"] == ["ocr_empty"]
def test_intake_temp_notice_uploads_splits_accepted_and_rejected(app, tmp_path, monkeypatch):
"""批量接入应分别返回 accepted / rejected,并生成统一 file_summary。"""
from app.services.shipping_notice import notice_upload
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path)
def fake_extract(saved_path):
name = str(saved_path).replace("\\", "/")
if name.endswith("/notice-a.txt"):
return "客户:ACME\nA001 x 10", {"warnings": [], "file_type": "txt"}
return "", {"warnings": ["ocr_empty"], "file_type": "pdf"}
monkeypatch.setattr(notice_upload, "extract_notice_text", fake_extract)
class _Upload:
def __init__(self, name: str, raw: bytes, mimetype: str):
self.filename = name
self._raw = raw
self.mimetype = mimetype
def read(self):
return self._raw
uploads = [
_Upload("notice-a.txt", b"ok", "text/plain"),
_Upload("notice-b.pdf", b"%PDF-1.4", "application/pdf"),
]
with app.app_context():
accepted, rejected = notice_upload.intake_temp_notice_uploads("req-batch", uploads)
summary = notice_upload.build_notice_file_summary(
total_files=len(uploads),
accepted=accepted,
rejected=rejected,
)
assert len(accepted) == 1
assert len(rejected) == 1
assert summary["accepted_count"] == 1
assert summary["rejected_count"] == 1
assert summary["accepted_files"][0]["filename"] == "notice-a.txt"
assert summary["rejected_files"][0]["filename"] == "notice-b.pdf"
def test_intake_notice_attachment_extract_failure(app, tmp_path, monkeypatch):
"""抽取异常时应标记 extract_failed 并保留 notice_extract_failed warning。"""
from app.services.shipping_notice import notice_upload
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path)
monkeypatch.setattr(
notice_upload,
"extract_notice_text",
lambda saved_path: (_ for _ in ()).throw(RuntimeError("ocr down")),
)
with app.app_context():
result = notice_upload.intake_notice_attachment(
filename="broken.pdf",
raw=BytesIO(b"%PDF").read(),
storage="task",
task_no="SN-INTAKE-FAIL",
)
assert result.accepted is False
assert result.status == "extract_failed"
assert result.warnings[0].startswith("notice_extract_failed:")
+59
View File
@@ -0,0 +1,59 @@
"""
backend/tests/test_openapi_snapshots.py
用途:校验 docs/openapi 下的静态快照与后端 OpenAPI builder 输出一致。
依赖:shipping_notice.open_api_spec、agent_runtime_context.open_api_spec、标准 json/pathlib。
逻辑:直接 import builder 生成动态字典,再与静态 JSON 做对象级比对,避免 Dify 导入文件漂移。
"""
from __future__ import annotations
import json
from pathlib import Path
from app.services.agent_runtime_context.openapi_spec import build_agent_runtime_context_openapi_spec
from app.services.shipping_notice.openapi_spec import build_dify_openapi_spec
DEFAULT_BASE_URL = "http://192.168.36.108:5052"
ROOT = Path(__file__).resolve().parents[2]
OPENAPI_DIR = ROOT / "docs" / "openapi"
def _load_snapshot(name: str) -> dict:
"""
读取静态 OpenAPI 快照。
Args:
name: docs/openapi 下的文件名。
Returns:
解析后的 JSON 对象。
"""
return json.loads((OPENAPI_DIR / name).read_text(encoding="utf-8"))
def test_shipping_notice_snapshot_matches_builder_output():
"""发货通知静态快照应与当前 builder 输出完全一致。"""
snapshot = _load_snapshot("shipping_notice_tools.dify.json")
generated = build_dify_openapi_spec(DEFAULT_BASE_URL)
assert snapshot == generated
assert snapshot["paths"]["/tools/submit_decision"]["post"]["operationId"] == "submit_decision"
snapshot_text = json.dumps(snapshot, ensure_ascii=False)
assert "reference_context" in snapshot_text
assert "状态机" in snapshot_text
assert "唯一 task_id" in snapshot_text
assert "不得自行宣布完成" in snapshot_text
def test_agent_runtime_context_snapshot_matches_builder_output():
"""运行态上下文静态快照应与当前 builder 输出完全一致。"""
snapshot = _load_snapshot("agent_runtime_context_tools.dify.json")
generated = build_agent_runtime_context_openapi_spec(DEFAULT_BASE_URL)
assert snapshot == generated
assert snapshot["paths"]["/tools/parse"]["post"]["operationId"] == "parse_agent_runtime_context"
snapshot_text = json.dumps(snapshot, ensure_ascii=False)
assert "reference_context" in snapshot_text
assert "状态机" in snapshot_text
assert "追问" in snapshot_text
+189 -31
View File
@@ -7,6 +7,7 @@
4. 工作台批量上传通知时仅为可解析文件建任务,并返回 envelope + 文件级摘要。
"""
import json
from datetime import datetime, timedelta
from io import BytesIO
@@ -131,6 +132,145 @@ def test_create_batch_tasks_and_switch_focus(app, client):
assert batch_row.current_focus_task_no == target_task_no
assert task_rows[0].batch_total == 2
assert task_rows[1].batch_total == 2
focus_events = (
ShippingTaskEvent.query.filter_by(task_id=task_rows[1].id, event_type="focus_switched")
.order_by(ShippingTaskEvent.id.desc())
.all()
)
assert len(focus_events) == 1
assert focus_events[0].detail_json["action"] == "switch_focus"
assert focus_events[0].detail_json["source"] == "tool_api"
assert focus_events[0].detail_json["previous_focus_task_no"] == task_rows[0].task_no
assert focus_events[0].detail_json["next_focus_task_no"] == task_rows[1].task_no
def test_workspace_submit_decision_updates_reference_context_last_action(app, client):
"""用户在工作台点击确认后,下次 runtime_context 应暴露标准 confirm 动作。"""
headers = _workspace_headers(app)
with app.app_context():
user = User.query.filter_by(username="shipping_workspace_user").order_by(User.id.desc()).first()
assert user is not None
batch = ShippingBatch(
batch_no="SB-WS-CONFIRM-001",
user_id=user.id,
conversation_id="conv-ws-confirm-001",
current_focus_task_no="SN-WS-CONFIRM-001",
file_count=1,
)
task = ShippingTask(
task_no="SN-WS-CONFIRM-001",
batch=batch,
user_id=user.id,
conversation_id="conv-ws-confirm-001",
source_type="manual",
process_status="pending_review",
review_status="parse_review",
pending_human_reason="low_confidence",
raw_content="客户:ACME\nA001 x 10",
)
db.session.add_all([batch, task])
db.session.commit()
res = client.post(
"/api/workspace/shipping-tasks/SN-WS-CONFIRM-001/submit-decision",
headers=headers,
json={"decision": "confirm", "comment": "用户确认"},
)
assert res.status_code == 200
data = res.get_json()
assert data["status"] in {"ok", "running"}
with app.app_context():
task = ShippingTask.query.filter_by(task_no="SN-WS-CONFIRM-001").one()
event = (
ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="parse_confirmed")
.order_by(ShippingTaskEvent.id.desc())
.first()
)
assert event is not None
assert event.detail_json["action"] == "confirm"
assert event.detail_json["source"] == "workspace_api"
inputs = dify_inputs.build_dify_chat_inputs("conv-ws-confirm-001")
runtime_context = json.loads(inputs["agent_runtime_context"])
assert runtime_context["reference_context"]["last_action_target"] == {
"type": "task",
"id": "SN-WS-CONFIRM-001",
"action": "confirm_parse",
}
def test_workspace_switch_focus_updates_reference_context(app, client):
"""用户切换 focus 后,下次 runtime_context 应同时反映新的 focus_object 与 switch_focus 动作。"""
headers = _workspace_headers(app)
with app.app_context():
user = User.query.filter_by(username="shipping_workspace_user").order_by(User.id.desc()).first()
assert user is not None
batch = ShippingBatch(
batch_no="SB-WS-FOCUS-001",
user_id=user.id,
conversation_id="conv-ws-focus-001",
current_focus_task_no="SN-WS-FOCUS-001",
file_count=2,
)
old_focus = ShippingTask(
task_no="SN-WS-FOCUS-001",
batch=batch,
user_id=user.id,
conversation_id="conv-ws-focus-001",
source_type="manual",
process_status="created",
batch_index=1,
batch_total=2,
)
new_focus = ShippingTask(
task_no="SN-WS-FOCUS-002",
batch=batch,
user_id=user.id,
conversation_id="conv-ws-focus-001",
source_type="manual",
process_status="pending_review",
match_status="shortage",
pending_human_reason="shortage",
shortage_json={"A001": 3},
batch_index=2,
batch_total=2,
)
db.session.add_all([batch, old_focus, new_focus])
db.session.commit()
res = client.post(
"/api/workspace/shipping-batches/SB-WS-FOCUS-001/focus-task",
headers=headers,
json={"task_no": "SN-WS-FOCUS-002", "comment": "切到异常票"},
)
assert res.status_code == 200
data = res.get_json()
assert data["batch"]["current_focus_task_no"] == "SN-WS-FOCUS-002"
with app.app_context():
target = ShippingTask.query.filter_by(task_no="SN-WS-FOCUS-002").one()
event = (
ShippingTaskEvent.query.filter_by(task_id=target.id, event_type="focus_switched")
.order_by(ShippingTaskEvent.id.desc())
.first()
)
assert event is not None
assert event.detail_json["action"] == "switch_focus"
assert event.detail_json["source"] == "workspace_api"
assert event.detail_json["previous_focus_task_no"] == "SN-WS-FOCUS-001"
assert event.detail_json["next_focus_task_no"] == "SN-WS-FOCUS-002"
inputs = dify_inputs.build_dify_chat_inputs("conv-ws-focus-001")
runtime_context = json.loads(inputs["agent_runtime_context"])
assert runtime_context["reference_context"]["focus_object"]["id"] == "SN-WS-FOCUS-002"
assert runtime_context["reference_context"]["last_action_target"] == {
"type": "task",
"id": "SN-WS-FOCUS-002",
"action": "switch_focus",
}
assert runtime_context["reference_context"]["last_failed_target"]["id"] == "SN-WS-FOCUS-002"
assert "candidates" not in runtime_context["reference_context"]
def test_contract_batch_status_keeps_single_focus_without_advancing_other_tasks(app, client):
@@ -487,10 +627,11 @@ def test_workspace_replace_notice_overwrites_current_task_without_new_batch(app,
assert task.export_file_name is None
def test_auto_progress_inventory_trigger_failure_marks_step3(app):
def test_auto_progress_inventory_trigger_failure_marks_step3(app, tmp_path):
"""库存自动获取失败时应进入第 3 步库存准备,而不是继续显示解析确认。"""
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(tmp_path / "empty_inventory_drop")
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = ""
with app.app_context():
user = User(username="shipping_inventory_step_user", email="shipping_inventory_step_user@example.com")
@@ -592,6 +733,7 @@ def test_auto_progress_resolves_dub_inventory_source_into_rpa_trigger(app, tmp_p
"""目的地 DUB 应解析到 DSV360_AWSDU,并写入 RPA 库存导出 trigger。"""
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(tmp_path / "empty_inventory_drop")
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(tmp_path / "inventory_triggers")
with app.app_context():
user = User(username="shipping_inventory_source_user", email="shipping_inventory_source_user@example.com")
@@ -979,6 +1121,8 @@ def test_workspace_conversation_batch_workspace_aggregates_multiple_batches(app,
assert [item["batch_no"] for item in data["batches"]] == ["SB-CONV-WS-A", "SB-CONV-WS-B"]
assert data["batches"][0]["focus_task"]["task_no"] == "SN-20260626-CONVA001"
assert len(data["batches"][1]["tasks"]) == 2
assert "ui_state" in data["batches"][0]["tasks"][0]
assert isinstance(data["batches"][0]["tasks"][0]["ui_state"]["action_buttons"], list)
def test_workspace_conversation_batch_workspace_filters_by_user(app, client):
@@ -1344,21 +1488,28 @@ def test_run_shipping_parse_via_dify_passes_task_context_without_persisting_chat
assert captured["session_id"] == session.session_id
assert captured["persist_chat_log"] is False
assert isinstance(captured["inputs"], dict)
assert captured["inputs"]["hxops_context"]["schema_version"] == "1"
assert captured["inputs"]["hxops_context"]["session"]["id"] == session.session_id
assert captured["inputs"]["hxops_context"]["request"]["id"] == f"shipping-orch-{task.task_no}"
assert captured["inputs"]["hxops_context"]["request"]["trigger_source"] == "backend_orchestrator"
assert captured["inputs"]["hxops_context"]["refs"] == [
{"field": "task", "value": task.task_no},
{"field": "batch", "value": batch.batch_no},
]
runtime_context = json.loads(captured["inputs"]["agent_runtime_context"])
assert runtime_context["schema_version"] == "1"
assert runtime_context["agent_code"] == "shipping_notice"
assert runtime_context["scope"] == "task_run"
assert runtime_context["platform"]["session_id"] == session.session_id
assert runtime_context["platform"]["request_id"] == f"shipping-orch-{task.task_no}"
assert runtime_context["platform"]["trigger_source"] == "backend_orchestrator"
assert runtime_context["refs"]["task_no"] == task.task_no
assert runtime_context["refs"]["batch_no"] == batch.batch_no
assert runtime_context["refs"]["run_purpose"] == "parse_notice"
assert runtime_context["domain"]["type"] == "shipping_notice"
assert runtime_context["domain"]["state_hint"]["focus_task_no"] == task.task_no
assert runtime_context["domain"]["state_hint"]["status"] == task.process_status
assert runtime_context["reference_context"]["focus_object"]["id"] == task.task_no
assert set(captured["inputs"].keys()) == {"agent_runtime_context"}
refreshed_session = ChatSession.query.filter_by(session_id=session.session_id).first()
assert refreshed_session is not None
assert refreshed_session.external_conversation_id == "22222222-2222-2222-2222-222222222222"
def test_build_dify_chat_inputs_returns_hxops_context_only(app):
"""货代发货 Agent 应只注入平台统一的 hxops_context。"""
def test_build_dify_chat_inputs_returns_agent_runtime_context_only(app):
"""货代发货 Agent 仅应向 Dify 注入 agent_runtime_context。"""
with app.app_context():
batch = ShippingBatch(
batch_no="SB-DIFY-INPUTS",
@@ -1382,20 +1533,26 @@ def test_build_dify_chat_inputs_returns_hxops_context_only(app):
request_id="req-frontend-001",
)
assert set(inputs.keys()) == {"hxops_context"}
assert inputs["hxops_context"]["schema_version"] == "1"
assert inputs["hxops_context"]["session"]["id"] == "conv-shipping-inputs-001"
assert inputs["hxops_context"]["request"]["id"] == "req-frontend-001"
assert inputs["hxops_context"]["request"]["trigger_source"] == "frontend_chat"
assert inputs["hxops_context"]["refs"] == [
{"field": "task", "value": "SN-20260622-DDDD0004"},
{"field": "batch", "value": "SB-DIFY-INPUTS"},
]
assert "instructions" not in inputs["hxops_context"]
assert set(inputs.keys()) == {"agent_runtime_context"}
runtime_context = json.loads(inputs["agent_runtime_context"])
assert runtime_context["schema_version"] == "1"
assert runtime_context["agent_code"] == "shipping_notice"
assert runtime_context["scope"] == "chat_turn"
assert runtime_context["platform"]["session_id"] == "conv-shipping-inputs-001"
assert runtime_context["platform"]["request_id"] == "req-frontend-001"
assert runtime_context["platform"]["trigger_source"] == "frontend_chat"
assert runtime_context["refs"] == {
"task_no": "SN-20260622-DDDD0004",
"batch_no": "SB-DIFY-INPUTS",
"run_purpose": "chat_turn",
}
assert runtime_context["domain"]["state_hint"]["focus_task_no"] == "SN-20260622-DDDD0004"
assert runtime_context["domain"]["state_hint"]["status"] == "created"
assert runtime_context["reference_context"]["focus_object"]["id"] == "SN-20260622-DDDD0004"
def test_build_dify_chat_inputs_requires_local_session_not_provider_conversation(app):
"""已有 Dify provider 会话号时,HXOPS 上下文仍应按本地 session 解析。"""
"""已有 Dify provider 会话号时,agent_runtime_context 仍应按本地 session 解析。"""
with app.app_context():
local_session_id = "conv-shipping-local-session-001"
provider_conversation_id = "f3b371e7-4d8b-40b6-80be-76fd98459c65"
@@ -1418,12 +1575,13 @@ def test_build_dify_chat_inputs_requires_local_session_not_provider_conversation
provider_inputs = dify_inputs.build_dify_chat_inputs(provider_conversation_id)
local_inputs = dify_inputs.build_dify_chat_inputs(local_session_id)
assert provider_inputs["hxops_context"]["refs"] == []
assert local_inputs["hxops_context"]["session"]["id"] == local_session_id
assert local_inputs["hxops_context"]["refs"] == [
{"field": "task", "value": "SN-20260626-LOCAL001"},
{"field": "batch", "value": "SB-DIFY-LOCAL"},
]
provider_runtime_context = json.loads(provider_inputs["agent_runtime_context"])
assert provider_runtime_context["refs"] == {"run_purpose": "chat_turn"}
local_runtime_context = json.loads(local_inputs["agent_runtime_context"])
assert local_runtime_context["refs"]["task_no"] == "SN-20260626-LOCAL001"
assert local_runtime_context["refs"]["batch_no"] == "SB-DIFY-LOCAL"
assert set(provider_inputs.keys()) == {"agent_runtime_context"}
assert set(local_inputs.keys()) == {"agent_runtime_context"}
def test_build_dify_chat_inputs_does_not_fallback_to_latest_task_without_explicit_anchor(app):
@@ -1447,9 +1605,9 @@ def test_build_dify_chat_inputs_does_not_fallback_to_latest_task_without_explici
inputs = dify_inputs.build_dify_chat_inputs(conversation_id)
assert set(inputs.keys()) == {"hxops_context"}
assert inputs["hxops_context"]["session"]["id"] == conversation_id
assert inputs["hxops_context"]["refs"] == []
assert set(inputs.keys()) == {"agent_runtime_context"}
runtime_context = json.loads(inputs["agent_runtime_context"])
assert runtime_context["refs"] == {"run_purpose": "chat_turn"}
def test_is_shipping_notice_chat_agent_accepts_current_dify_app_name():
@@ -14,6 +14,28 @@ def _tool_headers():
return {"Content-Type": "application/json", "X-Integration-Key": "test-integration-key"}
def test_inventory_rpa_single_attempt_messages_hide_fraction():
"""单次自动尝试模式不应再产出 1/1 计数,避免 Dify 误判仍会继续自动重试。"""
from app.services.shipping_notice.inventory_rpa_workflow import (
_inventory_rpa_attempt_label,
_inventory_rpa_running_prefix,
_inventory_rpa_running_message,
_inventory_rpa_triggered_message,
_inventory_rpa_triggered_prefix,
)
assert _inventory_rpa_attempt_label(attempt_no=1, max_attempts=1, manual_retry_round=False) == "当前配置为单次自动尝试"
assert _inventory_rpa_running_prefix(attempt_no=1, max_attempts=1) == "RPA 库存导出进行中。"
assert _inventory_rpa_triggered_prefix(attempt_no=1, max_attempts=1, manual_retry_round=False) == "已触发 RPA 库存导出。"
assert _inventory_rpa_attempt_label(attempt_no=1, max_attempts=1, manual_retry_round=True) == "手动第 1 次尝试"
assert _inventory_rpa_running_message(attempt_no=1, max_attempts=1) == "RPA 库存导出进行中。请稍后刷新状态;若长时间无结果,可改为上传库存 Excel。"
assert _inventory_rpa_triggered_message(
attempt_no=1,
max_attempts=1,
manual_retry_round=False,
) == "已触发 RPA 库存导出。若长时间无结果,可手动重试,或上传库存 Excel。"
def test_ensure_inventory_auto_triggers_rpa_running(app, client, tmp_path):
"""mode=auto 应返回 running 并在 DB 留下 inventory_rpa_triggered 事件。"""
trigger = tmp_path / "triggers"
@@ -54,11 +76,16 @@ def test_ensure_inventory_auto_triggers_rpa_running(app, client, tmp_path):
body = inv_res.get_json()
assert body["status"] == "running"
assert body.get("data", {}).get("rpa", {}).get("attempts") == 1
assert "1/1" not in body.get("message", "")
assert "360s" not in body.get("message", "")
assert "长时间无结果" in body.get("message", "")
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.pending_human_reason == "rpa_pending"
progress = (task.step_payload_json or {}).get("current_step_progress") or {}
assert progress.get("detail") == "当前配置为单次自动尝试"
events = (
ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered")
.all()
@@ -156,9 +183,14 @@ def test_confirm_inventory_source_triggers_rpa_export(app, tmp_path):
db.session.refresh(task)
assert result["status"] == "running"
assert "已触发 RPA 库存导出" in result["message"]
assert "长时间无结果" in result["message"]
assert "360s" not in result["message"]
assert task.process_status == "waiting_inventory"
assert task.pending_human_reason == "rpa_pending"
assert task.error_message is None
assert task.step_payload_json["rpa_inventory_source"]["source_code"] == "DSV360_AWSDU"
assert task.step_payload_json["current_step_progress"]["detail"] == "当前配置为单次自动尝试"
events = ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").all()
assert len(events) == 1
assert list(trigger.glob("inventory_export_SN-CONFIRM-SOURCE-RPA*.json"))
@@ -0,0 +1,475 @@
"""
backend/tests/test_shipping_notice_reference_context.py
用途:验证发货通知 reference_context 的 focus/动作/失败候选摘要构建。
依赖:models.ShippingBatch/ShippingTask/ShippingTaskEvent、shipping_notice.reference_context。
逻辑:直接构造批次、任务与少量事件,确保 Dify 只拿到短期指代线索,不会收到整批任务明细。
"""
from __future__ import annotations
import json
from datetime import datetime, timedelta
from app import db
from app.models import ShippingBatch, ShippingTask, ShippingTaskEvent
from app.services.agent_runtime_context.policy import MAX_RECENT_ACTIVITY_SUMMARY_CHARS
from app.services.shipping_notice.reference_context import build_shipping_reference_context
def _make_task(
*,
task_no: str,
batch: ShippingBatch,
updated_at: datetime,
process_status: str = "created",
current_step: str | None = None,
pending_human_reason: str | None = None,
review_status: str | None = None,
match_status: str | None = None,
upload_status: str | None = None,
shortage_json: dict | None = None,
error_message: str | None = None,
) -> ShippingTask:
"""构造测试任务,减少样板字段噪音。"""
return ShippingTask(
task_no=task_no,
batch=batch,
conversation_id=batch.conversation_id,
source_type="manual",
process_status=process_status,
current_step=current_step,
pending_human_reason=pending_human_reason,
review_status=review_status,
match_status=match_status,
upload_status=upload_status,
shortage_json=shortage_json,
error_message=error_message,
updated_at=updated_at,
created_at=updated_at - timedelta(minutes=5),
)
def test_build_shipping_reference_context_includes_focus_and_last_action(app):
"""当前 focus task 与最近确认动作应进入 reference_context。"""
with app.app_context():
batch = ShippingBatch(
batch_no="SB-REF-001",
conversation_id="conv-ref-001",
current_focus_task_no="SN-REF-FOCUS-001",
file_count=2,
)
action_task = _make_task(
task_no="SN-REF-ACTION-001",
batch=batch,
updated_at=datetime(2026, 7, 2, 9, 0, 0),
process_status="parsed",
)
focus_task = _make_task(
task_no="SN-REF-FOCUS-001",
batch=batch,
updated_at=datetime(2026, 7, 2, 9, 5, 0),
process_status="pending_review",
current_step="step2_parse_confirm",
)
db.session.add_all([batch, action_task, focus_task])
db.session.flush()
db.session.add(
ShippingTaskEvent(
task_id=action_task.id,
event_type="parse_confirmed",
detail_json={"comment": "ok"},
created_at=datetime(2026, 7, 2, 9, 6, 0),
)
)
db.session.commit()
context = build_shipping_reference_context(batch=batch, focus_task=focus_task)
assert context["focus_object"] == {"type": "task", "id": "SN-REF-FOCUS-001"}
assert context["last_action_target"] == {
"type": "task",
"id": "SN-REF-ACTION-001",
"action": "confirm_parse",
}
assert "当前 focus 为 SN-REF-FOCUS-001" in context["recent_activity_summary"]
assert "用户已确认 SN-REF-ACTION-001 解析" in context["recent_activity_summary"]
def test_build_shipping_reference_context_includes_last_failed_target(app):
"""最近失败任务应收敛为 last_failed_target,而不是要求 Dify 自己遍历整批任务。"""
with app.app_context():
batch = ShippingBatch(
batch_no="SB-REF-FAIL",
conversation_id="conv-ref-fail",
current_focus_task_no="SN-REF-FOCUS-002",
file_count=2,
)
focus_task = _make_task(
task_no="SN-REF-FOCUS-002",
batch=batch,
updated_at=datetime(2026, 7, 2, 10, 0, 0),
process_status="inventory_ready",
)
failed_task = _make_task(
task_no="SN-REF-FAIL-002",
batch=batch,
updated_at=datetime(2026, 7, 2, 10, 10, 0),
process_status="pending_review",
match_status="shortage",
pending_human_reason="shortage",
shortage_json={"A001": 10},
)
db.session.add_all([batch, focus_task, failed_task])
db.session.commit()
context = build_shipping_reference_context(batch=batch, focus_task=focus_task)
assert context["last_failed_target"] == {
"type": "task",
"id": "SN-REF-FAIL-002",
"reason": "shortage",
"label": "异常:库存不足",
}
assert "SN-REF-FAIL-002 库存匹配失败" in context["recent_activity_summary"]
def test_build_shipping_reference_context_limits_candidates_to_failure_tasks(app):
"""candidates 只应暴露少量失败/异常任务,不应把正常任务或整批明细塞进 context。"""
with app.app_context():
batch = ShippingBatch(
batch_no="SB-REF-CAND",
conversation_id="conv-ref-cand",
current_focus_task_no="SN-REF-FOCUS-003",
file_count=5,
)
focus_task = _make_task(
task_no="SN-REF-FOCUS-003",
batch=batch,
updated_at=datetime(2026, 7, 2, 11, 0, 0),
process_status="parsed",
)
shortage_task = _make_task(
task_no="SN-REF-SHORT-003",
batch=batch,
updated_at=datetime(2026, 7, 2, 11, 1, 0),
process_status="pending_review",
match_status="shortage",
pending_human_reason="shortage",
shortage_json={"A001": 1},
)
rejected_task = _make_task(
task_no="SN-REF-REJECT-003",
batch=batch,
updated_at=datetime(2026, 7, 2, 11, 2, 0),
process_status="rejected",
review_status="rejected",
)
upload_failed_task = _make_task(
task_no="SN-REF-UPFAIL-003",
batch=batch,
updated_at=datetime(2026, 7, 2, 11, 3, 0),
process_status="upload_failed",
upload_status="failed",
pending_human_reason="upload_rpa_failed",
)
normal_task = _make_task(
task_no="SN-REF-NORMAL-003",
batch=batch,
updated_at=datetime(2026, 7, 2, 11, 4, 0),
process_status="matched",
)
db.session.add_all([batch, focus_task, shortage_task, rejected_task, upload_failed_task, normal_task])
db.session.commit()
context = build_shipping_reference_context(batch=batch, focus_task=focus_task)
candidates = {item["id"]: item["label"] for item in context["candidates"]}
assert candidates == {
"SN-REF-UPFAIL-003": "异常:上传失败",
"SN-REF-REJECT-003": "已驳回",
"SN-REF-SHORT-003": "异常:库存不足",
}
assert "SN-REF-NORMAL-003" not in json.dumps(context, ensure_ascii=False)
def test_build_shipping_reference_context_controls_summary_length_and_avoids_full_batch_dump(app):
"""多任务批次应只输出短摘要,不能把所有 task_no 都拼进 recent_activity_summary。"""
with app.app_context():
batch = ShippingBatch(
batch_no="SB-REF-SUMMARY",
conversation_id="conv-ref-summary",
current_focus_task_no="SN-REF-FOCUS-004",
file_count=10,
)
focus_task = _make_task(
task_no="SN-REF-FOCUS-004",
batch=batch,
updated_at=datetime(2026, 7, 2, 12, 0, 0),
process_status="parsed",
)
db.session.add_all([batch, focus_task])
for index in range(10):
db.session.add(
_make_task(
task_no=f"SN-REF-NOISE-{index:03d}",
batch=batch,
updated_at=datetime(2026, 7, 2, 12, 1, 0) + timedelta(minutes=index),
process_status="pending_review" if index % 2 == 0 else "matched",
match_status="shortage" if index == 0 else None,
pending_human_reason="shortage" if index == 0 else None,
shortage_json={"SKU": index} if index == 0 else None,
)
)
db.session.commit()
context = build_shipping_reference_context(batch=batch, focus_task=focus_task)
summary = context["recent_activity_summary"]
assert len(summary) <= MAX_RECENT_ACTIVITY_SUMMARY_CHARS
assert "SN-REF-FOCUS-004" in summary
assert "SN-REF-NOISE-000" in summary
assert "SN-REF-NOISE-009" not in summary
def test_build_shipping_reference_context_maps_real_decision_event_names(app):
"""真实决策事件名应能映射到标准 action,避免 reference builder 只认理想化别名。"""
with app.app_context():
batch = ShippingBatch(
batch_no="SB-REF-ACTION-MAP",
conversation_id="conv-ref-action-map",
current_focus_task_no="SN-REF-ACTION-MAP-001",
file_count=2,
)
reject_task = _make_task(
task_no="SN-REF-REJECT-REAL",
batch=batch,
updated_at=datetime(2026, 7, 2, 13, 0, 0),
process_status="rejected",
review_status="rejected",
)
focus_task = _make_task(
task_no="SN-REF-ACTION-MAP-001",
batch=batch,
updated_at=datetime(2026, 7, 2, 13, 1, 0),
process_status="parsed",
)
db.session.add_all([batch, reject_task, focus_task])
db.session.flush()
db.session.add_all([
ShippingTaskEvent(
task_id=reject_task.id,
event_type="decision_rejected",
detail_json={"action": "reject", "target_id": reject_task.task_no},
created_at=datetime(2026, 7, 2, 13, 2, 0),
),
ShippingTaskEvent(
task_id=focus_task.id,
event_type="decision_rematch",
detail_json={"action": "rematch", "target_id": focus_task.task_no},
created_at=datetime(2026, 7, 2, 13, 3, 0),
),
])
db.session.commit()
context = build_shipping_reference_context(batch=batch, focus_task=focus_task)
assert context["last_action_target"] == {
"type": "task",
"id": "SN-REF-ACTION-MAP-001",
"action": "rematch",
}
assert context["last_failed_target"]["id"] == "SN-REF-REJECT-REAL"
assert context["last_failed_target"]["reason"] == "rejected"
def test_build_shipping_reference_context_recognizes_focus_switch_event(app):
"""focus_switched 应能进入 last_action_target,供 Dify 理解“刚才切过去那个”。"""
with app.app_context():
batch = ShippingBatch(
batch_no="SB-REF-SWITCH",
conversation_id="conv-ref-switch",
current_focus_task_no="SN-REF-SWITCH-002",
file_count=2,
)
old_focus = _make_task(
task_no="SN-REF-SWITCH-001",
batch=batch,
updated_at=datetime(2026, 7, 2, 14, 0, 0),
process_status="parsed",
)
new_focus = _make_task(
task_no="SN-REF-SWITCH-002",
batch=batch,
updated_at=datetime(2026, 7, 2, 14, 5, 0),
process_status="pending_review",
)
db.session.add_all([batch, old_focus, new_focus])
db.session.flush()
db.session.add(
ShippingTaskEvent(
task_id=new_focus.id,
event_type="focus_switched",
detail_json={
"action": "switch_focus",
"target_id": new_focus.task_no,
"previous_focus_task_no": old_focus.task_no,
"next_focus_task_no": new_focus.task_no,
},
created_at=datetime(2026, 7, 2, 14, 6, 0),
)
)
db.session.commit()
context = build_shipping_reference_context(batch=batch, focus_task=new_focus)
assert context["focus_object"] == {"type": "task", "id": "SN-REF-SWITCH-002"}
assert context["last_action_target"] == {
"type": "task",
"id": "SN-REF-SWITCH-002",
"action": "switch_focus",
}
assert "用户已切换 focus 到 SN-REF-SWITCH-002" in context["recent_activity_summary"]
def test_build_shipping_reference_context_distinguishes_confirm_parse_and_confirm_matched(app):
"""parse_confirmed 与 decision_confirmed 应映射到不同 action,避免“确认解析”和“确认匹配结果”混淆。"""
with app.app_context():
batch = ShippingBatch(
batch_no="SB-REF-CONFIRM-TYPES",
conversation_id="conv-ref-confirm-types",
current_focus_task_no="SN-REF-CONFIRM-TYPES-002",
file_count=2,
)
parse_task = _make_task(
task_no="SN-REF-CONFIRM-TYPES-001",
batch=batch,
updated_at=datetime(2026, 7, 2, 15, 0, 0),
process_status="parsed",
)
matched_task = _make_task(
task_no="SN-REF-CONFIRM-TYPES-002",
batch=batch,
updated_at=datetime(2026, 7, 2, 15, 1, 0),
process_status="matched",
)
db.session.add_all([batch, parse_task, matched_task])
db.session.flush()
db.session.add_all([
ShippingTaskEvent(
task_id=parse_task.id,
event_type="parse_confirmed",
detail_json={"source": "workspace_api", "target_id": parse_task.task_no},
created_at=datetime(2026, 7, 2, 15, 2, 0),
),
ShippingTaskEvent(
task_id=matched_task.id,
event_type="decision_confirmed",
detail_json={"source": "workspace_api", "target_id": matched_task.task_no},
created_at=datetime(2026, 7, 2, 15, 3, 0),
),
])
db.session.commit()
context = build_shipping_reference_context(batch=batch, focus_task=matched_task)
assert context["last_action_target"] == {
"type": "task",
"id": "SN-REF-CONFIRM-TYPES-002",
"action": "confirm_matched",
}
assert "用户已确认 SN-REF-CONFIRM-TYPES-002 当前结果" in context["recent_activity_summary"]
def test_build_shipping_reference_context_prefers_user_focus_switch_over_auto_switch(app):
"""用户切票与系统自动切票并存时,应优先保留用户动作,避免“刚才那个”被后台动作覆盖。"""
with app.app_context():
batch = ShippingBatch(
batch_no="SB-REF-SWITCH-PRIORITY",
conversation_id="conv-ref-switch-priority",
current_focus_task_no="SN-REF-SWITCH-PRIORITY-002",
file_count=2,
)
user_focus = _make_task(
task_no="SN-REF-SWITCH-PRIORITY-001",
batch=batch,
updated_at=datetime(2026, 7, 2, 16, 0, 0),
process_status="parsed",
)
auto_focus = _make_task(
task_no="SN-REF-SWITCH-PRIORITY-002",
batch=batch,
updated_at=datetime(2026, 7, 2, 16, 1, 0),
process_status="pending_review",
)
db.session.add_all([batch, user_focus, auto_focus])
db.session.flush()
db.session.add_all([
ShippingTaskEvent(
task_id=user_focus.id,
event_type="focus_switched",
detail_json={"source": "workspace_api", "target_id": user_focus.task_no},
created_at=datetime(2026, 7, 2, 16, 2, 0),
),
ShippingTaskEvent(
task_id=auto_focus.id,
event_type="focus_auto_switched",
detail_json={"source": "backend_orchestrator", "target_id": auto_focus.task_no},
created_at=datetime(2026, 7, 2, 16, 3, 0),
),
])
db.session.commit()
context = build_shipping_reference_context(batch=batch, focus_task=auto_focus)
assert context["focus_object"] == {"type": "task", "id": "SN-REF-SWITCH-PRIORITY-002"}
assert context["last_action_target"] == {
"type": "task",
"id": "SN-REF-SWITCH-PRIORITY-001",
"action": "switch_focus",
}
assert "用户已切换 focus 到 SN-REF-SWITCH-PRIORITY-001" in context["recent_activity_summary"]
def test_build_shipping_reference_context_uses_auto_focus_when_only_auto_switch_exists(app):
"""只有系统自动切票时,应显式暴露 auto_focus,避免与用户手动切票混淆。"""
with app.app_context():
batch = ShippingBatch(
batch_no="SB-REF-AUTO-FOCUS",
conversation_id="conv-ref-auto-focus",
current_focus_task_no="SN-REF-AUTO-FOCUS-002",
file_count=2,
)
old_focus = _make_task(
task_no="SN-REF-AUTO-FOCUS-001",
batch=batch,
updated_at=datetime(2026, 7, 2, 17, 0, 0),
process_status="parsed",
)
auto_focus = _make_task(
task_no="SN-REF-AUTO-FOCUS-002",
batch=batch,
updated_at=datetime(2026, 7, 2, 17, 1, 0),
process_status="pending_review",
)
db.session.add_all([batch, old_focus, auto_focus])
db.session.flush()
db.session.add(
ShippingTaskEvent(
task_id=auto_focus.id,
event_type="focus_auto_switched",
detail_json={"source": "backend_orchestrator", "target_id": auto_focus.task_no},
created_at=datetime(2026, 7, 2, 17, 2, 0),
)
)
db.session.commit()
context = build_shipping_reference_context(batch=batch, focus_task=auto_focus)
assert context["focus_object"] == {"type": "task", "id": "SN-REF-AUTO-FOCUS-002"}
assert context["last_action_target"] == {
"type": "task",
"id": "SN-REF-AUTO-FOCUS-002",
"action": "auto_focus",
}
assert "系统自动聚焦到 SN-REF-AUTO-FOCUS-002" in context["recent_activity_summary"]
+57 -11
View File
@@ -1,3 +1,6 @@
import json
from pathlib import Path
import pytest
from app import db
@@ -383,6 +386,44 @@ def test_openapi_spec_public(app, client):
assert "JSON 字符串" in map_json_schema["description"]
submit_decision = spec["paths"]["/tools/submit_decision"]["post"]["requestBody"]["content"]["application/json"]["schema"]
assert "retry_rpa" in submit_decision["properties"]["decision"]["enum"]
spec_text = str(spec)
assert "submit_decision" in spec_text
assert "match_inventory" in spec_text
assert "generate_shipment_excel" in spec_text
assert "upload_to_freight" in spec_text
assert "retry_task" in spec_text
assert "confirm_inventory_source" in spec_text
assert "唯一 task_id" in spec_text
assert "模糊指代不能直接推进" in spec_text
assert "状态机" in spec_text
assert "不得自行宣布完成" in spec_text
assert "不要在自然语言正文列出按钮清单" in spec_text
submit_desc = spec["paths"]["/tools/submit_decision"]["post"]["description"]
assert "唯一 task_id" in submit_desc
assert "模糊指代" in submit_desc
assert "needs_human 或 failed" in submit_desc
assert "按钮由 HXOPS 前端渲染" in submit_desc
def test_static_openapi_snapshot_contains_shipping_contract_keywords():
"""静态 OpenAPI 快照应同步最新推进约束,避免 Dify 导入旧版说明。"""
spec_path = Path(__file__).resolve().parents[2] / "docs" / "openapi" / "shipping_notice_tools.dify.json"
spec = json.loads(spec_path.read_text(encoding="utf-8"))
assert spec["openapi"] == "3.0.0"
assert "/tools/submit_decision" in spec["paths"]
spec_text = str(spec)
assert "reference_context" in spec_text
assert "状态机" in spec_text
assert "不得自行改写成完成" in spec_text
assert "不要在自然语言正文列出按钮清单" in spec_text
assert "match_inventory" in spec_text
assert "generate_shipment_excel" in spec_text
assert "upload_to_freight" in spec_text
submit_desc = spec["paths"]["/tools/submit_decision"]["post"]["description"]
assert "唯一 task_id" in submit_desc
assert "模糊指代" in submit_desc
assert "按钮由 HXOPS 前端渲染" in submit_desc
def test_parse_inventory_from_chat_text(app, client):
@@ -1390,11 +1431,11 @@ def test_submit_decision_confirm_inventory_mapping_enqueues_worker(app, client,
@pytest.mark.auto_rpa
def test_rpa_pending_timeout_recheck_triggers_next_inventory_export(app, client, tmp_path):
def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt(app, client, tmp_path):
from datetime import datetime, timedelta
from app.services.shipping_notice.batch_orchestrator import _run_single_task
from app.services.shipping_notice.constants import PH_RPA_PENDING
from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED, PH_RPA_PENDING
headers = _tool_headers(app)
trigger = tmp_path / "inventory_triggers"
@@ -1437,12 +1478,13 @@ def test_rpa_pending_timeout_recheck_triggers_next_inventory_export(app, client,
result = _run_single_task(task_id)
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert result["status"] == "running"
assert result["status"] == "needs_human"
assert task.process_status == "waiting_inventory"
assert task.pending_human_reason == PH_RPA_PENDING
assert task.pending_human_reason == PH_RPA_EXHAUSTED
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_failed").count() == 1
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").count() == 2
assert len(list(trigger.glob("inventory_export_*.json"))) == 1
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").count() == 1
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_exhausted").count() == 1
assert len(list(trigger.glob("inventory_export_*.json"))) == 0
@pytest.mark.auto_rpa
@@ -1453,8 +1495,11 @@ def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_pa
headers = _tool_headers(app)
trigger = tmp_path / "inventory_triggers"
inventory_drop = tmp_path / "inventory_drop"
trigger.mkdir()
inventory_drop.mkdir()
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger)
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(inventory_drop)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
@@ -1513,11 +1558,11 @@ def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_pa
@pytest.mark.auto_rpa
def test_batch_retry_rechecks_timed_out_rpa_pending_immediately(app, client, tmp_path):
def test_batch_retry_marks_timed_out_rpa_pending_task_as_exhausted(app, client, tmp_path):
from datetime import datetime, timedelta
from app.services.shipping_notice.batch_orchestrator import retry_batch_pending_tasks
from app.services.shipping_notice.constants import PH_RPA_PENDING
from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED, PH_RPA_PENDING
headers = _tool_headers(app)
trigger = tmp_path / "inventory_triggers"
@@ -1573,10 +1618,11 @@ def test_batch_retry_rechecks_timed_out_rpa_pending_immediately(app, client, tmp
assert result["started"] == 1
assert result["skipped"] == 0
assert task.process_status == "waiting_inventory"
assert task.pending_human_reason == PH_RPA_PENDING
assert task.pending_human_reason == PH_RPA_EXHAUSTED
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_failed").count() == 1
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").count() == 2
assert len(list(trigger.glob("inventory_export_*.json"))) == 1
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").count() == 1
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_exhausted").count() == 1
assert len(list(trigger.glob("inventory_export_*.json"))) == 0
def test_submit_decision_by_conversation_id(app, client):
@@ -0,0 +1,26 @@
"""
tests/test_shipping_notice_user_facing_status.py
用途:验证发货通知用户可见阶段文案的优先级,避免细粒度 pending 状态被通用 checkpoint 覆盖。
依赖:pytest、ShippingTask 模型、user_facing_status。
逻辑:构造最小 ShippingTask 实例,断言 rpa_pending 时优先展示具体的 RPA 导出提示。
"""
from app.models import ShippingTask
from app.services.shipping_notice.constants import PH_RPA_PENDING
from app.services.shipping_notice.user_facing_status import user_facing_task_stage
def test_user_facing_task_stage_prefers_specific_rpa_pending_reason() -> None:
"""
rpa_pending 时应优先展示 RPA 导出中的具体提示,而不是通用的“待上传或获取库存”。
核心逻辑:构造 waiting_inventory + rpa_pending 的任务,验证用户可见标题优先取 pending_human_reason。
"""
task = ShippingTask(
task_no="SN-TEST-RPA-PENDING",
process_status="waiting_inventory",
pending_human_reason=PH_RPA_PENDING,
)
assert user_facing_task_stage(task) == "RPA 正在导出库存,请稍候"