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(harness): order failure delivery before settlement
cyh7ed6c751d5a2
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.pyindex 004760b22..016d290cb 100644--- a/core/agent_auth_service.py+++ b/core/agent_auth_service.py@@ -982,22 +982,24 @@ class AgentAuthService:)durable_text = f"{error_text}\n\n{durable_prompt}"persist_errors: list[BaseException] = []- try:- from core.message_mirror import persist_agent_message+ target_platform = str(delivery_context.platform or "").strip()+ if target_platform == "avibe" or delivery.delivered_id is not None:+ try:+ from core.message_mirror import persist_agent_message- delivery.persisted_row = persist_agent_message(- delivery_context,- "notify",- durable_text,- error_sink=persist_errors,- )- except Exception as err:- delivery.error = err- delivery.error_stage = STAGE_PERSIST- logger.debug("auth recovery: failed to persist durable notify", exc_info=True)- if delivery.persisted_row is None and persist_errors:- delivery.error = persist_errors[0]- delivery.error_stage = STAGE_PERSIST+ delivery.persisted_row = persist_agent_message(+ delivery_context,+ "notify",+ durable_text,+ error_sink=persist_errors,+ )+ except Exception as err:+ delivery.error = err+ delivery.error_stage = STAGE_PERSIST+ logger.debug("auth recovery: failed to persist durable notify", exc_info=True)+ if delivery.persisted_row is None and persist_errors:+ delivery.error = persist_errors[0]+ delivery.error_stage = STAGE_PERSIST# Settle the failed turn through the outbound status chokepoint: a silent# terminal failure turns the dot red and releases the SSE waiter# without adding a second visible message (the recovery button above is thediff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex 98fee3210..f21caa2e1 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -815,6 +815,11 @@ class MessageHandler(BaseHandler):processing_indicator=processing_indicator,files=processed_files,)+ request.failure_handler = lambda error: self._emit_agent_dispatch_failure(+ context,+ request,+ error,+ )if processing_indicator is not None:self.controller.processing_indicator.apply_to_request(request, processing_indicator)try:@@ -868,15 +873,8 @@ class MessageHandler(BaseHandler):)except Exception as cleanup_err:logger.debug(f"Failed to clean up reaction on error: {cleanup_err}")- error_text = self.formatter.format_error(self._t("error.processMessageFailed", error=str(e)))- await emit_backend_failure(- self.controller,- context,- str(getattr(request, "vibe_agent_backend", None) or "agent"),- error_text,- display_text=error_text,- request=request,- )+ if not bool(getattr(request, "failure_handled", False)):+ await self._emit_agent_dispatch_failure(context, request, e)return str(e)finally:if not agent_dispatched:@@ -888,6 +886,26 @@ class MessageHandler(BaseHandler):if callable(mark_complete):mark_complete(context)+ async def _emit_agent_dispatch_failure(+ self,+ context: MessageContext,+ request: AgentRequest | None,+ error: BaseException,+ ) -> None:+ """Report one backend dispatch failure through the shared live boundary."""++ error_text = self.formatter.format_error(+ self._t("error.processMessageFailed", error=str(error))+ )+ await emit_backend_failure(+ self.controller,+ context,+ str(getattr(request, "vibe_agent_backend", None) or "agent"),+ error_text,+ display_text=error_text,+ request=request,+ )+async def _admit_human_delivery(self,*,diff --git a/modules/agents/base.py b/modules/agents/base.pyindex da5337490..8159ee030 100644--- a/modules/agents/base.py+++ b/modules/agents/base.py@@ -55,6 +55,11 @@ class AgentRequest:ack_reaction_emoji: Optional[str] = Nonetyping_indicator_active: bool = Falsetyping_indicator_task: Optional[Any] = None+ # The caller that owns user-facing failure copy can provide its reporter here.+ # AgentService invokes it before releasing the runtime Turn, so notification+ # delivery evidence and terminal settlement remain one ordered operation.+ failure_handler: Optional[Callable[[BaseException], Any]] = None+ failure_handled: bool = False# File attachments (downloaded or with URLs for download)files: Optional[List[FileAttachment]] = None# Internal stop diagnostics. Backend adapters set this when ``handle_stop``diff --git a/modules/agents/service.py b/modules/agents/service.pyindex f169c27b3..a25bbec0f 100644--- a/modules/agents/service.py+++ b/modules/agents/service.py@@ -411,29 +411,47 @@ class AgentService:if not scheduled:self.release_runtime_turn(request.context)raise- except Exception:- # The message handler converts backend exceptions into a terminal- # 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.+ except Exception as error:+ # The caller owns the user-facing failure copy. Invoke that shared+ # reporter while this runtime Turn is still current, so its notify+ # receipt is part of the terminal failure contract before the gate is+ # released. Direct AgentService callers without a reporter retain the+ # silent terminal fallback below.try:- emit = getattr(self.controller, "emit_agent_message", None)- if callable(emit):+ failure_handler = getattr(request, "failure_handler", None)+ if callable(failure_handler):+ request.failure_handled = Truetry:- await emit(- request.context,- "result",- "",- is_error=True,- level="silent",- output=terminal_output_for(request),- )+ handled = failure_handler(error)+ if inspect.isawaitable(handled):+ await handledexcept Exception:- logger.debug("Failed to emit terminal result for backend exception", exc_info=True)+ logger.exception("Failed to report backend exception before Turn release")+ await self._emit_exception_terminal_fallback(request)+ else:+ await self._emit_exception_terminal_fallback(request)finally:self.release_runtime_turn(request.context)raise+ async def _emit_exception_terminal_fallback(self, request: AgentRequest) -> None:+ """Best-effort settlement for callers without a visible failure owner."""++ emit = getattr(self.controller, "emit_agent_message", None)+ if not callable(emit):+ return+ try:+ await emit(+ request.context,+ "result",+ "",+ is_error=True,+ level="silent",+ output=terminal_output_for(request),+ )+ except Exception:+ logger.debug("Failed to emit terminal result for backend exception", exc_info=True)+async def clear_sessions(self, session_key: str) -> Dict[str, int]:cleared: Dict[str, int] = {}for name in list(self.agents.keys()):diff --git a/tests/test_agent_auth_service.py b/tests/test_agent_auth_service.pyindex bea96ea98..1b00b1bdb 100644--- a/tests/test_agent_auth_service.py+++ b/tests/test_agent_auth_service.py@@ -274,6 +274,78 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsyn},)+ async def test_auth_recovery_does_not_persist_an_undelivered_external_message(self):+ controller = _StubController()+ service = AgentAuthService(controller)+ service._send_message_with_button = AsyncMock(return_value=None)+ context = MessageContext(+ user_id="U1",+ channel_id="C1",+ platform="slack",+ platform_specific={+ "turn_token": "turn-auth-undelivered",+ "task_execution_id": "run-auth-undelivered",+ },+ )++ with patch(+ "core.message_mirror.persist_agent_message",+ return_value={"id": "message-auth-undelivered"},+ ) as persist:+ handled = await service.maybe_emit_auth_recovery_message(+ context,+ "codex",+ "Codex error: 401 Unauthorized",+ )++ self.assertTrue(handled)+ persist.assert_not_called()+ terminal_output = controller.emit_agent_message.await_args.kwargs["output"]+ self.assertEqual(+ terminal_output.metadata["turn_failure_notification"],+ {+ "failure_id": "turn:turn-auth-undelivered",+ "ack_evidence": None,+ "delivered": False,+ },+ )++ async def test_auth_recovery_keeps_local_persistence_without_a_send_id(self):+ controller = _StubController()+ service = AgentAuthService(controller)+ service._send_message_with_button = AsyncMock(return_value=None)+ context = MessageContext(+ user_id="U1",+ channel_id="ses-local",+ platform="avibe",+ platform_specific={+ "turn_token": "turn-auth-local",+ "task_execution_id": "run-auth-local",+ },+ )++ with patch(+ "core.message_mirror.persist_agent_message",+ return_value={"id": "message-auth-local"},+ ) as persist:+ handled = await service.maybe_emit_auth_recovery_message(+ context,+ "codex",+ "Codex error: 401 Unauthorized",+ )++ self.assertTrue(handled)+ persist.assert_called_once()+ terminal_output = controller.emit_agent_message.await_args.kwargs["output"]+ self.assertEqual(+ terminal_output.metadata["turn_failure_notification"],+ {+ "failure_id": "turn:turn-auth-local",+ "ack_evidence": "receipt",+ "delivered": True,+ },+ )+async def test_auth_recovery_sends_and_persists_to_delivery_override(self):controller = _StubController()source_client = controller.im_clientdiff --git a/tests/test_agent_service.py b/tests/test_agent_service.pyindex 74b69ee13..1df8a3924 100644--- a/tests/test_agent_service.py+++ b/tests/test_agent_service.py@@ -1425,6 +1425,68 @@ def test_agent_service_releases_gate_when_exception_terminal_emit_fails() -> Nonasyncio.run(_run())+def test_agent_service_reports_backend_failure_before_releasing_runtime_turn() -> None:+ """A caller-owned failure receipt must reach settlement before Turn release."""++ async def _run() -> None:+ from core.backend_failure import emit_backend_failure++ controller = _Controller()+ service = AgentService(controller=controller)+ controller.agent_service = service+ service.register(_RaisingRuntimeAgent())+ request = _request("boom")+ request.context.platform = "slack"+ request.context.platform_specific = {+ "turn_token": "turn-backend-failure",+ "task_execution_id": "run-backend-failure",+ "task_trigger_kind": "watch",+ }+ emitted: list[tuple[str, object, str]] = []++ async def _emit(_context, message_type, _text, **kwargs):+ gate = service._turn_gates["session:/repo"]+ emitted.append((message_type, kwargs.get("output"), gate.token))+ delivery = kwargs.get("delivery")+ if message_type == "notify" and delivery is not None:+ delivery.send_returned = True+ delivery.delivered_id = "slack-message-1"+ return delivery.delivered_id+ return None++ async def _report(error: BaseException) -> None:+ await emit_backend_failure(+ controller,+ request.context,+ "claude",+ str(error),+ display_text=f"Error: {error}",+ request=request,+ )++ controller.emit_agent_message = _emit+ request.failure_handler = _report++ with pytest.raises(RuntimeError, match="backend failed"):+ await service.handle_message("claude", request)++ assert [message_type for message_type, _output, _token in emitted] == [+ "notify",+ "result",+ ]+ terminal = emitted[-1][1]+ assert terminal.metadata["turn_failure_notification"] == {+ "failure_id": "turn:turn-backend-failure",+ "ack_evidence": "delivery_only",+ "delivered": True,+ }+ assert all(token for _message_type, _output, token in emitted)+ assert request.failure_handled is True+ assert not service._turn_gates["session:/repo"].lock.locked()++ asyncio.run(_run())++def test_agent_service_recovers_accepted_turn_when_owned_backend_dies() -> None:"""A dead accepted backend must release the runtime FIFO without a timeout."""