fix: route IM replies during pending permission to permission_reply (was leaking to agent queue)

This commit is contained in:
openbot committed 2026-10-06 20:40:51 +08:00
1 parent 0e4bcc5a1f
commit 1a25790d4a
3 files changed
+183 -1

No files matched your search

+19 -1
View File
@@ -100,7 +100,25 @@ def _safe_inbound(mgr: SessionManager, ch, m) -> None:
"channel": ch.name, "chat_id": m.chat_id, "channel": ch.name, "chat_id": m.chat_id,
"user_id": m.user_id, "text_len": len(m.text or ""), "user_id": m.user_id, "text_len": len(m.text or ""),
}) })
# 2) commands # 2) pending interaction answer (approval / question): the numbered
# or named reply routes to permission_reply, NOT to the agent.
ans = mgr.take_interaction_answer(ch.name, m.chat_id, m.text or "")
if ans == "consumed":
mgr._emit(f"{ch.name}:{m.chat_id}", "status", {"text": "已收到你的选择,继续处理…"})
return
if ans == "not_an_answer":
# pending interaction exists but text matches no option: prompt
# the user instead of silently forwarding to the agent
inter = mgr.pending_interaction(ch.name, m.chat_id) or {}
hint = "、".join(
f"{i+1}. {o.get('name', o.get('option_id'))}"
for i, o in enumerate(inter.get("options", []))
)
mgr._emit(f"{ch.name}:{m.chat_id}", "final", {
"text": f"当前有待选择的请求({inter.get('tool', '')}),请回复:{hint},或 r 拒绝。"
})
return
# 3) commands
if (m.text or "").strip().startswith("/"): if (m.text or "").strip().startswith("/"):
res = mgr.handle_command(ch.name, m.chat_id, m.text) res = mgr.handle_command(ch.name, m.chat_id, m.text)
if res is not None: if res is not None:
+57
View File
@@ -78,6 +78,7 @@ class PermissionRequest:
tool_title: str tool_title: str
tool_kind: str tool_kind: str
raw_request_id: Any raw_request_id: Any
options: list[dict[str, Any]] = field(default_factory=list)
answered: threading.Event = field(default_factory=threading.Event) answered: threading.Event = field(default_factory=threading.Event)
choice: str | None = None # optionId chosen, None = timeout/deny choice: str | None = None # optionId chosen, None = timeout/deny
@@ -383,6 +384,58 @@ class SessionManager:
return {"stop_reason": res.get("stopReason"), "session_id": b.acp_session_id, "agent": b.agent} return {"stop_reason": res.get("stopReason"), "session_id": b.acp_session_id, "agent": b.agent}
# -- permission --------------------------------------------------------------- # -- permission ---------------------------------------------------------------
def pending_interaction(self, channel: str, chat_id: str) -> dict[str, Any] | None:
"""The most recent pending interaction for this chat, if any."""
key = f"{channel}:{chat_id}"
with self._lock:
pendings = [p for p in self._pending_permissions.values() if p.key == key]
if not pendings:
return None
pr = pendings[-1] # newest
return {
"request_id": pr.request_id,
"tool": pr.tool_title,
"kind": pr.tool_kind,
"options": pr.options,
}
def take_interaction_answer(self, channel: str, chat_id: str, text: str) -> str:
"""If this chat has a pending interaction and text looks like an answer
(number, option name, allow/deny, r), consume it and answer the agent.
Returns "consumed" | "no_pending" | "not_an_answer".
"""
inter = self.pending_interaction(channel, chat_id)
if inter is None:
return "no_pending"
stripped = (text or "").strip()
if not stripped:
return "not_an_answer"
opts = inter["options"]
lower = stripped.lower()
# reject shorthand
if lower in ("r", "reject", "拒绝", "no", "n", "否"):
self.permission_reply(channel, chat_id, inter["request_id"], "reject_once")
return "consumed"
# numbered choice
choice: str | None = None
if stripped.isdigit():
idx = int(stripped) - 1
if 0 <= idx < len(opts):
choice = str(opts[idx]["option_id"])
else:
# option name or id, case-insensitive
for o in opts:
name = str(o.get("name", "")).lower()
oid = str(o.get("option_id", "")).lower()
if lower in (name, oid) or lower in name:
choice = str(o["option_id"])
break
if choice is None:
return "not_an_answer"
self.permission_reply(channel, chat_id, inter["request_id"], choice)
return "consumed"
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.
@@ -528,6 +581,10 @@ class SessionManager:
tool_title=tool.get("title", tool.get("toolCallId", "")), tool_title=tool.get("title", tool.get("toolCallId", "")),
tool_kind=tool.get("kind", ""), tool_kind=tool.get("kind", ""),
raw_request_id=None, raw_request_id=None,
options=[
{"option_id": o.get("optionId"), "name": o.get("name"), "kind": o.get("kind")}
for o in options
],
) )
self._emit(key, "interaction", { self._emit(key, "interaction", {
"interaction_type": "permission", "interaction_type": "permission",
+107
View File
@@ -265,6 +265,113 @@ def test_permission_wrong_chat_rejected(mgr):
th.join(timeout=3) th.join(timeout=3)
def test_interaction_answer_consumed_by_inbound(mgr, monkeypatch):
"""User's numbered reply during a pending permission must reach
permission_reply, not the agent."""
import agenthub.runtime as rt
events = []
mgr.switch("wecom", "c1", "opencode")
b = mgr.get_binding("wecom", "c1")
assert b is not None
mgr._attach_update_relay(b)
mgr.set_event_sink(lambda k, kind, p: events.append((kind, p)))
client = mgr._clients["opencode"]
# simulate agent asking permission (non-blocking thread like real client)
holder = {}
th = threading.Thread(target=lambda: holder.update(resp=client.req_handlers[0](
"session/request_permission",
{"sessionId": b.acp_session_id, "toolCall": {"title": "read /mnt/quant/README.md"},
"options": [{"optionId": "allow_once", "name": "Allow once", "kind": "allow_once"},
{"optionId": "allow_always", "name": "Always allow", "kind": "allow_always"},
{"optionId": "reject_once", "name": "Reject", "kind": "reject_once"}]})), daemon=True)
th.start()
time.sleep(0.2)
# inbound "2" via _safe_inbound
forwarded = []
def fake_prompt(*a, **k):
forwarded.append((a, k))
monkeypatch.setattr(mgr, "prompt", fake_prompt)
class Msg:
chat_id = "c1"
user_id = "u1"
text = "2"
images = None
class Ch:
name = "wecom"
rt._safe_inbound(mgr, Ch(), Msg())
time.sleep(0.3)
assert not forwarded, "answer leaked to the agent"
th.join(timeout=3)
resp = holder["resp"]
assert resp["outcome"]["optionId"] == "allow_always", resp
kinds = [k for k, _ in events]
assert "ack" in kinds and "status" in kinds
def test_interaction_answer_not_matching_prompts_hint(mgr, monkeypatch):
import agenthub.runtime as rt
events = []
mgr.switch("wecom", "c1", "opencode")
b = mgr.get_binding("wecom", "c1")
assert b is not None
mgr._attach_update_relay(b)
mgr.set_event_sink(lambda k, kind, p: events.append((kind, p)))
client = mgr._clients["opencode"]
th = threading.Thread(target=lambda: client.req_handlers[0](
"session/request_permission",
{"sessionId": b.acp_session_id, "toolCall": {"title": "t"},
"options": [{"optionId": "allow_once", "name": "Allow once", "kind": "allow_once"}]}), daemon=True)
th.start()
time.sleep(0.2)
class Msg:
chat_id = "c1"
user_id = "u1"
text = "好了吗"
images = None
class Ch:
name = "wecom"
rt._safe_inbound(mgr, Ch(), Msg())
time.sleep(0.3)
finals = [p for k, p in events if k == "final"]
assert finals and "待选择" in finals[0]["text"]
# cleanup: deny the pending one
mgr.take_interaction_answer("wecom", "c1", "r")
th.join(timeout=3)
def test_no_pending_answer_goes_to_agent(mgr, monkeypatch):
import agenthub.runtime as rt
forwarded = []
monkeypatch.setattr(mgr, "prompt", lambda *a, **k: forwarded.append(1))
class Msg:
chat_id = "cz"
user_id = "u"
text = "2"
images = None
class Ch:
name = "wecom"
rt._safe_inbound(mgr, Ch(), Msg())
time.sleep(0.3)
assert forwarded, "normal prompt should reach agent when nothing pending"
def test_permission_timeout_denies(mgr, monkeypatch): def test_permission_timeout_denies(mgr, monkeypatch):
mgr.permission_timeout_s = 0.3 mgr.permission_timeout_s = 0.3
mgr.switch("wecom", "c1", "opencode") mgr.switch("wecom", "c1", "opencode")