Files
inquiry_robot/inquiry-agent/tests/test_handoff_human.py
T

645 lines
25 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
转人工:缺项连问、虚拟号、摘要骨架。
"""
from __future__ import annotations
import os
import sys
import unittest
from datetime import datetime
from zoneinfo import ZoneInfo
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
if ROOT not in sys.path:
sys.path.insert(0, ROOT)
from agent.policy import handoff_human as hh
from agent.policy import inquiry_copy as copy
from agent.policy.air_text_flow import FlowSession
class _FakeGroup:
"""测试用企微群客户端:记录建群/发文字/发文件,不碰网络。"""
def __init__(self) -> None:
self.created: list[dict] = []
self.sent: list[dict] = []
self.files: list[dict] = []
def create_group(self, *, name: str, userids: list[str]) -> dict:
self.created.append({"name": name, "userids": list(userids)})
return {"ok": True, "chat_id": "wr_h1", "error": ""}
def send_group(self, *, chat_id: str, content: str, mention_userids=None) -> dict:
self.sent.append({"chat_id": chat_id, "content": content})
return {"ok": True}
def send_group_file(self, **kwargs) -> dict:
self.files.append(dict(kwargs))
return {"ok": True}
class _Sess:
def __init__(self) -> None:
self.clarify_missing_sig = ""
self.clarify_retry = 0
self.handoff_offer = ""
self.work_order_no = ""
self.virtual_work_order_no = ""
class HandoffCoreTests(unittest.TestCase):
def setUp(self) -> None:
hh.reset_virtual_seq_for_test()
def test_same_missing_set_offers_after_three_asks(self) -> None:
sess = _Sess()
keys = ["起运港", "目的港"]
self.assertEqual(hh.note_clarify_round(sess, keys), "ask")
self.assertEqual(sess.clarify_retry, 0)
self.assertEqual(hh.note_clarify_round(sess, keys), "ask")
self.assertEqual(sess.clarify_retry, 1)
self.assertEqual(hh.note_clarify_round(sess, keys), "ask")
self.assertEqual(sess.clarify_retry, 2)
self.assertEqual(hh.note_clarify_round(sess, keys), "handoff")
self.assertEqual(sess.clarify_retry, 3)
def test_changed_missing_resets_and_voids_clarify_offer(self) -> None:
sess = _Sess()
hh.note_clarify_round(sess, ["起运港"])
hh.note_clarify_round(sess, ["起运港"])
sess.handoff_offer = "clarify"
self.assertEqual(hh.note_clarify_round(sess, ["目的港"]), "ask")
self.assertEqual(sess.clarify_retry, 0)
self.assertEqual(sess.handoff_offer, "")
def test_virtual_no_prefix_not_wo(self) -> None:
no = hh.next_virtual_no(now=datetime(2026, 9, 20, tzinfo=ZoneInfo("Asia/Shanghai")))
self.assertTrue(no.startswith("VT20260920"))
self.assertEqual(len(no), 14)
self.assertFalse(no.startswith("WO"))
self.assertTrue(hh.is_virtual_no(no))
self.assertFalse(hh.is_virtual_no("WO202609200001"))
def test_handoff_brief_dashes_collab_and_glues_ticket(self) -> None:
text = copy.handoff_group_brief(
work_order_no="WO202609190018",
facts={
"运输类型": "跨境集拼",
"线路类别": "中港/中亚/中欧",
"运输分类": "普件(东南亚、中亚、中欧涉及境外段清派等特殊要求)",
"起运地": "深圳市",
"目的地": "南京市",
"毛重": "1KG",
"报价日期": "2026-09-19",
},
business_line="LAND",
product_names=["林绵勋", "罗小华", "吴季林"],
)
self.assertIn("@林绵勋 @罗小华 @吴季林", text)
self.assertIn("WO202609190018转人工", text)
self.assertNotIn("工单号:", text.split("转人工")[0][-6:])
self.assertIn("货物品名:-", text)
self.assertIn("客户名称:-", text)
self.assertNotIn("TMS报价", text)
def test_already_collab_copy(self) -> None:
self.assertEqual(copy.HANDOFF_ALREADY_COLLAB, "该工单已拉产品进群协同。")
def test_air_hint_contains_virtual(self) -> None:
text = copy.handoff_air_hint(work_order_no="VT202609200001")
self.assertEqual(
text,
"触发转人工,请手动把航线和智能体拉进原有空运群,并发送工单号 VT202609200001。",
)
self.assertNotIn("拉产品进群", text)
def test_clarify_progress_and_stale_wo(self) -> None:
self.assertTrue(copy.clarify_progress_line(1).startswith("参数提取不全(1/3)"))
self.assertEqual(copy.with_clarify_progress("请确认并补充以下信息:", 0), "请确认并补充以下信息:")
wrapped = copy.with_clarify_progress("请确认并补充以下信息:", 2)
self.assertTrue(wrapped.startswith("参数提取不全(2/3)"))
self.assertIn("请确认并补充以下信息", wrapped)
sess = _Sess()
sess.work_order_no = "WO202609180018"
sess.phase = "clarify"
no = hh.ticket_no_for_handoff_offer(sess)
self.assertTrue(str(no).startswith("VT"))
self.assertEqual(sess.work_order_no, "")
kept = _Sess()
kept.work_order_no = "WO202609180018"
kept.phase = "wait_collab"
self.assertEqual(hh.ticket_no_for_handoff_offer(kept), "WO202609180018")
def test_handoff_reuses_existing_formal_ticket(self) -> None:
"""已出过正式单:转人工沿用原单号,不再新开一张。"""
from agent.ledger.memory_ledger import MemoryLedger
ledger = MemoryLedger()
created = ledger.create_ticket(
sender_id="s1", business_line="AIR", facts={"起运港": "ZUH"}
)
no = created["work_order_no"]
sess = _Sess()
sess.work_order_no = no
sess.phase = "wait_collab"
sess.handoff_work_order_no = ""
sess.collab_mode = ""
class _Flow:
pass
flow = _Flow()
flow.ledger = ledger
got = hh.ensure_formal_ticket_for_handoff(flow, sess)
self.assertEqual(got, no)
self.assertEqual(sess.handoff_work_order_no, no)
self.assertEqual(len(ledger._tickets), 1)
class HandoffFlowOfferTests(unittest.TestCase):
"""海运:说「转人工」不出卡,直接建正式单 + 建群 + 发摘要和空白模板。"""
def setUp(self) -> None:
hh.reset_virtual_seq_for_test()
from agent.policy.sea_text_flow import reset_sea_text_flow_for_test
self.flow = reset_sea_text_flow_for_test()
self.replies: list[str] = []
self.groups = _FakeGroup()
self.flow._group_client = self.groups
self.flow.ledger.set_sea_staff(
[
{
"name": "林绵勋",
"wecomId": "prod1",
"roleCode": "sea",
"routes": "海运·全部线路",
"status": "active",
}
]
)
def reply(text: str, extra=None):
self.replies.append(text)
return "out"
self.reply = reply
def _partial(self, text: str) -> str:
return self.flow.on_text(sender_id="s1", text=text, reply=self.reply)
def test_three_same_clarify_builds_group_without_card(self) -> None:
"""连问三次仍不齐:海运不再出「拉产品进群」卡,直接建群把活交给产品。"""
self._partial("海运询价")
self._partial("还是那些")
self._partial("不知道")
phase = self._partial("还没有")
self.assertEqual(phase, "handoff_done")
joined = "\n".join(self.replies)
self.assertIn("参数提取不全(3/3)", joined)
self.assertNotIn(copy.BTN_PULL_COLLAB, joined)
self.assertTrue(self.groups.created)
self.assertTrue(self.groups.created[0]["name"].startswith("WO"))
brief = self.groups.sent[0]["content"]
self.assertIn("转人工", brief)
# 业务类型/报价场景只有陆运卡才有,海运摘要里出现这两行产品会以为漏填。
self.assertNotIn("业务类型:", brief)
self.assertNotIn("报价场景:", brief)
self.assertNotIn("TMS报价", brief)
sess = self.flow.session_of("s1")
self.assertTrue(sess.handoff_committed)
self.assertEqual(sess.collab_mode, "handoff")
self.assertEqual(sess.phase, "handoff_done")
# 不自动推空白模板:报价单要群里说「生成报价单」才出。
self.assertEqual(self.groups.files, [])
self.assertNotIn("空白报价模板", self.replies[-1])
self.assertIn("生成报价单", self.replies[-1])
def test_intent_handoff_creates_group_once(self) -> None:
"""销售说「转人工」直接建群;重复说不重复建群。"""
self._partial("海运询价")
phase = self.flow.offer_handoff(sender_id="s1", text="转人工", reply=self.reply)
self.assertEqual(phase, "handoff_done")
self.assertEqual(len(self.groups.created), 1)
self.assertTrue(self.groups.created[0]["name"].startswith("WO"))
sid = self.flow.session_of("s1")
self.assertTrue(sid.collab_chat_id)
again = self.flow.offer_handoff(sender_id="s1", text="转人工", reply=self.reply)
self.assertEqual(again, "handoff_done")
self.assertEqual(len(self.groups.created), 1)
def test_no_staff_does_not_build_empty_group(self) -> None:
"""没有可拉的海运产品:不建空群,并且再说一次还能重试。"""
from agent.policy.sea_text_flow import reset_sea_text_flow_for_test
# 重置换一个干净的海运单例:setUp 里注入的那份产品名单不能带进来。
self.flow = reset_sea_text_flow_for_test()
groups = _FakeGroup()
self.flow._group_client = groups
replies: list[str] = []
def reply(text: str, extra=None):
replies.append(text)
return "out"
self.flow.on_text(sender_id="s1", text="海运询价", reply=reply)
phase = self.flow.offer_handoff(sender_id="s1", text="转人工", reply=reply)
self.assertEqual(phase, "handoff_no_staff")
self.assertEqual(groups.created, [])
self.assertEqual(replies[-1], copy.sea_group_no_staff())
sess = self.flow.session_of("s1")
self.assertFalse(sess.handoff_committed)
self.assertEqual(sess.phase, "handoff_offer")
def test_new_inquiry_after_commit_starts_fresh(self) -> None:
self._partial("海运询价")
self.flow.offer_handoff(sender_id="s1", text="转人工", reply=self.reply)
self.replies.clear()
phase = self._partial("海运询价")
self.assertNotEqual(phase, "handoff_done")
joined = "\n".join(self.replies)
self.assertNotIn("已转人工,本单不再自动跟进", joined)
self.assertIn("请确认并补充以下信息", joined)
sess = self.flow.session_of("s1")
self.assertFalse(sess.handoff_committed)
self.assertEqual(sess.phase, "clarify")
def test_already_has_group_only_prompts(self) -> None:
self.flow._save(
FlowSession(
sender_id="s1",
thread_id="s1",
phase="collab_group",
business_line="SEA",
work_order_no="WO202609200099",
collab_chat_id="wr_exist",
status="已报价",
)
)
phase = self.flow.offer_handoff(sender_id="s1", text="转人工", reply=self.reply)
self.assertEqual(phase, "handoff_already")
self.assertEqual(self.replies[-1], copy.HANDOFF_ALREADY_COLLAB)
self.assertFalse(self.flow.session_of("s1").handoff_committed)
def test_route_contract_accepts_handoff_human(self) -> None:
from agent.routing.deepseek_a import DeepSeekARouter
from agent.routing.ordered_actions import ACTION_INTENTS, parse_ordered_actions_arguments
self.assertEqual(ACTION_INTENTS.get("HANDOFF_HUMAN"), "handoff_human")
parsed = parse_ordered_actions_arguments(
{
"decision_id": "d-h",
"intent": "handoff_human",
"ordered_action": {
"action_type": "HANDOFF_HUMAN",
"order": 1,
"target": {"work_order_no": ""},
"evidence": {"source_ref": "inbound:u1", "content_digest": "a" * 64},
},
}
)
self.assertEqual(parsed.to_route_decision().intent, "handoff_human")
router = DeepSeekARouter.from_settings()
sys_msg, _user = router.build_messages(text="帮我转人工", sender_id="u1")
self.assertIn("handoff_human", sys_msg["content"])
self.assertIn("口令不写死", sys_msg["content"])
self.assertIn("抱怨慢", sys_msg["content"])
def test_first_clarify_does_not_count(self) -> None:
self._partial("海运询价")
self.assertTrue(self.replies)
self.assertNotIn("参数提取不全(1/3)", self.replies[0])
self.assertIn("请确认并补充以下信息", self.replies[0])
self._partial("还是那些")
self.assertTrue(self.replies[-1].startswith("参数提取不全(1/3)"))
def test_air_handoff_before_create_creates_formal_ticket(self) -> None:
"""空运转人工:销售要发正式工单号,所以入口前必须先落正式单,不能再给 VT。"""
from agent.policy.air_text_flow import reset_air_text_flow_for_test
flow = reset_air_text_flow_for_test()
replies: list[str] = []
sess = FlowSession(
sender_id="air1",
thread_id="air1",
phase="clarify",
business_line="AIR",
work_order_no="WO202609180018",
facts={"起运港": "ZUH", "目的港": "CRK", "品名": "衣服"},
)
flow._save(sess)
phase = flow._offer_handoff_now(
sender_id="air1",
reason="clarify",
reply=lambda t, extra=None: replies.append(t) or "out",
sess=sess,
)
self.assertEqual(phase, "handoff_offer")
self.assertTrue(replies)
formal = str(sess.handoff_work_order_no or "")
self.assertTrue(formal.startswith("WO"), formal)
self.assertIn(formal, replies[0])
# 旧书签上的工单号不是本票,不能拿它冒充新转人工单。
self.assertNotIn("WO202609180018", replies[0])
self.assertEqual(sess.collab_mode, "handoff")
self.assertEqual(sess.work_order_no, "")
ticket = flow.ledger.get_ticket(work_order_no=formal)
self.assertIsNotNone(ticket)
self.assertEqual(ticket.collab_mode, "handoff")
def test_third_clarify_handoff_even_if_routed_as_adjust(self) -> None:
from agent.channel.queue import get_message_store
from agent.channel.wecom.models import InboundMessage
from agent.handlers.text_inquiry import handle_text_inquiry
from agent.routing.decision import RouteDecision
from agent.routing.dispatch import dispatch_inbound
# 内存 outbox 与会话存储是进程级单例:先清空、再用独立 sender,
# 否则同进程里别的用例残留的消息会让「不应出现按钮」这类断言假失败。
store = get_message_store()
store._outbox.clear()
sender = "s_clarify3"
handle_text_inquiry(
InboundMessage(sender_id=sender, message_id="h1", content="海运询价"),
store=store,
flow=self.flow,
)
handle_text_inquiry(
InboundMessage(sender_id=sender, message_id="h2", content="还是那些"),
store=store,
flow=self.flow,
)
handle_text_inquiry(
InboundMessage(sender_id=sender, message_id="h3", content="不知道"),
store=store,
flow=self.flow,
)
name = dispatch_inbound(
InboundMessage(sender_id=sender, message_id="h4", content="价格再低一点"),
RouteDecision(intent="quote_adjust"),
)
self.assertEqual(name, "quote_adjust")
sess = self.flow.session_of(sender)
self.assertEqual(sess.phase, "handoff_done")
self.assertEqual(sess.collab_mode, "handoff")
bodies = "\n".join(i.content for i in store._outbox.values())
self.assertIn("参数提取不全(3/3)", bodies)
self.assertNotIn(copy.BTN_PULL_COLLAB, bodies)
self.assertEqual(len(self.groups.created), 1)
class NamedTicketHandoffTests(unittest.TestCase):
"""点名工单号转人工时,只看那一张单,不看私聊里另一张已建群的单。"""
def _flow(self):
from agent.policy.land_text_flow import LandTextInquiryFlow
from agent.ledger.memory_ledger import MemoryLedger
return LandTextInquiryFlow(MemoryLedger())
def test_deal_followup_not_blocked_by_other_group(self) -> None:
flow = self._flow()
flow._save(
FlowSession(
sender_id="s1",
thread_id="s1",
phase="wait_deal",
business_line="LAND",
work_order_no="WO202610040002",
status="已报价",
quote={"total": "CNY 800", "quoteFileIssued": True},
)
)
flow._save(
FlowSession(
sender_id="s1",
thread_id="s1",
phase="collab_group",
business_line="LAND",
work_order_no="WO202610040004",
collab_chat_id="wr_other",
status="询价中",
)
)
replies: list[str] = []
def reply(text: str, extra=None) -> str:
replies.append(text)
_ = extra
return ""
phase = flow.offer_handoff(
sender_id="s1", text="WO202610040002转人工", reply=reply
)
# 陆运转人工现在先出「业务类型 + 报价场景」多项选择卡,提交后才建群。
self.assertEqual(phase, "handoff_land_pick")
self.assertIn("运输方式:陆运", replies[-1])
self.assertIn("业务类型", replies[-1])
self.assertIn("报价场景", replies[-1])
self.assertNotIn("原有空运群", replies[-1])
self.assertNotEqual(replies[-1], copy.HANDOFF_ALREADY_COLLAB)
named = flow.session_by_ticket("s1", "WO202610040002")
self.assertEqual(named.phase, "handoff_land_pick")
self.assertFalse((named.collab_chat_id or "").strip())
def test_named_ticket_with_group_still_blocked(self) -> None:
flow = self._flow()
flow._save(
FlowSession(
sender_id="s1",
thread_id="s1",
phase="collab_group",
business_line="LAND",
work_order_no="WO202610040002",
collab_chat_id="wr_real",
status="询价中",
)
)
replies: list[str] = []
def reply(text: str, extra=None) -> str:
replies.append(text)
_ = extra
return ""
phase = flow.offer_handoff(
sender_id="s1", text="WO202610040002转人工", reply=reply
)
self.assertEqual(phase, "handoff_already")
self.assertEqual(replies[-1], copy.HANDOFF_ALREADY_COLLAB)
def test_ledger_deal_ticket_without_group_offers_card(self) -> None:
from agent.ledger.memory_ledger import MemoryTicket
flow = self._flow()
no = "WO202610040012"
flow.ledger._tickets[no] = MemoryTicket(
work_order_no=no,
sales_wecom_id="s1",
business_line="LAND",
facts={"运输方式": "陆运"},
fingerprint="land-deal",
status="已报价",
quote={"total": "CNY 800", "quoteFileIssued": True},
quote_file_ready=True,
)
flow._save(
FlowSession(
sender_id="s1",
thread_id="s1",
phase="collab_group",
business_line="LAND",
work_order_no="WO202610040004",
collab_chat_id="wr_other",
status="询价中",
)
)
replies: list[str] = []
def reply(text: str, extra=None) -> str:
replies.append(text)
_ = extra
return ""
phase = flow.offer_handoff(sender_id="s1", text=f"{no}转人工", reply=reply)
# 陆运先出选卡;不能被另一张已建群的单挡成「已拉产品进群」。
self.assertEqual(phase, "handoff_land_pick")
self.assertIn("业务类型", "\n".join(replies))
self.assertNotIn(copy.HANDOFF_ALREADY_COLLAB, replies)
def test_air_deal_ticket_ignores_other_land_group(self) -> None:
"""空运成交跟进没有协同群时,不能被另一张陆运已拉群的单挡成「已拉产品进群」。"""
from agent.ledger.memory_ledger import MemoryTicket
flow = self._flow()
no = "WO202610040002"
flow.ledger._tickets[no] = MemoryTicket(
work_order_no=no,
sales_wecom_id="s1",
business_line="AIR",
facts={"运输方式": "空运", "目的港": "CRK"},
fingerprint="air-deal",
status="已报价",
quote={"total": "CNY 800", "quoteFileIssued": True},
quote_file_ready=True,
)
flow._save(
FlowSession(
sender_id="s1",
thread_id="s1",
phase="collab_group",
business_line="LAND",
work_order_no="WO202610040004",
collab_chat_id="wr_other",
status="询价中",
)
)
replies: list[str] = []
def reply(text: str, extra=None) -> str:
replies.append(text)
_ = extra
return ""
phase = flow.offer_handoff(sender_id="s1", text=f"{no}转人工", reply=reply)
joined = "\n".join(replies)
self.assertEqual(phase, "handoff_offer")
self.assertIn("原有空运群", joined)
self.assertNotIn("是否拉产品人员进群协同", joined)
self.assertNotIn(copy.HANDOFF_ALREADY_COLLAB, joined)
def test_ledger_mode_wins_over_stale_bookmark(self) -> None:
"""主账是空运时,进程里标成陆运的旧书签也不能改成陆运拉群卡。"""
from agent.ledger.memory_ledger import MemoryTicket
flow = self._flow()
no = "WO202610040002"
flow.ledger._tickets[no] = MemoryTicket(
work_order_no=no,
sales_wecom_id="s1",
business_line="AIR",
facts={},
fingerprint="air-wins",
status="已报价",
quote={"total": "CNY 800", "quoteFileIssued": True},
quote_file_ready=True,
)
flow._save(
FlowSession(
sender_id="s1",
thread_id="s1",
phase="wait_deal",
business_line="LAND",
work_order_no=no,
status="已报价",
)
)
replies: list[str] = []
def reply(text: str, extra=None) -> str:
replies.append(text)
_ = extra
return ""
phase = flow.offer_handoff(sender_id="s1", text=f"{no}转人工", reply=reply)
joined = "\n".join(replies)
self.assertEqual(phase, "handoff_offer")
self.assertIn("原有空运群", joined)
self.assertNotIn("运输方式:陆运", joined)
def test_sea_deal_ticket_builds_handoff_group(self) -> None:
"""海运已报价单点名转人工:沿用原工单号直接建群,不出陆运/空运卡。"""
from agent.ledger.memory_ledger import MemoryTicket
from agent.policy.sea_text_flow import reset_sea_text_flow_for_test
flow = reset_sea_text_flow_for_test()
groups = _FakeGroup()
flow._group_client = groups
flow.ledger.set_sea_staff(
[
{
"name": "林绵勋",
"wecomId": "prod1",
"roleCode": "sea",
"routes": "海运·全部线路",
"status": "active",
}
]
)
no = "WO202610040013"
flow.ledger._tickets[no] = MemoryTicket(
work_order_no=no,
sales_wecom_id="s1",
business_line="SEA",
facts={"运输方式": "海运"},
fingerprint="sea-deal",
status="已报价",
quote={"total": "USD 100", "quoteFileIssued": True},
quote_file_ready=True,
)
replies: list[str] = []
def reply(text: str, extra=None) -> str:
replies.append(text)
_ = extra
return ""
phase = flow.offer_handoff(sender_id="s1", text=f"{no}转人工", reply=reply)
joined = "\n".join(replies)
self.assertEqual(phase, "handoff_done")
self.assertEqual(len(groups.created), 1)
self.assertEqual(groups.created[0]["name"], no)
self.assertIn(no, joined)
self.assertNotIn("原有空运群", joined)
self.assertNotIn(copy.BTN_PULL_COLLAB, joined)
sess = flow.session_of("s1")
self.assertEqual(sess.collab_mode, "handoff")
self.assertEqual(sess.handoff_work_order_no, no)
if __name__ == "__main__":
unittest.main()