From 090281835ab82b47c7b21e650a3799a20d1d557e Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Mon, 6 Jul 2026 14:50:59 +0800 Subject: [PATCH] =?UTF-8?q?refactor(file-check):=20=E5=A2=9E=E5=BC=BA?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E6=A3=80=E6=A0=B8=E6=9C=8D=E5=8A=A1=EF=BC=8C?= =?UTF-8?q?=E6=96=B0=E5=A2=9E=E5=8F=AF=E9=9D=A0=E6=80=A7=E5=85=83=E4=BF=A1?= =?UTF-8?q?=E6=81=AF=E4=B8=8E=E9=94=99=E8=AF=AF=E5=88=86=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .dbg/retry-rpa-no-request.env | 2 - backend/app/api/workspace/file_check.py | 13 +- backend/app/services/dify.py | 295 ++++++++++++++---- backend/app/services/file_check.py | 275 +++++++++++++++- .../app/services/schedule/excel_service.py | 14 +- backend/app/services/schedule/srm_service.py | 70 +++-- .../shipping_notice/decision_workflow.py | 23 +- backend/app/services/shipping_notice/i18n.py | 6 +- .../tests/test_dify_workflow_reliability.py | 273 ++++++++++++++++ .../test_file_check_error_classification.py | 216 +++++++++++++ backend/tests/test_file_check_tools.py | 5 + debug-retry-rpa-no-request.md | 25 -- .../shipping/useChatShippingDecision.spec.ts | 19 +- .../chat/shipping/useChatShippingDecision.ts | 8 +- 14 files changed, 1093 insertions(+), 151 deletions(-) delete mode 100644 .dbg/retry-rpa-no-request.env create mode 100644 backend/tests/test_dify_workflow_reliability.py create mode 100644 backend/tests/test_file_check_error_classification.py delete mode 100644 debug-retry-rpa-no-request.md diff --git a/.dbg/retry-rpa-no-request.env b/.dbg/retry-rpa-no-request.env deleted file mode 100644 index b2e50e0d..00000000 --- a/.dbg/retry-rpa-no-request.env +++ /dev/null @@ -1,2 +0,0 @@ -DEBUG_SERVER_URL=http://127.0.0.1:7778/event -DEBUG_SESSION_ID=retry-rpa-no-request diff --git a/backend/app/api/workspace/file_check.py b/backend/app/api/workspace/file_check.py index 6a692313..2b7a4c0b 100644 --- a/backend/app/api/workspace/file_check.py +++ b/backend/app/api/workspace/file_check.py @@ -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 {} diff --git a/backend/app/services/dify.py b/backend/app/services/dify.py index 83ae013d..dc38d950 100644 --- a/backend/app/services/dify.py +++ b/backend/app/services/dify.py @@ -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( diff --git a/backend/app/services/file_check.py b/backend/app/services/file_check.py index c094b682..5da6d00b 100644 --- a/backend/app/services/file_check.py +++ b/backend/app/services/file_check.py @@ -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, } diff --git a/backend/app/services/schedule/excel_service.py b/backend/app/services/schedule/excel_service.py index 0270f270..7d675bab 100644 --- a/backend/app/services/schedule/excel_service.py +++ b/backend/app/services/schedule/excel_service.py @@ -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] = [] diff --git a/backend/app/services/schedule/srm_service.py b/backend/app/services/schedule/srm_service.py index 2f337650..f3a30516 100644 --- a/backend/app/services/schedule/srm_service.py +++ b/backend/app/services/schedule/srm_service.py @@ -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"), }) diff --git a/backend/app/services/shipping_notice/decision_workflow.py b/backend/app/services/shipping_notice/decision_workflow.py index f10afeff..a13625bd 100644 --- a/backend/app/services/shipping_notice/decision_workflow.py +++ b/backend/app/services/shipping_notice/decision_workflow.py @@ -41,7 +41,7 @@ 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, @@ -271,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 diff --git a/backend/app/services/shipping_notice/i18n.py b/backend/app/services/shipping_notice/i18n.py index feb62fd0..57365843 100644 --- a/backend/app/services/shipping_notice/i18n.py +++ b/backend/app/services/shipping_notice/i18n.py @@ -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 diff --git a/backend/tests/test_dify_workflow_reliability.py b/backend/tests/test_dify_workflow_reliability.py new file mode 100644 index 00000000..858244fb --- /dev/null +++ b/backend/tests/test_dify_workflow_reliability.py @@ -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 diff --git a/backend/tests/test_file_check_error_classification.py b/backend/tests/test_file_check_error_classification.py new file mode 100644 index 00000000..dff71252 --- /dev/null +++ b/backend/tests/test_file_check_error_classification.py @@ -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 diff --git a/backend/tests/test_file_check_tools.py b/backend/tests/test_file_check_tools.py index 59add9a0..15a98a1a 100644 --- a/backend/tests/test_file_check_tools.py +++ b/backend/tests/test_file_check_tools.py @@ -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) diff --git a/debug-retry-rpa-no-request.md b/debug-retry-rpa-no-request.md deleted file mode 100644 index 48be3cd0..00000000 --- a/debug-retry-rpa-no-request.md +++ /dev/null @@ -1,25 +0,0 @@ -# Debug Session: retry-rpa-no-request -- **Status**: [OPEN] -- **Issue**: 点击“重试 RPA”后,界面出现已触发/已重新触发类文案,但怀疑本轮并未真正写出 RPA trigger。 -- **Debug Server**: pending -- **Log File**: .dbg/trae-debug-log-retry-rpa-no-request.ndjson - -## Reproduction Steps -1. 打开发货通知聊天页,定位任务 `SN-20260702-9D76D759`。 -2. 在右侧工作台或聊天气泡中点击“重试 RPA”。 -3. 观察是否出现新的聊天回复、任务卡刷新以及后端 trigger 写入。 - -## Hypotheses & Verification -| ID | Hypothesis | Likelihood | Effort | Evidence | -|----|------------|------------|--------|----------| -| A | 前端点击后没有真正触发 decision 请求 | High | Low | Pending | -| B | 前端提交了 decision,但 `taskId/decision` 参数错误 | High | Low | Pending | -| C | 后端收到了 `retry_rpa`,但没有成功写出 trigger 文件 | High | Medium | Pending | -| D | trigger 已写出,但前端显示的是旧消息/旧状态 | Medium | Medium | Pending | -| E | 当前可见文本并非本轮点击实时产物,而是聊天消息复用 | Medium | Medium | Pending | - -## Log Evidence -- Pending - -## Verification Conclusion -- Pending diff --git a/frontend/src/features/chat/shipping/useChatShippingDecision.spec.ts b/frontend/src/features/chat/shipping/useChatShippingDecision.spec.ts index 1741f6ec..5265573a 100644 --- a/frontend/src/features/chat/shipping/useChatShippingDecision.spec.ts +++ b/frontend/src/features/chat/shipping/useChatShippingDecision.spec.ts @@ -9,17 +9,14 @@ import { describe, expect, it, vi } from 'vitest'; import { createShippingDecisionHandlers, type ShippingDecisionContext } from './useChatShippingDecision'; const { - autoProgressWorkspaceShippingTask, markWorkspaceShippingManualUploaded, submitWorkspaceShippingDecision, } = vi.hoisted(() => ({ - autoProgressWorkspaceShippingTask: vi.fn(), markWorkspaceShippingManualUploaded: vi.fn(), submitWorkspaceShippingDecision: vi.fn(), })); vi.mock('@/features/chat/api/shipping.api', () => ({ - autoProgressWorkspaceShippingTask, markWorkspaceShippingManualUploaded, submitWorkspaceShippingDecision, })); @@ -114,4 +111,20 @@ describe('useChatShippingDecision', () => { expect(submitWorkspaceShippingDecision).toHaveBeenCalledWith('SN-TARGET-009', 'retry_rpa'); expect(ctx.msg.warning).not.toHaveBeenCalled(); }); + + it('submits confirm_inventory_mapping via submit_decision instead of auto_progress', async () => { + submitWorkspaceShippingDecision.mockResolvedValue({ + status: 'running', + message: '库存字段对齐已确认,后台继续处理匹配与后续步骤。', + data: {}, + }); + const ctx = createContext(); + const { executeShippingDecision } = createShippingDecisionHandlers(ctx); + + const ok = await executeShippingDecision('confirm_inventory_mapping', '确认'); + + expect(ok).toBe(true); + expect(submitWorkspaceShippingDecision).toHaveBeenCalledWith('SN-FOCUS-001', 'confirm_inventory_mapping'); + expect(ctx.messages.value).toHaveLength(2); + }); }); diff --git a/frontend/src/features/chat/shipping/useChatShippingDecision.ts b/frontend/src/features/chat/shipping/useChatShippingDecision.ts index 4d22061e..dfea28fa 100644 --- a/frontend/src/features/chat/shipping/useChatShippingDecision.ts +++ b/frontend/src/features/chat/shipping/useChatShippingDecision.ts @@ -5,7 +5,6 @@ * 逻辑:由 useChatShipping 调用本文件;本文件负责把 confirm/reject/reparse 等决策提交到后端,并生成聊天区本地消息。 */ import { - autoProgressWorkspaceShippingTask, markWorkspaceShippingManualUploaded, submitWorkspaceShippingDecision, } from '@/features/chat/api/shipping.api'; @@ -101,10 +100,9 @@ export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) { taskId, }); // #endregion - const result = - decision === 'confirm_inventory_mapping' - ? await autoProgressWorkspaceShippingTask(taskId) - : await submitWorkspaceShippingDecision(taskId, decision); + // 字段对齐确认必须走 submit_decision(confirm_inventory_mapping); + // auto_progress 在 align_review 只会再次返回同一检查点,造成点击确认后死循环。 + const result = await submitWorkspaceShippingDecision(taskId, decision); // #region debug-point D:decision-after-submit void reportRetryRpaDebug('D', 'executeShippingDecision after submit', { decision,