Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
fix(session): bound retained history search results across pages
Xubin Ren8c4eb2c807c6
diff --git a/nanobot/webui/session_access.py b/nanobot/webui/session_access.pyindex b22f7ee98..ba935972a 100644--- a/nanobot/webui/session_access.py+++ b/nanobot/webui/session_access.py@@ -117,7 +117,7 @@ class WebuiSessionAccess:return Nonereturn self._sessions.read_session_metadata(session_key)- def _messages(self, session_key: str) -> list[SessionMessage]:+ def _messages(self, session_key: str, *, needle: str, limit: int) -> list[SessionMessage]:@cachedef load_session_messages() -> list[dict[str, Any]] | None:payload = self._sessions.read_session_file(session_key)@@ -130,10 +130,17 @@ class WebuiSessionAccess:if isinstance(message, dict)]+ def matching(raw_messages: object) -> list[SessionMessage]:+ return [+ message for message in _visible_messages(raw_messages)+ if not needle or needle in message["content"].casefold()+ ]+# The WebUI replay API returns one page, even when no limit is given.# Session tools need the older pages too, including turns no longer in# the compacted model history. Keep the UI's per-page replay budgets.- pages: list[list[object]] = []+ matches: list[SessionMessage] = []+ message_count = 0before: str | None = Nonewhile True:thread = build_webui_thread_response(@@ -143,11 +150,20 @@ class WebuiSessionAccess:)if thread is None:if before is None:- return _visible_messages(load_session_messages())+ return matching(load_session_messages())[-limit:]breakraw_messages = thread.get("messages")if isinstance(raw_messages, list):- pages.append(cast(list[object], raw_messages))+ page_messages = cast(list[object], raw_messages)+ message_count += len(page_messages)+ remaining = limit - len(matches)+ if remaining > 0:+ page_matches = matching(page_messages)[-remaining:]+ for message in page_matches:+ # Index relative to the conversation's end until we+ # know the total number of raw messages across pages.+ message["message_index"] -= message_count+ matches = page_matches + matchesraw_page = thread.get("page")if not isinstance(raw_page, dict):break@@ -157,9 +173,11 @@ class WebuiSessionAccess:breakbefore = cursor- # Page traversal is newest-first; filter after restoring chronological- # order so message indexes and the latest-match limits stay consistent.- return _visible_messages([message for page in reversed(pages) for message in page])+ # Global indexes still require counting older pages, but retain only+ # the requested matches, never the full conversation's raw traces.+ for message in matches:+ message["message_index"] += message_count+ return matchesdef search(self,@@ -202,11 +220,7 @@ class WebuiSessionAccess:if needed <= 0:breakkey = cast(str, row["key"])- matches = [- message- for message in self._messages(key)- if needle in message["content"].casefold()- ]+ matches = self._messages(key, needle=needle, limit=2)if not matches:continueupdated = row.get("updated_at")@@ -214,7 +228,7 @@ class WebuiSessionAccess:"session_key": key,"title": _row_title(row),"updated_at": updated if isinstance(updated, str) else None,- "messages": matches[-2:],+ "messages": matches,}))needed -= 1return [item[1] for item in ranked[:limit]]@@ -230,16 +244,13 @@ class WebuiSessionAccess:payload = self._metadata(session_key, exclude_session_key=exclude_session_key)if payload is None:return None- messages = self._messages(session_key)- needle = query.casefold()- if needle:- messages = [message for message in messages if needle in message["content"].casefold()]+ messages = self._messages(session_key, needle=query.casefold(), limit=limit)updated = payload.get("updated_at")return {"session_key": session_key,"title": _text(_session_metadata(payload).get("title")),"updated_at": updated if isinstance(updated, str) else None,- "messages": messages[-limit:],+ "messages": messages,}def normalize_mentions(diff --git a/tests/agent/tools/test_session_history_pagination.py b/tests/agent/tools/test_session_history_pagination.pyindex 42d0cb717..71b2f6b27 100644--- a/tests/agent/tools/test_session_history_pagination.py+++ b/tests/agent/tools/test_session_history_pagination.py@@ -3,6 +3,7 @@from __future__ import annotationsimport json+import weakrefimport pytest@@ -64,3 +65,97 @@ async def test_session_tools_find_old_matches_beyond_the_latest_page(assert [item["content"] for item in matches] == [f"launch decision {i}" for i in expected]assert [item["message_index"] for item in matches] == [i * 2 for i in expected]++[email protected]("query", ["", "visible"])+async def test_read_releases_raw_pages_while_preserving_global_indexes(tmp_path, monkeypatch, query):+ """Tool results are tiny; do not retain every page's raw trace payloads."""+ class TrackedMessage(dict):+ pass++ manager = SessionManager(tmp_path)+ key = "websocket:history"+ manager.save(manager.get_or_create(key))+ refs = []+ calls = []++ def page(_key, *, before=None, **_kwargs):+ # The immediately previous response can still be live while requesting+ # the next one. Older raw messages must already have been released.+ assert sum(ref() is not None for ref in refs) <= 5+ index = int(before) if before is not None else 0+ calls.append(index)+ start = (9 - index) * 5+ messages = [+ TrackedMessage(role="user", content=f"visible {start}"),+ TrackedMessage(role="tool", content="private tool result"),+ TrackedMessage(role="assistant", content=f"visible {start + 2}"),+ TrackedMessage(role="user", content="hidden", _hidden_history=True),+ TrackedMessage(role="assistant", content=""),+ ]+ refs.extend(weakref.ref(message) for message in messages)+ return {"messages": messages, "page": {+ "has_more_before": index < 9,+ "before_cursor": str(index + 1) if index < 9 else None,+ }}++ monkeypatch.setattr("nanobot.webui.session_access.build_webui_thread_response", page)+ with request_context(RequestContext(+ channel="websocket", chat_id="current", session_key="websocket:current",+ )):+ result = json.loads(await ReadSessionTool(manager).execute(session_key=key, query=query))+ expected = [30, 32, 35, 37, 40, 42, 45, 47]+ assert [item["message_index"] for item in result["messages"]] == expected+ assert [item["content"] for item in result["messages"]] == [f"visible {i}" for i in expected]+ assert calls == list(range(10))+ assert not any(ref() is not None for ref in refs)++[email protected]("state", ["canonical", "transcript", "mixed"])+async def test_session_tools_preserve_durable_sources_after_index_rebuild_and_restart(+ tmp_path, monkeypatch, state,+):+ webui_dir = tmp_path / "webui"+ monkeypatch.setattr("nanobot.webui.transcript.get_webui_dir", lambda: webui_dir)+ monkeypatch.setattr("nanobot.webui.session_list_index.get_webui_dir", lambda: webui_dir)+ manager = SessionManager(tmp_path)+ key = "websocket:history"+ if state != "transcript":+ session = manager.get_or_create(key)+ session.metadata.update({"title": "Project notes", "title_user_edited": True})+ session.add_message("user", "canonical needle")+ manager.save(session)+ if state != "canonical":+ append_transcript_object(key, {+ "event": "user", "chat_id": "history", "text": "display needle",+ })+ append_transcript_object(key, {"event": "turn_end", "chat_id": "history"})++ def durable_files():+ return {+ path: path.read_bytes()+ for root in (manager.sessions_dir, webui_dir)+ for path in root.rglob("*.jsonl")+ }++ original = durable_files()+ for _ in range(2):+ # Read-only tools may rebuild derived indexes, not canonical records.+ manager = SessionManager(tmp_path)+ with request_context(RequestContext(+ channel="websocket", chat_id="current", session_key="websocket:current",+ )):+ search = json.loads(await SearchSessionsTool(manager).execute(query="needle"))+ read = await ReadSessionTool(manager).execute(session_key=key, query="needle")+ assert [row["session_key"] for row in search["results"]] == [key]+ if state == "transcript":+ # Existing read/mention validation requires canonical metadata.+ assert "session not found" in str(read)+ assert manager.read_session_metadata(key) is None+ else:+ expected = "canonical needle" if state == "canonical" else "display needle"+ assert [item["content"] for item in json.loads(read)["messages"]] == [expected]+ assert durable_files() == original+ (manager.sessions_dir / ".webui_session_index.json").unlink(missing_ok=True)