fix(tui): accept goal requests during active turns (#5981)

* fix(tui): accept goal requests during active turns

* fix(goal): reuse live input routing and remove busy guards

* test(goal): cover followup streams across iteration budgets

* refactor(goal): expand slash commands into hidden agent input

* fix(goal): keep generated input permission scoped to users

* refactor(agent): encapsulate goal input permission scope

* refactor(goal): preserve task text without prompt wrapper

* test(goal): consolidate coverage and exercise restart recovery

* test(goal): wait for recovery reply without task registry race
This commit is contained in:
chengyongru authored and GitHub committed 2026-09-30 13:08:13 +08:00
1 parent b46d4dfd7d
commit 99ba062a97
15 files changed
+613 -360

No files matched your search

+60
View File
@@ -0,0 +1,60 @@
import asyncio
import pytest
from nanobot.agent.goal_permission import (
GoalInputScope,
goal_mutation_allowed,
goal_mutation_permission,
revoke_goal_mutation_permission,
)
from nanobot.bus.events import InboundMessage
def goal_message(**overrides):
fields = dict(
channel="websocket", sender_id="user", chat_id="test", content="Execute the plan",
metadata={"goal_requested": True},
)
fields.update(overrides)
return InboundMessage(**fields)
@pytest.mark.parametrize("overrides", [
{"channel": "system", "input_role": "user"},
{"sender_id": "subagent"},
{"input_role": "system"},
{"metadata": {"goal_requested": True, "_internal_continuation": True}},
{"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):
message = goal_message(**overrides)
with goal_mutation_permission(True):
with GoalInputScope(message) as scope:
assert goal_mutation_allowed() is False
scope.consume_inputs([message])
assert goal_mutation_allowed() is False
assert goal_mutation_allowed() is True
def test_revoked_permission_requires_a_new_explicit_request_to_reauthorize():
with GoalInputScope(goal_message()) as scope:
assert goal_mutation_allowed() is True
revoke_goal_mutation_permission()
scope.consume_inputs([goal_message(content="ok", metadata={})])
assert goal_mutation_allowed() is False
scope.consume_inputs([goal_message(content="Execute another plan")])
assert goal_mutation_allowed() is True
assert goal_mutation_allowed() is False
@pytest.mark.parametrize("error", [RuntimeError, asyncio.CancelledError])
def test_injected_permission_is_cleared_on_abnormal_exit(error):
with pytest.raises(error):
with GoalInputScope() as scope:
assert goal_mutation_allowed() is False
scope.consume_inputs([goal_message()])
assert goal_mutation_allowed() is True
raise error()
assert goal_mutation_allowed() is False
+27 -10
View File
@@ -581,11 +581,12 @@ class TestToolEventProgress:
assert {event.stream_id for event in [*deltas, *endings]} == {deltas[0].stream_id}
@pytest.mark.asyncio
@pytest.mark.parametrize("max_iterations", [1, 2])
async def test_followup_after_truncation_starts_a_new_stream(
self, tmp_path: Path,
self, tmp_path: Path, max_iterations: int,
) -> None:
loop = _make_loop(tmp_path)
loop.max_iterations = 1
loop.max_iterations = max_iterations
loop.tools.get_definitions = MagicMock(return_value=[])
_attach_webui_runtime_events(loop, loop.bus)
calls = 0
@@ -597,11 +598,17 @@ class TestToolEventProgress:
await on_content_delta("old partial")
loop._enqueue_session_message(InboundMessage(
channel="websocket", sender_id="u", chat_id="test", content="new question",
metadata={"_wants_stream": True},
))
return LLMResponse(content="old partial", finish_reason="length")
has_followup = any(
"new question" in str(message.get("content", ""))
for message in kwargs["messages"]
)
answer = "new answer" if has_followup else "old ending"
if on_content_delta is not None:
await on_content_delta("new answer")
return LLMResponse(content="new answer", finish_reason="stop")
await on_content_delta(answer)
return LLMResponse(content=answer, finish_reason="stop")
loop.provider.chat_stream_with_retry = chat
try:
@@ -616,15 +623,25 @@ class TestToolEventProgress:
endings = [
message.event for message in outbound if isinstance(message.event, StreamEndEvent)
]
assert [event.content for event in deltas] == ["old partial", "new answer"]
assert deltas[0].stream_id != deltas[1].stream_id
assert [(event.resuming, event.merge_next) for event in endings] == [
(True, False), (False, False),
]
if max_iterations == 1:
assert calls == 3
assert [event.content for event in deltas] == [
"old partial", "\n\nold ending", "new answer",
]
assert [(event.resuming, event.merge_next) for event in endings] == [
(True, True), (False, False), (False, False),
]
else:
assert calls == 2
assert [event.content for event in deltas] == ["old partial", "new answer"]
assert [(event.resuming, event.merge_next) for event in endings] == [
(True, False), (False, False),
]
assert deltas[0].stream_id != deltas[-1].stream_id
assert [
message.content for message in outbound
if isinstance(message.event, StreamedResponseEvent)
] == ["new answer"]
] == (["old partial\n\nold ending", "new answer"] if max_iterations == 1 else ["new answer"])
finally:
await loop.aclose()
+4 -18
View File
@@ -153,17 +153,6 @@ async def test_goal_command_can_implement_plan_from_prior_discussion(tmp_path):
],
usage=None,
),
LLMResponse(
content="trying to start another goal",
tool_calls=[
ToolCallRequest(
id="call_create_again",
name="create_goal",
arguments={"objective": "Start an unrelated follow-up."},
)
],
usage=None,
),
LLMResponse(content="done", tool_calls=[], usage=None),
])
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model")
@@ -186,14 +175,11 @@ async def test_goal_command_can_implement_plan_from_prior_discussion(tmp_path):
assert session.metadata[GOAL_STATE_KEY]["status"] == "completed"
first_request = provider.chat_stream_with_retry.await_args_list[0].kwargs["messages"]
assert "staged migration plan" in str(first_request)
assert "/goal implement the plan above" in str(first_request)
assert "implement the plan above" in str(first_request)
assert _GOAL_RUNTIME_GUIDANCE_TAG in str(first_request)
final_request = provider.chat_stream_with_retry.await_args_list[-1].kwargs["messages"]
assert "create_goal is unavailable for this turn" in str(final_request)
assert _GOAL_RUNTIME_GUIDANCE_TAG in str(session.messages[2]["content"])
assert _GOAL_RUNTIME_GUIDANCE_TAG not in str(
public_history_message(session.messages[2])["content"]
)
assert session.messages[2]["content"] == "/goal implement the plan above"
assert session.messages[3]["_hidden_history"] == {"kind": "goal_request"}
assert _GOAL_RUNTIME_GUIDANCE_TAG in str(session.messages[3]["content"])
@pytest.mark.asyncio
+263
View File
@@ -0,0 +1,263 @@
"""Explicit goal requests can steer a running session without restarting it."""
import asyncio
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.bus.events import InboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.providers.base import GenerationSettings, LLMResponse, 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
@pytest.mark.parametrize("command", [
"/goal execute the agreed plan",
"/GOAL@nanobot execute the agreed plan",
"/goal /tmp/project: execute the agreed plan",
])
async def test_goal_input_enters_running_turn_with_scoped_permission(tmp_path, command):
task = command.split(" ", 1)[1]
first_call = asyncio.Event()
release = asyncio.Event()
calls = []
permissions = []
provider = MagicMock()
provider.get_default_model.return_value = "test-model"
provider.generation = GenerationSettings()
provider.estimate_prompt_tokens.return_value = (100, "test")
async def respond(**kwargs):
calls.append(str(kwargs["messages"]))
permissions.append(goal_mutation_allowed())
if len(calls) == 1:
first_call.set()
await release.wait()
return LLMResponse(content="The plan is to verify the migration.")
if len(calls) == 2:
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
id="create", name="create_goal",
arguments={"objective": "Verify the migration as agreed in this conversation."},
)])
if len(calls) == 3:
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
id="complete", name="update_goal",
arguments={"action": "complete", "recap": "Migration verified."},
)])
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")
process = AsyncMock(wraps=loop._process_message)
loop._process_message = process
run = asyncio.create_task(loop.run())
try:
await loop.bus.publish_inbound(InboundMessage(
channel="cli", sender_id="user", chat_id="test", content="Discuss the migration.",
))
await asyncio.wait_for(first_call.wait(), 3)
await loop.bus.publish_inbound(InboundMessage(
channel="cli", sender_id="user", chat_id="test", content=command,
))
async with asyncio.timeout(3):
while loop._pending_queues["cli:test"].empty():
await asyncio.sleep(0)
assert len(calls) == 1
release.set()
await asyncio.wait_for(asyncio.gather(*loop._active_tasks["cli:test"]), 5)
session = loop.sessions.get_or_create("cli:test")
assert process.await_count == 1
assert permissions[:3] == [False, True, True]
assert "Discuss the migration" in calls[1]
assert task in calls[1]
assert "Goal Runtime Guidance" in calls[1]
assert session.metadata[GOAL_STATE_KEY]["status"] == "completed"
assert "Verify the migration" in session.metadata[GOAL_STATE_KEY]["objective"]
assert goal_mutation_allowed() is False
persisted = SessionManager(tmp_path).get_or_create("cli:test").messages
visible = public_history_messages([
row for row in persisted if not is_hidden_history_message(row)
])
assert sum(row.get("content") == command for row in visible) == 1
hidden = [row for row in persisted if is_hidden_history_message(row)]
assert len(hidden) == 1
assert public_history_messages(hidden)[0]["content"] == task
finally:
release.set()
loop.stop()
await asyncio.wait_for(run, 5)
async def test_scheduled_goal_command_cannot_generate_internal_input(tmp_path):
msg = InboundMessage(
channel="cli", sender_id="user", chat_id="test", content="/goal execute",
metadata={"_cron_trigger": {"job_id": "job"}},
)
loop = AgentLoop(bus=MessageBus(), provider=MagicMock(), 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()
assert "only be started by a user" in response.content
assert loop._pending_queues == {}
assert goal_mutation_allowed() is False
assert loop.sessions.get_or_create(msg.session_key).messages == []
finally:
await loop.aclose()
@pytest.mark.parametrize("boundary", ["text", "tool", "error", "empty"])
async def test_goal_at_iteration_limit_stays_queued_for_a_tool_capable_turn(tmp_path, boundary):
from agent.session_helpers import run_session
provider = MagicMock()
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", max_iterations=1,
)
calls = []
goal = InboundMessage(
channel="cli", sender_id="user", chat_id="test", content="/goal verify the migration",
)
async def respond(**kwargs):
calls.append(str(kwargs["messages"]))
if len(calls) == 1:
await loop._dispatch_command_inline(
goal, goal.session_key, goal.content, loop.commands.dispatch,
)
if boundary == "tool":
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
id="list", name="list_dir", arguments={"path": "."},
)])
if boundary == "error":
return LLMResponse(content="Temporary model error", finish_reason="error")
if boundary == "empty":
return LLMResponse(content="")
return LLMResponse(content="The migration plan is ready.")
if kwargs.get("tools") and GOAL_STATE_KEY not in loop.sessions.get_or_create("cli:test").metadata:
assert goal_mutation_allowed() is True
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
id="create", name="create_goal",
arguments={"objective": "Verify the migration."},
)])
if kwargs.get("tools"):
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
id="complete", name="update_goal",
arguments={"action": "complete", "recap": "Verified."},
)])
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="test", content="Discuss the migration.",
))
session = loop.sessions.get_or_create("cli:test")
assert session.metadata[GOAL_STATE_KEY]["status"] == "completed"
goal_calls = [call for call in calls if "Goal Runtime Guidance" in call]
assert goal_calls
assert "Discuss the migration" in goal_calls[0]
assert "verify the migration" in goal_calls[0]
assert goal_mutation_allowed() is False
finally:
await loop.aclose()
async def test_generated_goal_input_survives_pending_followup_recovery(tmp_path):
from nanobot.command.router import CommandContext
from nanobot.session.recovery import pending_followups, record_pending_followup
provider = MagicMock()
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")
message = InboundMessage(
channel="websocket", sender_id="user", chat_id="test", content="/goal /stop",
)
try:
generated = await loop.commands.dispatch(CommandContext(
msg=message, session=None, key=message.session_key,
raw=message.content, loop=loop, is_user_turn=True,
))
assert isinstance(generated, InboundMessage)
session = loop.sessions.get_or_create(message.session_key)
assert record_pending_followup(session, generated)
loop.sessions.save(session)
finally:
await loop.aclose()
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model")
session = loop.sessions.get_or_create(message.session_key)
recovered, = pending_followups(session)
responses = iter([
LLMResponse(content=None, tool_calls=[ToolCallRequest(
id="create", name="create_goal", arguments={"objective": "Verify the migration."},
)]),
LLMResponse(content=None, tool_calls=[ToolCallRequest(
id="complete", name="update_goal", arguments={"action": "complete", "recap": "Verified."},
)]),
LLMResponse(content="done"),
])
async def respond(**kwargs):
assert any(
row.get("role") == "user" and row.get("content", "").startswith("/stop")
for row in kwargs["messages"]
)
return next(responses)
provider.chat_stream_with_retry = AsyncMock(side_effect=respond)
run = asyncio.create_task(loop.run())
try:
assert recovered.content == "/stop"
assert recovered.metadata["goal_requested"] is True
assert goal_mutation_allowed() is False
await loop.bus.publish_inbound(recovered)
async with asyncio.timeout(5):
while (await loop.bus.consume_outbound()).content != "done":
pass
assert session.metadata[GOAL_STATE_KEY]["status"] == "completed"
assert pending_followups(session) == []
assert sum(row.get("content") == message.content for row in session.messages) == 1
assert sum(is_hidden_history_message(row) for row in session.messages) == 1
assert goal_mutation_allowed() is False
finally:
loop.stop()
await asyncio.wait_for(run, 5)
async def test_internal_continuation_cannot_inherit_goal_permission(tmp_path):
provider = MagicMock()
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")
message = InboundMessage(
channel="cli", sender_id="automation", chat_id="test", content="Continue working",
metadata={"goal_requested": True, "_internal_continuation": True},
)
provider.chat_stream_with_retry = AsyncMock(side_effect=[
LLMResponse(content=None, tool_calls=[ToolCallRequest(
id="create", name="create_goal", arguments={"objective": "An unauthorized goal."},
)]),
LLMResponse(content="done"),
])
try:
with goal_mutation_permission(True):
await loop._process_message(message, session_key="cli:test")
assert goal_mutation_allowed() is True
assert GOAL_STATE_KEY not in loop.sessions.get_or_create("cli:test").metadata
final_request = provider.chat_stream_with_retry.await_args.kwargs["messages"]
assert "create_goal is unavailable for this turn" in str(final_request)
assert goal_mutation_allowed() is False
finally:
await loop.aclose()
+60 -215
View File
@@ -1,249 +1,94 @@
"""Tests for caller-controlled continuation in AgentRunner.
When the continuation callback returns a message, the runner must not exit with
stop_reason="completed" after a plain-text final response. Instead it injects
that message and keeps looping, similar to a mid-turn injection.
"""
from __future__ import annotations
"""Caller-controlled continuation respects live state and the runner budget."""
from unittest.mock import AsyncMock, MagicMock
import pytest
from agent.runner_helpers import make_run_spec
from nanobot.agent.runner import AgentRunner
from nanobot.config.schema import AgentDefaults
from nanobot.providers.base import LLMProvider, LLMResponse
_MAX_TOOL_RESULT_CHARS = AgentDefaults().max_tool_result_chars
def _continue_goal() -> str:
return "Continue working toward the active sustained goal."
@pytest.mark.asyncio
async def test_runner_exits_normally_without_continuation_callback():
"""Without a continuation request, final text completes the run."""
from nanobot.agent.runner import AgentRunner
@pytest.fixture
def run_spec():
provider = MagicMock(spec=LLMProvider)
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(
content="all done", tool_calls=[], usage=None,
))
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="all done"))
tools = MagicMock()
tools.get_definitions.return_value = []
runner = AgentRunner()
result = await runner.run(make_run_spec(provider,
initial_messages=[{"role": "user", "content": "do task"}],
tools=tools,
model="test-model",
max_iterations=2,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
))
assert result.stop_reason == "completed"
assert result.final_content == "all done"
@pytest.mark.asyncio
async def test_runner_exits_normally_when_continuation_callback_returns_none():
"""A callback returning None leaves the final response terminal."""
from nanobot.agent.runner import AgentRunner
provider = MagicMock(spec=LLMProvider)
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(
content="all done", tool_calls=[], usage=None,
))
tools = MagicMock()
tools.get_definitions.return_value = []
runner = AgentRunner()
result = await runner.run(make_run_spec(provider,
initial_messages=[{"role": "user", "content": "do task"}],
tools=tools,
model="test-model",
max_iterations=2,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
continuation_callback=lambda: None,
))
assert result.stop_reason == "completed"
assert result.final_content == "all done"
@pytest.mark.asyncio
async def test_runner_continues_when_callback_returns_message():
"""A callback result after final text is injected for the next iteration.
We set max_iterations=3 and let the provider return final text every time.
Without the fix this would exit on the first iteration with stop_reason
"completed". With the fix the runner is forced to continue until
max_iterations is hit.
"""
from nanobot.agent.runner import AgentRunner
provider = MagicMock(spec=LLMProvider)
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(
content="still working", tool_calls=[], usage=None,
))
tools = MagicMock()
tools.get_definitions.return_value = []
runner = AgentRunner()
result = await runner.run(make_run_spec(provider,
return make_run_spec(
provider,
initial_messages=[{"role": "user", "content": "do task"}],
tools=tools,
model="test-model",
max_iterations=3,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
continuation_callback=_continue_goal,
))
# Because the callback keeps returning a message, the runner should never
# naturally complete. It loops until max_iterations is exhausted.
assert result.stop_reason == "max_iterations"
# The injected continuation message should be present in the message list.
user_msgs = [m for m in result.messages if m.get("role") == "user"]
assert any("active sustained goal" in str(m.get("content", "")) for m in user_msgs)
max_tool_result_chars=AgentDefaults().max_tool_result_chars,
)
@pytest.mark.asyncio
async def test_runner_respects_max_iterations_with_continuation():
"""A continuation request after one iteration still hits max_iterations."""
from nanobot.agent.runner import AgentRunner
@pytest.mark.parametrize("callback", [None, lambda: None], ids=["absent", "no-request"])
async def test_runner_completes_without_a_continuation_request(run_spec, callback):
run_spec.continuation_callback = callback
provider = MagicMock(spec=LLMProvider)
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(
content="still working", tool_calls=[], usage=None,
))
tools = MagicMock()
tools.get_definitions.return_value = []
result = await AgentRunner().run(run_spec)
runner = AgentRunner()
result = await runner.run(make_run_spec(provider,
initial_messages=[{"role": "user", "content": "do task"}],
tools=tools,
model="test-model",
max_iterations=1,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
continuation_callback=_continue_goal,
))
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 = lambda: continuation
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")
@pytest.mark.asyncio
async def test_runner_continuation_is_governed_by_max_iterations():
"""Caller-requested continuation is governed by max_iterations."""
from nanobot.agent.runner import AgentRunner
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",
)
callback = MagicMock(return_value="Continue working.")
run_spec.continuation_callback = callback
provider = MagicMock(spec=LLMProvider)
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(
content="still working", tool_calls=[], usage=None,
))
tools = MagicMock()
tools.get_definitions.return_value = []
max_iterations = 8
runner = AgentRunner()
result = await runner.run(make_run_spec(provider,
initial_messages=[{"role": "user", "content": "do task"}],
tools=tools,
model="test-model",
max_iterations=max_iterations,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
continuation_callback=_continue_goal,
finalize_on_max_iterations=False,
))
assert result.stop_reason == "max_iterations"
assert provider.chat_stream_with_retry.await_count == max_iterations
@pytest.mark.asyncio
async def test_runner_does_not_continue_on_error():
"""An LLM error remains terminal even when continuation is available."""
from nanobot.agent.runner import AgentRunner
provider = MagicMock(spec=LLMProvider)
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(
content=None, tool_calls=[], usage=None,
finish_reason="error",
))
tools = MagicMock()
tools.get_definitions.return_value = []
runner = AgentRunner()
result = await runner.run(make_run_spec(provider,
initial_messages=[{"role": "user", "content": "do task"}],
tools=tools,
model="test-model",
max_iterations=2,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
continuation_callback=_continue_goal,
))
result = await AgentRunner().run(run_spec)
assert result.stop_reason == "error"
assert run_spec.runtime.provider.chat_stream_with_retry.await_count == 1
callback.assert_not_called()
@pytest.mark.asyncio
async def test_runner_injects_continuation_callback_message():
"""The callback result becomes the injected user message."""
from nanobot.agent.runner import AgentRunner
async def test_runner_reads_continuation_state_after_each_response(run_spec):
continuation = None
calls = 0
provider = MagicMock(spec=LLMProvider)
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(
content="still working", tool_calls=[], usage=None,
))
tools = MagicMock()
tools.get_definitions.return_value = []
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.")
custom_msg = "CUSTOM_CONTINUE_PLEASE"
run_spec.runtime.provider.chat_stream_with_retry.side_effect = respond
run_spec.continuation_callback = lambda: continuation
runner = AgentRunner()
result = await runner.run(make_run_spec(provider,
initial_messages=[{"role": "user", "content": "do task"}],
tools=tools,
model="test-model",
max_iterations=2,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
continuation_callback=lambda: custom_msg,
))
result = await AgentRunner().run(run_spec)
user_msgs = [m for m in result.messages if m.get("role") == "user"]
assert any(custom_msg in str(m.get("content", "")) for m in user_msgs)
@pytest.mark.asyncio
async def test_runner_resolves_continuation_callback_lazily():
"""The continuation text can depend on goal metadata created during the run."""
from nanobot.agent.runner import AgentRunner
provider = MagicMock(spec=LLMProvider)
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(
content="still working", tool_calls=[], usage=None,
))
tools = MagicMock()
tools.get_definitions.return_value = []
calls = {"n": 0}
def dynamic_msg() -> str:
calls["n"] += 1
return "Goal (active):\nWrite the article draft."
runner = AgentRunner()
result = await runner.run(make_run_spec(provider,
initial_messages=[{"role": "user", "content": "do task"}],
tools=tools,
model="test-model",
max_iterations=1,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
continuation_callback=dynamic_msg,
finalize_on_max_iterations=False,
))
user_msgs = [m for m in result.messages if m.get("role") == "user"]
assert calls["n"] == 1
assert any("Write the article draft." in str(m.get("content", "")) for m in user_msgs)
assert calls == 2
assert result.stop_reason == "completed"
assert result.final_content == "The draft is complete."
+19 -11
View File
@@ -532,7 +532,7 @@ async def test_injected_followup_starts_new_length_recovery_chain():
@pytest.mark.asyncio
@pytest.mark.parametrize("max_iterations", [1, 3])
async def test_followup_interrupts_truncated_answer_before_next_request(max_iterations):
async def test_truncated_answer_followup_requires_remaining_iteration(max_iterations):
from nanobot.agent.hook import AgentHook, AgentHookContext
from nanobot.agent.runner import AgentRunner
@@ -571,12 +571,20 @@ async def test_followup_interrupts_truncated_answer_before_next_request(max_iter
injection_callback=_make_injection_callback(queue),
))
assert result.final_content == "4"
assert len(requests) == 2
assert endings[0] == (True, False)
second_request = "\n".join(str(message.get("content", "")) for message in requests[1])
assert "Never mind. What is 2+2?" in second_request
assert "Continue the same response from its exact endpoint" not in second_request
if max_iterations == 1:
assert "Never mind. What is 2+2?" not in second_request
assert queue.get_nowait()["content"] == "Never mind. What is 2+2?"
assert result.had_injections is False
assert result.final_content == "Unfinished old answer:\n\n4"
assert "Continue the same response from its exact endpoint" in second_request
else:
assert result.final_content == "4"
assert endings[0] == (True, False)
assert "Never mind. What is 2+2?" in second_request
assert queue.empty()
assert "Continue the same response from its exact endpoint" not in second_request
@pytest.mark.asyncio
@@ -1880,8 +1888,8 @@ async def test_max_iterations_without_finalization_keeps_late_injection_queued()
@pytest.mark.asyncio
async def test_max_iterations_finalization_consumes_late_injection():
"""The finalization model request receives the snapshot after the last iteration."""
async def test_max_iterations_finalization_keeps_late_injection_queued():
"""New input waits for a turn with tools instead of entering no-tools finalization."""
from nanobot.agent.hook import AgentHook
from nanobot.agent.runner import AgentRunner
from nanobot.bus.events import InboundMessage
@@ -1935,18 +1943,18 @@ async def test_max_iterations_finalization_consumes_late_injection():
))
assert result.stop_reason == "max_iterations"
assert result.had_injections is True
assert injection_queue.empty()
assert result.had_injections is False
assert injection_queue.get_nowait().content == "late follow-up after max iters"
assert call_count["n"] == 3
finalization_request = "\n".join(
str(message.get("content", "")) for message in captured_messages[-1]
)
assert "late follow-up after max iters" in finalization_request
assert "late follow-up after max iters" not in finalization_request
injected = [
m for m in result.messages
if m.get("role") == "user" and m.get("content") == "late follow-up after max iters"
]
assert len(injected) == 1
assert injected == []
@pytest.mark.asyncio
+27 -33
View File
@@ -5,7 +5,7 @@ import pytest
from nanobot.agent.goal_permission import goal_mutation_allowed
from nanobot.agent.loop import AgentLoop
from nanobot.bus.events import InboundMessage
from nanobot.bus.events import InboundMessage, OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.command.builtin import (
build_help_text,
@@ -16,6 +16,7 @@ from nanobot.command.builtin import (
)
from nanobot.command.router import CommandContext, CommandRouter
from nanobot.config.schema import ModelPresetConfig
from nanobot.session.history_visibility import HIDDEN_HISTORY_META
from nanobot.session.model_selection import (
SESSION_MODEL_PRESET_METADATA_KEY,
model_preset_from_metadata,
@@ -64,7 +65,8 @@ def _ctx(loop: AgentLoop, raw: str, args: str = "") -> CommandContext:
def _ctx_session(loop: AgentLoop, raw: str, args: str = "") -> CommandContext:
msg = InboundMessage(channel="cli", sender_id="user", chat_id="direct", content=raw)
return CommandContext(
msg=msg, session=MagicMock(), key=msg.session_key, raw=raw, args=args, loop=loop,
msg=msg, session=loop.sessions.get_or_create(msg.session_key),
key=msg.session_key, raw=raw, args=args, loop=loop,
is_user_turn=True,
)
@@ -256,34 +258,27 @@ async def test_goal_command_shows_usage_without_args(tmp_path) -> None:
@pytest.mark.asyncio
async def test_goal_command_rejects_mid_turn_without_session(tmp_path) -> None:
@pytest.mark.parametrize("with_session", [False, True])
async def test_goal_command_preserves_task_and_visible_command(tmp_path, with_session) -> None:
loop = _make_loop(tmp_path)
out = await cmd_goal(_ctx(loop, "/goal do work", args="do work"))
assert out is not None
assert out.channel == "cli"
assert out.chat_id == "direct"
assert out.metadata == {"render_as": "text"}
assert out.content == (
"A task is already running for this chat. "
"Use `/stop` first, then send `/goal <long-running task description>` again."
)
@pytest.mark.asyncio
async def test_goal_command_marks_turn_and_preserves_explicit_request(tmp_path) -> None:
loop = _make_loop(tmp_path)
ctx = _ctx_session(loop, "/goal audit the repo", args="audit the repo")
task = "检查 /tmp/project\n保留现有文件。"
command = f"/goal {task}"
ctx = _ctx_session(loop, command, args=task)
if not with_session:
ctx.session = None
out = await cmd_goal(ctx)
assert out is None
assert ctx.msg.content == "/goal audit the repo"
assert ctx.msg.metadata.get("original_command") == "/goal"
assert ctx.msg.metadata.get("original_content") == "/goal audit the repo"
assert ctx.msg.metadata.get("goal_requested") is True
assert isinstance(ctx.msg.metadata.get("goal_started_at"), int | float)
assert len(ctx.turn_scopes) == 1
with ctx.turn_scopes[0]:
assert goal_mutation_allowed() is True
assert isinstance(out, InboundMessage)
assert ctx.msg.content == command
assert out.content == task
assert out.metadata["original_content"] == command
assert out.metadata["goal_requested"] is True
assert out.metadata[HIDDEN_HISTORY_META] == {"kind": "goal_request"}
assert goal_mutation_allowed() is False
session = loop.sessions.get_or_create(ctx.key)
assert [(row["role"], row["content"]) for row in session.messages] == [
("user", command),
]
@pytest.mark.asyncio
@@ -293,14 +288,13 @@ async def test_goal_command_registered_on_router(tmp_path) -> None:
loop = _make_loop(tmp_path)
ctx = _ctx_session(loop, "/goal ship it", args="ship it")
out = await router.dispatch(ctx)
assert out is None
assert "ship it" in ctx.msg.content
assert len(ctx.turn_scopes) == 1
with ctx.turn_scopes[0]:
assert goal_mutation_allowed() is True
assert isinstance(out, InboundMessage)
assert out.content == "ship it"
assert out.metadata["goal_requested"] is True
assert goal_mutation_allowed() is False
@pytest.mark.asyncio
async def test_goal_command_does_not_allow_internal_turn(tmp_path) -> None:
loop = _make_loop(tmp_path)
@@ -321,7 +315,7 @@ async def test_goal_command_does_not_allow_internal_turn(tmp_path) -> None:
out = await cmd_goal(ctx)
assert out is not None
assert isinstance(out, OutboundMessage)
assert "only be started by a user" in out.content
assert ctx.turn_scopes == []