Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix(approvals): clearing a chat ends its failed sends too
trohitgb4a20e9da1c0
diff --git a/docs-internal/chat_protocol.md b/docs-internal/chat_protocol.mdindex d033f03d..85eb22ec 100644--- a/docs-internal/chat_protocol.md+++ b/docs-internal/chat_protocol.md@@ -489,8 +489,10 @@ What an employee sends to someone waits for the owner's OK while its workflow asRestore while it can, Try again (asking first when it may have gone), and "Sends when you resume" for a gate'sdraft whose employee is paused. Countdowns use the server's clock (`server_time`). Ctrl/Cmd+Enter sends the newestwaiting draft; in the edit box it sends that one.-- **Ends.** Clearing or resetting the chat cancels the drafts its runs made that still wait; a Reset cancels the- waiting gates too (`approvalGate.reset_execution_state`); deleting the workflow deletes its drafts and its rule.+- **Ends.** Clearing or resetting the chat cancels the drafts its runs made that still wait, and their failed sends,+ whose Try again would send from a conversation that is gone; a Reset cancels the waiting gates too+ (`approvalGate.reset_execution_state`); deleting the workflow deletes its drafts and its rule. Leaving a branch+ cancels only the drafts that still wait (see [Branches](#branches)), so a failure shows again on the way back.- **Expiry.** A gate's draft expires after the node's `timeout_hours` (168 by default), and the waiting gate ends it`expired` and lets nothing through. A held call's draft expires 168 hours after it was made(`DEFAULT_TIMEOUT_HOURS`); the chat watchdog ends it on its next round (`reconcile.expire_due`), announces it anddiff --git a/server/services/approvals/store.py b/server/services/approvals/store.pyindex a2ac8137..904dae1e 100644--- a/server/services/approvals/store.py+++ b/server/services/approvals/store.py@@ -200,10 +200,13 @@ def is_open(row: ApprovalRequest, now: Optional[datetime] = None) -> bool:return False-def cancellable(row: ApprovalRequest, now: Optional[datetime] = None) -> bool:+def cancellable(row: ApprovalRequest, now: Optional[datetime] = None, *, failed: bool = False) -> bool:"""What a Reset, a branch or a deleted run cancels: everything open- except a send already under way and a failure (nothing left to stop)."""- return row.status not in ("sending", "failed") and is_open(row, now)+ except a send already under way and a failure (nothing left to stop),+ unless ``failed``: clearing a conversation ends its failures too."""+ if row.status == "failed":+ return failed+ return row.status != "sending" and is_open(row, now)async def cancel_open(@@ -212,14 +215,16 @@ async def cancel_open(workflow_id: str,generation: Optional[int] = None,run_ids: Optional[Iterable[str]] = None,+ failed: bool = False,) -> List[ApprovalRequest]:"""Cancel a workflow's drafts that still wait (all generations, one, orthose of some chat runs): waiting, approved but not handed on yet, or- discarded and restorable."""+ discarded and restorable; with ``failed``, failed sends as well."""+ statuses = ("pending", "approved", "discarded", "failed") if failed else ("pending", "approved", "discarded")async with database.get_session() as session:query = select(ApprovalRequest).where(ApprovalRequest.workflow_id == workflow_id,- ApprovalRequest.status.in_(("pending", "approved", "discarded")),+ ApprovalRequest.status.in_(statuses),)if generation is not None:query = query.where(ApprovalRequest.generation == generation)@@ -232,7 +237,7 @@ async def cancel_open(now = _utcnow()cancelled: List[ApprovalRequest] = []for row in rows:- if not cancellable(row, now):+ if not cancellable(row, now, failed=failed):continuetry:cancelled.append(diff --git a/server/services/chat_thread.py b/server/services/chat_thread.pyindex 5e735325..2e17e6cc 100644--- a/server/services/chat_thread.py+++ b/server/services/chat_thread.py@@ -173,7 +173,9 @@ async def clear_chat_thread(database: Any, session_id: str, *, reason: str = "reasync def _cancel_drafts(database: Any, session_id: str) -> None:"""Drafts the conversation's runs made that still wait go with it: a- send nobody can see any more must not go out later."""+ send nobody can see any more must not go out later. So do its failed+ sends: kept, their card stayed in the empty chat, and its Try again+ would send from a conversation that is gone."""from services.chat import ledgertry:@@ -183,7 +185,7 @@ async def _cancel_drafts(database: Any, session_id: str) -> None:run_ids = await ledger.session_run_ids(database, session_id)if not run_ids:return- for row in await store.cancel_open(database, workflow_id=session_id, run_ids=run_ids):+ for row in await store.cancel_open(database, workflow_id=session_id, run_ids=run_ids, failed=True):waiter.notify(row.id)await notify_approval_changed(change_of(row, "cancelled"))except Exception:diff --git a/server/tests/services/approvals/test_tool_calls.py b/server/tests/services/approvals/test_tool_calls.pyindex 7b506cd5..1e4e0023 100644--- a/server/tests/services/approvals/test_tool_calls.py+++ b/server/tests/services/approvals/test_tool_calls.py@@ -334,6 +334,35 @@ async def test_clearing_the_chat_cancels_its_drafts(harness, nodes_loaded, monkeassert statuses == [("call_1", "cancelled"), ("call_2", "pending")]+async def test_clearing_the_chat_ends_its_failed_sends_too(harness, nodes_loaded, monkeypatch):+ # Kept, a failure's card stayed in the emptied chat, and its Try again+ # would send from a conversation that is gone.+ from services.chat import ledger, parts+ from services.chat_thread import clear_chat_thread++ async def show_approval(database, stream, **_):+ return None++ async def start_send(approved):+ return None++ monkeypatch.setattr(parts, "show_approval", show_approval)+ monkeypatch.setattr(execution, "start_send", start_send)+ monkeypatch.setattr(ledger, "session_run_ids", lambda database, session_id: _async(["r_1"]))+ await rules.set_ask_first(harness.database, "wf", True)+ await tool_calls.check(call(chat_stream={"run_id": "r_1", "session_id": "wf"}, chat_run_id="r_1"), get_node_class("whatsappSend"))+ (row,) = await store.list_approvals(harness.database, status="pending")+ await handle_decide_approval({"approval_id": row.id, "decision": "send", "decision_key": "k1"}, SOCKET)+ approved = await store.get(harness.database, row.id)+ await execution.claim_send(harness.database, row.id, approved.revision, "t-1")+ failed = await execution.record_outcome(harness.database, row.id, "t-1", "not_sent", "Bad request")+ assert failed.status == "failed"+ # Leaving its branch keeps the failure, which shows again on the way back.+ assert await store.cancel_open(harness.database, workflow_id="wf", run_ids=["r_1"]) == []+ await clear_chat_thread(harness.database, "wf")+ assert (await store.get(harness.database, row.id)).status == "cancelled"++async def _async(value):return value