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.

refactor(dispatcher): one presentation decision per agent output (#2878)

Call Whitea009bb61bb8e
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index 79fbc4669..e0e5de846 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -7,12 +7,12 @@ embedded in ``Controller.emit_agent_message``.
from __future__ import annotations
import asyncio
+import functools
import hashlib
import logging
import re
import tempfile
import time
-import unicodedata
from contextlib import asynccontextmanager
from dataclasses import dataclass, replace
from datetime import datetime, timezone
@@ -36,6 +36,13 @@ from core.message_mirror import (
persist_agent_message,
persist_silent_terminal,
)
+from core.presentation import (
+ DefaultPresentationPolicy,
+ ImDelivery,
+ PresentationInput,
+ PresentationPolicy,
+ validate_decision,
+)
from core.message_output import (
HARNESS_RUN_ID_TRIGGER_KINDS,
HARNESS_TRIGGER_KINDS,
@@ -78,6 +85,9 @@ from vibe.message_types import TRANSCRIPT_COPY_KEY
logger = logging.getLogger(__name__)
+# The types the presentation policy decides by name; any other is shown as narration.
+_PRESENTED_TYPES = frozenset({"result", "output", "notify", "system", "assistant", "toolcall"})
+
# Harness prompt echo (``emit_harness_prompt``). The echo is context for the reply
# that follows, not the payload, so a long generated prompt is cut rather than split
# across messages the way a result is.
@@ -313,8 +323,6 @@ _ACTION_TIME_HINT_S = 10.0
# above a per-step "now doing X" preamble, which stays in Activity. Length is
# display width, a wide (CJK) character counting two columns, so one bound
# means about 250 Chinese or 500 Latin characters.
-_INTERIM_MIN_LINES = 5
-_INTERIM_MIN_WIDTH = 500
# Name the result attachment gets when a platform has no native Markdown upload
# and the full text has to ride its ordinary file path instead.
_RESULT_DOCUMENT_NAME = "result.md"
@@ -422,6 +430,9 @@ class ConsolidatedMessageDispatcher:
# first use per turn (see ``_concise_progress_style``), dropped in
# ``_drop_status_keys``.
self._turn_progress_style: dict[str, str] = {}
+ # Decides how each output is shown (``core.presentation``); the seam a later
+ # policy replaces.
+ self.presentation_policy: PresentationPolicy = DefaultPresentationPolicy()
# 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
@@ -2239,6 +2250,62 @@ class ConsolidatedMessageDispatcher:
)
return []
+ def _presentation_input(
+ self,
+ context: MessageContext,
+ *,
+ im_client: Any,
+ settings_manager: Any,
+ settings_key: str,
+ canonical_type: str,
+ communication_type: str,
+ level: str,
+ text: Optional[str],
+ raw_text: Optional[str],
+ citations: Optional[CitationBundle],
+ output_semantics: MessageOutput,
+ background: bool,
+ ) -> tuple[PresentationInput, Any]:
+ """The presentation policy's input for one output, and the narration bubble it measured.
+
+ Everything here is what the dispatcher has always consulted, read the same
+ way: the target's platform and tool-call delivery, the channel's editing,
+ and, only when the policy asks, its hidden types and the turn's progress
+ style. A type that is neither an answer nor a process-log type is shown as
+ narration, as the log path has always treated it.
+ """
+
+ target_context = self._get_target_context(context)
+ kind = canonical_type if canonical_type in _PRESENTED_TYPES else "assistant"
+ log_kind = kind in {"system", "assistant", "toolcall"}
+ narration = None
+ if kind == "assistant" and level != "process" and not background and target_context.platform == "avibe":
+ # The bubble is the agent's words like a reply, so it gets the same
+ # button parse, and only the remaining body decides if it is one.
+ narration = process_reply(
+ raw_text,
+ include_quick_replies=getattr(self.controller.config, "reply_enhancements", True),
+ allow_unseparated_quick_replies=self._supports_quick_replies(target_context),
+ keep_file_links=True,
+ )
+ presentation = PresentationInput(
+ message_type=kind,
+ row_type=communication_type,
+ level=level,
+ platform=target_context.platform,
+ background=background,
+ body=text or "",
+ log_chunk=strip_file_links(materialize_citations(text, citations) or "").strip() if log_kind else "",
+ narration_body=narration.text if narration is not None else None,
+ metadata=output_semantics.metadata,
+ tools_deliverable=self._supports_toolcall_delivery(target_context) if kind == "toolcall" else True,
+ log_editable=self._supports_message_editing(im_client, context) if log_kind else True,
+ # Read once at most, however often the policy and the envelope check ask.
+ hidden=functools.cache(lambda: settings_manager.is_message_type_hidden(settings_key, kind)),
+ progress_style=functools.cache(lambda: self._concise_progress_style(context)),
+ )
+ return presentation, narration
+
@staticmethod
def _writes_on_delivery(canonical_type: str, output_semantics: MessageOutput) -> bool:
"""Whether this output's derived writes wait for its delivery evidence.
@@ -2849,14 +2916,6 @@ class ConsolidatedMessageDispatcher:
while len(self._harness_prompt_echo_order) > HARNESS_PROMPT_ECHO_MEMORY:
self._harness_prompt_echo_keys.discard(self._harness_prompt_echo_order.pop(0))
- @staticmethod
- def _is_interim_worthy(text: Optional[str]) -> bool:
- body = (text or "").strip()
- width = sum(2 if unicodedata.east_asian_width(ch) in "WF" else 1 for ch in body)
- if width >= _INTERIM_MIN_WIDTH:
- return True
- return sum(1 for line in body.splitlines() if line.strip()) >= _INTERIM_MIN_LINES
-
async def emit_agent_message(
self,
context: MessageContext,
@@ -3058,12 +3117,29 @@ class ConsolidatedMessageDispatcher:
"output_provenance": output_semantics.provenance(context),
},
)
- # ``level="silent"`` is the explicit visibility control (orthogonal to type):
- # the message already settled the dot above (for a terminal result), so here
- # we release the SSE waiter and return BEFORE any delivery / persistence /
- # streaming — no user-facing bubble, regardless of body. An empty/stripped
- # body (e.g. a ``<silent>`` directive reduced to nothing) is silent too.
- if level == "silent" or not text or not text.strip():
+ # How an output with content is shown is decided once, by the presentation
+ # policy (``core.presentation``); every branch below executes that decision,
+ # and a decision outside what they can execute is refused rather than half-run.
+ presentation, narration = self._presentation_input(
+ context,
+ im_client=im_client,
+ settings_manager=settings_manager,
+ settings_key=settings_key,
+ canonical_type=canonical_type,
+ communication_type=communication_type,
+ level=level,
+ text=text,
+ raw_text=raw_text,
+ citations=citations,
+ output_semantics=output_semantics,
+ background=bool((context.platform_specific or {}).get("suppress_delivery")),
+ )
+ # Nothing to show (``level="silent"``, or a body that is empty once silent
+ # directives are stripped) is a fact of the output, not a decision: no policy
+ # is asked, nothing is recorded or delivered, and only its lifecycle runs. The
+ # message already settled the dot above (for a terminal result), so release
+ # the SSE waiter and return BEFORE any delivery, persistence, or streaming.
+ if presentation.content_free:
async with self._terminal_emit(
context,
output_semantics,
@@ -3157,15 +3233,16 @@ class ConsolidatedMessageDispatcher:
settle_invisible_output()
return None
+ decision = validate_decision(presentation, self.presentation_policy.decide(presentation))
+ # Not outward: local history only, for any context, as a background Session's.
+ suppresses_outward_delivery = not decision.outward
+
# Resolve the delivery target once. Routed / post_to / thread replies
# land in a different channel than the source context, and the persisted
# row must follow the reply to where it was actually delivered (IM
# cross-platform history) — persist_agent_message attributes IM rows to
# this target's scope.
target_context = self._get_target_context(context)
- suppresses_outward_delivery = bool(
- (context.platform_specific or {}).get("suppress_delivery")
- )
output_metadata = output_semantics.provenance(context) if output is not None else None
if suppresses_outward_delivery:
# A background transcript row is local history, not an outward receipt.
@@ -3345,7 +3422,7 @@ class ConsolidatedMessageDispatcher:
# and the persisted row is the inbox/transcript source of truth.
persists_without_delivery = target_context.platform == "avibe"
- if suppresses_outward_delivery:
+ if not decision.outward:
async with self._terminal_emit(
context,
output_semantics,
@@ -3387,6 +3464,7 @@ class ConsolidatedMessageDispatcher:
native_message_id=native_output_id,
citations=citations,
existing_row_id=existing_row_id,
+ presentation=decision,
**background_reply,
)
else:
@@ -3399,6 +3477,7 @@ class ConsolidatedMessageDispatcher:
native_message_id=native_output_id,
citations=citations,
existing_row_id=existing_row_id,
+ presentation=decision,
**background_reply,
)
else:
@@ -3410,6 +3489,7 @@ class ConsolidatedMessageDispatcher:
native_message_id=native_output_id,
citations=citations,
existing_row_id=existing_row_id,
+ presentation=decision,
)
# The return value is the delivery evidence, and a background output's
# receipt is its local row: no row, no id (never a synthetic one), so a
@@ -3512,6 +3592,7 @@ class ConsolidatedMessageDispatcher:
native_message_id=native_output_id,
error_sink=persist_errors,
citations=citations,
+ presentation=decision,
)
if delivery is not None:
delivery.persisted_row = persisted_notify
@@ -3817,6 +3898,7 @@ class ConsolidatedMessageDispatcher:
native_message_id=native_output_id,
citations=citations,
existing_row_id=existing_row_id,
+ presentation=decision,
**delivered_reply,
)
else:
@@ -3829,6 +3911,7 @@ class ConsolidatedMessageDispatcher:
native_message_id=native_output_id,
citations=citations,
existing_row_id=existing_row_id,
+ presentation=decision,
**delivered_reply,
)
@@ -4039,40 +4122,20 @@ class ConsolidatedMessageDispatcher:
)
return None
- # Web only: substantial narration also lands as a transcript-visible
+ # Web only: substantial narration also lands as a transcript-visible, muted
# ``interim`` row. Every backend emits ``assistant`` only once later output
# has proved the text is not the Turn's final answer, so this never
- # duplicates the result. ``level="process"`` keeps a row log-only (for
- # example reasoning summaries).
+ # duplicates the result.
interim_row = None
- if (
- canonical_type == "assistant"
- and level != "process"
- and target_context.platform == "avibe"
- ):
- # The bubble is the agent's words like a reply, so it gets the same
- # button parse, and only the remaining body decides if it is one.
- interim = process_reply(
- raw_text,
- include_quick_replies=getattr(
- self.controller.config, "reply_enhancements", True
- ),
- allow_unseparated_quick_replies=self._supports_quick_replies(
- target_context
- ),
- keep_file_links=True,
+ if decision.transcript and narration is not None:
+ interim_row = persist_agent_message(
+ target_context,
+ "interim",
+ narration.text,
+ quick_replies=[b.text for b in _written_buttons(narration.buttons, citations)] or None,
+ citations=citations,
+ presentation=decision,
)
- if self._is_interim_worthy(interim.text):
- interim_row = persist_agent_message(
- target_context,
- "interim",
- interim.text,
- quick_replies=[
- b.text for b in _written_buttons(interim.buttons, citations)
- ]
- or None,
- citations=citations,
- )
# 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).
@@ -4085,6 +4148,7 @@ class ConsolidatedMessageDispatcher:
metadata={TRANSCRIPT_COPY_KEY: "interim"} if interim_row else None,
existing_row_id=existing_row_id,
hosted=hosted if canonical_type == "toolcall" else None,
+ presentation=decision,
)
# The row above is the only copy of an intermediate message that carries a
@@ -4093,63 +4157,37 @@ class ConsolidatedMessageDispatcher:
# the citations into ``text`` once here rather than at each of them.
text = materialize_citations(text, citations)
- # Target platform toolcall-delivery gate stays in FRONT of the concise
- # shortcut: when a turn is routed via ``delivery_override`` to a target
- # that cannot deliver toolcalls (e.g. the WeChat override flow), the
- # toolcall stays persisted-only and must NOT attempt a status bubble.
- if canonical_type == "toolcall" and not self._supports_toolcall_delivery(target_context):
- logger.info(
- "Skipping toolcall delivery for platform %s; persisted local process log only.",
- self._get_platform(target_context),
- )
- return None
-
- # The concise status bubble is a single ephemeral status line, NOT the
- # verbose per-message log that ``show_message_types`` governs. When a
- # status-bubble platform (Slack/Discord) is in ``concise`` style, render
- # tool-step / muttering emits into the bubble regardless of the
- # ``is_message_type_hidden`` visibility toggle below: persistence already
- # happened above so nothing is lost, and users who want zero process
- # output use ``off``. This bypasses ONLY the visibility toggle — the
- # target toolcall-delivery gate above still applies. ``system`` emits
- # carry no status label and stay on the gated path.
- if canonical_type in {"assistant", "toolcall"} and self._concise_progress_style(context) == "concise":
- # ``_render_concise_status`` renders a footer-only bubble when the
- # stripped body is empty but ``status_label`` is present, so do not
- # drop empty-body toolcall emits here.
- concise_chunk = strip_file_links(text).strip()
- return await self._render_concise_status(
- im_client, context, concise_chunk, status_label=status_label
- )
-
- if settings_manager.is_message_type_hidden(settings_key, canonical_type):
- preview = text if len(text) <= 500 else f"{text[:500]}…"
- logger.info(
- "Skipping %s message for settings %s (hidden). Preview: %s",
- canonical_type,
- settings_key,
- preview,
- )
+ if decision.im is ImDelivery.NONE:
+ if decision.reason == "tools_unsupported":
+ # A turn routed to a target that cannot deliver tool calls (the WeChat
+ # override flow) keeps them persisted only, without a status bubble.
+ logger.info(
+ "Skipping toolcall delivery for platform %s; persisted local process log only.",
+ self._get_platform(target_context),
+ )
+ elif decision.reason == "hidden":
+ preview = text if len(text) <= 500 else f"{text[:500]}…"
+ logger.info(
+ "Skipping %s message for settings %s (hidden). Preview: %s",
+ canonical_type,
+ settings_key,
+ preview,
+ )
return None
+ # The concise status bubble (Slack/Discord) is one replace-not-append line
+ # that is later edited into the result. ``_render_concise_status`` renders a
+ # footer-only bubble when the stripped body is empty but ``status_label`` is
+ # present, so an empty-body tool call still updates it.
chunk = strip_file_links(text).strip()
+ if decision.im is ImDelivery.STATUS:
+ return await self._render_concise_status(im_client, context, chunk, status_label=status_label)
- if not chunk:
- return None
-
+ # ``LOG``: one message per output where the platform cannot edit one, else
+ # the turn's consolidated, appended log (the verbose style).
if not self._supports_message_editing(im_client, context):
return await self._send_unconsolidated_log_message(im_client, context, chunk)
- # Concise status bubble (Slack/Discord): one replace-not-append line that
- # is later edited into the result. ``off`` shows no process bubble at all
- # (typing + final result only). ``verbose`` falls through to the legacy
- # append/split consolidation below (and is the path for all other platforms).
- progress_style = self._concise_progress_style(context)
- if progress_style == "off":
- return None
- if progress_style == "concise":
- return await self._render_concise_status(im_client, context, chunk, status_label=status_label)
-
consolidated_key = self._get_consolidated_message_key(context)
lock = self._get_consolidated_message_lock(consolidated_key)
diff --git a/core/message_mirror.py b/core/message_mirror.py
index 54db00443..62c4746ae 100644
--- a/core/message_mirror.py
+++ b/core/message_mirror.py
@@ -32,6 +32,7 @@ from typing import Any, Optional
from sqlalchemy.exc import IntegrityError
from core.citations import CitationBundle, finalize_citations, materialize_citations
+from core.presentation import PRESENTATION_METADATA_KEY, PresentationDecision, presentation_metadata
from core.run_settlement import NON_COMPLETING_TURN_SETTLEMENTS
from core.services import sessions as workbench_sessions_service
from modules.im.base import MessageContext
@@ -354,6 +355,7 @@ def persist_agent_message(
existing_row_id: Optional[str] = None,
hosted: Optional[dict] = None,
turn_reply: Optional[tuple[str, str]] = None,
+ presentation: Optional["PresentationDecision"] = None,
) -> Optional[dict]:
"""Persist one agent output into the workbench ``messages`` store.
@@ -363,6 +365,11 @@ def persist_agent_message(
the receipt exists exactly when the record does (docs/plans/reply-and-turn-end.md,
rule 5). A replayed output that finds its receipt already written records nothing.
+ ``presentation`` is the dispatcher's decision for this output
+ (``core.presentation``): the row (a tool call's trace event too) records it under
+ ``metadata["presentation"]``, it may decline the Web Push the catalog allows, and
+ an output it keeps local is not published to the Web, as with ``suppress_delivery``.
+
``existing_row_id`` names a row the backend already committed as its transcript
(the Avibe Agent): its display columns are written instead of inserting a
second row, and everything after the write (rank, ``message.new``, inbox) is
@@ -386,13 +393,18 @@ def persist_agent_message(
return
if not context.platform:
return
+ metadata = presentation_metadata(presentation, metadata)
# ``system`` messages are generated by us (init banners, status lines), not the
# agent — don't persist them at all (they have no place in the transcript and
# would only be noise in history) (user request).
if (canonical_type or "") == "system":
return
session_id = (context.platform_specific or {}).get("agent_session_id")
- suppress_delivery = bool((context.platform_specific or {}).get("suppress_delivery"))
+ # A decision that keeps the output local suppresses Web publication for any
+ # context, exactly as a background Session's ``suppress_delivery`` does.
+ suppress_delivery = bool((context.platform_specific or {}).get("suppress_delivery")) or (
+ presentation is not None and not presentation.outward
+ )
try:
engine = get_cached_sqlite_engine()
inbox_row = None
@@ -450,6 +462,11 @@ def persist_agent_message(
),
},
metadata={
+ **(
+ {PRESENTATION_METADATA_KEY: presentation.to_metadata()}
+ if presentation is not None
+ else {}
+ ),
"canonical_type": canonical_type or "tool_call",
# A native hosted call happened before the text of the response that
# carried it, though it is emitted after that row commits.
@@ -662,7 +679,8 @@ def persist_agent_message(
try:
from core.web_push_notifications import maybe_notify_inbox_message
- maybe_notify_inbox_message(appended_row, inbox_row)
+ if presentation is None or presentation.web_push:
+ maybe_notify_inbox_message(appended_row, inbox_row)
except Exception:
logger.debug("web push notification scheduling failed", exc_info=True)
return appended_row
diff --git a/core/presentation.py b/core/presentation.py
new file mode 100644
index 000000000..803713897
--- /dev/null
+++ b/core/presentation.py
@@ -0,0 +1,273 @@
+"""One presentation decision per agent output (docs/plans/reply-and-turn-end.md, PR 3).
+
+What an output *is* comes from the backend (``core.agent_output``); how Avibe *shows*
+it is decided here, once, by a ``PresentationPolicy``: whether it is a transcript row
+and renders muted, whether it is a Web Push, whether it goes out at all, and in what
+IM form. The dispatcher builds a ``PresentationInput`` for each output with content,
+asks the policy, and executes the decision; the output's record, where its type has
+one, stores the decision (``metadata["presentation"]``).
+
+``DefaultPresentationPolicy`` holds the rules Avibe has always applied, unchanged:
+the ``level`` grades, background (``suppress_delivery``) visibility, the Web interim
+copy of long narration, the catalog's Web Push flags, the target platform's tool-call
+delivery, the channel's hidden message types, and the turn's progress style. It is
+the only policy; the protocol is the seam a later policy (a decision model, or one
+that wraps this one) replaces it through, set as ``presentation_policy`` on the
+dispatcher. A replacement may differ from the default only by the allowed deltas
+documented on ``PresentationDecision``.
+"""
+
+from __future__ import annotations
+
+import unicodedata
+from dataclasses import dataclass
+from enum import Enum
+from typing import Any, Callable, Mapping, Optional, Protocol
+
+#: The ``metadata`` key an output's record stores its decision under.
+PRESENTATION_METADATA_KEY = "presentation"
+
+#: A Web narration bubble is kept as a transcript-visible ``interim`` copy once it
+#: has this many non-blank lines or this display width (wide characters count twice).
+INTERIM_MIN_LINES = 5
+INTERIM_MIN_WIDTH = 500
+
+#: The answer-like types: a transcript row, always delivered as a message.
+_MESSAGE_TYPES = frozenset({"result", "output", "error", "notify"})
+#: The process-log types: an Activity or trace record, delivered as the turn's log.
+_LOG_TYPES = frozenset({"system", "assistant", "toolcall"})
+#: A transcript row of these types renders muted (the released ``output``, the
+#: ``interim`` copy of narration).
+_MUTED_TYPES = frozenset({"output", "interim"})
+
+
+class ImDelivery(str, Enum):
+ """How an output goes out to its channel."""
+
+ #: It does not.
+ NONE = "none"
+ #: As the turn's concise status line.
+ STATUS = "status"
+ #: As the turn's process log (one consolidated message, or one per output).
+ LOG = "log"
+ #: As a message of its own.
+ MESSAGE = "message"
+
+
+@dataclass(frozen=True)
+class PresentationInput:
+ """What a policy may decide from: one output and its context.
+
+ ``message_type`` is the output's dispatched type (``result``, ``error``,
+ ``output``, ``notify``, ``assistant``, ``toolcall``, ``system``), ``row_type`` the
+ type its transcript row would carry. ``body`` is the visible text with silent
+ directives removed; ``log_chunk`` what a process log would show;
+ ``narration_body`` the bubble body a Web narration copy would carry, None where
+ no copy can be written (not a Web narration, ``level="process"``, or a background
+ Session). The
+ channel's hidden types and the turn's progress style are read only when a policy
+ asks, as the dispatcher has always read them. ``log_editable`` says whether the
+ channel can edit a message, which a consolidated log and a status line need.
+
+ ``content_free`` is a fact of the output, not a decision: an output with
+ ``level="silent"``, or with nothing left once silent directives are removed, is
+ never shown and never asked about. The dispatcher runs only its lifecycle (the
+ Turn end and its IM boundary row, Run settlement, releasing the stream).
+ """
+
+ message_type: str
+ row_type: str
+ level: str
+ platform: str
+ background: bool
+ body: str
+ log_chunk: str = ""
+ narration_body: Optional[str] = None
+ metadata: Optional[Mapping[str, Any]] = None
+ tools_deliverable: bool = True
+ log_editable: bool = True
+ hidden: Callable[[], bool] = lambda: False
+ progress_style: Callable[[], str] = lambda: "verbose"
+
+ @property
+ def content_free(self) -> bool:
+ return self.level == "silent" or not self.body.strip()
+
+
+@dataclass(frozen=True)
+class PresentationDecision:
+ """How one output with content is shown; ``reason`` names why it does not go out,
+ when it does not.
+
+ Whether an output has a record is not a decision but a fixed fact of its type,
+ kept best effort (none when its Session or scope row is not visible): an answer,
+ notice or narration (``result``, ``output``, ``error``, ``notify``, ``assistant``)
+ a ``messages`` row, a tool call an ``agent_events`` trace event, a ``system`` line
+ none. The record stores the decision under ``metadata["presentation"]``.
+
+ The dispatcher accepts the default policy's decision for the same output plus only
+ these deltas, each executed in full; any other difference raises ``ValueError``
+ (``validate_decision``) rather than being half-executed:
+
+ * narration's transcript copy on or off: for Web narration the dispatcher measured
+ (``assistant`` with a ``narration_body``), ``transcript`` and ``muted`` together
+ keep or drop its muted ``interim`` bubble;
+ * ``web_push`` declined where the default pushes.
+
+ Everything else (``outward``, ``im``, ``reason``, and the transcript of any other
+ output) equals the default. A later delta is added on its own, with its executor
+ support and tests, in the change that needs it.
+ """
+
+ policy: str
+ transcript: bool
+ muted: bool
+ web_push: bool
+ outward: bool
+ im: ImDelivery
+ reason: str = ""
+
+ def to_metadata(self) -> dict[str, Any]:
+ """What an output's record stores of its decision."""
+
+ return {
+ "policy": self.policy,
+ "outward": self.outward,
+ "transcript": self.transcript,
+ "muted": self.muted,
+ "web_push": self.web_push,
+ "im": self.im.value,
+ **({"reason": self.reason} if self.reason else {}),
+ }
+
+
+class PresentationPolicy(Protocol):
+ """Decides how one output is shown. ``id`` is recorded with every decision."""
+
+ id: str
+
+ def decide(self, presentation: PresentationInput) -> PresentationDecision: ...
+
+
+def interim_worthy(text: Optional[str]) -> bool:
+ """Whether narration is long enough to keep a transcript-visible copy."""
+
+ body = (text or "").strip()
+ width = sum(2 if unicodedata.east_asian_width(ch) in "WF" else 1 for ch in body)
+ if width >= INTERIM_MIN_WIDTH:
+ return True
+ return sum(1 for line in body.splitlines() if line.strip()) >= INTERIM_MIN_LINES
+
+
+def _web_push(row_type: str, metadata: Optional[Mapping[str, Any]]) -> bool:
+ from core.web_push_notifications import _is_notifiable_message
+
+ return _is_notifiable_message(row_type, dict(metadata) if metadata else None)
+
+
+class DefaultPresentationPolicy:
+ """The rules Avibe has always applied, in the order it has always applied them."""
+
+ id = "default/1"
+
+ def decide(self, presentation: PresentationInput) -> PresentationDecision:
+ def decision(**fields: Any) -> PresentationDecision:
+ values = {
+ "transcript": False,
+ "muted": False,
+ "web_push": False,
+ "outward": True,
+ "im": ImDelivery.NONE,
+ **fields,
+ }
+ return PresentationDecision(policy=self.id, **values)
+
+ kind = presentation.message_type
+ if kind in _MESSAGE_TYPES:
+ transcript = {"transcript": True, "muted": presentation.row_type in _MUTED_TYPES}
+ if presentation.background:
+ # A background Session keeps local history and delivers nothing outward.
+ return decision(**transcript, outward=False, reason="background")
+ return decision(
+ **transcript,
+ web_push=presentation.platform == "avibe"
+ and _web_push(presentation.row_type, presentation.metadata),
+ im=ImDelivery.MESSAGE,
+ )
+ if presentation.background:
+ return decision(outward=False, reason="background")
+ # Long Web narration also keeps a muted, transcript-visible ``interim`` copy;
+ # ``level="process"`` keeps it log-only.
+ copy = presentation.narration_body is not None and interim_worthy(presentation.narration_body)
+ shown = {"transcript": copy, "muted": copy}
+ if kind == "toolcall" and not presentation.tools_deliverable:
+ return decision(**shown, reason="tools_unsupported")
+ # The concise status line is the turn's single process line, not the verbose
+ # log the hidden types govern: narration and tool calls go to it regardless.
+ if kind in {"assistant", "toolcall"} and presentation.progress_style() == "concise":
+ return decision(**shown, im=ImDelivery.STATUS)
+ if presentation.hidden():
+ return decision(**shown, reason="hidden")
+ if not presentation.log_chunk:
+ return decision(**shown, reason="empty")
+ # A platform that cannot edit a message has no consolidated log or status
+ # line to keep: each process message is sent on its own, whatever the style.
+ if not presentation.log_editable:
+ return decision(**shown, im=ImDelivery.LOG)
+ style = presentation.progress_style()
+ if style == "off":
+ return decision(**shown, reason="style_off")
+ if style == "concise":
+ return decision(**shown, im=ImDelivery.STATUS)
+ return decision(**shown, im=ImDelivery.LOG)
+
+
+def validate_decision(presentation: PresentationInput, decision: PresentationDecision) -> PresentationDecision:
+ """``decision`` when it is the default decision plus allowed deltas, else ``ValueError``.
+
+ The allowed deltas are documented on ``PresentationDecision``.
+ """
+
+ default = DefaultPresentationPolicy().decide(presentation)
+ delta = {
+ field
+ for field in ("transcript", "muted", "web_push", "outward", "im", "reason")
+ if getattr(decision, field) != getattr(default, field)
+ }
+ allowed = set()
+ if presentation.message_type == "assistant" and presentation.narration_body is not None:
+ if decision.transcript is decision.muted:
+ allowed |= {"transcript", "muted"}
+ if default.web_push and not decision.web_push:
+ allowed.add("web_push")
+ if delta - allowed:
+ raise ValueError(
+ f"presentation policy {decision.policy!r} changes {sorted(delta - allowed)} of the default "
+ f"decision, which is not an allowed delta ({decision!r} vs {default!r})"
+ )
+ return decision
+
+
+def presentation_metadata(
+ decision: Optional[PresentationDecision], metadata: Optional[Mapping[str, Any]] = None
+) -> Optional[dict[str, Any]]:
+ """``metadata`` with the decision recorded, for the message it decided."""
+
+ if decision is None:
+ return dict(metadata) if metadata is not None else None
+ return {**(metadata or {}), PRESENTATION_METADATA_KEY: decision.to_metadata()}
+
+
+__all__ = [
+ "INTERIM_MIN_LINES",
+ "INTERIM_MIN_WIDTH",
+ "PRESENTATION_METADATA_KEY",
+ "DefaultPresentationPolicy",
+ "ImDelivery",
+ "PresentationDecision",
+ "PresentationInput",
+ "PresentationPolicy",
+ "interim_worthy",
+ "presentation_metadata",
+ "validate_decision",
+]
diff --git a/docs/plans/reply-and-turn-end.md b/docs/plans/reply-and-turn-end.md
index c4521e53f..dd3e7cfff 100644
--- a/docs/plans/reply-and-turn-end.md
+++ b/docs/plans/reply-and-turn-end.md
@@ -2,8 +2,9 @@
Status: approved by the owner (cyhhao), 2026-10-19. PR 1 (merged): shared
contract, Vibey, and Claude's pre-steer phase typed as a reply. PR 2a (merged):
-Codex and OpenCode on the reply rule, and rule 5 owned by the dispatcher. PR 2b:
-typed output events. Later: see Next steps.
+Codex and OpenCode on the reply rule, and rule 5 owned by the dispatcher. PR 2b
+(merged): typed output events. PR 3: the presentation decision point. Later: see
+Next steps.
## Background
@@ -329,7 +330,26 @@ Approved by the owner, in this order:
point per output event: transcript or not, muted, push, IM delivery.
Today's rules move into it unchanged as the default policy: the interim
length threshold, hidden types, IM concise mode, `suppress_delivery`. The
- decision is recorded on the message.
+ decision is recorded on the message. Shape (`core/presentation.py`): the
+ dispatcher builds a `PresentationInput` per output (its type, `level`,
+ target platform, background, body, and, read only when the policy asks,
+ the channel's hidden types and the turn's progress style), asks its
+ `presentation_policy`, and executes the `PresentationDecision` (`transcript`,
+ `muted`, `web_push`, `outward`, `im`: none, status, log or message). The
+ dispatcher accepts only the default decision for the same output plus
+ allowed deltas, each executed in full: narration's Web transcript copy (its
+ muted `interim` bubble) on or off, and a declined Web Push; any other
+ difference is refused. A later delta is added on its own, with its executor
+ support and tests, in the change that needs it. An output without content
+ (`level="silent"` or an empty body) is a fact of the input, not a decision:
+ no policy is asked, and only its lifecycle runs. Whether an output has a
+ record is a fixed, best-effort fact of its type (a `messages` row, a tool
+ call's `agent_events` trace event, none for `system`), not a decision.
+ `DefaultPresentationPolicy` (`default/1`) is the only policy; a later one (a
+ decision model, or one that wraps the default) replaces it through the same
+ protocol. Each record stores the decision under `metadata["presentation"]`
+ (additive; released readers ignore it). Vibey's
+ generated-images fallback goes through it with its released `output` type.
3. PR 4, structural only with no behavior change. One admission entry for
every input source: Web composer, IM, Harness, Show annotation, failure
retry, agent-initiated. Each input is normalized to sender, kind and
diff --git a/modules/agents/vibey/prompt.py b/modules/agents/vibey/prompt.py
index ff7f0477a..bb6f81c9f 100644
--- a/modules/agents/vibey/prompt.py
+++ b/modules/agents/vibey/prompt.py
@@ -17,7 +17,7 @@ framing. The backend's built-in Agent is Vibey, Avibe's own agent
(``VIBEY_PREAMBLE``); any other Agent on the backend gets ``AGENT_PREAMBLE``, and its
own definition, in the Avibe sections, says who it is. ``FINAL_REPLY_RULE`` is
Avibe's too: text between tool calls reaches the user only above the shared interim
-threshold (``ConsolidatedMessageDispatcher._is_interim_worthy``).
+threshold (``core.presentation.interim_worthy``).
"""
from __future__ import annotations
diff --git a/tests/scenarios/message_delivery/catalog.yaml b/tests/scenarios/message_delivery/catalog.yaml
index 179e9808a..9fdfd35d9 100644
--- a/tests/scenarios/message_delivery/catalog.yaml
+++ b/tests/scenarios/message_delivery/catalog.yaml
@@ -522,6 +522,18 @@ scenarios:
- tests/test_agent_output.py::test_each_event_maps_to_one_dispatch_call
- tests/test_agent_output.py::test_an_event_cannot_contradict_its_lifecycle
- tests/test_agent_output.py::test_an_emit_answers_with_its_delivery_receipt
+ - id: MESSAGE-DELIVERY-337
+ name: Every agent output with content gets one presentation decision from a replaceable policy (transcript row, muted, Web Push, outward, IM form), and an output without content is never asked about; the default policy holds the rules the dispatcher applied inline, unchanged (level, background visibility, the Web interim threshold, the catalog's Web Push flags, tool-call delivery, the concise status line, hidden types, editing, progress style), the dispatcher accepts only the default decision plus its allowed deltas (narration's Web transcript copy on or off, a declined Web Push), executes them in full, and refuses any other decision, and each output's record (a fixed, best-effort fact of its type) stores the decision under metadata.presentation
+ status: covered
+ kind: contract
+ layer: contract
+ test:
+ - tests/test_presentation.py::test_the_default_policy_decides_each_rule
+ - tests/test_presentation.py::test_only_the_default_decision_and_its_allowed_deltas_are_accepted
+ - tests/test_presentation.py::test_the_interim_threshold_counts_lines_and_display_width
+ - tests/test_presentation.py::test_a_decision_is_recorded_as_stable_metadata
+ - tests/test_message_dispatcher_turn_end.py::ReplyAndTurnEndTests::test_each_message_records_and_follows_its_presentation_decision
+ - tests/test_message_dispatcher_turn_end.py::ReplyAndTurnEndTests::test_each_allowed_delta_is_what_the_dispatcher_executes
- id: MESSAGE-DELIVERY-338
name: Every input source (Web composer, IM, Harness, Show annotation, failure retry, agent-initiated) is normalized into one envelope and admitted through one entry; one default admission policy holds each source's released priority (the OpenCode subagent exception, an Agent Run's --queue and legacy send_now, the scheduled P3 included) and the admitting history event records which policy decided and why
status: covered
diff --git a/tests/test_message_dispatcher_turn_end.py b/tests/test_message_dispatcher_turn_end.py
index b57bb0d75..f611acaa1 100644
--- a/tests/test_message_dispatcher_turn_end.py
+++ b/tests/test_message_dispatcher_turn_end.py
@@ -14,11 +14,13 @@ when the Turn delivered none.
from __future__ import annotations
+import json
import os
import sys
import tempfile
import unittest
from contextlib import contextmanager
+from dataclasses import replace
from pathlib import Path
from types import SimpleNamespace
from unittest import mock
@@ -31,6 +33,7 @@ from core.citations import CitationSource, register_citations
from core import message_dispatcher as dispatcher_module
from core.message_dispatcher import ConsolidatedMessageDispatcher
from core.message_output import MessageOutput, stop_output_for, terminal_turn_output
+from core.presentation import ImDelivery
from core.session_turns import SessionTurnManager
from modules.agents.base import AgentRequest, BaseAgent
from modules.im import MessageContext
@@ -51,6 +54,7 @@ from tests.test_message_dispatcher_status_bubble import (
SESSION = "ses_turn_end"
NOW = "2026-10-19T03:00:00Z"
FIRST = "The cache is shared; two writers race. Fixed in #12."
+SHOWN = {"policy": "default/1", "outward": True}
SECOND = "Yes, the fix also covers the CLI path."
REPLY = MessageOutput(completes_turn=False, completes_run=False)
@@ -230,6 +234,37 @@ class ReplyAndTurnEndTests(unittest.IsolatedAsyncioTestCase):
def harness_run(self, run_id: str | None = None) -> dict:
return self.runs.get_run(run_id or self.run_id)
+ @staticmethod
+ def agent_metadata() -> list[str]:
+ engine = create_sqlite_engine()
+ try:
+ with engine.connect() as conn:
+ return list(
+ conn.execute(
+ select(messages.c.metadata_json)
+ .where(messages.c.session_id == SESSION, messages.c.author == "agent")
+ .order_by(messages.c.created_at, messages.c.id)
+ ).scalars()
+ )
+ finally:
+ engine.dispose()
+
+ @staticmethod
+ def agent_presentations() -> list[tuple[str, dict]]:
+ engine = create_sqlite_engine()
+ try:
+ with engine.connect() as conn:
+ return [
+ (row.type, json.loads(row.metadata_json or "{}").get("presentation"))
+ for row in conn.execute(
+ select(messages.c.type, messages.c.metadata_json)
+ .where(messages.c.session_id == SESSION, messages.c.author == "agent")
+ .order_by(messages.c.created_at, messages.c.id)
+ )
+ ]
+ finally:
+ engine.dispose()
+
def pushed_texts(self) -> list[str]:
return [push["body"] for push in _ScheduledPush.pushes]
@@ -504,6 +539,161 @@ class ReplyAndTurnEndTests(unittest.IsolatedAsyncioTestCase):
run = self.harness_run()
self.assertEqual((run["status"], run["result_text"] or ""), ("succeeded", expected))
+ async def test_each_message_records_and_follows_its_presentation_decision(self):
+ """Scenario: MESSAGE-DELIVERY-337: every message the dispatcher writes records the
+ presentation decision it executed (``metadata["presentation"]``): a Web reply
+ is a pushed transcript message, long narration keeps a muted ``interim`` copy
+ beside its Activity row, and the released ``output`` type stays a muted,
+ unpushed transcript row. The decision is what the dispatcher executes: a policy
+ that declines the push leaves the reply's row without one."""
+ with self.state():
+ controller = _Controller("avibe")
+ context = self.context()
+ await controller.emit_agent_message(context, "assistant", FIVE_LINES)
+ await controller.emit_agent_message(context, "result", FIRST, output=REPLY)
+ await controller.emit_agent_message(
+ context,
+ "output",
+ "Generated images:\n\n![a](/tmp/a.png)",
+ output=MessageOutput(completes_turn=False, completes_run=False, records_run_output=False),
+ )
+
+ recorded = {row_type: presentation for row_type, presentation in self.agent_presentations()}
+ self.assertEqual(
+ recorded,
+ {
+ "assistant": {**SHOWN, "transcript": True, "muted": True, "web_push": False, "im": "log"},
+ "interim": {**SHOWN, "transcript": True, "muted": True, "web_push": False, "im": "log"},
+ "result": {**SHOWN, "transcript": True, "muted": False, "web_push": True, "im": "message"},
+ "output": {**SHOWN, "transcript": True, "muted": True, "web_push": False, "im": "message"},
+ },
+ )
+ self.assertEqual(self.pushed_texts(), [FIRST])
+
+ class _NoPush:
+ id = "no-push/1"
+
+ def __init__(self, inner):
+ self.inner = inner
+
+ def decide(self, presentation):
+ return replace(self.inner.decide(presentation), policy=self.id, web_push=False)
+
+ with self.state():
+ controller = _Controller("avibe")
+ controller.dispatcher.presentation_policy = _NoPush(controller.dispatcher.presentation_policy)
+ await controller.emit_agent_message(self.context(), "result", FIRST, output=REPLY)
+
+ self.assertEqual(self.agent_rows(), [("result", FIRST)])
+ self.assertEqual(self.pushed_texts(), [])
+ [(_, presentation)] = self.agent_presentations()
+ self.assertEqual((presentation["policy"], presentation["web_push"]), ("no-push/1", False))
+
+ async def test_each_allowed_delta_is_what_the_dispatcher_executes(self):
+ """Scenario: MESSAGE-DELIVERY-337: with the real dispatcher and store, a policy that
+ makes one allowed delta to the default decision changes exactly that behavior and
+ nothing else: the reply's push declined, narration's muted copy kept or dropped.
+ Any other change (the reply kept local, the log line sent nowhere or as the status
+ line, the reply not sent) raises before anything is written or sent. An output
+ without content is never asked about."""
+
+ def flip(**fields):
+ class _Flip:
+ id = "flip/1"
+
+ def __init__(self, inner):
+ self.inner = inner
+
+ def decide(self, presentation):
+ decision = self.inner.decide(presentation)
+ if presentation.message_type != fields["kind"]:
+ return decision
+ changes = {key: value for key, value in fields.items() if key != "kind"}
+ return replace(decision, policy=self.id, **changes)
+
+ return _Flip
+
+ async def reply(controller, context):
+ await controller.emit_agent_message(context, "result", FIRST, output=REPLY)
+
+ async def short_narration(controller, context):
+ await controller.emit_agent_message(context, "assistant", "Checking the lock.")
+
+ async def long_narration(controller, context):
+ await controller.emit_agent_message(context, "assistant", FIVE_LINES)
+
+ cases = {
+ "the push declined": (reply, flip(kind="result", web_push=False), {"pushes"}),
+ "a copy for short narration": (
+ short_narration,
+ flip(kind="assistant", transcript=True, muted=True),
+ {"rows", "published"},
+ ),
+ "no copy for long narration": (
+ long_narration,
+ flip(kind="assistant", transcript=False, muted=False),
+ {"rows", "published"},
+ ),
+ }
+
+ async def observe(emit, policy=None):
+ with self.state():
+ controller = _Controller("avibe")
+ controller.get_progress_style_for_context = lambda _context: "verbose"
+ if policy is not None:
+ controller.dispatcher.presentation_policy = policy(controller.dispatcher.presentation_policy)
+ await emit(controller, self.context())
+ rows = self.agent_rows()
+ return {
+ "rows": rows,
+ "pushes": self.pushed_texts(),
+ "sent": [text for _, _, text, _ in controller.im_client.sent],
+ "published": [event for event, _ in self.published if event in {"message.new", "inbox.session.updated"}],
+ "suppressed": any(
+ bool(json.loads(metadata or "{}").get("delivery_suppressed"))
+ for metadata in self.agent_metadata()
+ ),
+ "status_line": bool(controller.dispatcher._concise_bubble_keys),
+ }
+
+ for name, (emit, policy, changed) in cases.items():
+ with self.subTest(name):
+ default, flipped = await observe(emit), await observe(emit, policy)
+ self.assertEqual(
+ {key for key in default if default[key] != flipped[key]}, changed, (default, flipped)
+ )
+
+ class _NeverAsked:
+ id = "never/1"
+
+ def decide(self, presentation):
+ raise AssertionError(f"a policy was asked about an output without content: {presentation!r}")
+
+ with self.subTest("an output without content is never asked about"), self.state():
+ controller = _Controller("avibe")
+ controller.dispatcher.presentation_policy = _NeverAsked()
+ await controller.emit_agent_message(self.context(), "assistant", " ")
+ await controller.emit_agent_message(self.context(), "result", FIRST, output=REPLY, level="silent")
+ self.assertEqual((self.agent_rows(), self.pushed_texts(), controller.im_client.sent), ([], [], []))
+
+ rejected = {
+ "the reply kept local": (
+ reply,
+ flip(kind="result", outward=False, web_push=False, im=ImDelivery.NONE),
+ ),
+ "the reply not sent": (reply, flip(kind="result", im=ImDelivery.NONE)),
+ "the log line sent nowhere": (short_narration, flip(kind="assistant", im=ImDelivery.NONE)),
+ "the log line as the status line": (short_narration, flip(kind="assistant", im=ImDelivery.STATUS)),
+ }
+ for name, (emit, policy) in rejected.items():
+ with self.subTest(name), self.state():
+ controller = _Controller("avibe")
+ controller.get_progress_style_for_context = lambda _context: "verbose"
+ controller.dispatcher.presentation_policy = policy(controller.dispatcher.presentation_policy)
+ with self.assertRaises(ValueError):
+ await emit(controller, self.context())
+ self.assertEqual((self.agent_rows(), self.pushed_texts(), controller.im_client.sent), ([], [], []))
+
async def test_a_reply_or_a_failure_keeps_its_type_attached_or_detached(self):
"""Scenario: MESSAGE-DELIVERY-334.
diff --git a/tests/test_presentation.py b/tests/test_presentation.py
new file mode 100644
index 000000000..a1a55b15d
--- /dev/null
+++ b/tests/test_presentation.py
@@ -0,0 +1,264 @@
+"""One presentation decision per agent output (MESSAGE-DELIVERY-337).
+
+``DefaultPresentationPolicy`` holds the rules the dispatcher used to apply inline, in
+their order: ``level``, background visibility, the Web interim copy of long narration,
+the catalog's Web Push flags, the target's tool-call delivery, the concise status line,
+the channel's hidden types, an empty log line, a channel that cannot edit, and the
+turn's progress style. The dispatcher executes the decision and records it on the
+message it writes.
+"""
+
+from __future__ import annotations
+
+from dataclasses import replace
+
+import pytest
+
+from core.presentation import (
+ DefaultPresentationPolicy,
+ ImDelivery,
+ PresentationDecision,
+ PresentationInput,
+ interim_worthy,
+ validate_decision,
+)
+
+LONG = "\n".join(f"line {n}" for n in range(5))
+
+
+def _never(name):
+ def read():
+ raise AssertionError(f"the policy read the {name} it does not need")
+
+ return read
+
+
+def _input(message_type="result", **fields):
+ values = {
+ "row_type": message_type,
+ "level": "normal",
+ "platform": "slack",
+ "background": False,
+ "body": "text",
+ "log_chunk": "text",
+ "hidden": _never("hidden types"),
+ "progress_style": _never("progress style"),
+ **fields,
+ }
+ return PresentationInput(message_type=message_type, **values)
+
+
+def _decision(**fields):
+ values = {
+ "policy": "default/1",
+ "transcript": False,
+ "muted": False,
+ "web_push": False,
+ "outward": True,
+ "im": ImDelivery.NONE,
+ "reason": "",
+ **fields,
+ }
+ return PresentationDecision(**values)
+
+
+def _style(value):
+ return lambda: value
+
+
+ ("presentation", "expected"),
+ [
+ # answers and notices
+ pytest.param(
+ _input("result", platform="avibe"),
+ _decision(transcript=True, web_push=True, im=ImDelivery.MESSAGE),
+ id="web-reply-pushes",
+ ),
+ pytest.param(
+ _input("result"),
+ _decision(transcript=True, im=ImDelivery.MESSAGE),
+ id="im-reply-is-a-message",
+ ),
+ pytest.param(
+ _input("result", row_type="error", platform="avibe"),
+ _decision(transcript=True, web_push=True, im=ImDelivery.MESSAGE),
+ id="web-failure-pushes",
+ ),
+ pytest.param(
+ _input("output", platform="avibe"),
+ _decision(transcript=True, muted=True, im=ImDelivery.MESSAGE),
+ id="released-output-type-is-muted-and-silent",
+ ),
+ pytest.param(
+ _input("notify", platform="avibe"),
+ _decision(transcript=True, im=ImDelivery.MESSAGE),
+ id="notice-does-not-push",
+ ),
+ pytest.param(
+ _input("notify", platform="avibe", metadata={"event": "backend_failure"}),
+ _decision(transcript=True, web_push=True, im=ImDelivery.MESSAGE),
+ id="backend-failure-notice-pushes",
+ ),
+ pytest.param(
+ _input("result", platform="avibe", background=True),
+ _decision(transcript=True, outward=False, reason="background"),
+ id="background-reply-is-local-history",
+ ),
+ # narration's Web copy
+ pytest.param(
+ _input("assistant", platform="avibe", narration_body=LONG, log_editable=True, hidden=lambda: False,
+ progress_style=_style("verbose")),
+ _decision(transcript=True, muted=True, im=ImDelivery.LOG),
+ id="long-web-narration-keeps-a-muted-copy",
+ ),
+ pytest.param(
+ _input("assistant", platform="avibe", narration_body="short", hidden=lambda: False,
+ progress_style=_style("verbose")),
+ _decision(im=ImDelivery.LOG),
+ id="short-narration-is-activity-only",
+ ),
+ pytest.param(
+ _input("assistant", platform="avibe", level="process", hidden=lambda: False,
+ progress_style=_style("verbose")),
+ _decision(im=ImDelivery.LOG),
+ id="process-narration-keeps-no-copy",
+ ),
+ pytest.param(
+ _input("assistant", platform="avibe", background=True),
+ _decision(outward=False, reason="background"),
+ id="background-narration-keeps-no-copy",
+ ),
+ # the process log
+ pytest.param(
+ _input("toolcall", tools_deliverable=False),
+ _decision(reason="tools_unsupported"),
+ id="tools-the-target-cannot-deliver",
+ ),
+ pytest.param(
+ _input("toolcall", log_chunk="", progress_style=_style("concise")),
+ _decision(im=ImDelivery.STATUS),
+ id="concise-status-takes-narration-and-tools-even-hidden-or-empty",
+ ),
+ pytest.param(
+ _input("system", hidden=lambda: True),
+ _decision(reason="hidden"),
+ id="hidden-type",
+ ),
+ pytest.param(
+ _input("assistant", hidden=lambda: True, progress_style=_style("verbose")),
+ _decision(reason="hidden"),
+ id="hidden-narration-outside-concise",
+ ),
+ pytest.param(
+ _input("system", log_chunk="", hidden=lambda: False),
+ _decision(reason="empty"),
+ id="empty-log-line",
+ ),
+ pytest.param(
+ _input("assistant", log_editable=False, hidden=lambda: False, progress_style=_style("off")),
+ _decision(im=ImDelivery.LOG),
+ id="a-channel-that-cannot-edit-gets-every-line",
+ ),
+ pytest.param(
+ _input("system", hidden=lambda: False, progress_style=_style("off")),
+ _decision(reason="style_off"),
+ id="style-off",
+ ),
+ pytest.param(
+ _input("system", hidden=lambda: False, progress_style=_style("concise")),
+ _decision(im=ImDelivery.STATUS),
+ id="concise-system-line",
+ ),
+ pytest.param(
+ _input("assistant", hidden=lambda: False, progress_style=_style("verbose")),
+ _decision(im=ImDelivery.LOG),
+ id="verbose-log",
+ ),
+ ],
+)
+def test_the_default_policy_decides_each_rule(presentation, expected):
+ """MESSAGE-DELIVERY-337: each of the dispatcher's former inline rules, as one decision
+ inside the executable envelope; the hidden types and the progress style are read only
+ when a rule needs them."""
+ decision = DefaultPresentationPolicy().decide(presentation)
+ assert decision == expected
+ assert validate_decision(presentation, decision) is decision
+
+
+_SHOWN = {"hidden": lambda: False, "progress_style": _style("verbose")}
+WEB_REPLY = _input("result", platform="avibe")
+WEB_NOTIFY = _input("notify", platform="avibe")
+BACKGROUND_REPLY = _input("result", platform="avibe", background=True)
+SHORT_NARRATION = _input("assistant", platform="avibe", narration_body="short", **_SHOWN)
+LONG_NARRATION = _input("assistant", platform="avibe", narration_body=LONG, **_SHOWN)
+UNMEASURED_NARRATION = _input("assistant", **_SHOWN)
+UNEDITABLE_NARRATION = _input("assistant", platform="wechat", log_editable=False, **_SHOWN)
+WEB_TOOL = _input("toolcall", platform="avibe", **_SHOWN)
+
+
+ ("presentation", "changes", "accepted"),
+ [
+ pytest.param(WEB_REPLY, {}, True, id="the-default"),
+ pytest.param(WEB_REPLY, {"web_push": False}, True, id="push-declined"),
+ pytest.param(SHORT_NARRATION, {"transcript": True, "muted": True}, True, id="copy-on"),
+ pytest.param(LONG_NARRATION, {"transcript": False, "muted": False}, True, id="copy-off"),
+ pytest.param(WEB_NOTIFY, {"web_push": True}, False, id="push-added"),
+ pytest.param(WEB_REPLY, {"outward": False, "web_push": False, "im": ImDelivery.NONE}, False,
+ id="reply-kept-local"),
+ pytest.param(BACKGROUND_REPLY, {"outward": True, "im": ImDelivery.MESSAGE, "reason": ""}, False,
+ id="background-sent-outward"),
+ pytest.param(UNEDITABLE_NARRATION, {"im": ImDelivery.STATUS}, False, id="status-line-without-editing"),
+ pytest.param(SHORT_NARRATION, {"im": ImDelivery.NONE}, False, id="log-line-sent-nowhere"),
+ pytest.param(WEB_TOOL, {"outward": False, "im": ImDelivery.NONE}, False, id="tool-call-kept-local"),
+ pytest.param(WEB_REPLY, {"transcript": False}, False, id="reply-without-row"),
+ pytest.param(WEB_REPLY, {"muted": True}, False, id="reply-muted"),
+ pytest.param(SHORT_NARRATION, {"transcript": True}, False, id="copy-not-muted"),
+ pytest.param(UNMEASURED_NARRATION, {"transcript": True, "muted": True}, False,
+ id="copy-without-a-measured-body"),
+ pytest.param(WEB_TOOL, {"transcript": True, "muted": True}, False, id="copy-of-a-tool-call"),
+ pytest.param(SHORT_NARRATION, {"reason": "hidden"}, False, id="reason-changed"),
+ ],
+)
+def test_only_the_default_decision_and_its_allowed_deltas_are_accepted(presentation, changes, accepted):
+ """MESSAGE-DELIVERY-337: the envelope is the default decision plus two deltas, narration's
+ Web transcript copy on or off and a declined Web Push (``PresentationDecision``); any
+ other difference raises instead of being half-executed."""
+ decision = replace(DefaultPresentationPolicy().decide(presentation), policy="other/1", **changes)
+ if accepted:
+ assert validate_decision(presentation, decision) is decision
+ else:
+ with pytest.raises(ValueError):
+ validate_decision(presentation, decision)
+
+
+ ("text", "worthy"),
+ [
+ ("one\ntwo\nthree\nfour", False),
+ ("one\ntwo\nthree\nfour\nfive", True),
+ ("x" * 499, False),
+ ("x" * 500, True),
+ ("字" * 250, True),
+ ("字" * 249, False),
+ ],
+)
+def test_the_interim_threshold_counts_lines_and_display_width(text, worthy):
+ """MESSAGE-DELIVERY-337: five non-blank lines, or 500 columns with wide characters
+ counted twice."""
+ assert interim_worthy(text) is worthy
+
+
+def test_a_decision_is_recorded_as_stable_metadata():
+ """MESSAGE-DELIVERY-337: the record a message keeps names the policy and each decided field."""
+ decision = _decision(transcript=True, web_push=True, im=ImDelivery.MESSAGE)
+ assert decision.to_metadata() == {
+ "policy": "default/1",
+ "outward": True,
+ "transcript": True,
+ "muted": False,
+ "web_push": True,
+ "im": "message",
+ }
+ assert _decision(reason="hidden").to_metadata()["reason"] == "hidden"