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): preserve terminal failure diagnostics
cyhb0b7adcae084
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.pyindex 04c99e86d..f6f719278 100644--- a/core/message_dispatcher.py+++ b/core/message_dispatcher.py@@ -995,7 +995,10 @@ class ConsolidatedMessageDispatcher:if run_terminal_status and self._run_has_blocking_activity(run_id):defer_terminal = getattr(store, "defer_run_terminal", None)if callable(defer_terminal):- defer_terminal(run_id, terminal_status=run_terminal_status)+ defer_kwargs = {"terminal_status": run_terminal_status}+ if terminal_error is not None:+ defer_kwargs["error"] = terminal_error+ defer_terminal(run_id, **defer_kwargs)run_terminal_status = Nonerecord_output = getattr(store, "record_run_output", None)if callable(record_output):@@ -1351,9 +1354,8 @@ class ConsolidatedMessageDispatcher:- ``"normal"`` (default): delivered / persisted / streamed as usual.- ``"silent"``: settles the dot + releases the SSE waiter for a terminal``result``, then returns WITHOUT delivering, persisting, or streaming.- Used for intentional, non-noteworthy lifecycle events (e.g. a user-- initiated stop) so the turn ends cleanly with no user-facing bubble —- replacing the old "fake it with empty text" trick with an explicit flag.+ Used when lifecycle settlement must not add another visible bubble,+ including intentional stops and failures already shown as notifications.``status_label`` is an optional backend-computed clean tool-call label(claude-pipe style) used ONLY as the concise status-bubble body for the@@ -1387,10 +1389,14 @@ class ConsolidatedMessageDispatcher:# Terminal status-bubble reason word for the done/orphan footer:# a clean turn is "done" (✅); a failure is "stopped" (⏹) when it was an- # intentional silent stop (e.g. user stop), else "failed" (⏹). Computed- # here where both is_error + level are known, then threaded into the- # compose/tidy helpers so the footer marker stays consistent.- terminal_reason = "done" if not is_error else ("stopped" if level == "silent" else "failed")+ # intentional silent stop (e.g. user stop), else "failed" (⏹). An explicit+ # diagnostic distinguishes a silent backend failure from a silent stop.+ if not is_error:+ terminal_reason = "done"+ elif level == "silent" and terminal_error is None:+ terminal_reason = "stopped"+ else:+ terminal_reason = "failed"# OUTBOUND status chokepoint (one of exactly two — the other is the# inbound AgentService.handle_message). A terminal ``result`` ends the@@ -1525,6 +1531,7 @@ class ConsolidatedMessageDispatcher:recorded_text,message_id,is_error=is_error,+ terminal_error=terminal_error,output_semantics=output_semantics,)elif canonical_type == "result" or (context.platform_specific or {}).get("task_trigger_kind") != "agent_run":diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.pyindex 52eecb58b..521f5fc0c 100644--- a/core/scheduled_tasks.py+++ b/core/scheduled_tasks.py@@ -1122,12 +1122,19 @@ class TaskExecutionStore:error=error,)- def defer_run_terminal(self, run_id: str, *, terminal_status: str) -> bool:+ def defer_run_terminal(+ self,+ run_id: str,+ *,+ terminal_status: str,+ error: Optional[str] = None,+ ) -> bool:if self._sqlite is None:return Falsereturn self._sqlite.defer_run_terminal(run_id,terminal_status=terminal_status,+ error=error,)def update_callback_status(diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.pyindex 97285e7ee..296ccb7cd 100644--- a/modules/agents/claude_agent.py+++ b/modules/agents/claude_agent.py@@ -2312,6 +2312,12 @@ class ClaudeAgent(BaseAgent):str(getattr(message, "result", "") or "").strip(),cls._error_value_text(error_value),]+ error_token = cls._error_value_text(error_value).lower()+ if not candidates[0] and error_token in {+ "authentication_error",+ "authentication_failed",+ }:+ candidates.insert(0, "OAuth authentication failed.")if isinstance(errors, (list, tuple)):candidates.extend(cls._error_value_text(item) for item in errors)elif errors:diff --git a/storage/background.py b/storage/background.pyindex 2da52bea4..5d1484b56 100644--- a/storage/background.py+++ b/storage/background.py@@ -1277,11 +1277,15 @@ class SQLiteBackgroundTaskStore:result_payload = {}payload_changed = Falseeffective_terminal_status = terminal_status+ effective_terminal_error = errorif terminal_status and "deferred_terminal_status" in result_payload:effective_terminal_status = _stronger_terminal_status(result_payload.pop("deferred_terminal_status", None),terminal_status,)+ deferred_error = result_payload.pop("deferred_terminal_error", None)+ if deferred_error is not None:+ effective_terminal_error = str(deferred_error)payload_changed = Trueraw_outputs = result_payload.get("outputs")outputs = [dict(item) for item in raw_outputs if isinstance(item, dict)] if isinstance(raw_outputs, list) else []@@ -1334,8 +1338,8 @@ class SQLiteBackgroundTaskStore:"completed_at": now,"updated_at": now,}- if error is not None:- terminal_values["error"] = str(error)+ if effective_terminal_error is not None:+ terminal_values["error"] = str(effective_terminal_error)transition = conn.execute(update(agent_runs).where(agent_runs.c.id == run_id)@@ -1370,9 +1374,10 @@ class SQLiteBackgroundTaskStore:run_id: str,*,terminal_status: str,+ error: Optional[str] = None,updated_at: Optional[str] = None,) -> bool:- """Remember a terminal intent while an owned Activity still blocks it."""+ """Remember a terminal intent and diagnostic while an Activity blocks it."""now = updated_at or _utc_now_iso()row_to_publish = None@@ -1393,9 +1398,17 @@ class SQLiteBackgroundTaskStore:result_payload.get("deferred_terminal_status"),terminal_status,)- if result_payload.get("deferred_terminal_status") == normalized:+ status_changed = result_payload.get("deferred_terminal_status") != normalized+ error_text = str(error) if error is not None else None+ error_changed = bool(+ error_text is not None+ and not result_payload.get("deferred_terminal_error")+ )+ if not status_changed and not error_changed:return Falseresult_payload["deferred_terminal_status"] = normalized+ if error_changed:+ result_payload["deferred_terminal_error"] = error_textconn.execute(update(agent_runs).where(agent_runs.c.id == run_id)@@ -1438,6 +1451,7 @@ class SQLiteBackgroundTaskStore:if not deferred_status:return Falseresult_payload.pop("deferred_terminal_status", None)+ deferred_error = result_payload.pop("deferred_terminal_error", None)status = (_stronger_terminal_status(deferred_status, terminal_status)if terminal_status@@ -1449,8 +1463,9 @@ class SQLiteBackgroundTaskStore:"updated_at": now,"result_payload_json": _json_dumps(result_payload),}- if error is not None:- values["error"] = error+ effective_error = deferred_error if deferred_error is not None else error+ if effective_error is not None:+ values["error"] = str(effective_error)transition = conn.execute(update(agent_runs).where(agent_runs.c.id == run_id)diff --git a/tests/test_claude_agent_sessions.py b/tests/test_claude_agent_sessions.pyindex b28039249..e1043e854 100644--- a/tests/test_claude_agent_sessions.py+++ b/tests/test_claude_agent_sessions.py@@ -1999,7 +1999,13 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):await agent._receive_messages(_Client(), "session-1", "/tmp/work", context)- controller.agent_auth_service.maybe_emit_auth_recovery_message.assert_awaited_once()+ controller.agent_auth_service.maybe_emit_auth_recovery_message.assert_awaited_once_with(+ context,+ "claude",+ "❌ Claude error: OAuth authentication failed.",+ output=ANY,+ terminal_error="OAuth authentication failed.",+ )agent._remove_ack_reaction.assert_awaited_once_with(pending_request)self.assertNotIn(composite_key, controller.receiver_tasks)self.assertNotIn(composite_key, controller.claude_sessions)diff --git a/tests/test_message_dispatcher_result_fallback.py b/tests/test_message_dispatcher_result_fallback.pyindex 110dccf30..6564e81bb 100644--- a/tests/test_message_dispatcher_result_fallback.py+++ b/tests/test_message_dispatcher_result_fallback.py@@ -772,6 +772,26 @@ class MessageDispatcherStatusChokepointTests(unittest.IsolatedAsyncioTestCase):await dispatcher.emit_agent_message(_avibe_ctx(), "result", "", is_error=True)self.assertEqual(controller.status_calls, [("ses-1", "failed")])+ async def test_silent_backend_failure_collapses_status_as_failed(self):+ controller = _AvibeStatusController()+ dispatcher = ConsolidatedMessageDispatcher(controller)+ dispatcher._collapse_status_bubble = mock.AsyncMock()+ context = _avibe_ctx()+ with mock.patch("core.message_dispatcher.persist_agent_message"):+ await dispatcher.emit_agent_message(+ context,+ "result",+ "",+ is_error=True,+ level="silent",+ terminal_error="provider unavailable",+ )+ dispatcher._collapse_status_bubble.assert_awaited_once_with(+ context,+ controller.im_client,+ reason="failed",+ )+async def test_notify_does_not_settle_dot(self):controller = _AvibeStatusController()dispatcher = ConsolidatedMessageDispatcher(controller)diff --git a/tests/test_message_dispatcher_scheduled.py b/tests/test_message_dispatcher_scheduled.pyindex b51bffcd9..21ec87624 100644--- a/tests/test_message_dispatcher_scheduled.py+++ b/tests/test_message_dispatcher_scheduled.py@@ -245,6 +245,61 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(payload["terminal_status"], "failed")self.assertEqual(payload["error"], "provider unavailable")+ async def test_blocking_activity_defers_terminal_error_with_status(self):+ controller = _StubController()+ controller.agent_service = SimpleNamespace(+ activities=SimpleNamespace(has_blocking_run_activity=lambda _run_id: True),+ 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 defer_run_terminal(self, run_id, **kwargs):+ calls.append(("defer", run_id, kwargs))++ def record_run_output(self, run_id, **kwargs):+ calls.append(("output", 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(+ calls[0],+ (+ "defer",+ "run-failed",+ {"terminal_status": "failed", "error": "provider unavailable"},+ ),+ )+ self.assertEqual(calls[1][0:2], ("output", "run-failed"))+ self.assertIsNone(calls[1][2]["terminal_status"])+ self.assertEqual(calls[1][2]["error"], "provider unavailable")+async def test_notify_output_uses_stable_persistence_identity(self):controller = _StubController()dispatcher = ConsolidatedMessageDispatcher(controller)@@ -652,6 +707,46 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):],)+ async def test_suppressed_agent_run_failure_records_diagnostic(self):+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)+ context = MessageContext(+ user_id="scheduled",+ channel_id="C123",+ platform="slack",+ platform_specific={+ "suppress_delivery": True,+ "task_trigger_kind": "agent_run",+ "task_execution_id": "run-agent",+ },+ )+ 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()):+ message_id = await dispatcher.emit_agent_message(+ context,+ "result",+ "private failure",+ is_error=True,+ terminal_error="provider unavailable",+ )++ self.assertEqual(message_id, "suppressed:run-agent")+ self.assertEqual(len(calls), 1)+ self.assertEqual(calls[0][0], "run-agent")+ self.assertEqual(calls[0][1]["terminal_status"], "failed")+ self.assertEqual(calls[0][1]["error"], "provider unavailable")+async def test_suppressed_coalesced_agent_run_result_marks_each_run_terminal(self):controller = _StubController()dispatcher = ConsolidatedMessageDispatcher(controller)diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.pyindex bf918bbf6..84047d8cb 100644--- a/tests/test_scheduled_tasks.py+++ b/tests/test_scheduled_tasks.py@@ -2259,6 +2259,46 @@ def test_failed_run_records_error_and_enqueues_one_terminal_callback(assert callback_runs[0]["source_actor"] == f"{request.id}:terminal:failed"+def test_deferred_failure_preserves_error_through_later_output(+ tmp_path: Path,+ monkeypatch,+) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ request_store = TaskExecutionStore()+ request = request_store.enqueue_agent_run(+ session_id="target-session",+ message="delegated work",+ agent_name="claude",+ )+ assert request_store.claim(request.id) is not None+ sqlite_store = request_store._sqlite+ assert sqlite_store is not None++ assert sqlite_store.defer_run_terminal(+ request.id,+ terminal_status="failed",+ error="provider unavailable",+ ) is True+ running = request_store.get_run(request.id)+ assert running is not None+ assert running["result_payload"]["deferred_terminal_error"] == "provider unavailable"++ terminal = sqlite_store.record_run_output(+ request.id,+ output_id="activity-output",+ text="background output",+ terminal_status="succeeded",+ )++ settled = request_store.get_run(request.id)+ assert settled is not None+ assert terminal["terminal_transition"] is True+ assert settled["status"] == "failed"+ assert settled["error"] == "provider unavailable"+ assert "deferred_terminal_status" not in settled["result_payload"]+ assert "deferred_terminal_error" not in settled["result_payload"]++@pytest.mark.parametrize(("activity_status", "expected_run_status"),[