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): a silent final reply makes the Turn's last visible text its result (#2803)
Call White4eceb80f07ed
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.pyindex d1f06ad6f..d022bcd2b 100644--- a/core/message_dispatcher.py+++ b/core/message_dispatcher.py@@ -34,6 +34,7 @@ from core.message_mirror import (agent_message_exists,persist_agent_message,persist_silent_terminal,+ promote_turn_text_to_result,)from core.message_output import (HARNESS_RUN_ID_TRIGGER_KINDS,@@ -419,6 +420,13 @@ class ConsolidatedMessageDispatcher:# first use per turn (see ``_concise_progress_style``), dropped in# ``_drop_status_keys``.self._turn_progress_style: dict[str, str] = {}+ # Per turn-sink key (thread-scoped, so concurrent Turns in one channel stay+ # apart), the current Turn's latest transcript-visible text that did not+ # end it (an ``output`` boundary or an ``interim`` bubble), with that Turn's+ # token. A Turn that ends on a silent reply makes this row its result+ # (``promote_turn_text_to_result``). Every lifecycle-terminal emit takes+ # the entry, so it never outlives its Turn.+ self._turn_visible_text: dict[str, tuple[str, str]] = {}# Harness deliveries whose prompt has already been echoed to IM, kept as a# bounded FIFO (see ``emit_harness_prompt``). Per-process only: a restart# replay writes a new Delivery anyway, and a duplicated echo is cosmetic@@ -2775,6 +2783,26 @@ class ConsolidatedMessageDispatcher:return Truereturn sum(1 for line in body.splitlines() if line.strip()) >= _INTERIM_MIN_LINES+ def _remember_turn_text(self, context: MessageContext, row: Optional[dict]) -> None:+ """Record a persisted row as its Turn's latest visible text.++ Only a row whose Turn is identified: without a token, a later Turn's+ silent final could not tell this row apart from its own.+ """++ row_id = (row or {}).get("id")+ turn_token = (context.platform_specific or {}).get("turn_token")+ if row_id and turn_token:+ self._turn_visible_text[resolve_turn_sink_key(self.controller, context)] = (turn_token, row_id)++ def _take_turn_text(self, context: MessageContext) -> Optional[str]:+ """Remove and return the row recorded for this context's Turn, if any."""++ entry = self._turn_visible_text.pop(resolve_turn_sink_key(self.controller, context), None)+ if entry is None or entry[0] != (context.platform_specific or {}).get("turn_token"):+ return None+ return entry[1]+async def emit_agent_message(self,context: MessageContext,@@ -2869,6 +2897,7 @@ class ConsolidatedMessageDispatcher:and not output_semantics.detachedand current_runtime_turn)+ turn_text_row_id = self._take_turn_text(context) if mutates_turn_lifecycle else None# Terminal status-bubble reason word for the done/orphan footer:# a clean turn is "done" (✅); a failure is "stopped" (⏹) when it was an@@ -2897,6 +2926,12 @@ class ConsolidatedMessageDispatcher:output_semantics,is_error=is_error,)+ # Visible text that stays in the current Turn without ending it.+ remembers_turn_text = (+ visible_output_type+ and communication_type == "output"+ and not output_semantics.detached+ )if visible_output_type:if not current_runtime_turn and not output_semantics.detached:logger.info(@@ -2988,6 +3023,39 @@ class ConsolidatedMessageDispatcher:"Activity output batch recovery is incomplete",delivered=False,)+ # A reply that is empty once ``<silent>`` blocks are stripped never+ # displaces the Turn's earlier visible text: that text becomes the+ # result, rendered and notified as one. ``level="silent"`` is not a+ # reply but a settlement (a stop, a failure already shown, a+ # teardown), and a failed or stopped Turn has no result to promote.+ # The promotion waits for SQLite's write lock, so it runs off the+ # controller loop. It adds no cancellation point: a cancellation+ # that arrives meanwhile waits for it and is delivered at the next+ # await, as the Run terminal record below does.+ if (+ turn_text_row_id is not None+ and level != "silent"+ and terminal_reason == "done"+ ):+ suppress_promoted_delivery = bool(+ (context.platform_specific or {}).get("suppress_delivery")+ )+ step, cancelled = await land_step(+ self._run_off_loop(+ lambda: promote_turn_text_to_result(+ turn_text_row_id,+ suppress_delivery=suppress_promoted_delivery,+ )+ )+ )+ if step_failed(step):+ logger.warning(+ "Failed to promote Turn text %s to its result",+ turn_text_row_id,+ exc_info=None if step.cancelled() else step.exception(),+ )+ if cancelled:+ rearm_caught_cancellation()# This row is the IM turn's ONLY terminal boundary — an IM turn has# no durable execution owner, and ``list_turn_groups`` /# ``_latest_source_message_anchor`` both close a turn on it. So a@@ -3292,6 +3360,8 @@ class ConsolidatedMessageDispatcher:citations=citations,existing_row_id=existing_row_id,)+ if remembers_turn_text:+ self._remember_turn_text(context, persisted_output)local_message_id = (persisted_output or {}).get("id") or (f"suppressed:{(context.platform_specific or {}).get('task_execution_id') or canonical_type}")@@ -3702,6 +3772,8 @@ class ConsolidatedMessageDispatcher:citations=citations,existing_row_id=existing_row_id,)+ if remembers_turn_text:+ self._remember_turn_text(context, persisted_output)if settlement_waits_for_persistence:accepted_message = persisted_output or (@@ -3927,6 +3999,7 @@ class ConsolidatedMessageDispatcher:or None,citations=citations,)+ self._remember_turn_text(context, interim_row)# Persist the intermediate log row BEFORE the mute filter so muted# assistant / tool_call messages still land in the store (product# requirement: the process log is complete even when a channel hides it).diff --git a/core/message_mirror.py b/core/message_mirror.pyindex c8a25df88..0c4586fa8 100644--- a/core/message_mirror.py+++ b/core/message_mirror.py@@ -753,6 +753,95 @@ def _write_committed_row(return messages_service.get_message(conn, row_id, include_local_error_detail=True)+# Transcript-visible agent text that does not end its Turn: an ``output`` phase+# boundary and an ``interim`` narration bubble.+_TURN_TEXT_TYPES = ("output", "interim")+++def promote_turn_text_to_result(row_id: str, *, suppress_delivery: bool = False) -> Optional[dict]:+ """Make a Turn's last visible text its result once its final reply is silent.++ The row was delivered as text that did not end the Turn, and the Turn then+ ended on a reply that is empty once ``<silent>`` blocks are stripped. That+ text is what the Turn answered, so it takes the result type: it renders as a+ reply, settles the Inbox card, counts as unread, and pushes the notification+ a result pushes. Its body, its place in the transcript, and its read state+ stay as delivered, so text the reader has already seen is not unread again.++ The update is guarded on the row still being Turn text, so a repeated call+ changes, publishes, and notifies nothing.+ """++ import json++ from sqlalchemy import select, update++ from storage.agent_session_rows import reserve_write_lock+ from storage.models import messages++ try:+ engine = get_cached_sqlite_engine()+ inbox_row = None+ with engine.begin() as conn:+ # The content read below decides the write, so the write lock is held+ # from before it.+ reserve_write_lock(conn)+ turn_text = (+ messages.c.id == row_id,+ messages.c.author == "agent",+ messages.c.type.in_(_TURN_TEXT_TYPES),+ )+ stored = conn.execute(select(messages.c.content_json).where(*turn_text)).first()+ if stored is None:+ return None+ # ``content.kind`` names the type the row was persisted as; it moves+ # with the type, as every persist path keeps the two together.+ try:+ content = json.loads(stored[0] or "{}")+ except (TypeError, ValueError):+ content = {}+ if not isinstance(content, dict):+ content = {}+ promoted = conn.execute(+ update(messages)+ .where(*turn_text)+ .values(+ type="result",+ content_json=json.dumps({**content, "kind": "result"}),+ updated_at=messages_service.canonical_message_timestamp(_now()),+ )+ ).rowcount+ if promoted != 1:+ return None+ row = messages_service.get_message(conn, row_id, include_local_error_detail=True)+ # The same audience ``persist_agent_message`` publishes a new row to.+ session_id = (row or {}).get("session_id")+ visible = bool(+ row is not None+ and row.get("platform") == "avibe"+ and session_id+ and not suppress_delivery+ )+ if visible:+ inbox_row = messages_service.get_inbox_session(conn, session_id)+ if visible:+ from core.inbox_events import bus++ bus.publish("message.updated", row)+ if inbox_row is not None:+ bus.publish("inbox.session.updated", inbox_row)+ try:+ from core.web_push_notifications import maybe_notify_inbox_message++ maybe_notify_inbox_message(row, inbox_row)+ except Exception:+ logger.debug("web push notification scheduling failed", exc_info=True)+ return row+ except Exception:+ logger.exception("promote_turn_text_to_result: failure for row %s", row_id)+ return None++def persist_silent_terminal(context: MessageContext,*,diff --git a/modules/agents/vibey/agent.py b/modules/agents/vibey/agent.pyindex 7fb970d0d..2b740c765 100644--- a/modules/agents/vibey/agent.py+++ b/modules/agents/vibey/agent.py@@ -845,9 +845,11 @@ class VibeyAgent(BaseAgent):citations=citations,)else:- # A reply the model chose to keep silent.+ # A reply the model chose to keep silent: an empty reply, as the base+ # result path emits one, not a ``level="silent"`` settlement, so an+ # earlier visible reply in the Turn becomes its result.await self.controller.emit_agent_message(- context, "result", "", level="silent", output=terminal_output_for(request)+ context, "result", "", output=terminal_output_for(request))return# Generated images are paid for and already announced: they reach the userdiff --git a/tests/scenarios/message_delivery/catalog.yaml b/tests/scenarios/message_delivery/catalog.yamlindex be4f4c08d..95b4988dc 100644--- a/tests/scenarios/message_delivery/catalog.yaml+++ b/tests/scenarios/message_delivery/catalog.yaml@@ -394,5 +394,16 @@ scenarios:kind: regressionlayer: scenariotest: tests/test_vibey_agent.py::test_a_harness_input_during_a_persons_turn_leaves_the_answer_its_result_and_runs_next+ - id: MESSAGE-DELIVERY-325+ name: A silent final reply makes the Turn's last visible text its result, rendered and notified once+ status: covered+ kind: regression+ layer: contract+ test:+ - tests/test_message_dispatcher_silent_final.py::SilentFinalTurnResultTests::test_a_silent_final_makes_the_last_visible_text_the_result+ - tests/test_message_dispatcher_silent_final.py::SilentFinalTurnResultTests::test_concurrent_turns_in_one_channel_each_promote_their_own_text+ - tests/test_message_dispatcher_silent_final.py::SilentFinalTurnResultTests::test_a_cancellation_during_the_promotion_still_commits_the_turn+ - tests/test_message_dispatcher_silent_final.py::SilentFinalTurnResultTests::test_nothing_else_promotes_earlier_text+ - tests/test_vibey_agent.py::test_a_silent_final_leaves_the_visible_reply_before_it_as_the_resultnext_priority:- - MESSAGE-DELIVERY-325+ - MESSAGE-DELIVERY-326diff --git a/tests/test_message_dispatcher_silent_final.py b/tests/test_message_dispatcher_silent_final.pynew file mode 100644index 000000000..3020f41f9--- /dev/null+++ b/tests/test_message_dispatcher_silent_final.py@@ -0,0 +1,300 @@+"""A silent final reply never displaces the Turn's earlier visible text.++A Turn can show text that does not end it: a completed phase a later input+joined (``output``), or substantial narration (``interim``). When the Turn then+ends on a reply that is empty once ``<silent>`` blocks are stripped, that text+is the Turn's result: typed, rendered, and notified as one, exactly once.+"""++from __future__ import annotations++import asyncio+import json+import os+import sys+import tempfile+import threading+import unittest+from contextlib import contextmanager+from pathlib import Path+from types import SimpleNamespace+from unittest import mock++from sqlalchemy import select++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from core.message_dispatcher import ConsolidatedMessageDispatcher+from core.message_output import MessageOutput, stop_output_for, terminal_turn_output+from modules.agents.base import AgentRequest, BaseAgent+from modules.im import MessageContext+from storage.db import create_sqlite_engine, dispose_cached_sqlite_engines+from storage.importer import ensure_sqlite_state+from storage.models import agent_sessions, messages+from storage.settings_service import upsert_scope+from tests.test_message_dispatcher_interim import FIVE_LINES, FOUR_LINES+from tests.test_message_dispatcher_platform_limits import _StubController++SESSION = "ses_silent_final"+NOW = "2026-10-18T03:00:00Z"+REPORT = "CI is green on the exact head and the review thread is resolved."+PHASE = MessageOutput(completes_turn=False, completes_run=False)+++class _Controller(_StubController):+ def __init__(self, platform: str):+ super().__init__(platform)+ self.settings_manager = SimpleNamespace(sessions=None)+ self.dispatcher = ConsolidatedMessageDispatcher(self)+ # The Turn commit's last step: called only once the terminal emit armed it.+ self.committed_turns: list[MessageContext] = []+ self.session_turns = SimpleNamespace(+ on_terminal_result=lambda *_args, **_kwargs: None,+ on_terminal_delivery_complete=self.committed_turns.append,+ )++ async def emit_agent_message(self, *args, **kwargs):+ return await self.dispatcher.emit_agent_message(*args, **kwargs)+++class _Agent(BaseAgent):+ name = "stub"++ async def handle_message(self, request: AgentRequest) -> None:+ return None+++class _ScheduledPush:+ """``threading.Thread`` as Web Push uses it: records the push it would send."""++ pushes: list[dict] = []++ def __init__(self, *, target, args, daemon):+ self.payload = args[0]++ def start(self) -> None:+ self.pushes.append(self.payload)+++class SilentFinalTurnResultTests(unittest.IsolatedAsyncioTestCase):+ def setUp(self):+ push_thread = mock.patch(+ "core.web_push_notifications.threading", SimpleNamespace(Thread=_ScheduledPush)+ )+ push_thread.start()+ self.addCleanup(push_thread.stop)+ bus = mock.patch(+ "core.inbox_events.bus.publish",+ side_effect=lambda name, payload: self.published.append((name, payload)),+ )+ bus.start()+ self.addCleanup(bus.stop)++ @contextmanager+ def state(self):+ """A fresh store holding one Workbench Session, and nothing published yet."""+ _ScheduledPush.pushes = []+ self.published: list[tuple[str, dict]] = []+ with tempfile.TemporaryDirectory() as home, mock.patch.dict(os.environ, {"AVIBE_HOME": home}):+ dispose_cached_sqlite_engines()+ ensure_sqlite_state()+ self.seed_session(SESSION)+ try:+ yield+ finally:+ dispose_cached_sqlite_engines()++ @staticmethod+ def seed_session(session_id: str) -> None:+ engine = create_sqlite_engine()+ try:+ with engine.begin() as conn:+ scope_id = upsert_scope(+ conn, platform="avibe", scope_type="project", native_id="proj_silent", now=NOW+ )+ conn.execute(+ agent_sessions.insert().values(+ id=session_id, scope_id=scope_id, agent_backend="claude", agent_variant="default",+ session_anchor=f"anchor_{session_id}", native_session_id="", status="active",+ metadata_json="{}", created_at=NOW, updated_at=NOW, last_active_at=NOW,+ )+ )+ finally:+ engine.dispose()++ @staticmethod+ def context(platform: str = "avibe", turn: str = "trn_1") -> MessageContext:+ avibe = platform == "avibe"+ return MessageContext(+ user_id="workbench" if avibe else "u1",+ channel_id=SESSION if avibe else "c1",+ platform=platform,+ platform_specific={"agent_session_id": SESSION, "turn_token": turn},+ )++ @staticmethod+ def _visible_rows(session_id: str, *columns):+ engine = create_sqlite_engine()+ try:+ with engine.connect() as conn:+ return list(+ conn.execute(+ select(*columns)+ .where(messages.c.session_id == session_id, messages.c.author == "agent")+ .where(messages.c.type != "assistant")+ .order_by(messages.c.created_at)+ )+ )+ finally:+ engine.dispose()++ def agent_rows(self, session_id: str = SESSION) -> list[tuple[str, str]]:+ return [+ (row.type, row.content_text)+ for row in self._visible_rows(session_id, messages.c.type, messages.c.content_text)+ ]++ def content_kinds(self) -> list[str]:+ return [json.loads(row.content_json)["kind"] for row in self._visible_rows(SESSION, messages.c.content_json)]++ async def test_a_silent_final_makes_the_last_visible_text_the_result(self):+ """Scenario: MESSAGE-DELIVERY-325."""+ cases = [+ # A completed phase another input joined, then a silent answer to that input.+ ("output", REPORT, "avibe", ("output", REPORT, {"output": PHASE})),+ # Substantial narration shown as a Web bubble before the silent final.+ ("interim", FIVE_LINES, "avibe", ("assistant", FIVE_LINES, {})),+ # IM delivered the output as a message already; its row becomes the result.+ ("output", REPORT, "slack", ("output", REPORT, {"output": PHASE})),+ ]+ for shown_type, text, platform, (message_type, body, kwargs) in cases:+ with self.subTest(shown_type=shown_type, platform=platform), self.state():+ controller = _Controller(platform)+ context = self.context(platform)+ await controller.emit_agent_message(context, message_type, body, **kwargs)+ self.assertEqual(self.agent_rows(), [(shown_type, text)])++ # The base result path emits a ``<silent>`` final as an empty reply;+ # a retried terminal must neither change nor notify anything again.+ agent = _Agent(controller)+ for _ in range(2):+ await agent.emit_result_message(context, "<silent>nothing to add</silent>")++ self.assertEqual(self.agent_rows(), [("result", text)])+ self.assertEqual(self.content_kinds(), ["result"])+ updated = [payload for name, payload in self.published if name == "message.updated"]+ if platform == "avibe":+ [row] = updated+ self.assertEqual((row["type"], row["text"]), ("result", text))+ self.assertEqual(+ [push["message_id"] for push in _ScheduledPush.pushes], [row["id"]]+ )+ inbox = [payload for name, payload in self.published if name == "inbox.session.updated"]+ self.assertEqual(inbox[-1]["unread_count"], 1)+ else:+ self.assertEqual(updated, [])+ self.assertEqual(_ScheduledPush.pushes, [])++ async def test_concurrent_turns_in_one_channel_each_promote_their_own_text(self):+ """Scenario: MESSAGE-DELIVERY-325."""+ with self.state():+ for thread in ("t1", "t2"):+ self.seed_session(f"ses_{thread}")+ controller = _Controller("slack")+ agent = _Agent(controller)+ threads = {+ "t1": MessageContext(+ user_id="u1", channel_id="c1", platform="slack", thread_id="t1",+ platform_specific={"agent_session_id": "ses_t1", "turn_token": "trn_t1"},+ ),+ "t2": MessageContext(+ user_id="u1", channel_id="c1", platform="slack", thread_id="t2",+ platform_specific={"agent_session_id": "ses_t2", "turn_token": "trn_t2"},+ ),+ }+ for thread, context in threads.items():+ await controller.emit_agent_message(context, "output", f"Report from {thread}.", output=PHASE)+ for context in threads.values():+ await agent.emit_result_message(context, "<silent>noted</silent>")++ for thread in threads:+ self.assertEqual(self.agent_rows(f"ses_{thread}"), [("result", f"Report from {thread}.")])++ async def test_a_cancellation_during_the_promotion_still_commits_the_turn(self):+ """Scenario: MESSAGE-DELIVERY-325.++ A Stop or shutdown that cancels the final while the promotion runs off the+ loop waits for it: the row is promoted, the Turn commit runs, and the+ cancellation is delivered after it.+ """+ from core import message_mirror++ with self.state():+ controller = _Controller("avibe")+ await controller.emit_agent_message(self.context(), "output", REPORT, output=PHASE)+ promoting, release = threading.Event(), threading.Event()++ def held_promotion(*args, **kwargs):+ promoting.set()+ release.wait(5)+ return message_mirror.promote_turn_text_to_result(*args, **kwargs)++ with mock.patch(+ "core.message_dispatcher.promote_turn_text_to_result", side_effect=held_promotion+ ):+ final = asyncio.create_task(+ _Agent(controller).emit_result_message(self.context(), "<silent>noted</silent>")+ )+ self.assertTrue(await asyncio.to_thread(promoting.wait, 5))+ final.cancel()+ await asyncio.sleep(0.05)+ release.set()+ with self.assertRaises(asyncio.CancelledError):+ await final++ self.assertEqual(self.agent_rows(), [("result", REPORT)])+ self.assertEqual(len(controller.committed_turns), 1)++ async def test_nothing_else_promotes_earlier_text(self):+ """Scenario: MESSAGE-DELIVERY-325."""+ request = SimpleNamespace(output=None)+ report = ("output", REPORT, {"output": PHASE})+ silent_reply = {"text": "", "output": terminal_turn_output()}+ cases = {+ "a visible final is the result itself": (+ report, {"text": "Merged."}, [("output", REPORT), ("result", "Merged.")], 1,+ ),+ "a stop has no result": (+ report, {"text": "", "level": "silent", "output": stop_output_for(request)},+ [("output", REPORT)], 0,+ ),+ "a failure settles without one": (+ report, {"text": "", "is_error": True, "level": "silent", "output": terminal_turn_output()},+ [("output", REPORT)], 0,+ ),+ "a settlement is not a reply": (+ report, {"text": "", "level": "silent", "output": terminal_turn_output()},+ [("output", REPORT)], 0,+ ),+ "another Turn's final": (+ report, {**silent_reply, "context": self.context(turn="trn_2")}, [("output", REPORT)], 0,+ ),+ # A per-step preamble stays in Activity: it was never visible text.+ "narration kept in Activity": (("assistant", FOUR_LINES, {}), silent_reply, [], 0),+ }+ for name, ((message_type, body, kwargs), final, expected_rows, pushes) in cases.items():+ with self.subTest(name), self.state():+ controller = _Controller("avibe")+ await controller.emit_agent_message(self.context(), message_type, body, **kwargs)+ final = dict(final)+ context = final.pop("context", self.context())+ text = final.pop("text")+ await controller.emit_agent_message(context, "result", text, **final)++ self.assertEqual(self.agent_rows(), expected_rows)+ self.assertEqual(len(_ScheduledPush.pushes), pushes)+ self.assertNotIn("message.updated", [name for name, _ in self.published])+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_vibey_agent.py b/tests/test_vibey_agent.pyindex 15c51235f..989dd522a 100644--- a/tests/test_vibey_agent.py+++ b/tests/test_vibey_agent.py@@ -2151,6 +2151,40 @@ async def test_a_silent_final_shows_nothing_and_completes(engine, session, tmp_passert harness.controller.terminals[-1]["is_error"] is False+async def test_a_silent_final_leaves_the_visible_reply_before_it_as_the_result(+ engine, session, tmp_path, published, monkeypatch+) -> None:+ """Scenario: MESSAGE-DELIVERY-325.++ A silent final is an empty reply, as the other backends emit one, so it never displaces visible text.+ """+ from core import web_push_notifications++ pushes: list[dict] = []++ class _Thread:+ def __init__(self, *, target, args, daemon):+ self.payload = args[0]++ def start(self) -> None:+ pushes.append(self.payload)++ monkeypatch.setattr(web_push_notifications, "threading", SimpleNamespace(Thread=_Thread))+ report = "Found it.\nThe cache is shared.\nTwo writers race.\nThe lock went in #12.\nFixed and verified."+ call = ToolCallBlock(id="call_1", name="echo", arguments={"path": "src"})+ harness = _Harness(+ engine, tmp_path, "avibe", [[Done(assistant(report, calls=(call,)))], [Done(assistant("<silent>done</silent>"))]]+ )++ await harness.agent.handle_message(harness.request("fix the race"))++ [result] = harness.rows("result")+ assert result["content_text"] == report and harness.rows("interim") == []+ assert [payload["type"] for name, payload in published if name == "message.updated"] == ["result"]+ assert [push["message_id"] for push in pushes] == [result["id"]]+ assert harness.controller.terminals[-1]["is_error"] is False++async def test_a_silent_final_whose_run_failed_after_its_commit_is_typed_by_its_row(engine, session, tmp_path, published) -> None: