303 lines
10 KiB
Python
303 lines
10 KiB
Python
"""
|
|
backend/tests/test_chat_turn_runtime.py
|
|
|
|
覆盖 Chat Turn Runtime 平台层:SSE 生命周期、action 路由、ChatLog 落库与权限校验。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
|
|
from app import db
|
|
from app.models import Agent, ChatLog, User
|
|
|
|
|
|
def _parse_sse_events(raw: str) -> list[dict]:
|
|
events: list[dict] = []
|
|
for frame in raw.split("\n\n"):
|
|
for line in frame.split("\n"):
|
|
if not line.startswith("data: "):
|
|
continue
|
|
payload = line[6:].strip()
|
|
if payload:
|
|
events.append(json.loads(payload))
|
|
return events
|
|
|
|
|
|
def _create_shipping_agent() -> Agent:
|
|
agent = Agent(
|
|
name="货代发货通知 Agent",
|
|
description="test",
|
|
dify_api_key="test-key",
|
|
api_base_url="http://example.com",
|
|
agent_code="shipping_notice",
|
|
runtime_provider="hybrid",
|
|
conversation_mode="task_chat",
|
|
)
|
|
db.session.add(agent)
|
|
db.session.commit()
|
|
return agent
|
|
|
|
|
|
def _create_user() -> User:
|
|
user = User(username="chat_turn_user", email="chat_turn_user@example.com", role="admin", status="active")
|
|
user.set_password("password")
|
|
db.session.add(user)
|
|
db.session.commit()
|
|
return user
|
|
|
|
|
|
def _create_task_for_user(user_id: int) -> str:
|
|
from app.models import ShippingBatch, ShippingTask
|
|
|
|
batch = ShippingBatch(
|
|
batch_no="BATCH-TURN-001",
|
|
user_id=user_id,
|
|
file_count=1,
|
|
)
|
|
task = ShippingTask(
|
|
task_no="SN-20260706-ABCD1234",
|
|
batch=batch,
|
|
user_id=user_id,
|
|
source_type="manual",
|
|
process_status="created",
|
|
)
|
|
db.session.add_all([batch, task])
|
|
db.session.commit()
|
|
return task.task_no
|
|
|
|
|
|
def test_chat_turn_submit_decision_emits_run_lifecycle(app, client, monkeypatch):
|
|
user = _create_user()
|
|
agent = _create_shipping_agent()
|
|
task_no = _create_task_for_user(user.id)
|
|
|
|
monkeypatch.setattr(
|
|
"app.services.shipping_notice.chat_action_handlers.submit_decision",
|
|
lambda payload: {
|
|
"status": "ok",
|
|
"message": "已确认,请继续下一步。",
|
|
"task_id": task_no,
|
|
"data": {},
|
|
},
|
|
)
|
|
|
|
res = client.post(
|
|
"/api/chat/turns/stream",
|
|
headers={
|
|
"X-Username": user.username,
|
|
"X-Role": user.role,
|
|
"Content-Type": "application/json",
|
|
},
|
|
json={
|
|
"agent_id": agent.id,
|
|
"input": {
|
|
"type": "action",
|
|
"display_text": "确认",
|
|
"action_type": "shipping.submit_decision",
|
|
"payload": {"task_no": task_no, "decision": "confirm"},
|
|
},
|
|
},
|
|
)
|
|
assert res.status_code == 200
|
|
events = _parse_sse_events(res.get_data(as_text=True))
|
|
event_names = [item.get("event") for item in events]
|
|
assert "run.started" in event_names
|
|
assert "step.started" in event_names
|
|
assert "message.completed" in event_names or "message_end" in event_names
|
|
assert "run.completed" in event_names
|
|
|
|
logs = db.session.query(ChatLog).filter_by(user_id=user.id, agent_id=agent.id).all()
|
|
assert len(logs) == 1
|
|
assert logs[0].query == "确认"
|
|
assert "已确认" in logs[0].answer
|
|
|
|
|
|
def test_chat_turn_unknown_action_returns_failed(app, client):
|
|
user = _create_user()
|
|
agent = _create_shipping_agent()
|
|
res = client.post(
|
|
"/api/chat/turns/stream",
|
|
headers={"X-Username": user.username, "X-Role": user.role, "Content-Type": "application/json"},
|
|
json={
|
|
"agent_id": agent.id,
|
|
"input": {
|
|
"type": "action",
|
|
"display_text": "未知动作",
|
|
"action_type": "shipping.not_exists",
|
|
"payload": {},
|
|
},
|
|
},
|
|
)
|
|
assert res.status_code == 200
|
|
events = _parse_sse_events(res.get_data(as_text=True))
|
|
assert any(item.get("event") == "run.failed" for item in events)
|
|
|
|
|
|
def test_chat_turn_rejects_shipping_action_for_non_shipping_agent(app, client):
|
|
user = _create_user()
|
|
agent = Agent(name="通用入口", description="test", dify_api_key="k", api_base_url="http://example.com")
|
|
db.session.add(agent)
|
|
db.session.commit()
|
|
|
|
res = client.post(
|
|
"/api/chat/turns/stream",
|
|
headers={"X-Username": user.username, "X-Role": user.role, "Content-Type": "application/json"},
|
|
json={
|
|
"agent_id": agent.id,
|
|
"input": {
|
|
"type": "action",
|
|
"display_text": "确认",
|
|
"action_type": "shipping.submit_decision",
|
|
"payload": {"task_no": "SN-20260706-ABCD1234", "decision": "confirm"},
|
|
},
|
|
},
|
|
)
|
|
assert res.status_code == 200
|
|
events = _parse_sse_events(res.get_data(as_text=True))
|
|
assert any(item.get("event") == "run.failed" for item in events)
|
|
|
|
|
|
def test_chat_turn_multipart_upload_reads_agent_id_from_form(app, client, monkeypatch, tmp_path):
|
|
"""multipart 上传发货通知时,agent_id 应从 form 字段解析,而非 JSON body。"""
|
|
from io import BytesIO
|
|
|
|
user = _create_user()
|
|
agent = _create_shipping_agent()
|
|
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path)
|
|
monkeypatch.setattr(
|
|
"app.services.shipping_notice.batch_from_notices.create_shipping_batch_from_notice_items",
|
|
lambda **kwargs: {
|
|
"status": "ok",
|
|
"batch_no": "SB-MULTIPART-001",
|
|
"data": {
|
|
"tasks": [{"task_id": "SN-MULTIPART-001"}],
|
|
"focus_task": {"task_no": "SN-MULTIPART-001"},
|
|
},
|
|
},
|
|
)
|
|
|
|
res = client.post(
|
|
"/api/chat/turns/stream",
|
|
headers={"X-Username": user.username, "X-Role": user.role},
|
|
data={
|
|
"agent_id": str(agent.id),
|
|
"input": json.dumps(
|
|
{
|
|
"type": "upload_followup",
|
|
"display_text": "上传发货通知:notice.txt",
|
|
"action_type": "shipping.create_batch_from_notices",
|
|
"payload": {},
|
|
},
|
|
ensure_ascii=False,
|
|
),
|
|
"files": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice.txt"),
|
|
},
|
|
content_type="multipart/form-data",
|
|
)
|
|
assert res.status_code == 200
|
|
events = _parse_sse_events(res.get_data(as_text=True))
|
|
event_names = [item.get("event") for item in events]
|
|
assert "run.started" in event_names
|
|
assert "run.completed" in event_names
|
|
assert "run.failed" not in event_names
|
|
|
|
|
|
def test_chat_turn_create_batch_forwards_idempotency_key(app, client, monkeypatch, tmp_path):
|
|
"""shipping.create_batch_from_notices 应透传 payload 中的建单幂等键。"""
|
|
from io import BytesIO
|
|
|
|
user = _create_user()
|
|
agent = _create_shipping_agent()
|
|
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path)
|
|
captured: dict = {}
|
|
|
|
def fake_create(**kwargs):
|
|
captured.update(kwargs)
|
|
return {
|
|
"status": "ok",
|
|
"batch_no": "SB-CHAT-IDEM-001",
|
|
"data": {
|
|
"tasks": [{"task_id": "SN-CHAT-IDEM-001"}],
|
|
"focus_task": {"task_no": "SN-CHAT-IDEM-001"},
|
|
},
|
|
}
|
|
|
|
monkeypatch.setattr(
|
|
"app.services.shipping_notice.batch_from_notices.create_shipping_batch_from_notice_items",
|
|
fake_create,
|
|
)
|
|
|
|
res = client.post(
|
|
"/api/chat/turns/stream",
|
|
headers={"X-Username": user.username, "X-Role": user.role},
|
|
data={
|
|
"agent_id": str(agent.id),
|
|
"input": json.dumps(
|
|
{
|
|
"type": "upload_followup",
|
|
"display_text": "上传发货通知:notice.txt",
|
|
"action_type": "shipping.create_batch_from_notices",
|
|
"payload": {"idempotency_key": "chat-idem-001"},
|
|
},
|
|
ensure_ascii=False,
|
|
),
|
|
"files": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice.txt"),
|
|
},
|
|
content_type="multipart/form-data",
|
|
)
|
|
assert res.status_code == 200
|
|
res.get_data(as_text=True)
|
|
assert captured.get("create_idempotency_key") == "chat-idem-001"
|
|
notice_items = captured.get("notice_items") or []
|
|
assert notice_items
|
|
assert notice_items[0].get("source_content_hash")
|
|
|
|
|
|
def test_chat_turn_create_batch_idempotent_replay(app, client, monkeypatch, tmp_path):
|
|
"""相同幂等键重复 Chat Turn 不重复建批,并返回可恢复 UI state。"""
|
|
from io import BytesIO
|
|
|
|
user = _create_user()
|
|
agent = _create_shipping_agent()
|
|
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path)
|
|
orchestrator_calls: list[str] = []
|
|
monkeypatch.setattr(
|
|
"app.services.shipping_notice.batch_orchestrator.start_batch_orchestrator",
|
|
lambda batch_no: orchestrator_calls.append(batch_no) or True,
|
|
)
|
|
|
|
payload_input = {
|
|
"type": "upload_followup",
|
|
"display_text": "上传发货通知:notice.txt",
|
|
"action_type": "shipping.create_batch_from_notices",
|
|
"payload": {"idempotency_key": "chat-replay-integration-001"},
|
|
}
|
|
headers = {"X-Username": user.username, "X-Role": user.role}
|
|
raw = "客户:ACME\nA001 x 10".encode("utf-8")
|
|
|
|
def _post_turn():
|
|
return client.post(
|
|
"/api/chat/turns/stream",
|
|
headers=headers,
|
|
data={
|
|
"agent_id": str(agent.id),
|
|
"input": json.dumps(payload_input, ensure_ascii=False),
|
|
"files": (BytesIO(raw), "notice.txt"),
|
|
},
|
|
content_type="multipart/form-data",
|
|
)
|
|
|
|
first = _post_turn()
|
|
assert first.status_code == 200
|
|
first_events = _parse_sse_events(first.get_data(as_text=True))
|
|
assert "run.failed" not in [item.get("event") for item in first_events]
|
|
|
|
second = _post_turn()
|
|
assert second.status_code == 200
|
|
second_events = _parse_sse_events(second.get_data(as_text=True))
|
|
completed = [item for item in second_events if item.get("event") == "message.completed"]
|
|
assert completed
|
|
assert "已恢复此前创建的批次" in str(completed[-1].get("content", ""))
|
|
assert len(orchestrator_calls) == 1
|