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(core): normalize backend terminal failures
cyhff8b453c1c81
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.pyindex 9ec8aabfd..24c6c1645 100644--- a/core/agent_auth_service.py+++ b/core/agent_auth_service.py@@ -34,7 +34,7 @@ from modules.agents.opencode.message_processor import (from modules.agents.opencode.utils import resolve_opencode_model_id, resolve_opencode_reasoning_effortfrom modules.im import InlineButton, InlineKeyboard, MessageContextfrom core.resource_governance import governor_from_controller-from core.message_output import terminal_turn_output+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@@ -874,15 +874,22 @@ class AgentAuthService:return False- async def maybe_emit_auth_recovery_message(self, context: MessageContext, backend: str, error_text: str) -> bool:+ async def maybe_emit_auth_recovery_message(+ self,+ context: MessageContext,+ backend: str,+ error_text: str,+ *,+ output: MessageOutput | None = None,+ terminal_error: str | None = None,+ ) -> bool:"""Emit a reset-oauth button when the backend error is auth-related.- Each backend error-emit site calls this FIRST and emits its own terminal- error result only when this returns ``False``. When this DOES handle the- error (auth-related), the recovery message is a button row (not a result),- so settle the turn through the outbound chokepoint here by emitting a- terminal ``error`` result — that turns the workbench dot red and releases- the SSE waiter. No-op off-workbench (the outbound resolves no session id).+ Each backend error-emit site calls this FIRST and emits its own failure+ path only when this returns ``False``. When this DOES handle the error,+ the recovery message is a button row, so settle the turn separately+ through the outbound chokepoint with a silent terminal failure. No-op+ off-workbench (the outbound resolves no session id)."""if not classify_auth_error(backend, error_text):return False@@ -913,8 +920,8 @@ class AgentAuthService:persist_agent_message(context, "notify", durable_text)except Exception:logger.debug("auth recovery: failed to persist durable notify", exc_info=True)- # Settle the failed turn through the outbound status chokepoint: an empty- # terminal ``error`` result turns the dot red and releases the SSE waiter+ # 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# visible one). No-op off-workbench.try:@@ -923,7 +930,9 @@ class AgentAuthService:"result","",is_error=True,- output=terminal_turn_output(),+ level="silent",+ output=output or terminal_turn_output(),+ terminal_error=terminal_error or error_text,)except Exception:logger.debug("auth recovery: failed to settle turn status", exc_info=True)diff --git a/core/backend_failure.py b/core/backend_failure.pynew file mode 100644index 000000000..14a83c84c--- /dev/null+++ b/core/backend_failure.py@@ -0,0 +1,119 @@+"""Shared representation for authoritative backend terminal failures."""++from __future__ import annotations++import uuid+from typing import Any++from core.message_output import MessageOutput, terminal_output_for, terminal_turn_output+++def _terminal_output(request: Any, output: MessageOutput | None) -> MessageOutput:+ if output is not None:+ return output+ if request is not None:+ return terminal_output_for(request)+ return terminal_turn_output()+++def _failure_identity(+ context: Any,+ request: Any,+ explicit_id: str | None,+) -> str:+ identity = str(explicit_id or "").strip()+ if identity:+ return identity++ for source in (getattr(request, "context", None), context):+ payload = getattr(source, "platform_specific", None) or {}+ for key in (+ "task_execution_id",+ "turn_token",+ "agent_runtime_turn_token",+ ):+ identity = str(payload.get(key) or "").strip()+ if identity:+ return identity++ if request is not None:+ identity = str(getattr(request, "_backend_failure_id", "") or "").strip()+ if not identity:+ identity = uuid.uuid4().hex+ setattr(request, "_backend_failure_id", identity)+ return identity+ return uuid.uuid4().hex+++async def emit_backend_failure(+ controller: Any,+ context: Any,+ backend: str,+ diagnostic: str,+ *,+ display_text: str | None = None,+ request: Any = None,+ output: MessageOutput | None = None,+ failure_id: str | None = None,+) -> bool:+ """Notify once, then settle one terminal backend failure silently.++ Backend adapters own structured failure recognition. This helper owns the+ shared representation and keeps visible delivery separate from lifecycle+ settlement. The return value is true when auth recovery supplied the visible+ notification.+ """++ backend_name = str(backend or "backend").strip() or "backend"+ error = str(diagnostic or "").strip() or f"{backend_name} backend failed"+ visible = str(display_text or "").strip() or error+ terminal = _terminal_output(request, output)+ identity = _failure_identity(context, request, failure_id)+ notify_metadata = dict(terminal.metadata)+ notify_metadata.update(+ {+ "backend": backend_name,+ "event": "backend_failure",+ "failure_id": identity,+ }+ )+ notification = MessageOutput(+ completes_turn=False,+ completes_run=False,+ detached=terminal.detached,+ idempotency_key=f"backend-failure:{identity}",+ activity_id=terminal.activity_id,+ causation_id=terminal.causation_id,+ run_id=terminal.run_id,+ metadata=notify_metadata,+ )++ auth_service = getattr(controller, "agent_auth_service", None)+ maybe_recover = getattr(auth_service, "maybe_emit_auth_recovery_message", None)+ if callable(maybe_recover) and await maybe_recover(+ context,+ backend_name,+ visible,+ output=terminal,+ terminal_error=error,+ ):+ return True++ try:+ await controller.emit_agent_message(+ context,+ "notify",+ visible,+ output=notification,+ )+ finally:+ await controller.emit_agent_message(+ context,+ "result",+ "",+ is_error=True,+ level="silent",+ output=terminal,+ terminal_error=error,+ )+ return Falsediff --git a/core/controller.py b/core/controller.pyindex 1748eacd8..171491688 100644--- a/core/controller.py+++ b/core/controller.py@@ -1280,6 +1280,7 @@ class Controller:status_label: Optional[str] = None,result_footer: Optional[str] = None,output: MessageOutput | None = None,+ terminal_error: Optional[str] = None,):"""Backward-compatible entrypoint; delegated to message dispatcher."""try:@@ -1293,6 +1294,7 @@ class Controller:status_label=status_label,result_footer=result_footer,output=output,+ terminal_error=terminal_error,)finally:manager = getattr(self, "session_turns", None)diff --git a/core/message_dispatcher.py b/core/message_dispatcher.pyindex a3219f132..04c99e86d 100644--- a/core/message_dispatcher.py+++ b/core/message_dispatcher.py@@ -983,6 +983,7 @@ class ConsolidatedMessageDispatcher:text: str,message_id: str | None,terminal_status: str | None,+ terminal_error: str | None,output_semantics: MessageOutput,provenance: dict[str, Any],) -> None:@@ -1006,23 +1007,33 @@ class ConsolidatedMessageDispatcher:if not output_id:digest = hashlib.sha256(text.encode("utf-8")).hexdigest()[:20]output_id = f"content:{digest}"+ record_kwargs = {+ "output_id": output_id,+ "text": text,+ "message_id": message_id,+ "sequence": output_semantics.sequence,+ "provenance": provenance,+ "terminal_status": run_terminal_status,+ }+ if terminal_error is not None:+ record_kwargs["error"] = terminal_errorrecord_output(run_id,- output_id=output_id,- text=text,- message_id=message_id,- sequence=output_semantics.sequence,- provenance=provenance,- terminal_status=run_terminal_status,+ **record_kwargs,)else:# Compatibility for isolated stores and older persisted-state# adapters while the shared SQLite path owns the output ledger.+ record_kwargs = {+ "text": text,+ "message_id": message_id,+ "terminal_status": run_terminal_status,+ }+ if terminal_error is not None:+ record_kwargs["error"] = terminal_errorstore.record_run_message(run_id,- text=text,- message_id=message_id,- terminal_status=run_terminal_status,+ **record_kwargs,)def _run_has_blocking_activity(self, run_id: str) -> bool:@@ -1061,6 +1072,7 @@ class ConsolidatedMessageDispatcher:message_id: str | None,*,is_error: bool,+ terminal_error: str | None = None,output_semantics: MessageOutput | None = None,log_label: str = "agent run terminal result",) -> None:@@ -1093,6 +1105,7 @@ class ConsolidatedMessageDispatcher:text=text,message_id=message_id,terminal_status=terminal_status,+ terminal_error=terminal_error,output_semantics=semantics,provenance=semantics.provenance(context),)@@ -1115,6 +1128,7 @@ class ConsolidatedMessageDispatcher:message_id: str | None,*,is_error: bool,+ terminal_error: str | None = None,output_semantics: MessageOutput | None = None,) -> None:self._record_agent_run_terminal_result(@@ -1122,6 +1136,7 @@ class ConsolidatedMessageDispatcher:text,message_id,is_error=is_error,+ terminal_error=terminal_error,output_semantics=output_semantics,log_label="suppressed agent run terminal result",)@@ -1313,6 +1328,7 @@ class ConsolidatedMessageDispatcher:status_label: Optional[str] = None,result_footer: Optional[str] = None,output: MessageOutput | None = None,+ terminal_error: Optional[str] = None,) -> Optional[str]:"""Centralized dispatch for agent messages.@@ -1411,6 +1427,7 @@ class ConsolidatedMessageDispatcher:text,None,is_error=is_error,+ terminal_error=terminal_error,output_semantics=output_semantics,)if mutates_turn_lifecycle:@@ -1462,6 +1479,7 @@ class ConsolidatedMessageDispatcher:duplicate_result_text,None,is_error=is_error,+ terminal_error=terminal_error,output_semantics=output_semantics,)if mutates_turn_lifecycle:@@ -1534,7 +1552,13 @@ class ConsolidatedMessageDispatcher:# Record only once delivered (avibe always, via SSE) so a failed# IM send isn't stored as if the user received it.if persists_without_delivery or message_id is not None:- persist_agent_message(target_context, "notify", text)+ persist_agent_message(+ target_context,+ "notify",+ text,+ metadata=output_metadata,+ native_message_id=native_output_id,+ )# Live SSE turn stream for the web Chat page (no-op for IM/CLI).await _stream_chunk(self.controller, context, text=text, message_id=message_id, kind="notify")return message_id@@ -1781,6 +1805,7 @@ class ConsolidatedMessageDispatcher:persisted_result_text,primary_message_id,is_error=is_error,+ terminal_error=terminal_error,output_semantics=output_semantics,)@@ -1836,6 +1861,7 @@ class ConsolidatedMessageDispatcher:persisted_result_text,primary_message_id,is_error=is_error,+ terminal_error=terminal_error,output_semantics=output_semantics,)diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.pyindex 7db9c52f5..97285e7ee 100644--- a/modules/agents/claude_agent.py+++ b/modules/agents/claude_agent.py@@ -5,6 +5,7 @@ import uuidfrom typing import Callable, Optionalfrom core.agent_auth_service import classify_auth_error+from core.backend_failure import emit_backend_failurefrom core.message_output import MessageOutput, terminal_output_for, terminal_turn_outputfrom core.reply_enhancer import strip_silent_blocksfrom core.session_activities import SessionActivity, activity_completion_output@@ -54,6 +55,7 @@ class ClaudeAgent(BaseAgent):self._pending_assistant_message: dict[str, str] = {}self._native_session_ids: dict[str, str] = {}self._suppressed_synthetic_results: set[str] = set()+ self._suppressed_synthetic_error_text: dict[str, str] = {}self._suppress_receiver_runtime_release: set[str] = set()# Store reaction info per runtime session for cleanup after terminal# result. Under the runtime turn gate there is normally one active entry;@@ -172,38 +174,36 @@ class ClaudeAgent(BaseAgent):self._mark_session_idle_if_no_pending_requests(runtime_session_key)await self._remove_ack_reaction(request)error_notify = self._format_error_notify(e)- handled = await self.controller.agent_auth_service.maybe_emit_auth_recovery_message(- context,- "claude",- error_notify,- )- if not handled:- await self.session_handler.handle_session_error(runtime_session_key, context, e)- # ``handle_session_error`` sends through the IM client, which doesn't- # write to ``messages``, and the web Chat renders only durable- # ``message.new`` rows — so persist a terminal notify or the avibe- # user's prompt stops with no explanation (Codex P2). The HANDLED- # (auth) branch instead persists the full recovery text centrally in- # ``maybe_emit_auth_recovery_message``.- try:- from core.message_mirror import persist_agent_message-- persist_agent_message(context, "notify", error_notify)- except Exception:- logger.debug("claude: failed to persist terminal error row", exc_info=True)- # Synchronous failure (query/setup raised), no async receiver result- # coming: settle the turn through the OUTBOUND status chokepoint. An- # empty terminal error result turns the dot red AND releases the- # web-Chat stream waiter (the visible error was sent + persisted- # above), instead of waiting out the safety timeout. No-op off-workbench.try:- await self.controller.emit_agent_message(+ handled = await self.controller.agent_auth_service.maybe_emit_auth_recovery_message(context,- "result",- "",- is_error=True,+ "claude",+ error_notify,output=terminal_output_for(request),+ terminal_error=str(e),)+ if not handled:+ await self.session_handler.handle_session_error(runtime_session_key, context, e)+ # ``handle_session_error`` sends through the IM client, which doesn't+ # write to ``messages``, and the web Chat renders only durable+ # ``message.new`` rows. The auth branch persists its recovery text.+ try:+ from core.message_mirror import persist_agent_message++ persist_agent_message(context, "notify", error_notify)+ except Exception:+ logger.debug("claude: failed to persist terminal error row", exc_info=True)+ # No async receiver result is coming. Auth recovery settles its+ # own failure; otherwise do that here without another bubble.+ await self.controller.emit_agent_message(+ context,+ "result",+ "",+ is_error=True,+ level="silent",+ output=terminal_output_for(request),+ terminal_error=str(e),+ )finally:self._release_service_runtime_turn(context)finally:@@ -397,6 +397,7 @@ class ClaudeAgent(BaseAgent):self._pending_assistant_message.pop(composite_key, None)self._native_session_ids.pop(composite_key, None)self._suppressed_synthetic_results.discard(composite_key)+ self._suppressed_synthetic_error_text.pop(composite_key, None)if not preserve_pending_request_state:self._pending_reactions.pop(composite_key, None)pending_requests = self._pending_requests.pop(composite_key, None) or []@@ -672,7 +673,6 @@ class ClaudeAgent(BaseAgent):if context_tokens:self.controller.note_session_tokens(context, total=context_tokens)- auth_failure_assistant = self._is_auth_failure_assistant_message(message)assistant_text = self._extract_text_blocks(message, context)if output_mode == "detached":if assistant_text:@@ -682,26 +682,15 @@ class ClaudeAgent(BaseAgent):if assistant_text:self._detached_assistant_text[composite_key] = assistant_textcontinue- auth_failure_text = assistant_text or "OAuth authentication failed."- if await self._handle_auth_failure_result(- context,- composite_key,- "error" if auth_failure_assistant else "",- auth_failure_text if auth_failure_assistant else assistant_text,- ):- mark_session_idle = getattr(self.session_handler, "mark_session_idle", None)- if callable(mark_session_idle):- mark_session_idle(composite_key)- await self._clear_pending_reactions(composite_key, context)- self._last_assistant_text.pop(composite_key, None)- self._pending_assistant_message.pop(composite_key, None)- return- if await self._handle_synthetic_api_error_message(+ failure_disposition = await self._handle_assistant_terminal_failure(context,composite_key,message,assistant_text,- ):+ )+ if failure_disposition == "auth":+ return+ if failure_disposition:continueif assistant_text:self._last_assistant_text[composite_key] = assistant_text@@ -860,20 +849,16 @@ class ClaudeAgent(BaseAgent):if fallback:result_text = fallback- if await self._handle_auth_failure_result(+ failure_disposition = await self._handle_terminal_failure_result(context,composite_key,- getattr(message, "subtype", "") or "",+ message,result_text,- ):- self._retire_failed_auth_turn(composite_key, context)- mark_session_idle = getattr(self.session_handler, "mark_session_idle", None)- if callable(mark_session_idle):- mark_session_idle(composite_key)- await self._clear_pending_reactions(composite_key, context)- self._last_assistant_text.pop(composite_key, None)- self._pending_assistant_message.pop(composite_key, None)+ )+ if failure_disposition == "auth":return+ if failure_disposition:+ continue# NOTE: The pending assistant message is intentionally# NOT emitted here. ResultMessage.result already@@ -1012,7 +997,8 @@ class ClaudeAgent(BaseAgent):# context BEFORE clearing the FIFO (and before either the auth-recovery or# the non-auth emit below), mirroring the in-loop auth-failure paths (Codex P2)._pending = self._pending_requests.get(composite_key) or []- self._adopt_pending_turn_token(context, _pending[0] if _pending else None)+ pending_request = _pending[0] if _pending else None+ self._adopt_pending_turn_token(context, pending_request)# Clean up all pending reactions for this session on error —# the receiver is dead and won't process any more results.await self._clear_pending_reactions(composite_key, context)@@ -1021,6 +1007,8 @@ class ClaudeAgent(BaseAgent):context,"claude",error_notify,+ output=terminal_output_for(pending_request),+ terminal_error=str(e),)if not handled:await self.session_handler.handle_session_error(composite_key, context, e)@@ -1046,7 +1034,9 @@ class ClaudeAgent(BaseAgent):"result","",is_error=True,- output=terminal_turn_output(),+ level="silent",+ output=terminal_output_for(pending_request),+ terminal_error=str(e),)self._release_service_runtime_turn(context)# NOTE: no `finally` cleanup of pending reactions here.@@ -1059,6 +1049,7 @@ class ClaudeAgent(BaseAgent):# inside the loop.finally:self._suppressed_synthetic_results.discard(composite_key)+ self._suppressed_synthetic_error_text.pop(composite_key, None)detached_activity = self._detached_activity_outputs.pop(composite_key, None)if detached_activity is not None:registry = self._activity_registry()@@ -1105,58 +1096,126 @@ class ClaudeAgent(BaseAgent):"result","",is_error=True,+ level="silent",output=terminal_output_for(pending_request),+ terminal_error="Claude receiver ended without a terminal result",)finally:self._release_service_runtime_turn(context)- async def _handle_synthetic_api_error_message(+ async def _handle_assistant_terminal_failure(self,context: MessageContext,composite_key: str,message,text: str,- ) -> bool:- """Settle Claude Code synthetic API errors without publishing them as chat."""+ ) -> str | None:+ """Handle a structured AssistantMessage failure and its paired result."""- if not self._is_synthetic_api_error_message(message, text):- return False+ diagnostic = self._terminal_backend_failure(message, text)+ if diagnostic is None:+ return None- pending_request = self._pop_pending_request(composite_key)- self._requeue_request_activity(pending_request)+ handled_auth = await self._settle_terminal_backend_failure(+ context,+ composite_key,+ diagnostic,+ )+ if handled_auth:+ return "auth"+ self._suppressed_synthetic_results.add(composite_key)+ self._suppressed_synthetic_error_text[composite_key] = diagnostic+ return "failure"++ async def _handle_terminal_failure_result(+ self,+ context: MessageContext,+ composite_key: str,+ message,+ text: str | None,+ ) -> str | None:+ diagnostic = self._terminal_backend_failure(message, text)+ if diagnostic is None:+ return None+ handled_auth = await self._settle_terminal_backend_failure(+ context,+ composite_key,+ diagnostic,+ )+ return "auth" if handled_auth else "failure"++ async def _settle_terminal_backend_failure(+ self,+ context: MessageContext,+ composite_key: str,+ diagnostic: str,+ ) -> bool:+ pending_requests = self._pending_requests.get(composite_key) or []+ pending_request = pending_requests[0] if pending_requests else Noneself._adopt_pending_turn_token(context, pending_request)logger.warning(- "Claude malformed tool-use synthetic API error for session %s suppressed from user-visible transcript: %s",+ "Claude terminal backend failure for session %s: %s",composite_key,- text or "<empty>",+ diagnostic,)- await self.controller.emit_agent_message(+ handled_auth = await emit_backend_failure(+ self.controller,context,- "result",- "",- is_error=True,- output=terminal_output_for(pending_request),+ self.name,+ diagnostic,+ display_text=f"❌ Claude error: {diagnostic}",+ request=pending_request,)- if pending_request is not None:- await self._remove_ack_reaction(pending_request)+ if handled_auth:+ self._retire_failed_auth_turn(composite_key, context)+ await self._cleanup_runtime_session(+ composite_key,+ current_receiver_task=asyncio.current_task(),+ preserve_pending_request_state=True,+ )+ if pending_request is not None:+ await self._remove_ack_reaction(pending_request)+ self._discard_pending_reaction(composite_key)+ await self._clear_pending_reactions(composite_key, context)+ self._mark_session_idle_if_no_pending_requests(composite_key)+ return True++ popped_request = self._pop_pending_request(composite_key)+ self._requeue_request_activity(popped_request)+ if popped_request is not None:+ await self._remove_ack_reaction(popped_request)self._last_assistant_text.pop(composite_key, None)self._pending_assistant_message.pop(composite_key, None)- self._suppressed_synthetic_results.add(composite_key)self._discard_pending_reaction(composite_key)self._mark_session_idle_if_no_pending_requests(composite_key)- return True+ return Falsedef _consume_suppressed_synthetic_result(self, composite_key: str, message, text: Optional[str]) -> bool:if composite_key not in self._suppressed_synthetic_results:return False- if not self._is_malformed_tool_call_retry_failure_result(message, text):+ expected = " ".join(+ self._suppressed_synthetic_error_text.get(composite_key, "").lower().split()+ )+ actual = " ".join((text or "").lower().split())+ same_failure_text = bool(+ expected+ and actual+ and (expected in actual or actual in expected)+ )+ if (+ self._terminal_backend_failure(message, text) is None+ and not same_failure_text+ and not self._is_malformed_tool_call_retry_failure_result(message, text)+ ):self._suppressed_synthetic_results.discard(composite_key)+ self._suppressed_synthetic_error_text.pop(composite_key, None)return Falseself._suppressed_synthetic_results.discard(composite_key)+ self._suppressed_synthetic_error_text.pop(composite_key, None)logger.warning(- "Claude paired malformed tool-use synthetic ResultMessage for session %s suppressed: %s",+ "Claude paired terminal ResultMessage for session %s suppressed: %s",composite_key,text or "<empty>",)@@ -1848,16 +1907,11 @@ class ClaudeAgent(BaseAgent):return "activity"if composite_key in self._detached_unsolicited_outputs:return "detached"- # A malformed-tool-use synthetic API error pops the turn's real pending- # request and arms ``_suppressed_synthetic_results`` for the PAIRED- # ResultMessage, which the result branch then skips (``continue``) with NO- # terminal emit. That paired result reaches this hook with an empty FIFO +- # free gate, so opening an agent-initiated turn for it would leak the gate /- # pending request / active flag until EOF — and the NEXT user message for- # this Claude session would block behind the leaked gate (Codex P1). Skip- # while a suppressed synthetic result is pending; the set is cleared by- # ``_consume_suppressed_synthetic_result`` / cleanup, so real later turns- # open normally.+ # A structured AssistantMessage failure pops the turn's real pending+ # request and arms ``_suppressed_synthetic_results`` for its paired+ # ResultMessage. Opening an agent-initiated turn for that duplicate frame+ # would leak the gate and block the next user message. The marker is cleared+ # when the paired result is consumed or the receiver exits.if composite_key in self._suppressed_synthetic_results:return Noneregistry = self._activity_registry()@@ -2205,12 +2259,15 @@ class ClaudeAgent(BaseAgent):# active-turn guard would otherwise treat the stale token as a superseded# turn and skip the failed-status write for 2nd-or-later Claude auth failures.pending = self._pending_requests.get(composite_key) or []- self._adopt_pending_turn_token(context, pending[0] if pending else None)+ pending_request = pending[0] if pending else None+ self._adopt_pending_turn_token(context, pending_request)handled = await self.controller.agent_auth_service.maybe_emit_auth_recovery_message(context,"claude",f"❌ Claude error: {text}",+ output=terminal_output_for(pending_request),+ terminal_error=text,)if handled:await self._cleanup_runtime_session(@@ -2220,9 +2277,49 @@ class ClaudeAgent(BaseAgent):)return handled- def _is_auth_failure_assistant_message(self, message) -> bool:- error_kind = (getattr(message, "error", "") or "").strip().lower()- return error_kind == "authentication_failed"+ @staticmethod+ def _error_value_text(value) -> str:+ if isinstance(value, dict):+ for key in ("message", "error", "type", "name"):+ text = str(value.get(key) or "").strip()+ if text:+ return text+ return str(value).strip()+ return str(value or "").strip()++ @classmethod+ def _terminal_backend_failure(cls, message, text: Optional[str]) -> str | None:+ """Extract only structured terminal failure evidence from Claude frames."""++ subtype = str(getattr(message, "subtype", "") or "").strip().lower()+ error_value = getattr(message, "error", None)+ errors = getattr(message, "errors", None)+ api_status = getattr(message, "api_error_status", None)+ structured_failure = bool(+ getattr(message, "is_error", False)+ or error_value+ or bool(errors)+ or api_status+ or subtype == "failed"+ or subtype.startswith("error")+ or cls._is_synthetic_api_error_message(message, text)+ )+ if not structured_failure:+ return None++ candidates = [+ str(text or "").strip(),+ str(getattr(message, "result", "") or "").strip(),+ cls._error_value_text(error_value),+ ]+ if isinstance(errors, (list, tuple)):+ candidates.extend(cls._error_value_text(item) for item in errors)+ elif errors:+ candidates.append(cls._error_value_text(errors))+ if api_status:+ candidates.append(f"API error status {api_status}")+ candidates.append(subtype)+ return next((candidate for candidate in candidates if candidate), "Claude backend failed")@staticmethoddef _is_synthetic_api_error_message(message, text: Optional[str] = None) -> bool:diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.pyindex 9e5e24af0..9aad2537c 100644--- a/modules/agents/codex/agent.py+++ b/modules/agents/codex/agent.py@@ -16,6 +16,7 @@ from config.v2_config import (DEFAULT_CODEX_STUCK_ACTIVE_IDLE_EVICTION_MULTIPLIER,)from core.avibe_cloud import avibe_cloud_url_available+from core.backend_failure import emit_backend_failurefrom core.caller_context import caller_env_for_platform_payloadfrom core.message_output import terminal_output_forfrom core.services.session_fork import fork_source_state, pending_native_fork@@ -130,26 +131,26 @@ class CodexAgent(BaseAgent):try:transport = await self._get_or_create_transport(request.working_path)except FileNotFoundError:- # Terminal failure → emit as a RESULT (error): the outbound chokepoint- # turns the dot red and releases the SSE waiter (no separate latch).- await self.controller.emit_agent_message(+ await emit_backend_failure(+ self.controller,request.context,- "result",- "❌ Codex CLI not found. Please install it or set CODEX_CLI_PATH.",- is_error=True,- output=terminal_output_for(request),+ self.name,+ "Codex CLI not found",+ display_text="❌ Codex CLI not found. Please install it or set CODEX_CLI_PATH.",+ request=request,)await self._remove_ack_reaction(request)self._event_handler._release_stream_turn(request.context)returnexcept Exception as e:logger.error("Failed to start Codex transport: %s", e, exc_info=True)- await self.controller.emit_agent_message(+ await emit_backend_failure(+ self.controller,request.context,- "result",- f"❌ Failed to start Codex CLI: {e}",- is_error=True,- output=terminal_output_for(request),+ self.name,+ str(e),+ display_text=f"❌ Failed to start Codex CLI: {e}",+ request=request,)await self._remove_ack_reaction(request)self._event_handler._release_stream_turn(request.context)@@ -187,12 +188,13 @@ class CodexAgent(BaseAgent):if self._is_recoverable_transport_error(e):raiselogger.warning("Failed to interrupt turn %s: %s", active_turn, e)- await self.controller.emit_agent_message(+ await emit_backend_failure(+ self.controller,request.context,- "result",- f"❌ Failed to interrupt previous Codex turn: {e}",- is_error=True,- output=terminal_output_for(request),+ self.name,+ str(e),+ display_text=f"❌ Failed to interrupt previous Codex turn: {e}",+ request=request,)await self._remove_ack_reaction(request)self._event_handler._release_stream_turn(request.context)@@ -233,24 +235,14 @@ class CodexAgent(BaseAgent):self._turn_registry.clear_pending_turn_start(request.base_session_id, request)logger.error("Error in Codex handle_message: %s", e, exc_info=True)error_text = f"❌ Codex error: {e}"- handled = await self.controller.agent_auth_service.maybe_emit_auth_recovery_message(+ await emit_backend_failure(+ self.controller,request.context,- "codex",- error_text,+ self.name,+ str(e),+ display_text=error_text,+ request=request,)- if not handled:- # Terminal failure → RESULT (error): the outbound chokepoint- # turns the dot red. The auth-recovery branch (handled) emits- # its own terminal error result inside- # ``maybe_emit_auth_recovery_message``, so both paths settle- # the dot via the same outbound — no separate latch.- await self.controller.emit_agent_message(- request.context,- "result",- error_text,- is_error=True,- output=terminal_output_for(request),- )await self._remove_ack_reaction(request)# The turn never started (all retries failed) — release the# web-Chat working/Stop state instead of leaving it until thediff --git a/modules/agents/codex/event_handler.py b/modules/agents/codex/event_handler.pyindex 5e7397fcf..0474aa04b 100644--- a/modules/agents/codex/event_handler.py+++ b/modules/agents/codex/event_handler.py@@ -9,7 +9,7 @@ from pathlib import Pathfrom typing import TYPE_CHECKING, Anyfrom vibe.i18n import t as i18n_t-from core.message_output import terminal_output_for+from core.backend_failure import emit_backend_failureif TYPE_CHECKING:from modules.agents.base import AgentRequest@@ -160,26 +160,15 @@ class CodexEventHandler:if should_emit_terminal_error and not already_notified:message = f"❌ Codex turn failed: {error_msg}"- handled = await self._agent.controller.agent_auth_service.maybe_emit_auth_recovery_message(+ await emit_backend_failure(+ self._agent.controller,tracked_request.context,"codex",- message,+ error_msg or "Unknown error",+ display_text=message,+ request=tracked_request,+ failure_id=turn_id,)- if not handled:- # Terminal failure → RESULT (error): the outbound status- # chokepoint turns the dot red. The auth-recovery branch- # settles it via its own terminal error result.- await self._agent.controller.emit_agent_message(- tracked_request.context,- "result",- message,- is_error=True,- output=terminal_output_for(tracked_request),- )- # handled == True persists the durable recovery notify centrally in- # ``maybe_emit_auth_recovery_message`` (the auth service is the single- # home for the reset-prompt text); the not-handled branch persists via- # ``emit_agent_message`` above.error_was_user_visible = Trueelse:logger.info("Suppressing inactive Codex turn failure for %s: %s", turn_id, error_msg)@@ -344,42 +333,29 @@ class CodexEventHandler:and not turn_state.terminal_error_notified):text = f"❌ Codex turn failed: {message}"- handled = await self._agent.controller.agent_auth_service.maybe_emit_auth_recovery_message(+ await emit_backend_failure(+ self._agent.controller,request.context,"codex",- text,+ message,+ display_text=text,+ request=request,+ failure_id=turn_id,)- if not handled:- # Terminal failure → error RESULT so the outbound chokepoint- # turns the dot red (the later completed handler suppresses a- # second message once terminal_error_notified is set).- await self._agent.controller.emit_agent_message(- request.context,- "result",- text,- is_error=True,- output=terminal_output_for(request),- )turn_state.terminal_error_notified = Trueelse:logger.info("Logging inactive Codex turn error for %s: %s", turn_id, message)returntext = f"❌ Codex error: {message}"- handled = await self._agent.controller.agent_auth_service.maybe_emit_auth_recovery_message(+ await emit_backend_failure(+ self._agent.controller,request.context,"codex",- text,+ message,+ display_text=text,+ request=request,)- if not handled:- # No-turnId terminal error → error RESULT so the dot turns red.- await self._agent.controller.emit_agent_message(- request.context,- "result",- text,- is_error=True,- output=terminal_output_for(request),- )def _extract_error_message(self, error: Any) -> str:if isinstance(error, dict):diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.pyindex 0c01d6e75..fed9067d4 100644--- a/modules/agents/opencode/agent.py+++ b/modules/agents/opencode/agent.py@@ -14,6 +14,7 @@ import timefrom typing import Dict, Optionalfrom core.avibe_cloud import avibe_cloud_url_available+from core.backend_failure import emit_backend_failurefrom core.message_output import terminal_output_forfrom core.resource_governance import governor_from_controllerfrom core.system_prompt_injection import build_system_prompt_injection, get_enabled_agents_for_prompt@@ -197,14 +198,13 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):await server.ensure_running()except Exception as e:logger.error(f"Failed to start OpenCode server: {e}", exc_info=True)- # Terminal failure → emit as a RESULT (error): the outbound chokepoint- # turns the dot red and releases the SSE waiter. No separate latch.- await self.controller.emit_agent_message(+ await emit_backend_failure(+ self.controller,request.context,- "result",- f"Failed to start OpenCode server: {e}",- is_error=True,- output=terminal_output_for(request),+ self.name,+ str(e),+ display_text=f"Failed to start OpenCode server: {e}",+ request=request,)await self._remove_ack_reaction(request)return@@ -218,12 +218,13 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):# The previous session is gone server-side — surface it as a terminal# ERROR result (outbound chokepoint turns the dot red), don't silently# fork a fresh session and lose context.- await self.controller.emit_agent_message(+ await emit_backend_failure(+ self.controller,request.context,- "result",- f"❌ {e}",- is_error=True,- output=terminal_output_for(request),+ self.name,+ str(e),+ display_text=f"❌ {e}",+ request=request,)await self._remove_ack_reaction(request)return@@ -235,26 +236,24 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):# (which settles the dot itself); otherwise emit the error result here.logger.error(f"OpenCode session acquisition failed: {e}", exc_info=True)message = f"OpenCode error: {type(e).__name__}: {e}".strip()- handled = await self.controller.agent_auth_service.maybe_emit_auth_recovery_message(- request.context, "opencode", message+ await emit_backend_failure(+ self.controller,+ request.context,+ self.name,+ str(e),+ display_text=message,+ request=request,)- if not handled:- await self.controller.emit_agent_message(- request.context,- "result",- message,- is_error=True,- output=terminal_output_for(request),- )await self._remove_ack_reaction(request)returnif not session_id:- await self.controller.emit_agent_message(+ await emit_backend_failure(+ self.controller,request.context,- "result",+ self.name,"Failed to obtain OpenCode session ID",- is_error=True,- output=terminal_output_for(request),+ display_text="Failed to obtain OpenCode session ID",+ request=request,)await self._remove_ack_reaction(request)return@@ -470,25 +469,14 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):self.sessions.remove_active_poll(session_id)message = f"OpenCode request failed: {error_text}"- handled = await self.controller.agent_auth_service.maybe_emit_auth_recovery_message(+ await emit_backend_failure(+ self.controller,request.context,- "opencode",- message,+ self.name,+ error_text,+ display_text=message,+ request=request,)- if not handled:- # Terminal failure → error RESULT so the outbound chokepoint turns- # the dot red (auth-classified errors settle via the recovery path).- await self.controller.emit_agent_message(- request.context,- "result",- message,- is_error=True,- output=terminal_output_for(request),- )- # handled == True persists the durable recovery notify centrally in- # ``maybe_emit_auth_recovery_message`` (which also latches the turn- # failure for the workbench dot — auth AND non-auth); the not-handled- # branch persists via ``emit_agent_message`` above.finally:if run_registered:await server.mark_run_inactive(session_id)diff --git a/modules/agents/opencode/poll_loop.py b/modules/agents/opencode/poll_loop.pyindex ff20eecf4..2784a7f1e 100644--- a/modules/agents/opencode/poll_loop.py+++ b/modules/agents/opencode/poll_loop.py@@ -8,6 +8,7 @@ import timefrom typing import Any, Dict, Optionalfrom config.v2_config import DEFAULT_OPENCODE_ERROR_RETRY_LIMIT+from core.backend_failure import emit_backend_failurefrom core.message_context import build_context_session_keyfrom core.message_output import terminal_output_for, terminal_turn_outputfrom modules.agents.base import AgentRequest@@ -86,86 +87,6 @@ class OpenCodePollLoop:def _build_restored_context(self, poll_info):return self._build_restored_handle(poll_info).context- def _empty_terminal_message_text(- self,- *,- model_dict: Optional[Dict[str, str]],- reasoning_effort: Optional[str],- detail: Optional[str] = None,- ) -> str:- provider_id = (model_dict or {}).get("providerID") or self._t("common.default")- model_id = (model_dict or {}).get("modelID") or self._t("common.default")- variant = reasoning_effort or self._t("common.default")- if detail:- return self._t(- "error.opencodeProviderRuntimeError",- provider=provider_id,- model=model_id,- variant=variant,- detail=detail,- )- return self._t(- "error.opencodeEmptyResponse",- provider=provider_id,- model=model_id,- variant=variant,- )-- async def _empty_terminal_message_detail(- self,- server: OpenCodeServerManager,- session_id: str,- model_dict: Optional[Dict[str, str]] = None,- *,- since: Optional[float] = None,- ) -> Optional[str]:- try:- detail = await server.get_recent_session_error(session_id, since=since)- if detail:- return detail- provider_id = (model_dict or {}).get("providerID")- model_id = (model_dict or {}).get("modelID")- if provider_id and model_id:- return await server.get_provider_api_diagnostic(provider_id, model_id)- except Exception as err:- logger.debug("Failed to inspect OpenCode logs for %s: %s", session_id, err)- return None-- async def _emit_empty_terminal_failure(- self,- *,- context,- server: OpenCodeServerManager,- session_id: str,- model_dict: Optional[Dict[str, str]],- reasoning_effort: Optional[str],- prompt_started_at: Optional[float] = None,- ) -> None:- detail = await self._empty_terminal_message_detail(- server,- session_id,- model_dict=model_dict,- since=prompt_started_at,- )- message = self._empty_terminal_message_text(- model_dict=model_dict,- reasoning_effort=reasoning_effort,- detail=detail,- )- await self._agent.controller.emit_agent_message(- context,- "notify",- message,- )- await self._agent.controller.emit_agent_message(- context,- "result",- message,- is_error=True,- level="silent",- output=terminal_turn_output(),- )-def _build_restored_ack_request(self, poll_info) -> AgentRequest:handle = self._build_restored_handle(poll_info)context = handle.context@@ -251,8 +172,6 @@ class OpenCodePollLoop:emitted_assistant_messages: set[str] = set()poll_interval_seconds = 2.0final_text: Optional[str] = None- get_started_at = getattr(server, "get_last_prompt_started_at", None)- prompt_started_at = get_started_at(session_id) if callable(get_started_at) else Noneerror_retry_count = 0error_retry_limit = getattr(@@ -409,23 +328,17 @@ class OpenCodePollLoop:retry_err,)- message = f"OpenCode error: {error_name} - {error_msg[:500]}"- handled = await self._agent.controller.agent_auth_service.maybe_emit_auth_recovery_message(+ diagnostic = f"{error_name} - {error_msg[:500]}".strip(" -")+ message = f"OpenCode error: {diagnostic}"+ await emit_backend_failure(+ self._agent.controller,request.context,"opencode",- message,+ diagnostic,+ display_text=message,+ request=request,+ failure_id=str(last_id or ""),)- if not handled:- # Retry exhausted on a message error → terminal FAILURE.- # Emit an ERROR result so the outbound chokepoint turns the- # dot red (a bare notify never settles agent_status) (Codex P2).- await self._agent.controller.emit_agent_message(- request.context,- "result",- message,- is_error=True,- output=terminal_output_for(request),- )# Terminal: stop polling AND signal the caller NOT to emit the# "(No response from OpenCode)" warning result — that warning is# idle and would reset the dot we (or the auth-recovery path)@@ -459,15 +372,7 @@ class OpenCodePollLoop:(model_dict or {}).get("modelID"),reasoning_effort,)- await self._emit_empty_terminal_failure(- context=request.context,- server=server,- session_id=session_id,- model_dict=model_dict,- reasoning_effort=reasoning_effort,- prompt_started_at=prompt_started_at,- )- return None, False+ breakbreakawait asyncio.sleep(poll_interval_seconds)@@ -478,7 +383,8 @@ class OpenCodePollLoop:"""Continue a poll loop that was interrupted by restart."""session_id = poll_info.opencode_session_id- context = self._build_restored_context(poll_info)+ restored_request = self._build_restored_ack_request(poll_info)+ context = restored_request.contextawait self._agent.controller.emit_agent_message(context,@@ -492,10 +398,6 @@ class OpenCodePollLoop:emitted_assistant_messages = set(poll_info.emitted_assistant_messages)poll_interval_seconds = 2.0final_text: Optional[str] = None- get_started_at = getattr(server, "get_last_prompt_started_at", None)- prompt_started_at = getattr(poll_info, "prompt_started_at", None) or (- get_started_at(session_id) if callable(get_started_at) else None- )error_retry_count = 0error_retry_limit = getattr(@@ -619,23 +521,15 @@ class OpenCodePollLoop:error_retry_count += 1if error_retry_count > error_retry_limit:message = f"OpenCode error: {error_text}"- handled = await self._agent.controller.agent_auth_service.maybe_emit_auth_recovery_message(+ await emit_backend_failure(+ self._agent.controller,context,"opencode",- message,+ error_text,+ display_text=message,+ request=restored_request,+ failure_id=str(last_info.get("id") or ""),)- if not handled:- # Terminal failure (retry exhausted) on the- # restored poll path → ERROR result so the dot- # turns red, not a notify that leaves it- # running until the safety timeout (Codex P2).- await self._agent.controller.emit_agent_message(- context,- "result",- message,- is_error=True,- output=terminal_turn_output(),- )self._agent.sessions.remove_active_poll(session_id)await self.remove_restored_ack(poll_info)return@@ -662,17 +556,7 @@ class OpenCodePollLoop:"Restored OpenCode session %s completed without text/error",session_id,)- await self._emit_empty_terminal_failure(- context=context,- server=server,- session_id=session_id,- model_dict=getattr(poll_info, "model_dict", None),- reasoning_effort=getattr(poll_info, "reasoning_effort", None),- prompt_started_at=prompt_started_at,- )- self._agent.sessions.remove_active_poll(session_id)- await self.remove_restored_ack(poll_info)- return+ breakbreakawait asyncio.sleep(poll_interval_seconds)@@ -717,18 +601,12 @@ class OpenCodePollLoop:await self.remove_restored_ack(poll_info)message = f"Restored OpenCode session failed: {error_text}"- handled = await self._agent.controller.agent_auth_service.maybe_emit_auth_recovery_message(+ await emit_backend_failure(+ self._agent.controller,context,"opencode",- message,+ error_text,+ display_text=message,+ request=restored_request,+ failure_id=session_id,)- if not handled:- # Terminal failure → error RESULT so the outbound chokepoint turns- # the dot red (auth-classified errors settle via the recovery path).- await self._agent.controller.emit_agent_message(- context,- "result",- message,- is_error=True,- output=terminal_turn_output(),- )diff --git a/storage/background.py b/storage/background.pyindex dbc5c43b8..2da52bea4 100644--- a/storage/background.py+++ b/storage/background.py@@ -1199,6 +1199,7 @@ class SQLiteBackgroundTaskStore:text: str,message_id: str | None = None,terminal_status: Optional[str] = None,+ error: Optional[str] = None,updated_at: Optional[str] = None,) -> None:now = updated_at or _utc_now_iso()@@ -1224,6 +1225,8 @@ class SQLiteBackgroundTaskStore:if terminal_status:values["status"] = normalize_run_status(terminal_status)values["completed_at"] = now+ if error is not None:+ values["error"] = str(error)result = conn.execute(update(agent_runs).where(agent_runs.c.id == run_id)@@ -1245,6 +1248,7 @@ class SQLiteBackgroundTaskStore:sequence: int | None = None,provenance: Optional[dict[str, Any]] = None,terminal_status: Optional[str] = None,+ error: Optional[str] = None,updated_at: Optional[str] = None,) -> dict[str, Any]:"""Append one idempotent Run output and optionally settle the Run once."""@@ -1325,6 +1329,13 @@ class SQLiteBackgroundTaskStore:.values(**values))if effective_terminal_status:+ terminal_values: dict[str, Any] = {+ "status": normalize_run_status(effective_terminal_status),+ "completed_at": now,+ "updated_at": now,+ }+ if error is not None:+ terminal_values["error"] = str(error)transition = conn.execute(update(agent_runs).where(agent_runs.c.id == run_id)@@ -1334,11 +1345,7 @@ class SQLiteBackgroundTaskStore:+ _status_query_values("running")))- .values(- status=normalize_run_status(effective_terminal_status),- completed_at=now,- updated_at=now,- )+ .values(**terminal_values))terminal_transition = bool(transition.rowcount)diff --git a/tests/test_agent_auth_service.py b/tests/test_agent_auth_service.pyindex 850d5eaa3..d63ab969a 100644--- a/tests/test_agent_auth_service.py+++ b/tests/test_agent_auth_service.py@@ -219,7 +219,9 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsyn"result","",is_error=True,+ level="silent",output=ANY,+ terminal_error="❌ Codex error: 401 Unauthorized",)async def test_maybe_emit_auth_recovery_message_defers_non_auth_error_to_caller(self):diff --git a/tests/test_backend_failure.py b/tests/test_backend_failure.pynew file mode 100644index 000000000..e20d87685--- /dev/null+++ b/tests/test_backend_failure.py@@ -0,0 +1,161 @@+from __future__ import annotations++import unittest+from types import SimpleNamespace+from unittest.mock import ANY, AsyncMock, call++from core.backend_failure import emit_backend_failure+from modules.agents.base import AgentRequest+from modules.im import MessageContext+++def _request() -> AgentRequest:+ context = MessageContext(+ user_id="U1",+ channel_id="C1",+ platform="avibe",+ platform_specific={"turn_token": "turn-1"},+ )+ return AgentRequest(+ context=context,+ message="work",+ working_path="/tmp/work",+ base_session_id="session-1",+ composite_session_id="session-1:/tmp/work",+ session_key="avibe::project::p1",+ )+++class BackendFailureTests(unittest.IsolatedAsyncioTestCase):+ async def test_auth_recovery_owns_the_only_terminal_settlement(self) -> None:+ request = _request()+ controller = SimpleNamespace(+ agent_auth_service=SimpleNamespace(+ maybe_emit_auth_recovery_message=AsyncMock(return_value=True)+ ),+ emit_agent_message=AsyncMock(),+ )++ handled_auth = await emit_backend_failure(+ controller,+ request.context,+ "claude",+ "401 Unauthorized",+ request=request,+ )++ self.assertTrue(handled_auth)+ controller.emit_agent_message.assert_not_awaited()++ async def test_separates_notify_from_terminal_settlement(self) -> None:+ request = _request()+ controller = SimpleNamespace(+ agent_auth_service=SimpleNamespace(+ maybe_emit_auth_recovery_message=AsyncMock(return_value=False)+ ),+ emit_agent_message=AsyncMock(),+ )++ handled_auth = await emit_backend_failure(+ controller,+ request.context,+ "codex",+ "provider unavailable",+ display_text="Codex failed: provider unavailable",+ request=request,+ )++ self.assertFalse(handled_auth)+ auth_call = controller.agent_auth_service.maybe_emit_auth_recovery_message.await_args+ self.assertEqual(+ auth_call.args,+ (request.context, "codex", "Codex failed: provider unavailable"),+ )+ self.assertEqual(auth_call.kwargs["terminal_error"], "provider unavailable")+ terminal_output = auth_call.kwargs["output"]+ notify_call, terminal_call = controller.emit_agent_message.await_args_list+ self.assertEqual(+ notify_call,+ call(+ request.context,+ "notify",+ "Codex failed: provider unavailable",+ output=ANY,+ ),+ )+ self.assertFalse(notify_call.kwargs["output"].settles_run)+ self.assertEqual(+ notify_call.kwargs["output"].idempotency_key,+ "backend-failure:turn-1",+ )+ self.assertEqual(+ terminal_call,+ call(+ request.context,+ "result",+ "",+ is_error=True,+ level="silent",+ output=terminal_output,+ terminal_error="provider unavailable",+ ),+ )++ async def test_identity_is_stable_for_duplicate_terminal_events(self) -> None:+ request = _request()+ controller = SimpleNamespace(+ agent_auth_service=SimpleNamespace(+ maybe_emit_auth_recovery_message=AsyncMock(return_value=False)+ ),+ emit_agent_message=AsyncMock(),+ )++ await emit_backend_failure(controller, request.context, "claude", "server error", request=request)+ await emit_backend_failure(controller, request.context, "claude", "server error", request=request)++ notify_outputs = [+ item.kwargs["output"]+ for item in controller.emit_agent_message.await_args_list+ if item.args[1] == "notify"+ ]+ self.assertEqual(+ [output.idempotency_key for output in notify_outputs],+ ["backend-failure:turn-1", "backend-failure:turn-1"],+ )++ async def test_settles_lifecycle_when_notify_raises(self) -> None:+ request = _request()+ terminal_calls = []++ async def emit(_context, message_type, _text, **kwargs):+ if message_type == "notify":+ raise RuntimeError("delivery unavailable")+ terminal_calls.append(kwargs)++ controller = SimpleNamespace(+ agent_auth_service=SimpleNamespace(+ maybe_emit_auth_recovery_message=AsyncMock(return_value=False)+ ),+ emit_agent_message=emit,+ )++ with self.assertRaisesRegex(RuntimeError, "delivery unavailable"):+ await emit_backend_failure(+ controller,+ request.context,+ "opencode",+ "transport failed",+ request=request,+ )++ self.assertEqual(+ terminal_calls,+ [+ {+ "is_error": True,+ "level": "silent",+ "output": request.output,+ "terminal_error": "transport failed",+ }+ ],+ )diff --git a/tests/test_claude_agent_initiated_turn.py b/tests/test_claude_agent_initiated_turn.pyindex be4da0bbd..2c38206dd 100644--- a/tests/test_claude_agent_initiated_turn.py+++ b/tests/test_claude_agent_initiated_turn.py@@ -209,7 +209,7 @@ def _build_agent(*, running_calls=None, mark_idle_calls=None, active_calls=None)agent._maybe_capture_session_id = lambda *a, **k: Noneagent._consume_suppressed_synthetic_result = lambda *a, **k: Falseagent._handle_auth_failure_result = AsyncMock(return_value=False)- agent._handle_synthetic_api_error_message = AsyncMock(return_value=False)+ agent._handle_assistant_terminal_failure = AsyncMock(return_value=False)agent._reserved_native_session_id = lambda *a, **k: Noneagent._adopt_pending_turn_token = lambda *a, **k: Noneagent._get_formatter = lambda context: Nonediff --git a/tests/test_claude_agent_sessions.py b/tests/test_claude_agent_sessions.pyindex ca93a41e7..b28039249 100644--- a/tests/test_claude_agent_sessions.py+++ b/tests/test_claude_agent_sessions.py@@ -101,6 +101,16 @@ class _StubController:class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):+ def assert_backend_failure_emitted(self, emitter, context, display_text, diagnostic):+ self.assertEqual(emitter.await_count, 2)+ notify_call, terminal_call = emitter.await_args_list+ self.assertEqual(notify_call.args[:3], (context, "notify", display_text))+ self.assertFalse(notify_call.kwargs["output"].settles_run)+ self.assertEqual(terminal_call.args[:3], (context, "result", ""))+ self.assertTrue(terminal_call.kwargs["is_error"])+ self.assertEqual(terminal_call.kwargs["level"], "silent")+ self.assertEqual(terminal_call.kwargs["terminal_error"], diagnostic)+async def test_handle_message_serializes_queries_for_same_runtime_session(self):controller = _StubController()runtime_key = "wechat_o9:/tmp/work"@@ -348,7 +358,15 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(queries, [("first", runtime_key)])self.assertEqual(mark_active_calls, [runtime_key])self.assertIn(runtime_key, mark_idle_calls)- controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True, output=ANY)+ controller.emit_agent_message.assert_awaited_once_with(+ context,+ "result",+ "",+ is_error=True,+ level="silent",+ output=ANY,+ terminal_error="Claude receiver ended without a terminal result",+ )agent._remove_ack_reaction.assert_awaited_once_with(request)self.assertNotIn(runtime_key, agent._pending_requests)self.assertNotIn(runtime_key, controller.claude_sessions)@@ -1219,7 +1237,15 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):await agent._receive_messages(_FailingClient(), "session-1", "/tmp/work", context)agent.session_handler.handle_session_error.assert_awaited_once()- controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True, output=ANY)+ controller.emit_agent_message.assert_awaited_once_with(+ context,+ "result",+ "",+ is_error=True,+ level="silent",+ output=ANY,+ terminal_error="Connection lost",+ )persist.assert_called_once()self.assertEqual(persist.call_args.args[1], "notify")self.assertEqual(persist.call_args.args[2], "❌ Claude error: Connection lost")@@ -1253,11 +1279,22 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):await agent._receive_messages(_FailingClient(), "session-1", "/tmp/work", context)agent.session_handler.handle_session_error.assert_awaited_once()- controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True, output=ANY)+ terminal_error = "Failed to decode JSON: JSON message exceeded maximum buffer size of 1048576 bytes"+ controller.emit_agent_message.assert_awaited_once_with(+ context,+ "result",+ "",+ is_error=True,+ level="silent",+ output=ANY,+ terminal_error=terminal_error,+ )controller.agent_auth_service.maybe_emit_auth_recovery_message.assert_awaited_once_with(context,"claude","❌ Connection to Claude was lost. Please try your message again.",+ output=ANY,+ terminal_error=terminal_error,)persist.assert_called_once_with(context,@@ -1678,7 +1715,15 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):await asyncio.wait_for(receiver_task, timeout=1)- controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True, output=ANY)+ controller.emit_agent_message.assert_awaited_once_with(+ context,+ "result",+ "",+ is_error=True,+ level="silent",+ output=ANY,+ terminal_error="Claude receiver ended without a terminal result",+ )self.assertFalse(service._turn_gates[composite_key].lock.locked())self.assertNotIn(composite_key, controller.claude_sessions)self.assertNotIn(composite_key, agent._pending_requests)@@ -1852,7 +1897,15 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):await asyncio.wait_for(receiver_task, timeout=1)- controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True, output=ANY)+ controller.emit_agent_message.assert_awaited_once_with(+ context,+ "result",+ "",+ is_error=True,+ level="silent",+ output=ANY,+ terminal_error="Claude receiver ended without a terminal result",+ )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())@@ -1993,7 +2046,12 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):await agent._receive_messages(_Client(), "session-1", "/tmp/work", context, composite_key=composite_key)- controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True, output=ANY)+ self.assert_backend_failure_emitted(+ controller.emit_agent_message,+ context,+ f"❌ Claude error: {error_text}",+ error_text,+ )agent.emit_result_message.assert_not_awaited()agent._remove_ack_reaction.assert_awaited_once_with(pending_request)self.assertEqual(context.platform_specific["turn_token"], "T1")@@ -2048,7 +2106,12 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):await agent._receive_messages(_Client(), "session-1", "/tmp/work", context, composite_key=composite_key)- controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True, output=ANY)+ self.assert_backend_failure_emitted(+ controller.emit_agent_message,+ context,+ f"❌ Claude error: {error_text}",+ error_text,+ )agent.emit_result_message.assert_not_awaited()self.assertEqual(agent._pending_requests[composite_key], [next_request])self.assertEqual(agent._pending_reactions[composite_key], [("m2", ":eyes:")])@@ -2106,7 +2169,13 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):await agent._receive_messages(_Client(), "session-1", "/tmp/work", context, composite_key=composite_key)- controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True, output=ANY)+ diagnostic = "The model's tool call could not be parsed (retry also failed)."+ self.assert_backend_failure_emitted(+ controller.emit_agent_message,+ context,+ f"❌ Claude error: {diagnostic}",+ diagnostic,+ )agent.emit_result_message.assert_not_awaited()self.assertEqual(agent._pending_requests[composite_key], [next_request])self.assertEqual(agent._pending_reactions[composite_key], [("m2", ":eyes:")])@@ -2178,7 +2247,13 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):client.ready.set()await receiver_task- controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True, output=ANY)+ diagnostic = "The model's tool call could not be parsed (retry also failed)."+ self.assert_backend_failure_emitted(+ controller.emit_agent_message,+ context,+ f"❌ Claude error: {diagnostic}",+ diagnostic,+ )agent.emit_result_message.assert_not_awaited()self.assertEqual(agent._pending_requests[composite_key], [followup_request])self.assertEqual(agent._pending_reactions[composite_key], [("m2", ":eyes:")])@@ -2251,7 +2326,13 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):client.ready.set()await receiver_task- controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True, output=ANY)+ diagnostic = "The model's tool call could not be parsed (retry also failed)."+ self.assert_backend_failure_emitted(+ controller.emit_agent_message,+ context,+ f"❌ Claude error: {diagnostic}",+ diagnostic,+ )agent.emit_result_message.assert_awaited_once_with(context,"next turn result",@@ -2339,13 +2420,13 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):)self.assertNotIn(composite_key, agent._pending_requests)- async def test_non_malformed_synthetic_api_error_remains_visible(self):+ async def test_synthetic_server_error_notifies_and_suppresses_paired_result(self):controller = _StubController()controller._get_session_key = lambda context: "avibe::project::p1"controller.emit_agent_message = AsyncMock()agent = ClaudeAgent(controller)agent.emit_result_message = AsyncMock()- error_text = "Claude API rate_limit: retry later."+ error_text = "API Error: 503 provider unavailable"agent._extract_text_blocks = lambda message, context: error_textcontext = SimpleNamespace(user_id="U1",@@ -2364,7 +2445,8 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):"content": [],"isApiErrorMessage": True,"model": "<synthetic>",- "error": "rate_limit",+ "error": "server_error",+ "api_error_status": 503,},)()result_message = type(@@ -2383,16 +2465,97 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):await agent._receive_messages(_Client(), "session-1", "/tmp/work", context, composite_key=composite_key)- controller.emit_agent_message.assert_not_awaited()+ controller.agent_auth_service.maybe_emit_auth_recovery_message.assert_awaited_once_with(+ context,+ "claude",+ f"❌ Claude error: {error_text}",+ output=ANY,+ terminal_error=error_text,+ )+ self.assertEqual(controller.emit_agent_message.await_count, 2)+ notify_call, terminal_call = controller.emit_agent_message.await_args_list+ self.assertEqual(notify_call.args[:3], (context, "notify", f"❌ Claude error: {error_text}"))+ self.assertFalse(notify_call.kwargs["output"].settles_run)+ self.assertEqual(terminal_call.args[:3], (context, "result", ""))+ self.assertTrue(terminal_call.kwargs["is_error"])+ self.assertEqual(terminal_call.kwargs["level"], "silent")+ self.assertEqual(terminal_call.kwargs["terminal_error"], error_text)+ agent.emit_result_message.assert_not_awaited()+ self.assertNotIn(composite_key, agent._pending_requests)++ async def test_result_is_error_fails_without_error_subtype(self):+ controller = _StubController()+ controller._get_session_key = lambda context: "avibe::project::p1"+ controller.emit_agent_message = AsyncMock()+ agent = ClaudeAgent(controller)+ agent.emit_result_message = AsyncMock()+ context = SimpleNamespace(user_id="U1", channel_id="C1", platform_specific={})+ composite_key = "session-1:/tmp/work"+ pending_request = SimpleNamespace(context=SimpleNamespace(platform_specific={"turn_token": "T1"}))+ agent._pending_requests[composite_key] = [pending_request]+ result_message = type(+ "ResultMessage",+ (),+ {+ "subtype": "success",+ "is_error": True,+ "result": "provider rejected the request",+ "duration_ms": 1,+ },+ )()++ class _Client:+ def receive_messages(self):+ async def _iterate():+ yield result_message++ return _iterate()++ await agent._receive_messages(_Client(), "session-1", "/tmp/work", context, composite_key=composite_key)++ self.assertEqual(controller.emit_agent_message.await_count, 2)+ agent.emit_result_message.assert_not_awaited()+ terminal_call = controller.emit_agent_message.await_args_list[1]+ self.assertEqual(terminal_call.kwargs["terminal_error"], "provider rejected the request")++ async def test_success_result_with_error_words_remains_agent_output(self):+ controller = _StubController()+ controller._get_session_key = lambda context: "avibe::project::p1"+ controller.emit_agent_message = AsyncMock()+ agent = ClaudeAgent(controller)+ agent.emit_result_message = AsyncMock()+ context = SimpleNamespace(user_id="U1", channel_id="C1", platform_specific={})+ composite_key = "session-1:/tmp/work"+ pending_request = SimpleNamespace(context=SimpleNamespace(platform_specific={"turn_token": "T1"}))+ agent._pending_requests[composite_key] = [pending_request]+ result_message = type(+ "ResultMessage",+ (),+ {+ "subtype": "success",+ "is_error": False,+ "result": "The test failed with an error; I fixed it.",+ "duration_ms": 1,+ },+ )()++ class _Client:+ def receive_messages(self):+ async def _iterate():+ yield result_message++ return _iterate()++ await agent._receive_messages(_Client(), "session-1", "/tmp/work", context, composite_key=composite_key)+agent.emit_result_message.assert_awaited_once_with(context,- error_text,- subtype="error",+ "The test failed with an error; I fixed it.",+ subtype="success",duration_ms=1,parse_mode="markdown",request=pending_request,)- self.assertNotIn(composite_key, agent._pending_requests)async def test_assistant_auth_error_without_is_api_error_flag_still_triggers_recovery(self):"""Scenario: AUTH-SETUP-902"""diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.pyindex c6f208fbb..7fa9e4970 100644--- a/tests/test_codex_agent.py+++ b/tests/test_codex_agent.py@@ -904,15 +904,20 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):agent._event_handler.clear_pending.assert_not_called()agent._remove_ack_reaction.assert_awaited_once_with(request)- # The failed interrupt is a terminal failure → emitted as an ERROR result- # (the outbound status chokepoint turns the dot red), not a bare notify.- agent.controller.emit_agent_message.assert_awaited_once_with(- request.context,- "result",- "❌ Failed to interrupt previous Codex turn: interrupt failed",- is_error=True,- output=ANY,+ self.assertEqual(agent.controller.emit_agent_message.await_count, 2)+ notify_call, terminal_call = agent.controller.emit_agent_message.await_args_list+ self.assertEqual(+ notify_call.args[:3],+ (+ request.context,+ "notify",+ "❌ Failed to interrupt previous Codex turn: interrupt failed",+ ),)+ self.assertEqual(terminal_call.args[:3], (request.context, "result", ""))+ self.assertTrue(terminal_call.kwargs["is_error"])+ self.assertEqual(terminal_call.kwargs["level"], "silent")+ self.assertEqual(terminal_call.kwargs["terminal_error"], "interrupt failed")async def test_handle_message_recovers_from_broken_transport_once(self):agent = object.__new__(CodexAgent)diff --git a/tests/test_codex_event_handler.py b/tests/test_codex_event_handler.pyindex 23f97789a..c5170dc5a 100644--- a/tests/test_codex_event_handler.py+++ b/tests/test_codex_event_handler.py@@ -179,14 +179,19 @@ class CodexEventHandlerTests(unittest.IsolatedAsyncioTestCase):request.context,"codex","❌ Codex turn failed: unexpected status 401 Unauthorized:",- )- agent.controller.emit_agent_message.assert_awaited_once_with(- request.context,- "result",- "❌ Codex turn failed: unexpected status 401 Unauthorized:",- is_error=True,output=ANY,+ terminal_error="unexpected status 401 Unauthorized:",+ )+ self.assertEqual(agent.controller.emit_agent_message.await_count, 2)+ notify_call, terminal_call = agent.controller.emit_agent_message.await_args_list+ self.assertEqual(+ notify_call.args[:3],+ (request.context, "notify", "❌ Codex turn failed: unexpected status 401 Unauthorized:"),)+ self.assertEqual(terminal_call.args[:3], (request.context, "result", ""))+ self.assertTrue(terminal_call.kwargs["is_error"])+ self.assertEqual(terminal_call.kwargs["level"], "silent")+ self.assertEqual(terminal_call.kwargs["terminal_error"], "unexpected status 401 Unauthorized:")await handler._on_turn_completed({@@ -199,7 +204,7 @@ class CodexEventHandlerTests(unittest.IsolatedAsyncioTestCase):request,)- assert agent.controller.emit_agent_message.await_count == 1+ assert agent.controller.emit_agent_message.await_count == 2agent._remove_ack_reaction.assert_awaited_once_with(request)async def test_turn_failure_falls_back_to_completion_error_when_no_error_notification_arrives(self):@@ -223,16 +228,17 @@ class CodexEventHandlerTests(unittest.IsolatedAsyncioTestCase):request.context,"codex","❌ Codex turn failed: fallback message",- )- # Terminal failure → error RESULT (the outbound status chokepoint turns- # the dot red), not a bare notify.- agent.controller.emit_agent_message.assert_awaited_once_with(- request.context,- "result",- "❌ Codex turn failed: fallback message",- is_error=True,output=ANY,+ terminal_error="fallback message",+ )+ self.assertEqual(agent.controller.emit_agent_message.await_count, 2)+ notify_call, terminal_call = agent.controller.emit_agent_message.await_args_list+ self.assertEqual(+ notify_call.args[:3],+ (request.context, "notify", "❌ Codex turn failed: fallback message"),)+ self.assertEqual(terminal_call.args[:3], (request.context, "result", ""))+ self.assertEqual(terminal_call.kwargs["terminal_error"], "fallback message")agent._remove_ack_reaction.assert_awaited_once_with(request)async def test_unknown_turn_error_is_logged_without_emitting(self):diff --git a/tests/test_message_dispatcher_result_fallback.py b/tests/test_message_dispatcher_result_fallback.pyindex c666809f4..110dccf30 100644--- a/tests/test_message_dispatcher_result_fallback.py+++ b/tests/test_message_dispatcher_result_fallback.py@@ -312,6 +312,7 @@ class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):"already delivered",None,is_error=False,+ terminal_error=None,output_semantics=output,)dispatcher._collapse_status_bubble.assert_awaited_once()diff --git a/tests/test_message_dispatcher_scheduled.py b/tests/test_message_dispatcher_scheduled.pyindex a9dc3b983..b51bffcd9 100644--- a/tests/test_message_dispatcher_scheduled.py+++ b/tests/test_message_dispatcher_scheduled.py@@ -194,6 +194,105 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):self.assertIsNone(message_id)self.assertEqual(calls, [("run-empty", "", "succeeded")])+ async def test_terminal_failure_records_explicit_run_error_without_result_text(self):+ controller = _StubController()+ controller.agent_service = SimpleNamespace(+ activities=SimpleNamespace(has_blocking_run_activity=lambda _run_id: False),+ emit_matches_runtime_turn=lambda _context: True,+ release_runtime_turn=lambda _context: None,+ )+ dispatcher = ConsolidatedMessageDispatcher(controller)+ context = MessageContext(+ user_id="scheduled",+ channel_id="C123",+ platform="slack",+ platform_specific={+ "task_trigger_kind": "agent_run",+ "task_execution_id": "run-failed",+ },+ )+ calls = []++ class _Store:+ def get_run(self, run_id):+ return {"status": "running"}++ def record_run_output(self, run_id, **kwargs):+ calls.append((run_id, kwargs))++ def close(self):+ pass++ with patch.object(+ message_dispatcher_module,+ "SQLiteBackgroundTaskStore",+ return_value=_Store(),+ ):+ await dispatcher.emit_agent_message(+ context,+ "result",+ "",+ is_error=True,+ level="silent",+ output=MessageOutput(completes_turn=True, completes_run=True),+ terminal_error="provider unavailable",+ )++ self.assertEqual(len(calls), 1)+ run_id, payload = calls[0]+ self.assertEqual(run_id, "run-failed")+ self.assertEqual(payload["text"], "")+ self.assertEqual(payload["terminal_status"], "failed")+ self.assertEqual(payload["error"], "provider unavailable")++ async def test_notify_output_uses_stable_persistence_identity(self):+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)+ context = MessageContext(+ user_id="scheduled",+ channel_id="C123",+ platform="slack",+ )+ persisted_ids = set()+ persisted = []++ def exists(_context, native_message_id):+ return native_message_id in persisted_ids++ def persist(_context, message_type, text, **kwargs):+ native_message_id = kwargs["native_message_id"]+ persisted_ids.add(native_message_id)+ persisted.append((message_type, text, kwargs))+ return {"id": "row-1"}++ output = MessageOutput(+ idempotency_key="backend-failure:turn-1",+ metadata={"backend": "codex", "event": "backend_failure"},+ )+ with (+ patch.object(message_dispatcher_module, "agent_message_exists", side_effect=exists),+ patch.object(message_dispatcher_module, "persist_agent_message", side_effect=persist),+ ):+ first = await dispatcher.emit_agent_message(+ context,+ "notify",+ "Codex failed",+ output=output,+ )+ second = await dispatcher.emit_agent_message(+ context,+ "notify",+ "Codex failed",+ output=output,+ )++ self.assertEqual(first, "bot-msg-1")+ self.assertTrue(str(second).startswith("agent-output:codex:"))+ self.assertEqual(controller.im_client.sent, [("C123", None, "Codex failed")])+ self.assertEqual(len(persisted), 1)+ self.assertEqual(persisted[0][0:2], ("notify", "Codex failed"))+ self.assertEqual(persisted[0][2]["metadata"]["event"], "backend_failure")+async def test_activity_run_settlement_waits_for_successful_delivery(self):controller = _StubController()controller.im_client = _FailingIMClient()diff --git a/tests/test_multi_platform_runtime.py b/tests/test_multi_platform_runtime.pyindex 75feee3c4..cf8f29e0d 100644--- a/tests/test_multi_platform_runtime.py+++ b/tests/test_multi_platform_runtime.py@@ -1312,17 +1312,19 @@ def test_opencode_poll_aborts_disabled_question_toolcall():assert emitted[0][1] == "translated:error.opencodeQuestionToolDisabled"-def test_opencode_poll_emits_error_result_on_retry_exhaustion():+def test_opencode_poll_notifies_and_settles_on_retry_exhaustion():# A completed assistant message carrying an error, with retries exhausted# (error_retry_limit=0) and the auth-recovery path declining (non-auth error),- # is a terminal FAILURE. It must (a) emit an ERROR result so the dot turns red- # and (b) return should_emit=False so the caller does NOT then emit the idle- # "(No response from OpenCode)" warning that would reset the dot to idle (Codex P2).+ # is a terminal FAILURE. It emits one visible notification plus one silent+ # failed settlement, then suppresses the idle "(No response from OpenCode)"+ # result that would overwrite the terminal state.emitted = []class _AuthSvc:- async def maybe_emit_auth_recovery_message(self, context, backend, message):- return False # non-auth error → caller emits the terminal result itself+ async def maybe_emit_auth_recovery_message(+ self, context, backend, message, *, output=None, terminal_error=None+ ):+ return Falseclass _Formatter:def format_toolcall(self, *args, **kwargs):@@ -1344,8 +1346,9 @@ def test_opencode_poll_emits_error_result_on_retry_exhaustion():is_error=False,level="normal",output=None,+ terminal_error=None,):- emitted.append((message_type, is_error))+ emitted.append((message_type, text, is_error, level, terminal_error))class _Agent:opencode_config = type("OpenCodeConfig", (), {"error_retry_limit": 0})()@@ -1401,11 +1404,12 @@ def test_opencode_poll_emits_error_result_on_retry_exhaustion():# should_emit False → caller skips the idle "(No response)" warning that would# otherwise reset the dot we just turned red.assert should_emit is False- assert ("result", True) in emitted- assert not any(mtype == "notify" for mtype, _ in emitted)+ assert [item[0] for item in emitted] == ["notify", "result"]+ assert emitted[0][1] == "OpenCode error: ProviderError - rate limited"+ assert emitted[1][1:] == ("", True, "silent", "ProviderError - rate limited")-def test_opencode_poll_emits_notify_and_silent_error_result_on_empty_terminal_message():+def test_opencode_poll_keeps_explicit_empty_completion_on_success_path():emitted = []class _AuthSvc:@@ -1515,27 +1519,15 @@ def test_opencode_poll_emits_notify_and_silent_error_result_on_empty_terminal_me)assert final_text is None- assert should_emit is False- assert emitted == [- (- "notify",- "provider:glm/glm-5.2/(Default):AI_APICallError (ECONNRESET) while calling https://relay.example/messages",- False,- "normal",- ),- (- "result",- "provider:glm/glm-5.2/(Default):AI_APICallError (ECONNRESET) while calling https://relay.example/messages",- True,- "silent",- ),- ]+ assert should_emit is True+ assert emitted == []-def test_opencode_restored_poll_preserves_model_details_for_empty_terminal_probe():+def test_opencode_restored_poll_keeps_empty_completion_successful():emitted = []removed = []diagnostics = []+ results = []class _AuthSvc:async def maybe_emit_auth_recovery_message(self, context, backend, message):@@ -1632,8 +1624,8 @@ def test_opencode_restored_poll_preserves_model_details_for_empty_terminal_probedef _extract_response_text(self, message):return ""- async def emit_result_message(self, *args, **kwargs):- raise AssertionError("empty terminal path should emit failure directly")+ async def emit_result_message(self, context, text, **kwargs):+ results.append((text, kwargs))async def _remove_ack_reaction(self, request):return None@@ -1655,7 +1647,7 @@ def test_opencode_restored_poll_preserves_model_details_for_empty_terminal_probeloop = OpenCodePollLoop(_Agent())asyncio.run(loop.run_restored_poll_loop(poll))- assert diagnostics == [("glm", "glm-5.2")]+ assert diagnostics == []assert removed == ["oc-session"]assert emitted == [(@@ -1664,19 +1656,11 @@ def test_opencode_restored_poll_preserves_model_details_for_empty_terminal_probeFalse,"normal",),- (- "notify",- "provider:glm/glm-5.2/high:Provider API returned HTTP 503: No available accounts",- False,- "normal",- ),- (- "result",- "provider:glm/glm-5.2/high:Provider API returned HTTP 503: No available accounts",- True,- "silent",- ),]+ assert len(results) == 1+ assert results[0][0] == "(No response from OpenCode)"+ assert results[0][1]["subtype"] == "warning"+ assert isinstance(results[0][1]["started_at"], float)def test_processing_indicator_handle_is_source_of_truth_for_backend_cleanup():diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.pyindex b74a169e3..bf918bbf6 100644--- a/tests/test_scheduled_tasks.py+++ b/tests/test_scheduled_tasks.py@@ -2200,6 +2200,65 @@ def test_duplicate_terminal_output_does_not_append_result_text_again(assert "deferred_terminal_status" not in terminal["result_payload"]+def test_failed_run_records_error_and_enqueues_one_terminal_callback(+ tmp_path: Path,+ monkeypatch,+) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ caller_session_id = _make_avibe_session(monkeypatch, tmp_path)+ request_store = TaskExecutionStore()+ request = request_store.enqueue_agent_run(+ session_id="target-session",+ message="delegated work",+ agent_name="codex",+ callback_session_id=caller_session_id,+ )+ service = ScheduledTaskService(+ controller=_avibe_controller_double(+ gate=SimpleNamespace(submit_scheduled=lambda *_args, **_kwargs: None, in_flight={}),+ handle_scheduled_message=lambda *_args, **_kwargs: None,+ ),+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),+ request_store=request_store,+ )+ assert request_store.claim(request.id) is not None+ sqlite_store = request_store._sqlite+ assert sqlite_store is not None++ first = sqlite_store.record_run_output(+ request.id,+ output_id="terminal",+ text="",+ terminal_status="failed",+ error="provider unavailable",+ )+ duplicate = sqlite_store.record_run_output(+ request.id,+ output_id="terminal",+ text="",+ terminal_status="failed",+ error="provider unavailable",+ )+ asyncio.run(service._drain_callbacks())+ asyncio.run(service._drain_callbacks())++ original = request_store.get_run(request.id)+ assert original is not None+ assert first["terminal_transition"] is True+ assert duplicate["terminal_transition"] is False+ assert original["status"] == "failed"+ assert original["error"] == "provider unavailable"+ assert not original["result_text"]+ assert original["callback_status"] == "sent"+ callback_runs = [+ run+ for run in request_store.list_runs()+ if run.get("source_kind") == "callback" and run.get("parent_run_id") == request.id+ ]+ assert [run["message"] for run in callback_runs] == ["Error: provider unavailable"]+ assert callback_runs[0]["source_actor"] == f"{request.id}:terminal:failed"++@pytest.mark.parametrize(("activity_status", "expected_run_status"),[diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex acc070169..8d2b264a9 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -11,6 +11,7 @@ import { useRegisterComposerTarget, type ComposerInsertTarget } from '../../contimport type { SessionRuntimeState, VaultRequest, VibeAgentBrief, WorkbenchMessage, WorkbenchSession } from '../../context/ApiContext';import { apiFetch } from '../../lib/apiFetch';import { normalizeChatMessageFontSize } from '../../lib/chatDisplay';+import { isNotifyMessageType } from '../../lib/chatMessageTypes';import { useIosKeyboardInset } from '../../lib/useIosKeyboardInset';import { isProxyMediaUrl } from '../../lib/mediaProxy';import { localPath, type ShowPageLinkInfo } from '../../lib/showPageLinks';@@ -2432,9 +2433,9 @@ const MessageRow = memo(function MessageRow({ message, session, messageFontSize,// Each branch composes this onto its own ``justify-*`` so alignment is kept.const rowClass = (extra: string) => clsx('flex w-full', extra, highlighted && 'msg-highlight');- // A notify row is a turn-terminal marker (agent run that failed/stopped- // without a result) — a compact status pill, not an answer.- const isNotify = message.type === 'notify';+ // Runtime notifications and legacy error rows are compact status pills,+ // not Agent-authored answers.+ const isNotify = isNotifyMessageType(message.type);const isAgent = !isNotify && message.author === 'agent';const isSystem = !isNotify && message.author === 'system';// A harness-origin row is a user-role prompt the human didn't type (scheduleddiff --git a/ui/src/lib/chatMessageTypes.test.ts b/ui/src/lib/chatMessageTypes.test.tsnew file mode 100644index 000000000..3dbd09d78--- /dev/null+++ b/ui/src/lib/chatMessageTypes.test.ts@@ -0,0 +1,15 @@+import { describe, expect, it } from 'vitest';++import { isNotifyMessageType } from './chatMessageTypes';++describe('isNotifyMessageType', () => {+ it('renders current and legacy failure rows as notifications', () => {+ expect(isNotifyMessageType('notify')).toBe(true);+ expect(isNotifyMessageType('error')).toBe(true);+ });++ it('keeps agent results out of the notification treatment', () => {+ expect(isNotifyMessageType('result')).toBe(false);+ expect(isNotifyMessageType('assistant')).toBe(false);+ });+});diff --git a/ui/src/lib/chatMessageTypes.ts b/ui/src/lib/chatMessageTypes.tsnew file mode 100644index 000000000..947e58270--- /dev/null+++ b/ui/src/lib/chatMessageTypes.ts@@ -0,0 +1,2 @@+export const isNotifyMessageType = (type: string): boolean =>+ type === 'notify' || type === 'error';