Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(agents): settle runtime gates after terminal cleanup
cyha60052281c66
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.pyindex 82c6858e3..f64d63f98 100644--- a/core/message_dispatcher.py+++ b/core/message_dispatcher.py@@ -501,12 +501,11 @@ class ConsolidatedMessageDispatcher:return None# Settle the avibe dot for the ACTIVE turn's terminal result (idle, or# failed on is_error) via the turn owner, which applies the active-turn- # guard + skips non-avibe contexts. ``getattr`` keeps it a no-op for stub- # controllers without the owner.+ # guard + skips non-avibe contexts. Runtime gate release happens after+ # the result path clears/persists/streams its own state.manager = getattr(self.controller, "session_turns", None)if manager is not None:manager.on_terminal_result(context, is_error=is_error)- self._release_runtime_turn(context)text = strip_silent_blocks(text)# ``level="silent"`` is the explicit visibility control (orthogonal to type):# the message already settled the dot above (for a terminal result), so here@@ -514,19 +513,23 @@ class ConsolidatedMessageDispatcher:# streaming — no user-facing bubble, regardless of body. An empty/stripped# body (e.g. a ``<silent>`` directive reduced to nothing) is silent too.if level == "silent" or not text or not text.strip():- if canonical_type == "result":- # A terminal result — even silent/empty — still means the turn- # finished: release the streaming SSE waiter so it closes now- # instead of hanging until the safety timeout, with no visible chunk.- await self._clear_consolidated_state(context)- self._record_agent_run_terminal_result(- context,- text,- None,- is_error=is_error,- )- self._signal_turn_complete(context)- return None+ try:+ if canonical_type == "result":+ # A terminal result — even silent/empty — still means the turn+ # finished: release the streaming SSE waiter so it closes now+ # instead of hanging until the safety timeout, with no visible chunk.+ await self._clear_consolidated_state(context)+ self._record_agent_run_terminal_result(+ context,+ text,+ None,+ is_error=is_error,+ )+ self._signal_turn_complete(context)+ return None+ finally:+ if canonical_type == "result":+ self._release_runtime_turn(context)# Resolve the delivery target once. Routed / post_to / thread replies# land in a different channel than the source context, and the persisted@@ -559,24 +562,28 @@ class ConsolidatedMessageDispatcher:persists_without_delivery = target_context.platform == "avibe"if (context.platform_specific or {}).get("suppress_delivery"):- message_id = f"suppressed:{(context.platform_specific or {}).get('task_execution_id') or canonical_type}"- terminal_status = None- if (- canonical_type == "result"- and (context.platform_specific or {}).get("task_trigger_kind") == "agent_run"- ):- terminal_status = "failed" if is_error else "succeeded"- if canonical_type == "result" or (context.platform_specific or {}).get("task_trigger_kind") != "agent_run":- self._record_suppressed_run_message(- context,- text,- message_id,- terminal_status=terminal_status,- )- if canonical_type == "result":- await self._clear_consolidated_state(context)- self._signal_turn_complete(context)- return message_id+ try:+ message_id = f"suppressed:{(context.platform_specific or {}).get('task_execution_id') or canonical_type}"+ terminal_status = None+ if (+ canonical_type == "result"+ and (context.platform_specific or {}).get("task_trigger_kind") == "agent_run"+ ):+ terminal_status = "failed" if is_error else "succeeded"+ if canonical_type == "result" or (context.platform_specific or {}).get("task_trigger_kind") != "agent_run":+ self._record_suppressed_run_message(+ context,+ text,+ message_id,+ terminal_status=terminal_status,+ )+ if canonical_type == "result":+ await self._clear_consolidated_state(context)+ self._signal_turn_complete(context)+ return message_id+ finally:+ if canonical_type == "result":+ self._release_runtime_turn(context)if canonical_type == "notify":try:@@ -593,105 +600,38 @@ class ConsolidatedMessageDispatcher:return Noneif canonical_type == "result":- primary_message_id: Optional[str] = None- scheduled_anchor_message_id: Optional[str] = None- delivered_as_attachment = False-- # ``enhanced`` (extracted file links + quick-reply buttons) was- # computed above for persistence; reuse it for delivery.- display_text = enhanced.text if enhanced.text.strip() else text+ try:+ primary_message_id: Optional[str] = None+ scheduled_anchor_message_id: Optional[str] = None+ delivered_as_attachment = False- if self._result_within_limit(context, display_text):- try:- primary_message_id = await self._send_result_inline(- im_client,- target_context,- display_text,- enhanced.buttons if enhanced else [],- parse_mode,- )- scheduled_anchor_message_id = primary_message_id- except Exception as err:- if enhanced and enhanced.buttons and self._supports_quick_replies(context):- logger.warning("Failed to send result with quick replies, falling back: %s", err)- try:- primary_message_id = await im_client.send_message(- target_context, display_text, parse_mode=parse_mode- )- scheduled_anchor_message_id = primary_message_id- except Exception as fallback_err:- logger.error("Failed to send fallback result message: %s", fallback_err)- else:- logger.error("Failed to send result message: %s", err)- elif self._should_split_long_result(context):- try:- primary_message_id = await self._send_split_result_messages(- im_client,- target_context,- display_text,- enhanced.buttons if enhanced else [],- parse_mode,- )- scheduled_anchor_message_id = primary_message_id- except Exception as err:- logger.error("Failed to send split result messages: %s", err)- else:- summary = self._build_result_summary(display_text, self._get_result_max_chars(context))- try:- primary_message_id = await im_client.send_message(target_context, summary, parse_mode=parse_mode)- scheduled_anchor_message_id = primary_message_id- except Exception as err:- logger.error("Failed to send result summary: %s", err)+ # ``enhanced`` (extracted file links + quick-reply buttons) was+ # computed above for persistence; reuse it for delivery.+ display_text = enhanced.text if enhanced.text.strip() else text- if (- context.platform- or (context.platform_specific or {}).get("platform")- or self.controller.config.platform- ) in {"slack", "discord", "telegram", "lark"} and hasattr(im_client, "upload_markdown"):+ if self._result_within_limit(context, display_text):try:- attachment_message_id = await im_client.upload_markdown(+ primary_message_id = await self._send_result_inline(+ im_client,target_context,- title="result.md",- content=display_text,- filetype="markdown",+ display_text,+ enhanced.buttons if enhanced else [],+ parse_mode,)- if primary_message_id is None:- primary_message_id = attachment_message_id- delivered_as_attachment = True- if self._attachment_id_can_anchor_delivery(context):- scheduled_anchor_message_id = attachment_message_id+ scheduled_anchor_message_id = primary_message_idexcept Exception as err:- logger.warning(f"Failed to upload result attachment: {err}")- await im_client.send_message(- target_context,- self._t("error.resultAttachmentUploadFailed"),- parse_mode=parse_mode,- )-- # --- Fallback: card content rejected (e.g. table over limit) ---- if primary_message_id is None and display_text:- logger.warning("All direct result sends failed; attempting fallback delivery")- file_uploaded = False-- # Fallback 1: upload full content as .md file.- if hasattr(im_client, "upload_markdown"):- try:- primary_message_id = await im_client.upload_markdown(- target_context,- title="result.md",- content=display_text,- filetype="markdown",- )- file_uploaded = True- delivered_as_attachment = True- if self._attachment_id_can_anchor_delivery(context):- scheduled_anchor_message_id = primary_message_id- logger.info("Result delivered as .md file attachment (fallback)")- except Exception as upload_err:- logger.warning("upload_markdown fallback failed: %s", upload_err)-- # Fallback 2: split into multiple messages.- if not file_uploaded:+ if enhanced and enhanced.buttons and self._supports_quick_replies(context):+ logger.warning("Failed to send result with quick replies, falling back: %s", err)+ try:+ primary_message_id = await im_client.send_message(+ target_context, display_text, parse_mode=parse_mode+ )+ scheduled_anchor_message_id = primary_message_id+ except Exception as fallback_err:+ logger.error("Failed to send fallback result message: %s", fallback_err)+ else:+ logger.error("Failed to send result message: %s", err)+ elif self._should_split_long_result(context):try:primary_message_id = await self._send_split_result_messages(im_client,@@ -701,88 +641,158 @@ class ConsolidatedMessageDispatcher:parse_mode,)scheduled_anchor_message_id = primary_message_id- logger.info("Result delivered via split messages (fallback)")- except Exception as split_err:- logger.error("Split message fallback also failed: %s", split_err)-- # Explain attachment-only delivery or total failure once all attempts settle.- try:- if delivered_as_attachment:- notice = self._t("info.resultDeliveredAsAttachment")- elif primary_message_id is None and display_text:- notice = self._t("error.resultDeliveryFailed")+ except Exception as err:+ logger.error("Failed to send split result messages: %s", err)else:- notice = None- if notice:- await im_client.send_message(target_context, notice, parse_mode="markdown")- except Exception:- logger.error("Failed to send delivery status notification")+ summary = self._build_result_summary(display_text, self._get_result_max_chars(context))+ try:+ primary_message_id = await im_client.send_message(target_context, summary, parse_mode=parse_mode)+ scheduled_anchor_message_id = primary_message_id+ except Exception as err:+ logger.error("Failed to send result summary: %s", err)++ if (+ context.platform+ or (context.platform_specific or {}).get("platform")+ or self.controller.config.platform+ ) in {"slack", "discord", "telegram", "lark"} and hasattr(im_client, "upload_markdown"):+ try:+ attachment_message_id = await im_client.upload_markdown(+ target_context,+ title="result.md",+ content=display_text,+ filetype="markdown",+ )+ if primary_message_id is None:+ primary_message_id = attachment_message_id+ delivered_as_attachment = True+ if self._attachment_id_can_anchor_delivery(context):+ scheduled_anchor_message_id = attachment_message_id+ except Exception as err:+ logger.warning(f"Failed to upload result attachment: {err}")+ await im_client.send_message(+ target_context,+ self._t("error.resultAttachmentUploadFailed"),+ parse_mode=parse_mode,+ )++ # --- Fallback: card content rejected (e.g. table over limit) ---+ if primary_message_id is None and display_text:+ logger.warning("All direct result sends failed; attempting fallback delivery")+ file_uploaded = False- # Upload extracted file attachments- if enhanced and enhanced.files:- await self._upload_file_links(im_client, target_context, enhanced.files)+ # Fallback 1: upload full content as .md file.+ if hasattr(im_client, "upload_markdown"):+ try:+ primary_message_id = await im_client.upload_markdown(+ target_context,+ title="result.md",+ content=display_text,+ filetype="markdown",+ )+ file_uploaded = True+ delivered_as_attachment = True+ if self._attachment_id_can_anchor_delivery(context):+ scheduled_anchor_message_id = primary_message_id+ logger.info("Result delivered as .md file attachment (fallback)")+ except Exception as upload_err:+ logger.warning("upload_markdown fallback failed: %s", upload_err)++ # Fallback 2: split into multiple messages.+ if not file_uploaded:+ try:+ primary_message_id = await self._send_split_result_messages(+ im_client,+ target_context,+ display_text,+ enhanced.buttons if enhanced else [],+ parse_mode,+ )+ scheduled_anchor_message_id = primary_message_id+ logger.info("Result delivered via split messages (fallback)")+ except Exception as split_err:+ logger.error("Split message fallback also failed: %s", split_err)- if scheduled_anchor_message_id:+ # Explain attachment-only delivery or total failure once all attempts settle.try:- self.controller.session_handler.finalize_scheduled_delivery(context, scheduled_anchor_message_id)- except Exception as err:- logger.warning("Failed to finalize scheduled delivery anchor: %s", err)+ if delivered_as_attachment:+ notice = self._t("info.resultDeliveredAsAttachment")+ elif primary_message_id is None and display_text:+ notice = self._t("error.resultDeliveryFailed")+ else:+ notice = None+ if notice:+ await im_client.send_message(target_context, notice, parse_mode="markdown")+ except Exception:+ logger.error("Failed to send delivery status notification")- # Final result closes the current turn: clear consolidated- # assistant/tool/system message state so the next user turn starts- # a fresh log message instead of appending to the previous one.- await self._clear_consolidated_state(context)+ # Upload extracted file attachments+ if enhanced and enhanced.files:+ await self._upload_file_links(im_client, target_context, enhanced.files)- self._record_agent_run_terminal_result(- context,- display_text,- primary_message_id,- is_error=is_error,- )+ if scheduled_anchor_message_id:+ try:+ self.controller.session_handler.finalize_scheduled_delivery(context, scheduled_anchor_message_id)+ except Exception as err:+ logger.warning("Failed to finalize scheduled delivery anchor: %s", err)- # Persist the delivered result (cleaned text == what was shown).- # avibe always persists (SSE is its delivery); for IM a result that- # failed every send/upload (primary_message_id is None) is NOT- # recorded, matching the old outbound mirror's success-only rule.- if persists_without_delivery or primary_message_id is not None:- # A failed terminal result persists as type='error' so it shows in- # the transcript/inbox like any terminal message but is NOT counted- # as an unread agent reply (unread queries are result-only). Codex P2.- result_type = "error" if is_error else "result"- if target_context.platform == "avibe":- # Keep the ``file://`` links in the persisted avibe text so the- # workbench media-proxy rewrite (in ``persist_agent_message``)- # can turn them into inline images / file cards. ``persist_text``- # already has them stripped to plain labels for IM delivery.- # Also carry the parsed quick-reply labels so the workbench can- # render the button group (IM channels render native buttons- # from the same ``enhanced.buttons``).- avibe_enhanced = process_reply(- text, include_quick_replies=quick_replies_on, keep_file_links=True- )- avibe_text = avibe_enhanced.text or persist_text- persist_agent_message(- target_context,- result_type,- avibe_text,- quick_replies=[b.text for b in avibe_enhanced.buttons] or None,- )- else:- persist_agent_message(target_context, result_type, persist_text)+ # Final result closes the current turn: clear consolidated+ # assistant/tool/system message state so the next user turn starts+ # a fresh log message instead of appending to the previous one.+ await self._clear_consolidated_state(context)- if primary_message_id and display_text:- # Stream the delivered result to live consumers (avibe SSE).- await _stream_chunk(- self.controller, context, text=display_text, message_id=primary_message_id, kind="result"+ self._record_agent_run_terminal_result(+ context,+ display_text,+ primary_message_id,+ is_error=is_error,)- else:- # A terminal result still completes the turn even if every IM- # delivery path failed and therefore produced no durable message id.- # Without this release, direct agent_run and avibe turn waiters keep- # waiting forever despite the backend having already finished.- self._signal_turn_complete(context)-- return primary_message_id++ # Persist the delivered result (cleaned text == what was shown).+ # avibe always persists (SSE is its delivery); for IM a result that+ # failed every send/upload (primary_message_id is None) is NOT+ # recorded, matching the old outbound mirror's success-only rule.+ if persists_without_delivery or primary_message_id is not None:+ # A failed terminal result persists as type='error' so it shows in+ # the transcript/inbox like any terminal message but is NOT counted+ # as an unread agent reply (unread queries are result-only). Codex P2.+ result_type = "error" if is_error else "result"+ if target_context.platform == "avibe":+ # Keep the ``file://`` links in the persisted avibe text so the+ # workbench media-proxy rewrite (in ``persist_agent_message``)+ # can turn them into inline images / file cards. ``persist_text``+ # already has them stripped to plain labels for IM delivery.+ # Also carry the parsed quick-reply labels so the workbench can+ # render the button group (IM channels render native buttons+ # from the same ``enhanced.buttons``).+ avibe_enhanced = process_reply(+ text, include_quick_replies=quick_replies_on, keep_file_links=True+ )+ avibe_text = avibe_enhanced.text or persist_text+ persist_agent_message(+ target_context,+ result_type,+ avibe_text,+ quick_replies=[b.text for b in avibe_enhanced.buttons] or None,+ )+ else:+ persist_agent_message(target_context, result_type, persist_text)++ if primary_message_id and display_text:+ # Stream the delivered result to live consumers (avibe SSE).+ await _stream_chunk(+ self.controller, context, text=display_text, message_id=primary_message_id, kind="result"+ )+ else:+ # A terminal result still completes the turn even if every IM+ # delivery path failed and therefore produced no durable message id.+ # Without this release, direct agent_run and avibe turn waiters keep+ # waiting forever despite the backend having already finished.+ self._signal_turn_complete(context)++ return primary_message_id+ finally:+ self._release_runtime_turn(context)if canonical_type not in {"system", "assistant", "toolcall"}:canonical_type = "assistant"diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.pyindex 4237566bb..7f7a7be37 100644--- a/modules/agents/claude_agent.py+++ b/modules/agents/claude_agent.py@@ -758,20 +758,13 @@ class ClaudeAgent(BaseAgent):returnpending_request = pending_requests[0]- context_token = str((getattr(context, "platform_specific", None) or {}).get(AGENT_RUNTIME_TURN_TOKEN) or "")pending_token = str((getattr(getattr(pending_request, "context", None), "platform_specific", None) or {}).get(AGENT_RUNTIME_TURN_TOKEN)or "")- if not context_token or not pending_token:- return- if context_token and pending_token and context_token != pending_token:- logger.info(- "Ignoring Claude receiver EOF for %s because a newer runtime turn is pending",- composite_key,- )+ if not pending_token:returnlogger.warning("Claude receiver ended without a result for session %s", composite_key)self._adopt_pending_turn_token(context, pending_request)diff --git a/modules/agents/service.py b/modules/agents/service.pyindex d1305a181..2a5700787 100644--- a/modules/agents/service.py+++ b/modules/agents/service.py@@ -57,9 +57,18 @@ class AgentService:raiseexcept Exception:# The message handler converts backend exceptions into a terminal- # error result using the same context. Keep the gate current so that- # result is delivered and releases the runtime turn through the- # shared dispatcher path.+ # error result using the same context. Try that shared terminal path+ # here too; if delivery itself is broken, the finally below still+ # releases this turn's token so later prompts cannot hang forever.+ try:+ emit = getattr(self.controller, "emit_agent_message", None)+ if callable(emit):+ try:+ await emit(request.context, "result", "", is_error=True, level="silent")+ except Exception:+ logger.debug("Failed to emit terminal result for backend exception", exc_info=True)+ finally:+ self.release_runtime_turn(request.context)raiseasync def clear_sessions(self, session_key: str) -> Dict[str, int]:diff --git a/tests/test_agent_service.py b/tests/test_agent_service.pyindex 925d81c5b..22111d9e5 100644--- a/tests/test_agent_service.py+++ b/tests/test_agent_service.py@@ -29,6 +29,11 @@ class _RuntimeAgent:return False+class _RaisingRuntimeAgent(_RuntimeAgent):+ async def handle_message(self, _request):+ raise RuntimeError("backend failed")++class _ClearingRuntimeAgent:name = "codex"@@ -194,3 +199,28 @@ def test_agent_service_clear_sessions_does_not_release_new_turn_token() -> None:service.release_runtime_turn_key(runtime_key, "new-token")asyncio.run(_run())+++def test_agent_service_releases_gate_when_exception_terminal_emit_fails() -> None:+ async def _run():+ controller = _Controller()++ async def _emit(*_args, **_kwargs):+ raise RuntimeError("send failed")++ controller.emit_agent_message = _emit+ service = AgentService(controller=controller)+ agent = _RaisingRuntimeAgent()+ service.register(agent)+ request = _request("boom")++ try:+ await service.handle_message("claude", request)+ except RuntimeError as err:+ assert str(err) == "backend failed"+ else:+ raise AssertionError("backend exception should escape")++ assert not service._turn_gates["session:/repo"].lock.locked()++ asyncio.run(_run())diff --git a/tests/test_claude_agent_sessions.py b/tests/test_claude_agent_sessions.pyindex 06f76b6a3..f2c19969c 100644--- a/tests/test_claude_agent_sessions.py+++ b/tests/test_claude_agent_sessions.py@@ -1443,6 +1443,71 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):self.assertNotIn(composite_key, controller.claude_sessions)self.assertNotIn(composite_key, agent._pending_requests)+ async def test_receiver_eof_adopts_pending_turn_token_when_context_is_stale(self):+ controller = _StubController()+ controller._get_session_key = lambda context: "telegram::user::U1"+ agent = ClaudeAgent(controller)+ service = AgentService(controller)+ service.register(agent)+ controller.agent_service = service++ async def _emit(context, message_type, text, **_kwargs):+ if message_type == "result":+ service.release_runtime_turn(context)++ controller.emit_agent_message = AsyncMock(side_effect=_emit)+ composite_key = "session-1:/tmp/work"+ context = SimpleNamespace(+ user_id="U1",+ channel_id="C1",+ platform_specific={+ "turn_token": "old-turn",+ "agent_runtime_turn_key": composite_key,+ "agent_runtime_turn_token": "old-runtime",+ },+ )+ pending_request = SimpleNamespace(+ context=SimpleNamespace(+ platform_specific={+ "turn_token": "current-turn",+ "agent_runtime_turn_key": composite_key,+ "agent_runtime_turn_token": "current-runtime",+ }+ ),+ ack_reaction_message_id=None,+ ack_reaction_emoji=None,+ )+ agent._pending_requests[composite_key] = [pending_request]+ gate = service._get_turn_gate(composite_key)+ await gate.lock.acquire()+ gate.token = "current-runtime"++ class _Client:+ async def disconnect(self):+ return None++ def receive_messages(self):+ async def _iterate():+ if False:+ yield None++ return _iterate()++ client = _Client()+ controller.claude_sessions[composite_key] = client+ receiver_task = asyncio.create_task(+ agent._receive_messages(client, "session-1", "/tmp/work", context, composite_key=composite_key)+ )+ controller.receiver_tasks[composite_key] = receiver_task++ await asyncio.wait_for(receiver_task, timeout=1)++ controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True)+ self.assertEqual(context.platform_specific["turn_token"], "current-turn")+ self.assertEqual(context.platform_specific["agent_runtime_turn_token"], "current-runtime")+ self.assertFalse(service._turn_gates[composite_key].lock.locked())+ self.assertNotIn(composite_key, agent._pending_requests)+async def test_assistant_auth_error_prefers_oauth_recovery_message(self):controller = _StubController()controller.agent_auth_service.maybe_emit_auth_recovery_message = AsyncMock(return_value=True)diff --git a/tests/test_message_dispatcher_result_fallback.py b/tests/test_message_dispatcher_result_fallback.pyindex d73eb65f7..002172a95 100644--- a/tests/test_message_dispatcher_result_fallback.py+++ b/tests/test_message_dispatcher_result_fallback.py@@ -272,6 +272,38 @@ class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(controller.im_client.sent_messages, [])persist.assert_not_called()+ async def test_result_releases_runtime_gate_after_result_cleanup(self):+ controller = _StubController(platform="slack")+ events = []++ class _AgentService:+ @staticmethod+ def emit_matches_runtime_turn(_context):+ return True++ @staticmethod+ def release_runtime_turn(_context):+ events.append("release")++ controller.agent_service = _AgentService()+ dispatcher = ConsolidatedMessageDispatcher(controller)++ async def _clear_consolidated_state(_context):+ events.append("clear")++ dispatcher._clear_consolidated_state = _clear_consolidated_state+ context = MessageContext(+ user_id="U1",+ channel_id="C1",+ platform="slack",+ platform_specific={"agent_runtime_turn_key": "s:/repo", "agent_runtime_turn_token": "tok"},+ )++ with mock.patch("core.message_dispatcher.persist_agent_message"):+ await dispatcher.emit_agent_message(context, "result", "done")++ self.assertEqual(events, ["clear", "release"])+async def test_muted_log_message_still_persists(self):"""assistant / tool_call rows persist BEFORE the mute filter, so a mutedprocess log still lands in the store (product requirement)."""