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.

feat(turns): a reply is a result whether or not it ends its Turn (#2867)

Call White836944075e09
diff --git a/core/agent_core/agent/README.md b/core/agent_core/agent/README.md
index d27e5fd66..37b6a6dc8 100644
--- a/core/agent_core/agent/README.md
+++ b/core/agent_core/agent/README.md
@@ -122,9 +122,9 @@ localize that error rather than deliver a silent success.
Empty non-final responses with queued inputs can still continue to a reply;
tool calls, explicit hook end, and tool termination retain their contracts.
A tool-free reply that queued input made non-final, and that did not stop at
- its output limit, is committed `superseded`: a completed reply, stored as one
- in the same transaction and shown as one, unlike narration beside tool calls,
- a stream error's partial, or a truncated reply.
+ its output limit, is committed `superseded`: a completed reply, stored as a
+ `result` in the same transaction and shown as one, unlike narration beside
+ tool calls, a stream error's partial, or a truncated reply.
- A tool batch runs in groups (C-3 section 2): neighbouring calls to tools that
declare `concurrent` run at the same time, every other call runs alone, and
each group starts after the one before it has committed. Each group's
diff --git a/core/agent_core/harness/store.py b/core/agent_core/harness/store.py
index 4ba9710ae..10fb3ad82 100644
--- a/core/agent_core/harness/store.py
+++ b/core/agent_core/harness/store.py
@@ -66,7 +66,7 @@ class TranscriptStore(Protocol):
decides. ``images`` are those the run's committed tool results generated, which a final delivers with its
reply: its committed display carries them, so the row is a complete result even if delivery never runs.
``superseded``: a non-final response is a completed reply that pending input took the final word from, which
- commits as a visible reply (``output``), so it stays one even if delivery never runs.
+ commits as a reply (``result``) like a final, so it stays one even if delivery never runs.
"""
...
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index aa55f42e7..e90e16833 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -35,14 +35,11 @@ from core.message_mirror import (
delivered_committed_row,
persist_agent_message,
persist_silent_terminal,
- promote_turn_text_to_result,
- resumed_turn_text,
)
from core.message_output import (
HARNESS_RUN_ID_TRIGGER_KINDS,
HARNESS_TRIGGER_KINDS,
MessageOutput,
- communication_type_for_output,
neutralize_mentions,
output_for_message,
)
@@ -76,7 +73,6 @@ from storage.background import (
TERMINAL_RUN_STATUSES,
normalize_run_status,
)
-from storage.messages_service import canonical_message_timestamp
from vibe.i18n import t as i18n_t
from vibe.message_types import TRANSCRIPT_COPY_KEY
@@ -204,7 +200,7 @@ async def _stream_chunk(
text: str,
message_id: Optional[str],
kind: str,
- completes_turn: bool | None = None,
+ completes_turn: bool = False,
) -> None:
"""Forward one durable agent message to the live streaming turn sink.
@@ -214,9 +210,9 @@ async def _stream_chunk(
even though the agent's receiver runs on a background task carrying a
stale per-turn context. We resolve the sink by its *thread-scoped sink key*
(stable across a session's turns) rather than off the context, so reused
- agent sessions stream correctly too. A terminal ``result`` emit also marks the
- turn complete so ``dispatch_turn`` can close the stream right after it;
- multi-output callers explicitly pass ``completes_turn=False``. No
+ agent sessions stream correctly too. ``completes_turn`` marks the turn
+ complete so ``dispatch_turn`` can close the stream right after the chunk; a
+ chunk's kind never does, since a Turn may stream several replies. No
sink (IM / CLI turns) => no-op, byte-identical to master.
"""
@@ -241,8 +237,6 @@ async def _stream_chunk(
# A misbehaving SSE consumer must not block the underlying agent
# reply. Log + swallow, same posture as ``mirror_outbound``.
logger.exception("turn on_chunk raised; dropping chunk kind=%s", kind)
- if completes_turn is None:
- completes_turn = kind == "result"
if completes_turn:
_complete_turn_sink(sink, context)
@@ -423,13 +417,6 @@ 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, Optional[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
@@ -2786,39 +2773,6 @@ class ConsolidatedMessageDispatcher:
return True
return 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.
-
- The record is the Turn's last *persisted* visible text: promotion edits
- history, and a text whose row was never written is not in it. A row that
- sits earlier in the transcript than the one held (a retried earlier
- output) never displaces it; the order is the transcript's own
- (``messages_service.transcript_order_value``: when the row entered the
- transcript, then its id). 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 not (row_id and turn_token):
- return
- key = resolve_turn_sink_key(self.controller, context)
- entered = canonical_message_timestamp(row.get("delivered_at") or row.get("created_at"))
- order = (entered, str(row_id)) if entered else None
- held = self._turn_visible_text.get(key)
- if held is not None and held[0] == turn_token and order and held[2] and held[2] > order:
- return
- self._turn_visible_text[key] = (turn_token, row_id, order)
-
- 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,
@@ -2841,7 +2795,9 @@ class ConsolidatedMessageDispatcher:
Message Types:
- Log Messages (system/assistant/toolcall): consolidated into a single
editable message per conversation round. Can be hidden by user settings.
- - Result Message: final output, always sent immediately, not hideable.
+ - Result Message: a reply, always sent immediately, not hideable. A Turn
+ may reply more than once; the reply's type never says whether it ends
+ the Turn (docs/plans/reply-and-turn-end.md).
- Notify Message: notifications, always sent immediately.
``is_error`` marks a terminal ``result`` as a FAILED turn. It is the only
@@ -2877,6 +2833,8 @@ class ConsolidatedMessageDispatcher:
compatibility default remains one terminal result. Explicit nonterminal
outputs remain in the current Turn, while detached outputs are delivered
to the Session/IM surface without touching a newer Turn or its stream.
+ The terminal emit is the Turn's end; an empty one is its content-free
+ form (docs/plans/reply-and-turn-end.md).
``hosted`` is a ``toolcall``'s hosted-tool card (``core.hosted_activity``,
``HostedActivity.to_payload``). It rides on the persisted row for the Web
@@ -2913,7 +2871,6 @@ class ConsolidatedMessageDispatcher:
and not output_semantics.detached
and 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
@@ -2937,17 +2894,11 @@ class ConsolidatedMessageDispatcher:
terminal_reason = "failed"
visible_output_type = canonical_type in {"result", "output"}
- communication_type = communication_type_for_output(
- canonical_type,
- 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
- )
+ # What a reply is depends on the reply alone: a ``result`` (``error`` when it
+ # reports a failure) whether or not this emit also ends its Turn
+ # (docs/plans/reply-and-turn-end.md). ``output`` is a type released versions
+ # wrote for a reply that did not end its Turn; a caller may still name it.
+ communication_type = "error" if canonical_type == "result" and is_error else canonical_type
if visible_output_type:
if not current_runtime_turn and not output_semantics.detached:
logger.info(
@@ -3039,48 +2990,6 @@ 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 None
- and mutates_turn_lifecycle
- and level != "silent"
- and terminal_reason == "done"
- ):
- # A rerun after a restart: what its Turn showed before was delivered
- # by the process that died, so it is read from the Turn's rows.
- turn_text_row_id = resumed_turn_text(context)
- 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
@@ -3224,8 +3133,6 @@ class ConsolidatedMessageDispatcher:
logger.info("Skipping duplicate agent output %s", native_output_id or existing_row_id)
# A dispatcher that never saw the first emit (a recovery replay) learns
# the row here; an older output's retry keeps the newer row recorded.
- if remembers_turn_text:
- self._remember_turn_text(context, accepted_message)
accepted_output_semantics = self._output_with_accepted_provenance(
output_semantics,
accepted_message,
@@ -3395,8 +3302,6 @@ 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}"
)
@@ -3807,8 +3712,6 @@ 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 (
@@ -4034,7 +3937,6 @@ 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.py
index 15e96c761..258a0a955 100644
--- a/core/message_mirror.py
+++ b/core/message_mirror.py
@@ -37,7 +37,7 @@ from core.services import sessions as workbench_sessions_service
from modules.im.base import MessageContext
from storage import agent_events_service, messages_service, settings_service
from storage.db import get_cached_sqlite_engine
-from vibe.message_types import PROMOTED_FROM_KEY, PROMOTED_FROM_TYPES, activity_role_for, spec_for
+from vibe.message_types import activity_role_for, spec_for
logger = logging.getLogger(__name__)
@@ -757,101 +757,6 @@ def _write_committed_row(
return messages_service.get_message(conn, row_id, include_local_error_detail=True)
-
-
-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_(PROMOTED_FROM_TYPES),
- )
- stored = conn.execute(
- select(messages.c.type, messages.c.content_json, messages.c.metadata_json).where(*turn_text)
- ).first()
- if stored is None:
- return None
-
- def stored_object(raw: Optional[str]) -> dict:
- try:
- value = json.loads(raw or "{}")
- except (TypeError, ValueError):
- return {}
- return value if isinstance(value, dict) else {}
-
- # ``content.kind`` names the type the row was persisted as; it moves
- # with the type, as every persist path keeps the two together. The
- # metadata keeps the type it had, so the Activity timeline still sees
- # the row mid-Turn (``PROMOTED_FROM_KEY``).
- promoted = conn.execute(
- update(messages)
- .where(*turn_text)
- .values(
- type="result",
- content_json=json.dumps({**stored_object(stored.content_json), "kind": "result"}),
- metadata_json=json.dumps(
- {**stored_object(stored.metadata_json), PROMOTED_FROM_KEY: stored.type}
- ),
- 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,
*,
@@ -981,33 +886,6 @@ def delivered_committed_row(
return row
-def resumed_turn_text(context: MessageContext) -> Optional[str]:
- """The last visible text of a Turn a restart reran, from the Turn's own rows.
-
- The dispatcher remembers each Turn's visible text as it delivers it; what a rerun
- Turn showed before the restart was delivered by the process that died, so a
- silent final of the rerun reads it from the transcript (``last_turn_text``).
- """
-
- spec = context.platform_specific or {}
- session_id, turn_id = str(spec.get("agent_session_id") or ""), str(spec.get("turn_token") or "")
- if spec.get("vibey_resume") is not True or not session_id or not turn_id:
- return None
- from storage import message_deliveries
- from storage.agent_transcript import last_turn_text
-
- try:
- with get_cached_sqlite_engine().connect() as conn:
- turn = message_deliveries.get_turn(conn, turn_id)
- if turn is None or turn["session_id"] != session_id:
- return None
- found = last_turn_text(conn, session_id, since=str(turn.get("started_at") or turn["created_at"]))
- except Exception:
- logger.debug("resumed_turn_text: lookup failed", exc_info=True)
- return None
- return found[0] if found else None
-
-
def mirror_harness_inbound(
context: MessageContext,
text: str,
diff --git a/core/message_output.py b/core/message_output.py
index 1b263e96c..10bae0eea 100644
--- a/core/message_output.py
+++ b/core/message_output.py
@@ -47,6 +47,8 @@ HARNESS_PROMPT_ECHO_TIMEOUT_SECONDS = 5.0
class MessageOutput:
"""Lifecycle and hidden provenance for one user-visible agent output."""
+ # This emit is its Turn's end event (``docs/plans/reply-and-turn-end.md``). It
+ # never decides the output's type: a reply is a ``result`` either way.
completes_turn: bool = False
completes_run: bool | None = None
detached: bool = False
@@ -200,33 +202,6 @@ def output_for_message(message_type: str, output: MessageOutput | None) -> Messa
return MessageOutput(completes_turn=False, completes_run=False)
-def communication_type_for_output(
- message_type: str,
- output: MessageOutput,
- *,
- is_error: bool = False,
-) -> str:
- """Classify a visible output by the lifecycle authority it actually owns.
-
- Attached nonterminal output is persisted as ``output``. Detached completions
- retain their ``result`` / ``error`` notification family while metadata records
- their detached provenance without granting current-Turn timeline authority.
- """
-
- if message_type == "output":
- return "output"
- if message_type == "result":
- # Detached completion keeps its notification semantics. Lifecycle consumers
- # use its provenance without changing the visible type or current Turn.
- if output.detached:
- return "error" if is_error else "result"
- if not output.completes_turn:
- return "output"
- if is_error:
- return "error"
- return message_type
-
-
def terminal_turn_output() -> MessageOutput:
"""Explicitly grant one output authority to settle its Turn and Run."""
diff --git a/core/services/session_fork.py b/core/services/session_fork.py
index ddbe29932..3459d5b5b 100644
--- a/core/services/session_fork.py
+++ b/core/services/session_fork.py
@@ -32,6 +32,10 @@ TERMINAL_AGENT_OUTPUT_TYPES = {
for message_type in types_with("activityRole")
if spec_for(message_type)["activityRole"] == "terminal"
}
+# Agent rows that show a Turn completed: a terminal row always, and a reply when its
+# Turn is no longer running, since a Turn may reply more than once
+# (docs/plans/reply-and-turn-end.md).
+_COMPLETION_ACTIVITY_ROLES = frozenset({"reply", "terminal"})
SOURCE_PROGRESS_AGENT_OUTPUT_TYPES = {
message_type
for message_type in set(types_with("activityRole")) | set(types_with("transcript"))
@@ -137,7 +141,9 @@ class ForkSourceState:
@property
def anchor_is_terminal_agent_output(self) -> bool:
- return self.anchor_author == "agent" and self.anchor_activity_role == "terminal"
+ # A reservation anchors on a running Turn's input, so an agent anchor is a
+ # finished Turn's reply or terminal row.
+ return self.anchor_author == "agent" and self.anchor_activity_role in _COMPLETION_ACTIVITY_ROLES
@dataclass(frozen=True)
@@ -612,7 +618,7 @@ def fork_source_state(fork: dict[str, Any] | None) -> ForkSourceState:
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state, resolve_primary_platform_from_config
from storage.messages_service import transcript_order_value
- from storage.models import messages
+ from storage.models import messages, session_turns
ensure_sqlite_state(primary_platform=resolve_primary_platform_from_config(paths.get_state_dir()))
engine = create_sqlite_engine(paths.get_sqlite_state_path())
@@ -686,13 +692,27 @@ def fork_source_state(fork: dict[str, Any] | None) -> ForkSourceState:
latest_after_anchor_metadata = _load_metadata(
latest_after_anchor["metadata_json"] if latest_after_anchor else None
)
- has_terminal_agent_output_after_anchor = (
- latest_after_anchor_author == "agent"
- and activity_role_for(
- latest_after_anchor_type,
- latest_after_anchor_metadata,
+ latest_after_anchor_role = activity_role_for(
+ latest_after_anchor_type,
+ latest_after_anchor_metadata,
+ )
+ has_terminal_agent_output_after_anchor = latest_after_anchor_author == "agent" and (
+ latest_after_anchor_role == "terminal"
+ or (
+ latest_after_anchor_role == "reply"
+ # A reply ends nothing while its Turn still runs: input steered
+ # into it is being answered. IM Turns have no durable row, so
+ # their reply stays the latest evidence.
+ and conn.execute(
+ select(session_turns.c.id)
+ .where(
+ session_turns.c.session_id == source_session_id,
+ session_turns.c.state.in_(("starting", "active")),
+ )
+ .limit(1)
+ ).first()
+ is None
)
- == "terminal"
)
has_input_turn_after_anchor = (
conn.execute(
diff --git a/docs/plans/agent-core-contracts/agent-event.schema.json b/docs/plans/agent-core-contracts/agent-event.schema.json
index 145ba81f3..0735cd610 100644
--- a/docs/plans/agent-core-contracts/agent-event.schema.json
+++ b/docs/plans/agent-core-contracts/agent-event.schema.json
@@ -90,7 +90,7 @@
"superseded": {
"type": "boolean",
"default": false,
- "description": "True for a non-final response that is a completed reply pending input took the final word from: tool-free, not failed, a reply (`has_reply`), not stopped at its output limit, and committed non-final only because a steer or follow-up was pending. Its row commits as `output`, a visible reply. Never true for narration beside tool calls, a stream error's partial, or a truncated reply."
+ "description": "True for a non-final response that is a completed reply pending input took the final word from: tool-free, not failed, a reply (`has_reply`), not stopped at its output limit, and committed non-final only because a steer or follow-up was pending. Its row commits as `result`, a reply that does not end the Turn (released versions committed `output`). Never true for narration beside tool calls, a stream error's partial, or a truncated reply."
}
}
}
diff --git a/docs/plans/agent-core-contracts/loop-control.md b/docs/plans/agent-core-contracts/loop-control.md
index eb2f34101..7bba47c56 100644
--- a/docs/plans/agent-core-contracts/loop-control.md
+++ b/docs/plans/agent-core-contracts/loop-control.md
@@ -81,8 +81,8 @@ add a model call, increase an output limit, or replay a task. Non-final response
with pending steer/follow-up keep continuing normally; a tool-free one that
replies and did not stop at its output limit is a completed reply that the
pending input superseded, which the loop passes to `append_response` as
-`superseded`, so it commits as `output`, a visible reply, in the same
-transaction. A truncated one stays narration, as it would fail as a final. Truncated tool calls keep the existing bounded reissue
+`superseded`, so it commits as `result`, a reply like a final, in the same
+transaction (released versions committed it as `output`). A truncated one stays narration, as it would fail as a final. Truncated tool calls keep the existing bounded reissue
path without executing their partial arguments.
A final response with `stop_reason` `refusal` or `safety` and no text is still committed as the final
@@ -177,7 +177,7 @@ sent with that request gets the error result `Tool <name> is not available.`
| --- | --- |
| `run_started` | none; the Turn was opened by its delivery |
| `text_delta`, `thinking_delta` | dropped: no backend shows live partial text, and none will (owner decision, 2026-10-08), so progress comes from the committed narration and tool lines, as for the other backends |
-| `message_committed` | the committed `messages` row is delivered: `assistant` as activity, `output` (`superseded`, a reply pending input took the final word from) as a visible reply that a silent final makes the Turn's result, `result` as the reply |
+| `message_committed` | the committed `messages` row is delivered: `assistant` as activity, a `superseded` `result` (a reply pending input took the final word from) as a reply that does not end the Turn, the final `result` as the reply that ends it; a Turn whose final is silent settles with its last reply ([`reply-and-turn-end.md`](../reply-and-turn-end.md)) |
| `tool_started` | `agent_events` `tool_call` trace row; IM progress line |
| `tool_progress` | dropped: no backend shows live tool output, and none will (owner decision, 2026-10-08), so a running tool shows its `tool_started` line, as for the other backends |
| `tool_finished` | the committed `tool_result` row; a handed-over job names its Watch |
diff --git a/docs/plans/agent-core-contracts/transcript.md b/docs/plans/agent-core-contracts/transcript.md
index 13fb938c1..5a8386d48 100644
--- a/docs/plans/agent-core-contracts/transcript.md
+++ b/docs/plans/agent-core-contracts/transcript.md
@@ -12,7 +12,7 @@ unique per Session across both tables (partial unique index on each table, plus
| --- | --- | --- | --- | --- |
| user or steer input | `messages` | `user` | — | `content_json.model` = `ModelInput` |
| harness input | `messages` | `harness`, `agent_initiated`, `annotation` | — | `content_json.model` = `ModelInput` |
-| model response | `messages` | `assistant` or `output` (not final), `result` or `error` (final) | — | `content_json.model` = `ModelResponse` |
+| model response | `messages` | `assistant` or `result` (not final), `result` or `error` (final); `output` (not final, released versions) | — | `content_json.model` = `ModelResponse` |
| tool result | `agent_events` | `tool_result` | `context` | `content_json` = `ToolResult` |
| checkpoint | `agent_events` | `context_compaction` | `context` | `content_json` = `Compaction` |
| cleared result | `agent_events` | `context_edit` | `context` | `content_json` = `ContextEdit` |
@@ -23,9 +23,10 @@ A final response is `error` when it failed by itself (no text of its own: an emp
stop without an explanation), as the other backends' failed terminal rows are. A successful final with nothing to show
(a silent reply) is the hidden response type `assistant`: context, but no transcript row, inbox reply, or unread
result, as the other backends persist nothing visible for it; a terminal write at delivery (a run that failed after
-the commit) types it `error`. A non-final response is `output` when it is a reply pending input superseded and has
-text to show (`superseded`, [`loop-control.md`](loop-control.md)): a visible reply, which a silent final can make the
-Turn's `result`; every other non-final response is `assistant`. Context loading accepts all four.
+the commit) types it `error`. A non-final response is `result` when it is a reply pending input superseded and has
+text to show (`superseded`, [`loop-control.md`](loop-control.md)): a reply that does not end the Turn
+([`reply-and-turn-end.md`](../reply-and-turn-end.md)); released versions typed it `output`. Every other non-final
+response is `assistant`. Context loading accepts all four.
Display-only rows keep `context_seq` null: `interim`, `notify`, an `error` that reports a run failure, `vault`,
an `output` that is not a committed response, queued or removed inputs, and the `tool_call` trace row written at tool start (its `metadata_json` carries
diff --git a/docs/plans/reply-and-turn-end.md b/docs/plans/reply-and-turn-end.md
new file mode 100644
index 000000000..1907e976e
--- /dev/null
+++ b/docs/plans/reply-and-turn-end.md
@@ -0,0 +1,233 @@
+# A reply is not the end of a Turn
+
+Status: approved by the owner (cyhhao), 2026-10-19. PR 1: shared contract,
+Vibey, and Claude's pre-steer phase typed as a reply. PR 2 and later: see Next
+steps.
+
+## Background
+
+A Turn's reply was a `result` (green bubble, Web Push, unread, Inbox preview)
+only when it was the Turn's terminal emit. The "Turn ended" signal rode on the
+last reply (`MessageOutput.completes_turn`), so a reply's type encoded whether
+it ended the Turn. When input was steered into a running Turn while the agent
+was finishing a complete answer, that answer stopped being the end and was
+demoted:
+
+- the dispatcher stored a non-terminal `result` as `output`
+ (`communication_type_for_output`);
+- Vibey committed a reply a steer superseded as `output` (#2811);
+- Claude emitted the pre-steer phase as `output` (`_emit_primary_phase_output`);
+- Codex and OpenCode narrated it as `assistant`, shown on the Web as a muted
+ `interim` copy only when long.
+
+All of those render muted or not at all, and the steered input's answer became
+the result. A silent final then needed the earlier text promoted back to
+`result` (#2803, #2807, #2815). PR #2741 tried to avoid the demotion at
+admission and was reverted (#2858); admission and steering stay as they are.
+
+## Goal
+
+Separate the two facts. What a reply is depends only on the reply. When the
+Turn ends is a separate, content-free event from each backend's native
+completion signal, and only that event does Turn-end work.
+
+## Contract
+
+1. Reply type depends only on the reply, never on whether it ends the Turn or
+ who triggered it:
+ - a complete reply (the model finished speaking for this step; no tool call
+ follows in that step; not cut off at the output limit; non-empty after
+ stripping `<silent>`) is a `result`: green, Web Push, unread. A Turn may
+ have several `result` rows;
+ - narration (text followed by tool calls in the same step) is `assistant`:
+ Activity only, with the long-narration Web `interim` copy unchanged;
+ - a silent reply shows nothing.
+2. Per-backend detection of a complete reply:
+ - Vibey: a response with no tool calls, not failed, not `length`-truncated,
+ with display text;
+ - Claude: the reply text of a completed result, including the phase
+ completed before a steer was absorbed;
+ - Codex: `agentMessage.phase` (`final_answer` and `partial_answer` are
+ replies, `commentary` is narration); a null `phase` keeps today's rule (the
+ turn's last visible message is the reply);
+ - OpenCode: a completed assistant message whose finish is not `tool-calls`.
+3. "The Turn ended" is content-free and driven by the backend's native signal
+ (Vibey run end, Claude result with no pending steer, Codex `turn/completed`,
+ OpenCode idle/settlement). It, and only it: hides the thinking indicator,
+ closes the Activity group, finalizes IM (running reaction, status bubble,
+ duration footer), settles the Run and sends its callback, writes the Turn's
+ terminal snapshot, releases the runtime, and starts the next queued input.
+ Failed and stopped Turns end with their outcome; error notices stay status
+ pills.
+4. Web Push: one push per `result` row.
+5. Run settlement and callback text: the Turn's last visible reply, for every
+ Run attached to the Turn, including one a steer attached after that reply.
+ A Turn with no visible reply settles with empty text and sends no callback.
+ The dispatcher, which writes the delivered Run copy, owns this through PR 2's
+ typed Turn-end event; nothing reconstructs it afterwards. PR 1 keeps master's
+ settlement: a Turn end settles with its own text, so a content-free end after
+ a reply settles with empty text, as master does.
+6. The demotion and promotion patches are deleted. Stored `output`, `interim`
+ and promoted rows keep rendering as they do today.
+7. Consumers that read `result` as the Turn's end move to the Turn-end signal
+ or the durable Turn state.
+
+## Shape of the change
+
+### Dispatcher (`core/message_dispatcher.py`)
+
+The terminal emit stays the Turn-end event: `emit_agent_message("result", …)`
+with `output.completes_turn` is the only emit that releases the Turn, and an
+empty body is its content-free form (already used by stops, failures and silent
+finals). A backend whose reply coincides with its completion signal may still
+carry the reply on that emit (one IM message with the done footer); the reply
+part is delivered and typed exactly as a non-terminal reply would be.
+
+- A non-terminal, non-detached `result` is persisted and delivered as `result`
+ (`communication_type_for_output` no longer returns `output` for it).
+- A Turn end settles its Runs and writes the Turn snapshot with its own text,
+ as on master; a content-free end after a reply settles with empty text until
+ PR 2 (rule 5).
+- A Run's `result_payload.outputs` stays its append-only delivery log: every
+ reply records its Run output when it is delivered, Claude's pre-steer phase
+ included.
+- A failed or stopped Turn reports its outcome, never an earlier reply, and a
+ `level="silent"` end that carries text still records that text, as before.
+- Claude: its completed pre-steer phase is now a non-terminal `result` that
+ records its Run output.
+- Codex and OpenCode: their terminal text already is the last visible reply
+ (Codex keeps the last visible `agentMessage` as the result candidate and a
+ silent message never displaces it; OpenCode substitutes the last visible
+ completed reply for a silent final), so their Runs settle with it as today.
+- `_stream_chunk` no longer derives Turn completion from `kind == "result"`.
+
+### Message catalog (`vibe/message_types.json`)
+
+`result.activityRole` becomes `reply`, a new role: it closes the current
+Activity phase and is the agent's answer, but it does not end the Turn. Turn
+end comes from the durable Turn row (`session_turns`), the IM `silent_terminal`
+trace, `error`, or a backend-failure `notify`. No partial index reads
+`activityRole`, so there is no migration.
+
+### Vibey
+
+- `_response_type`: a non-final reply a steer superseded commits as `result`.
+- The adapter emits it as a non-terminal `result`; the run's final reply still
+ rides the Turn-end emit at run end; a silent final is the content-free end.
+- `committed_final` (restart recovery) no longer needs the row type to tell a
+ superseded reply from a final: a superseded reply always has its steer after
+ it, consumed (later `context_seq`) or accepted into the Turn and unconsumed.
+ The legacy `output` check stays for rows released versions wrote.
+
+## Consumer migration
+
+| Consumer | Today | After |
+| --- | --- | --- |
+| `communication_type_for_output` | non-terminal `result` → `output` | stays `result` |
+| silent-final promotion (`promote_turn_text_to_result`, `resumed_turn_text`) | retypes earlier `output`/`interim` to `result` | deleted |
+| Claude pre-steer phase (`_emit_primary_phase_output`) | `output` | non-terminal `result` |
+| Run `result_text` / callback on a silent final | empty | unchanged in PR 1; PR 2: the Turn's last delivered reply, settled by the dispatcher |
+| Turn snapshot `result_text` on a silent final | empty | unchanged in PR 1; PR 2: as the Run |
+| `_stream_chunk` default | `kind == "result"` completes the Turn | completion only when the caller says so |
+| Activity grouping (`storage/agent_activity_service.py`) | `result` ends the Turn | `reply` closes the Activity group like a boundary; the durable Turn row / IM marker ends the Turn; promoted rows keep their recorded role; the Session's terminal Turns are read newest first through `ix_session_turns_session_created`, within the window and with no temporary sort |
+| Live Activity card (`ChatPage`, `chatMessageTypes.ts`) | `result` settles the generation | `reply` resets it like a boundary; `turn.end` settles |
+| Thinking bubble (`ChatPage`) | hides on a `result` row | hides on `turn.end` (or a failure terminal row) |
+| Pet failure notice (`petState.latestFailureNotice`) | a `result` ends the lookup as a terminal | a reply ends the lookup |
+| Fork anchors (`core/services/session_fork.py`) | a `result` after the anchor means the source completed | a reply or terminal after the anchor means completion only when the source has no running durable Turn |
+| Vibey restart recovery (`committed_final`) | `output` means "not final" | finality from later or unconsumed input; `output` still read for released rows |
+| Inbox awaiting-reply (`messages_service.list_inbox_sessions`) | durable Turn state of the latest input | unchanged: already Turn state; legacy fallback keeps `inboxSettlesReply` |
+| `completes_turn` consumers (`base.emit_result_message`, `backend_failure`, `session_activities`, `scheduled_tasks`, Claude Activity outputs) | lifecycle authority | unchanged: it names the Turn-end emit |
+
+## Deletions
+
+PR 1: the dispatcher downgrade; the whole silent-final promotion
+(`promote_turn_text_to_result`, `resumed_turn_text`, the dispatcher's legacy
+`output` memo); Vibey superseded→`output`; Claude's pre-steer `output` type.
+
+PR 2: Codex narration of the previous visible `agentMessage` and OpenCode's
+superseded replies as `assistant`, with the rest of the backend migration.
+
+## Compatibility
+
+- Rows written by released versions keep their type: `output` renders muted,
+ `interim` renders muted, a promoted `result` (`metadata.promoted_from`) keeps
+ its recorded Activity role. `PROMOTED_FROM_KEY` stays readable; nothing
+ writes it any more.
+- `committed_final` still treats a stored `output` as not final.
+- No schema or index change; `activityRole` is not part of any partial index.
+- IM Turns have no durable Turn row; a visible IM reply closes its Activity
+ group, and the IM `silent_terminal` trace is still written for a reply-less
+ IM Turn end.
+
+## Known by design
+
+- PR 1 keeps master's silent-end Run settlement: a Turn that replied and then
+ ended content-free (a silent final, a Vibey or Claude Turn whose steered
+ input needed no answer) settles its Runs and its snapshot with empty text, as
+ master does (master promoted only the Web row). Codex and OpenCode still
+ substitute their last visible reply themselves. Settling with the Turn's last
+ delivered reply is PR 2's (Next steps).
+- On the Web the thinking indicator stays until `turn.end`, so it can show
+ briefly under a final reply while the runner commits the Turn.
+- In IM a reply that does not end the Turn is its own message without the done
+ footer; the status bubble keeps running and is retired at the Turn end, as a
+ phase output was.
+- IM Turns have no durable running state, so a fork of an IM source taken
+ mid-Turn reads a reply after its anchor as completion, as it read a `result`.
+
+## Test plan
+
+Scenario `MESSAGE-DELIVERY-334` (`tests/scenarios/message_delivery/catalog.yaml`).
+
+- Dispatcher (owner boundary): a non-terminal reply followed by the steered
+ input's reply both persist as `result`, each pushes once and is on the Run's
+ output log once, and the Turn ends once after both, on its own final or on a
+ content-free end that settles as master does; a silent final after a visible
+ reply promotes nothing and pushes nothing new; narration stays `assistant`
+ and leaves the Run text empty; a stop and a failure end the Turn once and
+ carry no reply text; IM finalization (running indicator, status bubble)
+ happens once, at the Turn end.
+- Vibey (owner boundary): a complete reply followed by a steered input commits
+ and delivers as `result` and pushes once, the steered reply is a second
+ `result`, and the Turn ends once after both; a rerun after a restart promotes
+ no stored `output`.
+- Claude: a completed pre-steer phase emits a non-terminal `result` that
+ records its Run output.
+- Activity: the terminal-Turn read is pinned to an index-ordered SEARCH with no
+ temporary sort.
+- Activity grouping, fork completion, and the UI message-role helpers keep their
+ rendering for single-reply Turns and treat a mid-Turn reply as a phase
+ boundary.
+- PR 2: one primary regression per backend at its owning boundary.
+
+## Next steps
+
+Approved by the owner, in this order:
+
+1. PR 2. Claude, Codex and OpenCode move to the reply rule. In the same PR,
+ every backend, Vibey included, reports output through one typed event set:
+ reply, narration, tool activity, turn end (outcome), and error. This
+ replaces type strings plus `MessageOutput` flags, so the dispatcher no
+ longer infers semantics. Vibey's agent-event schema is the starting point.
+ The same PR completes rule 5: the dispatcher, which writes the delivered Run
+ copy, settles a Run whose Turn ends with no reply of its own with the Turn's
+ last delivered reply, on the typed Turn-end event. Requirements found in
+ PR 1's review: only a reply whose delivery succeeded counts; the text is the
+ one the dispatcher wrote (quick replies and file links stripped, citations
+ written out), not the backend's source text; it holds across a restart
+ rerun and startup reconciliation, and for every Run attached to the Turn,
+ one a steer attached after the reply included.
+2. PR 3, structural only with no behavior change. One presentation decision
+ 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.
+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
+ content, and its priority is decided through one default policy that holds
+ today's per-source defaults. Who decided is recorded in the delivery
+ history.
+
+Out of scope for now: Mailbox, P2 (doorbell, owner-confirmed meaning, not
+specified yet) and P4, decision models, firewall rules.
diff --git a/docs/plans/vibey-restart-auto-resume.md b/docs/plans/vibey-restart-auto-resume.md
index d630bcf30..7a2147dc6 100644
--- a/docs/plans/vibey-restart-auto-resume.md
+++ b/docs/plans/vibey-restart-auto-resume.md
@@ -194,16 +194,16 @@ exists; "handled" names where the in-place design still owns it.
recovers a waiting Turn again. `release_for_service_shutdown` skips a Vibey
Turn nobody asked to stop.
- `core/message_dispatcher.py` with `core/message_mirror.py`: item 8's delivery
- evidence (`delivered_committed_row`) and a rerun's silent-final result
- (`resumed_turn_text`), both bounded reads on the controller loop.
+ evidence (`delivered_committed_row`), a bounded read on the controller loop.
- `core/restart_resume.py`: `restart_resume_plan` (item 1, the steer wait, and
item 6's streak).
- `storage/message_deliveries.py`: `rotate_restart_generation` (the writer
transaction of item 2) and `turn_has_unresolved_steer`; `bind_native_start`
keeps the restart streak when the rerun binds its generation.
- `storage/agent_transcript.py`: `last_response` and `committed_final`, bounded
- reads of the context tail, and `last_turn_text`, the silent final's result,
- bounded by the Turn's start. A final follows the loop's own rule: no tool
+ reads of the context tail, and `last_turn_reply`, the reply a rerun's silent
+ final settles with (`docs/plans/reply-and-turn-end.md`), keyed by the Turn and
+ read off the loop. A final follows the loop's own rule: no tool
calls, not the `error`/`aborted` partial a failed stream commits, and no
input after it.
- `modules/agents/vibey/agent.py`: a rerun takes a committed final
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index c31ae07b0..a2b0a2750 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -4869,18 +4869,17 @@ class ClaudeAgent(BaseAgent):
completes_turn=False,
)
if activity is not None
- else MessageOutput(
- completes_turn=False,
- completes_run=False,
- records_run_output=False,
- )
+ # A reply: recorded on the Turn's Runs when it is delivered, like any other.
+ else MessageOutput(completes_turn=False, completes_run=False)
)
emitted_text = text or (
str(activity.metadata.get("summary") or "") if activity else ""
)
+ # A completed phase is a reply like any other: a ``result`` that does not end
+ # the Turn (docs/plans/reply-and-turn-end.md).
message_id = await self.controller.emit_agent_message(
context,
- "output",
+ "result",
emitted_text,
parse_mode="markdown",
output=output,
diff --git a/modules/agents/vibey/agent.py b/modules/agents/vibey/agent.py
index cc5fd3dd2..c11b9943b 100644
--- a/modules/agents/vibey/agent.py
+++ b/modules/agents/vibey/agent.py
@@ -885,8 +885,10 @@ class VibeyAgent(BaseAgent):
if event.final:
# Delivered at the end of the run, which decides how the Turn settles.
run.final_row = event.message_id
+ elif event.superseded:
+ await self._emit_reply(run, event.message_id)
else:
- await self._emit_narration(run, event.message_id, superseded=event.superseded)
+ await self._emit_narration(run, event.message_id)
elif isinstance(event, ToolStarted):
run.tool_started[event.tool_call_id] = time.monotonic()
await self._emit_tool_started(run, event)
@@ -957,9 +959,8 @@ class VibeyAgent(BaseAgent):
citations=citations,
)
else:
- # 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.
+ # A reply the model chose to keep silent: the Turn's end with no reply of
+ # its own; any earlier reply in the Turn was already delivered as one.
await self.controller.emit_agent_message(
context, "result", "", output=terminal_output_for(request)
)
@@ -1521,14 +1522,20 @@ class VibeyAgent(BaseAgent):
# --- output helpers ------------------------------------------------------
- async def _emit_narration(self, run: _Run, row_id: str, *, superseded: bool = False) -> None:
- """A non-final response through the same process path as the other backends' narration.
+ async def _emit_narration(self, run: _Run, row_id: str) -> None:
+ """A non-final response through the same process path as the other backends' narration."""
+ await self._emit_non_final(run, row_id, "assistant")
- A ``superseded`` response is a completed reply that later input took the final
- word from, not narration: like Claude's pre-steer phase, it is an ``output``
- boundary, transcript-visible whatever its length, which a silent final makes
- the Turn's result (#2803).
+ async def _emit_reply(self, run: _Run, row_id: str) -> None:
+ """A completed reply later input took the final word from: a ``result`` that does not end the Turn.
+
+ What a reply is depends on the reply alone (``docs/plans/reply-and-turn-end.md``):
+ it is green, notifies, and counts as unread like the final, whatever its
+ length; the steered input's answer is the Turn's next reply.
"""
+ await self._emit_non_final(run, row_id, "result")
+
+ async def _emit_non_final(self, run: _Run, row_id: str, message_type: str) -> None:
message = run.responses.get(row_id)
body, citations = self._display_with_citations(message, final=False) if message is not None else ("", None)
if not body.strip():
@@ -1536,13 +1543,13 @@ class VibeyAgent(BaseAgent):
try:
await self.controller.emit_agent_message(
run.request.context,
- "output" if superseded else "assistant",
+ message_type,
body,
output=MessageOutput(completes_turn=False, completes_run=False, persisted_row_id=row_id),
citations=citations,
)
except Exception:
- logger.exception("Vibey could not show narration %s", row_id)
+ logger.exception("Vibey could not show response %s", row_id)
def _display_with_citations(
self, message: AssistantMessage, *, final: bool, replied: bool = False, images: Sequence[HostedImage] = ()
diff --git a/storage/agent_activity_service.py b/storage/agent_activity_service.py
index 7658e5e9d..3c1166000 100644
--- a/storage/agent_activity_service.py
+++ b/storage/agent_activity_service.py
@@ -5,9 +5,12 @@ Composes the two persisted trace sources into per-turn groups:
* interim ``assistant`` messages (``messages`` table, ``type='assistant'``), and
* activity and migrated terminal events from ``agent_events``.
-A *turn* ends at the agent's terminal reply (``result`` / ``error`` /
-backend-failure ``notify``) or, when a new turn starts without one, is reported
-as ``interrupted``. Durable input roles and start boundaries come from the
+A *turn* ends at its durable Turn row (``session_turns``), the IM
+``silent_terminal`` trace, or a terminal row (``error`` / backend-failure
+``notify``), or, when a new turn starts without one, is reported as
+``interrupted``. A reply (``result``) closes the activity before it, like a
+phase boundary, without ending the Turn: a Turn may reply more than once
+(``docs/plans/reply-and-turn-end.md``). Durable input roles and start boundaries come from the
Delivery-to-Turn ownership graph: an initial Delivery opens its accepted Turn,
while accepted steer participants remain inside that Turn. Legacy/non-durable
rows fall back to transcript chronology. Message/event rows persist whole-second
@@ -23,8 +26,8 @@ bounds the event scan.
Each group is keyed by the id of its first activity row (stable across summary
and detail reads). ``anchor_message_id`` is the transcript message the chip
-renders against: the terminal reply for done/failed turns, or the next turn's
-opening message for an interrupted turn (``None`` when the interrupted turn is
+renders against: the reply or terminal row that closed it for done/failed
+groups, or the next turn's opening message for an interrupted turn (``None`` when the interrupted turn is
the last thing in the session — the chip trails the transcript).
Reads are bounded (recent tail) so a pathological session never triggers an
@@ -37,7 +40,7 @@ from __future__ import annotations
from datetime import datetime, timezone
from typing import Any, Optional
-from sqlalchemy import func, select
+from sqlalchemy import select
from core.backend_failure import is_backend_failure_notification
from storage import agent_events_service, messages_service
@@ -59,7 +62,7 @@ MESSAGE_SCAN_LIMIT = 500
EVENT_SCAN_LIMIT = 2000
# Message types that participate in turn structure: visible or hidden turn openers,
-# terminals (result/error/notify/silent-marker), and interim assistant activity rows.
+# replies, terminals (error/notify/silent-marker), and interim assistant activity rows.
# Hidden lifecycle rows are fetched even though they are not in TRANSCRIPT_TYPES so
# the activity projection preserves the complete Turn boundary.
_CONDITIONAL_TERMINAL_TYPES = types_with("terminalWhenEvents")
@@ -130,9 +133,9 @@ def _activity_role(msg_type: Any, metadata: Optional[dict]) -> str:
Only Activity grouping reads the promotion marker: the row stays where its text
was mid-Turn, so the Turn's groups are the ones that text had. Every other
- reader, fork recovery among them, sees the Turn's terminal output it now is.
- The marker counts only on a ``result`` and only with a type promotion writes,
- because a client may put any metadata on its own message.
+ reader, fork recovery among them, sees the reply it now is. The marker counts
+ only on a ``result`` and only with a type promotion writes, because a client
+ may put any metadata on its own message.
"""
message_type = msg_type if isinstance(msg_type, str) else ""
values = metadata or {}
@@ -145,11 +148,10 @@ def _activity_role(msg_type: Any, metadata: Optional[dict]) -> str:
def _is_terminal(msg_type: Any, author: Any, metadata: Optional[dict]) -> bool:
"""Whether an agent message legally CLOSES a turn.
- Terminals: a visible ``result``/``error`` reply, a ``backend_failure`` ``notify``
- diagnostic, OR — when the turn produced nothing user-visible (a ``<silent>``-
- stripped/empty final, or a reply-less bookkeeping turn) — the invisible ``silent``
- event persisted at the delivery chokepoint. Only cancel/Stop (no terminal at all)
- stays ``interrupted``.
+ Terminals: a visible ``error`` row or a ``backend_failure`` ``notify`` diagnostic.
+ A ``result`` is a reply, not a terminal: the Turn ends at its durable Turn row
+ or the invisible ``silent`` event (added to the timeline in ``_timeline``). Only
+ cancel/Stop (no terminal at all) stays ``interrupted``.
A PLAIN ``notify`` is deliberately NOT terminal: agents emit mid-turn notify rows
that explicitly do not end the turn (e.g. Claude's model-refusal fallback), so
@@ -323,7 +325,9 @@ def _timeline(conn, session_id: str, *, include_text: bool) -> list[dict[str, An
# A row with no text (a response that only called tools, or a hidden silent
# final) shows nothing; other backends never persist one.
kind = "activity" if str(msg.get("text") or "").strip() else "ignore"
- elif activity_role == "boundary":
+ elif activity_role in {"boundary", "reply"}:
+ # A reply closes the activity before it, like a phase boundary; the
+ # Turn ends at its durable Turn row or the IM silent marker.
kind = "boundary"
else:
kind = "ignore"
@@ -446,8 +450,12 @@ def _timeline(conn, session_id: str, *, include_text: bool) -> list[dict[str, An
.where(session_turns.c.state == "terminal")
.where(session_turns.c.terminal_outcome != "not_written")
.where(session_turns.c.terminal_at.is_not(None))
+ # The Session's latest Turns in index order (``ix_session_turns_session_created``):
+ # a Session runs its Turns one at a time, so the latest created are the latest
+ # ended, and the scan stops at the window instead of sorting the whole history.
+ # The timeline is sorted by each terminal's own time below.
.order_by(
- func.julianday(session_turns.c.terminal_at).desc(),
+ session_turns.c.created_at.desc(),
session_turns.c.id.desc(),
)
.limit(MESSAGE_SCAN_LIMIT)
@@ -492,7 +500,7 @@ def _make_group(
"id": pending[0]["id"],
# A group is positioned relative to a transcript message that is AT OR BEFORE
# the group's own end (never a future message): done/failed anchor to their
- # terminal reply (rendered BEFORE it — hug the reply from above); interrupted
+ # reply or terminal row (rendered BEFORE it — hug it from above); interrupted
# anchor to the turn's trigger / the boundary before its activity (rendered
# AFTER it). ``open_turn`` marks the last un-terminated turn — the only group
# the frontend may promote into the tail live card while it is still running.
@@ -663,7 +671,7 @@ def _build_groups(items: list[dict[str, Any]], *, include_rows: bool) -> list[di
# A silent marker is invisible in the transcript, so its DONE group
# anchors to the (visible) turn trigger AFTER it — never to the marker,
# which the frontend can't position against (#935 backward-anchor). A
- # visible terminal (result/error/notify) anchors to itself, BEFORE it
+ # visible terminal (error/notify) anchors to itself, BEFORE it
# (the chip hugs the reply from above).
if item["is_silent"]:
anchor_id, anchor_position = last_boundary_id, "after"
diff --git a/storage/agent_transcript.py b/storage/agent_transcript.py
index e91ed769e..24459b89b 100644
--- a/storage/agent_transcript.py
+++ b/storage/agent_transcript.py
@@ -91,15 +91,15 @@ from storage.agent_session_rows import reserve_write_lock
from storage.message_deliveries import TURN_OWNER_STATES
from storage.models import agent_events, agent_sessions, message_deliveries, messages, scopes, session_turns
from storage.vibey_recovery import VIBEY_RECOVERY_INPUT_PREDICATE
-from vibe.message_types import PROMOTED_FROM_TYPES
INPUT_TYPES = ("user", "harness", "agent_initiated", "annotation")
# A final response is ``result``, or ``error`` when ``final_outcome`` says it failed:
# the row carries its outcome, as the other backends' terminal rows do. A final with
# nothing to show (a silent reply) is the hidden response type ``assistant``: context,
# but no transcript row, inbox reply, or unread result, as the other backends persist
-# nothing visible for it. A non-final reply that pending input superseded commits as
-# ``output``, a visible reply, which a silent final can make the Turn's ``result``.
+# nothing visible for it. A non-final reply that pending input superseded is a reply
+# all the same, ``result`` (docs/plans/reply-and-turn-end.md); released versions
+# committed it as ``output``, which stays a response type.
FINAL_TYPES = ("result", "error")
RESPONSE_TYPES = ("assistant", "output", *FINAL_TYPES)
CONTEXT_VISIBILITY = "context"
@@ -145,7 +145,7 @@ def final_outcome(message: AssistantMessage, *, replied: Optional[bool] = None)
def _response_type(message: AssistantMessage, *, final: bool, display_text: str, replied: bool, superseded: bool) -> str:
if not final:
- return "output" if superseded and display_text.strip() else "assistant"
+ return "result" if superseded and display_text.strip() else "assistant"
if final_outcome(message, replied=replied) == "failed":
return "error"
return "result" if display_text.strip() else "assistant"
@@ -830,8 +830,9 @@ def committed_final(conn: Connection, session_id: str, turn_id: str) -> Optional
a Turn has work left unless its last committed response has no tool calls, did not
stop with ``error`` or ``aborted`` (the partial a failed stream commits), and no
input follows it, in the context or still waiting to enter it (an accepted steer no
- run consumed). Every read is bounded by the Session's context tail or by the Turn's
- own Deliveries.
+ run consumed). A reply a steer superseded is a ``result`` like a final, and that
+ steer is what follows it. Every read is bounded by the Session's context tail or by
+ the Turn's own Deliveries.
"""
response = last_response(conn, session_id)
if (
@@ -839,7 +840,7 @@ def committed_final(conn: Connection, session_id: str, turn_id: str) -> Optional
or response.turn_id != turn_id
or response.has_tool_calls
or response.stop_reason in _UNFINISHED_STOP_REASONS
- # A reply pending input superseded is visible, never final.
+ # Released versions committed a reply pending input superseded as ``output``.
or response.message_type == "output"
):
return None
@@ -866,33 +867,6 @@ def committed_final(conn: Connection, session_id: str, turn_id: str) -> Optional
return None if unconsumed is not None else response
-def last_turn_text(conn: Connection, session_id: str, *, since: str) -> Optional[tuple[str, str]]:
- """``(row_id, text)`` of the last visible text the Session's agent wrote since ``since``.
-
- What a Turn that ends on a silent final leaves as its result
- (``promote_turn_text_to_result``): its narration (``interim``) or a superseded
- reply (``output``). A Session runs one Turn at a time, so with ``since`` the
- Turn's start these are the Turn's own rows; each read is an index-keyed
- ``SEARCH`` bounded by that window.
- """
- latest: Optional[tuple[str, str, str]] = None
- for message_type in PROMOTED_FROM_TYPES:
- row = conn.execute(
- select(messages.c.created_at, messages.c.id, messages.c.content_text)
- .where(
- messages.c.session_id == session_id,
- messages.c.type == message_type,
- messages.c.created_at >= since,
- messages.c.author == "agent",
- )
- .order_by(messages.c.created_at.desc(), messages.c.id.desc())
- .limit(1)
- ).first()
- if row is not None and str(row.content_text or "").strip() and (latest is None or (row[0], row[1]) > latest[:2]):
- latest = (str(row.created_at), str(row.id), str(row.content_text))
- return (latest[1], latest[2]) if latest else None
-
-
def fork_link(conn: Connection, session_id: str) -> Optional[tuple[str, int]]:
"""``(source_session_id, anchor_seq)`` when the Session inherits a context."""
raw = conn.execute(
diff --git a/tests/scenarios/message_delivery/catalog.yaml b/tests/scenarios/message_delivery/catalog.yaml
index 88ad62389..229ad42a7 100644
--- a/tests/scenarios/message_delivery/catalog.yaml
+++ b/tests/scenarios/message_delivery/catalog.yaml
@@ -390,30 +390,23 @@ scenarios:
- tests/test_backend_failure_retry.py::test_restart_notice_names_the_watch_running_the_command_and_offers_no_retry
- tests/test_backend_failure_retry.py::test_a_restart_notice_waits_until_its_running_command_is_handed_over
- id: MESSAGE-DELIVERY-325
- name: A silent final reply makes the Turn's last visible text its result, rendered and notified once
+ name: A result released versions promoted from a silent final (metadata.promoted_from) keeps its Turn's Activity and its place in the pet; nothing promotes any more (MESSAGE-DELIVERY-334)
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_a_replayed_output_is_recorded_without_displacing_newer_text
- - 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_result
- tests/test_agent_activity_service.py::test_a_promoted_silent_final_result_keeps_the_turns_activity
- tests/test_agent_activity_service.py::test_a_promotion_marker_counts_only_on_a_promoted_result
supporting_tests:
- ui/src/pet/petState.test.ts
- ui/src/pet/PetPage.test.tsx
- id: MESSAGE-DELIVERY-326
- name: A Vibey reply a steer superseded stays a visible reply whatever its length, and a silent final makes it the Turn's result
+ name: A Vibey reply a steer superseded commits as a result from its commit, whatever its length, and a restart's rerun does not read it as the Turn's final
status: covered
kind: regression
layer: contract
test:
- - tests/test_vibey_agent.py::test_a_short_reply_a_steer_superseded_stays_a_visible_reply
- - tests/test_agent_transcript.py::test_a_reply_pending_input_superseded_commits_as_a_visible_reply
+ - tests/test_agent_transcript.py::test_a_reply_pending_input_superseded_commits_as_a_reply
- id: MESSAGE-DELIVERY-327
name: Startup reruns a Vibey Turn a restart cut in place from its transcript, once its surface can deliver, without a notice
status: covered
@@ -467,7 +460,7 @@ scenarios:
layer: contract
test: tests/test_vibey_agent.py::test_a_run_the_service_stop_cut_leaves_its_turn_open_for_its_restart_rerun
- id: MESSAGE-DELIVERY-333
- name: The rerun of a Turn whose final was committed ends with it through the live end, with no model call; a final not yet delivered is sent once, one already delivered is not sent again, a silent final promotes the Turn's earlier visible text, and the Turn stays open across another restart until then
+ name: The rerun of a Turn whose final was committed ends with it through the live end, with no model call; a final not yet delivered is sent once, one already delivered is not sent again, a silent final promotes nothing and leaves the reply the Turn showed before the restart as it was, and the Turn stays open across another restart until then
status: covered
kind: recovery
layer: contract
@@ -476,5 +469,28 @@ scenarios:
- tests/test_backend_failure_retry.py::test_restart_reruns_a_cut_vibey_turn_in_place_without_a_notice
- tests/test_backend_failure_retry.py::test_a_cut_vibey_turn_that_no_longer_qualifies_keeps_the_restart_notice
- tests/test_agent_transcript.py::test_the_restart_reads_of_a_turns_context_tail_stay_bounded
+ - id: MESSAGE-DELIVERY-334
+ name: A reply is a result whether or not it ends its Turn; a Turn may reply more than once (a steered input's answer is a second result, each notified once), and only the Turn end settles the Run, writes the Turn snapshot, hides the thinking indicator, and finalizes IM, once; a silent final after a reply promotes nothing; the Activity read of a Session's terminal Turns stays an index-ordered SEARCH within its window
+ status: covered
+ kind: regression
+ layer: contract
+ test:
+ - tests/test_message_dispatcher_turn_end.py::ReplyAndTurnEndTests::test_a_turn_replies_twice_and_ends_once_after_both
+ - tests/test_message_dispatcher_turn_end.py::ReplyAndTurnEndTests::test_a_silent_final_after_a_reply_promotes_nothing
+ - tests/test_claude_agent_sessions.py::ClaudeAgentSessionTests::test_steered_assistant_and_result_settle_the_pending_turn
+ - tests/test_message_dispatcher_turn_end.py::ReplyAndTurnEndTests::test_a_reply_or_a_failure_keeps_its_type_attached_or_detached
+ - tests/test_message_dispatcher_turn_end.py::ReplyAndTurnEndTests::test_only_a_reply_is_a_completed_turns_answer
+ - tests/test_message_dispatcher_turn_end.py::TurnEndFinalizesImOnceTests::test_im_surfaces_finalize_once_at_the_turn_end
+ - tests/test_vibey_agent.py::test_a_reply_a_steer_superseded_is_a_result_and_the_turn_ends_once_after_both
+ - tests/test_vibey_agent.py::test_a_silent_final_after_narration_shows_no_reply
+ - tests/test_vibey_agent.py::test_a_restart_rerun_ends_with_the_final_its_cut_run_committed
+ - tests/test_dispatcher_stream_chunk.py::test_only_the_turn_end_sets_done_event
+ - tests/test_session_fork.py::test_a_reply_while_the_source_turn_runs_is_not_its_completion
+ - tests/test_agent_activity_service.py::test_nonterminal_output_completes_prior_activity_and_anchors_later_work
+ - tests/test_agent_activity_service.py::test_the_turn_terminal_read_stays_within_the_window
+ supporting_tests:
+ - ui/src/components/workbench/ChatPage.hydration.test.tsx
+ - ui/src/lib/chatMessageTypes.test.ts
+ - ui/src/pet/petState.test.ts
next_priority:
- - MESSAGE-DELIVERY-334
+ - MESSAGE-DELIVERY-335
diff --git a/tests/test_agent_activity_service.py b/tests/test_agent_activity_service.py
index df6b36543..99af744b4 100644
--- a/tests/test_agent_activity_service.py
+++ b/tests/test_agent_activity_service.py
@@ -875,9 +875,12 @@ def test_activity_after_nonterminal_output_anchors_to_that_output(isolated_state
assert groups[0]["open"] is False
[email protected]("reply_type", ["output", "result"])
def test_nonterminal_output_completes_prior_activity_and_anchors_later_work(
- isolated_state,
+ isolated_state, reply_type
):
+ """MESSAGE-DELIVERY-334: a reply (``result``, or a legacy ``output``) closes the activity before
+ it without ending the Turn, so the work after it is the same Turn's, timed from the reply."""
engine = create_sqlite_engine()
sid = "ses_output_completion_boundary"
with engine.begin() as conn:
@@ -906,7 +909,7 @@ def test_nonterminal_output_completes_prior_activity_and_anchors_later_work(
scope,
sid,
mid="m_output",
- mtype="output",
+ mtype=reply_type,
author="agent",
created_at="2026-06-01T10:00:02Z",
text="primary answer",
@@ -945,6 +948,7 @@ def test_nonterminal_output_completes_prior_activity_and_anchors_later_work(
assert groups[1]["anchor_message_id"] == "m_output"
assert groups[1]["anchor_position"] == "after"
assert groups[1]["open"] is False
+ assert groups[1]["started_at"] == "2026-06-01T10:00:02Z"
@pytest.mark.parametrize(
@@ -2007,24 +2011,22 @@ def test_stop_without_terminal_stays_interrupted(isolated_state):
@pytest.mark.parametrize("shown_type", ["interim", "output"])
-def test_a_promoted_silent_final_result_keeps_the_turns_activity(isolated_state, monkeypatch, shown_type):
+def test_a_promoted_silent_final_result_keeps_the_turns_activity(isolated_state, shown_type):
"""Scenario: MESSAGE-DELIVERY-325.
- A Turn's text promoted to its result when the Turn ended on a silent reply
- renders as the result, but stays where it was mid-Turn: the Activity groups
- around it are exactly the ones its text had before promotion.
+ Released versions promoted a Turn's text to its result when the Turn ended on a
+ silent reply (``metadata.promoted_from``). Such a row renders as the result but
+ stays where it was mid-Turn: the Activity groups around it are exactly the ones
+ its text had before promotion.
"""
- from types import SimpleNamespace
+ import json
- from core import web_push_notifications
- from core.message_mirror import promote_turn_text_to_result
- from vibe.message_types import activity_role_for
+ from sqlalchemy import update
+
+ from storage import messages_service
+ from storage.models import messages
+ from vibe.message_types import PROMOTED_FROM_KEY, activity_role_for
- monkeypatch.setattr(
- web_push_notifications,
- "threading",
- SimpleNamespace(Thread=lambda **_kwargs: SimpleNamespace(start=lambda: None)),
- )
engine = create_sqlite_engine()
sid, turn_id = "ses_promoted", "trn_promoted"
with engine.begin() as conn:
@@ -2083,14 +2085,25 @@ def test_a_promoted_silent_final_result_keeps_the_turns_activity(isolated_state,
with engine.connect() as conn:
before = agent_activity_service.list_turn_groups(conn, session_id=sid)["groups"]
- promoted = promote_turn_text_to_result("m_text")
+ # What a released version's promotion wrote.
+ with engine.begin() as conn:
+ conn.execute(
+ update(messages)
+ .where(messages.c.id == "m_text")
+ .values(
+ type="result",
+ content_json=json.dumps({"text": "The report.", "kind": "result"}),
+ metadata_json=json.dumps({"turn_id": turn_id, PROMOTED_FROM_KEY: shown_type}),
+ )
+ )
+ promoted = messages_service.get_message(conn, "m_text")
assert promoted is not None and promoted["type"] == "result"
with engine.connect() as conn:
after = agent_activity_service.list_turn_groups(conn, session_id=sid)["groups"]
assert after == before
- # Everywhere else, fork recovery among them, the row is the Turn's terminal output.
- assert activity_role_for(promoted["type"], promoted["metadata"]) == "terminal"
+ # Everywhere else, fork recovery among them, the row is a reply.
+ assert activity_role_for(promoted["type"], promoted["metadata"]) == "reply"
def test_a_promotion_marker_counts_only_on_a_promoted_result(isolated_state):
@@ -2118,3 +2131,42 @@ def test_a_promotion_marker_counts_only_on_a_promoted_result(isolated_state):
("interrupted", "m_q1", 1),
("done", "m_r2", 1),
]
+
+
+def test_the_turn_terminal_read_stays_within_the_window(isolated_state):
+ """Every Activity refresh reads the Session's terminal Turns; a reply and a Turn end
+ each refresh it (MESSAGE-DELIVERY-334). The read walks ``ix_session_turns_session_created``
+ newest first and stops at its window: a SEARCH with no temporary sort, so a long-lived
+ Session's whole Turn history is never sorted (AGENTS.md "Controller Event Loop")."""
+ import sqlite3
+
+ from sqlalchemy import event
+
+ from config import paths
+
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ _seed_session(conn, session_id="ses_window")
+ statements: list[tuple[str, object]] = []
+
+ def capture(_conn, _cursor, statement, parameters, _context, _executemany):
+ statements.append((statement, parameters))
+
+ event.listen(engine, "before_cursor_execute", capture)
+ try:
+ with engine.connect() as conn:
+ agent_activity_service.list_turn_groups(conn, session_id="ses_window")
+ finally:
+ event.remove(engine, "before_cursor_execute", capture)
+
+ [(sql, params)] = [
+ (sql, params)
+ for sql, params in statements
+ if "FROM session_turns" in sql and "terminal_at IS NOT NULL" in sql and "JOIN" not in sql
+ ]
+ raw = sqlite3.connect(str(paths.get_sqlite_state_path()))
+ try:
+ plan = [row[-1] for row in raw.execute("EXPLAIN QUERY PLAN " + sql, params)]
+ finally:
+ raw.close()
+ assert plan == ["SEARCH session_turns USING INDEX ix_session_turns_session_created (session_id=?)"], plan
diff --git a/tests/test_agent_transcript.py b/tests/test_agent_transcript.py
index 0c8f48044..60c427dd2 100644
--- a/tests/test_agent_transcript.py
+++ b/tests/test_agent_transcript.py
@@ -513,16 +513,20 @@ async def test_a_final_commits_as_the_loops_reply_decision_says(engine, replied,
@pytest.mark.parametrize(
("superseded", "text", "row_type"),
- [(True, "4.", "output"), (True, "<silent>later</silent>", "assistant"), (False, "4.", "assistant")],
+ [(True, "4.", "result"), (True, "<silent>later</silent>", "assistant"), (False, "4.", "assistant")],
ids=["superseded-reply", "superseded-silent", "narration"],
)
-async def test_a_reply_pending_input_superseded_commits_as_a_visible_reply(engine, superseded, text, row_type) -> None:
- """MESSAGE-DELIVERY-326: the row is a visible reply from its commit, so it stays one if the process stops before
- its delivery; one with nothing to show stays hidden, as a silent final does."""
+async def test_a_reply_pending_input_superseded_commits_as_a_reply(engine, superseded, text, row_type) -> None:
+ """MESSAGE-DELIVERY-326 / MESSAGE-DELIVERY-334: the row is a reply (``result``) from its commit, so it stays one
+ if the process stops before its delivery, and the steer after it keeps it from reading as the Turn's final; one
+ with nothing to show stays hidden, as a silent final does."""
+ from storage.agent_transcript import committed_final
+
with engine.begin() as conn:
home = _scope(conn, "C-home")
_session(conn, "ses_main", home)
- consumed = _row(conn, "ses_main", home, "2+2?")
+ consumed = _accepted_turn(conn, "ses_main", home, "2+2?", "turn_main")
+ steer = _row(conn, "ses_main", home, "thanks")
def render(message, *, final, replied, images):
body = "".join(block.text for block in message.content if isinstance(block, TextBlock) and block.text)
@@ -530,10 +534,16 @@ async def test_a_reply_pending_input_superseded_commits_as_a_visible_reply(engin
store = SQLiteTranscriptStore(engine, render=render)
await store.consume_input("ses_main", consumed, _user("2+2?"))
- reply = await store.append_response("ses_main", _assistant(text), final=False, superseded=superseded)
+ reply = await store.append_response(
+ "ses_main", _assistant(text), final=False, superseded=superseded, turn_id="turn_main"
+ )
+ # The loop consumes the pending steer right after the reply it superseded.
+ await store.consume_input("ses_main", steer, _user("thanks"))
with engine.connect() as conn:
committed = conn.execute(select(messages.c.type).where(messages.c.id == reply.row_id)).scalar_one()
+ # A restart's rerun reads the steer after it: the reply is not the Turn's final.
+ assert committed_final(conn, "ses_main", "turn_main") is None
assert committed == row_type
# Whatever its type, it is context.
assert [entry.row_id for entry in await store.load("ses_main") if entry.kind == "response"] == [reply.row_id]
@@ -543,16 +553,15 @@ async def test_the_restart_reads_of_a_turns_context_tail_stay_bounded(engine) ->
"""MESSAGE-DELIVERY-327 / MESSAGE-DELIVERY-333: restart recovery decides each cut Turn
(``restart_resume_plan``, its restart streak included) and releases its runtime generation to
rerun it; the rerun finds the final it committed, and its end asks whether that final was
- delivered and what a silent final leaves as the result, the last two on the controller loop.
- Every read is an indexed SEARCH keyed by the Turn, a row id, the Session's context tail, or the
- Turn's own time window: no scan, and a temporary sort only over the Turn's own Deliveries, never
- over the growing history."""
+ delivered, on the controller loop. Every read is an indexed SEARCH keyed by the Turn, a row id,
+ or the Session's context tail: no scan, and a temporary sort only over the Turn's own
+ Deliveries, never over the growing history."""
from sqlalchemy import event
- from core.message_mirror import delivered_committed_row, resumed_turn_text
+ from core.message_mirror import delivered_committed_row
from core.restart_resume import restart_resume_plan, restart_streak
from modules.im.base import MessageContext
- from storage.agent_transcript import committed_final, last_turn_text
+ from storage.agent_transcript import committed_final
from storage.db import get_cached_sqlite_engine
with engine.begin() as conn:
@@ -586,11 +595,8 @@ async def test_the_restart_reads_of_a_turns_context_tail_stay_bounded(engine) ->
cut_turn = message_deliveries.get_turn(conn, "turn_cut")
assert restart_resume_plan(conn, cut_turn) == "rerun"
assert committed_final(conn, "ses_cut", "turn_cut") is None
- # A silent final's result: the Turn's last narration or superseded reply.
- last_turn_text(conn, "ses_main", since="2026-01-01T00:00:00.000000Z")
- # The rerun's end, on the loop: the final's delivery, and a silent final's result.
+ # The rerun's end, on the loop: the final's delivery.
assert delivered_committed_row(rerun, final.row_id, outward=True) is None
- assert resumed_turn_text(rerun) is None
with engine.begin() as conn:
# The rerun's writer transaction: the streak, and the released generation.
streak, response_seq = restart_streak(conn, cut_turn)
@@ -609,7 +615,7 @@ async def test_the_restart_reads_of_a_turns_context_tail_stay_bounded(engine) ->
turn_keys = ("(turn_id=?)", "(current_target_turn_id=?)")
bounded = re.compile(
r"SEARCH \w+ USING (?:COVERING )?INDEX \w+ \((?:id=\?|delivery_id=\?|turn_id=\?|current_target_turn_id=\?"
- r"|session_id=\? AND context_seq>\?|session_id=\? AND type=\? AND created_at>\?)\)"
+ r"|session_id=\? AND context_seq>\?)\)"
)
for (sql, _params), plan in zip(statements, plans):
searches = [step for step in plan if step.startswith(("SEARCH", "SCAN"))]
diff --git a/tests/test_claude_agent_sessions.py b/tests/test_claude_agent_sessions.py
index 80a432e7f..89e416ab0 100644
--- a/tests/test_claude_agent_sessions.py
+++ b/tests/test_claude_agent_sessions.py
@@ -1016,7 +1016,11 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(agent._pending_steering_input_state(composite_key), "unknown")
async def test_steered_assistant_and_result_settle_the_pending_turn(self):
- """A Result before the native input echo remains nonterminal."""
+ """A Result before the native input echo remains nonterminal.
+
+ MESSAGE-DELIVERY-334: that completed phase is a reply, a ``result`` that does
+ not end the Turn and records its Run output.
+ """
controller = _StubController()
controller._get_session_key = lambda _context: "session-1"
controller.emit_agent_message = AsyncMock()
@@ -1098,13 +1102,24 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
parse_mode="markdown",
request=pending_request,
)
+ # MESSAGE-DELIVERY-334: the completed pre-steer phase is a reply (``result``)
+ # that does not end the Turn.
controller.emit_agent_message.assert_any_await(
context,
- "output",
+ "result",
"primary final answer",
parse_mode="markdown",
output=ANY,
)
+ phase_output = next(
+ call.kwargs["output"]
+ for call in controller.emit_agent_message.await_args_list
+ if call.args[1:3] == ("result", "primary final answer")
+ )
+ self.assertFalse(phase_output.completes_turn)
+ # A reply records its Run output like every other reply (Codex: record Claude
+ # phase replies on attached Run ledgers).
+ self.assertTrue(phase_output.records_run_output)
self.assertNotIn(composite_key, agent._pending_requests)
async def test_presteer_result_stays_visible_without_agent_initiated_turn(self):
@@ -1116,7 +1131,8 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
output_semantics = []
async def _emit_output(emit_context, message_type, *_args, **kwargs):
- if message_type == "output":
+ # The completed pre-steer phase: a reply that does not end the Turn.
+ if message_type == "result" and not getattr(kwargs.get("output"), "completes_turn", True):
output_tokens.append(
emit_context.platform_specific.get("agent_runtime_turn_token")
)
@@ -1213,7 +1229,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
controller.emit_agent_message.assert_any_await(
context,
- "output",
+ "result",
"primary work completed",
parse_mode="markdown",
output=ANY,
@@ -1229,7 +1245,8 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
self.assertNotIn(composite_key, agent._pending_requests)
self.assertEqual(output_tokens, ["R2"])
self.assertEqual(len(output_semantics), 1)
- self.assertFalse(output_semantics[0].records_run_output)
+ # A reply records its Run output like every other reply (MESSAGE-DELIVERY-334).
+ self.assertTrue(output_semantics[0].records_run_output)
begin_agent_initiated_turn.assert_not_awaited()
async def test_presteer_result_settles_its_claimed_activity_without_closing_turn(self):
@@ -1311,7 +1328,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
)
primary_call = controller.emit_agent_message.await_args_list[0]
- self.assertEqual(primary_call.args[1:3], ("output", "primary result"))
+ self.assertEqual(primary_call.args[1:3], ("result", "primary result"))
primary_output = primary_call.kwargs["output"]
self.assertFalse(primary_output.completes_turn)
self.assertTrue(primary_output.settles_run)
@@ -1409,7 +1426,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
)
primary_call = controller.emit_agent_message.await_args_list[0]
- self.assertEqual(primary_call.args[1], "output")
+ self.assertEqual(primary_call.args[1], "result")
self.assertEqual(
primary_call.args[2],
"<silent>Claude turn completed without assistant text.</silent>",
@@ -1562,7 +1579,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
controller.emit_agent_message.assert_awaited_once_with(
context,
- "output",
+ "result",
"primary answer",
parse_mode="markdown",
output=ANY,
@@ -1889,7 +1906,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
controller.emit_agent_message.assert_any_await(
context,
- "output",
+ "result",
"primary answer",
parse_mode="markdown",
output=ANY,
@@ -1906,7 +1923,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
self.assertNotIn(composite_key, agent._pending_requests)
self.assertEqual(
emissions,
- [("output", "primary answer"), ("result", "steered answer")],
+ [("result", "primary answer"), ("result", "steered answer")],
)
async def test_buffered_pre_steer_assistant_keeps_primary_result_ownership(self):
diff --git a/tests/test_claude_receiver_result_settle.py b/tests/test_claude_receiver_result_settle.py
index f93b2c6f5..6bd2f3b24 100644
--- a/tests/test_claude_receiver_result_settle.py
+++ b/tests/test_claude_receiver_result_settle.py
@@ -445,7 +445,7 @@ class ResultSettlesTurnOnEmitFailureTests(unittest.IsolatedAsyncioTestCase):
agent.emit_result_message.assert_not_awaited()
agent.controller.emit_agent_message.assert_awaited_once_with(
context,
- "output",
+ "result",
"buffered primary result",
parse_mode="markdown",
output=ANY,
@@ -654,7 +654,7 @@ class ResultSettlesTurnOnEmitFailureTests(unittest.IsolatedAsyncioTestCase):
agent.controller.emit_agent_message.assert_awaited_once_with(
context,
- "output",
+ "result",
"primary result",
parse_mode="markdown",
output=ANY,
diff --git a/tests/test_claude_result_provenance.py b/tests/test_claude_result_provenance.py
index b3fe8c1cc..64a06f859 100644
--- a/tests/test_claude_result_provenance.py
+++ b/tests/test_claude_result_provenance.py
@@ -156,7 +156,7 @@ def _visible_emits(agent):
return [
(call.args[1], call.args[2])
for call in agent.controller.emit_agent_message.await_args_list
- if len(call.args) > 2 and call.args[1] in {"assistant", "toolcall", "output"}
+ if len(call.args) > 2 and call.args[1] in {"assistant", "toolcall", "output", "result"}
]
@@ -758,19 +758,20 @@ class ClaudeResultProvenanceTests(unittest.IsolatedAsyncioTestCase):
)
# Same order and shape the live path emits: the pre-steer text
- # closes its phase as a non-terminal output at the boundary.
+ # closes its phase as a reply that does not end the Turn
+ # (MESSAGE-DELIVERY-334: a completed phase is a ``result``).
self.assertEqual(
_visible_emits(agent),
[
("toolcall", "Bash(pwd)"),
- ("output", "answer before steer"),
+ ("result", "answer before steer"),
*post_steer_emits,
],
)
presteer_output = next(
call.kwargs["output"]
for call in agent.controller.emit_agent_message.await_args_list
- if call.args[1] == "output"
+ if call.args[1] == "result"
)
self.assertFalse(presteer_output.completes_turn)
self.assertEqual(agent.emit_result_message.await_count, 1)
diff --git a/tests/test_dispatcher_stream_chunk.py b/tests/test_dispatcher_stream_chunk.py
index c7d97461e..eea05e3dd 100644
--- a/tests/test_dispatcher_stream_chunk.py
+++ b/tests/test_dispatcher_stream_chunk.py
@@ -5,9 +5,10 @@ The hook bridges the in-process dispatcher to the SSE stream exposed by
from ``controller.active_turn_sinks`` — not off the context — so a reused
agent session, whose long-lived receiver carries a stale per-turn context,
still streams to the current turn. It forwards the envelope to the
-registered ``on_chunk``, swallows callback errors, and a ``result`` emit
-sets the sink's done event so ``dispatch_turn`` can close the stream. No
-sink (IM bots / CLI) => silent no-op.
+registered ``on_chunk``, swallows callback errors, and a chunk that completes its
+Turn (``completes_turn``) sets the sink's done event so ``dispatch_turn`` can close
+the stream; a reply chunk alone does not, since a Turn may reply more than once.
+No sink (IM bots / CLI) => silent no-op.
"""
from __future__ import annotations
@@ -72,21 +73,24 @@ def test_forwards_envelope_to_sink_on_chunk():
cb.assert_awaited_once_with({"text": "agent reply", "message_id": "m_42", "kind": "result"})
-def test_result_kind_sets_done_event():
+def test_only_the_turn_end_sets_done_event():
+ """MESSAGE-DELIVERY-334: a reply chunk keeps the stream open; only the Turn's end releases it."""
controller = _ControllerDouble()
done = asyncio.Event()
controller.register_turn_sink("avibe::C", on_chunk=AsyncMock(), done_event=done)
- asyncio.run(_stream_chunk(controller, _ctx(), text="final", message_id="m1", kind="result"))
- assert done.is_set(), "a result emit must release the streaming dispatch"
+ asyncio.run(_stream_chunk(controller, _ctx(), text="first", message_id="m1", kind="result"))
+ assert not done.is_set(), "a reply that does not end its Turn must keep the stream open"
+ asyncio.run(_stream_chunk(controller, _ctx(), text="final", message_id="m2", kind="result", completes_turn=True))
+ assert done.is_set(), "the Turn's end must release the streaming dispatch"
-def test_result_kind_stamps_terminal_settlement_on_sink():
+def test_turn_end_stamps_terminal_settlement_on_sink():
# The stamp is what tells a durable caller (an ``agent_runs`` row) that a REAL
# terminal result arrived, so the out-of-band writer owns the terminal state.
# Without it every honest run would be re-settled as failed.
controller = _ControllerDouble()
controller.register_turn_sink("avibe::C", on_chunk=AsyncMock(), done_event=asyncio.Event())
- asyncio.run(_stream_chunk(controller, _ctx(), text="final", message_id="m1", kind="result"))
+ asyncio.run(_stream_chunk(controller, _ctx(), text="final", message_id="m1", kind="result", completes_turn=True))
assert controller.get_turn_sink("avibe::C")["settled_by"] == SETTLED_BY_TERMINAL_RESULT
@@ -109,7 +113,7 @@ def test_result_does_not_overwrite_an_acknowledged_stop_stamp():
sink["settled_by"] = SETTLED_BY_STOPPED
done.set()
- asyncio.run(_stream_chunk(controller, _ctx(), text="final", message_id="m1", kind="result"))
+ asyncio.run(_stream_chunk(controller, _ctx(), text="final", message_id="m1", kind="result", completes_turn=True))
assert sink["settled_by"] == SETTLED_BY_STOPPED
@@ -130,7 +134,7 @@ def test_result_does_not_overwrite_a_contained_teardown_stamp():
sink["settled_by"] = SETTLED_BY_BACKEND_REFRESH
done.set()
- asyncio.run(_stream_chunk(controller, _ctx(), text="final", message_id="m1", kind="result"))
+ asyncio.run(_stream_chunk(controller, _ctx(), text="final", message_id="m1", kind="result", completes_turn=True))
assert sink["settled_by"] == SETTLED_BY_BACKEND_REFRESH
@@ -150,7 +154,7 @@ def test_result_still_upgrades_the_pessimistic_no_result_stamp():
sink = controller.get_turn_sink("avibe::C")
sink["settled_by"] = SETTLED_BY_NO_TERMINAL_RESULT
- asyncio.run(_stream_chunk(controller, _ctx(), text="final", message_id="m1", kind="result"))
+ asyncio.run(_stream_chunk(controller, _ctx(), text="final", message_id="m1", kind="result", completes_turn=True))
assert sink["settled_by"] == SETTLED_BY_TERMINAL_RESULT
@@ -168,7 +172,7 @@ def test_stale_result_does_not_stamp_active_turns_sink():
# neither via the done event nor via the settlement stamp.
controller = _ControllerDouble()
controller.register_turn_sink("avibe::C", on_chunk=AsyncMock(), done_event=asyncio.Event(), turn_token="T2")
- asyncio.run(_stream_chunk(controller, _ctx(turn_token="T1"), text="stale", message_id="m1", kind="result"))
+ asyncio.run(_stream_chunk(controller, _ctx(turn_token="T1"), text="stale", message_id="m1", kind="result", completes_turn=True))
assert controller.get_turn_sink("avibe::C").get("settled_by") is None
@@ -198,7 +202,7 @@ def test_result_with_matching_turn_token_completes():
controller = _ControllerDouble()
done = asyncio.Event()
controller.register_turn_sink("avibe::C", on_chunk=AsyncMock(), done_event=done, turn_token="T2")
- asyncio.run(_stream_chunk(controller, _ctx(turn_token="T2"), text="final", message_id="m1", kind="result"))
+ asyncio.run(_stream_chunk(controller, _ctx(turn_token="T2"), text="final", message_id="m1", kind="result", completes_turn=True))
assert done.is_set(), "a result for the active turn must release the stream"
@@ -212,7 +216,7 @@ def test_stale_result_does_not_complete_active_turn_but_still_forwards():
done = asyncio.Event()
cb = AsyncMock()
controller.register_turn_sink("avibe::C", on_chunk=cb, done_event=done, turn_token="T2")
- asyncio.run(_stream_chunk(controller, _ctx(turn_token="T1"), text="stale", message_id="m1", kind="result"))
+ asyncio.run(_stream_chunk(controller, _ctx(turn_token="T1"), text="stale", message_id="m1", kind="result", completes_turn=True))
assert not done.is_set(), "a stale turn's result must not end the active turn"
cb.assert_awaited_once() # but the chunk was still forwarded
@@ -230,7 +234,7 @@ def test_absent_ctx_token_does_not_complete_tokened_turn():
controller = _ControllerDouble()
done = asyncio.Event()
controller.register_turn_sink("avibe::C", on_chunk=AsyncMock(), done_event=done, turn_token="T2")
- asyncio.run(_stream_chunk(controller, _ctx(turn_token=None), text="final", message_id="m1", kind="result"))
+ asyncio.run(_stream_chunk(controller, _ctx(turn_token=None), text="final", message_id="m1", kind="result", completes_turn=True))
assert not done.is_set(), "tokenless emit must NOT complete a tokened (live) turn"
diff --git a/tests/test_message_dispatcher_result_fallback.py b/tests/test_message_dispatcher_result_fallback.py
index e291e9537..59a3ffa26 100644
--- a/tests/test_message_dispatcher_result_fallback.py
+++ b/tests/test_message_dispatcher_result_fallback.py
@@ -12,7 +12,6 @@ from core.message_dispatcher import ConsolidatedMessageDispatcher
from core.delivery_evidence import DeliveryEvidence
from core.message_output import (
MessageOutput,
- communication_type_for_output,
contained_teardown_output_for,
stop_output_for,
)
@@ -147,38 +146,6 @@ class _StubController:
class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):
- def test_visible_output_type_follows_turn_authority(self):
- self.assertEqual(
- communication_type_for_output(
- "result",
- MessageOutput(completes_turn=False),
- ),
- "output",
- )
- self.assertEqual(
- communication_type_for_output(
- "result",
- MessageOutput(completes_turn=True, detached=True),
- is_error=True,
- ),
- "error",
- )
- self.assertEqual(
- communication_type_for_output(
- "result",
- MessageOutput(completes_turn=True, detached=True),
- ),
- "result",
- )
- self.assertEqual(
- communication_type_for_output(
- "result",
- MessageOutput(completes_turn=True),
- is_error=True,
- ),
- "error",
- )
-
def test_terminal_snapshot_elects_fallback_after_excluding_canceled_runs(self):
controller = _StubController(platform="slack")
dispatcher = ConsolidatedMessageDispatcher(controller)
diff --git a/tests/test_message_dispatcher_silent_final.py b/tests/test_message_dispatcher_silent_final.py
deleted file mode 100644
index 0055d65e8..000000000
--- a/tests/test_message_dispatcher_silent_final.py
+++ /dev/null
@@ -1,343 +0,0 @@
-"""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_a_replayed_output_is_recorded_without_displacing_newer_text(self):
- """Scenario: MESSAGE-DELIVERY-325.
-
- An output replayed through the accepted-receipt short-circuit is recorded
- by a dispatcher that never saw its first emit, and a retry of an older
- output leaves the newer row recorded.
- """
-
- def phase(key: str) -> MessageOutput:
- return MessageOutput(completes_turn=False, completes_run=False, idempotency_key=key)
-
- with self.subTest("a fresh dispatcher replays the output"), self.state():
- await _Controller("avibe").emit_agent_message(self.context(), "output", REPORT, output=phase("p1"))
- recovered = _Controller("avibe")
- await recovered.emit_agent_message(self.context(), "output", REPORT, output=phase("p1"))
- await _Agent(recovered).emit_result_message(self.context(), "<silent>noted</silent>")
-
- self.assertEqual(self.agent_rows(), [("result", REPORT)])
-
- with self.subTest("a local-only output is replayed visibly after a newer one"), self.state():
- # The replayed row keeps its creation time but enters the transcript
- # now (``delivered_at``), after the newer output: it is the text shown last.
- controller = _Controller("avibe")
- background = self.context()
- background.platform_specific["suppress_delivery"] = True
- await controller.emit_agent_message(background, "output", REPORT, output=phase("p1"))
- await controller.emit_agent_message(self.context(), "output", "Second report.", output=phase("p2"))
- await controller.emit_agent_message(self.context(), "output", REPORT, output=phase("p1"))
- await _Agent(controller).emit_result_message(self.context(), "<silent>noted</silent>")
-
- self.assertEqual(
- sorted(self.agent_rows()), [("output", "Second report."), ("result", REPORT)]
- )
-
- with self.subTest("an older output is retried after a newer one"), self.state():
- controller = _Controller("avibe")
- await controller.emit_agent_message(self.context(), "output", REPORT, output=phase("p1"))
- await controller.emit_agent_message(self.context(), "output", "Second report.", output=phase("p2"))
- await controller.emit_agent_message(self.context(), "output", REPORT, output=phase("p1"))
- await _Agent(controller).emit_result_message(self.context(), "<silent>noted</silent>")
-
- self.assertEqual(self.agent_rows(), [("output", REPORT), ("result", "Second report.")])
-
- 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_message_dispatcher_turn_end.py b/tests/test_message_dispatcher_turn_end.py
new file mode 100644
index 000000000..ccfd47bea
--- /dev/null
+++ b/tests/test_message_dispatcher_turn_end.py
@@ -0,0 +1,338 @@
+"""A reply is not the end of its Turn (docs/plans/reply-and-turn-end.md).
+
+Scenario: MESSAGE-DELIVERY-334. A reply is a ``result`` whether or not its emit
+also ends the Turn, so a Turn can reply more than once; only the Turn-end emit
+settles the Run, writes the Turn snapshot, commits the Turn, and finalizes the
+IM surfaces. A Turn end with no reply of its own settles the Run and the snapshot
+as master does (empty text); settling it with the Turn's last delivered reply is
+PR 2's typed Turn-end event (docs/plans/reply-and-turn-end.md).
+"""
+
+from __future__ import annotations
+
+import os
+import sys
+import tempfile
+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
+from tests.test_message_dispatcher_platform_limits import _StubController
+from tests.test_message_dispatcher_status_bubble import (
+ _StubController as _BubbleController,
+ _ctx as _bubble_context,
+ _dispatcher as _bubble_dispatcher,
+)
+
+SESSION = "ses_turn_end"
+NOW = "2026-10-19T03:00:00Z"
+FIRST = "The cache is shared; two writers race. Fixed in #12."
+SECOND = "Yes, the fix also covers the CLI path."
+REPLY = 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's snapshot, and its commit: the commit runs once the Turn end armed it.
+ self.snapshots: list[dict] = []
+ self.committed_turns: list[MessageContext] = []
+ self.session_turns = SimpleNamespace(
+ on_terminal_result=lambda _context, **kwargs: self.snapshots.append(kwargs),
+ 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 ReplyAndTurnEndTests(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 one running Harness Run."""
+ from core.scheduled_tasks import TaskExecutionStore
+
+ _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()
+ engine = create_sqlite_engine()
+ try:
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn, platform="avibe", scope_type="project", native_id="proj_turn_end", now=NOW
+ )
+ conn.execute(
+ agent_sessions.insert().values(
+ id=SESSION, scope_id=scope_id, agent_backend="claude", agent_variant="default",
+ session_anchor=f"anchor_{SESSION}", native_session_id="", status="active",
+ metadata_json="{}", created_at=NOW, updated_at=NOW, last_active_at=NOW,
+ )
+ )
+ finally:
+ engine.dispose()
+ self.runs = TaskExecutionStore()
+ self.run_id = self.running_run("task-turn-end")
+ try:
+ yield
+ finally:
+ dispose_cached_sqlite_engines()
+
+ def context(self, platform: str = "avibe") -> 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": "trn_1",
+ "task_trigger_kind": "scheduled",
+ "task_execution_id": self.run_id,
+ },
+ )
+
+ @staticmethod
+ def agent_rows() -> list[tuple[str, str]]:
+ engine = create_sqlite_engine()
+ try:
+ with engine.connect() as conn:
+ return [
+ (row.type, row.content_text)
+ for row in conn.execute(
+ select(messages.c.type, messages.c.content_text)
+ .where(messages.c.session_id == SESSION, messages.c.author == "agent")
+ .order_by(messages.c.created_at, messages.c.id)
+ )
+ ]
+ finally:
+ engine.dispose()
+
+ def running_run(self, task_id: str) -> str:
+ run = self.runs.enqueue_task_run(task_id)
+ assert self.runs.claim(run.id) is not None
+ return run.id
+
+ def harness_run(self, run_id: str | None = None) -> dict:
+ return self.runs.get_run(run_id or self.run_id)
+
+ def pushed_texts(self) -> list[str]:
+ return [push["body"] for push in _ScheduledPush.pushes]
+
+ async def test_a_turn_replies_twice_and_ends_once_after_both(self):
+ """Scenario: MESSAGE-DELIVERY-334.
+
+ The reply before a steer stays a reply, the steered input's answer is a
+ second one, and the Turn ends once, after both: on its own final reply, or
+ on a content-free end.
+ """
+ for ends_with in ("its final reply", "a content-free end"):
+ with self.subTest(ends_with=ends_with), self.state():
+ controller = _Controller("avibe")
+ context = self.context()
+ await controller.emit_agent_message(context, "result", FIRST, output=REPLY)
+ # Replying did not end the Turn.
+ self.assertEqual((controller.snapshots, controller.committed_turns), ([], []))
+ self.assertEqual(self.harness_run()["status"], "running")
+ if ends_with == "its final reply":
+ await _Agent(controller).emit_result_message(context, SECOND)
+ else:
+ await controller.emit_agent_message(context, "result", SECOND, output=REPLY)
+ await controller.emit_agent_message(context, "result", "", output=terminal_turn_output())
+
+ self.assertEqual(self.agent_rows(), [("result", FIRST), ("result", SECOND)])
+ self.assertEqual(self.pushed_texts(), [FIRST, SECOND])
+ self.assertNotIn("message.updated", [name for name, _ in self.published])
+ # The end's own text settles the snapshot and the Run, as on master: a
+ # content-free end carries none (PR 2 settles it with the last reply).
+ own_text = SECOND if ends_with == "its final reply" else ""
+ [snapshot] = controller.snapshots
+ self.assertEqual((snapshot["is_error"], snapshot["terminal_evidence"]["result_text"]), (False, own_text))
+ self.assertEqual(len(controller.committed_turns), 1)
+ run = self.harness_run()
+ self.assertEqual((run["status"], run["result_text"] or ""), ("succeeded", own_text))
+ # Each delivered reply is on the Run's output log once.
+ self.assertEqual([entry["text"] for entry in run["result_payload"]["outputs"]], [FIRST, SECOND])
+
+ async def test_a_silent_final_after_a_reply_promotes_nothing(self):
+ """Scenario: MESSAGE-DELIVERY-334."""
+ for platform in ("avibe", "slack"):
+ with self.subTest(platform=platform), self.state():
+ controller = _Controller(platform)
+ context = self.context(platform)
+ await controller.emit_agent_message(context, "result", FIRST, output=REPLY)
+ # The base result path emits a ``<silent>`` final as the content-free end.
+ await _Agent(controller).emit_result_message(context, "<silent>nothing to add</silent>")
+
+ self.assertEqual(self.agent_rows(), [("result", FIRST)])
+ self.assertNotIn("message.updated", [name for name, _ in self.published])
+ self.assertEqual(self.pushed_texts(), [FIRST] if platform == "avibe" else [])
+ [snapshot] = controller.snapshots
+ self.assertEqual(snapshot["terminal_evidence"]["result_text"], "")
+ self.assertEqual(len(controller.committed_turns), 1)
+ run = self.harness_run()
+ self.assertEqual(run["status"], "succeeded")
+ self.assertEqual([entry["text"] for entry in run["result_payload"]["outputs"]], [FIRST])
+
+ async def test_a_reply_or_a_failure_keeps_its_type_attached_or_detached(self):
+ """Scenario: MESSAGE-DELIVERY-334.
+
+ Lifecycle authority never decides the type: a failure is ``error`` whether it
+ ends the current Turn or reports detached work, and a detached completion
+ keeps ``result`` (its provenance, not its type, says it is detached).
+ """
+ detached = MessageOutput(completes_turn=False, completes_run=False, detached=True)
+ cases = {
+ "an attached failure": (terminal_turn_output(), True, "error"),
+ "a detached completion": (detached, False, "result"),
+ "a detached failure": (detached, True, "error"),
+ }
+ for name, (output, is_error, expected) in cases.items():
+ with self.subTest(name), self.state():
+ controller = _Controller("avibe")
+ await controller.emit_agent_message(
+ self.context(), "result", FIRST, output=output, is_error=is_error
+ )
+
+ self.assertEqual(self.agent_rows(), [(expected, FIRST)])
+ [row] = [payload for event, payload in self.published if event == "message.new"]
+ self.assertIs(bool(row["metadata"].get("detached")), output.detached)
+
+ async def test_only_a_reply_is_a_completed_turns_answer(self):
+ """Scenario: MESSAGE-DELIVERY-334.
+
+ Narration stays narration, and a Turn that fails or is stopped ends once
+ with its outcome, never an earlier reply as its answer.
+ """
+ cases = {
+ "narration before tool calls": (
+ ("assistant", FIVE_LINES, {}),
+ {"text": "<silent>noted</silent>", "output": terminal_turn_output()},
+ [("assistant", FIVE_LINES)], "succeeded", "",
+ ),
+ "a failure after a reply": (
+ ("result", FIRST, {"output": REPLY}),
+ {"text": "", "is_error": True, "level": "silent", "output": terminal_turn_output()},
+ [("result", FIRST)], "failed", "",
+ ),
+ "a stop after a reply": (
+ ("result", FIRST, {"output": REPLY}),
+ {"text": "", "level": "silent", "output": stop_output_for(SimpleNamespace(output=None))},
+ [("result", FIRST)], "running", None,
+ ),
+ }
+ for name, (shown, end, rows, status, result_text) in cases.items():
+ with self.subTest(name), self.state():
+ controller = _Controller("avibe")
+ context = self.context()
+ message_type, body, kwargs = shown
+ await controller.emit_agent_message(context, message_type, body, **kwargs)
+ end = dict(end)
+ await controller.emit_agent_message(context, "result", end.pop("text"), **end)
+
+ # ``interim`` is the Web copy of long narration; it is not a reply.
+ self.assertEqual([row for row in self.agent_rows() if row[0] != "interim"], rows)
+ [snapshot] = controller.snapshots
+ self.assertEqual(snapshot["terminal_evidence"]["result_text"], "")
+ self.assertEqual(len(controller.committed_turns), 1)
+ run = self.harness_run()
+ # A stop's own writer settles its Run; the Turn end leaves it alone.
+ self.assertEqual((run["status"], run["result_text"] or None), (status, result_text or None))
+
+
+class _Indicator:
+ def __init__(self) -> None:
+ self.finished = 0
+
+ async def finish_terminal_turn(self, _context) -> None:
+ self.finished += 1
+
+
+class TurnEndFinalizesImOnceTests(unittest.IsolatedAsyncioTestCase):
+ async def test_im_surfaces_finalize_once_at_the_turn_end(self):
+ """Scenario: MESSAGE-DELIVERY-334.
+
+ A reply that does not end the Turn is its own message and leaves the
+ running reaction and the status bubble alone; the Turn's end retires them
+ once, whether it carries the final reply or nothing.
+ """
+ for ends_with in ("its final reply", "a content-free end"):
+ with self.subTest(ends_with=ends_with), mock.patch("core.message_dispatcher.persist_agent_message"):
+ controller = _BubbleController(platform="slack")
+ controller.processing_indicator = _Indicator()
+ dispatcher = _bubble_dispatcher(controller)
+ context = _bubble_context()
+ context.platform_specific = {"turn_token": "trn_1"}
+ client = controller.im_client
+
+ await dispatcher.emit_agent_message(context, "toolcall", "🔧 `Bash` `{}`") # bubble msg-1
+ await dispatcher.emit_agent_message(context, "result", FIRST, output=REPLY)
+ self.assertEqual(client.sent[-1], ("msg-2", FIRST, None))
+ self.assertEqual((client.deletes, controller.processing_indicator.finished), ([], 0))
+ await dispatcher.emit_agent_message(context, "toolcall", "🔧 `Read` `{}`")
+ self.assertEqual(client.edits[-1][0], "msg-1")
+
+ if ends_with == "its final reply":
+ await dispatcher.emit_agent_message(context, "result", SECOND, output=terminal_turn_output())
+ self.assertEqual(client.sent[-1], ("msg-3", SECOND, "✅ done"))
+ self.assertEqual(client.deletes, ["msg-1"])
+ else:
+ await dispatcher.emit_agent_message(context, "result", "", output=terminal_turn_output())
+ self.assertEqual(client.edits[-1][:2], ("msg-1", ""))
+ self.assertTrue(client.edits[-1][2].startswith("✅ done"))
+ self.assertEqual(len(client.sent), 2)
+ self.assertEqual(controller.processing_indicator.finished, 1)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_message_type_catalog.py b/tests/test_message_type_catalog.py
index 3bab3b282..598ef6563 100644
--- a/tests/test_message_type_catalog.py
+++ b/tests/test_message_type_catalog.py
@@ -220,10 +220,14 @@ def test_activity_fetch_and_terminal_semantics_match_current_service() -> None:
metadata = {"detached": detached}
if event is not None:
metadata["event"] = event
+ # A ``result`` is a reply, not a Turn end (docs/plans/reply-and-turn-end.md).
legacy_expected = (
- message_type in {"result", "error"}
+ message_type == "error"
or (message_type == "notify" and event == "backend_failure")
) and not (detached and spec["detachedCompletion"])
+ assert (activity_role_for(message_type, metadata) == "reply") is (
+ message_type == "result" and not detached
+ )
assert (
activity_role_for(message_type, metadata) == "terminal"
) is legacy_expected
@@ -258,7 +262,7 @@ def test_replayed_failure_is_not_foreground_activity() -> None:
assert not is_detached_completion("notify", metadata)
assert not agent_activity_service._is_terminal("notify", "agent", metadata)
assert activity_role_for("notify", {**metadata, "replayed": False}) == "terminal"
- assert activity_role_for("result", metadata) == "terminal"
+ assert activity_role_for("result", metadata) == "reply"
def test_web_push_candidate_exact_and_unread_sets_match_current_service() -> None:
diff --git a/tests/test_message_type_python_consumers.py b/tests/test_message_type_python_consumers.py
index 5db5f5535..79fabd802 100644
--- a/tests/test_message_type_python_consumers.py
+++ b/tests/test_message_type_python_consumers.py
@@ -43,10 +43,7 @@ def test_backend_failure_predicate_matches_legacy_type_and_event_pair() -> None:
def test_fork_activity_sets_match_legacy_values() -> None:
- assert session_fork.TERMINAL_AGENT_OUTPUT_TYPES == {
- "result",
- "error",
- }
+ assert session_fork.TERMINAL_AGENT_OUTPUT_TYPES == {"error"}
assert session_fork.SOURCE_PROGRESS_AGENT_OUTPUT_TYPES == {
"assistant",
"output",
diff --git a/tests/test_session_fork.py b/tests/test_session_fork.py
index d8533d238..9395823f2 100644
--- a/tests/test_session_fork.py
+++ b/tests/test_session_fork.py
@@ -1361,6 +1361,48 @@ def test_fork_source_has_agent_output_after_anchor(tmp_path: Path, monkeypatch:
engine.dispose()
+def test_a_reply_while_the_source_turn_runs_is_not_its_completion(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """MESSAGE-DELIVERY-334: a Turn may reply more than once (a steered input is answered in the
+ same Turn), so a reply after the fork anchor shows the source completed only once its durable
+ Turn is no longer running."""
+ from config import paths
+ from storage.importer import ensure_sqlite_state
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ db_path = paths.get_sqlite_state_path()
+ source_id = _seed_source_session(db_path, tmp_path)
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.begin() as conn:
+ row = conn.execute(select(agent_sessions).where(agent_sessions.c.id == source_id)).mappings().one()
+ turn_id = _seed_started_delivery(conn, scope_id=row["scope_id"], session_id=source_id, text="fix it")
+ anchor = messages_service.append(
+ conn, scope_id=row["scope_id"], session_id=source_id, platform="avibe",
+ author="user", message_type="user", text="fix it",
+ )
+ messages_service.append(
+ conn, scope_id=row["scope_id"], session_id=source_id, platform="avibe",
+ author="agent", message_type="result", text="fixed; the steered question next",
+ )
+ fork = {"source_session_id": source_id, "source_message_id": anchor["id"]}
+
+ assert fork_source_has_agent_output_after_anchor(fork) is False
+
+ with engine.begin() as conn:
+ conn.execute(
+ session_turns.update()
+ .where(session_turns.c.id == turn_id)
+ .values(state="terminal", terminal_outcome="completed", terminal_at="2026-08-01T00:02:00Z")
+ )
+
+ assert fork_source_has_agent_output_after_anchor(fork) is True
+ finally:
+ engine.dispose()
+
+
def test_fork_source_state_identifies_completed_anchor(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
from config import paths
from storage.importer import ensure_sqlite_state
diff --git a/tests/test_vibey_agent.py b/tests/test_vibey_agent.py
index a40832668..43ab993ca 100644
--- a/tests/test_vibey_agent.py
+++ b/tests/test_vibey_agent.py
@@ -2072,13 +2072,8 @@ async def test_a_silent_final_shows_nothing_and_completes(engine, session, tmp_p
assert 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.
- """
+def _recorded_pushes(monkeypatch) -> list[dict]:
+ """The Web Push payloads the dispatcher schedules, one per notifying row."""
from core import web_push_notifications
pushes: list[dict] = []
@@ -2091,6 +2086,16 @@ async def test_a_silent_final_leaves_the_visible_reply_before_it_as_the_result(
pushes.append(self.payload)
monkeypatch.setattr(web_push_notifications, "threading", SimpleNamespace(Thread=_Thread))
+ return pushes
+
+
+async def test_a_silent_final_after_narration_shows_no_reply(engine, session, tmp_path, published, monkeypatch) -> None:
+ """Scenario: MESSAGE-DELIVERY-334.
+
+ Narration beside tool calls is narration however long it is: its Web bubble stays muted, and a
+ Turn whose final is silent ends with no reply, nothing promoted, and nothing notified.
+ """
+ pushes = _recorded_pushes(monkeypatch)
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(
@@ -2099,40 +2104,27 @@ async def test_a_silent_final_leaves_the_visible_reply_before_it_as_the_result(
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
+ assert harness.rows("result") == [] and [row["content_text"] for row in harness.rows("interim")] == [report]
+ assert [name for name, _ in published if name == "message.updated"] == [] and pushes == []
+ assert harness.controller.terminals[-1]["is_error"] is False and harness.controller.terminal_texts == [""]
@pytest.mark.parametrize(
("stop_reason", "final"),
- [("stop", "<silent>already answered</silent>"), ("stop", "You're welcome."), ("length", "<silent>noted</silent>")],
- ids=["silent", "visible", "truncated"],
+ [("stop", "You're welcome."), ("stop", "<silent>already answered</silent>"), ("length", "<silent>noted</silent>")],
+ ids=["visible", "silent", "truncated"],
)
-async def test_a_short_reply_a_steer_superseded_stays_a_visible_reply(
+async def test_a_reply_a_steer_superseded_is_a_result_and_the_turn_ends_once_after_both(
engine, session, tmp_path, published, monkeypatch, stop_reason, final
) -> None:
- """Scenario: MESSAGE-DELIVERY-326.
+ """Scenario: MESSAGE-DELIVERY-334.
- A reply that a steer took the final word from is a completed reply, not narration: an
- ``output`` boundary whatever its length, kept in the context, and the Turn's result when
- the steered phase answers ``<silent>``. One cut off at its output limit was never completed,
- so it stays narration.
+ A reply a steer took the final word from is a reply: a ``result`` whatever its length,
+ green and notified once, and the steered input's answer is the Turn's second. The Turn
+ ends once, after both; a silent answer to the steer ends it with nothing promoted. One
+ cut off at its output limit was never completed, so it stays narration.
"""
- 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))
+ pushes = _recorded_pushes(monkeypatch)
generating, steered = asyncio.Event(), asyncio.Event()
async def answer(_request, _cancel):
@@ -2141,6 +2133,8 @@ async def test_a_short_reply_a_steer_superseded_stays_a_visible_reply(
yield Done(assistant("4.", stop_reason=stop_reason))
harness = _Harness(engine, tmp_path, "avibe", [answer, [Done(assistant(final))]])
+ # The Turn's end, in order with the replies the dispatcher announces.
+ harness.controller.session_turns.on_terminal_delivery_complete = lambda _context: published.append(("turn.end", {}))
request = harness.request("2+2?")
turn_id = _turn(request.context)
running = asyncio.create_task(harness.agent.handle_message(request))
@@ -2158,20 +2152,27 @@ async def test_a_short_reply_a_steer_superseded_stays_a_visible_reply(
rows = await harness.context_rows()
assert [entry.kind for entry in rows] == ["input", "response", "input", "response"]
- assert harness.rows("interim") == [] and harness.controller.terminals[-1]["is_error"] is False
+ assert harness.rows("interim") == [] and harness.rows("output") == []
+ assert [name for name, _ in published if name == "message.updated"] == []
+ assert len(harness.controller.terminals) == 1 and harness.controller.terminals[0]["is_error"] is False
+ sequence = [
+ payload.get("id") if name == "message.new" else name
+ for name, payload in published
+ if name == "turn.end" or (name == "message.new" and payload.get("type") == "result")
+ ]
if stop_reason == "length":
- assert harness.rows("output") == [] and harness.rows("result") == [] and pushes == []
+ assert harness.rows("result") == [] and pushes == [] and sequence == ["turn.end"]
assert [row["id"] for row in harness.rows("assistant")][0] == rows[1].row_id
+ assert harness.controller.terminal_texts == [""]
return
- [result] = harness.rows("result")
- if final.startswith("<silent>"):
- assert result["id"] == rows[1].row_id and result["content_text"] == "4."
- assert harness.rows("output") == []
- else:
- [reply] = harness.rows("output")
- assert reply["id"] == rows[1].row_id and reply["content_text"] == "4."
- assert result["id"] == rows[3].row_id and result["content_text"] == final
- assert [push["message_id"] for push in pushes] == [result["id"]]
+ replies = [rows[1].row_id] if final.startswith("<silent>") else [rows[1].row_id, rows[3].row_id]
+ results = {row["id"]: row["content_text"] for row in harness.rows("result")}
+ assert sorted(results) == sorted(replies) and results[rows[1].row_id] == "4."
+ assert [push["message_id"] for push in pushes] == replies
+ assert sequence == [*replies, "turn.end"]
+ # The end's own text settles the Turn, as on master: a silent end carries none (settling
+ # it with the Turn's last reply is PR 2's typed Turn-end event).
+ assert harness.controller.terminal_texts == ["" if final.startswith("<silent>") else final]
async def test_a_silent_final_whose_run_failed_after_its_commit_is_typed_by_its_row(
@@ -2587,14 +2588,15 @@ async def test_a_restart_rerun_ends_with_the_final_its_cut_run_committed(
"""MESSAGE-DELIVERY-333: the run a restart cut had committed the Turn's final, so the rerun
ends with that row through the live end, with no model call. A final that process never sent
to IM is delivered once, with the image that run generated; one whose delivery the dispatcher
- recorded is not sent again; a silent final leaves the narration that process showed as the
- Turn's result."""
+ recorded is not sent again; a silent final leaves the reply that process showed as it was
+ and promotes nothing, not even a phase a released version stored as ``output``
+ (MESSAGE-DELIVERY-334)."""
from dataclasses import replace
from core.message_output import MessageOutput, terminal_output_for
answer = "The cache is safe: one writer holds the lock."
- narration = "Found it.\nThe cache is shared.\nTwo writers race.\nThe lock went in #12.\nFixed and verified."
+ reply = "Found it: two writers raced; the lock went in #12."
harness = _Harness(engine, tmp_path, platform, [])
# The previous process: the Turn's final committed, then the restart cut the run.
request = harness.request("is the cache safe?")
@@ -2605,12 +2607,18 @@ async def test_a_restart_rerun_ends_with_the_final_its_cut_run_committed(
SESSION, request.context.platform_specific["delivery_id"], UserMessage((text("is the cache safe?"),))
)
if case == "silent":
- shown = await harness.agent.store.append_response(SESSION, assistant(narration), final=False)
+ # An earlier phase a released version stored as ``output``, then a reply a steer
+ # superseded, which that process showed before the Turn's silent final.
+ await harness.controller.emit_agent_message(
+ request.context, "output", "An earlier phase.",
+ output=MessageOutput(completes_turn=False, completes_run=False),
+ )
+ shown = await harness.agent.store.append_response(SESSION, assistant(reply), final=False, superseded=True)
await harness.controller.emit_agent_message(
- request.context, "assistant", narration,
+ request.context, "result", reply,
output=MessageOutput(completes_turn=False, completes_run=False, persisted_row_id=shown.row_id),
)
- [shown] = harness.rows("interim")
+ [shown] = harness.rows("result")
image = tmp_path / "lighthouse.jpg"
image.write_bytes(_JPEG)
final = await harness.agent.store.append_response(
@@ -2646,8 +2654,9 @@ async def test_a_restart_rerun_ends_with_the_final_its_cut_run_committed(
assert harness.controller.terminals[-1] == {"turn": cut_turn, "is_error": False, "settled_by": "terminal_result"}
[result] = harness.rows("result")
if case == "silent":
- assert (result["id"], result["content_text"]) == (shown["id"], narration)
- assert harness.rows("interim") == []
+ assert (result["id"], result["content_text"]) == (shown["id"], reply)
+ assert [row["content_text"] for row in harness.rows("output")] == ["An earlier phase."]
+ assert [name for name, _ in published if name == "message.updated"] == []
return
assert result["id"] == final.row_id and result["content_text"].startswith(answer)
sent, uploads = harness.controller.im_client.sent, harness.controller.im_client.uploads
diff --git a/ui/src/components/workbench/ChatPage.hydration.test.tsx b/ui/src/components/workbench/ChatPage.hydration.test.tsx
index c23b3e55f..77a67ae6f 100644
--- a/ui/src/components/workbench/ChatPage.hydration.test.tsx
+++ b/ui/src/components/workbench/ChatPage.hydration.test.tsx
@@ -1032,6 +1032,44 @@ describe('ChatPage transcript hydration', () => {
});
});
+ describe.each([false, true])('reply before the Turn ends with Activity enabled=%s', (activityEnabled) => {
+ it('MESSAGE-DELIVERY-334 keeps the Turn thinking after a reply until turn.end', async () => {
+ // A Turn may reply more than once (a steered input is answered in the same
+ // Turn), so a reply is drawn as the Agent's answer and only turn.end settles.
+ mocks.api.getSession.mockResolvedValue({ id: 'session-new' });
+ mocks.api.getSessionBootstrap.mockResolvedValue({
+ ...bootstrapPayload('session-new'),
+ config: { ui: { show_agent_activity: activityEnabled } },
+ turn_state: { ...idleTurnState, foreground: 'running', in_flight: true },
+ messages: [projectedMessage('owner-start', '修一下缓存')],
+ });
+ render(
+ <MemoryRouter initialEntries={['/chat/session-new']}>
+ <Routes>
+ <Route path="/chat/:sessionId" element={<ChatPage />} />
+ </Routes>
+ </MemoryRouter>,
+ );
+ await screen.findByText('chat.thinking');
+ act(() => mocks.events?.onMessageNew({
+ ...projectedMessage('first-reply', '缓存已修好。'),
+ author: 'agent', source: 'agent', type: 'result',
+ created_at: '2026-08-15T00:00:30Z',
+ metadata: { turn_id: 'current-turn' },
+ }));
+
+ const row = document.querySelector('[data-message-id="first-reply"]');
+ expect(row!.textContent).toContain('缓存已修好。');
+ // The Agent's answer, not the muted phase bubble.
+ expect(row!.querySelector('.border-mint\\/25')).not.toBeNull();
+ expect(screen.getByText('chat.thinking')).toBeTruthy();
+ expect(mocks.composer?.busy).toBe(true);
+
+ act(() => mocks.events?.onTurnEnd({ session_id: 'session-new' }));
+ expect(screen.queryByText('chat.thinking')).toBeNull();
+ });
+ });
+
describe.each([false, true])('retried failure with Activity enabled=%s', (activityEnabled) => {
it.each(['live', 'bootstrap'])('keeps the retried work thinking after a %s retry admission', async (delivery) => {
// Vibey's retry resumes the transcript and adds no row after the notice, so the
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index a0fbb3a1a..41c39800d 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -4164,15 +4164,15 @@ export const Transcript: React.FC<TranscriptProps> = ({
if (needsLatestReload) setShowJump(true);
}, [needsLatestReload]);
- // The reply arrives atomically as a persisted ``result`` row (no streaming
- // card), so the thinking bubble shows for the whole gap between send and
- // reply. Hide it the moment the last row is a fresh agent terminal — a
- // successful ``result``, a legacy ``error``, or a structured backend-failure
- // ``notify`` all end the visible response. ``working`` itself still settles
- // only from turn.end or the authoritative turn-state poll, so a late row from
- // an older Turn cannot clear Stop for a newer one. A failure notice whose Retry
- // was admitted no longer ends it: the retried work is the response now, and
- // Vibey's in-place retry adds no row after the notice.
+ // A reply arrives atomically as a persisted ``result`` row (no streaming card),
+ // and a Turn may reply more than once (input steered into it is answered in the
+ // same Turn), so the thinking bubble shows until the Turn ends: ``working``
+ // settles only from turn.end or the authoritative turn-state poll, so a late
+ // row from an older Turn cannot clear Stop for a newer one. A failure terminal
+ // (a legacy ``error`` or a structured backend-failure ``notify``) hides it at
+ // once, since it is the Turn's end. A failure notice whose Retry was admitted
+ // no longer ends it: the retried work is the response now, and Vibey's
+ // in-place retry adds no row after the notice.
const lastMessage = messages.length > 0 ? messages[messages.length - 1] : null;
const lastIsAgentTerminal =
!!lastMessage && isTerminalAgentMessage(lastMessage) && !isRetriedFailureNotice(lastMessage);
diff --git a/ui/src/lib/chatMessageTypes.test.ts b/ui/src/lib/chatMessageTypes.test.ts
index e1305e0e7..4b1226812 100644
--- a/ui/src/lib/chatMessageTypes.test.ts
+++ b/ui/src/lib/chatMessageTypes.test.ts
@@ -57,8 +57,7 @@ describe('isNotifyMessageType', () => {
});
describe('isTerminalAgentMessage', () => {
- it('recognizes results, legacy errors, and structured backend failures', () => {
- expect(isTerminalAgentMessage({ author: 'agent', type: 'result' })).toBe(true);
+ it('recognizes legacy errors and structured backend failures', () => {
expect(isTerminalAgentMessage({ author: 'agent', type: 'error' })).toBe(true);
expect(
isTerminalAgentMessage({
@@ -69,7 +68,9 @@ describe('isTerminalAgentMessage', () => {
).toBe(true);
});
- it('keeps ordinary notifications and user rows nonterminal', () => {
+ it('keeps replies, ordinary notifications and user rows nonterminal', () => {
+ // A Turn may reply more than once: a reply never ends it (docs/plans/reply-and-turn-end.md).
+ expect(isTerminalAgentMessage({ author: 'agent', type: 'result' })).toBe(false);
expect(isTerminalAgentMessage({ author: 'agent', type: 'output' })).toBe(false);
expect(isTerminalAgentMessage({ author: 'agent', type: 'notify' })).toBe(false);
expect(
@@ -105,7 +106,7 @@ describe('isTerminalAgentMessage', () => {
expect(isTerminalAgentMessage({
...message, metadata: { ...message.metadata, replayed: false },
})).toBe(true);
- expect(isTerminalAgentMessage({ author: 'agent', type: 'result', metadata: { replayed: true } })).toBe(true);
+ expect(isTerminalAgentMessage({ author: 'agent', type: 'result', metadata: { replayed: true } })).toBe(false);
});
});
@@ -126,13 +127,13 @@ describe('isBoundaryMessage', () => {
});
describe('isAgentActivityBoundaryMessage', () => {
- it('advances Activity only for the catalog effective boundary role', () => {
+ it('advances Activity only for the catalog effective boundary and reply roles', () => {
for (const type of messageTypeNames()) {
const spec = specFor(type);
for (const detached of [false, true]) {
for (const event of [undefined, ...spec.terminalWhenEvents]) {
const message = { type, metadata: { detached, event } };
- const isBoundary = spec.activityRole === 'boundary'
+ const isBoundary = (spec.activityRole === 'boundary' || spec.activityRole === 'reply')
&& !(detached && spec.detachedCompletion)
&& event === undefined;
expect(isAgentActivityBoundaryMessage({ ...message, author: 'agent' }), type).toBe(isBoundary);
diff --git a/ui/src/lib/chatMessageTypes.ts b/ui/src/lib/chatMessageTypes.ts
index d4eb467d1..fec314d64 100644
--- a/ui/src/lib/chatMessageTypes.ts
+++ b/ui/src/lib/chatMessageTypes.ts
@@ -121,21 +121,26 @@ export function isRetriedFailureNotice(
return typeof action?.state === 'string' && ADMITTED_RETRY_STATES.includes(action.state);
}
-// A terminal reply the TRANSCRIPT shows: the catalog's terminal activity role
-// intersected with transcript visibility (``silent`` is terminal for activity
-// bookkeeping but never rendered), plus the conditional terminals that only settle
-// a turn for specific metadata events (``notify`` + ``backend_failure``).
+// A terminal row the TRANSCRIPT shows: the catalog's terminal activity role
+// intersected with transcript visibility, plus the conditional terminals that only
+// settle a turn for specific metadata events (``notify`` + ``backend_failure``). A
+// ``result`` is a reply, not a terminal: a Turn may reply more than once and ends
+// at ``turn.end`` (docs/plans/reply-and-turn-end.md).
export const isTerminalAgentMessage = (message: TerminalAgentMessageCandidate): boolean => {
if (message.author !== 'agent') return false;
const spec = specFor(message.type);
return spec.transcript && activityRoleForMessage(message) === 'terminal';
};
-// A phase boundary advances the Activity group without settling the Turn.
-// Presentation's isBoundaryMessage also includes detached legacy completions,
-// which must not invalidate the foreground group's live rows or hydration.
+// A reply or a phase boundary closes the current Activity group without settling
+// the Turn. Presentation's isBoundaryMessage also includes detached legacy
+// completions, which must not invalidate the foreground group's live rows or
+// hydration; it excludes replies, which draw as the Agent's answer.
+const isActivityPhaseEnd = (role: ReturnType<typeof specFor>['activityRole']): boolean =>
+ role === 'boundary' || role === 'reply';
+
export const isAgentActivityBoundaryMessage = (message: TerminalAgentMessageCandidate): boolean =>
- message.author === 'agent' && activityRoleForMessage(message) === 'boundary';
+ message.author === 'agent' && isActivityPhaseEnd(activityRoleForMessage(message));
// Historical failures and detached completions refresh durable Activity without
// affecting its live generation. Only current terminal replies settle the Turn.
@@ -144,6 +149,6 @@ export const shouldRefreshAgentActivityForMessage = (
): boolean => {
if (message.author !== 'agent') return false;
const role = activityRoleForMessage(message);
- return role === 'boundary' || role === 'terminal'
+ return isActivityPhaseEnd(role) || role === 'terminal'
|| isDetachedCompletionMessage(message) || isReplayedFailureNotice(message);
};
diff --git a/ui/src/lib/messageTypes.test.ts b/ui/src/lib/messageTypes.test.ts
index d3a2f7599..4685f2c66 100644
--- a/ui/src/lib/messageTypes.test.ts
+++ b/ui/src/lib/messageTypes.test.ts
@@ -78,11 +78,11 @@ const wasHarnessInputType = (type: string): boolean =>
type TerminalCandidate = { author: string; type: string; metadata?: Record<string, unknown> | null };
+// A ``result`` is a reply, not a Turn end (docs/plans/reply-and-turn-end.md).
const wasTerminalAgentMessage = (message: TerminalCandidate): boolean =>
message.author === 'agent' &&
message.metadata?.detached !== true &&
- (message.type === 'result' ||
- message.type === 'error' ||
+ (message.type === 'error' ||
(message.type === 'notify' && message.metadata?.event === 'backend_failure'));
describe('catalog-derived predicates match the communication-record boundary', () => {
@@ -127,7 +127,7 @@ describe('catalog-derived predicates match the communication-record boundary', (
}
});
- it('visible terminal replies (isTerminalAgentMessage), across authors and events', () => {
+ it('visible terminal rows (isTerminalAgentMessage), across authors and events', () => {
const metadataCases: Array<Record<string, unknown> | null | undefined> = [
undefined,
null,
diff --git a/ui/src/pet/petState.ts b/ui/src/pet/petState.ts
index bcf01a39a..5cd4ea49b 100644
--- a/ui/src/pet/petState.ts
+++ b/ui/src/pet/petState.ts
@@ -4,7 +4,7 @@ import type {
WorkbenchMessage,
WorkbenchSession,
} from '@/context/ApiContext';
-import { isBackendFailureNotice, isTerminalAgentMessage, isTranscriptMessage } from '@/lib/chatMessageTypes';
+import { isBackendFailureNotice, isDetachedCompletionMessage, isTerminalAgentMessage, isTranscriptMessage } from '@/lib/chatMessageTypes';
import { specFor } from '@/lib/messageTypes';
import type { PetPose } from './PetAvatar';
@@ -54,6 +54,8 @@ export const latestFailureNotice = (messages: WorkbenchMessage[]): WorkbenchMess
for (let index = messages.length - 1; index >= 0; index -= 1) {
const message = messages[index];
if (isUserInput(message)) return null;
+ // A reply after the notice answered the exchange (a retry that went on to reply).
+ if (isAgentResult(message) && !isDetachedCompletionMessage(message)) return null;
// The foreground exchange ends at its terminal row, by the transcript's own rule:
// detached completions and replayed failures report work outside it and are skipped.
if (isTerminalAgentMessage(message)) return isBackendFailureNotice(message) ? message : null;
diff --git a/vibe/message_types.json b/vibe/message_types.json
index 818fddf7c..1faaa63cf 100644
--- a/vibe/message_types.json
+++ b/vibe/message_types.json
@@ -64,7 +64,7 @@
"inboxActivity": true,
"inboxPreview": true,
"inboxSettlesReply": true,
- "activityRole": "terminal",
+ "activityRole": "reply",
"detachedCompletion": true,
"unread": true,
"webPush": true,
diff --git a/vibe/message_types.py b/vibe/message_types.py
index f00a22ab3..30cd10682 100644
--- a/vibe/message_types.py
+++ b/vibe/message_types.py
@@ -26,7 +26,10 @@ _LIST_PROPERTIES = {
"agentRenderWhenEvents",
}
_ENUM_PROPERTIES = {
- "activityRole": {"none", "turn_start", "activity", "boundary", "terminal"},
+ # ``reply``: the agent's answer, which closes the current Activity phase like a
+ # ``boundary`` but never ends the Turn; a Turn ends at its durable Turn row, the IM
+ # ``silent_terminal`` trace, or a ``terminal`` row (docs/plans/reply-and-turn-end.md).
+ "activityRole": {"none", "turn_start", "activity", "boundary", "reply", "terminal"},
"render": {
"none",
"user",
@@ -153,12 +156,13 @@ def is_detached_completion(message_type: str, metadata: Any = None) -> bool:
TRANSCRIPT_COPY_KEY = "transcript_copy"
-# Metadata on a ``result`` promoted from Turn text when its Turn ended on a silent
-# reply (``core.message_mirror.promote_turn_text_to_result``): the type it was
-# persisted as, one of ``PROMOTED_FROM_TYPES``. The row is that Turn's terminal
-# output everywhere; only Activity grouping keeps it where its text was mid-Turn.
+# Metadata on a ``result`` that released versions promoted from Turn text when its
+# Turn ended on a silent reply: the type it was persisted as, one of
+# ``PROMOTED_FROM_TYPES``. Nothing promotes any more (docs/plans/reply-and-turn-end.md);
+# the marker stays readable on those rows. The row is a reply everywhere; only
+# Activity grouping keeps it where its text was mid-Turn.
PROMOTED_FROM_KEY = "promoted_from"
-# Transcript-visible agent text that does not end its Turn, and so can be promoted.
+# The types a released version's promotion retyped.
PROMOTED_FROM_TYPES = ("output", "interim")