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()
|
||||
@@ -206,8 +206,7 @@ async def test_runtime_event_publisher_consumes_turn_metadata_on_complete() -> N
|
||||
publisher.record_turn_latency("cli:direct", 123)
|
||||
first_round = LLMUsage.reported(input_tokens=40, output_tokens=2)
|
||||
second_round = LLMUsage.reported(input_tokens=60, output_tokens=3)
|
||||
publisher.record_turn_usage("cli:direct", [first_round])
|
||||
publisher.record_turn_usage("cli:direct", [second_round])
|
||||
publisher.record_turn_usage("cli:direct", [first_round, second_round])
|
||||
|
||||
await publisher.turn_completed(
|
||||
channel="cli",
|
||||
|
||||
@@ -56,8 +56,9 @@ def test_interactive_agent_routes_a_complete_user_turn(
|
||||
channels_config = None
|
||||
|
||||
@classmethod
|
||||
def from_config(cls, _config, bus, **_kwargs):
|
||||
def from_config(cls, _config, bus, **kwargs):
|
||||
instance = cls(bus)
|
||||
seen["builtin_assembly"] = kwargs["builtin_assembly"]
|
||||
seen["loop"] = instance
|
||||
return instance
|
||||
|
||||
@@ -109,6 +110,8 @@ def test_interactive_agent_routes_a_complete_user_turn(
|
||||
monkeypatch.setattr("nanobot.cli.agent._model_display", lambda *_args: ("test-model", ""))
|
||||
monkeypatch.setattr("nanobot.cli.agent.consume_restart_notice_from_env", lambda: None)
|
||||
monkeypatch.setattr("nanobot.cli.agent.AgentLoop", _AgentLoop)
|
||||
install_goal = MagicMock()
|
||||
monkeypatch.setattr("nanobot.goal.assembly.install_goal", install_goal)
|
||||
monkeypatch.setattr("nanobot.cli.agent.StreamRenderer", _Renderer)
|
||||
monkeypatch.setattr("nanobot.providers.factory.make_provider", lambda *_args: object())
|
||||
monkeypatch.setattr(
|
||||
@@ -136,6 +139,7 @@ def test_interactive_agent_routes_a_complete_user_turn(
|
||||
assert inbound.metadata == {"_wants_stream": True}
|
||||
loop = seen["loop"]
|
||||
assert isinstance(loop, _AgentLoop)
|
||||
assert seen["builtin_assembly"] is install_goal
|
||||
assert loop.aclose_calls == 1
|
||||
assert len(renderers) == 1
|
||||
renderer = renderers[0]
|
||||
|
||||
+57
-12
@@ -91,6 +91,11 @@ class _StopGatewayError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def _patch_fake_agent_loop(monkeypatch, target, fake):
|
||||
monkeypatch.setattr(target, fake)
|
||||
monkeypatch.setattr("nanobot.goal.assembly.install_goal", MagicMock())
|
||||
|
||||
|
||||
class _GatewayAgentContractStub:
|
||||
"""Minimal stable AgentLoop surface required by gateway assembly tests."""
|
||||
|
||||
@@ -1689,6 +1694,46 @@ def test_agent_uses_explicit_config_path(mock_agent_runtime, tmp_path: Path):
|
||||
assert mock_agent_runtime["load_config"].call_args.args == (config_path.resolve(),)
|
||||
|
||||
|
||||
def test_one_shot_agent_assembles_goal_without_background_queue(monkeypatch, tmp_path: Path) -> None:
|
||||
from nanobot.providers.base import GenerationSettings, LLMResponse, ToolCallRequest
|
||||
from nanobot.session.manager import SessionManager
|
||||
|
||||
config = Config()
|
||||
config.agents.defaults.workspace = str(tmp_path / "workspace")
|
||||
config.agents.defaults.max_tool_iterations = 1
|
||||
config.bind_source_path(tmp_path / "instance" / "config.json")
|
||||
provider = _fake_provider()
|
||||
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="goal", name="create_goal", arguments={"objective": "Do the synthetic task."},
|
||||
)]),
|
||||
LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||
id="complete", name="update_goal", arguments={"action": "complete", "recap": "Verified."},
|
||||
)]),
|
||||
LLMResponse(content="Verified."),
|
||||
])
|
||||
monkeypatch.setattr("nanobot.cli.agent._load_runtime_config", lambda *_args: config)
|
||||
monkeypatch.setattr("nanobot.cli.agent.sync_workspace_templates", lambda *_args: None)
|
||||
monkeypatch.setattr("nanobot.cli.agent.is_default_workspace", lambda *_args: False)
|
||||
monkeypatch.setattr("nanobot.providers.factory.make_provider", lambda *_args: provider)
|
||||
monkeypatch.setattr("nanobot.config.home._home_path", tmp_path / "home")
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", tmp_path / "instance" / "config.json")
|
||||
|
||||
result = runner.invoke(app, ["agent", "--classic", "-m", "/goal Do the synthetic task."])
|
||||
assert result.exit_code == 0, result.output
|
||||
assert provider.chat_stream_with_retry.await_count == 3
|
||||
calls = provider.chat_stream_with_retry.await_args_list
|
||||
assert all(call.kwargs["tools"] for call in calls[:2])
|
||||
assert not calls[2].kwargs.get("tools")
|
||||
assert "Verified." in result.output
|
||||
sessions = SessionManager(config.workspace_path, sessions_root=tmp_path / "instance" / "sessions")
|
||||
goal = sessions.get_or_create("cli:direct").metadata["goal_state"]
|
||||
assert goal["status"] == "completed" and goal["objective"] == "Do the synthetic task."
|
||||
|
||||
|
||||
def test_agent_config_sets_active_path(monkeypatch, tmp_path: Path) -> None:
|
||||
config_file = tmp_path / "instance" / "config.json"
|
||||
config_file.parent.mkdir(parents=True)
|
||||
@@ -1720,7 +1765,7 @@ def test_agent_config_sets_active_path(monkeypatch, tmp_path: Path) -> None:
|
||||
async def aclose(self) -> None:
|
||||
return None
|
||||
|
||||
monkeypatch.setattr("nanobot.cli.agent.AgentLoop", _FakeAgentLoop)
|
||||
_patch_fake_agent_loop(monkeypatch, "nanobot.cli.agent.AgentLoop", _FakeAgentLoop)
|
||||
monkeypatch.setattr("nanobot.cli.terminal._print_agent_response", lambda *_args, **_kwargs: None)
|
||||
|
||||
result = runner.invoke(app, ["agent", "-m", "hello", "-c", str(config_file)])
|
||||
@@ -1762,7 +1807,7 @@ def test_agent_uses_workspace_directory_for_cron_store(monkeypatch, tmp_path: Pa
|
||||
return None
|
||||
|
||||
monkeypatch.setattr("nanobot.cron.service.CronService", _FakeCron)
|
||||
monkeypatch.setattr("nanobot.cli.agent.AgentLoop", _FakeAgentLoop)
|
||||
_patch_fake_agent_loop(monkeypatch, "nanobot.cli.agent.AgentLoop", _FakeAgentLoop)
|
||||
monkeypatch.setattr("nanobot.cli.terminal._print_agent_response", lambda *_args, **_kwargs: None)
|
||||
|
||||
result = runner.invoke(app, ["agent", "-m", "hello", "-c", str(config_file)])
|
||||
@@ -1812,7 +1857,7 @@ def test_agent_workspace_override_does_not_migrate_legacy_cron(
|
||||
return None
|
||||
|
||||
monkeypatch.setattr("nanobot.cron.service.CronService", _FakeCron)
|
||||
monkeypatch.setattr("nanobot.cli.agent.AgentLoop", _FakeAgentLoop)
|
||||
_patch_fake_agent_loop(monkeypatch, "nanobot.cli.agent.AgentLoop", _FakeAgentLoop)
|
||||
monkeypatch.setattr("nanobot.cli.terminal._print_agent_response", lambda *_args, **_kwargs: None)
|
||||
|
||||
result = runner.invoke(
|
||||
@@ -1868,7 +1913,7 @@ def test_agent_custom_config_workspace_does_not_migrate_legacy_cron(
|
||||
return None
|
||||
|
||||
monkeypatch.setattr("nanobot.cron.service.CronService", _FakeCron)
|
||||
monkeypatch.setattr("nanobot.cli.agent.AgentLoop", _FakeAgentLoop)
|
||||
_patch_fake_agent_loop(monkeypatch, "nanobot.cli.agent.AgentLoop", _FakeAgentLoop)
|
||||
monkeypatch.setattr(
|
||||
"nanobot.cli.terminal._print_agent_response", lambda *_args, **_kwargs: None
|
||||
)
|
||||
@@ -2248,7 +2293,7 @@ def test_heartbeat_empty_response_is_not_evaluated(
|
||||
session_manager=_FakeSessionManager,
|
||||
cron_service=_FakeCron,
|
||||
)
|
||||
monkeypatch.setattr("nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop)
|
||||
_patch_fake_agent_loop(monkeypatch, "nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop)
|
||||
monkeypatch.setattr("nanobot.channels.manager.ChannelManager", _FakeChannelManager)
|
||||
monkeypatch.setattr("nanobot.cli.gateway_runtime.ensure_webui_session_archives", AsyncMock(return_value=[]))
|
||||
monkeypatch.setattr("nanobot.cli.gateway_runtime.evaluate_response", _unexpected_evaluator)
|
||||
@@ -3156,7 +3201,7 @@ def _patch_serve_runtime(monkeypatch, config: Config, seen: dict[str, object]) -
|
||||
message_bus=MessageBus,
|
||||
session_manager=lambda _workspace: _EmptyGatewaySessionManager(),
|
||||
)
|
||||
monkeypatch.setattr("nanobot.cli.commands.AgentLoop", _FakeAgentLoop)
|
||||
_patch_fake_agent_loop(monkeypatch, "nanobot.cli.commands.AgentLoop", _FakeAgentLoop)
|
||||
monkeypatch.setattr("nanobot.api.server.create_app", _fake_create_app)
|
||||
monkeypatch.setattr("aiohttp.web.run_app", _fake_run_app)
|
||||
|
||||
@@ -3341,7 +3386,7 @@ def test_gateway_unbound_agent_cron_is_skipped(
|
||||
raise AssertionError("unbound cron job must not be evaluated for delivery")
|
||||
|
||||
monkeypatch.setattr("nanobot.cron.service.CronService", _FakeCron)
|
||||
monkeypatch.setattr("nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop)
|
||||
_patch_fake_agent_loop(monkeypatch, "nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop)
|
||||
monkeypatch.setattr("nanobot.channels.manager.ChannelManager", _StopAfterCronSetup)
|
||||
monkeypatch.setattr(
|
||||
"nanobot.cli.gateway_runtime.evaluate_response",
|
||||
@@ -3457,7 +3502,7 @@ def test_gateway_bound_cron_runs_as_session_turn(
|
||||
raise AssertionError("bound cron must not use legacy response evaluator")
|
||||
|
||||
monkeypatch.setattr("nanobot.cron.service.CronService", _FakeCron)
|
||||
monkeypatch.setattr("nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop)
|
||||
_patch_fake_agent_loop(monkeypatch, "nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop)
|
||||
monkeypatch.setattr("nanobot.channels.manager.ChannelManager", _StopAfterCronSetup)
|
||||
monkeypatch.setattr("nanobot.cli.gateway_runtime.evaluate_response", _unexpected_evaluator)
|
||||
|
||||
@@ -3699,7 +3744,7 @@ def test_gateway_local_trigger_queue_submits_agent_turns(
|
||||
seen["local_trigger_queue_kwargs"] = kwargs
|
||||
raise _StopGatewayError("stop")
|
||||
|
||||
monkeypatch.setattr("nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop)
|
||||
_patch_fake_agent_loop(monkeypatch, "nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop)
|
||||
monkeypatch.setattr("nanobot.channels.manager.ChannelManager", _FakeChannelManager)
|
||||
monkeypatch.setattr(
|
||||
"nanobot.triggers.local_runner.run_local_trigger_queue",
|
||||
@@ -4017,7 +4062,7 @@ def test_gateway_health_endpoint_binds_and_serves_expected_responses(
|
||||
message_bus=MessageBus,
|
||||
session_manager=lambda _workspace: _EmptyGatewaySessionManager(),
|
||||
)
|
||||
monkeypatch.setattr("nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop)
|
||||
_patch_fake_agent_loop(monkeypatch, "nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop)
|
||||
monkeypatch.setattr("nanobot.channels.manager.ChannelManager", _FakeChannelManager)
|
||||
monkeypatch.setattr("nanobot.cron.service.CronService", _FakeCronService)
|
||||
monkeypatch.setattr("asyncio.start_server", _fake_start_server)
|
||||
@@ -4235,7 +4280,7 @@ def test_gateway_failure_exits_nonzero_after_cleanup(
|
||||
message_bus=MessageBus,
|
||||
session_manager=lambda _workspace: _EmptyGatewaySessionManager(),
|
||||
)
|
||||
monkeypatch.setattr("nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop)
|
||||
_patch_fake_agent_loop(monkeypatch, "nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop)
|
||||
monkeypatch.setattr("nanobot.cli.gateway_runtime.MCPProvider", _FakeMCPProvider)
|
||||
monkeypatch.setattr("nanobot.channels.manager.ChannelManager", _FakeChannelManager)
|
||||
monkeypatch.setattr("nanobot.cron.service.CronService", _FakeCronService)
|
||||
@@ -4404,7 +4449,7 @@ def test_gateway_shutdown_event_exits_forever_runtime_tasks(
|
||||
message_bus=MessageBus,
|
||||
session_manager=lambda _workspace: _EmptyGatewaySessionManager(),
|
||||
)
|
||||
monkeypatch.setattr("nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop)
|
||||
_patch_fake_agent_loop(monkeypatch, "nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop)
|
||||
monkeypatch.setattr("nanobot.channels.manager.ChannelManager", _FakeChannelManager)
|
||||
monkeypatch.setattr("nanobot.cron.service.CronService", _FakeCronService)
|
||||
monkeypatch.setattr("asyncio.start_server", _fake_start_server)
|
||||
|
||||
@@ -7,9 +7,8 @@ import pytest
|
||||
|
||||
from nanobot.agent.memory import MemoryStore
|
||||
from nanobot.bus.events import InboundMessage, OutboundMessage
|
||||
from nanobot.command.application import build_help_text, builtin_command_palette
|
||||
from nanobot.command.builtin import (
|
||||
build_help_text,
|
||||
builtin_command_palette,
|
||||
cmd_dream,
|
||||
cmd_dream_log,
|
||||
cmd_dream_prompt,
|
||||
|
||||
@@ -5,11 +5,8 @@ from types import SimpleNamespace
|
||||
import pytest
|
||||
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.command.builtin import (
|
||||
build_help_text,
|
||||
builtin_command_palette,
|
||||
cmd_evaluator_prompt,
|
||||
)
|
||||
from nanobot.command.application import build_help_text, builtin_command_palette
|
||||
from nanobot.command.builtin import cmd_evaluator_prompt
|
||||
from nanobot.command.router import CommandContext
|
||||
from nanobot.utils.evaluator import default_evaluator_prompt
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.mark.parametrize("first_module", ["nanobot.goal.command", "nanobot.command.builtin"])
|
||||
def test_goal_and_builtin_commands_import_in_either_order(first_module):
|
||||
script = f"""
|
||||
import {first_module}
|
||||
from nanobot.goal.command import register_goal_command
|
||||
from nanobot.command import CommandRouter, register_builtin_commands
|
||||
|
||||
router = CommandRouter()
|
||||
register_builtin_commands(router)
|
||||
assert router.is_dispatchable_command('/goal ship it')
|
||||
standalone = CommandRouter()
|
||||
register_goal_command(standalone)
|
||||
assert standalone.is_dispatchable_command('/goal ship it')
|
||||
"""
|
||||
subprocess.run([sys.executable, "-B", "-c", script], check=True)
|
||||
@@ -1,5 +1,5 @@
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -7,15 +7,15 @@ from nanobot.agent.goal_permission import goal_mutation_allowed
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.bus.events import InboundMessage, OutboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.command.builtin import (
|
||||
from nanobot.command.application import (
|
||||
build_help_text,
|
||||
builtin_command_palette,
|
||||
cmd_goal,
|
||||
cmd_model,
|
||||
register_builtin_commands,
|
||||
)
|
||||
from nanobot.command.router import CommandContext, CommandRouter
|
||||
from nanobot.command.builtin import cmd_model
|
||||
from nanobot.command.router import CommandContext, CommandExpansion, CommandInput, CommandRouter
|
||||
from nanobot.config.schema import ModelPresetConfig
|
||||
from nanobot.goal.command import cmd_goal, register_goal_command
|
||||
from nanobot.session.history_visibility import HIDDEN_HISTORY_META
|
||||
from nanobot.session.model_selection import (
|
||||
SESSION_MODEL_PRESET_METADATA_KEY,
|
||||
@@ -241,7 +241,8 @@ def test_model_command_in_help_and_palette() -> None:
|
||||
@pytest.mark.asyncio
|
||||
async def test_goal_command_shows_usage_without_args(tmp_path) -> None:
|
||||
loop = _make_loop(tmp_path)
|
||||
out = await cmd_goal(_ctx(loop, "/goal"))
|
||||
ctx = _ctx(loop, "/goal")
|
||||
out = await cmd_goal(CommandInput(ctx.msg, ctx.args, ctx.is_user_turn))
|
||||
assert out is not None
|
||||
assert out.channel == "cli"
|
||||
assert out.chat_id == "direct"
|
||||
@@ -256,11 +257,18 @@ async def test_goal_command_preserves_task_and_visible_command(tmp_path, with_se
|
||||
task = "检查 /tmp/project\n保留现有文件。"
|
||||
command = f"/goal {task}"
|
||||
ctx = _ctx_session(loop, command, args=task)
|
||||
ctx.msg.media = ["attachment.png"]
|
||||
ctx.msg.metadata = {"request_id": "request-1"}
|
||||
ctx.session = await loop.sessions.state.get(ctx.key) if with_session else None
|
||||
out = await cmd_goal(ctx)
|
||||
expansion = await cmd_goal(CommandInput(ctx.msg, ctx.args, ctx.is_user_turn))
|
||||
assert isinstance(expansion, CommandExpansion)
|
||||
out = await loop._prepare_command_expansion(ctx, expansion)
|
||||
assert isinstance(out, InboundMessage)
|
||||
assert ctx.msg.content == command
|
||||
assert out.content == task
|
||||
assert out.media == ["attachment.png"]
|
||||
assert out.metadata["request_id"] == "request-1"
|
||||
assert out.metadata["original_command"] == "/goal"
|
||||
assert out.metadata["original_content"] == command
|
||||
assert out.metadata["goal_requested"] is True
|
||||
assert out.metadata[HIDDEN_HISTORY_META] == {"kind": "goal_request"}
|
||||
@@ -269,6 +277,8 @@ async def test_goal_command_preserves_task_and_visible_command(tmp_path, with_se
|
||||
assert [(row["role"], row["content"]) for row in session.messages] == [
|
||||
("user", command),
|
||||
]
|
||||
assert session.messages[0]["_command"] is True
|
||||
assert session.messages[0]["media"] == ["attachment.png"]
|
||||
|
||||
|
||||
|
||||
@@ -277,16 +287,72 @@ async def test_goal_command_registered_on_router(tmp_path) -> None:
|
||||
router = CommandRouter()
|
||||
register_builtin_commands(router)
|
||||
loop = _make_loop(tmp_path)
|
||||
usage = await router.dispatch(_ctx(loop, "/goal"))
|
||||
assert isinstance(usage, OutboundMessage)
|
||||
assert usage.content == "Usage: /goal <long-running task description>"
|
||||
assert usage.metadata == {"render_as": "text"}
|
||||
ctx = _ctx_session(loop, "/goal ship it", args="ship it")
|
||||
ctx.session = await loop.sessions.state.get(ctx.key)
|
||||
out = await router.dispatch(ctx)
|
||||
assert isinstance(out, InboundMessage)
|
||||
assert out.content == "ship it"
|
||||
assert out.metadata["goal_requested"] is True
|
||||
assert isinstance(out, CommandExpansion)
|
||||
assert out.message.content == "ship it"
|
||||
assert out.message.metadata["goal_requested"] is True
|
||||
assert goal_mutation_allowed() is False
|
||||
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_goal_command_can_be_registered_independently(tmp_path) -> None:
|
||||
router = CommandRouter()
|
||||
register_goal_command(router)
|
||||
loop = _make_loop(tmp_path)
|
||||
|
||||
usage = await router.dispatch(_ctx(loop, "/goal"))
|
||||
ctx = _ctx_session(loop, "/goal ship it")
|
||||
ctx.session = await loop.sessions.state.get(ctx.key)
|
||||
task = await router.dispatch(ctx)
|
||||
|
||||
assert isinstance(usage, OutboundMessage)
|
||||
assert usage.content == "Usage: /goal <long-running task description>"
|
||||
assert isinstance(task, CommandExpansion)
|
||||
assert task.message.content == "ship it"
|
||||
assert task.message.metadata["goal_requested"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("with_session", [False, True])
|
||||
async def test_goal_command_rejects_transient_session_without_changing_history(
|
||||
tmp_path, monkeypatch, with_session,
|
||||
) -> None:
|
||||
loop = _make_loop(tmp_path)
|
||||
loop.provider.aclose = AsyncMock()
|
||||
ctx = _ctx(loop, "/goal keep going", args="keep going")
|
||||
ctx.is_user_turn = True
|
||||
ctx.msg.metadata = {"request_id": "request-1"}
|
||||
session = await loop.sessions.state.register_transient(ctx.key)
|
||||
session.add_message("user", "Earlier private message")
|
||||
await loop.sessions.state.prepare_input(session)
|
||||
ctx.session = session if with_session else None
|
||||
prepare_input = AsyncMock(wraps=loop.sessions.state.prepare_input)
|
||||
monkeypatch.setattr(loop.sessions.state, "prepare_input", prepare_input)
|
||||
try:
|
||||
expansion = await cmd_goal(CommandInput(ctx.msg, ctx.args, ctx.is_user_turn))
|
||||
assert isinstance(expansion, CommandExpansion)
|
||||
out = await loop._prepare_command_expansion(ctx, expansion)
|
||||
|
||||
assert isinstance(out, OutboundMessage)
|
||||
assert out.content == "Goals can't start in a temporary session. Use a persistent session for `/goal`."
|
||||
assert out.metadata == {"request_id": "request-1", "render_as": "text"}
|
||||
prepare_input.assert_not_awaited()
|
||||
assert [row["content"] for row in session.messages] == ["Earlier private message"]
|
||||
current = await loop.sessions.state.read(ctx.key)
|
||||
assert current is not None and not current.policy.persist
|
||||
assert [row["content"] for row in current.messages] == ["Earlier private message"]
|
||||
assert loop.sessions.read_session_file(ctx.key) is None
|
||||
finally:
|
||||
await loop.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_goal_command_does_not_allow_internal_turn(tmp_path) -> None:
|
||||
loop = _make_loop(tmp_path)
|
||||
@@ -305,17 +371,25 @@ async def test_goal_command_does_not_allow_internal_turn(tmp_path) -> None:
|
||||
is_user_turn=False,
|
||||
)
|
||||
|
||||
out = await cmd_goal(ctx)
|
||||
out = await cmd_goal(CommandInput(ctx.msg, ctx.args, ctx.is_user_turn))
|
||||
|
||||
assert isinstance(out, OutboundMessage)
|
||||
assert "only be started by a user" in out.content
|
||||
assert ctx.turn_scopes == []
|
||||
|
||||
|
||||
def test_goal_command_in_help_and_palette() -> None:
|
||||
palette = builtin_command_palette()
|
||||
goal = next(item for item in palette if item["command"] == "/goal")
|
||||
assert goal["arg_hint"] == "<goal>"
|
||||
assert goal["lifecycle"] == "agent_turn_with_args"
|
||||
assert goal["accepts_args"] is True
|
||||
assert goal == {
|
||||
"command": "/goal",
|
||||
"title": "Start long-running goal",
|
||||
"description": "Tell the agent to treat the request as a long-running goal.",
|
||||
"icon": "activity",
|
||||
"arg_hint": "<goal>",
|
||||
"lifecycle": "agent_turn_with_args",
|
||||
"accepts_args": True,
|
||||
}
|
||||
commands = [item["command"] for item in palette]
|
||||
goal_index = commands.index("/goal")
|
||||
assert commands[goal_index - 1:goal_index + 2] == ["/history", "/goal", "/trigger"]
|
||||
assert "/goal <goal>" in build_help_text()
|
||||
@@ -5,7 +5,7 @@ from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.command.builtin import (
|
||||
from nanobot.command.application import (
|
||||
builtin_command_starts_agent_turn,
|
||||
register_builtin_commands,
|
||||
)
|
||||
@@ -141,6 +141,7 @@ class TestMidTurnCommandDispatchedDirectly:
|
||||
async def test_help_dispatched_with_session_none(
|
||||
self, router: CommandRouter, fake_loop: MagicMock, fake_msg: MagicMock,
|
||||
) -> None:
|
||||
fake_loop.commands = router
|
||||
ctx = CommandContext(
|
||||
msg=fake_msg, session=None,
|
||||
key="test:chat1", raw="/help", loop=fake_loop,
|
||||
@@ -151,6 +152,7 @@ class TestMidTurnCommandDispatchedDirectly:
|
||||
assert result.chat_id == "chat1"
|
||||
assert result.metadata["render_as"] == "text"
|
||||
assert "/new" in result.content
|
||||
assert "/goal <goal>" in result.content
|
||||
assert "/pairing [list|approve <code>|deny <code>|revoke <user_id>]" in result.content
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -7,7 +7,8 @@ from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.agent.skills import SkillsLoader
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.command.builtin import cmd_skill, register_builtin_commands
|
||||
from nanobot.command.application import register_builtin_commands
|
||||
from nanobot.command.builtin import cmd_skill
|
||||
from nanobot.command.router import CommandContext, CommandRouter
|
||||
from nanobot.config.schema import ModelPresetConfig
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ from types import SimpleNamespace
|
||||
import pytest
|
||||
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.command.builtin import build_help_text, register_builtin_commands
|
||||
from nanobot.command.application import build_help_text, register_builtin_commands
|
||||
from nanobot.command.router import CommandContext, CommandRouter
|
||||
from nanobot.session.keys import UNIFIED_SESSION_KEY
|
||||
from nanobot.triggers.local_store import LocalTriggerStore
|
||||
|
||||
@@ -6,7 +6,6 @@ from nanobot.session.goal_state import (
|
||||
discard_legacy_goal_state_key,
|
||||
explicit_goal_requested,
|
||||
goal_state_runtime_lines,
|
||||
goal_state_ws_blob,
|
||||
parse_goal_state,
|
||||
sustained_goal_active,
|
||||
)
|
||||
@@ -78,48 +77,6 @@ def test_parse_goal_state_accepts_json_string():
|
||||
}
|
||||
|
||||
|
||||
def test_goal_state_ws_blob_inactive_when_missing_or_completed():
|
||||
assert goal_state_ws_blob(None) == {"active": False}
|
||||
assert goal_state_ws_blob({}) == {"active": False}
|
||||
assert goal_state_ws_blob({GOAL_STATE_KEY: {"status": "completed", "objective": "x"}}) == {
|
||||
"active": False,
|
||||
}
|
||||
|
||||
|
||||
def test_goal_state_ws_blob_active_shape():
|
||||
meta = {
|
||||
GOAL_STATE_KEY: {
|
||||
"status": "active",
|
||||
"objective": "Build feature.",
|
||||
"ui_summary": "feat",
|
||||
},
|
||||
}
|
||||
assert goal_state_ws_blob(meta) == {
|
||||
"active": True,
|
||||
"status": "active",
|
||||
"ui_summary": "feat",
|
||||
"objective": "Build feature.",
|
||||
}
|
||||
|
||||
|
||||
def test_goal_state_ws_blob_preserves_blocked_state_for_host_attention():
|
||||
meta = {
|
||||
GOAL_STATE_KEY: {
|
||||
"status": "blocked",
|
||||
"objective": "Deploy safely.",
|
||||
"ui_summary": "Approval required",
|
||||
"recap": "Production access is required.",
|
||||
},
|
||||
}
|
||||
assert goal_state_ws_blob(meta) == {
|
||||
"active": False,
|
||||
"status": "blocked",
|
||||
"ui_summary": "Approval required",
|
||||
"objective": "Deploy safely.",
|
||||
"recap": "Production access is required.",
|
||||
}
|
||||
|
||||
|
||||
def test_sustained_goal_active_false_when_missing_or_completed():
|
||||
assert sustained_goal_active(None) is False
|
||||
assert sustained_goal_active({}) is False
|
||||
|
||||
@@ -1,163 +1,107 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.agent.tools.context import RequestContext
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.session.goal_state import (
|
||||
GOAL_STATE_KEY,
|
||||
explicit_goal_requested,
|
||||
sustained_goal_turn,
|
||||
)
|
||||
from nanobot.session.recovery import REQUEST_ORIGIN_METADATA_KEY
|
||||
from nanobot.goal.runtime import GoalExecutionPolicy
|
||||
from nanobot.session.goal_state import GOAL_STATE_KEY
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.turn_continuation import (
|
||||
INTERNAL_CONTINUATION_KIND_META,
|
||||
INTERNAL_CONTINUATION_META,
|
||||
INTERNAL_CONTINUATION_RUN_STARTED_AT_META,
|
||||
_save_skip_for_turn,
|
||||
internal_continuation_run_started_at,
|
||||
maybe_continue_turn,
|
||||
should_finalize_on_max_iterations,
|
||||
should_stream_budget_response,
|
||||
sustained_goal_continuation_inbound,
|
||||
iteration_limit_context,
|
||||
record_iteration_limit,
|
||||
save_skip_for_turn,
|
||||
should_persist_user_message,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_maybe_continue_turn_queues_internal_message():
|
||||
meta = {
|
||||
GOAL_STATE_KEY: {
|
||||
"status": "active",
|
||||
"objective": "Finish the migration.",
|
||||
"ui_summary": "migration",
|
||||
},
|
||||
}
|
||||
messages = [
|
||||
{"role": "system", "content": "system"},
|
||||
{"role": "user", "content": "start"},
|
||||
{"role": "assistant", "content": "paused"},
|
||||
]
|
||||
pending: asyncio.Queue[InboundMessage] = asyncio.Queue()
|
||||
ctx = SimpleNamespace(
|
||||
session=SimpleNamespace(metadata=meta),
|
||||
msg=InboundMessage(
|
||||
channel="feishu",
|
||||
sender_id="u1",
|
||||
chat_id="c1",
|
||||
content="start",
|
||||
metadata={
|
||||
"message_id": "msg-1",
|
||||
"origin_message_id": "msg-0",
|
||||
"_wants_stream": True,
|
||||
"webui": True,
|
||||
"original_command": "/goal",
|
||||
"goal_requested": True,
|
||||
},
|
||||
),
|
||||
session_key="feishu:c1",
|
||||
request_context=RequestContext(
|
||||
channel="feishu", chat_id="c1", message_id="msg-1", turn_id="turn-1",
|
||||
),
|
||||
pending_queue=pending,
|
||||
stop_reason="max_iterations",
|
||||
final_content="paused",
|
||||
all_messages=messages,
|
||||
suppress_response=False,
|
||||
visible_run_started_at=1234.5,
|
||||
)
|
||||
|
||||
assert await maybe_continue_turn(ctx, session_metadata=ctx.session.metadata) is True
|
||||
|
||||
queued = pending.get_nowait()
|
||||
assert queued.sender_id == "system:continuation"
|
||||
assert queued.metadata[INTERNAL_CONTINUATION_META] is True
|
||||
assert queued.metadata[INTERNAL_CONTINUATION_KIND_META] == "sustained_goal"
|
||||
assert sustained_goal_continuation_inbound(queued.metadata) is True
|
||||
assert queued.metadata[INTERNAL_CONTINUATION_RUN_STARTED_AT_META] == 1234.5
|
||||
assert internal_continuation_run_started_at(queued.metadata) == 1234.5
|
||||
assert queued.metadata["webui"] is True
|
||||
assert queued.metadata["message_id"] == "msg-1"
|
||||
assert queued.metadata[REQUEST_ORIGIN_METADATA_KEY] == {
|
||||
"message_id": "msg-1", "turn_id": "turn-1",
|
||||
}
|
||||
assert REQUEST_ORIGIN_METADATA_KEY not in ctx.msg.metadata
|
||||
assert queued.metadata["origin_message_id"] == "msg-0"
|
||||
assert queued.metadata["_wants_stream"] is True
|
||||
assert not explicit_goal_requested(queued.metadata)
|
||||
assert sustained_goal_turn(meta, message_metadata=queued.metadata)
|
||||
assert "Finish the migration." in queued.content
|
||||
assert ctx.all_messages == messages[:-1]
|
||||
assert ctx.final_content == ""
|
||||
assert ctx.suppress_response is True
|
||||
assert meta["_sustained_goal_continuation_rounds"] == 1
|
||||
@pytest.mark.parametrize("status", ["completed", "cancelled", "blocked"])
|
||||
async def test_goal_scope_reads_current_objective_and_closure(tmp_path, status):
|
||||
sessions = SessionManager(tmp_path)
|
||||
session = await sessions.state.get("feishu:c1")
|
||||
try:
|
||||
with GoalExecutionPolicy(sessions.state).scope(session.key, session.generation, persistent=True) as scope:
|
||||
assert await scope.continuation_prompt() is None
|
||||
await sessions.state.update_metadata(session.key, {
|
||||
GOAL_STATE_KEY: {"status": "active", "objective": "Finish the migration."},
|
||||
})
|
||||
assert "Finish the migration." in await scope.continuation_prompt()
|
||||
await sessions.state.update_metadata(session.key, {
|
||||
GOAL_STATE_KEY: {"status": "active", "objective": "A replacement."},
|
||||
})
|
||||
prompt = await scope.continuation_prompt()
|
||||
assert "A replacement." in prompt and "Finish the migration." not in prompt
|
||||
await sessions.state.update_metadata(session.key, {
|
||||
GOAL_STATE_KEY: {"status": status, "objective": "A replacement."},
|
||||
})
|
||||
assert await scope.continuation_prompt() is None
|
||||
finally:
|
||||
await sessions.state.aclose()
|
||||
|
||||
|
||||
def test_generic_internal_continuation_is_not_a_sustained_goal_continuation() -> None:
|
||||
assert sustained_goal_continuation_inbound({INTERNAL_CONTINUATION_META: True}) is False
|
||||
@pytest.mark.parametrize("operation", ["reset", "delete"])
|
||||
async def test_goal_scope_does_not_continue_a_replaced_generation(tmp_path, operation):
|
||||
sessions = SessionManager(tmp_path)
|
||||
session = await sessions.state.get("cli:test")
|
||||
await sessions.state.update_metadata(session.key, {
|
||||
GOAL_STATE_KEY: {"status": "active", "objective": "Old objective."},
|
||||
})
|
||||
try:
|
||||
with GoalExecutionPolicy(sessions.state).scope(session.key, session.generation, persistent=True) as scope:
|
||||
assert "Old objective." in await scope.continuation_prompt()
|
||||
if operation == "reset":
|
||||
await sessions.state.reset(session.key)
|
||||
else:
|
||||
assert await sessions.state.delete(session.key)
|
||||
assert await scope.continuation_prompt() is None
|
||||
replacement = await sessions.state.get(session.key)
|
||||
await sessions.state.update_metadata(session.key, {
|
||||
GOAL_STATE_KEY: {"status": "active", "objective": "New generation's objective."},
|
||||
})
|
||||
assert replacement.generation != session.generation
|
||||
assert await scope.continuation_prompt() is None
|
||||
with GoalExecutionPolicy(sessions.state).scope(session.key, replacement.generation, persistent=True) as scope:
|
||||
assert "New generation's objective." in await scope.continuation_prompt()
|
||||
finally:
|
||||
await sessions.state.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_internal_continuation_respects_round_limit():
|
||||
meta = {
|
||||
GOAL_STATE_KEY: {"status": "active", "objective": "x"},
|
||||
"_sustained_goal_continuation_rounds": 12,
|
||||
}
|
||||
ctx = SimpleNamespace(
|
||||
session=SimpleNamespace(metadata=meta),
|
||||
msg=InboundMessage(channel="feishu", sender_id="u1", chat_id="c1", content="start"),
|
||||
session_key="feishu:c1",
|
||||
pending_queue=asyncio.Queue(),
|
||||
stop_reason="max_iterations",
|
||||
final_content="paused",
|
||||
all_messages=[],
|
||||
)
|
||||
|
||||
assert should_stream_budget_response(
|
||||
stop_reason="max_iterations",
|
||||
pending_queue_available=True,
|
||||
session_metadata=meta,
|
||||
)
|
||||
assert await maybe_continue_turn(ctx, session_metadata=ctx.session.metadata) is False
|
||||
async def test_iteration_limit_guidance_is_for_the_next_user_request_not_recovery(tmp_path):
|
||||
sessions = SessionManager(tmp_path)
|
||||
session = await sessions.state.get("cli:test")
|
||||
request = RequestContext(channel="cli", chat_id="test", session_key=session.key)
|
||||
try:
|
||||
await sessions.state.mutate_metadata(
|
||||
session.key, lambda metadata: record_iteration_limit(metadata, "max_iterations"),
|
||||
)
|
||||
context = await iteration_limit_context(sessions.state, request)
|
||||
assert context is not None and "Follow the current request" in context.content
|
||||
recovery = RequestContext(
|
||||
channel="cli", chat_id="test", session_key=session.key,
|
||||
metadata={INTERNAL_CONTINUATION_META: True},
|
||||
)
|
||||
assert await iteration_limit_context(sessions.state, recovery) is None
|
||||
await sessions.state.mutate_metadata(
|
||||
session.key, lambda metadata: record_iteration_limit(metadata, "completed"),
|
||||
)
|
||||
assert await iteration_limit_context(sessions.state, request) is None
|
||||
finally:
|
||||
await sessions.state.aclose()
|
||||
|
||||
|
||||
def test_internal_continuation_requires_budget_boundary_and_queue():
|
||||
meta = {GOAL_STATE_KEY: {"status": "active", "objective": "x"}}
|
||||
|
||||
assert should_stream_budget_response(
|
||||
stop_reason="completed",
|
||||
pending_queue_available=True,
|
||||
session_metadata=meta,
|
||||
)
|
||||
assert should_stream_budget_response(
|
||||
stop_reason="max_iterations",
|
||||
pending_queue_available=False,
|
||||
session_metadata=meta,
|
||||
)
|
||||
assert not should_finalize_on_max_iterations(
|
||||
pending_queue_available=True,
|
||||
session_metadata=meta,
|
||||
)
|
||||
assert should_finalize_on_max_iterations(
|
||||
pending_queue_available=False,
|
||||
session_metadata=meta,
|
||||
)
|
||||
assert should_finalize_on_max_iterations(
|
||||
pending_queue_available=True,
|
||||
session_metadata={},
|
||||
)
|
||||
def test_explicit_recovery_does_not_persist_a_synthetic_user_input():
|
||||
metadata = {INTERNAL_CONTINUATION_META: True}
|
||||
assert not should_persist_user_message(metadata)
|
||||
assert save_skip_for_turn(
|
||||
message_metadata=metadata, initial_message_count=3, input_persisted_early=False,
|
||||
) == 3
|
||||
assert should_persist_user_message(None)
|
||||
|
||||
|
||||
def test_save_skip_unchanged_for_standalone_current_message():
|
||||
assert _save_skip_for_turn(
|
||||
message_metadata=None,
|
||||
initial_message_count=3,
|
||||
input_persisted_early=True,
|
||||
assert save_skip_for_turn(
|
||||
message_metadata=None, initial_message_count=3, input_persisted_early=True,
|
||||
) == 3
|
||||
assert _save_skip_for_turn(
|
||||
message_metadata=None,
|
||||
initial_message_count=3,
|
||||
input_persisted_early=False,
|
||||
assert save_skip_for_turn(
|
||||
message_metadata=None, initial_message_count=3, input_persisted_early=False,
|
||||
) == 2
|
||||
@@ -506,6 +506,189 @@ async def test_ephemeral_run_does_not_invoke_persisted_turn_callback(tmp_path):
|
||||
assert seen == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("existing_session", [False, True])
|
||||
@pytest.mark.parametrize("streamed", [False, True])
|
||||
async def test_ephemeral_goal_is_rejected_without_changing_session(
|
||||
tmp_path, monkeypatch, existing_session, streamed,
|
||||
):
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.goal.assembly import install_goal
|
||||
|
||||
provider = _fake_provider("test-model")
|
||||
provider.aclose = AsyncMock()
|
||||
provider.chat_stream_with_retry = AsyncMock()
|
||||
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model",
|
||||
builtin_assembly=install_goal)
|
||||
bot = Nanobot(loop)
|
||||
key = "sdk:temporary-goal"
|
||||
if existing_session:
|
||||
session = await loop.sessions.state.get(key)
|
||||
session.add_message("user", "Earlier durable message")
|
||||
await loop.sessions.state.prepare_input(session)
|
||||
before = loop.sessions.read_session_file(key)
|
||||
prepare_input = AsyncMock(wraps=loop.sessions.state.prepare_input)
|
||||
monkeypatch.setattr(loop.sessions.state, "prepare_input", prepare_input)
|
||||
try:
|
||||
if streamed:
|
||||
run = await bot.run_streamed("/goal temporary task", session_key=key, ephemeral=True)
|
||||
result = await run.wait()
|
||||
else:
|
||||
result = await bot.run("/goal temporary task", session_key=key, ephemeral=True)
|
||||
|
||||
assert result.content == "Goals can't start in a temporary session. Use a persistent session for `/goal`."
|
||||
provider.chat_stream_with_retry.assert_not_awaited()
|
||||
prepare_input.assert_not_awaited()
|
||||
assert loop.sessions.read_session_file(key) == before
|
||||
current = await loop.sessions.state.read(key)
|
||||
if existing_session:
|
||||
assert current is not None and current.policy.persist
|
||||
assert [row["content"] for row in current.messages] == ["Earlier durable message"]
|
||||
else:
|
||||
assert current is None
|
||||
finally:
|
||||
await bot.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sdk_from_config_assembles_goal_for_direct_runs(tmp_path, monkeypatch):
|
||||
import json
|
||||
|
||||
from nanobot.providers.base import GenerationSettings, LLMResponse, ToolCallRequest
|
||||
|
||||
config = tmp_path / "instance" / "config.json"
|
||||
config.parent.mkdir()
|
||||
config.write_text(json.dumps({"agents": {"defaults": {
|
||||
"workspace": str(tmp_path / "workspace"), "model": "test-model", "maxToolIterations": 1,
|
||||
}}}), encoding="utf-8")
|
||||
provider = _fake_provider("test-model")
|
||||
provider.aclose = AsyncMock()
|
||||
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="create", name="create_goal", arguments={"objective": "Verify the SDK task."},
|
||||
)]),
|
||||
LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||
id="complete", name="update_goal", arguments={"action": "complete", "recap": "Verified."},
|
||||
)]),
|
||||
LLMResponse(content="Verified."),
|
||||
])
|
||||
monkeypatch.setattr("nanobot.providers.factory.make_provider", lambda *_args: provider)
|
||||
bot = Nanobot.from_config(config)
|
||||
try:
|
||||
result = await bot.run("/goal Verify the SDK task", session_key="sdk:goal")
|
||||
assert result.content == "Verified."
|
||||
session = await bot._loop.sessions.state.read("sdk:goal")
|
||||
assert session.metadata["goal_state"]["status"] == "completed"
|
||||
assert provider.chat_stream_with_retry.await_count == 3
|
||||
assert all(call.kwargs["tools"] for call in provider.chat_stream_with_retry.await_args_list[:2])
|
||||
assert not provider.chat_stream_with_retry.await_args.kwargs.get("tools")
|
||||
finally:
|
||||
await bot.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ephemeral_sdk_turn_cannot_update_a_durable_goal(tmp_path):
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.goal.assembly import install_goal
|
||||
from nanobot.providers.base import LLMResponse, ToolCallRequest
|
||||
|
||||
provider = _fake_provider("test-model")
|
||||
provider.aclose = AsyncMock()
|
||||
provider.chat_stream_with_retry = AsyncMock(side_effect=[
|
||||
LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||
id="update", name="update_goal", arguments={"action": "complete", "recap": "Not allowed."},
|
||||
)]),
|
||||
LLMResponse(content="Temporary reply."),
|
||||
])
|
||||
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model",
|
||||
builtin_assembly=install_goal)
|
||||
bot = Nanobot(loop)
|
||||
session = await loop.sessions.state.get("sdk:existing-goal")
|
||||
await loop.sessions.state.update_metadata(session.key, {
|
||||
"goal_state": {"status": "active", "objective": "Keep this durable goal."},
|
||||
})
|
||||
before = loop.sessions.read_session_file(session.key)
|
||||
try:
|
||||
result = await bot.run("Temporary question", session_key=session.key, ephemeral=True)
|
||||
assert result.content == "Temporary reply."
|
||||
assert "requires an active chat session" in str(provider.chat_stream_with_retry.await_args.kwargs["messages"])
|
||||
assert loop.sessions.read_session_file(session.key) == before
|
||||
current = await loop.sessions.state.read(session.key)
|
||||
assert current.metadata["goal_state"]["status"] == "active"
|
||||
finally:
|
||||
await bot.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("operation", ["clear", "delete"])
|
||||
async def test_sdk_goal_tool_cannot_write_after_session_generation_changes(tmp_path, operation):
|
||||
from nanobot.agent.hook import AgentHook
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.goal.assembly import install_goal
|
||||
from nanobot.providers.base import LLMResponse, ToolCallRequest
|
||||
|
||||
waiting = asyncio.Event()
|
||||
release = asyncio.Event()
|
||||
executed = asyncio.Event()
|
||||
finish = asyncio.Event()
|
||||
|
||||
class HoldTool(AgentHook):
|
||||
async def before_execute_tools(self, _context):
|
||||
waiting.set()
|
||||
await release.wait()
|
||||
|
||||
async def _settle(self):
|
||||
executed.set()
|
||||
await finish.wait()
|
||||
|
||||
async def after_execute_tool(self, _context, _call, _tool, _params, _result):
|
||||
await self._settle()
|
||||
|
||||
async def on_execute_tool_error(self, _context, _call, _tool, _params, _error):
|
||||
await self._settle()
|
||||
|
||||
provider = _fake_provider("test-model")
|
||||
provider.aclose = AsyncMock()
|
||||
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content=None, tool_calls=[
|
||||
ToolCallRequest(id="create", name="create_goal", arguments={"objective": "Old execution."}),
|
||||
]))
|
||||
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model",
|
||||
builtin_assembly=install_goal)
|
||||
bot = Nanobot(loop)
|
||||
key = "sdk:generation-check"
|
||||
run = asyncio.create_task(bot.run("/goal Old execution", session_key=key, hooks=[HoldTool()]))
|
||||
try:
|
||||
await asyncio.wait_for(waiting.wait(), 5)
|
||||
if operation == "clear":
|
||||
await bot.sessions.clear(key)
|
||||
else:
|
||||
assert await bot.sessions.delete(key)
|
||||
release.set()
|
||||
await asyncio.wait_for(executed.wait(), 5)
|
||||
current = await loop.sessions.state.read_header(key)
|
||||
if operation == "delete":
|
||||
assert current is None
|
||||
else:
|
||||
assert current is not None and "goal_state" not in current.metadata
|
||||
finish.set()
|
||||
await asyncio.gather(run, return_exceptions=True)
|
||||
current = await loop.sessions.state.read_header(key)
|
||||
if operation == "delete":
|
||||
assert current is None
|
||||
else:
|
||||
assert current is not None and "goal_state" not in current.metadata
|
||||
finally:
|
||||
release.set()
|
||||
finish.set()
|
||||
await asyncio.gather(run, return_exceptions=True)
|
||||
await bot.aclose()
|
||||
|
||||
|
||||
def test_import_from_top_level():
|
||||
import nanobot
|
||||
|
||||
|
||||
@@ -619,17 +619,20 @@ async def test_empty_response_falls_back_without_retry(aiohttp_client) -> None:
|
||||
@pytest.mark.asyncio
|
||||
async def test_process_direct_accepts_media() -> None:
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.agent.turn_delivery import TurnDeliveryFactory
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.bus.runtime_events import RuntimeEventPublisher
|
||||
|
||||
loop = AgentLoop.__new__(AgentLoop)
|
||||
loop._session_locks = {}
|
||||
loop.bus = MessageBus()
|
||||
loop.runtime_event_publisher = RuntimeEventPublisher(loop.bus)
|
||||
loop.turn_delivery_factory = TurnDeliveryFactory(loop.bus)
|
||||
loop.runtime_event_publisher = loop.turn_delivery_factory.runtime_event_publisher
|
||||
|
||||
captured_msg = None
|
||||
|
||||
async def fake_process(msg, *, session_key="", on_progress=None, on_stream=None, on_stream_end=None, ephemeral=False):
|
||||
async def fake_process(
|
||||
msg, *, session_key="", on_progress=None, on_stream=None, on_stream_end=None, ephemeral=False, delivery=None,
|
||||
):
|
||||
nonlocal captured_msg
|
||||
captured_msg = msg
|
||||
return None
|
||||
|
||||
@@ -86,7 +86,7 @@ async def test_runner_recovery_diagnostics_obey_private_policy(log_content, kind
|
||||
if kind == "injection":
|
||||
spec.injection_callback = AsyncMock(side_effect=ValueError(_SECRET))
|
||||
elif kind == "continuation":
|
||||
spec.continuation_callback = MagicMock(side_effect=ValueError(_SECRET))
|
||||
spec.continuation_callback = AsyncMock(side_effect=ValueError(_SECRET))
|
||||
elif kind == "finalization":
|
||||
spec.max_iterations = 0
|
||||
provider.chat_stream_with_retry = AsyncMock(side_effect=ValueError(_SECRET))
|
||||
@@ -101,11 +101,14 @@ async def test_runner_recovery_diagnostics_obey_private_policy(log_content, kind
|
||||
spec.hook = BrokenFinallyHook()
|
||||
|
||||
with request_context(RequestContext(channel="websocket", chat_id="test", log_content=log_content)):
|
||||
if kind == "finally":
|
||||
if kind in {"finally", "continuation"}:
|
||||
with pytest.raises(ValueError, match=_SECRET):
|
||||
await AgentRunner().run(spec)
|
||||
else:
|
||||
await AgentRunner().run(spec)
|
||||
if kind == "continuation":
|
||||
assert all(_SECRET not in r["message"] for r in diagnostic_records)
|
||||
return
|
||||
errors = [r for r in diagnostic_records if r["level"].name == "ERROR"]
|
||||
assert errors
|
||||
assert all((r["exception"] is not None) is log_content for r in errors)
|
||||
|
||||
@@ -2,6 +2,7 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import socket
|
||||
import subprocess
|
||||
@@ -14,6 +15,7 @@ from urllib.parse import quote
|
||||
import httpx
|
||||
import pytest
|
||||
import websockets
|
||||
from aiohttp import web
|
||||
|
||||
from nanobot.agent.subagent_sessions import SubagentSessions
|
||||
from nanobot.agent.subagent_status import SubagentStatus
|
||||
@@ -473,3 +475,201 @@ def test_gateway_restart_restores_a_completed_answer_without_replaying_model(
|
||||
asyncio.run(assert_attach_state())
|
||||
finally:
|
||||
_stop_gateway(second)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stop_during_checkpoint", [False, True])
|
||||
async def test_real_gateway_goal_single_run_and_stop(tmp_path: Path, stop_during_checkpoint: bool) -> None:
|
||||
"""Exercise the actual gateway and WebSocket with a synthetic local model."""
|
||||
checkpoint_waiting = asyncio.Event()
|
||||
closing_request = asyncio.Event()
|
||||
release_close = asyncio.Event()
|
||||
requests: list[dict] = []
|
||||
|
||||
async def barrier(_request: web.Request) -> web.Response:
|
||||
checkpoint_waiting.set()
|
||||
return web.Response(text="ready")
|
||||
|
||||
async def model(request: web.Request) -> web.StreamResponse:
|
||||
payload = await request.json()
|
||||
is_title = any(
|
||||
"You write short, neutral chat titles" in str(message.get("content"))
|
||||
for message in payload.get("messages", [])
|
||||
)
|
||||
if is_title:
|
||||
text, reason, tool = "Synthetic goal", "stop", None
|
||||
else:
|
||||
requests.append(payload)
|
||||
number = len(requests)
|
||||
text, reason, tool = None, "tool_calls", None
|
||||
if number == 1:
|
||||
tool = ("create_goal", {"objective": "Verify the synthetic task."})
|
||||
elif number <= 16:
|
||||
tool = ("list_dir", {"path": "."})
|
||||
elif stop_during_checkpoint:
|
||||
assert number == 17
|
||||
assert "Handle this independent input" in str(payload["messages"])
|
||||
text, reason = "Handled independent input.", "content_filter"
|
||||
elif number == 17:
|
||||
closing_request.set()
|
||||
await release_close.wait()
|
||||
tool = ("update_goal", {"action": "complete", "recap": "Verified."})
|
||||
else:
|
||||
assert number == 18 and not payload.get("tools")
|
||||
text, reason = "Verified.", "stop"
|
||||
message: dict = {"role": "assistant", "content": text}
|
||||
if tool is not None:
|
||||
message["tool_calls"] = [{
|
||||
"id": f"call-{len(requests)}", "type": "function",
|
||||
"function": {"name": tool[0], "arguments": json.dumps(tool[1])},
|
||||
}]
|
||||
usage = {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}
|
||||
if not payload.get("stream"):
|
||||
return web.json_response({
|
||||
"id": "synthetic", "object": "chat.completion", "created": 1,
|
||||
"model": "smoke-model", "choices": [{"index": 0, "message": message, "finish_reason": reason}],
|
||||
"usage": usage,
|
||||
})
|
||||
delta: dict = {"role": "assistant"}
|
||||
if text is not None:
|
||||
delta["content"] = text
|
||||
if tool is not None:
|
||||
delta["tool_calls"] = [{"index": 0, **message["tool_calls"][0]}]
|
||||
response = web.StreamResponse(headers={"Content-Type": "text/event-stream"})
|
||||
await response.prepare(request)
|
||||
for choice in (
|
||||
{"index": 0, "delta": delta, "finish_reason": None},
|
||||
{"index": 0, "delta": {}, "finish_reason": reason},
|
||||
):
|
||||
chunk = {"id": "synthetic", "object": "chat.completion.chunk", "created": 1,
|
||||
"model": "smoke-model", "choices": [choice], "usage": usage}
|
||||
await response.write(f"data: {json.dumps(chunk)}\n\n".encode())
|
||||
await response.write(b"data: [DONE]\n\n")
|
||||
return response
|
||||
|
||||
app = web.Application()
|
||||
app.router.add_get("/barrier", barrier)
|
||||
app.router.add_post("/v1/chat/completions", model)
|
||||
server = web.AppRunner(app)
|
||||
await server.setup()
|
||||
site = web.TCPSite(server, "127.0.0.1", 0)
|
||||
await site.start()
|
||||
assert site._server is not None and site._server.sockets # noqa: SLF001
|
||||
model_port = site._server.sockets[0].getsockname()[1] # noqa: SLF001
|
||||
ws_port, gateway_port = _free_port(), _free_port()
|
||||
home, workspace = tmp_path / "home", tmp_path / "workspace"
|
||||
home.mkdir()
|
||||
workspace.mkdir()
|
||||
config_path, log_path = tmp_path / "config.json", tmp_path / "gateway.log"
|
||||
_write_smoke_config(config_path, workspace=workspace, ws_port=ws_port, gateway_port=gateway_port)
|
||||
config = json.loads(config_path.read_text(encoding="utf-8"))
|
||||
config["providers"]["custom"]["apiBase"] = f"http://127.0.0.1:{model_port}/v1"
|
||||
config_path.write_text(json.dumps(config), encoding="utf-8")
|
||||
launcher = """
|
||||
import asyncio, sys, urllib.request
|
||||
from nanobot.session.state import SessionState
|
||||
original = SessionState.checkpoint_view
|
||||
barrier_url = sys.argv[3]
|
||||
held = False
|
||||
async def checkpoint(self, session, payload):
|
||||
global held
|
||||
await original(self, session, payload)
|
||||
results = payload.get('completed_tool_results', [])
|
||||
if barrier_url and not held and results and results[-1].get('tool_call_id') == 'call-16':
|
||||
held = True
|
||||
def signal():
|
||||
with urllib.request.urlopen(barrier_url) as response:
|
||||
response.read()
|
||||
await asyncio.to_thread(signal)
|
||||
await asyncio.Event().wait()
|
||||
SessionState.checkpoint_view = checkpoint
|
||||
home, config = sys.argv[1:3]
|
||||
sys.argv = ['nanobot', '--home', home, 'gateway', '--config', config]
|
||||
from nanobot.cli.entry import main
|
||||
main()
|
||||
"""
|
||||
env = {key: value for key, value in os.environ.items() if not key.startswith("NANOBOT_")}
|
||||
env.update({"HOME": str(home), "USERPROFILE": str(home), "APPDATA": str(home),
|
||||
"LOCALAPPDATA": str(home), "TMP": str(tmp_path), "TEMP": str(tmp_path),
|
||||
"NO_PROXY": "localhost,127.0.0.1", "no_proxy": "localhost,127.0.0.1"})
|
||||
creationflags = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
|
||||
process = None
|
||||
try:
|
||||
with log_path.open("wb") as log:
|
||||
process = subprocess.Popen(
|
||||
[sys.executable, "-c", launcher, str(home), str(config_path),
|
||||
f"http://127.0.0.1:{model_port}/barrier" if stop_during_checkpoint else ""],
|
||||
cwd=Path(__file__).resolve().parents[2], env=env, stdout=log,
|
||||
stderr=subprocess.STDOUT, creationflags=creationflags,
|
||||
)
|
||||
bootstrap = await asyncio.to_thread(
|
||||
_wait_for_bootstrap, f"http://127.0.0.1:{ws_port}", process, log_path,
|
||||
)
|
||||
async with websockets.connect(bootstrap["ws_url"] + "?token=" + bootstrap["token"] + "&client_id=goal-e2e") as ws:
|
||||
await _recv_until(ws, "ready")
|
||||
await ws.send(json.dumps({"type": "new_chat"}))
|
||||
chat_id = (await _recv_until(ws, "attached"))["chat_id"]
|
||||
await _recv_until(ws, "session_updated")
|
||||
await ws.send(json.dumps({"type": "message", "chat_id": chat_id,
|
||||
"content": "/goal Verify the synthetic task",
|
||||
"webui": True, "turn_id": "goal-e2e"}))
|
||||
events: list[dict] = []
|
||||
|
||||
async def receive_until(predicate):
|
||||
async with asyncio.timeout(20):
|
||||
while True:
|
||||
event = json.loads(await ws.recv())
|
||||
events.append(event)
|
||||
if predicate(event):
|
||||
return event
|
||||
|
||||
if stop_during_checkpoint:
|
||||
await asyncio.wait_for(checkpoint_waiting.wait(), 20)
|
||||
await ws.send(json.dumps({"type": "message", "chat_id": chat_id,
|
||||
"content": "/stop", "webui": True}))
|
||||
end = await receive_until(lambda event: event.get("event") == "turn_end")
|
||||
assert end.get("outcome") == "cancelled"
|
||||
assert end["goal_state"]["status"] == "active"
|
||||
await receive_until(lambda event: event.get("event") == "goal_status" and event.get("status") == "idle")
|
||||
assert len(requests) == 16
|
||||
running = [event for event in events if event.get("event") == "goal_status" and event.get("status") == "running"]
|
||||
# Submitting Stop hydrates the current status before cancellation.
|
||||
assert {event.get("turn_id") for event in running} == {"goal-e2e"}
|
||||
assert running[0]["started_at"] > 0
|
||||
assert len({event["started_at"] for event in running}) == 1
|
||||
assert sum(event.get("event") == "turn_end" for event in events) == 1
|
||||
await ws.send(json.dumps({"type": "message", "chat_id": chat_id,
|
||||
"content": "Handle this independent input", "webui": True,
|
||||
"turn_id": "follow-up"}))
|
||||
followup = await receive_until(lambda event: event.get("event") == "turn_end")
|
||||
assert followup.get("turn_id") == "follow-up"
|
||||
assert len(requests) == 17
|
||||
else:
|
||||
await asyncio.wait_for(closing_request.wait(), 20)
|
||||
await receive_until(lambda event: event.get("event") == "goal_status" and event.get("status") == "running")
|
||||
assert not any(event.get("event") == "turn_end" for event in events)
|
||||
release_close.set()
|
||||
end = await receive_until(lambda event: event.get("event") == "turn_end")
|
||||
assert end.get("turn_id") == "goal-e2e"
|
||||
assert not end["goal_state"]["active"]
|
||||
assert len(requests) == 18
|
||||
await receive_until(lambda event: event.get("event") == "goal_status" and event.get("status") == "idle")
|
||||
assert sum(event.get("event") == "goal_status" and event.get("status") == "running" for event in events) == 1
|
||||
assert sum(event.get("event") == "turn_end" for event in events) == 1
|
||||
assert any(event.get("event") == "goal_state" and event.get("goal_state", {}).get("active") for event in events)
|
||||
reconnect_bootstrap = await asyncio.to_thread(_get_bootstrap, f"http://127.0.0.1:{ws_port}/webui/bootstrap")
|
||||
async with websockets.connect(reconnect_bootstrap["ws_url"] + "?token=" + reconnect_bootstrap["token"] + "&client_id=goal-reconnect") as reconnected:
|
||||
await _recv_until(reconnected, "ready")
|
||||
await reconnected.send(json.dumps({"type": "attach", "chat_id": chat_id}))
|
||||
await _recv_until(reconnected, "attached")
|
||||
state = await _recv_until(reconnected, "goal_state")
|
||||
assert state["goal_state"] == {"active": False}
|
||||
finally:
|
||||
release_close.set()
|
||||
if process is not None and process.poll() is None:
|
||||
if sys.platform == "win32":
|
||||
subprocess.run(["taskkill", "/PID", str(process.pid), "/T", "/F"],
|
||||
capture_output=True, check=True, creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
else:
|
||||
process.terminate()
|
||||
process.wait(timeout=30)
|
||||
await server.cleanup()
|
||||
@@ -0,0 +1,130 @@
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.bus.outbound_events import GoalStateSyncEvent, TurnEndEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.bus.runtime_events import GoalStateChanged, RuntimeEventContext
|
||||
from nanobot.session.goal_state import GOAL_STATE_KEY, goal_state_runtime_lines
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.webui_turns import WebuiTurnCoordinator
|
||||
from nanobot.webui.goal_state import goal_state_ws_blob
|
||||
from nanobot.webui.session_projection import WebUISessionProjection
|
||||
|
||||
|
||||
def test_goal_state_ws_blob_inactive_when_missing_or_completed():
|
||||
assert goal_state_ws_blob(None) == {"active": False}
|
||||
assert goal_state_ws_blob({}) == {"active": False}
|
||||
assert goal_state_ws_blob({GOAL_STATE_KEY: {"status": "completed", "objective": "x"}}) == {
|
||||
"active": False,
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("current_goal", [None, {"status": "completed"}])
|
||||
def test_goal_state_ws_does_not_revive_superseded_legacy_goal(current_goal):
|
||||
metadata = {
|
||||
GOAL_STATE_KEY: current_goal,
|
||||
"thread_goal": {"status": "active", "objective": "Old goal"},
|
||||
}
|
||||
|
||||
assert goal_state_ws_blob(metadata) == {"active": False}
|
||||
|
||||
|
||||
def test_goal_state_ws_blob_active_shape():
|
||||
meta = {
|
||||
GOAL_STATE_KEY: {
|
||||
"status": "active",
|
||||
"objective": "Build feature.",
|
||||
"ui_summary": "feat",
|
||||
},
|
||||
}
|
||||
assert goal_state_ws_blob(meta) == {
|
||||
"active": True,
|
||||
"status": "active",
|
||||
"ui_summary": "feat",
|
||||
"objective": "Build feature.",
|
||||
}
|
||||
|
||||
|
||||
def test_goal_state_ws_blob_preserves_blocked_state_for_host_attention():
|
||||
meta = {
|
||||
GOAL_STATE_KEY: {
|
||||
"status": "blocked",
|
||||
"objective": "Deploy safely.",
|
||||
"ui_summary": "Approval required",
|
||||
"recap": "Production access is required.",
|
||||
},
|
||||
}
|
||||
assert goal_state_ws_blob(meta) == {
|
||||
"active": False,
|
||||
"status": "blocked",
|
||||
"ui_summary": "Approval required",
|
||||
"objective": "Deploy safely.",
|
||||
"recap": "Production access is required.",
|
||||
}
|
||||
|
||||
|
||||
def test_goal_state_ws_truncation_is_display_only_for_legacy_json():
|
||||
objective = "x" * 598 + " " + "finish the objective"
|
||||
summary = "s" * 130
|
||||
recap = "r" * 250
|
||||
legacy_goal = json.dumps({
|
||||
"status": "active",
|
||||
"objective": objective,
|
||||
"ui_summary": summary,
|
||||
"recap": recap,
|
||||
})
|
||||
metadata = {"thread_goal": legacy_goal}
|
||||
|
||||
assert goal_state_ws_blob(metadata) == {
|
||||
"active": True,
|
||||
"status": "active",
|
||||
"objective": "x" * 598 + "…",
|
||||
"ui_summary": summary[:120],
|
||||
"recap": recap[:240],
|
||||
}
|
||||
assert metadata["thread_goal"] == legacy_goal
|
||||
assert goal_state_runtime_lines(metadata) == [
|
||||
"Goal (active):", objective, f"Summary: {summary}",
|
||||
]
|
||||
|
||||
|
||||
async def test_long_goal_uses_same_display_snapshot_for_live_end_and_reconnect(tmp_path):
|
||||
sessions = SessionManager(tmp_path)
|
||||
bus = MessageBus()
|
||||
coordinator = WebuiTurnCoordinator(
|
||||
bus=bus, sessions=sessions, schedule_background=lambda coro: coro.close(),
|
||||
)
|
||||
coordinator.subscribe()
|
||||
key = "websocket:goal-view"
|
||||
objective = "x" * 700
|
||||
metadata = {GOAL_STATE_KEY: {"status": "active", "objective": objective}}
|
||||
expected = {"active": True, "status": "active", "objective": "x" * 600 + "…"}
|
||||
try:
|
||||
await sessions.state.get(key)
|
||||
await sessions.state.update_metadata(key, metadata)
|
||||
await bus.publish(GoalStateChanged(
|
||||
context=RuntimeEventContext(channel="websocket", chat_id="goal-view", session_key=key),
|
||||
session_metadata=metadata,
|
||||
))
|
||||
live_event = bus.outbound.get_nowait().event
|
||||
assert isinstance(live_event, GoalStateSyncEvent)
|
||||
assert live_event.goal_state == expected
|
||||
|
||||
await coordinator.handle_turn_end(
|
||||
InboundMessage(channel="websocket", sender_id="user", chat_id="goal-view", content="go"),
|
||||
session_key=key, latency_ms=None,
|
||||
)
|
||||
end_event = bus.outbound.get_nowait().event
|
||||
assert isinstance(end_event, TurnEndEvent)
|
||||
assert end_event.goal_state == expected
|
||||
|
||||
assert await WebUISessionProjection(sessions).hydration_events(key, "goal-view") == (
|
||||
{"event": "goal_state", "chat_id": "goal-view", "goal_state": expected},
|
||||
)
|
||||
stored = await sessions.state.read_metadata(key)
|
||||
assert stored is not None
|
||||
assert stored["metadata"][GOAL_STATE_KEY]["objective"] == objective
|
||||
finally:
|
||||
await sessions.state.aclose()
|
||||
@@ -101,7 +101,7 @@ async def test_hydration_events_restore_goal_and_running_turn(
|
||||
)
|
||||
|
||||
|
||||
async def test_hydration_events_are_quiet_without_actionable_state(
|
||||
async def test_hydration_clears_stale_goal_without_an_active_goal(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
sessions = MagicMock()
|
||||
@@ -115,7 +115,7 @@ async def test_hydration_events_are_quiet_without_actionable_state(
|
||||
assert await WebUISessionProjection(sessions).hydration_events(
|
||||
"websocket:chat-1",
|
||||
"chat-1",
|
||||
) == ()
|
||||
) == ({"event": "goal_state", "chat_id": "chat-1", "goal_state": {"active": False}},)
|
||||
|
||||
|
||||
async def test_hydration_yields_during_metadata_read_and_reads_live_turn_on_loop(
|
||||
@@ -157,4 +157,5 @@ async def test_hydration_yields_during_metadata_read_and_reads_live_turn_on_loop
|
||||
finally:
|
||||
release.set()
|
||||
events = await task
|
||||
assert events[0]["status"] == "running"
|
||||
assert events[0]["goal_state"] == {"active": False}
|
||||
assert events[1]["status"] == "running"
|
||||
Reference in new issue
Block a user