feat(subagent): add session-owned task messaging and cancellation (#5985)
let's go!
This commit is contained in:
1 parent
f75470e72f
commit
6ff96f2a8f
93 files changed
+5632
-1156
No files matched your search
@@ -1,11 +1,24 @@
|
||||
"""Session-worker completion helpers for integration tests."""
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.agent.subagent_status import SubagentStatus
|
||||
from nanobot.bus.events import InboundMessage
|
||||
|
||||
|
||||
def save_completed_subagent(loop: AgentLoop, task_id: str, owner: str) -> None:
|
||||
"""Persist the child that owns a synthetic completion notification."""
|
||||
assert loop.subagents.sessions is not None
|
||||
now = time.monotonic()
|
||||
loop.subagents.sessions.create(SubagentStatus(
|
||||
task_id=task_id, label=task_id, task_description="Background work",
|
||||
owner=owner, started_at=now, finished_at=now, completed_at=time.time(),
|
||||
state="done", phase="done",
|
||||
))
|
||||
|
||||
|
||||
async def run_session(loop: AgentLoop, msg: InboundMessage) -> None:
|
||||
"""Submit input and wait for its session worker to finish."""
|
||||
loop._enqueue_session_message(msg)
|
||||
|
||||
@@ -6,7 +6,7 @@ from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from agent.session_helpers import run_session
|
||||
from agent.session_helpers import run_session, save_completed_subagent
|
||||
from nanobot.agent.context import TranscriptInput
|
||||
from nanobot.agent.hooks import create_file_edit_activity_hook
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
@@ -869,6 +869,7 @@ class TestToolEventProgress:
|
||||
session.add_message("user", "Run this in the background")
|
||||
session.metadata.update({"webui": True, "title": "Existing title"})
|
||||
loop.sessions.save(session)
|
||||
save_completed_subagent(loop, "sub-1", session_key)
|
||||
dispatch = asyncio.create_task(run_session(loop, InboundMessage(
|
||||
channel="system",
|
||||
sender_id="subagent",
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
import asyncio
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
@@ -640,8 +640,8 @@ async def test_next_turn_after_llm_error_keeps_turn_boundary(tmp_path):
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_subagent_max_iterations_announces_existing_fallback(tmp_path, monkeypatch):
|
||||
from nanobot.agent.subagent import SubagentManager, SubagentStatus
|
||||
async def test_subagent_max_iterations_announces_partial_incomplete_result(tmp_path, monkeypatch):
|
||||
from nanobot.agent.subagent import SubagentManager
|
||||
from nanobot.bus.queue import MessageBus
|
||||
|
||||
bus = MessageBus()
|
||||
@@ -658,24 +658,28 @@ async def test_subagent_max_iterations_announces_existing_fallback(tmp_path, mon
|
||||
consolidator=MagicMock(),
|
||||
max_iterations=2,
|
||||
)
|
||||
mgr._announce_result = AsyncMock()
|
||||
|
||||
async def fake_execute(self, **kwargs):
|
||||
return "tool result"
|
||||
|
||||
monkeypatch.setattr("nanobot.agent.tools.filesystem.ListDirTool.execute", fake_execute)
|
||||
|
||||
status = SubagentStatus(task_id="sub-1", label="label", task_description="do task", started_at=time.monotonic())
|
||||
await mgr._run_subagent(
|
||||
"sub-1",
|
||||
"do task",
|
||||
"label",
|
||||
{"channel": "test", "chat_id": "c1"},
|
||||
status,
|
||||
LLMRuntime.capture(provider, "test-model", context_window_tokens=128_000),
|
||||
await mgr.spawn(
|
||||
task="do task",
|
||||
label="label",
|
||||
origin_channel="test",
|
||||
origin_chat_id="c1",
|
||||
runtime=LLMRuntime.capture(provider, "test-model", context_window_tokens=128_000),
|
||||
)
|
||||
await asyncio.gather(*mgr._running_tasks.values(), return_exceptions=True)
|
||||
|
||||
mgr._announce_result.assert_awaited_once()
|
||||
args = mgr._announce_result.await_args.args
|
||||
assert args[3] == "Task completed but no final response was generated."
|
||||
assert args[5] == "ok"
|
||||
status = next(iter(mgr.statuses_for_session("test:c1").values()))
|
||||
assert status.state == "incomplete"
|
||||
assert status.stop_reason == "max_iterations"
|
||||
assert status.partial is True
|
||||
assert status.result == "working"
|
||||
notice = await asyncio.wait_for(bus.consume_inbound(), timeout=1)
|
||||
assert notice.metadata["subagent_state"] == "incomplete"
|
||||
assert notice.metadata["subagent_partial"] is True
|
||||
assert "working" in notice.content
|
||||
await mgr.close()
|
||||
@@ -7,7 +7,7 @@ from unittest.mock import AsyncMock, MagicMock
|
||||
import pytest
|
||||
from loguru import logger
|
||||
|
||||
from agent.session_helpers import run_session
|
||||
from agent.session_helpers import run_session, save_completed_subagent
|
||||
from nanobot.agent.context import ContextBuilder, TranscriptInput
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.agent.runner import AgentRunResult
|
||||
@@ -1088,6 +1088,7 @@ async def test_subagent_followup_stages_provider_state_before_turn_runs(
|
||||
session = loop.sessions.get_or_create("cli:subagent-crash")
|
||||
session.provider_state = _provider_state()
|
||||
loop.sessions.save(session)
|
||||
save_completed_subagent(loop, "sub-1", session.key)
|
||||
|
||||
msg = InboundMessage(
|
||||
channel="system",
|
||||
@@ -1119,6 +1120,7 @@ async def test_subagent_followup_state_is_durable_before_prompt_assembly(
|
||||
session = loop.sessions.get_or_create("cli:subagent-prompt-crash")
|
||||
session.provider_state = _provider_state()
|
||||
loop.sessions.save(session)
|
||||
save_completed_subagent(loop, "sub-1", session.key)
|
||||
|
||||
msg = InboundMessage(
|
||||
channel="system",
|
||||
@@ -1152,6 +1154,7 @@ async def test_subagent_redelivery_does_not_duplicate_staged_provider_input(
|
||||
session = loop.sessions.get_or_create("cli:subagent-redelivery")
|
||||
session.provider_state = _provider_state()
|
||||
loop.sessions.save(session)
|
||||
save_completed_subagent(loop, "sub-1", session.key)
|
||||
msg = InboundMessage(
|
||||
channel="system",
|
||||
sender_id="subagent",
|
||||
@@ -1201,6 +1204,7 @@ async def test_subagent_followup_clears_state_before_compatibility_failure(
|
||||
session = loop.sessions.get_or_create("cli:subagent-compat-crash")
|
||||
session.provider_state = _provider_state()
|
||||
loop.sessions.save(session)
|
||||
save_completed_subagent(loop, "sub-1", session.key)
|
||||
|
||||
msg = InboundMessage(
|
||||
channel="system",
|
||||
@@ -1759,11 +1763,11 @@ async def test_process_direct_skip_user_persist_does_not_save_retry_user(
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_request_context_uses_effective_key_for_spawn_tool(tmp_path: Path) -> None:
|
||||
async def test_request_context_uses_effective_key_for_subagent_tool(tmp_path: Path) -> None:
|
||||
loop = _make_full_loop(tmp_path)
|
||||
spawn_tool = loop.tools.get("spawn")
|
||||
assert spawn_tool is not None
|
||||
spawn_tool._manager.spawn = AsyncMock(return_value="started") # type: ignore[attr-defined]
|
||||
subagent_tool = loop.tools.get("subagent")
|
||||
assert subagent_tool is not None
|
||||
subagent_tool._manager.spawn = AsyncMock(return_value="started") # type: ignore[attr-defined]
|
||||
runtime = loop.llm_runtime()
|
||||
|
||||
with request_context(RequestContext(
|
||||
@@ -1772,9 +1776,9 @@ async def test_request_context_uses_effective_key_for_spawn_tool(tmp_path: Path)
|
||||
session_key="discord:parent-456:thread:thread-777",
|
||||
runtime=runtime,
|
||||
)):
|
||||
await spawn_tool.execute(task="inspect context")
|
||||
await subagent_tool.execute(action="create", task="inspect context")
|
||||
|
||||
call = spawn_tool._manager.spawn.await_args.kwargs # type: ignore[attr-defined]
|
||||
call = subagent_tool._manager.spawn.await_args.kwargs # type: ignore[attr-defined]
|
||||
assert call["origin_channel"] == "discord"
|
||||
assert call["origin_chat_id"] == "thread-777"
|
||||
assert call["session_key"] == "discord:parent-456:thread:thread-777"
|
||||
@@ -1940,6 +1944,7 @@ async def test_system_subagent_followup_is_persisted_before_prompt_assembly(tmp_
|
||||
session.add_message("user", "question")
|
||||
session.add_message("assistant", "working")
|
||||
loop.sessions.save(session)
|
||||
save_completed_subagent(loop, "sub-1", session.key)
|
||||
|
||||
runtime = loop.llm_runtime()
|
||||
seen: dict[str, object] = {}
|
||||
@@ -2040,6 +2045,7 @@ async def test_turn_usage_is_persisted_with_the_saved_session(tmp_path: Path) ->
|
||||
@pytest.mark.asyncio
|
||||
async def test_system_subagent_followup_does_not_log_content(tmp_path: Path) -> None:
|
||||
loop = _make_full_loop(tmp_path)
|
||||
save_completed_subagent(loop, "sub-logs", "cli:logs")
|
||||
|
||||
async def fake_run_agent_loop(transcript_input, **_kwargs):
|
||||
initial_messages = _assembled_messages(loop.context, transcript_input)
|
||||
@@ -2076,6 +2082,7 @@ async def test_system_subagent_followup_does_not_log_content(tmp_path: Path) ->
|
||||
@pytest.mark.asyncio
|
||||
async def test_system_subagent_followup_uses_common_turn_lifecycle(tmp_path: Path) -> None:
|
||||
loop = _make_full_loop(tmp_path)
|
||||
save_completed_subagent(loop, "sub-1", "cli:test")
|
||||
visited: list[str] = []
|
||||
|
||||
for name in (
|
||||
@@ -2204,6 +2211,7 @@ async def test_multiple_subagent_followups_all_persist_as_standalone_history(tmp
|
||||
loop._run_agent_loop = fake_run_agent_loop # type: ignore[method-assign]
|
||||
|
||||
for idx in range(3):
|
||||
save_completed_subagent(loop, f"sub-{idx}", "cli:multi")
|
||||
await loop._process_message(
|
||||
InboundMessage(
|
||||
channel="system",
|
||||
@@ -2291,11 +2299,11 @@ def test_subagent_followup_skips_empty_content() -> None:
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_request_context_passes_thread_session_key_to_spawn(tmp_path: Path) -> None:
|
||||
async def test_request_context_passes_thread_session_key_to_subagent_create(tmp_path: Path) -> None:
|
||||
loop = _make_full_loop(tmp_path)
|
||||
spawn_tool = loop.tools.get("spawn")
|
||||
assert spawn_tool is not None
|
||||
spawn_tool._manager.spawn = AsyncMock(return_value="started") # type: ignore[attr-defined]
|
||||
subagent_tool = loop.tools.get("subagent")
|
||||
assert subagent_tool is not None
|
||||
subagent_tool._manager.spawn = AsyncMock(return_value="started") # type: ignore[attr-defined]
|
||||
runtime = loop.llm_runtime()
|
||||
|
||||
with request_context(RequestContext(
|
||||
@@ -2306,9 +2314,9 @@ async def test_request_context_passes_thread_session_key_to_spawn(tmp_path: Path
|
||||
session_key="slack:C123:1700.42",
|
||||
runtime=runtime,
|
||||
)):
|
||||
await spawn_tool.execute(task="inspect thread")
|
||||
await subagent_tool.execute(action="create", task="inspect thread")
|
||||
|
||||
call = spawn_tool._manager.spawn.await_args.kwargs # type: ignore[attr-defined]
|
||||
call = subagent_tool._manager.spawn.await_args.kwargs # type: ignore[attr-defined]
|
||||
assert call["session_key"] == "slack:C123:1700.42"
|
||||
assert call["origin_message_id"] == "msg-123"
|
||||
assert call["runtime"] is runtime
|
||||
@@ -2321,6 +2329,7 @@ async def test_system_subagent_followup_uses_thread_session_and_slack_metadata(t
|
||||
thread_session = loop.sessions.get_or_create("slack:C123:1700.42")
|
||||
thread_session.add_message("user", "thread question")
|
||||
loop.sessions.save(thread_session)
|
||||
save_completed_subagent(loop, "sub-1", thread_session.key)
|
||||
|
||||
seen: dict[str, object] = {}
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@ from loguru import logger
|
||||
from agent.session_helpers import run_session
|
||||
from nanobot.agent.context import TranscriptInput
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.agent.runner import AgentRunResult
|
||||
from nanobot.agent.subagent_sessions import SubagentSessions
|
||||
from nanobot.agent.tools.context import current_request_context
|
||||
from nanobot.agent.tools.registry import ToolRegistry
|
||||
from nanobot.bus.events import (
|
||||
@@ -19,6 +21,8 @@ from nanobot.providers.base import GenerationSettings, LLMResponse, ToolCallRequ
|
||||
from nanobot.runtime_context import RuntimeContextBlock
|
||||
from nanobot.session.keys import UNIFIED_SESSION_KEY
|
||||
from nanobot.session.manager import SessionPolicy
|
||||
from nanobot.webui.temporary_chats import WebUITemporaryChats
|
||||
from nanobot.webui.workspaces import WebUIWorkspaceController
|
||||
|
||||
|
||||
def _message(key: str, content: str) -> InboundMessage:
|
||||
@@ -53,11 +57,14 @@ def _loop(tmp_path, responses: list[str], **kwargs) -> AgentLoop:
|
||||
async def test_transient_session_keeps_history_without_persisting_or_durable_tools(tmp_path) -> None:
|
||||
loop = _loop(tmp_path, ["first answer", "second answer"])
|
||||
loop.context.memory.write_memory("private durable memory")
|
||||
key = "websocket:transient-test"
|
||||
loop.sessions.get_or_create_transient(
|
||||
key,
|
||||
disabled_tools={"create_goal", "update_goal", "spawn", "cron"},
|
||||
temporary_chats = WebUITemporaryChats(
|
||||
bus=loop.bus, session_manager=loop.sessions, logger=logger,
|
||||
workspaces=WebUIWorkspaceController(
|
||||
session_manager=loop.sessions, default_workspace=tmp_path,
|
||||
default_restrict_to_workspace=True,
|
||||
),
|
||||
)
|
||||
key = f"websocket:{temporary_chats.create(object(), trusted_webui=True)}"
|
||||
|
||||
await loop._process_message(_message(key, "first question"))
|
||||
await loop._process_message(_message(key, "second question"))
|
||||
@@ -66,7 +73,7 @@ async def test_transient_session_keeps_history_without_persisting_or_durable_too
|
||||
assert "private durable memory" not in str(calls[0].kwargs["messages"])
|
||||
tool_names = {item["function"]["name"] for item in calls[0].kwargs["tools"]}
|
||||
assert "read_session" in tool_names
|
||||
assert {"create_goal", "update_goal", "spawn", "cron"}.isdisjoint(tool_names)
|
||||
assert {"create_goal", "update_goal", "subagent", "cron"}.isdisjoint(tool_names)
|
||||
assert "first answer" in str(calls[1].kwargs["messages"])
|
||||
session = loop.sessions.get_cached(key)
|
||||
assert session is not None
|
||||
@@ -77,6 +84,8 @@ async def test_transient_session_keeps_history_without_persisting_or_durable_too
|
||||
"assistant",
|
||||
]
|
||||
assert loop.sessions.read_session_file(key) is None
|
||||
temporary_chats.close()
|
||||
await loop.aclose()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("selection", ["explicit_empty", "disable_all", "default"])
|
||||
@@ -295,6 +304,47 @@ async def test_missing_required_session_cannot_fall_back_to_disk(tmp_path) -> No
|
||||
assert loop.sessions.read_session_file(key) is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_required_durable_session_survives_cache_eviction(tmp_path) -> None:
|
||||
loop = _loop(tmp_path, ["received"])
|
||||
key = "websocket:durable-parent"
|
||||
session = loop.sessions.get_or_create(key)
|
||||
session.add_message("user", "earlier question")
|
||||
loop.sessions.save(session)
|
||||
loop.sessions.invalidate(key)
|
||||
try:
|
||||
response = await loop._process_message(_message(key, "follow-up"))
|
||||
assert response is not None and response.content == "received"
|
||||
assert "earlier question" in str(loop.provider.chat_stream_with_retry.await_args.kwargs["messages"])
|
||||
finally:
|
||||
await loop.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_deleted_child_cannot_notify_a_recreated_parent(tmp_path) -> None:
|
||||
loop = _loop(tmp_path, [])
|
||||
key = "websocket:recreated-parent"
|
||||
loop.subagents.runner.run = AsyncMock(return_value=AgentRunResult(messages=[], final_content="old result"))
|
||||
try:
|
||||
await loop.subagents.spawn("old task", session_key=key, runtime=loop.llm_runtime())
|
||||
await asyncio.gather(*loop.subagents._running_tasks.values())
|
||||
task_id, = loop.subagents.statuses_for_session(key)
|
||||
notice = await asyncio.wait_for(loop.bus.consume_inbound(), timeout=2)
|
||||
assert notice.require_existing_session
|
||||
assert loop.sessions.delete_session(key)
|
||||
assert loop.sessions.read_session_file(SubagentSessions.key(task_id)) is None
|
||||
loop.sessions.save(loop.sessions.get_or_create(key))
|
||||
|
||||
assert loop.subagents.statuses_for_session(key) == {}
|
||||
loop._enqueue_session_message(notice)
|
||||
assert key not in loop._pending_queues
|
||||
assert await loop._process_message(notice) is None
|
||||
loop.provider.chat_stream_with_retry.assert_not_awaited()
|
||||
assert loop.sessions.read_session_file(key)["messages"] == []
|
||||
finally:
|
||||
await loop.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_session_discard_control_cancels_active_turn(tmp_path, monkeypatch) -> None:
|
||||
provider_started = asyncio.Event()
|
||||
@@ -322,7 +372,7 @@ async def test_session_discard_control_cancels_active_turn(tmp_path, monkeypatch
|
||||
previous_file_state = loop._file_state_store.for_session(key)
|
||||
loop.sessions.get_or_create_transient(
|
||||
key,
|
||||
disabled_tools={"create_goal", "update_goal", "spawn", "cron"},
|
||||
disabled_tools={"create_goal", "update_goal", "subagent", "cron"},
|
||||
)
|
||||
run_task = asyncio.create_task(loop.run())
|
||||
await loop.bus.publish_inbound(_message(key, "private"))
|
||||
|
||||
@@ -8,7 +8,7 @@ import pytest
|
||||
|
||||
from nanobot.agent.memory import Consolidator
|
||||
from nanobot.agent.runner import AgentRunResult
|
||||
from nanobot.agent.subagent import SubagentManager, SubagentStatus
|
||||
from nanobot.agent.subagent import SubagentManager
|
||||
from nanobot.agent.tools.filesystem import FileToolsConfig
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.config.schema import ToolsConfig
|
||||
@@ -39,6 +39,10 @@ async def test_subagent_uses_tool_loader():
|
||||
assert tools.has("write_file")
|
||||
assert not tools.has("message")
|
||||
assert not tools.has("spawn")
|
||||
assert not tools.has("subagent")
|
||||
assert not tools.has("send_session_message")
|
||||
assert not tools.has("read_session")
|
||||
assert not tools.has("my")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -152,22 +156,16 @@ async def test_subagent_keeps_project_runtime_scope_with_agent_owned_tools(tmp_p
|
||||
return_value=AgentRunResult(final_content="ok", messages=[], stop_reason="completed")
|
||||
)
|
||||
manager._announce_result = AsyncMock()
|
||||
status = SubagentStatus(
|
||||
task_id="t1",
|
||||
label="label",
|
||||
task_description="task",
|
||||
started_at=0.0,
|
||||
)
|
||||
|
||||
await manager._run_subagent(
|
||||
"t1",
|
||||
"task",
|
||||
"label",
|
||||
{"channel": "websocket", "chat_id": "direct"},
|
||||
status,
|
||||
_runtime(provider),
|
||||
await manager.spawn(
|
||||
task="task",
|
||||
label="label",
|
||||
origin_channel="websocket",
|
||||
origin_chat_id="direct",
|
||||
runtime=_runtime(provider),
|
||||
workspace_scope=build_workspace_scope(project, "restricted"),
|
||||
)
|
||||
await asyncio.gather(*manager._running_tasks.values(), return_exceptions=True)
|
||||
|
||||
spec = manager.runner.run.call_args.args[0]
|
||||
assert spec.workspace == project
|
||||
|
||||
@@ -0,0 +1,894 @@
|
||||
"""Private task ownership, message receipts, cancellation, and shell lifetime."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
from loguru import logger
|
||||
|
||||
from nanobot.agent.memory import Consolidator
|
||||
from nanobot.agent.runner import AgentRunResult
|
||||
from nanobot.agent.subagent import SubagentManager
|
||||
from nanobot.agent.tools.base import Tool
|
||||
from nanobot.agent.tools.context import RequestContext, current_request_context, request_context
|
||||
from nanobot.agent.tools.registry import ToolRegistry, is_tool_error_result
|
||||
from nanobot.agent.tools.shell import ExecTool
|
||||
from nanobot.agent.tools.subagent import SubagentTool
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.nanobot import Nanobot
|
||||
from nanobot.providers.base import GenerationSettings, LLMProvider, LLMResponse, ToolCallRequest
|
||||
from nanobot.session.webui_turns import WebuiTurnRoutePolicy
|
||||
from nanobot.utils.llm_runtime import LLMRuntime
|
||||
|
||||
|
||||
def setup(tmp_path, **kwargs):
|
||||
manager = SubagentManager(
|
||||
workspace=tmp_path, bus=MessageBus(), max_tool_result_chars=16000,
|
||||
consolidator=MagicMock(spec=Consolidator), **kwargs,
|
||||
)
|
||||
provider = MagicMock(spec=LLMProvider)
|
||||
provider.generation = GenerationSettings()
|
||||
runtime = LLMRuntime.capture(provider, "test", context_window_tokens=128000)
|
||||
ctx = RequestContext("websocket", "route", session_key="owner", runtime=runtime)
|
||||
return manager, provider, ctx
|
||||
|
||||
|
||||
async def spawn(manager, ctx, text="task"):
|
||||
with request_context(ctx):
|
||||
result = await SubagentTool(manager).execute(action="create", task=text)
|
||||
task_id = re.search(r"id: ([\w-]+)", result).group(1)
|
||||
assert str(uuid.UUID(task_id)) == task_id
|
||||
return task_id
|
||||
|
||||
|
||||
async def control(manager, ctx, task_id, action=None, message=None):
|
||||
with request_context(ctx):
|
||||
return await SubagentTool(manager).execute(action or "check", task_id, message)
|
||||
|
||||
|
||||
async def settled(manager):
|
||||
await asyncio.gather(*list(manager._running_tasks.values()), return_exceptions=True)
|
||||
await asyncio.sleep(0)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_direct_turn_waits_for_child_without_a_background_consumer(loop_factory):
|
||||
loop = loop_factory()
|
||||
loop.provider.provider_name = "test"
|
||||
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=[
|
||||
LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||
id="delegate", name="subagent",
|
||||
arguments={"action": "create", "task": "Inspect the configuration"},
|
||||
)]),
|
||||
LLMResponse(content="Verified child findings"),
|
||||
LLMResponse(content="Parent conclusion from the child findings"),
|
||||
])
|
||||
try:
|
||||
response = await loop.process_direct("Delegate this inspection")
|
||||
assert response.content == "Parent conclusion from the child findings"
|
||||
parent_followup = loop.provider.chat_stream_with_retry.call_args_list[-1].kwargs["messages"]
|
||||
assert any(m.get("role") == "tool" and m.get("content") == "Verified child findings"
|
||||
for m in parent_followup)
|
||||
assert loop.bus.inbound_size == 0
|
||||
assert loop.subagents.get_running_count() == 0
|
||||
assert next(iter(loop.subagents.statuses_for_session("cli:direct").values())).state == "done"
|
||||
finally:
|
||||
await loop.subagents.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("existing_parent", [False, True])
|
||||
@pytest.mark.parametrize("streamed", [False, True])
|
||||
async def test_sdk_ephemeral_delegation_never_persists_on_later_flush(
|
||||
loop_factory, existing_parent, streamed,
|
||||
):
|
||||
loop = loop_factory()
|
||||
bot = Nanobot(loop)
|
||||
key = "sdk:ephemeral-delegation"
|
||||
parent = loop.sessions.get_or_create(key)
|
||||
if existing_parent:
|
||||
parent.add_message("user", "Earlier durable question")
|
||||
loop.sessions.save(parent)
|
||||
before = {path.name: path.read_bytes() for path in loop.sessions.sessions_dir.glob("*.jsonl")}
|
||||
secret = "private-delegation-marker"
|
||||
source = loop.workspace / f"{secret}.txt"
|
||||
source.write_text(secret * 1000, encoding="utf-8")
|
||||
loop.max_tool_result_chars = 2048
|
||||
responses = iter([
|
||||
LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||
id="delegate", name="subagent", arguments={"action": "create", "task": secret},
|
||||
)]),
|
||||
LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||
id="inspect", name="read_file", arguments={"path": str(source)},
|
||||
)]),
|
||||
LLMResponse(content=f"Child findings: {secret}"),
|
||||
LLMResponse(content=f"Parent conclusion: {secret}"),
|
||||
])
|
||||
requests = []
|
||||
|
||||
async def respond(**kwargs):
|
||||
requests.append(current_request_context())
|
||||
return next(responses)
|
||||
|
||||
loop.provider.provider_name = "test"
|
||||
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=respond)
|
||||
logs = []
|
||||
sink = logger.add(lambda message: logs.append(message.record["message"]))
|
||||
consumer = asyncio.create_task(loop.run())
|
||||
try:
|
||||
await asyncio.sleep(0)
|
||||
assert loop._running
|
||||
if streamed:
|
||||
stream = await bot.run_streamed(secret, session_key=key, ephemeral=True)
|
||||
result = await stream.wait()
|
||||
else:
|
||||
result = await bot.run(secret, session_key=key, ephemeral=True)
|
||||
assert result.content == f"Parent conclusion: {secret}"
|
||||
assert all(ctx is not None and not ctx.log_content and not ctx.persist_session for ctx in requests)
|
||||
assert secret not in "\n".join(logs)
|
||||
assert {path.name: path.read_bytes() for path in loop.sessions.sessions_dir.glob("*.jsonl")} == before
|
||||
assert not list(loop.sessions.sessions_dir.glob("*.checkpoint.json"))
|
||||
assert not (loop.workspace / ".nanobot" / "tool-results").exists()
|
||||
assert loop.bus.inbound_size == 0
|
||||
|
||||
loop.provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="Durable answer"))
|
||||
await bot.run("Durable follow-up", session_key=key)
|
||||
bot.sessions.flush()
|
||||
saved = "\n".join(path.read_text() for path in loop.sessions.sessions_dir.glob("*.jsonl"))
|
||||
assert "Durable answer" in saved
|
||||
assert ("Earlier durable question" in saved) is existing_parent
|
||||
assert secret not in saved
|
||||
assert len(list(loop.sessions.sessions_dir.glob("*.jsonl"))) == 1
|
||||
finally:
|
||||
loop.stop()
|
||||
await asyncio.wait_for(consumer, timeout=2)
|
||||
logger.remove(sink)
|
||||
await bot.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_child_origin_uses_the_channel_turn_identity(loop_factory):
|
||||
loop = loop_factory()
|
||||
loop.provider.provider_name = "test"
|
||||
loop.turn_delivery_factory.route_policy = WebuiTurnRoutePolicy(loop.sessions)
|
||||
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=[
|
||||
LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||
id="delegate", name="subagent", arguments={"action": "create", "task": "Inspect config"},
|
||||
)]),
|
||||
LLMResponse(content="Child findings"),
|
||||
LLMResponse(content="Parent conclusion"),
|
||||
])
|
||||
message = InboundMessage("websocket", "user", "origin-check", "Delegate this inspection",
|
||||
metadata={"webui_turn_id": "visible-parent-turn"})
|
||||
try:
|
||||
await loop._process_message(message)
|
||||
status = next(iter(loop.subagents.statuses_for_session(message.session_key).values()))
|
||||
assert status.origin_turn_id == "visible-parent-turn"
|
||||
finally:
|
||||
await loop.subagents.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_owner_canonical_fallback_and_absent_context(tmp_path):
|
||||
manager, _, ctx = setup(tmp_path)
|
||||
manager.runner.run = AsyncMock(return_value=AgentRunResult(messages=[], final_content="private"))
|
||||
task_id = await spawn(manager, ctx)
|
||||
receipt = manager.send(task_id, "owner", "follow-up")
|
||||
snapshot = manager.statuses_for_session("owner")[task_id]
|
||||
snapshot.state = "cancelled"
|
||||
snapshot.owner = "other"
|
||||
snapshot.receipts.clear()
|
||||
current = manager.runtime_statuses()[task_id]
|
||||
assert current.state == "queued"
|
||||
assert current.owner == "owner"
|
||||
assert current.receipts == {receipt["message_id"]: "accepted"}
|
||||
await settled(manager)
|
||||
terminal = await manager.cancel(task_id, "owner")
|
||||
terminal.result = "tampered"
|
||||
terminal.receipts.clear()
|
||||
current = manager.statuses_for_session("owner")[task_id]
|
||||
assert current.result == "private"
|
||||
assert current.receipts == {receipt["message_id"]: "undelivered"}
|
||||
denied = await SubagentTool(manager).execute("cancel", task_id)
|
||||
assert is_tool_error_result(denied)
|
||||
for stranger in [RequestContext("websocket", "route", session_key="other"),
|
||||
RequestContext("websocket", "route"), RequestContext("", "")]:
|
||||
for action in [None, "send", "cancel"]:
|
||||
assert await control(manager, stranger, task_id, action, "secret") == denied
|
||||
assert await control(manager, ctx, "missing") == denied
|
||||
# Canonical identity, not the transport route, owns the task.
|
||||
same_owner = RequestContext("cli", "different", session_key="owner")
|
||||
assert json.loads(await control(manager, same_owner, task_id))["result"] == "private"
|
||||
fallback = RequestContext("cli", "fallback", runtime=ctx.runtime)
|
||||
fallback_id = await spawn(manager, fallback)
|
||||
await settled(manager)
|
||||
assert await control(manager, fallback, fallback_id, "cancel") == denied
|
||||
explicit_owner = RequestContext("cli", "fallback", session_key="cli:fallback")
|
||||
assert json.loads(await control(manager, explicit_owner, fallback_id))["state"] == "done"
|
||||
assert manager.statuses_for_session(None) == {}
|
||||
await manager.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_bounded_fifo_snapshot_and_terminal_receipts(tmp_path):
|
||||
manager, _, ctx = setup(tmp_path)
|
||||
entered, drain, drained, finish = (asyncio.Event() for _ in range(4))
|
||||
snapshots = []
|
||||
|
||||
async def run(spec):
|
||||
entered.set()
|
||||
await drain.wait()
|
||||
snapshots.append(await spec.injection_callback())
|
||||
drained.set()
|
||||
await finish.wait()
|
||||
return AgentRunResult(messages=[], final_content="done")
|
||||
|
||||
manager.runner.run = run
|
||||
task_id = await spawn(manager, ctx)
|
||||
await entered.wait()
|
||||
for invalid in ["", " ", "x" * 8193, "界" * 2731]:
|
||||
assert is_tool_error_result(await control(manager, ctx, task_id, "send", invalid))
|
||||
receipts = []
|
||||
for i in range(manager.MAX_INBOX):
|
||||
receipt = json.loads(await control(manager, ctx, task_id, "send", str(i)))
|
||||
assert receipt["receipt"] == "accepted" and not receipt["delivered"]
|
||||
receipts.append(receipt["message_id"])
|
||||
assert is_tool_error_result(await control(manager, ctx, task_id, "send", "overflow"))
|
||||
drain.set()
|
||||
await drained.wait()
|
||||
assert snapshots == [[{"role": "user", "content": str(i)} for i in range(manager.MAX_INBOX)]]
|
||||
last = json.loads(await control(manager, ctx, task_id, "send", "late"))["message_id"]
|
||||
finish.set()
|
||||
await settled(manager)
|
||||
status = json.loads(await control(manager, ctx, task_id))
|
||||
assert status["state"] == "done"
|
||||
assert status["receipts"] == {**dict.fromkeys(receipts, "delivered"), last: "undelivered"}
|
||||
assert is_tool_error_result(await control(manager, ctx, task_id, "send", "no restart"))
|
||||
notice = await manager.bus.consume_inbound()
|
||||
assert notice.metadata["subagent_task_id"] == task_id
|
||||
assert notice.metadata["subagent_message_receipts"] == status["receipts"]
|
||||
assert last in notice.content
|
||||
assert manager.bus.inbound_size == 0
|
||||
await manager.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lifetime_receipt_limit_rejects_without_silent_eviction(tmp_path):
|
||||
manager, _, ctx = setup(tmp_path)
|
||||
manager.MAX_MESSAGES = 2
|
||||
entered = asyncio.Event()
|
||||
specs = []
|
||||
|
||||
async def run(spec):
|
||||
specs.append(spec)
|
||||
entered.set()
|
||||
await asyncio.Event().wait()
|
||||
|
||||
manager.runner.run = run
|
||||
task_id = await spawn(manager, ctx)
|
||||
await entered.wait()
|
||||
for text in ["one", "two"]:
|
||||
assert not is_tool_error_result(await control(manager, ctx, task_id, "send", text))
|
||||
await specs[0].injection_callback()
|
||||
assert is_tool_error_result(await control(manager, ctx, task_id, "send", "three"))
|
||||
await control(manager, ctx, task_id, "cancel")
|
||||
assert len(json.loads(await control(manager, ctx, task_id))["receipts"]) == 2
|
||||
await manager.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("begun", [False, True])
|
||||
async def test_queued_cancel_is_idempotent_and_never_admitted(tmp_path, begun):
|
||||
manager, _, ctx = setup(tmp_path, max_concurrent_subagents=1)
|
||||
entered = asyncio.Event()
|
||||
calls = []
|
||||
|
||||
async def run(spec):
|
||||
calls.append(spec.initial_messages[-1]["content"])
|
||||
entered.set()
|
||||
await asyncio.Event().wait()
|
||||
|
||||
manager.runner.run = run
|
||||
await spawn(manager, ctx, "occupy")
|
||||
await entered.wait()
|
||||
queued = await spawn(manager, ctx, "queued")
|
||||
accepted = json.loads(await control(manager, ctx, queued, "send", "pending"))
|
||||
if begun:
|
||||
await asyncio.sleep(0)
|
||||
a, b = await asyncio.gather(control(manager, ctx, queued, "cancel"),
|
||||
control(manager, ctx, queued, "cancel"))
|
||||
assert json.loads(a) == json.loads(b)
|
||||
assert json.loads(a)["state"] == "cancelled"
|
||||
assert json.loads(a)["receipts"][accepted["message_id"]] == "undelivered"
|
||||
assert calls == ["occupy"]
|
||||
assert manager.bus.inbound_size == 1
|
||||
await manager.close()
|
||||
assert manager.bus.inbound_size == 1
|
||||
with request_context(ctx):
|
||||
assert is_tool_error_result(await SubagentTool(manager).execute(action="create", task="after close"))
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_real_runner_injects_followup_without_durable_child_session(tmp_path):
|
||||
manager, provider, ctx = setup(tmp_path)
|
||||
entered, release = asyncio.Event(), asyncio.Event()
|
||||
requests = []
|
||||
|
||||
async def chat(**kwargs):
|
||||
requests.append([dict(m) for m in kwargs["messages"]])
|
||||
if len(requests) == 1:
|
||||
entered.set()
|
||||
await release.wait()
|
||||
return LLMResponse(content="answer")
|
||||
|
||||
provider.chat_stream_with_retry = AsyncMock(side_effect=chat)
|
||||
task_id = await spawn(manager, ctx)
|
||||
await entered.wait()
|
||||
ids = [json.loads(await control(manager, ctx, task_id, "send", text))["message_id"]
|
||||
for text in ["first update", "second update"]]
|
||||
release.set()
|
||||
await settled(manager)
|
||||
assert len(requests) == 2
|
||||
user_text = "\n".join(m["content"] for m in requests[-1] if m["role"] == "user")
|
||||
assert user_text.index("first update") < user_text.index("second update")
|
||||
assert json.loads(await control(manager, ctx, task_id))["receipts"] == dict.fromkeys(ids, "delivered")
|
||||
assert not (tmp_path / "sessions").exists()
|
||||
await manager.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_iteration_limit_returns_partial_findings_without_success_notice(tmp_path):
|
||||
manager, provider, ctx = setup(tmp_path, max_iterations=1)
|
||||
(tmp_path / "note.txt").write_text("evidence", encoding="utf-8")
|
||||
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(
|
||||
content="Found the relevant file; verification is still pending.",
|
||||
tool_calls=[ToolCallRequest("read", "read_file", {"path": "note.txt"})],
|
||||
))
|
||||
task_id = await spawn(manager, ctx)
|
||||
await settled(manager)
|
||||
status = json.loads(await control(manager, ctx, task_id))
|
||||
assert status["state"] == "incomplete"
|
||||
assert status["stop_reason"] == "max_iterations"
|
||||
assert status["partial"] is True
|
||||
assert status["result"] == "Found the relevant file; verification is still pending."
|
||||
notice = await manager.bus.consume_inbound()
|
||||
assert "completed successfully" not in notice.content
|
||||
assert notice.metadata["subagent_state"] == "incomplete"
|
||||
assert notice.metadata["subagent_partial"] is True
|
||||
assert notice.metadata["subagent_stop_reason"] == "max_iterations"
|
||||
with request_context(ctx):
|
||||
inline = await SubagentTool(manager).execute("create", task="verify", wait=True)
|
||||
assert is_tool_error_result(inline)
|
||||
assert "max_iterations" in inline
|
||||
assert "verification is still pending" in inline
|
||||
await manager.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("inline", [False, True])
|
||||
async def test_cancel_preserves_completed_iteration_output_and_receipts(tmp_path, inline):
|
||||
manager, provider, ctx = setup(tmp_path)
|
||||
(tmp_path / "note.txt").write_text("evidence", encoding="utf-8")
|
||||
entered = asyncio.Event()
|
||||
calls = 0
|
||||
|
||||
async def chat(**kwargs):
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
if calls == 1:
|
||||
return LLMResponse(content="Found a possible cause; not yet verified.", tool_calls=[
|
||||
ToolCallRequest("read", "read_file", {"path": "note.txt"}),
|
||||
])
|
||||
entered.set()
|
||||
await asyncio.Event().wait()
|
||||
|
||||
provider.chat_stream_with_retry = AsyncMock(side_effect=chat)
|
||||
if inline:
|
||||
execution = asyncio.create_task(manager.run_inline(
|
||||
task="task", session_key=ctx.session_key, runtime=ctx.runtime,
|
||||
))
|
||||
else:
|
||||
task_id = await spawn(manager, ctx)
|
||||
await entered.wait()
|
||||
if inline:
|
||||
task_id = next(iter(manager.statuses_for_session(ctx.session_key)))
|
||||
receipt = json.loads(await control(manager, ctx, task_id, "send", "please verify"))
|
||||
status = json.loads(await control(manager, ctx, task_id, "cancel"))
|
||||
assert status["state"] == "cancelled"
|
||||
assert status["partial"] is True
|
||||
assert status["result"] == "Found a possible cause; not yet verified."
|
||||
assert status["receipts"][receipt["message_id"]] == "undelivered"
|
||||
if inline:
|
||||
result = await execution
|
||||
assert is_tool_error_result(result)
|
||||
assert result == f"Task cancelled.\nPartial result:\n{status['result']}"
|
||||
assert manager.bus.inbound_size == 0
|
||||
else:
|
||||
notice = await manager.bus.consume_inbound()
|
||||
assert status["result"] in notice.content
|
||||
assert notice.metadata["subagent_state"] == "cancelled"
|
||||
await manager.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_empty_final_response_is_a_failure(tmp_path):
|
||||
manager, provider, ctx = setup(tmp_path)
|
||||
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content=""))
|
||||
task_id = await spawn(manager, ctx)
|
||||
await settled(manager)
|
||||
status = json.loads(await control(manager, ctx, task_id))
|
||||
assert status["state"] == "error"
|
||||
assert status["stop_reason"] == "empty_final_response"
|
||||
assert status["error"]
|
||||
notice = await manager.bus.consume_inbound()
|
||||
assert "completed successfully" not in notice.content
|
||||
assert notice.metadata["subagent_state"] == "error"
|
||||
await manager.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_host_without_background_consumer_returns_the_child_result(tmp_path):
|
||||
manager, _, ctx = setup(tmp_path)
|
||||
ctx = RequestContext("cli", "oneshot", session_key="cli:oneshot", runtime=ctx.runtime,
|
||||
can_receive_background_results=False)
|
||||
manager.runner.run = AsyncMock(return_value=AgentRunResult(messages=[], final_content="verified"))
|
||||
with request_context(ctx):
|
||||
result = await SubagentTool(manager).execute("create", task="verify")
|
||||
assert result == "verified"
|
||||
assert manager.get_running_count() == 0
|
||||
assert manager.bus.inbound_size == 0
|
||||
await manager.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_provider_suppressed_cancellation_cannot_execute_returned_tools(tmp_path):
|
||||
manager, provider, ctx = setup(tmp_path)
|
||||
entered = asyncio.Event()
|
||||
|
||||
async def chat(**kwargs):
|
||||
entered.set()
|
||||
try:
|
||||
await asyncio.Event().wait()
|
||||
except asyncio.CancelledError:
|
||||
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||
id="write", name="write_file", arguments={"path": "resurrected.txt", "content": "bad"},
|
||||
)])
|
||||
|
||||
provider.chat_stream_with_retry = AsyncMock(side_effect=chat)
|
||||
task_id = await spawn(manager, ctx)
|
||||
await entered.wait()
|
||||
assert json.loads(await control(manager, ctx, task_id, "cancel"))["state"] == "cancelled"
|
||||
assert provider.chat_stream_with_retry.await_count == 1
|
||||
assert not (tmp_path / "resurrected.txt").exists()
|
||||
assert manager.bus.inbound_size == 1
|
||||
await manager.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("ending", ["done", "error", "cancel"])
|
||||
async def test_real_task_process_cleanup_preserves_sibling_parent_and_work_products(tmp_path, ending):
|
||||
manager, _, ctx = setup(tmp_path)
|
||||
script = tmp_path / "worker.py"
|
||||
script.write_text("import sys\nprint('READY', flush=True)\nfor line in sys.stdin:\n print(line.strip(), flush=True)\n")
|
||||
argv = [sys.executable, "-u", str(script)]
|
||||
command = subprocess.list2cmdline(argv) if os.name == "nt" else shlex.join(argv)
|
||||
kwargs = {"command": command, "yield_time_ms": 100, "timeout": 60}
|
||||
if os.name == "nt":
|
||||
kwargs["shell"] = "cmd"
|
||||
events = {name: asyncio.Event() for name in ["one", "two"]}
|
||||
releases = {name: asyncio.Event() for name in events}
|
||||
exec_ids = {}
|
||||
processes = {}
|
||||
|
||||
async def run(spec):
|
||||
name = spec.initial_messages[-1]["content"]
|
||||
written = await spec.tools.execute("write_file", {"path": f"{name}-output.txt", "content": name})
|
||||
assert not is_tool_error_result(written), written
|
||||
output = await spec.tools.execute("exec", kwargs)
|
||||
assert not is_tool_error_result(output), output
|
||||
exec_ids[name] = re.search(r"session_id: (\w+)", output).group(1)
|
||||
exec_manager = spec.tools.get("exec")._session_manager
|
||||
processes[name] = exec_manager._sessions[exec_ids[name]].process
|
||||
events[name].set()
|
||||
await releases[name].wait()
|
||||
if name == "one" and ending == "error":
|
||||
raise RuntimeError("task failed")
|
||||
return AgentRunResult(messages=[], final_content="finished")
|
||||
|
||||
manager.runner.run = run
|
||||
# The parent's exec manager must not be closed by task cancellation.
|
||||
parent_exec = ExecTool(working_dir=str(tmp_path), session_manager=manager._exec_session_manager)
|
||||
try:
|
||||
with request_context(ctx):
|
||||
output = await parent_exec.execute(**kwargs)
|
||||
parent_id = re.search(r"session_id: (\w+)", output).group(1)
|
||||
one = await spawn(manager, ctx, "one")
|
||||
two = await spawn(manager, ctx, "two")
|
||||
await asyncio.wait_for(asyncio.gather(*(event.wait() for event in events.values())), 15)
|
||||
one_exec_manager = manager._tasks[one].exec_manager
|
||||
if ending == "cancel":
|
||||
await control(manager, ctx, one, "cancel")
|
||||
else:
|
||||
releases["one"].set()
|
||||
await asyncio.gather(manager._running_tasks[one], return_exceptions=True)
|
||||
expected = {"cancel": "cancelled", "error": "error", "done": "done"}[ending]
|
||||
assert json.loads(await control(manager, ctx, one))["state"] == expected
|
||||
assert await asyncio.wait_for(processes["one"].wait(), timeout=5) is not None
|
||||
with pytest.raises(KeyError):
|
||||
await one_exec_manager.write(
|
||||
session_id=exec_ids["one"], chars=None, close_stdin=False, terminate=False,
|
||||
yield_time_ms=0, max_output_chars=1000, owner_session_key=f"subagent:{one}",
|
||||
)
|
||||
for session_id, owner, exec_manager in [
|
||||
(exec_ids["two"], f"subagent:{two}", manager._tasks[two].exec_manager),
|
||||
(parent_id, "owner", manager._exec_session_manager),
|
||||
]:
|
||||
poll = await exec_manager.write(
|
||||
session_id=session_id, chars="SURVIVED\n", close_stdin=False, terminate=False,
|
||||
yield_time_ms=1000, max_output_chars=1000, owner_session_key=owner,
|
||||
)
|
||||
assert not poll.done
|
||||
assert "SURVIVED" in poll.output
|
||||
assert script.exists()
|
||||
assert await manager.cancel_by_session("owner") == 1
|
||||
assert manager.bus.inbound_size == 1 # No cancelled sibling notice on parent stop.
|
||||
parent_poll = await manager._exec_session_manager.write(
|
||||
session_id=parent_id, chars="STILL ALIVE\n", close_stdin=False, terminate=False,
|
||||
yield_time_ms=1000, max_output_chars=1000, owner_session_key="owner",
|
||||
)
|
||||
assert not parent_poll.done and "STILL ALIVE" in parent_poll.output
|
||||
finally:
|
||||
await manager.close()
|
||||
assert script.exists()
|
||||
assert (tmp_path / "one-output.txt").read_text() == "one"
|
||||
assert (tmp_path / "two-output.txt").read_text() == "two"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_terminal_retention_and_active_capacity_are_bounded(tmp_path):
|
||||
manager, _, ctx = setup(tmp_path)
|
||||
manager.MAX_TERMINAL = 2
|
||||
manager.MAX_ACTIVE = 1
|
||||
entered, release = asyncio.Event(), asyncio.Event()
|
||||
|
||||
async def run(spec):
|
||||
entered.set()
|
||||
await release.wait()
|
||||
return AgentRunResult(messages=[], final_content="done")
|
||||
|
||||
manager.runner.run = run
|
||||
first = await spawn(manager, ctx)
|
||||
await entered.wait()
|
||||
with request_context(ctx):
|
||||
assert is_tool_error_result(await SubagentTool(manager).execute(action="create", task="overflow"))
|
||||
release.set()
|
||||
await settled(manager)
|
||||
for _ in range(3):
|
||||
await spawn(manager, ctx)
|
||||
await settled(manager)
|
||||
assert len(manager.runtime_statuses()) == 2
|
||||
assert len(manager.statuses_for_session("owner")) == 2
|
||||
assert is_tool_error_result(await control(manager, ctx, first))
|
||||
await manager.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("shutdown", [False, True])
|
||||
async def test_completion_wins_cancel_race_and_rejects_late_messages(tmp_path, shutdown):
|
||||
manager, _, ctx = setup(tmp_path)
|
||||
manager.runner.run = AsyncMock(return_value=AgentRunResult(messages=[], final_content="finished"))
|
||||
cleaning, release = asyncio.Event(), asyncio.Event()
|
||||
task_id = await spawn(manager, ctx)
|
||||
exec_manager = manager._tasks[task_id].exec_manager
|
||||
cleanup = exec_manager.close_all
|
||||
|
||||
async def gated_cleanup():
|
||||
cleaning.set()
|
||||
await release.wait()
|
||||
return await cleanup()
|
||||
|
||||
exec_manager.close_all = gated_cleanup
|
||||
message_id = json.loads(await control(manager, ctx, task_id, "send", "too late"))["message_id"]
|
||||
await cleaning.wait()
|
||||
assert json.loads(await control(manager, ctx, task_id))["state"] == "stopping"
|
||||
assert is_tool_error_result(await control(manager, ctx, task_id, "send", "rejected"))
|
||||
cancellation = asyncio.create_task(manager.close() if shutdown else control(manager, ctx, task_id, "cancel"))
|
||||
await asyncio.sleep(0)
|
||||
release.set()
|
||||
await cancellation
|
||||
await settled(manager)
|
||||
state = json.loads(await control(manager, ctx, task_id))
|
||||
assert state["state"] == "done"
|
||||
assert state["receipts"][message_id] == "undelivered"
|
||||
assert state["result"] == "finished"
|
||||
assert manager.bus.inbound_size == (0 if shutdown else 1)
|
||||
await manager.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("late_failure", [False, True])
|
||||
async def test_cancel_wins_over_late_execution_result(tmp_path, late_failure):
|
||||
manager, _, ctx = setup(tmp_path)
|
||||
entered, stopping, release = (asyncio.Event() for _ in range(3))
|
||||
|
||||
async def run(spec):
|
||||
entered.set()
|
||||
try:
|
||||
await asyncio.Event().wait()
|
||||
except asyncio.CancelledError:
|
||||
stopping.set()
|
||||
await release.wait()
|
||||
if late_failure:
|
||||
raise RuntimeError("late failure")
|
||||
return AgentRunResult(messages=[], final_content="not success")
|
||||
|
||||
manager.runner.run = run
|
||||
task_id = await spawn(manager, ctx)
|
||||
await entered.wait()
|
||||
message_id = json.loads(await control(manager, ctx, task_id, "send", "pending"))["message_id"]
|
||||
cancelled = asyncio.create_task(control(manager, ctx, task_id, "cancel"))
|
||||
await stopping.wait()
|
||||
assert is_tool_error_result(await control(manager, ctx, task_id, "send", "late"))
|
||||
release.set()
|
||||
state = json.loads(await cancelled)
|
||||
assert state["state"] == "cancelled"
|
||||
assert state["receipts"][message_id] == "undelivered"
|
||||
assert state["result"] == "Task cancelled."
|
||||
assert json.loads(await control(manager, ctx, task_id, "cancel")) == state
|
||||
assert manager.bus.inbound_size == 1
|
||||
await manager.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_inline_caller_cancel_closes_child_without_notice(tmp_path):
|
||||
manager, _, ctx = setup(tmp_path)
|
||||
entered = asyncio.Event()
|
||||
|
||||
async def run(spec):
|
||||
entered.set()
|
||||
await asyncio.Event().wait()
|
||||
|
||||
manager.runner.run = run
|
||||
with request_context(ctx):
|
||||
inline = asyncio.create_task(SubagentTool(manager).execute(action="create", task="wait", wait=True))
|
||||
await entered.wait()
|
||||
inline.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await inline
|
||||
assert [s.state for s in manager.statuses_for_session("owner").values()] == ["cancelled"]
|
||||
assert manager.get_running_count() == 0
|
||||
assert manager.bus.inbound_size == 0
|
||||
await manager.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cleanup_failure_survives_status_eviction_and_shutdown_retries(tmp_path):
|
||||
manager, _, ctx = setup(tmp_path)
|
||||
manager.MAX_TERMINAL = 1
|
||||
manager.runner.run = AsyncMock(return_value=AgentRunResult(
|
||||
messages=[], final_content="x" * (manager.max_tool_result_chars + 1),
|
||||
))
|
||||
task_id = await spawn(manager, ctx)
|
||||
exec_manager = manager._tasks[task_id].exec_manager
|
||||
original_cleanup = exec_manager.close_all
|
||||
exec_manager.close_all = AsyncMock(side_effect=RuntimeError("cleanup failed"))
|
||||
message_id = json.loads(await control(manager, ctx, task_id, "send", "pending"))["message_id"]
|
||||
await settled(manager)
|
||||
state = json.loads(await control(manager, ctx, task_id))
|
||||
assert state["state"] == "error"
|
||||
assert "cleanup failed" in state["error"]
|
||||
assert state["receipts"][message_id] == "undelivered"
|
||||
assert json.loads(await control(manager, ctx, task_id, "cancel")) == state
|
||||
exec_manager.close_all.assert_awaited_once()
|
||||
assert manager.bus.inbound_size == 1
|
||||
assert task_id in manager._tasks
|
||||
assert len(manager._tasks[task_id].outcome.result) == manager.max_tool_result_chars
|
||||
newer = await spawn(manager, ctx)
|
||||
await settled(manager)
|
||||
assert json.loads(await control(manager, ctx, newer))["state"] == "done"
|
||||
assert is_tool_error_result(await control(manager, ctx, task_id, "cancel"))
|
||||
manager.MAX_ACTIVE = 1
|
||||
with request_context(ctx):
|
||||
assert is_tool_error_result(await SubagentTool(manager).execute(action="create", task="over capacity"))
|
||||
exec_manager.close_all = original_cleanup
|
||||
await manager.close()
|
||||
assert not manager._tasks
|
||||
assert list(manager.runtime_statuses()) == [newer]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tool_suppressed_cancellation_cannot_start_next_tool(tmp_path):
|
||||
manager, provider, ctx = setup(tmp_path)
|
||||
entered = asyncio.Event()
|
||||
calls = []
|
||||
|
||||
class PauseTool(Tool):
|
||||
name = "pause"
|
||||
description = "Wait for a signal."
|
||||
parameters = {"type": "object", "properties": {}}
|
||||
|
||||
async def execute(self, **kwargs):
|
||||
calls.append("pause")
|
||||
entered.set()
|
||||
try:
|
||||
await asyncio.Event().wait()
|
||||
except asyncio.CancelledError:
|
||||
return "suppressed"
|
||||
|
||||
registry = ToolRegistry()
|
||||
registry.register(PauseTool())
|
||||
manager._build_tools = lambda **kwargs: registry
|
||||
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(
|
||||
content=None,
|
||||
tool_calls=[ToolCallRequest(id=str(i), name="pause", arguments={}) for i in range(2)],
|
||||
))
|
||||
task_id = await spawn(manager, ctx)
|
||||
await entered.wait()
|
||||
assert json.loads(await control(manager, ctx, task_id, "cancel"))["state"] == "cancelled"
|
||||
assert calls == ["pause"]
|
||||
assert provider.chat_stream_with_retry.await_count == 1
|
||||
await manager.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_long_running_task_receipts_survive_newer_task_retention(tmp_path):
|
||||
manager, _, ctx = setup(tmp_path)
|
||||
manager.MAX_TERMINAL = 1
|
||||
entered, release = asyncio.Event(), asyncio.Event()
|
||||
|
||||
async def run(spec):
|
||||
if spec.initial_messages[-1]["content"] == "old":
|
||||
entered.set()
|
||||
await release.wait()
|
||||
return AgentRunResult(messages=[], final_content="done")
|
||||
|
||||
manager.runner.run = run
|
||||
old = await spawn(manager, ctx, "old")
|
||||
await entered.wait()
|
||||
message_id = json.loads(await control(manager, ctx, old, "send", "pending"))["message_id"]
|
||||
newer = await spawn(manager, ctx, "new")
|
||||
await manager._running_tasks[newer]
|
||||
release.set()
|
||||
await settled(manager)
|
||||
assert is_tool_error_result(await control(manager, ctx, newer))
|
||||
assert json.loads(await control(manager, ctx, old))["receipts"][message_id] == "undelivered"
|
||||
await manager.bus.consume_inbound()
|
||||
notice = await manager.bus.consume_inbound()
|
||||
assert notice.metadata["subagent_task_id"] == old
|
||||
assert notice.metadata["subagent_message_receipts"] == {message_id: "undelivered"}
|
||||
await manager.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("operation", ["cancel", "session", "close", "inline"])
|
||||
async def test_resistant_dependency_has_bounded_stop_and_no_late_result(tmp_path, operation):
|
||||
manager, provider, ctx = setup(tmp_path, max_concurrent_subagents=1)
|
||||
manager.CANCEL_WAIT_SECONDS = 0.02
|
||||
entered, cancelled, release = (asyncio.Event() for _ in range(3))
|
||||
|
||||
async def chat(**kwargs):
|
||||
entered.set()
|
||||
try:
|
||||
await asyncio.Event().wait()
|
||||
except asyncio.CancelledError:
|
||||
cancelled.set()
|
||||
await release.wait()
|
||||
return LLMResponse(content="must not publish", tool_calls=[ToolCallRequest(
|
||||
id="late", name="write_file", arguments={"path": "late.txt", "content": "bad"},
|
||||
)])
|
||||
|
||||
provider.chat_stream_with_retry = AsyncMock(side_effect=chat)
|
||||
inline = None
|
||||
if operation == "inline":
|
||||
with request_context(ctx):
|
||||
inline = asyncio.create_task(SubagentTool(manager).execute(action="create", task="wait", wait=True))
|
||||
await entered.wait()
|
||||
task_id = next(iter(manager.statuses_for_session("owner")))
|
||||
else:
|
||||
task_id = await spawn(manager, ctx)
|
||||
await entered.wait()
|
||||
record = manager._tasks[task_id]
|
||||
status = record.status
|
||||
try:
|
||||
if operation == "cancel":
|
||||
result = await asyncio.wait_for(control(manager, ctx, task_id, "cancel"), 1)
|
||||
assert json.loads(result)["state"] == "stopping"
|
||||
elif operation == "session":
|
||||
assert await asyncio.wait_for(manager.cancel_by_session("owner"), 1) == 1
|
||||
elif operation == "close":
|
||||
await asyncio.wait_for(manager.close(), 1)
|
||||
else:
|
||||
inline.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await asyncio.wait_for(inline, 1)
|
||||
assert cancelled.is_set()
|
||||
assert status.state == "stopping"
|
||||
assert manager.get_running_count() == 1
|
||||
assert manager._run_slots.locked()
|
||||
assert record.cleanup_task.done()
|
||||
assert record.exec_manager._closed
|
||||
assert is_tool_error_result(await control(manager, ctx, task_id, "send", "rejected"))
|
||||
# Repeated cancel is bounded and must not interrupt the resistant coroutine.
|
||||
assert json.loads(await control(manager, ctx, task_id, "cancel"))["state"] == "stopping"
|
||||
assert manager.bus.inbound_size == 0
|
||||
finally:
|
||||
release.set()
|
||||
await asyncio.wait_for(settled(manager), 2)
|
||||
await manager.close()
|
||||
assert status.state == "cancelled"
|
||||
assert not (tmp_path / "late.txt").exists()
|
||||
assert provider.chat_stream_with_retry.await_count == 1
|
||||
assert manager.get_running_count() == 0
|
||||
assert manager.bus.inbound_size == (1 if operation == "cancel" else 0)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_targeted_inline_cancel_does_not_cancel_waiting_parent(tmp_path):
|
||||
manager, _, ctx = setup(tmp_path)
|
||||
entered = asyncio.Event()
|
||||
|
||||
async def run(spec):
|
||||
entered.set()
|
||||
await asyncio.Event().wait()
|
||||
|
||||
manager.runner.run = run
|
||||
with request_context(ctx):
|
||||
parent = asyncio.create_task(SubagentTool(manager).execute(action="create", task="wait", wait=True))
|
||||
await entered.wait()
|
||||
task_id = next(iter(manager.statuses_for_session("owner")))
|
||||
await control(manager, ctx, task_id, "cancel")
|
||||
assert is_tool_error_result(await parent)
|
||||
assert not parent.cancelled()
|
||||
assert manager.bus.inbound_size == 0
|
||||
await manager.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cleanup_wait_is_bounded_and_repeated_cancel_does_not_interrupt_it(tmp_path):
|
||||
manager, _, ctx = setup(tmp_path)
|
||||
manager.CANCEL_WAIT_SECONDS = 0.02
|
||||
manager.runner.run = AsyncMock(return_value=AgentRunResult(messages=[], final_content="done"))
|
||||
cleaning, release = asyncio.Event(), asyncio.Event()
|
||||
task_id = await spawn(manager, ctx)
|
||||
record = manager._tasks[task_id]
|
||||
status = record.status
|
||||
original = record.exec_manager.close_all
|
||||
|
||||
async def cleanup():
|
||||
cleaning.set()
|
||||
await release.wait()
|
||||
return await original()
|
||||
|
||||
record.exec_manager.close_all = cleanup
|
||||
await cleaning.wait()
|
||||
try:
|
||||
assert json.loads(await asyncio.wait_for(control(manager, ctx, task_id, "cancel"), 1))["state"] == "stopping"
|
||||
await asyncio.wait_for(manager.close(), 1)
|
||||
assert status.state == "stopping"
|
||||
assert manager.get_running_count() == 1
|
||||
assert not record.cleanup_task.done()
|
||||
finally:
|
||||
release.set()
|
||||
await asyncio.wait_for(settled(manager), 2)
|
||||
assert status.state == "done"
|
||||
assert manager.bus.inbound_size == 0
|
||||
|
||||
|
||||
def test_subagent_schema_exposes_task_actions(tmp_path):
|
||||
manager, _, _ = setup(tmp_path)
|
||||
properties = SubagentTool(manager).parameters["properties"]
|
||||
assert properties["action"]["enum"] == ["create", "send", "cancel", "check"]
|
||||
assert "owner" not in properties
|
||||
tool = SubagentTool(manager)
|
||||
assert tool.validate_params({"action": "create", "task": "review"}) == []
|
||||
assert tool.validate_params({"action": "check"}) == []
|
||||
assert tool.validate_params({"action": "send", "task_id": "task", "message": "update"}) == []
|
||||
assert tool.validate_params({"action": "cancel", "task_id": "task"}) == []
|
||||
@@ -70,8 +70,16 @@ async def _drain_subagent_tasks(sm: SubagentManager) -> None:
|
||||
@pytest.mark.asyncio
|
||||
async def test_close_cancels_tasks_before_closing_exec_sessions(tmp_path):
|
||||
sm = _manager(tmp_path)
|
||||
task = asyncio.create_task(asyncio.Event().wait())
|
||||
sm._running_tasks["t1"] = task
|
||||
entered = asyncio.Event()
|
||||
|
||||
async def run(spec):
|
||||
entered.set()
|
||||
await asyncio.Event().wait()
|
||||
|
||||
sm.runner.run = run
|
||||
await sm.spawn("task", runtime=_runtime())
|
||||
task = next(iter(sm._running_tasks.values()))
|
||||
await entered.wait()
|
||||
|
||||
async def close_exec_sessions() -> int:
|
||||
assert task.done()
|
||||
@@ -96,7 +104,8 @@ class TestSubagentStatus:
|
||||
task_id="abc", label="test", task_description="do stuff",
|
||||
started_at=time.monotonic(),
|
||||
)
|
||||
assert s.phase == "initializing"
|
||||
assert s.phase == "queued"
|
||||
assert s.state == "queued"
|
||||
assert s.iteration == 0
|
||||
assert s.tool_events == []
|
||||
assert s.usage is None
|
||||
@@ -214,14 +223,13 @@ class TestSpawn:
|
||||
sm.runner.run = AsyncMock(return_value=AgentRunResult(
|
||||
final_content="done", messages=[], stop_reason="completed",
|
||||
))
|
||||
statuses = sm.runtime_statuses()
|
||||
assert not statuses
|
||||
assert not sm.runtime_statuses()
|
||||
await sm.spawn("my task", runtime=_runtime())
|
||||
statuses = sm.runtime_statuses()
|
||||
assert len(statuses) == 1
|
||||
assert next(iter(statuses.values())).task_description == "my task"
|
||||
await _drain_subagent_tasks(sm)
|
||||
# Status cleaned up after task completes
|
||||
assert not statuses
|
||||
assert [s.state for s in sm.statuses_for_session("cli:direct").values()] == ["done"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_registers_in_session_tasks(self, tmp_path):
|
||||
@@ -233,15 +241,14 @@ class TestSpawn:
|
||||
sm.runner.run = _slow_run
|
||||
|
||||
await sm.spawn("task", runtime=_runtime(), session_key="s1")
|
||||
assert "s1" in sm._session_tasks
|
||||
assert len(sm._session_tasks["s1"]) == 1
|
||||
assert len(sm.statuses_for_session("s1")) == 1
|
||||
|
||||
block.set()
|
||||
await _drain_subagent_tasks(sm)
|
||||
assert "s1" not in sm._session_tasks
|
||||
assert [s.state for s in sm.statuses_for_session("s1").values()] == ["done"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_session_key_no_registration(self, tmp_path):
|
||||
async def test_no_session_key_registers_channel_chat_owner(self, tmp_path):
|
||||
sm = _manager(tmp_path)
|
||||
block = asyncio.Event()
|
||||
async def _slow_run(spec):
|
||||
@@ -250,7 +257,7 @@ class TestSpawn:
|
||||
sm.runner.run = _slow_run
|
||||
|
||||
await sm.spawn("task", runtime=_runtime())
|
||||
assert len(sm._session_tasks) == 0
|
||||
assert len(sm.statuses_for_session("cli:direct")) == 1
|
||||
|
||||
block.set()
|
||||
await _drain_subagent_tasks(sm)
|
||||
@@ -266,7 +273,7 @@ class TestSpawn:
|
||||
|
||||
long_label_source = "A" * 50
|
||||
await sm.spawn(long_label_source, runtime=_runtime(), session_key="s1")
|
||||
status = next(iter(sm._task_statuses.values()))
|
||||
status = next(iter(sm.runtime_statuses().values()))
|
||||
assert status.label == long_label_source[:30] + "..."
|
||||
|
||||
block.set()
|
||||
@@ -284,14 +291,14 @@ class TestSpawn:
|
||||
await sm.spawn(
|
||||
"task", runtime=_runtime(), label="Custom Label", session_key="s1"
|
||||
)
|
||||
status = next(iter(sm._task_statuses.values()))
|
||||
status = next(iter(sm.runtime_statuses().values()))
|
||||
assert status.label == "Custom Label"
|
||||
|
||||
block.set()
|
||||
await _drain_subagent_tasks(sm)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cleanup_callback_removes_all_entries(self, tmp_path):
|
||||
async def test_cleanup_callback_retains_terminal_status(self, tmp_path):
|
||||
sm = _manager(tmp_path)
|
||||
sm.runner.run = AsyncMock(return_value=AgentRunResult(
|
||||
final_content="done", messages=[], stop_reason="completed",
|
||||
@@ -299,8 +306,7 @@ class TestSpawn:
|
||||
await sm.spawn("task", runtime=_runtime(), session_key="s1")
|
||||
await _drain_subagent_tasks(sm)
|
||||
assert len(sm._running_tasks) == 0
|
||||
assert len(sm._task_statuses) == 0
|
||||
assert len(sm._session_tasks) == 0
|
||||
assert [s.state for s in sm.statuses_for_session("s1").values()] == ["done"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_runtime_is_captured_before_background_task_starts(self, tmp_path):
|
||||
@@ -351,12 +357,14 @@ class TestRunSubagent:
|
||||
final_content="Task done!", messages=[], stop_reason="completed",
|
||||
))
|
||||
with patch.object(sm, "_announce_result", new_callable=AsyncMock) as mock_announce:
|
||||
await sm._run_subagent(
|
||||
"t1", "do task", "label",
|
||||
{"channel": "cli", "chat_id": "direct"},
|
||||
SubagentStatus(task_id="t1", label="label", task_description="do task", started_at=time.monotonic()),
|
||||
_runtime(),
|
||||
await sm.spawn(
|
||||
task="do task",
|
||||
label="label",
|
||||
origin_channel="cli",
|
||||
origin_chat_id="direct",
|
||||
runtime=_runtime(),
|
||||
)
|
||||
await asyncio.gather(*sm._running_tasks.values(), return_exceptions=True)
|
||||
mock_announce.assert_called_once()
|
||||
assert mock_announce.call_args.args[-2] == "ok"
|
||||
|
||||
@@ -364,12 +372,16 @@ class TestRunSubagent:
|
||||
async def test_exception_run(self, tmp_path):
|
||||
sm = _manager(tmp_path)
|
||||
sm.runner.run = AsyncMock(side_effect=RuntimeError("LLM down"))
|
||||
status = SubagentStatus(task_id="t1", label="label", task_description="do task", started_at=time.monotonic())
|
||||
with patch.object(sm, "_announce_result", new_callable=AsyncMock) as mock_announce:
|
||||
await sm._run_subagent(
|
||||
"t1", "do task", "label",
|
||||
{"channel": "cli", "chat_id": "direct"}, status, _runtime(),
|
||||
await sm.spawn(
|
||||
task="do task",
|
||||
label="label",
|
||||
origin_channel="cli",
|
||||
origin_chat_id="direct",
|
||||
runtime=_runtime(),
|
||||
)
|
||||
await asyncio.gather(*sm._running_tasks.values(), return_exceptions=True)
|
||||
status = next(iter(sm.runtime_statuses().values()))
|
||||
assert status.phase == "error"
|
||||
assert "LLM down" in status.error
|
||||
assert mock_announce.call_args.args[-2] == "error"
|
||||
@@ -380,12 +392,16 @@ class TestRunSubagent:
|
||||
sm.runner.run = AsyncMock(return_value=AgentRunResult(
|
||||
final_content="ok", messages=[], stop_reason="completed",
|
||||
))
|
||||
status = SubagentStatus(task_id="t1", label="label", task_description="do task", started_at=time.monotonic())
|
||||
with patch.object(sm, "_announce_result", new_callable=AsyncMock):
|
||||
await sm._run_subagent(
|
||||
"t1", "do task", "label",
|
||||
{"channel": "cli", "chat_id": "direct"}, status, _runtime(),
|
||||
await sm.spawn(
|
||||
task="do task",
|
||||
label="label",
|
||||
origin_channel="cli",
|
||||
origin_chat_id="direct",
|
||||
runtime=_runtime(),
|
||||
)
|
||||
await asyncio.gather(*sm._running_tasks.values(), return_exceptions=True)
|
||||
status = next(iter(sm.runtime_statuses().values()))
|
||||
assert status.phase == "done"
|
||||
assert status.stop_reason == "completed"
|
||||
|
||||
@@ -499,7 +515,7 @@ class TestCancelBySession:
|
||||
runtime = _runtime()
|
||||
await sm.spawn("task1", runtime=runtime, session_key="s1")
|
||||
await sm.spawn("task2", runtime=runtime, session_key="s1")
|
||||
assert len(sm._session_tasks.get("s1", set())) == 2
|
||||
assert len(sm.statuses_for_session("s1")) == 2
|
||||
|
||||
count = await sm.cancel_by_session("s1")
|
||||
assert count == 2
|
||||
@@ -539,7 +555,7 @@ class TestCancelBySession:
|
||||
|
||||
assert not queued_entered.is_set()
|
||||
assert sm._running_tasks == {}
|
||||
assert sm._session_tasks == {}
|
||||
assert [s.state for s in sm.statuses_for_session("s1").values()] == ["cancelled", "cancelled"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_already_done_not_counted(self, tmp_path):
|
||||
@@ -597,8 +613,8 @@ class TestRunningCounts:
|
||||
|
||||
class TestSubagentHook:
|
||||
@pytest.mark.asyncio
|
||||
async def test_before_execute_tools_logs(self, tmp_path):
|
||||
hook = _SubagentHook("t1")
|
||||
async def test_before_execute_tools_without_status_preserves_calls(self):
|
||||
hook = _SubagentHook()
|
||||
tool_call = MagicMock()
|
||||
tool_call.name = "read_file"
|
||||
tool_call.arguments = {"path": "/tmp/test"}
|
||||
@@ -612,7 +628,7 @@ class TestSubagentHook:
|
||||
status = SubagentStatus(
|
||||
task_id="t1", label="test", task_description="do", started_at=time.monotonic(),
|
||||
)
|
||||
hook = _SubagentHook("t1", status)
|
||||
hook = _SubagentHook(status)
|
||||
ctx = _make_hook_context(
|
||||
iteration=3,
|
||||
tool_events=[{"name": "read_file", "status": "ok", "detail": ""}],
|
||||
@@ -625,7 +641,7 @@ class TestSubagentHook:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_after_iteration_no_status_noop(self):
|
||||
hook = _SubagentHook("t1", status=None)
|
||||
hook = _SubagentHook()
|
||||
ctx = _make_hook_context(iteration=5)
|
||||
result = await hook.after_iteration(ctx)
|
||||
assert result is None
|
||||
@@ -636,7 +652,7 @@ class TestSubagentHook:
|
||||
status = SubagentStatus(
|
||||
task_id="t1", label="test", task_description="do", started_at=time.monotonic(),
|
||||
)
|
||||
hook = _SubagentHook("t1", status)
|
||||
hook = _SubagentHook(status)
|
||||
ctx = _make_hook_context(error="something broke")
|
||||
await hook.after_iteration(ctx)
|
||||
assert status.error == "something broke"
|
||||
@@ -3,7 +3,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
@@ -455,7 +454,7 @@ class TestDispatch:
|
||||
|
||||
class TestSubagentCancellation:
|
||||
@pytest.mark.asyncio
|
||||
async def test_cancel_by_session(self):
|
||||
async def test_cancel_by_session(self, tmp_path):
|
||||
from nanobot.agent.subagent import SubagentManager
|
||||
from nanobot.bus.queue import MessageBus
|
||||
|
||||
@@ -468,18 +467,20 @@ class TestSubagentCancellation:
|
||||
)
|
||||
|
||||
cancelled = asyncio.Event()
|
||||
started = asyncio.Event()
|
||||
mgr.workspace = tmp_path
|
||||
|
||||
async def slow():
|
||||
async def slow(spec):
|
||||
started.set()
|
||||
try:
|
||||
await asyncio.sleep(60)
|
||||
except asyncio.CancelledError:
|
||||
cancelled.set()
|
||||
raise
|
||||
|
||||
task = asyncio.create_task(slow())
|
||||
await asyncio.sleep(0)
|
||||
mgr._running_tasks["sub-1"] = task
|
||||
mgr._session_tasks["test:c1"] = {"sub-1"}
|
||||
mgr.runner.run = slow
|
||||
await mgr.spawn("task", runtime=_runtime(MagicMock()), session_key="test:c1")
|
||||
await started.wait()
|
||||
|
||||
count = await mgr.cancel_by_session("test:c1")
|
||||
assert count == 1
|
||||
@@ -500,7 +501,7 @@ class TestSubagentCancellation:
|
||||
assert await mgr.cancel_by_session("nonexistent") == 0
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cancel_by_session_terminates_exec_sessions(self):
|
||||
async def test_cancel_by_session_does_not_terminate_parent_exec_sessions(self):
|
||||
from nanobot.agent.subagent import SubagentManager
|
||||
from nanobot.agent.tools.exec_session import ExecSessionManager
|
||||
from nanobot.bus.queue import MessageBus
|
||||
@@ -519,7 +520,7 @@ class TestSubagentCancellation:
|
||||
|
||||
await mgr.cancel_by_session("test:c1")
|
||||
|
||||
mock_exec_mgr.terminate_by_owner.assert_awaited_once_with("test:c1")
|
||||
mock_exec_mgr.terminate_by_owner.assert_not_awaited()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_subagent_preserves_reasoning_fields_in_tool_turn(self, monkeypatch, tmp_path):
|
||||
@@ -559,16 +560,14 @@ class TestSubagentCancellation:
|
||||
|
||||
monkeypatch.setattr("nanobot.agent.tools.filesystem.ListDirTool.execute", fake_execute)
|
||||
|
||||
from nanobot.agent.subagent import SubagentStatus
|
||||
status = SubagentStatus(task_id="sub-1", label="label", task_description="do task", started_at=time.monotonic())
|
||||
await mgr._run_subagent(
|
||||
"sub-1",
|
||||
"do task",
|
||||
"label",
|
||||
{"channel": "test", "chat_id": "c1"},
|
||||
status,
|
||||
_runtime(provider),
|
||||
await mgr.spawn(
|
||||
task="do task",
|
||||
label="label",
|
||||
origin_channel="test",
|
||||
origin_chat_id="c1",
|
||||
runtime=_runtime(provider),
|
||||
)
|
||||
await asyncio.gather(*mgr._running_tasks.values(), return_exceptions=True)
|
||||
|
||||
assistant_messages = [
|
||||
msg for msg in captured_second_call
|
||||
@@ -608,16 +607,14 @@ class TestSubagentCancellation:
|
||||
|
||||
mgr.runner.run = AsyncMock(side_effect=fake_run)
|
||||
|
||||
from nanobot.agent.subagent import SubagentStatus
|
||||
status = SubagentStatus(task_id="sub-1", label="label", task_description="do task", started_at=time.monotonic())
|
||||
await mgr._run_subagent(
|
||||
"sub-1",
|
||||
"do task",
|
||||
"label",
|
||||
{"channel": "test", "chat_id": "c1"},
|
||||
status,
|
||||
_runtime(provider),
|
||||
await mgr.spawn(
|
||||
task="do task",
|
||||
label="label",
|
||||
origin_channel="test",
|
||||
origin_chat_id="c1",
|
||||
runtime=_runtime(provider),
|
||||
)
|
||||
await asyncio.gather(*mgr._running_tasks.values(), return_exceptions=True)
|
||||
|
||||
mgr.runner.run.assert_awaited_once()
|
||||
mgr._announce_result.assert_awaited_once()
|
||||
@@ -666,16 +663,14 @@ class TestSubagentCancellation:
|
||||
|
||||
monkeypatch.setattr("nanobot.agent.tools.filesystem.ListDirTool.execute", fake_execute)
|
||||
|
||||
from nanobot.agent.subagent import SubagentStatus
|
||||
status = SubagentStatus(task_id="sub-1", label="label", task_description="do task", started_at=time.monotonic())
|
||||
await mgr._run_subagent(
|
||||
"sub-1",
|
||||
"do task",
|
||||
"label",
|
||||
{"channel": "test", "chat_id": "c1"},
|
||||
status,
|
||||
_runtime(provider),
|
||||
await mgr.spawn(
|
||||
task="do task",
|
||||
label="label",
|
||||
origin_channel="test",
|
||||
origin_chat_id="c1",
|
||||
runtime=_runtime(provider),
|
||||
)
|
||||
await asyncio.gather(*mgr._running_tasks.values(), return_exceptions=True)
|
||||
|
||||
mgr._announce_result.assert_awaited_once()
|
||||
args = mgr._announce_result.await_args.args
|
||||
@@ -686,7 +681,7 @@ class TestSubagentCancellation:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cancel_by_session_cancels_running_subagent_tool(self, monkeypatch, tmp_path):
|
||||
from nanobot.agent.subagent import SubagentManager, SubagentStatus
|
||||
from nanobot.agent.subagent import SubagentManager
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.providers.base import LLMResponse, ToolCallRequest
|
||||
|
||||
@@ -718,15 +713,8 @@ class TestSubagentCancellation:
|
||||
|
||||
monkeypatch.setattr("nanobot.agent.tools.filesystem.ListDirTool.execute", fake_execute)
|
||||
|
||||
task = asyncio.create_task(
|
||||
mgr._run_subagent(
|
||||
"sub-1", "do task", "label", {"channel": "test", "chat_id": "c1"},
|
||||
SubagentStatus(task_id="sub-1", label="label", task_description="do task", started_at=time.monotonic()),
|
||||
_runtime(provider),
|
||||
)
|
||||
)
|
||||
mgr._running_tasks["sub-1"] = task
|
||||
mgr._session_tasks["test:c1"] = {"sub-1"}
|
||||
await mgr.spawn("do task", label="label", runtime=_runtime(provider), session_key="test:c1")
|
||||
task = next(iter(mgr._running_tasks.values()))
|
||||
|
||||
await asyncio.wait_for(started.wait(), timeout=1.0)
|
||||
|
||||
@@ -794,9 +782,8 @@ class TestSubagentAnnounceSessionKey:
|
||||
assert msg.chat_id == "discord:333"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_session_key_flows_through_run_subagent(self):
|
||||
"""Verify session_key in origin propagates from _run_subagent to _announce_result."""
|
||||
from nanobot.agent.subagent import SubagentStatus
|
||||
async def test_spawn_routes_result_to_parent_session(self):
|
||||
"""Background results return to the parent's canonical session."""
|
||||
|
||||
mgr, bus = self._make_mgr()
|
||||
|
||||
@@ -810,16 +797,15 @@ class TestSubagentAnnounceSessionKey:
|
||||
|
||||
mgr.runner.run = AsyncMock(side_effect=fake_run)
|
||||
|
||||
status = SubagentStatus(
|
||||
task_id="sub-4", label="label", task_description="task",
|
||||
started_at=time.monotonic(),
|
||||
)
|
||||
await mgr._run_subagent(
|
||||
"sub-4", "task", "label",
|
||||
{"channel": "telegram", "chat_id": "444", "session_key": UNIFIED_SESSION_KEY},
|
||||
status,
|
||||
_runtime(),
|
||||
await mgr.spawn(
|
||||
task="task",
|
||||
label="label",
|
||||
origin_channel="telegram",
|
||||
origin_chat_id="444",
|
||||
runtime=_runtime(),
|
||||
session_key=UNIFIED_SESSION_KEY,
|
||||
)
|
||||
await asyncio.gather(*mgr._running_tasks.values(), return_exceptions=True)
|
||||
|
||||
msg = await bus.consume_inbound()
|
||||
assert msg.session_key_override == UNIFIED_SESSION_KEY
|
||||
@@ -16,7 +16,7 @@ from nanobot.agent.tools.image_generation import ImageGenerationError, ImageGene
|
||||
from nanobot.agent.tools.message import MessageTool
|
||||
from nanobot.agent.tools.search import GrepTool
|
||||
from nanobot.agent.tools.shell import ExecTool
|
||||
from nanobot.agent.tools.spawn import SpawnTool
|
||||
from nanobot.agent.tools.subagent import SubagentTool
|
||||
from nanobot.apps.cli.service import CliAppManager, CliAppsRuntimeConfig
|
||||
from nanobot.config.schema import ImageGenerationToolConfig, ProviderConfig, ToolsConfig
|
||||
from nanobot.security.workspace_access import (
|
||||
@@ -532,7 +532,7 @@ async def test_cli_app_scope_controls_working_dir(
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_spawn_tool_forwards_current_workspace_scope(tmp_path: Path) -> None:
|
||||
async def test_subagent_tool_forwards_current_workspace_scope(tmp_path: Path) -> None:
|
||||
project = tmp_path / "project"
|
||||
project.mkdir()
|
||||
scope = validate_workspace_scope_payload(
|
||||
@@ -555,7 +555,7 @@ async def test_spawn_tool_forwards_current_workspace_scope(tmp_path: Path) -> No
|
||||
return "spawned"
|
||||
|
||||
manager = Manager()
|
||||
tool = SpawnTool(manager) # type: ignore[arg-type]
|
||||
tool = SubagentTool(manager) # type: ignore[arg-type]
|
||||
token = bind_workspace_scope(scope)
|
||||
try:
|
||||
with request_context(RequestContext(
|
||||
@@ -563,7 +563,7 @@ async def test_spawn_tool_forwards_current_workspace_scope(tmp_path: Path) -> No
|
||||
chat_id="chat",
|
||||
runtime=MagicMock(),
|
||||
)):
|
||||
result = await tool.execute(task="inspect")
|
||||
result = await tool.execute(action="create", task="inspect")
|
||||
finally:
|
||||
reset_workspace_scope(token)
|
||||
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
@@ -71,7 +73,6 @@ def test_runtime_snapshot_has_exact_allowlist_and_redacts_secrets(tmp_path: Path
|
||||
"tool_names",
|
||||
"web_config",
|
||||
"exec_config",
|
||||
"subagents",
|
||||
})
|
||||
assert RUNTIME_SNAPSHOT_KEYS == expected_snapshot_keys
|
||||
assert frozenset(values) == expected_snapshot_keys
|
||||
@@ -247,64 +248,117 @@ def runtime() -> LLMRuntime:
|
||||
return LLMRuntime(MagicMock(), "test", GenerationSettings(), 128_000)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key", [None, "subagents", "subagents._task_statuses"])
|
||||
async def test_my_subagent_snapshot_is_session_scoped(tmp_path, key, runtime):
|
||||
@pytest.mark.parametrize("params", [
|
||||
{"action": "create"},
|
||||
{"action": "create", "task": " "},
|
||||
{"action": "send", "message": "update"},
|
||||
{"action": "cancel"},
|
||||
])
|
||||
async def test_subagent_rejects_missing_action_inputs(tmp_path, runtime, params):
|
||||
loop = _make_loop(tmp_path)
|
||||
with request_context(RequestContext("test", "route", session_key="owner", runtime=runtime)):
|
||||
result = await loop.tools.execute("subagent", params)
|
||||
assert result.startswith("Error:")
|
||||
assert loop.subagents.get_running_count() == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("single_task", [False, True])
|
||||
async def test_subagent_check_is_session_scoped(tmp_path, single_task, runtime):
|
||||
loop = _make_loop(tmp_path)
|
||||
manager = loop.subagents
|
||||
# Spawn without yielding to the child runner: queued tasks must be scoped too.
|
||||
# Queued tasks must be scoped before their runner starts.
|
||||
await manager.spawn("ALPHA_PRIVATE_TASK", label="ALPHA_LABEL", session_key="owner:a", runtime=runtime)
|
||||
await manager.spawn("BETA_PRIVATE_TASK", label="BETA_LABEL", session_key="owner:b", runtime=runtime)
|
||||
try:
|
||||
tool = _my_tool(loop)
|
||||
with request_context(RequestContext("test", "same-chat", session_key="owner:a")):
|
||||
snapshot = tool._runtime_control.snapshot()
|
||||
assert len(snapshot.subagent_statuses) == 1
|
||||
assert "BETA" not in repr(snapshot.as_mapping())
|
||||
result = await tool.execute(action="check", key=key)
|
||||
assert "ALPHA_LABEL" in result
|
||||
assert "BETA" not in result
|
||||
with request_context(RequestContext("test", "same-chat", session_key="owner:b")):
|
||||
result = await tool.execute(action="check", key=key)
|
||||
assert "BETA_LABEL" in result
|
||||
assert "ALPHA" not in result
|
||||
for owner, visible, hidden in [("owner:a", "ALPHA", "BETA"), ("owner:b", "BETA", "ALPHA")]:
|
||||
with request_context(RequestContext("test", "same-chat", session_key=owner)):
|
||||
params = {"action": "check"}
|
||||
if single_task:
|
||||
params["task_id"] = next(iter(manager.statuses_for_session(owner)))
|
||||
result = await loop.tools.execute("subagent", params)
|
||||
assert visible + "_LABEL" in result
|
||||
assert visible + "_PRIVATE_TASK" in result
|
||||
assert hidden not in result
|
||||
assert "queued" in result
|
||||
overview = await loop.tools.execute("my", {"action": "check"})
|
||||
assert "ALPHA" not in overview and "BETA" not in overview
|
||||
assert "not accessible" in await loop.tools.execute("my", {
|
||||
"action": "check", "key": "subagents",
|
||||
})
|
||||
finally:
|
||||
await manager.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field", ["", ".task_description", ".tool_events", ".usage"])
|
||||
async def test_my_rejects_other_sessions_task_paths(tmp_path, field, runtime):
|
||||
async def test_subagent_check_rejects_foreign_task(tmp_path, runtime):
|
||||
loop = _make_loop(tmp_path)
|
||||
manager = loop.subagents
|
||||
await manager.spawn("PRIVATE_TASK", session_key="owner:a", runtime=runtime)
|
||||
try:
|
||||
task_id = next(iter(manager.statuses_for_session("owner:a")))
|
||||
tool = _my_tool(loop)
|
||||
with request_context(RequestContext("test", "same-chat", session_key="owner:a")):
|
||||
detail = await tool.execute(action="check", key=f"subagents._task_statuses.{task_id}")
|
||||
assert "PRIVATE_TASK" in detail
|
||||
with request_context(RequestContext("test", "same-chat", session_key="owner:b")):
|
||||
result = await tool.execute(
|
||||
action="check", key=f"subagents._task_statuses.{task_id}{field}",
|
||||
)
|
||||
assert result.startswith("Error:")
|
||||
assert "PRIVATE_TASK" not in result
|
||||
result = await loop.tools.execute("subagent", {"action": "check", "task_id": task_id})
|
||||
unknown = await loop.tools.execute("subagent", {"action": "check", "task_id": "unknown"})
|
||||
assert result == unknown
|
||||
assert result.startswith("Error: task unavailable")
|
||||
finally:
|
||||
await manager.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("session_key", [None, ""])
|
||||
async def test_my_without_session_cannot_enumerate_tasks(tmp_path, session_key, runtime):
|
||||
async def test_subagent_check_without_session_cannot_enumerate_tasks(tmp_path, session_key, runtime):
|
||||
loop = _make_loop(tmp_path)
|
||||
manager = loop.subagents
|
||||
await manager.spawn("PRIVATE_TASK", session_key="owner:a", runtime=runtime)
|
||||
try:
|
||||
tool = _my_tool(loop)
|
||||
assert tool._runtime_control.snapshot().subagent_statuses == {}
|
||||
assert "PRIVATE_TASK" not in await tool.execute(action="check")
|
||||
assert "unavailable" in await tool.execute(action="check", key="subagents")
|
||||
task_id = next(iter(manager.statuses_for_session("owner:a")))
|
||||
assert "unavailable" in await loop.tools.execute("subagent", {"action": "check"})
|
||||
with request_context(RequestContext("test", "same-chat", session_key=session_key)):
|
||||
assert tool._runtime_control.snapshot().subagent_statuses == {}
|
||||
assert "PRIVATE_TASK" not in await tool.execute(action="check")
|
||||
assert "unavailable" in await tool.execute(action="check", key="subagents._task_statuses")
|
||||
assert "unavailable" in await loop.tools.execute("subagent", {"action": "check"})
|
||||
assert "unavailable" in await loop.tools.execute("subagent", {
|
||||
"action": "check", "task_id": task_id,
|
||||
})
|
||||
finally:
|
||||
await manager.close()
|
||||
|
||||
|
||||
async def test_subagent_check_retained_results_and_receipts_are_scoped_and_detached(tmp_path, runtime):
|
||||
from nanobot.agent.runner import AgentRunResult
|
||||
|
||||
loop = _make_loop(tmp_path)
|
||||
manager = loop.subagents
|
||||
entered, release = asyncio.Event(), asyncio.Event()
|
||||
|
||||
async def run(spec):
|
||||
entered.set()
|
||||
await release.wait()
|
||||
return AgentRunResult(messages=[], final_content="PRIVATE_RESULT")
|
||||
|
||||
manager.runner.run = run
|
||||
owner = RequestContext("test", "route", session_key="owner:a", runtime=runtime)
|
||||
try:
|
||||
with request_context(owner):
|
||||
await loop.tools.execute("subagent", {"action": "create", "task": "private"})
|
||||
await entered.wait()
|
||||
task_id = next(iter(manager.statuses_for_session("owner:a")))
|
||||
sent = json.loads(await loop.tools.execute("subagent", {
|
||||
"action": "send", "task_id": task_id, "message": "pending",
|
||||
}))
|
||||
release.set()
|
||||
await asyncio.gather(*manager._running_tasks.values())
|
||||
params = {"action": "check", "task_id": task_id}
|
||||
result = json.loads(await loop.tools.execute("subagent", params))
|
||||
assert result["state"] == "done"
|
||||
assert result["result"] == "PRIVATE_RESULT"
|
||||
assert result["receipts"] == {sent["message_id"]: "undelivered"}
|
||||
snapshot = manager.check(task_id, "owner:a")
|
||||
snapshot.receipts.clear()
|
||||
snapshot.result = "tampered"
|
||||
assert json.loads(await loop.tools.execute("subagent", params)) == result
|
||||
listed = json.loads(await loop.tools.execute("subagent", {"action": "check"}))
|
||||
assert listed == {"tasks": [result]}
|
||||
with request_context(RequestContext("test", "route", session_key="owner:b")):
|
||||
assert "unavailable" in await loop.tools.execute("subagent", params)
|
||||
assert json.loads(await loop.tools.execute("subagent", {"action": "check"})) == {"tasks": []}
|
||||
finally:
|
||||
release.set()
|
||||
await manager.close()
|
||||
@@ -40,6 +40,7 @@ def _make_mock_loop(**overrides):
|
||||
loop._unified_session = False
|
||||
loop._extra_hooks = []
|
||||
loop.set_runtime_model.side_effect = lambda value: setattr(loop, "model", value)
|
||||
loop.set_runtime_max_iterations.side_effect = lambda value: setattr(loop, "max_iterations", value)
|
||||
loop.set_runtime_context_window.side_effect = lambda value: setattr(
|
||||
loop,
|
||||
"context_window_tokens",
|
||||
@@ -59,12 +60,6 @@ def _make_mock_loop(**overrides):
|
||||
|
||||
# SubagentManager mock
|
||||
loop.subagents = MagicMock()
|
||||
loop.subagents._running_tasks = {"abc123": MagicMock(done=MagicMock(return_value=False))}
|
||||
loop.subagents._task_statuses = {}
|
||||
loop.subagents.statuses_for_session.side_effect = (
|
||||
lambda key: loop.subagents._task_statuses if key == "test:owner" else {}
|
||||
)
|
||||
loop.subagents.get_running_count = MagicMock(return_value=1)
|
||||
|
||||
for k, v in overrides.items():
|
||||
setattr(loop, k, v)
|
||||
@@ -412,11 +407,11 @@ class TestModifyOpen:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_modify_subagents_blocked(self):
|
||||
"""subagents is READ_ONLY — cannot be replaced."""
|
||||
"""Subagent control is outside the self-inspection capability."""
|
||||
tool = _make_tool()
|
||||
new_subagents = MagicMock()
|
||||
result = await tool.execute(action="set", key="subagents", value=new_subagents)
|
||||
assert "read-only" in result
|
||||
assert "protected" in result
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_modify_runner_blocked(self):
|
||||
@@ -584,78 +579,6 @@ class TestDeniedAttrs:
|
||||
assert "protected" in result, f"{attr} should be blocked"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# SubagentStatus formatting
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestSubagentStatusFormatting:
|
||||
|
||||
def test_format_single_status(self):
|
||||
"""_format_value should produce a rich multi-line display for a SubagentStatus."""
|
||||
from nanobot.agent.subagent import SubagentStatus
|
||||
|
||||
status = SubagentStatus(
|
||||
task_id="abc12345",
|
||||
label="read logs and summarize",
|
||||
task_description="Read the log files and produce a summary",
|
||||
started_at=time.monotonic() - 12.4,
|
||||
phase="awaiting_tools",
|
||||
iteration=3,
|
||||
tool_events=[
|
||||
{"name": "read_file", "status": "ok", "detail": "read app.log"},
|
||||
{"name": "grep", "status": "ok", "detail": "searched ERROR"},
|
||||
{"name": "exec", "status": "error", "detail": "timeout"},
|
||||
],
|
||||
usage=LLMUsage.reported(input_tokens=4500, output_tokens=1200),
|
||||
)
|
||||
result = MyTool._format_value(status)
|
||||
assert "abc12345" in result
|
||||
assert "read logs and summarize" in result
|
||||
assert "awaiting_tools" in result
|
||||
assert "iteration: 3" in result
|
||||
assert "read_file(ok)" in result
|
||||
assert "exec(error)" in result
|
||||
assert "4500" in result
|
||||
|
||||
def test_format_status_dict(self):
|
||||
"""_format_value should handle dict[str, SubagentStatus] with rich display."""
|
||||
from nanobot.agent.subagent import SubagentStatus
|
||||
|
||||
statuses = {
|
||||
"abc12345": SubagentStatus(
|
||||
task_id="abc12345",
|
||||
label="task A",
|
||||
task_description="Do task A",
|
||||
started_at=time.monotonic() - 5.0,
|
||||
phase="awaiting_tools",
|
||||
iteration=1,
|
||||
),
|
||||
}
|
||||
result = MyTool._format_value(statuses)
|
||||
assert "1 subagent(s)" in result
|
||||
assert "abc12345" in result
|
||||
assert "task A" in result
|
||||
|
||||
def test_format_empty_status_dict(self):
|
||||
"""Empty dict[str, SubagentStatus] should show 'no running subagents'."""
|
||||
result = MyTool._format_value({})
|
||||
assert "{}" in result
|
||||
|
||||
def test_format_status_with_error(self):
|
||||
"""Status with error should include the error message."""
|
||||
from nanobot.agent.subagent import SubagentStatus
|
||||
|
||||
status = SubagentStatus(
|
||||
task_id="err00001",
|
||||
label="failing task",
|
||||
task_description="A task that fails",
|
||||
started_at=time.monotonic() - 1.0,
|
||||
phase="error",
|
||||
error="Connection refused",
|
||||
)
|
||||
result = MyTool._format_value(status)
|
||||
assert "error: Connection refused" in result
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# _SubagentHook after_iteration updates status
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -674,7 +597,7 @@ class TestSubagentHookStatus:
|
||||
task_description="test",
|
||||
started_at=time.monotonic(),
|
||||
)
|
||||
hook = _SubagentHook("test", status)
|
||||
hook = _SubagentHook(status)
|
||||
|
||||
context = AgentHookContext(
|
||||
iteration=5,
|
||||
@@ -701,7 +624,7 @@ class TestSubagentHookStatus:
|
||||
task_description="test",
|
||||
started_at=time.monotonic(),
|
||||
)
|
||||
hook = _SubagentHook("test", status)
|
||||
hook = _SubagentHook(status)
|
||||
|
||||
context = AgentHookContext(
|
||||
iteration=1,
|
||||
@@ -718,7 +641,7 @@ class TestSubagentHookStatus:
|
||||
from nanobot.agent.hook import AgentHookContext
|
||||
from nanobot.agent.subagent import _SubagentHook
|
||||
|
||||
hook = _SubagentHook("test")
|
||||
hook = _SubagentHook()
|
||||
context = AgentHookContext(iteration=1, messages=[])
|
||||
result = await hook.after_iteration(context)
|
||||
|
||||
@@ -780,60 +703,6 @@ class TestCheckpointCallback:
|
||||
assert status.iteration == 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# check subagents._task_statuses via dot-path
|
||||
# Task status inspection requires the owning session context.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestInspectTaskStatuses:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_inspect_task_statuses_accessible(self):
|
||||
"""subagents is READ_ONLY — check should show subagent statuses."""
|
||||
from nanobot.agent.subagent import SubagentStatus
|
||||
|
||||
loop = _make_mock_loop()
|
||||
loop.subagents._task_statuses = {
|
||||
"abc12345": SubagentStatus(
|
||||
task_id="abc12345",
|
||||
label="read logs",
|
||||
task_description="Read the log files",
|
||||
started_at=time.monotonic() - 8.0,
|
||||
phase="awaiting_tools",
|
||||
iteration=2,
|
||||
tool_events=[{"name": "read_file", "status": "ok", "detail": "ok"}],
|
||||
usage=LLMUsage.reported(input_tokens=500, output_tokens=100),
|
||||
),
|
||||
}
|
||||
tool = _make_tool(loop=loop)
|
||||
with request_context(RequestContext("test", "owner", session_key="test:owner")):
|
||||
result = await tool.execute(action="check", key="subagents._task_statuses")
|
||||
assert "abc12345" in result
|
||||
assert "read logs" in result
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_inspect_single_subagent_status_accessible(self):
|
||||
"""subagents._task_statuses.<id> should return individual SubagentStatus."""
|
||||
from nanobot.agent.subagent import SubagentStatus
|
||||
|
||||
loop = _make_mock_loop()
|
||||
status = SubagentStatus(
|
||||
task_id="xyz",
|
||||
label="search code",
|
||||
task_description="Search the codebase",
|
||||
started_at=time.monotonic() - 3.0,
|
||||
phase="done",
|
||||
iteration=4,
|
||||
stop_reason="completed",
|
||||
)
|
||||
loop.subagents._task_statuses = {"xyz": status}
|
||||
tool = _make_tool(loop=loop)
|
||||
with request_context(RequestContext("test", "owner", session_key="test:owner")):
|
||||
result = await tool.execute(action="check", key="subagents._task_statuses.xyz")
|
||||
assert "search code" in result
|
||||
assert "completed" in result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# read-only mode (tools.my.allow_set=False)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
"""Tests for subagent tool registration and wiring."""
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
@@ -9,7 +8,9 @@ import pytest
|
||||
|
||||
from nanobot.agent.context import TranscriptInput
|
||||
from nanobot.agent.memory import Consolidator
|
||||
from nanobot.agent.runner import AgentRunResult
|
||||
from nanobot.agent.tools.context import RequestContext
|
||||
from nanobot.agent.tools.registry import is_tool_error_result
|
||||
from nanobot.config.schema import AgentDefaults
|
||||
from nanobot.providers.base import GenerationSettings
|
||||
from nanobot.utils.llm_runtime import LLMRuntime
|
||||
@@ -35,7 +36,8 @@ async def test_run_inline_returns_result_without_announcement(tmp_path):
|
||||
bus=MessageBus(),
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
)
|
||||
manager.runner.run = AsyncMock(return_value=SimpleNamespace(
|
||||
manager.runner.run = AsyncMock(return_value=AgentRunResult(
|
||||
messages=[],
|
||||
stop_reason="done",
|
||||
final_content="review result",
|
||||
error=None,
|
||||
@@ -52,8 +54,7 @@ async def test_run_inline_returns_result_without_announcement(tmp_path):
|
||||
assert result == "review result"
|
||||
manager._announce_result.assert_not_awaited()
|
||||
assert manager._running_tasks == {}
|
||||
assert manager._task_statuses == {}
|
||||
assert manager._session_tasks == {}
|
||||
assert [s.state for s in manager.statuses_for_session("test:c1").values()] == ["done"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -69,7 +70,8 @@ async def test_run_inline_returns_structured_error(tmp_path):
|
||||
bus=MessageBus(),
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
)
|
||||
manager.runner.run = AsyncMock(return_value=SimpleNamespace(
|
||||
manager.runner.run = AsyncMock(return_value=AgentRunResult(
|
||||
messages=[],
|
||||
stop_reason="error",
|
||||
final_content=None,
|
||||
error="subagent failed",
|
||||
@@ -85,13 +87,13 @@ async def test_run_inline_returns_structured_error(tmp_path):
|
||||
assert result == "subagent failed"
|
||||
assert is_tool_error_result(result)
|
||||
assert manager._running_tasks == {}
|
||||
assert manager._session_tasks == {}
|
||||
assert [s.state for s in manager.statuses_for_session("test:c1").values()] == ["error"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_subagent_exec_tool_receives_allowed_env_keys(tmp_path):
|
||||
"""allowed_env_keys from ExecToolConfig must be forwarded to the subagent's ExecTool."""
|
||||
from nanobot.agent.subagent import SubagentManager, SubagentStatus
|
||||
from nanobot.agent.subagent import SubagentManager
|
||||
from nanobot.agent.tools.shell import ExecToolConfig
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.config.schema import ToolsConfig
|
||||
@@ -112,7 +114,8 @@ async def test_subagent_exec_tool_receives_allowed_env_keys(tmp_path):
|
||||
exec_tool = spec.tools.get("exec")
|
||||
assert exec_tool is not None
|
||||
assert exec_tool.allowed_env_keys == ["GOPATH", "JAVA_HOME"]
|
||||
return SimpleNamespace(
|
||||
return AgentRunResult(
|
||||
messages=[],
|
||||
stop_reason="done",
|
||||
final_content="done",
|
||||
error=None,
|
||||
@@ -121,17 +124,14 @@ async def test_subagent_exec_tool_receives_allowed_env_keys(tmp_path):
|
||||
|
||||
mgr.runner.run = AsyncMock(side_effect=fake_run)
|
||||
|
||||
status = SubagentStatus(
|
||||
task_id="sub-1", label="label", task_description="do task", started_at=time.monotonic()
|
||||
)
|
||||
await mgr._run_subagent(
|
||||
"sub-1",
|
||||
"do task",
|
||||
"label",
|
||||
{"channel": "test", "chat_id": "c1"},
|
||||
status,
|
||||
_runtime(provider),
|
||||
await mgr.spawn(
|
||||
task="do task",
|
||||
label="label",
|
||||
origin_channel="test",
|
||||
origin_chat_id="c1",
|
||||
runtime=_runtime(provider),
|
||||
)
|
||||
await asyncio.gather(*mgr._running_tasks.values(), return_exceptions=True)
|
||||
|
||||
mgr.runner.run.assert_awaited_once()
|
||||
|
||||
@@ -139,7 +139,7 @@ async def test_subagent_exec_tool_receives_allowed_env_keys(tmp_path):
|
||||
@pytest.mark.asyncio
|
||||
async def test_subagent_uses_configured_max_iterations(tmp_path):
|
||||
"""Subagents should honor the configured tool-iteration limit."""
|
||||
from nanobot.agent.subagent import SubagentManager, SubagentStatus
|
||||
from nanobot.agent.subagent import SubagentManager
|
||||
from nanobot.bus.queue import MessageBus
|
||||
|
||||
bus = MessageBus()
|
||||
@@ -156,7 +156,8 @@ async def test_subagent_uses_configured_max_iterations(tmp_path):
|
||||
|
||||
async def fake_run(spec):
|
||||
assert spec.max_iterations == 37
|
||||
return SimpleNamespace(
|
||||
return AgentRunResult(
|
||||
messages=[],
|
||||
stop_reason="done",
|
||||
final_content="done",
|
||||
error=None,
|
||||
@@ -165,17 +166,14 @@ async def test_subagent_uses_configured_max_iterations(tmp_path):
|
||||
|
||||
mgr.runner.run = AsyncMock(side_effect=fake_run)
|
||||
|
||||
status = SubagentStatus(
|
||||
task_id="sub-1", label="label", task_description="do task", started_at=time.monotonic()
|
||||
)
|
||||
await mgr._run_subagent(
|
||||
"sub-1",
|
||||
"do task",
|
||||
"label",
|
||||
{"channel": "test", "chat_id": "c1"},
|
||||
status,
|
||||
_runtime(provider),
|
||||
await mgr.spawn(
|
||||
task="do task",
|
||||
label="label",
|
||||
origin_channel="test",
|
||||
origin_chat_id="c1",
|
||||
runtime=_runtime(provider),
|
||||
)
|
||||
await asyncio.gather(*mgr._running_tasks.values(), return_exceptions=True)
|
||||
|
||||
mgr.runner.run.assert_awaited_once()
|
||||
|
||||
@@ -203,7 +201,8 @@ async def test_spawn_forwards_temperature_to_run_spec(tmp_path):
|
||||
async def fake_run(spec):
|
||||
seen["temperature"] = spec.runtime.generation.temperature
|
||||
seen["runtime"] = spec.runtime
|
||||
return SimpleNamespace(
|
||||
return AgentRunResult(
|
||||
messages=[],
|
||||
stop_reason="done", final_content="done", error=None, tool_events=[],
|
||||
)
|
||||
|
||||
@@ -221,7 +220,7 @@ async def test_spawn_forwards_temperature_to_run_spec(tmp_path):
|
||||
async def test_background_spawn_waits_for_concurrency_capacity(tmp_path):
|
||||
"""Background tasks should be accepted and start when capacity becomes available."""
|
||||
from nanobot.agent.subagent import SubagentManager
|
||||
from nanobot.agent.tools.spawn import SpawnTool
|
||||
from nanobot.agent.tools.subagent import SubagentTool
|
||||
from nanobot.bus.queue import MessageBus
|
||||
|
||||
bus = MessageBus()
|
||||
@@ -249,7 +248,8 @@ async def test_background_spawn_waits_for_concurrency_capacity(tmp_path):
|
||||
else:
|
||||
second_entered.set()
|
||||
await release_second.wait()
|
||||
return SimpleNamespace(
|
||||
return AgentRunResult(
|
||||
messages=[],
|
||||
stop_reason="done",
|
||||
final_content="done",
|
||||
error=None,
|
||||
@@ -260,23 +260,23 @@ async def test_background_spawn_waits_for_concurrency_capacity(tmp_path):
|
||||
|
||||
from nanobot.agent.tools.context import RequestContext, request_context
|
||||
|
||||
tool = SpawnTool(mgr)
|
||||
tool = SubagentTool(mgr)
|
||||
with request_context(RequestContext(
|
||||
channel="test",
|
||||
chat_id="c1",
|
||||
session_key="test:c1",
|
||||
runtime=_runtime(provider),
|
||||
)):
|
||||
first_result = await tool.execute(task="first task")
|
||||
first_result = await tool.execute(action="create", task="first task")
|
||||
assert "started" in first_result
|
||||
await asyncio.wait_for(first_entered.wait(), timeout=1.0)
|
||||
|
||||
second_result = await tool.execute(task="second task")
|
||||
second_result = await tool.execute(action="create", task="second task")
|
||||
assert "started" in second_result
|
||||
tasks = list(mgr._running_tasks.values())
|
||||
await asyncio.sleep(0)
|
||||
assert not second_entered.is_set()
|
||||
phases = {status.task_description: status.phase for status in mgr._task_statuses.values()}
|
||||
phases = {status.task_description: status.phase for status in mgr.runtime_statuses().values()}
|
||||
assert phases == {"first task": "initializing", "second task": "queued"}
|
||||
|
||||
release_first.set()
|
||||
@@ -288,9 +288,9 @@ async def test_background_spawn_waits_for_concurrency_capacity(tmp_path):
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_spawn_tool_waits_for_inline_result():
|
||||
async def test_subagent_tool_waits_for_inline_result():
|
||||
from nanobot.agent.tools.context import RequestContext, request_context
|
||||
from nanobot.agent.tools.spawn import SpawnTool
|
||||
from nanobot.agent.tools.subagent import SubagentTool
|
||||
|
||||
class Manager:
|
||||
max_concurrent_subagents = 1
|
||||
@@ -306,7 +306,7 @@ async def test_spawn_tool_waits_for_inline_result():
|
||||
return await self.inline(**kwargs)
|
||||
|
||||
manager = Manager()
|
||||
tool = SpawnTool(manager)
|
||||
tool = SubagentTool(manager)
|
||||
runtime = _runtime(MagicMock())
|
||||
with request_context(RequestContext(
|
||||
channel="test",
|
||||
@@ -314,7 +314,7 @@ async def test_spawn_tool_waits_for_inline_result():
|
||||
session_key="test:c1",
|
||||
runtime=runtime,
|
||||
)):
|
||||
result = await tool.execute(task="review this", wait=True)
|
||||
result = await tool.execute(action="create", task="review this", wait=True)
|
||||
|
||||
assert result == "review result"
|
||||
manager.inline.assert_awaited_once()
|
||||
@@ -325,7 +325,7 @@ async def test_spawn_tool_waits_for_inline_result():
|
||||
async def test_inline_spawn_waits_for_concurrency_capacity(tmp_path):
|
||||
from nanobot.agent.subagent import SubagentManager
|
||||
from nanobot.agent.tools.context import RequestContext, request_context
|
||||
from nanobot.agent.tools.spawn import SpawnTool
|
||||
from nanobot.agent.tools.subagent import SubagentTool
|
||||
from nanobot.bus.queue import MessageBus
|
||||
|
||||
manager = SubagentManager(
|
||||
@@ -348,7 +348,8 @@ async def test_inline_spawn_waits_for_concurrency_capacity(tmp_path):
|
||||
else:
|
||||
second_entered.set()
|
||||
await release_second.wait()
|
||||
return SimpleNamespace(
|
||||
return AgentRunResult(
|
||||
messages=[],
|
||||
stop_reason="done",
|
||||
final_content="done",
|
||||
error=None,
|
||||
@@ -356,17 +357,17 @@ async def test_inline_spawn_waits_for_concurrency_capacity(tmp_path):
|
||||
)
|
||||
|
||||
manager.runner.run = AsyncMock(side_effect=fake_run)
|
||||
tool = SpawnTool(manager)
|
||||
tool = SubagentTool(manager)
|
||||
with request_context(RequestContext(
|
||||
channel="test",
|
||||
chat_id="c1",
|
||||
session_key="test:c1",
|
||||
runtime=_runtime(MagicMock()),
|
||||
)):
|
||||
first = asyncio.create_task(tool.execute(task="first", wait=True))
|
||||
first = asyncio.create_task(tool.execute(action="create", task="first", wait=True))
|
||||
await asyncio.wait_for(first_entered.wait(), timeout=1.0)
|
||||
|
||||
second = asyncio.create_task(tool.execute(task="second", wait=True))
|
||||
second = asyncio.create_task(tool.execute(action="create", task="second", wait=True))
|
||||
await asyncio.sleep(0)
|
||||
|
||||
assert not second.done()
|
||||
@@ -379,7 +380,7 @@ async def test_inline_spawn_waits_for_concurrency_capacity(tmp_path):
|
||||
assert await second == "done"
|
||||
|
||||
assert manager.get_running_count() == 0
|
||||
assert manager._session_tasks == {}
|
||||
assert [s.state for s in manager.statuses_for_session("test:c1").values()] == ["done", "done"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -390,7 +391,7 @@ async def test_runner_executes_inline_spawn_batch_concurrently(tmp_path):
|
||||
from nanobot.agent.tools.context import RequestContext, request_context
|
||||
from nanobot.agent.tools.execution import execute_tool_calls
|
||||
from nanobot.agent.tools.registry import ToolRegistry
|
||||
from nanobot.agent.tools.spawn import SpawnTool
|
||||
from nanobot.agent.tools.subagent import SubagentTool
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.providers.base import ToolCallRequest
|
||||
|
||||
@@ -410,7 +411,8 @@ async def test_runner_executes_inline_spawn_batch_concurrently(tmp_path):
|
||||
if len(entered) == 2:
|
||||
both_entered.set()
|
||||
await release.wait()
|
||||
return SimpleNamespace(
|
||||
return AgentRunResult(
|
||||
messages=[],
|
||||
stop_reason="done",
|
||||
final_content=spec.initial_messages[-1]["content"],
|
||||
error=None,
|
||||
@@ -419,18 +421,18 @@ async def test_runner_executes_inline_spawn_batch_concurrently(tmp_path):
|
||||
|
||||
manager.runner.run = AsyncMock(side_effect=fake_run)
|
||||
tools = ToolRegistry()
|
||||
tools.register(SpawnTool(manager))
|
||||
tools.register(SubagentTool(manager))
|
||||
runtime = _runtime(MagicMock())
|
||||
calls = [
|
||||
ToolCallRequest(
|
||||
id="spawn-1",
|
||||
name="spawn",
|
||||
arguments={"task": "first", "wait": True},
|
||||
id="create-1",
|
||||
name="subagent",
|
||||
arguments={"action": "create", "task": "first", "wait": True},
|
||||
),
|
||||
ToolCallRequest(
|
||||
id="spawn-2",
|
||||
name="spawn",
|
||||
arguments={"task": "second", "wait": True},
|
||||
id="create-2",
|
||||
name="subagent",
|
||||
arguments={"action": "create", "task": "second", "wait": True},
|
||||
),
|
||||
]
|
||||
|
||||
@@ -485,11 +487,11 @@ async def test_cancel_by_session_cancels_inline_subagent(tmp_path):
|
||||
await asyncio.wait_for(entered.wait(), timeout=1.0)
|
||||
|
||||
assert await manager.cancel_by_session("test:c1") == 1
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await inline
|
||||
result = await inline
|
||||
assert is_tool_error_result(result)
|
||||
assert result == "Task cancelled."
|
||||
assert manager._running_tasks == {}
|
||||
assert manager._task_statuses == {}
|
||||
assert manager._session_tasks == {}
|
||||
assert [s.state for s in manager.statuses_for_session("test:c1").values()] == ["cancelled"]
|
||||
|
||||
|
||||
def test_subagent_default_max_concurrent_matches_agent_defaults(tmp_path):
|
||||
@@ -567,13 +569,12 @@ async def test_agent_loop_syncs_updated_max_iterations_before_run(tmp_path):
|
||||
async def fake_run(spec):
|
||||
assert spec.max_iterations == 55
|
||||
assert loop.subagents.max_iterations == 55
|
||||
return SimpleNamespace(
|
||||
return AgentRunResult(
|
||||
messages=[],
|
||||
stop_reason="done",
|
||||
final_content="done",
|
||||
error=None,
|
||||
tool_events=[],
|
||||
messages=[],
|
||||
usage=None,
|
||||
had_injections=False,
|
||||
tools_used=[],
|
||||
)
|
||||
@@ -609,13 +610,12 @@ async def test_drain_pending_no_block_when_no_subagents(tmp_path):
|
||||
nonlocal injection_callback, terminal_injection_callback
|
||||
injection_callback = spec.injection_callback
|
||||
terminal_injection_callback = spec.terminal_injection_callback
|
||||
return SimpleNamespace(
|
||||
return AgentRunResult(
|
||||
messages=[],
|
||||
stop_reason="done",
|
||||
final_content="done",
|
||||
error=None,
|
||||
tool_events=[],
|
||||
messages=[],
|
||||
usage=None,
|
||||
had_injections=False,
|
||||
tools_used=[],
|
||||
provider_state=None,
|
||||
@@ -660,13 +660,12 @@ async def test_terminal_drain_timeout(tmp_path):
|
||||
async def fake_runner_run(spec):
|
||||
nonlocal terminal_injection_callback
|
||||
terminal_injection_callback = spec.terminal_injection_callback
|
||||
return SimpleNamespace(
|
||||
return AgentRunResult(
|
||||
messages=[],
|
||||
stop_reason="done",
|
||||
final_content="done",
|
||||
error=None,
|
||||
tool_events=[],
|
||||
messages=[],
|
||||
usage=None,
|
||||
had_injections=False,
|
||||
tools_used=[],
|
||||
provider_state=None,
|
||||
@@ -674,13 +673,11 @@ async def test_terminal_drain_timeout(tmp_path):
|
||||
|
||||
loop.runner.run = AsyncMock(side_effect=fake_runner_run)
|
||||
|
||||
# Register a "running" sub-agent that will never complete
|
||||
async def _hang_forever():
|
||||
async def _hang_forever(spec):
|
||||
await asyncio.Event().wait()
|
||||
|
||||
hang_task = asyncio.create_task(_hang_forever())
|
||||
loop.subagents._session_tasks.setdefault(session.key, set()).add("sub-timeout-1")
|
||||
loop.subagents._running_tasks["sub-timeout-1"] = hang_task
|
||||
loop.subagents.runner.run = _hang_forever
|
||||
await loop.subagents.spawn("pending", runtime=loop.llm_runtime(), session_key=session.key)
|
||||
|
||||
runtime = loop.llm_runtime()
|
||||
await loop._run_agent_loop(
|
||||
@@ -707,12 +704,7 @@ async def test_terminal_drain_timeout(tmp_path):
|
||||
results = await terminal_injection_callback()
|
||||
assert results == []
|
||||
|
||||
# Cleanup
|
||||
hang_task.cancel()
|
||||
try:
|
||||
await hang_task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
await loop.subagents.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -736,13 +728,12 @@ async def test_terminal_drain_reuses_one_timeout_budget(tmp_path):
|
||||
async def fake_runner_run(spec):
|
||||
nonlocal terminal_injection_callback
|
||||
terminal_injection_callback = spec.terminal_injection_callback
|
||||
return SimpleNamespace(
|
||||
return AgentRunResult(
|
||||
messages=[],
|
||||
stop_reason="done",
|
||||
final_content="done",
|
||||
error=None,
|
||||
tool_events=[],
|
||||
messages=[],
|
||||
usage=None,
|
||||
had_injections=False,
|
||||
tools_used=[],
|
||||
provider_state=None,
|
||||
@@ -750,12 +741,11 @@ async def test_terminal_drain_reuses_one_timeout_budget(tmp_path):
|
||||
|
||||
loop.runner.run = AsyncMock(side_effect=fake_runner_run)
|
||||
|
||||
async def _hang_forever():
|
||||
async def _hang_forever(spec):
|
||||
await asyncio.Event().wait()
|
||||
|
||||
hang_task = asyncio.create_task(_hang_forever())
|
||||
loop.subagents._session_tasks.setdefault(session.key, set()).add("sub-deadline-1")
|
||||
loop.subagents._running_tasks["sub-deadline-1"] = hang_task
|
||||
loop.subagents.runner.run = _hang_forever
|
||||
await loop.subagents.spawn("pending", runtime=loop.llm_runtime(), session_key=session.key)
|
||||
|
||||
await loop._run_agent_loop(
|
||||
TranscriptInput(history=[{"role": "user", "content": "test"}], current_message=None),
|
||||
@@ -788,6 +778,4 @@ async def test_terminal_drain_reuses_one_timeout_budget(tmp_path):
|
||||
|
||||
assert timeouts == [300.0, 200.0]
|
||||
|
||||
hang_task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await hang_task
|
||||
await loop.subagents.close()
|
||||
Reference in new issue
Block a user