refactor(goal): sustain one ReAct run until the goal closes (#6538)
* refactor(goal): sustain one ReAct run until the goal closes Keep active goals in the same runner beyond the ordinary iteration limit, with a final answer after successful closure. Remove cross-turn goal handoffs, continuation allowances and rollback bookkeeping while preserving input authorization, recovery, cancellation and terminal lifecycle ownership. Contributes to NAN-392 Co-authored-by: chengyongru <chengyongru.ai@gmail.com> * test(goal): consolidate sustained-run regression coverage Retain lifecycle, history, usage, provider-state privacy and checkpoint cancellation assertions in the existing long-run scenarios. Remove duplicate smoke cases and parameter combinations that do not exercise distinct behavior; keep real Gateway, authorization and generation regressions.
This commit is contained in:
1 parent
3545539128
commit
62c2ed4e7e
68 files changed
+2683
-1421
No files matched your search
@@ -28,10 +28,10 @@ def goal_message(**overrides):
|
||||
{"metadata": {"goal_requested": True, "_cron_trigger": {"job_id": "job"}}},
|
||||
{"metadata": {"goal_requested": True, "_local_trigger": {"trigger_id": "trigger"}}},
|
||||
])
|
||||
def test_background_input_cannot_authorize_initial_or_injected_work(overrides):
|
||||
def test_consumed_background_input_cannot_authorize_work(overrides):
|
||||
message = goal_message(**overrides)
|
||||
with goal_mutation_permission(True):
|
||||
with GoalInputScope(message) as scope:
|
||||
with GoalInputScope() as scope:
|
||||
assert goal_mutation_allowed() is False
|
||||
scope.consume_inputs([message])
|
||||
assert goal_mutation_allowed() is False
|
||||
@@ -39,7 +39,9 @@ def test_background_input_cannot_authorize_initial_or_injected_work(overrides):
|
||||
|
||||
|
||||
def test_revoked_permission_requires_a_new_explicit_request_to_reauthorize():
|
||||
with GoalInputScope(goal_message()) as scope:
|
||||
with GoalInputScope() as scope:
|
||||
assert goal_mutation_allowed() is False
|
||||
scope.consume_inputs([goal_message()])
|
||||
assert goal_mutation_allowed() is True
|
||||
revoke_goal_mutation_permission()
|
||||
scope.consume_inputs([goal_message(content="ok", metadata={})])
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from copy import deepcopy
|
||||
from typing import Any
|
||||
@@ -11,8 +10,8 @@ from unittest.mock import AsyncMock
|
||||
import pytest
|
||||
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.goal.assembly import install_goal
|
||||
from nanobot.providers.base import LLMProvider, LLMResponse, ToolCallRequest
|
||||
from nanobot.runtime_context import public_history_messages
|
||||
from nanobot.session.goal_state import GOAL_STATE_KEY
|
||||
@@ -55,6 +54,7 @@ def _make_loop(tmp_path, requests: list[list[dict[str, Any]]]) -> AgentLoop:
|
||||
model="test-model",
|
||||
context_window_tokens=128_000,
|
||||
max_iterations=2,
|
||||
builtin_assembly=install_goal,
|
||||
)
|
||||
exec_tool = loop.tools.get("exec")
|
||||
assert exec_tool is not None
|
||||
@@ -115,28 +115,38 @@ async def test_stop_survives_restart_and_keeps_history_prefix(tmp_path):
|
||||
await loop.aclose()
|
||||
|
||||
|
||||
async def test_goal_budget_handoff_is_not_an_abandoned_turn(tmp_path):
|
||||
async def test_goal_completed_after_iteration_limit_is_not_an_abandoned_turn(tmp_path):
|
||||
requests: list[list[dict[str, Any]]] = []
|
||||
loop = _make_loop(tmp_path, requests)
|
||||
pending: asyncio.Queue[InboundMessage] = asyncio.Queue()
|
||||
chat = loop.provider.chat
|
||||
|
||||
async def complete_after_overrun(messages, tools=None, **kwargs):
|
||||
if len(requests) == 3:
|
||||
requests.append(deepcopy(messages))
|
||||
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||
id="complete", name="update_goal", arguments={"action": "complete", "recap": "Verified."},
|
||||
)])
|
||||
return await chat(messages, tools=tools, **kwargs)
|
||||
|
||||
loop.provider.chat = complete_after_overrun
|
||||
loop.runner.run = AsyncMock(wraps=loop.runner.run)
|
||||
try:
|
||||
await loop.sessions.state.get("cli:goal")
|
||||
await loop.sessions.state.update_metadata("cli:goal", {
|
||||
GOAL_STATE_KEY: {"status": "active", "objective": "run the tests"},
|
||||
})
|
||||
await loop._process_message(
|
||||
InboundMessage(channel="cli", sender_id="user", chat_id="goal", content="run the tests"),
|
||||
pending_queue=pending,
|
||||
)
|
||||
continuation = pending.get_nowait()
|
||||
assert continuation.sender_id == "system:continuation"
|
||||
result = await loop.process_direct("run the tests", session_key="cli:goal")
|
||||
assert result.content == "done"
|
||||
assert len(requests) == 5
|
||||
loop.runner.run.assert_awaited_once()
|
||||
session = await loop.sessions.state.read("cli:goal")
|
||||
assert session.metadata[GOAL_STATE_KEY]["status"] == "completed"
|
||||
assert [row["tool_call_id"] for row in session.messages if row["role"] == "tool"] == [
|
||||
"call_1", "call_2", "call_3", "complete",
|
||||
]
|
||||
|
||||
next_request = len(requests)
|
||||
await loop.process_direct("give me a progress update", session_key="cli:goal")
|
||||
assert _STOP_MARKER not in _last_user_content(requests[next_request])
|
||||
next_request = len(requests)
|
||||
await loop._process_message(continuation, pending_queue=pending)
|
||||
assert _STOP_MARKER not in _last_user_content(requests[next_request])
|
||||
assert _STOP_MARKER not in _last_user_content(requests[-1])
|
||||
finally:
|
||||
await loop.aclose()
|
||||
|
||||
|
||||
@@ -333,12 +333,15 @@ class TestToolEventProgress:
|
||||
|
||||
provider.chat_stream_with_retry = chat_stream_with_retry
|
||||
provider.chat_with_retry = AsyncMock()
|
||||
from nanobot.goal.assembly import install_goal
|
||||
|
||||
loop = AgentLoop(
|
||||
bus=bus,
|
||||
provider=provider,
|
||||
workspace=tmp_path,
|
||||
model="test-model",
|
||||
hook_factories=[create_file_edit_activity_hook],
|
||||
builtin_assembly=install_goal,
|
||||
)
|
||||
tool = WriteFileTool(workspace=tmp_path)
|
||||
loop.tools.get_definitions = MagicMock(return_value=[
|
||||
|
||||
@@ -7,13 +7,14 @@ import pytest
|
||||
|
||||
from agent.session_helpers import mock_session_manager
|
||||
from nanobot.agent.context import TranscriptInput
|
||||
from nanobot.agent.goal_permission import goal_mutation_allowed, goal_mutation_permission
|
||||
from nanobot.agent.goal_permission import goal_mutation_allowed
|
||||
from nanobot.agent.tools.context import RequestContext
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.bus.outbound_events import StreamedResponseEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.config.schema import AgentDefaults
|
||||
from nanobot.events import RetryStatusEvent
|
||||
from nanobot.goal.assembly import install_goal
|
||||
from nanobot.providers.base import (
|
||||
GenerationSettings,
|
||||
LLMProvider,
|
||||
@@ -98,27 +99,6 @@ async def test_loop_uses_structured_retry_status_without_legacy_text(tmp_path):
|
||||
assert outbound.chat_id == "chat-a"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ephemeral_runner_enters_and_restores_turn_scopes(tmp_path):
|
||||
loop = _make_loop(tmp_path)
|
||||
|
||||
async def chat_stream_with_retry(**_kwargs):
|
||||
assert goal_mutation_allowed() is True
|
||||
return LLMResponse(content="done", tool_calls=[], usage=None)
|
||||
|
||||
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=chat_stream_with_retry)
|
||||
loop.tools.get_definitions = MagicMock(return_value=[])
|
||||
|
||||
await loop._run_agent_loop(
|
||||
TranscriptInput(history=[], current_message=None),
|
||||
runtime=loop.llm_runtime(),
|
||||
ephemeral=True,
|
||||
turn_scopes=[goal_mutation_permission(True)],
|
||||
)
|
||||
|
||||
assert goal_mutation_allowed() is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_goal_command_can_implement_plan_from_prior_discussion(tmp_path):
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
@@ -154,7 +134,8 @@ async def test_goal_command_can_implement_plan_from_prior_discussion(tmp_path):
|
||||
),
|
||||
LLMResponse(content="done", tool_calls=[], usage=None),
|
||||
])
|
||||
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model")
|
||||
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model",
|
||||
builtin_assembly=install_goal)
|
||||
session = loop.sessions.get_or_create("cli:direct")
|
||||
session.add_message("user", "Let's agree on the migration implementation.")
|
||||
session.add_message("assistant", "Use the staged migration plan and run integration tests.")
|
||||
@@ -349,7 +330,8 @@ async def test_non_goal_direct_turn_cannot_reuse_prior_goal_command(tmp_path):
|
||||
),
|
||||
LLMResponse(content="handled as a one-time task", tool_calls=[], usage=None),
|
||||
])
|
||||
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model")
|
||||
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model",
|
||||
builtin_assembly=install_goal)
|
||||
session = loop.sessions.get_or_create("api:default")
|
||||
session.add_message("user", "/goal old completed request")
|
||||
session.add_message("assistant", "The old request is complete.")
|
||||
|
||||
+332
-247
@@ -1,5 +1,6 @@
|
||||
import asyncio
|
||||
import json
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
@@ -21,8 +22,17 @@ from nanobot.bus.outbound_events import (
|
||||
TurnEndEvent,
|
||||
)
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.bus.runtime_events import TurnCompleted, TurnRunStatusChanged
|
||||
from nanobot.cron.session_turns import CRON_HISTORY_META, CRON_TRIGGER_META
|
||||
from nanobot.providers.base import LLMProvider, LLMResponse, LLMUsage, ProviderConversationState
|
||||
from nanobot.goal.assembly import install_goal
|
||||
from nanobot.providers.base import (
|
||||
GenerationSettings,
|
||||
LLMProvider,
|
||||
LLMResponse,
|
||||
LLMUsage,
|
||||
ProviderConversationState,
|
||||
ToolCallRequest,
|
||||
)
|
||||
from nanobot.providers.factory import ProviderSnapshot
|
||||
from nanobot.runtime_context import (
|
||||
RUNTIME_CONTEXT_HISTORY_META,
|
||||
@@ -119,14 +129,16 @@ def _runtime_message(content, blocks: list[RuntimeContextBlock]) -> dict:
|
||||
|
||||
|
||||
def _make_full_loop(tmp_path: Path) -> AgentLoop:
|
||||
provider = MagicMock()
|
||||
provider = MagicMock(aclose=AsyncMock())
|
||||
provider.provider_name = "test"
|
||||
provider.get_default_model.return_value = "test-model"
|
||||
provider.generation = SimpleNamespace(max_tokens=4096)
|
||||
provider.generation = GenerationSettings(max_tokens=4096)
|
||||
provider.estimate_prompt_tokens.return_value = (100, "test")
|
||||
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="Test title"))
|
||||
bus = MessageBus()
|
||||
loop = AgentLoop(
|
||||
bus=bus, provider=provider, workspace=tmp_path, model="test-model",
|
||||
builtin_assembly=install_goal,
|
||||
)
|
||||
WebuiTurnCoordinator(
|
||||
bus=loop.bus,
|
||||
@@ -1382,256 +1394,270 @@ async def test_process_message_does_not_duplicate_early_persisted_user_message(t
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_internal_continuation_queues_turn_without_fake_user_history(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
async def test_explicit_recovery_continues_without_fake_user_history(tmp_path: Path) -> None:
|
||||
loop = _make_full_loop(tmp_path)
|
||||
session = loop.sessions.get_or_create("feishu:c-auto")
|
||||
session.metadata[GOAL_STATE_KEY] = {
|
||||
"status": "active",
|
||||
"objective": "Finish the long goal.",
|
||||
}
|
||||
session = loop.sessions.get_or_create("feishu:recovery")
|
||||
session.add_message("user", "Inspect the migration")
|
||||
session.add_message("assistant", "Evidence collected before interruption.")
|
||||
loop.sessions.save(session)
|
||||
|
||||
calls: list[dict] = []
|
||||
|
||||
async def fake_run_agent_loop(transcript_input, *, metadata=None, **_kwargs):
|
||||
initial_messages = _assembled_messages(loop.context, transcript_input)
|
||||
calls.append({"initial_messages": initial_messages, "metadata": metadata})
|
||||
if len(calls) == 1:
|
||||
return _agent_run_result(
|
||||
"paused",
|
||||
[*initial_messages, {"role": "assistant", "content": "paused"}],
|
||||
stop_reason="max_iterations",
|
||||
)
|
||||
return _agent_run_result(
|
||||
"done",
|
||||
[*initial_messages, {"role": "assistant", "content": "done"}],
|
||||
)
|
||||
|
||||
loop._run_agent_loop = fake_run_agent_loop # type: ignore[method-assign]
|
||||
pending: asyncio.Queue[InboundMessage] = asyncio.Queue()
|
||||
|
||||
first = await loop._process_message(
|
||||
InboundMessage(
|
||||
channel="feishu",
|
||||
sender_id="u1",
|
||||
chat_id="c-auto",
|
||||
content="start the goal",
|
||||
),
|
||||
pending_queue=pending,
|
||||
)
|
||||
|
||||
assert first is None
|
||||
queued = pending.get_nowait()
|
||||
assert queued.sender_id == "system:continuation"
|
||||
assert queued.metadata[INTERNAL_CONTINUATION_META] is True
|
||||
assert "Finish the long goal." in queued.content
|
||||
|
||||
session = loop.sessions.get_or_create("feishu:c-auto")
|
||||
assert "Finish the long goal." in str(session.messages[0]["content"])
|
||||
assert [
|
||||
{k: v for k, v in m.items() if k in {"role", "content"}}
|
||||
for m in map(public_history_message, session.messages)
|
||||
] == [{"role": "user", "content": "start the goal"}]
|
||||
|
||||
second = await loop._process_message(queued, pending_queue=asyncio.Queue())
|
||||
|
||||
assert second is not None
|
||||
assert second.content == "done"
|
||||
session = loop.sessions.get_or_create("feishu:c-auto")
|
||||
assert [
|
||||
{k: v for k, v in m.items() if k in {"role", "content"}}
|
||||
for m in map(public_history_message, session.messages)
|
||||
] == [
|
||||
{"role": "user", "content": "start the goal"},
|
||||
{"role": "assistant", "content": "done"},
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_internal_continuation_preserves_streaming_route_metadata(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
loop = _make_full_loop(tmp_path)
|
||||
session = loop.sessions.get_or_create("feishu:c-stream")
|
||||
session.metadata[GOAL_STATE_KEY] = {
|
||||
"status": "active",
|
||||
"objective": "Finish the streamed long goal.",
|
||||
}
|
||||
loop.sessions.save(session)
|
||||
|
||||
calls = 0
|
||||
|
||||
async def fake_run_agent_loop(transcript_input, *, events, streaming, **_kwargs):
|
||||
nonlocal calls
|
||||
initial_messages = _assembled_messages(loop.context, transcript_input)
|
||||
calls += 1
|
||||
if calls == 1:
|
||||
return _agent_run_result(
|
||||
"paused",
|
||||
[*initial_messages, {"role": "assistant", "content": "paused"}],
|
||||
stop_reason="max_iterations",
|
||||
)
|
||||
assert streaming
|
||||
await events.emit(StreamDeltaEvent(content="done"))
|
||||
await events.emit(StreamEndEvent())
|
||||
return _agent_run_result(
|
||||
"done",
|
||||
[*initial_messages, {"role": "assistant", "content": "done"}],
|
||||
)
|
||||
|
||||
loop._run_agent_loop = fake_run_agent_loop # type: ignore[method-assign]
|
||||
|
||||
await run_session(loop, InboundMessage(
|
||||
channel="feishu",
|
||||
sender_id="u1",
|
||||
chat_id="c-stream",
|
||||
content="start the goal",
|
||||
metadata={
|
||||
"_wants_stream": True,
|
||||
"message_id": "om_001",
|
||||
"origin_message_id": "root_001",
|
||||
},
|
||||
))
|
||||
|
||||
outbound = []
|
||||
while loop.bus.outbound_size:
|
||||
outbound.append(await loop.bus.consume_outbound())
|
||||
deltas = [m for m in outbound if isinstance(m.event, StreamDeltaEvent)]
|
||||
ends = [m for m in outbound if isinstance(m.event, StreamEndEvent)]
|
||||
streamed_markers = [m for m in outbound if isinstance(m.event, StreamedResponseEvent)]
|
||||
|
||||
assert [m.content for m in deltas] == ["done"]
|
||||
assert len(ends) == 1
|
||||
assert isinstance(ends[0].event, StreamEndEvent)
|
||||
assert ends[0].event.resuming is False
|
||||
assert ends[0].metadata["message_id"] == "om_001"
|
||||
assert ends[0].metadata["origin_message_id"] == "root_001"
|
||||
assert isinstance(ends[0].event.stream_id, str)
|
||||
assert streamed_markers and streamed_markers[-1].content == "done"
|
||||
assert loop.bus.inbound_size == 0
|
||||
assert calls == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("content", ["start the goal", "/goal start the goal"])
|
||||
async def test_websocket_internal_continuation_keeps_single_visible_run(
|
||||
tmp_path: Path, content: str,
|
||||
) -> None:
|
||||
loop = _make_full_loop(tmp_path)
|
||||
session = loop.sessions.get_or_create("websocket:c-auto")
|
||||
session.metadata[GOAL_STATE_KEY] = {
|
||||
"status": "active",
|
||||
"objective": "Finish the long goal.",
|
||||
}
|
||||
loop.sessions.save(session)
|
||||
|
||||
calls = 0
|
||||
|
||||
async def fake_run_agent_loop(transcript_input, **_kwargs):
|
||||
nonlocal calls
|
||||
initial_messages = _assembled_messages(loop.context, transcript_input)
|
||||
calls += 1
|
||||
if calls == 1:
|
||||
return _agent_run_result(
|
||||
"paused",
|
||||
[*initial_messages, {"role": "assistant", "content": "paused"}],
|
||||
stop_reason="max_iterations",
|
||||
)
|
||||
return _agent_run_result(
|
||||
"done",
|
||||
[*initial_messages, {"role": "assistant", "content": "done"}],
|
||||
)
|
||||
|
||||
loop._run_agent_loop = fake_run_agent_loop # type: ignore[method-assign]
|
||||
|
||||
await run_session(loop, InboundMessage(
|
||||
channel="websocket",
|
||||
sender_id="u1",
|
||||
chat_id="c-auto",
|
||||
content=content,
|
||||
metadata={"webui": True},
|
||||
))
|
||||
|
||||
first_outbound = []
|
||||
while loop.bus.outbound_size:
|
||||
first_outbound.append(await loop.bus.consume_outbound())
|
||||
first_statuses = [m.event for m in first_outbound if isinstance(m.event, GoalStatusEvent)]
|
||||
assert [m.status for m in first_statuses] == ["running", "running", "idle"]
|
||||
started_at = first_statuses[0].started_at
|
||||
assert first_statuses[1].started_at == started_at
|
||||
turn_end = [m for m in first_outbound if isinstance(m.event, TurnEndEvent)]
|
||||
assert len(turn_end) == 1
|
||||
assert isinstance(turn_end[0].event, TurnEndEvent)
|
||||
assert isinstance(turn_end[0].event.latency_ms, int)
|
||||
assert loop.bus.inbound_size == 0
|
||||
assert calls == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("content", ["start the goal", "/goal start the goal"])
|
||||
async def test_stop_after_continuation_queued_ends_visible_run(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, content: str,
|
||||
) -> None:
|
||||
from nanobot.command.builtin import cmd_stop
|
||||
from nanobot.command.router import CommandContext
|
||||
|
||||
loop = _make_full_loop(tmp_path)
|
||||
session = loop.sessions.get_or_create("websocket:c-stop-continuation")
|
||||
session.metadata[GOAL_STATE_KEY] = {
|
||||
"status": "active",
|
||||
"objective": "Finish the long goal.",
|
||||
}
|
||||
loop.sessions.save(session)
|
||||
calls = 0
|
||||
|
||||
async def fake_run_agent_loop(transcript_input, **_kwargs):
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
initial_messages = _assembled_messages(loop.context, transcript_input)
|
||||
return _agent_run_result(
|
||||
"paused",
|
||||
[*initial_messages, {"role": "assistant", "content": "paused"}],
|
||||
stop_reason="max_iterations",
|
||||
)
|
||||
|
||||
loop._run_agent_loop = fake_run_agent_loop # type: ignore[method-assign]
|
||||
saving = asyncio.Event()
|
||||
finish_turn = loop.sessions.state.finish_turn
|
||||
|
||||
async def hold_first_save(session):
|
||||
if not saving.is_set():
|
||||
saving.set()
|
||||
await asyncio.Event().wait()
|
||||
await finish_turn(session)
|
||||
|
||||
monkeypatch.setattr(loop.sessions.state, "finish_turn", hold_first_save)
|
||||
msg = InboundMessage(
|
||||
channel="websocket", sender_id="u1", chat_id="c-stop-continuation",
|
||||
content=content, metadata={"webui": True},
|
||||
)
|
||||
await loop._enqueue_session_message(msg)
|
||||
loop.provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="done"))
|
||||
try:
|
||||
await asyncio.wait_for(saving.wait(), timeout=5)
|
||||
result = await loop._process_message(InboundMessage(
|
||||
channel="feishu", sender_id="system:recovery", chat_id="recovery",
|
||||
content="Continue the interrupted request from saved context.",
|
||||
metadata={INTERNAL_CONTINUATION_META: True},
|
||||
))
|
||||
assert result is not None and result.content == "done"
|
||||
saved = await loop.sessions.state.read(session.key)
|
||||
assert [
|
||||
{k: v for k, v in row.items() if k in {"role", "content"}}
|
||||
for row in map(public_history_message, saved.messages)
|
||||
] == [
|
||||
{"role": "user", "content": "Inspect the migration"},
|
||||
{"role": "assistant", "content": "Evidence collected before interruption."},
|
||||
{"role": "assistant", "content": "done"},
|
||||
]
|
||||
prompt = loop.provider.chat_stream_with_retry.await_args.kwargs["messages"]
|
||||
assert "Continue the interrupted request from saved context." in str(prompt)
|
||||
finally:
|
||||
await loop.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_same_run_goal_preserves_streaming_route_metadata(tmp_path: Path) -> None:
|
||||
loop = _make_full_loop(tmp_path)
|
||||
loop.max_iterations = 1
|
||||
session = await loop.sessions.state.get("feishu:c-stream")
|
||||
await loop.sessions.state.update_metadata(session.key, {GOAL_STATE_KEY: {
|
||||
"status": "active", "objective": "Finish the streamed long goal.",
|
||||
}})
|
||||
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=[
|
||||
LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||
id="list", name="list_dir", arguments={"path": "."},
|
||||
)]),
|
||||
LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||
id="complete", name="update_goal", arguments={"action": "complete", "recap": "done"},
|
||||
)]),
|
||||
LLMResponse(content="done"),
|
||||
])
|
||||
loop.runner.run = AsyncMock(wraps=loop.runner.run)
|
||||
try:
|
||||
await run_session(loop, InboundMessage(
|
||||
channel="feishu", sender_id="u1", chat_id="c-stream", content="start the goal",
|
||||
metadata={"_wants_stream": True, "message_id": "om_001", "origin_message_id": "root_001"},
|
||||
))
|
||||
outbound = []
|
||||
while loop.bus.outbound_size:
|
||||
outbound.append(await loop.bus.consume_outbound())
|
||||
deltas = [m for m in outbound if isinstance(m.event, StreamDeltaEvent)]
|
||||
ends = [m for m in outbound if isinstance(m.event, StreamEndEvent)]
|
||||
streamed_markers = [m for m in outbound if isinstance(m.event, StreamedResponseEvent)]
|
||||
assert [m.content for m in deltas] == ["done"]
|
||||
assert [item.event.resuming for item in ends] == [True, True, False]
|
||||
assert all(item.metadata["message_id"] == "om_001" for item in ends)
|
||||
assert all(item.metadata["origin_message_id"] == "root_001" for item in ends)
|
||||
assert all(isinstance(item.event.stream_id, str) for item in ends)
|
||||
assert streamed_markers and streamed_markers[-1].content == "done"
|
||||
assert loop.bus.inbound_size == 0
|
||||
assert loop.provider.chat_stream_with_retry.await_count == 3
|
||||
loop.runner.run.assert_awaited_once()
|
||||
finally:
|
||||
await loop.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stop_during_committed_goal_checkpoint_settles_queued_command(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
|
||||
):
|
||||
loop = _make_full_loop(tmp_path)
|
||||
loop.provider.aclose = AsyncMock()
|
||||
loop.consolidator.compact_idle_session = AsyncMock()
|
||||
loop.max_iterations = 1
|
||||
gate = asyncio.Semaphore(1)
|
||||
loop._concurrency_gate = gate
|
||||
session = loop.sessions.get_or_create("websocket:committed-checkpoint")
|
||||
session.metadata[GOAL_STATE_KEY] = {"status": "active", "objective": "Finish the goal."}
|
||||
loop.sessions.save(session)
|
||||
calls = 0
|
||||
|
||||
async def respond(*args, **kwargs):
|
||||
nonlocal calls
|
||||
if args and "You write short, neutral chat titles" in str(args[0]):
|
||||
return LLMResponse(content="Goal checkpoint")
|
||||
calls += 1
|
||||
if calls == 3:
|
||||
await loop._dispatch_inbound(InboundMessage(
|
||||
channel="websocket", sender_id="user", chat_id="committed-checkpoint",
|
||||
content="/compact", metadata={"webui": True, "message_id": "queued-compact"},
|
||||
))
|
||||
if calls <= 3:
|
||||
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||
id=f"list-{calls}", name="list_dir", arguments={"path": "."},
|
||||
)])
|
||||
if calls == 4:
|
||||
assert "list-1" in str(kwargs["messages"]) and "list-3" in str(kwargs["messages"])
|
||||
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||
id="cancel", name="update_goal", arguments={"action": "cancel", "recap": "Stopped work."},
|
||||
)])
|
||||
assert calls == 5
|
||||
return LLMResponse(content="handled later")
|
||||
|
||||
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=respond)
|
||||
loop.runner.run = AsyncMock(wraps=loop.runner.run)
|
||||
committed, release = threading.Event(), threading.Event()
|
||||
publish = loop.sessions.state._publish
|
||||
|
||||
def hold_after_commit(saved, *args, **kwargs):
|
||||
checkpoint = saved.metadata.get(RUNTIME_CHECKPOINT_KEY, {})
|
||||
if checkpoint.get("phase") == "tools_completed" and calls == 3 and not committed.is_set():
|
||||
committed.set()
|
||||
if not release.wait(5):
|
||||
raise TimeoutError("test did not release the committed save")
|
||||
return publish(saved, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(loop.sessions.state, "_publish", hold_after_commit)
|
||||
msg = InboundMessage(
|
||||
channel="websocket", sender_id="user", chat_id="committed-checkpoint", content="Continue",
|
||||
metadata={"webui": True, "message_id": "goal-input"},
|
||||
)
|
||||
completed = []
|
||||
statuses = []
|
||||
loop.bus.subscribe(completed.append, TurnCompleted)
|
||||
loop.bus.subscribe(statuses.append, TurnRunStatusChanged)
|
||||
stop_acknowledged = asyncio.Event()
|
||||
publish_outbound = loop.bus.publish_outbound
|
||||
|
||||
async def observe_stop_reply(message):
|
||||
await publish_outbound(message)
|
||||
if message.metadata.get("message_id") == "stop-attempt" and message.content.startswith("Stopped "):
|
||||
stop_acknowledged.set()
|
||||
|
||||
monkeypatch.setattr(loop.bus, "publish_outbound", observe_stop_reply)
|
||||
bus_task = asyncio.create_task(loop.run())
|
||||
try:
|
||||
await loop.bus.publish_inbound(msg)
|
||||
assert await asyncio.wait_for(asyncio.to_thread(committed.wait), 5)
|
||||
worker, = loop._active_tasks[msg.session_key]
|
||||
assert gate.locked()
|
||||
assert loop._pending_queues[msg.session_key].qsize() == 1
|
||||
stop_msg = InboundMessage(
|
||||
channel="websocket", sender_id="u1", chat_id=msg.chat_id, content="/stop",
|
||||
channel="websocket", sender_id="user", chat_id=msg.chat_id, content="/stop",
|
||||
metadata={"message_id": "stop-attempt"},
|
||||
)
|
||||
result = await cmd_stop(CommandContext(
|
||||
msg=stop_msg, session=None, key=msg.session_key, raw="/stop", loop=loop,
|
||||
))
|
||||
assert "Stopped 1 task(s)" in result.content
|
||||
finally:
|
||||
await loop._cancel_active_tasks(msg.session_key)
|
||||
await loop.bus.publish_inbound(stop_msg)
|
||||
async with asyncio.timeout(5):
|
||||
while not worker.cancelling():
|
||||
await asyncio.sleep(0)
|
||||
release.set()
|
||||
await asyncio.wait_for(stop_acknowledged.wait(), 5)
|
||||
assert not bus_task.done(), "Stop terminated the inbound loop"
|
||||
assert not gate.locked()
|
||||
saved = await loop.sessions.state.read(msg.session_key)
|
||||
assert saved.metadata[GOAL_STATE_KEY]["status"] == "active"
|
||||
assert RUNTIME_CHECKPOINT_KEY not in saved.metadata
|
||||
assert [row["tool_call_id"] for row in saved.messages if row["role"] == "tool"] == [
|
||||
"list-1", "list-2", "list-3",
|
||||
]
|
||||
assert msg.session_key not in loop._pending_queues
|
||||
assert not loop._active_tasks.get(msg.session_key)
|
||||
assert calls == 3
|
||||
loop.runner.run.assert_awaited_once()
|
||||
assert [(event.context.metadata.get("message_id"), event.outcome) for event in completed
|
||||
if event.context.metadata.get("message_id") in {"goal-input", "queued-compact"}] == [
|
||||
("goal-input", "cancelled"), ("queued-compact", "completed"),
|
||||
]
|
||||
assert [(event.context.metadata.get("message_id"), event.status) for event in statuses] == [
|
||||
("goal-input", "running"), ("goal-input", "idle"),
|
||||
]
|
||||
loop.consolidator.compact_idle_session.assert_not_awaited()
|
||||
|
||||
outbound = []
|
||||
while loop.bus.outbound_size:
|
||||
outbound.append(await loop.bus.consume_outbound())
|
||||
statuses = [m.event.status for m in outbound if isinstance(m.event, GoalStatusEvent)]
|
||||
assert statuses == ["running", "idle"]
|
||||
assert calls == 1
|
||||
assert msg.session_key not in loop._pending_queues
|
||||
outbound = []
|
||||
while loop.bus.outbound_size:
|
||||
outbound.append(await loop.bus.consume_outbound())
|
||||
stop_responses = [item.content for item in outbound if item.content.startswith("Stopped ")]
|
||||
assert stop_responses == ["Stopped 1 task(s)."]
|
||||
endings = [item.event for item in outbound if isinstance(item.event, TurnEndEvent)]
|
||||
cancelled = [event for event in endings if event.outcome == "cancelled"]
|
||||
assert len(cancelled) == 1 and cancelled[0].goal_state["status"] == "active"
|
||||
assert [item.event.status for item in outbound if isinstance(item.event, GoalStatusEvent)] == [
|
||||
"running", "idle",
|
||||
]
|
||||
|
||||
followup = InboundMessage(
|
||||
channel="websocket", sender_id="user", chat_id=msg.chat_id, content="Independent input",
|
||||
metadata={"webui": True, "message_id": "independent-input"},
|
||||
)
|
||||
await loop.bus.publish_inbound(followup)
|
||||
async with asyncio.timeout(5):
|
||||
while msg.session_key in loop._pending_queues or not any(
|
||||
event.context.metadata.get("message_id") == "independent-input"
|
||||
for event in completed
|
||||
):
|
||||
await asyncio.sleep(0)
|
||||
assert calls == 5 and loop.runner.run.await_count == 2
|
||||
assert msg.session_key not in loop._pending_queues
|
||||
followup_outbound = []
|
||||
while loop.bus.outbound_size:
|
||||
followup_outbound.append(await loop.bus.consume_outbound())
|
||||
assert any(item.content == "handled later" for item in followup_outbound)
|
||||
loop.consolidator.compact_idle_session.assert_not_awaited()
|
||||
finally:
|
||||
release.set()
|
||||
loop.stop()
|
||||
await asyncio.wait_for(asyncio.gather(bus_task, return_exceptions=True), 5)
|
||||
await loop.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("operation", ["reset", "delete"])
|
||||
async def test_active_goal_checkpoint_cannot_revive_an_old_generation(tmp_path: Path, operation):
|
||||
loop = _make_full_loop(tmp_path)
|
||||
loop.max_iterations = 1
|
||||
session = await loop.sessions.state.get("websocket:old-generation")
|
||||
await loop.sessions.state.update_metadata(session.key, {
|
||||
GOAL_STATE_KEY: {"status": "active", "objective": "Old goal."},
|
||||
})
|
||||
waiting, release = asyncio.Event(), asyncio.Event()
|
||||
calls = 0
|
||||
|
||||
async def respond(**kwargs):
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
assert calls <= 2
|
||||
if calls == 1:
|
||||
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||
id="list", name="list_dir", arguments={"path": "."},
|
||||
)])
|
||||
waiting.set()
|
||||
await release.wait()
|
||||
return LLMResponse(content="Old generation's late answer.")
|
||||
|
||||
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=respond)
|
||||
worker = asyncio.create_task(run_session(loop, InboundMessage(
|
||||
channel="websocket", sender_id="user", chat_id="old-generation", content="Continue",
|
||||
metadata={"webui": True},
|
||||
)))
|
||||
try:
|
||||
await asyncio.wait_for(waiting.wait(), 5)
|
||||
if operation == "reset":
|
||||
await loop.sessions.state.reset(session.key)
|
||||
else:
|
||||
assert await loop.sessions.state.delete(session.key, expected_generation=session.generation)
|
||||
release.set()
|
||||
await asyncio.wait_for(worker, 5)
|
||||
current = await loop.sessions.state.read(session.key)
|
||||
if operation == "reset":
|
||||
assert current is not None and current.generation != session.generation
|
||||
assert current.messages == []
|
||||
assert GOAL_STATE_KEY not in current.metadata
|
||||
else:
|
||||
assert current is None
|
||||
assert calls == 2
|
||||
finally:
|
||||
release.set()
|
||||
await loop._cancel_active_tasks(session.key)
|
||||
await asyncio.gather(worker, return_exceptions=True)
|
||||
await loop.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -2034,7 +2060,9 @@ async def test_system_subagent_followup_is_persisted_before_prompt_assembly(tmp_
|
||||
assert request.sender_id == "subagent"
|
||||
assert request.metadata == {"subagent_task_id": "sub-1"}
|
||||
assert request.turn_id
|
||||
record_runtime.assert_called_once_with("cli:test", runtime)
|
||||
assert record_runtime.call_count == 1
|
||||
assert record_runtime.call_args.args == ("cli:test", runtime)
|
||||
assert isinstance(record_runtime.call_args.kwargs["run_id"], str)
|
||||
initial_messages = seen["initial_messages"]
|
||||
assert isinstance(initial_messages, list)
|
||||
non_system = [m for m in initial_messages if m.get("role") != "system"]
|
||||
@@ -2624,3 +2652,60 @@ def test_save_turn_drops_duplicate_tool_result_ids() -> None:
|
||||
|
||||
assert [m["role"] for m in session.messages] == ["assistant", "tool"]
|
||||
assert session.messages[1]["content"] == "first"
|
||||
|
||||
|
||||
async def test_stop_during_goal_completion_publishes_one_terminal_event(tmp_path):
|
||||
loop = _make_full_loop(tmp_path)
|
||||
loop.max_iterations = 1
|
||||
key = "websocket:goal-completion"
|
||||
await loop.sessions.state.get(key)
|
||||
await loop.sessions.state.update_metadata(key, {
|
||||
GOAL_STATE_KEY: {"status": "active", "objective": "Verify the result."},
|
||||
"title": "Goal completion", "title_user_edited": True,
|
||||
})
|
||||
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=[
|
||||
LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||
id="complete", name="update_goal", arguments={"action": "complete", "recap": "Verified."},
|
||||
)]),
|
||||
LLMResponse(content="Verified."),
|
||||
])
|
||||
publishing, release = asyncio.Event(), asyncio.Event()
|
||||
completed = []
|
||||
|
||||
async def hold_completion(event):
|
||||
completed.append(event)
|
||||
publishing.set()
|
||||
await release.wait()
|
||||
|
||||
loop.bus.subscribe(hold_completion, TurnCompleted)
|
||||
stop = None
|
||||
try:
|
||||
await loop._enqueue_session_message(InboundMessage(
|
||||
channel="websocket", sender_id="user", chat_id="goal-completion", content="Continue",
|
||||
metadata={"webui": True},
|
||||
))
|
||||
await asyncio.wait_for(publishing.wait(), 5)
|
||||
worker, = loop._active_tasks[key]
|
||||
stop = asyncio.create_task(loop._cancel_active_tasks(key))
|
||||
async with asyncio.timeout(5):
|
||||
while not worker.cancelling():
|
||||
await asyncio.sleep(0)
|
||||
release.set()
|
||||
assert await asyncio.wait_for(stop, 5) == 1
|
||||
assert [event.outcome for event in completed] == ["completed"]
|
||||
outbound = []
|
||||
while not loop.bus.outbound.empty():
|
||||
outbound.append(loop.bus.outbound.get_nowait())
|
||||
endings = [item.event for item in outbound if isinstance(item.event, TurnEndEvent)]
|
||||
assert len(endings) == 1 and endings[0].outcome == "completed"
|
||||
assert [item.event.status for item in outbound if isinstance(item.event, GoalStatusEvent)] == [
|
||||
"running", "idle",
|
||||
]
|
||||
saved = await loop.sessions.state.read(key)
|
||||
assert saved.metadata[GOAL_STATE_KEY]["status"] == "completed"
|
||||
assert saved.messages[-1]["content"] == "Verified."
|
||||
finally:
|
||||
release.set()
|
||||
if stop is not None:
|
||||
await asyncio.gather(stop, return_exceptions=True)
|
||||
await loop.aclose()
|
||||
@@ -5,14 +5,27 @@ import pytest
|
||||
|
||||
from agent.session_helpers import stop_loop
|
||||
from nanobot.agent.goal_permission import goal_mutation_allowed, goal_mutation_permission
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.agent.loop import AgentLoop as CoreAgentLoop
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.bus.outbound_events import GoalStatusEvent, TurnEndEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.providers.base import GenerationSettings, LLMResponse, ToolCallRequest
|
||||
from nanobot.goal.assembly import install_goal
|
||||
from nanobot.providers.base import (
|
||||
GenerationSettings,
|
||||
LLMResponse,
|
||||
LLMUsage,
|
||||
ProviderConversationState,
|
||||
ToolCallRequest,
|
||||
)
|
||||
from nanobot.runtime_context import public_history_messages
|
||||
from nanobot.session.goal_state import GOAL_STATE_KEY
|
||||
from nanobot.session.history_visibility import is_hidden_history_message
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.webui_turns import WebuiTurnCoordinator
|
||||
|
||||
|
||||
def _assembled_loop(*args, **kwargs):
|
||||
return CoreAgentLoop(*args, builtin_assembly=install_goal, **kwargs)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("command", [
|
||||
@@ -51,7 +64,7 @@ async def test_goal_input_enters_running_turn_with_scoped_permission(tmp_path, c
|
||||
return LLMResponse(content="done")
|
||||
|
||||
provider.chat_stream_with_retry = AsyncMock(side_effect=respond)
|
||||
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model")
|
||||
loop = _assembled_loop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model")
|
||||
process = AsyncMock(wraps=loop._process_message)
|
||||
loop._process_message = process
|
||||
run = asyncio.create_task(loop.run())
|
||||
@@ -96,7 +109,7 @@ async def test_scheduled_goal_command_cannot_generate_internal_input(tmp_path):
|
||||
channel="cli", sender_id="user", chat_id="test", content="/goal execute",
|
||||
metadata={"_cron_trigger": {"job_id": "job"}},
|
||||
)
|
||||
loop = AgentLoop(bus=MessageBus(), provider=MagicMock(aclose=AsyncMock()), workspace=tmp_path, model="test-model")
|
||||
loop = _assembled_loop(bus=MessageBus(), provider=MagicMock(aclose=AsyncMock()), workspace=tmp_path, model="test-model")
|
||||
try:
|
||||
await loop._dispatch_command_inline(msg, msg.session_key, msg.content, loop.commands.dispatch)
|
||||
response = loop.bus.outbound.get_nowait()
|
||||
@@ -116,7 +129,7 @@ async def test_goal_at_iteration_limit_stays_queued_for_a_tool_capable_turn(tmp_
|
||||
provider.get_default_model.return_value = "test-model"
|
||||
provider.generation = GenerationSettings()
|
||||
provider.estimate_prompt_tokens.return_value = (100, "test")
|
||||
loop = AgentLoop(
|
||||
loop = _assembled_loop(
|
||||
bus=MessageBus(), provider=provider, workspace=tmp_path,
|
||||
model="test-model", max_iterations=1,
|
||||
)
|
||||
@@ -170,28 +183,31 @@ async def test_goal_at_iteration_limit_stays_queued_for_a_tool_capable_turn(tmp_
|
||||
|
||||
|
||||
async def test_generated_goal_input_survives_pending_followup_recovery(tmp_path):
|
||||
from nanobot.command.router import CommandContext
|
||||
from nanobot.command.router import CommandContext, CommandExpansion
|
||||
from nanobot.session.recovery import pending_followups
|
||||
|
||||
provider = MagicMock(aclose=AsyncMock())
|
||||
provider.get_default_model.return_value = "test-model"
|
||||
provider.generation = GenerationSettings()
|
||||
provider.estimate_prompt_tokens.return_value = (100, "test")
|
||||
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model")
|
||||
loop = _assembled_loop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model")
|
||||
message = InboundMessage(
|
||||
channel="websocket", sender_id="user", chat_id="test", content="/goal /stop",
|
||||
)
|
||||
try:
|
||||
generated = await loop.commands.dispatch(CommandContext(
|
||||
context = CommandContext(
|
||||
msg=message, session=None, key=message.session_key,
|
||||
raw=message.content, loop=loop, is_user_turn=True,
|
||||
))
|
||||
)
|
||||
expansion = await loop.commands.dispatch(context)
|
||||
assert isinstance(expansion, CommandExpansion)
|
||||
generated = await loop._prepare_command_expansion(context, expansion)
|
||||
assert isinstance(generated, InboundMessage)
|
||||
assert await loop.sessions.state.queue_followup(message.session_key, generated)
|
||||
finally:
|
||||
await loop.aclose()
|
||||
|
||||
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model")
|
||||
loop = _assembled_loop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model")
|
||||
session = (await loop.sessions.state.get(message.session_key))
|
||||
recovered, = pending_followups(session)
|
||||
responses = iter([
|
||||
@@ -237,7 +253,7 @@ async def test_internal_continuation_cannot_inherit_goal_permission(tmp_path):
|
||||
provider.get_default_model.return_value = "test-model"
|
||||
provider.generation = GenerationSettings()
|
||||
provider.estimate_prompt_tokens.return_value = (100, "test")
|
||||
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model")
|
||||
loop = _assembled_loop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model")
|
||||
message = InboundMessage(
|
||||
channel="cli", sender_id="automation", chat_id="test", content="Continue working",
|
||||
metadata={"goal_requested": True, "_internal_continuation": True},
|
||||
@@ -258,3 +274,293 @@ async def test_internal_continuation_cannot_inherit_goal_permission(tmp_path):
|
||||
assert goal_mutation_allowed() is False
|
||||
finally:
|
||||
await loop.aclose()
|
||||
|
||||
|
||||
async def test_goal_checkpoint_failure_finishes_visible_run_without_restarting(tmp_path, monkeypatch):
|
||||
from agent.session_helpers import run_session
|
||||
|
||||
bus = MessageBus()
|
||||
provider = MagicMock(aclose=AsyncMock())
|
||||
provider.get_default_model.return_value = "test-model"
|
||||
provider.generation = GenerationSettings()
|
||||
provider.estimate_prompt_tokens.return_value = (100, "test")
|
||||
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||
id="list", name="list_dir", arguments={"path": "."},
|
||||
)]))
|
||||
loop = _assembled_loop(bus=bus, provider=provider, workspace=tmp_path, model="test-model", max_iterations=1)
|
||||
WebuiTurnCoordinator(
|
||||
bus=bus, sessions=loop.sessions,
|
||||
schedule_background=lambda coro: loop.schedule_background(coro),
|
||||
).subscribe()
|
||||
session = await loop.sessions.state.get("websocket:goal-save-fail")
|
||||
await loop.sessions.state.update_metadata(session.key, {
|
||||
"webui": True, "title": "Goal", "title_user_edited": True,
|
||||
GOAL_STATE_KEY: {"status": "active", "objective": "Verify the task."},
|
||||
})
|
||||
checkpoint_view = loop.sessions.state.checkpoint_view
|
||||
checkpoints = 0
|
||||
|
||||
async def fail_checkpoint(session, payload):
|
||||
nonlocal checkpoints
|
||||
if payload["phase"] == "tools_completed":
|
||||
checkpoints += 1
|
||||
if checkpoints == 3:
|
||||
raise OSError("synthetic checkpoint failure")
|
||||
await checkpoint_view(session, payload)
|
||||
|
||||
monkeypatch.setattr(loop.sessions.state, "checkpoint_view", fail_checkpoint)
|
||||
loop.runner.run = AsyncMock(wraps=loop.runner.run)
|
||||
try:
|
||||
await run_session(loop, InboundMessage(
|
||||
channel="websocket", sender_id="user", chat_id="goal-save-fail", content="Continue",
|
||||
metadata={"webui": True, "webui_turn_id": "save-fail-turn"},
|
||||
))
|
||||
events = []
|
||||
while not bus.outbound.empty():
|
||||
events.append(bus.outbound.get_nowait())
|
||||
endings = [m.event for m in events if isinstance(m.event, TurnEndEvent)]
|
||||
assert len(endings) == 1 and endings[0].outcome == "failed"
|
||||
assert [m.event.status for m in events if isinstance(m.event, GoalStatusEvent)] == ["running", "idle"]
|
||||
assert provider.chat_stream_with_retry.await_count == 3
|
||||
loop.runner.run.assert_awaited_once()
|
||||
assert session.key not in loop._pending_queues
|
||||
saved = await loop.sessions.state.read(session.key)
|
||||
assert saved.metadata[GOAL_STATE_KEY]["status"] == "active"
|
||||
finally:
|
||||
await loop.aclose()
|
||||
|
||||
|
||||
async def test_active_goal_keeps_candidate_history_until_successful_closure(tmp_path):
|
||||
from agent.session_helpers import run_session
|
||||
|
||||
bus = MessageBus()
|
||||
provider = MagicMock(aclose=AsyncMock())
|
||||
provider.get_default_model.return_value = "test-model"
|
||||
provider.generation = GenerationSettings()
|
||||
provider.estimate_prompt_tokens.return_value = (100, "test")
|
||||
provider.can_resume_conversation_state.return_value = True
|
||||
state = ProviderConversationState(
|
||||
kind="openai_responses", provider="openai:test", model="test-model", version=1,
|
||||
payload={"items": [{"type": "reasoning", "encrypted_content": "private-goal-state"}]},
|
||||
)
|
||||
usage = LLMUsage(input_tokens=10, output_tokens=5, total_tokens=15, reported_tokens=15)
|
||||
entered, release = asyncio.Event(), asyncio.Event()
|
||||
calls = []
|
||||
|
||||
async def respond(**kwargs):
|
||||
calls.append(kwargs)
|
||||
if len(calls) > 1:
|
||||
resumed = kwargs["provider_context"].conversation_state
|
||||
assert resumed is not None and resumed.payload == state.payload
|
||||
assert any(row.get("content") == "Evidence 1 recorded." for row in kwargs["messages"])
|
||||
if len(calls) <= 16:
|
||||
assert any("Please continue working toward the objective" in str(row.get("content"))
|
||||
for row in resumed.pending_messages)
|
||||
else:
|
||||
assert any(row.get("tool_call_id") == "close" for row in resumed.pending_messages)
|
||||
if len(calls) <= 15:
|
||||
assert kwargs.get("tools")
|
||||
return LLMResponse(content=f"Evidence {len(calls)} recorded.", usage=usage, provider_state=state)
|
||||
if len(calls) == 16:
|
||||
assert kwargs.get("tools")
|
||||
entered.set()
|
||||
await release.wait()
|
||||
return LLMResponse(content=None, usage=usage, provider_state=state, tool_calls=[ToolCallRequest(
|
||||
id="close", name="update_goal", arguments={"action": "complete", "recap": "Evidence reviewed."},
|
||||
)])
|
||||
assert len(calls) == 17 and not kwargs.get("tools")
|
||||
return LLMResponse(content="Evidence reviewed.", usage=usage, provider_state=state)
|
||||
|
||||
provider.chat_stream_with_retry = AsyncMock(side_effect=respond)
|
||||
loop = _assembled_loop(bus=bus, provider=provider, workspace=tmp_path,
|
||||
model="test-model", max_iterations=1)
|
||||
loop.runner.run = AsyncMock(wraps=loop.runner.run)
|
||||
loop._process_message = AsyncMock(wraps=loop._process_message)
|
||||
WebuiTurnCoordinator(
|
||||
bus=bus, sessions=loop.sessions,
|
||||
schedule_background=lambda coro: loop.schedule_background(coro),
|
||||
).subscribe()
|
||||
session = await loop.sessions.state.get("websocket:goal-limit")
|
||||
await loop.sessions.state.update_metadata(session.key, {
|
||||
GOAL_STATE_KEY: {"status": "active", "objective": "Keep investigating."},
|
||||
"webui": True, "title": "Goal", "title_user_edited": True,
|
||||
})
|
||||
run = asyncio.create_task(run_session(loop, InboundMessage(
|
||||
channel="websocket", sender_id="user", chat_id="goal-limit", content="/goal Keep investigating.",
|
||||
metadata={"webui": True, "webui_turn_id": "goal-turn"},
|
||||
)))
|
||||
try:
|
||||
await asyncio.wait_for(entered.wait(), 5)
|
||||
events = []
|
||||
while not bus.outbound.empty():
|
||||
events.append(bus.outbound.get_nowait())
|
||||
assert [m.event.status for m in events if isinstance(m.event, GoalStatusEvent)] == ["running"]
|
||||
assert not any(isinstance(m.event, TurnEndEvent) for m in events)
|
||||
release.set()
|
||||
await asyncio.wait_for(run, 5)
|
||||
while not bus.outbound.empty():
|
||||
events.append(bus.outbound.get_nowait())
|
||||
statuses = [m.event for m in events if isinstance(m.event, GoalStatusEvent)]
|
||||
assert [event.status for event in statuses] == ["running", "idle"]
|
||||
assert statuses[0].started_at is not None
|
||||
endings = [m.event for m in events if isinstance(m.event, TurnEndEvent)]
|
||||
assert len(endings) == 1 and endings[0].outcome == "completed"
|
||||
assert isinstance(endings[0].latency_ms, int)
|
||||
assert endings[0].usage is not None and endings[0].usage.total_tokens == 255
|
||||
assert len(endings[0].round_usages) == 17
|
||||
assert len(calls) == 17
|
||||
loop.runner.run.assert_awaited_once()
|
||||
loop._process_message.assert_awaited_once()
|
||||
saved = await loop.sessions.state.read(session.key)
|
||||
assert saved.metadata[GOAL_STATE_KEY]["status"] == "completed"
|
||||
assert saved.provider_state is not None and saved.provider_state.payload == state.payload
|
||||
visible = public_history_messages([row for row in saved.messages if not is_hidden_history_message(row)])
|
||||
assert [row["content"] for row in visible if row["role"] == "user"] == ["/goal Keep investigating."]
|
||||
for number in range(1, 16):
|
||||
assert sum(row.get("content") == f"Evidence {number} recorded." for row in visible) == 1
|
||||
assert sum(row.get("content") == "Evidence reviewed." for row in visible) == 1
|
||||
assert visible[-1]["content"] == "Evidence reviewed."
|
||||
assert [row["tool_call_id"] for row in saved.messages if row["role"] == "tool"] == ["close"]
|
||||
assert sum(row.get("_hidden_history") == {"kind": "internal_continuation"} for row in saved.messages) == 15
|
||||
assert "private-goal-state" not in str(visible)
|
||||
assert session.key not in loop._pending_queues
|
||||
finally:
|
||||
release.set()
|
||||
if not run.done():
|
||||
await loop._cancel_active_tasks(session.key)
|
||||
await asyncio.gather(run, return_exceptions=True)
|
||||
await loop.aclose()
|
||||
|
||||
|
||||
async def test_replaced_goal_uses_current_objective_for_same_run_prompt(tmp_path):
|
||||
from agent.session_helpers import run_session
|
||||
|
||||
provider = MagicMock(aclose=AsyncMock())
|
||||
provider.get_default_model.return_value = "test-model"
|
||||
provider.generation = GenerationSettings()
|
||||
provider.estimate_prompt_tokens.return_value = (100, "test")
|
||||
loop = _assembled_loop(bus=MessageBus(), provider=provider, workspace=tmp_path,
|
||||
model="test-model", max_iterations=1)
|
||||
session = await loop.sessions.state.get("cli:replacement")
|
||||
await loop.sessions.state.update_metadata(session.key, {
|
||||
GOAL_STATE_KEY: {"status": "active", "objective": "Old objective."},
|
||||
})
|
||||
calls = []
|
||||
replacement = InboundMessage(
|
||||
channel="cli", sender_id="user", chat_id="replacement", content="/goal New objective.",
|
||||
)
|
||||
|
||||
async def respond(**kwargs):
|
||||
calls.append(kwargs)
|
||||
if len(calls) == 1:
|
||||
await loop._dispatch_command_inline(
|
||||
replacement, replacement.session_key, replacement.content, loop.commands.dispatch,
|
||||
)
|
||||
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||
id="list", name="list_dir", arguments={"path": "."},
|
||||
)])
|
||||
if len(calls) == 2:
|
||||
assert goal_mutation_allowed()
|
||||
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||
id="replace", name="update_goal", arguments={"action": "replace", "objective": "New objective."},
|
||||
)])
|
||||
if len(calls) == 3:
|
||||
return LLMResponse(content="The replacement objective needs one more check.")
|
||||
if len(calls) == 4:
|
||||
prompts = [
|
||||
message["content"] for message in kwargs["messages"]
|
||||
if is_hidden_history_message(message) and message.get("role") == "user"
|
||||
]
|
||||
assert prompts and "New objective." in prompts[-1] and "Old objective." not in prompts[-1]
|
||||
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||
id="complete", name="update_goal", arguments={"action": "complete", "recap": "Done."},
|
||||
)])
|
||||
return LLMResponse(content="Done.")
|
||||
|
||||
provider.chat_stream_with_retry = AsyncMock(side_effect=respond)
|
||||
try:
|
||||
await run_session(loop, InboundMessage(
|
||||
channel="cli", sender_id="user", chat_id="replacement", content="Continue the old objective.",
|
||||
))
|
||||
assert len(calls) == 5
|
||||
saved = await loop.sessions.state.read(session.key)
|
||||
assert saved.metadata[GOAL_STATE_KEY]["objective"] == "New objective."
|
||||
assert saved.metadata[GOAL_STATE_KEY]["status"] == "completed"
|
||||
visible = public_history_messages([row for row in saved.messages if not is_hidden_history_message(row)])
|
||||
assert sum(row.get("content") == replacement.content for row in visible) == 1
|
||||
finally:
|
||||
await loop.aclose()
|
||||
|
||||
|
||||
async def test_failed_goal_completion_keeps_running_until_a_successful_block(tmp_path, monkeypatch):
|
||||
provider = MagicMock(aclose=AsyncMock())
|
||||
provider.get_default_model.return_value = "test-model"
|
||||
provider.generation = GenerationSettings()
|
||||
provider.estimate_prompt_tokens.return_value = (100, "test")
|
||||
provider.chat_stream_with_retry = AsyncMock(side_effect=[
|
||||
LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||
id="complete", name="update_goal", arguments={"action": "complete", "recap": "Done."},
|
||||
)]),
|
||||
LLMResponse(content="The task is done."),
|
||||
LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||
id="block", name="update_goal", arguments={"action": "block", "recap": "Save failed."},
|
||||
)]),
|
||||
LLMResponse(content="The goal is blocked."),
|
||||
])
|
||||
loop = _assembled_loop(bus=MessageBus(), provider=provider, workspace=tmp_path,
|
||||
model="test-model", max_iterations=4)
|
||||
session = await loop.sessions.state.get("cli:failed-goal-update")
|
||||
await loop.sessions.state.update_metadata(session.key, {
|
||||
GOAL_STATE_KEY: {"status": "active", "objective": "Verify the task."},
|
||||
})
|
||||
replace_metadata = loop.sessions._store.replace_metadata
|
||||
|
||||
def fail_completion(key, metadata, **kwargs):
|
||||
if metadata.get(GOAL_STATE_KEY, {}).get("status") == "completed":
|
||||
raise OSError("synthetic goal commit failure")
|
||||
return replace_metadata(key, metadata, **kwargs)
|
||||
|
||||
monkeypatch.setattr(loop.sessions._store, "replace_metadata", fail_completion)
|
||||
try:
|
||||
result = await loop.process_direct("Continue", session_key=session.key)
|
||||
assert result.content == "The goal is blocked."
|
||||
assert provider.chat_stream_with_retry.await_count == 4
|
||||
calls = provider.chat_stream_with_retry.await_args_list
|
||||
assert "synthetic goal commit failure" in str(calls[1].kwargs["messages"])
|
||||
assert "Please continue working toward the objective" in str(calls[2].kwargs["messages"])
|
||||
saved = await loop.sessions.state.read(session.key)
|
||||
assert saved.metadata[GOAL_STATE_KEY]["status"] == "blocked"
|
||||
finally:
|
||||
await loop.aclose()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("operation", ["reset", "delete"])
|
||||
async def test_queued_goal_command_does_not_write_to_an_obsolete_generation(tmp_path, operation):
|
||||
from nanobot.session.sqlite_store import SessionConflictError
|
||||
|
||||
provider = MagicMock(aclose=AsyncMock())
|
||||
provider.get_default_model.return_value = "test-model"
|
||||
provider.generation = GenerationSettings()
|
||||
loop = _assembled_loop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model")
|
||||
key = "websocket:old-goal-command"
|
||||
session = await loop.sessions.state.get(key)
|
||||
message = InboundMessage(
|
||||
channel="websocket", sender_id="user", chat_id="old-goal-command", content="/goal Old task",
|
||||
session_generation=session.generation, require_existing_session=True,
|
||||
)
|
||||
try:
|
||||
if operation == "reset":
|
||||
await loop.sessions.state.reset(key)
|
||||
else:
|
||||
assert await loop.sessions.state.delete(key)
|
||||
with pytest.raises(SessionConflictError):
|
||||
await loop._dispatch_command_inline(message, key, message.content, loop.commands.dispatch)
|
||||
current = await loop.sessions.state.read(key)
|
||||
if operation == "delete":
|
||||
assert current is None
|
||||
else:
|
||||
assert current is not None and current.generation != session.generation
|
||||
assert current.messages == []
|
||||
assert key not in loop._pending_queues
|
||||
finally:
|
||||
await loop.aclose()
|
||||
@@ -864,7 +864,7 @@ async def test_runner_does_not_auto_continue_goal_after_policy_terminal(
|
||||
model="test-model",
|
||||
max_iterations=3,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
continuation_callback=AsyncMock(return_value="Continue working."),
|
||||
continuation_callback=AsyncMock(return_value="Continue the goal."),
|
||||
terminal_injection_callback=terminal_injection_callback,
|
||||
))
|
||||
|
||||
@@ -1005,6 +1005,7 @@ async def test_runner_length_recovery_preserves_prefix_at_max_iterations():
|
||||
max_iterations_message="limit reached",
|
||||
))
|
||||
|
||||
assert provider.chat_stream_with_retry.await_count == 1
|
||||
assert result.stop_reason == "max_iterations"
|
||||
assert result.final_content == "partial answer\n\nlimit reached"
|
||||
assert result.pending_stream_content == "\n\nlimit reached"
|
||||
|
||||
@@ -3,17 +3,27 @@ from unittest.mock import AsyncMock, MagicMock
|
||||
import pytest
|
||||
|
||||
from agent.runner_helpers import make_run_spec
|
||||
from nanobot.agent.hook import AgentHook
|
||||
from nanobot.agent.runner import AgentRunner
|
||||
from nanobot.config.schema import AgentDefaults
|
||||
from nanobot.providers.base import LLMProvider, LLMResponse
|
||||
from nanobot.providers.base import (
|
||||
LLMProvider,
|
||||
LLMResponse,
|
||||
LLMUsage,
|
||||
ProviderConversationState,
|
||||
ToolCallRequest,
|
||||
)
|
||||
from nanobot.utils.runtime import EMPTY_FINAL_RESPONSE_MESSAGE
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def run_spec():
|
||||
provider = MagicMock(spec=LLMProvider)
|
||||
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="all done"))
|
||||
provider.supports_native_compaction.return_value = False
|
||||
tools = MagicMock()
|
||||
tools.get_definitions.return_value = []
|
||||
tools.execute = AsyncMock(return_value="tool result")
|
||||
return make_run_spec(
|
||||
provider,
|
||||
initial_messages=[{"role": "user", "content": "do task"}],
|
||||
@@ -27,66 +37,265 @@ def run_spec():
|
||||
@pytest.mark.parametrize("callback", [None, AsyncMock(return_value=None)], ids=["absent", "no-request"])
|
||||
async def test_runner_completes_without_a_continuation_request(run_spec, callback):
|
||||
run_spec.continuation_callback = callback
|
||||
|
||||
result = await AgentRunner().run(run_spec)
|
||||
|
||||
assert result.stop_reason == "completed"
|
||||
assert result.final_content == "all done"
|
||||
assert run_spec.runtime.provider.chat_stream_with_retry.await_count == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("max_iterations,finalize", [(1, True), (3, True), (8, False)])
|
||||
async def test_continuation_injects_text_without_exceeding_budget(run_spec, max_iterations, finalize):
|
||||
continuation = "Continue working toward the active sustained goal."
|
||||
run_spec.max_iterations = max_iterations
|
||||
run_spec.finalize_on_max_iterations = finalize
|
||||
run_spec.continuation_callback = AsyncMock(side_effect=lambda: continuation)
|
||||
async def test_continuation_extends_budget_without_reset(run_spec):
|
||||
run_spec.max_iterations = 1
|
||||
total_rounds = 14
|
||||
calls = 0
|
||||
|
||||
async def respond(**kwargs):
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
if calls > 1:
|
||||
assert kwargs["messages"][-1]["content"] == f"Continue goal step {calls - 1}."
|
||||
return LLMResponse(
|
||||
content="all done" if calls == total_rounds else f"Progress {calls}.",
|
||||
usage=LLMUsage.reported(input_tokens=1, output_tokens=1),
|
||||
)
|
||||
|
||||
async def continuation():
|
||||
return f"Continue goal step {calls}." if calls < total_rounds else None
|
||||
|
||||
run_spec.runtime.provider.chat_stream_with_retry.side_effect = respond
|
||||
run_spec.continuation_callback = AsyncMock(side_effect=continuation)
|
||||
run_spec.hook = AgentHook()
|
||||
run_spec.hook.before_iteration = AsyncMock()
|
||||
|
||||
result = await AgentRunner().run(run_spec)
|
||||
|
||||
assert result.stop_reason == "max_iterations"
|
||||
requests = run_spec.runtime.provider.chat_stream_with_retry.await_args_list
|
||||
assert len(requests) == max_iterations + int(finalize)
|
||||
assert {"role": "user", "content": continuation} in result.messages
|
||||
if max_iterations > 1:
|
||||
assert {"role": "user", "content": continuation} in requests[1].kwargs["messages"]
|
||||
if finalize:
|
||||
assert not requests[-1].kwargs.get("tools")
|
||||
assert result.stop_reason == "completed"
|
||||
assert result.final_content == "all done"
|
||||
assert result.had_injections is True
|
||||
assert calls == total_rounds
|
||||
assert run_spec.continuation_callback.await_count == total_rounds
|
||||
assert [
|
||||
call.args[0].iteration for call in run_spec.hook.before_iteration.await_args_list
|
||||
] == list(range(total_rounds))
|
||||
continuations = [row for row in result.messages if row.get("_hidden_history")]
|
||||
assert len(continuations) == total_rounds - 1
|
||||
assert all(row["_hidden_history"] == {"kind": "internal_continuation"} for row in continuations)
|
||||
assert len(result.round_usages) == total_rounds
|
||||
assert result.usage.request_count == total_rounds
|
||||
assert result.usage.total_tokens == total_rounds * 2
|
||||
|
||||
|
||||
async def test_runner_does_not_request_continuation_on_error(run_spec):
|
||||
run_spec.runtime.provider.chat_stream_with_retry.return_value = LLMResponse(
|
||||
content=None, finish_reason="error",
|
||||
)
|
||||
@pytest.mark.parametrize("finalize,finalization_fails", [(True, False), (False, False), (True, True)])
|
||||
async def test_goal_closing_after_tool_overrun_gets_bounded_finalization(run_spec, finalize, finalization_fails):
|
||||
run_spec.max_iterations = 1
|
||||
run_spec.finalize_on_max_iterations = finalize
|
||||
run_spec.max_iterations_message = "limit reached"
|
||||
goal_active = True
|
||||
tool_rounds = 14
|
||||
completed_tools = 0
|
||||
|
||||
async def respond(**kwargs):
|
||||
if goal_active:
|
||||
assert kwargs["tools"] is not None
|
||||
return LLMResponse(
|
||||
content=None,
|
||||
tool_calls=[ToolCallRequest(id=f"work-{completed_tools}", name="work", arguments={})],
|
||||
usage=LLMUsage.reported(input_tokens=1, output_tokens=1),
|
||||
)
|
||||
assert kwargs["tools"] is None
|
||||
assert kwargs["messages"][-2]["content"] == "goal completed"
|
||||
assert kwargs["messages"][-1]["content"] == (
|
||||
"Please provide your response to the user based on the conversation above."
|
||||
)
|
||||
return LLMResponse(
|
||||
content="Provider unavailable." if finalization_fails else "All goal work is complete.",
|
||||
finish_reason="error" if finalization_fails else "stop",
|
||||
usage=LLMUsage.reported(input_tokens=2, output_tokens=3),
|
||||
)
|
||||
|
||||
async def execute(*_args, **_kwargs):
|
||||
nonlocal goal_active, completed_tools
|
||||
completed_tools += 1
|
||||
goal_active = completed_tools < tool_rounds
|
||||
return "work completed" if goal_active else "goal completed"
|
||||
|
||||
async def continuation():
|
||||
return "Continue the goal." if goal_active else None
|
||||
|
||||
run_spec.runtime.provider.chat_stream_with_retry.side_effect = respond
|
||||
run_spec.tools.execute.side_effect = execute
|
||||
run_spec.continuation_callback = AsyncMock(side_effect=continuation)
|
||||
run_spec.hook = AgentHook()
|
||||
run_spec.hook.finalize_content = MagicMock(side_effect=lambda _context, content: content)
|
||||
|
||||
result = await AgentRunner().run(run_spec)
|
||||
|
||||
assert completed_tools == tool_rounds
|
||||
assert result.tools_used == ["work"] * tool_rounds
|
||||
if finalization_fails:
|
||||
assert result.stop_reason == "empty_final_response"
|
||||
assert result.error == result.final_content == EMPTY_FINAL_RESPONSE_MESSAGE
|
||||
else:
|
||||
assert result.stop_reason == ("completed" if finalize else "max_iterations")
|
||||
assert result.final_content == ("All goal work is complete." if finalize else "limit reached")
|
||||
assert result.pending_stream_content == (result.final_content if finalize else None)
|
||||
assert result.messages[-1]["content"] == result.final_content
|
||||
assert run_spec.runtime.provider.chat_stream_with_retry.await_count == tool_rounds + int(finalize)
|
||||
assert run_spec.continuation_callback.await_count == tool_rounds
|
||||
assert result.usage.request_count == tool_rounds + int(finalize)
|
||||
assert len(result.round_usages) == tool_rounds + int(finalize)
|
||||
if finalize and not finalization_fails:
|
||||
assert run_spec.hook.finalize_content.call_args.args[0].iteration == tool_rounds
|
||||
|
||||
|
||||
@pytest.mark.parametrize("finish_reason", ["error", "refusal", "content_filter"])
|
||||
@pytest.mark.parametrize("tool_name", ["work", ""], ids=["valid-call", "malformed-call"])
|
||||
async def test_runner_does_not_auto_continue_terminal_provider_response(run_spec, finish_reason, tool_name):
|
||||
run_spec.max_iterations = 1
|
||||
run_spec.runtime.provider.chat_stream_with_retry.side_effect = [
|
||||
LLMResponse(
|
||||
content="Provider stopped this request.", finish_reason=finish_reason,
|
||||
tool_calls=[ToolCallRequest(id="blocked", name=tool_name, arguments={})],
|
||||
),
|
||||
AssertionError("terminal response must not trigger another model request"),
|
||||
]
|
||||
callback = AsyncMock(return_value="Continue working.")
|
||||
run_spec.continuation_callback = callback
|
||||
|
||||
result = await AgentRunner().run(run_spec)
|
||||
|
||||
assert result.stop_reason == "error"
|
||||
assert result.stop_reason == ("error" if finish_reason == "error" else "completed")
|
||||
assert result.final_content == "Provider stopped this request."
|
||||
assert run_spec.runtime.provider.chat_stream_with_retry.await_count == 1
|
||||
callback.assert_not_called()
|
||||
run_spec.tools.execute.assert_not_awaited()
|
||||
callback.assert_not_awaited()
|
||||
|
||||
|
||||
async def test_runner_reads_continuation_state_after_each_response(run_spec):
|
||||
continuation = None
|
||||
calls = 0
|
||||
@pytest.mark.parametrize("response_kind", ["text", "tool"])
|
||||
async def test_real_followup_precedes_goal_at_iteration_cap(run_spec, response_kind):
|
||||
followup = {"role": "user", "content": "Stop the goal and answer this instead."}
|
||||
pending = []
|
||||
goal_active = True
|
||||
requests = []
|
||||
run_spec.max_iterations = 1
|
||||
|
||||
async def respond(**kwargs):
|
||||
nonlocal continuation, calls
|
||||
calls += 1
|
||||
if calls == 1:
|
||||
continuation = "Write the article draft."
|
||||
return LLMResponse(content="The goal is now active.")
|
||||
assert {"role": "user", "content": continuation} in kwargs["messages"]
|
||||
continuation = None
|
||||
return LLMResponse(content="The draft is complete.")
|
||||
requests.append(kwargs["messages"])
|
||||
if len(requests) == 1:
|
||||
pending.append(followup)
|
||||
return (
|
||||
LLMResponse(content="Goal checkpoint.") if response_kind == "text" else
|
||||
LLMResponse(content=None, tool_calls=[
|
||||
ToolCallRequest(id="work", name="work", arguments={}),
|
||||
])
|
||||
)
|
||||
assert kwargs["messages"][-1] == followup
|
||||
assert not goal_active
|
||||
return LLMResponse(content="Follow-up answered.")
|
||||
|
||||
async def drain():
|
||||
nonlocal goal_active
|
||||
batch = list(pending)
|
||||
pending.clear()
|
||||
if batch:
|
||||
goal_active = False
|
||||
return batch
|
||||
|
||||
async def continuation():
|
||||
return "Continue the goal." if goal_active else None
|
||||
|
||||
run_spec.runtime.provider.chat_stream_with_retry.side_effect = respond
|
||||
run_spec.continuation_callback = AsyncMock(side_effect=lambda: continuation)
|
||||
run_spec.injection_callback = drain
|
||||
run_spec.continuation_callback = continuation
|
||||
result = await AgentRunner().run(run_spec)
|
||||
|
||||
assert len(requests) == 2
|
||||
assert pending == []
|
||||
assert result.stop_reason == "completed"
|
||||
assert result.final_content == "Follow-up answered."
|
||||
assert result.had_injections is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize("response_kind", ["text", "tool"])
|
||||
async def test_runner_propagates_continuation_failure(run_spec, response_kind):
|
||||
run_spec.max_iterations = 1
|
||||
if response_kind == "tool":
|
||||
run_spec.runtime.provider.chat_stream_with_retry.return_value = LLMResponse(
|
||||
content=None, tool_calls=[ToolCallRequest(id="work", name="work", arguments={})],
|
||||
)
|
||||
run_spec.continuation_callback = AsyncMock(side_effect=RuntimeError("goal lookup failed"))
|
||||
with pytest.raises(RuntimeError, match="goal lookup failed"):
|
||||
await AgentRunner().run(run_spec)
|
||||
assert run_spec.runtime.provider.chat_stream_with_retry.await_count == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("response_kind", ["text", "tool"])
|
||||
async def test_continuation_preserves_transcript_checkpoints_and_provider_state(run_spec, tmp_path, response_kind):
|
||||
from nanobot.agent.tools.filesystem import ListDirTool
|
||||
from nanobot.agent.tools.registry import ToolRegistry
|
||||
|
||||
(tmp_path / "evidence.txt").write_text("evidence", encoding="utf-8")
|
||||
tools = ToolRegistry()
|
||||
tools.register(ListDirTool(workspace=tmp_path, allowed_dir=tmp_path))
|
||||
run_spec.tools = tools
|
||||
run_spec.max_iterations = 1
|
||||
state = ProviderConversationState(
|
||||
kind="openai_responses", provider="openai:test", model="test-model",
|
||||
version=1, payload={"items": []},
|
||||
)
|
||||
final_state = ProviderConversationState(
|
||||
kind="openai_responses", provider="openai:test", model="test-model",
|
||||
version=1, payload={"items": [{"type": "message", "role": "assistant"}]},
|
||||
)
|
||||
run_spec.runtime.provider.can_resume_conversation_state.return_value = True
|
||||
goal_active = True
|
||||
requests = []
|
||||
|
||||
async def respond(**kwargs):
|
||||
nonlocal goal_active
|
||||
requests.append(kwargs)
|
||||
if len(requests) == 1:
|
||||
return (
|
||||
LLMResponse(content="Observed evidence.", provider_state=state)
|
||||
if response_kind == "text" else
|
||||
LLMResponse(content=None, provider_state=state, tool_calls=[
|
||||
ToolCallRequest(id="list", name="list_dir", arguments={"path": "."}),
|
||||
])
|
||||
)
|
||||
goal_active = False
|
||||
return LLMResponse(content="Final evidence summary.", provider_state=final_state)
|
||||
|
||||
async def continuation():
|
||||
return "Continue." if goal_active else None
|
||||
|
||||
run_spec.runtime.provider.chat_stream_with_retry.side_effect = respond
|
||||
run_spec.continuation_callback = continuation
|
||||
run_spec.checkpoint_callback = AsyncMock()
|
||||
run_spec.hook = AgentHook()
|
||||
run_spec.hook.wants_streaming = MagicMock(return_value=True)
|
||||
run_spec.hook.on_stream_end = AsyncMock()
|
||||
|
||||
result = await AgentRunner().run(run_spec)
|
||||
|
||||
assert calls == 2
|
||||
assert result.stop_reason == "completed"
|
||||
assert result.final_content == "The draft is complete."
|
||||
assert result.final_content == "Final evidence summary."
|
||||
assert len(requests) == 2
|
||||
assert [call.kwargs["resuming"] for call in run_spec.hook.on_stream_end.await_args_list] == [True, False]
|
||||
checkpoint = run_spec.checkpoint_callback.await_args.args[0]
|
||||
assert checkpoint["phase"] == "final_response"
|
||||
assert checkpoint["iteration"] == 1
|
||||
assert checkpoint["assistant_message"] == result.messages[-1]
|
||||
assert checkpoint["preceding_messages"] == result.messages[1:-1]
|
||||
assert checkpoint["provider_state"] == result.provider_state
|
||||
assert result.provider_state is not None
|
||||
assert result.provider_state.payload == final_state.payload
|
||||
assert result.provider_state.pending_messages == []
|
||||
resumed_state = requests[1]["provider_context"].conversation_state
|
||||
assert resumed_state.payload == state.payload
|
||||
if response_kind == "text":
|
||||
assert resumed_state.pending_messages == [{
|
||||
"role": "user", "content": "Continue.",
|
||||
"_hidden_history": {"kind": "internal_continuation"},
|
||||
}]
|
||||
else:
|
||||
assert resumed_state.pending_messages[0]["role"] == "tool"
|
||||
assert "evidence.txt" in resumed_state.pending_messages[0]["content"]
|
||||
@@ -379,7 +379,7 @@ async def test_goal_continuation_precedes_terminal_wait():
|
||||
continuation_checks = 0
|
||||
terminal_waits = 0
|
||||
|
||||
async def continue_goal() -> str | None:
|
||||
async def continue_goal():
|
||||
nonlocal continuation_checks
|
||||
continuation_checks += 1
|
||||
return "Continue the active goal." if continuation_checks == 1 else None
|
||||
@@ -1599,7 +1599,7 @@ async def test_busy_session_burst_reaches_next_model_call_as_one_ordered_batch(
|
||||
if log_content else "[content hidden]"
|
||||
)
|
||||
assert record["message"] == (
|
||||
f"Injected {len(followups)} follow-up message(s) after final response (snapshot 1): {preview}"
|
||||
f"Injected {len(followups)} follow-up message(s) after final response: {preview}"
|
||||
)
|
||||
assert record["level"].name == "INFO"
|
||||
assert record["extra"]["session_key"] == "cli:c"
|
||||
|
||||
@@ -4,19 +4,22 @@ from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from agent.session_helpers import run_session, stop_loop
|
||||
from agent.session_helpers import run_session, stop_loop, visible_message
|
||||
from nanobot.agent.automation_turns import AutomationTurnError
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.agent.tools.context import current_request_context
|
||||
from nanobot.agent.tools.cron import CronTool
|
||||
from nanobot.bus.events import InboundMessage, OutboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.bus.runtime_events import TurnCompleted
|
||||
from nanobot.cron.service import CronService
|
||||
from nanobot.cron.session_turns import CRON_DEFER_UNTIL_IDLE_META, CRON_TRIGGER_META
|
||||
from nanobot.providers.base import GenerationSettings, LLMResponse, ToolCallRequest
|
||||
from nanobot.goal.assembly import install_goal
|
||||
from nanobot.providers.base import GenerationSettings, LLMResponse, LLMUsage, ToolCallRequest
|
||||
from nanobot.runtime_context import public_history_messages
|
||||
from nanobot.session.automation_turns import AUTOMATION_HISTORY_META
|
||||
from nanobot.session.goal_state import GOAL_STATE_KEY
|
||||
from nanobot.session.history_visibility import is_hidden_history_message
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.recovery import (
|
||||
PENDING_FOLLOWUPS_KEY,
|
||||
@@ -36,6 +39,7 @@ async def loop(tmp_path):
|
||||
provider.estimate_prompt_tokens.return_value = (100, "test")
|
||||
agent = AgentLoop(
|
||||
bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model",
|
||||
builtin_assembly=install_goal,
|
||||
)
|
||||
agent.tools.get_definitions = MagicMock(return_value=[])
|
||||
try:
|
||||
@@ -592,7 +596,7 @@ async def test_cron_restriction_follows_the_current_turn(loop, tmp_path, start_w
|
||||
|
||||
|
||||
@pytest.mark.parametrize("complete_on_followup", [False, True])
|
||||
async def test_goal_continuation_after_followup_keeps_control_identity(loop, complete_on_followup):
|
||||
async def test_active_goal_prioritizes_real_followup_before_internal_prompt(loop, complete_on_followup):
|
||||
loop.max_iterations = 1
|
||||
loop.tools.prepare_call = MagicMock(return_value=(None, {}, None))
|
||||
loop.tools.execute = AsyncMock(return_value="ok")
|
||||
@@ -612,15 +616,14 @@ async def test_goal_continuation_after_followup_keeps_control_identity(loop, com
|
||||
await asyncio.sleep(0)
|
||||
elif complete_on_followup or len(requests) == 3:
|
||||
await loop.sessions.state.update_metadata(session.key, {
|
||||
GOAL_STATE_KEY: {"status": "complete", "objective": "Finish the long goal"},
|
||||
GOAL_STATE_KEY: {"status": "completed", "objective": "Finish the long goal"},
|
||||
})
|
||||
return LLMResponse(content="done")
|
||||
return LLMResponse(
|
||||
content="working", finish_reason="tool_calls",
|
||||
tool_calls=[ToolCallRequest(id=f"call-{len(requests)}", name="noop", arguments={})],
|
||||
)
|
||||
assert len(requests) <= 3
|
||||
return LLMResponse(content="One more check is needed.")
|
||||
|
||||
loop.provider.chat_stream_with_retry = chat
|
||||
loop.runner.run = AsyncMock(wraps=loop.runner.run)
|
||||
run_task = asyncio.create_task(loop.run())
|
||||
try:
|
||||
await loop.bus.publish_inbound(InboundMessage(
|
||||
@@ -630,12 +633,15 @@ async def test_goal_continuation_after_followup_keeps_control_identity(loop, com
|
||||
while not requests or "cli:test" in loop._pending_queues:
|
||||
await asyncio.sleep(0.01)
|
||||
assert len(requests) == (2 if complete_on_followup else 3)
|
||||
continuation_text = "Continue the active sustained goal after the previous turn"
|
||||
assert continuation_text not in str(requests[1])
|
||||
assert visible_message(requests[1][-1])["content"] == "Inspect file B first"
|
||||
if not complete_on_followup:
|
||||
assert continuation_text in str(requests[2])
|
||||
assert is_hidden_history_message(requests[2][-1])
|
||||
assert "Please continue working toward the objective" in requests[2][-1]["content"]
|
||||
loop.runner.run.assert_awaited_once()
|
||||
loop.sessions.invalidate("cli:test")
|
||||
history = public_history_messages(loop.sessions.get_or_create("cli:test").messages)
|
||||
history = public_history_messages([
|
||||
row for row in loop.sessions.get_or_create("cli:test").messages if not is_hidden_history_message(row)
|
||||
])
|
||||
assert [message["content"] for message in history if message["role"] == "user"] == [
|
||||
"Start the goal", "Inspect file B first",
|
||||
]
|
||||
@@ -644,7 +650,7 @@ async def test_goal_continuation_after_followup_keeps_control_identity(loop, com
|
||||
await asyncio.wait_for(run_task, timeout=3)
|
||||
|
||||
|
||||
async def test_queued_continuation_keeps_its_origin_after_another_chat_runs(loop):
|
||||
async def test_active_goal_keeps_origin_until_queued_independent_command_runs(loop):
|
||||
loop._unified_session = True
|
||||
loop.max_iterations = 1
|
||||
loop.tools.prepare_call = MagicMock(return_value=(None, {}, None))
|
||||
@@ -654,15 +660,21 @@ async def test_queued_continuation_keeps_its_origin_after_another_chat_runs(loop
|
||||
session.metadata[GOAL_STATE_KEY] = {"status": "active", "objective": "Finish the goal"}
|
||||
loop.sessions.save(session)
|
||||
requests = []
|
||||
completed = []
|
||||
loop.bus.subscribe(completed.append, TurnCompleted)
|
||||
loop.consolidator.compact_idle_session = AsyncMock()
|
||||
loop.runner.run = AsyncMock(wraps=loop.runner.run)
|
||||
persisted_origin = None
|
||||
|
||||
async def chat(**kwargs):
|
||||
nonlocal persisted_origin
|
||||
context = current_request_context()
|
||||
requests.append((context.chat_id, context.message_id, context.turn_id))
|
||||
tokens = len(requests) * 10
|
||||
usage = LLMUsage(input_tokens=tokens, output_tokens=0, total_tokens=tokens, reported_tokens=tokens)
|
||||
if len(requests) == 1:
|
||||
await loop.bus.publish_inbound(InboundMessage(
|
||||
channel="feishu", sender_id="user", chat_id="chat-b", content="Inspect B first",
|
||||
channel="feishu", sender_id="user", chat_id="chat-b", content="/compact",
|
||||
metadata={"message_id": "message-b"},
|
||||
))
|
||||
async with asyncio.timeout(3):
|
||||
@@ -671,12 +683,13 @@ async def test_queued_continuation_keeps_its_origin_after_another_chat_runs(loop
|
||||
elif len(requests) == 3:
|
||||
persisted = SessionManager(loop.workspace).get_or_create(key)
|
||||
persisted_origin = persisted.metadata[REQUEST_ORIGIN_METADATA_KEY]
|
||||
await loop.tools.get("message").execute(content="Continuation reply")
|
||||
loop.consolidator.compact_idle_session.assert_not_awaited()
|
||||
await loop.tools.get("message").execute(content="Goal reply")
|
||||
await loop.sessions.state.mutate_metadata(
|
||||
key, lambda metadata: metadata[GOAL_STATE_KEY].update(status="complete"),
|
||||
key, lambda metadata: metadata[GOAL_STATE_KEY].update(status="completed"),
|
||||
)
|
||||
return LLMResponse(content="done")
|
||||
return LLMResponse(content="working", finish_reason="tool_calls", tool_calls=[
|
||||
return LLMResponse(content="done", usage=usage)
|
||||
return LLMResponse(content="working", finish_reason="tool_calls", usage=usage, tool_calls=[
|
||||
ToolCallRequest(id=f"call-{len(requests)}", name="noop", arguments={}),
|
||||
])
|
||||
|
||||
@@ -690,16 +703,78 @@ async def test_queued_continuation_keeps_its_origin_after_another_chat_runs(loop
|
||||
async with asyncio.timeout(5):
|
||||
while not requests or key in loop._pending_queues:
|
||||
await asyncio.sleep(0.01)
|
||||
assert [request[:2] for request in requests] == [
|
||||
("chat-a", "message-a"), ("chat-b", "message-b"), ("chat-a", "message-a"),
|
||||
]
|
||||
assert requests[2][2] == requests[0][2]
|
||||
assert [request[:2] for request in requests] == [("chat-a", "message-a")] * 3
|
||||
assert len({request[2] for request in requests}) == 1
|
||||
loop.runner.run.assert_awaited_once()
|
||||
loop.consolidator.compact_idle_session.assert_awaited_once()
|
||||
assert persisted_origin == {"message_id": "message-a", "turn_id": requests[0][2]}
|
||||
by_chat = {event.context.chat_id: event for event in completed}
|
||||
assert set(by_chat) == {"chat-a", "chat-b"}
|
||||
assert by_chat["chat-a"].outcome == "completed"
|
||||
assert len(completed) == 2
|
||||
assert by_chat["chat-a"].usage.total_tokens == 60
|
||||
assert [usage.total_tokens for usage in by_chat["chat-a"].round_usages] == [10, 20, 30]
|
||||
assert by_chat["chat-b"].outcome == "completed"
|
||||
assert by_chat["chat-b"].context.metadata["message_id"] == "message-b"
|
||||
assert by_chat["chat-b"].usage is None
|
||||
assert by_chat["chat-b"].round_usages == ()
|
||||
replies = []
|
||||
while not loop.bus.outbound.empty():
|
||||
reply = loop.bus.outbound.get_nowait()
|
||||
if reply.content == "Continuation reply":
|
||||
if reply.content == "Goal reply":
|
||||
replies.append((reply.chat_id, reply.metadata.get("message_id")))
|
||||
assert replies == [("chat-a", "message-a")]
|
||||
finally:
|
||||
await stop_loop(loop, worker, timeout=3)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("operation", ["reset", "delete"])
|
||||
async def test_stop_does_not_restore_an_obsolete_generation(loop, operation):
|
||||
key = "websocket:stop-old-generation"
|
||||
session = loop.sessions.get_or_create(key)
|
||||
session.metadata[GOAL_STATE_KEY] = {"status": "active", "objective": "Old goal"}
|
||||
loop.sessions.save(session)
|
||||
waiting = asyncio.Event()
|
||||
release = asyncio.Event()
|
||||
calls = 0
|
||||
|
||||
async def chat(**_kwargs):
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
if calls == 1:
|
||||
waiting.set()
|
||||
await release.wait()
|
||||
return LLMResponse(content="New turn handled.", finish_reason="content_filter")
|
||||
|
||||
loop.provider.chat_stream_with_retry = chat
|
||||
worker = asyncio.create_task(loop.run())
|
||||
try:
|
||||
await loop.bus.publish_inbound(InboundMessage(
|
||||
channel="websocket", sender_id="user", chat_id="stop-old-generation", content="Work",
|
||||
))
|
||||
await asyncio.wait_for(waiting.wait(), 5)
|
||||
if operation == "reset":
|
||||
await loop.sessions.state.reset(key)
|
||||
else:
|
||||
assert await loop.sessions.state.delete(key)
|
||||
assert await loop._cancel_active_tasks(key) == 1
|
||||
current = await loop.sessions.state.read_header(key)
|
||||
if operation == "delete":
|
||||
assert current is None
|
||||
else:
|
||||
assert current is not None and current.generation != session.generation
|
||||
assert GOAL_STATE_KEY not in current.metadata
|
||||
|
||||
release.set()
|
||||
await loop.bus.publish_inbound(InboundMessage(
|
||||
channel="websocket", sender_id="user", chat_id="stop-old-generation", content="Fresh input",
|
||||
))
|
||||
async with asyncio.timeout(5):
|
||||
while calls < 2 or key in loop._pending_queues:
|
||||
await asyncio.sleep(0)
|
||||
current = await loop.sessions.state.read_header(key)
|
||||
assert current is not None and current.generation != session.generation
|
||||
assert GOAL_STATE_KEY not in current.metadata
|
||||
finally:
|
||||
release.set()
|
||||
await stop_loop(loop, worker, timeout=5)
|
||||
@@ -491,11 +491,15 @@ def test_public_history_omits_cli_app_breadcrumb():
|
||||
|
||||
|
||||
def test_fork_session_before_user_index_copies_only_prefix(tmp_path):
|
||||
from nanobot.goal.runtime import GOAL_GENERATION_VOLATILE_KEYS
|
||||
|
||||
manager = SessionManager(tmp_path)
|
||||
manager.exclude_generation_metadata(GOAL_GENERATION_VOLATILE_KEYS)
|
||||
source = manager.get_or_create("websocket:source")
|
||||
source.metadata["webui"] = True
|
||||
source.metadata["title"] = "Old title"
|
||||
source.metadata["goal_state"] = {"status": "active", "objective": "do not inherit"}
|
||||
source.metadata["_sustained_goal_continuation_rounds"] = 7
|
||||
source.add_message("user", "round1")
|
||||
source.add_message("assistant", "answer1")
|
||||
source.add_message("user", "round2 fork me")
|
||||
@@ -514,6 +518,7 @@ def test_fork_session_before_user_index_copies_only_prefix(tmp_path):
|
||||
assert forked.metadata["webui"] is True
|
||||
assert "title" not in forked.metadata
|
||||
assert "goal_state" not in forked.metadata
|
||||
assert "_sustained_goal_continuation_rounds" not in forked.metadata
|
||||
saved = manager.read_session_file("websocket:fork")
|
||||
assert [m["content"] for m in saved["messages"]] == ["round1", "answer1"]
|
||||
|
||||
|
||||
@@ -93,6 +93,7 @@ async def test_dispatch_cancellation_restores_checkpoint():
|
||||
)
|
||||
|
||||
loop.sessions.get_or_create = MagicMock(return_value=session)
|
||||
loop.sessions.state.read = AsyncMock(return_value=session)
|
||||
loop.sessions.save = MagicMock()
|
||||
|
||||
async def _cancel(*_args, **_kwargs):
|
||||
|
||||
@@ -11,7 +11,8 @@ from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.agent.tools.file_state import FileStateStore
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.command.builtin import cmd_new, register_builtin_commands
|
||||
from nanobot.command.application import register_builtin_commands
|
||||
from nanobot.command.builtin import cmd_new
|
||||
from nanobot.command.router import CommandContext, CommandRouter
|
||||
from nanobot.config.schema import AgentDefaults, Config
|
||||
from nanobot.session.keys import UNIFIED_SESSION_KEY
|
||||
|
||||
@@ -1,27 +1,27 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from dataclasses import replace
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.agent.goal_permission import goal_mutation_allowed, goal_mutation_permission
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.agent.tools.base import Tool
|
||||
from nanobot.agent.tools.context import (
|
||||
RequestContext,
|
||||
current_request_context,
|
||||
request_context,
|
||||
)
|
||||
from nanobot.agent.tools.long_task import (
|
||||
CreateGoalTool,
|
||||
UpdateGoalTool,
|
||||
)
|
||||
from nanobot.agent.tools.registry import ToolRegistry
|
||||
from nanobot.bus.outbound_events import GoalStateSyncEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.goal.assembly import install_goal
|
||||
from nanobot.goal.runtime import GoalExecutionPolicy
|
||||
from nanobot.goal.tools import CreateGoalTool, UpdateGoalTool
|
||||
from nanobot.session.goal_state import GOAL_STATE_KEY, MAX_GOAL_OBJECTIVE_CHARS
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.turn_continuation import should_finalize_on_max_iterations
|
||||
from nanobot.session.webui_turns import WebuiTurnCoordinator
|
||||
|
||||
|
||||
@@ -60,7 +60,15 @@ def _tools(
|
||||
return create, update, rc
|
||||
|
||||
|
||||
async def _bound_context(sm: SessionManager, ctx: RequestContext) -> RequestContext:
|
||||
if ctx.session_generation is not None or ctx.session_key is None:
|
||||
return ctx
|
||||
session = await sm.state.get_header(ctx.session_key)
|
||||
return replace(ctx, session_generation=session.generation)
|
||||
|
||||
|
||||
async def _execute(tool, ctx: RequestContext, *, allowed: bool = True, **kwargs):
|
||||
ctx = await _bound_context(tool._sessions, ctx)
|
||||
with request_context(ctx), goal_mutation_permission(allowed):
|
||||
return await tool.execute(**kwargs)
|
||||
|
||||
@@ -70,7 +78,6 @@ async def test_create_goal_records_goal_metadata(tmp_path):
|
||||
sm = SessionManager(tmp_path)
|
||||
create, _update, ctx = _tools(sm)
|
||||
await sm.state.get("websocket:c1")
|
||||
await sm.state.update_metadata("websocket:c1", {"_sustained_goal_continuation_rounds": 12})
|
||||
|
||||
out = await _execute(
|
||||
create,
|
||||
@@ -86,15 +93,9 @@ async def test_create_goal_records_goal_metadata(tmp_path):
|
||||
assert blob["status"] == "active"
|
||||
assert blob["objective"] == "Do the thing"
|
||||
assert blob["ui_summary"] == "thing"
|
||||
sess = sm.get_or_create("websocket:c1")
|
||||
assert "_sustained_goal_continuation_rounds" not in sess.metadata
|
||||
assert "_sustained_goal_continuation_rounds" not in (
|
||||
SessionManager(tmp_path).get_or_create("websocket:c1").metadata
|
||||
)
|
||||
assert not should_finalize_on_max_iterations(
|
||||
pending_queue_available=True,
|
||||
session_metadata=sess.metadata,
|
||||
)
|
||||
assert SessionManager(tmp_path).get_or_create(sess.key).metadata[GOAL_STATE_KEY] == blob
|
||||
with GoalExecutionPolicy(sm.state).scope(sess.key, sess.generation, persistent=True) as scope:
|
||||
assert "Do the thing" in await scope.continuation_prompt()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -153,6 +154,7 @@ async def test_update_goal_complete_closes_active_goal(tmp_path):
|
||||
sm = SessionManager(tmp_path)
|
||||
create, update, ctx = _tools(sm)
|
||||
|
||||
ctx = await _bound_context(sm, ctx)
|
||||
with request_context(ctx), goal_mutation_permission(True):
|
||||
await create.execute(objective="X")
|
||||
out = await update.execute(action="complete", recap="Done.")
|
||||
@@ -174,10 +176,6 @@ async def test_update_goal_replace_keeps_goal_active_with_new_objective(tmp_path
|
||||
create, update, ctx = _tools(sm)
|
||||
|
||||
await _execute(create, ctx, objective="Old")
|
||||
await sm.state.update_metadata(
|
||||
"websocket:c1",
|
||||
{"_sustained_goal_continuation_rounds": 12},
|
||||
)
|
||||
out = await _execute(
|
||||
update,
|
||||
_request_context(),
|
||||
@@ -193,14 +191,9 @@ async def test_update_goal_replace_keeps_goal_active_with_new_objective(tmp_path
|
||||
assert blob["previous_objective"] == "Old"
|
||||
assert blob["ui_summary"] == "new"
|
||||
sess = sm.get_or_create("websocket:c1")
|
||||
assert "_sustained_goal_continuation_rounds" not in sess.metadata
|
||||
assert "_sustained_goal_continuation_rounds" not in (
|
||||
SessionManager(tmp_path).get_or_create("websocket:c1").metadata
|
||||
)
|
||||
assert not should_finalize_on_max_iterations(
|
||||
pending_queue_available=True,
|
||||
session_metadata=sess.metadata,
|
||||
)
|
||||
assert SessionManager(tmp_path).get_or_create(sess.key).metadata[GOAL_STATE_KEY] == blob
|
||||
with GoalExecutionPolicy(sm.state).scope(sess.key, sess.generation, persistent=True) as scope:
|
||||
assert "New" in await scope.continuation_prompt()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -209,7 +202,6 @@ async def test_goal_state_mutations_roll_back_on_save_failure(tmp_path, monkeypa
|
||||
create, update, _context = _tools(sm)
|
||||
sess = sm.get_or_create("websocket:c1")
|
||||
sess.metadata["marker"] = {"keep": True}
|
||||
sess.metadata["_sustained_goal_continuation_rounds"] = 12
|
||||
sm.save(sess)
|
||||
original_save = sm._store.replace_metadata
|
||||
create_context = _request_context()
|
||||
@@ -221,18 +213,11 @@ async def test_goal_state_mutations_roll_back_on_save_failure(tmp_path, monkeypa
|
||||
with pytest.raises(OSError, match="disk unavailable"):
|
||||
await _execute(create, create_context, objective="Old")
|
||||
|
||||
assert sess.metadata == {
|
||||
"marker": {"keep": True},
|
||||
"_sustained_goal_continuation_rounds": 12,
|
||||
}
|
||||
assert sess.metadata == {"marker": {"keep": True}}
|
||||
assert GOAL_STATE_KEY not in SessionManager(tmp_path).get_or_create("websocket:c1").metadata
|
||||
|
||||
monkeypatch.setattr(sm._store, "replace_metadata", original_save)
|
||||
assert "Goal recorded" in await _execute(create, create_context, objective="Old")
|
||||
await sm.state.update_metadata(
|
||||
"websocket:c1",
|
||||
{"_sustained_goal_continuation_rounds": 12},
|
||||
)
|
||||
sess = sm.get_or_create("websocket:c1")
|
||||
replace_context = _request_context()
|
||||
|
||||
@@ -241,10 +226,10 @@ async def test_goal_state_mutations_roll_back_on_save_failure(tmp_path, monkeypa
|
||||
await _execute(update, replace_context, action="replace", objective="New")
|
||||
|
||||
assert sess.metadata[GOAL_STATE_KEY]["objective"] == "Old"
|
||||
assert sess.metadata["_sustained_goal_continuation_rounds"] == 12
|
||||
assert sess.metadata["marker"] == {"keep": True}
|
||||
persisted = SessionManager(tmp_path).get_or_create("websocket:c1").metadata
|
||||
assert persisted[GOAL_STATE_KEY]["objective"] == "Old"
|
||||
assert persisted["_sustained_goal_continuation_rounds"] == 12
|
||||
assert persisted["marker"] == {"keep": True}
|
||||
|
||||
monkeypatch.setattr(sm._store, "replace_metadata", original_save)
|
||||
assert "Goal replaced" in await _execute(
|
||||
@@ -254,7 +239,7 @@ async def test_goal_state_mutations_roll_back_on_save_failure(tmp_path, monkeypa
|
||||
objective="New",
|
||||
)
|
||||
sess = sm.get_or_create("websocket:c1")
|
||||
assert "_sustained_goal_continuation_rounds" not in sess.metadata
|
||||
assert sess.metadata["marker"] == {"keep": True}
|
||||
assert (
|
||||
SessionManager(tmp_path).get_or_create("websocket:c1").metadata[GOAL_STATE_KEY]["objective"]
|
||||
== "New"
|
||||
@@ -294,7 +279,7 @@ async def test_active_goal_create_failure_preserves_permission_for_replace(tmp_p
|
||||
create, update, initial_context = _tools(sm)
|
||||
assert "Goal recorded" in await _execute(create, initial_context, objective="Old")
|
||||
|
||||
replacement_context = _request_context()
|
||||
replacement_context = await _bound_context(sm, _request_context())
|
||||
with request_context(replacement_context), goal_mutation_permission(True):
|
||||
create_out = await create.execute(objective="New")
|
||||
assert goal_mutation_allowed() is True
|
||||
@@ -323,7 +308,7 @@ async def test_update_goal_replace_requires_explicit_goal_permission(tmp_path):
|
||||
assert "replacing the goal is unavailable for this turn" in str(unauthorized)
|
||||
assert "/goal <task>" in str(unauthorized)
|
||||
assert sm.get_or_create("websocket:c1").metadata[GOAL_STATE_KEY]["objective"] == "Old"
|
||||
replace_context = _request_context()
|
||||
replace_context = await _bound_context(sm, _request_context())
|
||||
|
||||
with request_context(replace_context), goal_mutation_permission(True):
|
||||
assert "Goal replaced" in await update.execute(action="replace", objective="New")
|
||||
@@ -352,6 +337,8 @@ async def test_goal_tools_keep_request_context_per_task(tmp_path):
|
||||
metadata=_goal_metadata(),
|
||||
)
|
||||
|
||||
ctx_a = await _bound_context(sm, ctx_a)
|
||||
ctx_b = await _bound_context(sm, ctx_b)
|
||||
task_a = asyncio.create_task(_execute(create, ctx_a, objective="Goal A"))
|
||||
task_b = asyncio.create_task(_execute(create, ctx_b, objective="Goal B"))
|
||||
await asyncio.gather(task_a, task_b)
|
||||
@@ -390,7 +377,7 @@ async def test_registry_does_not_reuse_goal_context_after_request_scope(tmp_path
|
||||
sess = sm.get_or_create("websocket:c1")
|
||||
sess.metadata[GOAL_STATE_KEY] = {"status": "active", "objective": "Old"}
|
||||
sm.save(sess)
|
||||
ctx = _request_context()
|
||||
ctx = await _bound_context(sm, _request_context())
|
||||
|
||||
with request_context(ctx), goal_mutation_permission(True):
|
||||
create_out = await registry.execute("create_goal", {"objective": "New"})
|
||||
@@ -472,11 +459,12 @@ async def test_update_goal_without_active_is_noop_message(tmp_path):
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_goal_tools_registered_in_base_registry(tmp_path):
|
||||
async def test_goal_tools_registered_by_builtin_assembly(tmp_path):
|
||||
bus = MessageBus()
|
||||
provider = MagicMock()
|
||||
provider.get_default_model.return_value = "test-model"
|
||||
loop = AgentLoop(bus=bus, provider=provider, workspace=tmp_path, model="test-model")
|
||||
loop = AgentLoop(bus=bus, provider=provider, workspace=tmp_path, model="test-model",
|
||||
builtin_assembly=install_goal)
|
||||
|
||||
create = loop.tools.get("create_goal")
|
||||
update = loop.tools.get("update_goal")
|
||||
@@ -502,3 +490,41 @@ async def test_goal_tools_registered_in_base_registry(tmp_path):
|
||||
).lower()
|
||||
assert "authoriz" not in model_visible_contract
|
||||
assert "/goal" not in model_visible_contract
|
||||
|
||||
|
||||
@pytest.mark.parametrize("caller_supplied", [False, True])
|
||||
async def test_goal_assembly_preserves_builtin_plugin_precedence(tmp_path, monkeypatch, caller_supplied):
|
||||
from nanobot.agent.tools.loader import ToolLoader
|
||||
|
||||
class ConflictingTool(Tool):
|
||||
@property
|
||||
def name(self):
|
||||
return "create_goal"
|
||||
|
||||
@property
|
||||
def description(self):
|
||||
return "Synthetic conflicting tool"
|
||||
|
||||
@property
|
||||
def parameters(self):
|
||||
return {"type": "object", "properties": {}}
|
||||
|
||||
async def execute(self, **kwargs):
|
||||
return "external"
|
||||
|
||||
monkeypatch.setattr(ToolLoader, "_discover_plugins", lambda _self: {"external": ConflictingTool})
|
||||
registry = ToolRegistry()
|
||||
supplied = ConflictingTool()
|
||||
if caller_supplied:
|
||||
registry.register(supplied)
|
||||
provider = MagicMock(aclose=AsyncMock())
|
||||
provider.get_default_model.return_value = "test-model"
|
||||
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model",
|
||||
tool_registry=registry, builtin_assembly=install_goal)
|
||||
try:
|
||||
if caller_supplied:
|
||||
assert loop.tools.get("create_goal") is supplied
|
||||
else:
|
||||
assert isinstance(loop.tools.get("create_goal"), CreateGoalTool)
|
||||
finally:
|
||||
await loop.aclose()
|
||||
Reference in new issue
Block a user