From 3e890954739a024cc7c3110b485115b700a4fbec Mon Sep 17 00:00:00 2001 From: NginxL <8777777+NginxL@users.noreply.github.com> Date: Sun, 6 Dec 2026 21:25:43 +0800 Subject: [PATCH 1/2] /agent card hold: a card answered just before its turn ended still owes its outcome Persona lets a tool call go while its approval card waits (approval.WaitingText / ClarifyingText in the tool result) and later sends the card's outcome as a message that starts the next turn. When the owner answered between the two, no card waited any more when the turn's end was read, and the words about the card were posted as the answer (review of PR #67, P1-1). The tool result is now remembered as an owed outcome (card_owed) until the outcome's message comes (the hub's injected approval_* mark, or Persona's marker or older wording when unmarked); a turn that ends while it is owed is held like one with a waiting card. Co-Authored-By: Claude Opus 5.5 --- core/openmate_core/agent.py | 65 ++++++++++- tests/test_agent_approval.py | 218 +++++++++++++++++++++++++++++++++++ 2 files changed, 281 insertions(+), 2 deletions(-) diff --git a/core/openmate_core/agent.py b/core/openmate_core/agent.py index 27c6b5b..20c0b73 100644 --- a/core/openmate_core/agent.py +++ b/core/openmate_core/agent.py @@ -10,7 +10,8 @@ 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 +free, and the turn after the outcome answers as usual (_card_waits; a card answered just before the turn ended still +owes that outcome, which the tool call's result says: card_owed). /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 @@ -2828,6 +2829,16 @@ def _poll(self, run: dict) -> None: 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 _card_left_waiting(it): + # Persona let a tool call of this request go while its card waits for the owner: the card's + # outcome is owed, as a later message that starts the turn that answers (_turn_ended) + cur["card_owed"] = time.time() + elif cur.get("card_owed") and _card_outcome(it): + # that message: the words before it only said the card waits, and the turn it starts (still + # under way, though the one before may have ended in this same read) is the one that answers + del cur["card_owed"] + last_text, answered, ended = None, False, False + log.info("/agent %s: the outcome of the card it waited on came", 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 @@ -3025,7 +3036,12 @@ def _turn_ended(self, run_id: str) -> None: 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" + if card is False and first.get("card_owed"): + # no card waits now, but one this request's tool call was let go for has not told its outcome: the + # owner answered it after that (before or as the turn ended); the outcome waits for this turn's end, + # then starts the next turn, which answers + card = True + 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": @@ -4040,3 +4056,48 @@ def _item_time(it: dict) -> float: def _interrupted(text: str) -> bool: """The notice Persona's transcript writes for a stopped turn (transcript.InterruptedNotice).""" return (text or "").strip() == "已中断" + + +# What Persona gives a tool call its approval card holds when the card outlives the call: the card stays waiting for the +# owner, and a later message tells the conversation its outcome. Persona's approval.WaitingText and +# approval.ClarifyingText (github.com/nwverse/persona, server/internal/approval/approval.go, commit 926e3861a5). +_CARD_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.") +_CARD_CLARIFYING = ("The owner asked a question about this approval. It is not an approval decision and nothing changed. " + "The question arrives as a separate owner message; answer it then. The original approval card " + "remains valid and is still pending; do not retry the tool or create another approval. A later " + "message reports its outcome.") +# The message with a card's outcome when the hub has not marked it (Persona's older wording): parseLegacyApprovalResult +# (server/internal/prompts/approval_result.go, same commit) +_CARD_OUTCOME = re.compile(r"^Approval [A-Za-z0-9_.:-]+ is (?:[^.\n]+ and is no longer pending\.|no longer pending\. " + r"Its one-time continuation was already consumed or is no longer available\.)(?:\s|$)") + + +def _card_left_waiting(it: dict) -> bool: + """A tool call's result that is not its outcome: Persona let the call go while its card still waits, and the card's + outcome comes as a later message. The same test as Persona's nonFinalApprovalResult (server/internal/assistant/ + fleet_ix_terminal.go, commit 926e3861a5): the very words, or a PreToolUse hook's error around them.""" + if it.get("role") != "user" or it.get("kind") != "tool_result": + return False + text = (it.get("text") or "").strip() + if text.startswith("PreToolUse:"): + i = text.find("hook error:") + if not it.get("is_error") or i < 0: + return False + text = text[i + len("hook error:"):].strip() + return any(text == w or text.startswith(w + " ") for w in (_CARD_WAITING, _CARD_CLARIFYING)) + + +def _card_outcome(it: dict) -> bool: + """The message Persona sends into a conversation with the outcome of a card that outlived its tool call (approved, + denied, expired…). The hub marks it (prompts.IsApprovalResult: injected, kind system, state approval_*); the text + is read only when it does not.""" + if it.get("role") != "user" or it.get("kind") != "text": + return False + inj = it.get("injected") + if isinstance(inj, dict) and inj: + return inj.get("kind") == "system" and str(inj.get("state") or "").startswith("approval_") + text = (it.get("text") or "").lstrip() + return text.startswith("") or bool(_CARD_OUTCOME.match(text)) diff --git a/tests/test_agent_approval.py b/tests/test_agent_approval.py index 8aec9fa..7b6659f 100644 --- a/tests/test_agent_approval.py +++ b/tests/test_agent_approval.py @@ -260,7 +260,225 @@ def test_a_hub_that_never_lists_the_cards_holds_while_the_row_counts_one(self): self.assertTrue(h.sent()[-1]["text"].startswith("写好了。")) +def marked_outcome(h, run, word, ix="ix-approval-1"): + """The card's outcome as the hub hands it out: Persona's marker on its first line (prompts.ApprovalResultMarker) + and the hub's mark on the item (hub.withInjected). It starts the next turn.""" + sid = run["session_id"] + head = ('{"id":"%s","status":"%s","kind":"approval","summary":"Bash"}' + '' % (ix, word)) + with h.http.lock: + h.http.sessions[sid]["working"] = True + h.http.add(sid, "user", "text", head + "\nApproval %s is %s and is no longer pending." % (ix, word), + injected={"kind": "system", "state": "approval_" + word, "line": "审批结果:" + word}) + + +def held(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's outcome") + + +class AnsweredAsTheTurnEndsTest(unittest.TestCase): + """The owner answers the card after Persona let its tool call go and before the extension reads the end of the + turn (a review of PR #67, P1): no card waits by then, yet its outcome is still to come, queued behind the turn, + and starts the next one. The turn's words only said the card waits: nothing is posted, the one reply stays free, + and the next turn answers.""" + + def setUp(self): + self.tmp = os.path.realpath(tempfile.mkdtemp(prefix="openmate-card-test-")) + self.addCleanup(shutil.rmtree, self.tmp, True) + + @staticmethod + def raced(h, run, result=WAITING, outcome=None, **kw): + """In one read: the tool call let go while its card waits, the words about it, the owner's answer, the end of + the turn (and, with `outcome`, the outcome's message right after it).""" + sid = run["session_id"] + with h.http.lock: + h.http.add(sid, "assistant", "tool_use", tool_name="Bash", tool_use_id="toolu_1") + CardTest.raise_card(h, run) + h.http.add(sid, "user", "tool_result", result, tool_use_id="toolu_1", **kw) + h.http.add(sid, "assistant", "text", STUCK) + CardTest.end_card(h, run) # answered now: no card waits when the extension reads the end of the turn + h.http.end_turn(sid) + if outcome: + marked_outcome(h, run, outcome) + + def test_approved_then_the_answer_with_its_picture_goes(self): + h = wechat(self) + h.world.images_ok = True + run = running(h, ask(h, "/agent 把接龙成员写到群公告的成员里面,然后截图")) + sid = run["session_id"] + n = len(h.sent()) + self.raced(h, run) + cur = held(h, run) + time.sleep(0.3) + 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.assertTrue(cur.get("card_owed")) + marked_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=CardTest.picture(self)) + 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)) + self.assertFalse(h.app.store.run_get(run["id"]).get("card_owed")) + + 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 = running(h, ask(h, "/agent 把接龙成员写到群公告的成员里面")) + sid = run["session_id"] + n = len(h.sent()) + self.raced(h, run) + held(h, run) + time.sleep(0.2) + self.assertEqual(len(h.sent()), n) + marked_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_the_outcome_read_together_with_the_end_of_the_turn(self): + """The outcome's message already follows the end of the turn when the extension reads it: the turn under way + is the outcome's, and its end answers.""" + h = wechat(self) + run = running(h, ask(h, "/agent 把接龙成员写到群公告的成员里面")) + sid = run["session_id"] + n = len(h.sent()) + self.raced(h, run, outcome="approved") + wait_until(lambda: h.app.store.run_get(run["id"])["last_seq"] >= h.http.sessions[sid]["items"][-1]["seq"], + what="read") + time.sleep(0.3) + self.assertEqual(len(h.sent()), n) + cur = h.app.store.run_get(run["id"]) + self.assertEqual(cur["state"], "running") + self.assertFalse(cur.get("last_text"), "the words before the outcome are not kept to be posted") + self.assertFalse(cur.get("card_owed")) + 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", "写好了:接龙 25 人已在成员名录里。") + 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("写好了:接龙 25 人已在成员名录里。"), texts) + + def test_a_hook_error_around_the_words_too(self): + """A PreToolUse hook's error that wraps Persona's words (Persona's nonFinalApprovalResult takes it so).""" + h = wechat(self) + run = running(h, ask(h, "/agent 把接龙成员写到群公告的成员里面")) + sid = run["session_id"] + n = len(h.sent()) + self.raced(h, run, result="PreToolUse:Bash hook error: " + WAITING, is_error=True) + held(h, run) + time.sleep(0.2) + self.assertEqual(len(h.sent()), n) + marked_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_the_hub_cannot_say_for_long_the_outcome_still_owed_holds(self): + """The session's row cannot be read for agent_hub_wait: no card is known to wait, but the outcome is owed.""" + 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")): + self.raced(h, run) + wait_until(lambda: h.app.store.run_get(run["id"]).get("card_unsure"), what="put off") + held(h, run) + time.sleep(0.2) + self.assertEqual(len(h.sent()), n) + marked_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_feishu_held_too_then_answered_through_the_tool(self): + h = agent(self) + run = running(h, ask(h, "/agent 把名单写进成员页")) + sid = run["session_id"] + self.raced(h, run) + held(h, run) + time.sleep(0.3) + self.assertEqual(answers(h), [], "no answer posted") + self.assertFalse(any("还卡在审批卡上" in s["text"] for s in h.sent())) + marked_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)], ["名单写好了。\n\n" + SUFFIX]) + + class UnchangedTest(unittest.TestCase): + def test_a_card_approved_within_its_first_wait_is_no_hold(self): + """Approved while its tool call still waited: the call has its real result, no outcome message is owed, and + the turn's last words are the answer as before.""" + h = wechat(self) + run = running(h, ask(h, "/agent 把接龙成员写到群公告的成员里面")) + sid = run["session_id"] + n = len(h.sent()) + with h.http.lock: + h.http.add(sid, "assistant", "tool_use", tool_name="Bash", tool_use_id="toolu_1") + CardTest.raise_card(h, run) + CardTest.end_card(h, run) + h.http.add(sid, "user", "tool_result", "群公告已更新", tool_use_id="toolu_1") + h.http.add(sid, "assistant", "text", "写好了:接龙 25 人已在成员名录里。") + 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, texts) + self.assertTrue(texts[0].startswith("写好了:接龙 25 人已在成员名录里。")) + cur = h.app.store.run_get(run["id"]) + self.assertFalse(cur.get("card_hold") or cur.get("card_owed")) + + def test_an_earlier_requests_outcome_does_not_drop_this_answer(self): + """The outcome of a card an earlier request waited on comes after this request's turn: this one owes none, so + its last words are its answer as before.""" + h = wechat(self) + run = running(h, ask(h, "/agent 总结一下")) + sid = run["session_id"] + n = len(h.sent()) + with h.http.lock: + h.http.add(sid, "assistant", "text", "总结:周五前更新接口文档。") + h.http.end_turn(sid) + marked_outcome(h, run, "approved", "ix-old") + 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("总结:周五前更新接口文档。")) + def test_no_card_the_last_words_are_the_answer_as_before(self): h = wechat(self) run = running(h, ask(h, "/agent 总结一下")) From 7041d5159b7dd9290235b005d1e2549fb35df65f Mon Sep 17 00:00:00 2001 From: NginxL <8777777+NginxL@users.noreply.github.com> Date: Sun, 6 Dec 2026 21:54:04 +0800 Subject: [PATCH 2/2] /agent card owed: a question card's outcome is not an approval's; tests for a question about the card (review 1) Co-Authored-By: Claude Opus 5.5 --- core/openmate_core/agent.py | 23 +++++++--- tests/test_agent_approval.py | 85 ++++++++++++++++++++++++++++++++++++ 2 files changed, 102 insertions(+), 6 deletions(-) diff --git a/core/openmate_core/agent.py b/core/openmate_core/agent.py index 20c0b73..8018b70 100644 --- a/core/openmate_core/agent.py +++ b/core/openmate_core/agent.py @@ -3041,7 +3041,7 @@ def _turn_ended(self, run_id: str) -> None: # owner answered it after that (before or as the turn ended); the outcome waits for this turn's end, # then starts the next turn, which answers card = True - tasks =self._open_tasks(first) if card is False and first is not None and self._may_await(first) else "none" + 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": @@ -4069,8 +4069,10 @@ def _interrupted(text: str) -> bool: "The question arrives as a separate owner message; answer it then. The original approval card " "remains valid and is still pending; do not retry the tool or create another approval. A later " "message reports its outcome.") -# The message with a card's outcome when the hub has not marked it (Persona's older wording): parseLegacyApprovalResult -# (server/internal/prompts/approval_result.go, same commit) +# The message with a card's outcome when the hub has not marked it: Persona's marker on its first line +# (prompts.ApprovalResultMarker) or its older wording (parseLegacyApprovalResult), server/internal/prompts/ +# approval_result.go, same commit +_CARD_MARK = ("", "") _CARD_OUTCOME = re.compile(r"^Approval [A-Za-z0-9_.:-]+ is (?:[^.\n]+ and is no longer pending\.|no longer pending\. " r"Its one-time continuation was already consumed or is no longer available\.)(?:\s|$)") @@ -4093,11 +4095,20 @@ def _card_left_waiting(it: dict) -> bool: def _card_outcome(it: dict) -> bool: """The message Persona sends into a conversation with the outcome of a card that outlived its tool call (approved, denied, expired…). The hub marks it (prompts.IsApprovalResult: injected, kind system, state approval_*); the text - is read only when it does not.""" + is read only when it does not: Persona's marker on its first line, or its older wording. A question card's (a + question that a restart cancelled: approval_question_*) is not an approval's.""" if it.get("role") != "user" or it.get("kind") != "text": return False inj = it.get("injected") if isinstance(inj, dict) and inj: - return inj.get("kind") == "system" and str(inj.get("state") or "").startswith("approval_") + state = str(inj.get("state") or "") + return inj.get("kind") == "system" and state.startswith("approval_") and not state.startswith("approval_question") text = (it.get("text") or "").lstrip() - return text.startswith("") or bool(_CARD_OUTCOME.match(text)) + head = text.split("\n", 1)[0].strip() + if head.startswith(_CARD_MARK[0]) and head.endswith(_CARD_MARK[1]): + try: + meta = json.loads(head[len(_CARD_MARK[0]):-len(_CARD_MARK[1])]) + except ValueError: + return False + return isinstance(meta, dict) and meta.get("kind") == "approval" + return bool(_CARD_OUTCOME.match(text)) diff --git a/tests/test_agent_approval.py b/tests/test_agent_approval.py index 7b6659f..cdd9a1e 100644 --- a/tests/test_agent_approval.py +++ b/tests/test_agent_approval.py @@ -28,6 +28,11 @@ "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.") +# What Persona gives the tool call when the owner asked a question about its card: approval.ClarifyingText (same file). +CLARIFYING = ("The owner asked a question about this approval. It is not an approval decision and nothing changed. The " + "question arrives as a separate owner message; answer it then. The original approval card remains valid " + "and is still pending; do not retry the tool or create another approval. A later message reports its " + "outcome.") STUCK = "还卡在审批卡上:读本机保存的会长账号文件去公会站登录。这张卡还没批,所以还没做。批了之后我写好名单、截图回复一次。" @@ -421,6 +426,41 @@ def test_the_hub_cannot_say_for_long_the_outcome_still_owed_holds(self): wait_until(lambda: len(h.sent()) > n, what="the answer") self.assertTrue(h.sent()[-1]["text"].startswith("写好了。")) + def test_a_question_about_the_card_then_answered_as_that_turn_ends(self): + """The owner asks about the card (Persona's ClarifyingText to the tool call; the question comes as an owner's + message, the conversation answers it) and approves just before that turn ends: the answer to the question is + not the request's, and the outcome is still owed.""" + h = wechat(self) + run = running(h, ask(h, "/agent 把接龙成员写到群公告的成员里面")) + sid = run["session_id"] + n = len(h.sent()) + with h.http.lock: + h.http.add(sid, "assistant", "tool_use", tool_name="Bash", tool_use_id="toolu_1") + CardTest.raise_card(h, run) + h.http.add(sid, "user", "tool_result", CLARIFYING, tool_use_id="toolu_1") + h.http.add(sid, "assistant", "text", "主人对审批卡有个问题,等问题来了再回答。") + h.http.end_turn(sid) + first = held(h, run)["card_hold"] + with h.http.lock: + h.http.sessions[sid]["working"] = True + h.http.add(sid, "user", "text", "这个账号文件是哪来的?") + h.http.add(sid, "assistant", "text", "是上周从公会站导出的会长账号文件。") + CardTest.end_card(h, run) + 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.assertTrue(again.get("card_owed"), "the owner's question is not the card's outcome") + time.sleep(0.3) + self.assertEqual(len(h.sent()), n) + marked_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") + time.sleep(0.2) + texts = [s["text"] for s in h.sent()[n:]] + self.assertEqual(len(texts), 1, texts) + self.assertTrue(texts[0].startswith("写好了"), texts) + def test_feishu_held_too_then_answered_through_the_tool(self): h = agent(self) run = running(h, ask(h, "/agent 把名单写进成员页")) @@ -439,6 +479,51 @@ def test_feishu_held_too_then_answered_through_the_tool(self): self.assertEqual([s["text"] for s in answers(h)], ["名单写好了。\n\n" + SUFFIX]) +class SignalTest(unittest.TestCase): + """What the extension goes by: Persona's own words in the tool call's result, and the marked outcome message.""" + + def test_a_tool_call_let_go_while_its_card_waits(self): + from openmate_core.agent import _card_left_waiting + + def result(text, **kw): + return dict({"role": "user", "kind": "tool_result", "text": text}, **kw) + + for it, want in ((result(WAITING), True), + (result(WAITING[:-len(" The command was not executed.")]), True), + (result("\n" + CLARIFYING + "\n"), True), + (result("PreToolUse:Bash hook error: " + WAITING, is_error=True), True), + (result("PreToolUse:Bash hook error: " + WAITING), False), # not an error: not the hook's + (result("PreToolUse:Bash hook error: 群公告已更新", is_error=True), False), + (result(WAITING[:-len(" The command was not executed.")] + "!"), False), # not its words + (result("群公告已更新"), False), + ({"role": "assistant", "kind": "text", "text": WAITING}, False), + ({"role": "user", "kind": "text", "text": WAITING}, False)): + with self.subTest(it): + self.assertEqual(_card_left_waiting(it), want) + + def test_the_cards_outcome(self): + from openmate_core.agent import _card_outcome + + def text(t, **kw): + return dict({"role": "user", "kind": "text", "text": t}, **kw) + + marker = '{"id":"ix-1","status":"%s","kind":"%s","summary":"Bash"}\n' + for it, want in ((text("…", injected={"kind": "system", "state": "approval_denied", "line": "…"}), True), + (text("…", injected={"kind": "system", "state": "approval_question_invalidated"}), False), + (text("…", injected={"kind": "task_notice", "state": "done"}), False), + (text(marker % ("approved", "approval") + "Approval ix-1 is approved and is no longer pending."), + True), + (text(marker % ("invalidated", "question") + "Question ix-1 was cancelled."), False), + (text("Approval ix-1 is expired and is no longer pending. Ask again if still wanted."), True), + (text("Approval ix-1 is no longer pending. Its one-time continuation was already consumed or " + "is no longer available."), True), + (text("怎么样了"), False), + ({"role": "assistant", "kind": "text", "text": "Approval ix-1 is approved and is no longer " + "pending."}, False)): + with self.subTest(it): + self.assertEqual(_card_outcome(it), want) + + class UnchangedTest(unittest.TestCase): def test_a_card_approved_within_its_first_wait_is_no_hold(self): """Approved while its tool call still waited: the call has its real result, no outcome message is owed, and