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

@@ -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 正在导出库存,请稍候"