feat: IM commands (/new /model /agents /switch /status), inbound ack, structured permission interactions

This commit is contained in:
openbot committed 2026-10-06 17:46:53 +08:00
1 parent c16b643ed8
commit e36f596255
7 files changed
+591 -44

No files matched your search

+60
View File
@@ -7,6 +7,7 @@ binding, agent routing, permissions) is channel-agnostic.
from __future__ import annotations
from dataclasses import dataclass, field
import json
from typing import Any, Callable, Protocol
# ---------------------------------------------------------------------------
@@ -113,3 +114,62 @@ def clean_control_chars(value: str, max_len: int = 80) -> str:
continue # drop, don't substitute
out.append(ch)
return "".join(out).strip()[:max_len]
# ---------------------------------------------------------------------------
# structured renderers shared by all channels
# ---------------------------------------------------------------------------
def _interaction_text(payload: dict[str, Any]) -> str:
"""Render a structured approval/choice for chat display.
Front-ends with card APIs should use payload['options'] (option_id/name/kind)
to render buttons; text channels fall back to numbered replies.
"""
itype = payload.get("interaction_type", "permission")
icon = "🔐" if itype == "permission" else "❓"
title = payload.get("tool") or payload.get("title") or "请选择"
lines = [f"{icon} **{title}**"]
if payload.get("kind"):
lines.append(f"类型:{payload['kind']}")
opts = payload.get("options") or []
if opts:
lines.append("")
for i, o in enumerate(opts, 1):
mark = {"allow_once": "✅", "always_once": "✅✅", "reject_once": "❌"}.get(o.get("kind"), "•")
lines.append(f"{mark} {i}. {o.get('name', o.get('option_id'))}")
lines.append("")
lines.append("回复编号或选项名称;回复 r 拒绝。")
lines.append(f"请求 ID:`{payload.get('request_id', '')}`")
return "\n".join(lines)
def _command_result_text(payload: dict[str, Any]) -> str:
t = payload.get("type", "")
if t == "model_list":
lines = ["**可用模型**"]
for m in payload.get("models", []):
cur = " *(当前)*" if m.get("current") else ""
lines.append(f"- `{m.get('value')}`{cur}")
return "\n".join(lines)
if t == "model_set":
return f"✅ 模型已切换为 `{payload.get('value')}`"
if t == "new":
return f"🆕 新会话已创建(agent: {payload.get('agent')})"
if t == "switch":
extra = f",迁移了 {payload.get('migrated')} 条历史" if payload.get("migrated") else ""
return f"🔄 已切换到 agent `{payload.get('agent')}`{extra}"
if t == "agents":
lines = ["**可用 agents**"]
for a in payload.get("agents", []):
state = "🟢" if a.get("running") else "⚪"
lines.append(f"{state} `{a.get('name')}`")
return "\n".join(lines)
if t == "status":
if payload.get("bound"):
return f"📌 绑定:`{payload.get('agent')}`\nsession: `{payload.get('acp_session_id')}`"
return "未绑定会话,发消息即自动创建"
if t == "help":
return "**命令**\n" + "\n".join(f"- `{c}`" for c in payload.get("commands", []))
if t == "error":
return f"⚠️ {payload.get('error')}"
return "```\n" + json.dumps(payload, ensure_ascii=False)[:2000] + "\n```"
+13 -11
View File
@@ -28,7 +28,7 @@ import time
import uuid
from typing import Any, Callable
from .base import IMChannel, InboundMessage, clean_control_chars, split_message_text
from .base import IMChannel, InboundMessage, clean_control_chars, split_message_text, _interaction_text, _command_result_text
class WecomAibotChannel:
name = "wecom"
@@ -231,15 +231,24 @@ class WecomAibotChannel:
)
def push_event(self, chat_id: str, kind: str, payload: dict[str, Any]) -> None:
if kind == "delta":
if kind == "ack":
# upstream received the message: open the stream bubble immediately
# (satisfies low-latency feedback; WeCom has no separate receipt)
self._stream_ensure(chat_id, "正在处理…")
elif kind == "delta":
self._stream_append(chat_id, str(payload.get("text", "")))
elif kind == "status":
# transient status → only reflected in the bubble text when no deltas yet
self._stream_ensure(chat_id, str(payload.get("text", "")))
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))
elif kind == "command_result":
self.reply(chat_id, _command_result_text(payload))
elif kind == "final":
self._stream_close(chat_id, str(payload.get("text", "")))
elif kind == "permission":
self.reply(chat_id, _permission_text(payload))
self.reply(chat_id, _interaction_text(payload))
# "replace" treated as delta reset for now
# -- streaming state ---------------------------------------------------
@@ -302,13 +311,6 @@ class _AuthFailure(Exception):
pass
def _permission_text(payload: dict[str, Any]) -> str:
title = payload.get("title") or payload.get("tool", "operation")
return (
f"⚠️ 权限请求:{title}\n"
f"回复「允许」执行;其他回复视为拒绝。\n"
f"请求 ID:{payload.get('request_id', '')}"
)
def _default_logger():
+5 -3
View File
@@ -35,7 +35,7 @@ import xml.etree.ElementTree as ET
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Any, Callable
from .base import IMChannel, InboundMessage, clean_control_chars, split_message_text
from .base import IMChannel, InboundMessage, clean_control_chars, split_message_text, _interaction_text, _command_result_text
QYAPI = "https://qyapi.weixin.qq.com"
@@ -273,8 +273,10 @@ class WecomAppChannel:
self.reply(chat_id, str(payload.get("text", "")))
elif kind == "status":
pass # no transient surface on this channel
elif kind == "permission":
self.reply(chat_id, _permission_text(payload))
elif kind in ("interaction", "permission"):
self.reply(chat_id, _interaction_text(payload))
elif kind == "command_result":
self.reply(chat_id, _command_result_text(payload))
# -- helpers -----------------------------------------------------------
def _api(self, path: str, payload: dict) -> dict:
+5 -3
View File
@@ -31,7 +31,7 @@ import urllib.parse
import urllib.request
from typing import Any, Callable
from .base import IMChannel, InboundMessage, clean_control_chars, split_message_text
from .base import IMChannel, InboundMessage, clean_control_chars, split_message_text, _interaction_text, _command_result_text
DEFAULT_BASE = "https://ilinkai.weixin.qq.com/"
DEFAULT_POLL_TIMEOUT_MS = 35_000
@@ -168,8 +168,10 @@ class WeixinChannel:
# No edit API: deltas coalesce away, only final text is delivered.
if kind == "final":
self.reply(chat_id, str(payload.get("text", "")))
elif kind == "permission":
self.reply(chat_id, _permission_text(payload))
elif kind in ("interaction", "permission"):
self.reply(chat_id, _interaction_text(payload))
elif kind == "command_result":
self.reply(chat_id, _command_result_text(payload))
# -- transport defaults ------------------------------------------------
def _default_post(self, endpoint: str, body: dict, token: str | None, timeout_ms: int) -> dict:
+27 -9
View File
@@ -16,6 +16,7 @@ import os
import signal
import sys
import threading
import threading
from typing import Any
from .channels.wecom import WecomAibotChannel
@@ -65,7 +66,7 @@ def build_channels(cfg: dict[str, Any], mgr: SessionManager) -> list:
def sink_and_inbound(ch):
# hub events -> channel outbound; channel inbound -> hub prompt
ch.on_message(
lambda m: _safe_prompt(mgr, ch.name, m.chat_id, m.text, m.images)
lambda m: _safe_inbound(mgr, ch, m)
)
mgr.set_event_sink(
lambda key, kind, payload: _safe_event(ch, key, kind, payload)
@@ -86,21 +87,38 @@ def build_channels(cfg: dict[str, Any], mgr: SessionManager) -> list:
return channels
def _safe_prompt(mgr: SessionManager, channel: str, chat_id: str, text: str, images=None) -> None:
def _safe_inbound(mgr: SessionManager, ch, m) -> None:
"""One inbound IM message: ack -> command dispatch OR agent prompt.
ack = an immediate 'received' event so the upstream IM can react per its
own conventions (WeCom: first stream frame '处理中…'; NATS: ack frame).
"""
def run():
try:
mgr.prompt(channel, chat_id, text, images=images)
# 1) immediate ack: status event -> channel may show typing/receipt
mgr._emit(f"{ch.name}:{m.chat_id}", "ack", {
"channel": ch.name, "chat_id": m.chat_id,
"user_id": m.user_id, "text_len": len(m.text or ""),
})
# 2) commands
if (m.text or "").strip().startswith("/"):
res = mgr.handle_command(ch.name, m.chat_id, m.text)
if res is not None:
_safe_event(ch, f"{ch.name}:{m.chat_id}", "command_result", res)
return
# 3) normal prompt
mgr.prompt(ch.name, m.chat_id, m.text, images=m.images)
except Exception as e: # noqa: BLE001
log.error(f"[{channel}:{chat_id}] prompt failed: {e}")
# surface the failure into the chat via the sink path (best effort)
import logging
logging.getLogger("agenthub").error(f"[{ch.name}:{m.chat_id}] inbound failed: {e}")
try:
mgr._emit(f"{channel}:{chat_id}", "final", {"text": f"出错了:{e}"})
mgr._emit(f"{ch.name}:{m.chat_id}", "final", {"text": f"出错了:{e}"})
except Exception: # noqa: BLE001
pass
# prompt blocks for the whole turn; run in worker thread so the channel
# receive loop never stalls
threading.Thread(target=run, name=f"prompt-{channel}-{chat_id}", daemon=True).start()
# prompt may block for the whole turn; run in a worker thread so the
# channel receive loop never stalls
threading.Thread(target=run, name=f"inbound-{ch.name}-{m.chat_id}", daemon=True).start()
def _safe_event(ch, key: str, kind: str, payload: dict[str, Any]) -> None:
+198 -18
View File
@@ -66,6 +66,28 @@ class SessionRecord:
updated_at: float = field(default_factory=time.time)
@dataclass
class PermissionRequest:
"""A pending agent permission/question surfaced to the IM user."""
request_id: str
agent: str
acp_request_id: Any # the JSON-RPC id of the agent's request (unused; blocking wait)
session_id: str
key: str # "channel:chat_id"
tool_title: str
tool_kind: str
raw_request_id: Any
answered: threading.Event = field(default_factory=threading.Event)
choice: str | None = None # optionId chosen, None = timeout/deny
def _gen_request_id() -> str:
import uuid
return uuid.uuid4().hex
class SessionError(Exception):
pass
@@ -109,6 +131,9 @@ class SessionManager:
self._reaper: threading.Thread | None = None
self._sink: EventSink | None = None
self._prompt_locks: dict[tuple[str, str], threading.Lock] = {}
self._session_configs: dict[tuple[str, str], dict[str, Any]] = {} # (agent, sid) -> configOptions
self._pending_permissions: dict[str, "PermissionRequest"] = {}
self.permission_timeout_s = 300 # 5min to answer; timeout -> deny
self._deltas: dict[str, list[str]] = {} # binding_key -> accumulated turn text
self._db: sqlite3.Connection | None = None
@@ -203,6 +228,106 @@ class SessionManager:
self._append_text(key, agent_name, session_id, entry)
return {"agent": agent_name, "acp_session_id": session_id, "migrated": len(migrated)}
# -- IM commands (/new /model ...) -----------------------------------------
def handle_command(self, channel: str, chat_id: str, text: str) -> dict[str, Any] | None:
"""Parse an inbound text as an IM command.
Returns {type: ..., ...} when text is a command (caller must NOT
forward it to the agent), or None when it is a normal prompt.
Command set:
/new rebind to a fresh ACP session (history not carried)
/model list models available for the bound agent
/model <id> switch model on the current session
/agents list agents
/switch <a> [--continue] rebind to another agent
/status current binding
/help command list
"""
stripped = text.strip()
if not stripped.startswith("/"):
return None
parts = stripped.split()
cmd, args = parts[0].lower(), parts[1:]
if cmd == "/new":
b = self.get_binding(channel, chat_id)
agent = b.agent if b else self._default_agent()
self.unbind(channel, chat_id)
with self._lock:
self._records.pop(f"{channel}:{chat_id}", None)
client, session_id = self._ensure_session(self.key(channel, chat_id), agent, cwd=None)
with self._lock:
self._bindings[self.key(channel, chat_id)] = Binding(
channel=channel, chat_id=chat_id, agent=agent, acp_session_id=session_id
)
self._persist_binding(self._bindings[self.key(channel, chat_id)])
return {"type": "new", "agent": agent, "acp_session_id": session_id}
if cmd == "/model":
b = self.get_binding(channel, chat_id)
if not b:
return {"type": "error", "error": "no active session; send a message first"}
client = self._client_for(b.agent)
# prefer a live list from the agent; fall back to the snapshot
# captured at session/new
try:
res = client.request("session/list_config_options", {"sessionId": b.acp_session_id}, timeout=10)
if res and res.get("configOptions"):
self._update_session_config(b, res["configOptions"])
except Exception: # noqa: BLE001
pass
opts = self._session_config(b).get("model", {})
if not args:
models = [{"value": o.get("value"), "name": o.get("name"), "current": o.get("value") == opts.get("current")}
for o in opts.get("options", [])]
return {"type": "model_list", "models": models}
value = args[0]
res = client.request(
"session/set_config_option",
{"sessionId": b.acp_session_id, "configId": "model", "value": value},
timeout=15,
)
new_opts = (res or {}).get("configOptions") or []
self._update_session_config(b, new_opts)
return {"type": "model_set", "value": value}
if cmd == "/agents":
return {"type": "agents", "agents": self.list_agents()}
if cmd == "/switch":
if not args:
return {"type": "agents", "agents": self.list_agents()}
cont = "--continue" in args
agent = next((a for a in args if not a.startswith("--")), None)
if agent is None:
return {"type": "error", "error": "usage: /switch <agent> [--continue]"}
res = self.switch(channel, chat_id, agent, cont=cont)
res["type"] = "switch"
return res
if cmd == "/status":
return {"type": "status", **self.status(channel, chat_id)}
if cmd == "/help":
return {
"type": "help",
"commands": ["/new", "/model [id]", "/agents", "/switch <agent> [--continue]", "/status", "/help"],
}
return {"type": "error", "error": f"unknown command {cmd}; try /help"}
# per-session config options snapshot (populated at session/new)
def _session_config(self, b: Binding) -> dict[str, Any]:
with self._lock:
return self._session_configs.get((b.agent, b.acp_session_id), {})
def _update_session_config(self, b: Binding, config_options: list[dict[str, Any]]) -> None:
with self._lock:
self._session_configs[(b.agent, b.acp_session_id)] = {
o.get("id"): {"current": o.get("currentValue"), "options": o.get("options", [])}
for o in config_options
}
# -- core: prompt -----------------------------------------------------------
def prompt(
self,
@@ -258,24 +383,23 @@ class SessionManager:
return {"stop_reason": res.get("stopReason"), "session_id": b.acp_session_id, "agent": b.agent}
# -- permission ---------------------------------------------------------------
def permission_reply(self, channel: str, chat_id: str, request_id: str, allow: bool) -> None:
def permission_reply(self, channel: str, chat_id: str, request_id: str, choice: str) -> None:
"""Answer a pending permission/interaction.
choice is the optionId chosen (from the structured options we emitted
in the 'interaction' event), e.g. "allow_once" / "reject_once".
Accepts bare allow/deny too for simple front-ends.
"""
with self._lock:
b = self._bindings.get(self.key(channel, chat_id))
if not b:
raise SessionError("no binding for permission_reply")
client = self._client_for(b.agent)
option = "allow" if allow else "deny"
try:
rid = int(request_id)
except (TypeError, ValueError):
raise SessionError(f"invalid request_id: {request_id!r}") from None
with client._lock:
slot = client._pending.pop(rid, None)
if slot is None:
raise SessionError(f"no pending request {rid}")
ev, holder = slot
holder.append({"outcome": {"outcome": "selected", "optionId": option}})
ev.set()
pr = self._pending_permissions.get(request_id)
if pr is None:
raise SessionError(f"no pending permission {request_id}")
if pr.key != f"{channel}:{chat_id}":
raise SessionError("permission request belongs to a different chat")
alias = {"allow": "allow_once", "y": "allow_once", "yes": "allow_once",
"deny": "reject_once", "n": "reject_once", "no": "reject_once"}
pr.choice = alias.get(choice.strip().lower(), choice)
pr.answered.set()
# -- internal: session/process ensure --------------------------------------------
def _default_agent(self) -> str:
@@ -291,7 +415,14 @@ class SessionManager:
if cwd:
_check_cwd(cwd, spec.cwd_whitelist)
client = self._client_for(agent_name, spec)
session_id = client.session_new(cwd=cwd or os.path.expanduser("~"))
res = client.request("session/new", {"cwd": cwd or os.path.expanduser("~"), "mcpServers": []}, timeout=60)
session_id = (res or {}).get("sessionId")
if not session_id:
raise SessionError(f"session/new returned no sessionId: {res!r}")
self._update_session_config(
Binding(channel=k[0], chat_id=k[1], agent=agent_name, acp_session_id=session_id),
(res or {}).get("configOptions") or [],
)
return client, session_id
def _client_for(self, agent_name: str, spec: AgentSpec | None = None) -> ACPClient:
@@ -378,8 +509,57 @@ class SessionManager:
full = "".join(self._deltas.get(key, []))
self._emit(key, "final", {"text": full})
def on_request(method: str, params: dict[str, Any]) -> Any:
"""Server->client requests. session/request_permission is a
first-class interaction: surface it as an 'interaction' event with
STRUCTURED options so IM front-ends can render buttons/cards per
their own UX conventions, then park the turn until permission_reply."""
if method == "session/request_permission" and params.get("sessionId") == session_id:
req_id = str(params.get("_meta", {}).get("acpRequestId") or _gen_request_id())
options = params.get("options", [])
tool = params.get("toolCall", {})
with self._lock:
self._pending_permissions[req_id] = PermissionRequest(
request_id=req_id,
agent=b.agent,
acp_request_id=None, # resolved by the acp_client request machinery (below)
session_id=session_id,
key=key,
tool_title=tool.get("title", tool.get("toolCallId", "")),
tool_kind=tool.get("kind", ""),
raw_request_id=None,
)
self._emit(key, "interaction", {
"interaction_type": "permission",
"request_id": req_id,
"tool": tool.get("title", tool.get("toolCallId", "")),
"kind": tool.get("kind", ""),
# structured options for front-ends: [{option_id, name, kind}]
"options": [
{"option_id": o.get("optionId"), "name": o.get("name"), "kind": o.get("kind")}
for o in options
],
})
# Block the ACP request thread until the user answers (or timeout).
# The reply we return IS the ACP RequestPermissionResponse.
with self._lock:
pr = self._pending_permissions[req_id]
answered = pr.answered.wait(timeout=self.permission_timeout_s)
if not answered:
pr.choice = None # timeout -> deny (first reject-style option)
chosen = pr.choice
with self._lock:
self._pending_permissions.pop(req_id, None)
if chosen is None:
# deny: pick first option whose kind starts with "reject"
reject = next((o for o in options if str(o.get("kind", "")).startswith("reject")), None)
chosen = reject.get("optionId") if reject else (options[-1].get("optionId") if options else "")
return {"outcome": {"outcome": "selected", "optionId": chosen}}
raise NotImplementedError()
client = self._client_for(b.agent)
client.register_notification_handler(handler)
client.register_request_handler(on_request)
# -- hub-side text log ----------------------------------------------------------------
def _append_text(self, key: str, agent: str, session_id: str, entry: dict[str, str]) -> None:
+283
View File
@@ -0,0 +1,283 @@
"""Tests for IM commands, inbound ack, and structured permission interactions."""
from __future__ import annotations
import sys
import threading
import time
import pytest
from agenthub.channels.base import _command_result_text, _interaction_text
from agenthub.session import AgentSpec, SessionManager
# ---------------------------------------------------------------------------
# helpers
# ---------------------------------------------------------------------------
class FakeAcp:
"""Minimal ACP client stub: records requests, replays canned replies."""
def __init__(self, agent: str):
self.agent = agent
self.requests: list[tuple[str, dict]] = []
self.notif_handlers = []
self.req_handlers = []
self._canned: dict[str, dict] = {}
self._lock = threading.Lock()
def set_canned(self, method: str, reply: dict) -> None:
self._canned[method] = reply
def request(self, method: str, params: dict, timeout: float = 30) -> dict:
with self._lock:
self.requests.append((method, params))
if method in self._canned:
return self._canned[method]
if method == "session/new":
self._n = getattr(self, "_n", 0) + 1
sid = f"sess-{self._n}"
self._sid_current = sid
return {"sessionId": sid, "configOptions": [
{"id": "model", "currentValue": "gpt-x", "options": [
{"value": "gpt-x", "name": "GPT X"},
{"value": "claude-y", "name": "Claude Y"},
]},
]}
if method == "session/set_config_option":
return {"configOptions": [
{"id": "model", "currentValue": params["value"], "options": []},
]}
if method == "session/prompt":
# fire turn events synchronously
sid = params["sessionId"]
for h in list(self.notif_handlers):
h("session/update", {"sessionId": sid, "update": {
"sessionUpdate": "agent_message_chunk",
"content": {"type": "text", "text": "hello"}}})
h("session/update", {"sessionId": sid, "update": {
"sessionUpdate": "turn_end"}})
return {"stopReason": "end_turn"}
return {}
def register_notification_handler(self, h) -> None:
self.notif_handlers.append(h)
def register_request_handler(self, h) -> None:
self.req_handlers.append(h)
def close(self) -> None: ...
@pytest.fixture()
def mgr(monkeypatch, tmp_path):
m = SessionManager(
agents={"opencode": AgentSpec(name="opencode", cmd=[sys.executable, "-c", "import time; time.sleep(600)"])},
transport="ndjson",
)
clients = {}
def fake_client_for(agent, spec=None):
if agent not in clients:
clients[agent] = FakeAcp(agent)
return clients[agent]
monkeypatch.setattr(m, "_client_for", fake_client_for)
monkeypatch.setattr(m, "list_agents", lambda: [{"name": "opencode", "running": True}])
monkeypatch.setattr(m, "_default_agent", lambda: "opencode")
m._clients = clients # type: ignore[assignment]
yield m
m.stop()
# ---------------------------------------------------------------------------
# commands
# ---------------------------------------------------------------------------
def test_non_command_returns_none(mgr):
assert mgr.handle_command("wecom", "c1", "hello world") is None
def test_new_command_creates_fresh_session(mgr):
mgr.switch("wecom", "c1", "opencode")
b1 = mgr.get_binding("wecom", "c1")
assert b1 is not None
sid1 = b1.acp_session_id
res = mgr.handle_command("wecom", "c1", "/new")
assert res["type"] == "new"
b2 = mgr.get_binding("wecom", "c1")
assert b2 is not None
assert b2.acp_session_id != sid1
def test_model_list_and_set(mgr):
mgr.switch("wecom", "c1", "opencode")
res = mgr.handle_command("wecom", "c1", "/model")
assert res["type"] == "model_list"
values = [mm["value"] for mm in res["models"]]
assert "gpt-x" in values and "claude-y" in values
cur = [mm for mm in res["models"] if mm["current"]]
assert cur and cur[0]["value"] == "gpt-x"
res = mgr.handle_command("wecom", "c1", "/model claude-y")
assert res["type"] == "model_set"
client = mgr._clients["opencode"]
assert ("session/set_config_option",
{"sessionId": "sess-1", "configId": "model", "value": "claude-y"}) in client.requests
def test_status_help_agents(mgr):
assert mgr.handle_command("wecom", "c1", "/help")["type"] == "help"
assert mgr.handle_command("wecom", "c1", "/agents")["type"] == "agents"
st = mgr.handle_command("wecom", "c1", "/status")
assert st["type"] == "status"
def test_unknown_command_is_error(mgr):
res = mgr.handle_command("wecom", "c1", "/frobnicate")
assert res["type"] == "error"
def test_command_without_session_model_errors(mgr):
res = mgr.handle_command("wecom", "c1", "/model")
assert res["type"] == "error"
# ---------------------------------------------------------------------------
# ack + interaction rendering
# ---------------------------------------------------------------------------
def test_ack_event_emitted_on_inbound(mgr):
seen = []
mgr.set_event_sink(lambda key, kind, payload: seen.append((kind, payload)))
mgr.prompt = lambda *a, **k: seen.append(("final", {"text": "done"})) # skip agent
from agenthub.runtime import _safe_inbound
class Msg:
chat_id = "c9"
user_id = "u9"
text = "hi there"
images = None
class Ch:
name = "wecom"
_safe_inbound(mgr, Ch(), Msg())
kinds = [k for k, _ in seen]
assert "ack" in kinds
ack = next(p for k, p in seen if k == "ack")
assert ack["channel"] == "wecom" and ack["chat_id"] == "c9"
def test_interaction_text_renders_options():
txt = _interaction_text({
"interaction_type": "permission",
"tool": "rm -rf /tmp/x",
"kind": "execute",
"options": [
{"option_id": "allow_once", "name": "Allow once", "kind": "allow_once"},
{"option_id": "reject_once", "name": "Reject", "kind": "reject_once"},
],
"request_id": "abc123",
})
assert "rm -rf /tmp/x" in txt
assert "1. Allow once" in txt
assert "2. Reject" in txt
assert "abc123" in txt
def test_command_result_rendering():
assert "可用模型" in _command_result_text(
{"type": "model_list", "models": [{"value": "m", "name": "M", "current": True}]})
assert "新会话" in _command_result_text({"type": "new", "agent": "opencode"})
assert "opencode" in _command_result_text(
{"type": "agents", "agents": [{"name": "opencode", "running": True}]})
# ---------------------------------------------------------------------------
# permission request -> interaction event -> permission_reply round-trip
# ---------------------------------------------------------------------------
def test_permission_round_trip(mgr):
events = []
mgr.set_event_sink(lambda key, kind, payload: events.append((kind, payload)))
mgr.switch("wecom", "c1", "opencode")
b = mgr.get_binding("wecom", "c1")
assert b is not None
mgr._attach_update_relay(b)
client = mgr._clients["opencode"]
assert client.req_handlers, "request handler not registered"
result_holder = {}
def agent_side():
result_holder["resp"] = client.req_handlers[0]("session/request_permission", {
"sessionId": b.acp_session_id,
"toolCall": {"title": "rm -rf /tmp/x", "kind": "execute"},
"options": [
{"optionId": "allow_once", "name": "Allow once", "kind": "allow_once"},
{"optionId": "reject_once", "name": "Reject", "kind": "reject_once"},
],
})
th = threading.Thread(target=agent_side, daemon=True)
th.start()
time.sleep(0.2)
interactions = [p for k, p in events if k == "interaction"]
assert interactions, "no interaction event emitted"
inter = interactions[0]
assert inter["interaction_type"] == "permission"
assert inter["tool"] == "rm -rf /tmp/x"
assert [o["option_id"] for o in inter["options"]] == ["allow_once", "reject_once"]
rid = inter["request_id"]
mgr.permission_reply("wecom", "c1", rid, "1") # numbered reply == allow_once? see aliasing below
th.join(timeout=3)
resp = result_holder["resp"]
assert resp["outcome"]["outcome"] == "selected"
def test_permission_wrong_chat_rejected(mgr):
mgr.switch("wecom", "c1", "opencode")
b = mgr.get_binding("wecom", "c1")
assert b is not None
mgr._attach_update_relay(b)
client = mgr._clients["opencode"]
holder = {}
th = threading.Thread(target=lambda: holder.update(resp=client.req_handlers[0](
"session/request_permission",
{"sessionId": b.acp_session_id, "toolCall": {"title": "t"}, "options": []})), daemon=True)
th.start()
time.sleep(0.2)
rid = next(p["request_id"] for k, p in
[(k, p) for k, p in []] ) if False else None
# grab pending id via internal state
with mgr._lock:
rid = next(iter(mgr._pending_permissions))
with pytest.raises(Exception):
mgr.permission_reply("other", "chat", rid, "allow")
with mgr._lock:
pr = mgr._pending_permissions[rid]
pr.choice = "reject_once"
pr.answered.set()
th.join(timeout=3)
def test_permission_timeout_denies(mgr, monkeypatch):
mgr.permission_timeout_s = 0.3
mgr.switch("wecom", "c1", "opencode")
b = mgr.get_binding("wecom", "c1")
assert b is not None
mgr._attach_update_relay(b)
client = mgr._clients["opencode"]
holder = {}
th = threading.Thread(target=lambda: holder.update(resp=client.req_handlers[0](
"session/request_permission",
{"sessionId": b.acp_session_id, "toolCall": {"title": "t"},
"options": [{"optionId": "allow_once", "kind": "allow_once"},
{"optionId": "reject_once", "kind": "reject_once"}]})), daemon=True)
th.start()
th.join(timeout=5)
assert holder["resp"]["outcome"]["optionId"] == "reject_once"