Files
nanobot/tests/agent/test_runner_goal_continue.py
T
chengyongru 8f6a5594fb refactor(session): centralize state ownership in SQLite (#5943)
* fix(session): move persistence off event loop

* refactor(session): isolate async persistence boundary

* refactor(session): keep a single session manager

* refactor(session): use stateless async adapters

* fix(session): serialize local persistence without file-lock contention

* refactor(session): own async persistence and snapshot commits

* refactor(session): narrow persistence changes to async adapters

* refactor(session): remove redundant async forwarding helpers

* fix(command): offload compact session persistence

* fix(session): adapt idle compaction to current main

* fix(webui): offload session metadata persistence

* refactor(session): centralize state ownership in SQLite

* fix(session): skip storage for non-recoverable followups

* test(webui): honor the full gateway event deadline

* perf(session): persist incremental changes and reuse owner snapshots

* test(agent): allow durable worker shutdown in burst test

* fix(gateway): drain session storage on Windows console shutdown

* fix(session): enforce bounded ownership and lifecycle-safe persistence

* fix: reject unresolved home paths and stabilize platform tests

* fix(session): preserve request context compatibility and owner-backed tests

* docs: focus configuration guide on user-facing behavior

* fix(session): adapt goal admission to async ownership after rebase

* fix(session): integrate current gateway and subagent contracts

* fix(session): align rebased workspace admission and async tests

* fix(session): support compatible SQLite schema evolution

* test(agent): use session owner in workspace context regressions

* test: stabilize Windows lifecycle and browser checks

* refactor(session): remove premature JSONL file export

* ci: bound Windows full-suite worker concurrency

* chore: remove session state refactor notes

* fix(session): queue writes and retain worker connections

* perf(webui): read detached metadata for session and task lists

* perf(agent): bound prompt preparation and local token counting

* docs: remove internal session storage guide

* perf(session): skip archived transcripts during idle scans

* fix(session): coordinate turns and isolate legacy session data

Bind WebUI input generations to the execution session and serialize idle
and SDK compaction with turns. Keep turn drafts through preparation so the
latest channel route persists.

Move imported workspace JSONL and checkpoints to durable private backups
before gateway admission, resuming cleanup after interruptions. Remove
committed child sessions when task creation is cancelled.

Validation: focused Python and frontend regressions, Ruff, BasedPyright,
import boundaries, WebUI build, and isolated gateway/browser flows.

* fix(agent): keep cancellation hooks independent of prompt preparation

* fix(session): preserve admission, delivery, and migration contracts

* fix(agent): preserve cancellation settlement after rebase

* fix(session): preserve request attribution through async ownership
2026-10-16 17:28:47 +08:00

95 lines
3.5 KiB
Python

"""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
@pytest.fixture
def run_spec():
provider = MagicMock(spec=LLMProvider)
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="all done"))
tools = MagicMock()
tools.get_definitions.return_value = []
return make_run_spec(
provider,
initial_messages=[{"role": "user", "content": "do task"}],
tools=tools,
model="test-model",
max_iterations=3,
max_tool_result_chars=AgentDefaults().max_tool_result_chars,
)
@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)
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")
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 = AsyncMock(return_value="Continue working.")
run_spec.continuation_callback = callback
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()
async def test_runner_reads_continuation_state_after_each_response(run_spec):
continuation = None
calls = 0
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.")
run_spec.runtime.provider.chat_stream_with_retry.side_effect = respond
run_spec.continuation_callback = AsyncMock(side_effect=lambda: continuation)
result = await AgentRunner().run(run_spec)
assert calls == 2
assert result.stop_reason == "completed"
assert result.final_content == "The draft is complete."