refactor(agent-runtime, shipping-notice, frontend): 重构上下文体系,修复重试RPA无响应问题

- 替换原有的hxops_context模块为全新的代理运行时上下文平台协议,统一跨业务上下文注入逻辑
- 新增多语言操作繁忙提示文案(覆盖中、繁、英、泰四语),前端绑定页面繁忙状态实现操作阻断
- 调整RPA库存导出重试策略:移除可配置的最大自动重试次数,改为固定单次自动重试,手动重试需用户显式触发
- 优化任务用户态状态展示逻辑,优先展示具体的pending原因而非通用状态文案
- 重构任务焦点切换逻辑,统一事件日志与处理流程,复用switch_batch_focus工具函数
- 修复clearAllHistory函数残留UI问题,确保清空会话后完全复位发货通知相关视图
- 更新OpenAPI文档与静态快照,补充工具使用约束说明
- 新增调试打点日志与问题排查文档,完善全套单元测试与快照校验用例
- 更新RPA脚本的README文档,调整登录方式说明与浏览器 profile 路径配置
- 删除废弃的hxops_context模块,迁移所有相关调用到新的上下文体系
This commit is contained in:
hugo committed 2026-07-03 17:01:42 +08:00
1 parent 60dd0c0f58
commit 8846ce159f
102 files changed
+18289 -9072

No files matched your search

+2
View File
@@ -26,6 +26,7 @@ def register_blueprints(app: Flask) -> None:
from app.api.internal_jobs import internal_jobs_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
@@ -53,5 +54,6 @@ def register_blueprints(app: Flask) -> None:
app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs')
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(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"),
)
)
+52 -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.services.integration_api import IntegrationApiService
from app.core.decorators import require_agent_permission
@@ -46,6 +47,26 @@ def _can_use_leave_feature(agent_proxy) -> bool:
return agent_name in LEAVE_FEATURE_AGENT_NAMES
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 _session_title_from_text(text: str) -> str:
value = str(text or '').strip()
if not value:
@@ -1231,7 +1252,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:
@@ -1244,23 +1283,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
@@ -1272,15 +1314,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)}})
+176 -36
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,36 @@ def _require_user():
return user
def _ok(payload: dict):
"""返回带 request_id 的成功 envelope,供工作台读接口复用。"""
return ok(payload, request_id=getattr(g, 'request_id', None))
def _notice_file_type(upload) -> str | None:
"""提取上传文件 MIME type;为空时返回 None,保持响应字段稳定。"""
return str(getattr(upload, 'mimetype', '') or '').strip() or None
def _build_notice_file_summary(
*,
total_files: int,
accepted_files: list[dict],
rejected_files: list[dict],
) -> dict[str, object]:
"""
构建工作台批量上传预检摘要。
核心逻辑:把可建任务文件与被拒文件统一汇总到 file_summary,供前端回显和测试断言使用。
"""
return {
'total_files': total_files,
'accepted_count': len(accepted_files),
'rejected_count': len(rejected_files),
'accepted_files': accepted_files,
'rejected_files': rejected_files,
}
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET'])
def workspace_shipping_tasks():
"""列出当前用户可见的发货任务,可按批次与处理状态过滤。"""
@@ -73,10 +108,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 +122,87 @@ 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 (
cleanup_temp_notice_uploads,
extract_notice_text,
guess_source_type,
max_notice_chars,
save_temp_notice_upload,
)
conversation_id = str(request.form.get('conversation_id') or '').strip()
temp_request_id = str(getattr(g, 'request_id', None) or uuid.uuid4().hex)
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}
accepted_files: list[dict] = []
rejected_files: list[dict] = []
try:
for index, upload in enumerate(uploads, start=1):
raw = upload.read() or b''
filename = upload.filename or 'notice'
source_type = guess_source_type(filename)
source_file_type = _notice_file_type(upload)
text = ''
warnings: list[str] = []
try:
saved_path = save_temp_notice_upload(temp_request_id, index, 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': source_file_type,
'raw_text': text,
'warnings': warnings,
}
)
accepted_files.append(
{
'filename': filename,
'source_type': source_type,
'source_file_type': source_file_type,
'text_length': len(text),
'warnings': warnings,
}
)
continue
rejected_files.append(
{
'filename': filename,
'source_type': source_type,
'source_file_type': source_file_type,
'reason': 'empty_text',
'message': 'notice text is empty after extraction',
'warnings': warnings,
}
)
finally:
cleanup_temp_notice_uploads(temp_request_id)
file_summary = _build_notice_file_summary(
total_files=len(uploads),
accepted_files=accepted_files,
rejected_files=rejected_files,
)
if not notice_items:
raise ValidationError(
'all uploaded files failed extraction or contained no parseable text',
details={'rejected_files': 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 +223,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 +285,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)})
@@ -277,16 +394,39 @@ def workspace_replace_shipping_task_notice(task_no: str):
data = result.setdefault('data', {})
if isinstance(data, dict):
data['notice_upload'] = {'filename': filename, **(meta if isinstance(meta, dict) else {})}
return jsonify(result)
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 +505,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