feat(wecom): interactive approval template cards
- interaction events on wecom render as button_interaction template cards (aibot_send_msg template_card): title=tool, buttons keyed <req_id>|<option_id>, 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)
This commit is contained in:
1 parent
10420f9d72
commit
ef2259ad5e
4 files changed
+221
-3
No files matched your search
@@ -61,6 +61,9 @@ class WecomAibotChannel:
|
|||||||
self._streams: dict[str, dict] = {}
|
self._streams: dict[str, dict] = {}
|
||||||
self._req_ids: dict[str, str] = {}
|
self._req_ids: dict[str, str] = {}
|
||||||
self._stream_lock = threading.Lock()
|
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 ---------------------------------------------------------
|
# -- IMChannel ---------------------------------------------------------
|
||||||
def start(self) -> None:
|
def start(self) -> None:
|
||||||
@@ -165,6 +168,8 @@ class WecomAibotChannel:
|
|||||||
event = (body.get("event") or {}).get("eventtype", "")
|
event = (body.get("event") or {}).get("eventtype", "")
|
||||||
if event == "enter_chat":
|
if event == "enter_chat":
|
||||||
self._respond_welcome(ws, req_id)
|
self._respond_welcome(ws, req_id)
|
||||||
|
elif event == "template_card_event":
|
||||||
|
self._on_card_click(body, ws, req_id)
|
||||||
return
|
return
|
||||||
|
|
||||||
sender = (body.get("from") or {}).get("userid") or body.get("sender") or ""
|
sender = (body.get("from") or {}).get("userid") or body.get("sender") or ""
|
||||||
@@ -275,8 +280,15 @@ class WecomAibotChannel:
|
|||||||
if marker:
|
if marker:
|
||||||
self._stream_append(chat_id, marker)
|
self._stream_append(chat_id, marker)
|
||||||
elif kind == "interaction":
|
elif kind == "interaction":
|
||||||
# approval / choice question: close current bubble with a
|
# approval / choice question: render as an interactive template
|
||||||
# structured render; user replies in chat (M1: text-based choice)
|
# 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))
|
self._stream_close(chat_id, _interaction_text(payload))
|
||||||
elif kind == "command_result":
|
elif kind == "command_result":
|
||||||
self.reply(chat_id, _command_result_text(payload))
|
self.reply(chat_id, _command_result_text(payload))
|
||||||
@@ -286,6 +298,83 @@ class WecomAibotChannel:
|
|||||||
self.reply(chat_id, _interaction_text(payload))
|
self.reply(chat_id, _interaction_text(payload))
|
||||||
# "replace" treated as delta reset for now
|
# "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 = '<request_id>|<option_id>' 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 ---------------------------------------------------
|
# -- streaming state ---------------------------------------------------
|
||||||
def _stream_key_states(self, chat_id: str) -> dict:
|
def _stream_key_states(self, chat_id: str) -> dict:
|
||||||
with self._stream_lock:
|
with self._stream_lock:
|
||||||
|
|||||||
@@ -76,7 +76,10 @@ def build_channels(cfg: dict[str, Any], mgr: SessionManager) -> list:
|
|||||||
wcfg = ccfg["wecom"]
|
wcfg = ccfg["wecom"]
|
||||||
# real long-connection transport unless the config says otherwise
|
# real long-connection transport unless the config says otherwise
|
||||||
ws_factory = None if wcfg.get("mock_transport") else make_ws_factory()
|
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:
|
if "wecom-app" in ccfg:
|
||||||
sink_and_inbound(WecomAppChannel(ccfg["wecom-app"]))
|
sink_and_inbound(WecomAppChannel(ccfg["wecom-app"]))
|
||||||
if "weixin" in ccfg:
|
if "weixin" in ccfg:
|
||||||
|
|||||||
@@ -480,6 +480,21 @@ class SessionManager:
|
|||||||
if pr is not None:
|
if pr is not None:
|
||||||
pr.route_key = route_key
|
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:
|
def permission_reply(self, channel: str, chat_id: str, request_id: str, choice: str) -> None:
|
||||||
"""Answer a pending permission/interaction.
|
"""Answer a pending permission/interaction.
|
||||||
|
|
||||||
|
|||||||
@@ -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")
|
||||||
Reference in new issue
Block a user