Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(messages): keep nonterminal output distinct (#1599)
Call White6bdfbb4e4585
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.pyindex 16d238ccf..b692a628a 100644--- a/core/message_dispatcher.py+++ b/core/message_dispatcher.py@@ -34,6 +34,7 @@ from core.message_output import (HARNESS_RUN_ID_TRIGGER_KINDS,HARNESS_TRIGGER_KINDS,MessageOutput,+ communication_type_for_output,output_for_message,)from core.reply_enhancer import process_reply, strip_file_links, strip_silent_blocks@@ -2167,6 +2168,11 @@ class ConsolidatedMessageDispatcher:terminal_reason = "failed"visible_output_type = canonical_type in {"result", "output"}+ communication_type = communication_type_for_output(+ canonical_type,+ output_semantics,+ is_error=is_error,+ )if visible_output_type:if not current_runtime_turn and not output_semantics.detached:logger.info(@@ -2485,7 +2491,6 @@ class ConsolidatedMessageDispatcher:recorded_text = self._fold_footer(persist_text, result_footer)persisted_output = Noneif visible_output_type:- result_type = "error" if is_error else canonical_typeif target_context.platform == "avibe":background_enhanced = process_reply(raw_text,@@ -2497,7 +2502,7 @@ class ConsolidatedMessageDispatcher:)persisted_output = persist_agent_message(target_context,- result_type,+ communication_type,background_enhanced.text or persist_text,quick_replies=[b.text for b in background_enhanced.buttons] or None,result_footer=result_footer,@@ -2507,7 +2512,7 @@ class ConsolidatedMessageDispatcher:else:persisted_output = persist_agent_message(target_context,- result_type,+ communication_type,recorded_text,result_footer=result_footer,metadata=output_metadata,@@ -2894,7 +2899,6 @@ class ConsolidatedMessageDispatcher:# A failed terminal result persists as type='error' so it shows in# the transcript/inbox like any terminal message but is NOT counted# as an unread agent reply (unread queries are result-only). Codex P2.- result_type = "error" if is_error else canonical_typeif target_context.platform == "avibe":# Keep the ``file://`` links in the persisted avibe text so the# workbench media-proxy rewrite (in ``persist_agent_message``)@@ -2913,7 +2917,7 @@ class ConsolidatedMessageDispatcher:)persisted_output = persist_agent_message(target_context,- result_type,+ communication_type,avibe_enhanced.text or persist_text,quick_replies=[b.text for b in avibe_enhanced.buttons] or None,result_footer=folded_footer,@@ -2923,7 +2927,7 @@ class ConsolidatedMessageDispatcher:else:persisted_output = persist_agent_message(target_context,- result_type,+ communication_type,persisted_result_text,result_footer=folded_footer,metadata=output_metadata,@@ -3009,7 +3013,7 @@ class ConsolidatedMessageDispatcher:context,text=display_text,message_id=primary_message_id,- kind=canonical_type,+ kind=communication_type,completes_turn=mutates_turn_lifecycle,)elif mutates_turn_lifecycle:diff --git a/core/message_mirror.py b/core/message_mirror.pyindex 4e34a936c..9af228ee5 100644--- a/core/message_mirror.py+++ b/core/message_mirror.py@@ -424,11 +424,11 @@ def persist_agent_message(appended_row is Noneand native_message_idand not suppress_delivery- and canonical_type in {"result", "error", "notify"}+ and spec_for(message_type)["inboxPreview"]):# The unique row may be local-only history from an earlier# suppress_delivery attempt. This call occurs after the visible- # result/notify send, so only now may that row become a receipt.+ # output send, so only now may that row become a receipt.appended_row = messages_service.promote_suppressed_native_message(conn,platform=context.platform,diff --git a/core/message_output.py b/core/message_output.pyindex 0b468f67b..cf888808b 100644--- a/core/message_output.py+++ b/core/message_output.py@@ -136,6 +136,33 @@ def output_for_message(message_type: str, output: MessageOutput | None) -> Messareturn MessageOutput(completes_turn=False, completes_run=False)+def communication_type_for_output(+ message_type: str,+ output: MessageOutput,+ *,+ is_error: bool = False,+) -> str:+ """Classify a visible output by the lifecycle authority it actually owns.++ Attached nonterminal output is persisted as ``output``. Detached completions+ retain their ``result`` / ``error`` notification family while metadata records+ their detached provenance without granting current-Turn timeline authority.+ """++ if message_type == "output":+ return "output"+ if message_type == "result":+ # Detached completion keeps its notification semantics. Lifecycle consumers+ # use its provenance without changing the visible type or current Turn.+ if output.detached:+ return "error" if is_error else "result"+ if not output.completes_turn:+ return "output"+ if is_error:+ return "error"+ return message_type++def terminal_turn_output() -> MessageOutput:"""Explicitly grant one output authority to settle its Turn and Run."""diff --git a/core/services/session_fork.py b/core/services/session_fork.pyindex ddaa9a91d..a5d7e7303 100644--- a/core/services/session_fork.py+++ b/core/services/session_fork.py@@ -15,14 +15,13 @@ from pathlib import Pathfrom typing import Any, Mapping, Optionalfrom config import paths-from core.backend_failure import BACKEND_FAILURE_EVENT, is_backend_failure_notificationfrom vibe.authorization import (AuthorizationContext,require_instance_role,)from vibe.i18n import tfrom vibe.message_identity import INPUT_TURN_AUTHOR_TYPES, is_input_turn-from vibe.message_types import spec_for, types_with+from vibe.message_types import activity_role_for, spec_for, types_withTRIM_LATEST_RUNNING_TURN_BACKENDS = {"codex", "opencode"}# Turn settlement is read from ``session_turns`` below, so a reply-less completion@@ -41,6 +40,7 @@ SOURCE_PROGRESS_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)_CONDITIONAL_TERMINAL_TYPES = types_with("terminalWhenEvents")+_DETACHED_COMPLETION_TYPES = types_with("detachedCompletion")_FORK_ANCHOR_TYPES = tuple(dict.fromkeys((@@ -126,13 +126,11 @@ class ForkSourceState:has_messages_after_anchor: bool = Falsehas_terminal_agent_output_after_anchor: bool = Falsehas_input_turn_after_anchor: bool = False- anchor_is_backend_failure: bool = False+ anchor_activity_role: str = "none"@propertydef anchor_is_terminal_agent_output(self) -> bool:- return self.anchor_author == "agent" and (- self.anchor_type in TERMINAL_AGENT_OUTPUT_TYPES or self.anchor_is_backend_failure- )+ return self.anchor_author == "agent" and self.anchor_activity_role == "terminal"@dataclass(frozen=True)@@ -566,6 +564,14 @@ def fork_source_state(fork: dict[str, Any] | None) -> ForkSourceState:),),after_anchor,+ ~and_(+ messages.c.type.in_(_DETACHED_COMPLETION_TYPES),+ func.coalesce(+ func.json_extract(messages.c.metadata_json, "$.detached"),+ 0,+ )+ == 1,+ ),).order_by(transcript_order_value().desc(), messages.c.id.desc()).limit(1)@@ -581,13 +587,11 @@ def fork_source_state(fork: dict[str, Any] | None) -> ForkSourceState:)has_terminal_agent_output_after_anchor = (latest_after_anchor_author == "agent"- and (- latest_after_anchor_type in TERMINAL_AGENT_OUTPUT_TYPES- or is_backend_failure_notification(- latest_after_anchor_type,- latest_after_anchor_metadata,- )+ and activity_role_for(+ latest_after_anchor_type,+ latest_after_anchor_metadata,)+ == "terminal")has_input_turn_after_anchor = (conn.execute(@@ -614,8 +618,8 @@ def fork_source_state(fork: dict[str, Any] | None) -> ForkSourceState:has_messages_after_anchor=latest_after_anchor is not None,has_terminal_agent_output_after_anchor=has_terminal_agent_output_after_anchor,has_input_turn_after_anchor=has_input_turn_after_anchor,- anchor_is_backend_failure=is_backend_failure_notification(- anchor["type"],+ anchor_activity_role=activity_role_for(+ str(anchor["type"] or "").strip(),_load_metadata(anchor["metadata_json"]),),)diff --git a/storage/agent_activity_service.py b/storage/agent_activity_service.pyindex 040a0418b..d9b4e5701 100644--- a/storage/agent_activity_service.py+++ b/storage/agent_activity_service.py@@ -42,7 +42,12 @@ from sqlalchemy import func, selectfrom core.backend_failure import is_backend_failure_notificationfrom storage import agent_events_service, messages_servicefrom storage.models import message_deliveries, session_turns-from vibe.message_types import spec_for, types_with+from vibe.message_types import (+ activity_role_for,+ is_detached_completion,+ spec_for,+ types_with,+)# Bound the scan. The Chat retains ~300 recent messages and pages older on# demand; covering the most-recent MESSAGE_SCAN_LIMIT transcript messages (and@@ -61,6 +66,7 @@ _TRANSCRIPT_ACTIVITY_TYPES = tuple(for message_type in types_with("transcript")if spec_for(message_type)["activityRole"] != "none"or spec_for(message_type)["terminalWhenEvents"]+ or spec_for(message_type)["detachedCompletion"])_NON_TRANSCRIPT_START_TYPES = tuple(message_type@@ -134,11 +140,10 @@ def _is_terminal(msg_type: Any, author: Any, metadata: Optional[dict]) -> bool:"""if author != "agent":return False- spec = spec_for(msg_type if isinstance(msg_type, str) else "")- return (- spec["activityRole"] == "terminal"- or (metadata or {}).get("event") in spec["terminalWhenEvents"]- )+ return activity_role_for(+ msg_type if isinstance(msg_type, str) else "",+ metadata,+ ) == "terminal"def _outcome_status(terminal_outcome: Any) -> str:@@ -177,8 +182,9 @@ _PHASE_RANK = {"turn_start": 0,"activity": 1,"boundary": 2,- "terminal": 3,- "ignore": 4,+ "detached_completion": 3,+ "terminal": 4,+ "ignore": 5,}@@ -236,6 +242,7 @@ def _timeline(conn, session_id: str, *, include_text: bool) -> list[dict[str, Anmessage_deliveries.c.message_id,message_deliveries.c.id.label("delivery_id"),message_deliveries.c.materialized_at,+ session_turns.c.id.label("turn_id"),session_turns.c.initial_delivery_id,session_turns.c.started_at,session_turns.c.created_at.label("turn_created_at"),@@ -263,10 +270,18 @@ def _timeline(conn, session_id: str, *, include_text: bool) -> list[dict[str, Anmtype = msg.get("type")author = msg.get("author")metadata = msg.get("metadata") or {}- activity_role = spec_for(mtype if isinstance(mtype, str) else "")["activityRole"]+ activity_role = activity_role_for(+ mtype if isinstance(mtype, str) else "",+ metadata,+ )accepted_role = accepted_roles.get(str(msg.get("id") or ""))if _is_terminal(mtype, author, metadata):kind = "terminal"+ elif is_detached_completion(+ mtype if isinstance(mtype, str) else "",+ metadata,+ ):+ kind = "detached_completion"elif activity_role == "turn_start":kind = ("turn_start"@@ -303,6 +318,12 @@ def _timeline(conn, session_id: str, *, include_text: bool) -> list[dict[str, An"kind": kind,"id": msg.get("id"),"mtype": mtype,+ "turn_id": str(+ metadata.get("turn_id")+ or (accepted_role or {}).get("turn_id")+ or ""+ ).strip()+ or None,"is_transcript": bool(spec_for(mtype if isinstance(mtype, str) else "")["transcript"]),@@ -313,7 +334,11 @@ def _timeline(conn, session_id: str, *, include_text: bool) -> list[dict[str, An# rather than the marker itself; ``terminal_status`` is resolved here so# ``notify`` failure/normal is decided with its metadata in hand."is_silent": False,- "terminal_status": _terminal_status(mtype, metadata) if kind == "terminal" else None,+ "terminal_status": (+ _terminal_status(mtype, metadata)+ if kind in {"boundary", "detached_completion", "terminal"}+ else None+ ),})# Bound events to the scanned message window: in a long session the 500-message@@ -342,6 +367,7 @@ def _timeline(conn, session_id: str, *, include_text: bool) -> list[dict[str, An"kind": "terminal","id": event.get("id"),"mtype": "silent_terminal",+ "turn_id": str(event.get("turn_id") or "").strip() or None,"row_kind": "turn_terminal","text": None,"is_silent": True,@@ -362,6 +388,7 @@ def _timeline(conn, session_id: str, *, include_text: bool) -> list[dict[str, An"kind": "activity","id": event.get("id"),"mtype": "tool_call",+ "turn_id": str(event.get("turn_id") or "").strip() or None,"row_kind": "tool_call","text": event.get("text") if include_text else None,}@@ -392,6 +419,7 @@ def _timeline(conn, session_id: str, *, include_text: bool) -> list[dict[str, An"kind": "terminal","id": f"turn-terminal:{turn['id']}","mtype": "turn_terminal",+ "turn_id": str(turn["id"] or "").strip() or None,"row_kind": "turn_terminal","text": None,"is_silent": True,@@ -414,6 +442,7 @@ def _make_group(started_iso: Optional[str],ended_iso: Optional[str],include_rows: bool,+ turn_id: Optional[str],) -> dict[str, Any]:started = started_iso or pending[0]["created_at"]group: dict[str, Any] = {@@ -432,6 +461,7 @@ def _make_group("started_at": started,"ended_at": ended_iso,"duration_ms": _duration_ms(started, ended_iso),+ "_turn_id": turn_id,}if include_rows:group["rows"] = [@@ -450,6 +480,7 @@ def _build_groups(items: list[dict[str, Any]], *, include_rows: bool) -> list[digroups: list[dict[str, Any]] = []pending: list[dict[str, Any]] = []turn_start_iso: Optional[str] = None+ turn_id: Optional[str] = None# Id of the most recent transcript-visible boundary (turn_start OR terminal). An# interrupted turn anchors BACKWARD to this — the boundary immediately before its# activity (its trigger) — so its chip is positioned by its OWN chronology and@@ -458,6 +489,8 @@ def _build_groups(items: list[dict[str, Any]], *, include_rows: bool) -> list[difor item in items:kind = item["kind"]if kind == "activity":+ if turn_id is None:+ turn_id = item.get("turn_id")pending.append(item)elif kind == "turn_start":if pending:@@ -474,10 +507,12 @@ def _build_groups(items: list[dict[str, Any]], *, include_rows: bool) -> list[distarted_iso=turn_start_iso,ended_iso=pending[-1]["created_at"],include_rows=include_rows,+ turn_id=turn_id,))pending = []turn_start_iso = item["created_at"]+ turn_id = item.get("turn_id")if item["is_transcript"]:last_boundary_id = item["id"]elif kind == "boundary":@@ -485,13 +520,14 @@ def _build_groups(items: list[dict[str, Any]], *, include_rows: bool) -> list[digroups.append(_make_group(pending,- status="done",+ status=item["terminal_status"],anchor_id=item["id"],anchor_position="before",open_turn=False,started_iso=turn_start_iso,ended_iso=item["created_at"],include_rows=include_rows,+ turn_id=turn_id,))pending = []@@ -501,6 +537,74 @@ def _build_groups(items: list[dict[str, Any]], *, include_rows: bool) -> list[diturn_start_iso = item["created_at"]if item["is_transcript"]:last_boundary_id = item["id"]+ elif kind == "detached_completion":+ owner_turn_id = item.get("turn_id")+ pending_turn_ids = {+ pending_item.get("turn_id")+ for pending_item in pending+ if pending_item.get("turn_id")+ }+ has_unresolved_origin = any(+ group["status"] == "interrupted" for group in groups+ )+ provenance_matches_pending = bool(+ owner_turn_id+ and (+ (+ owner_turn_id == turn_id+ and pending_turn_ids <= {owner_turn_id}+ )+ or (turn_id is None and pending_turn_ids == {owner_turn_id})+ )+ )+ owns_pending = bool(+ provenance_matches_pending+ # Recovered legacy activity may have no provenance on either side.+ # Only the sole unresolved group is safe to close chronologically.+ or (+ owner_turn_id is None+ and turn_id is None+ and not pending_turn_ids+ and not has_unresolved_origin+ )+ )+ if pending and owns_pending:+ groups.append(+ _make_group(+ pending,+ status=item["terminal_status"],+ anchor_id=item["id"],+ anchor_position="before",+ open_turn=False,+ started_iso=turn_start_iso,+ ended_iso=item["created_at"],+ include_rows=include_rows,+ turn_id=owner_turn_id,+ )+ )+ pending = []+ turn_start_iso = None+ turn_id = None+ elif owner_turn_id:+ # A later Turn may already have interrupted the origin group. Repair+ # that group by provenance without consuming the newer Turn's rows.+ for group in reversed(groups):+ if (+ group.get("_turn_id") == owner_turn_id+ and group["status"] == "interrupted"+ ):+ group.update(+ status=item["terminal_status"],+ anchor_message_id=item["id"],+ anchor_position="before",+ open=False,+ ended_at=item["created_at"],+ duration_ms=_duration_ms(+ group.get("started_at"),+ item["created_at"],+ ),+ )+ breakelif kind == "terminal":if pending:# A silent marker is invisible in the transcript, so its DONE group@@ -522,10 +626,12 @@ def _build_groups(items: list[dict[str, Any]], *, include_rows: bool) -> list[distarted_iso=turn_start_iso,ended_iso=item["created_at"],include_rows=include_rows,+ turn_id=turn_id,))pending = []turn_start_iso = None+ turn_id = None# 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).@@ -546,8 +652,11 @@ def _build_groups(items: list[dict[str, Any]], *, include_rows: bool) -> list[distarted_iso=turn_start_iso,ended_iso=pending[-1]["created_at"],include_rows=include_rows,+ turn_id=turn_id,))+ for group in groups:+ group.pop("_turn_id", None)return groupsdiff --git a/storage/background.py b/storage/background.pyindex a508df1f3..2f0b2429d 100644--- a/storage/background.py+++ b/storage/background.py@@ -59,6 +59,7 @@ from storage.session_reclaim import (DEFINITION_AGENT_BINDING_REVISION_KEY,SESSION_SETTINGS_SNAPSHOT_KEY,)+from vibe.message_types import types_withlogger = logging.getLogger(__name__)@@ -67,6 +68,7 @@ RUN_LAST_ACTIVITY_METADATA_KEY = "last_activity_at"TASK_RETIREMENT_SCHEDULE_CONSUMED = "schedule_consumed"TASK_RETIREMENT_SCHEDULE_MISSED = "schedule_missed"TASK_SCHEDULE_CONSUMED_METADATA_KEY = "task_schedule_consumed"+_VISIBLE_MESSAGE_RECEIPT_TYPES = types_with("inboxPreview")def task_schedule_generation(metadata: Any) -> Optional[dict[str, str]]:@@ -5437,7 +5439,7 @@ class SQLiteBackgroundTaskStore:select(literal(1)).select_from(messages).where(messages.c.session_id == child.c.session_id)- .where(messages.c.type == "result")+ .where(messages.c.type.in_(_VISIBLE_MESSAGE_RECEIPT_TYPES)).where(func.json_valid(messages.c.metadata_json) == 1).where(or_(@@ -5576,8 +5578,9 @@ class SQLiteBackgroundTaskStore:their own, while a receipt in suppressed background history proves persistence,not visibility. This read joins the child and target Session and projects thestate the notice lane actually needs: queued/running is pending, succeeded with- effective delivery evidence is sent, and every other terminal outcome releases- the notice as failed. All three lookups are primary-key probes in one statement.+ an inbox-preview Message receipt or native delivery evidence is sent, and every+ other terminal outcome releases the notice as failed. All three lookups are+ primary-key probes in one statement.``None`` means "no callback exists for this run" (no target session), whichis different from a callback whose status column is empty — a target withdiff --git a/storage/messages_service.py b/storage/messages_service.pyindex 5f93896d1..523f32d07 100644--- a/storage/messages_service.py+++ b/storage/messages_service.py@@ -1091,6 +1091,7 @@ INBOX_ACTIVITY_TYPES = types_with("inboxActivity")TRANSCRIPT_TYPES = types_with("transcript")_INBOX_PREVIEW_TYPES = types_with("inboxPreview")_INBOX_SETTLES_REPLY_TYPES = types_with("inboxSettlesReply")+_DETACHED_COMPLETION_TYPES = types_with("detachedCompletion")_UNREAD_TYPES = types_with("unread")@@ -1264,6 +1265,7 @@ def list_inbox_sessions(types: Optional[tuple[str, ...]] = None,conversation_only: bool = False,input_turn_only: bool = False,+ active_turn_reply_only: bool = False,) -> Any:msg = messages.alias()order_value = transcript_order_value(msg)@@ -1281,6 +1283,14 @@ def list_inbox_sessions(query = query.where(msg.c.author == author)if types is not None:query = query.where(msg.c.type.in_(types))+ if active_turn_reply_only:+ query = query.where(+ ~and_(+ msg.c.type.in_(_DETACHED_COMPLETION_TYPES),+ func.coalesce(func.json_extract(msg.c.metadata_json, "$.detached"), 0)+ == 1,+ )+ )if input_turn_only:query = query.where(or_(@@ -1301,8 +1311,16 @@ def list_inbox_sessions(last_author = _latest_message_value("author", conversation_only=True)preview_id = _latest_message_value("id", types=_INBOX_PREVIEW_TYPES)preview_at = _latest_message_value(None, types=_INBOX_PREVIEW_TYPES)- last_terminal_id = _latest_message_value("id", types=_INBOX_SETTLES_REPLY_TYPES)- last_terminal_at = _latest_message_value(None, types=_INBOX_SETTLES_REPLY_TYPES)+ last_terminal_id = _latest_message_value(+ "id",+ types=_INBOX_SETTLES_REPLY_TYPES,+ active_turn_reply_only=True,+ )+ last_terminal_at = _latest_message_value(+ None,+ types=_INBOX_SETTLES_REPLY_TYPES,+ active_turn_reply_only=True,+ )last_turn_terminal_id = (select(session_turns.c.id).where(diff --git a/tests/test_agent_activity_service.py b/tests/test_agent_activity_service.pyindex 04f82d79e..9f1b4ca16 100644--- a/tests/test_agent_activity_service.py+++ b/tests/test_agent_activity_service.py@@ -91,6 +91,7 @@ def _evt(text,event_type="tool_call",metadata=None,+ turn_id=None,):conn.execute(agent_events.insert().values(@@ -104,6 +105,7 @@ def _evt(content_json=json.dumps({"kind": "tool_call", "text": text}),metadata_json=json.dumps(metadata or {}),source="agent",+ turn_id=turn_id,created_at=created_at,updated_at=created_at,)@@ -713,6 +715,309 @@ def test_nonterminal_output_completes_prior_activity_and_anchors_later_work(assert groups[1]["open"] is False+ ("message_type", "metadata", "expected_status"),+ [+ ("result", {"detached": True}, "done"),+ ("error", {"detached": True}, "failed"),+ (+ "notify",+ {"detached": True, "event": "backend_failure"},+ "failed",+ ),+ ],+)+def test_detached_completion_closes_only_activity_with_matching_turn_provenance(+ isolated_state,+ message_type,+ metadata,+ expected_status,+):+ engine = create_sqlite_engine()+ sid = f"ses_detached_{message_type}"+ 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:00Z",+ text="primary",+ source="user",+ metadata={"turn_id": "turn-background"},+ )+ _evt(+ conn,+ scope,+ sid,+ eid="e_before",+ created_at="2026-06-01T10:00:01Z",+ text="background work",+ turn_id="turn-background",+ )+ _msg(+ conn,+ scope,+ sid,+ mid="m_detached",+ mtype=message_type,+ author="agent",+ created_at="2026-06-01T10:00:02Z",+ text="background completed",+ metadata={**metadata, "turn_id": "turn-background"},+ )++ with engine.connect() as conn:+ groups = agent_activity_service.list_turn_groups(conn, session_id=sid)[+ "groups"+ ]++ assert [group["status"] for group in groups] == [expected_status]+ assert groups[0]["anchor_message_id"] == "m_detached"+ assert groups[0]["anchor_position"] == "before"+++ ("message_type", "metadata", "expected_status"),+ [+ ("result", {"detached": True}, "done"),+ ("error", {"detached": True}, "failed"),+ (+ "notify",+ {"detached": True, "event": "backend_failure"},+ "failed",+ ),+ ],+)+def test_provenance_free_detached_completion_closes_unambiguous_activity(+ isolated_state,+ message_type,+ metadata,+ expected_status,+):+ engine = create_sqlite_engine()+ sid = f"ses_detached_unowned_{message_type}"+ 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:00Z",+ text="legacy activity",+ source="user",+ )+ _evt(+ conn,+ scope,+ sid,+ eid="e_before",+ created_at="2026-06-01T10:00:01Z",+ text="recovered background work",+ )+ _msg(+ conn,+ scope,+ sid,+ mid="m_detached",+ mtype=message_type,+ author="agent",+ created_at="2026-06-01T10:00:02Z",+ text="background completed",+ metadata=metadata,+ )++ with engine.connect() as conn:+ groups = agent_activity_service.list_turn_groups(conn, session_id=sid)[+ "groups"+ ]++ assert [group["status"] for group in groups] == [expected_status]+ assert groups[0]["anchor_message_id"] == "m_detached"+ assert groups[0]["anchor_position"] == "before"+ assert groups[0]["open"] is False+++def test_provenance_free_detached_completion_does_not_guess_after_interleaving(+ isolated_state,+):+ engine = create_sqlite_engine()+ sid = "ses_detached_unowned_interleaved"+ 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:00Z",+ text="background origin",+ source="user",+ )+ _evt(+ conn,+ scope,+ sid,+ eid="e_background",+ created_at="2026-06-01T10:00:01Z",+ text="background work",+ )+ _msg(+ conn,+ scope,+ sid,+ mid="m_u2",+ mtype="user",+ author="user",+ created_at="2026-06-01T10:00:02Z",+ text="new turn",+ source="user",+ )+ _evt(+ conn,+ scope,+ sid,+ eid="e_current",+ created_at="2026-06-01T10:00:03Z",+ text="current work",+ )+ _msg(+ conn,+ scope,+ sid,+ mid="m_detached",+ mtype="error",+ author="agent",+ created_at="2026-06-01T10:00:04Z",+ text="background failed",+ metadata={"detached": True},+ )+ _msg(+ conn,+ scope,+ sid,+ mid="m_current_result",+ mtype="result",+ author="agent",+ created_at="2026-06-01T10:00:05Z",+ text="current completed",+ )++ with engine.connect() as conn:+ groups = agent_activity_service.list_turn_groups(conn, session_id=sid)[+ "groups"+ ]++ assert [group["status"] for group in groups] == ["interrupted", "done"]+ assert groups[0]["anchor_message_id"] == "m_u1"+ assert groups[1]["anchor_message_id"] == "m_current_result"+++ ("message_type", "metadata", "expected_status"),+ [+ ("result", {"detached": True}, "done"),+ ("error", {"detached": True}, "failed"),+ (+ "notify",+ {"detached": True, "event": "backend_failure"},+ "failed",+ ),+ ],+)+def test_detached_completion_repairs_its_origin_without_consuming_newer_activity(+ isolated_state,+ message_type,+ metadata,+ expected_status,+):+ engine = create_sqlite_engine()+ sid = f"ses_detached_interleaved_{message_type}"+ 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:00Z",+ text="background origin",+ source="user",+ metadata={"turn_id": "turn-background"},+ )+ _evt(+ conn,+ scope,+ sid,+ eid="e_background",+ created_at="2026-06-01T10:00:01Z",+ text="background work",+ turn_id="turn-background",+ )+ _msg(+ conn,+ scope,+ sid,+ mid="m_u2",+ mtype="user",+ author="user",+ created_at="2026-06-01T10:00:02Z",+ text="new turn",+ source="user",+ metadata={"turn_id": "turn-current"},+ )+ _evt(+ conn,+ scope,+ sid,+ eid="e_current",+ created_at="2026-06-01T10:00:03Z",+ text="current work",+ turn_id="turn-current",+ )+ _msg(+ conn,+ scope,+ sid,+ mid="m_detached",+ mtype=message_type,+ author="agent",+ created_at="2026-06-01T10:00:04Z",+ text="background completed",+ metadata={**metadata, "turn_id": "turn-background"},+ )+ _msg(+ conn,+ scope,+ sid,+ mid="m_current_result",+ mtype="result",+ author="agent",+ created_at="2026-06-01T10:00:05Z",+ text="current completed",+ metadata={"turn_id": "turn-current"},+ )++ with engine.connect() as conn:+ groups = agent_activity_service.list_turn_groups(conn, session_id=sid)[+ "groups"+ ]++ assert [group["status"] for group in groups] == [expected_status, "done"]+ assert groups[0]["anchor_message_id"] == "m_detached"+ assert groups[1]["anchor_message_id"] == "m_current_result"++def test_get_turn_group_unknown_id_returns_none(isolated_state):engine = create_sqlite_engine()sid = "ses_none"diff --git a/tests/test_harness_failure_visibility.py b/tests/test_harness_failure_visibility.pyindex 010e2e974..14e6313c6 100644--- a/tests/test_harness_failure_visibility.py+++ b/tests/test_harness_failure_visibility.py@@ -6491,11 +6491,12 @@ def _callback_session()-def _persist_callback_result(+def _persist_callback_receipt(sqlite_store,run_id: str,*,text: str,+ message_type: str = "result",delivery_suppressed: bool = False,) -> None:"""Materialize the durable message receipt that a callback success requires."""@@ -6510,7 +6511,7 @@ def _persist_callback_result(platform="avibe",author="agent",source="agent",- message_type="result",+ message_type=message_type,text=text,metadata={"run_id": run_id,@@ -6551,7 +6552,11 @@ def _notice_drain_service(tmp_path: Path, sqlite_store, requests) -> tuple[Any,return service, delivered-def test_failed_run_with_callback_delivers_exactly_one_message(tmp_path: Path) -> None:[email protected]("receipt_type", ["result", "output"])+def test_failed_run_with_callback_delivers_exactly_one_message(+ tmp_path: Path,+ receipt_type: str,+) -> None:"""Owed by the plan (corrected 2026-07-29): a pending callback IS the delivery.A failed run carrying ``callback_session_id`` gets a user-visible result turn@@ -6618,7 +6623,12 @@ def test_failed_run_with_callback_delivers_exactly_one_message(tmp_path: Path) -terminal_status="succeeded",)assert delivered_callback["terminal_transition"]- _persist_callback_result(sqlite, callback.id, text="callback delivered")+ _persist_callback_receipt(+ sqlite,+ callback.id,+ text="callback delivered",+ message_type=receipt_type,+ )sqlite.update_owed_failure_notice("run-cb", next_attempt_at=None)asyncio.run(service._drain_failure_notices())notice = sqlite.owed_failure_notice("run-cb")@@ -6900,7 +6910,7 @@ def test_owed_notice_takes_over_when_callback_receipt_is_in_a_hidden_session(terminal_status="succeeded",)assert recorded["terminal_transition"]- _persist_callback_result(sqlite, callback.id, text="hidden callback body")+ _persist_callback_receipt(sqlite, callback.id, text="hidden callback body")assert sqlite.run_callback_state("run-cb-hidden") == "failed"service, delivered = _notice_drain_service(tmp_path, sqlite, requests)@@ -6941,7 +6951,7 @@ def test_suppressed_callback_history_is_not_visible_delivery_evidence(text="local callback history",terminal_status="succeeded",)- _persist_callback_result(+ _persist_callback_receipt(sqlite,callback.id,text="local callback history",@@ -7606,7 +7616,7 @@ def test_hfr_440_one_sibling_callback_suppresses_the_whole_turn_fallback(text="shared Turn callback delivered",terminal_status="succeeded",)- _persist_callback_result(sqlite, callback.id, text="shared Turn callback delivered")+ _persist_callback_receipt(sqlite, callback.id, text="shared Turn callback delivered")service, delivered = _notice_drain_service(tmp_path, sqlite, requests)import core.scheduled_tasks as scheduled_tasks@@ -7806,7 +7816,7 @@ def test_hfr_449_canceled_parent_keeps_armed_callback_evidence(text="callback delivered",terminal_status="succeeded",)- _persist_callback_result(sqlite, callback.id, text="callback delivered")+ _persist_callback_receipt(sqlite, callback.id, text="callback delivered")assert sqlite.cancel_run(parent.id)return parent, callbackdiff --git a/tests/test_message_dispatcher_result_fallback.py b/tests/test_message_dispatcher_result_fallback.pyindex ff922cbf0..0e388c61d 100644--- a/tests/test_message_dispatcher_result_fallback.py+++ b/tests/test_message_dispatcher_result_fallback.py@@ -12,6 +12,7 @@ from core.message_dispatcher import ConsolidatedMessageDispatcherfrom core.delivery_evidence import DeliveryEvidencefrom core.message_output import (MessageOutput,+ communication_type_for_output,contained_teardown_output_for,stop_output_for,)@@ -146,6 +147,38 @@ class _StubController:class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):+ def test_visible_output_type_follows_turn_authority(self):+ self.assertEqual(+ communication_type_for_output(+ "result",+ MessageOutput(completes_turn=False),+ ),+ "output",+ )+ self.assertEqual(+ communication_type_for_output(+ "result",+ MessageOutput(completes_turn=True, detached=True),+ is_error=True,+ ),+ "error",+ )+ self.assertEqual(+ communication_type_for_output(+ "result",+ MessageOutput(completes_turn=True, detached=True),+ ),+ "result",+ )+ self.assertEqual(+ communication_type_for_output(+ "result",+ MessageOutput(completes_turn=True),+ is_error=True,+ ),+ "error",+ )+def test_terminal_snapshot_elects_fallback_after_excluding_canceled_runs(self):controller = _StubController(platform="slack")dispatcher = ConsolidatedMessageDispatcher(controller)@@ -398,6 +431,7 @@ class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):controller.agent_service.release_runtime_turn.assert_not_called()turn_chunk.assert_not_awaited()persist.assert_called_once()+ self.assertEqual(persist.call_args.args[1], "result")self.assertEqual(persist.call_args.kwargs["metadata"]["activity_id"], "task-1")self.assertTrue(persist.call_args.kwargs["metadata"]["detached"])diff --git a/tests/test_message_mirror.py b/tests/test_message_mirror.pyindex 218ee3249..6233ba06e 100644--- a/tests/test_message_mirror.py+++ b/tests/test_message_mirror.py@@ -203,6 +203,43 @@ def test_agent_output_provenance_is_hidden_metadata_and_deduplicated(isolated_st}+def test_visible_replay_promotes_suppressed_nonterminal_output(isolated_state):+ native_message_id = "agent-output:codex:run-1:primary"+ suppressed = MessageContext(+ user_id="U_alice",+ channel_id="C_general",+ platform="slack",+ platform_specific={"suppress_delivery": True},+ )+ visible = MessageContext(+ user_id="U_alice",+ channel_id="C_general",+ platform="slack",+ )++ local = persist_agent_message(+ suppressed,+ "output",+ "local history",+ metadata={"delivery_suppressed": True, "run_id": "run-1"},+ native_message_id=native_message_id,+ )+ promoted = persist_agent_message(+ visible,+ "output",+ "visible reply",+ metadata={"run_id": "run-1"},+ native_message_id=native_message_id,+ )++ assert local is not None+ assert promoted is not None+ assert promoted["id"] == local["id"]+ assert promoted["type"] == "output"+ assert promoted["text"] == "visible reply"+ assert promoted["metadata"] == {"run_id": "run-1"}++def test_persist_agent_reuses_cached_sqlite_engine(isolated_state, monkeypatch):import storage.db as sqlite_dbdiff --git a/tests/test_message_type_catalog.py b/tests/test_message_type_catalog.pyindex 90264bdb2..093a7a28f 100644--- a/tests/test_message_type_catalog.py+++ b/tests/test_message_type_catalog.py@@ -11,8 +11,10 @@ from storage import agent_activity_service, messages_servicefrom storage.models import messagesfrom vibe.message_identity import INPUT_TURN_AUTHOR_TYPESfrom vibe.message_types import (+ activity_role_for,build_partial_index_predicate,input_author_type_pairs,+ is_detached_completion,spec_for,types_with,)@@ -178,6 +180,7 @@ def test_annotation_catalog_contract_is_explicit() -> None:"inboxPreview": False,"inboxSettlesReply": False,"activityRole": "none",+ "detachedCompletion": False,"terminalWhenEvents": (),"unread": False,"webPush": False,@@ -193,6 +196,7 @@ def test_activity_fetch_and_terminal_semantics_match_current_service() -> None:for message_type in _catalog_types()if spec_for(message_type)["activityRole"] != "none"or spec_for(message_type)["terminalWhenEvents"]+ or spec_for(message_type)["detachedCompletion"]}expected_relevant = ("user",@@ -210,19 +214,21 @@ def test_activity_fetch_and_terminal_semantics_match_current_service() -> None:for message_type in _catalog_types():spec = spec_for(message_type)for event in (None, "backend_failure", "other"):- metadata = {"event": event} if event is not None else {}- legacy_expected = (- message_type in {"result", "error", "silent"}- or (message_type == "notify" and event == "backend_failure")- )- assert (- spec["activityRole"] == "terminal"- or event in spec["terminalWhenEvents"]- ) is legacy_expected- assert (- agent_activity_service._is_terminal(message_type, "agent", metadata)- is legacy_expected- )+ for detached in (False, True):+ metadata = {"detached": detached}+ if event is not None:+ metadata["event"] = event+ legacy_expected = (+ message_type in {"result", "error"}+ or (message_type == "notify" and event == "backend_failure")+ ) and not (detached and spec["detachedCompletion"])+ assert (+ activity_role_for(message_type, metadata) == "terminal"+ ) is legacy_expected+ assert (+ agent_activity_service._is_terminal(message_type, "agent", metadata)+ is legacy_expected+ )assert not agent_activity_service._is_terminal(" result ", "agent", {})assert (agent_activity_service._terminal_status(@@ -233,6 +239,17 @@ def test_activity_fetch_and_terminal_semantics_match_current_service() -> None:)+def test_detached_completion_classification_is_catalog_owned() -> None:+ assert types_with("detachedCompletion") == ("result", "notify", "error")+ for message_type in _catalog_types():+ spec = spec_for(message_type)+ expected = "none" if spec["detachedCompletion"] else spec["activityRole"]+ assert activity_role_for(message_type, {"detached": True}) == expected+ assert is_detached_completion(message_type, {"detached": True}) is bool(+ spec["detachedCompletion"]+ )++def test_web_push_candidate_exact_and_unread_sets_match_current_service() -> None:expected_candidates = {"result", "error", "notify"}expected_unread = {"result"}diff --git a/tests/test_messages_service.py b/tests/test_messages_service.pyindex 07616adaa..22e141a2f 100644--- a/tests/test_messages_service.py+++ b/tests/test_messages_service.py@@ -4,6 +4,7 @@ regress: pagination cursor and the ``mark_session_read`` boundary check.from __future__ import annotations+import jsonimport sysimport timefrom pathlib import Path@@ -1286,6 +1287,7 @@ def _insert_msg(msg_type=None,msg_id=None,delivered_at=None,+ metadata=None,):"""Direct insert so the test controls created_at (second-resolution) + read_at.@@ -1305,7 +1307,7 @@ def _insert_msg(type=resolved_type,content_text=text,content_json="{}",- metadata_json="{}",+ metadata_json=json.dumps(metadata or {}),created_at=created_at,updated_at=created_at,delivered_at=delivered_at,@@ -1504,6 +1506,32 @@ def test_list_inbox_sessions_awaiting_reply_persists_through_agent_stream(isolatassert row2["preview_text"] == "R2"+def test_detached_completion_does_not_settle_current_inbox_reply(isolated_state):+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_scope(conn)+ _seed_titled_session(conn, scope_id, "ses_detached", "Detached")+ _insert_msg(conn, scope_id, "ses_detached", "agent", "R1", "2026-05-30T10:01:00Z")+ _insert_msg(conn, scope_id, "ses_detached", "user", "new turn", "2026-05-30T10:05:00Z")+ _insert_msg(+ conn,+ scope_id,+ "ses_detached",+ "agent",+ "background completed",+ "2026-05-30T10:06:00Z",+ read=False,+ metadata={"detached": True, "activity_id": "background-1"},+ )++ with engine.connect() as conn:+ row = messages_service.list_inbox_sessions(conn, platform="avibe")["sessions"][0]++ assert row["preview_text"] == "background completed"+ assert row["unread_count"] == 1+ assert row["replied"] is True++def test_list_inbox_sessions_silent_completion_clears_awaiting(isolated_state):"""A terminal Turn snapshot settles Inbox state without a pseudo Message."""engine = create_sqlite_engine()diff --git a/tests/test_session_fork.py b/tests/test_session_fork.pyindex a020ae27b..dd98789ef 100644--- a/tests/test_session_fork.py+++ b/tests/test_session_fork.py@@ -1375,7 +1375,45 @@ def test_fork_source_state_treats_backend_failure_notify_anchor_as_terminal(engine.dispose()-def test_fork_source_state_treats_backend_failure_notify_after_anchor_as_terminal(+def test_fork_source_state_keeps_detached_failure_outside_current_turn(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ from config import paths+ from storage.importer import ensure_sqlite_state++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ ensure_sqlite_state()+ db_path = paths.get_sqlite_state_path()+ source_id = _seed_source_session(db_path, tmp_path)+ engine = create_sqlite_engine(db_path)+ try:+ with engine.begin() as conn:+ row = conn.execute(select(agent_sessions).where(agent_sessions.c.id == source_id)).mappings().one()+ notify = messages_service.append(+ conn,+ scope_id=row["scope_id"],+ session_id=source_id,+ platform="avibe",+ author="agent",+ message_type="notify",+ text="Background run failed",+ metadata={+ "event": "backend_failure",+ "failure_id": "failure_detached",+ "detached": True,+ },+ )++ fork = {"source_session_id": source_id, "source_message_id": notify["id"]}+ state = fork_source_state(fork)++ assert state.anchor_is_terminal_agent_output is False+ assert fork_anchor_is_terminal_agent_output(fork) is False+ finally:+ engine.dispose()+++def test_fork_source_state_keeps_terminal_visible_past_later_detached_completion(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:from config import paths@@ -1408,6 +1446,16 @@ def test_fork_source_state_treats_backend_failure_notify_after_anchor_as_terminatext="Codex backend failed",metadata={"event": "backend_failure", "failure_id": "failure_1"},)+ messages_service.append(+ conn,+ scope_id=row["scope_id"],+ session_id=source_id,+ platform="avibe",+ author="agent",+ message_type="result",+ text="Older background work completed",+ metadata={"detached": True, "turn_id": "turn-background"},+ )state = fork_source_state({"source_session_id": source_id, "source_message_id": user["id"]})diff --git a/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx b/ui/src/components/workbench/ChatArchivedReadOnly.test.tsxindex c8dde128c..9fa79cc1a 100644--- a/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx+++ b/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx@@ -257,6 +257,39 @@ describe('archived Agent display names', () => {});});+describe('nonterminal Agent output', () => {+ it('keeps Agent identity but uses the muted boundary presentation', () => {+ for (const message of [+ { ...agentWithQuickReplies(), type: 'output', content: {} },+ { ...agentWithQuickReplies(), type: 'result', content: {}, metadata: { detached: true } },+ ] as WorkbenchMessage[]) {+ const markup = render(+ <MessageRow message={message} session={session()} messageFontSize={13} />,+ );++ expect(markup).toContain('lucide-bot');+ expect(markup).toContain('bg-foreground/[0.03]');+ expect(markup).not.toContain('bg-mint/[0.09]');+ }+ });++ it('keeps a detached backend failure in the status presentation', () => {+ const message = {+ ...agentWithQuickReplies(),+ type: 'notify',+ content: {},+ metadata: { detached: true, event: 'backend_failure' },+ } as WorkbenchMessage;+ const markup = render(+ <MessageRow message={message} session={session()} messageFontSize={13} />,+ );++ expect(markup).toContain('lucide-bell');+ expect(markup).toContain('bg-gold/[0.08]');+ expect(markup).not.toContain('lucide-bot');+ });+});+// ── Codex review #3 (ChatPage.tsx:2540) ───────────────────────────────────────// The previous round kept the Show Page toggle and the Share control on the// theory that the store already refuses archived mutations. That is thediff --git a/ui/src/components/workbench/ChatPage.hydration.test.tsx b/ui/src/components/workbench/ChatPage.hydration.test.tsxindex b68bea4ec..64a5b3081 100644--- a/ui/src/components/workbench/ChatPage.hydration.test.tsx+++ b/ui/src/components/workbench/ChatPage.hydration.test.tsx@@ -9,6 +9,8 @@ const mocks = vi.hoisted(() => ({connectWorkbenchEvents: vi.fn(),getCachedSessionDraft: vi.fn(),getSession: vi.fn(),+ getSessionActivity: vi.fn(),+ getSessionActivityGroup: vi.fn(),getSessionBootstrap: vi.fn(),getTurnState: vi.fn(),getWorkbenchPrefs: vi.fn(),@@ -19,6 +21,8 @@ const mocks = vi.hoisted(() => ({events: null as null | {onConnected: () => void;onAuthorizationChanged: (data: { resource_kinds?: string[] }) => void;+ onMessageNew: (message: ReturnType<typeof projectedMessage>) => void;+ onTurnStart: (data: { session_id: string }) => void;onTurnEnd: (data: { session_id: string }) => void;},}));@@ -190,6 +194,8 @@ describe('ChatPage transcript hydration', () => {});mocks.api.getCachedSessionDraft.mockReturnValue(null);mocks.api.getSession.mockReturnValue(sessionRow.promise);+ mocks.api.getSessionActivity.mockResolvedValue({ groups: [] });+ mocks.api.getSessionActivityGroup.mockResolvedValue({});mocks.api.getSessionBootstrap.mockReturnValue(bootstrap.promise);mocks.api.getTurnState.mockResolvedValue(idleTurnState);mocks.api.getWorkbenchPrefs.mockResolvedValue({});@@ -363,4 +369,52 @@ describe('ChatPage transcript hydration', () => {await waitFor(() => expect(screen.getByText('chat.transcriptEmpty')).toBeTruthy());expect(screen.queryByText(projected.text)).toBeNull();});++ it('refreshes detached Activity without settling the current live generation', async () => {+ mocks.api.getSession.mockResolvedValue({ id: 'session-new' });+ mocks.api.getSessionBootstrap.mockResolvedValue({+ ...bootstrapPayload('session-new'),+ config: { ui: { show_agent_activity: true } },+ });++ render(+ <MemoryRouter initialEntries={['/chat/session-new']}>+ <Routes>+ <Route path="/chat/:sessionId" element={<ChatPage />} />+ </Routes>+ </MemoryRouter>,+ );++ await waitFor(() => expect(mocks.api.getSessionActivity).toHaveBeenCalled());+ mocks.api.getSessionActivity.mockClear();+ const detachedRefresh = deferred<{ groups: never[] }>();+ mocks.api.getSessionActivity.mockReturnValue(detachedRefresh.promise);++ act(() => {+ mocks.events?.onTurnStart({ session_id: 'session-new' });+ mocks.events?.onMessageNew({+ ...projectedMessage('active-step-1', 'first active step'),+ author: 'agent',+ type: 'assistant',+ source: 'agent',+ });+ mocks.events?.onMessageNew({+ ...projectedMessage('detached-result', 'background completed'),+ author: 'agent',+ type: 'result',+ source: 'agent',+ metadata: { detached: true, activity_id: 'background-1' },+ });+ mocks.events?.onMessageNew({+ ...projectedMessage('active-step-2', 'second active step'),+ author: 'agent',+ type: 'assistant',+ source: 'agent',+ });+ });++ await waitFor(() => expect(mocks.api.getSessionActivity).toHaveBeenCalledTimes(1));+ expect(screen.getByText('first active step')).toBeTruthy();+ expect(screen.getByText('second active step')).toBeTruthy();+ });});diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex 960fb8933..fb17ff68a 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -17,7 +17,7 @@ import { apiFetch } from '../../lib/apiFetch';import { readChatViewMode, writeChatViewMode } from '../../lib/chatViewMemory';import { normalizeChatMessageFontSize } from '../../lib/chatDisplay';import { annotationStandIn, annotationTitleKey, readAnnotationView } from '../../lib/annotationView';-import { isTerminalAgentMessage, isTranscriptMessage } from '../../lib/chatMessageTypes';+import { isTerminalAgentMessage, isTranscriptMessage, shouldRefreshAgentActivityForMessage } from '../../lib/chatMessageTypes';import { chatRowKind, drawsEmptyBodyPlaceholder, isAgentAuthored } from '../../lib/chatRowKind';import { useIosKeyboardInset } from '../../lib/useIosKeyboardInset';import { isProxyMediaUrl } from '../../lib/mediaProxy';@@ -1548,11 +1548,10 @@ export const ChatPage: React.FC = () => {// Harness live rows can precede read-side provenance enrichment. Pull// the enriched REST row so trigger/source chips update without reload.if (needsHarnessProvenanceReconcile(msg)) void reconcile();- // Agent Activity: a terminal reply settles the turn → mark the generation- // settled and rebuild groups from storage (chip, rows, status, duration all- // come from the endpoint, never the lossy live buffer).- if (showAgentActivityRef.current && isTerminalAgentMessage(msg)) {- dispatchLive({ type: 'settle' });+ // Rebuild durable Activity groups for a phase boundary, terminal reply, or+ // detached completion. Only a terminal reply owns this live generation.+ if (showAgentActivityRef.current && shouldRefreshAgentActivityForMessage(msg)) {+ if (isTerminalAgentMessage(msg)) dispatchLive({ type: 'settle' });scheduleActivityRefresh(workingRef.current);}// Don't clear ``working`` from a result row here: with the queue, a@@ -4306,6 +4305,7 @@ export const MessageRow = memo(function MessageRow({const row = chatRowKind(message);const isNotify = row.kind === 'notify';const isAgent = row.kind === 'agent';+ const isBoundary = row.kind === 'boundary';// ...and, separately, who wrote it. Only the agent's own words may carry the// agent-authored Markdown affordances, and its reverse annotation is still its// own words even though a different card draws it.@@ -4554,15 +4554,16 @@ export const MessageRow = memo(function MessageRow({);}- // ----- Agent / system: left-aligned bubble with avatar + name header ------ const name = isAgent+ // ----- Agent / boundary / system: left-aligned bubble with identity header -----+ const agentIdentity = isAgent || isBoundary;+ const name = agentIdentity? agentDisplayName || session.agent_name || message.author_name: message.author_name;return (<div data-message-id={message.id} className={rowClass('justify-start')}><div className="group/message flex max-w-[min(92%,860px)] flex-col items-start gap-1"><div className="flex items-center gap-2 px-0.5">- <RoleAvatar tone={isAgent ? 'mint' : 'muted'}>{isAgent ? <Bot /> : <Info />}</RoleAvatar>+ <RoleAvatar tone={isAgent ? 'mint' : 'muted'}>{agentIdentity ? <Bot /> : <Info />}</RoleAvatar>{name && <span className="text-[11px] font-medium text-muted">{name}</span>}</div>{bodyNode || attachmentsNode ? (diff --git a/ui/src/lib/chatMessageTypes.test.ts b/ui/src/lib/chatMessageTypes.test.tsindex d2b119384..3f345cedf 100644--- a/ui/src/lib/chatMessageTypes.test.ts+++ b/ui/src/lib/chatMessageTypes.test.ts@@ -1,6 +1,14 @@import { describe, expect, it } from 'vitest';-import { isNotifyMessageType, isTerminalAgentMessage, isTranscriptMessage } from './chatMessageTypes';+import {+ isBoundaryMessage,+ isDetachedCompletionMessage,+ isNotifyMessageType,+ isTerminalAgentMessage,+ isTranscriptMessage,+ shouldRefreshAgentActivityForMessage,+} from './chatMessageTypes';+import { messageTypeNames, specFor } from './messageTypes';describe('isTranscriptMessage', () => {it('shows the rows the transcript has always shown, and hides process log', () => {@@ -71,4 +79,55 @@ describe('isTerminalAgentMessage', () => {).toBe(false);expect(isTerminalAgentMessage({ author: 'user', type: 'result' })).toBe(false);});++ it('never lets a detached legacy result settle the active turn', () => {+ for (const type of ['result', 'error', 'notify']) {+ expect(isTerminalAgentMessage({ author: 'agent', type, metadata: { detached: true } }), type).toBe(false);+ }+ });+});++describe('isBoundaryMessage', () => {+ it('recognizes current output rows and legacy detached results', () => {+ expect(isBoundaryMessage({ type: 'output' })).toBe(true);+ expect(isBoundaryMessage({ type: 'result', metadata: { detached: true } })).toBe(true);+ expect(isBoundaryMessage({ type: 'result' })).toBe(false);+ });++ it('keeps every status-rendered type in its notification family when detached', () => {+ const statusTypes = messageTypeNames().filter((type) => specFor(type).render === 'status');+ expect(statusTypes.length).toBeGreaterThan(0);+ for (const type of statusTypes) {+ expect(isBoundaryMessage({ type, metadata: { detached: true } }), type).toBe(false);+ }+ });+});++describe('isDetachedCompletionMessage', () => {+ it('classifies lifecycle provenance independently from presentation', () => {+ for (const type of ['result', 'error', 'notify']) {+ expect(isDetachedCompletionMessage({ type, metadata: { detached: true } }), type).toBe(true);+ }+ expect(isDetachedCompletionMessage({ type: 'output', metadata: { detached: true } })).toBe(false);+ expect(isDetachedCompletionMessage({ type: 'result' })).toBe(false);+ });+});++describe('shouldRefreshAgentActivityForMessage', () => {+ it('refreshes Activity groups for terminal replies and detached completions', () => {+ for (const type of ['output', 'result', 'error']) {+ expect(shouldRefreshAgentActivityForMessage({ author: 'agent', type }), type).toBe(true);+ }+ for (const type of ['result', 'error', 'notify']) {+ expect(+ shouldRefreshAgentActivityForMessage({ author: 'agent', type, metadata: { detached: true } }),+ type,+ ).toBe(true);+ }+ });++ it('ignores non-boundary process and user rows', () => {+ expect(shouldRefreshAgentActivityForMessage({ author: 'agent', type: 'assistant' })).toBe(false);+ expect(shouldRefreshAgentActivityForMessage({ author: 'user', type: 'result' })).toBe(false);+ });});diff --git a/ui/src/lib/chatMessageTypes.ts b/ui/src/lib/chatMessageTypes.tsindex 310b127c7..9e89c10a2 100644--- a/ui/src/lib/chatMessageTypes.ts+++ b/ui/src/lib/chatMessageTypes.ts@@ -21,19 +21,53 @@ export const isNotifyMessageType = (type: string): boolean => specFor(type).rendexport const isTranscriptMessage = (message: { type: string }): boolean => specFor(message.type).transcript;type TerminalMessageCandidate = {- author: string;type: string;metadata?: Record<string, unknown> | null;};+export const isDetachedCompletionMessage = (message: TerminalMessageCandidate): boolean => {+ const spec = specFor(message.type);+ return message.metadata?.detached === true && spec.detachedCompletion;+};++const activityRoleForMessage = (+ message: TerminalMessageCandidate,+): ReturnType<typeof specFor>['activityRole'] => {+ const spec = specFor(message.type);+ if (isDetachedCompletionMessage(message)) return 'none';+ const event = message.metadata?.event;+ if (typeof event === 'string' && spec.terminalWhenEvents.includes(event)) return 'terminal';+ return spec.activityRole;+};++// A phase boundary uses the muted Agent presentation. The detached-result case+// keeps rows written by older servers on that presentation; notification types+// remain status pills even when detached.+export const isBoundaryMessage = (message: TerminalMessageCandidate): boolean => {+ const spec = specFor(message.type);+ return spec.render === 'agent' && (+ activityRoleForMessage(message) === 'boundary' || isDetachedCompletionMessage(message)+ );+};++type TerminalAgentMessageCandidate = TerminalMessageCandidate & { author: string };+// A terminal reply the TRANSCRIPT shows: the catalog's terminal activity role// intersected with transcript visibility (``silent`` is terminal for activity// bookkeeping but never rendered), plus the conditional terminals that only settle// a turn for specific metadata events (``notify`` + ``backend_failure``).-export const isTerminalAgentMessage = (message: TerminalMessageCandidate): boolean => {+export const isTerminalAgentMessage = (message: TerminalAgentMessageCandidate): boolean => {if (message.author !== 'agent') return false;const spec = specFor(message.type);- if (spec.transcript && spec.activityRole === 'terminal') return true;- const event = message.metadata?.event;- return typeof event === 'string' && spec.terminalWhenEvents.includes(event);+ return spec.transcript && activityRoleForMessage(message) === 'terminal';+};++// Terminal replies, nonterminal phase boundaries, and detached completions all+// require a durable Activity refresh. Only terminal replies settle the live Turn.+export const shouldRefreshAgentActivityForMessage = (+ message: TerminalAgentMessageCandidate,+): boolean => {+ if (message.author !== 'agent') return false;+ const role = activityRoleForMessage(message);+ return role === 'boundary' || role === 'terminal' || isDetachedCompletionMessage(message);};diff --git a/ui/src/lib/chatRowKind.test.ts b/ui/src/lib/chatRowKind.test.tsindex b95bbc07c..de46b8602 100644--- a/ui/src/lib/chatRowKind.test.ts+++ b/ui/src/lib/chatRowKind.test.ts@@ -26,6 +26,7 @@ describe('chatRowKind', () => {it('keeps the pre-existing role families intact', () => {expect(row({ author: 'user', source: 'user' })).toEqual({ kind: 'user' });expect(row({ author: 'agent', type: 'result' })).toEqual({ kind: 'agent' });+ expect(row({ author: 'agent', type: 'output' })).toEqual({ kind: 'boundary' });expect(row({ author: 'system', type: 'user' })).toEqual({ kind: 'system' });expect(row({ author: 'harness', source: 'harness', type: 'harness' })).toEqual({ kind: 'harness' });expect(row({ author: 'harness', source: 'harness', type: 'vault' })).toEqual({ kind: 'harness' });@@ -33,6 +34,16 @@ describe('chatRowKind', () => {expect(row({ author: 'agent', type: 'error' })).toEqual({ kind: 'notify' });});+ it('keeps legacy detached results in the boundary family', () => {+ expect(row({ author: 'agent', type: 'result', metadata: { detached: true } })).toEqual({ kind: 'boundary' });+ });++ it('keeps detached failure notifications in the notify family', () => {+ for (const type of ['notify', 'error']) {+ expect(row({ author: 'agent', type, metadata: { detached: true } }), type).toEqual({ kind: 'notify' });+ }+ });+it('draws an annotation card for both directions', () => {expect(chatRowKind(FORWARD)).toEqual({kind: 'annotation',@@ -126,6 +137,7 @@ describe('drawsEmptyBodyPlaceholder', () => {it('fills an ordinary empty bubble', () => {expect(drawsEmptyBodyPlaceholder({ kind: 'user' }, false)).toBe(true);expect(drawsEmptyBodyPlaceholder({ kind: 'agent' }, false)).toBe(true);+ expect(drawsEmptyBodyPlaceholder({ kind: 'boundary' }, false)).toBe(true);expect(drawsEmptyBodyPlaceholder({ kind: 'harness' }, false)).toBe(true);});diff --git a/ui/src/lib/chatRowKind.ts b/ui/src/lib/chatRowKind.tsindex 4fb1a5085..d0e03f47c 100644--- a/ui/src/lib/chatRowKind.ts+++ b/ui/src/lib/chatRowKind.ts@@ -18,7 +18,7 @@// ``author`` and ``source`` still decide among the ROLE families below, which is// what they legitimately describe. What they no longer do is decide whether a// typed row is that type.-import { isNotifyMessageType } from './chatMessageTypes';+import { isBoundaryMessage, isNotifyMessageType } from './chatMessageTypes';import { readAnnotationView, type AnnotationView } from './annotationView';// A row typed ``annotation`` whose display record is unreadable. Every writer of@@ -32,6 +32,7 @@ const UNREADABLE_ANNOTATION: AnnotationView = { direction: 'agent', resolved: fa// family and then disagree with a second lookup about what is in it.export type ChatRowKind =| { kind: 'annotation'; annotation: AnnotationView }+ | { kind: 'boundary' }| { kind: 'notify' }| { kind: 'agent' }| { kind: 'system' }@@ -43,6 +44,7 @@ type ChatRowFields = {author: string;source?: string | null;content?: unknown;+ metadata?: Record<string, unknown> | null;};export function chatRowKind(message: ChatRowFields): ChatRowKind {@@ -52,6 +54,7 @@ export function chatRowKind(message: ChatRowFields): ChatRowKind {if (message.type === 'annotation') {return { kind: 'annotation', annotation: readAnnotationView(message.content) ?? UNREADABLE_ANNOTATION };}+ if (isBoundaryMessage(message)) return { kind: 'boundary' };// Runtime notifications and legacy error rows are compact status pills, not// Agent-authored answers.if (isNotifyMessageType(message.type)) return { kind: 'notify' };diff --git a/ui/src/lib/messageTypes.test.ts b/ui/src/lib/messageTypes.test.tsindex 5affe1421..d3a2f7599 100644--- a/ui/src/lib/messageTypes.test.ts+++ b/ui/src/lib/messageTypes.test.ts@@ -80,6 +80,7 @@ type TerminalCandidate = { author: string; type: string; metadata?: Record<strinconst wasTerminalAgentMessage = (message: TerminalCandidate): boolean =>message.author === 'agent' &&+ message.metadata?.detached !== true &&(message.type === 'result' ||message.type === 'error' ||(message.type === 'notify' && message.metadata?.event === 'backend_failure'));@@ -134,6 +135,8 @@ describe('catalog-derived predicates match the communication-record boundary', ({ event: 'backend_failure' },{ event: 'activity_completed' },{ event: 42 },+ { detached: true },+ { event: 'backend_failure', detached: true },];for (const type of PROBE_TYPES) {for (const author of ['agent', 'user', 'system', 'harness']) {diff --git a/ui/src/lib/vaultRequestPlacement.test.ts b/ui/src/lib/vaultRequestPlacement.test.tsindex ec8012cfe..bb5a5db0f 100644--- a/ui/src/lib/vaultRequestPlacement.test.ts+++ b/ui/src/lib/vaultRequestPlacement.test.ts@@ -121,6 +121,57 @@ describe('placeVaultProvisionRequests', () => {expect(placed.byMessageId.has('agent-later')).toBe(false);});+ it('keeps a nonterminal Agent output eligible to own its request card', () => {+ const output = { ...message('agent-output', '2026-07-30T10:00:10Z'), type: 'output' };+ const placed = placeVaultProvisionRequests(+ [output],+ [request('p', 'provision', '2026-07-30T10:00:00Z', output.id)],+ );++ expect(placed.byMessageId.get(output.id)?.map((item) => item.id)).toEqual(['p']);+ expect(placed.unanchored).toEqual([]);+ });++ it('does not infer an unrelated detached completion as the request owner', () => {+ const detached = {+ ...message('background-completion', '2026-07-30T10:00:05Z'),+ metadata: { detached: true, turn_id: 'turn-background' },+ };+ const current = {+ ...message('current-reply', '2026-07-30T10:00:10Z'),+ metadata: { turn_id: 'turn-current' },+ };+ const placed = placeVaultProvisionRequests(+ [message('user-before', '2026-07-30T09:59:00Z', 'user'), detached, current],+ [request('p', 'provision', '2026-07-30T10:00:00Z')],+ );++ expect(placed.byMessageId.has(detached.id)).toBe(false);+ expect(placed.byMessageId.get(current.id)?.map((item) => item.id)).toEqual(['p']);+ });++ it('accepts a detached completion only when request provenance matches', () => {+ const detached = {+ ...message('background-completion', '2026-07-30T10:00:05Z'),+ metadata: { detached: true, turn_id: 'turn-background' },+ };+ const placed = placeVaultProvisionRequests(+ [detached],+ [+ request(+ 'p',+ 'provision',+ '2026-07-30T10:00:00Z',+ null,+ { turn_id: 'turn-background' },+ ),+ ],+ );++ expect(placed.byMessageId.get(detached.id)?.map((item) => item.id)).toEqual(['p']);+ expect(placed.unanchored).toEqual([]);+ });+it('uses the message id clock when the reply shares the request second', () => {const sameSecondMessages = [orderedMessage('11111111', '2026-07-30T10:00:00.100Z', '2026-07-30T10:00:00Z', 'user'),diff --git a/ui/src/lib/vaultRequestPlacement.ts b/ui/src/lib/vaultRequestPlacement.tsindex 2d4809559..fb39fc03c 100644--- a/ui/src/lib/vaultRequestPlacement.ts+++ b/ui/src/lib/vaultRequestPlacement.ts@@ -1,4 +1,5 @@import type { VaultRequest, WorkbenchMessage } from '@/context/ApiContext';+import { isDetachedCompletionMessage } from '@/lib/chatMessageTypes';import { chatRowKind } from '@/lib/chatRowKind';import { specFor } from '@/lib/messageTypes';import { messageOrderTimeMs, timestampOrderTimeMs, transcriptOrderTimeMs } from '@/lib/transcriptOrder';@@ -21,8 +22,13 @@ export type VaultProvisionPlacement = {unanchored: VaultRequest[];};-function isAgentReply(message: WorkbenchMessage): boolean {- return chatRowKind(message).kind === 'agent';+function isAgentReplyWithExplicitProvenance(message: WorkbenchMessage): boolean {+ const kind = chatRowKind(message).kind;+ return kind === 'agent' || kind === 'boundary';+}++function isInferredAgentReply(message: WorkbenchMessage): boolean {+ return !isDetachedCompletionMessage(message) && isAgentReplyWithExplicitProvenance(message);}function isInputTurn(message: WorkbenchMessage): boolean {@@ -86,7 +92,7 @@ function inferReplyWithinTurn(// An anchorless request belongs only to the turn that created it. Once a// later user/harness input starts another turn, no later Agent row can own it.if (isInputTurn(message)) return undefined;- if (isAgentReply(message)) return message;+ if (isInferredAgentReply(message)) return message;}return undefined;}@@ -117,7 +123,7 @@ function inferReplyFromSourceMessage(? replyBeforeRequest: undefined;}- if (!isAgentReply(message)) continue;+ if (!isInferredAgentReply(message)) continue;if (Number.isNaN(requestTime) || messageOrderTimeMs(message) >= requestTime) return message;// Some legacy request rows point at an older input even though the request// was persisted after that turn's reply. Keep it as a fallback only when@@ -142,7 +148,7 @@ export function placeVaultProvisionRequests(const byMessageId = new Map<string, VaultRequest[]>();const unanchored: VaultRequest[] = [];const messagesById = new Map(messages.map((message) => [message.id, message]));- const agentMessages = messages.filter(isAgentReply);+ const agentMessages = messages.filter(isAgentReplyWithExplicitProvenance);// Window coverage follows transcript-entry order. A queued row can be authored// before the request but only enter the visible transcript after it, so its// message-id clock must not make a trimmed request look loaded.@@ -155,11 +161,13 @@ export function placeVaultProvisionRequests(? request.message_id: null;const explicit = explicitReplyId ? messagesById.get(explicitReplyId) : undefined;- if (explicit && isAgentReply(explicit)) {+ if (explicit && isAgentReplyWithExplicitProvenance(explicit)) {appendRequest(byMessageId, explicit.id, request);continue;}- const explicitReplyUnresolved = Boolean(explicitReplyId && (!explicit || !isAgentReply(explicit)));+ const explicitReplyUnresolved = Boolean(+ explicitReplyId && (!explicit || !isAgentReplyWithExplicitProvenance(explicit))+ );const requestTime = timestampOrderTimeMs(request.created_at);const sameTurn = agentMessages.find((message) => sameRequestTurn(request, message));diff --git a/vibe/message_types.json b/vibe/message_types.jsonindex c45a77de6..86df7d338 100644--- a/vibe/message_types.json+++ b/vibe/message_types.json@@ -7,6 +7,7 @@"inboxPreview": false,"inboxSettlesReply": false,"activityRole": "none",+ "detachedCompletion": false,"terminalWhenEvents": [],"unread": false,"webPush": false,@@ -63,6 +64,7 @@"inboxPreview": true,"inboxSettlesReply": true,"activityRole": "terminal",+ "detachedCompletion": true,"unread": true,"webPush": true,"render": "agent"@@ -72,6 +74,7 @@"inboxActivity": true,"inboxPreview": true,"inboxSettlesReply": true,+ "detachedCompletion": true,"terminalWhenEvents": ["backend_failure"],@@ -93,6 +96,7 @@"inboxPreview": true,"inboxSettlesReply": true,"activityRole": "terminal",+ "detachedCompletion": true,"webPush": true,"render": "status"},diff --git a/vibe/message_types.py b/vibe/message_types.pyindex 2c420086a..7fa5d1eee 100644--- a/vibe/message_types.py+++ b/vibe/message_types.py@@ -13,6 +13,7 @@ _BOOL_PROPERTIES = {"inboxActivity","inboxPreview","inboxSettlesReply",+ "detachedCompletion","unread","webPush",}@@ -133,6 +134,28 @@ def spec_for(message_type: str) -> Mapping[str, Any]:return _TYPE_SPECS.get(message_type, _DEFAULT_SPEC)+def is_detached_completion(message_type: str, metadata: Any = None) -> bool:+ """Whether a row reports completion of work outside the current Turn."""++ values = metadata if isinstance(metadata, Mapping) else {}+ return bool(+ values.get("detached") is True+ and spec_for(message_type)["detachedCompletion"]+ )+++def activity_role_for(message_type: str, metadata: Any = None) -> str:+ """Resolve one row's role in the current Turn's Activity timeline."""++ spec = spec_for(message_type)+ values = metadata if isinstance(metadata, Mapping) else {}+ if is_detached_completion(message_type, values):+ return "none"+ if values.get("event") in spec["terminalWhenEvents"]:+ return "terminal"+ return str(spec["activityRole"])++def _sql_quote(value: str) -> str:return "'" + value.replace("'", "''") + "'"@@ -169,8 +192,10 @@ def build_partial_index_predicate(index_name: str) -> str:__all__ = [+ "activity_role_for","build_partial_index_predicate","input_author_type_pairs",+ "is_detached_completion","spec_for","types_with",]