Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions packages/runtime/src/ginno_runtime/channels/ask_relay.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,9 +171,6 @@ async def _mirror_question(session_id: str, data: dict) -> None:
channel = (shared._SESSIONS.get(session_id) or {}).get("channel")
if channel and channel != "wecom":
return
if data.get("multi"):
# 企微文本回执一次只能提交一个答案。
return

try:
ad = _wecom_adapter()
Expand Down
31 changes: 23 additions & 8 deletions packages/runtime/src/ginno_runtime/channels/wecom/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,24 +275,39 @@ async def _try_answer(self, req_id: str, chat_key: str, text: str) -> bool:
# 一次性凭证:先弹登记再恢复——之后任何重放只可能命中墓碑或被
# 守卫/checkpointer 双信号拒绝,不存在二次执行路径。
sid = str(pending.get("session_id") or "")
questions = pending.get("questions") or []
if questions:
answers = p.parse_multi_answer(text, questions)
if answers is None:
if self.client is not None:
try:
await self.client.send_markdown(chat_key, p.MULTI_ANSWER_GUIDE)
except Exception: # noqa: BLE001
pass
return True
response = {"multi": True, "answers": answers}
summary = " / ".join(a["answer"] or "(跳过)" for a in answers)
skipped = all(a["skip"] for a in answers)
else:
response = p.parse_answer(text, pending.get("options") or [])
summary = response["answer"]
skipped = response["skip"]

self._pending_q.pop(chat_key, None)
value = p.parse_answer(text, list(pending.get("options") or []))
from ...api.stream.resume import resume_question

ok = await resume_question(
sid,
answer=str(value.get("answer") or ""),
option_index=value.get("option_index"),
skip=bool(value.get("skip")),
# 主动镜像关联当前进程的停车守卫。桌面已答时不再重新武装。
arm_from_checkpoint=not pending.get("proactive"),
answered_by="wecom",
**response,
)
if ok:
self.mark_question_answered(
chat_key, qid=str(pending.get("question_id") or ""),
session_id=sid, answer=str(value.get("answer") or ""),
skip=bool(value.get("skip")), raw=text, answered_by="wecom")
session_id=sid, answer=summary,
skip=skipped, raw=text, answered_by="wecom")
return True
# 过期 qid / 已答(守卫空且 checkpoint 无 parked):拒绝并告知。
# 不再像旧 resume 管线那样回落成新 turn——迟到的「2」开新 turn
Expand Down Expand Up @@ -636,7 +651,7 @@ def question_destination(self, session_id: str) -> str | None:

