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(claude): preserve delayed steering ownership (#1227)
Call Whiteaf4e425f9cef
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.pyindex ed50f52a2..063d0e8fd 100644--- a/core/handlers/session_handler.py+++ b/core/handlers/session_handler.py@@ -1470,8 +1470,9 @@ class SessionHandler(BaseHandler):agent_system_prompt=agent_system_prompt,)- # Create extra_args for CLI passthrough (fallback for model)- extra_args: Dict[str, str | None] = {}+ # Echo native input frames so the long-lived receiver can correlate+ # accepted steering with Claude's actual input consumption.+ extra_args: Dict[str, str | None] = {"replay-user-messages": None}if runtime_model:extra_args["model"] = runtime_modeldiff --git a/core/message_dispatcher.py b/core/message_dispatcher.pyindex dc75014e2..6d92f0fd8 100644--- a/core/message_dispatcher.py+++ b/core/message_dispatcher.py@@ -1510,6 +1510,8 @@ class ConsolidatedMessageDispatcher:log_label: str = "agent run terminal result",) -> None:semantics = output_semantics or MessageOutput(completes_turn=True)+ if not semantics.records_run_output:+ returnrequire_confirmation = semantics.requires_delivery_for_run_settlementrun_ids = self._terminal_agent_run_ids(context, semantics)if not run_ids:@@ -2039,13 +2041,18 @@ class ConsolidatedMessageDispatcher:else:terminal_reason = "failed"- if canonical_type == "result":+ visible_output_type = canonical_type in {"result", "output"}+ if visible_output_type:if not current_runtime_turn and not output_semantics.detached:- logger.info("Dropping stale result emit for superseded runtime turn in %s", self._get_session_key(context))+ logger.info(+ "Dropping stale %s emit for superseded runtime turn in %s",+ canonical_type,+ self._get_session_key(context),+ )return Noneraw_text = textenhanced = None- if canonical_type == "result" and level != "silent":+ if visible_output_type and level != "silent":quick_replies_on = getattr(self.controller.config, "reply_enhancements", True)enhanced = process_reply(raw_text, include_quick_replies=quick_replies_on)text = enhanced.visible_text@@ -2184,7 +2191,7 @@ class ConsolidatedMessageDispatcher:# raw text would surface markup in the inbox preview / chat transcript# that was never shown. Computed once here and reused for delivery below.persist_text = text- if canonical_type == "result":+ if visible_output_type:persist_text = enhanced.text if enhanced.text.strip() else textaccepted_message = None@@ -2331,8 +2338,8 @@ class ConsolidatedMessageDispatcher:try:recorded_text = self._fold_footer(persist_text, result_footer)persisted_output = None- if canonical_type == "result":- result_type = "error" if is_error else "result"+ if visible_output_type:+ result_type = "error" if is_error else canonical_typeif target_context.platform == "avibe":background_enhanced = process_reply(raw_text,@@ -2468,7 +2475,7 @@ class ConsolidatedMessageDispatcher:delivery.error_stage = STAGE_STREAMreturn message_id- if canonical_type == "result":+ if visible_output_type:try:primary_message_id: Optional[str] = Nonescheduled_anchor_message_id: Optional[str] = None@@ -2738,7 +2745,7 @@ 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 "result"+ 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``)@@ -2848,7 +2855,7 @@ class ConsolidatedMessageDispatcher:context,text=display_text,message_id=primary_message_id,- kind="result",+ kind=canonical_type,completes_turn=mutates_turn_lifecycle,)elif mutates_turn_lifecycle:diff --git a/core/message_mirror.py b/core/message_mirror.pyindex 3addb8b3b..60fc173ab 100644--- a/core/message_mirror.py+++ b/core/message_mirror.py@@ -253,6 +253,7 @@ _AGENT_TYPE_BY_CANONICAL = {# (result-only) don't count it, while it stays in the transcript/inbox."error": "error","notify": "notify",+ "output": "output","assistant": "assistant","system": "assistant",}diff --git a/core/message_output.py b/core/message_output.pyindex 42eb046f4..0b468f67b 100644--- a/core/message_output.py+++ b/core/message_output.py@@ -58,6 +58,7 @@ class MessageOutput:sequence: int | None = Nonerun_id: str | None = Nonerun_ids: tuple[str, ...] = ()+ records_run_output: bool = Truerequires_delivery_for_run_settlement: bool = Falsesettled_by: str | None = Nonemetadata: Mapping[str, Any] = field(default_factory=dict)diff --git a/core/services/session_fork.py b/core/services/session_fork.pyindex 328b8ea4e..aa4ad772d 100644--- a/core/services/session_fork.py+++ b/core/services/session_fork.py@@ -30,8 +30,9 @@ TERMINAL_AGENT_OUTPUT_TYPES = {}SOURCE_PROGRESS_AGENT_OUTPUT_TYPES = {message_type- for message_type in types_with("activityRole")+ for message_type in set(types_with("activityRole")) | set(types_with("transcript"))if spec_for(message_type)["activityRole"] in {"activity", "terminal"}+ or spec_for(message_type)["render"] == "agent"}ACTIVE_SOURCE_RUN_STATUSES = ("pending", "queued", "processing", "running")INPUT_TURN_MESSAGE_TYPES = tuple(message_type for _, message_type in INPUT_TURN_AUTHOR_TYPES)diff --git a/core/session_turns.py b/core/session_turns.pyindex e58726d93..6c626c573 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -7317,7 +7317,10 @@ class SessionTurnManager:platform="avibe",author="harness",source="harness",- message_type="harness",+ # This durable row owns the backend-started Turn for+ # Stop/FSM/history, but it is not a user instruction+ # and must not render as a chat bubble.+ message_type="agent_initiated",text=trigger_text,metadata={"source": "agent_initiated",diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.pyindex 5764da6a7..f94a3e23f 100644--- a/modules/agents/claude_agent.py+++ b/modules/agents/claude_agent.py@@ -2,7 +2,8 @@ import asyncioimport loggingimport osimport uuid-from typing import Any, Callable, Optional+from dataclasses import dataclass+from typing import Any, Callable, Literal, Optionalfrom core.agent_auth_service import classify_auth_errorfrom core.backend_failure import backend_failure_notification_output, emit_backend_failure@@ -53,6 +54,13 @@ from modules.im import MessageContextlogger = logging.getLogger(__name__)+@dataclass+class _ClaudeInputReceipt:+ text: str+ kind: Literal["primary", "steer"]+ state: Literal["writing", "accepted", "unknown"] = "writing"++class ClaudeAgent(BaseAgent):"""Existing Claude Code integration extracted into an agent backend."""@@ -85,10 +93,9 @@ class ClaudeAgent(BaseAgent):self._pending_requests: dict[str, list[AgentRequest]] = {}self._steering_locks: dict[str, asyncio.Lock] = {}self._steering_generations: dict[str, int] = {}- self._steering_terminal_barriers: dict[str, list[str]] = {}- self._steering_response_generations: dict[str, int] = {}+ self._native_input_receipts: dict[str, list[_ClaudeInputReceipt]] = {}self._ambiguous_primary_results: dict[str, object] = {}- self._ambiguous_input_shutdowns: set[str] = set()+ self._steering_input_shutdowns: set[str] = set()self._ambiguous_interrupts: set[str] = set()self._steering_closing: set[str] = set()self._steering_writers: set[str] = set()@@ -192,9 +199,19 @@ class ClaudeAgent(BaseAgent):# Prepare message with file attachment info if presentmessage = self._prepare_message_with_files(request)+ input_receipt = self._register_native_input(+ runtime_session_key,+ message,+ kind="primary",+ )mark_backend_dispatch_attempted(request.context)- await client.query(message, session_id=runtime_session_key)+ try:+ await client.query(message, session_id=runtime_session_key)+ except (Exception, asyncio.CancelledError):+ self._remove_native_input_receipt(runtime_session_key, input_receipt)+ raise+ input_receipt.state = "accepted"if (runtime_session_key not in self.receiver_tasksor self.receiver_tasks[runtime_session_key].done()@@ -806,7 +823,7 @@ class ClaudeAgent(BaseAgent):or receiver_task.done()or composite_key not in active_sessionsor composite_key in self._steering_closing_keys()- or composite_key in self._ambiguous_input_shutdown_keys()+ or composite_key in self._steering_input_shutdown_keys()or composite_key in self._ambiguous_interrupt_keys()):return None@@ -865,16 +882,13 @@ class ClaudeAgent(BaseAgent):generations = getattr(self, "_steering_generations", None)if generations is not None:generations.pop(composite_key, None)- barriers = getattr(self, "_steering_terminal_barriers", None)- if barriers is not None:- barriers.pop(composite_key, None)- response_generations = getattr(self, "_steering_response_generations", None)- if response_generations is not None:- response_generations.pop(composite_key, None)+ receipts = getattr(self, "_native_input_receipts", None)+ if receipts is not None:+ receipts.pop(composite_key, None)ambiguous_results = getattr(self, "_ambiguous_primary_results", None)if ambiguous_results is not None:ambiguous_results.pop(composite_key, None)- input_shutdowns = getattr(self, "_ambiguous_input_shutdowns", None)+ input_shutdowns = getattr(self, "_steering_input_shutdowns", None)if input_shutdowns is not None:input_shutdowns.discard(composite_key)ambiguous_interrupts = getattr(self, "_ambiguous_interrupts", None)@@ -886,75 +900,123 @@ class ClaudeAgent(BaseAgent):def _advance_steering_generation(self,composite_key: str,- *,- barrier: str = "accepted",) -> None:current_generation = self._steering_generation(composite_key)self._steering_generations[composite_key] = current_generation + 1- barriers = getattr(self, "_steering_terminal_barriers", None)- if barriers is None:- barriers = {}- self._steering_terminal_barriers = barriers- barriers.setdefault(composite_key, []).append(barrier)-- def _next_terminal_barrier(self, composite_key: str) -> str | None:- barriers = getattr(self, "_steering_terminal_barriers", None) or {}- pending = barriers.get(composite_key) or []- return pending[0] if pending else None-- def _consume_terminal_barrier(self, composite_key: str) -> str | None:- barriers = getattr(self, "_steering_terminal_barriers", None) or {}- pending = barriers.get(composite_key) or []- if not pending:++ def _register_native_input(+ self,+ composite_key: str,+ text: str,+ *,+ kind: Literal["primary", "steer"],+ ) -> _ClaudeInputReceipt:+ receipt = _ClaudeInputReceipt(text=text, kind=kind)+ self._native_input_receipt_map().setdefault(composite_key, []).append(receipt)+ return receipt++ def _native_input_receipt_map(self) -> dict[str, list[_ClaudeInputReceipt]]:+ receipts = getattr(self, "_native_input_receipts", None)+ if receipts is None:+ receipts = {}+ self._native_input_receipts = receipts+ return receipts++ def _remove_native_input_receipt(+ self,+ composite_key: str,+ receipt: _ClaudeInputReceipt,+ ) -> None:+ receipt_map = self._native_input_receipt_map()+ receipts = receipt_map.get(composite_key) or []+ for index, candidate in enumerate(receipts):+ if candidate is receipt:+ receipts.pop(index)+ break+ if not receipts:+ receipt_map.pop(composite_key, None)++ @staticmethod+ def _native_user_input_text(message) -> str | None:+ if getattr(message, "parent_tool_use_id", None) is not None:+ return None+ content = getattr(message, "content", None)+ if isinstance(content, str):+ return content+ if isinstance(content, list):+ texts = [+ block.text+ for block in content+ if isinstance(block, TextBlock) and isinstance(block.text, str)+ ]+ if len(texts) == len(content):+ return "\n".join(texts)+ return None++ def _observe_native_user_input(+ self,+ composite_key: str,+ message,+ ) -> _ClaudeInputReceipt | None:+ text = self._native_user_input_text(message)+ if text is None:return None- barrier = pending.pop(0)- if not pending:- barriers.pop(composite_key, None)- return barrier+ receipt_map = self._native_input_receipt_map()+ receipts = receipt_map.get(composite_key) or []+ for index, receipt in enumerate(receipts):+ if receipt.text != text:+ continue+ receipts.pop(index)+ if not receipts:+ receipt_map.pop(composite_key, None)+ logger.debug(+ "Observed Claude %s input receipt for %s",+ receipt.kind,+ composite_key,+ )+ return receipt+ return None++ def _pending_steering_input_state(self, composite_key: str) -> str | None:+ for receipt in self._native_input_receipt_map().get(composite_key) or []:+ if receipt.kind == "steer":+ return receipt.state+ return None++ def _discard_completed_primary_input_receipts(self, composite_key: str) -> None:+ receipt_map = self._native_input_receipt_map()+ receipts = receipt_map.get(composite_key) or []+ receipts[:] = [receipt for receipt in receipts if receipt.kind != "primary"]+ if not receipts:+ receipt_map.pop(composite_key, None)++ def _clear_native_input_receipts(self, composite_key: str) -> None:+ self._native_input_receipt_map().pop(composite_key, None)def _terminal_claim_superseded(self,composite_key: str,expected_steering_generation: int,) -> bool:- """Consume a terminal frame that predates a native steer.-- Claude's receiver can deliver a ResultMessage after the steering write,- even when the corresponding AssistantMessage was already emitted. That- result belongs to the steered continuation and must settle the Turn. Only- suppress the accepted barrier when no post-steer assistant response was- observed; this preserves the guard for a buffered pre-steer ResultMessage- without dropping the real steered answer.- """+ """Whether a terminal frame arrived before Claude echoed the steer input."""generation_changed = expected_steering_generation != self._steering_generation(composite_key)- barrier = self._next_terminal_barrier(composite_key)- response_generation = (- getattr(self, "_steering_response_generations", {}) or {}- ).get(composite_key)- if (- barrier == "accepted"- and response_generation == self._steering_generation(composite_key)- ):- self._consume_terminal_barrier(composite_key)- return generation_changed- buffered_terminal = self._consume_terminal_barrier(composite_key) is not None- return generation_changed or buffered_terminal+ return generation_changed or self._pending_steering_input_state(composite_key) is not None@staticmethod- def _ambiguous_steering_input_closer(client):+ def _steering_input_closer(client):end_input = getattr(client, "end_input", None)if callable(end_input):return end_inputend_input = getattr(getattr(client, "_transport", None), "end_input", None)return end_input if callable(end_input) else None- def _ambiguous_input_shutdown_keys(self) -> set[str]:- shutdowns = getattr(self, "_ambiguous_input_shutdowns", None)+ def _steering_input_shutdown_keys(self) -> set[str]:+ shutdowns = getattr(self, "_steering_input_shutdowns", None)if shutdowns is None:shutdowns = set()- self._ambiguous_input_shutdowns = shutdowns+ self._steering_input_shutdowns = shutdownsreturn shutdownsdef _ambiguous_interrupt_keys(self) -> set[str]:@@ -964,23 +1026,25 @@ class ClaudeAgent(BaseAgent):self._ambiguous_interrupts = interruptsreturn interrupts- async def _end_ambiguous_steering_input(+ async def _close_steering_input(self,composite_key: str,end_input,- ) -> None:- """Half-close native input so delivered work finishes before a durable EOF."""- # Once a write is ambiguous, this runtime cannot safely accept another- # steer until its sole receiver reaches a durable terminal boundary.- self._ambiguous_input_shutdown_keys().add(composite_key)+ ) -> str | None:+ """Half-close input after a write whose acceptance is ambiguous."""+ # An ambiguous writer cannot accept another steer safely. EOF bounds the+ # reconciliation while preserving any prompt that reached Claude.+ self._steering_input_shutdown_keys().add(composite_key)try:await end_input()- except Exception: # noqa: BLE001 - the existing receiver keeps ownership+ return None+ except Exception as exc: # noqa: BLE001 - the existing receiver keeps ownershiplogger.warning(- "Failed to half-close ambiguous Claude steering input for %s; preserving the live receiver",+ "Failed to half-close Claude steering input for %s; preserving the live receiver",composite_key,exc_info=True,)+ return str(exc)async def steer_active_turn(self,@@ -998,7 +1062,7 @@ class ClaudeAgent(BaseAgent):or receiver_task.done()or composite_key not in active_sessionsor composite_key in self._steering_closing_keys()- or composite_key in self._ambiguous_input_shutdown_keys()+ or composite_key in self._steering_input_shutdown_keys()or composite_key in self._ambiguous_interrupt_keys()):return steer_result(@@ -1023,25 +1087,27 @@ class ClaudeAgent(BaseAgent):backend=self.name,)primary_request_count = len(primary_requests)- end_input = self._ambiguous_steering_input_closer(client)+ end_input = self._steering_input_closer(client)if end_input is None:return steer_result(SteerOutcome.REFUSED,reason="native_input_reconciliation_unsupported",backend=self.name,)-writers = self._steering_writer_keys()writers.add(composite_key)+ input_receipt = self._register_native_input(+ composite_key,+ request.text,+ kind="steer",+ )try:try:await client.query(request.text, session_id=composite_key)except (asyncio.TimeoutError, TimeoutError) as exc:- self._advance_steering_generation(- composite_key,- barrier="unknown",- )- await self._end_ambiguous_steering_input(+ input_receipt.state = "unknown"+ self._advance_steering_generation(composite_key)+ await self._close_steering_input(composite_key,end_input,)@@ -1067,11 +1133,9 @@ class ClaudeAgent(BaseAgent):"unexpected eof",)):- self._advance_steering_generation(- composite_key,- barrier="unknown",- )- await self._end_ambiguous_steering_input(+ input_receipt.state = "unknown"+ self._advance_steering_generation(composite_key)+ await self._close_steering_input(composite_key,end_input,)@@ -1090,17 +1154,16 @@ class ClaudeAgent(BaseAgent):"process that exited with error",)):+ self._remove_native_input_receipt(composite_key, input_receipt)return steer_result(SteerOutcome.REFUSED,reason="runtime_unavailable",backend=self.name,diagnostic=diagnostic,)- self._advance_steering_generation(- composite_key,- barrier="unknown",- )- await self._end_ambiguous_steering_input(+ input_receipt.state = "unknown"+ self._advance_steering_generation(composite_key)+ await self._close_steering_input(composite_key,end_input,)@@ -1113,8 +1176,7 @@ class ClaudeAgent(BaseAgent):finally:writers.discard(composite_key)- self._advance_steering_generation(composite_key)- if (+ runtime_stable = not (self.claude_sessions.get(composite_key) is not clientor self.receiver_tasks.get(composite_key) is not receiver_taskor receiver_task.done()@@ -1122,12 +1184,28 @@ class ClaudeAgent(BaseAgent):or self._pending_requests.get(composite_key) is not primary_requestsor len(primary_requests) != primary_request_countor primary_requests[0] is not target.agent_request- ):+ )+ if not runtime_stable:+ input_receipt.state = "unknown"+ self._advance_steering_generation(composite_key)+ close_diagnostic = await self._close_steering_input(+ composite_key,+ end_input,+ )+ if close_diagnostic is not None:+ return steer_result(+ SteerOutcome.UNKNOWN,+ reason="native_input_close_failed",+ backend=self.name,+ diagnostic=close_diagnostic,+ )return steer_result(SteerOutcome.UNKNOWN,reason="receiver_generation_changed",backend=self.name,)+ input_receipt.state = "accepted"+ self._advance_steering_generation(composite_key)return steer_result(SteerOutcome.ACCEPTED,backend=self.name,@@ -1281,23 +1359,33 @@ class ClaudeAgent(BaseAgent):message_stream = client.receive_messages().__aiter__()while True:settling_ambiguous_primary = False- terminal_steering_generation = None+ settling_ambiguous_assistant_text = None+ settling_ambiguous_had_foreground_tools = False+ # Capture the steering generation before waiting for the next+ # native frame. A frame already buffered in the SDK must retain+ # the ownership state at the time its receive was started.+ terminal_steering_generation = self._steering_generation(composite_key)try:message = await anext(message_stream)- # Capture ownership at the receive boundary. The receiver may- # yield while it captures session metadata or opens an- # agent-initiated turn; sampling generation later can relabel a- # buffered pre-steer frame as the steered continuation.- terminal_steering_generation = self._steering_generation(composite_key)except StopAsyncIteration:- message = self._ambiguous_primary_results.pop(composite_key, None)- if message is None:+ buffered = self._ambiguous_primary_results.pop(composite_key, None)+ if buffered is None:break+ (+ message,+ settling_ambiguous_assistant_text,+ settling_ambiguous_had_foreground_tools,+ ) = self._unpack_buffered_terminal(buffered)settling_ambiguous_primary = Trueexcept Exception:- message = self._ambiguous_primary_results.pop(composite_key, None)- if message is None:+ buffered = self._ambiguous_primary_results.pop(composite_key, None)+ if buffered is None:raise+ (+ message,+ settling_ambiguous_assistant_text,+ settling_ambiguous_had_foreground_tools,+ ) = self._unpack_buffered_terminal(buffered)settling_ambiguous_primary = Truelogger.warning("Settling buffered Claude primary result after receiver failure for %s",@@ -1310,6 +1398,12 @@ class ClaudeAgent(BaseAgent):current_receiver_task=asyncio.current_task(),preserve_pending_request_state=True,)+ if settling_ambiguous_assistant_text:+ self._last_assistant_text[composite_key] = (+ settling_ambiguous_assistant_text+ )+ if settling_ambiguous_had_foreground_tools:+ self._turns_with_foreground_tools.add(composite_key)try:claude_session_id = self._maybe_capture_session_id(message,@@ -1350,6 +1444,18 @@ class ClaudeAgent(BaseAgent):message_type = self._detect_message_type(message)if message_type not in {"assistant", "result", "system"}:terminal_steering_generation = None+ if message_type == "user":+ async with self._steering_lock(composite_key):+ receipt = self._observe_native_user_input(+ composite_key,+ message,+ )+ if receipt is not None and receipt.kind == "steer":+ await self._retire_primary_phase_on_steer_receipt(+ context,+ composite_key,+ )+ continueformatter = self._get_formatter(context)is_model_refusal_fallback = self._is_model_refusal_fallback_message(message)model_refusal_fallback_notice = (@@ -1437,10 +1543,6 @@ class ClaudeAgent(BaseAgent):if assistant_text:self._detached_assistant_text[composite_key] = assistant_textcontinue- if assistant_text and terminal_steering_generation:- self._steering_response_generations[composite_key] = (- terminal_steering_generation- )async with self._steering_lock(composite_key):if composite_key in self._steering_closing_keys():logger.info(@@ -1456,6 +1558,9 @@ class ClaudeAgent(BaseAgent):terminal_steering_generation,)):+ self._discard_completed_primary_input_receipts(+ composite_key+ )self._suppressed_synthetic_results.add(composite_key)self._suppressed_synthetic_error_text[composite_key] = diagnosticlogger.info(@@ -1463,6 +1568,8 @@ class ClaudeAgent(BaseAgent):composite_key,)continue+ if diagnostic is not None:+ self._clear_native_input_receipts(composite_key)failure_disposition = await self._handle_assistant_terminal_failure(context,composite_key,@@ -1693,6 +1800,9 @@ class ClaudeAgent(BaseAgent):)self._clear_detached_foreground_tool_state(composite_key)continue+ terminal_superseded = False+ superseded_result_text = ""+ superseded_request = Noneasync with self._steering_lock(composite_key):self._pending_assistant_message.pop(composite_key, None)if self._consume_suppressed_synthetic_result(@@ -1704,61 +1814,99 @@ class ClaudeAgent(BaseAgent):self._foreground_tool_use_ids.pop(composite_key, None)self._turns_with_foreground_tools.discard(composite_key)continue+ if not settling_ambiguous_primary:+ await self._emit_buffered_primary_phase(+ context,+ composite_key,+ )if (not settling_ambiguous_primary- and self._next_terminal_barrier(composite_key) == "unknown"+ and self._pending_steering_input_state(composite_key)+ == "unknown"):- self._consume_terminal_barrier(composite_key)- self._ambiguous_primary_results[composite_key] = message+ self._discard_completed_primary_input_receipts(+ composite_key+ )+ self._ambiguous_primary_results[composite_key] = (+ message,+ self._last_assistant_text.get(composite_key),+ composite_key in self._turns_with_foreground_tools,+ )+ self._clear_result_phase_state(composite_key)logger.info("Deferring Claude primary result until ambiguous steering reaches native EOF or a later result for %s",composite_key,)continue- if not settling_ambiguous_primary:- self._ambiguous_primary_results.pop(composite_key, None)- if (- composite_key in self._steering_closing_keys()- or (- not settling_ambiguous_primary- and self._terminal_claim_superseded(- composite_key,- terminal_steering_generation,- )- )- ):+ if composite_key in self._steering_closing_keys():logger.info(- "Ignoring Claude terminal result superseded by steering or teardown for %s",+ "Ignoring Claude terminal result during teardown for %s",composite_key,)continue- failure_disposition = await self._handle_terminal_failure_result(- context,- composite_key,- message,- raw_result_text- or self._last_assistant_text.get(composite_key),+ terminal_superseded = bool(+ not settling_ambiguous_primary+ and self._terminal_claim_superseded(+ composite_key,+ terminal_steering_generation,+ ))- if failure_disposition == "auth":- self._foreground_tool_use_ids.pop(composite_key, None)- self._turns_with_foreground_tools.discard(composite_key)- return- if failure_disposition:- self._foreground_tool_use_ids.pop(composite_key, None)- self._turns_with_foreground_tools.discard(composite_key)- continue+ if terminal_superseded:+ self._discard_completed_primary_input_receipts(+ composite_key+ )+ pending = self._pending_requests.get(composite_key) or []+ superseded_request = pending[0] if pending else None+ superseded_result_text = self._select_terminal_text(+ composite_key,+ raw_result_text,+ )+ else:+ self._clear_native_input_receipts(composite_key)+ failure_disposition = await self._handle_terminal_failure_result(+ context,+ composite_key,+ message,+ raw_result_text+ or self._last_assistant_text.get(composite_key),+ )+ if failure_disposition == "auth":+ self._foreground_tool_use_ids.pop(composite_key, None)+ self._turns_with_foreground_tools.discard(composite_key)+ return+ if failure_disposition:+ self._foreground_tool_use_ids.pop(composite_key, None)+ self._turns_with_foreground_tools.discard(composite_key)+ continue++ # ResultMessage.result already contains the last+ # AssistantMessage, so only the terminal owner emits it.+ pending_request = self._pop_pending_request(composite_key)+ output_activities = self._request_activities(pending_request)+ output_activity = output_activities[-1] if output_activities else None+ result_text = self._select_terminal_text(+ composite_key,+ raw_result_text,+ )- # ResultMessage.result already contains the last- # AssistantMessage, so only the terminal owner emits it.- pending_request = self._pop_pending_request(composite_key)- output_activities = self._request_activities(pending_request)- output_activity = output_activities[-1] if output_activities else None- result_text = self._select_terminal_text(+ if terminal_superseded:+ self._adopt_pending_turn_token(context, superseded_request)+ if superseded_result_text or self._request_activities(+ superseded_request+ ):+ await self._emit_primary_phase_output(+ context,+ superseded_request,+ superseded_result_text,+ )+ self._clear_result_phase_state(composite_key)+ logger.info(+ "Kept Claude Turn open across a pre-steer terminal result for %s",composite_key,- raw_result_text,)+ continue# The receiver is long-lived and reused across a session's# turns, so ``context`` still carries the FIRST turn's@@ -2732,6 +2880,121 @@ class ClaudeAgent(BaseAgent):return "<silent>Claude turn completed without assistant text.</silent>"return str(sdk_result or "")+ def _clear_result_phase_state(self, composite_key: str) -> None:+ """Retire response-local evidence before Claude consumes another input."""++ self._last_assistant_text.pop(composite_key, None)+ self._pending_assistant_message.pop(composite_key, None)+ self._foreground_tool_use_ids.pop(composite_key, None)+ self._turns_with_foreground_tools.discard(composite_key)++ async def _emit_primary_phase_output(+ self,+ context: MessageContext,+ request: AgentRequest | None,+ text: str,+ ) -> None:+ """Emit a completed pre-steer phase without closing the shared Turn."""++ activities = self._request_activities(request)+ activity = activities[-1] if activities else None+ output = (+ self._activity_message_output(+ activity,+ activities=activities,+ detached=False,+ completes_turn=False,+ )+ if activity is not None+ else MessageOutput(+ completes_turn=False,+ completes_run=False,+ records_run_output=False,+ )+ )+ emitted_text = text or (+ str(activity.metadata.get("summary") or "") if activity else ""+ )+ message_id = await self.controller.emit_agent_message(+ context,+ "output",+ emitted_text,+ parse_mode="markdown",+ output=output,+ )+ if activity is None:+ return+ if strip_silent_blocks(emitted_text).strip():+ self._require_activity_delivery(activity, message_id)+ self._clear_request_activities(request)+ if request is not None:+ request.output = terminal_turn_output()++ async def _emit_buffered_primary_phase(+ self,+ context: MessageContext,+ composite_key: str,+ ) -> bool:+ """Emit and retire a buffered Result once later input/output proves it primary."""++ buffered = self._ambiguous_primary_results.pop(composite_key, None)+ if buffered is None:+ return False+ buffered_text = self._select_buffered_terminal_text(+ composite_key,+ buffered,+ )+ pending = self._pending_requests.get(composite_key) or []+ buffered_request = pending[0] if pending else None+ if buffered_text or self._request_activities(buffered_request):+ self._adopt_pending_turn_token(context, buffered_request)+ await self._emit_primary_phase_output(+ context,+ buffered_request,+ buffered_text,+ )+ return True++ async def _retire_primary_phase_on_steer_receipt(+ self,+ context: MessageContext,+ composite_key: str,+ ) -> None:+ """Close all response-local primary state at the native input boundary."""++ if not await self._emit_buffered_primary_phase(context, composite_key):+ pending = self._pending_requests.get(composite_key) or []+ primary_request = pending[0] if pending else None+ primary_text = self._select_terminal_text(composite_key, None)+ if primary_text or self._request_activities(primary_request):+ self._adopt_pending_turn_token(context, primary_request)+ await self._emit_primary_phase_output(+ context,+ primary_request,+ primary_text,+ )+ self._clear_result_phase_state(composite_key)++ def _select_buffered_terminal_text(self, composite_key: str, buffered) -> str:+ """Render a buffered pre-steer result without using newer assistant text."""+ message, assistant_text, had_foreground_tools = self._unpack_buffered_terminal(+ buffered+ )+ if assistant_text:+ return str(assistant_text).strip()+ if had_foreground_tools:+ return "<silent>Claude turn completed without assistant text.</silent>"+ return str(getattr(message, "result", "") or "")++ @staticmethod+ def _unpack_buffered_terminal(+ buffered,+ ) -> tuple[object, str | None, bool]:+ if isinstance(buffered, tuple) and len(buffered) == 3:+ message, assistant_text, had_foreground_tools = buffered+ return message, assistant_text, bool(had_foreground_tools)+ return buffered, None, False+def _select_detached_result_text(self,composite_key: str,diff --git a/storage/agent_activity_service.py b/storage/agent_activity_service.pyindex c406cd10f..040a0418b 100644--- a/storage/agent_activity_service.py+++ b/storage/agent_activity_service.py@@ -51,10 +51,10 @@ from vibe.message_types import spec_for, types_withMESSAGE_SCAN_LIMIT = 500EVENT_SCAN_LIMIT = 2000-# Message types that participate in turn structure: turn openers (user/harness),-# 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.+# Message types that participate in turn structure: visible or hidden turn openers,+# terminals (result/error/notify/silent-marker), and interim assistant activity rows.+# Hidden lifecycle rows are fetched even though they are not in TRANSCRIPT_TYPES so+# the activity projection preserves the complete Turn boundary._CONDITIONAL_TERMINAL_TYPES = types_with("terminalWhenEvents")_TRANSCRIPT_ACTIVITY_TYPES = tuple(message_type@@ -62,6 +62,12 @@ _TRANSCRIPT_ACTIVITY_TYPES = tuple(if spec_for(message_type)["activityRole"] != "none"or spec_for(message_type)["terminalWhenEvents"])+_NON_TRANSCRIPT_START_TYPES = tuple(+ message_type+ for message_type in types_with("activityRole")+ if spec_for(message_type)["activityRole"] == "turn_start"+ and message_type not in _TRANSCRIPT_ACTIVITY_TYPES+)_NON_TRANSCRIPT_TERMINAL_TYPES = tuple(message_typefor message_type in types_with("activityRole")@@ -75,6 +81,7 @@ _ACTIVITY_TYPES = tuple()_RELEVANT_MESSAGE_TYPES = (*_TRANSCRIPT_ACTIVITY_TYPES,+ *_NON_TRANSCRIPT_START_TYPES,*_NON_TRANSCRIPT_TERMINAL_TYPES,*_ACTIVITY_TYPES,)@@ -166,7 +173,13 @@ def _terminal_status(msg_type: Any, metadata: Optional[dict] = None) -> str:# Fallback tiebreak only (used when a row's microsecond id prefix can't be decoded,# e.g. format drift): within a single turn the order is open → work → close.-_PHASE_RANK = {"turn_start": 0, "activity": 1, "terminal": 2, "ignore": 3}+_PHASE_RANK = {+ "turn_start": 0,+ "activity": 1,+ "boundary": 2,+ "terminal": 3,+ "ignore": 4,+}def _emit_micros(row_id: Optional[str], ts: datetime) -> int:@@ -264,6 +277,8 @@ def _timeline(conn, session_id: str, *, include_text: bool) -> list[dict[str, An)elif activity_role == "activity":kind = "activity"+ elif activity_role == "boundary":+ kind = "boundary"else:kind = "ignore"created_at = msg.get("created_at")@@ -288,6 +303,9 @@ def _timeline(conn, session_id: str, *, include_text: bool) -> list[dict[str, An"kind": kind,"id": msg.get("id"),"mtype": mtype,+ "is_transcript": bool(+ spec_for(mtype if isinstance(mtype, str) else "")["transcript"]+ ),"row_kind": "assistant","text": msg.get("text") if include_text else None,# The silent marker is a terminal that is INVISIBLE in the transcript,@@ -460,7 +478,29 @@ def _build_groups(items: list[dict[str, Any]], *, include_rows: bool) -> list[di)pending = []turn_start_iso = item["created_at"]- last_boundary_id = item["id"]+ if item["is_transcript"]:+ last_boundary_id = item["id"]+ elif kind == "boundary":+ if pending:+ groups.append(+ _make_group(+ pending,+ status="done",+ anchor_id=item["id"],+ anchor_position="before",+ open_turn=False,+ started_iso=turn_start_iso,+ ended_iso=item["created_at"],+ include_rows=include_rows,+ )+ )+ pending = []+ # This output completes the preceding visible work without ending the+ # logical Turn. Later activity belongs after this boundary and times+ # from it until the eventual terminal or interruption.+ turn_start_iso = item["created_at"]+ if item["is_transcript"]:+ last_boundary_id = item["id"]elif kind == "terminal":if pending:# A silent marker is invisible in the transcript, so its DONE groupdiff --git a/storage/alembic/versions/20260808_0048_agent_lifecycle_message_indexes.py b/storage/alembic/versions/20260808_0048_agent_lifecycle_message_indexes.pynew file mode 100644index 000000000..1f168f38c--- /dev/null+++ b/storage/alembic/versions/20260808_0048_agent_lifecycle_message_indexes.py@@ -0,0 +1,90 @@+"""index hidden agent starts and visible nonterminal outputs++Revision ID: 20260808_0048+Revises: 20260806_0047+Create Date: 2026-08-08+"""++from __future__ import annotations++from alembic import op++revision = "20260808_0048"+down_revision = "20260806_0047"+branch_labels = None+depends_on = None++_ORDER_EXPR = "coalesce(delivered_at, created_at)"++UPGRADE_ACTIVITY_PREDICATE = (+ "session_id is not null and type in "+ "('user', 'harness', 'agent_initiated', 'annotation', 'output', "+ "'result', 'notify', 'error', 'assistant')"+)+DOWNGRADE_ACTIVITY_PREDICATE = (+ "session_id is not null and type in "+ "('user', 'harness', 'annotation', 'result', 'notify', 'error', 'assistant')"+)+UPGRADE_USER_SEND_PREDICATE = (+ "session_id is not null and ((author = 'user' and type = 'user') "+ "or (author = 'harness' and type = 'harness') "+ "or (author = 'harness' and type = 'agent_initiated') "+ "or (author = 'harness' and type = 'annotation'))"+)+UPGRADE_AGENT_REPLY_PREDICATE = (+ "session_id is not null and type in ('output', 'result', 'notify', 'error')"+)+DOWNGRADE_AGENT_REPLY_PREDICATE = (+ "session_id is not null and type in ('result', 'notify', 'error')"+)+DOWNGRADE_USER_SEND_PREDICATE = (+ "session_id is not null and ((author = 'user' and type = 'user') "+ "or (author = 'harness' and type = 'harness') "+ "or (author = 'harness' and type = 'annotation'))"+)+++def _replace_indexes(+ *,+ activity_predicate: str,+ agent_reply_predicate: str,+ user_send_predicate: str,+) -> None:+ bind = op.get_bind()+ for name in (+ "ix_messages_inbox_activity",+ "ix_messages_inbox_agent_reply",+ "ix_messages_inbox_user_send",+ ):+ bind.exec_driver_sql(f"drop index if exists {name}")+ bind.exec_driver_sql(+ "create index ix_messages_inbox_activity "+ f"on messages (platform, session_id, {_ORDER_EXPR} desc, id desc) "+ f"where {activity_predicate}"+ )+ bind.exec_driver_sql(+ "create index ix_messages_inbox_agent_reply "+ f"on messages (platform, session_id, {_ORDER_EXPR} desc, id desc) "+ f"where {agent_reply_predicate}"+ )+ bind.exec_driver_sql(+ "create index ix_messages_inbox_user_send "+ f"on messages (platform, session_id, {_ORDER_EXPR} desc, id desc) "+ f"where {user_send_predicate}"+ )+++def upgrade() -> None:+ _replace_indexes(+ activity_predicate=UPGRADE_ACTIVITY_PREDICATE,+ agent_reply_predicate=UPGRADE_AGENT_REPLY_PREDICATE,+ user_send_predicate=UPGRADE_USER_SEND_PREDICATE,+ )+++def downgrade() -> None:+ _replace_indexes(+ activity_predicate=DOWNGRADE_ACTIVITY_PREDICATE,+ agent_reply_predicate=DOWNGRADE_AGENT_REPLY_PREDICATE,+ user_send_predicate=DOWNGRADE_USER_SEND_PREDICATE,+ )diff --git a/tests/scenarios/harness_failure_recovery/catalog.yaml b/tests/scenarios/harness_failure_recovery/catalog.yamlindex c2e1ad1c9..996d237d0 100644--- a/tests/scenarios/harness_failure_recovery/catalog.yaml+++ b/tests/scenarios/harness_failure_recovery/catalog.yaml@@ -3871,15 +3871,17 @@ scenarios:# native evidence either accepts the attempt or closes it terminally.test: tests/test_agent_steering.py::test_opencode_keeps_reconciliation_armed_after_post_write_idle- id: HFR-435- name: a Claude steered Assistant response owns the following terminal result+ name: Claude input echoes establish steering result ownershipstatus: coveredkind: recoverylayer: contractbackend: claude- # The accepted steering barrier suppresses only a buffered pre-steer result.- # Once the receiver has emitted Assistant text in the current generation,- # its ResultMessage is the real continuation and must settle the pending Turn.- test: tests/test_claude_agent_sessions.py::test_steered_assistant_and_result_settle_the_pending_turn+ # A transport write only queues input, while Claude may merge several inputs+ # into one response. Avibe enables the CLI's replay-user-messages protocol so+ # each consumed input produces a native top-level UserMessage echo in FIFO+ # order. A Result before the echo stays nonterminal; a Result after every echo+ # can settle the shared Turn.+ test: tests/test_claude_agent_sessions.py::test_user_echo_allows_one_result_to_own_primary_and_steer- id: HFR-436name: Watch waiter health is independent from downstream event processingstatus: covered@@ -4122,6 +4124,26 @@ scenarios:# Activity completions reserve SQLite's writer slot before reading deferred# participants or their owner, so one Turn cannot elect competing fallbacks.test: tests/test_harness_failure_visibility.py::test_hfr_459_deferred_owner_election_reserves_writer_before_reads+ - id: HFR-460+ name: delayed Claude steering remains user-owned across the primary Result+ status: covered+ kind: recovery+ layer: contract+ backend: claude+ # Claude can finish the active query before it dequeues an accepted steer.+ # The primary Result remains visible as nonterminal output, the same logical+ # Turn stays open, and the later steered Result settles it without creating+ # an agent-initiated Harness Message.+ test: tests/test_claude_agent_sessions.py::test_presteer_result_stays_visible_without_agent_initiated_turn+ - id: HFR-461+ name: genuine backend-initiated continuation keeps a hidden lifecycle input+ status: covered+ kind: safety+ layer: contract+ backend: shared+ # The durable input keeps Turn ownership, Stop, and audit history intact but+ # is not a human instruction and therefore never renders in the transcript.+ test: tests/test_session_delivery_fsm.py::test_agent_initiated_continuation_materializes_as_hidden_turn_inputmanual_evidence:- local Incus backend process death after prompt acceptance- local Incus controller restart with persisted queued successordiff --git a/tests/test_agent_activity_service.py b/tests/test_agent_activity_service.pyindex 552edfe80..04f82d79e 100644--- a/tests/test_agent_activity_service.py+++ b/tests/test_agent_activity_service.py@@ -581,6 +581,138 @@ def test_send_while_busy_override_interrupt_anchors_backward(isolated_state):assert turn3["anchor_message_id"] == over3 and turn3["open"] is True+def test_activity_after_nonterminal_output_anchors_to_that_output(isolated_state):+ """A delayed-steer answer is the visible boundary for later interrupted work."""++ engine = create_sqlite_engine()+ sid = "ses_output_boundary"+ 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",+ )+ _msg(+ conn,+ scope,+ sid,+ mid="m_output",+ mtype="output",+ author="agent",+ created_at="2026-06-01T10:00:01Z",+ text="primary answer",+ )+ _evt(+ conn,+ scope,+ sid,+ eid="e_after_output",+ created_at="2026-06-01T10:00:02Z",+ text="continued work",+ )+ _msg(+ conn,+ scope,+ sid,+ mid="m_u2",+ mtype="user",+ author="user",+ created_at="2026-06-01T10:00:03Z",+ text="next turn",+ source="user",+ )++ with engine.connect() as conn:+ groups = agent_activity_service.list_turn_groups(conn, session_id=sid)[+ "groups"+ ]++ assert len(groups) == 1+ assert groups[0]["status"] == "interrupted"+ assert groups[0]["anchor_message_id"] == "m_output"+ assert groups[0]["anchor_position"] == "after"+ assert groups[0]["open"] is False+++def test_nonterminal_output_completes_prior_activity_and_anchors_later_work(+ isolated_state,+):+ engine = create_sqlite_engine()+ sid = "ses_output_completion_boundary"+ 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",+ )+ _evt(+ conn,+ scope,+ sid,+ eid="e_before_output",+ created_at="2026-06-01T10:00:01Z",+ text="primary work",+ )+ _msg(+ conn,+ scope,+ sid,+ mid="m_output",+ mtype="output",+ author="agent",+ created_at="2026-06-01T10:00:02Z",+ text="primary answer",+ )+ _evt(+ conn,+ scope,+ sid,+ eid="e_after_output",+ created_at="2026-06-01T10:00:03Z",+ text="steered work",+ )+ _msg(+ conn,+ scope,+ sid,+ mid="m_u2",+ mtype="user",+ author="user",+ created_at="2026-06-01T10:00:04Z",+ text="next turn",+ source="user",+ )++ with engine.connect() as conn:+ groups = agent_activity_service.list_turn_groups(conn, session_id=sid)[+ "groups"+ ]++ assert len(groups) == 2+ assert groups[0]["status"] == "done"+ assert groups[0]["anchor_message_id"] == "m_output"+ assert groups[0]["anchor_position"] == "before"+ assert groups[0]["open"] is False+ assert groups[1]["status"] == "interrupted"+ assert groups[1]["anchor_message_id"] == "m_output"+ assert groups[1]["anchor_position"] == "after"+ assert groups[1]["open"] is False++def test_get_turn_group_unknown_id_returns_none(isolated_state):engine = create_sqlite_engine()sid = "ses_none"@@ -601,6 +733,77 @@ def test_get_turn_group_unknown_id_returns_none(isolated_state):# no terminal at all (cancel/Stop) = interrupted.[email protected]("ending", ["silent", "interrupted"])+def test_hidden_agent_started_turn_keeps_transcript_visible_activity_anchor(+ isolated_state,+ ending,+):+ engine = create_sqlite_engine()+ sid = f"ses_hidden_start_{ending}"+ with engine.begin() as conn:+ scope = _seed_session(conn, session_id=sid)+ _msg(+ conn,+ scope,+ sid,+ mid="m_previous",+ mtype="result",+ author="agent",+ created_at="2026-06-01T10:00:00Z",+ text="previous answer",+ )+ _msg(+ conn,+ scope,+ sid,+ mid="m_hidden",+ mtype="agent_initiated",+ author="harness",+ source="harness",+ created_at="2026-06-01T10:00:01Z",+ text="internal continuation",+ )+ _evt(+ conn,+ scope,+ sid,+ eid="e_hidden",+ created_at="2026-06-01T10:00:02Z",+ text="tool",+ )+ if ending == "silent":+ _evt(+ conn,+ scope,+ sid,+ eid="e_terminal",+ created_at="2026-06-01T10:00:03Z",+ text="",+ event_type="silent_terminal",+ metadata={"terminal_outcome": "completed"},+ )+ else:+ _msg(+ conn,+ scope,+ sid,+ mid="m_next",+ mtype="user",+ author="user",+ source="user",+ created_at="2026-06-01T10:00:03Z",+ text="next question",+ )++ with engine.connect() as conn:+ groups = agent_activity_service.list_turn_groups(conn, session_id=sid)["groups"]++ assert len(groups) == 1+ assert groups[0]["anchor_message_id"] == "m_previous"+ assert groups[0]["anchor_message_id"] != "m_hidden"+ assert groups[0]["anchor_position"] == "after"++def test_silent_completion_marks_turn_done(isolated_state):"""A reply-less terminal Turn closes activity without a pseudo Message."""engine = create_sqlite_engine()diff --git a/tests/test_agent_steering.py b/tests/test_agent_steering.pyindex f173b05dc..c882789ce 100644--- a/tests/test_agent_steering.py+++ b/tests/test_agent_steering.py@@ -383,6 +383,7 @@ async def test_claude_uses_one_client_receiver_and_primary_result_owner() -> Nonassert agent.receiver_tasks == {"runtime-key": receiver_task}assert agent._pending_requests["runtime-key"] is primary_requestsassert agent._pending_requests["runtime-key"] == [primary]+ client._transport.end_input.assert_not_awaited()# Steering admission is not execution progress and must not refresh the# stuck-runtime clock before assistant/tool output arrives.assert agent.session_handler.activity_touches == []@@ -491,6 +492,37 @@ async def test_claude_preserves_receiver_when_ambiguous_input_half_close_fails()await _cancel_tasks(gate_task, receiver_task)+async def test_claude_accepts_stable_steer_without_closing_native_input() -> None:+ primary = _primary_request(backend="claude")+ gate_task = await _held_task()+ receiver_task = await _held_task()+ client = _ClaudeClient()+ client._transport.end_input = AsyncMock(side_effect=RuntimeError("stdin close failed"))+ agent = object.__new__(ClaudeAgent)+ agent.claude_sessions = {"runtime-key": client}+ agent.receiver_tasks = {"runtime-key": receiver_task}+ agent.session_handler = _ClaudeSessionHandler("runtime-key")+ agent._pending_requests = {"runtime-key": [primary]}+ controller = _controller_with_active_gate(agent, primary, gate_task)+ try:+ identity = active_steer_identity(controller, "claude", "avibe-session")+ assert identity is not None++ receipt = await steer_active_turn(+ controller,+ "claude",+ _steer_request(identity[1]),+ )++ assert receipt.outcome is SteerOutcome.ACCEPTED+ assert client.queries[-1] == (STEER_TEXT, "runtime-key")+ client._transport.end_input.assert_not_awaited()+ assert not receiver_task.done()+ finally:+ await _cancel_tasks(gate_task, receiver_task)++@pytest.mark.anyioasync def test_shared_boundary_finishes_native_reconciliation_before_propagating_cancel() -> None:primary = _primary_request(backend="claude")@@ -529,7 +561,7 @@ async def test_shared_boundary_finishes_native_reconciliation_before_propagatingawait callerassert agent._steering_generation("runtime-key") == 1- assert agent._next_terminal_barrier("runtime-key") == "accepted"+ assert agent._pending_steering_input_state("runtime-key") == "accepted"assert agent._pending_requests["runtime-key"] == [primary]assert not receiver_task.done()finally:diff --git a/tests/test_agent_tool_policy.py b/tests/test_agent_tool_policy.pyindex f81f10598..b232c6699 100644--- a/tests/test_agent_tool_policy.py+++ b/tests/test_agent_tool_policy.py@@ -393,7 +393,9 @@ def test_hooks_are_wired_when_the_sdk_supports_them(monkeypatch):hooks = handler._build_claude_tool_policy_hooks()assert list(hooks) == ["PreToolUse"]- assert set(captured["matcher"].split("|")) == set(policy.session_only_background_tool_names())+ assert set(captured["matcher"].split("|")) == set(+ policy.session_only_background_tool_names()+ )assert captured["hooks"] == [handler._guard_session_only_background_tools]# The precise hook path owns enforcement, so nothing extra is denied by name.assert handler._claude_disallowed_tools(hooks) == sh.CLAUDE_REMOTE_DISALLOWED_TOOLSdiff --git a/tests/test_claude_agent_sessions.py b/tests/test_claude_agent_sessions.pyindex 516253de4..44085c347 100644--- a/tests/test_claude_agent_sessions.py+++ b/tests/test_claude_agent_sessions.py@@ -18,7 +18,7 @@ from core.session_activities import SessionActivity, activity_completion_outputfrom core.services.agent_steering import ActiveSteerTarget, SteerOutcome, SteerRequestfrom modules.agents.claude_agent import ClaudeAgentfrom modules.agents.service import AgentService-from modules.claude_sdk_compat import TextBlock+from modules.claude_sdk_compat import TextBlock, UserMessageclass _StubSessions:@@ -502,6 +502,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):interrupt_called = asyncio.Event()class _Client:+async def query(self, _text, *, session_id):query_started.set()await release_query.wait()@@ -883,29 +884,23 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(agent._pending_reactions[composite_key], [("m2", ":eyes:")])self.assertTrue(controller.session_manager.session.session_active[composite_key])- def test_steered_result_after_assistant_response_is_not_suppressed(self):- controller = _StubController()- agent = ClaudeAgent(controller)- composite_key = "session-1:/tmp/work"- agent._steering_generations[composite_key] = 1- agent._steering_terminal_barriers[composite_key] = ["accepted"]- agent._steering_response_generations[composite_key] = 1-- self.assertFalse(agent._terminal_claim_superseded(composite_key, 1))- self.assertIsNone(agent._next_terminal_barrier(composite_key))-def test_buffered_result_without_steered_assistant_is_suppressed(self):controller = _StubController()agent = ClaudeAgent(controller)composite_key = "session-1:/tmp/work"agent._steering_generations[composite_key] = 1- agent._steering_terminal_barriers[composite_key] = ["accepted"]+ receipt = agent._register_native_input(+ composite_key,+ "steered prompt",+ kind="steer",+ )+ receipt.state = "unknown"self.assertTrue(agent._terminal_claim_superseded(composite_key, 1))- self.assertIsNone(agent._next_terminal_barrier(composite_key))+ self.assertEqual(agent._pending_steering_input_state(composite_key), "unknown")async def test_steered_assistant_and_result_settle_the_pending_turn(self):- """HFR-435: the steered Assistant owns its following terminal result."""+ """A Result before the native input echo remains nonterminal."""controller = _StubController()controller._get_session_key = lambda _context: "session-1"controller.emit_agent_message = AsyncMock()@@ -929,9 +924,22 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):ack_reaction_emoji=None,)agent._pending_requests[composite_key] = [pending_request]- agent._steering_generations[composite_key] = 1- agent._steering_terminal_barriers[composite_key] = ["accepted"]-+ receipt = agent._register_native_input(+ composite_key,+ "steered prompt",+ kind="steer",+ )+ receipt.state = "accepted"+ agent._advance_steering_generation(composite_key)+ primary_result = type(+ "ResultMessage",+ (),+ {+ "subtype": "success",+ "result": "primary final answer",+ "duration_ms": 1,+ },+ )()text_block = TextBlock("steered final answer")assistant_message = type("AssistantMessage",@@ -944,13 +952,15 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):{"subtype": "success","result": "steered final answer",- "duration_ms": 1,+ "duration_ms": 2,},)()class _Client:def receive_messages(self):async def _iterate():+ yield primary_result+ yield UserMessage("steered prompt")yield assistant_messageyield result_message@@ -968,11 +978,656 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):context,"steered final answer",subtype="success",- duration_ms=1,+ duration_ms=2,+ parse_mode="markdown",+ request=pending_request,+ )+ controller.emit_agent_message.assert_any_await(+ context,+ "output",+ "primary final answer",+ parse_mode="markdown",+ output=ANY,+ )+ self.assertNotIn(composite_key, agent._pending_requests)++ async def test_presteer_result_stays_visible_without_agent_initiated_turn(self):+ """HFR-460: queued native steering keeps its user-owned Turn."""++ controller = _StubController()+ controller._get_session_key = lambda _context: "session-1"+ output_tokens = []+ output_semantics = []++ async def _emit_output(emit_context, message_type, *_args, **kwargs):+ if message_type == "output":+ output_tokens.append(+ emit_context.platform_specific.get("agent_runtime_turn_token")+ )+ output_semantics.append(kwargs.get("output"))++ controller.emit_agent_message = AsyncMock(side_effect=_emit_output)+ controller.session_handler.mark_session_idle = lambda _key: None+ controller.session_handler.handle_session_error = AsyncMock()+ begin_agent_initiated_turn = AsyncMock()+ controller.agent_service = SimpleNamespace(+ activity_registry=None,+ begin_agent_initiated_turn=begin_agent_initiated_turn,+ )+ agent = ClaudeAgent(controller)+ agent.emit_result_message = AsyncMock()+ agent._get_formatter = lambda _context: SimpleNamespace(+ format_assistant_message=lambda parts: "\n\n".join(parts),+ )+ composite_key = "session-delayed-steer:/tmp/work"+ context = SimpleNamespace(+ user_id="U1",+ channel_id="C1",+ platform_specific={+ "turn_token": "T1",+ "agent_runtime_turn_token": "R1",+ },+ )+ pending_request = SimpleNamespace(+ context=SimpleNamespace(+ platform_specific={+ "turn_token": "T2",+ "agent_runtime_turn_token": "R2",+ }+ ),+ started_at=None,+ ack_reaction_message_id=None,+ ack_reaction_emoji=None,+ )+ agent._pending_requests[composite_key] = [pending_request]+ receipt = agent._register_native_input(+ composite_key,+ "steered prompt",+ kind="steer",+ )+ receipt.state = "accepted"+ agent._advance_steering_generation(composite_key)+ primary_assistant = type(+ "AssistantMessage",+ (),+ {"content": [TextBlock("primary work completed")]},+ )()+ primary_result = type(+ "ResultMessage",+ (),+ {+ "subtype": "success",+ "result": "primary work completed",+ "duration_ms": 1,+ },+ )()+ steered_assistant = type(+ "AssistantMessage",+ (),+ {"content": [TextBlock("screenshots ready")]},+ )()+ steered_result = type(+ "ResultMessage",+ (),+ {+ "subtype": "success",+ "result": "screenshots ready",+ "duration_ms": 2,+ },+ )()++ class _Client:+ def receive_messages(self):+ async def _iterate():+ yield primary_assistant+ yield primary_result+ yield UserMessage("steered prompt")+ yield steered_assistant+ yield steered_result++ return _iterate()++ await agent._receive_messages(+ _Client(),+ "session-delayed-steer",+ "/tmp/work",+ context,+ composite_key=composite_key,+ )++ controller.emit_agent_message.assert_any_await(+ context,+ "output",+ "primary work completed",+ parse_mode="markdown",+ output=ANY,+ )+ agent.emit_result_message.assert_awaited_once_with(+ context,+ "screenshots ready",+ subtype="success",+ duration_ms=2,+ parse_mode="markdown",+ request=pending_request,+ )+ self.assertNotIn(composite_key, agent._pending_requests)+ self.assertEqual(output_tokens, ["R2"])+ self.assertEqual(len(output_semantics), 1)+ self.assertFalse(output_semantics[0].records_run_output)+ begin_agent_initiated_turn.assert_not_awaited()++ async def test_presteer_result_settles_its_claimed_activity_without_closing_turn(self):+ controller = _StubController()+ controller._get_session_key = lambda _context: "session-1"+ controller.emit_agent_message = AsyncMock(return_value="primary-output")+ controller.session_handler.mark_session_idle = lambda _key: None+ controller.session_handler.handle_session_error = AsyncMock()+ agent = ClaudeAgent(controller)+ agent.emit_result_message = AsyncMock()+ composite_key = "session-presteer-activity:/tmp/work"+ context = SimpleNamespace(+ user_id="U1",+ channel_id="C1",+ platform_specific={"turn_token": "T1"},+ )+ activity = SessionActivity(+ id="activity-primary",+ backend="claude",+ runtime_key=composite_key,+ session_id="session-presteer-activity",+ kind="task",+ status="completed",+ turn_id="T1",+ run_id="run-primary",+ )+ pending_request = SimpleNamespace(+ context=context,+ started_at=None,+ ack_reaction_message_id=None,+ ack_reaction_emoji=None,+ output_activities=[activity],+ output=activity_completion_output(+ activity,+ detached=False,+ completes_turn=True,+ ),+ )+ agent._pending_requests[composite_key] = [pending_request]+ receipt = agent._register_native_input(+ composite_key,+ "steered prompt",+ kind="steer",+ )+ receipt.state = "accepted"+ agent._advance_steering_generation(composite_key)++ class _Client:+ def receive_messages(self):+ async def _iterate():+ yield type(+ "ResultMessage",+ (),+ {+ "subtype": "success",+ "result": "primary result",+ "duration_ms": 1,+ },+ )()+ yield UserMessage("steered prompt")+ yield type(+ "ResultMessage",+ (),+ {+ "subtype": "success",+ "result": "steered result",+ "duration_ms": 2,+ },+ )()++ return _iterate()++ await agent._receive_messages(+ _Client(),+ "session-presteer-activity",+ "/tmp/work",+ context,+ composite_key=composite_key,+ )++ primary_call = controller.emit_agent_message.await_args_list[0]+ self.assertEqual(primary_call.args[1:3], ("output", "primary result"))+ primary_output = primary_call.kwargs["output"]+ self.assertFalse(primary_output.completes_turn)+ self.assertTrue(primary_output.settles_run)+ self.assertEqual(primary_output.activity_id, "activity-primary")+ self.assertEqual(primary_output.run_ids, ("run-primary",))+ self.assertEqual(pending_request.output_activities, [])+ self.assertTrue(pending_request.output.completes_turn)+ self.assertIsNone(pending_request.output.activity_id)+ agent.emit_result_message.assert_awaited_once_with(+ context,+ "steered result",+ subtype="success",+ duration_ms=2,+ parse_mode="markdown",+ request=pending_request,+ )++ async def test_silent_presteer_result_settles_activity_without_a_message_id(self):+ controller = _StubController()+ controller._get_session_key = lambda _context: "session-1"+ controller.emit_agent_message = AsyncMock(return_value=None)+ controller.session_handler.mark_session_idle = lambda _key: None+ controller.session_handler.handle_session_error = AsyncMock()+ agent = ClaudeAgent(controller)+ agent.emit_result_message = AsyncMock()+ composite_key = "session-silent-presteer-activity:/tmp/work"+ context = SimpleNamespace(+ user_id="U1",+ channel_id="C1",+ platform_specific={"turn_token": "T1"},+ )+ activity = SessionActivity(+ id="activity-primary",+ backend="claude",+ runtime_key=composite_key,+ session_id="session-silent-presteer-activity",+ kind="task",+ status="completed",+ turn_id="T1",+ run_id="run-primary",+ )+ pending_request = SimpleNamespace(+ context=context,+ started_at=None,+ ack_reaction_message_id=None,+ ack_reaction_emoji=None,+ output_activities=[activity],+ output=activity_completion_output(+ activity,+ detached=False,+ completes_turn=True,+ ),+ )+ agent._pending_requests[composite_key] = [pending_request]+ agent._turns_with_foreground_tools.add(composite_key)+ receipt = agent._register_native_input(+ composite_key,+ "steered prompt",+ kind="steer",+ )+ receipt.state = "accepted"+ agent._advance_steering_generation(composite_key)++ class _Client:+ def receive_messages(self):+ async def _iterate():+ yield type(+ "ResultMessage",+ (),+ {+ "subtype": "success",+ "result": "tool-only primary",+ "duration_ms": 1,+ },+ )()+ yield UserMessage("steered prompt")+ yield type(+ "ResultMessage",+ (),+ {+ "subtype": "success",+ "result": "steered result",+ "duration_ms": 2,+ },+ )()++ return _iterate()++ await agent._receive_messages(+ _Client(),+ "session-silent-presteer-activity",+ "/tmp/work",+ context,+ composite_key=composite_key,+ )++ primary_call = controller.emit_agent_message.await_args_list[0]+ self.assertEqual(primary_call.args[1], "output")+ self.assertEqual(+ primary_call.args[2],+ "<silent>Claude turn completed without assistant text.</silent>",+ )+ self.assertEqual(pending_request.output_activities, [])+ self.assertNotIn(composite_key, agent._turns_with_foreground_tools)+ agent.emit_result_message.assert_awaited_once_with(+ context,+ "steered result",+ subtype="success",+ duration_ms=2,+ parse_mode="markdown",+ request=pending_request,+ )++ async def test_user_echo_allows_one_result_to_own_primary_and_steer(self):+ """HFR-435: Claude may merge a steer into the primary Result."""++ controller = _StubController()+ controller._get_session_key = lambda _context: "session-1"+ controller.emit_agent_message = AsyncMock()+ controller.session_handler.mark_session_idle = lambda _key: None+ controller.session_handler.handle_session_error = AsyncMock()+ agent = ClaudeAgent(controller)+ agent.emit_result_message = AsyncMock()+ agent._get_formatter = lambda _context: SimpleNamespace(+ format_assistant_message=lambda parts: "\n\n".join(parts),+ )+ composite_key = "session-merged-steer:/tmp/work"+ context = SimpleNamespace(+ user_id="U1",+ channel_id="C1",+ platform_specific={"turn_token": "T1"},+ )+ pending_request = SimpleNamespace(+ context=context,+ started_at=None,+ ack_reaction_message_id=None,+ ack_reaction_emoji=None,+ )+ agent._pending_requests[composite_key] = [pending_request]+ receipt = agent._register_native_input(+ composite_key,+ "steered prompt",+ kind="steer",+ )+ receipt.state = "accepted"+ agent._advance_steering_generation(composite_key)++ class _Client:+ def receive_messages(self):+ async def _iterate():+ yield UserMessage("steered prompt")+ yield type(+ "AssistantMessage",+ (),+ {"content": [TextBlock("primary and steer answered")]},+ )()+ yield type(+ "ResultMessage",+ (),+ {+ "subtype": "success",+ "result": "primary and steer answered",+ "duration_ms": 2,+ },+ )()++ return _iterate()++ await agent._receive_messages(+ _Client(),+ "session-merged-steer",+ "/tmp/work",+ context,+ composite_key=composite_key,+ )++ agent.emit_result_message.assert_awaited_once_with(+ context,+ "primary and steer answered",+ subtype="success",+ duration_ms=2,+ parse_mode="markdown",+ request=pending_request,+ )+ self.assertNotIn(composite_key, agent._pending_requests)+ self.assertNotIn(composite_key, agent._native_input_receipts)++ async def test_user_echo_retires_primary_assistant_before_result_only_steer(self):+ controller = _StubController()+ controller._get_session_key = lambda _context: "session-1"+ controller.emit_agent_message = AsyncMock(return_value="primary-output")+ controller.session_handler.mark_session_idle = lambda _key: None+ controller.session_handler.handle_session_error = AsyncMock()+ agent = ClaudeAgent(controller)+ agent.emit_result_message = AsyncMock()+ agent._get_formatter = lambda _context: SimpleNamespace(+ format_assistant_message=lambda parts: "\n\n".join(parts),+ )+ composite_key = "session-assistant-receipt:/tmp/work"+ context = SimpleNamespace(+ user_id="U1",+ channel_id="C1",+ platform_specific={"turn_token": "T1"},+ )+ pending_request = SimpleNamespace(+ context=context,+ started_at=None,+ ack_reaction_message_id=None,+ ack_reaction_emoji=None,+ )+ agent._pending_requests[composite_key] = [pending_request]+ receipt = agent._register_native_input(+ composite_key,+ "steered prompt",+ kind="steer",+ )+ receipt.state = "accepted"+ agent._advance_steering_generation(composite_key)++ class _Client:+ def receive_messages(self):+ async def _iterate():+ yield type(+ "AssistantMessage",+ (),+ {"content": [TextBlock("primary answer")]},+ )()+ yield UserMessage("steered prompt")+ yield type(+ "ResultMessage",+ (),+ {+ "subtype": "success",+ "result": "steered result",+ "duration_ms": 2,+ },+ )()++ return _iterate()++ await agent._receive_messages(+ _Client(),+ "session-assistant-receipt",+ "/tmp/work",+ context,+ composite_key=composite_key,+ )++ controller.emit_agent_message.assert_awaited_once_with(+ context,+ "output",+ "primary answer",+ parse_mode="markdown",+ output=ANY,+ )+ agent.emit_result_message.assert_awaited_once_with(+ context,+ "steered result",+ subtype="success",+ duration_ms=2,+ parse_mode="markdown",+ request=pending_request,+ )+ self.assertNotIn(composite_key, agent._last_assistant_text)++ async def test_repeated_user_echoes_allow_one_merged_result_to_settle(self):+ """HFR-460: repeated steering does not require one Result per input."""++ controller = _StubController()+ controller._get_session_key = lambda _context: "session-1"+ controller.emit_agent_message = AsyncMock()+ controller.session_handler.mark_session_idle = lambda _key: None+ controller.session_handler.handle_session_error = AsyncMock()+ agent = ClaudeAgent(controller)+ agent.emit_result_message = AsyncMock()+ agent._get_formatter = lambda _context: SimpleNamespace(+ format_assistant_message=lambda parts: "\n\n".join(parts),+ )+ composite_key = "session-repeated-steer:/tmp/work"+ context = SimpleNamespace(+ user_id="U1",+ channel_id="C1",+ platform_specific={"turn_token": "T1"},+ )+ pending_request = SimpleNamespace(+ context=context,+ started_at=None,+ ack_reaction_message_id=None,+ ack_reaction_emoji=None,+ )+ agent._pending_requests[composite_key] = [pending_request]+ for text in ("first steer", "second steer"):+ receipt = agent._register_native_input(+ composite_key,+ text,+ kind="steer",+ )+ receipt.state = "accepted"+ agent._advance_steering_generation(composite_key)++ class _Client:+ def receive_messages(self):+ async def _iterate():+ yield UserMessage("first steer")+ yield UserMessage("second steer")+ yield type(+ "ResultMessage",+ (),+ {+ "subtype": "success",+ "result": "both steers answered",+ "duration_ms": 3,+ },+ )()++ return _iterate()++ await agent._receive_messages(+ _Client(),+ "session-repeated-steer",+ "/tmp/work",+ context,+ composite_key=composite_key,+ )++ agent.emit_result_message.assert_awaited_once_with(+ context,+ "both steers answered",+ subtype="success",+ duration_ms=3,parse_mode="markdown",request=pending_request,)self.assertNotIn(composite_key, agent._pending_requests)+ self.assertNotIn(composite_key, agent._native_input_receipts)++ async def test_ambiguous_results_emit_each_answer_in_order(self):+ controller = _StubController()+ controller._get_session_key = lambda _context: "session-1"+ emissions = []++ async def _emit_output(_context, message_type, text, **_kwargs):+ emissions.append((message_type, text))++ controller.emit_agent_message = AsyncMock(side_effect=_emit_output)+ controller.session_handler.mark_session_idle = lambda _key: None+ controller.session_handler.handle_session_error = AsyncMock()+ agent = ClaudeAgent(controller)+ async def _emit_result(_context, text, **_kwargs):+ emissions.append(("result", text))++ agent.emit_result_message = AsyncMock(side_effect=_emit_result)+ agent._get_formatter = lambda _context: SimpleNamespace(+ format_assistant_message=lambda parts: "\n\n".join(parts),+ )+ composite_key = "session-ambiguous:/tmp/work"+ context = SimpleNamespace(+ user_id="U1",+ channel_id="C1",+ platform_specific={"turn_token": "T1"},+ )+ pending_request = SimpleNamespace(+ context=context,+ started_at=None,+ ack_reaction_message_id=None,+ ack_reaction_emoji=None,+ )+ agent._pending_requests[composite_key] = [pending_request]+ agent._turns_with_foreground_tools.add(composite_key)+ agent._foreground_tool_use_ids[composite_key] = {"primary-tool"}+ receipt = agent._register_native_input(+ composite_key,+ "steered prompt",+ kind="steer",+ )+ receipt.state = "unknown"+ agent._advance_steering_generation(composite_key)++ primary_assistant = type(+ "AssistantMessage",+ (),+ {"content": [TextBlock("primary answer")]},+ )()+ primary_result = type(+ "ResultMessage",+ (),+ {"subtype": "success", "result": "primary answer", "duration_ms": 1},+ )()+ steered_result = type(+ "ResultMessage",+ (),+ {"subtype": "success", "result": "steered answer", "duration_ms": 2},+ )()+ class _Client:+ def receive_messages(self):+ async def _iterate():+ yield primary_assistant+ yield primary_result+ yield UserMessage("steered prompt")+ yield steered_result++ return _iterate()++ await agent._receive_messages(+ _Client(),+ "session-ambiguous",+ "/tmp/work",+ context,+ composite_key=composite_key,+ )++ controller.emit_agent_message.assert_any_await(+ context,+ "output",+ "primary answer",+ parse_mode="markdown",+ output=ANY,+ )+ agent.emit_result_message.assert_awaited_once_with(+ context,+ "steered answer",+ subtype="success",+ duration_ms=2,+ parse_mode="markdown",+ request=pending_request,+ )+ self.assertNotIn(composite_key, agent._ambiguous_primary_results)+ self.assertNotIn(composite_key, agent._pending_requests)+ self.assertEqual(+ emissions,+ [("output", "primary answer"), ("result", "steered answer")],+ )async def test_buffered_pre_steer_assistant_keeps_primary_result_ownership(self):controller = _StubController()@@ -1000,7 +1655,8 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):agent._pending_requests[composite_key] = [pending_request]assistant_received = asyncio.Event()release_assistant = asyncio.Event()- terminal_processed = asyncio.Event()+ result_receive_waiting = asyncio.Event()+ release_result = asyncio.Event()end_stream = asyncio.Event()original_begin = agent._maybe_begin_agent_initiated_turn@@ -1011,15 +1667,6 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):return await original_begin(*args, **kwargs)agent._maybe_begin_agent_initiated_turn = _hold_assistant- terminal_claim = agent._terminal_claim_superseded-- def _observe_terminal_claim(*args):- superseded = terminal_claim(*args)- if asyncio.current_task() is receiver_task:- terminal_processed.set()- return superseded-- agent._terminal_claim_superseded = _observe_terminal_claimassistant_message = type("AssistantMessage",(),@@ -1039,6 +1686,8 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):def receive_messages(self):async def _iterate():yield assistant_message+ result_receive_waiting.set()+ await release_result.wait()yield result_messageawait end_stream.wait()@@ -1054,9 +1703,22 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):))await assistant_received.wait()- agent._advance_steering_generation(composite_key)release_assistant.set()- await asyncio.wait_for(terminal_processed.wait(), timeout=1)+ await result_receive_waiting.wait()+ receipt = agent._register_native_input(+ composite_key,+ "steered prompt",+ kind="steer",+ )+ receipt.state = "unknown"+ agent._advance_steering_generation(composite_key)+ release_result.set()+ for _ in range(100):+ if composite_key in agent._ambiguous_primary_results:+ break+ await asyncio.sleep(0)+ else:+ self.fail("primary Result was not buffered behind the steering EOF boundary")self.assertEqual(agent._pending_requests[composite_key], [pending_request])agent.emit_result_message.assert_not_awaited()@@ -1064,6 +1726,67 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):receiver_task.cancel()await asyncio.gather(receiver_task, return_exceptions=True)+ async def test_buffered_tool_only_result_keeps_foreground_state_through_eof(self):+ controller = _StubController()+ controller._get_session_key = lambda _context: "session-1"+ controller.emit_agent_message = AsyncMock()+ controller.session_handler.mark_session_idle = lambda _key: None+ controller.session_handler.handle_session_error = AsyncMock()+ agent = ClaudeAgent(controller)+ agent.emit_result_message = AsyncMock()+ composite_key = "session-buffered-tool:/tmp/work"+ context = SimpleNamespace(+ user_id="U1",+ channel_id="C1",+ platform_specific={"turn_token": "T1"},+ )+ pending_request = SimpleNamespace(+ context=context,+ started_at=None,+ ack_reaction_message_id=None,+ ack_reaction_emoji=None,+ )+ agent._pending_requests[composite_key] = [pending_request]+ agent._turns_with_foreground_tools.add(composite_key)+ receipt = agent._register_native_input(+ composite_key,+ "steered prompt",+ kind="steer",+ )+ receipt.state = "unknown"+ agent._advance_steering_generation(composite_key)++ result_message = type(+ "ResultMessage",+ (),+ {+ "subtype": "success",+ "result": "Bash completed",+ "duration_ms": 1,+ },+ )()++ class _Client:+ def receive_messages(self):+ async def _iterate():+ yield result_message++ return _iterate()++ await agent._receive_messages(+ _Client(),+ "session-buffered-tool",+ "/tmp/work",+ context,+ composite_key=composite_key,+ )++ agent.emit_result_message.assert_awaited_once()+ selected = agent.emit_result_message.await_args.args[1]+ self.assertIn("<silent>", selected)+ self.assertNotIn("Bash completed", selected)+ self.assertNotIn(composite_key, agent._pending_requests)+async def test_toolcall_emit_adopts_current_pending_turn_token(self):controller = _StubController()controller._get_session_key = lambda _context: "session-1"diff --git a/tests/test_claude_cli_path.py b/tests/test_claude_cli_path.pyindex 0f2df94b4..4d3524a70 100644--- a/tests/test_claude_cli_path.py+++ b/tests/test_claude_cli_path.py@@ -314,7 +314,10 @@ def test_session_handler_sets_claude_fork_session_for_pending_native_fork(monkeyassert captured["connected"] is Trueassert captured["options"].resume == "claude-source"assert captured["options"].fork_session is True- assert captured["options"].extra_args == {"model": "claude-sonnet-4-5"}+ assert captured["options"].extra_args == {+ "replay-user-messages": None,+ "model": "claude-sonnet-4-5",+ }assert captured["options"].settings == '{"autoMemoryEnabled":false}'assert captured["options"].effort == "high"assert not hasattr(client, "_vibe_native_session_id")@@ -1103,7 +1106,10 @@ def test_session_handler_does_not_repeat_claude_model_control_request(monkeypatcassert first_client is second_clientassert len(captured["clients"]) == 1- assert captured["options"].extra_args == {"model": "claude-sonnet-4-5"}+ assert captured["options"].extra_args == {+ "replay-user-messages": None,+ "model": "claude-sonnet-4-5",+ }assert first_client.model_calls == []@@ -1431,7 +1437,7 @@ def test_session_handler_does_not_send_none_model_control_request_for_cached_defclient = _run_session(handler, context)_run_session(handler, context)- assert captured["options"].extra_args == {}+ assert captured["options"].extra_args == {"replay-user-messages": None}assert client.model_calls == []diff --git a/tests/test_claude_receiver_result_settle.py b/tests/test_claude_receiver_result_settle.pyindex bbaf5822b..8b83d8019 100644--- a/tests/test_claude_receiver_result_settle.py+++ b/tests/test_claude_receiver_result_settle.py@@ -18,13 +18,14 @@ import sysimport unittestfrom pathlib import Pathfrom types import SimpleNamespace-from unittest.mock import AsyncMock, Mock, patch+from unittest.mock import ANY, AsyncMock, Mock, patchsys.path.insert(0, str(Path(__file__).resolve().parents[1]))from core.services.agent_steering import ActiveSteerTarget, SteerOutcome, SteerRequestfrom modules.agents.claude_agent import ClaudeAgentfrom modules.agents.service import AgentService+from modules.claude_sdk_compat import UserMessageclass _ResultMessage:@@ -39,6 +40,11 @@ class _AssistantFailureMessage:is_error = True+class SystemMessage:+ subtype = "init"+ data = {"subtype": "init"}++def _one_result_client():class _Client:def receive_messages(self):@@ -65,18 +71,28 @@ def _build_agent(mark_idle_calls):),receiver_tasks={},claude_sessions={},- claude_client=SimpleNamespace(_is_skip_message=lambda message: False),+ claude_client=SimpleNamespace(+ _is_skip_message=lambda message: False,+ format_message=lambda *args, **kwargs: "",+ ),session_handler=SimpleNamespace(mark_session_idle=lambda key: mark_idle_calls.append(key),touch_session_activity=lambda key: None,),+ emit_agent_message=AsyncMock(return_value=None),)controller._get_session_key = lambda context: "session-key"agent = ClaudeAgent(controller)# Stub the external bits the result branch touches so the test isolates the# settle-on-failure contract.- agent._detect_message_type = lambda message: "result"+ agent._detect_message_type = lambda message: (+ "system"+ if isinstance(message, SystemMessage)+ else "user"+ if isinstance(message, UserMessage)+ else "result"+ )agent._maybe_capture_session_id = lambda *a, **k: Noneagent._consume_suppressed_synthetic_result = lambda *a, **k: Falseagent._handle_auth_failure_result = AsyncMock(return_value=False)@@ -275,6 +291,7 @@ class ResultSettlesTurnOnEmitFailureTests(unittest.IsolatedAsyncioTestCase):first.result = "primary result"yield firstawait second_result_ready.wait()+ yield UserMessage("补充:`exact`")second = _ResultMessage()second.result = "steered result"yield second@@ -357,6 +374,7 @@ class ResultSettlesTurnOnEmitFailureTests(unittest.IsolatedAsyncioTestCase):buffered.result = "buffered primary result"yield bufferedawait final_result_ready.wait()+ yield UserMessage("continue after buffered result")final = _ResultMessage()final.result = "steered result"yield final@@ -411,6 +429,13 @@ class ResultSettlesTurnOnEmitFailureTests(unittest.IsolatedAsyncioTestCase):await buffered_result_processed.wait()self.assertEqual(agent._pending_requests[composite_key], [primary_request])agent.emit_result_message.assert_not_awaited()+ agent.controller.emit_agent_message.assert_awaited_once_with(+ context,+ "output",+ "buffered primary result",+ parse_mode="markdown",+ output=ANY,+ )final_result_ready.set()await receiver_task@@ -446,6 +471,7 @@ class ResultSettlesTurnOnEmitFailureTests(unittest.IsolatedAsyncioTestCase):first.result = "primary result"yield firstawait second_result_ready.wait()+ yield UserMessage("ambiguous input")second = _ResultMessage()second.result = "reconciled result"yield second@@ -577,6 +603,51 @@ class ResultSettlesTurnOnEmitFailureTests(unittest.IsolatedAsyncioTestCase):self.assertNotIn(composite_key, agent.claude_sessions)self.assertNotIn(composite_key, agent.receiver_tasks)+ async def test_ambiguous_steer_echo_then_eof_rejects_buffered_primary_as_terminal(self):+ mark_idle_calls: list[str] = []+ agent = _build_agent(mark_idle_calls)+ context = SimpleNamespace(user_id="U1", channel_id="C1", platform_specific={})+ composite_key = "session-ambiguous-consumed:/tmp/work"+ primary_request = SimpleNamespace(context=context)+ agent._pending_requests[composite_key] = [primary_request]+ agent.emit_result_message = AsyncMock(return_value=None)+ receipt = agent._register_native_input(+ composite_key,+ "ambiguous input",+ kind="steer",+ )+ receipt.state = "unknown"+ agent._advance_steering_generation(composite_key)++ class _ConsumedClient:+ def receive_messages(self):+ async def _iterate():+ primary = _ResultMessage()+ primary.result = "primary result"+ yield primary+ yield UserMessage("ambiguous input")++ return _iterate()++ await agent._receive_messages(+ _ConsumedClient(),+ "session-ambiguous-consumed",+ "/tmp/work",+ context,+ composite_key=composite_key,+ )++ agent.controller.emit_agent_message.assert_awaited_once_with(+ context,+ "output",+ "primary result",+ parse_mode="markdown",+ output=ANY,+ )+ agent.emit_result_message.assert_not_awaited()+ agent._handle_receiver_eof.assert_awaited_once_with(composite_key, context)+ self.assertNotIn(composite_key, agent._ambiguous_primary_results)+async def test_failed_ambiguous_half_close_preserves_work_until_later_result(self):mark_idle_calls: list[str] = []agent = _build_agent(mark_idle_calls)@@ -605,6 +676,7 @@ class ResultSettlesTurnOnEmitFailureTests(unittest.IsolatedAsyncioTestCase):result_yielded.set()yield primaryawait second_result_ready.wait()+ yield UserMessage("ambiguous input")second = _ResultMessage()second.result = "reconciled result"yield second@@ -765,7 +837,7 @@ class ResultSettlesTurnOnEmitFailureTests(unittest.IsolatedAsyncioTestCase):receiver_task.cancel()await asyncio.gather(receiver_task, return_exceptions=True)- async def test_unmatched_activity_flush_does_not_consume_terminal_barrier(self):+ async def test_unmatched_activity_flush_preserves_pending_input_receipt(self):mark_idle_calls: list[str] = []agent = _build_agent(mark_idle_calls)context = SimpleNamespace(user_id="U1", channel_id="C1", platform_specific={})@@ -776,6 +848,12 @@ class ResultSettlesTurnOnEmitFailureTests(unittest.IsolatedAsyncioTestCase):agent._activity_registry = lambda: registryagent._claim_activity_batch_for_turns = Mock(return_value=[])expected_generation = agent._steering_generation(composite_key)+ receipt = agent._register_native_input(+ composite_key,+ "steered prompt",+ kind="steer",+ )+ receipt.state = "unknown"agent._advance_steering_generation(composite_key)retry = await agent._flush_completed_activity_outputs(@@ -785,7 +863,7 @@ class ResultSettlesTurnOnEmitFailureTests(unittest.IsolatedAsyncioTestCase):)self.assertTrue(retry)- self.assertEqual(agent._next_terminal_barrier(composite_key), "accepted")+ self.assertEqual(agent._pending_steering_input_state(composite_key), "unknown")self.assertEqual(agent._pending_requests[composite_key], [primary_request])async def test_concurrent_receiver_eof_makes_steering_ack_ambiguous(self):@@ -1202,7 +1280,13 @@ class ResultSettlesTurnOnEmitFailureTests(unittest.IsolatedAsyncioTestCase):agent._pending_requests[composite_key] = [primary_request]agent.emit_result_message = AsyncMock(return_value=None)agent._detect_message_type = lambda message: (- "assistant" if isinstance(message, _AssistantFailureMessage) else "result"+ "assistant"+ if isinstance(message, _AssistantFailureMessage)+ else "system"+ if isinstance(message, SystemMessage)+ else "user"+ if isinstance(message, UserMessage)+ else "result")agent._handle_assistant_terminal_failure = AsyncMock(return_value="failure")consume_suppressed_result = ClaudeAgent._consume_suppressed_synthetic_result.__get__(agent)@@ -1221,6 +1305,7 @@ class ResultSettlesTurnOnEmitFailureTests(unittest.IsolatedAsyncioTestCase):failure_generation_captured = asyncio.Event()paired_result_ready = asyncio.Event()first_steered_result_ready = asyncio.Event()+ first_steered_result_processed = asyncio.Event()second_steered_result_ready = asyncio.Event()class _SteeringClient:@@ -1237,10 +1322,13 @@ class ResultSettlesTurnOnEmitFailureTests(unittest.IsolatedAsyncioTestCase):failed.result = "primary failed"yield failedawait first_steered_result_ready.wait()+ yield UserMessage("continue after failure")first_steered = _ResultMessage()first_steered.result = "first steered result"yield first_steered+ first_steered_result_processed.set()await second_steered_result_ready.wait()+ yield UserMessage("continue after failure")second_steered = _ResultMessage()second_steered.result = "second steered result"yield second_steered@@ -1300,6 +1388,7 @@ class ResultSettlesTurnOnEmitFailureTests(unittest.IsolatedAsyncioTestCase):second_receipt = await agent.steer_active_turn(request, target)self.assertIs(second_receipt.outcome, SteerOutcome.ACCEPTED)+ client._transport.end_input.assert_not_awaited()paired_result_ready.set()await paired_result_consumed.wait()@@ -1307,6 +1396,7 @@ class ResultSettlesTurnOnEmitFailureTests(unittest.IsolatedAsyncioTestCase):agent.emit_result_message.assert_not_awaited()first_steered_result_ready.set()+ await first_steered_result_processed.wait()await asyncio.sleep(0)self.assertEqual(agent._pending_requests[composite_key], [primary_request])agent.emit_result_message.assert_not_awaited()diff --git a/tests/test_message_dispatcher_result_fallback.py b/tests/test_message_dispatcher_result_fallback.pyindex 268ae72bd..75e2d30c6 100644--- a/tests/test_message_dispatcher_result_fallback.py+++ b/tests/test_message_dispatcher_result_fallback.py@@ -1073,6 +1073,68 @@ class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):persist.assert_called_once()self.assertEqual(persist.call_args.args[1], "notify")+ async def test_output_is_delivered_and_persisted_without_settling(self):+ controller = _StubController(platform="slack")+ dispatcher = ConsolidatedMessageDispatcher(controller)+ context = MessageContext(user_id="U1", channel_id="C1", platform="slack")++ with (+ mock.patch(+ "core.message_dispatcher.persist_agent_message",+ return_value={"id": "msg-output"},+ ) as persist,+ mock.patch(+ "core.message_dispatcher._stream_chunk",+ new=mock.AsyncMock(),+ ) as stream,+ ):+ message_id = await dispatcher.emit_agent_message(+ context,+ "output",+ "primary answer",+ output=MessageOutput(completes_turn=False, completes_run=False),+ )++ self.assertEqual(message_id, "msg-1")+ self.assertEqual(controller.im_client.sent_messages, [("C1", "primary answer", "markdown")])+ self.assertEqual(persist.call_args.args[1], "output")+ stream.assert_awaited_once()+ self.assertEqual(stream.call_args.kwargs["kind"], "output")+ self.assertFalse(stream.call_args.kwargs["completes_turn"])++ async def test_output_can_explicitly_skip_agent_run_recording(self):+ controller = _StubController(platform="slack")+ dispatcher = ConsolidatedMessageDispatcher(controller)+ context = MessageContext(+ user_id="U1",+ channel_id="C1",+ platform="slack",+ platform_specific={"accepted_agent_run_ids": ["run-steer"]},+ )++ with (+ mock.patch(+ "core.message_dispatcher.persist_agent_message",+ return_value={"id": "msg-output"},+ ),+ mock.patch.object(+ dispatcher,+ "_record_agent_run_terminal_for_ids",+ ) as record,+ ):+ await dispatcher.emit_agent_message(+ context,+ "output",+ "primary answer",+ output=MessageOutput(+ completes_turn=False,+ completes_run=False,+ records_run_output=False,+ ),+ )++ record.assert_not_called()+async def test_notify_not_persisted_when_send_fails(self):class _FailClient(_StubIMClient):async def send_message(self, *args, **kwargs):diff --git a/tests/test_message_mirror.py b/tests/test_message_mirror.pyindex ef8f583d5..9b5914b12 100644--- a/tests/test_message_mirror.py+++ b/tests/test_message_mirror.py@@ -686,6 +686,76 @@ def test_persist_agent_assistant_publishes_when_activity_enabled(isolated_state,assert [m["type"] for m in every["messages"]] == ["assistant"]+def test_persist_agent_output_is_visible_without_activity_streaming(+ isolated_state,+ monkeypatch,+):+ import core.message_mirror as mm+ from core import inbox_events++ monkeypatch.setattr(mm, "_activity_streaming_enabled", lambda: False)++ 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_output",+ now=now,+ )+ conn.execute(+ agent_sessions.insert().values(+ id="ses_output",+ scope_id=scope_id,+ agent_backend="claude",+ agent_variant="default",+ session_anchor="anchor_ses_output",+ native_session_id="",+ status="active",+ metadata_json="{}",+ created_at=now,+ updated_at=now,+ last_active_at=now,+ )+ )++ ctx = MessageContext(+ user_id="workbench",+ channel_id="ses_output",+ platform="avibe",+ platform_specific={"agent_session_id": "ses_output"},+ )++ async def scenario():+ sub_id, queue = inbox_events.bus.subscribe()+ events: dict[str, dict] = {}+ try:+ persist_agent_message(ctx, "output", "primary answer")+ for _ in range(2):+ event = await asyncio.wait_for(queue.get(), timeout=1.0)+ events[event[0]] = event[1]+ finally:+ inbox_events.bus.unsubscribe(sub_id)+ return events++ events = asyncio.run(scenario())+ assert events["message.new"]["type"] == "output"+ assert events["message.new"]["text"] == "primary answer"+ assert events["inbox.session.updated"]["preview_text"] == "primary answer"+ assert events["inbox.session.updated"]["replied"] is False++ with engine.connect() as conn:+ transcript = messages_service.list_session_messages(+ conn,+ session_id="ses_output",+ )+ assert [(row["type"], row["text"]) for row in transcript["messages"]] == [+ ("output", "primary answer")+ ]++def test_persist_system_message_is_not_persisted(isolated_state):"""A canonical ``system`` message (init banner / status line — generated byus, not the agent) is NOT persisted at all and publishes nothing (userdiff --git a/tests/test_message_type_catalog.py b/tests/test_message_type_catalog.pyindex 4b30c56f4..a07fa19b6 100644--- a/tests/test_message_type_catalog.py+++ b/tests/test_message_type_catalog.py@@ -86,7 +86,15 @@ def test_catalog_resource_and_defaults_are_cross_language_data() -> None:def test_transcript_types_match_current_constant() -> None:- expected = ("user", "harness", "annotation", "result", "notify", "error")+ expected = (+ "user",+ "harness",+ "annotation",+ "output",+ "result",+ "notify",+ "error",+ )assert types_with("transcript") == expectedassert messages_service.TRANSCRIPT_TYPES == expected@@ -95,13 +103,23 @@ def test_searchable_types_match_current_default_query() -> None:connection = _CaptureConnection()messages_service.search_messages(connection, query="catalog-probe")- expected = ("user", "harness", "annotation", "result")+ expected = ("user", "harness", "annotation", "output", "result")assert types_with("searchable") == expectedassert _message_type_sequences(connection.statements[-1]) == {expected}def test_inbox_activity_types_match_current_constant() -> None:- expected = ("user", "harness", "annotation", "result", "notify", "error", "assistant")+ expected = (+ "user",+ "harness",+ "agent_initiated",+ "annotation",+ "output",+ "result",+ "notify",+ "error",+ "assistant",+ )assert types_with("inboxActivity") == expectedassert messages_service.INBOX_ACTIVITY_TYPES == expected@@ -111,7 +129,7 @@ def test_inbox_preview_and_settlement_types_match_current_query() -> None:messages_service.list_inbox_sessions(connection)current_query_sets = _message_type_sequences(connection.statements[-1])- expected_preview = ("result", "notify", "error")+ expected_preview = ("output", "result", "notify", "error")expected_settlement = ("result", "notify", "error")expected_unread = ("result",)assert types_with("inboxPreview") == expected_preview@@ -142,6 +160,7 @@ def test_input_turn_pairs_match_current_constant() -> None:expected = (("user", "user"),("harness", "harness"),+ ("harness", "agent_initiated"),("harness", "annotation"),)assert input_author_type_pairs() == expected@@ -166,6 +185,7 @@ def test_annotation_catalog_contract_is_explicit() -> None:def test_activity_fetch_and_terminal_semantics_match_current_service() -> None:+ assert spec_for("output")["activityRole"] == "boundary"derived_relevant = {message_typefor message_type in _catalog_types()@@ -175,6 +195,8 @@ def test_activity_fetch_and_terminal_semantics_match_current_service() -> None:expected_relevant = ("user","harness",+ "agent_initiated",+ "output","result","notify","error",diff --git a/tests/test_message_type_python_consumers.py b/tests/test_message_type_python_consumers.pyindex 8abe7b43e..64b6d938c 100644--- a/tests/test_message_type_python_consumers.py+++ b/tests/test_message_type_python_consumers.py@@ -10,6 +10,7 @@ def test_backend_failure_predicate_matches_legacy_type_and_event_pair() -> None:"user","harness","annotation",+ "output","result","notify","error",@@ -47,6 +48,7 @@ def test_fork_activity_sets_match_legacy_values() -> None:}assert session_fork.SOURCE_PROGRESS_AGENT_OUTPUT_TYPES == {"assistant",+ "output","result","error",}@@ -54,6 +56,7 @@ def test_fork_activity_sets_match_legacy_values() -> None:"user","harness","annotation",+ "output","result","notify","error",@@ -61,11 +64,16 @@ def test_fork_activity_sets_match_legacy_values() -> None:def test_show_git_input_message_types_match_legacy_values() -> None:- assert show_git._INPUT_TURN_MESSAGE_TYPES == ("user", "harness", "annotation")+ assert show_git._INPUT_TURN_MESSAGE_TYPES == (+ "user",+ "harness",+ "agent_initiated",+ "annotation",+ )def test_mirror_catalog_roles_match_legacy_type_sets() -> None:- assert set(types_with("inboxPreview")) == {"result", "notify", "error"}+ assert set(types_with("inboxPreview")) == {"output", "result", "notify", "error"}assert {message_typefor message_type in types_with("activityRole")diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.pyindex 5290ebab2..8045cb1f7 100644--- a/tests/test_session_delivery_fsm.py+++ b/tests/test_session_delivery_fsm.py@@ -5933,9 +5933,11 @@ async def test_terminal_commit_publishes_replyless_inbox_settlement(@pytest.mark.anyio-async def test_agent_initiated_continuation_materializes_in_configured_language(+async def test_agent_initiated_continuation_materializes_as_hidden_turn_input(managers,) -> None:+ """HFR-461: backend continuation keeps a hidden lifecycle input."""+manager, _other, engine, _engine_b, _starts = managersmanager.controller.config.language = "zh"context = _context()@@ -5943,8 +5945,15 @@ async def test_agent_initiated_continuation_materializes_in_configured_language(assert manager.register_agent_initiated_turn(context) is Truewith engine.connect() as conn:row = messages_service.get_message(conn, str(context.message_id))+ transcript = messages_service.list_session_messages(+ conn,+ session_id="ses_fsm",+ types=messages_service.TRANSCRIPT_TYPES,+ )assert row is not None+ assert row["type"] == "agent_initiated"assert row["text"] == "Agent 主动发起的续接"+ assert transcript["messages"] == []sink = manager.get_turn_sink(manager.controller._get_session_key(context))assert sink is not Nonediff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.pyindex feda087f7..b19a877bc 100644--- a/tests/test_sqlite_state_migration.py+++ b/tests/test_sqlite_state_migration.py@@ -31,18 +31,20 @@ from vibe.message_types import build_partial_index_predicatepytestmark = pytest.mark.no_sqlite_template-HEAD_REVISION = "20260806_0047"+HEAD_REVISION = "20260808_0048"MESSAGE_PARTIAL_INDEX_PREDICATES = {"ix_messages_inbox_activity": ("session_id is not null and type in "- "('user', 'harness', 'annotation', 'result', 'notify', 'error', 'assistant')"+ "('user', 'harness', 'agent_initiated', 'annotation', 'output', "+ "'result', 'notify', 'error', 'assistant')"),"ix_messages_inbox_agent_reply": (- "session_id is not null and type in ('result', 'notify', 'error')"+ "session_id is not null and type in ('output', 'result', 'notify', 'error')"),"ix_messages_inbox_user_send": ("session_id is not null and ((author = 'user' and type = 'user') ""or (author = 'harness' and type = 'harness') "+ "or (author = 'harness' and type = 'agent_initiated') ""or (author = 'harness' and type = 'annotation'))"),}@@ -75,16 +77,57 @@ def test_message_partial_index_ddl_matches_catalog_contract()-def test_show_annotation_migration_predicate_matches_catalog() -> None:+def test_agent_lifecycle_message_index_migration_matches_catalog() -> None:migration = import_module(- "storage.alembic.versions.20260727_0038_show_annotation_type"+ "storage.alembic.versions.20260808_0048_agent_lifecycle_message_indexes")+ assert migration.UPGRADE_ACTIVITY_PREDICATE == build_partial_index_predicate(+ "ix_messages_inbox_activity"+ )+ assert migration.UPGRADE_AGENT_REPLY_PREDICATE == build_partial_index_predicate(+ "ix_messages_inbox_agent_reply"+ )assert migration.UPGRADE_USER_SEND_PREDICATE == build_partial_index_predicate("ix_messages_inbox_user_send")+def test_agent_lifecycle_message_index_migration_upgrades_and_downgrades(+ tmp_path: Path,+) -> None:+ db_path = tmp_path / "vibe.sqlite"+ run_migrations(db_path, revision="20260806_0047")++ with sqlite3.connect(db_path) as conn:+ previous_activity = _index_sql(conn, "ix_messages_inbox_activity")+ previous_agent_reply = _index_sql(conn, "ix_messages_inbox_agent_reply")+ previous_user_send = _index_sql(conn, "ix_messages_inbox_user_send")++ run_migrations(db_path)++ with sqlite3.connect(db_path) as conn:+ assert _index_sql(conn, "ix_messages_inbox_activity").endswith(+ MESSAGE_PARTIAL_INDEX_PREDICATES["ix_messages_inbox_activity"]+ )+ assert _index_sql(conn, "ix_messages_inbox_user_send").endswith(+ MESSAGE_PARTIAL_INDEX_PREDICATES["ix_messages_inbox_user_send"]+ )+ assert _index_sql(conn, "ix_messages_inbox_agent_reply").endswith(+ MESSAGE_PARTIAL_INDEX_PREDICATES["ix_messages_inbox_agent_reply"]+ )+ assert conn.execute("select version_num from alembic_version").fetchone() == (+ HEAD_REVISION,+ )++ command.downgrade(migrations.alembic_config(db_path), "20260806_0047")++ with sqlite3.connect(db_path) as conn:+ assert _index_sql(conn, "ix_messages_inbox_activity") == previous_activity+ assert _index_sql(conn, "ix_messages_inbox_agent_reply") == previous_agent_reply+ assert _index_sql(conn, "ix_messages_inbox_user_send") == previous_user_send++class _Pre335Cursor(sqlite3.Cursor):def execute(self, sql, parameters=()):normalized = " ".join(str(sql).upper().split())diff --git a/ui/src/lib/chatMessageTypes.test.ts b/ui/src/lib/chatMessageTypes.test.tsindex 94d308d8e..86909efd2 100644--- a/ui/src/lib/chatMessageTypes.test.ts+++ b/ui/src/lib/chatMessageTypes.test.ts@@ -4,7 +4,7 @@ import { isNotifyMessageType, isTerminalAgentMessage, isTranscriptMessage } fromdescribe('isTranscriptMessage', () => {it('shows the rows the transcript has always shown, and hides process log', () => {- for (const type of ['user', 'harness', 'result', 'notify', 'error']) {+ for (const type of ['user', 'harness', 'output', 'result', 'notify', 'error']) {expect(isTranscriptMessage({ type }), type).toBe(true);}for (const type of ['assistant', 'tool_call', 'draft', 'pending', 'silent', 'future_type']) {@@ -60,6 +60,7 @@ describe('isTerminalAgentMessage', () => {});it('keeps ordinary notifications and user rows nonterminal', () => {+ expect(isTerminalAgentMessage({ author: 'agent', type: 'output' })).toBe(false);expect(isTerminalAgentMessage({ author: 'agent', type: 'notify' })).toBe(false);expect(isTerminalAgentMessage({diff --git a/ui/src/lib/messageTypes.test.ts b/ui/src/lib/messageTypes.test.tsindex 1fe255942..6e3d34036 100644--- a/ui/src/lib/messageTypes.test.ts+++ b/ui/src/lib/messageTypes.test.ts@@ -41,7 +41,9 @@ const RETIRED_PSEUDO_MESSAGE_TYPES = [const CANONICAL_MESSAGE_TYPES = ['user','harness',+ 'agent_initiated','annotation',+ 'output','result','notify','error',@@ -60,6 +62,7 @@ const wasTranscript = (type: string): boolean =>type === 'user' ||type === 'harness' ||type === 'annotation' ||+ type === 'output' ||type === 'result' ||type === 'error' ||type === 'notify';@@ -68,7 +71,8 @@ const wasNotify = (type: string): boolean => type === 'notify' || type === 'erroconst wasActivity = (type: string): boolean => type === 'assistant';-const wasHarnessInputType = (type: string): boolean => type === 'harness' || type === 'annotation';+const wasHarnessInputType = (type: string): boolean =>+ type === 'harness' || type === 'agent_initiated' || type === 'annotation';type TerminalCandidate = { author: string; type: string; metadata?: Record<string, unknown> | null };diff --git a/vibe/message_types.json b/vibe/message_types.jsonindex f0e6ead5a..471f2a03c 100644--- a/vibe/message_types.json+++ b/vibe/message_types.json@@ -34,6 +34,13 @@"activityRole": "turn_start","render": "harness"},+ "agent_initiated": {+ "inboxActivity": true,+ "inputAuthors": [+ "harness"+ ],+ "activityRole": "turn_start"+ },"annotation": {"transcript": true,"searchable": true,@@ -41,6 +48,14 @@"inputAuthors": ["harness"],"render": "annotation"},+ "output": {+ "transcript": true,+ "searchable": true,+ "inboxActivity": true,+ "inboxPreview": true,+ "activityRole": "boundary",+ "render": "agent"+ },"result": {"transcript": true,"searchable": true,diff --git a/vibe/message_types.py b/vibe/message_types.pyindex 852872a22..2c420086a 100644--- a/vibe/message_types.py+++ b/vibe/message_types.py@@ -22,7 +22,7 @@ _LIST_PROPERTIES = {"webPushWhenEvents",}_ENUM_PROPERTIES = {- "activityRole": {"none", "turn_start", "activity", "terminal"},+ "activityRole": {"none", "turn_start", "activity", "boundary", "terminal"},"render": {"none","user",