diff --git a/core/openmate_core/agent.py b/core/openmate_core/agent.py index eda7761..27c6b5b 100644 --- a/core/openmate_core/agent.py +++ b/core/openmate_core/agent.py @@ -7,8 +7,11 @@ and answers with _agent_reply, bound to this request by its id. A request in the thread of an earlier one goes on in that conversation. If the turn ends without a reply through the tool, the latest answer is posted once instead (never both). A turn ends at its turn_duration item; Claude Code does not always write one, so a session that -answered and then stayed quiet for `agent_settle` has ended its turn too when its status says done or idle. /stop, /停止 or /停 in the thread (or quoting the request) stops it. Runs are kept in the store, -so a restart goes on waiting for the running ones. +answered and then stayed quiet for `agent_settle` has ended its turn too when its status says done or idle. A turn that +ends while a card the request raised waits for the owner (a command held for approval: Persona tells the tool call to +end the turn, and the card's outcome later starts the next one) answers nothing: nothing is posted, the one reply stays +free, and the turn after the outcome answers as usual (_card_waits). /stop, /停止 or /停 in the thread (or quoting the +request) stops it. Runs are kept in the store, so a restart goes on waiting for the running ones. A follow-up in a thread whose conversation handed its work to a task (a to-do it opened, still open, with an Agent on it) goes straight to that Agent (`agent_forward`, on by default): the thread is told it was handed on, and the task's @@ -50,6 +53,7 @@ from .wire import RPCError START_REPLAY_MOST = 25 * 86400.0 # a start older than this is not asked again (the hub keeps receipts 30 days) +CARD_SKEW = 30.0 # a card raised this long before its request (the hub's clock against this one's) is still the request's CHECK = "请先在 Persona 里看看有没有新开的会话;没有的话再重新发送。" log = logging.getLogger("openmate.agent") @@ -384,6 +388,7 @@ def __init__(self, app): self._own: Dict[tuple, List[float]] = {} # a tool's formatted sends (own_send): their echoes are none either self._own_gen = 0 # one more at each forget: a send's end from the account before is none of the next one's self._asked: Dict[str, float] = {} # run id → when its session's status was last asked + self._held_read: Dict[str, float] = {} # run id → when the conversation of a run held for a card was last read self._handing: Dict[str, tuple] = {} # run id → (chat, thread, asked at) of a follow-up being handed to an Agent self._handed = threading.Condition(self._mu) @@ -2772,9 +2777,23 @@ def _transcript(self, mid: str, sid: str, after: int, deadline: Optional[float] return items, after def _poll(self, run: dict) -> None: + t = self.app.timing + now = time.time() send_until = run.get("send_wait_until") or 0 - if not send_until and time.time() - (run.get("reconciled_at") or run["created"]) > self.app.timing.agent_timeout: - self._timeout(run["id"]) + held = float(run.get("card_hold") or 0) # its turn ended on a card that waits for the owner (_turn_ended) + if held: + if now - held > t.agent_approval_wait: + self._timeout(run["id"]) + return + with self._mu: + if now - self._held_read.get(run["id"], 0.0) < t.agent_hold_poll: + return # nothing goes on before the card's outcome starts the next turn: read now and then + self._held_read[run["id"]] = now + for k in [k for k, at in self._held_read.items() if now - at > 3600]: + del self._held_read[k] + elif not send_until and now - max(float(run.get("reconciled_at") or run["created"]), + float(run.get("card_resumed") or 0)) > t.agent_timeout: + self._timeout(run["id"]) # (the turn after a card's outcome has its own agent_timeout) return mid, sid = run["machine_id"], run["session_id"] try: @@ -2803,8 +2822,17 @@ def _poll(self, run: dict) -> None: log.info("/agent send reconciliation %s: found", cur["id"]) continue kind, role = it.get("kind") or "", it.get("role") or "" + if cur.pop("card_unsure", None): + # the conversation went on before the hub said whether a card waited when that turn ended + # (a card's outcome, say): its words are not posted; the turn now under way ends as usual + cur.pop("card_unsure_since", None) + last_text = None + log.info("/agent %s: the conversation went on while its turn's end was put off", cur["id"]) if role == "assistant": answered = True + if cur.get("card_hold"): # the next turn (the card's outcome came): its end is the answer's + cur["card_hold"], cur["card_resumed"] = 0, time.time() + log.info("/agent %s: the conversation goes on after the card it waited on", cur["id"]) if role == "assistant" and kind == "text" and (it.get("text") or "").strip(): last_text = {"id": it.get("id") or "", "text": it.get("text") or "", "full": int(it.get("full_size") or 0)} elif kind == "turn_duration" or it.get("turn_duration"): @@ -2822,6 +2850,8 @@ def _poll(self, run: dict) -> None: if send_until and not run.get("ours_seen") and time.time() >= send_until: self._send_unseen(run) return + if not ended and not interrupted and run.get("card_unsure"): + ended = True # its turn ended when the hub could not say whether a card waits there: asked again if not ended and not interrupted and self._settled(run): ended = True if interrupted: @@ -2945,14 +2975,80 @@ def _end_awaiting(self, run_id: str, outcome: str = "done") -> None: cur["awaiting"] = "" self.store.run_put(cur) + @staticmethod + def _unanswered(run: dict) -> bool: + """Nothing answered the request yet: its turn's end would post the turn's last words as the answer.""" + return run.get("kind") not in QUIET_KINDS and not int(run.get("replies") or 0) \ + and not int(run.get("reply_inflight") or 0) and not run.get("fallback") + + def _card_waits(self, run: dict, last: bool = False) -> Optional[bool]: + """Whether a card raised for this request in its conversation still waits for the owner; None when the hub + cannot say now. Such a card is a command Persona holds for the owner's approval (or a question): when nobody + answered it in time, Persona gives the tool call a non-final result ("The owner has not answered this approval + yet … End this turn now … A later message will report its outcome"), keeps the card waiting (24 h) and tells + the conversation its outcome in a later message, which starts the next turn. So a turn that ends meanwhile has + no answer in its last words. The session's row counts the cards waiting there (pending_interactions); the cards + the hub shows say whether one was raised since this request was asked (an earlier request's card still waiting + is not this one's). One the hub does not show extensions (a private card) may be this one's: it counts. + last: the hub could not say for agent_hub_wait already; a read that fails now is taken as its answer was.""" + mid, sid = run.get("machine_id") or "", run.get("session_id") or "" + if not (mid and sid and self.hub.available): + return False + try: + row = self.hub.session_row(mid, sid) or {} + except HubError as e: + return self._card_unknown(e, False, last) # no row: as before, the last words are the answer + n = int(row.get("pending_interactions") or 0) + if n <= 0 and row.get("state") != "needs_you": + return False + try: + cards = [i for i in self.hub.pending_interactions() + if i.get("machine_id") == mid and i.get("session_id") == sid] + except HubError as e: + return self._card_unknown(e, n > 0, last) # a card waits there, whose cannot be told + since = float(run.get("created") or 0) - CARD_SKEW + if any(not hub_time(i.get("created_at")) or hub_time(i.get("created_at")) >= since for i in cards): + return True # (one with no time known: taken as this request's) + return len(cards) < n + + @staticmethod + def _card_unknown(e: HubError, refused: bool, last: bool) -> Optional[bool]: + """_card_waits when a read failed: asked again at the next read (None), unless the hub refuses it for good + (403, 404: no such route or scope) or could not say for agent_hub_wait already (last): then `refused`.""" + log.info("/agent: whether a card waits in the conversation could not be read (%s)", e.code or e.status) + return refused if last or e.status in (403, 404) else None + def _turn_ended(self, run_id: str) -> None: first = self.store.run_get(run_id) # (the hub asked before the run's lock is taken: its answer may take a while) - tasks = self._open_tasks(first) if first is not None and self._may_await(first) else "none" + card: Optional[bool] = False + if first is not None and self._unanswered(first): # a card waiting comes first: the run is not over + unsure = float(first.get("card_unsure_since") or 0) + card = self._card_waits(first, bool(unsure) and time.time() - unsure > self.app.timing.agent_hub_wait) + tasks = self._open_tasks(first) if card is False and first is not None and self._may_await(first) else "none" with self._lock(run_id): cur = self.store.run_get(run_id) if cur is None or cur["state"] != "running": return + if card is not False and self._unanswered(cur): + if card is None: + # whether its last words are an answer cannot be told now: nothing is posted, asked again (at + # most agent_hub_wait), unless the conversation goes on meanwhile (_poll) + cur["card_unsure"] = True + cur.setdefault("card_unsure_since", time.time()) + else: + # a card it raised waits for the owner: its last words only say so. Nothing is posted and nothing + # takes the one reply; the turn after the card's outcome (approved, denied, expired) answers it, + # through the tool or its last words, as usual. Its 🤔 stays meanwhile + cur.pop("card_unsure", None) + cur.pop("card_unsure_since", None) + cur["card_hold"], cur["answered"], cur["last_text"] = time.time(), False, None + log.info("/agent %s: the turn ended while a card it raised waits for the owner: no answer yet", + run_id) + self.store.run_put(cur) + return + cur.pop("card_unsure", None) + cur.pop("card_unsure_since", None) post = None awaiting = tasks != "none" and self._may_await(cur) if awaiting: @@ -3044,8 +3140,11 @@ def _timeout(self, run_id: str) -> None: self.store.run_put(cur) self._end_reaction(run_id, "failed") if notice: + t = self.app.timing + waited = ("要你处理的卡片等了 %s" % _span(t.agent_approval_wait)) if cur.get("card_hold") \ + else ("等了 %s" % _span(t.agent_timeout)) mid = self._post_once(cur, "agent:%s:timeout" % run_id, - "等了 %s 还没有结果,不再等待。可以在 Persona 里打开这个会话看进度。" % _span(self.app.timing.agent_timeout), + "%s还没有结果,不再等待。可以在 Persona 里打开这个会话看进度。" % waited, **self._where(cur)) with self._lock(run_id): cur = self.store.run_get(run_id) diff --git a/core/openmate_core/platform.py b/core/openmate_core/platform.py index ddd8f1a..5465659 100644 --- a/core/openmate_core/platform.py +++ b/core/openmate_core/platform.py @@ -161,4 +161,8 @@ class Timing: agent_task_wait_most: float = 86400.0 # a request waiting on its to-dos (agent_task_wait) times out this late… agent_task_recheck: float = 60.0 # …and asks the hub about them at most this often mute_batch: int = 10 # …at most this many groups per round, in the background (an Inbox read never waits for it) + # A request whose turn ended while a card it raised waits for the owner (Persona's approval cards stay 24 h after + # the tool call gave up waiting, then say they expired) waits this long for the turn after the card's outcome… + agent_approval_wait: float = 25 * 3600.0 + agent_hold_poll: float = 30.0 # …and its conversation is read this often meanwhile extra: Dict[str, float] = field(default_factory=dict) diff --git a/extensions/openmate-feishu/persona-extension.json b/extensions/openmate-feishu/persona-extension.json index d8078e2..1d36702 100644 --- a/extensions/openmate-feishu/persona-extension.json +++ b/extensions/openmate-feishu/persona-extension.json @@ -2,7 +2,7 @@ "manifest_version": 1, "id": "openmate-feishu", "name": "飞书(OpenMate)", - "version": "0.11.81", + "version": "0.11.82", "description": "把飞书私聊和群消息接进 Persona 的收件箱和知识库,通过确认卡片以你的身份发消息,支持 /agent。通过你自己安装的 LarkAgentX(非官方网页协议)连接,与飞书官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", diff --git a/extensions/openmate-wechat/persona-extension.json b/extensions/openmate-wechat/persona-extension.json index 384a309..17be6ff 100644 --- a/extensions/openmate-wechat/persona-extension.json +++ b/extensions/openmate-wechat/persona-extension.json @@ -2,7 +2,7 @@ "manifest_version": 1, "id": "openmate-wechat", "name": "微信(OpenMate)", - "version": "0.1.76", + "version": "0.1.77", "description": "把微信私聊和群里 @你 的消息接进 Persona 的收件箱和会话页,私聊进知识库;在微信里用 /agent 让 Agent 以你的身份处理和回复,勾选的群里有人 @ 你时自动代答,助手代发的消息都要你在确认卡片上确认。以一台新电脑的身份登录你的微信(非官方协议),与腾讯官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", diff --git a/packages/openmate-feishu/0.11.82/openmate-feishu-0.11.82.tar.gz b/packages/openmate-feishu/0.11.82/openmate-feishu-0.11.82.tar.gz new file mode 100644 index 0000000..9a76bff Binary files /dev/null and b/packages/openmate-feishu/0.11.82/openmate-feishu-0.11.82.tar.gz differ diff --git a/packages/openmate-wechat/0.1.77/openmate-wechat-0.1.77.tar.gz b/packages/openmate-wechat/0.1.77/openmate-wechat-0.1.77.tar.gz new file mode 100644 index 0000000..84ecc29 Binary files /dev/null and b/packages/openmate-wechat/0.1.77/openmate-wechat-0.1.77.tar.gz differ diff --git a/persona-extensions.json b/persona-extensions.json index f84cd3b..06cb988 100644 --- a/persona-extensions.json +++ b/persona-extensions.json @@ -9,7 +9,7 @@ "manifest_version": 1, "id": "openmate-feishu", "name": "飞书(OpenMate)", - "version": "0.11.81", + "version": "0.11.82", "description": "把飞书私聊和群消息接进 Persona 的收件箱和知识库,通过确认卡片以你的身份发消息,支持 /agent。通过你自己安装的 LarkAgentX(非官方网页协议)连接,与飞书官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", @@ -540,9 +540,9 @@ "icon": "assets/icon.png", "packages": [ { - "url": "packages/openmate-feishu/0.11.81/openmate-feishu-0.11.81.tar.gz", - "sha256": "851f0d2b8803408bda48551e38d699c766aa6fc74bc1408fa7d18738dec1d8c6", - "size": 419375 + "url": "packages/openmate-feishu/0.11.82/openmate-feishu-0.11.82.tar.gz", + "sha256": "226c6e064c8caae7b1d60410119472939d14253a8b6f934fe33dc649389b4302", + "size": 421476 } ] }, @@ -551,7 +551,7 @@ "manifest_version": 1, "id": "openmate-wechat", "name": "微信(OpenMate)", - "version": "0.1.76", + "version": "0.1.77", "description": "把微信私聊和群里 @你 的消息接进 Persona 的收件箱和会话页,私聊进知识库;在微信里用 /agent 让 Agent 以你的身份处理和回复,勾选的群里有人 @ 你时自动代答,助手代发的消息都要你在确认卡片上确认。以一台新电脑的身份登录你的微信(非官方协议),与腾讯官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", @@ -849,9 +849,9 @@ "icon": "assets/icon.png", "packages": [ { - "url": "packages/openmate-wechat/0.1.76/openmate-wechat-0.1.76.tar.gz", - "sha256": "832c3d2ed643afe6ec7ca291cdd311570db763a72f0ebc5b020a333f96629807", - "size": 318320 + "url": "packages/openmate-wechat/0.1.77/openmate-wechat-0.1.77.tar.gz", + "sha256": "871d635387716cdb1dbb69c38d80600ea2de758bf7b65815fbe04d64556e56c1", + "size": 320434 } ] } diff --git a/tests/harness.py b/tests/harness.py index a047b24..93380c8 100644 --- a/tests/harness.py +++ b/tests/harness.py @@ -40,6 +40,8 @@ def fast(**kw) -> Timing: sent_retry=(0.05, 0.05, 0.05), warm_pages=False, agent_model_wait=1.0) if "channel_poll" in Timing.__dataclass_fields__: # the channel's (older code has none: its tests fail elsewhere) base.update(channel_poll=0.05, channel_retry=(0.05, 0.05), channel_unseen=0.3) + if "agent_hold_poll" in Timing.__dataclass_fields__: # a run held for a card (older code has none) + base.update(agent_hold_poll=0.05) base.update(kw) return Timing(**base) diff --git a/tests/test_agent_approval.py b/tests/test_agent_approval.py new file mode 100644 index 0000000..8aec9fa --- /dev/null +++ b/tests/test_agent_approval.py @@ -0,0 +1,403 @@ +"""/agent and a card that waits for the owner. A command Persona holds for the owner's approval keeps the tool call +waiting a while; unanswered by then, the call gets a non-final result that ends the turn, the card stays waiting, and +its outcome (approved, denied, expired) comes as a later message that starts the next turn. The turn that ended on the +card has no answer in its last words: nothing is posted and the one reply stays free (on WeChat, which answers once), +and the turn after the outcome answers as usual, a picture with it too.""" + +try: # first: every temporary directory of this run in one, removed at its end + import _runtmp # noqa: F401 +except ImportError: # (started by its path from elsewhere: its directory is not on the path) + pass +import os +import shutil +import tempfile +import time +import unittest + +from harness import fast, stamp, wait_until +from test_agent import SUFFIX, agent, ask, replies, running +from test_wechat_platform import wechat + +PNG = b"\x89PNG\r\n\x1a\n" + b"\x00" * 64 + +# The tool result Persona gives a command its approval card holds when the owner has not answered in time: Persona's +# approval.WaitingText (github.com/nwverse/persona, server/internal/approval/approval.go, commit f22a94312d), plus what +# its runtime adds for a command (server/internal/node/assistant_runtime.go). Only the transcript's look: what the +# extension goes by is the hub's count of the cards waiting in the session and the waiting cards themselves. +WAITING = ("The owner has not answered this approval yet. Nothing changed. End this turn now. The card stays pending in " + "the Persona app and web, where the owner can still allow or deny it, even without a notification; do not " + "retry the tool or create another approval. A later message will report its outcome. " + "The command was not executed.") +STUCK = "还卡在审批卡上:读本机保存的会长账号文件去公会站登录。这张卡还没批,所以还没做。批了之后我写好名单、截图回复一次。" + + +class CardTest(unittest.TestCase): + def setUp(self): + self.tmp = os.path.realpath(tempfile.mkdtemp(prefix="openmate-card-test-")) + self.addCleanup(shutil.rmtree, self.tmp, True) + + def picture(self): + p = os.path.join(self.tmp, "members.png") + with open(p, "wb") as f: + f.write(PNG) + return p + + def start(self, h, text="/agent 把接龙成员写到群公告的成员里面,然后截图看下成员列表"): + run = running(h, ask(h, text)) + return run, run["session_id"] + + @staticmethod + def raise_card(h, run, ix="ix-approval-1", at=None): + """Persona holds a command for the owner's approval in the run's conversation: the card waits.""" + sid = run["session_id"] + with h.http.lock: + s = h.http.sessions[sid] + s["pending_interactions"] = int(s.get("pending_interactions") or 0) + 1 + h.http.interactions.append({"id": ix, "kind": "permission", "tool_name": "Bash", "machine_id": run["machine_id"], + "session_id": sid, "created_at": stamp(at)}) + + @staticmethod + def end_card(h, run, ix="ix-approval-1"): + sid = run["session_id"] + with h.http.lock: + s = h.http.sessions[sid] + s["pending_interactions"] = int(s.get("pending_interactions") or 0) - 1 + if s["pending_interactions"] <= 0: + s.pop("pending_interactions") + h.http.interactions[:] = [i for i in h.http.interactions if i["id"] != ix] + + @classmethod + def stuck_items(cls, h, run): + """The turn that ends on the card: the command's tool call gave up waiting, the Agent says it waits.""" + sid = run["session_id"] + h.http.add(sid, "assistant", "tool_use", tool_name="Bash", tool_use_id="toolu_1") + cls.raise_card(h, run) + h.http.add(sid, "user", "tool_result", WAITING, tool_use_id="toolu_1") + h.http.add(sid, "assistant", "text", STUCK) + h.http.end_turn(sid) + + def stuck_turn(self, h, run): + self.stuck_items(h, run) + return wait_until(lambda: (lambda r: r if r.get("card_hold") else None)(h.app.store.run_get(run["id"])), + what="the run held for the card") + + @staticmethod + def outcome(h, run, word): + """The card ended: Persona tells the conversation, which starts the next turn.""" + sid = run["session_id"] + h.http.sessions[sid]["working"] = True + h.http.add(sid, "user", "text", "Approval ix-approval-1 is %s and is no longer pending." % word) + + def test_a_turn_ended_on_a_waiting_card_posts_nothing_and_keeps_the_reply(self): + h = wechat(self) + run, sid = self.start(h) + n = len(h.sent()) + held = self.stuck_turn(h, run) + time.sleep(0.4) # many polls: still nothing + self.assertEqual(len(h.sent()), n, "the words about the card are no answer: nothing posted") + cur = h.app.store.run_get(run["id"]) + self.assertEqual(cur["state"], "running") + self.assertFalse(cur.get("fallback"), "the one reply is not taken") + self.assertIsNone(h.app.store.send_get("agent:%s:fallback" % run["id"])) + self.assertFalse(held.get("last_text"), "its words are not kept to be posted later") + + def test_approved_then_the_answer_with_its_picture_goes(self): + h = wechat(self) + h.world.images_ok = True + run, sid = self.start(h) + n = len(h.sent()) + self.stuck_turn(h, run) + self.end_card(h, run) + self.outcome(h, run, "approved") + h.http.add(sid, "assistant", "tool_use", tool_name="Bash", tool_use_id="toolu_2") + h.http.add(sid, "user", "tool_result", "ok", tool_use_id="toolu_2") + out = h.tool("agent_reply", request=run["id"], text="接龙 25 人已写进成员名录,见截图。", image=self.picture()) + self.assertIn("图片也发出了", out) + self.assertEqual(len(h.world.images), 1) + h.http.add(sid, "assistant", "text", "已回复。") + h.http.end_turn(sid) + wait_until(lambda: h.app.store.run_get(run["id"])["state"] == "done", what="done") + time.sleep(0.2) + texts = [s["text"] for s in h.sent()[n:]] + self.assertEqual(len(texts), 1, texts) + self.assertTrue(texts[0].startswith("接龙 25 人已写进成员名录,见截图。"), texts) + self.assertNotIn("还卡在审批卡上", "".join(texts)) + + def test_denied_or_expired_the_next_turn_answers_once(self): + for word, last in (("denied", "审批被拒了:没有登录公会站,也没写入任何数据。"), + ("expired", "审批卡过期了:没有登录公会站,也没写入任何数据。要做的话请再发一次。")): + with self.subTest(word): + h = wechat(self) + run, sid = self.start(h) + n = len(h.sent()) + self.stuck_turn(h, run) + self.end_card(h, run) + self.outcome(h, run, word) + h.http.add(sid, "assistant", "text", last) + h.http.end_turn(sid) + wait_until(lambda: len(h.sent()) > n, what="the answer") + time.sleep(0.3) + texts = [s["text"] for s in h.sent()[n:]] + self.assertEqual(len(texts), 1, texts) + self.assertTrue(texts[0].startswith(last), texts) + cur = h.app.store.run_get(run["id"]) + self.assertEqual((cur["state"], cur["fallback"]), ("done", "sent")) + + def test_a_card_that_never_ends_still_gets_its_notice(self): + h = _wechat_with(self, fast(agent_approval_wait=0.6)) + run, sid = self.start(h) + n = len(h.sent()) + self.stuck_turn(h, run) + wait_until(lambda: len(h.sent()) > n, what="the notice") + time.sleep(0.3) + texts = [s["text"] for s in h.sent()[n:]] + self.assertEqual(len(texts), 1, texts) + self.assertIn("要你处理的卡片等了", texts[0]) + self.assertEqual(h.app.store.run_get(run["id"])["state"], "timeout") + + def test_a_question_while_held_that_ends_on_the_same_card_stays_held(self): + h = wechat(self) + run, sid = self.start(h) + n = len(h.sent()) + first = self.stuck_turn(h, run)["card_hold"] + # the owner writes into the conversation meanwhile; the card still waits, and the turn says so again + h.http.sessions[sid]["working"] = True + h.http.add(sid, "user", "text", "怎么样了") + h.http.add(sid, "assistant", "text", STUCK) + h.http.end_turn(sid) + again = wait_until(lambda: (lambda r: r if r.get("card_resumed") and r.get("card_hold", 0) > first else None)( + h.app.store.run_get(run["id"])), what="went on, then held again") + self.assertFalse(again.get("last_text")) + time.sleep(0.3) + self.assertEqual(len(h.sent()), n) + self.end_card(h, run) + self.outcome(h, run, "approved") + h.http.add(sid, "assistant", "text", "写好了:接龙 25 人已在成员名录里。") + h.http.end_turn(sid) + wait_until(lambda: len(h.sent()) > n, what="the answer") + self.assertTrue(h.sent()[-1]["text"].startswith("写好了")) + + def test_the_hub_cannot_say_then_nothing_goes_till_it_can(self): + h = wechat(self) + run, sid = self.start(h) + n = len(h.sent()) + h.http.interactions_status = 503 + h.http.add(sid, "assistant", "tool_use", tool_name="Bash", tool_use_id="toolu_1") + self.raise_card(h, run) + h.http.add(sid, "user", "tool_result", WAITING, tool_use_id="toolu_1") + h.http.add(sid, "assistant", "text", STUCK) + h.http.end_turn(sid) + wait_until(lambda: h.app.store.run_get(run["id"]).get("card_unsure"), what="unsure") + time.sleep(0.3) + self.assertEqual(len(h.sent()), n) + self.assertEqual(h.app.store.run_get(run["id"])["state"], "running") + h.http.interactions_status = None # the hub answers again: the card waits, so it is held + wait_until(lambda: h.app.store.run_get(run["id"]).get("card_hold"), what="held") + self.assertFalse(h.app.store.run_get(run["id"]).get("card_unsure")) + self.assertEqual(len(h.sent()), n) + + def test_the_conversation_goes_on_before_the_hub_can_say(self): + h = wechat(self) + run, sid = self.start(h) + n = len(h.sent()) + h.http.interactions_status = 503 + self.stuck_items(h, run) + wait_until(lambda: h.app.store.run_get(run["id"]).get("card_unsure"), what="unsure") + with h.http.lock: # the hub answers again just as the card ends and its outcome starts the next turn + h.http.interactions_status = None + self.end_card(h, run) + self.outcome(h, run, "approved") + time.sleep(0.3) + self.assertEqual(len(h.sent()), n, "the words about the card are not posted once the conversation went on") + cur = h.app.store.run_get(run["id"]) + self.assertEqual(cur["state"], "running") + self.assertFalse(cur.get("card_unsure")) + h.http.add(sid, "assistant", "text", "开始写名单……") + time.sleep(0.3) + self.assertEqual(len(h.sent()), n, "nor the next turn's half-written words") + h.http.add(sid, "assistant", "text", "写好了:名单已更新。") + h.http.end_turn(sid) + wait_until(lambda: len(h.sent()) > n, what="the answer") + time.sleep(0.2) + texts = [s["text"] for s in h.sent()[n:]] + self.assertEqual(len(texts), 1, texts) + self.assertTrue(texts[0].startswith("写好了:名单已更新。")) + + def test_held_across_a_restart(self): + h = wechat(self) + run, sid = self.start(h) + n = len(h.sent()) + self.stuck_turn(h, run) + import openmate_wechat + + h = h.restart(platform=openmate_wechat.platform()) # (restart keeps no platform: WeChat's again) + h.wait_ok() + time.sleep(0.3) + self.assertEqual(len(h.sent()), n) + cur = h.app.store.run_get(run["id"]) + self.assertEqual(cur["state"], "running") + self.assertTrue(cur.get("card_hold")) + self.end_card(h, run) + self.outcome(h, run, "approved") + h.http.add(sid, "assistant", "text", "写好了。") + h.http.end_turn(sid) + wait_until(lambda: len(h.sent()) > n, what="the answer") + self.assertTrue(h.sent()[-1]["text"].startswith("写好了。")) + + def test_a_hub_that_never_lists_the_cards_holds_while_the_row_counts_one(self): + h = wechat(self) + run, sid = self.start(h) + n = len(h.sent()) + h.http.interactions_status = 403 # refused for good: whose the waiting card is cannot be told + self.stuck_turn(h, run) + time.sleep(0.2) + self.assertEqual(len(h.sent()), n) + self.end_card(h, run) + self.outcome(h, run, "approved") + h.http.add(sid, "assistant", "text", "写好了。") + h.http.end_turn(sid) + wait_until(lambda: len(h.sent()) > n, what="the answer") + self.assertTrue(h.sent()[-1]["text"].startswith("写好了。")) + + +class UnchangedTest(unittest.TestCase): + def test_no_card_the_last_words_are_the_answer_as_before(self): + h = wechat(self) + run = running(h, ask(h, "/agent 总结一下")) + sid = run["session_id"] + n = len(h.sent()) + h.http.add(sid, "assistant", "text", "总结:周五前更新接口文档。") + h.http.end_turn(sid) + wait_until(lambda: len(h.sent()) > n, what="the fallback") + time.sleep(0.2) + texts = [s["text"] for s in h.sent()[n:]] + self.assertEqual(len(texts), 1) + self.assertTrue(texts[0].startswith("总结:周五前更新接口文档。")) + self.assertEqual(h.http.interactions_asked(), 0, "no card waits: the waiting cards are not read") + cur = h.app.store.run_get(run["id"]) + self.assertEqual((cur["state"], cur["fallback"]), ("done", "sent")) + with self.assertRaises(Exception) as e: + h.tool("agent_reply", request=run["id"], text="再说一次") + self.assertIn("只回复一次", str(e.exception)) + + def test_an_earlier_requests_card_does_not_hold_this_one(self): + h = wechat(self) + run = running(h, ask(h, "/agent 总结一下")) + sid = run["session_id"] + CardTest.raise_card(h, run, "ix-old", at=time.time() - 3600) # raised an hour before this request + n = len(h.sent()) + h.http.add(sid, "assistant", "text", "总结:周五前更新接口文档。") + h.http.end_turn(sid) + wait_until(lambda: len(h.sent()) > n, what="the fallback") + self.assertTrue(h.sent()[-1]["text"].startswith("总结:周五前更新接口文档。")) + self.assertFalse(h.app.store.run_get(run["id"]).get("card_hold")) + + def test_a_card_the_hub_does_not_show_holds(self): + h = wechat(self) + run = running(h, ask(h, "/agent 总结一下")) + sid = run["session_id"] + h.http.sessions[sid]["pending_interactions"] = 1 # counted in the row, not listed (a private card) + n = len(h.sent()) + h.http.add(sid, "assistant", "text", STUCK) + h.http.end_turn(sid) + wait_until(lambda: h.app.store.run_get(run["id"]).get("card_hold"), what="held") + time.sleep(0.2) + self.assertEqual(len(h.sent()), n) + + +class RowUnreadableTest(unittest.TestCase): + def test_no_card_and_a_row_that_cannot_be_read_still_answers(self): + from unittest.mock import patch + + from openmate_core.hub import HubError + + h = _wechat_with(self, fast(agent_hub_wait=0.5)) + run = running(h, ask(h, "/agent 总结一下")) + sid = run["session_id"] + n = len(h.sent()) + with patch.object(h.app.hub, "session_row", side_effect=HubError(503, "busy")): + h.http.add(sid, "assistant", "text", "总结:周五前更新接口文档。") + h.http.end_turn(sid) + wait_until(lambda: h.app.store.run_get(run["id"]).get("card_unsure"), what="put off") + self.assertEqual(len(h.sent()), n) + # the hub cannot say for agent_hub_wait: as before, the last words are the answer + wait_until(lambda: len(h.sent()) > n, what="the fallback") + time.sleep(0.2) + texts = [s["text"] for s in h.sent()[n:]] + self.assertEqual(len(texts), 1, texts) + self.assertTrue(texts[0].startswith("总结:周五前更新接口文档。")) + cur = h.app.store.run_get(run["id"]) + self.assertEqual((cur["state"], cur["fallback"]), ("done", "sent")) + self.assertFalse(cur.get("card_unsure")) + + +class FeishuTest(unittest.TestCase): + """Feishu edits messages and takes more than one reply: held the same way, and the answer after it goes.""" + + def test_held_then_answered_through_the_tool(self): + h = agent(self) + run = running(h, ask(h, "/agent 把名单写进成员页,然后截图")) + sid = run["session_id"] + h.tool("agent_reply", request=run["id"], text="开始写名单", progress=True) + progress = h.app.store.run_get(run["id"]).get("progress_id") + self.assertTrue(progress) + CardTest.raise_card(h, run) + h.http.add(sid, "user", "tool_result", WAITING) + h.http.add(sid, "assistant", "text", STUCK) + h.http.end_turn(sid) + wait_until(lambda: h.app.store.run_get(run["id"]).get("card_hold"), what="held") + time.sleep(0.3) + self.assertEqual(answers(h, progress), [], "no answer posted") + self.assertFalse(any("还卡在审批卡上" in s["text"] for s in h.sent())) + CardTest.end_card(h, run) + CardTest.outcome(h, run, "approved") + h.tool("agent_reply", request=run["id"], text="名单写好了。") + h.http.add(sid, "assistant", "text", "已回复") + h.http.end_turn(sid) + wait_until(lambda: h.app.store.run_get(run["id"])["state"] == "done", what="done") + time.sleep(0.2) + self.assertEqual([s["text"] for s in answers(h, progress)], ["名单写好了。\n\n" + SUFFIX]) + + def test_a_card_comes_before_the_work_it_handed_out(self): + """Feishu waits for the work a conversation handed out (agent_task_wait): a card waiting is checked first, so + the turn after its outcome is still followed and its last words answer.""" + h = agent(self) + run = running(h, ask(h, "/agent 把名单写进成员页")) + sid = run["session_id"] + todo = h.http.add_todo("todo-1", sid, [("mac-agent", "agent-1")]) + CardTest.stuck_items(h, run) + held = wait_until(lambda: (lambda r: r if r.get("card_hold") else None)(h.app.store.run_get(run["id"])), + what="held") + time.sleep(0.3) + self.assertFalse(held.get("awaiting")) + self.assertFalse(any("还卡在审批卡上" in s["text"] for s in h.sent()), "neither as the answer nor as progress") + CardTest.end_card(h, run) + todo["done_at"] = stamp() + CardTest.outcome(h, run, "denied") + h.http.add(sid, "assistant", "text", "审批被拒了,没有写名单。") + h.http.end_turn(sid) + wait_until(lambda: answers(h), what="the answer") + time.sleep(0.2) + self.assertEqual([s["text"] for s in answers(h)], ["审批被拒了,没有写名单。\n\n" + SUFFIX]) + + +def answers(h, progress=""): + """The answers posted (the progress message, edited in place, is not one).""" + return [s for s in replies(h) if s["id"] != progress] + + +def _wechat_with(test, timing): + """test_wechat_platform.wechat with its own timing.""" + import openmate_wechat + from harness import Harness + + config ={"agent": True, "agent_reply_header": " ", "agent_ack_reaction": "", "agent_done_reaction": "", + "agent_fail_reaction": ""} + h = Harness(test, config=config, timing=timing, platform=openmate_wechat.platform()) + h.sign_in() + wait_until(lambda: h.app._catchup_done.is_set(), what="catch-up") + return h + + +if __name__ == "__main__": + unittest.main()