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.

fix(activity): silent / reply-less completions are DONE, not Interrupted (#951)

Call White06dee6bc6b84
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index 79ef771a8..5f00fcc35 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -19,7 +19,11 @@ from config.platform_registry import get_platform_descriptor
from config.v2_config import DEFAULT_AGENT_PROGRESS_STYLE
from modules.im import MessageContext
from modules.im.formatters.base_formatter import to_status_label
-from core.message_mirror import agent_message_exists, persist_agent_message
+from core.message_mirror import (
+ agent_message_exists,
+ persist_agent_message,
+ persist_silent_completion_marker,
+)
from core.message_output import MessageOutput, output_for_message
from core.reply_enhancer import process_reply, strip_file_links, strip_silent_blocks
from core.session_turns import emit_matches_active_turn
@@ -1426,6 +1430,30 @@ class ConsolidatedMessageDispatcher:
await self._collapse_status_bubble(context, im_client, reason=terminal_reason)
await self._clear_consolidated_state(context)
self._signal_turn_complete(context)
+ suppress_delivery = bool((context.platform_specific or {}).get("suppress_delivery"))
+ if level != "silent" and not is_error and not suppress_delivery:
+ # A CLEAN silent completion — ``level='normal'`` with an
+ # empty/``<silent>``-stripped body (we're already inside the
+ # ``level=='silent' or not text.strip()`` branch, so here the
+ # body is empty). Persist an INVISIBLE ``silent`` terminal
+ # marker; without it the activity grouping sees "activity rows +
+ # no terminal" and misreads a legal completion as interrupted.
+ #
+ # This must NOT fire for ``level='silent'``: the user-stop paths
+ # (codex/claude/opencode) emit a terminal ``result`` with
+ # ``level='silent'`` and ``is_error=False`` — a stop legitimately
+ # stays ``interrupted``, so ``not is_error`` is the wrong gate.
+ # Backend failures also arrive ``level='silent'`` (after a
+ # visible notify), and are excluded here too. And a
+ # ``suppress_delivery`` run is a private/background turn that
+ # intentionally leaves NO message history — writing a marker
+ # would pollute the cross-platform store + activity/fork state,
+ # so it is excluded (mirrors the suppressed-delivery path that
+ # already skips ``persist_agent_message``).
+ try:
+ persist_silent_completion_marker(context)
+ except Exception:
+ logger.exception("emit_agent_message: silent completion marker failed")
return None
finally:
if mutates_turn_lifecycle:
diff --git a/core/message_mirror.py b/core/message_mirror.py
index f772d4957..d0156c7a0 100644
--- a/core/message_mirror.py
+++ b/core/message_mirror.py
@@ -246,6 +246,72 @@ def _trace_ids_from_context(context: MessageContext) -> tuple[Optional[str], Opt
return turn_id, run_id
+def persist_silent_completion_marker(context: MessageContext) -> None:
+ """Persist the invisible ``silent`` terminal marker for a turn that completed
+ NORMALLY but delivered no user-visible message — a ``<silent>``-stripped/empty
+ final reply, or a reply-less bookkeeping turn (common for watch/scheduled runs).
+
+ Written ONCE per turn at the delivery chokepoint
+ (``MessageDispatcher.emit_agent_message``) on the clean-completion path only — NOT
+ for cancel/Stop (which legitimately stays ``interrupted``) nor backend failures
+ (which already emit a visible ``notify``). It exists solely so the activity
+ grouping closes the turn as DONE instead of misreading "activity + no terminal" as
+ interrupted; it is never delivered, or shown as a transcript bubble (see
+ ``messages_service.SILENT_TYPE`` and its allowlist/denylist exclusions). Writes via
+ ``_append_quietly`` directly — bypassing ``persist_agent_message``'s empty-text
+ guard and the ``message.new`` publish (the marker is invisible in the transcript).
+
+ It DOES recompute + publish the inbox row, though: the marker counts as a reply for
+ the inbox awaiting/replied flag, so an open sidebar must clear "awaiting the agent"
+ live instead of staying stale until a reconnect. No web-push (a silent completion is
+ not a notifiable reply). Best-effort: the caller wraps it; a failure must never break
+ turn completion.
+ """
+ if not context.platform:
+ return
+ session_id = (context.platform_specific or {}).get("agent_session_id")
+ engine = get_cached_sqlite_engine()
+ inbox_row = None
+ with engine.begin() as conn:
+ if context.platform == "avibe":
+ session_row = _session_row(conn, session_id) if session_id else None
+ scope_id = session_row["scope_id"] if session_row else None
+ else:
+ session_row = None
+ scope_id = _resolve_scope_id(conn, context)
+ if scope_id is None:
+ return
+ agent_name, _backend = _agent_provenance_from_context(context, session_row)
+ _append_quietly(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ platform=context.platform,
+ author="agent",
+ source="agent",
+ author_name=agent_name,
+ message_type=messages_service.SILENT_TYPE,
+ text="",
+ metadata=None,
+ native_message_id=None,
+ parent_native_message_id=context.thread_id,
+ content={"kind": "silent"},
+ )
+ # Recompute the session's inbox row so the awaiting/replied flag clears live.
+ # avibe-only (the workbench inbox is avibe-scoped; IM rows aren't shown there).
+ if context.platform == "avibe" and session_id:
+ inbox_row = messages_service.get_inbox_session(conn, session_id)
+ if inbox_row is not None:
+ # Same ``inbox.session.updated`` event a visible reply publishes — but NOT
+ # ``message.new`` (no transcript bubble) and NOT web-push (not a notifiable reply).
+ try:
+ from core.inbox_events import bus
+
+ bus.publish("inbox.session.updated", inbox_row)
+ except Exception:
+ logger.debug("persist_silent_completion_marker: inbox publish failed", exc_info=True)
+
+
def persist_agent_message(
context: MessageContext,
canonical_type: str,
diff --git a/core/services/session_fork.py b/core/services/session_fork.py
index 7ae3a69e4..916efaace 100644
--- a/core/services/session_fork.py
+++ b/core/services/session_fork.py
@@ -19,7 +19,10 @@ from vibe.i18n import t
from vibe.message_identity import INPUT_TURN_AUTHOR_TYPES, is_input_turn
TRIM_LATEST_RUNNING_TURN_BACKENDS = {"codex", "opencode"}
-TERMINAL_AGENT_OUTPUT_TYPES = {"result", "error"}
+# ``silent`` is the invisible completion marker (messages_service.SILENT_TYPE): a turn
+# that finished with no user-visible reply is still TERMINAL, so a fork created after
+# it must not trim/roll back the completed turn as if it were still running.
+TERMINAL_AGENT_OUTPUT_TYPES = {"result", "error", "silent"}
SOURCE_PROGRESS_AGENT_OUTPUT_TYPES = {"assistant", *TERMINAL_AGENT_OUTPUT_TYPES}
ACTIVE_SOURCE_RUN_STATUSES = ("pending", "queued", "processing", "running")
INPUT_TURN_MESSAGE_TYPES = tuple(message_type for _, message_type in INPUT_TURN_AUTHOR_TYPES)
@@ -539,7 +542,7 @@ def _forked_session_title(source_title: str, lang: str = "en") -> str:
def _latest_source_message_anchor(conn: Any, source_session_id: str) -> SourceMessageAnchor:
from sqlalchemy import func, or_, select
- from storage.messages_service import TRANSCRIPT_TYPES
+ from storage.messages_service import SILENT_TYPE, TRANSCRIPT_TYPES
from storage.models import messages
row = conn.execute(
@@ -547,7 +550,11 @@ def _latest_source_message_anchor(conn: Any, source_session_id: str) -> SourceMe
.where(
messages.c.session_id == source_session_id,
or_(
- messages.c.type.in_(list(TRANSCRIPT_TYPES)),
+ # Include the invisible ``silent`` completion marker so a turn that
+ # finished silently is the anchor (a terminal, NOT a running input),
+ # otherwise the anchor falls back to the input row and the fork treats
+ # the completed turn as still running and trims/rolls it back.
+ messages.c.type.in_([*TRANSCRIPT_TYPES, SILENT_TYPE]),
func.json_extract(messages.c.metadata_json, "$.source") == "show_page",
),
)
diff --git a/docs/plans/chat-agent-activity-panel.md b/docs/plans/chat-agent-activity-panel.md
index 2da3e5674..07e5a2a7f 100644
--- a/docs/plans/chat-agent-activity-panel.md
+++ b/docs/plans/chat-agent-activity-panel.md
@@ -366,3 +366,86 @@ guard auto-covering the new field); `ruff` clean; changed-file `eslint` clean.
60vh scroll feel + top-open, the compact fade-at-cap, the eye-pill live toggle +
cross-device persistence, the D JSON dialog open/copy/close, and the tier-1/2/3
rendering against real per-backend `format_toolcall` output.
+
+## As-built implementation notes (silent-completion terminal taxonomy)
+
+**Bug.** P1 defined `interrupted` as "a turn's activity that ends without a terminal
+result". That wrongly captured **silent completions** (final reply is entirely a
+`<silent>` block → stripped → nothing delivered) and **reply-less bookkeeping turns**
+(common for watch/scheduled orchestration): the turn ran tool steps, finished
+normally, but wrote no `messages` row, so the grouping saw "activity + no terminal"
+and rendered a gold "Interrupted · stopped at step N" chip. Nothing was interrupted.
+
+**Terminal taxonomy (as-built).** A turn's activity group closes as:
+
+| Ending | Grouping status |
+| --- | --- |
+| visible `result` reply | `done` |
+| **invisible `silent` marker** (silent-stripped / empty final, or reply-less completion) | `done` |
+| `error`, or `backend_failure` `notify` | `failed` |
+| cancel / Stop, or no terminal at all | `interrupted` |
+
+A **plain `notify` is NOT terminal** — agents emit mid-turn notify rows that keep the
+turn going (e.g. Claude's model-refusal fallback), so treating every notify as terminal
+would split one turn into two. A genuine notify-only COMPLETION is closed by the
+`silent` marker instead (its turn still emits an empty final result at the chokepoint).
+
+**Invisible `silent` marker.** When a turn completes NORMALLY with nothing
+user-visible to send, the delivery chokepoint
+(`MessageDispatcher.emit_agent_message`, the `mutates_turn_lifecycle` branch) persists
+ONE `messages` row of a **dedicated `type='silent'`** via
+`message_mirror.persist_silent_completion_marker` → `messages_service.append`
+(bypassing the empty-text guard and the `message.new` publish — no transcript bubble).
+**Gate: `level != "silent" and not is_error and not suppress_delivery`.** This is the
+load-bearing distinction: the real user-stop paths (codex/claude/opencode) emit a
+terminal `result` with `level="silent"` and `is_error=False`, so `not is_error` ALONE
+would wrongly mark a stop as done — a stop must stay `interrupted`. A genuine
+`<silent>`-block/empty completion is `level="normal"` with an empty body; backend
+failures arrive `level="silent"` (after a visible notify); a `suppress_delivery`
+private/background run intentionally leaves NO history — all excluded.
+
+The marker DOES recompute + publish `inbox.session.updated` (avibe): since it now
+clears the inbox awaiting/replied flag, an open sidebar must drop "awaiting the agent"
+live rather than staying stale until reconnect. But it publishes NO `message.new` (no
+transcript bubble) and NO web-push (a silent completion is not a notifiable reply).
+
+A **dedicated type** (not the originally-sketched `result` + `content.kind='silent'`)
+was chosen after finding the read layer is **allowlist**-based: `type='silent'` is
+auto-excluded from the transcript (`TRANSCRIPT_TYPES`), inbox preview, unread, web-push
+and the live-publish gate with ZERO new guards — mirroring the invisible-type precedent
+(`pending`/`queued`/`draft`/`harness_dedupe`). (A `result`-typed marker would have
+leaked into ~8 allowlist reads.) Teaching the rest of the system about the new type:
+- **`NON_CONVERSATION_TYPES`** gains `silent` — the marker never bumps the inbox
+ activity clock / last-author.
+- **Inbox awaiting/replied** compares `last_input_at` against a terminal timestamp that
+ INCLUDES `silent` (not the visible-only `preview_*`), so a silently-completed turn is
+ no longer stuck showing "awaiting the agent"; the preview TEXT stays the last visible
+ reply.
+- **`ix_messages_inbox_activity`** partial-index predicate adds `silent` (models.py +
+ migrations.py + alembic `20260721_0031`) — a stricter `NOT IN` query predicate does
+ NOT reuse a looser partial index on SQLite, so the predicates must match or inbox
+ refreshes fall back to scans.
+- **Session fork** treats `silent` as terminal in BOTH the anchor query
+ (`_latest_source_message_anchor`, else the anchor falls back to the input row and the
+ completed turn is trimmed/rolled back as if running) and `TERMINAL_AGENT_OUTPUT_TYPES`.
+
+**Grouping.** `agent_activity_service` adds `silent` to `_RELEVANT_MESSAGE_TYPES` (so
+its timeline — separate from the transcript allowlist — sees the marker) and
+`_is_terminal` (result/error/silent + `backend_failure` notify). Because the marker is
+invisible in the transcript, a group closing on it anchors to the **visible turn
+trigger** AFTER it (never the marker — which the frontend can't position against, per
+the #935 backward anchor invariant), and the marker never becomes `last_boundary_id`. A
+visible terminal still anchors to itself, BEFORE it. **Frontend: no change** — the
+marker never reaches it; `done` flows through `groupFromWire` and renders as the ✓ chip.
+
+**Evidence.** `tests/test_agent_activity_service.py` — silent completion → done
+(watch-triggered, tool steps, silent finish; anchored to the visible trigger); a
+mid-turn notify does NOT split/close a turn; backend_failure notify → failed; Stop (no
+terminal) → interrupted. `tests/test_message_dispatcher_result_fallback.py` — the
+chokepoint writes the marker on a clean completion, NOT on a `level="silent"` stop nor
+an `is_error` result. `tests/test_message_mirror.py` — the marker persists but is
+excluded from the transcript allowlist + `NON_CONVERSATION_TYPES`.
+`tests/test_messages_service.py` — a silent completion clears the inbox "awaiting" flag
+while the preview stays the last visible reply. `tests/test_session_fork.py` — a
+silently-completed codex/opencode source turn is terminal (no trim). IM delivery
+untouched (marker is avibe-persistence only).
diff --git a/storage/agent_activity_service.py b/storage/agent_activity_service.py
index c4a1bf3fd..37a735556 100644
--- a/storage/agent_activity_service.py
+++ b/storage/agent_activity_service.py
@@ -44,13 +44,16 @@ MESSAGE_SCAN_LIMIT = 500
EVENT_SCAN_LIMIT = 2000
# Message types that participate in turn structure: turn openers (user/harness),
-# terminals (result/error/notify), and the interim assistant activity rows.
+# terminals (result/error/notify/silent-marker), and the interim assistant activity
+# rows. The invisible ``silent`` marker is fetched here (it is NOT in TRANSCRIPT_TYPES)
+# so a turn that completed with no user-visible reply still has a terminal to close on.
_RELEVANT_MESSAGE_TYPES = (
"user",
messages_service.HARNESS_TYPE,
"result",
"error",
"notify",
+ messages_service.SILENT_TYPE,
"assistant",
)
@@ -86,18 +89,37 @@ def _duration_ms(started_iso: Optional[str], ended_iso: Optional[str]) -> Option
def _is_terminal(msg_type: Any, author: Any, metadata: Optional[dict]) -> bool:
- """Mirror the frontend ``isTerminalAgentMessage`` predicate."""
+ """Whether an agent message legally CLOSES a turn.
+
+ Terminals: a visible ``result``/``error`` reply, a ``backend_failure`` ``notify``
+ diagnostic, OR — when the turn produced nothing user-visible (a ``<silent>``-
+ stripped/empty final, or a reply-less bookkeeping turn) — the invisible ``silent``
+ marker persisted at the delivery chokepoint. Only cancel/Stop (no terminal at all)
+ stays ``interrupted``.
+
+ A PLAIN ``notify`` is deliberately NOT terminal: agents emit mid-turn notify rows
+ that explicitly do not end the turn (e.g. Claude's model-refusal fallback), so
+ treating every notify as terminal would split one turn into two groups. A genuine
+ notify-only COMPLETION is instead closed by the ``silent`` marker (its turn still
+ emits an empty final result at the chokepoint), not by the notify row.
+ """
if author != "agent":
return False
- if msg_type in ("result", "error"):
+ if msg_type in ("result", "error", messages_service.SILENT_TYPE):
return True
if msg_type == "notify" and (metadata or {}).get("event") == "backend_failure":
return True
return False
-def _terminal_status(msg_type: Any) -> str:
- return "done" if msg_type == "result" else "failed"
+def _terminal_status(msg_type: Any, metadata: Optional[dict] = None) -> str:
+ """done for a normal completion (result / silent marker); failed for an ``error``
+ or a ``backend_failure`` notify."""
+ if msg_type == "error":
+ return "failed"
+ if msg_type == "notify" and (metadata or {}).get("event") == "backend_failure":
+ return "failed"
+ return "done"
# Fallback tiebreak only (used when a row's microsecond id prefix can't be decoded,
@@ -169,6 +191,12 @@ def _timeline(conn, session_id: str, *, include_text: bool) -> list[dict[str, An
"mtype": mtype,
"row_kind": "assistant",
"text": msg.get("text") if include_text else None,
+ # The silent marker is a terminal that is INVISIBLE in the transcript,
+ # so a group closing on it must anchor to the (visible) turn trigger
+ # rather than the marker itself; ``terminal_status`` is resolved here so
+ # ``notify`` failure/normal is decided with its metadata in hand.
+ "is_silent": mtype == messages_service.SILENT_TYPE,
+ "terminal_status": _terminal_status(mtype, metadata) if kind == "terminal" else None,
}
)
# Bound events to the scanned message window: in a long session the 500-message
@@ -280,12 +308,21 @@ def _build_groups(items: list[dict[str, Any]], *, include_rows: bool) -> list[di
last_boundary_id = item["id"]
elif kind == "terminal":
if pending:
+ # A silent marker is invisible in the transcript, so its DONE group
+ # anchors to the (visible) turn trigger AFTER it — never to the marker,
+ # which the frontend can't position against (#935 backward-anchor). A
+ # visible terminal (result/error/notify) anchors to itself, BEFORE it
+ # (the chip hugs the reply from above).
+ if item["is_silent"]:
+ anchor_id, anchor_position = last_boundary_id, "after"
+ else:
+ anchor_id, anchor_position = item["id"], "before"
groups.append(
_make_group(
pending,
- status=_terminal_status(item["mtype"]),
- anchor_id=item["id"],
- anchor_position="before",
+ status=item["terminal_status"],
+ anchor_id=anchor_id,
+ anchor_position=anchor_position,
open_turn=False,
started_iso=turn_start_iso,
ended_iso=item["created_at"],
@@ -294,7 +331,11 @@ def _build_groups(items: list[dict[str, Any]], *, include_rows: bool) -> list[di
)
pending = []
turn_start_iso = None
- last_boundary_id = item["id"]
+ # Keep ``last_boundary_id`` on a TRANSCRIPT-VISIBLE row: a visible terminal
+ # becomes the new boundary; the invisible silent marker does NOT (a later
+ # turn must still anchor to a row the frontend can render).
+ if not item["is_silent"]:
+ last_boundary_id = item["id"]
# kind == "ignore": leave pending + boundary + turn_start untouched
if pending:
# The last un-terminated turn. Anchor AFTER its trigger (never the tail); the
diff --git a/storage/alembic/versions/20260721_0031_silent_marker_inbox_index.py b/storage/alembic/versions/20260721_0031_silent_marker_inbox_index.py
new file mode 100644
index 000000000..1c94a6e6d
--- /dev/null
+++ b/storage/alembic/versions/20260721_0031_silent_marker_inbox_index.py
@@ -0,0 +1,44 @@
+"""exclude silent completion markers from the inbox activity index
+
+The invisible ``silent`` completion marker (messages_service.SILENT_TYPE) is added to
+``NON_CONVERSATION_TYPES``, so the inbox ``conversation_only`` subqueries now filter
+``type NOT IN (..., 'silent')``. The partial index ``ix_messages_inbox_activity`` must
+carry the same predicate, or SQLite stops using it for those top-1 probes (a stricter
+``NOT IN`` predicate does not match the looser partial index) and large inbox refreshes
+fall back to scans.
+
+Revision ID: 20260721_0031
+Revises: 20260716_0030
+Create Date: 2026-07-21
+"""
+
+from __future__ import annotations
+
+from alembic import op
+
+revision = "20260721_0031"
+down_revision = "20260716_0030"
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+ bind = op.get_bind()
+ bind.exec_driver_sql("drop index if exists ix_messages_inbox_activity")
+ bind.exec_driver_sql(
+ "create index ix_messages_inbox_activity "
+ "on messages (platform, session_id, created_at desc, id desc) "
+ "where session_id is not null and "
+ "type not in ('queued', 'draft', 'pending', 'harness_dedupe', 'silent')"
+ )
+
+
+def downgrade() -> None:
+ bind = op.get_bind()
+ bind.exec_driver_sql("drop index if exists ix_messages_inbox_activity")
+ bind.exec_driver_sql(
+ "create index ix_messages_inbox_activity "
+ "on messages (platform, session_id, created_at desc, id desc) "
+ "where session_id is not null and "
+ "type not in ('queued', 'draft', 'pending', 'harness_dedupe')"
+ )
diff --git a/storage/messages_service.py b/storage/messages_service.py
index 4e481226c..e2f1a9d88 100644
--- a/storage/messages_service.py
+++ b/storage/messages_service.py
@@ -575,8 +575,19 @@ PENDING_TYPE = "pending"
# Hidden row used only to keep native-message-id dedupe coverage after multiple
# queued harness callbacks are coalesced into one dispatched turn.
HARNESS_DEDUPE_TYPE = "harness_dedupe"
-# Ephemeral types that must never count as inbox activity / conversation.
-NON_CONVERSATION_TYPES = (QUEUED_TYPE, DRAFT_TYPE, PENDING_TYPE, HARNESS_DEDUPE_TYPE)
+# An INVISIBLE, agent-authored terminal marker persisted when a turn completes
+# NORMALLY but produces no user-visible message — a ``<silent>``-stripped or empty
+# final reply, or a reply-less bookkeeping turn (common for watch/scheduled
+# orchestration). It exists ONLY so the activity grouping can close such a turn as
+# DONE instead of misreading "activity rows + no terminal" as ``interrupted``. It is
+# kept out of every user-facing surface by the allowlist reads (TRANSCRIPT_TYPES,
+# inbox preview, unread, web-push, live publish) and, being author='agent', is listed
+# in NON_CONVERSATION_TYPES below so it never bumps the inbox activity clock / last
+# author. Never delivered to IM (avibe-persistence only).
+SILENT_TYPE = "silent"
+# Types that must never count as inbox conversation activity: the ephemeral user rows
+# above plus the invisible agent silent-completion marker.
+NON_CONVERSATION_TYPES = (QUEUED_TYPE, DRAFT_TYPE, PENDING_TYPE, HARNESS_DEDUPE_TYPE, SILENT_TYPE)
# The transcript-visible types — the SINGLE source of truth shared by the
# history fetch (``list_session_messages``) AND the live ``message.new`` publish
@@ -925,6 +936,13 @@ def list_inbox_sessions(
last_author = _latest_message_value("author", conversation_only=True)
preview_id = _latest_message_value("id", types=("result", "notify", "error"))
preview_at = _latest_message_value("created_at", types=("result", "notify", "error"))
+ # The awaiting/replied calc must count the INVISIBLE ``silent`` completion marker
+ # as a reply too (a reply-less turn is still answered) — otherwise a silently
+ # completed turn keeps the sidebar showing "awaiting the agent". The PREVIEW text
+ # stays the last VISIBLE reply, so ``silent`` is included here but NOT in preview_*.
+ _terminal_types = ("result", "notify", "error", SILENT_TYPE)
+ last_terminal_id = _latest_message_value("id", types=_terminal_types)
+ last_terminal_at = _latest_message_value("created_at", types=_terminal_types)
last_input_at = _latest_message_value(
"created_at", conversation_only=True, input_turn_only=True
)
@@ -957,6 +975,8 @@ def list_inbox_sessions(
unread_count_col,
preview_id.label("preview_id"),
preview_at.label("preview_at"),
+ last_terminal_id.label("last_terminal_id"),
+ last_terminal_at.label("last_terminal_at"),
last_input_at.label("last_input_at"),
last_input_id.label("last_input_id"),
)
@@ -1023,14 +1043,17 @@ def list_inbox_sessions(
# reply.
last_input_at = row["last_input_at"]
last_input_id = row["last_input_id"]
- preview_at = row["preview_at"]
- preview_id = row["preview_id"]
+ # Compare against the last TERMINAL (incl. the invisible ``silent`` marker),
+ # not the preview: a silently-completed turn HAS replied even though its text
+ # is not the visible preview.
+ terminal_at = row["last_terminal_at"]
+ terminal_id = row["last_terminal_id"]
awaiting_reply = bool(
last_input_at is not None
- and preview_at is not None
+ and terminal_at is not None
and (
- last_input_at > preview_at
- or (last_input_at == preview_at and (last_input_id or "") > (preview_id or ""))
+ last_input_at > terminal_at
+ or (last_input_at == terminal_at and (last_input_id or "") > (terminal_id or ""))
)
)
sessions.append(
diff --git a/storage/migrations.py b/storage/migrations.py
index 43a5f5cd6..3bee6a1d8 100644
--- a/storage/migrations.py
+++ b/storage/migrations.py
@@ -638,7 +638,7 @@ def _ensure_messages_query_indexes(conn: sqlite3.Connection, tables: set[str]) -
conn.execute(
"create index ix_messages_inbox_activity "
"on messages (platform, session_id, created_at desc, id desc) "
- "where session_id is not null and type not in ('queued', 'draft', 'pending', 'harness_dedupe')"
+ "where session_id is not null and type not in ('queued', 'draft', 'pending', 'harness_dedupe', 'silent')"
)
conn.execute(
"create index if not exists ix_messages_inbox_agent_reply "
diff --git a/storage/models.py b/storage/models.py
index ec11af715..5d94a8913 100644
--- a/storage/models.py
+++ b/storage/models.py
@@ -366,7 +366,9 @@ messages = Table(
"session_id",
text("created_at desc"),
text("id desc"),
- sqlite_where=text("session_id is not null and type not in ('queued', 'draft', 'pending', 'harness_dedupe')"),
+ sqlite_where=text(
+ "session_id is not null and type not in ('queued', 'draft', 'pending', 'harness_dedupe', 'silent')"
+ ),
),
Index(
"ix_messages_inbox_agent_reply",
diff --git a/tests/test_agent_activity_service.py b/tests/test_agent_activity_service.py
index 9ab591186..a52fe67a9 100644
--- a/tests/test_agent_activity_service.py
+++ b/tests/test_agent_activity_service.py
@@ -461,3 +461,94 @@ def test_get_turn_group_unknown_id_returns_none(isolated_state):
assert agent_activity_service.get_turn_group(conn, session_id=sid, group_id="nope") is None
found = agent_activity_service.get_turn_group(conn, session_id=sid, group_id="e_t")
assert found is not None and found["steps"] == 1
+
+
+# ===== Terminal taxonomy (silent completions, notify, error, Stop) =====
+# result / notify / silent-marker = done; backend_failure notify / error = failed;
+# no terminal at all (cancel/Stop) = interrupted.
+
+
+def test_silent_completion_marks_turn_done(isolated_state):
+ """The reported bug: a watch-triggered turn runs tool steps then finishes with a
+ ``<silent>`` reply (stripped, nothing delivered → an invisible ``silent`` marker).
+ It MUST be ``done``, not ``interrupted``, and — since the marker is invisible in
+ the transcript — anchored to the (visible) trigger AFTER it, not the marker."""
+ engine = create_sqlite_engine()
+ sid = "ses_silent"
+ with engine.begin() as conn:
+ scope = _seed_session(conn, session_id=sid)
+ _msg(conn, scope, sid, mid="m_h1", mtype="harness", author="harness", created_at="2026-06-01T10:00:00.000000+00:00", text="watch fired", source="harness")
+ _evt(conn, scope, sid, eid="e_s1", created_at="2026-06-01T10:00:01Z", text="🔧 `Bash` `{\"command\":\"a\"}`")
+ _evt(conn, scope, sid, eid="e_s2", created_at="2026-06-01T10:00:02Z", text="🔧 `Read` `{\"file_path\":\"b\"}`")
+ # The invisible marker (type='silent', empty text) written at the chokepoint.
+ _msg(conn, scope, sid, mid="m_sil1", mtype="silent", author="agent", created_at="2026-06-01T10:00:03.000000+00:00", text="")
+
+ with engine.connect() as conn:
+ groups = agent_activity_service.list_turn_groups(conn, session_id=sid)["groups"]
+ assert len(groups) == 1
+ g = groups[0]
+ assert g["status"] == "done"
+ assert g["anchor_message_id"] == "m_h1" # visible trigger, not the invisible marker
+ assert g["anchor_position"] == "after"
+ assert g["open"] is False
+ assert g["steps"] == 2
+
+
+def test_midturn_notify_does_not_split_or_close_a_turn(isolated_state):
+ """A plain (non-backend-failure) ``notify`` is NOT terminal: agents emit mid-turn
+ notify rows that keep the turn going (e.g. Claude's model-refusal fallback). It must
+ not close the pending group or split the turn — the turn still closes on its real
+ terminal, keeping all steps in ONE group. (A genuine notify-only completion is
+ closed by the silent marker instead — see test_silent_completion_marks_turn_done.)"""
+ engine = create_sqlite_engine()
+ sid = "ses_notify"
+ with engine.begin() as conn:
+ scope = _seed_session(conn, session_id=sid)
+ _msg(conn, scope, sid, mid="m_u", mtype="user", author="user", created_at="2026-06-01T10:00:00.000000+00:00", text="q", source="user")
+ _evt(conn, scope, sid, eid="e_n1", created_at="2026-06-01T10:00:01Z", text="🔧 `Bash` `{\"command\":\"x\"}`")
+ _msg(conn, scope, sid, mid="m_n1", mtype="notify", author="agent", created_at="2026-06-01T10:00:02.000000+00:00", text="refusal fallback")
+ _evt(conn, scope, sid, eid="e_n2", created_at="2026-06-01T10:00:03Z", text="🔧 `Read` `{\"file_path\":\"y\"}`")
+ _msg(conn, scope, sid, mid="m_r1", mtype="result", author="agent", created_at="2026-06-01T10:00:04.000000+00:00", text="answer")
+
+ with engine.connect() as conn:
+ groups = agent_activity_service.list_turn_groups(conn, session_id=sid)["groups"]
+ # ONE done group spanning both tool steps — the mid-turn notify neither closed nor
+ # split it; the turn closed on its real terminal.
+ assert [g["status"] for g in groups] == ["done"]
+ assert groups[0]["steps"] == 2
+ assert groups[0]["anchor_message_id"] == "m_r1"
+ assert groups[0]["anchor_position"] == "before"
+
+
+def test_backend_failure_notify_is_failed(isolated_state):
+ """A ``backend_failure`` notify stays a FAILED terminal (not done)."""
+ engine = create_sqlite_engine()
+ sid = "ses_bf"
+ with engine.begin() as conn:
+ scope = _seed_session(conn, session_id=sid)
+ _msg(conn, scope, sid, mid="m_u", mtype="user", author="user", created_at="2026-06-01T10:00:00.000000+00:00", text="q", source="user")
+ _evt(conn, scope, sid, eid="e_b1", created_at="2026-06-01T10:00:01Z", text="🔧 `Bash` `{\"command\":\"x\"}`")
+ _msg(conn, scope, sid, mid="m_bf", mtype="notify", author="agent", created_at="2026-06-01T10:00:02.000000+00:00", text="backend died", metadata={"event": "backend_failure"})
+
+ with engine.connect() as conn:
+ groups = agent_activity_service.list_turn_groups(conn, session_id=sid)["groups"]
+ assert [g["status"] for g in groups] == ["failed"]
+
+
+def test_stop_without_terminal_stays_interrupted(isolated_state):
+ """Cancel/Stop writes NO marker (no visible terminal, no silent marker), so a
+ turn with activity and no terminal before the next turn stays ``interrupted``."""
+ engine = create_sqlite_engine()
+ sid = "ses_stop"
+ with engine.begin() as conn:
+ scope = _seed_session(conn, session_id=sid)
+ _msg(conn, scope, sid, mid="m_u1", mtype="user", author="user", created_at="2026-06-01T10:00:00.000000+00:00", text="q1", source="user")
+ _evt(conn, scope, sid, eid="e_st1", created_at="2026-06-01T10:00:01Z", text="🔧 `Bash` `{\"command\":\"x\"}`")
+ # User stopped it, then started a new turn — no terminal for turn 1.
+ _msg(conn, scope, sid, mid="m_u2", mtype="user", author="user", created_at="2026-06-01T10:01:00.000000+00:00", text="q2", source="user")
+
+ with engine.connect() as conn:
+ groups = agent_activity_service.list_turn_groups(conn, session_id=sid)["groups"]
+ assert [g["status"] for g in groups] == ["interrupted"]
+ assert groups[0]["anchor_message_id"] == "m_u1" # anchored to its own trigger
+ assert groups[0]["anchor_position"] == "after"
diff --git a/tests/test_message_dispatcher_result_fallback.py b/tests/test_message_dispatcher_result_fallback.py
index 6564e81bb..cd51e74b9 100644
--- a/tests/test_message_dispatcher_result_fallback.py
+++ b/tests/test_message_dispatcher_result_fallback.py
@@ -772,6 +772,59 @@ class MessageDispatcherStatusChokepointTests(unittest.IsolatedAsyncioTestCase):
await dispatcher.emit_agent_message(_avibe_ctx(), "result", "", is_error=True)
self.assertEqual(controller.status_calls, [("ses-1", "failed")])
+ async def test_clean_silent_completion_writes_marker(self):
+ # The fix: a clean (non-error) terminal result with no visible body — a
+ # ``<silent>``-stripped / empty final reply — persists the invisible ``silent``
+ # marker so the activity grouping closes the turn as DONE, not interrupted.
+ controller = _AvibeStatusController()
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ ctx = _avibe_ctx()
+ with mock.patch("core.message_dispatcher.persist_agent_message"), mock.patch(
+ "core.message_dispatcher.persist_silent_completion_marker"
+ ) as marker:
+ await dispatcher.emit_agent_message(ctx, "result", "")
+ marker.assert_called_once_with(ctx)
+
+ async def test_user_stop_writes_no_marker(self):
+ # The REAL stop paths (codex/claude/opencode) emit a terminal result with
+ # ``level='silent'`` and ``is_error=False`` — a stop legitimately stays
+ # interrupted, so NO silent marker. (``not is_error`` alone would wrongly mark
+ # it — the gate keys on ``level != 'silent'`` too. P1.)
+ controller = _AvibeStatusController()
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ with mock.patch("core.message_dispatcher.persist_agent_message"), mock.patch(
+ "core.message_dispatcher.persist_silent_completion_marker"
+ ) as marker:
+ await dispatcher.emit_agent_message(_avibe_ctx(), "result", "", level="silent")
+ marker.assert_not_called()
+
+ async def test_error_completion_writes_no_marker(self):
+ # An ``is_error`` terminal is a FAILURE, never a done marker.
+ controller = _AvibeStatusController()
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ with mock.patch("core.message_dispatcher.persist_agent_message"), mock.patch(
+ "core.message_dispatcher.persist_silent_completion_marker"
+ ) as marker:
+ await dispatcher.emit_agent_message(_avibe_ctx(), "result", "", is_error=True)
+ marker.assert_not_called()
+
+ async def test_suppress_delivery_writes_no_marker(self):
+ # A private/background run (``suppress_delivery``) intentionally leaves NO
+ # message history — no silent marker, so it never pollutes the cross-platform
+ # store / activity / fork state (mirrors the suppressed-delivery path that
+ # already skips ``persist_agent_message``).
+ controller = _AvibeStatusController()
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ ctx = MessageContext(
+ user_id="U1", channel_id="ses-1", platform="avibe",
+ platform_specific={"agent_session_id": "ses-1", "suppress_delivery": True},
+ )
+ with mock.patch("core.message_dispatcher.persist_agent_message"), mock.patch(
+ "core.message_dispatcher.persist_silent_completion_marker"
+ ) as marker:
+ await dispatcher.emit_agent_message(ctx, "result", "")
+ marker.assert_not_called()
+
async def test_silent_backend_failure_collapses_status_as_failed(self):
controller = _AvibeStatusController()
dispatcher = ConsolidatedMessageDispatcher(controller)
diff --git a/tests/test_message_mirror.py b/tests/test_message_mirror.py
index 9daea818d..9a4911a47 100644
--- a/tests/test_message_mirror.py
+++ b/tests/test_message_mirror.py
@@ -26,8 +26,14 @@ from sqlalchemy import select
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
-from core.message_mirror import mirror_harness_inbound, mirror_inbound, persist_agent_message
+from core.message_mirror import (
+ mirror_harness_inbound,
+ mirror_inbound,
+ persist_agent_message,
+ persist_silent_completion_marker,
+)
from modules.im import MessageContext
+from storage import messages_service
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
from storage.models import agent_events, agent_sessions, messages, scopes
@@ -854,3 +860,89 @@ def test_avibe_inbound_is_noop(isolated_state):
with engine.connect() as conn:
rows = conn.execute(select(messages).where(messages.c.author == "user")).mappings().all()
assert rows == []
+
+
+def test_silent_completion_marker_persisted_but_invisible(isolated_state):
+ """``persist_silent_completion_marker`` writes an agent-authored ``silent`` row
+ (empty text, content.kind='silent') that is EXCLUDED from the transcript allowlist
+ and from the inbox conversation clock, so the last visible message is unchanged."""
+ engine = create_sqlite_engine()
+ now = "2026-05-30T12:00:00Z"
+ with engine.begin() as conn:
+ scope_id = upsert_scope(conn, platform="avibe", scope_type="project", native_id="proj_sil", now=now)
+ conn.execute(
+ agent_sessions.insert().values(
+ id="ses_sil", scope_id=scope_id, agent_backend="claude", agent_variant="default",
+ session_anchor="anchor_ses_sil", native_session_id="", status="active", metadata_json="{}",
+ created_at=now, updated_at=now, last_active_at=now,
+ )
+ )
+ # A real, visible reply for an earlier turn — must stay the "last visible" one.
+ conn.execute(
+ messages.insert().values(
+ id="m_vis", scope_id=scope_id, session_id="ses_sil", platform="avibe", author="agent",
+ type="result", source="agent", content_text="the visible answer", content_json="{}",
+ metadata_json="{}", created_at=now, updated_at=now,
+ )
+ )
+
+ ctx = MessageContext(
+ user_id="workbench", channel_id="ses_sil", platform="avibe",
+ platform_specific={"agent_session_id": "ses_sil"},
+ )
+ persist_silent_completion_marker(ctx)
+
+ with engine.connect() as conn:
+ rows = conn.execute(select(messages).where(messages.c.session_id == "ses_sil")).mappings().all()
+ transcript = messages_service.list_session_messages(
+ conn, session_id="ses_sil", limit=50, tail=True, types=messages_service.TRANSCRIPT_TYPES
+ )["messages"]
+
+ silent_rows = [r for r in rows if r["type"] == "silent"]
+ assert len(silent_rows) == 1 # persisted
+ assert silent_rows[0]["author"] == "agent"
+ assert (silent_rows[0]["content_text"] or "") == ""
+ assert json.loads(silent_rows[0]["content_json"]).get("kind") == "silent"
+
+ # Invisible: excluded from the transcript allowlist; last visible row unchanged.
+ assert "silent" not in [m["type"] for m in transcript]
+ assert transcript[-1]["type"] == "result" and transcript[-1]["text"] == "the visible answer"
+ # And kept out of the inbox conversation clock (never bumps last-activity/author).
+ assert messages_service.SILENT_TYPE in messages_service.NON_CONVERSATION_TYPES
+ assert messages_service.SILENT_TYPE not in messages_service.TRANSCRIPT_TYPES
+
+
+def test_silent_completion_marker_publishes_inbox_update_not_message(isolated_state):
+ """The marker clears the inbox awaiting flag, so it publishes ``inbox.session.updated``
+ (live sidebar refresh) — but NOT ``message.new`` (no transcript bubble)."""
+ from unittest import mock
+
+ engine = create_sqlite_engine()
+ now = "2026-05-30T12:00:00Z"
+ with engine.begin() as conn:
+ scope_id = upsert_scope(conn, platform="avibe", scope_type="project", native_id="proj_pub", now=now)
+ conn.execute(
+ agent_sessions.insert().values(
+ id="ses_pub", scope_id=scope_id, agent_backend="claude", agent_variant="default",
+ session_anchor="anchor_ses_pub", native_session_id="", status="active", metadata_json="{}",
+ created_at=now, updated_at=now, last_active_at=now,
+ )
+ )
+ conn.execute(
+ messages.insert().values(
+ id="m_vis", scope_id=scope_id, session_id="ses_pub", platform="avibe", author="agent",
+ type="result", source="agent", content_text="visible", content_json="{}",
+ metadata_json="{}", created_at=now, updated_at=now,
+ )
+ )
+
+ ctx = MessageContext(
+ user_id="workbench", channel_id="ses_pub", platform="avibe",
+ platform_specific={"agent_session_id": "ses_pub"},
+ )
+ with mock.patch("core.inbox_events.bus.publish") as publish:
+ persist_silent_completion_marker(ctx)
+
+ published = [call.args[0] for call in publish.call_args_list]
+ assert "inbox.session.updated" in published # sidebar awaiting clears live
+ assert "message.new" not in published # invisible: no transcript bubble
diff --git a/tests/test_messages_service.py b/tests/test_messages_service.py
index 757e89085..ee39d1fb1 100644
--- a/tests/test_messages_service.py
+++ b/tests/test_messages_service.py
@@ -690,6 +690,29 @@ def test_list_inbox_sessions_awaiting_reply_persists_through_agent_stream(isolat
assert row2["preview_text"] == "R2"
+def test_list_inbox_sessions_silent_completion_clears_awaiting(isolated_state):
+ """A turn that completes with only the INVISIBLE ``silent`` marker still counts as
+ the agent having replied — ``replied`` (awaiting) clears — while the preview text
+ stays the last VISIBLE reply (silent is not a preview type)."""
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_titled_session(conn, scope_id, "ses_sil", "Silent")
+ _insert_msg(conn, scope_id, "ses_sil", "user", "first", "2026-05-30T10:00:00Z")
+ _insert_msg(conn, scope_id, "ses_sil", "agent", "R1", "2026-05-30T10:01:00Z") # visible reply
+ # turn 2: user follows up; the agent runs and finishes SILENTLY (marker only).
+ _insert_msg(conn, scope_id, "ses_sil", "user", "second", "2026-05-30T10:05:00Z")
+ _insert_msg(
+ conn, scope_id, "ses_sil", "agent", "", "2026-05-30T10:07:00Z",
+ read=False, msg_type=messages_service.SILENT_TYPE,
+ )
+
+ with engine.connect() as conn:
+ row = messages_service.list_inbox_sessions(conn, platform="avibe")["sessions"][0]
+ assert row["replied"] is False # the silent completion answered the follow-up
+ assert row["preview_text"] == "R1" # preview stays the last VISIBLE reply
+
+
def test_list_inbox_sessions_counts_harness_prompt_as_pending_input(isolated_state):
engine = create_sqlite_engine()
with engine.begin() as conn:
diff --git a/tests/test_session_fork.py b/tests/test_session_fork.py
index 0c7ac3797..ea603cf7d 100644
--- a/tests/test_session_fork.py
+++ b/tests/test_session_fork.py
@@ -1408,3 +1408,35 @@ def test_fork_metadata_from_session_metadata_preserves_trim_fields() -> None:
"native_turn_started": True,
"opencode_fork_message_id": "oc-msg-2",
}
+
+
+def test_reserve_forked_session_silent_completion_is_terminal_no_trim(tmp_path: Path) -> None:
+ """A codex/opencode source whose latest turn completed SILENTLY (the invisible
+ ``silent`` marker follows its input + activity) is TERMINAL — the fork must not
+ trim/roll back the completed turn as if it were still running."""
+ db_path = tmp_path / "vibe.sqlite"
+ source_id = _seed_source_session(db_path, tmp_path) # agent_backend='codex'
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.begin() as conn:
+ scope_id = conn.execute(
+ select(agent_sessions.c.scope_id).where(agent_sessions.c.id == source_id)
+ ).mappings().one()["scope_id"]
+ messages_service.append(
+ conn, scope_id=scope_id, session_id=source_id, platform="avibe",
+ author="user", message_type="user", text="do the thing",
+ )
+ messages_service.append(
+ conn, scope_id=scope_id, session_id=source_id, platform="avibe",
+ author="agent", message_type="assistant", text="working",
+ )
+ messages_service.append(
+ conn, scope_id=scope_id, session_id=source_id, platform="avibe",
+ author="agent", message_type=messages_service.SILENT_TYPE, text="",
+ )
+ finally:
+ engine.dispose()
+
+ result = reserve_forked_session(source_session_id=source_id, db_path=db_path)
+ # A terminal exists after the input anchor → not a running turn → no trim.
+ assert result.fork.trim_latest_running_turn is False
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index 159364bb3..05c574017 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -19,7 +19,7 @@ from storage.models import metadata
from storage.settings_service import SQLiteSettingsService
-HEAD_REVISION = "20260716_0030"
+HEAD_REVISION = "20260721_0031"
def _index_sql(conn: sqlite3.Connection, name: str) -> str: