* 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
124 lines
4.2 KiB
Python
124 lines
4.2 KiB
Python
"""Tests for token-bounded session history replay."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from pathlib import Path
|
|
from unittest.mock import AsyncMock, MagicMock
|
|
|
|
import pytest
|
|
|
|
from nanobot.agent.loop import AgentLoop
|
|
from nanobot.bus.events import InboundMessage
|
|
from nanobot.bus.queue import MessageBus
|
|
from nanobot.providers.base import LLMResponse
|
|
from nanobot.session.manager import Session
|
|
|
|
|
|
def _make_loop(tmp_path: Path, context_window_tokens: int = 200_000) -> AgentLoop:
|
|
provider = MagicMock()
|
|
provider.get_default_model.return_value = "test-model"
|
|
provider.generation.max_tokens = 4096
|
|
return AgentLoop(
|
|
bus=MessageBus(),
|
|
provider=provider,
|
|
workspace=tmp_path,
|
|
model="test-model",
|
|
context_window_tokens=context_window_tokens,
|
|
)
|
|
|
|
|
|
def _populated_session(turns: int) -> Session:
|
|
session = Session(key="test:populated")
|
|
for index in range(turns):
|
|
session.add_message("user", f"msg-{index}")
|
|
session.add_message("assistant", f"reply-{index}")
|
|
return session
|
|
|
|
|
|
def _tool_round(call_id: str) -> list[dict]:
|
|
return [
|
|
{
|
|
"role": "assistant",
|
|
"content": None,
|
|
"tool_calls": [
|
|
{"id": call_id, "type": "function", "function": {"name": "x", "arguments": "{}"}}
|
|
],
|
|
},
|
|
{"role": "tool", "tool_call_id": call_id, "name": "x", "content": "ok"},
|
|
]
|
|
|
|
|
|
def test_default_history_has_no_message_count_limit() -> None:
|
|
session = _populated_session(1_001)
|
|
|
|
history = session.get_history()
|
|
|
|
assert len(history) == 2_002
|
|
assert history[0]["content"] == "msg-0"
|
|
assert history[-1]["content"] == "reply-1000"
|
|
|
|
|
|
def test_explicit_message_limit_still_starts_at_user_turn() -> None:
|
|
history = _populated_session(30).get_history(max_messages=25)
|
|
|
|
assert len(history) <= 25
|
|
assert history[0]["role"] == "user"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_process_message_hands_complete_replay_to_runner(tmp_path: Path) -> None:
|
|
loop = _make_loop(tmp_path, context_window_tokens=32_768)
|
|
loop.provider.chat_stream_with_retry = AsyncMock(
|
|
return_value=LLMResponse(content="ok", tool_calls=[], usage=None)
|
|
)
|
|
loop.tools.get_definitions = MagicMock(return_value=[])
|
|
|
|
session = await loop.sessions.state.import_messages("cli:test", _populated_session(30).messages)
|
|
expected_history = session.get_history()
|
|
loop.provider.aclose = AsyncMock()
|
|
result = await loop.process_direct("hello", session_key="cli:test")
|
|
|
|
assert result is not None
|
|
sent = loop.provider.chat_stream_with_retry.await_args.kwargs["messages"]
|
|
assert sent[1:-1] == expected_history
|
|
assert sent[-1]["content"].startswith("hello\n\n")
|
|
await loop.aclose()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_runner_checkpoint_keeps_current_user_as_replay_boundary(tmp_path: Path) -> None:
|
|
loop = _make_loop(tmp_path, context_window_tokens=8_000)
|
|
loop.provider.estimate_prompt_tokens.side_effect = (
|
|
lambda messages, tools, model: (100 * len(messages), "test")
|
|
)
|
|
loop.provider.chat_stream_with_retry = AsyncMock(
|
|
return_value=LLMResponse(content="ok", tool_calls=[], usage=None)
|
|
)
|
|
loop.tools.get_definitions = MagicMock(return_value=[])
|
|
|
|
session = loop.sessions.get_or_create("cli:test")
|
|
session.add_message("user", "old")
|
|
session.add_message("assistant", "old answer")
|
|
session.add_message("user", "long older turn")
|
|
for index in range(70):
|
|
session.messages.extend(_tool_round(f"older-{index}"))
|
|
session.add_message("assistant", "older final")
|
|
|
|
result = await loop._process_message(
|
|
InboundMessage(
|
|
channel="cli",
|
|
sender_id="user",
|
|
chat_id="test",
|
|
content="new question",
|
|
)
|
|
)
|
|
|
|
assert result is not None
|
|
sent_messages = loop.provider.chat_stream_with_retry.await_args.kwargs["messages"]
|
|
sent_text = "\n".join(str(message.get("content")) for message in sent_messages)
|
|
assert "new question" in sent_text
|
|
assert [message["role"] for message in sent_messages] == ["system", "user"]
|
|
assert sent_messages[1]["content"].startswith("new question\n\n")
|
|
assert "File access:" in sent_messages[1]["content"]
|
|
assert any(message.get("content") == "long older turn" for message in session.messages)
|