Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

fix(harness): preserve Turn failure delivery evidence

cyh9a32fc109f88
diff --git a/core/backend_failure.py b/core/backend_failure.py
index 350545dc7..010b48988 100644
--- a/core/backend_failure.py
+++ b/core/backend_failure.py
@@ -258,16 +258,18 @@ async def emit_backend_failure(
auth recovery supplied that immediate notification.
``delivery``, when supplied, is filled in with what the notify attempt actually
- proved. Harness supplies an evidence object automatically because linked Runs
- owe a durable fallback; other callers opt in when they need the same proof. A
- clean return alone is not enough to distinguish a delivered message from a lost
- one.
+ proved. A durable Turn or legacy Harness Run supplies an evidence object
+ automatically so Runs attached after settlement inherit the same proof. A clean
+ return alone is not enough to distinguish a delivered message from a lost one.
"""
backend_name = str(backend or "backend").strip() or "backend"
error, visible = _failure_texts(backend_name, diagnostic, display_text)
terminal = _terminal_output(request, output)
harness_run_id = _harness_run_identity(context, request)
+ owns_failure_contract = bool(
+ _turn_failure_identity(context, request) or harness_run_id
+ )
notification = backend_failure_notification_output(
context,
backend_name,
@@ -277,7 +279,7 @@ async def emit_backend_failure(
)
notification_identity = str(notification.metadata.get("failure_id") or "").strip()
live_delivery = delivery
- if harness_run_id and live_delivery is None:
+ if owns_failure_contract and live_delivery is None:
live_delivery = DeliveryEvidence()
platform_specific = getattr(context, "platform_specific", None) or {}
@@ -309,7 +311,7 @@ async def emit_backend_failure(
async def settle_terminal_failure() -> None:
terminal_output = terminal
- if harness_run_id:
+ if owns_failure_contract:
metadata = dict(terminal.metadata)
metadata["turn_failure_notification"] = {
"failure_id": notification_identity,
@@ -354,9 +356,9 @@ async def emit_backend_failure(
if handled_auth:
return True
- # ``delivery`` is passed only when the emitter supports it. Harness creates the
- # object automatically, but controller-like test and integration doubles with
- # the legacy signature must keep working.
+ # ``delivery`` is passed only when the emitter supports it. Durable Turn and
+ # Harness contexts create the object automatically, but controller-like test
+ # and integration doubles with the legacy signature must keep working.
notify_kwargs: dict[str, Any] = {"output": notification}
if live_delivery is not None:
emit = controller.emit_agent_message
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index 26af4297c..5a7578fdc 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -13,6 +13,7 @@ from core.audio_asr import (
detect_audio_mime_from_sample,
format_audio_transcript_echo,
)
+from core.backend_failure import emit_backend_failure
from core.message_output import (
HARNESS_PROMPT_ECHO_SPEC_KEY,
terminal_output_for,
@@ -845,17 +846,10 @@ class MessageHandler(BaseHandler):
session_id=str(bound_session_id),
)
except KeyError:
- await self._handle_missing_agent(context, agent_name)
- # Synchronous terminal failure (no agent dispatched). Settle the
- # turn through the OUTBOUND status chokepoint: an empty terminal
- # error result turns the dot red + releases the SSE waiter (the
- # missing-agent message was already shown above). No separate latch.
- await self.controller.emit_agent_message(
+ await self._handle_missing_agent(
context,
- "result",
- "",
- is_error=True,
- output=terminal_output_for(request),
+ agent_name,
+ request=request,
)
# Clean up reaction on error
await self._remove_ack_reaction(context, request)
@@ -1612,14 +1606,30 @@ class MessageHandler(BaseHandler):
logger.error(f"Error handling inline stop: {e}", exc_info=True)
return False
- async def _handle_missing_agent(self, context: MessageContext, agent_name: str):
- """Notify user when a requested agent backend is unavailable."""
+ async def _handle_missing_agent(
+ self,
+ context: MessageContext,
+ agent_name: str,
+ *,
+ request: AgentRequest | None = None,
+ ) -> None:
+ """Notify and, for a dispatched Turn, settle a missing Agent failure."""
target = agent_name or self.controller.agent_service.default_agent
backend = self._missing_agent_backend(context, target)
display_backend = display_name_for_backend(backend) if backend else str(target)
hint_key = f"error.agentNotConfiguredHint.{backend}" if backend else "error.agentNotConfiguredHint.generic"
hint = self._t(hint_key)
msg = f"❌ {self._t('error.agentNotConfigured', agent=target, backend=display_backend, hint=hint)}"
+ if request is not None:
+ await emit_backend_failure(
+ self.controller,
+ context,
+ backend or str(target),
+ msg,
+ display_text=msg,
+ request=request,
+ )
+ return
await self._get_im_client(context).send_message(context, msg)
await self._stream_terminal_error(context, msg)
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index 49fe9504c..5390551ac 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -1377,7 +1377,7 @@ class ConsolidatedMessageDispatcher:
if isinstance(notification, dict) and str(notification.get("failure_id") or "").strip():
return output_semantics
turn_id = str((context.platform_specific or {}).get("turn_token") or "").strip()
- if not turn_id or not self._terminal_agent_run_ids(context, output_semantics):
+ if not turn_id:
return output_semantics
metadata = dict(output_semantics.metadata)
metadata["turn_failure_notification"] = {
diff --git a/docs/plans/harness-watch-run-failure-boundary.md b/docs/plans/harness-watch-run-failure-boundary.md
index a86ebf15e..ed7fb1623 100644
--- a/docs/plans/harness-watch-run-failure-boundary.md
+++ b/docs/plans/harness-watch-run-failure-boundary.md
@@ -175,8 +175,10 @@ does not claim that an event was detected.
- `HFR-459`: independent Activity completions reserve the SQLite writer before
reading deferred participants and electing their shared Turn fallback owner.
- `HFR-472`: an empty failed Harness Turn synthesizes the existing Turn failure
- contract before its immutable snapshot, so every accepted Run shares one
- fallback owner instead of emitting one notice per Run.
+ contract before its immutable snapshot, even before the first participant is
+ attached, so every accepted Run shares one fallback owner instead of emitting
+ one notice per Run. A primary error already delivered through the shared
+ backend-failure path carries its acknowledgement into the same contract.
Residual manual check: trigger two one-shot Watches into one failing Turn and
confirm that the conversation contains one backend error, both Runs are failed,
diff --git a/tests/scenarios/harness_failure_recovery/catalog.yaml b/tests/scenarios/harness_failure_recovery/catalog.yaml
index c58e6edf3..63438ac05 100644
--- a/tests/scenarios/harness_failure_recovery/catalog.yaml
+++ b/tests/scenarios/harness_failure_recovery/catalog.yaml
@@ -4241,8 +4241,9 @@ scenarios:
kind: failure_recovery
layer: contract
backend: shared
- # The shared dispatcher stamps one Turn failure identity before the immutable
- # terminal snapshot; the existing atomic settlement elects one Run owner.
+ # The shared dispatcher stamps one Turn failure identity before participants
+ # arrive; an already shown primary keeps its acknowledgement, and the existing
+ # atomic settlement elects one Run owner only when participants exist.
test: tests/test_message_dispatcher_result_fallback.py::MessageDispatcherResultFallbackTests::test_hfr_472_empty_failed_turn_creates_one_shared_fallback_contract
manual_evidence:
- local Incus backend process death after prompt acceptance
diff --git a/tests/test_backend_failure.py b/tests/test_backend_failure.py
index 00a158e06..b0d05de60 100644
--- a/tests/test_backend_failure.py
+++ b/tests/test_backend_failure.py
@@ -28,6 +28,43 @@ def _request() -> AgentRequest:
class BackendFailureTests(unittest.IsolatedAsyncioTestCase):
+ async def test_turn_without_current_runs_preserves_primary_delivery_for_late_runs(
+ self,
+ ) -> None:
+ request = _request()
+ emissions = []
+
+ async def emit(context, message_type, text, **kwargs):
+ emissions.append((message_type, text, kwargs))
+ evidence = kwargs.get("delivery")
+ if message_type == "notify" and evidence is not None:
+ evidence.persisted_row = {"id": "msg-primary"}
+ return "msg-primary"
+ return None
+
+ controller = SimpleNamespace(
+ agent_auth_service=SimpleNamespace(),
+ emit_agent_message=emit,
+ )
+
+ await emit_backend_failure(
+ controller,
+ request.context,
+ "codex",
+ "provider unavailable",
+ request=request,
+ )
+
+ terminal_output = emissions[1][2]["output"]
+ self.assertEqual(
+ terminal_output.metadata["turn_failure_notification"],
+ {
+ "failure_id": "turn-1",
+ "ack_evidence": "receipt",
+ "delivered": True,
+ },
+ )
+
async def test_harness_turn_notifies_live_and_carries_delivery_evidence_to_settlement(
self,
) -> None:
@@ -258,14 +295,18 @@ class BackendFailureTests(unittest.IsolatedAsyncioTestCase):
request=request,
)
- controller.emit_agent_message.assert_awaited_once_with(
- request.context,
- "result",
- "",
- is_error=True,
- level="silent",
- output=request.output,
- terminal_error="401 Unauthorized",
+ terminal_call = controller.emit_agent_message.await_args
+ self.assertEqual(terminal_call.args, (request.context, "result", ""))
+ self.assertTrue(terminal_call.kwargs["is_error"])
+ self.assertEqual(terminal_call.kwargs["level"], "silent")
+ self.assertEqual(terminal_call.kwargs["terminal_error"], "401 Unauthorized")
+ self.assertEqual(
+ terminal_call.kwargs["output"].metadata["turn_failure_notification"],
+ {
+ "failure_id": "turn-1",
+ "ack_evidence": None,
+ "delivered": False,
+ },
)
async def test_separates_notify_from_terminal_settlement(self) -> None:
@@ -293,7 +334,6 @@ class BackendFailureTests(unittest.IsolatedAsyncioTestCase):
(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,
@@ -302,6 +342,7 @@ class BackendFailureTests(unittest.IsolatedAsyncioTestCase):
"notify",
"Codex failed: provider unavailable",
output=ANY,
+ delivery=ANY,
),
)
self.assertFalse(notify_call.kwargs["output"].settles_run)
@@ -325,10 +366,18 @@ class BackendFailureTests(unittest.IsolatedAsyncioTestCase):
"",
is_error=True,
level="silent",
- output=terminal_output,
+ output=ANY,
terminal_error="provider unavailable",
),
)
+ self.assertEqual(
+ terminal_call.kwargs["output"].metadata["turn_failure_notification"],
+ {
+ "failure_id": "turn-1",
+ "ack_evidence": "delivery_only",
+ "delivered": False,
+ },
+ )
async def test_identity_is_stable_for_duplicate_terminal_events(self) -> None:
request = _request()
@@ -377,14 +426,15 @@ class BackendFailureTests(unittest.IsolatedAsyncioTestCase):
request=request,
)
+ self.assertEqual(len(terminal_calls), 1)
+ self.assertTrue(terminal_calls[0]["is_error"])
+ self.assertEqual(terminal_calls[0]["level"], "silent")
+ self.assertEqual(terminal_calls[0]["terminal_error"], "transport failed")
self.assertEqual(
- terminal_calls,
- [
- {
- "is_error": True,
- "level": "silent",
- "output": request.output,
- "terminal_error": "transport failed",
- }
- ],
+ terminal_calls[0]["output"].metadata["turn_failure_notification"],
+ {
+ "failure_id": "turn-1",
+ "ack_evidence": None,
+ "delivered": False,
+ },
)
diff --git a/tests/test_message_dispatcher_result_fallback.py b/tests/test_message_dispatcher_result_fallback.py
index 17c4fc35f..e389f219e 100644
--- a/tests/test_message_dispatcher_result_fallback.py
+++ b/tests/test_message_dispatcher_result_fallback.py
@@ -284,6 +284,41 @@ class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):
)
self.assertEqual(controller.im_client.sent_messages, [])
+ async def test_hfr_472_contract_is_snapshotted_before_the_first_run_arrives(self):
+ controller = self._terminal_lifecycle_controller()
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ dispatcher._collapse_status_bubble = mock.AsyncMock()
+ dispatcher._clear_consolidated_state = mock.AsyncMock()
+ context = MessageContext(
+ user_id="U1",
+ channel_id="C1",
+ platform="slack",
+ platform_specific={
+ "agent_runtime_turn_key": "runtime-1",
+ "agent_runtime_turn_token": "runtime-turn-1",
+ "turn_token": "turn-before-run",
+ },
+ )
+
+ await dispatcher.emit_agent_message(
+ context,
+ "result",
+ "",
+ is_error=True,
+ output=MessageOutput(completes_turn=True, completes_run=True),
+ )
+
+ evidence = controller.session_turns.on_terminal_result.call_args.kwargs[
+ "terminal_evidence"
+ ]
+ self.assertEqual(
+ evidence["output_provenance"]["turn_failure_notification"],
+ {
+ "failure_id": "turn:turn-before-run",
+ "delivered": False,
+ },
+ )
+
def test_visible_direct_error_does_not_create_a_turn_fallback_contract(self):
dispatcher = ConsolidatedMessageDispatcher(_StubController(platform="slack"))
context = MessageContext(
diff --git a/tests/test_message_handler_missing_agent.py b/tests/test_message_handler_missing_agent.py
index 14321dff9..426ee2b6f 100644
--- a/tests/test_message_handler_missing_agent.py
+++ b/tests/test_message_handler_missing_agent.py
@@ -5,6 +5,7 @@ from types import SimpleNamespace
import anyio
from core.handlers.message_handler import MessageHandler
+from modules.agents.base import AgentRequest
from modules.im import MessageContext
@@ -26,7 +27,9 @@ class _StubController:
self.session_manager = SimpleNamespace()
self.receiver_tasks = {}
self.agent_service = SimpleNamespace(default_agent="claude", agents={})
+ self.agent_auth_service = SimpleNamespace()
self.vibe_agent_store = SimpleNamespace(get=lambda _name: None)
+ self.emissions = []
def get_im_client_for_context(self, context):
return self.im_client
@@ -34,6 +37,14 @@ class _StubController:
def _get_lang(self) -> str:
return "zh"
+ async def emit_agent_message(self, context, message_type, text, **kwargs):
+ self.emissions.append((message_type, text, kwargs))
+ evidence = kwargs.get("delivery")
+ if message_type == "notify" and evidence is not None:
+ evidence.persisted_row = {"id": "msg-primary"}
+ return "msg-primary"
+ return None
+
def test_missing_opencode_agent_hint_does_not_mention_codex():
controller = _StubController()
@@ -51,3 +62,48 @@ def test_missing_opencode_agent_hint_does_not_mention_codex():
assert "OpenCode" in sent
assert "OPENCODE_CLI_PATH" in sent
assert "Codex" not in sent
+
+
+def test_dispatched_missing_agent_preserves_primary_delivery_in_terminal_contract():
+ controller = _StubController()
+ handler = MessageHandler(controller)
+ context = MessageContext(
+ user_id="U1",
+ channel_id="C1",
+ platform="avibe",
+ platform_specific={
+ "turn_token": "turn-missing-agent",
+ "task_execution_id": "run-missing-agent",
+ "task_trigger_kind": "scheduled",
+ },
+ )
+ request = AgentRequest(
+ context=context,
+ message="work",
+ user_message="work",
+ working_path="/tmp/work",
+ base_session_id="session-1",
+ composite_session_id="session-1:/tmp/work",
+ session_key="avibe::project::p1",
+ )
+
+ async def run() -> None:
+ await handler._handle_missing_agent(
+ context,
+ "opencode",
+ request=request,
+ )
+
+ anyio.run(run)
+
+ assert [message_type for message_type, _text, _kwargs in controller.emissions] == [
+ "notify",
+ "result",
+ ]
+ terminal = controller.emissions[1][2]["output"]
+ assert terminal.metadata["turn_failure_notification"] == {
+ "failure_id": "turn:turn-missing-agent",
+ "ack_evidence": "receipt",
+ "delivered": True,
+ }
+ assert controller.im_client.sent == []