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): Codex and OpenCode reply as results; a reply-less end settles with the last reply (#2869)

Call Whitebdd0043e3476
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index e90e16833..79fbc4669 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -359,6 +359,11 @@ class _ResultSplit:
links_whole: bool
+# The Turn-end read of a Turn's last delivered reply: three tries, and the pauses
+# between them (well under a second in all) before it is read as no reply.
+_TURN_REPLY_READ_BACKOFFS: tuple[Optional[float], ...] = (0.1, 0.3, None)
+
+
class ConsolidatedMessageDispatcher:
"""Dispatch agent messages while preserving existing product behavior."""
@@ -2234,6 +2239,85 @@ class ConsolidatedMessageDispatcher:
)
return []
+ @staticmethod
+ def _writes_on_delivery(canonical_type: str, output_semantics: MessageOutput) -> bool:
+ """Whether this output's derived writes wait for its delivery evidence.
+
+ A reply that does not end its Turn (a ``result`` that settles no Run) records
+ its Run output entry, the Turn's last reply, and through the emit's return
+ value any backend mark, only at the delivered-reply point: on Web and
+ background delivery once its receipt row is persisted, on IM once the
+ platform accepted the send (docs/plans/reply-and-turn-end.md). Finals and
+ Activity outputs keep their own settlement order.
+ """
+
+ return (
+ canonical_type == "result"
+ and not output_semantics.settles_run
+ and not output_semantics.requires_delivery_for_run_settlement
+ )
+
+ @staticmethod
+ def _turn_reply(
+ context: MessageContext,
+ canonical_type: str,
+ output_semantics: MessageOutput,
+ run_copy: str,
+ *,
+ is_error: bool,
+ level: str,
+ ) -> dict[str, tuple[str, str]]:
+ """``persist_agent_message``'s ``turn_reply`` for a reply that does not end its Turn.
+
+ Such a reply is what a later content-free end settles with
+ (docs/plans/reply-and-turn-end.md, rule 5): its receipt write records its Run
+ copy for the Turn in the same transaction. A final carries its own text, and
+ narration, notices, failures, detached and Activity outputs belong to no
+ Turn's answer. Empty when there is nothing to record, so a stand-in for the
+ persistence call keeps the signature it always had.
+ """
+
+ if canonical_type != "result" or is_error or level == "silent" or not (run_copy or "").strip():
+ return {}
+ if (
+ output_semantics.completes_turn
+ or output_semantics.detached
+ or not output_semantics.records_run_output
+ or output_semantics.requires_delivery_for_run_settlement
+ ):
+ return {}
+ turn_id = str((context.platform_specific or {}).get("turn_token") or "").strip()
+ return {"turn_reply": (turn_id, run_copy)} if turn_id else {}
+
+ async def _turn_last_reply(self, context: MessageContext) -> Optional[str]:
+ """The Run copy of the Turn's last delivered reply, read off the loop.
+
+ Rule 5 is best effort (docs/plans/reply-and-turn-end.md): a read that still
+ fails after a short bounded retry is logged and read as no reply, so the Turn
+ settles with "" as a content-free end always did, rather than holding or
+ failing the Turn's end.
+ """
+
+ turn_id = str((context.platform_specific or {}).get("turn_token") or "").strip()
+ manager = getattr(self.controller, "session_turns", None)
+ read = getattr(manager, "turn_last_reply", None)
+ if not turn_id or not callable(read):
+ return None
+ for attempt, backoff in enumerate(_TURN_REPLY_READ_BACKOFFS, start=1):
+ try:
+ return await self._run_off_loop(lambda: read(turn_id))
+ except Exception as err:
+ if backoff is None:
+ logger.warning(
+ "Failed to read the last reply of Turn %s after %d attempts; settling with no reply: %s",
+ turn_id,
+ attempt,
+ err,
+ )
+ return None
+ await asyncio.sleep(backoff)
+ return None
+
async def _record_suppressed_agent_run_terminal_result(
self,
context: MessageContext,
@@ -2936,6 +3020,14 @@ class ConsolidatedMessageDispatcher:
context,
output_semantics,
)
+ # A Turn that ends done without a reply of its own settles with its last
+ # delivered reply: the Run copy this dispatcher recorded for the Turn when it
+ # delivered that reply (``session_turn_replies``), or "" when it delivered none
+ # (docs/plans/reply-and-turn-end.md, rule 5).
+ ends_without_reply = mutates_turn_lifecycle and not (text and text.strip())
+ turn_reply: Optional[str] = None
+ if ends_without_reply and terminal_reason == "done" and output_semantics.settles_run:
+ turn_reply = await self._turn_last_reply(context)
# Persist the exact terminal body in the Turn snapshot before delivery.
# A steer accepted after this Turn settles can then complete its Agent Run
# without guessing from transcript order or requiring a live sink.
@@ -2954,7 +3046,13 @@ class ConsolidatedMessageDispatcher:
is_error=is_error,
settled_by=self._turn_release_settlement(output_semantics),
terminal_evidence={
- "result_text": self._fold_footer(terminal_body, result_footer),
+ # A footer is never a reply: an end without one records the
+ # Turn's last reply, or nothing.
+ "result_text": (
+ (turn_reply or "")
+ if ends_without_reply
+ else self._fold_footer(terminal_body, result_footer)
+ ),
"terminal_error": terminal_error,
"settles_run": output_semantics.settles_run,
"output_provenance": output_semantics.provenance(context),
@@ -3015,10 +3113,11 @@ class ConsolidatedMessageDispatcher:
if canonical_type == "result" and output_semantics.settles_run:
# Run completion is independent from visible Message and Turn
# completion cardinality. A detached/empty final output may
- # settle its origin Run without touching the current Turn.
+ # settle its origin Run without touching the current Turn; a
+ # Turn end without a reply of its own settles with the Turn's.
await self._record_agent_run_terminal_result(
context,
- materialize_citations(text, citations),
+ turn_reply if turn_reply else materialize_citations(text, citations),
None,
is_error=is_error,
terminal_error=terminal_error,
@@ -3253,6 +3352,14 @@ class ConsolidatedMessageDispatcher:
mutates_turn_lifecycle=mutates_turn_lifecycle,
) as commit:
recorded_text = self._fold_footer(persist_text, result_footer)
+ # A run record carries text alone, so its copy is written here.
+ # The persisted row below keeps its tokens: it is finalized with
+ # a sidecar bound to the body the reader is actually shown.
+ written_recorded_text = materialize_citations(recorded_text, citations)
+ # A background Turn's local row is its reply's receipt.
+ background_reply = self._turn_reply(
+ context, canonical_type, output_semantics, written_recorded_text, is_error=is_error, level=level
+ )
persisted_output = None
if visible_output_type:
if target_context.platform == "avibe":
@@ -3280,6 +3387,7 @@ class ConsolidatedMessageDispatcher:
native_message_id=native_output_id,
citations=citations,
existing_row_id=existing_row_id,
+ **background_reply,
)
else:
persisted_output = persist_agent_message(
@@ -3291,6 +3399,7 @@ class ConsolidatedMessageDispatcher:
native_message_id=native_output_id,
citations=citations,
existing_row_id=existing_row_id,
+ **background_reply,
)
else:
persisted_output = persist_agent_message(
@@ -3302,9 +3411,10 @@ class ConsolidatedMessageDispatcher:
citations=citations,
existing_row_id=existing_row_id,
)
- local_message_id = (persisted_output or {}).get("id") or (
- f"suppressed:{(context.platform_specific or {}).get('task_execution_id') or canonical_type}"
- )
+ # The return value is the delivery evidence, and a background output's
+ # receipt is its local row: no row, no id (never a synthetic one), so a
+ # caller that waits for evidence never mistakes a failed write for it.
+ local_message_id = (persisted_output or {}).get("id")
terminal_status = None
# These two branches are one rule and must be edited as a pair:
# the ``elif`` is the negation of the ``if``. A terminal result on
@@ -3313,11 +3423,11 @@ class ConsolidatedMessageDispatcher:
# message recorder, except an intermediate message on a Harness run,
# which belongs to no output ledger entry and is recorded by neither.
suppressed_trigger_kind = (context.platform_specific or {}).get("task_trigger_kind")
- # A run record carries text alone, so its copy is written here.
- # The persisted row above keeps its tokens: it is finalized with
- # a sidecar bound to the body the reader is actually shown.
- written_recorded_text = materialize_citations(recorded_text, citations)
- if canonical_type == "result" and suppressed_trigger_kind in HARNESS_TRIGGER_KINDS:
+ if persisted_output is None and self._writes_on_delivery(canonical_type, output_semantics):
+ # A background reply's receipt is its local row: without one there
+ # is nothing delivered to record.
+ pass
+ elif canonical_type == "result" and suppressed_trigger_kind in HARNESS_TRIGGER_KINDS:
await self._record_suppressed_agent_run_terminal_result(
context,
written_recorded_text,
@@ -3651,7 +3761,8 @@ class ConsolidatedMessageDispatcher:
settlement_output_semantics = output_semantics
settlement_result_text = written_result_text
- if not settlement_waits_for_persistence:
+ writes_on_delivery = self._writes_on_delivery(canonical_type, output_semantics)
+ if not settlement_waits_for_persistence and not writes_on_delivery:
await self._record_agent_run_terminal_result(
context,
written_result_text,
@@ -3666,6 +3777,12 @@ class ConsolidatedMessageDispatcher:
# failed every send/upload (primary_message_id is None) is NOT
# recorded, matching the old outbound mirror's success-only rule.
persisted_output = None
+ # The row written below is the reply's receipt (on avibe its delivery,
+ # on IM written once the send returned): the Turn's record of its last
+ # reply commits with it (rule 5).
+ delivered_reply = self._turn_reply(
+ context, canonical_type, output_semantics, written_result_text, is_error=is_error, level=level
+ )
if persists_without_delivery or primary_message_id is not None:
# A failed terminal result persists as type='error' so it shows in
# the transcript/inbox like any terminal message but is NOT counted
@@ -3700,6 +3817,7 @@ class ConsolidatedMessageDispatcher:
native_message_id=native_output_id,
citations=citations,
existing_row_id=existing_row_id,
+ **delivered_reply,
)
else:
persisted_output = persist_agent_message(
@@ -3711,8 +3829,26 @@ class ConsolidatedMessageDispatcher:
native_message_id=native_output_id,
citations=citations,
existing_row_id=existing_row_id,
+ **delivered_reply,
)
+ # The delivered-reply point: a non-terminal reply's Run output entry is
+ # written only with its delivery evidence (its Turn record committed
+ # with the receipt above; the return value below is a backend's).
+ if writes_on_delivery and (
+ persisted_output is not None
+ if target_context.platform == "avibe"
+ else primary_message_id is not None
+ ):
+ await self._record_agent_run_terminal_result(
+ context,
+ written_result_text,
+ primary_message_id,
+ is_error=is_error,
+ terminal_error=terminal_error,
+ output_semantics=output_semantics,
+ )
+
if settlement_waits_for_persistence:
accepted_message = persisted_output or (
agent_message_exists(target_context, native_output_id)
diff --git a/core/message_mirror.py b/core/message_mirror.py
index 258a0a955..54db00443 100644
--- a/core/message_mirror.py
+++ b/core/message_mirror.py
@@ -35,7 +35,7 @@ from core.citations import CitationBundle, finalize_citations, materialize_citat
from core.run_settlement import NON_COMPLETING_TURN_SETTLEMENTS
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 import agent_events_service, message_deliveries, messages_service, settings_service
from storage.db import get_cached_sqlite_engine
from vibe.message_types import activity_role_for, spec_for
@@ -353,9 +353,16 @@ def persist_agent_message(
error_sink: Optional[list] = None,
existing_row_id: Optional[str] = None,
hosted: Optional[dict] = None,
+ turn_reply: Optional[tuple[str, str]] = None,
) -> Optional[dict]:
"""Persist one agent output into the workbench ``messages`` store.
+ ``turn_reply`` is ``(turn_id, run_copy)`` for a reply that does not end its live
+ Turn: the reply's Run copy is recorded as the Turn's last delivered reply
+ (``session_turn_replies``) in the same transaction that writes this receipt, so
+ the receipt exists exactly when the record does (docs/plans/reply-and-turn-end.md,
+ rule 5). A replayed output that finds its receipt already written records nothing.
+
``existing_row_id`` names a row the backend already committed as its transcript
(the Avibe Agent): its display columns are written instead of inserting a
second row, and everything after the write (rank, ``message.new``, inbox) is
@@ -534,6 +541,10 @@ def persist_agent_message(
parent_native_message_id=context.thread_id,
content=content,
)
+ if turn_reply is not None and appended_row is not None:
+ # This write is the reply's receipt: the Turn's record commits
+ # with it, or neither does (a failure here fails the receipt).
+ message_deliveries.record_turn_reply(conn, *turn_reply)
if (
existing_row_id is None
and appended_row is None
diff --git a/core/session_turns.py b/core/session_turns.py
index bbd28c887..a3709b969 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -1195,6 +1195,22 @@ class SessionTurnManager:
with self._sqlite_engine().connect() as conn:
return delivery_store.accepted_agent_run_ids_for_turn(conn, turn_id)
+ def record_turn_reply(self, turn_id: str, text: str) -> bool:
+ """Record a delivered reply's Run copy on its live Turn (blocking; call off the loop)."""
+
+ if not turn_id or not self._durable_schema_available():
+ return False
+ with self._sqlite_engine().begin() as conn:
+ return delivery_store.record_turn_reply(conn, turn_id, text)
+
+ def turn_last_reply(self, turn_id: str) -> Optional[str]:
+ """The Run copy of the Turn's last delivered reply (blocking; call off the loop)."""
+
+ if not turn_id or not self._durable_schema_available():
+ return None
+ with self._sqlite_engine().connect() as conn:
+ return delivery_store.turn_last_reply(conn, turn_id)
+
def busy_session_ids(self) -> set[str]:
"""Sessions whose gate is occupied by a live turn RIGHT NOW.
diff --git a/docs/plans/reply-and-turn-end.md b/docs/plans/reply-and-turn-end.md
index 1907e976e..df173f68c 100644
--- a/docs/plans/reply-and-turn-end.md
+++ b/docs/plans/reply-and-turn-end.md
@@ -1,8 +1,9 @@
# 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.
+Status: approved by the owner (cyhhao), 2026-10-19. PR 1 (merged): shared
+contract, Vibey, and Claude's pre-steer phase typed as a reply. PR 2a: Codex and
+OpenCode on the reply rule, and rule 5 owned by the dispatcher. PR 2b and later:
+see Next steps.
## Background
@@ -63,10 +64,19 @@ completion signal, and only that event does Turn-end work.
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.
+ The dispatcher, which writes the delivered Run copy, owns this (PR 2a): when
+ it delivers a reply that does not end the Turn, it records that reply's Run
+ copy for the durable Turn (`session_turn_replies`, one row per Turn), and a
+ done Turn end with no reply of its own settles the Turn snapshot and every
+ attached Run with it. Producers forward nothing and nothing reconstructs it.
+ Rule 5 is best effort, not exactly-once (an IM send is an external effect no
+ local record can commit with), with one degradation policy: the local
+ receipt is the record, written atomically with the reply's receipt row, so
+ when that row's write fails after an IM send the transcript and the record
+ both lack the reply and the end settles with the previous recorded reply, or
+ ""; a read of the record that still fails after a short bounded retry is
+ logged and read as no reply, so the end settles with "" rather than holding
+ or failing the Turn's end.
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
@@ -85,9 +95,48 @@ 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 Turn end that carries text settles its Runs and writes the Turn snapshot
+ with it. A done Turn end with no text of its own (a silent final, an empty
+ end, a footer-only end) settles them with the Turn's row in
+ `session_turn_replies`, read by primary key off the loop, or with "" when the
+ Turn delivered no reply (rule 5). Failed, stopped and teardown ends never
+ read it.
+- The write: a reply that does not end its Turn records its Run copy (the same
+ copy the Runs get: `process_reply` applied, citations written out) for the
+ live Turn in the same SQLite transaction that writes its receipt, the row
+ `persist_agent_message` writes (on the Web its delivery, on IM once the send
+ returned, in a background Session its local row, for Vibey the display write
+ into its committed row). The receipt exists exactly when the record does: a
+ record that cannot be written fails the receipt the way a failed row write
+ does, and a crash between an IM send and its row write leaves neither, so a
+ replay sends again, as before. It is one upsert keyed by the Turn's id,
+ guarded by the Turn being `starting` or `active`, in a table of its own
+ (`turn_id` → `session_turns.id`, deferred, `ON DELETE CASCADE`), so it never
+ takes part in the Turn's compare-and-set and no transition writes or clears
+ it. A replay that finds its receipt records nothing, so an earlier reply never
+ displaces a newer one; narration, notices, failures, detached and Activity
+ outputs never write it. The last delivered reply wins, so A, B, A settle with A.
+- Every write derived from a reply that does not end its Turn happens only at
+ the dispatcher's delivered-reply point, once delivery evidence exists (on the
+ Web and in a background Session its receipt row persisted, on IM the platform
+ accepted the send): its Run output entry, its record as the Turn's last reply
+ (committed with the receipt), and a backend's own mark (OpenCode's emitted
+ id, from the emit's returned message id). Finals and Activity outputs keep
+ their settlement order. The emit's return value is that evidence: a
+ background output returns its local row's id, never a synthetic one, and
+ nothing when the row was not written. The Run output entry is best effort
+ under rule 5's policy: it is written in its own step after the receipt, so a
+ crash between the two can leave it out of `result_payload.outputs`, and a
+ replay never backfills it.
+- Every reply carries the identity its backend gives it as `idempotency_key`
+ (OpenCode's message id, Codex's item id, Vibey's committed row id, Claude's
+ `ResultMessage.uuid`), so two replies with the same text stay two entries in
+ a Run's `result_payload.outputs` and a replay stays one. A Claude phase
+ rebuilt from assistant frames at a steer receipt has no Result and so no
+ identity; it falls back to its text.
+- A footer is never a reply: with nothing visible to say, `base.emit_result_message`
+ emits an empty end and passes the duration footer only as `result_footer`,
+ so a footer-only end is content-free.
- 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.
@@ -95,10 +144,19 @@ part is delivered and typed exactly as a non-terminal reply would be.
`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.
+- Codex (PR 2a): `agentMessage.phase` decides. `final_answer` and
+ `partial_answer` are reply candidates; once anything follows a held candidate
+ (another answer, commentary, a tool call), it is delivered first, in turn
+ order, as a `result` that does not end the Turn. `commentary` is narration. A
+ message with no phase keeps the last-visible rule: a visible item after it
+ (a message, commentary, a tool call) makes it narration, delivered first in
+ the provider's order. The last
+ candidate rides the `turn/completed` end, and a silent answer never displaces
+ a visible one.
+- OpenCode (PR 2a): every completed assistant message whose finish is not
+ `tool-calls` is a reply. Earlier ones are delivered at settlement as
+ `result`s that do not end the Turn; the last visible one rides the end, and a
+ silent final never displaces it.
- `_stream_chunk` no longer derives Turn completion from `kind == "result"`.
### Message catalog (`vibe/message_types.json`)
@@ -126,8 +184,11 @@ trace, `error`, or a backend-failure `notify`. No partial index reads
| `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 |
+| Run `result_text` / callback on a silent final | empty | PR 2a: the Turn's last delivered reply (`session_turn_replies`), "" when none |
+| Turn snapshot `result_text` on a silent final | empty | PR 2a: as the Run |
+| Footer-only end (`show_duration`, no reply) | a green `result` row holding the footer, pushed, unread; Runs settle with the footer | PR 2a: content-free; no row, the concise status bubble keeps its done line, Runs settle as rule 5 says |
+| Codex earlier `agentMessage` (`codex/event_handler.py`) | narrated as `assistant` | PR 2a: `result` when its phase is an answer; `commentary` narration; no phase unchanged |
+| OpenCode superseded reply (`opencode/poll_loop.py`) | `assistant` | PR 2a: `result` |
| `_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 |
@@ -144,8 +205,8 @@ 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.
+PR 2a: Codex narration of an earlier answer and OpenCode's superseded replies
+as `assistant`; the base result path's footer promotion.
## Compatibility
@@ -154,19 +215,41 @@ superseded replies as `assistant`, with the rest of the backend migration.
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.
+- PR 1: no schema or index change; `activityRole` is not part of any partial
+ index. PR 2a: migration 0071 adds the table `session_turn_replies`
+ (additive). Released versions never read it; a database they wrote upgrades
+ with every Turn reading as having delivered no reply, and downgrade drops the
+ table.
- 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).
+- User-visible (PR 2a): a Turn that ends with no reply while `show_duration`
+ is on no longer posts a footer-only message (Web or IM verbose mode). The
+ Turn still visibly ends: the thinking indicator hides on `turn.end`, the IM
+ running reaction clears, and the concise status bubble collapses to its done
+ line with the run time.
+- A reply's Run output entry is best effort: it is written after the reply's
+ receipt, in its own step, so a crash between the two leaves it out of the
+ Run's `result_payload.outputs`; a replay finds the receipt and does not
+ backfill it.
+- Rule 5 is best effort (rule 5's degradation policy): an IM reply whose row
+ write fails after its send has no receipt and no record, so the Turn settles
+ with the reply before it; a record read that keeps failing settles with "".
+- A reply whose every send failed is not retried (the dispatcher posts its
+ delivery-failed notice) and the Turn ends normally. OpenCode records a reply
+ as emitted only once the dispatcher returned delivery evidence, so a restored
+ poll still owes an undelivered one; Codex keeps no emitted state for a
+ flushed reply, so nothing marks a failed one delivered.
+- A Turn with no durable row (legacy and CLI paths) has no recorded reply, so
+ its content-free end settles with empty text as before.
+- A Turn that ended content-free lists its last reply twice in a Run's
+ `result_payload.outputs`: once as delivered, once as the settlement entry
+ under the terminal identity, as every final's terminal record is.
+- Codex `commentary` that ends a Turn is narration, so such a Turn has no reply
+ of its own and settles as rule 5 says.
- 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
@@ -177,20 +260,34 @@ superseded replies as `assistant`, with the rest of the backend migration.
## Test plan
-Scenario `MESSAGE-DELIVERY-334` (`tests/scenarios/message_delivery/catalog.yaml`).
+Scenarios `MESSAGE-DELIVERY-334` (PR 1) and `MESSAGE-DELIVERY-335` (PR 2a)
+(`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.
+ output log, and the Turn ends once after both and settles with the last reply;
+ 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.
+- Rule 5 (PR 2a, dispatcher with the real Turn row and Run store): every
+ content-free done end (silent final, empty end with the footer shown or
+ hidden, a bare end), on the Web and IM, adds no row and settles the snapshot
+ and every attached Run, a steered one included, with the written copy of the
+ last delivered reply (A after A, B, A), read by an end in a new process; a
+ reply whose send failed is skipped, and a Turn that delivered none settles
+ with ""; a footer-only end posts nothing and still collapses the concise
+ bubble, finishes the running indicator, and clears the reaction. Storage: a
+ reply write and a real Turn transition both land, the write and read are
+ primary-key SEARCHes, and a released database upgrades (its running Turn
+ ends content-free with ""), downgrades on SQLite before 3.35 too, and
+ upgrades again.
+- Codex and OpenCode (PR 2a): an answer a steer follows stays a `result` that
+ does not end the Turn, in turn order; `commentary` is narration.
- 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`.
+ `result`, and the Turn ends once after both and settles with the last reply;
+ a rerun after a restart promotes no stored `output` and settles with the
+ reply the dead process delivered.
- 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
@@ -198,25 +295,32 @@ Scenario `MESSAGE-DELIVERY-334` (`tests/scenarios/message_delivery/catalog.yaml`
- 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.
+- PR 2b: 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.
+1. PR 2, split by the orchestrator into two PRs:
+ - PR 2a (behavior, with migration 0071; merges only with the owner's
+ approval): Codex and OpenCode move to the reply rule (Claude and Vibey
+ are on it since PR 1), and the dispatcher owns rule 5 through
+ `session_turn_replies`. 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, under repeated identical replies, and
+ for every Run attached to the Turn, one a steer attached after the reply
+ included. A footer-only end is content-free.
+ - PR 2b (structural only, no behavior change, branched from master after
+ 2a merges): 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, and rule 5 moves onto the typed Turn-end event. Emits
+ return a typed delivery receipt (delivered, with its receipt row or the
+ platform's message id; or not delivered) instead of an id or `None`, so
+ delivery evidence is a type rather than a convention every caller reads.
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
diff --git a/modules/agents/base.py b/modules/agents/base.py
index 5ab746b69..dedbcdfde 100644
--- a/modules/agents/base.py
+++ b/modules/agents/base.py
@@ -714,13 +714,11 @@ class BaseAgent(ABC):
if raw_suffix:
parts.append(raw_suffix)
body = "\n".join(parts)
- # Footer-only completion (show_duration on, no visible result/suffix):
- # promote the footnote to the visible body so a duration/token-only turn
- # is still delivered/persisted/streamed. An empty body would otherwise be
- # treated as a silent terminal result and the footnote would be lost.
- if not body.strip() and result_footer:
- body = result_footer
- result_footer = None
+ # A footer is never a reply: with no visible result or suffix this is the
+ # Turn's content-free end, and the footer rides only as ``result_footer``
+ # (the concise status bubble still shows its done line). The dispatcher
+ # settles the Turn's Runs with its last reply, if any
+ # (docs/plans/reply-and-turn-end.md).
message_id = await self.controller.emit_agent_message(
context,
"result",
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index a2b0a2750..b40ba46f8 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -121,6 +121,14 @@ def _claude_launch_inputs(claude_config: Any) -> dict[str, Any]:
if key not in _CLAUDE_LIVE_CONFIG_FIELDS
}
+
+def _result_uuid(message: object) -> Optional[str]:
+ """A ``ResultMessage``'s stream identity, None when it carries none."""
+
+ value = getattr(message, "uuid", None)
+ return value if isinstance(value, str) and value else None
+
+
class ClaudeAgent(BaseAgent):
"""Existing Claude Code integration extracted into an agent backend."""
@@ -2749,6 +2757,7 @@ class ClaudeAgent(BaseAgent):
context,
superseded_request,
superseded_result_text,
+ reply_id=_result_uuid(message),
)
self._clear_result_phase_state(composite_key)
logger.info(
@@ -4856,8 +4865,16 @@ class ClaudeAgent(BaseAgent):
context: MessageContext,
request: AgentRequest | None,
text: str,
+ *,
+ reply_id: str | None = None,
) -> None:
- """Emit a completed pre-steer phase without closing the shared Turn."""
+ """Emit a completed pre-steer phase without closing the shared Turn.
+
+ ``reply_id`` is the phase's ``ResultMessage.uuid`` when the stream gave one:
+ the reply's identity, so two phases with the same text stay two deliveries
+ and a replay of one stays one. A phase rebuilt from assistant frames at a
+ steer receipt has no Result, and so no identity.
+ """
activities = self._request_activities(request)
activity = activities[-1] if activities else None
@@ -4870,7 +4887,7 @@ class ClaudeAgent(BaseAgent):
)
if activity is not None
# A reply: recorded on the Turn's Runs when it is delivered, like any other.
- else MessageOutput(completes_turn=False, completes_run=False)
+ else MessageOutput(completes_turn=False, completes_run=False, idempotency_key=reply_id or None)
)
emitted_text = text or (
str(activity.metadata.get("summary") or "") if activity else ""
@@ -4910,10 +4927,12 @@ class ClaudeAgent(BaseAgent):
buffered_request = pending[0] if pending else None
if buffered_text or self._request_activities(buffered_request):
self._adopt_pending_turn_token(context, buffered_request)
+ buffered_message, _, _ = self._unpack_buffered_terminal(buffered)
await self._emit_primary_phase_output(
context,
buffered_request,
buffered_text,
+ reply_id=_result_uuid(buffered_message),
)
return True
diff --git a/modules/agents/codex/event_handler.py b/modules/agents/codex/event_handler.py
index e04a2f710..514110b53 100644
--- a/modules/agents/codex/event_handler.py
+++ b/modules/agents/codex/event_handler.py
@@ -16,6 +16,7 @@ from typing import TYPE_CHECKING, Any, Collection, Mapping
from vibe.i18n import t as i18n_t
from core.backend_failure import emit_backend_failure
+from core.message_output import MessageOutput
from core.citations import (
CitationBundle,
CitationSource,
@@ -52,6 +53,12 @@ _MAX_CITATION_SOURCES_PER_THREAD = 512
# Refs one thread is known not to define. Bounded like the sources it mirrors;
# forgetting one costs a re-scan of that thread's history, never a citation.
_MAX_CITATION_ABSENT_REFS_PER_THREAD = 512
+# ``agentMessage.phase`` values that make a message a reply: Codex's declared
+# answer, whether more output follows it or not. ``commentary`` is narration, and
+# a message with no phase keeps the last-visible rule (docs/plans/reply-and-turn-end.md).
+_REPLY_PHASES = frozenset({"final_answer", "partial_answer"})
+# The held role of a reply that does not end the Turn.
+_REPLY_ROLE = "result"
class CodexEventHandler:
@@ -307,19 +314,24 @@ class CodexEventHandler:
if item_type == "agentMessage":
text = item.get("text", "")
- if text:
+ phase = item.get("phase") if isinstance(item.get("phase"), str) else None
+ text_is_visible = bool(text and strip_silent_blocks(text).strip())
+ if phase == "commentary":
+ # Narration, never the Turn's reply.
+ if text_is_visible:
+ await self._narrate(request, turn_state, thread_id, "assistant", text)
+ elif text:
+ if text_is_visible:
+ # The held message is no longer the last word: it goes out first.
+ await self._flush_pending(turn_state, thread_id, visible_follower=True)
prev = turn_state.pending_assistant if turn_state else None
- text_is_visible = bool(strip_silent_blocks(text).strip())
prev_is_visible = bool(prev and strip_silent_blocks(prev[0]).strip())
- if text_is_visible and prev_is_visible:
- prev_text, prev_pm = prev
- await self._narrate(
- request, turn_state, thread_id, "assistant", prev_text, prev_pm
- )
# A silent terminal response may settle the turn, but it must
# not displace an earlier visible result candidate.
if turn_state and (text_is_visible or not prev_is_visible):
turn_state.pending_assistant = (text, "markdown")
+ turn_state.pending_assistant_phase = phase
+ turn_state.pending_assistant_id = str(item.get("id") or "") or None
elif item_type == "commandExecution":
command = item.get("command", "")
@@ -555,9 +567,56 @@ class CodexEventHandler:
resolved, citations, _ = await self._prepare_citations(text, thread_id, request)
await self._emit_narration(request, role, resolved, parse_mode, citations, level)
return
+ # What follows the held message makes it go out first, in turn order.
+ await self._flush_pending(turn_state, thread_id, visible_follower=level != "process")
+ await self._hold(turn_state, thread_id, role, text, parse_mode, level)
+
+ async def _flush_pending(
+ self, turn_state: CodexTurnState | None, thread_id: str, *, visible_follower: bool
+ ) -> None:
+ """Deliver the held message ahead of what follows it, in turn order.
+
+ Once anything follows the held visible message it is not the Turn's last
+ word (docs/plans/reply-and-turn-end.md). An answer Codex declared
+ (``agentMessage.phase``) is still a reply: a ``result`` that does not end the
+ Turn, whatever follows it. A message with no phase keeps the last-visible
+ rule: a visible item after it (another message, commentary, a tool call)
+ makes it narration; process-only narration (a reasoning summary) leaves it
+ where it is.
+ """
+ held = turn_state.pending_assistant if turn_state else None
+ if not held or not strip_silent_blocks(held[0]).strip():
+ return
+ if turn_state.pending_assistant_phase in _REPLY_PHASES:
+ role, output_key = _REPLY_ROLE, turn_state.pending_assistant_id
+ elif visible_follower:
+ role, output_key = "assistant", None
+ else:
+ return
+ turn_state.pending_assistant = None
+ turn_state.pending_assistant_phase = None
+ turn_state.pending_assistant_id = None
+ await self._hold(turn_state, thread_id, role, held[0], held[1], output_key=output_key)
+
+ async def _hold(
+ self,
+ turn_state: CodexTurnState,
+ thread_id: str,
+ role: str,
+ text: str,
+ parse_mode: str | None = "markdown",
+ level: str = "normal",
+ *,
+ output_key: str | None = None,
+ ) -> None:
turn_state.pending_narration.append(
CodexHeldMessage(
- role=role, text=text, parse_mode=parse_mode, thread_id=thread_id, level=level
+ role=role,
+ text=text,
+ parse_mode=parse_mode,
+ thread_id=thread_id,
+ level=level,
+ output_key=output_key,
)
)
await self._drain_narration(turn_state)
@@ -570,12 +629,24 @@ class CodexEventHandler:
parse_mode: str | None,
citations: CitationBundle | None,
level: str = "normal",
+ output_key: str | None = None,
) -> None:
await self._agent.controller.emit_agent_message(
request.context,
role,
text,
parse_mode=parse_mode or "markdown",
+ # A reply that does not end the Turn, identified by its item id so two
+ # replies with the same text stay two; narration keeps the call it had.
+ **(
+ {
+ "output": MessageOutput(
+ completes_turn=False, completes_run=False, idempotency_key=output_key
+ )
+ }
+ if role == _REPLY_ROLE
+ else {}
+ ),
# Forwarded only when non-default, like ``citations`` below.
**({"level": level} if level != "normal" else {}),
# Forwarded only when there is a sidecar, so a message without
@@ -605,7 +676,7 @@ class CodexEventHandler:
return
held.pop(0)
await self._emit_narration(
- request, entry.role, resolved, entry.parse_mode, citations, entry.level
+ request, entry.role, resolved, entry.parse_mode, citations, entry.level, entry.output_key
)
def _persist_turn_generated_images(self, params: dict[str, Any]) -> None:
diff --git a/modules/agents/codex/turn_state.py b/modules/agents/codex/turn_state.py
index 27892c883..ff79f4f33 100644
--- a/modules/agents/codex/turn_state.py
+++ b/modules/agents/codex/turn_state.py
@@ -23,6 +23,8 @@ class CodexHeldMessage:
parse_mode: Optional[str]
thread_id: str
level: str = "normal"
+ # A reply's stable identity (the ``agentMessage`` item id), None for narration.
+ output_key: Optional[str] = None
@dataclass
@@ -30,6 +32,11 @@ class CodexTurnState:
turn_id: str
request: AgentRequest
pending_assistant: Optional[Tuple[str, Optional[str]]] = None
+ # The ``agentMessage.phase`` Codex gave the held message, None when it named
+ # none (``docs/plans/reply-and-turn-end.md``).
+ pending_assistant_phase: Optional[str] = None
+ # Its ``agentMessage`` item id.
+ pending_assistant_id: Optional[str] = None
# Narration this turn has produced but not yet delivered, oldest first,
# because the source that will attribute part of it has not arrived. Held as
# one queue per turn so the order the turn narrated in is the order the user
@@ -174,6 +181,8 @@ class CodexTurnRegistry:
state.visible_to_user = False
state.pending_assistant = None
+ state.pending_assistant_phase = None
+ state.pending_assistant_id = None
# A hidden turn says nothing further, so everything it was still holding
# back goes with it rather than surfacing under its successor.
state.pending_narration.clear()
diff --git a/modules/agents/opencode/poll_loop.py b/modules/agents/opencode/poll_loop.py
index f1ed0de9e..7324c667c 100644
--- a/modules/agents/opencode/poll_loop.py
+++ b/modules/agents/opencode/poll_loop.py
@@ -16,7 +16,7 @@ from config.v2_config import (
from core.backend_failure import emit_backend_failure
from core.handlers.model_hub.retry import RECOVERY_EXHAUSTED_CODE
from core.message_context import build_context_session_key
-from core.message_output import terminal_output_for, terminal_turn_output
+from core.message_output import MessageOutput, terminal_output_for, terminal_turn_output
from core.processing_indicator import STOPPED_REACTION_EMOJI
from core.reply_enhancer import strip_silent_blocks
from modules.agents.base import AgentRequest
@@ -508,12 +508,15 @@ class OpenCodePollLoop:
"""Final text for the settlement message, keeping superseded replies.
A steer injected while the model is finishing a text reply moves the
- settlement to the reply that answers the steer. Earlier completed
- replies in the Turn are not the result, but they must still reach the
- user: the last visible reply is the result, earlier visible replies
- are emitted as intermediate assistant messages, and a silent reply
- never displaces a visible one. Emitted IDs are persisted so a
- restored poll does not deliver the same reply again.
+ settlement to the reply that answers the steer. Every completed reply
+ that is not a tool-calls step is a reply all the same
+ (docs/plans/reply-and-turn-end.md): the last visible one rides the
+ settlement, earlier visible ones are delivered first as replies that do
+ not end the Turn, and a silent reply never displaces a visible one.
+ A reply's id is recorded as emitted, and persisted so a restored poll does
+ not deliver it again, only once the dispatcher returned delivery evidence;
+ a reply whose every send failed is not retried (the dispatcher already
+ told the user), and the Turn still ends.
"""
settlement_id = _message_info(settlement_message).get("id")
@@ -552,12 +555,23 @@ class OpenCodePollLoop:
message_id,
settlement_id,
)
- await self._agent.controller.emit_agent_message(
+ delivered = await self._agent.controller.emit_agent_message(
context,
- "assistant",
+ "result",
text,
parse_mode="markdown",
+ # OpenCode's message id: two replies with the same text stay two
+ # deliveries, and a restored poll's replay of one stays one.
+ output=MessageOutput(
+ completes_turn=False, completes_run=False, idempotency_key=str(message_id)
+ ),
)
+ if not delivered:
+ logger.warning(
+ "OpenCode reply %s was not delivered; it stays unrecorded as emitted",
+ message_id,
+ )
+ continue
emitted_message_ids.add(message_id)
self._persist_emitted_assistant_messages(session_id, emitted_message_ids)
return final_text
diff --git a/modules/agents/vibey/agent.py b/modules/agents/vibey/agent.py
index c11b9943b..832249f42 100644
--- a/modules/agents/vibey/agent.py
+++ b/modules/agents/vibey/agent.py
@@ -1545,7 +1545,14 @@ class VibeyAgent(BaseAgent):
run.request.context,
message_type,
body,
- output=MessageOutput(completes_turn=False, completes_run=False, persisted_row_id=row_id),
+ output=MessageOutput(
+ completes_turn=False,
+ completes_run=False,
+ persisted_row_id=row_id,
+ # A reply is identified by its committed row: two replies with the
+ # same text stay two, and a replay of one stays one.
+ idempotency_key=row_id if message_type == "result" else None,
+ ),
citations=citations,
)
except Exception:
diff --git a/storage/alembic/versions/20261020_0071_session_turn_replies.py b/storage/alembic/versions/20261020_0071_session_turn_replies.py
new file mode 100644
index 000000000..2588883c8
--- /dev/null
+++ b/storage/alembic/versions/20261020_0071_session_turn_replies.py
@@ -0,0 +1,63 @@
+"""record each Turn's last delivered reply
+
+A Run whose Turn ends without a reply of its own settles with the Turn's last
+delivered reply (``docs/plans/reply-and-turn-end.md``, rule 5). The dispatcher
+writes that reply's Run copy into ``session_turn_replies`` when it delivers the
+reply and reads it back at the Turn end, so a Turn rerun after a restart, and the
+terminal snapshot that reconciliation reads, settle with what the user saw.
+
+One row per Turn, keyed by the Turn's id, written and read by primary key only. A
+table of its own, so it never takes part in the Turn's compare-and-set and no
+``session_turns`` read sees it. Additive: released versions never read it, and
+downgrade drops it.
+
+Revision ID: 20261020_0071
+Revises: 20261018_0070
+Create Date: 2026-10-20
+"""
+
+from __future__ import annotations
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "20261020_0071"
+down_revision = "20261018_0070"
+branch_labels = None
+depends_on = None
+MIGRATION_SAFETY = "additive"
+
+_TABLE = "session_turn_replies"
+
+
+def _tables(bind) -> set[str]:
+ return {
+ str(row[0])
+ for row in bind.exec_driver_sql("select name from sqlite_master where type = 'table'")
+ }
+
+
+def upgrade() -> None:
+ tables = _tables(op.get_bind())
+ if "session_turns" not in tables or _TABLE in tables:
+ return
+ op.create_table(
+ _TABLE,
+ sa.Column("turn_id", sa.String(), nullable=False),
+ sa.Column("reply_text", sa.Text(), nullable=False),
+ sa.Column("updated_at", sa.String(), nullable=False),
+ sa.PrimaryKeyConstraint("turn_id"),
+ sa.ForeignKeyConstraint(
+ ["turn_id"],
+ ["session_turns.id"],
+ ondelete="CASCADE",
+ deferrable=True,
+ initially="DEFERRED",
+ name="fk_session_turn_replies_turn",
+ ),
+ )
+
+
+def downgrade() -> None:
+ if _TABLE in _tables(op.get_bind()):
+ op.drop_table(_TABLE)
diff --git a/storage/message_deliveries.py b/storage/message_deliveries.py
index c98c39b59..7721460ca 100644
--- a/storage/message_deliveries.py
+++ b/storage/message_deliveries.py
@@ -8,7 +8,22 @@ from collections.abc import Mapping
from datetime import datetime, timezone
from typing import Any, Iterable, Literal
-from sqlalchemy import Select, and_, func, literal_column, or_, select, text, union, union_all, update
+from sqlalchemy import (
+ Select,
+ String,
+ Text,
+ and_,
+ func,
+ literal,
+ literal_column,
+ or_,
+ select,
+ text,
+ union,
+ union_all,
+ update,
+)
+from sqlalchemy.dialects.sqlite import insert as sqlite_insert
from sqlalchemy.engine import Connection
from core.agent_input import HARNESS_SOURCE_FIELDS
@@ -24,6 +39,7 @@ from storage.models import (
agent_sessions,
message_deliveries,
messages,
+ session_turn_replies,
session_turns,
show_session_events,
)
@@ -884,6 +900,46 @@ def cas_turn(
return get_turn(conn, turn_id) if result.rowcount == 1 else None
+def record_turn_reply(conn: Connection, turn_id: str, text: str) -> bool:
+ """Record the Run copy of a reply the dispatcher delivered for a live Turn.
+
+ The Turn's last delivered reply is what a Turn that ends without a reply of its
+ own settles with (``docs/plans/reply-and-turn-end.md``, rule 5). One upsert keyed
+ by the Turn's id, guarded by the Turn being live: it lives in a table of its own,
+ so it never bumps the Turn's ``version`` or takes part in ``cas_turn``, and a Turn
+ that is no longer live keeps what it ended with.
+ """
+
+ live_turn = (
+ select(
+ session_turns.c.id,
+ literal(text, type_=Text()),
+ literal(utc_now_iso(), type_=String()),
+ )
+ .where(session_turns.c.id == turn_id)
+ .where(session_turns.c.state.in_(TURN_OWNER_STATES))
+ )
+ statement = sqlite_insert(session_turn_replies).from_select(
+ ["turn_id", "reply_text", "updated_at"], live_turn
+ )
+ statement = statement.on_conflict_do_update(
+ index_elements=[session_turn_replies.c.turn_id],
+ set_={
+ "reply_text": statement.excluded.reply_text,
+ "updated_at": statement.excluded.updated_at,
+ },
+ )
+ return conn.execute(statement).rowcount == 1
+
+
+def turn_last_reply(conn: Connection, turn_id: str) -> str | None:
+ """The Run copy of the Turn's last delivered reply, None when it delivered none."""
+
+ return conn.execute(
+ select(session_turn_replies.c.reply_text).where(session_turn_replies.c.turn_id == turn_id)
+ ).scalar_one_or_none()
+
+
def cas_delivery(
conn: Connection,
delivery_id: str,
diff --git a/storage/migrations.py b/storage/migrations.py
index 2194c6cf5..24e281cf4 100644
--- a/storage/migrations.py
+++ b/storage/migrations.py
@@ -64,6 +64,7 @@ HEAD_TABLES = INITIAL_TABLES | {
"messages",
"message_deliveries",
"session_turns",
+ "session_turn_replies",
"agent_events",
"skill_usage_daily",
"show_session_events",
diff --git a/storage/models.py b/storage/models.py
index 9749a23f6..c74c2a532 100644
--- a/storage/models.py
+++ b/storage/models.py
@@ -943,6 +943,28 @@ session_turns = Table(
),
)
+
+# The Run copy of each Turn's last delivered reply, which a Turn that ends without a
+# reply of its own settles with (docs/plans/reply-and-turn-end.md, rule 5). One row per
+# Turn, written by the dispatcher by primary key when it delivers a reply and read at the
+# Turn's end; a table of its own, so it is outside the Turn's compare-and-set by
+# construction.
+session_turn_replies = Table(
+ "session_turn_replies",
+ metadata,
+ Column("turn_id", String, primary_key=True),
+ Column("reply_text", Text, nullable=False),
+ Column("updated_at", String, nullable=False),
+ ForeignKeyConstraint(
+ ["turn_id"],
+ ["session_turns.id"],
+ ondelete="CASCADE",
+ deferrable=True,
+ initially="DEFERRED",
+ name="fk_session_turn_replies_turn",
+ ),
+)
+
# One durable operational owner per submitted content-bearing input. Before
# positive native acceptance the complete immutable Message candidate lives only
# here. Acceptance moves one Delivery snapshot, or one ordered merged batch,
diff --git a/tests/scenarios/message_delivery/catalog.yaml b/tests/scenarios/message_delivery/catalog.yaml
index 229ad42a7..9643da906 100644
--- a/tests/scenarios/message_delivery/catalog.yaml
+++ b/tests/scenarios/message_delivery/catalog.yaml
@@ -376,7 +376,7 @@ scenarios:
layer: contract
test: tests/test_harness_failure_retry.py::test_harness_restart_notice_retries_through_web_and_controller
- id: MESSAGE-DELIVERY-321
- name: OpenCode steer keeps a superseded completed reply and a silent reply never displaces it
+ name: OpenCode steer keeps a superseded completed reply, delivered as a reply that does not end the Turn, and a silent reply never displaces it
status: covered
kind: regression
layer: contract
@@ -470,13 +470,13 @@ scenarios:
- 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
+ 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 content-free end 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_message_dispatcher_turn_end.py::ReplyAndTurnEndTests::test_an_end_without_a_reply_settles_with_the_last_delivered_reply
- 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
@@ -492,5 +492,26 @@ scenarios:
- ui/src/components/workbench/ChatPage.hydration.test.tsx
- ui/src/lib/chatMessageTypes.test.ts
- ui/src/pet/petState.test.ts
+ - id: MESSAGE-DELIVERY-335
+ name: Every backend types a complete reply a steer follows as a result that does not end the Turn (Codex by agentMessage.phase, commentary narration; OpenCode by a finish that is not tool-calls); a done Turn end with no reply of its own, a footer-only end included, posts nothing and settles its snapshot and every attached Run with the written copy of its last delivered reply, recorded by the dispatcher for the durable Turn (session_turn_replies) outside its compare-and-set, across a restart and repeated replies, or "" when it delivered none
+ status: covered
+ kind: regression
+ layer: contract
+ test:
+ - tests/test_message_dispatcher_turn_end.py::ReplyAndTurnEndTests::test_an_end_without_a_reply_settles_with_the_last_delivered_reply
+ - tests/test_message_dispatcher_turn_end.py::ReplyAndTurnEndTests::test_only_a_delivered_reply_is_what_the_turn_settles_with
+ - 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_only_a_reply_is_a_completed_turns_answer
+ - tests/test_message_dispatcher_turn_end.py::TurnEndFinalizesImOnceTests::test_a_footer_only_end_posts_nothing_and_still_ends_the_turn
+ - tests/test_turn_last_reply_store.py::test_a_reply_write_and_a_turn_transition_both_land
+ - tests/test_turn_last_reply_store.py::test_the_reply_write_and_read_are_primary_key_searches
+ - tests/test_turn_last_reply_store.py::test_a_released_database_upgrades_and_its_running_turn_ends_without_a_reply
+ - tests/test_codex_event_handler.py::CodexEventHandlerTests::test_an_answer_a_steer_follows_stays_a_reply_in_turn_order
+ - tests/test_codex_event_handler.py::CodexEventHandlerTests::test_a_silent_answer_keeps_the_declared_answer_as_the_turns_reply
+ - tests/test_opencode_steer_superseded_reply.py::test_steer_keeps_superseded_completed_reply
+ - tests/test_claude_agent_sessions.py::ClaudeAgentSessionTests::test_steered_assistant_and_result_settle_the_pending_turn
+ - 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_restart_rerun_ends_with_the_final_its_cut_run_committed
+ - tests/test_agent_silent_result.py::AgentSilentResultTests::test_a_footer_only_end_is_content_free
next_priority:
- - MESSAGE-DELIVERY-335
+ - MESSAGE-DELIVERY-336
diff --git a/tests/test_agent_context_seq_migration.py b/tests/test_agent_context_seq_migration.py
index 590e631f1..8f2979156 100644
--- a/tests/test_agent_context_seq_migration.py
+++ b/tests/test_agent_context_seq_migration.py
@@ -56,7 +56,7 @@ def test_context_seq_upgrade_and_downgrade_keep_released_rows(tmp_path):
migrations.run_migrations(path)
with sqlite3.connect(path) as conn:
- assert conn.execute("SELECT version_num FROM alembic_version").fetchone() == ("20261018_0070",)
+ assert conn.execute("SELECT version_num FROM alembic_version").fetchone() == ("20261020_0071",)
assert_released_rows_unchanged(conn)
assert _index_sql(conn, "ix_agent_events_turn_sequence_id") is not None
for table, (first, same_session, other_session) in _IDS.items():
diff --git a/tests/test_agent_silent_result.py b/tests/test_agent_silent_result.py
index cc38a246c..854de6158 100644
--- a/tests/test_agent_silent_result.py
+++ b/tests/test_agent_silent_result.py
@@ -81,20 +81,18 @@ class AgentSilentResultTests(unittest.IsolatedAsyncioTestCase):
# result path settles the dot + releases the stream.
self.assertEqual(controller.messages, [("result", "", "markdown")])
- async def test_footer_only_result_is_promoted_to_visible_body(self):
- # show_duration on + no visible result/suffix: the duration/token footnote
- # is promoted to the visible body (and NOT sent as a separate footer), so a
- # timing-only completion is still delivered/persisted instead of going
- # silent (Codex P2).
+ async def test_a_footer_only_end_is_content_free(self):
+ """MESSAGE-DELIVERY-335: show_duration on and nothing visible to say. A footer is
+ never a reply, so the end is content-free: an empty body, the footer only as
+ ``result_footer`` (the dispatcher settles the Turn with its last reply)."""
controller = _StubController(token_field="1.2k tok")
agent = _StubAgent(controller)
context = MessageContext(user_id="U1", channel_id="C1", platform="slack")
await agent.emit_result_message(context, "", subtype="success", duration_ms=5000)
- self.assertEqual(controller.messages, [("result", "✅ ⏱️ 5s · 🪙 1.2k tok", "markdown")])
- # Promoted to body, so no separate subtext footer is passed.
- self.assertEqual(controller.result_footers, [None])
+ self.assertEqual(controller.messages, [("result", "", "markdown")])
+ self.assertEqual(controller.result_footers, ["✅ ⏱️ 5s · 🪙 1.2k tok"])
async def test_an_uncited_result_does_not_require_the_citation_keyword(self):
"""The controller is substitutable, so an empty sidecar stays unsent.
diff --git a/tests/test_claude_agent_sessions.py b/tests/test_claude_agent_sessions.py
index 89e416ab0..7a905844a 100644
--- a/tests/test_claude_agent_sessions.py
+++ b/tests/test_claude_agent_sessions.py
@@ -1018,8 +1018,8 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
async def test_steered_assistant_and_result_settle_the_pending_turn(self):
"""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.
+ MESSAGE-DELIVERY-334 / MESSAGE-DELIVERY-335: 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"
@@ -1058,6 +1058,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
"subtype": "success",
"result": "primary final answer",
"duration_ms": 1,
+ "uuid": "res_primary",
},
)()
text_block = TextBlock("steered final answer")
@@ -1120,6 +1121,8 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
# 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)
+ # MESSAGE-DELIVERY-335: identified by its Result, so a same-text phase stays its own.
+ self.assertEqual(phase_output.idempotency_key, "res_primary")
self.assertNotIn(composite_key, agent._pending_requests)
async def test_presteer_result_stays_visible_without_agent_initiated_turn(self):
diff --git a/tests/test_codex_citations.py b/tests/test_codex_citations.py
index 9d95a42ae..94abb3439 100644
--- a/tests/test_codex_citations.py
+++ b/tests/test_codex_citations.py
@@ -747,9 +747,11 @@ class CodexCitationReadinessTests(IsolatedCodexHome, unittest.IsolatedAsyncioTes
await self.item(self.guide_search())
+ # Provider order: the message before the tool call goes out ahead of it
+ # (MESSAGE-DELIVERY-335), and the last message is the reply still held.
self.assertEqual(
self.delivered,
- [f"First. [developers.openai.com]({GUIDE_URL})", "[bash]", "Second."],
+ [f"First. [developers.openai.com]({GUIDE_URL})", "Second.", "[bash]"],
)
async def test_a_second_held_message_resolves_against_its_own_ref(self):
diff --git a/tests/test_codex_event_handler.py b/tests/test_codex_event_handler.py
index 3cbd6e459..c943df459 100644
--- a/tests/test_codex_event_handler.py
+++ b/tests/test_codex_event_handler.py
@@ -24,6 +24,8 @@ class _TurnState:
self.turn_id = turn_id
self.request = request
self.pending_assistant = None
+ self.pending_assistant_phase = None
+ self.pending_assistant_id = None
self.pending_narration = []
self.terminal_error = None
self.terminal_error_notified = False
@@ -588,6 +590,110 @@ class CodexEventHandlerTests(unittest.IsolatedAsyncioTestCase):
agent.emit_result_message.assert_awaited_once()
assert agent.emit_result_message.await_args.args[1] == "Final answer"
+ async def test_an_answer_a_steer_follows_stays_a_reply_in_turn_order(self):
+ """Scenario: MESSAGE-DELIVERY-335.
+
+ Codex declares each answer with ``agentMessage.phase``. An answer that more
+ output follows (here: the steered input's commentary, a tool call, and its
+ own answer) is still a reply: a ``result`` that does not end the Turn,
+ delivered before what follows it. ``commentary`` is narration, and the last
+ answer rides the Turn end.
+ """
+ agent = _StubAgent()
+ handler = CodexEventHandler(agent)
+ request = SimpleNamespace(base_session_id="session-1", context=object(), started_at=0)
+ agent._turn_registry.register_turn("turn-1", request)
+ agent._get_formatter = lambda _context: SimpleNamespace(
+ format_toolcall=lambda name, payload, **_kwargs: f"tool {payload['command']}"
+ )
+
+ for item in (
+ {"type": "agentMessage", "id": "msg_1", "text": "Looking at the cache.", "phase": "commentary"},
+ {"type": "agentMessage", "id": "msg_2", "text": "The cache is safe.", "phase": "final_answer"},
+ # The steered input: "and the lock?"
+ {"type": "agentMessage", "id": "msg_3", "text": "Checking the lock.", "phase": "commentary"},
+ {"type": "commandExecution", "command": "rg lock", "status": "completed", "exitCode": 0},
+ {"type": "agentMessage", "id": "msg_4", "text": "The cache is safe.", "phase": "partial_answer"},
+ {"type": "agentMessage", "id": "msg_5", "text": "The lock is fine too.", "phase": "final_answer"},
+ ):
+ await handler._on_item_completed({"turnId": "turn-1", "item": item}, request)
+ await handler._on_turn_completed({"turn": {"id": "turn-1", "status": "completed"}}, request)
+
+ emitted = [
+ (call.args[1], call.args[2], call.kwargs.get("output"))
+ for call in agent.controller.emit_agent_message.await_args_list
+ ]
+ assert [(role, text) for role, text, _ in emitted] == [
+ ("assistant", "Looking at the cache."),
+ ("result", "The cache is safe."),
+ ("assistant", "Checking the lock."),
+ ("toolcall", "tool rg lock"),
+ ("result", "The cache is safe."),
+ ]
+ for role, _, output in emitted:
+ if role == "result":
+ assert output is not None and not output.completes_turn and not output.settles_run
+ else:
+ assert output is None
+ # Each reply is identified by its item, so the same text twice stays two replies.
+ assert [output.idempotency_key for role, _, output in emitted if role == "result"] == ["msg_2", "msg_4"]
+ agent.emit_result_message.assert_awaited_once()
+ assert agent.emit_result_message.await_args.args[1] == "The lock is fine too."
+
+ async def test_a_message_without_a_phase_goes_out_before_what_follows_it(self):
+ """Scenario: MESSAGE-DELIVERY-335.
+
+ A message with no phase is the reply only while it is the last visible item:
+ commentary or a tool call after it makes it narration, delivered first, in
+ the provider's order; a Turn that then completes has no reply of its own.
+ """
+ agent = _StubAgent()
+ handler = CodexEventHandler(agent)
+ request = SimpleNamespace(base_session_id="session-1", context=object(), started_at=0)
+ agent._turn_registry.register_turn("turn-1", request)
+ agent._get_formatter = lambda _context: SimpleNamespace(
+ format_toolcall=lambda name, payload, **_kwargs: f"tool {payload['command']}"
+ )
+
+ for item in (
+ {"type": "agentMessage", "id": "msg_1", "text": "The cache is safe."},
+ {"type": "agentMessage", "id": "msg_2", "text": "Checking the lock.", "phase": "commentary"},
+ {"type": "agentMessage", "id": "msg_3", "text": "One writer holds it."},
+ {"type": "commandExecution", "command": "rg lock", "status": "completed", "exitCode": 0},
+ ):
+ await handler._on_item_completed({"turnId": "turn-1", "item": item}, request)
+ await handler._on_turn_completed({"turn": {"id": "turn-1", "status": "completed"}}, request)
+
+ assert [
+ (call.args[1], call.args[2], call.kwargs.get("output"))
+ for call in agent.controller.emit_agent_message.await_args_list
+ ] == [
+ ("assistant", "The cache is safe.", None),
+ ("assistant", "Checking the lock.", None),
+ ("assistant", "One writer holds it.", None),
+ ("toolcall", "tool rg lock", None),
+ ]
+ agent.emit_result_message.assert_awaited_once()
+ assert not agent.emit_result_message.await_args.args[1]
+
+ async def test_a_silent_answer_keeps_the_declared_answer_as_the_turns_reply(self):
+ """Scenario: MESSAGE-DELIVERY-335: a silent answer after a declared one shows nothing
+ and does not demote it; that answer rides the Turn end."""
+ agent = _StubAgent()
+ handler = CodexEventHandler(agent)
+ request = SimpleNamespace(base_session_id="session-1", context=object(), started_at=0)
+ agent._turn_registry.register_turn("turn-1", request)
+
+ for item in (
+ {"type": "agentMessage", "text": "Regression report", "phase": "final_answer"},
+ {"type": "agentMessage", "text": "<silent>Watch acknowledged</silent>", "phase": "final_answer"},
+ ):
+ await handler._on_item_completed({"turnId": "turn-1", "item": item}, request)
+ await handler._on_turn_completed({"turn": {"id": "turn-1", "status": "completed"}}, request)
+
+ agent.controller.emit_agent_message.assert_not_awaited()
+ assert agent.emit_result_message.await_args.args[1] == "Regression report"
+
async def test_reasoning_summary_stays_process_only(self):
agent = _StubAgent()
handler = CodexEventHandler(agent)
diff --git a/tests/test_message_dispatcher_scheduled.py b/tests/test_message_dispatcher_scheduled.py
index 9d52fd5ff..03c30e45f 100644
--- a/tests/test_message_dispatcher_scheduled.py
+++ b/tests/test_message_dispatcher_scheduled.py
@@ -2442,7 +2442,9 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):
),
)
- self.assertEqual(message_id, "suppressed:run-suppressed-cleanup")
+ # No local row was written here (this stub has no scope to write it under), so
+ # there is no receipt and no id: never a synthetic one (MESSAGE-DELIVERY-335).
+ self.assertIsNone(message_id)
self.assertEqual(controller.im_client.sent, [])
self.assertEqual(settled, ["activity-suppressed-cleanup"])
self.assertFalse(
@@ -2784,7 +2786,9 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):
with patch.object(message_dispatcher_module, "SQLiteBackgroundTaskStore", return_value=_Store()):
message_id = await dispatcher.emit_agent_message(context, "result", "private output")
- self.assertEqual(message_id, "suppressed:run-1")
+ # No local row was written here (this stub has no scope to write it under), so
+ # there is no receipt and no id: never a synthetic one (MESSAGE-DELIVERY-335).
+ self.assertIsNone(message_id)
self.assertEqual(
calls,
[
@@ -2818,7 +2822,9 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):
with patch.object(message_dispatcher_module, "SQLiteBackgroundTaskStore", return_value=_Store()):
message_id = await dispatcher.emit_agent_message(context, "result", "private agent output")
- self.assertEqual(message_id, "suppressed:run-agent")
+ # No local row was written here (this stub has no scope to write it under), so
+ # there is no receipt and no id: never a synthetic one (MESSAGE-DELIVERY-335).
+ self.assertIsNone(message_id)
self.assertEqual(
calls,
[
@@ -2861,7 +2867,9 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):
terminal_error="provider unavailable",
)
- self.assertEqual(message_id, "suppressed:run-agent")
+ # No local row was written here (this stub has no scope to write it under), so
+ # there is no receipt and no id: never a synthetic one (MESSAGE-DELIVERY-335).
+ self.assertIsNone(message_id)
self.assertEqual(len(calls), 1)
self.assertEqual(calls[0][0], "run-agent")
self.assertEqual(calls[0][1]["terminal_status"], "failed")
@@ -2893,7 +2901,9 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):
with patch.object(message_dispatcher_module, "SQLiteBackgroundTaskStore", return_value=_Store()):
message_id = await dispatcher.emit_agent_message(context, "result", "private agent output")
- self.assertEqual(message_id, "suppressed:run-1")
+ # No local row was written here (this stub has no scope to write it under), so
+ # there is no receipt and no id: never a synthetic one (MESSAGE-DELIVERY-335).
+ self.assertIsNone(message_id)
self.assertEqual(
calls,
[
@@ -2935,7 +2945,9 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):
with patch.object(message_dispatcher_module, "SQLiteBackgroundTaskStore", return_value=_Store()):
message_id = await dispatcher.emit_agent_message(context, "result", "private agent output")
- self.assertEqual(message_id, "suppressed:run-1")
+ # No local row was written here (this stub has no scope to write it under), so
+ # there is no receipt and no id: never a synthetic one (MESSAGE-DELIVERY-335).
+ self.assertIsNone(message_id)
self.assertEqual(
calls,
[
@@ -3125,10 +3137,12 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):
assistant_id = await dispatcher.emit_agent_message(context, "assistant", "working note")
result_id = await dispatcher.emit_agent_message(context, "result", "final result")
- self.assertEqual(system_id, "suppressed:run-agent")
- self.assertEqual(tool_id, "suppressed:run-agent")
- self.assertEqual(assistant_id, "suppressed:run-agent")
- self.assertEqual(result_id, "suppressed:run-agent")
+ # No local row was written here (this stub has no scope to write it under), so
+ # there is no receipt and no id: never a synthetic one (MESSAGE-DELIVERY-335).
+ self.assertIsNone(system_id)
+ self.assertIsNone(tool_id)
+ self.assertIsNone(assistant_id)
+ self.assertIsNone(result_id)
self.assertEqual(controller.im_client.sent, [])
self.assertEqual(
calls,
@@ -3163,7 +3177,9 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):
with patch.object(message_dispatcher_module, "SQLiteBackgroundTaskStore", return_value=_Store()):
message_id = await dispatcher.emit_agent_message(context, "notify", "auth recovery required")
- self.assertEqual(message_id, "suppressed:run-1")
+ # No local row was written here (this stub has no scope to write it under), so
+ # there is no receipt and no id: never a synthetic one (MESSAGE-DELIVERY-335).
+ self.assertIsNone(message_id)
self.assertEqual(controller.im_client.sent, [])
self.assertEqual(calls, [])
diff --git a/tests/test_message_dispatcher_turn_end.py b/tests/test_message_dispatcher_turn_end.py
index ccfd47bea..b57bb0d75 100644
--- a/tests/test_message_dispatcher_turn_end.py
+++ b/tests/test_message_dispatcher_turn_end.py
@@ -3,9 +3,13 @@
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).
+IM surfaces.
+
+Scenario: MESSAGE-DELIVERY-335. A Turn end with no reply of its own (a silent final,
+an empty end, a footer-only end) is content-free: it adds no row, and every attached
+Run and the Turn snapshot settle with the Run copy of the Turn's last delivered reply,
+which the dispatcher wrote onto the durable Turn when it delivered that reply, or ""
+when the Turn delivered none.
"""
from __future__ import annotations
@@ -23,10 +27,15 @@ from sqlalchemy import select
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+from core.citations import CitationSource, register_citations
+from core import message_dispatcher as dispatcher_module
from core.message_dispatcher import ConsolidatedMessageDispatcher
from core.message_output import MessageOutput, stop_output_for, terminal_turn_output
+from core.session_turns import SessionTurnManager
from modules.agents.base import AgentRequest, BaseAgent
from modules.im import MessageContext
+from modules.im.formatters.slack_formatter import SlackFormatter
+from storage import message_deliveries
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
@@ -50,19 +59,60 @@ class _Controller(_StubController):
def __init__(self, platform: str):
super().__init__(platform)
self.settings_manager = SimpleNamespace(sessions=None)
+ # The duration footer a base result end composes.
+ self.config.show_duration = True
+ self.im_client.formatter = SlackFormatter()
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] = []
+ # Runs a steer attached to the Turn (the Turn owner's durable attribution).
+ self.steered_runs: list[str] = []
+ # The durable Turn row's own reads and writes are the real Turn owner's.
+ turns = SessionTurnManager()
self.session_turns = SimpleNamespace(
on_terminal_result=lambda _context, **kwargs: self.snapshots.append(kwargs),
on_terminal_delivery_complete=self.committed_turns.append,
+ accepted_agent_run_ids_for_turn=lambda _turn_id: list(self.steered_runs),
+ record_turn_reply=turns.record_turn_reply,
+ turn_last_reply=turns.turn_last_reply,
)
async def emit_agent_message(self, *args, **kwargs):
return await self.dispatcher.emit_agent_message(*args, **kwargs)
+def _live_turn(conn, scope_id: str) -> None:
+ """The durable Turn ``trn_1``, accepted and running, as the Turn owner leaves it."""
+ delivery = message_deliveries.insert_delivery(
+ conn,
+ delivery_id="dlv_trn_1",
+ session_id=SESSION,
+ priority="p3",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=scope_id, session_id=SESSION, platform="avibe", author="user", source="user",
+ message_type="user", text="is the cache safe?",
+ ),
+ dispatch_text="is the cache safe?",
+ now=NOW,
+ )
+ claimed = message_deliveries.claim_start_batch(
+ conn, turn_id="trn_1", session_id=SESSION, backend="claude", deliveries=[delivery],
+ dispatch_text="is the cache safe?",
+ )
+ assert message_deliveries.bind_native_start(
+ conn, "trn_1", expected_version=int(claimed["turn"]["version"]), runtime_key="runtime",
+ runtime_turn_id="trn_1", native_turn_id="trn_1",
+ )
+ assert message_deliveries.materialize_start_acceptance(conn, turn_id="trn_1", evidence={"kind": "test"})
+
+
+@contextmanager
+def _no_logs():
+ yield
+
+
class _Agent(BaseAgent):
name = "stub"
@@ -119,6 +169,7 @@ class ReplyAndTurnEndTests(unittest.IsolatedAsyncioTestCase):
metadata_json="{}", created_at=NOW, updated_at=NOW, last_active_at=NOW,
)
)
+ _live_turn(conn, scope_id)
finally:
engine.dispose()
self.runs = TaskExecutionStore()
@@ -158,6 +209,19 @@ class ReplyAndTurnEndTests(unittest.IsolatedAsyncioTestCase):
finally:
engine.dispose()
+ @staticmethod
+ def agent_row_ids() -> list:
+ engine = create_sqlite_engine()
+ try:
+ with engine.connect() as conn:
+ return list(
+ conn.execute(
+ select(messages.c.id).where(messages.c.session_id == SESSION, messages.c.author == "agent")
+ )
+ )
+ 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
@@ -170,7 +234,7 @@ class ReplyAndTurnEndTests(unittest.IsolatedAsyncioTestCase):
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.
+ """Scenario: MESSAGE-DELIVERY-334 / MESSAGE-DELIVERY-335.
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
@@ -193,36 +257,252 @@ class ReplyAndTurnEndTests(unittest.IsolatedAsyncioTestCase):
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 ""
+ # Either way the Turn settles with its last reply: its own final, or the
+ # one it delivered before a content-free end (MESSAGE-DELIVERY-335).
[snapshot] = controller.snapshots
- self.assertEqual((snapshot["is_error"], snapshot["terminal_evidence"]["result_text"]), (False, own_text))
+ self.assertEqual((snapshot["is_error"], snapshot["terminal_evidence"]["result_text"]), (False, SECOND))
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])
+ self.assertEqual((run["status"], run["result_text"]), ("succeeded", SECOND))
+ # Each delivered reply is on the Run's output log; a content-free end
+ # adds its settlement under the terminal identity, as every final does.
+ outputs = [entry["text"] for entry in run["result_payload"]["outputs"]]
+ self.assertEqual(outputs[:2], [FIRST, SECOND])
+ self.assertEqual(outputs[2:], [] if ends_with == "its final reply" else [SECOND])
+
+ async def test_an_end_without_a_reply_settles_with_the_last_delivered_reply(self):
+ """Scenario: MESSAGE-DELIVERY-335 (and MESSAGE-DELIVERY-334: a content-free end
+ after a reply promotes nothing).
+
+ Every content-free end of a done Turn (a silent final, an empty end with the
+ duration footer shown or hidden, a backend's bare end) adds no row and pushes
+ nothing, and the snapshot and every Run attached to the Turn, one a steer
+ attached after the reply included, settle with the last reply it delivered:
+ the copy the dispatcher wrote (quick replies and file links stripped,
+ citations written out), A after A, B, A, read from the durable Turn by the
+ end in a new process.
+ """
+ source = (
+ "Two writers raced.\ue200cite\ue202turn0view0\ue201 See [the report](file:///tmp/report.md)."
+ "\n\n---\n[👍 Thanks] | [🔁 Rerun]"
+ )
+ written = "Two writers raced. [example.com](https://example.com/race) See the report."
+ registered, citations = register_citations(
+ source,
+ {"turn0view0": CitationSource(ref_id="turn0view0", title="Race report", url="https://example.com/race")},
+ unresolved_label="(source unavailable)",
+ )
- 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>")
+ async def silent_final(agent, controller, context):
+ await agent.emit_result_message(context, "<silent>noted</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 [])
+ async def empty_end(show_duration):
+ async def end(agent, controller, context):
+ controller.config.show_duration = show_duration
+ await agent.emit_result_message(context, "", duration_ms=5000)
+
+ return end
+
+ async def bare_end(agent, controller, context):
+ await controller.emit_agent_message(context, "result", "", output=terminal_turn_output())
+
+ ends = {
+ "a silent final": silent_final,
+ "an empty end, duration shown": await empty_end(True),
+ "an empty end, duration hidden": await empty_end(False),
+ "a bare end": bare_end,
+ }
+ for platform in ("avibe", "slack"):
+ for name, end in ends.items():
+ with self.subTest(platform=platform, end=name), self.state():
+ context = self.context(platform)
+ process = _Controller(platform)
+ process.config.reply_enhancements = True
+ await process.emit_agent_message(context, "result", registered, output=REPLY, citations=citations)
+ steered = self.running_run("task-steered")
+ await process.emit_agent_message(context, "result", SECOND, output=REPLY)
+ await process.emit_agent_message(context, "result", registered, output=REPLY, citations=citations)
+
+ # The Turn ends in a new process: nothing in memory carries the reply.
+ restarted = _Controller(platform)
+ restarted.steered_runs = [steered]
+ await end(_Agent(restarted), restarted, context)
+
+ self.assertEqual([row[0] for row in self.agent_rows()], ["result"] * 3)
+ self.assertEqual(len(self.pushed_texts()), 3 if platform == "avibe" else 0)
+ self.assertNotIn("message.updated", [event for event, _ in self.published])
+ [snapshot] = restarted.snapshots
+ self.assertEqual(snapshot["terminal_evidence"]["result_text"], written)
+ self.assertEqual(len(restarted.committed_turns), 1)
+ for run_id in (self.run_id, steered):
+ run = self.harness_run(run_id)
+ self.assertEqual((run["status"], run["result_text"]), ("succeeded", written))
+
+ async def test_only_a_delivered_reply_is_what_the_turn_settles_with(self):
+ """Scenario: MESSAGE-DELIVERY-335: a reply whose every send failed never reached the user,
+ so a content-free end settles with the one before it; a Turn that delivered no reply
+ settles with nothing (and so sends no callback), and a failure or a stop reports its
+ outcome, never an earlier reply (``test_only_a_reply_is_a_completed_turns_answer``)."""
+ for delivered in ((FIRST,), ()):
+ with self.subTest(delivered=delivered), self.state():
+ controller = _Controller("slack")
+ context = self.context("slack")
+ send = controller.im_client.send_message
+
+ async def lossy_send(target, text, *args, **kwargs):
+ if SECOND in text:
+ raise RuntimeError("Slack is down")
+ return await send(target, text, *args, **kwargs)
+
+ controller.im_client.send_message = lossy_send
+ for reply in delivered:
+ await controller.emit_agent_message(context, "result", reply, output=REPLY)
+ await controller.emit_agent_message(context, "result", SECOND, output=REPLY)
+ await _Agent(controller).emit_result_message(context, "", duration_ms=5000)
+
+ expected = delivered[-1] if delivered else ""
[snapshot] = controller.snapshots
- self.assertEqual(snapshot["terminal_evidence"]["result_text"], "")
- self.assertEqual(len(controller.committed_turns), 1)
+ self.assertEqual(snapshot["terminal_evidence"]["result_text"], expected)
run = self.harness_run()
- self.assertEqual(run["status"], "succeeded")
- self.assertEqual([entry["text"] for entry in run["result_payload"]["outputs"]], [FIRST])
+ self.assertEqual((run["status"], run["result_text"] or ""), ("succeeded", expected))
+
+ async def test_a_turns_last_reply_is_recorded_with_its_receipt(self):
+ """Scenario: MESSAGE-DELIVERY-335.
+
+ A reply's record as the Turn's last reply commits in the transaction that writes
+ its receipt: a process that dies right after that commit still leaves it for the
+ Turn's end; a record that cannot be written fails the receipt and leaves nothing
+ behind; a replay of an earlier reply finds its receipt and records nothing, so it
+ never displaces a newer one. Each reply is its own delivery by its identity, the
+ same text twice included.
+ """
+
+ def reply(key: str) -> MessageOutput:
+ return MessageOutput(completes_turn=False, completes_run=False, idempotency_key=key)
+
+ for case in ("the process dies after the receipt", "the record fails", "an older reply replays"):
+ with self.subTest(case), self.state():
+ context = self.context()
+ controller = _Controller("avibe")
+ await controller.emit_agent_message(context, "result", FIRST, output=reply("out_1"))
+ if case == "the process dies after the receipt":
+ real_persist = dispatcher_module.persist_agent_message
+
+ def persist_then_die(*args, **kwargs):
+ real_persist(*args, **kwargs)
+ raise RuntimeError("the process died after the receipt committed")
+
+ with mock.patch.object(dispatcher_module, "persist_agent_message", persist_then_die):
+ with self.assertRaises(RuntimeError):
+ await controller.emit_agent_message(context, "result", SECOND, output=reply("out_2"))
+ expected, rows = SECOND, [FIRST, SECOND]
+ elif case == "the record fails":
+ with mock.patch(
+ "storage.message_deliveries.record_turn_reply",
+ side_effect=RuntimeError("database is locked"),
+ ):
+ await controller.emit_agent_message(context, "result", SECOND, output=reply("out_2"))
+ expected, rows = FIRST, [FIRST]
+ else:
+ await controller.emit_agent_message(context, "result", SECOND, output=reply("out_2"))
+ await controller.emit_agent_message(context, "result", SECOND, output=reply("out_3"))
+ await controller.emit_agent_message(context, "result", FIRST, output=reply("out_1"))
+ expected, rows = SECOND, [FIRST, SECOND, SECOND]
+
+ # The Turn ends in a new process.
+ restarted = _Controller("avibe")
+ await restarted.emit_agent_message(context, "result", "", output=terminal_turn_output())
+
+ self.assertEqual([text for _, text in self.agent_rows()], rows)
+ [snapshot] = restarted.snapshots
+ self.assertEqual(snapshot["terminal_evidence"]["result_text"], expected)
+ run = self.harness_run()
+ self.assertEqual((run["status"], run["result_text"]), ("succeeded", expected))
+ if case == "an older reply replays":
+ # Each delivered reply is on the Run's log by its identity: the same
+ # text twice is two entries, and the replay adds none.
+ self.assertEqual(
+ [entry["id"] for entry in run["result_payload"]["outputs"]],
+ ["out_1", "out_2", "out_3", "terminal"],
+ )
+
+ async def test_a_replys_derived_writes_wait_for_its_delivery(self):
+ """Scenario: MESSAGE-DELIVERY-335: every write derived from a reply that does not end
+ its Turn waits for its delivery evidence. An IM reply whose every send failed leaves
+ no Run output entry, no record as the Turn's last reply, and no delivery evidence
+ for its backend to mark; the same reply delivered writes each exactly once."""
+ with self.state():
+ controller = _Controller("slack")
+ context = self.context("slack")
+ send = controller.im_client.send_message
+
+ async def down(*_args, **_kwargs):
+ raise RuntimeError("Slack is down")
+
+ controller.im_client.send_message = down
+ evidence = await controller.emit_agent_message(context, "result", FIRST, output=REPLY)
+ self.assertIsNone(evidence)
+ self.assertEqual((self.harness_run()["result_payload"] or {}).get("outputs") or [], [])
+ self.assertIsNone(controller.session_turns.turn_last_reply("trn_1"))
+
+ controller.im_client.send_message = send
+ evidence = await controller.emit_agent_message(context, "result", FIRST, output=REPLY)
+ self.assertIsNotNone(evidence)
+ self.assertEqual([entry["text"] for entry in self.harness_run()["result_payload"]["outputs"]], [FIRST])
+ self.assertEqual(controller.session_turns.turn_last_reply("trn_1"), FIRST)
+ self.assertEqual(self.agent_rows(), [("result", FIRST)])
+
+ async def test_a_background_emit_returns_its_receipt_or_nothing(self):
+ """Scenario: MESSAGE-DELIVERY-335: an emit's return value is its delivery evidence. A
+ background (``suppress_delivery``) output's receipt is its local row: its id when the
+ row was written, and nothing, never a synthetic id, when the write failed, so a caller
+ that waits for evidence (OpenCode's emitted mark, an Activity's delivery check) never
+ takes a failed write for a delivery."""
+ for persisted in (True, False):
+ with self.subTest(persisted=persisted), self.state():
+ controller = _Controller("avibe")
+ context = self.context()
+ context.platform_specific["suppress_delivery"] = True
+ if persisted:
+ evidence = await controller.emit_agent_message(context, "result", FIRST, output=REPLY)
+ [row_id] = [row.id for row in self.agent_row_ids()]
+ self.assertEqual(evidence, row_id)
+ self.assertEqual(controller.session_turns.turn_last_reply("trn_1"), FIRST)
+ else:
+ with mock.patch.object(dispatcher_module, "persist_agent_message", return_value=None):
+ evidence = await controller.emit_agent_message(context, "result", FIRST, output=REPLY)
+ self.assertIsNone(evidence)
+ self.assertIsNone(controller.session_turns.turn_last_reply("trn_1"))
+ self.assertEqual((self.harness_run()["result_payload"] or {}).get("outputs") or [], [])
+
+ async def test_a_failed_last_reply_read_is_retried_then_read_as_none(self):
+ """Scenario: MESSAGE-DELIVERY-335: rule 5 is best effort. A read of the Turn's last
+ reply that fails is retried briefly; one that keeps failing is logged and read as
+ no reply, so the end settles with "" instead of holding or failing the Turn's end."""
+ for failures, expected in ((2, FIRST), (3, "")):
+ with self.subTest(failures=failures), self.state():
+ context = self.context()
+ await _Controller("avibe").emit_agent_message(context, "result", FIRST, output=REPLY)
+ restarted = _Controller("avibe")
+ read = restarted.session_turns.turn_last_reply
+ attempts = []
+
+ def flaky_read(turn_id, read=read, attempts=attempts, failures=failures):
+ attempts.append(turn_id)
+ if len(attempts) <= failures:
+ raise RuntimeError("database is locked")
+ return read(turn_id)
+
+ restarted.session_turns.turn_last_reply = flaky_read
+ with self.assertLogs("core.message_dispatcher", level="WARNING") if failures == 3 else _no_logs():
+ await restarted.emit_agent_message(context, "result", "", output=terminal_turn_output())
+
+ self.assertEqual(len(attempts), 3)
+ [snapshot] = restarted.snapshots
+ self.assertEqual(snapshot["terminal_evidence"]["result_text"], expected)
+ self.assertEqual(len(restarted.committed_turns), 1)
+ run = self.harness_run()
+ self.assertEqual((run["status"], run["result_text"] or ""), ("succeeded", expected))
async def test_a_reply_or_a_failure_keeps_its_type_attached_or_detached(self):
"""Scenario: MESSAGE-DELIVERY-334.
@@ -249,7 +529,7 @@ class ReplyAndTurnEndTests(unittest.IsolatedAsyncioTestCase):
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.
+ """Scenario: MESSAGE-DELIVERY-334 / MESSAGE-DELIVERY-335.
Narration stays narration, and a Turn that fails or is stopped ends once
with its outcome, never an earlier reply as its answer.
@@ -333,6 +613,41 @@ class TurnEndFinalizesImOnceTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(len(client.sent), 2)
self.assertEqual(controller.processing_indicator.finished, 1)
+ async def test_a_footer_only_end_posts_nothing_and_still_ends_the_turn(self):
+ """Scenario: MESSAGE-DELIVERY-335.
+
+ With the duration shown and nothing to say, the end is content-free: no
+ message carries the footer alone, in concise or verbose mode. The Turn still
+ visibly ends: the concise status bubble collapses to its done line (with the
+ run time), the running indicator finishes, and the request's reaction clears.
+ """
+ for style in ("concise", "verbose"):
+ with self.subTest(style=style), mock.patch("core.message_dispatcher.persist_agent_message"):
+ controller = _BubbleController(platform="slack", progress_style=style)
+ controller.processing_indicator = _Indicator()
+ controller.settings_manager = SimpleNamespace(sessions=None)
+ controller.config.show_duration = True
+ controller.im_client.formatter = SlackFormatter()
+ dispatcher = _bubble_dispatcher(controller)
+ controller.emit_agent_message = dispatcher.emit_agent_message
+ context = _bubble_context()
+ context.platform_specific = {"turn_token": "trn_1"}
+ client = controller.im_client
+ agent = _Agent(controller)
+ agent._remove_ack_reaction = mock.AsyncMock()
+ request = SimpleNamespace(output=None, context=context)
+
+ await dispatcher.emit_agent_message(context, "toolcall", "🔧 `Bash` `{}`")
+ sent_before = list(client.sent)
+ await agent.emit_result_message(context, "", duration_ms=5000, request=request)
+
+ self.assertEqual(client.sent, sent_before)
+ if style == "concise":
+ self.assertEqual(client.edits[-1][:2], ("msg-1", ""))
+ self.assertTrue(client.edits[-1][2].startswith("✅ done"))
+ self.assertEqual(controller.processing_indicator.finished, 1)
+ agent._remove_ack_reaction.assert_awaited_once_with(request)
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_multi_platform_runtime.py b/tests/test_multi_platform_runtime.py
index f0df853b5..d995600df 100644
--- a/tests/test_multi_platform_runtime.py
+++ b/tests/test_multi_platform_runtime.py
@@ -1836,6 +1836,26 @@ def test_opencode_poll_settles_error_when_trailing_user_is_last():
]
+def _ends_the_turn(message_type, output):
+ """A ``result`` is a reply; only one with Turn-end authority settles the Turn (a result
+ without an explicit output keeps the terminal default) (MESSAGE-DELIVERY-335)."""
+
+ return message_type == "result" and (output is None or output.completes_turn)
+
+
+def _assert_no_turn_end_while_the_steer_is_live(emitted):
+ """Nothing ends the Turn while an accepted steer is live (the poll returns the end to its
+ caller), and the reply before the steer is a reply that does not end the Turn, delivered
+ only once the steer's answer settled the poll (MESSAGE-DELIVERY-335)."""
+
+ for args, kwargs, polls_at_emit in emitted:
+ output = kwargs.get("output")
+ assert output is None or not output.completes_turn, (args, kwargs)
+ if args[1] == "result":
+ assert output is not None and not output.settles_run, (args, kwargs)
+ assert polls_at_emit == 3, (args, polls_at_emit)
+
+
def test_opencode_poll_keeps_accepted_steer_pending_while_native_busy(monkeypatch):
"""A trailing user while OpenCode is busy is a live steer, not a hang."""
@@ -1858,7 +1878,7 @@ def test_opencode_poll_keeps_accepted_steer_pending_while_native_busy(monkeypatc
return f"translated:{key}"
async def emit_agent_message(self, *args, **kwargs):
- emitted.append((args, kwargs))
+ emitted.append((args, kwargs, polls["n"]))
class _Agent:
opencode_config = type("OpenCodeConfig", (), {"error_retry_limit": 0})()
@@ -1932,7 +1952,7 @@ def test_opencode_poll_keeps_accepted_steer_pending_while_native_busy(monkeypatc
assert (final_text, should_emit) == ("steered", True)
assert polls["n"] == 3
- assert not any(item[0][1] == "result" for item in emitted)
+ _assert_no_turn_end_while_the_steer_is_live(emitted)
def test_opencode_poll_uses_snapshot_live_flag_instead_of_rereading_status(monkeypatch):
@@ -1958,7 +1978,7 @@ def test_opencode_poll_uses_snapshot_live_flag_instead_of_rereading_status(monke
return f"translated:{key}"
async def emit_agent_message(self, *args, **kwargs):
- emitted.append((args, kwargs))
+ emitted.append((args, kwargs, polls["n"]))
class _Agent:
opencode_config = type("OpenCodeConfig", (), {"error_retry_limit": 0})()
@@ -2036,7 +2056,7 @@ def test_opencode_poll_uses_snapshot_live_flag_instead_of_rereading_status(monke
assert (final_text, should_emit) == ("steered", True)
assert polls["n"] == 3
assert status_reads["n"] == 0
- assert not any(item[0][1] == "result" for item in emitted)
+ _assert_no_turn_end_while_the_steer_is_live(emitted)
def test_opencode_poll_keeps_retry_pending_on_empty_inflight_assistant(monkeypatch):
@@ -2074,7 +2094,7 @@ def test_opencode_poll_keeps_retry_pending_on_empty_inflight_assistant(monkeypat
output=None,
terminal_error=None,
):
- emitted.append((message_type, text, is_error, level, terminal_error))
+ emitted.append((message_type, text, is_error, level, terminal_error, output))
class _Agent:
opencode_config = type("OpenCodeConfig", (), {"error_retry_limit": 0})()
@@ -2141,7 +2161,7 @@ def test_opencode_poll_keeps_retry_pending_on_empty_inflight_assistant(monkeypat
assert (final_text, should_emit) == ("recovered", True)
assert polls["n"] == 3
- assert not any(item[0] == "result" for item in emitted)
+ assert not any(_ends_the_turn(item[0], item[5]) for item in emitted)
def test_opencode_poll_keeps_continue_pending_through_idle_visibility_gap(monkeypatch):
@@ -2182,7 +2202,7 @@ def test_opencode_poll_keeps_continue_pending_through_idle_visibility_gap(monkey
output=None,
terminal_error=None,
):
- emitted.append((message_type, text, is_error, level, terminal_error))
+ emitted.append((message_type, text, is_error, level, terminal_error, output))
class _Agent:
opencode_config = type("OpenCodeConfig", (), {"error_retry_limit": 1})()
@@ -2280,7 +2300,7 @@ def test_opencode_poll_keeps_continue_pending_through_idle_visibility_gap(monkey
assert (final_text, should_emit) == ("recovered", True)
assert polls["n"] >= 3
- assert not any(item[0] == "result" for item in emitted)
+ assert not any(_ends_the_turn(item[0], item[5]) for item in emitted)
def test_opencode_poll_keeps_retry_pending_before_continue_user_appears(monkeypatch):
@@ -2395,7 +2415,7 @@ def test_opencode_poll_keeps_retry_pending_before_continue_user_appears(monkeypa
assert (final_text, should_emit) == ("recovered", True)
assert polls["n"] >= 3
- assert not any(item[0][1] == "result" for item in emitted)
+ assert not any(_ends_the_turn(item[0][1], item[1].get("output")) for item in emitted)
def test_opencode_poll_does_not_settle_error_while_followup_has_parts():
@@ -2470,7 +2490,7 @@ def test_opencode_poll_does_not_settle_error_while_followup_has_parts():
assert (final_text, should_emit) == ("recovered", True)
assert polls["n"] == 2
- assert not any(item[0][1] == "result" for item in emitted)
+ assert not any(_ends_the_turn(item[0][1], item[1].get("output")) for item in emitted)
def test_opencode_poll_keeps_explicit_empty_completion_on_success_path():
diff --git a/tests/test_opencode_steer_superseded_reply.py b/tests/test_opencode_steer_superseded_reply.py
index 05fbaa947..cdd1424db 100644
--- a/tests/test_opencode_steer_superseded_reply.py
+++ b/tests/test_opencode_steer_superseded_reply.py
@@ -136,25 +136,43 @@ def _assistant_emits(agent):
]
+def _reply_emits(agent):
+ """Replies delivered before the settlement: ``result`` rows that do not end the Turn,
+ each identified by its OpenCode message id (MESSAGE-DELIVERY-335)."""
+
+ replies = []
+ for call in agent.controller.emit_agent_message.await_args_list:
+ if call.args[1] != "result":
+ continue
+ output = call.kwargs.get("output")
+ assert output is not None and not output.completes_turn and not output.settles_run
+ assert output.idempotency_key == "reply-a"
+ replies.append(call.args[2])
+ return replies
+
+
@pytest.mark.parametrize("path", ["live", "restored"])
@pytest.mark.parametrize(
("messages", "expected_result", "expected_emits"),
[
# A silent answer to the steer must not replace the visible reply.
(_turn(REPORT, SILENT), REPORT, []),
- # A visible answer to the steer is the result; A still reaches the user.
+ # A visible answer to the steer rides the Turn end; A is a reply delivered before it.
(_turn(REPORT, "Callbacks noted."), "Callbacks noted.", [REPORT]),
+ # The same text twice is two replies.
+ (_turn(REPORT, REPORT), REPORT, [REPORT]),
# A silent reply superseded by a visible one is not re-sent.
(_turn(SILENT, "Callbacks noted."), "Callbacks noted.", []),
# When every reply is silent, the Turn stays silent.
(_turn(SILENT, SILENT), SILENT, []),
],
- ids=["silent-steer-reply", "visible-steer-reply", "silent-superseded", "all-silent"],
+ ids=["silent-steer-reply", "visible-steer-reply", "same-text-reply", "silent-superseded", "all-silent"],
)
async def test_steer_keeps_superseded_completed_reply(
monkeypatch, path, messages, expected_result, expected_emits
):
- """MESSAGE-DELIVERY-321."""
+ """MESSAGE-DELIVERY-321 / MESSAGE-DELIVERY-335: a completed reply a steer follows is a
+ reply, a ``result`` that does not end the Turn, never narration."""
monkeypatch.setattr("modules.agents.opencode.poll_loop._POLL_INTERVAL_SECONDS", 0)
results: list[str] = []
@@ -166,7 +184,8 @@ async def test_steer_keeps_superseded_completed_reply(
final_text = await _restored_poll(messages, agent, results)
assert final_text == expected_result
- assert _assistant_emits(agent) == expected_emits
+ assert _reply_emits(agent) == expected_emits
+ assert _assistant_emits(agent) == []
async def test_tool_call_step_text_is_not_emitted_twice(monkeypatch):
@@ -197,4 +216,21 @@ async def test_restored_poll_does_not_resend_a_persisted_superseded_reply(monkey
)
assert final_text == "Callbacks noted."
- assert _assistant_emits(restored) == []
+ assert _reply_emits(restored) == [] and _assistant_emits(restored) == []
+
+
+async def test_an_undelivered_reply_is_not_recorded_as_emitted(monkeypatch):
+ """MESSAGE-DELIVERY-335: a reply the dispatcher could not deliver (no message id) is not
+ recorded as emitted, so a restored poll still owes it; the Turn still settles on the
+ steer's answer (a reply whose every send failed is not retried)."""
+
+ monkeypatch.setattr("modules.agents.opencode.poll_loop._POLL_INTERVAL_SECONDS", 0)
+ persisted: dict = {}
+ agent = _agent([], persisted)
+ agent.controller.emit_agent_message = AsyncMock(return_value=None)
+
+ final_text = await _live_poll(_turn(REPORT, "Callbacks noted."), agent)
+
+ assert final_text == "Callbacks noted."
+ assert [call.args[2] for call in agent.controller.emit_agent_message.await_args_list] == [REPORT]
+ assert "reply-a" not in persisted.get("emitted_assistant_messages", [])
diff --git a/tests/test_skill_observability_migration.py b/tests/test_skill_observability_migration.py
index 977281443..a050b5ab4 100644
--- a/tests/test_skill_observability_migration.py
+++ b/tests/test_skill_observability_migration.py
@@ -35,7 +35,7 @@ def test_skill_schema_upgrade_downgrade_preserves_existing_events(tmp_path):
migrations.run_migrations(path)
with sqlite3.connect(path) as conn:
assert conn.execute(f"SELECT {columns} FROM agent_events ORDER BY id").fetchall() == original
- assert conn.execute("SELECT version_num FROM alembic_version").fetchone() == ("20261018_0070",)
+ assert conn.execute("SELECT version_num FROM alembic_version").fetchone() == ("20261020_0071",)
assert conn.execute("SELECT count(*) FROM skill_usage_daily").fetchone() == (0,)
assert {row[2] for row in conn.execute("PRAGMA foreign_key_list(skill_usage_daily)")} == {
"scopes",
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index db4441193..fcdd46c8a 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -38,7 +38,7 @@ from vibe.message_types import build_partial_index_predicate
pytestmark = pytest.mark.no_sqlite_template
-HEAD_REVISION = "20261018_0070"
+HEAD_REVISION = "20261020_0071"
PREVIOUS_HEAD_REVISION = "20261016_0068"
_SCOPE_ID_DRIFT_TABLES = ("messages", "agent_events", "media_objects")
# ``storage.models`` builds a bare ``MetaData()``, so its foreign keys are unnamed and
diff --git a/tests/test_turn_last_reply_store.py b/tests/test_turn_last_reply_store.py
new file mode 100644
index 000000000..a39395a57
--- /dev/null
+++ b/tests/test_turn_last_reply_store.py
@@ -0,0 +1,250 @@
+"""The Turn's last delivered reply (docs/plans/reply-and-turn-end.md, rule 5).
+
+Scenario: MESSAGE-DELIVERY-335. ``session_turn_replies`` holds, per Turn, the Run copy of
+the last reply the dispatcher delivered; the dispatcher writes it on delivery and reads it
+at a content-free Turn end. It is a table of its own: the write is one upsert keyed by the
+Turn's id, never bumps the Turn's ``version``, and a transition that races it still lands.
+"""
+
+from __future__ import annotations
+
+import json
+import sqlite3
+
+import pytest
+from alembic import command
+from sqlalchemy import event, select
+
+from config import paths
+from core.message_output import terminal_turn_output
+from storage import message_deliveries, migrations
+from storage.db import create_sqlite_engine, dispose_cached_sqlite_engines
+from storage.importer import ensure_sqlite_state
+from storage.models import session_turn_replies
+from storage.settings_service import upsert_scope
+
+NOW = "2026-10-20T00:00:00.000000Z"
+SESSION = "ses_last_reply"
+TURN = "trn_last_reply"
+REVISION = "20261020_0071"
+PREVIOUS_REVISION = "20261018_0070"
+
+
+def _seed(conn) -> dict:
+ """A Session and one Turn claimed through the real Delivery path, still ``starting``."""
+ scope_id = upsert_scope(conn, platform="avibe", scope_type="project", native_id="proj_last_reply", now=NOW)
+ conn.exec_driver_sql(
+ "insert into agent_sessions (id, scope_id, agent_name, agent_backend, agent_variant, session_anchor, "
+ "workdir, native_session_id, status, visibility, pinned, agent_status, metadata_json, created_at, "
+ "updated_at, last_active_at) values (?, ?, 'codex', 'codex', 'codex', ?, '/tmp', ?, 'active', "
+ "'foreground', 0, 'idle', ?, ?, ?, ?)",
+ (SESSION, scope_id, SESSION, SESSION, json.dumps({}), NOW, NOW, NOW),
+ )
+ delivery = message_deliveries.insert_delivery(
+ conn,
+ delivery_id="dlv_last_reply",
+ session_id=SESSION,
+ priority="p3",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=scope_id,
+ session_id=SESSION,
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type="user",
+ text="is the cache safe?",
+ ),
+ dispatch_text="is the cache safe?",
+ now=NOW,
+ )
+ claimed = message_deliveries.claim_start_batch(
+ conn, turn_id=TURN, session_id=SESSION, backend="codex", deliveries=[delivery], dispatch_text="is it?"
+ )
+ return claimed["turn"]
+
+
+def test_a_reply_write_and_a_turn_transition_both_land():
+ """MESSAGE-DELIVERY-335: a reply recorded between a transition's read and its
+ compare-and-set does not make the transition lose, and the transition neither writes
+ nor clears the reply; once the Turn is no longer live, nothing more is recorded."""
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ try:
+ with engine.begin() as conn:
+ starting = _seed(conn)
+ assert starting["state"] == "starting"
+ # The reply lands after the activation read the Turn's version...
+ assert message_deliveries.record_turn_reply(conn, TURN, "The cache is safe.")
+ assert message_deliveries.get_turn(conn, TURN)["version"] == starting["version"]
+ # ...and the activation's compare-and-set on that version still succeeds.
+ active = message_deliveries.bind_native_start(
+ conn,
+ TURN,
+ expected_version=int(starting["version"]),
+ runtime_key="runtime",
+ runtime_turn_id=TURN,
+ native_turn_id=TURN,
+ )
+ assert active is not None and active["state"] == "active"
+ assert message_deliveries.turn_last_reply(conn, TURN) == "The cache is safe."
+
+ # Repeated replies: the last delivered one wins, identical text included.
+ for reply in ("The lock is fine too.", "The cache is safe."):
+ assert message_deliveries.record_turn_reply(conn, TURN, reply)
+ settled = message_deliveries.terminalize_turn(
+ conn, TURN, outcome="completed", settled_by="terminal_result", evidence_kind="test"
+ )
+ assert settled["changed"] and settled["turn"]["state"] == "terminal"
+ assert message_deliveries.turn_last_reply(conn, TURN) == "The cache is safe."
+
+ # A Turn that ended keeps what it ended with; one that never existed has none.
+ assert not message_deliveries.record_turn_reply(conn, TURN, "Too late.")
+ assert not message_deliveries.record_turn_reply(conn, "trn_unknown", "Nobody's.")
+ assert message_deliveries.turn_last_reply(conn, TURN) == "The cache is safe."
+ assert message_deliveries.turn_last_reply(conn, "trn_unknown") is None
+ assert conn.execute(select(session_turn_replies.c.turn_id)).scalars().all() == [TURN]
+ finally:
+ engine.dispose()
+
+
+def test_the_reply_write_and_read_are_primary_key_searches():
+ """MESSAGE-DELIVERY-335: both run on every reply and every Turn end; each touches one
+ row by primary key, the write's live-Turn guard included."""
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ statements: list[tuple[str, tuple]] = []
+
+ def capture(_conn, _cursor, statement, parameters, _context, _executemany):
+ if "session_turn_replies" in statement:
+ statements.append((statement, parameters))
+
+ try:
+ with engine.begin() as conn:
+ _seed(conn)
+ event.listen(engine, "before_cursor_execute", capture)
+ with engine.begin() as conn:
+ message_deliveries.record_turn_reply(conn, TURN, "The cache is safe.")
+ message_deliveries.turn_last_reply(conn, TURN)
+ event.remove(engine, "before_cursor_execute", capture)
+ assert [sql.split()[0] for sql, _ in statements] == ["INSERT", "SELECT"]
+ with engine.connect() as conn:
+ plans = [
+ [row[-1] for row in conn.exec_driver_sql("EXPLAIN QUERY PLAN " + sql, params)]
+ for sql, params in statements
+ ]
+ finally:
+ engine.dispose()
+ assert plans == [
+ ["SEARCH session_turns USING INDEX sqlite_autoindex_session_turns_1 (id=?)"],
+ ["SEARCH session_turn_replies USING INDEX sqlite_autoindex_session_turn_replies_1 (turn_id=?)"],
+ ], plans
+
+
+class _Pre335Connection(sqlite3.Connection):
+ """SQLite before 3.35, which has no ``DROP COLUMN``."""
+
+ def cursor(self, factory=None):
+ cursor = super().cursor(factory or _Pre335Cursor)
+ return cursor
+
+
+class _Pre335Cursor(sqlite3.Cursor):
+ def execute(self, sql, parameters=()):
+ if " DROP COLUMN " in f" {' '.join(str(sql).upper().split())} ":
+ raise sqlite3.OperationalError('near "DROP": syntax error')
+ return super().execute(sql, parameters)
+
+
[email protected]_sqlite_template
[email protected]("sqlite_drops_columns", [True, False], ids=["sqlite", "sqlite-before-3.35"])
+async def test_a_released_database_upgrades_and_its_running_turn_ends_without_a_reply(
+ tmp_path, monkeypatch, sqlite_drops_columns
+):
+ """MESSAGE-DELIVERY-335: a database a released version wrote (no table) upgrades with its
+ running Turn intact; that Turn has no reply on record, so its content-free end settles
+ its Run with "". Downgrade drops the table, on SQLite before 3.35 too, and the database
+ upgrades again."""
+ from core.scheduled_tasks import TaskExecutionStore
+ from tests.test_message_dispatcher_turn_end import _Controller
+
+ if not sqlite_drops_columns:
+ real_connect = sqlite3.connect
+
+ def legacy_connect(*args, **kwargs):
+ kwargs["factory"] = _Pre335Connection
+ return real_connect(*args, **kwargs)
+
+ monkeypatch.setattr(sqlite3, "connect", legacy_connect)
+ monkeypatch.setattr(sqlite3.dbapi2, "connect", legacy_connect)
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ dispose_cached_sqlite_engines()
+ path = paths.get_sqlite_state_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ migrations.run_migrations(path, revision=PREVIOUS_REVISION)
+ # The released shape, a running Turn written as a released version writes it (its
+ # Session and Delivery rows are not what this migration is about, so no foreign keys).
+ with sqlite3.connect(path) as conn:
+ assert "session_turn_replies" not in {
+ row[0] for row in conn.execute("select name from sqlite_master where type = 'table'")
+ }
+ conn.execute(
+ "insert into session_turns (id, session_id, initial_delivery_id, state, backend, "
+ "start_attempt_id, start_receipt_outcome, dispatch_text, dispatch_sha256, version, "
+ "created_at, updated_at) values (?, ?, ?, 'active', 'codex', 'atm_released', 'accepted', "
+ "'is it?', 'sha', 3, ?, ?)",
+ (TURN, SESSION, "dlv_released", NOW, NOW),
+ )
+
+ try:
+ ensure_sqlite_state()
+ engine = create_sqlite_engine(path)
+ try:
+ with engine.connect() as conn:
+ assert message_deliveries.turn_last_reply(conn, TURN) is None
+ turn = message_deliveries.get_turn(conn, TURN)
+ assert (turn["state"], turn["version"]) == ("active", 3)
+ finally:
+ engine.dispose()
+ runs = TaskExecutionStore()
+ run = runs.enqueue_task_run("task-released")
+ assert runs.claim(run.id) is not None
+ controller = _Controller("avibe")
+ context = controller_context(run.id)
+ await controller.emit_agent_message(context, "result", "", output=terminal_turn_output())
+ [snapshot] = controller.snapshots
+ assert snapshot["terminal_evidence"]["result_text"] == ""
+ settled = runs.get_run(run.id)
+ assert (settled["status"], settled["result_text"] or "") == ("succeeded", "")
+ finally:
+ dispose_cached_sqlite_engines()
+
+ with sqlite3.connect(path) as conn:
+ assert conn.execute("select version_num from alembic_version").fetchone() == (REVISION,)
+ command.downgrade(migrations.alembic_config(path), PREVIOUS_REVISION)
+ with sqlite3.connect(path) as conn:
+ tables = {row[0] for row in conn.execute("select name from sqlite_master where type = 'table'")}
+ assert "session_turn_replies" not in tables
+ assert conn.execute("select state, version from session_turns where id = ?", (TURN,)).fetchone() == (
+ "active",
+ 3,
+ )
+ migrations.run_migrations(path)
+ with sqlite3.connect(path) as conn:
+ assert conn.execute("select count(*) from session_turn_replies").fetchone() == (0,)
+
+
+def controller_context(run_id: str):
+ from modules.im import MessageContext
+
+ return MessageContext(
+ user_id="workbench",
+ channel_id=SESSION,
+ platform="avibe",
+ platform_specific={
+ "agent_session_id": SESSION,
+ "turn_token": TURN,
+ "task_trigger_kind": "scheduled",
+ "task_execution_id": run_id,
+ },
+ )
diff --git a/tests/test_vibey_agent.py b/tests/test_vibey_agent.py
index 43ab993ca..d09222181 100644
--- a/tests/test_vibey_agent.py
+++ b/tests/test_vibey_agent.py
@@ -66,6 +66,7 @@ from core.agent_core.messages import (
from core.agent_core.tools.base import CallInstance, JobStatus, ToolResult, ToolSpec
from core.message_dispatcher import ConsolidatedMessageDispatcher
from core.services.agent_steering import ActiveSteerTarget, SteerOutcome, SteerRequest
+from core.session_turns import SessionTurnManager
from modules.agents.vibey import VibeyAgent
from modules.agents.vibey.errors import _KIND_KEYS, error_key
from modules.agents.vibey.media import MediaSnapshots
@@ -224,11 +225,16 @@ class _Controller:
mark_runtime_turn_started=self._native_start,
release_runtime_turn=lambda context, **_kw: self.released.append(_turn(context)),
)
+ # The durable Turn row's own reply reads and writes are the real Turn owner's.
+ turns = SessionTurnManager()
+ turns._engine = engine
self.session_turns = SimpleNamespace(
on_terminal_result=self._terminal,
on_terminal_delivery_complete=lambda _context: None,
model_hub_turn_id_for_task=lambda: None,
_build_context=lambda session_id: _context(platform, session_id, turn_id="redelivery", delivery_id=""),
+ record_turn_reply=turns.record_turn_reply,
+ turn_last_reply=turns.turn_last_reply,
)
self.model_hub_runtime = SimpleNamespace(
resolve=self._resolve, snapshot=lambda: ModelHubConfig(sources=list(self.hub_sources))
@@ -2117,7 +2123,7 @@ async def test_a_silent_final_after_narration_shows_no_reply(engine, session, tm
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-334.
+ """Scenario: MESSAGE-DELIVERY-334 / MESSAGE-DELIVERY-335.
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
@@ -2168,11 +2174,14 @@ async def test_a_reply_a_steer_superseded_is_a_result_and_the_turn_ends_once_aft
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."
+ # The reply is identified by its committed row (MESSAGE-DELIVERY-335).
+ [reply_row] = [row for row in harness.rows("result") if row["id"] == rows[1].row_id]
+ assert str(reply_row["native_message_id"]).endswith(f":{rows[1].row_id}")
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]
+ # The Turn settles with its last reply: a silent end with the one it delivered before
+ # (MESSAGE-DELIVERY-335).
+ assert harness.controller.terminal_texts == ["4." if final.startswith("<silent>") else final]
async def test_a_silent_final_whose_run_failed_after_its_commit_is_typed_by_its_row(
@@ -2588,9 +2597,10 @@ 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 reply that process showed as it was
- and promotes nothing, not even a phase a released version stored as ``output``
- (MESSAGE-DELIVERY-334)."""
+ recorded is not sent again; a silent final leaves the reply that process showed as it was,
+ promotes nothing, not even a phase a released version stored as ``output``
+ (MESSAGE-DELIVERY-334), and settles with that reply, which the dead process's dispatcher
+ recorded on the durable Turn (MESSAGE-DELIVERY-335)."""
from dataclasses import replace
from core.message_output import MessageOutput, terminal_output_for
@@ -2657,6 +2667,7 @@ async def test_a_restart_rerun_ends_with_the_final_its_cut_run_committed(
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"] == []
+ assert harness.controller.terminal_texts[-1] == reply
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/tests/test_web_push_provider_invalidation_migration.py b/tests/test_web_push_provider_invalidation_migration.py
index f9bd43523..ffdb67fce 100644
--- a/tests/test_web_push_provider_invalidation_migration.py
+++ b/tests/test_web_push_provider_invalidation_migration.py
@@ -69,7 +69,7 @@ def test_upgrade_keeps_legacy_disabled_failure_opted_out(tmp_path):
web_push_service.mark_send_failure(conn, endpoint=enabled["endpoint"], disable=True)
with sqlite3.connect(path) as conn:
assert conn.execute("select version_num from alembic_version").fetchone() == (
- "20261018_0070",
+ "20261020_0071",
)
command.downgrade(migrations.alembic_config(path), "20260907_0061")