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:
chengyongruandchengyongru authored and GitHub committed 2026-11-03 22:47:00 +08:00
1 parent 3545539128
commit 62c2ed4e7e
68 files changed
+2683 -1421

No files matched your search

+1 -2
View File
@@ -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
+21
View File
@@ -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)
+89 -15
View File
@@ -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()
+3 -1
View File
@@ -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
+2 -1
View File
@@ -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
+1 -1
View File
@@ -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