Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(society): release a turn that ended without a result; close settled approval cards (#314)
Ruben Lütkeeac613566e6f
diff --git a/dodaios/agent_chat/approval_bridge.py b/dodaios/agent_chat/approval_bridge.pyindex cccc8f1043..4610e099f9 100644--- a/dodaios/agent_chat/approval_bridge.py+++ b/dodaios/agent_chat/approval_bridge.py@@ -102,8 +102,14 @@ class ChatApprovalBridge:self._grants: dict[str, ChatGrant] = {}self._args: OrderedDict[UUID, dict[str, Any]] = OrderedDict()self._tasks: set[asyncio.Task[None]] = set()+ #: Open cards by ticket. A ticket settled anywhere else — the executor's+ #: own timeout, another surface's answer — closes its card here, so a+ #: late click can no longer read "approved" for a call that was refused.+ self._asking: dict[UUID, asyncio.Task[None]] = {}bus.subscribe(ActionProposed, self._on_proposed)bus.subscribe(ActionApprovalRequired, self._on_required)+ bus.subscribe(ActionApproved, self._on_settled)+ bus.subscribe(ActionDenied, self._on_settled)# ------------------------------------------------------------ grants@@ -157,10 +163,29 @@ class ChatApprovalBridge:name=f"agent-chat-approval-{grant.session_id[:8]}",)self._tasks.add(task)+ self._asking[event.trace_id] = tasktask.add_done_callback(self._tasks.discard)+ task.add_done_callback(lambda done, tid=event.trace_id: self._forget(tid, done))except Exception: # noqa: BLE001 — AP-18: a subscriber never raises into the buslog.warning("chat approval bridge: could not handle an approval request", exc_info=True)+ def _forget(self, trace_id: UUID, task: asyncio.Task[Any] | None) -> None:+ if self._asking.get(trace_id) is task:+ del self._asking[trace_id]++ async def _on_settled(self, event: ActionApproved | ActionDenied) -> None:+ """Close the card of a ticket that was decided without it."""+ try:+ task = self._asking.pop(event.trace_id, None)+ if task is not None and not task.done():+ log.info(+ "chat approval bridge: %s was settled elsewhere; closing its card",+ event.tool_name,+ )+ task.cancel()+ except Exception: # noqa: BLE001 — AP-18: a subscriber never raises into the bus+ log.warning("chat approval bridge: could not close a settled card", exc_info=True)+# ------------------------------------------------------------ policy@staticmethod@@ -196,6 +221,8 @@ class ChatApprovalBridge:except Exception: # noqa: BLE001 — the ticket must be answered either waylog.warning("chat approval bridge: the card failed; denying", exc_info=True)decision = "deny"+ # Our own answer below must not read as "settled elsewhere".+ self._forget(event.trace_id, asyncio.current_task())if decision in ("allow", "allow_always"):if decision == "allow_always":grant.always_allowed.add(_bare(event.tool_name))diff --git a/dodaios/agent_chat/service.py b/dodaios/agent_chat/service.pyindex 1d56ef1c92..b5af542bb1 100644--- a/dodaios/agent_chat/service.py+++ b/dodaios/agent_chat/service.py@@ -2068,6 +2068,21 @@ class AgentChatService:)try:decision = await fut+ except asyncio.CancelledError:+ # Nobody will answer this card any more (the ticket expired or was+ # decided elsewhere, or the turn stopped). Close it, so it cannot+ # take a click that would no longer reach anything.+ try:+ await self._emit(+ session_id,+ make_event(+ "approval_resolved",+ {"turn_id": turn_id, "approval_id": approval_id, "decision": "cancel"},+ ),+ )+ except Exception: # noqa: BLE001 — the cancellation must still propagate+ log.warning("agent chat: could not close approval card %s", approval_id)+ raisefinally:self._approvals.pop(approval_id, None)self._approval_session.pop(approval_id, None)diff --git a/dodaios/society/runtime.py b/dodaios/society/runtime.pyindex 92eb2b4974..5120b18e5d 100644--- a/dodaios/society/runtime.py+++ b/dodaios/society/runtime.py@@ -94,6 +94,10 @@ _LEAD_INCOMING_TYPES: Final[frozenset[MsgType]] = frozenset({MsgType.SAY, MsgType.QUERY, MsgType.ANSWER, MsgType.PROPOSE})_WATCH_EVENT_POLL_SECONDS: Final[float] = 2.0+#: Quiet polls in a row, each after a durable read, that the chat must report no+#: running turn before the watcher stops waiting for a terminal event. Two, so a+#: turn that ends between the read and the check is still read on the next poll.+_WATCH_GONE_POLLS: Final[int] = 2#: The drill switch: a file in the data dir that injects a named fault._DRILL_FILE: Final[str] = "society_drill.json"_DRILL_MAX_S: Final[float] = 30.0@@ -111,6 +115,18 @@ def set_current_runtime(runtime: SocietyRuntime | None) -> None:_current = runtime+def _turn_alive(svc: Any, session_id: str) -> bool:+ """Whether the chat still runs a turn here; unknown counts as alive."""+ is_running = getattr(svc, "is_running", None)+ if not callable(is_running):+ return True+ try:+ return bool(is_running(session_id))+ except Exception: # noqa: BLE001 - an unanswerable probe must not end a live turn+ log.debug("society: turn liveness probe failed for %s", session_id, exc_info=True)+ return True++def _pause_self_build() -> bool:"""The society kill switch also pauses the self-building loop.@@ -1014,13 +1030,28 @@ class SocietyRuntime:used_browser = Falselast_seq = 0read_failures = 0+ gone_polls = 0+ polled = Falsequest_trace = env.trace_id.startswith("quest:")try:while True:+ if polled:+ # A quiet poll found no terminal event. A turn whose task has+ # ended without writing one (a runner that returned early, a+ # failed final write) would otherwise hold this agent's slot+ # and the lead's report forever.+ polled = False+ gone_polls = 0 if _turn_alive(svc, session_id) else gone_polls + 1+ if gone_polls >= _WATCH_GONE_POLLS:+ status = "blocked"+ error = "The agent's turn ended without reporting a result."+ log.warning("society: %s ended without a terminal event", run_id)+ breaktry:events = [await asyncio.wait_for(queue.get(), timeout=_WATCH_EVENT_POLL_SECONDS)]+ gone_polls = 0except TimeoutError:# The service drops a subscriber whose queue overflows. Its# events remain durable, so recover the missing terminal.@@ -1028,6 +1059,7 @@ class SocietyRuntime:events = await asyncio.to_thread(svc.store.list_events, session_id, after_seq=last_seq)+ polled = Trueexcept Exception: # noqa: BLE001 - a broken chat store must release the slotread_failures += 1log.warning(diff --git a/tests/unit/agent_chat/test_agent_chat_service.py b/tests/unit/agent_chat/test_agent_chat_service.pyindex 4bad67d59e..8618eca452 100644--- a/tests/unit/agent_chat/test_agent_chat_service.py+++ b/tests/unit/agent_chat/test_agent_chat_service.py@@ -213,6 +213,27 @@ def test_deny_feeds_a_denied_result_and_allow_always_flips_the_mode(tmp_path: Paasyncio.run(scenario())+def test_an_abandoned_approval_card_is_closed(tmp_path: Path, scripted):+ """A card whose ask is cancelled (its ticket settled elsewhere) must not stay open."""++ async def scenario() -> None:+ svc = AgentChatService(AgentChatStore(":memory:"))+ session = svc.create_session(provider="fakeprov", cwd=str(tmp_path))+ q = svc.subscribe(session.session_id)+ asking = asyncio.create_task(+ svc._ask(session.session_id, "turn-1", "row-1", "Write", {}, "a.txt") # noqa: SLF001+ )+ opened = (await _drain(q, "approval_required"))[-1]["payload"]+ asking.cancel()+ await asyncio.gather(asking, return_exceptions=True)+ closed = (await _drain(q, "approval_resolved"))[-1]["payload"]+ assert closed["approval_id"] == opened["approval_id"]+ assert closed["decision"] == "cancel"+ assert not svc.resolve_approval(session.session_id, opened["approval_id"], "allow")++ asyncio.run(scenario())++def test_cancel_ends_the_turn(tmp_path: Path, scripted):ScriptedBrain.script = [[diff --git a/tests/unit/agent_chat/test_approval_bridge.py b/tests/unit/agent_chat/test_approval_bridge.pyindex 9f0f14ad55..30e8f51dd0 100644--- a/tests/unit/agent_chat/test_approval_bridge.py+++ b/tests/unit/agent_chat/test_approval_bridge.py@@ -14,7 +14,7 @@ from dodaios.agent_chat import folder_tools as ftfrom dodaios.agent_chat.approval_bridge import ChatApprovalBridge, ChatGrant, approval_reffrom dodaios.core.bus import EventBusfrom dodaios.core.config import SafetyConfig-from dodaios.core.events import ActionApprovalRequired, ActionDenied+from dodaios.core.events import ActionApprovalRequired, ActionApproved, ActionDeniedfrom dodaios.safety.approval import ApprovalWorkflowfrom dodaios.safety.risk_tier import RiskTierEvaluatorfrom dodaios.safety.tool_executor import APPROVAL_DENIED_PREFIX, ToolExecutor@@ -115,6 +115,94 @@ async def test_deny_on_the_card_yields_approval_denied(tmp_path: Path):assert denials and denials[-1].reason == "declined by the person"+class _OpenCard(_Card):+ """A card nobody clicks; records whether it was closed under it."""++ def __init__(self) -> None:+ super().__init__("allow")+ self.release.clear()+ self.closed = False++ async def __call__(self, call_id: str, name: str, args: dict[str, Any], summary: str) -> str:+ try:+ return await super().__call__(call_id, name, args, summary)+ except asyncio.CancelledError:+ self.closed = True+ raise+++def _approvals(bus: EventBus) -> list[ActionApproved]:+ seen: list[ActionApproved] = []++ async def _capture(event: ActionApproved) -> None:+ seen.append(event)++ bus.subscribe(ActionApproved, _capture)+ return seen+++async def test_an_expired_ticket_closes_its_card(tmp_path: Path):+ """A click after the executor gave up must not read as an approval."""+ executor, bridge, bus = _stack(timeout_s=0.05)+ approvals = _approvals(bus)+ card = _OpenCard()+ bridge.arm(REF, _grant(card, "ask"))+ write = ft.folder_tools(tmp_path)["Write"]++ result = await executor.execute(+ write, {"file_path": "a.txt", "content": "hi"}, config_snapshot=_snapshot(0.05)+ )+ await asyncio.sleep(0.01)++ assert not result.success and not (tmp_path / "a.txt").exists()+ assert card.asked and card.closed+ card.release.set()+ await asyncio.sleep(0.01)+ assert approvals == []+++async def test_a_ticket_answered_elsewhere_closes_its_card(tmp_path: Path):+ executor, bridge, bus = _stack()+ card = _OpenCard()+ bridge.arm(REF, _grant(card, "ask"))+ tickets: list[ActionApprovalRequired] = []++ async def _answer_elsewhere(event: ActionApprovalRequired) -> None:+ tickets.append(event)++ bus.subscribe(ActionApprovalRequired, _answer_elsewhere)+ write = ft.folder_tools(tmp_path)["Write"]+ running = asyncio.create_task(+ executor.execute(write, {"file_path": "b.txt", "content": "x"}, config_snapshot=_snapshot())+ )+ for _ in range(20):+ await asyncio.sleep(0)+ assert card.asked and tickets+ await bus.publish(+ ActionApproved(trace_id=tickets[0].trace_id, tool_name="Write", approved_by="user")+ )+ result = await asyncio.wait_for(running, timeout=5.0)+ await asyncio.sleep(0.01)++ assert result.success+ assert card.closed+++async def test_the_cards_own_answer_does_not_close_it_twice(tmp_path: Path):+ executor, bridge, bus = _stack()+ denials = _denials(bus)+ card = _Card("deny")+ bridge.arm(REF, _grant(card, "ask"))+ write = ft.folder_tools(tmp_path)["Write"]++ await executor.execute(+ write, {"file_path": "c.txt", "content": "x"}, config_snapshot=_snapshot()+ )++ assert [d.reason for d in denials][0] == "declined by the person"+ assert bridge._asking == {} # noqa: SLF001 - nothing left open++async def test_reads_never_ask(tmp_path: Path):(tmp_path / "r.txt").write_text("x", encoding="utf-8")executor, bridge, _ = _stack()diff --git a/tests/unit/society/test_chat_binding.py b/tests/unit/society/test_chat_binding.pyindex 335173ebed..ef35e2a426 100644--- a/tests/unit/society/test_chat_binding.py+++ b/tests/unit/society/test_chat_binding.py@@ -1037,9 +1037,13 @@ class FakeTurnService(FakeService):async def send(self, session_id: str, text: str, attachments=None, *, incoming=None) -> str:self.sent.append((session_id, text))+ # A sent turn runs until it finishes, as in the real service: the+ # watcher must not take a quiet but live turn for one that has ended.+ self.busy.add(session_id)return "turn-1"async def finish(self, session_id: str, text: str, *, status: str = "ok") -> None:+ self.busy.discard(session_id)for q in list(self.queues.get(session_id, [])):q.put_nowait({"kind": "assistant_text", "payload": {"turn_id": "turn-1", "text": text}})q.put_nowait(@@ -1197,6 +1201,49 @@ async def test_lost_subscriber_recovers_the_durable_turn_result(tmp_path: Path,await rt.close()+async def test_turn_that_ends_without_a_terminal_event_releases_the_slot(+ tmp_path: Path, monkeypatch+):+ import asyncio++ import dodaios.society.runtime as runtime_module+ from dodaios.agent_chat.events import make_event++ monkeypatch.setattr(runtime_module, "_WATCH_EVENT_POLL_SECONDS", 0.01)+ svc = FakeTurnService(AgentChatStore(tmp_path / "agent_chat.db"))+ cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path / "data")))+ rt = SocietyRuntime(+ tmp_path, seed_starter_team=False, chat_service=lambda: svc, cfg=lambda: cfg+ )+ await rt.ensure_started()+ try:+ await rt.roster.create(name="Scout", provider="openai")+ env = await rt.say(+ from_agent="user", to_agent="scout", text="Find the answer", msg_type=MsgType.ASSIGN+ )+ svc.busy.add("society:scout") # The turn is running...+ for q in svc.queues["society:scout"]:+ q.put_nowait(make_event("assistant_text", {"turn_id": "turn-1", "text": "Halfway."}))+ await asyncio.sleep(0.08)+ thread = await rt.store.events_for_trace(env.trace_id)+ assert thread[-1].msg_type is MsgType.CLAIM, "a live turn is waited for, however quiet"+ svc.busy.discard("society:scout") # ...and its task ends without turn_finished.+ for _ in range(50):+ thread = await rt.store.events_for_trace(env.trace_id)+ if thread[-1].msg_type is MsgType.RESULT:+ break+ await asyncio.sleep(0.01)+ else:+ pytest.fail("watcher kept waiting for a turn that no longer runs")+ assert thread[-1].payload["status"] == "blocked"+ assert thread[-1].payload["open"] == [+ "The agent's turn ended without reporting a result."+ ]+ assert rt.scheduler.running == {}+ finally:+ await rt.close()++async def test_durable_read_failure_releases_the_agent_slot(tmp_path: Path, monkeypatch):import asyncio