From f94f245dcac6fbb573e99244fedeec8e6310bbd0 Mon Sep 17 00:00:00 2001 From: chengyongru Date: Thu, 12 Nov 2026 19:04:53 +0800 Subject: [PATCH] refactor(agent): clarify run-local input and checkpoint ownership --- .agent/navigation.md | 2 +- nanobot/agent/loop.py | 324 +++++++++-------------- nanobot/agent/pending_inputs.py | 81 ++++++ nanobot/agent/runner.py | 22 +- nanobot/agent/subagent.py | 4 +- tests/agent/test_runner_injections.py | 97 +++++++ tests/agent/tools/test_subagent_tools.py | 10 +- 7 files changed, 327 insertions(+), 213 deletions(-) create mode 100644 nanobot/agent/pending_inputs.py diff --git a/.agent/navigation.md b/.agent/navigation.md index dc395c766..d965b57c5 100644 --- a/.agent/navigation.md +++ b/.agent/navigation.md @@ -12,7 +12,7 @@ Choose the affected behavior below, then read its owner and existing tests. Foll | Shell process launch or cleanup | [`execution/processes.py`](../nanobot/execution/processes.py) owns native process trees; [`agent/tools/exec_session.py`](../nanobot/agent/tools/exec_session.py) owns session state and output | [`test_exec_platform.py`](../tests/tools/test_exec_platform.py), [`test_shell_reap.py`](../tests/tools/test_shell_reap.py), [`test_shell_execution_budgets.py`](../tests/tools/test_shell_execution_budgets.py) | | Slash commands or command dispatch | [`command/router.py`](../nanobot/command/router.py), [`command/builtin.py`](../nanobot/command/builtin.py) | [`tests/command/`](../tests/command/) | | Turn scheduling, cancellation, or delivery | [`agent/loop.py`](../nanobot/agent/loop.py), [`agent/turn_delivery.py`](../nanobot/agent/turn_delivery.py) | [`test_loop_concurrency.py`](../tests/agent/test_loop_concurrency.py), [`test_task_cancel.py`](../tests/agent/test_task_cancel.py), [`test_turn_delivery.py`](../tests/agent/test_turn_delivery.py) | -| Model/tool iterations, retry, or injected input | [`agent/runner.py`](../nanobot/agent/runner.py) | [`test_runner_core.py`](../tests/agent/test_runner_core.py), [`test_runner_fallback.py`](../tests/agent/test_runner_fallback.py), [`test_runner_injections.py`](../tests/agent/test_runner_injections.py) | +| Model/tool iterations, retry, or injected input | [`agent/runner.py`](../nanobot/agent/runner.py); [`agent/pending_inputs.py`](../nanobot/agent/pending_inputs.py) owns run-local input batches and terminal waits, while `AgentLoop` prepares each input | [`test_runner_core.py`](../tests/agent/test_runner_core.py), [`test_runner_fallback.py`](../tests/agent/test_runner_fallback.py), [`test_runner_injections.py`](../tests/agent/test_runner_injections.py) | | Prompt assembly, skills, or context limits | [`agent/context.py`](../nanobot/agent/context.py), [`agent/context_governance.py`](../nanobot/agent/context_governance.py); [prompt cautions](gotchas.md#prompt-templates) | [`test_context_builder.py`](../tests/agent/test_context_builder.py), [`test_skills_loader.py`](../tests/agent/test_skills_loader.py), [`test_context_governance.py`](../tests/agent/test_context_governance.py) | | Session persistence or recovery | [`session/state.py`](../nanobot/session/state.py), [`session/sqlite_store.py`](../nanobot/session/sqlite_store.py), [`session/recovery.py`](../nanobot/session/recovery.py) | [`tests/session/`](../tests/session/), [`test_loop_recovery.py`](../tests/agent/test_loop_recovery.py) | | WebUI/TUI wire events or displayed history | [`webui/outbound_delivery.py`](../nanobot/webui/outbound_delivery.py), [`webui/transcript.py`](../nanobot/webui/transcript.py); [client compatibility](review-guide.md) | [`tests/webui/`](../tests/webui/), [`WebSocket tests`](../nanobot/channels/websocket/tests/), and affected client tests | diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index d7958ab13..569e3acbe 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -26,7 +26,8 @@ from nanobot.agent.execution_policy import ExecutionControlError, ExecutionPolic from nanobot.agent.hook import AgentHook, AgentTurnHookFactory from nanobot.agent.memory import Consolidator from nanobot.agent.model_runtime import ModelRuntimeResolver -from nanobot.agent.runner import AgentRunner, AgentRunResult, AgentRunSpec +from nanobot.agent.pending_inputs import PendingInputs +from nanobot.agent.runner import AgentCheckpoint, AgentRunner, AgentRunResult, AgentRunSpec from nanobot.agent.subagent import SubagentManager from nanobot.agent.tools.context import RequestContext, bind_request_context, reset_request_context from nanobot.agent.tools.exec_session import ExecSessionManager @@ -997,6 +998,97 @@ class AgentLoop: return delivery.remember_session_route(session.metadata) + async def _prepare_injected_input( + self, + message: InboundMessage, + *, + request: RequestContext, + runtime: LLMRuntime, + session: Session | None, + tools: ToolRegistry, + ) -> dict[str, Any] | None: + # Commands and independent turns retain their own worker and completion. + if not self._can_inject_message(message): + return None + content = message.content + image_paths = message.media if message.media else None + if image_paths: + content, image_paths = reference_non_image_attachments(content, image_paths) + image_paths = image_paths or None + user_content = self.context.build_user_content(content, image_paths=image_paths) + row: dict[str, Any] = { + "role": "user", "content": user_content, + "_meta": input_history_metadata(message), + } + if HIDDEN_HISTORY_META in message.metadata: + row[HIDDEN_HISTORY_META] = message.metadata[HIDDEN_HISTORY_META] + metadata_value = cast(object, message.metadata) + metadata = message.metadata if isinstance(metadata_value, dict) else {} + if message.is_user_input: + active_session_key = session.key if session is not None else request.session_key + route = self.turn_delivery_factory.input_route(message, active_session_key or message.session_key) + scope = await self.runner.prepare_prompt( + self.workspace_scopes.for_turn, + channel=route.channel, + message_metadata=_prompt_scope_metadata(metadata), + session_metadata=_prompt_scope_metadata(session.metadata) if session is not None else None, + ) + # A follow-up cannot inherit another input's tool authority. + # Leave it for the FIFO worker to run with its own scope. + if scope != request.workspace_scope: + return None + pending_request = RequestContext( + channel=route.channel, + chat_id=route.chat_id, + message_id=metadata.get("message_id"), + session_key=active_session_key, + session_generation=session.generation if session is not None else None, + original_user_text=message.content, + runtime=runtime, + metadata=dict(metadata), + attributes=dict(request.attributes), + sender_id=message.sender_id, + turn_id=request.turn_id, + workspace=scope.project_path, + workspace_scope=request.workspace_scope, + log_content=request.log_content, + ) + blocks = await self._resolve_runtime_context_for_request(pending_request, tools) + row["content"], runtime_marker = append_runtime_context(user_content, blocks) + if runtime_marker is not None: + row["_meta"][RUNTIME_CONTEXT_MESSAGE_META] = runtime_marker + if message.sender_id == "subagent" and metadata.get("injected_event") == "subagent_result": + subagent_marker: dict[str, Any] = {"kind": "subagent_result"} + task_id = metadata.get("subagent_task_id") + if isinstance(task_id, str) and task_id: + subagent_marker["subagent_task_id"] = task_id + row["subagent_task_id"] = task_id + row[HIDDEN_HISTORY_META] = subagent_marker + row["injected_event"] = "subagent_result" + followup_id = metadata.get(PENDING_FOLLOWUP_ID_KEY) + if isinstance(followup_id, str) and followup_id: + row[PENDING_FOLLOWUP_ID_KEY] = followup_id + return row + + async def _checkpoint_turn(self, session: Session, payload: AgentCheckpoint) -> None: + public_payload: dict[str, Any] = dict(payload) + preceding = Session(key=session.key) + self._save_turn(preceding, payload["preceding_messages"], skip=0) + public_payload["preceding_messages"] = preceding.messages + public_payload["consumed_followup_ids"] = sorted(preceding.consumed_followup_ids) + public_payload.pop("provider_state", None) + previous_state = session.provider_state + if "provider_state" in payload: + session.provider_state = payload["provider_state"] + public_payload[self._PROVIDER_STATE_CHECKPOINT_VERSION_KEY] = ( + self._PROVIDER_STATE_CHECKPOINT_VERSION + ) + try: + await self._set_runtime_checkpoint(session, public_payload) + except BaseException: + session.provider_state = previous_state + raise + async def _run_agent_loop( self, transcript_input: TranscriptInput, @@ -1024,193 +1116,6 @@ class AgentLoop: commit_session and session is not None and (not ephemeral or not session.policy.persist) ) - async def _checkpoint(payload: dict[str, Any]) -> None: - if session is None or not retain_session_state: - return - public_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) - previous_state = session.provider_state - public_payload.pop(self._PROVIDER_STATE_CHECKPOINT_VERSION_KEY, None) - if "provider_state" in payload and ( - private_state is None - or isinstance(private_state, ProviderConversationState) - ): - session.provider_state = private_state - public_payload[self._PROVIDER_STATE_CHECKPOINT_VERSION_KEY] = ( - self._PROVIDER_STATE_CHECKPOINT_VERSION - ) - try: - await self._set_runtime_checkpoint(session, public_payload) - except BaseException: - session.provider_state = previous_state - raise - - async def _drain_pending( - *, - first_msg: InboundMessage | None = None, - ) -> list[dict[str, Any]]: - if pending_queue is None: - return [] - - # Capture the boundary before converting any message. Conversion - # resolves runtime context and may await, so reading until QueueEmpty - # afterwards would let later arrivals leak into this model step. - pending_messages: list[InboundMessage] = [] - if first_msg is not None: - pending_messages.append(first_msg) - snapshot_size = pending_queue.qsize() - for _ in range(snapshot_size): - try: - pending_messages.append(pending_queue.get_nowait()) - except asyncio.QueueEmpty: - break - - async def _to_user_message(pending_msg: InboundMessage) -> dict[str, Any] | None: - content = pending_msg.content - image_paths = pending_msg.media if pending_msg.media else None - if image_paths: - content, image_paths = reference_non_image_attachments( - content, - image_paths, - ) - image_paths = image_paths or None - user_content = self.context.build_user_content( - content, - image_paths=image_paths, - ) - row: dict[str, Any] = { - "role": "user", "content": user_content, - "_meta": input_history_metadata(pending_msg), - } - if HIDDEN_HISTORY_META in pending_msg.metadata: - row[HIDDEN_HISTORY_META] = pending_msg.metadata[HIDDEN_HISTORY_META] - metadata_value = cast(object, pending_msg.metadata) - metadata = ( - pending_msg.metadata - if isinstance(metadata_value, dict) - else {} - ) - if pending_msg.is_user_input: - route = self.turn_delivery_factory.input_route(pending_msg, active_session_key or pending_msg.session_key) - scope = await self.runner.prepare_prompt( - self.workspace_scopes.for_turn, - channel=route.channel, - message_metadata=_prompt_scope_metadata(metadata), - session_metadata=_prompt_scope_metadata(session.metadata) if session is not None else None, - ) - # A follow-up cannot inherit another input's tool authority. - # Leave it for the FIFO worker to run with its own scope. - if scope != effective_scope: - return None - pending_request = RequestContext( - channel=route.channel, - chat_id=route.chat_id, - message_id=metadata.get("message_id"), - session_key=active_session_key, - session_generation=session.generation if session is not None else None, - original_user_text=pending_msg.content, - runtime=runtime, - metadata=dict(metadata), - attributes=dict(request_ctx.attributes), - sender_id=pending_msg.sender_id, - turn_id=request_ctx.turn_id, - workspace=scope.project_path, - # Injected input continues the active run's tool policy. - workspace_scope=effective_scope, - log_content=request_ctx.log_content, - ) - blocks = await self._resolve_runtime_context_for_request( - pending_request, - effective_tools, - ) - row["content"], runtime_marker = append_runtime_context( - user_content, - blocks, - ) - if runtime_marker is not None: - row["_meta"][RUNTIME_CONTEXT_MESSAGE_META] = runtime_marker - if ( - pending_msg.sender_id == "subagent" - and metadata.get("injected_event") == "subagent_result" - ): - subagent_marker: dict[str, Any] = {"kind": "subagent_result"} - task_id = metadata.get("subagent_task_id") - if isinstance(task_id, str) and task_id: - subagent_marker["subagent_task_id"] = task_id - row["subagent_task_id"] = task_id - row[HIDDEN_HISTORY_META] = subagent_marker - row["injected_event"] = "subagent_result" - followup_id = metadata.get(PENDING_FOLLOWUP_ID_KEY) - if isinstance(followup_id, str) and followup_id: - row[PENDING_FOLLOWUP_ID_KEY] = followup_id - return row - - consumed = 0 - try: - converted: list[dict[str, Any]] = [] - consumed_inputs: list[InboundMessage] = [] - for pending_msg in pending_messages: - # Independent turns are FIFO barriers. Their worker path - # owns completion, command dispatch, and control metadata. - if not self._can_inject_message(pending_msg): - break - row = await _to_user_message(pending_msg) - if row is None: - break - converted.append(row) - consumed_inputs.append(pending_msg) - if execution_scope is not None: - try: - execution_scope.consume_inputs(consumed_inputs) - except Exception as exc: - raise ExecutionControlError("could not accept consumed inputs") from exc - consumed = len(converted) - return converted - finally: - # Commit only a successfully converted prefix. On failure or - # cancellation, return the whole snapshot ahead of later arrivals. - unconsumed = pending_messages[consumed:] - if unconsumed: - later = [pending_queue.get_nowait() for _ in range(pending_queue.qsize())] - for pending_msg in [*unconsumed, *later]: - pending_queue.put_nowait(pending_msg) - - terminal_wait_deadline: float | None = None - - async def _wait_for_pending() -> list[dict[str, Any]]: - nonlocal terminal_wait_deadline - - items = await _drain_pending() - if ( - items - or pending_queue is None - or session is None - or self.subagents.get_running_count_by_session(session.key) == 0 - ): - return items - - now = asyncio.get_running_loop().time() - if terminal_wait_deadline is None: - terminal_wait_deadline = now + _SUBAGENT_TERMINAL_WAIT_SECONDS - remaining = terminal_wait_deadline - now - if remaining <= 0: - return [] - - try: - msg = await asyncio.wait_for(pending_queue.get(), timeout=remaining) - except asyncio.TimeoutError: - logger.warning( - "Timeout waiting for sub-agent completion before session {} exits", - session.key, - ) - return [] - - return await _drain_pending(first_msg=msg) - request_ctx = request_context or RequestContext( channel="cli", chat_id="direct", @@ -1263,12 +1168,13 @@ class AgentLoop: ), ) effective_tools = tools if tools is not None else self.tools - file_state_token = bind_file_states(self._file_state_store.for_session(active_session_key)) - request_token = bind_request_context(request_ctx) - workspace_token = bind_workspace_scope(effective_scope) - turn_scope_stack = ExitStack() - execution_scope: ExecutionScope | None = None - try: + with ExitStack() as turn_scope_stack: + turn_scope_stack.callback( + reset_file_states, bind_file_states(self._file_state_store.for_session(active_session_key)), + ) + turn_scope_stack.callback(reset_request_context, bind_request_context(request_ctx)) + turn_scope_stack.callback(reset_workspace_scope, bind_workspace_scope(effective_scope)) + execution_scope: ExecutionScope | None = None if self.execution_policy is not None: execution_scope = turn_scope_stack.enter_context(self.execution_policy.scope( active_session_key, @@ -1278,6 +1184,20 @@ class AgentLoop: if initial_message is not None: execution_scope.consume_inputs((initial_message,)) + pending_inputs = PendingInputs( + queue=pending_queue, + prepare=partial( + self._prepare_injected_input, + request=request_ctx, runtime=runtime, session=session, tools=effective_tools, + ), + consume=execution_scope.consume_inputs if execution_scope is not None else None, + session_key=session.key if session is not None else None, + running_subagents=( + partial(self.subagents.get_running_count_by_session, session.key) + if session is not None else None + ), + terminal_wait_seconds=_SUBAGENT_TERMINAL_WAIT_SECONDS, + ) if pending_queue is not None else None hook = build_agent_turn_hook(AgentTurnHookSpec( events=events, streaming=streaming, @@ -1311,7 +1231,10 @@ class AgentLoop: workspace=None if ephemeral else effective_scope.project_path, session_key=session.key if session else None, provider_retry_mode=self.provider_retry_mode, - checkpoint_callback=_checkpoint, + checkpoint_callback=( + partial(self._checkpoint_turn, session) + if session is not None and retain_session_state else None + ), consolidate_history=partial( self.consolidator.summarize_transcript, runtime=runtime, @@ -1326,8 +1249,10 @@ class AgentLoop: tools=effective_tools.get_definitions(), persist=session is not None and not ephemeral, ), - injection_callback=_drain_pending, - terminal_injection_callback=_wait_for_pending, + injection_callback=pending_inputs.drain if pending_inputs is not None else None, + terminal_injection_callback=( + pending_inputs.wait_at_terminal if pending_inputs is not None else None + ), continuation_callback=( execution_scope.continuation_prompt if execution_scope is not None else None ), @@ -1339,11 +1264,6 @@ class AgentLoop: ), events=events, )) - finally: - turn_scope_stack.close() - reset_workspace_scope(workspace_token) - reset_request_context(request_token) - reset_file_states(file_state_token) if session is not None and retain_session_state: session.provider_state = result.provider_state if result.stop_reason == "max_iterations": diff --git a/nanobot/agent/pending_inputs.py b/nanobot/agent/pending_inputs.py new file mode 100644 index 000000000..534e4474d --- /dev/null +++ b/nanobot/agent/pending_inputs.py @@ -0,0 +1,81 @@ +"""Run-local FIFO input batches and bounded terminal waits.""" + +from __future__ import annotations + +import asyncio +from collections.abc import Awaitable, Callable, Iterable +from dataclasses import dataclass, field +from typing import Any + +from loguru import logger + +from nanobot.agent.execution_policy import ExecutionControlError +from nanobot.bus.events import InboundMessage + + +@dataclass +class PendingInputs: + """Consume only a prepared prefix; leave independent turns to the session worker.""" + + queue: asyncio.Queue[InboundMessage] + prepare: Callable[[InboundMessage], Awaitable[dict[str, Any] | None]] + consume: Callable[[Iterable[InboundMessage]], None] | None = None + session_key: str | None = None + running_subagents: Callable[[], int] | None = None + terminal_wait_seconds: float = 300.0 + _terminal_wait_deadline: float | None = field(default=None, init=False, repr=False) + + async def drain( + self, *, first_msg: InboundMessage | None = None, + ) -> list[dict[str, Any]]: + # Fix the boundary before preparation can await; later arrivals belong + # to the next model step even if they arrive during context resolution. + pending = [first_msg] if first_msg is not None else [] + for _ in range(self.queue.qsize()): + pending.append(self.queue.get_nowait()) + + consumed = 0 + try: + converted: list[dict[str, Any]] = [] + for message in pending: + row = await self.prepare(message) + if row is None: + break + converted.append(row) + if self.consume is not None: + try: + self.consume(pending[:len(converted)]) + except Exception as exc: + raise ExecutionControlError("could not accept consumed inputs") from exc + consumed = len(converted) + return converted + finally: + # Conversion or authorization failure returns the entire snapshot. + # A FIFO barrier returns the unconsumed suffix ahead of later inputs. + unconsumed = pending[consumed:] + if unconsumed: + later = [self.queue.get_nowait() for _ in range(self.queue.qsize())] + for message in [*unconsumed, *later]: + self.queue.put_nowait(message) + + async def wait_at_terminal(self) -> list[dict[str, Any]]: + items = await self.drain() + if items or self.running_subagents is None or self.running_subagents() == 0: + return items + + now = asyncio.get_running_loop().time() + if self._terminal_wait_deadline is None: + self._terminal_wait_deadline = now + self.terminal_wait_seconds + remaining = self._terminal_wait_deadline - now + if remaining <= 0: + return [] + + try: + message = await asyncio.wait_for(self.queue.get(), timeout=remaining) + except asyncio.TimeoutError: + logger.warning( + "Timeout waiting for sub-agent completion before session {} exits", + self.session_key, + ) + return [] + return await self.drain(first_msg=message) diff --git a/nanobot/agent/runner.py b/nanobot/agent/runner.py index 58d6bfe16..52efe76f8 100644 --- a/nanobot/agent/runner.py +++ b/nanobot/agent/runner.py @@ -6,7 +6,7 @@ from collections.abc import Awaitable, Callable, Iterable from copy import deepcopy from dataclasses import dataclass, field, replace from pathlib import Path -from typing import Any, Literal, ParamSpec, TypeVar, cast +from typing import Any, Literal, NotRequired, ParamSpec, TypedDict, TypeVar, cast from uuid import uuid4 from loguru import logger @@ -70,8 +70,24 @@ def _raise_if_cancelling() -> None: raise asyncio.CancelledError +class AgentCheckpointState(TypedDict): + """Runner state at a recovery boundary; omission retains private provider state.""" + + phase: Literal["model_input", "awaiting_tools", "tools_completed", "final_response"] + iteration: int + model: str + assistant_message: dict[str, Any] | None + completed_tool_results: list[dict[str, Any]] + pending_tool_calls: list[dict[str, Any]] + provider_state: NotRequired[ProviderConversationState | None] + + +class AgentCheckpoint(AgentCheckpointState): + preceding_messages: list[dict[str, Any]] + + ContinuationCallback = Callable[[], Awaitable[str | None]] -CheckpointCallback = Callable[[dict[str, Any]], Awaitable[None]] +CheckpointCallback = Callable[[AgentCheckpoint], Awaitable[None]] InjectionCallback = Callable[[], Awaitable[Iterable[Any] | None]] _DEFAULT_ERROR_MESSAGE = "Sorry, I encountered an error calling the AI model." @@ -1508,7 +1524,7 @@ class AgentRunner: async def _emit_checkpoint( self, spec: AgentRunSpec, - payload: dict[str, Any], + payload: AgentCheckpointState, messages: list[dict[str, Any]], ) -> None: callback = spec.checkpoint_callback diff --git a/nanobot/agent/subagent.py b/nanobot/agent/subagent.py index 06fd3fdb2..3927c2d26 100644 --- a/nanobot/agent/subagent.py +++ b/nanobot/agent/subagent.py @@ -16,7 +16,7 @@ from loguru import logger from nanobot.agent.hook import AgentHook, AgentHookContext from nanobot.agent.hooks import create_file_edit_activity_hook -from nanobot.agent.runner import AgentRunner, AgentRunSpec +from nanobot.agent.runner import AgentCheckpoint, AgentRunner, AgentRunSpec from nanobot.agent.session_activity import SessionActivity from nanobot.agent.subagent_sessions import SubagentSessions from nanobot.agent.subagent_status import SubagentState as SubagentState @@ -755,7 +755,7 @@ class SubagentManager: logger.info("Subagent [{}] starting task: {}", task_id, label if record.session.policy.log_content else "[content hidden]") - async def _on_checkpoint(payload: dict[str, Any]) -> None: + async def _on_checkpoint(payload: AgentCheckpoint) -> None: record.raise_if_stopping() phase = payload.get("phase", status.phase) iteration = payload.get("iteration", status.iteration) diff --git a/tests/agent/test_runner_injections.py b/tests/agent/test_runner_injections.py index 3591a25f5..bbfdd53a1 100644 --- a/tests/agent/test_runner_injections.py +++ b/tests/agent/test_runner_injections.py @@ -2017,3 +2017,100 @@ async def test_error_path_is_not_stopped_by_an_arbitrary_injection_cap(): assert result.had_injections is True assert call_count["n"] == 8 + + +@pytest.mark.asyncio +async def test_cancelling_input_conversion_preserves_other_concurrent_run(tmp_path): + from nanobot.agent.loop import AgentLoop + from nanobot.agent.tools.context import current_request_context, request_context + from nanobot.bus.events import InboundMessage + from nanobot.bus.queue import MessageBus + + provider = MagicMock(aclose=AsyncMock()) + provider.get_default_model.return_value = "test-model" + requests = [] + + async def respond(*, messages, **kwargs): + requests.append((current_request_context().session_key, [dict(row) for row in messages])) + # Stop the first execution while the second is inside its model request. + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert current_request_context().session_key == "cli:second" + return LLMResponse(content="second run finished") + + provider.chat_stream_with_retry = respond + loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model") + loop.tools.get_definitions = MagicMock(return_value=[]) + conversion_started = asyncio.Event() + never_release = asyncio.Event() + prepared_for = [] + + async def prepare_context(request): + prepared_for.append((request.session_key, request.original_user_text)) + assert current_request_context().session_key == request.session_key + if request.original_user_text == "first private input": + conversion_started.set() + await never_release.wait() + return None + + loop.register_runtime_context_provider(prepare_context) + runtime = loop.llm_runtime() + first, second = asyncio.Queue(), asyncio.Queue() + for content in ["first private input", "first tail"]: + first.put_nowait(InboundMessage("cli", "u", "first", content)) + for content in ["second input", "second tail"]: + second.put_nowait(InboundMessage("cli", "u", "second", content)) + outer = RequestContext(channel="test", chat_id="outer", session_key="test:outer") + restored = [] + + async def first_run(): + try: + return await loop._run_agent_loop( + TranscriptInput(history=[{"role": "user", "content": "first root"}], current_message=None), + runtime=runtime, + request_context=RequestContext(channel="cli", chat_id="first", session_key="cli:first", runtime=runtime), + pending_queue=first, + ) + finally: + restored.append(current_request_context()) + + task = None + try: + with request_context(outer): + task = asyncio.create_task(first_run()) + await asyncio.wait_for(conversion_started.wait(), timeout=5) + first.put_nowait(InboundMessage("cli", "u", "first", "first later arrival")) + result = await loop._run_agent_loop( + TranscriptInput(history=[{"role": "user", "content": "second root"}], current_message=None), + runtime=runtime, + request_context=RequestContext(channel="cli", chat_id="second", session_key="cli:second", runtime=runtime), + pending_queue=second, + ) + assert current_request_context() is outer + + assert result.final_content == "second run finished" + assert restored == [outer] + assert [first.get_nowait().content for _ in range(first.qsize())] == [ + "first private input", "first tail", "first later arrival", + ] + assert second.empty() + assert prepared_for == [ + ("cli:first", "first private input"), + ("cli:second", "second input"), + ("cli:second", "second tail"), + ] + assert len(requests) == 1 + key, messages = requests[0] + assert key == "cli:second" + assert [visible_message(row)["content"] for row in messages if row["role"] == "user"] == [ + "second root\n\nsecond input\n\nsecond tail", + ] + assert [visible_message(row)["content"] for row in result.messages if row["role"] == "user"] == [ + "second root", "second input", "second tail", + ] + finally: + if task is not None and not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + await loop.aclose() diff --git a/tests/agent/tools/test_subagent_tools.py b/tests/agent/tools/test_subagent_tools.py index af72853e4..883efaeaa 100644 --- a/tests/agent/tools/test_subagent_tools.py +++ b/tests/agent/tools/test_subagent_tools.py @@ -730,7 +730,7 @@ async def test_terminal_drain_timeout(tmp_path): awaitable.close() raise asyncio.TimeoutError - with patch("nanobot.agent.loop.asyncio.wait_for", side_effect=_timeout): + with patch("nanobot.agent.pending_inputs.asyncio.wait_for", side_effect=_timeout): results = await terminal_injection_callback() assert results == [] @@ -800,10 +800,10 @@ async def test_terminal_drain_reuses_one_timeout_budget(tmp_path): loop.tools.get_runtime_context_providers = MagicMock(return_value=[]) fake_loop = MagicMock(wraps=asyncio.get_running_loop()) fake_loop.time = clock - loop_asyncio = SimpleNamespace(**vars(asyncio)) - loop_asyncio.get_running_loop = lambda: fake_loop - loop_asyncio.wait_for = _deliver - with patch("nanobot.agent.loop.asyncio", loop_asyncio): + pending_asyncio = SimpleNamespace(**vars(asyncio)) + pending_asyncio.get_running_loop = lambda: fake_loop + pending_asyncio.wait_for = _deliver + with patch("nanobot.agent.pending_inputs.asyncio", pending_asyncio): assert await terminal_injection_callback() assert await terminal_injection_callback()