From ef2259ad5ef561f53ea248dbaeb6bb6b8afc51cb Mon Sep 17 00:00:00 2001 From: OpenBot Date: Wed, 14 Oct 2026 17:55:58 +0800 Subject: [PATCH] feat(wecom): interactive approval template cards MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - interaction events on wecom render as button_interaction template cards (aibot_send_msg template_card): title=tool, buttons keyed |, task_id=request_id, allow=primary style, reject=danger - aibot_event_callback template_card_event -> card_answer_cb -> SessionManager.answer_card(req_id, option_id) answers the pending permission directly (presented anti-race rule kept); card updated in place via aibot_respond_update_msg (已批准/已拒绝) - text fallback on card send failure; numbered text replies still work - tests: tests/test_approval_card.py (4 cases) --- src/agenthub/channels/wecom.py | 95 +++++++++++++++++++++++++++- src/agenthub/runtime.py | 5 +- src/agenthub/session.py | 15 +++++ tests/test_approval_card.py | 111 +++++++++++++++++++++++++++++++++ 4 files changed, 222 insertions(+), 4 deletions(-) create mode 100644 tests/test_approval_card.py diff --git a/src/agenthub/channels/wecom.py b/src/agenthub/channels/wecom.py index 54b95a7..c1e772c 100644 --- a/src/agenthub/channels/wecom.py +++ b/src/agenthub/channels/wecom.py @@ -61,6 +61,9 @@ class WecomAibotChannel: self._streams: dict[str, dict] = {} self._req_ids: dict[str, str] = {} self._stream_lock = threading.Lock() + # approval card answers: set by runtime, called as + # cb(request_id, option_id, answered_by) -> None + self.card_answer_cb: Callable[[str, str, str], None] | None = None # -- IMChannel --------------------------------------------------------- def start(self) -> None: @@ -165,6 +168,8 @@ class WecomAibotChannel: event = (body.get("event") or {}).get("eventtype", "") if event == "enter_chat": self._respond_welcome(ws, req_id) + elif event == "template_card_event": + self._on_card_click(body, ws, req_id) return sender = (body.get("from") or {}).get("userid") or body.get("sender") or "" @@ -275,9 +280,16 @@ class WecomAibotChannel: if marker: self._stream_append(chat_id, marker) elif kind == "interaction": - # approval / choice question: close current bubble with a - # structured render; user replies in chat (M1: text-based choice) - self._stream_close(chat_id, _interaction_text(payload)) + # approval / choice question: render as an interactive template + # card (button_interaction); falls back to text if the card send + # is not possible. The card click callback answers via + # card_answer_cb; numbered text replies still work. + try: + self._send_approval_card(chat_id, payload) + self._stream_close(chat_id, "🔒 审批请求已发卡片,请点击按钮或回复编号。") + except Exception as e: # noqa: BLE001 + self._logger.warning(f"[wecom] approval card send failed: {e}") + self._stream_close(chat_id, _interaction_text(payload)) elif kind == "command_result": self.reply(chat_id, _command_result_text(payload)) elif kind == "final": @@ -286,6 +298,83 @@ class WecomAibotChannel: self.reply(chat_id, _interaction_text(payload)) # "replace" treated as delta reset for now + # -- approval cards ------------------------------------------------------ + _BTN_STYLE = {"allow_once": 1, "always_once": 1, "reject_once": 4} # 1 primary, 4 danger + + def _send_approval_card(self, chat_id: str, payload: dict[str, Any]) -> None: + """Send a button_interaction template card via aibot_send_msg. + + Button key = '|' so the click callback can + route the answer back to the exact pending permission. task_id is + the request_id (unique per approval, reused by the update call). + """ + req_id = str(payload.get("request_id") or "") + opts = payload.get("options") or [] + buttons = [ + { + "text": str(o.get("name") or o.get("option_id"))[:12], + "style": self._BTN_STYLE.get(o.get("kind"), 0), + "key": f"{req_id}|{o.get('option_id')}", + } + for o in opts + ][:6] # WeCom card cap: 6 buttons + card = { + "card_type": "button_interaction", + "source": {"desc": "agenthub"}, + "main_title": {"title": f"🔐 {str(payload.get('tool') or '审批请求')[:26]}"}, + "sub_title_text": f"agent: {payload.get('agent', '')} · 请求 {req_id[:8]}", + "button_list": buttons, + "task_id": req_id.replace("-", "_").replace("@", "_")[:128], + } + self._send( + { + "cmd": "aibot_send_msg", + "headers": {"req_id": uuid.uuid4().hex}, + "body": { + "chatid": chat_id, + "chat_type": 0, + "msgtype": "template_card", + "template_card": card, + }, + } + ) + + def _on_card_click(self, body: dict[str, Any], ws: Any, cb_req_id: str) -> None: + """aibot_event_callback eventtype=template_card_event: route the + button answer to the pending permission, then update the card.""" + evt = (body.get("event") or {}).get("template_card_event") or {} + event_key = str(evt.get("event_key") or "") + sender = str(((body.get("from") or {}).get("userid")) or "") + self._logger.info(f"[wecom] card click: key={event_key[:60]} by={sender}") + req_id, _, option_id = event_key.partition("|") + answered = False + if req_id and option_id and self.card_answer_cb: + try: + self.card_answer_cb(req_id, option_id, sender) + answered = True + except Exception as e: # noqa: BLE001 + self._logger.error(f"[wecom] card answer failed: {e}") + # update the card so the user sees the decision was taken + task_id = str(evt.get("task_id") or "").replace("-", "_").replace("@", "_")[:128] + title = "✅ 已批准" if answered and "reject" not in option_id else ("❌ 已拒绝" if answered else "⚠️ 处理失败") + try: + self._send( + { + "cmd": "aibot_respond_update_msg", + "headers": {"req_id": cb_req_id}, + "body": { + "response_type": "update_template_card", + "template_card": { + "card_type": "button_interaction", + "main_title": {"title": f"{title} · {req_id[:8]}"}, + "task_id": task_id, + }, + }, + } + ) + except Exception as e: # noqa: BLE001 + self._logger.warning(f"[wecom] card update failed: {e}") + # -- streaming state --------------------------------------------------- def _stream_key_states(self, chat_id: str) -> dict: with self._stream_lock: diff --git a/src/agenthub/runtime.py b/src/agenthub/runtime.py index 5190fdf..412e22f 100644 --- a/src/agenthub/runtime.py +++ b/src/agenthub/runtime.py @@ -76,7 +76,10 @@ def build_channels(cfg: dict[str, Any], mgr: SessionManager) -> list: wcfg = ccfg["wecom"] # real long-connection transport unless the config says otherwise ws_factory = None if wcfg.get("mock_transport") else make_ws_factory() - sink_and_inbound(WecomAibotChannel(wcfg, ws_factory=ws_factory)) + wecom = WecomAibotChannel(wcfg, ws_factory=ws_factory) + # approval card button clicks answer the pending permission directly + wecom.card_answer_cb = lambda req, opt, by: mgr.answer_card(req, opt, by) + sink_and_inbound(wecom) if "wecom-app" in ccfg: sink_and_inbound(WecomAppChannel(ccfg["wecom-app"])) if "weixin" in ccfg: diff --git a/src/agenthub/session.py b/src/agenthub/session.py index cb6d756..3d45e48 100644 --- a/src/agenthub/session.py +++ b/src/agenthub/session.py @@ -480,6 +480,21 @@ class SessionManager: if pr is not None: pr.route_key = route_key + def answer_card(self, request_id: str, option_id: str, answered_by: str = "") -> None: + """Answer a pending permission from a template-card button click. + + The card key carries the exact request_id + option_id, so no chat + matching is needed; presented is required (same anti-race rule as + permission_reply).""" + with self._lock: + pr = self._pending_permissions.get(request_id) + if pr is None: + raise SessionError(f"no pending permission {request_id}") + if not pr.presented: + raise SessionError("permission request not yet shown; try again in a moment") + pr.choice = option_id + pr.answered.set() + def permission_reply(self, channel: str, chat_id: str, request_id: str, choice: str) -> None: """Answer a pending permission/interaction. diff --git a/tests/test_approval_card.py b/tests/test_approval_card.py new file mode 100644 index 0000000..a48db54 --- /dev/null +++ b/tests/test_approval_card.py @@ -0,0 +1,111 @@ +"""Tests: wecom approval template cards. + +card send frame shape, click event -> card_answer_cb, card update frame, +and SessionManager.answer_card. +""" + +import json + +from agenthub.channels.wecom import WecomAibotChannel +from agenthub.session import SessionManager, PermissionRequest + + +def _ch() -> WecomAibotChannel: + return WecomAibotChannel( + {"bot_id": "b", "secret": "s", "mock_transport": True}, ws_factory=None + ) + + +def _outbox(ch: WecomAibotChannel) -> list[dict]: + return [json.loads(x) for x in ch._outbox] + + +def test_interaction_sends_template_card(): + ch = _ch() + ch.push_event("vex1023", "interaction", { + "interaction_type": "permission", "request_id": "req-1234", + "tool": "run cmd", "kind": "execute", "agent": "opencode", + "options": [ + {"option_id": "allow_once", "name": "Allow once", "kind": "allow_once"}, + {"option_id": "reject_once", "name": "Reject", "kind": "reject_once"}, + ], + }) + frames = _outbox(ch) + card = [f for f in frames if f.get("cmd") == "aibot_send_msg" + and f["body"].get("msgtype") == "template_card"] + assert card, frames + tc = card[0]["body"]["template_card"] + assert tc["card_type"] == "button_interaction" + assert tc["task_id"] == "req_1234" + keys = [b["key"] for b in tc["button_list"]] + assert keys == ["req-1234|allow_once", "req-1234|reject_once"] + assert tc["button_list"][1]["style"] == 4 # reject = danger style + + +def test_card_click_answers_permission(): + ch = _ch() + answered = [] + + def cb(req, opt, by): + answered.append((req, opt, by)) + + ch.card_answer_cb = cb + ch._on_card_click( + { + "from": {"userid": "vex1023"}, + "event": { + "eventtype": "template_card_event", + "template_card_event": { + "card_type": "button_interaction", + "event_key": "req-1234|allow_once", + "task_id": "req_1234", + }, + }, + }, + ws=None, + cb_req_id="cb-1", + ) + assert answered == [("req-1234", "allow_once", "vex1023")] + frames = _outbox(ch) + upd = [f for f in frames if f.get("cmd") == "aibot_respond_update_msg"] + assert upd and upd[0]["headers"]["req_id"] == "cb-1" + assert "已批准" in upd[0]["body"]["template_card"]["main_title"]["title"] + assert upd[0]["body"]["template_card"]["task_id"] == "req_1234" + + +def test_card_click_reject_title(): + ch = _ch() + ch.card_answer_cb = lambda *a: None + ch._on_card_click( + { + "event": {"eventtype": "template_card_event", + "template_card_event": {"event_key": "r1|reject_once", "task_id": "r1"}}, + }, ws=None, cb_req_id="cb2", + ) + upd = [f for f in _outbox(ch) if f.get("cmd") == "aibot_respond_update_msg"] + assert "已拒绝" in upd[0]["body"]["template_card"]["main_title"]["title"] + + +def _mgr() -> SessionManager: + return SessionManager(agents={}, client_factory=lambda spec: None) + + +def _pending(mgr: SessionManager, req_id="req1") -> None: + mgr._pending_permissions[req_id] = PermissionRequest( + request_id=req_id, agent="a", acp_request_id=None, session_id="s", + key="nats:c", tool_title="t", tool_kind="execute", raw_request_id=None, + options=[{"option_id": "allow_once", "name": "A", "kind": "allow_once"}], + ) + mgr._pending_permissions[req_id].presented = True + + +def test_answer_card_sets_choice(): + import pytest + from agenthub.session import SessionError + mgr = _mgr() + _pending(mgr) + mgr.answer_card("req1", "allow_once", "vex1023") + assert mgr._pending_permissions["req1"].choice == "allow_once" + # unknown request id -> error + with pytest.raises(SessionError): + mgr.answer_card("nope", "allow_once")