Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
fix(runtime): preserve recovery history and prevent unsafe MCP replays (#6537)
chengyongru384b7638307e
diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.pyindex f7e30917b..eed12efdd 100644--- a/nanobot/agent/loop.py+++ b/nanobot/agent/loop.py@@ -1048,6 +1048,10 @@ class AgentLoop:if session is None or ephemeral:returnpublic_payload = dict(payload)+ preceding = Session(key=session.key)+ self._save_turn(preceding, public_payload["preceding_messages"], skip=0)+ public_payload["preceding_messages"] = preceding.messages+ public_payload["consumed_followup_ids"] = sorted(preceding.consumed_followup_ids)private_state = public_payload.pop("provider_state", None)public_payload.pop(self._PROVIDER_STATE_CHECKPOINT_VERSION_KEY, None)if "provider_state" in payload and (diff --git a/nanobot/agent/runner.py b/nanobot/agent/runner.pyindex bede1f154..b1ce652fb 100644--- a/nanobot/agent/runner.py+++ b/nanobot/agent/runner.py@@ -222,6 +222,7 @@ class AgentRunner:await self._emit_checkpoint(spec,checkpoint,+ messages,)self._append_injected_messages(messages, injections)if real_injection:@@ -549,6 +550,7 @@ class AgentRunner:"completed_tool_results": [],"pending_tool_calls": [tc.to_openai_tool_call() for tc in response.tool_calls],},+ messages,)await hook.before_execute_tools(context)@@ -609,6 +611,7 @@ class AgentRunner:model_messages=checkpoint_model_messages,),},+ messages,)empty_content_retries = 0length_recovery_parts.clear()@@ -832,6 +835,7 @@ class AgentRunner:"pending_tool_calls": [],"provider_state": conversation_state.checkpoint(messages),},+ messages,)if length_recovery_parts:final_content = (@@ -1405,10 +1409,22 @@ class AgentRunner:self,spec: AgentRunSpec,payload: dict[str, Any],+ messages: list[dict[str, Any]],) -> None:callback = spec.checkpoint_callbackif callback is not None:- await callback(payload)+ if spec.transcript_input is not None:+ start = spec.transcript_input.message_count+ else:+ assert spec.initial_messages is not None+ start = len(spec.initial_messages)+ # Replacing the checkpoint must retain every earlier round of this+ # run, including follow-ups consumed since the accepted input.+ batch_size = 1 + len(payload["completed_tool_results"])+ await callback({+ **payload,+ "preceding_messages": messages[start:len(messages) - batch_size],+ })@staticmethoddef _append_final_message(messages: list[dict[str, Any]], content: str | None) -> None:diff --git a/nanobot/agent/tools/mcp.py b/nanobot/agent/tools/mcp.pyindex 720d775d6..daef67910 100644--- a/nanobot/agent/tools/mcp.py+++ b/nanobot/agent/tools/mcp.py@@ -36,9 +36,8 @@ if TYPE_CHECKING:from nanobot.agent.tools.mcp_oauth import MCPOAuthHandlersfrom nanobot.config.schema import Config, MCPServerConfig-# Transient connection errors that warrant a single retry.-# These typically happen when an MCP server restarts or a network-# connection is interrupted between calls.+# Transient stream failures. Retrying also requires an operation safe to replay+# or proof that the tool request has not started._TRANSIENT_EXC_NAMES: frozenset[str] = frozenset(("ClosedResourceError","BrokenResourceError",@@ -522,10 +521,14 @@ class _MCPWrapperBase(Tool):_session: ClientSession_server_name: str_name: str+ _replay_safe: bool- def _set_mcp_connection(self, session: ClientSession, server_name: str) -> None:+ def _set_mcp_connection(+ self, session: ClientSession, server_name: str, *, replay_safe: bool,+ ) -> None:self._session = sessionself._server_name = server_name+ self._replay_safe = replay_safeself._reconnect: _ReconnectCallback | None = Nonedef set_reconnect_handler(self, reconnect: _ReconnectCallback) -> None:@@ -540,14 +543,13 @@ class _MCPWrapperBase(Tool):if already_refreshed or not _is_session_terminated(exc) or self._reconnect is None:return Falselogger.warning(- "MCP {} '{}' session terminated; reconnecting server '{}' before retry",+ "MCP {} '{}' session terminated; reconnecting server '{}'",capability_kind,self._name,self._server_name,)refreshed_tool = await self._reconnect(self._server_name, self._name, self)- refreshed_session = getattr(refreshed_tool, "_session", None)- if refreshed_session is None:+ if not isinstance(refreshed_tool, _MCPWrapperBase):logger.warning("MCP {} '{}' could not refresh session for server '{}'",capability_kind,@@ -555,12 +557,23 @@ class _MCPWrapperBase(Tool):self._server_name,)return False- self._session = refreshed_session+ self._session = refreshed_tool._session+ self._replay_safe = refreshed_tool._replay_safereturn True+ def _unknown_tool_outcome(self, reason: str) -> ToolResult:+ logger.warning(+ "MCP tool '{}' {}; outcome unknown, not replaying", self._name, reason,+ )+ return ToolResult.error(+ f"(MCP tool call outcome is unknown; {reason}. The operation "+ "may have completed and was not replayed after this failure. Check its outcome before "+ "retrying to avoid duplicate side effects.)"+ )+async def _request_with_recovery(self,- request: Callable[[], Awaitable[_MCPResultT]],+ request: Callable[[ClientSession], Awaitable[_MCPResultT]],timeout: float,capability_kind: Literal["tool", "resource", "prompt"],) -> _MCPResultT | ToolResult:@@ -569,10 +582,30 @@ class _MCPWrapperBase(Tool):operation = f"{capability_kind} {'read' if capability_kind == 'resource' else 'call'}"refreshed_session = Falseretried = False+ request_started = False++ async def attempt(session: ClientSession, replay_safe: bool) -> _MCPResultT:+ nonlocal request_started+ if not replay_safe and self._reconnect is not None:+ # Repair stale sessions before submitting a non-replayable call.+ # A failed ping proves that this attempt never called the tool;+ # an exception from call_tool itself cannot provide that proof.+ await session.send_ping()+ request_started = True+ return await request(session)+while True:+ # Keep the declaration bound to the actual session used by this+ # attempt, even if another call reconnects this wrapper meanwhile.+ session, replay_safe = self._session, self._replay_safe+ if request_started and not replay_safe:+ return self._unknown_tool_outcome("no longer permits safe replay after reconnect")try:- return await asyncio.wait_for(request(), timeout=timeout)+ # Preflight and submission share the existing per-attempt timeout.+ return await asyncio.wait_for(attempt(session, replay_safe), timeout=timeout)except asyncio.TimeoutError:+ if request_started and not replay_safe:+ return self._unknown_tool_outcome(f"timed out after {timeout}s")logger.warning("MCP {} '{}' timed out after {}s", capability_kind, self._name, timeout)@@ -584,6 +617,10 @@ class _MCPWrapperBase(Tool):logger.warning("MCP {} '{}' was cancelled by server/SDK", capability_kind, self._name)return ToolResult.error(f"(MCP {operation} was cancelled)")except Exception as exc:+ if request_started and not replay_safe and (+ _is_session_terminated(exc) or isinstance(exc, httpx.TransportError)+ ):+ return self._unknown_tool_outcome(f"lost its response ({type(exc).__name__})")if await self._refresh_session_after_termination(exc, refreshed_session, capability_kind):@@ -673,13 +710,23 @@ class MCPToolWrapper(_MCPWrapperBase):tool_def: MCPToolDefinition,tool_timeout: int = 30,):- self._set_mcp_connection(session, server_name)self._original_name = tool_def.nameself._name = _sanitize_mcp_tool_name(f"mcp_{server_name}_{tool_def.name}")self._description = tool_def.description or tool_def.nameraw_schema = tool_def.inputSchema or {"type": "object", "properties": {}}self._parameters = _normalize_schema_for_openai(raw_schema)self._tool_timeout = tool_timeout+ # Replay is opt-in through explicit server declarations, not inferred+ # from names or destructiveHint=False (additive writes can duplicate).+ # This trusts the server's contract; it is not client-side deduplication+ # and does not change tool permissions or concurrency classification.+ annotations = getattr(tool_def, "annotations", None)+ self._set_mcp_connection(+ session, server_name,+ replay_safe=annotations is not None and (+ annotations.readOnlyHint is True or annotations.idempotentHint is True+ ),+ )@propertydef name(self) -> str:@@ -695,7 +742,7 @@ class MCPToolWrapper(_MCPWrapperBase):async def execute(self, **kwargs: Any) -> str:result = await self._request_with_recovery(- lambda: self._session.call_tool(self._original_name, arguments=kwargs),+ lambda session: session.call_tool(self._original_name, arguments=kwargs),self._tool_timeout,"tool",)@@ -781,7 +828,7 @@ class MCPResourceWrapper(_MCPWrapperBase):resource_def: Resource,resource_timeout: int = 30,):- self._set_mcp_connection(session, server_name)+ self._set_mcp_connection(session, server_name, replay_safe=True)self._uri = resource_def.uriself._name = _sanitize_mcp_tool_name(f"mcp_{server_name}_resource_{resource_def.name}")desc = resource_def.description or resource_def.name@@ -813,12 +860,12 @@ class MCPResourceWrapper(_MCPWrapperBase):from mcp import typesresult = await self._request_with_recovery(- lambda: self._session.read_resource(self._uri),+ lambda session: session.read_resource(self._uri),self._resource_timeout,"resource",)if isinstance(result, ToolResult):- return str(result)+ return resultparts: list[str] = []for block in result.contents:if isinstance(block, types.TextResourceContents):@@ -842,7 +889,7 @@ class MCPPromptWrapper(_MCPWrapperBase):prompt_def: Prompt,prompt_timeout: int = 30,):- self._set_mcp_connection(session, server_name)+ self._set_mcp_connection(session, server_name, replay_safe=True)self._prompt_name = prompt_def.nameself._name = _sanitize_mcp_tool_name(f"mcp_{server_name}_prompt_{prompt_def.name}")desc = prompt_def.description or prompt_def.name@@ -887,12 +934,12 @@ class MCPPromptWrapper(_MCPWrapperBase):from mcp import typesresult = await self._request_with_recovery(- lambda: self._session.get_prompt(self._prompt_name, arguments=kwargs),+ lambda session: session.get_prompt(self._prompt_name, arguments=kwargs),self._prompt_timeout,"prompt",)if isinstance(result, ToolResult):- return str(result)+ return resultparts: list[str] = []for message in result.messages:content = message.contentdiff --git a/nanobot/cli/gateway_runtime.py b/nanobot/cli/gateway_runtime.pyindex 6bf3300f5..f71e61a41 100644--- a/nanobot/cli/gateway_runtime.py+++ b/nanobot/cli/gateway_runtime.py@@ -992,7 +992,6 @@ def _run_claimed_gateway(tasks: list[asyncio.Task[Any]] = []shutdown_task: asyncio.Task[Any] | None = Noneruntime_tasks: asyncio.Future[list[Any]] | None = None- startup_complete = Falseshutdown_event = asyncio.Event()cli_terminal._ensure_interactive_tty_mode()restore_shutdown_handlers = _install_gateway_shutdown_handlers(@@ -1096,7 +1095,6 @@ def _run_claimed_gateway(name="nanobot-webui-dev-server",))runtime_tasks = asyncio.gather(*tasks)- startup_complete = Trueshutdown_task = asyncio.create_task(shutdown_event.wait(),name="nanobot-gateway-shutdown",@@ -1118,10 +1116,7 @@ def _run_claimed_gateway(console.print("\n[red]Error: Gateway crashed unexpectedly[/red]")console.print(traceback.format_exc())- if not startup_complete:- # Do not report a successful gateway command when startup- # failed before any runtime task or listener was created.- raise typer.Exit(1)+ raise typer.Exit(1)finally:try:if shutdown_task and not shutdown_task.done():diff --git a/nanobot/session/recovery.py b/nanobot/session/recovery.pyindex e2a81d6d0..a3febe68a 100644--- a/nanobot/session/recovery.py+++ b/nanobot/session/recovery.py@@ -215,6 +215,33 @@ def _checkpoint_tool_call_ids(return ids if len(ids) == len(set(ids)) else None+def _checkpoint_prefix_is_complete(value: object) -> bool:+ if not isinstance(value, list):+ return False+ pending: set[str] = set()+ for value_row in cast(list[object], value):+ if not isinstance(value_row, dict):+ return False+ row = cast(dict[str, Any], value_row)+ role = row.get("role")+ if role == "tool":+ call_id = row.get("tool_call_id")+ if not isinstance(call_id, str) or call_id not in pending:+ return False+ pending.remove(call_id)+ elif role in ("user", "assistant"):+ if pending:+ return False+ if role == "assistant" and row.get("tool_calls") is not None:+ ids = _checkpoint_tool_call_ids(row["tool_calls"])+ if ids is None:+ return False+ pending.update(ids)+ else:+ return False+ return not pending++def runtime_checkpoint_is_well_formed(checkpoint: Mapping[str, Any]) -> bool:"""Return whether a checkpoint is safe to offer for continuation.@@ -222,6 +249,8 @@ def runtime_checkpoint_is_well_formed(checkpoint: Mapping[str, Any]) -> bool:Continue is stricter: silently dropping a malformed tool result could makethe model repeat an external side effect."""+ if not _checkpoint_prefix_is_complete(checkpoint.get("preceding_messages", [])):+ return Falseassistant_value = cast(object, checkpoint.get("assistant_message"))if not isinstance(assistant_value, dict):return False@@ -294,7 +323,11 @@ def restore_runtime_checkpoint(session: Session) -> bool:completed = cast(list[object], completed_value) if isinstance(completed_value, list) else []pending = cast(list[object], pending_value) if isinstance(pending_value, list) else []- restored: list[dict[str, Any]] = []+ preceding = data.get("preceding_messages", [])+ restored = (+ [dict(cast(dict[str, Any], row)) for row in cast(list[object], preceding) if isinstance(row, dict)]+ if isinstance(preceding, list) else []+ )if isinstance(assistant, dict):assistant_row = cast(dict[str, Any], assistant)else:@@ -331,21 +364,31 @@ def restore_runtime_checkpoint(session: Session) -> bool:"role": "tool","tool_call_id": tool_call_id,"name": name if isinstance(name, str) and name else "tool",- "content": "Error: Task interrupted before this tool finished.",+ "content": "Error: Task interrupted; this tool's outcome is unknown. Check its effects before retrying.","timestamp": datetime.now().isoformat(),"_recovery_interrupted": True,})overlap = 0- for size in range(min(len(session.messages), len(restored)), 0, -1):- if all(- _checkpoint_message_key(left) == _checkpoint_message_key(right)- for left, right in zip(session.messages[-size:], restored[:size])- ):- overlap = size- break+ # Cumulative checkpoints contain only the delta after accepted input. The+ # owner commits it and clears the checkpoint in one transaction, so none of+ # it is already in history. Equal text can belong to distinct user inputs.+ # Only legacy single-batch checkpoints may overlap a materialized tail.+ if "preceding_messages" not in data:+ for size in range(min(len(session.messages), len(restored)), 0, -1):+ if all(+ _checkpoint_message_key(left) == _checkpoint_message_key(right)+ for left, right in zip(session.messages[-size:], restored[:size])+ ):+ overlap = size+ breaksession.messages.extend(restored[overlap:])+ followup_ids = data.get("consumed_followup_ids", [])+ if isinstance(followup_ids, list) and followup_ids:+ session.consumed_followup_ids |= {+ value for value in cast(list[object], followup_ids) if isinstance(value, str)+ }assistant_data = cast(dict[str, Any], assistant) if isinstance(assistant, dict) else Nonesynchronized = (diff --git a/nanobot/webui/recovery.py b/nanobot/webui/recovery.pyindex c1c7fb991..392214cb8 100644--- a/nanobot/webui/recovery.py+++ b/nanobot/webui/recovery.py@@ -143,6 +143,12 @@ class RecoveryCoordinator:state = recovery_state_from_metadata(session.metadata)if state and state["status"] in {"resuming", "awaiting_user", "failed"}:await self._cancel_active_recovery(message.session_key)+ # Cancellation may have committed the checkpoint or completed the+ # recovery. Classify a fresh owner draft after that handoff.+ session = await self.sessions.state.get(message.session_key)+ state = recovery_state_from_metadata(session.metadata)+ if not state or state["status"] not in {"resuming", "awaiting_user", "failed"}:+ return Trueif state.get("reason") != "model_request_failed":restore_runtime_checkpoint(session)if not restore_pending_interruption(session, superseded=True):diff --git a/tests/agent/test_loop_recovery.py b/tests/agent/test_loop_recovery.pyindex 05eaecb69..617b17c6e 100644--- a/tests/agent/test_loop_recovery.py+++ b/tests/agent/test_loop_recovery.py@@ -13,6 +13,7 @@ from nanobot.agent.turn_delivery import TurnDeliveryFactoryfrom nanobot.bus.events import InboundMessage, OutboundMessagefrom nanobot.bus.queue import MessageBusfrom nanobot.providers.base import GenerationSettings, LLMProvider, LLMResponse, ToolCallRequest+from nanobot.runtime_context import public_history_messagefrom nanobot.session.manager import SessionManagerfrom nanobot.session.recovery import (PENDING_USER_TURN_KEY,@@ -355,3 +356,188 @@ async def test_recovery_distinguishes_explicit_stop_from_gateway_shutdown(assert RECOVERY_METADATA_KEY not in restored.metadatafinally:await restarted.state.aclose()+++def _recovery_loop(tmp_path, provider, sessions=None):+ bus = MessageBus()+ sessions = sessions or SessionManager(tmp_path)+ recovery = RecoveryCoordinator(sessions, bus)+ loop = AgentLoop(+ bus=bus, provider=provider, workspace=tmp_path, model="test-model",+ session_manager=sessions, recovery_admission=recovery,+ turn_delivery_factory=TurnDeliveryFactory(bus, WebuiTurnRoutePolicy(sessions)),+ )+ return loop, recovery++[email protected](("boundary", "gateway_shutdown"), [+ ("awaiting_tools", False), ("tools_completed", False), ("final_response", False),+ ("awaiting_tools", True), ("tools_completed", True), ("final_response", True),+ ("completed", False),+])+async def test_multiround_recovery_keeps_completed_work_and_consumed_followup(+ tmp_path, monkeypatch, boundary, gateway_shutdown,+):+ from nanobot.session.recovery import pending_followups++ provider = MagicMock(aclose=AsyncMock())+ provider.get_default_model.return_value = "test-model"+ provider.generation = GenerationSettings()+ provider.can_resume_conversation_state.return_value = False+ requests = []+ responses = iter([+ LLMResponse(content=None, tool_calls=[ToolCallRequest("A", "read_file", {"path": "A.txt"})]),+ LLMResponse(content=None, tool_calls=[ToolCallRequest("B", "read_file", {"path": "B.txt"})]),+ LLMResponse(content="Both results received."),+ LLMResponse(content="Continued without repeating work."),+ ])++ async def respond(**kwargs):+ requests.append(deepcopy(kwargs["messages"]))+ return next(responses)++ provider.chat_stream_with_retry = AsyncMock(side_effect=respond)+ loop, recovery = _recovery_loop(tmp_path, provider)+ first_tool = asyncio.Event()+ release_first = asyncio.Event()+ reached = asyncio.Event()+ attempts = []+ tool = loop.tools.get("read_file")++ async def read(path, **kwargs):+ attempts.append(path)+ if path == "A.txt":+ first_tool.set()+ await release_first.wait()+ elif boundary == "awaiting_tools":+ reached.set()+ await asyncio.Event().wait()+ return f"result for {path}"++ monkeypatch.setattr(tool, "execute", read)+ checkpoint = loop._set_runtime_checkpoint++ async def save_checkpoint(session, payload):+ await checkpoint(session, payload)+ if payload["iteration"] > 0 and payload["phase"] == boundary and boundary != "awaiting_tools":+ reached.set()+ await asyncio.Event().wait()++ monkeypatch.setattr(loop, "_set_runtime_checkpoint", save_checkpoint)+ request = InboundMessage(+ channel="websocket", sender_id="user", chat_id="chat", content="Read two notes",+ metadata={"webui": True, "webui_turn_id": "initial"},+ )+ try:+ await loop._dispatch_inbound(request)+ await asyncio.wait_for(first_tool.wait(), 5)+ await loop._dispatch_inbound(InboundMessage(+ channel="websocket", sender_id="user", chat_id="chat", content="Keep both results",+ metadata={"webui": True, "webui_turn_id": "followup"},+ ))+ release_first.set()+ if boundary == "completed":+ await asyncio.gather(*loop._active_tasks[request.session_key])+ else:+ await asyncio.wait_for(reached.wait(), 5)+ if gateway_shutdown:+ loop.preserve_inflight_turns_on_shutdown()+ else:+ await loop._dispatch_inbound(InboundMessage(+ channel="websocket", sender_id="user", chat_id="chat", content="/stop",+ ))+ finally:+ await loop.aclose()++ sessions = SessionManager(tmp_path)+ resumed, recovery = _recovery_loop(tmp_path, provider, sessions)+ try:+ await recovery.scan()+ stored = await sessions.state.get(request.session_key)+ tools = [row for row in stored.messages if row["role"] == "tool"]+ assert [row["tool_call_id"] for row in tools] == ["A", "B"]+ assert tools[0]["content"] == "result for A.txt"+ if boundary == "awaiting_tools":+ assert tools[1]["_recovery_interrupted"] is True+ assert "outcome is unknown" in tools[1]["content"]+ else:+ assert tools[1]["content"] == "result for B.txt"+ assert [public_history_message(row)["content"] for row in stored.messages if row["role"] == "user"] == [+ "Read two notes", "Keep both results",+ ]+ assert pending_followups(stored) == []+ assert resumed.bus.inbound.empty()+ calls = [call["id"] for row in stored.messages for call in row.get("tool_calls", [])]+ assert calls == ["A", "B"]+ if boundary in {"final_response", "completed"}:+ assert stored.messages[-1]["content"] == "Both results received."+ if gateway_shutdown and boundary in {"awaiting_tools", "tools_completed"}:+ state = stored.metadata[RECOVERY_METADATA_KEY]+ assert state["status"] == "awaiting_user"+ await recovery.handle_action("continue", {"chat_id": "chat", "recovery_id": state["recovery_id"]})+ await resumed._dispatch_one(resumed.bus.inbound.get_nowait(), asyncio.Queue())+ history = requests[-1]+ assert [row["tool_call_id"] for row in history if row["role"] == "tool"] == ["A", "B"]+ assert attempts == ["A.txt", "B.txt"]+ finally:+ await resumed.aclose()+++async def test_new_input_waits_for_real_recovery_cancellation_before_reading_draft(tmp_path, monkeypatch):+ provider = MagicMock(aclose=AsyncMock())+ provider.get_default_model.return_value = "test-model"+ provider.generation = GenerationSettings()+ provider.can_resume_conversation_state.return_value = False+ provider.chat_stream_with_retry = AsyncMock(side_effect=[+ LLMResponse(content=None, tool_calls=[ToolCallRequest("C", "read_file", {"path": "C.txt"})]),+ LLMResponse(content="New input answered."),+ ])+ loop, recovery = _recovery_loop(tmp_path, provider)+ session = await loop.sessions.state.get("websocket:chat")+ session.add_message("user", "Earlier request")+ session.metadata["title"] = "Recovery handoff"+ session.metadata[RECOVERY_METADATA_KEY] = {+ "status": "awaiting_user", "recovery_id": "recover", "attempts": 0,+ }+ await loop.sessions.state.prepare_input(session)+ entered = asyncio.Event()+ cancelled = asyncio.Event()++ async def read(**kwargs):+ entered.set()+ try:+ await asyncio.Event().wait()+ finally:+ cancelled.set()++ monkeypatch.setattr(loop.tools.get("read_file"), "execute", read)+ coordinator = WebuiTurnCoordinator(loop.bus, loop.sessions, loop.schedule_background, recovery=recovery)+ try:+ with coordinator.connected():+ await recovery.handle_action("continue", {"chat_id": "chat", "recovery_id": "recover"})+ await loop._dispatch_inbound(loop.bus.inbound.get_nowait())+ await asyncio.wait_for(entered.wait(), 5)+ old_tasks = tuple(loop._active_tasks[session.key])+ await loop._dispatch_inbound(InboundMessage(+ channel="websocket", sender_id="user", chat_id="chat", content="Replace the old task",+ metadata={"webui": True, "webui_turn_id": "new-input"},+ ))+ assert cancelled.is_set()+ assert all(task.done() for task in old_tasks)+ await asyncio.gather(*loop._active_tasks[session.key])+ finally:+ await loop.aclose()++ reopened = SessionManager(tmp_path)+ try:+ saved = await reopened.state.get(session.key)+ assert [row["tool_call_id"] for row in saved.messages if row["role"] == "tool"] == ["C"]+ assert [call["id"] for row in saved.messages for call in row.get("tool_calls", [])] == ["C"]+ assert [public_history_message(row)["content"] for row in saved.messages if row["role"] == "user"] == [+ "Earlier request", "Replace the old task",+ ]+ assert saved.messages[-1]["content"] == "New input answered."+ assert provider.chat_stream_with_retry.await_count == 2+ assert RUNTIME_CHECKPOINT_KEY not in saved.metadata+ finally:+ await reopened.state.aclose()diff --git a/tests/agent/test_loop_save_turn.py b/tests/agent/test_loop_save_turn.pyindex 53c8c5081..078d06b1b 100644--- a/tests/agent/test_loop_save_turn.py+++ b/tests/agent/test_loop_save_turn.py@@ -835,7 +835,9 @@ def test_restore_runtime_checkpoint_rehydrates_completed_and_pending_tools() ->assert session.messages[0]["role"] == "assistant"assert session.messages[1]["tool_call_id"] == "call_done"assert session.messages[2]["tool_call_id"] == "call_pending"- assert "interrupted before this tool finished" in session.messages[2]["content"].lower()+ assert "outcome is unknown" in session.messages[2]["content"]+ assert "Check its effects before retrying" in session.messages[2]["content"]+ assert session.messages[2]["_recovery_interrupted"] is Trueassert session.provider_state is None@@ -1974,7 +1976,7 @@ async def test_stop_preserves_runtime_checkpoint_for_next_turn(tmp_path: Path) -"role": "tool","tool_call_id": "call_pending","name": "exec",- "content": "Error: Task interrupted before this tool finished.",+ "content": "Error: Task interrupted; this tool's outcome is unknown. Check its effects before retrying.",},{"role": "user", "content": "continue here"},{"role": "assistant", "content": "next answer"},diff --git a/tests/agent/test_mcp_connection.py b/tests/agent/test_mcp_connection.pyindex 70bfcfa3d..9af164f5e 100644--- a/tests/agent/test_mcp_connection.py+++ b/tests/agent/test_mcp_connection.py@@ -539,7 +539,7 @@ async def test_reload_mcp_servers_skips_oauth_server_waiting_for_authorization(@pytest.mark.asyncio-async def test_mcp_tool_reconnects_after_session_terminated(+async def test_mcp_tool_reconnects_before_submission_after_session_terminated(tmp_path,monkeypatch: pytest.MonkeyPatch,):@@ -558,11 +558,13 @@ async def test_mcp_tool_reconnects_after_session_terminated(self.index = indexself.call_count = 0+ async def send_ping(self) -> None:+ if self.index == 1:+ raise McpError(ErrorData(code=-32000, message="Session terminated"))+async def call_tool(self, _name: str, arguments: dict[str, Any]) -> Any:self.call_count += 1assert arguments == {"symbol": "AAPL"}- if self.index == 1:- raise McpError(ErrorData(code=-32000, message="Session terminated"))return SimpleNamespace(content=[mcp_types.TextContent(type="text", text="recovered")])@@ -597,7 +599,7 @@ async def test_mcp_tool_reconnects_after_session_terminated(assert output == "recovered"assert connect_count == 2assert closed == ["remote"]- assert sessions[0].call_count == 1+ assert sessions[0].call_count == 0assert sessions[1].call_count == 1assert provider.connected_server_names == {"remote"}assert registry.get("mcp_remote_quote") is not old_tool@@ -617,10 +619,12 @@ async def test_mcp_reconnect_handler_uses_sanitized_server_prefix(def __init__(self, index: int) -> None:self.index = index- async def call_tool(self, _name: str, arguments: dict[str, Any]) -> Any:- assert arguments == {}+ async def send_ping(self) -> None:if self.index == 1:raise McpError(ErrorData(code=-32000, message="Session terminated"))++ async def call_tool(self, _name: str, arguments: dict[str, Any]) -> Any:+ assert arguments == {}return SimpleNamespace(content=[mcp_types.TextContent(type="text", text="recovered")])@@ -738,9 +742,11 @@ async def test_shared_proxy_snapshot_survives_reconnect_and_reloads_only_opted_iclass Session:expired = False- async def call_tool(self, _name: str, arguments: dict[str, Any]) -> Any:+ async def send_ping(self) -> None:if self.expired:raise McpError(ErrorData(code=-32000, message="Session terminated"))++ async def call_tool(self, _name: str, arguments: dict[str, Any]) -> Any:return SimpleNamespace(content=[mcp_types.TextContent(type="text", text="ok")])async def mark_closed(name: str) -> None:diff --git a/tests/agent/test_mcp_transient_retry.py b/tests/agent/test_mcp_transient_retry.pyindex 3cd771b13..492b77d5d 100644--- a/tests/agent/test_mcp_transient_retry.py+++ b/tests/agent/test_mcp_transient_retry.py@@ -1,6 +1,6 @@import asynciofrom types import SimpleNamespace-from unittest.mock import AsyncMock, patch+from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom loguru import logger@@ -8,7 +8,11 @@ from mcp import types as mcp_typesfrom mcp.shared.exceptions import McpErrorfrom mcp.types import ErrorData+from agent.runner_helpers import make_run_spec+from nanobot.agent.hook import AgentHook, AgentHookContext+from nanobot.agent.runner import AgentRunnerfrom nanobot.agent.tools.context import RequestContext, request_context+from nanobot.agent.tools.execution import execute_tool_callsfrom nanobot.agent.tools.mcp import (MCPPromptWrapper,MCPResourceWrapper,@@ -16,7 +20,13 @@ from nanobot.agent.tools.mcp import (_is_session_terminated,_is_transient,)-from nanobot.agent.tools.registry import is_tool_error_result+from nanobot.agent.tools.registry import (+ ToolRegistry,+ is_tool_error_result,+ with_tool_error_hint,+)+from nanobot.config.schema import AgentDefaults+from nanobot.providers.base import LLMResponse, ToolCallRequestclass _FakeClosedResourceError(Exception):@@ -84,8 +94,9 @@ def test_is_session_terminated_recognizes_connection_closed_mcp_error():def _make_tool_def(name="test_tool"):return SimpleNamespace(name=name,- description="A test tool",+ description="A read-only test tool",inputSchema={"type": "object", "properties": {}},+ annotations=mcp_types.ToolAnnotations(readOnlyHint=True),)@@ -456,21 +467,54 @@ async def test_prompt_reconnects_on_connection_closed_exception():assert new_session.get_prompt.call_count == 1-async def test_tool_refresh_leaves_one_transient_retry_available():[email protected]("fresh_annotations", [+ mcp_types.ToolAnnotations(idempotentHint=True), None,+ mcp_types.ToolAnnotations(readOnlyHint=False, idempotentHint=False),+], ids=["still-idempotent", "unknown", "non-idempotent"])+async def test_tool_refresh_rechecks_replay_contract_and_keeps_retry_budget(fresh_annotations):old, fresh = AsyncMock(), AsyncMock()old.call_tool.side_effect = ConnectionResetError("old")- fresh.call_tool.side_effect = [ConnectionResetError("fresh"), _make_tool_result("ok")]- wrapper = MCPToolWrapper(old, "srv", _make_tool_def())- reconnect = AsyncMock(return_value=MCPToolWrapper(fresh, "srv", _make_tool_def()))+ effects = []++ async def submit_then_lose_response(name, arguments):+ effects.append((name, arguments))+ if len(effects) == 1:+ raise ConnectionResetError("fresh response lost after commit")+ return _make_tool_result("ok")++ fresh.call_tool.side_effect = submit_then_lose_response+ definition = mcp_types.Tool(+ name="test_tool", inputSchema={"type": "object"},+ annotations=mcp_types.ToolAnnotations(idempotentHint=True),+ )+ wrapper = MCPToolWrapper(old, "srv", definition)+ replacement = MCPToolWrapper(fresh, "srv", definition.model_copy(update={"annotations": fresh_annotations}))+ reconnect = AsyncMock(return_value=replacement)wrapper.set_reconnect_handler(reconnect)with patch("nanobot.agent.tools.mcp.asyncio.sleep", new_callable=AsyncMock) as sleep:- assert await wrapper.execute(value="unchanged") == "ok"+ output = await wrapper.execute(value="unchanged")+ if fresh_annotations is not None and fresh_annotations.idempotentHint:+ assert output == "ok"+ assert effects == [("test_tool", {"value": "unchanged"})] * 2+ sleep.assert_awaited_once_with(1)+ else:+ assert is_tool_error_result(output)+ assert "outcome is unknown" in output+ fresh.call_tool.assert_not_awaited()+ assert effects == []+ sleep.assert_not_awaited()+ # A later authorized operation uses the new contract too: its lost+ # response must not acquire the old wrapper's replay permission.+ later = await wrapper.execute(value="new input")+ assert is_tool_error_result(later)+ assert "outcome is unknown" in later+ assert effects == [("test_tool", {"value": "new input"})]+ fresh.call_tool.assert_awaited_once()+ sleep.assert_not_awaited()old.call_tool.assert_awaited_once_with("test_tool", arguments={"value": "unchanged"})- assert fresh.call_tool.await_count == 2reconnect.assert_awaited_once_with("srv", wrapper.name, wrapper)- sleep.assert_awaited_once_with(1)async def test_tool_later_refresh_does_not_reset_transient_budget():@@ -581,8 +625,290 @@ async def test_request_error_logs_hide_content_and_prompt_retains_error_detail(kfinally:logger.remove(sink)assert output == expected- assert is_tool_error_result(output) is (kind == "tool")+ assert is_tool_error_result(output)error = next(record for record in records if record["level"].name == "ERROR")assert "[content hidden]" in error["message"]assert error["exception"] is Noneassert all("private-request-content" not in record["message"] for record in records)+++class _RecordingToolHook(AgentHook):+ def __init__(self):+ self.errors = []+ self.successes = []++ async def on_execute_tool_error(self, context, tool_call, tool, params, error):+ self.errors.append(error)++ async def after_execute_tool(self, context, tool_call, tool, params, result):+ self.successes.append(result)+++async def _run_mcp_call(registry, call, hook):+ provider = MagicMock()+ provider.chat_stream_with_retry = AsyncMock(side_effect=[+ LLMResponse(content=None, tool_calls=[call]),+ LLMResponse(content="done"),+ ])+ return await AgentRunner().run(make_run_spec(+ provider, tools=registry, model="test-model", max_iterations=2,+ initial_messages=[{"role": "user", "content": "run the MCP operation"}],+ max_tool_result_chars=AgentDefaults().max_tool_result_chars,+ hook=hook,+ ))++[email protected]("annotations", [None, mcp_types.ToolAnnotations(+ readOnlyHint=False, idempotentHint=False, destructiveHint=False,+)], ids=["unknown", "non-idempotent-additive"])+async def test_submitted_tool_transport_loss_is_unknown_not_replayed(annotations):+ effects = []+ disconnected = False+ old, fresh = AsyncMock(), AsyncMock()++ async def ping():+ if disconnected:+ raise _connection_closed_error()++ async def submit_then_lose_response(name, arguments):+ nonlocal disconnected+ effects.append((name, arguments))+ disconnected = True+ raise McpError(ErrorData(code=-32000, message="Connection closed: private-submission"))++ async def submit(name, arguments):+ effects.append((name, arguments))+ return _make_tool_result("created")++ old.send_ping.side_effect = ping+ old.call_tool.side_effect = submit_then_lose_response+ fresh.call_tool.side_effect = submit+ definition = mcp_types.Tool(name="create", inputSchema={"type": "object"}, annotations=annotations)+ wrapper = MCPToolWrapper(old, "srv", definition)+ replacement = MCPToolWrapper(fresh, "srv", definition)+ reconnect = AsyncMock(return_value=replacement)+ wrapper.set_reconnect_handler(reconnect)+ registry = ToolRegistry()+ registry.register(wrapper)+ hook = _RecordingToolHook()+ records = []+ sink = logger.add(lambda message: records.append(message.record), level="DEBUG")+ try:+ with request_context(RequestContext(channel="test", chat_id="test", log_content=False)):+ result = await _run_mcp_call(+ registry, ToolCallRequest(id="create-1", name=wrapper.name, arguments={"title": "first"}), hook,+ )+ finally:+ logger.remove(sink)++ assert records and all("private-submission" not in record["message"] for record in records)+ assert all(record["exception"] is None for record in records)+ assert effects == [("create", {"title": "first"})]+ assert result.tool_events[0]["status"] == "error"+ assert result.tools_used == []+ assert len(hook.errors) == 1 and not hook.successes+ assert is_tool_error_result(hook.errors[0])+ assert "outcome is unknown" in hook.errors[0]+ assert "duplicate side effects" in hook.errors[0]+ assert "not replayed" in hook.errors[0]+ reconnect.assert_not_awaited()+ fresh.call_tool.assert_not_awaited()++ # A later user-authorized call can repair the connection before submitting,+ # without replaying the first call or inheriting its outcome/retry state.+ assert await registry.execute(wrapper.name, {"title": "second"}) == "created"+ assert effects == [("create", {"title": "first"}), ("create", {"title": "second"})]+ reconnect.assert_awaited_once()+ old.call_tool.assert_awaited_once()+ fresh.call_tool.assert_awaited_once_with("create", arguments={"title": "second"})+++async def test_explicitly_idempotent_tool_can_recover_with_the_same_arguments():+ records = {}+ submissions = []++ async def set_record(name, arguments):+ submissions.append((name, arguments.copy()))+ records[arguments["id"]] = arguments["value"]+ if len(submissions) == 1:+ raise ConnectionResetError("response lost after commit")+ return _make_tool_result("saved")++ session = AsyncMock()+ session.call_tool.side_effect = set_record+ definition = mcp_types.Tool(+ name="set_record", inputSchema={"type": "object"},+ annotations=mcp_types.ToolAnnotations(readOnlyHint=False, idempotentHint=True),+ )+ wrapper = MCPToolWrapper(session, "srv", definition)+ registry = ToolRegistry()+ registry.register(wrapper)+ with patch("nanobot.agent.tools.mcp.asyncio.sleep", new_callable=AsyncMock) as sleep:+ output = await registry.execute(wrapper.name, {"id": "one", "value": "saved"})+ assert output == "saved"+ assert not is_tool_error_result(output)+ assert records == {"one": "saved"}+ assert submissions == [("set_record", {"id": "one", "value": "saved"})] * 2+ sleep.assert_awaited_once_with(1)++[email protected]("case", [+ "resource_timeout", "prompt_mcp_error", "resource_exhausted", "prompt_exhausted",+ "resource_success", "prompt_success",+])+async def test_resource_prompt_results_keep_runtime_classification(case):+ session = AsyncMock()+ is_resource = case.startswith("resource")+ if is_resource:+ wrapper = MCPResourceWrapper(session, "srv", _make_resource_def(), resource_timeout=5)+ request = session.read_resource+ else:+ wrapper = MCPPromptWrapper(session, "srv", _make_prompt_def(), prompt_timeout=5)+ request = session.get_prompt+ failed = not case.endswith("success")+ if case.endswith("timeout"):+ request.side_effect = asyncio.TimeoutError()+ expected = "(MCP resource read timed out after 5s)"+ elif case.endswith("mcp_error"):+ request.side_effect = McpError(ErrorData(code=-32602, message="prompt missing"))+ expected = "(MCP prompt call failed: prompt missing [code -32602])"+ elif case.endswith("exhausted"):+ request.side_effect = ConnectionResetError("lost")+ operation = "resource read" if is_resource else "prompt call"+ expected = f"(MCP {operation} failed after retry: ConnectionResetError)"+ else:+ expected = "Error: is a valid example in this document"+ request.return_value = (+ _make_resource_result(expected) if is_resource else _make_prompt_result(expected)+ )+ registry = ToolRegistry()+ registry.register(wrapper)+ call = ToolCallRequest(id="read-1", name=wrapper.name, arguments={})+ with patch("nanobot.agent.tools.mcp.asyncio.sleep", new_callable=AsyncMock):+ direct = await registry.execute(wrapper.name, {})+ assert is_tool_error_result(direct) is failed+ assert direct == (with_tool_error_hint(expected) if failed else expected)++ hook = _RecordingToolHook()+ outputs, events = await execute_tool_calls(+ registry, [call], concurrent=False, external_lookup_counts={},+ workspace_violation_counts={}, hook=hook,+ context=AgentHookContext(iteration=0, messages=[]),+ )+ assert events[0]["status"] == ("error" if failed else "ok")+ assert expected in outputs[0]+ assert hook.errors == ([expected] if failed else [])+ assert hook.successes == ([] if failed else [expected])++ runner_hook = _RecordingToolHook()+ result = await _run_mcp_call(registry, call, runner_hook)+ assert result.tool_events[0]["status"] == ("error" if failed else "ok")+ assert result.tools_used == ([] if failed else [wrapper.name])+ assert runner_hook.errors == ([expected] if failed else [])+ assert runner_hook.successes == ([] if failed else [expected])+ if failed:+ assert is_tool_error_result(runner_hook.errors[0])+ assert expected in next(msg["content"] for msg in result.messages if msg["role"] == "tool")+++async def test_unknown_tool_without_reconnect_does_not_retry_after_side_effect():+ effects = []++ async def submit_then_disconnect(name, arguments):+ effects.append((name, arguments))+ raise ConnectionResetError("response lost")++ session = AsyncMock()+ session.call_tool.side_effect = submit_then_disconnect+ wrapper = MCPToolWrapper(session, "srv", mcp_types.Tool(name="send", inputSchema={"type": "object"}))+ registry = ToolRegistry()+ registry.register(wrapper)+ with patch("nanobot.agent.tools.mcp.asyncio.sleep", new_callable=AsyncMock) as sleep:+ output = await registry.execute(wrapper.name, {"message": "hello"})+ assert effects == [("send", {"message": "hello"})]+ assert is_tool_error_result(output)+ assert "outcome is unknown" in output+ sleep.assert_not_awaited()++[email protected]("kind", ["resource", "prompt"])+async def test_resource_prompt_external_cancellation_propagates_without_hooks(kind):+ entered = asyncio.Event()++ async def block(*args, **kwargs):+ entered.set()+ await asyncio.Event().wait()++ session = AsyncMock()+ if kind == "resource":+ session.read_resource.side_effect = block+ wrapper = MCPResourceWrapper(session, "srv", _make_resource_def())+ request = session.read_resource+ else:+ session.get_prompt.side_effect = block+ wrapper = MCPPromptWrapper(session, "srv", _make_prompt_def())+ request = session.get_prompt+ registry = ToolRegistry()+ registry.register(wrapper)+ hook = _RecordingToolHook()+ task = asyncio.create_task(execute_tool_calls(+ registry, [ToolCallRequest(id="read-1", name=wrapper.name, arguments={})],+ concurrent=False, external_lookup_counts={}, workspace_violation_counts={},+ hook=hook, context=AgentHookContext(iteration=0, messages=[]),+ ))+ try:+ await asyncio.wait_for(entered.wait(), timeout=2)+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task+ finally:+ if not task.done():+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)+ request.assert_awaited_once()+ assert not hook.errors and not hook.successes++[email protected]("cancel", [False, True], ids=["timeout", "task-cancellation"])[email protected]("submitted", [False, True], ids=["preflight", "submitted"])+async def test_non_replayable_tool_timeout_and_cancellation_do_not_repeat(cancel, submitted):+ entered = asyncio.Event()+ effects = []++ async def block(*args, **kwargs):+ if submitted:+ effects.append("committed before response loss")+ entered.set()+ await asyncio.Event().wait()++ session = AsyncMock()+ if submitted:+ session.call_tool.side_effect = block+ else:+ session.send_ping.side_effect = block+ wrapper = MCPToolWrapper(+ session, "srv", mcp_types.Tool(name="send", inputSchema={"type": "object"}),+ tool_timeout=5 if cancel else 0.01,+ )+ reconnect = AsyncMock()+ wrapper.set_reconnect_handler(reconnect)+ task = asyncio.create_task(wrapper.execute())+ try:+ await asyncio.wait_for(entered.wait(), timeout=2)+ if cancel:+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task+ else:+ result = await asyncio.wait_for(task, timeout=2)+ assert is_tool_error_result(result)+ assert "timed out after 0.01s" in result+ assert ("outcome is unknown" in result) is submitted+ finally:+ if not task.done():+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)+ session.send_ping.assert_awaited_once()+ assert session.call_tool.await_count == int(submitted)+ assert effects == (["committed before response loss"] if submitted else [])+ reconnect.assert_not_awaited()diff --git a/tests/cli/test_commands.py b/tests/cli/test_commands.pyindex c5ee87dac..d42f5def8 100644--- a/tests/cli/test_commands.py+++ b/tests/cli/test_commands.py@@ -12,6 +12,7 @@ from unittest.mock import AsyncMock, MagicMock, patchfrom urllib.parse import urlparseimport pytest+import typerfrom typer.testing import CliRunnerfrom nanobot.agent.memory import MemoryStore@@ -3705,11 +3706,13 @@ def test_gateway_local_trigger_queue_submits_agent_turns(_fake_run_local_trigger_queue,)- cli_commands._run_gateway(- config,- health_server_enabled=False,- unconfigured_provider_error=setup_error,- )+ with pytest.raises(typer.Exit) as exc_info:+ cli_commands._run_gateway(+ config,+ health_server_enabled=False,+ unconfigured_provider_error=setup_error,+ )+ assert exc_info.value.exit_code == 1agent = seen["agent"]agent_kwargs = seen["agent_from_config_kwargs"]@@ -4021,7 +4024,7 @@ def test_gateway_health_endpoint_binds_and_serves_expected_responses(result = runner.invoke(app, ["gateway", "--config", str(config_file)])- assert result.exit_code == 0+ assert result.exit_code == 1assert captured["host"] == hostassert captured["port"] == 18791assert f"Health endpoint: {display_url}" in result.stdout@@ -4117,9 +4120,11 @@ def test_gateway_health_endpoint_binds_and_serves_expected_responses(assert timed_out_writer.output == b""-def test_gateway_agent_task_owns_initial_mcp_provider_close([email protected]("failure_phase", ["startup", "runtime"])+def test_gateway_failure_exits_nonzero_after_cleanup(monkeypatch,tmp_path: Path,+ failure_phase: str,) -> None:config_file = _write_instance_config(tmp_path)config = Config()@@ -4199,7 +4204,8 @@ def test_gateway_agent_task_owns_initial_mcp_provider_close(self.on_job = Noneasync def start(self) -> None:- return None+ if failure_phase == "startup":+ raise _StopGatewayError("gateway startup failed")def stop(self) -> None:seen["cron_stopped"] = True@@ -4218,7 +4224,7 @@ def test_gateway_agent_task_owns_initial_mcp_provider_close(return Falseasync def serve_forever(self) -> None:- raise _StopGatewayError("stop")+ raise _StopGatewayError("gateway runtime failed")async def _fake_start_server(_handler, _host: str, _port: int):return _FakeServer()@@ -4237,18 +4243,23 @@ def test_gateway_agent_task_owns_initial_mcp_provider_close(result = runner.invoke(app, ["gateway", "--config", str(config_file)])- assert result.exit_code == 0+ assert result.exit_code == 1+ assert "Gateway crashed unexpectedly" in result.stdout+ assert f"_StopGatewayError: gateway {failure_phase} failed" in result.stdoutassert seen["agent_stopped"] is Trueassert seen["inflight_turns_preserved"] is Trueassert seen["agent_closed"] is True- assert seen["agent_task_cleaned_up"] is Trueassert seen["channels_stopped"] is Trueassert seen["cron_stopped"] is Truemcp_provider = seen["mcp_provider"]assert isinstance(mcp_provider, _FakeMCPProvider)- assert mcp_provider.connect_task is seen["agent_task"]- assert mcp_provider.close_tasks[0] is mcp_provider.connect_task- assert len(mcp_provider.close_tasks) == 2+ if failure_phase == "runtime":+ assert seen["agent_task_cleaned_up"] is True+ assert mcp_provider.connect_task is seen["agent_task"]+ assert mcp_provider.close_tasks[0] is mcp_provider.connect_task+ assert len(mcp_provider.close_tasks) == 2+ else:+ assert len(mcp_provider.close_tasks) == 1hooks = seen["hooks"]assert isinstance(hooks, list)assert len(hooks) == 1diff --git a/tests/session/test_followup_commit.py b/tests/session/test_followup_commit.pyindex 73b8573ea..f469fb087 100644--- a/tests/session/test_followup_commit.py+++ b/tests/session/test_followup_commit.py@@ -11,8 +11,13 @@ from nanobot.bus.events import INBOUND_META_TURN_ID, InboundMessagefrom nanobot.bus.queue import MessageBusfrom nanobot.providers.base import GenerationSettings, LLMResponsefrom nanobot.runtime_context import public_history_message-from nanobot.session.manager import SessionManager-from nanobot.session.recovery import PENDING_FOLLOWUP_ID_KEY, pending_followups+from nanobot.session.manager import Session, SessionManager+from nanobot.session.recovery import (+ PENDING_FOLLOWUP_ID_KEY,+ RUNTIME_CHECKPOINT_KEY,+ pending_followups,+ restore_runtime_checkpoint,+)from nanobot.webui.recovery import RecoveryCoordinator@@ -76,7 +81,8 @@ async def test_late_consumption_commits_history_and_only_its_ids(tmp_path, monkeawait reopened.state.aclose()-async def test_failed_followup_commit_rolls_back_history_and_ack_then_can_retry(tmp_path):[email protected]("recover_checkpoint", [False, True])+async def test_failed_followup_commit_rolls_back_history_and_ack_then_can_retry(tmp_path, recover_checkpoint):sessions = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "sessions")state = sessions.statetry:@@ -84,10 +90,22 @@ async def test_failed_followup_commit_rolls_back_history_and_ack_then_can_retry(draft.add_message("user", "initial input")await state.prepare_input(draft)identifier = await state.queue_followup(draft.key, _input("consumed input", "follow-up"))- _loop(sessions)._save_turn(draft, [+ projection = Session(key=draft.key) if recover_checkpoint else draft+ _loop(sessions)._save_turn(projection, [{"role": "user", "content": "consumed input", PENDING_FOLLOWUP_ID_KEY: identifier},{"role": "assistant", "content": "completed answer"},], skip=0)+ if recover_checkpoint:+ await state.checkpoint_view(draft, {+ "phase": "final_response",+ "preceding_messages": projection.messages[:-1],+ "assistant_message": projection.messages[-1],+ "completed_tool_results": [],+ "pending_tool_calls": [],+ "consumed_followup_ids": list(projection.consumed_followup_ids),+ })+ draft = await state.get(draft.key)+ assert restore_runtime_checkpoint(draft)with sqlite3.connect(sessions._store.path) as db:db.execute("""CREATE TRIGGER reject_ack BEFORE DELETE ON pending_inputsBEGIN SELECT RAISE(ABORT, 'failed follow-up commit'); END""")@@ -96,6 +114,7 @@ async def test_failed_followup_commit_rolls_back_history_and_ack_then_can_retry(for stored in (sessions.read_session_snapshot(draft.key), state.peek(draft.key)):assert [row["content"] for row in stored.messages] == ["initial input"]assert [item.content for item in pending_followups(stored)] == ["consumed input"]+ assert (RUNTIME_CHECKPOINT_KEY in stored.metadata) is recover_checkpointwith sqlite3.connect(sessions._store.path) as db:db.execute("DROP TRIGGER reject_ack")await state.finish_turn(draft)@@ -127,7 +146,8 @@ async def test_recovered_input_keeps_admission_identity_and_timestamp(tmp_path):await state.aclose()-async def test_injected_inputs_keep_their_own_identity_through_runner_and_commit(tmp_path):[email protected]("interrupt", [False, True], ids=["completed", "checkpoint-recovery"])+async def test_injected_inputs_keep_their_own_identity_through_runner_and_commit(tmp_path, monkeypatch, interrupt):import asyncioprovider = MagicMock(aclose=AsyncMock())@@ -136,9 +156,24 @@ async def test_injected_inputs_keep_their_own_identity_through_runner_and_commitprovider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="completed answer"))loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path / "workspace", model="test-model")loop.sessions = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "sessions")+ # Plain-text inputs are valid without extension-provided runtime context.+ monkeypatch.setattr(loop, "_resolve_runtime_context_for_request", AsyncMock(return_value=[]))+ checkpoint_saved = asyncio.Event()+ checkpoint = loop._set_runtime_checkpoint++ async def save_checkpoint(session, payload):+ await checkpoint(session, payload)+ checkpoint_saved.set()+ if interrupt:+ await asyncio.Event().wait()++ monkeypatch.setattr(loop, "_set_runtime_checkpoint", save_checkpoint)try:draft = await loop.sessions.state.get("websocket:chat")- draft.add_message("user", "initial input")+ draft.add_message(+ "user", "intentionally identical text", **{INBOUND_META_TURN_ID: "initial-input"},+ timestamp="2026-10-18T19:00:00",+ )await loop.sessions.state.prepare_input(draft)queue = asyncio.Queue()for turn_id in ("first-input", "second-input"):@@ -147,22 +182,46 @@ async def test_injected_inputs_keep_their_own_identity_through_runner_and_commitmessage.metadata[PENDING_FOLLOWUP_ID_KEY] = identifierqueue.put_nowait(message)runtime = loop.llm_runtime()- result = await loop._run_agent_loop(+ task = asyncio.create_task(loop._run_agent_loop(TranscriptInput(history=draft.get_history(), current_message=None),runtime=runtime, session=draft, pending_queue=queue,request_context=RequestContext(channel="websocket", chat_id="chat", session_key=draft.key,turn_id="active-run", runtime=runtime,),- )- loop._save_turn(draft, result.messages, skip=2)- await loop.sessions.state.finish_turn(draft)- stored = await loop.sessions.state.get(draft.key)- injected = [row for row in stored.messages if row.get("role") == "user"][1:]- assert [public_history_message(row)["content"] for row in injected] == ["intentionally identical text"] * 2- assert [row[INBOUND_META_TURN_ID] for row in injected] == ["first-input", "second-input"]- assert [row["timestamp"] for row in injected] == ["2026-10-18T19:00:00"] * 2- assert pending_followups(stored) == []+ ))+ try:+ await asyncio.wait_for(checkpoint_saved.wait(), 5)+ if interrupt:+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task+ assert len(pending_followups(await loop.sessions.state.get(draft.key))) == 2+ else:+ result = await task+ loop._save_turn(draft, result.messages, skip=2)+ await loop.sessions.state.finish_turn(draft)+ finally:+ if not task.done():+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)provider.chat_stream_with_retry.assert_awaited_once()finally:await loop.aclose()++ reopened = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "sessions")+ try:+ bus = MessageBus()+ recovery = RecoveryCoordinator(reopened, bus)+ await recovery.scan()+ stored = await reopened.state.get(draft.key)+ inputs = [row for row in stored.messages if row.get("role") == "user"]+ assert [public_history_message(row)["content"] for row in inputs] == ["intentionally identical text"] * 3+ assert [row[INBOUND_META_TURN_ID] for row in inputs] == ["initial-input", "first-input", "second-input"]+ assert [row["timestamp"] for row in inputs] == ["2026-10-18T19:00:00"] * 3+ assert pending_followups(stored) == []+ assert bus.inbound.empty()+ await recovery.scan()+ assert (await reopened.state.get(draft.key)).messages == stored.messages+ finally:+ await reopened.state.aclose()diff --git a/tests/session/test_recovery.py b/tests/session/test_recovery.pyindex 4439b6bf9..37c73bac7 100644--- a/tests/session/test_recovery.py+++ b/tests/session/test_recovery.py@@ -465,7 +465,8 @@ async def test_malformed_final_response_is_not_reported_as_restored(tmp_path: Pa@pytest.mark.asyncio-async def test_checkpoint_with_missing_tool_result_cannot_continue(tmp_path: Path) -> None:[email protected]("earlier_round", [False, True])+async def test_checkpoint_with_missing_tool_result_cannot_continue(tmp_path: Path, earlier_round: bool) -> None:sessions = SessionManager(tmp_path)session = sessions.get_or_create("websocket:chat")session.messages.append({"role": "user", "content": "send both"})@@ -490,6 +491,15 @@ async def test_checkpoint_with_missing_tool_result_cannot_continue(tmp_path: Pat],"pending_tool_calls": [],}+ if earlier_round:+ checkpoint = session.metadata[RUNTIME_CHECKPOINT_KEY]+ session.metadata[RUNTIME_CHECKPOINT_KEY] = {+ "phase": "final_response",+ "assistant_message": {"role": "assistant", "content": "finished"},+ "completed_tool_results": [],+ "pending_tool_calls": [],+ "preceding_messages": [checkpoint["assistant_message"], *checkpoint["completed_tool_results"]],+ }_persist(sessions, session)coordinator, _, restarted = _coordinator(tmp_path)diff --git a/tests/tools/test_mcp_proxy.py b/tests/tools/test_mcp_proxy.pyindex 0a4e5402c..34ee077ef 100644--- a/tests/tools/test_mcp_proxy.py+++ b/tests/tools/test_mcp_proxy.py@@ -104,6 +104,7 @@ class _RecordingMCPProxy:result = {"tools": [{"name": "echo", "description": "Echo over the selected route","inputSchema": {"type": "object", "properties": {}},+ "annotations": {"readOnlyHint": True},}]}elif method == "tools/call":if self.terminate_next_call:diff --git a/tests/tools/test_mcp_tool.py b/tests/tools/test_mcp_tool.pyindex 31e55f871..2f7369789 100644--- a/tests/tools/test_mcp_tool.py+++ b/tests/tools/test_mcp_tool.py@@ -718,7 +718,7 @@ async def test_execute_notes_unstorable_image_block(tmp_path: Path) -> None:@pytest.mark.asyncio-async def test_execute_returns_timeout_message() -> None:+async def test_execute_returns_unknown_outcome_on_submitted_timeout() -> None:async def call_tool(_name: str, arguments: dict) -> object:await asyncio.sleep(1)return SimpleNamespace(content=[])@@ -727,7 +727,11 @@ async def test_execute_returns_timeout_message() -> None:result = await wrapper.execute()- assert result == "(MCP tool call timed out after 0.01s)"+ assert result == (+ "(MCP tool call outcome is unknown; timed out after 0.01s. The operation "+ "may have completed and was not replayed after this failure. Check its outcome before "+ "retrying to avoid duplicate side effects.)"+ )assert is_tool_error_result(result)diff --git a/tests/tools/test_private_tool_logging.py b/tests/tools/test_private_tool_logging.pyindex e3660e17e..35e75e695 100644--- a/tests/tools/test_private_tool_logging.py+++ b/tests/tools/test_private_tool_logging.py@@ -46,7 +46,10 @@ async def test_mcp_reconnect_failure_obeys_private_log_policy(yield # pragma: no covermonkeypatch.setattr("mcp.client.stdio.stdio_client", broken_stdio)- session = SimpleNamespace(call_tool=AsyncMock(side_effect=RuntimeError("session terminated")))+ session = SimpleNamespace(+ send_ping=AsyncMock(side_effect=RuntimeError("session terminated")),+ call_tool=AsyncMock(),+ )wrapper = MCPToolWrapper(session, "sample", SimpleNamespace(name="search", description="synthetic", inputSchema={},))@@ -61,6 +64,8 @@ async def test_mcp_reconnect_failure_obeys_private_log_policy(await provider.aclose()assert "failed" in result+ session.send_ping.assert_awaited_once()+ session.call_tool.assert_not_awaited()failures = [r for r in diagnostic_recordsif "connection failure" in r["message"] or "failed to connect" in r["message"]@@ -122,7 +127,10 @@ async def test_mcp_private_errors_exclude_exception_payloads(log_content, kind, monkeypatch, diagnostic_records,):session = MagicMock()- definition = SimpleNamespace(name="sample", description="sample", inputSchema={})+ definition = SimpleNamespace(+ name="sample", description="sample", inputSchema={},+ annotations=types.ToolAnnotations(readOnlyHint=True) if kind == "retry" else None,+ )error = ValueError(_SECRET)if kind in {"tool", "render", "retry"}:tool = MCPToolWrapper(session, "test", definition)@@ -148,6 +156,8 @@ async def test_mcp_private_errors_exclude_exception_payloads(with request_context(RequestContext(channel="websocket", chat_id="test", log_content=log_content)):result = await tool.execute()assert "failed" in result or "malformed" in result+ if kind == "retry":+ assert session.call_tool.await_count == 2errors = [r for r in diagnostic_records if r["level"].name == "ERROR"]assert errorsif log_content: