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:
1 parent
60dd0c0f58
commit
8846ce159f
102 files changed
+18289
-9072
No files matched your search
@@ -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
|
||||
|
||||
Reference in new issue
Block a user