async def register_pending_question(
self, chat_key: str, session_id: str, question_id: str, options: list,
*, proactive: bool = False,
*, questions: list[dict] | None = None, proactive: bool = False,
) -> dict | None:
previous = self._pending_q.get(chat_key)
if previous is not None:
Expand All @@ -649,7 +664,7 @@ async def register_pending_question(
return None
pending = {
"session_id": session_id, "question_id": question_id,
"options": options, "proactive": proactive,
"options": options, "questions": questions or [], "proactive": proactive,
}
self._pending_q[chat_key] = pending
# 新问题作废旧墓碑:之后的拒绝提示不得误引上一问的答案
Expand Down
60 changes: 49 additions & 11 deletions packages/runtime/src/ginno_runtime/channels/wecom/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,17 +187,55 @@ def extract_mixed(body: dict) -> tuple[str, dict | None]:
return " ".join(parts), image


def parse_answer(text: str, options: list) -> dict:
"""把用户回复解析成 resume 载荷(ask_user 文本作答路径)。
MULTI_ANSWER_GUIDE = (
"请用一条消息按题号逐行回复,例如 `1. 2` 表示第 1 题选第 2 项,"
"`2. 你的回答` 表示第 2 题作答。单题可填 `跳过`,整组可直接回复 `跳过`。"
)
_SKIP_ANSWERS = {"跳过", "skip", "跳过这个问题"}
_NUMBERED_ANSWER = re.compile(r"([1-9])[.、::)]\s*(.+)")

「跳过/skip」→ skip;纯数字 → option_index(1-based);其余按自由文本。
"""

def parse_answer(text: str, options: list[str]) -> dict:
"""解析一道题的回复。用户从 1 开始编号,恢复时使用从 0 开始的索引。"""
t = text.strip()
if t.lower() in ("跳过", "skip", "跳过这个问题"):
return {"kind": "user_answer", "answer": "", "option_index": None, "skip": True}
if t.isdigit():
idx = int(t)
if t.lower() in _SKIP_ANSWERS:
return {"answer": "", "option_index": None, "skip": True}
if options and t.isdecimal():
try:
idx = int(t)
except ValueError:
idx = 0
if 1 <= idx <= len(options):
return {"kind": "user_answer", "answer": str(options[idx - 1]),
"option_index": idx - 1, "skip": False}
return {"kind": "user_answer", "answer": t, "option_index": None, "skip": False}
return {"answer": options[idx - 1], "option_index": idx - 1, "skip": False}
return {"answer": t, "option_index": None, "skip": False}


def parse_multi_answer(text: str, questions: list[dict]) -> list[dict] | None:
"""按题号解析一条完整回复。缺题、题号重复或不合法的答案返回 None。"""
if text.strip().lower() in _SKIP_ANSWERS:
return [parse_answer(text, []) for _ in questions]

answers: dict[int, dict] = {}
for line in text.splitlines():
if not line.strip():
continue
match = _NUMBERED_ANSWER.fullmatch(line.strip())
if not match:
return None
index = int(match[1]) - 1
if index >= len(questions) or index in answers:
return None
question = questions[index]
options = question.get("options") or []
answer = parse_answer(match[2], options)
if not answer["skip"] and answer["option_index"] is None:
value = answer["answer"]
if value in options:
answer["option_index"] = options.index(value)
elif not question.get("allow_free_text", True) or (options and value.isdecimal()):
return None
answers[index] = answer

if len(answers) != len(questions):
return None
return [answers[i] for i in range(len(questions))]
19 changes: 15 additions & 4 deletions packages/runtime/src/ginno_runtime/channels/wecom/tap.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,16 +211,27 @@ async def _flush_text_media(self) -> None:
async def _send_question(self, data: dict) -> bool:
q_id = str(data.get("qid") or data.get("id") or "")
options = list(data.get("options") or [])
questions = data.get("questions") or []
lines = [f"\n\n❓ **{data.get('header') or 'Ginno 提问'}**",
str(data.get("question") or "")]
for i, opt in enumerate(options):
lines.append(f"{i + 1}. {opt}")
lines.append("\n(直接回复数字或文字作答;回复「跳过」跳过)")
if questions:
for i, question in enumerate(questions, 1):
header = question.get("header")
title = f"第 {i} 题 · {header}" if header else f"第 {i} 题"
lines.extend(["", f"**{title}**", "", question["question"]])
if sub_options := question.get("options"):
lines.append("")
lines.extend(f"{j}. {option}" for j, option in enumerate(sub_options, 1))
lines.extend(["", p.MULTI_ANSWER_GUIDE])
else:
lines.extend(f"{i}. {option}" for i, option in enumerate(options, 1))
lines.append("\n(直接回复数字或文字作答;回复「跳过」跳过)")
md = "\n".join(lines)
timeout_s = float(self.adapter.config.get("ask_timeout_s") or 600)
# 回执到达前就可以收到用户回复,先占用该聊天的待答位置。
pending = await self.adapter.register_pending_question(
self.chat_key, self.session_id, q_id, options, proactive=not self.req_id)
self.chat_key, self.session_id, q_id, options,
questions=questions, proactive=not self.req_id)
if pending is None:
return False
try:
Expand Down
79 changes: 79 additions & 0 deletions packages/runtime/tests/e2e/test_wecom_question_delivery.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,82 @@ async def send_answer():
receipt = json.loads(results[0]["content"])
assert receipt["source"] == "option"
assert receipt["answer"] == "B" and receipt["option_index"] == 1


