refactor(sessions)!: retire the global shared session (#6621)
Co-authored-by: chengyongru <chengyongru.ai@gmail.com>
This commit is contained in:
1 parent
28d73b6942
commit
e6b0aec2a8
77 files changed
+311
-1255
No files matched your search
@@ -43,7 +43,6 @@ def make_loop(
|
||||
model: str = "test-model",
|
||||
context_window_tokens: int = 128_000,
|
||||
session_ttl_minutes: int = 0,
|
||||
unified_session: bool = False,
|
||||
tools_config=None,
|
||||
model_presets: dict | None = None,
|
||||
hooks: list | None = None,
|
||||
@@ -67,7 +66,6 @@ def make_loop(
|
||||
model=model,
|
||||
context_window_tokens=context_window_tokens,
|
||||
session_ttl_minutes=session_ttl_minutes,
|
||||
unified_session=unified_session,
|
||||
)
|
||||
if tools_config is not None:
|
||||
kwargs["tools_config"] = tools_config
|
||||
|
||||
@@ -33,8 +33,8 @@ async def save_completed_subagent(loop: AgentLoop, task_id: str, owner: str) ->
|
||||
|
||||
async def run_session(loop: AgentLoop, msg: InboundMessage) -> None:
|
||||
"""Submit input and wait for its session worker to finish."""
|
||||
(await loop._enqueue_session_message(msg))
|
||||
await asyncio.gather(*loop._active_tasks[loop._effective_session_key(msg)])
|
||||
await loop._enqueue_session_message(msg)
|
||||
await asyncio.gather(*loop._active_tasks[msg.session_key])
|
||||
|
||||
|
||||
async def stop_loop(loop: AgentLoop, worker: asyncio.Task[None], *, timeout: float) -> None:
|
||||
|
||||
@@ -19,13 +19,12 @@ from nanobot.events import NO_EVENTS, ContextCompactionEvent
|
||||
from nanobot.providers.base import LLMResponse
|
||||
from nanobot.runtime_context import public_history_message
|
||||
from nanobot.sdk.clients import RuntimeClient
|
||||
from nanobot.session.keys import HEARTBEAT_SESSION_KEY, UNIFIED_SESSION_KEY
|
||||
from nanobot.session.keys import HEARTBEAT_SESSION_KEY
|
||||
|
||||
|
||||
def _make_loop(
|
||||
tmp_path: Path,
|
||||
session_ttl_minutes: int = 15,
|
||||
unified_session: bool = False,
|
||||
) -> AgentLoop:
|
||||
"""Create a minimal AgentLoop for testing."""
|
||||
bus = MessageBus()
|
||||
@@ -41,7 +40,6 @@ def _make_loop(
|
||||
model="test-model",
|
||||
context_window_tokens=128_000,
|
||||
session_ttl_minutes=session_ttl_minutes,
|
||||
unified_session=unified_session,
|
||||
)
|
||||
loop.tools.get_definitions = MagicMock(return_value=[])
|
||||
return loop
|
||||
@@ -230,33 +228,6 @@ async def test_idle_compaction_skips_subagent_sessions(tmp_path, monkeypatch, re
|
||||
await loop.aclose()
|
||||
|
||||
|
||||
async def test_expired_unified_turn_keeps_latest_delivery_route(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("nanobot.config.home._home_path", tmp_path / "home")
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", tmp_path / "config.json")
|
||||
loop = _make_loop(tmp_path / "workspace", unified_session=True)
|
||||
session = loop.sessions.get_or_create(UNIFIED_SESSION_KEY)
|
||||
session.metadata["last_channel"] = "telegram:old"
|
||||
session.metadata["_compaction_route"] = {
|
||||
"channel": "telegram", "chat_id": "old", "metadata": {},
|
||||
}
|
||||
session.updated_at = datetime.now() - timedelta(minutes=20)
|
||||
loop.sessions.save(session)
|
||||
try:
|
||||
response = await loop.process_direct(
|
||||
"hello", session_key=UNIFIED_SESSION_KEY, channel="discord", chat_id="new",
|
||||
)
|
||||
|
||||
assert response is not None and response.content == "ok"
|
||||
saved = await loop.sessions.state.get(UNIFIED_SESSION_KEY)
|
||||
assert saved.generation == session.generation
|
||||
assert saved.metadata["last_channel"] == "discord:new"
|
||||
assert saved.metadata["_compaction_route"] == {
|
||||
"channel": "discord", "chat_id": "new", "metadata": {},
|
||||
}
|
||||
finally:
|
||||
await loop.aclose()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("compaction", ["idle", "compact_session", "compact_idle_session"])
|
||||
async def test_turn_resuming_during_archive_commits_reply(tmp_path, monkeypatch, compaction):
|
||||
monkeypatch.setattr("nanobot.config.home._home_path", tmp_path / "home")
|
||||
|
||||
@@ -492,14 +492,14 @@ class TestPrepareSession:
|
||||
ac = _make_autocompact(ttl=15)
|
||||
session = _make_session(
|
||||
updated_at=datetime.now() - timedelta(minutes=20),
|
||||
metadata={"last_channel": "discord:new"},
|
||||
metadata={"title": "Project notes"},
|
||||
)
|
||||
if archiving:
|
||||
ac._archiving.add(session.key)
|
||||
|
||||
prepared, _ = await ac.prepare_session(session, session.key)
|
||||
|
||||
assert prepared.metadata["last_channel"] == "discord:new"
|
||||
assert prepared.metadata["title"] == "Project notes"
|
||||
|
||||
async def test_hot_path_summary_from_summaries(self):
|
||||
ac = _make_autocompact()
|
||||
|
||||
@@ -21,7 +21,6 @@ from nanobot.runtime_context import (
|
||||
RuntimeContextBlock,
|
||||
append_runtime_context,
|
||||
)
|
||||
from nanobot.session.keys import UNIFIED_SESSION_KEY, remember_last_channel
|
||||
from nanobot.session.manager import Session
|
||||
from nanobot.utils.llm_runtime import LLMRuntime
|
||||
from nanobot.utils.prompt_templates import render_template
|
||||
@@ -1481,7 +1480,7 @@ class TestCompactIdleSession:
|
||||
assert sent[-1]["content"] == _ARCHIVE_PROMPT
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reuses_real_prefix_for_unified_session_workspace(
|
||||
async def test_reuses_real_prefix_for_webui_session_workspace(
|
||||
self,
|
||||
loop_factory,
|
||||
mock_provider,
|
||||
@@ -1491,14 +1490,13 @@ class TestCompactIdleSession:
|
||||
project.mkdir()
|
||||
(tmp_path / "AGENTS.md").write_text("GLOBAL_WORKSPACE_MARKER", encoding="utf-8")
|
||||
(project / "AGENTS.md").write_text("PROJECT_WORKSPACE_MARKER", encoding="utf-8")
|
||||
loop = loop_factory(provider=mock_provider, unified_session=True)
|
||||
loop = loop_factory(provider=mock_provider)
|
||||
runtime = loop.llm_runtime()
|
||||
runtime.provider.chat_stream_with_retry.return_value = LLMResponse(
|
||||
content="Summary.",
|
||||
finish_reason="stop",
|
||||
)
|
||||
session = loop.sessions.get_or_create(UNIFIED_SESSION_KEY)
|
||||
remember_last_channel(session.metadata, "websocket", "scope")
|
||||
session = loop.sessions.get_or_create("websocket:scope")
|
||||
session.metadata["workspace_scope"] = {
|
||||
"project_path": str(project),
|
||||
"access_mode": "restricted",
|
||||
|
||||
@@ -1115,13 +1115,13 @@ class TestToolEventProgress:
|
||||
|
||||
captured: dict[str, object] = {}
|
||||
|
||||
async def fake_title_after_turn(**kwargs: object) -> bool:
|
||||
async def fake_generate_title(**kwargs: object) -> bool:
|
||||
captured.update(kwargs)
|
||||
return False
|
||||
|
||||
monkeypatch.setattr(
|
||||
"nanobot.session.webui_turns.maybe_generate_webui_title_after_turn",
|
||||
fake_title_after_turn,
|
||||
"nanobot.session.webui_turns.maybe_generate_webui_title",
|
||||
fake_generate_title,
|
||||
)
|
||||
scheduled_title: list[object] = []
|
||||
|
||||
@@ -1157,39 +1157,6 @@ class TestToolEventProgress:
|
||||
assert captured["provider"] is provider
|
||||
assert captured["model"] == "test-model"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("metadata", [{}, {"webui": False}])
|
||||
async def test_webui_title_requires_inbound_opt_in(
|
||||
self,
|
||||
tmp_path: Path,
|
||||
metadata: dict[str, object],
|
||||
) -> None:
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.webui_turns import maybe_generate_webui_title_after_turn
|
||||
|
||||
sessions = SessionManager(tmp_path)
|
||||
session = sessions.get_or_create("websocket:chat1")
|
||||
session.metadata["webui"] = True
|
||||
session.add_message("user", "say hello")
|
||||
session.add_message("assistant", "Hello")
|
||||
sessions.save(session)
|
||||
provider = MagicMock()
|
||||
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="Greeting"))
|
||||
|
||||
generated = await maybe_generate_webui_title_after_turn(
|
||||
channel="websocket",
|
||||
chat_id="chat1",
|
||||
metadata=metadata,
|
||||
sessions=sessions,
|
||||
session_key=session.key,
|
||||
provider=provider,
|
||||
model="test-model",
|
||||
)
|
||||
|
||||
assert generated is False
|
||||
provider.chat_stream_with_retry.assert_not_awaited()
|
||||
assert "title" not in session.metadata
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("metadata", [{}, {"webui": False}])
|
||||
async def test_webui_turn_without_opt_in_does_not_schedule_title(
|
||||
@@ -1232,7 +1199,6 @@ class TestToolEventProgress:
|
||||
async def test_webui_command_turn_does_not_schedule_title_generation(
|
||||
self,
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
bus = MessageBus()
|
||||
provider = MagicMock()
|
||||
@@ -1241,13 +1207,6 @@ class TestToolEventProgress:
|
||||
loop = AgentLoop(bus=bus, provider=provider, workspace=tmp_path, model="test-model")
|
||||
_attach_webui_runtime_events(loop, bus)
|
||||
|
||||
async def fake_title_after_turn(**_kwargs: object) -> bool:
|
||||
raise AssertionError("command-only turns should not generate titles")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"nanobot.session.webui_turns.maybe_generate_webui_title_after_turn",
|
||||
fake_title_after_turn,
|
||||
)
|
||||
scheduled: list[object] = []
|
||||
loop.schedule_background = scheduled.append # type: ignore[method-assign]
|
||||
|
||||
|
||||
@@ -127,7 +127,6 @@ async def test_recovery_continuation_runs_without_a_sustained_goal(
|
||||
|
||||
loop = AgentLoop.__new__(AgentLoop)
|
||||
loop.sessions = sessions
|
||||
loop._unified_session = False
|
||||
loop._recovery_admission = recovery
|
||||
loop._session_locks = {}
|
||||
loop._concurrency_gate = None
|
||||
|
||||
@@ -44,10 +44,6 @@ from nanobot.runtime_context import (
|
||||
)
|
||||
from nanobot.session.automation_turns import AUTOMATION_HISTORY_META
|
||||
from nanobot.session.goal_state import GOAL_STATE_KEY
|
||||
from nanobot.session.keys import (
|
||||
LAST_CHANNEL_METADATA_KEY,
|
||||
UNIFIED_SESSION_KEY,
|
||||
)
|
||||
from nanobot.session.manager import Session
|
||||
from nanobot.session.recovery import (
|
||||
PENDING_FOLLOWUP_ID_KEY,
|
||||
@@ -71,7 +67,6 @@ from nanobot.session.webui_turns import (
|
||||
WebuiTurnCoordinator,
|
||||
clean_generated_title,
|
||||
maybe_generate_webui_title,
|
||||
maybe_generate_webui_title_after_turn,
|
||||
)
|
||||
from nanobot.triggers.local_session_turns import LOCAL_TRIGGER_META
|
||||
|
||||
@@ -466,69 +461,6 @@ async def test_generate_webui_title_ignores_cron_internal_turns(tmp_path: Path)
|
||||
loop.provider.chat_stream_with_retry.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_generate_webui_title_projects_onto_chat_session_under_unified_routing(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
loop = _make_full_loop(tmp_path)
|
||||
loop.provider.chat_stream_with_retry = AsyncMock(
|
||||
return_value=LLMResponse(content='"查询临期 IP"', finish_reason="stop")
|
||||
)
|
||||
unified = loop.sessions.get_or_create(UNIFIED_SESSION_KEY)
|
||||
unified.metadata[WEBUI_SESSION_METADATA_KEY] = True
|
||||
unified.metadata[WEBUI_TITLE_METADATA_KEY] = "开启私聊Topic功能"
|
||||
unified.add_message("user", "很早以前的问题")
|
||||
unified.add_message("assistant", "很久以前的回答。")
|
||||
unified.add_message("user", "帮我查一下临期IP有哪些")
|
||||
unified.add_message("assistant", "以下是临期 IP 列表。")
|
||||
loop.sessions.save(unified)
|
||||
|
||||
generated = await maybe_generate_webui_title_after_turn(
|
||||
channel="websocket",
|
||||
chat_id="chat-projection",
|
||||
metadata={WEBUI_SESSION_METADATA_KEY: True},
|
||||
sessions=loop.sessions,
|
||||
session_key=UNIFIED_SESSION_KEY,
|
||||
provider=loop.provider,
|
||||
model=loop.model,
|
||||
)
|
||||
|
||||
assert generated is True
|
||||
chat = loop.sessions.get_or_create("websocket:chat-projection")
|
||||
assert chat.metadata[WEBUI_TITLE_METADATA_KEY] == "查询临期 IP"
|
||||
assert unified.metadata[WEBUI_TITLE_METADATA_KEY] == "开启私聊Topic功能"
|
||||
prompt = loop.provider.chat_stream_with_retry.await_args.args[0][1]["content"]
|
||||
assert "帮我查一下临期IP有哪些" in prompt
|
||||
assert "很早以前的问题" not in prompt
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_projected_title_generation_skips_existing_chat_title(tmp_path: Path) -> None:
|
||||
loop = _make_full_loop(tmp_path)
|
||||
unified = loop.sessions.get_or_create(UNIFIED_SESSION_KEY)
|
||||
unified.metadata[WEBUI_SESSION_METADATA_KEY] = True
|
||||
unified.add_message("user", "帮我查一下临期IP有哪些")
|
||||
unified.add_message("assistant", "以下是临期 IP 列表。")
|
||||
chat = loop.sessions.get_or_create("websocket:chat-existing")
|
||||
chat.metadata[WEBUI_TITLE_METADATA_KEY] = "Existing title"
|
||||
loop.sessions.save(chat)
|
||||
loop.sessions.save(unified)
|
||||
|
||||
generated = await maybe_generate_webui_title_after_turn(
|
||||
channel="websocket",
|
||||
chat_id="chat-existing",
|
||||
metadata={WEBUI_SESSION_METADATA_KEY: True},
|
||||
sessions=loop.sessions,
|
||||
session_key=UNIFIED_SESSION_KEY,
|
||||
provider=loop.provider,
|
||||
model=loop.model,
|
||||
)
|
||||
|
||||
assert generated is False
|
||||
assert chat.metadata[WEBUI_TITLE_METADATA_KEY] == "Existing title"
|
||||
loop.provider.chat_stream_with_retry.assert_not_awaited()
|
||||
|
||||
|
||||
def test_save_turn_keeps_multimodal_runtime_context_for_model_replay() -> None:
|
||||
loop = _mk_loop()
|
||||
session = Session(key="test:runtime-only")
|
||||
@@ -1203,9 +1135,8 @@ async def test_subagent_followup_clears_state_before_compatibility_failure(
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_process_message_persists_unified_session_delivery_route(tmp_path: Path) -> None:
|
||||
async def test_process_message_persists_delivery_route_on_failure(tmp_path: Path) -> None:
|
||||
loop = _make_full_loop(tmp_path)
|
||||
loop._unified_session = True
|
||||
loop._run_agent_loop = AsyncMock(side_effect=RuntimeError("boom")) # type: ignore[method-assign]
|
||||
|
||||
msg = InboundMessage(
|
||||
@@ -1213,79 +1144,17 @@ async def test_process_message_persists_unified_session_delivery_route(tmp_path:
|
||||
sender_id="u1",
|
||||
chat_id="oc_123",
|
||||
content="persist my route",
|
||||
session_key_override=UNIFIED_SESSION_KEY,
|
||||
)
|
||||
with pytest.raises(RuntimeError, match="boom"):
|
||||
await loop._process_message(msg)
|
||||
|
||||
loop.sessions.invalidate(UNIFIED_SESSION_KEY)
|
||||
persisted = loop.sessions.get_or_create(UNIFIED_SESSION_KEY)
|
||||
assert persisted.metadata[LAST_CHANNEL_METADATA_KEY] == "feishu:oc_123"
|
||||
loop.sessions.invalidate("feishu:oc_123")
|
||||
persisted = loop.sessions.get_or_create("feishu:oc_123")
|
||||
assert persisted.metadata["_compaction_route"] == {
|
||||
"channel": "feishu", "chat_id": "oc_123", "metadata": {},
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("msg", "is_user_turn"),
|
||||
[
|
||||
(
|
||||
InboundMessage(
|
||||
channel="cli",
|
||||
sender_id="u1",
|
||||
chat_id="direct",
|
||||
content="cli input",
|
||||
),
|
||||
True,
|
||||
),
|
||||
(
|
||||
InboundMessage(
|
||||
channel="system",
|
||||
sender_id="system",
|
||||
chat_id="discord:automation",
|
||||
content="system event",
|
||||
),
|
||||
False,
|
||||
),
|
||||
(
|
||||
InboundMessage(
|
||||
channel="discord",
|
||||
sender_id="subagent",
|
||||
chat_id="subagent-result",
|
||||
content="subagent result",
|
||||
),
|
||||
True,
|
||||
),
|
||||
(
|
||||
InboundMessage(
|
||||
channel="discord",
|
||||
sender_id="u1",
|
||||
chat_id="automation",
|
||||
content="scheduled turn",
|
||||
metadata={CRON_TRIGGER_META: {"job_id": "job-1"}},
|
||||
),
|
||||
True,
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_unified_session_route_ignores_non_user_destinations(
|
||||
tmp_path: Path,
|
||||
msg: InboundMessage,
|
||||
is_user_turn: bool,
|
||||
) -> None:
|
||||
loop = _make_full_loop(tmp_path)
|
||||
loop._unified_session = True
|
||||
session = loop.sessions.get_or_create(UNIFIED_SESSION_KEY)
|
||||
session.metadata[LAST_CHANNEL_METADATA_KEY] = "telegram:existing"
|
||||
|
||||
loop._remember_session_route(
|
||||
session, msg, is_user_turn=is_user_turn,
|
||||
delivery=loop.turn_delivery_factory.unrouted(msg, session.key),
|
||||
)
|
||||
|
||||
assert session.metadata[LAST_CHANNEL_METADATA_KEY] == "telegram:existing"
|
||||
|
||||
|
||||
# 1x1 PNG used by the media-persistence tests. Attachment preparation filters
|
||||
# ``msg.media`` down to paths that magic-byte-sniff as images, so the test
|
||||
# fixture needs real bytes on disk (not just placeholder paths).
|
||||
|
||||
@@ -18,8 +18,7 @@ from nanobot.bus.events import (
|
||||
)
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.providers.base import GenerationSettings, LLMResponse, ToolCallRequest
|
||||
from nanobot.runtime_context import RuntimeContextBlock, public_history_message
|
||||
from nanobot.session.keys import UNIFIED_SESSION_KEY
|
||||
from nanobot.runtime_context import RuntimeContextBlock
|
||||
from nanobot.session.manager import SessionPolicy
|
||||
from nanobot.webui.temporary_chats import WebUITemporaryChats
|
||||
from nanobot.webui.workspaces import WebUIWorkspaceController
|
||||
@@ -269,26 +268,6 @@ async def test_session_worker_errors_keep_private_content_out_of_logs(
|
||||
assert secret not in str([r["message"] for r in records])
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_transient_session_stays_outside_unified_session(tmp_path) -> None:
|
||||
loop = _loop(tmp_path, ["private answer"], unified_session=True)
|
||||
durable = loop.sessions.get_or_create(UNIFIED_SESSION_KEY)
|
||||
durable.add_message("user", "durable question")
|
||||
loop.sessions.save(durable)
|
||||
key = "websocket:transient-unified"
|
||||
await loop.sessions.state.register_transient(key)
|
||||
|
||||
await run_session(loop, _message(key, "private question"))
|
||||
|
||||
transient = await loop.sessions.state.get(key)
|
||||
assert [public_history_message(message)["content"] for message in transient.messages] == [
|
||||
"private question",
|
||||
"private answer",
|
||||
]
|
||||
assert [message["content"] for message in durable.messages] == ["durable question"]
|
||||
assert loop.sessions.read_session_file(key) is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_missing_required_session_cannot_fall_back_to_disk(tmp_path) -> None:
|
||||
loop = _loop(tmp_path, [])
|
||||
|
||||
@@ -111,7 +111,7 @@ async def test_scheduled_goal_command_cannot_generate_internal_input(tmp_path):
|
||||
)
|
||||
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)
|
||||
await loop._dispatch_command_inline(msg, 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 == {}
|
||||
@@ -142,7 +142,7 @@ async def test_goal_at_iteration_limit_stays_queued_for_a_tool_capable_turn(tmp_
|
||||
calls.append(str(kwargs["messages"]))
|
||||
if len(calls) == 1:
|
||||
await loop._dispatch_command_inline(
|
||||
goal, goal.session_key, goal.content, loop.commands.dispatch,
|
||||
goal, goal.content, loop.commands.dispatch,
|
||||
)
|
||||
if boundary == "tool":
|
||||
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||
@@ -454,7 +454,7 @@ async def test_replaced_goal_uses_current_objective_for_same_run_prompt(tmp_path
|
||||
calls.append(kwargs)
|
||||
if len(calls) == 1:
|
||||
await loop._dispatch_command_inline(
|
||||
replacement, replacement.session_key, replacement.content, loop.commands.dispatch,
|
||||
replacement, replacement.content, loop.commands.dispatch,
|
||||
)
|
||||
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||
id="list", name="list_dir", arguments={"path": "."},
|
||||
@@ -554,7 +554,7 @@ async def test_queued_goal_command_does_not_write_to_an_obsolete_generation(tmp_
|
||||
else:
|
||||
assert await loop.sessions.state.delete(key)
|
||||
with pytest.raises(SessionConflictError):
|
||||
await loop._dispatch_command_inline(message, key, message.content, loop.commands.dispatch)
|
||||
await loop._dispatch_command_inline(message, message.content, loop.commands.dispatch)
|
||||
current = await loop.sessions.state.read(key)
|
||||
if operation == "delete":
|
||||
assert current is None
|
||||
|
||||
@@ -1081,13 +1081,11 @@ async def test_no_injections_flag_is_false_by_default():
|
||||
@pytest.mark.asyncio
|
||||
async def test_followup_routed_to_pending_queue(tmp_path):
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.session.keys import UNIFIED_SESSION_KEY
|
||||
|
||||
loop = _make_loop(tmp_path)
|
||||
loop._unified_session = True
|
||||
|
||||
pending = asyncio.Queue(maxsize=20)
|
||||
loop._pending_queues[UNIFIED_SESSION_KEY] = pending
|
||||
loop._pending_queues["discord:c"] = pending
|
||||
|
||||
run_task = asyncio.create_task(loop.run())
|
||||
msg = InboundMessage(channel="discord", sender_id="u", chat_id="c", content="follow-up")
|
||||
@@ -1100,7 +1098,7 @@ async def test_followup_routed_to_pending_queue(tmp_path):
|
||||
|
||||
assert loop._active_tasks == {}
|
||||
assert queued_msg.content == "follow-up"
|
||||
assert queued_msg.session_key == UNIFIED_SESSION_KEY
|
||||
assert queued_msg.session_key == "discord:c"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -1133,44 +1131,6 @@ async def test_websocket_followup_is_admitted_before_recovery_queue(tmp_path):
|
||||
await asyncio.wait_for(run_task, timeout=2)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("channel", ["websocket", "discord"])
|
||||
async def test_unified_followup_admits_effective_session(tmp_path, channel):
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.session.keys import UNIFIED_SESSION_KEY
|
||||
|
||||
admission = MagicMock()
|
||||
admission.admit = AsyncMock(return_value=True)
|
||||
loop = _make_loop(tmp_path, recovery_admission=admission)
|
||||
loop._unified_session = True
|
||||
|
||||
pending = asyncio.Queue(maxsize=20)
|
||||
loop._pending_queues[UNIFIED_SESSION_KEY] = pending
|
||||
|
||||
msg = InboundMessage(
|
||||
channel=channel,
|
||||
sender_id="u",
|
||||
chat_id="chat",
|
||||
content="new request",
|
||||
)
|
||||
try:
|
||||
# Exercise the real routing/journaling boundary to completion. This is
|
||||
# a session-key contract, not a two-second SQLite fsync benchmark.
|
||||
await loop._dispatch_inbound(msg)
|
||||
queued_msg = pending.get_nowait()
|
||||
admission.admit.assert_awaited_once()
|
||||
admitted_msg = admission.admit.await_args.args[0]
|
||||
assert admitted_msg.session_key == UNIFIED_SESSION_KEY
|
||||
assert queued_msg.session_key == UNIFIED_SESSION_KEY
|
||||
assert queued_msg.content == msg.content
|
||||
if channel == "websocket":
|
||||
assert queued_msg.metadata["_recovery_followup_id"]
|
||||
else:
|
||||
assert queued_msg.metadata == msg.metadata
|
||||
finally:
|
||||
await loop.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_mid_turn_subagent_result_does_not_resolve_a_new_turn_route(tmp_path):
|
||||
from nanobot.bus.events import InboundMessage
|
||||
|
||||
@@ -163,8 +163,7 @@ async def test_new_during_active_turn_stops_it_and_resets_session(loop):
|
||||
|
||||
|
||||
@pytest.mark.parametrize("followup_scope", ["same", "restricted", "other-project"])
|
||||
async def test_unified_followup_keeps_its_workspace_authority(loop, tmp_path, followup_scope):
|
||||
loop._unified_session = True
|
||||
async def test_followup_keeps_its_workspace_authority(loop, tmp_path, followup_scope):
|
||||
project = tmp_path / "other-project"
|
||||
project.mkdir()
|
||||
initial_scope = {"project_path": str(tmp_path), "access_mode": "full"}
|
||||
@@ -179,11 +178,11 @@ async def test_unified_followup_keeps_its_workspace_authority(loop, tmp_path, fo
|
||||
observed.append(scope.metadata())
|
||||
if len(observed) == 1:
|
||||
await loop.bus.publish_inbound(InboundMessage(
|
||||
channel="websocket", sender_id="client", chat_id="followup", content="second",
|
||||
channel="websocket", sender_id="client", chat_id="initial", content="second",
|
||||
metadata={"workspace_scope": next_scope},
|
||||
))
|
||||
async with asyncio.timeout(3):
|
||||
while loop._pending_queues["unified:default"].empty():
|
||||
while loop._pending_queues["websocket:initial"].empty():
|
||||
await asyncio.sleep(0)
|
||||
return LLMResponse(content="done")
|
||||
|
||||
@@ -196,7 +195,7 @@ async def test_unified_followup_keeps_its_workspace_authority(loop, tmp_path, fo
|
||||
metadata={"workspace_scope": initial_scope},
|
||||
))
|
||||
async with asyncio.timeout(5):
|
||||
while not observed or "unified:default" in loop._pending_queues:
|
||||
while not observed or "websocket:initial" in loop._pending_queues:
|
||||
await asyncio.sleep(0.01)
|
||||
assert observed == [initial_scope, next_scope]
|
||||
assert loop.runner.run.await_count == (1 if followup_scope == "same" else 2)
|
||||
@@ -525,7 +524,7 @@ async def test_stopped_followups_are_not_recovered_but_shutdown_preserves_them(
|
||||
stop = InboundMessage(
|
||||
channel="websocket", sender_id="u", chat_id="test", content="/stop",
|
||||
)
|
||||
await loop._dispatch_command_inline(stop, key, "/stop", loop.commands.dispatch_priority)
|
||||
await loop._dispatch_command_inline(stop, stop.content, loop.commands.dispatch_priority)
|
||||
|
||||
# Use fresh managers and the real startup scan: a cache-only assertion can
|
||||
# miss the canceled journal being replayed from disk on the next restart.
|
||||
@@ -684,7 +683,7 @@ async def test_ingress_sources_share_one_session_worker(loop, bus_running):
|
||||
else:
|
||||
(await loop._enqueue_session_message(second))
|
||||
compact = InboundMessage(channel="websocket", sender_id="u", chat_id="test", content="/compact")
|
||||
await loop._dispatch_command_inline(compact, key, compact.content, loop.commands.dispatch)
|
||||
await loop._dispatch_command_inline(compact, compact.content, loop.commands.dispatch)
|
||||
assert len(loop._active_tasks[key]) == 1
|
||||
release.set()
|
||||
results = await asyncio.wait_for(asyncio.gather(cron, trigger), timeout=3)
|
||||
@@ -809,11 +808,10 @@ async def test_active_goal_prioritizes_real_followup_before_internal_prompt(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))
|
||||
loop.tools.execute = AsyncMock(return_value="ok")
|
||||
key = "unified:default"
|
||||
key = "feishu:chat-a"
|
||||
session = loop.sessions.get_or_create(key)
|
||||
session.metadata[GOAL_STATE_KEY] = {"status": "active", "objective": "Finish the goal"}
|
||||
loop.sessions.save(session)
|
||||
@@ -832,7 +830,7 @@ async def test_active_goal_keeps_origin_until_queued_independent_command_runs(lo
|
||||
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="/compact",
|
||||
channel="feishu", sender_id="user", chat_id="chat-a", content="/compact",
|
||||
metadata={"message_id": "message-b"},
|
||||
))
|
||||
async with asyncio.timeout(3):
|
||||
@@ -866,16 +864,16 @@ async def test_active_goal_keeps_origin_until_queued_independent_command_runs(lo
|
||||
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"
|
||||
by_message = {event.context.metadata.get("message_id"): event for event in completed}
|
||||
assert set(by_message) == {"message-a", "message-b"}
|
||||
assert by_message["message-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 == ()
|
||||
assert by_message["message-a"].usage.total_tokens == 60
|
||||
assert [usage.total_tokens for usage in by_message["message-a"].round_usages] == [10, 20, 30]
|
||||
assert by_message["message-b"].outcome == "completed"
|
||||
assert by_message["message-b"].context.metadata["message_id"] == "message-b"
|
||||
assert by_message["message-b"].usage is None
|
||||
assert by_message["message-b"].round_usages == ()
|
||||
replies = []
|
||||
while not loop.bus.outbound.empty():
|
||||
reply = loop.bus.outbound.get_nowait()
|
||||
|
||||
@@ -11,7 +11,6 @@ from nanobot.agent.memory import Consolidator
|
||||
from nanobot.bus.outbound_events import StreamDeltaEvent, StreamEndEvent
|
||||
from nanobot.config.schema import AgentDefaults
|
||||
from nanobot.providers.base import GenerationSettings
|
||||
from nanobot.session.keys import UNIFIED_SESSION_KEY
|
||||
from nanobot.utils.llm_runtime import LLMRuntime
|
||||
|
||||
_MAX_TOOL_RESULT_CHARS = AgentDefaults().max_tool_result_chars
|
||||
@@ -740,28 +739,15 @@ class TestSubagentAnnounceSessionKey:
|
||||
return mgr, bus
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_announce_uses_effective_key_in_unified_mode(self):
|
||||
"""In unified session mode, session_key_override must be 'unified:default'
|
||||
so the result matches the pending queue key."""
|
||||
async def test_announce_uses_explicit_topic_session_key(self):
|
||||
mgr, bus = self._make_mgr()
|
||||
|
||||
origin = {"channel": "telegram", "chat_id": "111", "session_key": UNIFIED_SESSION_KEY}
|
||||
origin = {"channel": "telegram", "chat_id": "111", "session_key": "telegram:111:topic:5"}
|
||||
await mgr._announce_result("sub-1", "label", "task", "result", origin, "ok")
|
||||
|
||||
msg = await bus.consume_inbound()
|
||||
assert msg.session_key_override == UNIFIED_SESSION_KEY
|
||||
assert msg.session_key == UNIFIED_SESSION_KEY
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_announce_uses_raw_key_in_normal_mode(self):
|
||||
mgr, bus = self._make_mgr()
|
||||
|
||||
origin = {"channel": "telegram", "chat_id": "222", "session_key": "telegram:222"}
|
||||
await mgr._announce_result("sub-2", "label", "task", "result", origin, "ok")
|
||||
|
||||
msg = await bus.consume_inbound()
|
||||
assert msg.session_key_override == "telegram:222"
|
||||
assert msg.session_key == "telegram:222"
|
||||
assert msg.session_key_override == "telegram:111:topic:5"
|
||||
assert msg.session_key == "telegram:111:topic:5"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_announce_falls_back_to_origin_when_no_session_key(self):
|
||||
@@ -796,9 +782,9 @@ class TestSubagentAnnounceSessionKey:
|
||||
origin_channel="telegram",
|
||||
origin_chat_id="444",
|
||||
runtime=_runtime(),
|
||||
session_key=UNIFIED_SESSION_KEY,
|
||||
session_key="telegram:444:topic:5",
|
||||
)
|
||||
await asyncio.gather(*mgr._running_tasks.values(), return_exceptions=True)
|
||||
|
||||
msg = await bus.consume_inbound()
|
||||
assert msg.session_key_override == UNIFIED_SESSION_KEY
|
||||
assert msg.session_key_override == "telegram:444:topic:5"
|
||||
@@ -45,7 +45,6 @@ async def test_internal_compaction_never_reaches_its_result_destination(channel,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("unified", [False, True])
|
||||
@pytest.mark.parametrize(("key", "channel", "chat_id", "metadata"), [
|
||||
("slack:C123:1700000000.000100", "slack", "C123",
|
||||
{"slack": {"thread_ts": "1700000000.000100"}}),
|
||||
@@ -59,14 +58,13 @@ async def test_internal_compaction_never_reaches_its_result_destination(channel,
|
||||
("dingtalk:group:conversation:user", "dingtalk", "group:conversation", {}),
|
||||
])
|
||||
async def test_session_route_delivers_automatic_and_manual_compaction(
|
||||
key, channel, chat_id, metadata, unified,
|
||||
key, channel, chat_id, metadata,
|
||||
) -> None:
|
||||
factory = TurnDeliveryFactory(MessageBus())
|
||||
automatic = ContextCompactionEvent(compaction_id="auto-1", phase="started")
|
||||
notified = ContextCompactionEvent(
|
||||
compaction_id="notified-1", phase="started", notify=True,
|
||||
)
|
||||
key = "unified:default" if unified else key
|
||||
msg = InboundMessage(
|
||||
channel=channel, sender_id="user", chat_id=chat_id, content="hello",
|
||||
metadata={
|
||||
@@ -90,9 +88,9 @@ async def test_session_route_delivers_automatic_and_manual_compaction(
|
||||
assert [outbound.event for outbound in outbounds] == [automatic, notified]
|
||||
|
||||
|
||||
async def test_idle_compaction_keeps_its_route_when_a_unified_session_moves() -> None:
|
||||
async def test_idle_compaction_keeps_its_route_when_the_saved_route_changes() -> None:
|
||||
factory = TurnDeliveryFactory(MessageBus())
|
||||
key = "unified:default"
|
||||
key = "sdk:workflow"
|
||||
session_metadata = {}
|
||||
original = InboundMessage(
|
||||
channel="slack", sender_id="user", chat_id="C123", content="hello",
|
||||
@@ -476,29 +474,23 @@ async def test_late_subagent_route_requires_webui_owned_session(tmp_path: Path)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unified_display_route_admits_alias_generation_and_rejects_stale_lifetime(tmp_path):
|
||||
async def test_cross_session_display_route_rejects_stale_lifetime(tmp_path):
|
||||
from nanobot.session.display_history import HISTORY_GENERATION_METADATA_KEY
|
||||
from nanobot.session.sqlite_store import SessionConflictError
|
||||
|
||||
sessions = SessionManager(tmp_path)
|
||||
alias = await sessions.state.get_header("websocket:chat")
|
||||
source = await sessions.state.get_header("unified:default")
|
||||
target = await sessions.state.get_header("websocket:chat")
|
||||
source = await sessions.state.get_header("heartbeat")
|
||||
policy = WebuiTurnRoutePolicy(sessions)
|
||||
factory = TurnDeliveryFactory(MessageBus(), route_policy=policy, route_admission=policy.admit)
|
||||
message = InboundMessage(channel="system", sender_id="cron", chat_id="websocket:chat", content="notice")
|
||||
delivery = factory.create(message, source.key)
|
||||
await delivery.bind_session_generation(source.generation)
|
||||
assert delivery.route.metadata[HISTORY_GENERATION_METADATA_KEY] == alias.generation
|
||||
assert delivery.route.metadata[HISTORY_GENERATION_METADATA_KEY] == target.generation
|
||||
assert delivery.delivery_message.session_generation == source.generation
|
||||
response = delivery.background_response("done", stop_reason="end_turn", streamed=False, latency_ms=1)
|
||||
assert response.metadata[HISTORY_GENERATION_METADATA_KEY] == alias.generation
|
||||
await sessions.state.delete(alias.key)
|
||||
replacement = await sessions.state.get_header(alias.key)
|
||||
stale = factory.create(InboundMessage(
|
||||
channel="websocket", sender_id="user", chat_id="chat", content="old queued input",
|
||||
metadata={HISTORY_GENERATION_METADATA_KEY: alias.generation},
|
||||
), source.key)
|
||||
assert response.metadata[HISTORY_GENERATION_METADATA_KEY] == target.generation
|
||||
await sessions.state.reset(target.key)
|
||||
with pytest.raises(SessionConflictError):
|
||||
await stale.bind_session_generation(source.generation)
|
||||
assert replacement.generation != alias.generation
|
||||
await policy.admit(delivery.route, source.key, source.generation)
|
||||
await sessions.state.aclose()
|
||||
@@ -1,372 +0,0 @@
|
||||
import asyncio
|
||||
import json
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from agent.session_helpers import mock_session_manager, run_session
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.agent.tools.file_state import FileStateStore
|
||||
from nanobot.agent.tools.filesystem import ReadFileTool
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
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
|
||||
from nanobot.session.manager import SessionManager
|
||||
|
||||
|
||||
def _make_loop(tmp_path: Path, unified_session: bool = False) -> AgentLoop:
|
||||
"""Create a minimal AgentLoop for dispatch-level tests."""
|
||||
bus = MessageBus()
|
||||
provider = MagicMock()
|
||||
provider.get_default_model.return_value = "test-model"
|
||||
|
||||
with patch("nanobot.agent.loop.SessionManager", side_effect=mock_session_manager), \
|
||||
patch("nanobot.agent.loop.SubagentManager") as mock_sub_mgr:
|
||||
mock_sub_mgr.return_value.cancel_by_session = AsyncMock(return_value=0)
|
||||
loop = AgentLoop(
|
||||
bus=bus,
|
||||
provider=provider,
|
||||
workspace=tmp_path,
|
||||
unified_session=unified_session,
|
||||
)
|
||||
return loop
|
||||
|
||||
|
||||
def _make_msg(channel: str = "telegram", chat_id: str = "111",
|
||||
session_key_override: str | None = None) -> InboundMessage:
|
||||
return InboundMessage(
|
||||
channel=channel,
|
||||
chat_id=chat_id,
|
||||
sender_id="user1",
|
||||
content="hello",
|
||||
session_key_override=session_key_override,
|
||||
)
|
||||
|
||||
|
||||
class TestUnifiedSessionDispatch:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unified_session_rewrites_key_to_unified_default(self, tmp_path: Path):
|
||||
loop = _make_loop(tmp_path, unified_session=True)
|
||||
|
||||
captured: list[str] = []
|
||||
|
||||
async def fake_process(msg, **kwargs):
|
||||
captured.append(msg.session_key)
|
||||
return None
|
||||
|
||||
loop._process_message = fake_process # type: ignore[method-assign]
|
||||
|
||||
msg = _make_msg(channel="telegram", chat_id="111")
|
||||
await run_session(loop, msg)
|
||||
|
||||
assert captured == ["unified:default"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unified_session_different_channels_share_same_key(self, tmp_path: Path):
|
||||
loop = _make_loop(tmp_path, unified_session=True)
|
||||
|
||||
captured: list[str] = []
|
||||
|
||||
async def fake_process(msg, **kwargs):
|
||||
captured.append(msg.session_key)
|
||||
return None
|
||||
|
||||
loop._process_message = fake_process # type: ignore[method-assign]
|
||||
|
||||
await run_session(loop, _make_msg(channel="telegram", chat_id="111"))
|
||||
await run_session(loop, _make_msg(channel="discord", chat_id="222"))
|
||||
await run_session(loop, _make_msg(channel="cli", chat_id="direct"))
|
||||
|
||||
assert captured == ["unified:default", "unified:default", "unified:default"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unified_session_disabled_preserves_original_key(self, tmp_path: Path):
|
||||
loop = _make_loop(tmp_path, unified_session=False)
|
||||
|
||||
captured: list[str] = []
|
||||
|
||||
async def fake_process(msg, **kwargs):
|
||||
captured.append(msg.session_key)
|
||||
return None
|
||||
|
||||
loop._process_message = fake_process # type: ignore[method-assign]
|
||||
|
||||
msg = _make_msg(channel="telegram", chat_id="999")
|
||||
await run_session(loop, msg)
|
||||
|
||||
assert captured == ["telegram:999"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unified_session_respects_existing_override(self, tmp_path: Path):
|
||||
loop = _make_loop(tmp_path, unified_session=True)
|
||||
|
||||
captured: list[str] = []
|
||||
|
||||
async def fake_process(msg, **kwargs):
|
||||
captured.append(msg.session_key)
|
||||
return None
|
||||
|
||||
loop._process_message = fake_process # type: ignore[method-assign]
|
||||
|
||||
msg = _make_msg(channel="telegram", chat_id="111", session_key_override="telegram:thread:42")
|
||||
await run_session(loop, msg)
|
||||
|
||||
assert captured == ["telegram:thread:42"]
|
||||
|
||||
def test_unified_session_default_is_false(self, tmp_path: Path):
|
||||
loop = _make_loop(tmp_path)
|
||||
assert loop._unified_session is False
|
||||
|
||||
|
||||
class TestUnifiedSessionConfig:
|
||||
|
||||
def test_agent_defaults_unified_session_default_is_false(self):
|
||||
defaults = AgentDefaults()
|
||||
assert defaults.unified_session is False
|
||||
|
||||
def test_agent_defaults_unified_session_can_be_enabled(self):
|
||||
defaults = AgentDefaults(unified_session=True)
|
||||
assert defaults.unified_session is True
|
||||
|
||||
def test_config_serialises_unified_session_as_camel_case(self):
|
||||
config = Config()
|
||||
data = config.model_dump(mode="json", by_alias=True)
|
||||
agents_defaults = data["agents"]["defaults"]
|
||||
assert "unifiedSession" in agents_defaults
|
||||
assert agents_defaults["unifiedSession"] is False
|
||||
|
||||
def test_config_parses_unified_session_from_camel_case(self):
|
||||
raw = {"agents": {"defaults": {"unifiedSession": True}}}
|
||||
config = Config.model_validate(raw)
|
||||
assert config.agents.defaults.unified_session is True
|
||||
|
||||
def test_config_parses_unified_session_from_snake_case(self):
|
||||
raw = {"agents": {"defaults": {"unified_session": True}}}
|
||||
config = Config.model_validate(raw)
|
||||
assert config.agents.defaults.unified_session is True
|
||||
|
||||
def test_onboard_generated_config_contains_unified_session(self, tmp_path: Path):
|
||||
from nanobot.config.loader import save_config
|
||||
|
||||
config = Config()
|
||||
config_path = tmp_path / "config.json"
|
||||
save_config(config, config_path)
|
||||
|
||||
with open(config_path, encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
|
||||
agents_defaults = data["agents"]["defaults"]
|
||||
assert "unifiedSession" in agents_defaults, (
|
||||
"onboard-generated config.json must contain 'unifiedSession' key"
|
||||
)
|
||||
assert agents_defaults["unifiedSession"] is False
|
||||
|
||||
|
||||
class TestCmdNewUnifiedSession:
|
||||
|
||||
def test_new_is_not_a_priority_command(self):
|
||||
router = CommandRouter()
|
||||
register_builtin_commands(router)
|
||||
assert router.is_priority("/new") is False
|
||||
|
||||
def test_new_is_an_exact_command(self):
|
||||
router = CommandRouter()
|
||||
register_builtin_commands(router)
|
||||
assert "/new" in router._exact
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cmd_new_clears_unified_session(self, tmp_path: Path):
|
||||
sessions = SessionManager(tmp_path)
|
||||
|
||||
shared = sessions.get_or_create("unified:default")
|
||||
shared.add_message("user", "hello from telegram")
|
||||
shared.add_message("assistant", "hi there")
|
||||
sessions.save(shared)
|
||||
assert len(sessions.get_or_create("unified:default").messages) == 2
|
||||
expected_snapshot = list(shared.messages)
|
||||
|
||||
# schedule_background is a *sync* method that schedules a coroutine via
|
||||
# asyncio.create_task(). Mirror that exactly so the coroutine is consumed
|
||||
# and no RuntimeWarning is emitted.
|
||||
admitted_runtime = MagicMock(name="admitted_runtime")
|
||||
file_state_store = FileStateStore()
|
||||
previous_file_state = file_state_store.for_session("unified:default")
|
||||
tracked_file = tmp_path / "tracked.txt"
|
||||
tracked_file.write_text("tracked", encoding="utf-8")
|
||||
await ReadFileTool(workspace=tmp_path, file_states=previous_file_state).execute(
|
||||
path=str(tracked_file),
|
||||
)
|
||||
assert previous_file_state.get(tracked_file) is not None
|
||||
loop = SimpleNamespace(
|
||||
sessions=sessions,
|
||||
consolidator=SimpleNamespace(archive_session=AsyncMock(return_value=True)),
|
||||
_cancel_active_tasks=AsyncMock(return_value=0),
|
||||
discard_session_file_state=file_state_store.discard,
|
||||
llm_runtime=MagicMock(return_value=MagicMock()),
|
||||
schedule_background=lambda coro: asyncio.ensure_future(coro),
|
||||
)
|
||||
|
||||
msg = InboundMessage(
|
||||
channel="telegram", sender_id="user1", chat_id="111", content="/new",
|
||||
session_key_override="unified:default",
|
||||
)
|
||||
ctx = CommandContext(
|
||||
msg=msg,
|
||||
session=None,
|
||||
key="unified:default",
|
||||
raw="/new",
|
||||
loop=loop,
|
||||
runtime=admitted_runtime,
|
||||
)
|
||||
|
||||
result = await cmd_new(ctx)
|
||||
|
||||
assert "New session started" in result.content
|
||||
sessions.invalidate("unified:default")
|
||||
reloaded = sessions.get_or_create("unified:default")
|
||||
assert reloaded.messages == []
|
||||
reset_file_state = file_state_store.for_session("unified:default")
|
||||
assert reset_file_state is not previous_file_state
|
||||
assert reset_file_state.get(tracked_file) is None
|
||||
archived = loop.consolidator.archive_session.call_args.args[0]
|
||||
assert archived.key == "unified:default"
|
||||
assert archived.messages == expected_snapshot
|
||||
assert archived.last_archived == 0
|
||||
loop.consolidator.archive_session.assert_called_once_with(
|
||||
archived,
|
||||
archive_end=len(expected_snapshot),
|
||||
runtime=admitted_runtime,
|
||||
)
|
||||
loop.llm_runtime.assert_not_called()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cmd_new_in_unified_mode_does_not_affect_other_sessions(self, tmp_path: Path):
|
||||
sessions = SessionManager(tmp_path)
|
||||
|
||||
other = sessions.get_or_create("discord:999")
|
||||
other.add_message("user", "discord message")
|
||||
sessions.save(other)
|
||||
|
||||
shared = sessions.get_or_create("unified:default")
|
||||
shared.add_message("user", "shared message")
|
||||
sessions.save(shared)
|
||||
|
||||
loop = SimpleNamespace(
|
||||
sessions=sessions,
|
||||
consolidator=SimpleNamespace(archive_session=AsyncMock(return_value=True)),
|
||||
_cancel_active_tasks=AsyncMock(return_value=0),
|
||||
discard_session_file_state=MagicMock(),
|
||||
runtime_for_session=AsyncMock(return_value=MagicMock()),
|
||||
schedule_background=lambda coro: asyncio.ensure_future(coro),
|
||||
)
|
||||
|
||||
msg = InboundMessage(
|
||||
channel="telegram", sender_id="user1", chat_id="111", content="/new",
|
||||
session_key_override="unified:default",
|
||||
)
|
||||
ctx = CommandContext(msg=msg, session=None, key="unified:default", raw="/new", loop=loop)
|
||||
await cmd_new(ctx)
|
||||
|
||||
sessions.invalidate("unified:default")
|
||||
sessions.invalidate("discord:999")
|
||||
assert sessions.get_or_create("unified:default").messages == []
|
||||
assert len(sessions.get_or_create("discord:999").messages) == 1
|
||||
|
||||
|
||||
class TestStopCommandWithUnifiedSession:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_active_tasks_use_effective_key_in_unified_mode(self, tmp_path: Path):
|
||||
loop = _make_loop(tmp_path, unified_session=True)
|
||||
|
||||
msg = _make_msg(channel="telegram", chat_id="123456")
|
||||
|
||||
loop._process_message = AsyncMock(return_value=None)
|
||||
(await loop._enqueue_session_message(msg))
|
||||
assert set(loop._active_tasks) == {UNIFIED_SESSION_KEY}
|
||||
await asyncio.gather(*loop._active_tasks[UNIFIED_SESSION_KEY])
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stop_command_finds_task_in_unified_mode(self, tmp_path: Path):
|
||||
from nanobot.command.builtin import cmd_stop
|
||||
|
||||
loop = _make_loop(tmp_path, unified_session=True)
|
||||
|
||||
async def long_running():
|
||||
await asyncio.sleep(10)
|
||||
|
||||
task = asyncio.create_task(long_running())
|
||||
loop._active_tasks[UNIFIED_SESSION_KEY] = {task}
|
||||
|
||||
msg = InboundMessage(
|
||||
channel="telegram",
|
||||
chat_id="123456",
|
||||
sender_id="user1",
|
||||
content="/stop",
|
||||
session_key_override=UNIFIED_SESSION_KEY,
|
||||
)
|
||||
|
||||
ctx = CommandContext(msg=msg, session=None, key=UNIFIED_SESSION_KEY, raw="/stop", loop=loop)
|
||||
|
||||
result = await cmd_stop(ctx)
|
||||
|
||||
assert task.cancelled() or task.done()
|
||||
assert "Stopped 1 task" in result.content
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stop_command_uses_effective_key_without_session_override(self, tmp_path: Path):
|
||||
from nanobot.command.builtin import cmd_stop
|
||||
|
||||
loop = _make_loop(tmp_path, unified_session=True)
|
||||
|
||||
async def long_running():
|
||||
await asyncio.sleep(10)
|
||||
|
||||
task = asyncio.create_task(long_running())
|
||||
loop._active_tasks[UNIFIED_SESSION_KEY] = {task}
|
||||
msg = InboundMessage(
|
||||
channel="telegram",
|
||||
chat_id="123456",
|
||||
sender_id="user1",
|
||||
content="/stop",
|
||||
)
|
||||
ctx = CommandContext(msg=msg, session=None, key=UNIFIED_SESSION_KEY, raw="/stop", loop=loop)
|
||||
|
||||
result = await cmd_stop(ctx)
|
||||
|
||||
assert task.cancelled() or task.done()
|
||||
assert "Stopped 1 task" in result.content
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stop_command_cross_channel_in_unified_mode(self, tmp_path: Path):
|
||||
from nanobot.command.builtin import cmd_stop
|
||||
|
||||
loop = _make_loop(tmp_path, unified_session=True)
|
||||
|
||||
async def long_running():
|
||||
await asyncio.sleep(10)
|
||||
|
||||
task1 = asyncio.create_task(long_running())
|
||||
task2 = asyncio.create_task(long_running())
|
||||
loop._active_tasks[UNIFIED_SESSION_KEY] = {task1, task2}
|
||||
|
||||
msg = InboundMessage(
|
||||
channel="discord",
|
||||
chat_id="789012",
|
||||
sender_id="user2",
|
||||
content="/stop",
|
||||
session_key_override=UNIFIED_SESSION_KEY,
|
||||
)
|
||||
|
||||
ctx = CommandContext(msg=msg, session=None, key=UNIFIED_SESSION_KEY, raw="/stop", loop=loop)
|
||||
|
||||
result = await cmd_stop(ctx)
|
||||
|
||||
assert "Stopped 2 task" in result.content
|
||||
@@ -28,13 +28,11 @@ from nanobot.security.workspace_access import (
|
||||
build_workspace_scope,
|
||||
reset_workspace_scope,
|
||||
)
|
||||
from nanobot.session.keys import UNIFIED_SESSION_KEY
|
||||
from nanobot.utils.llm_runtime import LLMRuntime
|
||||
|
||||
|
||||
def _make_loop(
|
||||
tmp_path: Path, *, allow_set: bool = False, restricted: bool = False, sandbox: str = "",
|
||||
unified_session: bool = False,
|
||||
) -> AgentLoop:
|
||||
provider = MagicMock()
|
||||
provider.get_default_model.return_value = "test-model"
|
||||
@@ -49,7 +47,6 @@ def _make_loop(
|
||||
model="test-model",
|
||||
tools_config=tools_config,
|
||||
restrict_to_workspace=restricted,
|
||||
unified_session=unified_session,
|
||||
)
|
||||
|
||||
|
||||
@@ -505,7 +502,7 @@ async def test_followup_only_joins_matching_tool_scope(tmp_path: Path, same_scop
|
||||
project = tmp_path / "project"
|
||||
project.mkdir()
|
||||
(project / "marker.txt").write_text("active project", encoding="utf-8")
|
||||
loop = _make_loop(tmp_path / "agent", unified_session=True)
|
||||
loop = _make_loop(tmp_path / "agent")
|
||||
loop.provider.generation = GenerationSettings()
|
||||
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=[
|
||||
LLMResponse(content=None, tool_calls=[
|
||||
@@ -513,7 +510,7 @@ async def test_followup_only_joins_matching_tool_scope(tmp_path: Path, same_scop
|
||||
]),
|
||||
LLMResponse(content="done"),
|
||||
])
|
||||
session = await loop.sessions.state.get(UNIFIED_SESSION_KEY)
|
||||
session = await loop.sessions.state.get("websocket:chat")
|
||||
session.metadata["workspace_scope"] = {"project_path": str(project), "access_mode": "restricted"}
|
||||
session.add_message("user", "Start")
|
||||
await loop.sessions.state.prepare_input(session)
|
||||
|
||||
@@ -32,7 +32,6 @@ def _make_mock_loop(**overrides):
|
||||
loop.model_preset = None
|
||||
loop.model_presets = {}
|
||||
loop._concurrency_gate = None
|
||||
loop._unified_session = False
|
||||
loop._extra_hooks = []
|
||||
loop.set_runtime_model.side_effect = lambda value: setattr(loop, "model", value)
|
||||
loop.set_runtime_max_iterations.side_effect = lambda value: setattr(loop, "max_iterations", value)
|
||||
|
||||
Reference in new issue
Block a user