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): unify Turn failure delivery evidence
cyh3bce000ab01a
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.pyindex 91fc2488a..449edc8d7 100644--- a/core/agent_auth_service.py+++ b/core/agent_auth_service.py@@ -14,6 +14,10 @@ import uuidfrom dataclasses import dataclass, fieldfrom typing import Any, Callable, Optional+from core.backend_failure import terminal_backend_failure_output+from core.delivery_evidence import DeliveryEvidence, STAGE_PERSIST, STAGE_SEND+from core.message_output import MessageOutput, terminal_turn_output+from core.resource_governance import governor_from_controllerfrom modules.claude_sdk_compat import (CLAUDE_SDK_AVAILABLE,CLAUDE_SDK_MAX_BUFFER_SIZE,@@ -38,8 +42,6 @@ from modules.agents.opencode.utils import (resolve_opencode_reasoning_effort,)from modules.im import InlineButton, InlineKeyboard, MessageContext-from core.resource_governance import governor_from_controller-from core.message_output import MessageOutput, terminal_turn_outputfrom vibe.i18n import t as i18n_tfrom vibe.opencode_config import remove_opencode_provider_api_key@@ -938,17 +940,25 @@ class AgentAuthService:backend == "codex"and getattr(backend_config, "auth_mode", None) == "api_key")- if uses_codex_api_key:- recovery_text = f"{error_text}\n\n{self._t('command.setup.apiKeyRecoveryPrompt', backend=backend)}"- await self._send_message(context, recovery_text)- else:- recovery_text = f"{error_text}\n\n{self._t('command.setup.resetPrompt', backend=backend)}"- await self._send_message_with_button(- context,- recovery_text,- button_text=self._t("button.resetOAuth"),- callback_data=f"auth_setup:{backend}",- )+ delivery = DeliveryEvidence()+ try:+ if uses_codex_api_key:+ recovery_text = f"{error_text}\n\n{self._t('command.setup.apiKeyRecoveryPrompt', backend=backend)}"+ delivered_id = await self._send_message(context, recovery_text)+ else:+ recovery_text = f"{error_text}\n\n{self._t('command.setup.resetPrompt', backend=backend)}"+ delivered_id = await self._send_message_with_button(+ context,+ recovery_text,+ button_text=self._t("button.resetOAuth"),+ callback_data=f"auth_setup:{backend}",+ )+ except Exception as err:+ delivery.error = err+ delivery.error_stage = STAGE_SEND+ raise+ delivery.send_returned = True+ delivery.delivered_id = str(delivered_id) if delivered_id is not None else None# Transport sends are not durable ``messages`` rows, and the web Chat# renders only durable rows. Persist the recovery text here, the single# home for it, rather than letting each backend store an error-only copy@@ -966,12 +976,23 @@ class AgentAuthService:else self._t("command.setup.resetPromptPlain", backend=backend))durable_text = f"{error_text}\n\n{durable_prompt}"+ persist_errors: list[BaseException] = []try:from core.message_mirror import persist_agent_message- persist_agent_message(context, "notify", durable_text)- except Exception:+ delivery.persisted_row = persist_agent_message(+ context,+ "notify",+ durable_text,+ error_sink=persist_errors,+ )+ except Exception as err:+ delivery.error = err+ delivery.error_stage = STAGE_PERSISTlogger.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 the@@ -983,7 +1004,11 @@ class AgentAuthService:"",is_error=True,level="silent",- output=output or terminal_turn_output(),+ output=terminal_backend_failure_output(+ context,+ output=output or terminal_turn_output(),+ delivery=delivery,+ ),terminal_error=terminal_error or error_text,)except Exception:diff --git a/core/backend_failure.py b/core/backend_failure.pyindex 010b48988..cc56546d8 100644--- a/core/backend_failure.py+++ b/core/backend_failure.py@@ -164,6 +164,84 @@ def backend_failure_notification_output()+def _target_delivery_platform(context: Any) -> str:+ platform_specific = getattr(context, "platform_specific", None) or {}+ delivery_override = (+ platform_specific.get("delivery_override")+ if isinstance(platform_specific, dict)+ else None+ )+ return str(+ (+ delivery_override.get("platform")+ if isinstance(delivery_override, dict)+ else None+ )+ or getattr(context, "platform", "")+ or ""+ ).strip()+++def _acknowledges_target(+ context: Any,+ evidence: str | None,+) -> bool:+ if evidence == ACK_EVIDENCE_RECEIPT:+ return True+ return (+ evidence == ACK_EVIDENCE_DELIVERY_ONLY+ and _target_delivery_platform(context) != "avibe"+ )+++def terminal_backend_failure_output(+ context: Any,+ *,+ request: Any = None,+ output: MessageOutput | None = None,+ failure_id: str | None = None,+ delivery: DeliveryEvidence | None = None,+) -> MessageOutput:+ """Attach one monotonic Turn failure-delivery contract to a terminal output.++ Some failures use the ordinary ``notify`` dispatcher while others need a+ specialized visible path, such as an OAuth recovery button. Both must settle+ with the same evidence contract or a later Harness Run cannot distinguish an+ error the user already saw from an error that still needs a fallback notice.+ """++ terminal = _terminal_output(request, output)+ if not (_turn_failure_identity(context, request) or _harness_run_identity(context, request)):+ return terminal++ metadata = dict(terminal.metadata)+ existing = metadata.get("turn_failure_notification")+ existing_notification = dict(existing) if isinstance(existing, dict) else {}+ identity = str(existing_notification.get("failure_id") or "").strip()+ if not identity:+ identity = _failure_identity(context, request, failure_id)++ incoming_ack = delivery.ack_evidence if delivery is not None else None+ existing_ack = str(existing_notification.get("ack_evidence") or "").strip() or None+ ack_priority = {None: 0, ACK_EVIDENCE_DELIVERY_ONLY: 1, ACK_EVIDENCE_RECEIPT: 2}+ ack_evidence = (+ incoming_ack+ if ack_priority.get(incoming_ack, 1 if incoming_ack else 0)+ > ack_priority.get(existing_ack, 1 if existing_ack else 0)+ else existing_ack+ )+ existing_notification.update(+ {+ "failure_id": identity,+ "ack_evidence": ack_evidence,+ "delivered": bool(existing_notification.get("delivered"))+ or _acknowledges_target(context, ack_evidence),+ }+ )+ metadata["turn_failure_notification"] = existing_notification+ return replace(terminal, metadata=metadata)++async def emit_replayed_backend_failure(controller: Any,context: Any,@@ -282,43 +360,14 @@ async def emit_backend_failure(if owns_failure_contract and live_delivery is None:live_delivery = DeliveryEvidence()- platform_specific = getattr(context, "platform_specific", None) or {}- delivery_override = (- platform_specific.get("delivery_override")- if isinstance(platform_specific, dict)- else None- )- target_platform = str(- (- delivery_override.get("platform")- if isinstance(delivery_override, dict)- else None- )- or getattr(context, "platform", "")- or ""- ).strip()-- def notification_acknowledged() -> bool:- if live_delivery is None:- return False- evidence = live_delivery.ack_evidence- if evidence == ACK_EVIDENCE_RECEIPT:- return True- return (- evidence == ACK_EVIDENCE_DELIVERY_ONLY- and target_platform != "avibe"- )-async def settle_terminal_failure() -> None:- terminal_output = terminal- if owns_failure_contract:- metadata = dict(terminal.metadata)- metadata["turn_failure_notification"] = {- "failure_id": notification_identity,- "ack_evidence": live_delivery.ack_evidence if live_delivery else None,- "delivered": notification_acknowledged(),- }- terminal_output = replace(terminal, metadata=metadata)+ terminal_output = terminal_backend_failure_output(+ context,+ request=request,+ output=terminal,+ failure_id=notification_identity,+ delivery=live_delivery,+ )await controller.emit_agent_message(context,"result",diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex 5a7578fdc..10db6caca 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -13,7 +13,8 @@ from core.audio_asr import (detect_audio_mime_from_sample,format_audio_transcript_echo,)-from core.backend_failure import emit_backend_failure+from core.backend_failure import emit_backend_failure, terminal_backend_failure_output+from core.delivery_evidence import DeliveryEvidence, STAGE_PERSIST, STAGE_SEND, STAGE_STREAMfrom core.message_output import (HARNESS_PROMPT_ECHO_SPEC_KEY,terminal_output_for,@@ -873,21 +874,45 @@ 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 self._get_im_client(context).send_message(context, error_text)+ delivery = DeliveryEvidence()+ try:+ delivered_id = await self._get_im_client(context).send_message(+ context,+ error_text,+ )+ except Exception as delivery_err:+ delivery.error = delivery_err+ delivery.error_stage = STAGE_SEND+ raise+ delivery.send_returned = True+ delivery.delivered_id = (+ str(delivered_id) if delivered_id is not None else None+ )# Surface the failure into the live web-Chat SSE stream first...- await self._stream_terminal_error(context, error_text)+ await self._stream_terminal_error(+ context,+ error_text,+ delivery=delivery,+ )# ...then settle the failed turn through the OUTBOUND status chokepoint:# an empty terminal error result turns the dot red + releases the SSE- # waiter (the visible error was sent + streamed above). No separate latch.+ # waiter. The shared contract carries proof that the direct error path+ # already delivered, so linked Runs cannot emit another fallback.+ terminal_output = (+ terminal_output_for(request)+ if request is not None+ else terminal_turn_output()+ )await self.controller.emit_agent_message(context,"result","",is_error=True,- output=(- terminal_output_for(request)- if request is not None- else terminal_turn_output()+ output=terminal_backend_failure_output(+ context,+ request=request,+ output=terminal_output,+ delivery=delivery,),)return str(e)@@ -1650,7 +1675,13 @@ class MessageHandler(BaseHandler):backend = getattr(agent, "backend", None)return str(backend) if is_agent_backend(str(backend)) else None- async def _stream_terminal_error(self, context: MessageContext, text: str) -> None:+ async def _stream_terminal_error(+ self,+ context: MessageContext,+ text: str,+ *,+ delivery: DeliveryEvidence | None = None,+ ) -> None:"""Surface a synchronous, no-agent-dispatched failure (missing backend,a pre-dispatch exception) into the web Chat so the browser shows itinstead of silently ending the turn with only the user's prompt visible.@@ -1665,14 +1696,32 @@ class MessageHandler(BaseHandler):# Persisted as ``notify`` → renders as a status box, not an answer;# publishes message.new so the async send path surfaces it.- persist_agent_message(context, "notify", text)- except Exception:+ persist_errors: list[BaseException] = []+ persisted = persist_agent_message(+ context,+ "notify",+ text,+ native_message_id=(delivery.delivered_id if delivery else None),+ error_sink=persist_errors,+ )+ if delivery is not None:+ delivery.persisted_row = persisted+ if persisted is None and persist_errors:+ delivery.error = persist_errors[0]+ delivery.error_stage = STAGE_PERSIST+ except Exception as err:+ if delivery is not None:+ delivery.error = err+ delivery.error_stage = STAGE_PERSISTlogger.debug("failed to persist terminal error row", exc_info=True)try:from core.message_dispatcher import _stream_chunkawait _stream_chunk(self.controller, context, text=text, message_id=None, kind="error")- except Exception:+ except Exception as err:+ if delivery is not None:+ delivery.error = err+ delivery.error_stage = STAGE_STREAMlogger.debug("failed to stream terminal error chunk", exc_info=True)async def _delete_ack(self, channel_id: str, request: AgentRequest):diff --git a/docs/plans/harness-watch-run-failure-boundary.md b/docs/plans/harness-watch-run-failure-boundary.mdindex ed7fb1623..c6ff7dba3 100644--- a/docs/plans/harness-watch-run-failure-boundary.md+++ b/docs/plans/harness-watch-run-failure-boundary.md@@ -178,7 +178,8 @@ does not claim that an event was detected.contract before its immutable snapshot, even before the first participant isattached, so every accepted Run shares one fallback owner instead of emittingone notice per Run. A primary error already delivered through the shared- backend-failure path carries its acknowledgement into the same contract.+ backend-failure path, the message-handler exception path, or auth recovery+ carries its acknowledgement into the same monotonic contract.Residual manual check: trigger two one-shot Watches into one failing Turn andconfirm that the conversation contains one backend error, both Runs are failed,diff --git a/tests/scenarios/harness_failure_recovery/catalog.yaml b/tests/scenarios/harness_failure_recovery/catalog.yamlindex 63438ac05..7241a482b 100644--- a/tests/scenarios/harness_failure_recovery/catalog.yaml+++ b/tests/scenarios/harness_failure_recovery/catalog.yaml@@ -4242,8 +4242,8 @@ scenarios:layer: contractbackend: shared# The shared dispatcher stamps one Turn failure identity before participants- # arrive; an already shown primary keeps its acknowledgement, and the existing- # atomic settlement elects one Run owner only when participants exist.+ # arrive; backend, handler, and auth-recovery delivery paths preserve an already+ # shown primary, and atomic settlement elects one owner only when Runs exist.test: tests/test_message_dispatcher_result_fallback.py::MessageDispatcherResultFallbackTests::test_hfr_472_empty_failed_turn_creates_one_shared_fallback_contractmanual_evidence:- local Incus backend process death after prompt acceptancediff --git a/tests/test_agent_auth_service.py b/tests/test_agent_auth_service.pyindex ed456ba97..6f9bcd40c 100644--- a/tests/test_agent_auth_service.py+++ b/tests/test_agent_auth_service.py@@ -240,6 +240,40 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsynterminal_error="❌ Codex error: 401 Unauthorized",)+ async def test_auth_recovery_carries_primary_receipt_into_turn_settlement(self):+ controller = _StubController()+ service = AgentAuthService(controller)+ context = MessageContext(+ user_id="U1",+ channel_id="C1",+ platform="slack",+ platform_specific={+ "turn_token": "turn-auth",+ "task_execution_id": "run-auth",+ },+ )++ with patch(+ "core.message_mirror.persist_agent_message",+ return_value={"id": "message-auth"},+ ):+ handled = await service.maybe_emit_auth_recovery_message(+ context,+ "codex",+ "❌ Codex error: 401 Unauthorized",+ )++ self.assertTrue(handled)+ terminal_output = controller.emit_agent_message.await_args.kwargs["output"]+ self.assertEqual(+ terminal_output.metadata["turn_failure_notification"],+ {+ "failure_id": "turn:turn-auth",+ "ack_evidence": "receipt",+ "delivered": True,+ },+ )+async def test_codex_api_key_auth_error_points_to_key_settings_without_oauth_button(self):from config.v2_compat import to_app_configfrom config.v2_config import AgentsConfig, RuntimeConfig, SlackConfig, V2Configdiff --git a/tests/test_backend_failure.py b/tests/test_backend_failure.pyindex b0d05de60..070fc409a 100644--- a/tests/test_backend_failure.py+++ b/tests/test_backend_failure.py@@ -4,7 +4,9 @@ import unittestfrom types import SimpleNamespacefrom unittest.mock import ANY, AsyncMock, call-from core.backend_failure import emit_backend_failure+from core.backend_failure import emit_backend_failure, terminal_backend_failure_output+from core.delivery_evidence import DeliveryEvidence+from core.message_output import MessageOutputfrom modules.agents.base import AgentRequestfrom modules.im import MessageContext@@ -28,6 +30,40 @@ def _request() -> AgentRequest:class BackendFailureTests(unittest.IsolatedAsyncioTestCase):+ async def test_terminal_contract_never_downgrades_existing_delivery_evidence(+ self,+ ) -> None:+ request = _request()+ output = MessageOutput(+ completes_turn=True,+ completes_run=True,+ metadata={+ "turn_failure_notification": {+ "failure_id": "turn:turn-1",+ "ack_evidence": "receipt",+ "delivered": True,+ "fallback_run_id": "run-owner",+ }+ },+ )++ merged = terminal_backend_failure_output(+ request.context,+ request=request,+ output=output,+ delivery=DeliveryEvidence(),+ )++ self.assertEqual(+ merged.metadata["turn_failure_notification"],+ {+ "failure_id": "turn:turn-1",+ "ack_evidence": "receipt",+ "delivered": True,+ "fallback_run_id": "run-owner",+ },+ )+async def test_turn_without_current_runs_preserves_primary_delivery_for_late_runs(self,) -> None:diff --git a/tests/test_message_handler_typing.py b/tests/test_message_handler_typing.pyindex d8da86c79..41013a7cf 100644--- a/tests/test_message_handler_typing.py+++ b/tests/test_message_handler_typing.py@@ -1512,6 +1512,7 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):async def test_scheduled_turn_returns_error_string_after_notifying_im(self):controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)controller.agent_service.error = RuntimeError("boom")+ controller.emit_agent_message = AsyncMock(return_value=None)handler = MessageHandler(controller)handler.set_session_handler(_StubSessionHandler())context = MessageContext(@@ -1519,12 +1520,25 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):channel_id="C1",message_id="scheduled:task-1:abc",platform="slack",+ platform_specific={+ "turn_token": "turn-scheduled-error",+ "task_execution_id": "run-scheduled-error",+ },)result = await handler.handle_scheduled_message(context, "hello")self.assertEqual(result, "boom")self.assertEqual(controller.im_client.sent_messages, [("C1", "Error: boom")])+ terminal_output = controller.emit_agent_message.await_args.kwargs["output"]+ self.assertEqual(+ terminal_output.metadata["turn_failure_notification"],+ {+ "failure_id": "turn:turn-scheduled-error",+ "ack_evidence": "delivery_only",+ "delivered": True,+ },+ )async def test_durable_scheduled_turn_does_not_mirror_before_acceptance(self):controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)