@pytest.mark.parametrize("mirrored", [False, True], ids=["direct", "mirrored"])
def test_wecom_delivers_and_resumes_each_question(
client, create_session, ws_conv, isolated_home, monkeypatch, mirrored,
):
sid = create_session([
script(tool_calls=[script_tool_call(
"ask_user",
{
"header": "三道题",
"questions": [
{"header": "出行", "question": "怎么去?", "options": ["走路", "坐车"],
"allow_free_text": False},
{"question": "什么时间?"},
{"question": "带什么?", "options": ["雨伞", "水"]},
],
},
"call_wecom_multi",
)]),
script(text="收到答复。"),
])
settings = isolated_home / "settings.json"
raw = json.loads(settings.read_text())
raw["ask_relay_wecom"] = True
settings.write_text(json.dumps(raw))
chat = "bound-user"
ad = WeComChannelAdapter()
ad._mapper = SessionMapper(isolated_home / "channels" / "test-mappings.json")
ad._mapper.bind(user_id=chat, chat_id=chat, ginno_session=sid)
ad.client = AsyncMock()
monkeypatch.setattr(builtin, "_wecom_adapter", ad)
client.portal.call(mark_channel_meta, server_shared._SESSIONS[sid], "wecom")

async def send_text(text, req_id):
await ad.handle_msg(
{"from": {"userid": chat}, "chattype": "single", "msgtype": "text",
"text": {"content": text}},
{"headers": {"req_id": req_id}},
)

async def verify_card_and_answer():
if mirrored:
ad.client.send_markdown.assert_awaited_once()
destination, card = ad.client.send_markdown.await_args.args
assert destination == chat
else:
card = ad.client.respond.await_args.args[1]["stream"]["content"]
ad.client.send_markdown.assert_not_awaited()
for content in ("三道题", "出行", "怎么去?", "什么时间?", "带什么?", "2. 坐车"):
assert content in card
pending = ad._pending_q[chat]
await send_text("1. 2", "incomplete-answer")
assert ad._pending_q[chat] is pending
assert sid in server_shared._PENDING_RESUME
assert "逐行回复" in ad.client.send_markdown.await_args.args[1]
streams_before_answer = ad.client.respond.await_count
await send_text("1. 2\n2. 晚上\n3. 跳过", "complete-answer")
assert chat not in ad._pending_q
assert ad.client.respond.await_count == streams_before_answer

with ws_conv(sid) as conv:
if mirrored:
assert client.portal.call(_wake_parent_turn, sid, "子代理结果", {}) == "ran"
else:
client.portal.call(send_text, "请问我三道题", "test-question")
parked = conv.recv_until("user.question", "message.end", "error")
assert events_of(parked, "user.question")[0]["multi"] is True
client.portal.call(verify_card_and_answer)
resumed = conv.recv_until("message.end", "error")
assert not events_of(resumed, "error")

results = [e for e in events_of(resumed, "tool.end") if e.get("id") == "call_wecom_multi"]
assert len(results) == 1
receipt = json.loads(results[0]["content"])
assert receipt["multi"] is True
assert [(r["source"], r["answer"], r["option_index"]) for r in receipt["results"]] == [
("option", "坐车", 1), ("free_text", "晚上", None), ("skipped", "", None),
]
22 changes: 20 additions & 2 deletions packages/runtime/tests/unit/test_wecom_channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,21 @@ def test_parse_answer():
assert oob["answer"] == "9" # 越界数字按自由文本


def test_parse_multi_answer_validates_each_question():
questions = [{"options": ["A", "B"], "allow_free_text": False}, {}]
assert p.parse_multi_answer("2:123\n1、B", questions) == [
{"answer": "B", "option_index": 1, "skip": False},
{"answer": "123", "option_index": None, "skip": False},
]
assert p.parse_multi_answer("跳过", questions) == [
{"answer": "", "option_index": None, "skip": True},
{"answer": "", "option_index": None, "skip": True},
]
for invalid in ("1. B", "1. B\n1. A", "1. B\n3. 晚上", "1. 9\n2. 晚上",
"1. 随便\n2. 晚上"):
assert p.parse_multi_answer(invalid, questions) is None


# ---------------------------------------------------------------- sessions


Expand Down Expand Up @@ -391,8 +406,11 @@ def __init__(self, config=None):
self.pending: dict[str, dict] = {}
self.answered: dict[str, dict] = {}

async def register_pending_question(self, chat_key, session_id, qid, options, *, proactive=False):
pending = {"session_id": session_id, "question_id": qid, "options": options}
async def register_pending_question(
self, chat_key, session_id, qid, options, *, questions=None, proactive=False,
):
pending = {"session_id": session_id, "question_id": qid, "options": options,
"questions": questions or []}
self.pending[chat_key] = pending
return pending

Expand Down
Loading