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(dispatcher): treat a partial split result as undelivered (#2601)
Max80e6d359031a
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.pyindex 52aa8d48e..d52591eae 100644--- a/core/message_dispatcher.py+++ b/core/message_dispatcher.py@@ -3192,6 +3192,9 @@ class ConsolidatedMessageDispatcher:primary_message_id: Optional[str] = Nonescheduled_anchor_message_id: Optional[str] = Nonedelivered_as_attachment = False+ # Set once the result has been split-sent, whether or not it fully+ # arrived: the fallback must not split-send the same content again.+ split_attempted = False# Concise status bubble (Slack/Discord): the live process bubble for# this turn. The result is ALWAYS delivered as a NEW message (never@@ -3287,6 +3290,7 @@ class ConsolidatedMessageDispatcher:else:logger.error("Failed to send result message: %s", err)elif self._should_split_long_result(context):+ split_attempted = Truetry:primary_message_id = await self._send_split_result_messages(im_client,@@ -3353,8 +3357,10 @@ class ConsolidatedMessageDispatcher:scheduled_anchor_message_id = primary_message_idlogger.info("Result delivered as .md file attachment (fallback)")- # Fallback 2: split into multiple messages.- if not file_uploaded:+ # Fallback 2: split into multiple messages, unless the split+ # path already ran; repeating it would resend the chunks the+ # user has already received.+ if not file_uploaded and not split_attempted:try:primary_message_id = await self._send_split_result_messages(im_client,@@ -3365,7 +3371,8 @@ class ConsolidatedMessageDispatcher:subtext=done_footer,)scheduled_anchor_message_id = primary_message_id- logger.info("Result delivered via split messages (fallback)")+ if primary_message_id is not None:+ logger.info("Result delivered via split messages (fallback)")except Exception as split_err:logger.error("Split message fallback also failed: %s", split_err)@@ -3941,7 +3948,10 @@ class ConsolidatedMessageDispatcher:Quick-reply buttons and the ``subtext`` done-footer both ride on the LASTchunk (a mid-stream footer would read wrong); every chunk is a new send so- the result notifies. Returns the first chunk's id (the delivery anchor).+ the result notifies. Returns the first chunk's id (the delivery anchor)+ only when EVERY chunk was delivered, and ``None`` otherwise: the caller+ reads a non-empty id as "the whole result reached the user", so a partial+ split must hand the complete content to the caller's fallback instead."""plan = self._plan_result_split_for_context(context, text)if not plan.links_whole:@@ -3971,8 +3981,7 @@ class ConsolidatedMessageDispatcher:logger.warning("Failed to send split result chunk with quick replies, falling back: %s", err)if message_id is None:- # A later-chunk failure must NOT propagate so an earlier delivered- # chunk isn't lost — best-effort, log, continue.+ # Keep the send error local; the missing id is handled below.try:message_id = await self._send_result_inline(im_client, context, chunk, [], parse_mode, subtext=chunk_subtext@@ -3981,15 +3990,16 @@ class ConsolidatedMessageDispatcher:logger.warning("Failed to send split result chunk %d: %s", index, err)message_id = None- if index == 0 and message_id is None:- # The HEAD chunk failed: abandon the split and return None so the- # caller's fallback delivers the COMPLETE content (e.g. as a .md- # upload). Returning a later chunk's id here would mark a head-less- # partial — the user seeing only the tail — as a successful delivery.- logger.warning("Split result head chunk failed to send; abandoning partial split")+ if message_id is None:+ # Any missing chunk means the user did not get the whole result:+ # head-less, tail-less, or with a hole in the middle. Stop sending+ # and return None so the caller's fallback delivers the COMPLETE+ # content (e.g. as a .md upload) rather than recording a partial+ # as a successful delivery.+ logger.warning("Split result chunk %d of %d failed to send; abandoning partial split", index, len(chunks))return None- if first_message_id is None and message_id is not None:+ if first_message_id is None:first_message_id = message_idreturn first_message_iddiff --git a/tests/test_message_dispatcher_result_fallback.py b/tests/test_message_dispatcher_result_fallback.pyindex 32296e48e..68588ccf4 100644--- a/tests/test_message_dispatcher_result_fallback.py+++ b/tests/test_message_dispatcher_result_fallback.py@@ -1396,6 +1396,63 @@ class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):self.assertIsNone(result)persist.assert_not_called()+ async def _emit_split_result(self, *, fail_chunk: int | None, upload_id: str | None):+ """Emit a Discord result long enough to split, optionally failing one chunk."""++ class _FlakyChunkClient(_StubIMClient):+ def __init__(self):+ super().__init__(upload_id=upload_id)+ self.chunk_attempts = 0++ async def send_message(self, context, text, parse_mode=None, reply_to=None):+ if text.startswith("x"):+ attempt = self.chunk_attempts+ self.chunk_attempts += 1+ if attempt == fail_chunk:+ raise RuntimeError("chunk send failed")+ return await super().send_message(context, text, parse_mode, reply_to)++ controller = _StubController(platform="discord", im_client=_FlakyChunkClient())+ dispatcher = ConsolidatedMessageDispatcher(controller)+ context = MessageContext(user_id="U1", channel_id="C1", platform="discord")+ text = "x" * 5000+ with mock.patch("core.message_dispatcher.persist_agent_message") as persist:+ message_id = await dispatcher.emit_agent_message(context, "result", text)+ return controller.im_client, dispatcher, text, message_id, persist++ async def test_split_result_later_chunk_failure_delivers_complete_document(self):+ client, dispatcher, text, message_id, persist = await self._emit_split_result(fail_chunk=1, upload_id="file-1")++ # The split stops at the failed chunk and the complete result is uploaded once.+ self.assertEqual(client.chunk_attempts, 2)+ self.assertEqual([upload[2] for upload in client.uploaded_markdowns], [text])+ self.assertEqual(message_id, "file-1")+ sent_texts = [sent[1] for sent in client.sent_messages]+ self.assertIn(dispatcher._t("info.resultDeliveredAsAttachment"), sent_texts)+ persist.assert_called_once()++ async def test_split_result_later_chunk_and_upload_failure_reports_failure_without_resending(self):+ client, dispatcher, _text, message_id, persist = await self._emit_split_result(fail_chunk=1, upload_id=None)++ # No second split: chunk 0 is never resent, and the turn reports failure.+ self.assertEqual(client.chunk_attempts, 2)+ self.assertEqual(len(client.uploaded_markdowns), 1)+ self.assertIsNone(message_id)+ sent_texts = [sent[1] for sent in client.sent_messages]+ self.assertEqual(len([sent for sent in sent_texts if sent.startswith("x")]), 1)+ self.assertIn(dispatcher._t("error.resultDeliveryFailed"), sent_texts)+ persist.assert_not_called()++ async def test_split_result_all_chunks_delivered_uploads_nothing(self):+ client, dispatcher, text, message_id, persist = await self._emit_split_result(fail_chunk=None, upload_id="file-1")++ self.assertGreaterEqual(client.chunk_attempts, 3)+ chunks = [sent[1] for sent in client.sent_messages if sent[1].startswith("x")]+ self.assertEqual("".join(chunks), text)+ self.assertEqual(message_id, "msg-1")+ self.assertEqual(client.uploaded_markdowns, [])+ persist.assert_called_once()+async def test_removed_platform_result_drop_is_not_persisted(self):controller = _StubController(platform="discord", im_client=_DropClient())dispatcher = ConsolidatedMessageDispatcher(controller)diff --git a/tests/test_message_dispatcher_status_bubble.py b/tests/test_message_dispatcher_status_bubble.pyindex a9107b7ca..2855aeb0e 100644--- a/tests/test_message_dispatcher_status_bubble.py+++ b/tests/test_message_dispatcher_status_bubble.py@@ -465,19 +465,20 @@ class StatusBubbleResultTests(unittest.IsolatedAsyncioTestCase):# The bubble was deleted (never reused as a chunk).self.assertEqual(controller.im_client.deletes, ["msg-1"])- async def test_split_later_chunk_failure_keeps_first_chunk(self):- # Discord long result: chunk 0 sends fine, a later chunk send fails. The- # failure must NOT propagate; the first chunk stays delivered and the- # bubble is still retired (deleted).+ async def test_split_later_chunk_failure_is_not_reported_as_delivered(self):+ # Discord long result: chunk 0 sends fine, a later chunk send fails. A+ # partial split must not count as delivery: the split stops at the failed+ # chunk, is never re-sent, and (with no file route on this client) the+ # turn ends with the delivery-failed notice instead of a success anchor.class _FailLaterChunk(_EditClient):def __init__(self):super().__init__()- self._x_sends = 0+ self.chunk_attempts = 0async def send_message(self, context, text, parse_mode=None, reply_to=None, subtext=None):if text.startswith("x"):- self._x_sends += 1- if self._x_sends >= 2: # fail the 2nd+ chunk+ self.chunk_attempts += 1+ if self.chunk_attempts >= 2: # fail the 2nd+ chunkraise RuntimeError("later chunk send failed")return await super().send_message(context, text, parse_mode, reply_to, subtext)@@ -486,9 +487,14 @@ class StatusBubbleResultTests(unittest.IsolatedAsyncioTestCase):ctx = _ctx("discord")with mock.patch("core.message_dispatcher.persist_agent_message"):await d.emit_agent_message(ctx, "toolcall", "🔧 `Bash` `{}`") # bubble msg-1- result_id = await d.emit_agent_message(ctx, "result", "x" * 2500)- self.assertEqual(result_id, "msg-2") # first chunk delivered- self.assertEqual(controller.im_client.deletes, ["msg-1"]) # bubble still retired+ result_id = await d.emit_agent_message(ctx, "result", "x" * 5000)+ self.assertIsNone(result_id)+ # Chunk 0 delivered, chunk 1 failed, nothing after it and no second split.+ self.assertEqual(controller.im_client.chunk_attempts, 2)+ sent_texts = [text for _, text, _ in controller.im_client.sent]+ self.assertEqual(len([text for text in sent_texts if text.startswith("x")]), 1)+ self.assertIn(d._t("error.resultDeliveryFailed"), sent_texts)+ self.assertNotIn("msg-1", controller.im_client.deletes) # bubble not retired as deliveredasync def test_split_head_chunk_failure_returns_none(self):# If the HEAD chunk fails to send, the split is abandoned (returns None) so