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
refactor(session): decouple history tools from WebUI replay (#6017)
chengyongru49043054500c
diff --git a/docs/architecture.md b/docs/architecture.mdindex 249471ba0..3a52ff0c3 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -178,6 +178,12 @@ explicit; do not treat the entire agent workspace as an allowed root.Session history is the near-term conversation replay. Memory is the longer-term workspace state.+`nanobot/session/history.py` reads full persisted session records for+`search_sessions` and `read_session`, including messages before summary+checkpoints. Tool results contain public user and assistant text with indexes+into the original session messages. WebUI transcript events and replay pagination+are owned by the display adapter and do not supply tool history.+| Store | File area ||---|---|| Session JSONL files | `<config-dir>/sessions/<workspace-id>/` |diff --git a/nanobot/agent/tools/sessions.py b/nanobot/agent/tools/sessions.pyindex d2a44dd34..0e04fc470 100644--- a/nanobot/agent/tools/sessions.py+++ b/nanobot/agent/tools/sessions.py@@ -13,12 +13,12 @@ from urllib.parse import quotefrom nanobot.agent.tools.base import Tool, ToolResult, tool_parametersfrom nanobot.agent.tools.context import ToolContext, current_request_session_keyfrom nanobot.agent.tools.schema import StringSchema, tool_parameters_schema+from nanobot.session.history import SessionHistoryReaderfrom nanobot.session.manager import SessionManagerfrom nanobot.session.session_handles import (SessionHandleResolver,normalize_session_handle,)-from nanobot.webui.session_access import WebuiSessionAccess_SEARCH_LIMIT = 5_READ_LIMIT = 8@@ -53,7 +53,7 @@ def _session_ref(session_key: str) -> str:class _SessionTool(Tool):def __init__(self, sessions: SessionManager) -> None:- self._access = WebuiSessionAccess(sessions)+ self._access = SessionHistoryReader(sessions)@classmethoddef create(cls, ctx: ToolContext) -> Tool:diff --git a/nanobot/session/history.py b/nanobot/session/history.pynew file mode 100644index 000000000..3a7f4b981--- /dev/null+++ b/nanobot/session/history.py@@ -0,0 +1,148 @@+"""Read searchable conversation text from persisted session records."""++from __future__ import annotations++from collections.abc import Mapping+from typing import Any, TypedDict, cast++from nanobot.runtime_context import public_history_message+from nanobot.session.history_visibility import is_hidden_history_message+from nanobot.session.manager import SessionManager+++class SessionMessage(TypedDict):+ message_index: int+ role: str+ timestamp: str | int | None+ content: str+++class SessionMatch(TypedDict):+ session_key: str+ title: str+ updated_at: str | None+ messages: list[SessionMessage]+++def _text(value: object) -> str:+ return value.strip()[:160] if isinstance(value, str) else ""+++def _message_text(message: Mapping[str, Any]) -> str:+ content = message.get("content")+ if isinstance(content, str):+ return content.strip()+ if not isinstance(content, list):+ return ""+ parts: list[str] = []+ for raw_block in cast(list[object], content):+ if not isinstance(raw_block, dict):+ continue+ block = cast(dict[object, object], raw_block)+ text = block.get("text")+ if block.get("type") == "text" and isinstance(text, str):+ parts.append(text)+ return "\n".join(parts).strip()+++def _matching_messages(raw_messages: object, *, needle: str, limit: int) -> list[SessionMessage]:+ if not isinstance(raw_messages, list):+ return []+ messages = cast(list[object], raw_messages)+ matches: list[SessionMessage] = []+ for index in range(len(messages) - 1, -1, -1):+ raw_message = messages[index]+ if not isinstance(raw_message, dict):+ continue+ message = cast(dict[str, Any], raw_message)+ role = message.get("role")+ if role not in {"user", "assistant"} or message.get("_command") or is_hidden_history_message(message):+ continue+ public = public_history_message(message)+ text = _message_text(public)+ if not text or (needle and needle not in text.casefold()):+ continue+ timestamp = public.get("timestamp")+ matches.append({+ "message_index": index,+ "role": cast(str, role),+ "timestamp": timestamp if isinstance(timestamp, (str, int)) else None,+ "content": text,+ })+ if len(matches) == limit:+ break+ matches.reverse()+ return matches+++class SessionHistoryReader:+ """Search full persisted history, including messages before summary checkpoints."""++ def __init__(self, sessions: SessionManager) -> None:+ self._sessions = sessions++ def search(+ self,+ query: str,+ limit: int,+ *,+ exclude_session_key: str | None = None,+ ) -> list[SessionMatch]:+ needle = query.casefold()+ ranked: list[tuple[int, SessionMatch]] = []+ remaining: list[dict[str, Any]] = []+ for row in self._sessions.list_sessions():+ key = row.get("key")+ if not isinstance(key, str) or key == exclude_session_key:+ continue+ title = _text(row.get("title"))+ folded = title.casefold()+ rank = (+ 0 if folded == needle+ else 1 if folded.startswith(needle)+ else 2 if needle in folded+ else None+ )+ if rank is None:+ remaining.append(row)+ continue+ updated = row.get("updated_at")+ ranked.append((rank, {+ "session_key": key,+ "title": title,+ "updated_at": updated if isinstance(updated, str) else None,+ "messages": [],+ }))++ ranked.sort(key=lambda item: item[0])+ for row in remaining:+ if len(ranked) >= limit:+ break+ match = self.read(cast(str, row["key"]), query=query, limit=2)+ if match is not None and match["messages"]:+ match["title"] = _text(row.get("title")) or _text(match["messages"][0]["content"])+ ranked.append((3, match))+ return [item[1] for item in ranked[:limit]]++ def read(+ self,+ session_key: str,+ *,+ query: str,+ limit: int,+ exclude_session_key: str | None = None,+ ) -> SessionMatch | None:+ if session_key == exclude_session_key:+ return None+ payload = self._sessions.read_session_file(session_key)+ if payload is None:+ return None+ raw_metadata = cast(object, payload.get("metadata"))+ metadata = cast(dict[str, Any], raw_metadata) if isinstance(raw_metadata, dict) else {}+ updated = payload.get("updated_at")+ return {+ "session_key": session_key,+ "title": _text(metadata.get("title")),+ "updated_at": updated if isinstance(updated, str) else None,+ "messages": _matching_messages(payload.get("messages"), needle=query.casefold(), limit=limit),+ }diff --git a/nanobot/webui/session_access.py b/nanobot/webui/session_access.pyindex 8e24f8d76..b0e8b5c39 100644--- a/nanobot/webui/session_access.py+++ b/nanobot/webui/session_access.py@@ -1,27 +1,18 @@-"""Read and validate persisted conversations for WebUI and session tools."""+"""Validate WebUI session references against persisted session metadata."""from __future__ import annotationsimport jsonfrom collections.abc import Mapping-from functools import cachefrom typing import Any, TypedDict, castfrom nanobot.runtime_context import (RuntimeContextBlock,- public_history_message,wrap_runtime_context_lines,)-from nanobot.session.history_visibility import is_hidden_history_messagefrom nanobot.session.manager import SessionManagerfrom nanobot.session.session_handles import SessionHandleResolver-from nanobot.webui.session_list_index import list_webui_sessions-from nanobot.webui.transcript import (- build_webui_thread_response,- normalize_session_mentions_metadata,-)--_VISIBLE_ROLES = {"user", "assistant"}+from nanobot.webui.transcript import normalize_session_mentions_metadataclass SessionMention(TypedDict):@@ -31,127 +22,6 @@ class SessionMention(TypedDict):title: str-class SessionMessage(TypedDict):- message_index: int- role: str- timestamp: str | int | None- content: str---class SessionMatch(TypedDict):- session_key: str- title: str- updated_at: str | None- messages: list[SessionMessage]---def _message_text(message: Mapping[str, Any]) -> str:- content = message.get("content")- if isinstance(content, str):- return content.strip()- if not isinstance(content, list):- return ""- parts: list[str] = []- for raw_block in cast(list[object], content):- if not isinstance(raw_block, dict):- continue- block = cast(dict[object, object], raw_block)- text = block.get("text")- if block.get("type") == "text" and isinstance(text, str):- parts.append(text)- return "\n".join(parts).strip()---def _visible_messages(raw_messages: object) -> list[SessionMessage]:- if not isinstance(raw_messages, list):- return []- visible: list[SessionMessage] = []- for index, raw_message in enumerate(cast(list[object], raw_messages)):- if not isinstance(raw_message, dict):- continue- message = cast(dict[str, Any], raw_message)- role = message.get("role")- if role not in _VISIBLE_ROLES or message.get("_command") or is_hidden_history_message(message):- continue- public = public_history_message(message)- text = _message_text(public)- if not text:- continue- timestamp = public.get("createdAt", public.get("timestamp"))- visible.append({- "message_index": index,- "role": cast(str, role),- "timestamp": timestamp if isinstance(timestamp, (str, int)) else None,- "content": text,- })- return visible---def _visible_projection_events(raw_events: object) -> list[SessionMessage]:- """Extract searchable conversation text from the event protocol.-- This is intentionally narrower than the WebUI projector: session tools- expose only user and assistant answer text, never reasoning or activity.- """- if not isinstance(raw_events, list):- return []- visible: list[SessionMessage] = []- stream_parts: list[str] = []- stream_timestamp: str | int | None = None-- def append(role: str, text: object, timestamp: object) -> None:- content = text.strip() if isinstance(text, str) else ""- if not content:- return- visible.append({- "message_index": len(visible),- "role": role,- "timestamp": timestamp if isinstance(timestamp, (str, int)) else None,- "content": content,- })-- def flush_stream(final_text: object = None) -> None:- nonlocal stream_timestamp- text = final_text if isinstance(final_text, str) else "".join(stream_parts)- append("assistant", text, stream_timestamp)- stream_parts.clear()- stream_timestamp = None-- for raw_event in cast(list[object], raw_events):- if not isinstance(raw_event, dict):- continue- event = cast(dict[str, Any], raw_event)- name = event.get("event")- timestamp = event.get("created_at_ms")- if name == "user_message":- flush_stream()- append("user", event.get("text"), timestamp)- elif name == "delta":- text = event.get("text")- if isinstance(text, str):- if not stream_parts:- stream_timestamp = timestamp if isinstance(timestamp, (str, int)) else None- stream_parts.append(text)- elif name == "stream_end":- if event.get("resuming") is True and event.get("merge_next") is True:- text = event.get("text")- if isinstance(text, str):- stream_parts[:] = [text]- continue- flush_stream(event.get("text"))- elif name == "message":- kind = event.get("kind")- if kind in {"tool_hint", "progress", "reasoning"}:- flush_stream()- continue- flush_stream()- append("assistant", event.get("text"), timestamp)- elif name in {"reasoning_delta", "reasoning_end", "file_edit", "turn_end"}:- flush_stream()- flush_stream()- return visible--def _text(value: object) -> str:return value.strip()[:160] if isinstance(value, str) else ""@@ -161,12 +31,8 @@ def _session_metadata(payload: Mapping[str, Any]) -> dict[str, Any]:return cast(dict[str, Any], raw) if isinstance(raw, dict) else {}-def _row_title(row: Mapping[str, Any]) -> str:- return _text(row.get("title")) or _text(row.get("preview"))--class WebuiSessionAccess:- """Own listing, validation, and history reads for session references."""+ """Validate and normalize session references selected in the WebUI."""def __init__(self, sessions: SessionManager) -> None:self._sessions = sessions@@ -182,145 +48,6 @@ class WebuiSessionAccess:return Nonereturn self._sessions.read_session_metadata(session_key)- def _messages(self, session_key: str, *, needle: str, limit: int) -> list[SessionMessage]:- @cache- def load_session_messages() -> list[dict[str, Any]] | None:- payload = self._sessions.read_session_file(session_key)- raw_messages = payload.get("messages") if payload is not None else None- if not isinstance(raw_messages, list):- return []- return [- cast(dict[str, Any], message)- for message in cast(list[object], raw_messages)- 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.- matches: list[SessionMessage] = []- message_count = 0- before: str | None = None- while True:- thread = build_webui_thread_response(- session_key,- session_messages_loader=load_session_messages,- before=before,- )- if thread is None:- if before is None:- return matching(load_session_messages())[-limit:]- break- raw_events = thread.get("events")- if isinstance(raw_events, list):- page_messages = _visible_projection_events(cast(list[object], raw_events))- message_count += len(page_messages)- remaining = limit - len(matches)- if remaining > 0:- page_matches = [- message for message in page_messages- if not needle or needle in message["content"].casefold()- ][-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 + matches- raw_page = thread.get("page")- if not isinstance(raw_page, dict):- break- page = cast(dict[str, Any], raw_page)- cursor = page.get("before_cursor")- if not page.get("has_more_before") or not isinstance(cursor, str) or cursor == before:- break- before = cursor-- # 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 matches-- def search(- self,- query: str,- limit: int,- *,- exclude_session_key: str | None = None,- ) -> list[SessionMatch]:- needle = query.casefold()- rows: list[dict[str, Any]] = []- for row in list_webui_sessions(self._sessions):- key = row.get("key")- if isinstance(key, str) and key != exclude_session_key:- rows.append(row)- ranked: list[tuple[int, SessionMatch]] = []- remaining: list[dict[str, Any]] = []- for row in rows:- title = _row_title(row)- folded = title.casefold()- rank = (- 0 if folded == needle- else 1 if folded.startswith(needle)- else 2 if needle in folded- else None- )- if rank is None:- remaining.append(row)- continue- updated = row.get("updated_at")- ranked.append((rank, {- "session_key": cast(str, row["key"]),- "title": title,- "updated_at": updated if isinstance(updated, str) else None,- "messages": [],- }))-- ranked.sort(key=lambda item: item[0])- needed = max(0, limit - len(ranked))- for row in remaining:- if needed <= 0:- break- key = cast(str, row["key"])- matches = self._messages(key, needle=needle, limit=2)- if not matches:- continue- updated = row.get("updated_at")- ranked.append((3, {- "session_key": key,- "title": _row_title(row),- "updated_at": updated if isinstance(updated, str) else None,- "messages": matches,- }))- needed -= 1- return [item[1] for item in ranked[:limit]]-- def read(- self,- session_key: str,- *,- query: str,- limit: int,- exclude_session_key: str | None = None,- ) -> SessionMatch | None:- 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(), 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,- }-def normalize_mentions(self,raw: object,@@ -352,6 +79,7 @@ class WebuiSessionAccess:seen_names.add(folded_name)return normalized+def session_mentions_runtime_context(mentions: list[SessionMention],) -> RuntimeContextBlock | None:diff --git a/tests/agent/tools/test_session_history.py b/tests/agent/tools/test_session_history.pynew file mode 100644index 000000000..df6620e8c--- /dev/null+++ b/tests/agent/tools/test_session_history.py@@ -0,0 +1,100 @@+"""Session tools read full canonical history independently of WebUI replay."""++from __future__ import annotations++import json++import pytest++from nanobot.agent.tools.context import RequestContext, request_context+from nanobot.agent.tools.sessions import ReadSessionTool, SearchSessionsTool+from nanobot.session.manager import SessionManager+from nanobot.webui.transcript import append_transcript_object++[email protected]("compacted", [False, True])[email protected]("tool_name", ["search", "read"])+async def test_session_tools_find_old_matches_in_full_session(+ tmp_path, compacted, tool_name,+):+ manager = SessionManager(tmp_path)+ key = "sdk:history"+ session = manager.get_or_create(key)+ session.metadata.update({"title": "Project notes", "title_user_edited": True})+ for index in range(180):+ text = f"launch decision {index}" if index < 10 else f"unrelated update {index}"+ session.add_message("user", text)+ session.add_message("assistant", f"acknowledged {index}")+ if compacted:+ session.commit_summary_checkpoint("Project updates are complete.")+ assert session.get_history() == []+ manager.save(session)+ manager = SessionManager(tmp_path)++ with request_context(RequestContext(+ channel="sdk", chat_id="current", session_key="sdk:current",+ )):+ if tool_name == "search":+ output = json.loads(await SearchSessionsTool(manager).execute(query="launch decision"))+ assert [item["session_key"] for item in output["results"]] == [key]+ matches = output["results"][0]["excerpts"]+ expected = range(8, 10)+ else:+ output = json.loads(await ReadSessionTool(manager).execute(+ session_key=key, query="launch decision",+ ))+ matches = output["messages"]+ expected = range(2, 10)+ latest = json.loads(await ReadSessionTool(manager).execute(session_key=key))+ assert len(latest["messages"]) == 8+ assert [item["message_index"] for item in latest["messages"]] == list(range(352, 360))+ assert latest["messages"][-1]["content"] == "acknowledged 179"++ 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]("state", ["canonical", "transcript", "mixed"])+async def test_session_tools_use_canonical_records_after_restart(tmp_path, monkeypatch, state):+ webui_dir = tmp_path / "webui"+ monkeypatch.setattr("nanobot.webui.transcript.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-only 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):+ 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")+ display_search = json.loads(await SearchSessionsTool(manager).execute(query="display-only"))+ if state == "transcript":+ assert search["results"] == []+ assert read.is_error and "session not found" in str(read)+ else:+ assert [row["session_key"] for row in search["results"]] == [key]+ assert search["results"][0]["excerpts"][0]["content"] == "canonical needle"+ assert [item["content"] for item in json.loads(read)["messages"]] == ["canonical needle"]+ assert display_search["results"] == []+ assert durable_files() == originaldiff --git a/tests/agent/tools/test_session_history_pagination.py b/tests/agent/tools/test_session_history_pagination.pydeleted file mode 100644index 9701ddaf6..000000000--- a/tests/agent/tools/test_session_history_pagination.py+++ /dev/null@@ -1,164 +0,0 @@-"""Session tools must not mistake a transcript page for the whole conversation."""--from __future__ import annotations--import json-import weakref--import pytest--from nanobot.agent.tools.context import RequestContext, request_context-from nanobot.agent.tools.sessions import ReadSessionTool, SearchSessionsTool-from nanobot.session.manager import SessionManager-from nanobot.webui.transcript import append_transcript_object, webui_transcript_segments_dir--[email protected]("compacted", [False, True])[email protected]("tool_name", ["search", "read"])-async def test_session_tools_find_old_matches_beyond_the_latest_page(- tmp_path, monkeypatch, compacted, tool_name,-):- 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)- if compacted:- monkeypatch.setattr("nanobot.webui.transcript._ACTIVE_TRANSCRIPT_ROTATE_BYTES", 8192)- monkeypatch.setattr("nanobot.webui.transcript._TARGET_ACTIVE_TRANSCRIPT_BYTES", 4096)- manager = SessionManager(tmp_path)- key = "websocket:history"- session = manager.get_or_create(key)- session.metadata.update({"title": "Project notes", "title_user_edited": True})- for index in range(180):- text = f"launch decision {index}" if index < 10 else f"unrelated update {index}"- session.add_message("user", text)- session.add_message("assistant", f"acknowledged {index}")- for record in (- {"event": "user", "text": text},- {"event": "message", "text": f"acknowledged {index}"},- {"event": "turn_end"},- ):- append_transcript_object(key, record)- if compacted:- session.messages = session.messages[-2:]- assert any(webui_transcript_segments_dir(key).glob("*.jsonl"))- manager.save(session)-- with request_context(RequestContext(- channel="websocket", chat_id="current", session_key="websocket:current",- )):- if tool_name == "search":- output = json.loads(await SearchSessionsTool(manager).execute(query="launch decision"))- assert [item["session_key"] for item in output["results"]] == [key]- matches = output["results"][0]["excerpts"]- expected = range(8, 10)- else:- output = json.loads(await ReadSessionTool(manager).execute(- session_key=key, query="launch decision",- ))- matches = output["messages"]- expected = range(2, 10)- latest = json.loads(await ReadSessionTool(manager).execute(session_key=key))- assert len(latest["messages"]) == 8- assert [item["message_index"] for item in latest["messages"]] == list(range(352, 360))- assert latest["messages"][-1]["content"] == "acknowledged 179"-- 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- events = [- TrackedMessage(event="user_message", text=f"visible {start}"),- TrackedMessage(event="message", kind="progress", text="private tool result"),- TrackedMessage(event="message", text=f"visible {start + 2}"),- TrackedMessage(event="reasoning_delta", text="private reasoning"),- TrackedMessage(event="message", text=""),- ]- refs.extend(weakref.ref(event) for event in events)- return {"events": events, "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_indexes = list(range(12, 20))- expected_values = [30, 32, 35, 37, 40, 42, 45, 47]- assert [item["message_index"] for item in result["messages"]] == expected_indexes- assert [item["content"] for item in result["messages"]] == [- f"visible {i}" for i in expected_values- ]- 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)diff --git a/tests/agent/tools/test_sessions.py b/tests/agent/tools/test_sessions.pyindex 52e35c138..185e12f33 100644--- a/tests/agent/tools/test_sessions.py+++ b/tests/agent/tools/test_sessions.py@@ -15,7 +15,6 @@ from nanobot.agent.tools.sessions import ReadSessionTool, SearchSessionsToolfrom nanobot.runtime_context import RuntimeContextBlock, append_runtime_contextfrom nanobot.session.manager import SessionManagerfrom nanobot.session.session_handles import SessionHandleResolver-from nanobot.webui.transcript import append_transcript_objectdef _save_session(@@ -79,39 +78,7 @@ def test_session_tools_do_not_own_runtime_context(tmp_path) -> None:@pytest.mark.asyncio-async def test_search_sessions_reads_the_full_webui_transcript_after_compaction(- tmp_path,- monkeypatch,-):- 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)- _save_session(- manager,- "websocket:history",- title="History",- messages=[{"role": "assistant", "content": "retained suffix"}],- )- append_transcript_object("websocket:history", {- "event": "user",- "text": "decision only in the old transcript",- })-- with _webui_request():- result = _decode(await SearchSessionsTool(manager).execute(query="old transcript"))-- assert [row["session_key"] for row in result["results"]] == ["websocket:history"]- assert result["results"][0]["excerpts"][0]["content"] == (- "decision only in the old transcript"- )---async def test_search_sessions_has_no_hidden_content_scan_cutoff(tmp_path, monkeypatch):- 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)+async def test_search_sessions_has_no_hidden_content_scan_cutoff(tmp_path):manager = SessionManager(tmp_path)for index in range(200):_save_session(@@ -136,10 +103,7 @@ async def test_search_sessions_has_no_hidden_content_scan_cutoff(tmp_path, monke@pytest.mark.asyncio-async def test_search_sessions_ranks_titles_before_message_matches(tmp_path, monkeypatch):- 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)+async def test_search_sessions_ranks_titles_before_message_matches(tmp_path):manager = SessionManager(tmp_path)_save_session(manager,@@ -182,10 +146,10 @@ async def test_session_tools_hide_private_and_non_conversation_messages(tmp_path_save_session(manager,"websocket:history",- title="History",+ title="",messages=[- {"role": "user", "content": content, "_runtime_context": marker},{"role": "user", "content": "hidden needle", "_hidden_history": True},+ {"role": "user", "content": content, "_runtime_context": marker},{"role": "tool", "content": "tool needle"},{"role": "assistant", "content": "visible answer"},],@@ -203,6 +167,7 @@ async def test_session_tools_hide_private_and_non_conversation_messages(tmp_path"visible question","visible answer",]+ assert [message["message_index"] for message in messages] == [1, 3]assert all("secret runtime context" not in message["content"] for message in messages)@@ -351,10 +316,7 @@ async def test_read_session_accepts_a_persisted_session_handle(tmp_path):@pytest.mark.asyncio-async def test_session_tools_work_without_request_context(tmp_path, monkeypatch):- 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)+async def test_session_tools_work_without_request_context(tmp_path):manager = SessionManager(tmp_path)_save_session(manager,diff --git a/tests/providers/test_openai_codex_oauth.py b/tests/providers/test_openai_codex_oauth.pyindex 1e58c8506..07211d2d7 100644--- a/tests/providers/test_openai_codex_oauth.py+++ b/tests/providers/test_openai_codex_oauth.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport timefrom collections.abc import Callable+from types import SimpleNamespacefrom urllib.parse import parse_qs, urlencode, urlsplitimport pytest@@ -229,17 +230,20 @@ def test_dependency_error_is_bounded_and_does_not_expose_callback(def test_remote_flow_expires_while_waiting_for_callback(monkeypatch: pytest.MonkeyPatch,) -> None:+ now = 0.0+ monkeypatch.setattr(codex_oauth, "time", SimpleNamespace(monotonic=lambda: now))monkeypatch.setattr(codex_oauth,"login_oauth_interactive",_fake_interactive_login({}),)flow = start_openai_codex_oauth_login(- timeout_s=0.05,+ timeout_s=60,open_browser=False,)try:- time.sleep(0.08)+ assert complete_openai_codex_oauth_login(flow) is None+ now = 61.0with pytest.raises(OpenAICodexOAuthError, match="expired"):complete_openai_codex_oauth_login(flow)finally:diff --git a/tests/webui/test_session_mentions.py b/tests/webui/test_session_mentions.pyindex 3c3093d4b..f7c1f8764 100644--- a/tests/webui/test_session_mentions.py+++ b/tests/webui/test_session_mentions.py@@ -91,10 +91,7 @@ def test_session_mention_context_treats_titles_as_data() -> None:assert json.loads(block.content.splitlines()[2])[0]["session_key"] == "websocket:history"-def test_session_mentions_do_not_isolate_workspaces(tmp_path, monkeypatch) -> None:- 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)+def test_session_mentions_do_not_isolate_workspaces(tmp_path) -> None:manager = SessionManager(tmp_path)project_b = tmp_path / "b"project_b.mkdir()@@ -121,17 +118,6 @@ def test_session_mentions_do_not_isolate_workspaces(tmp_path, monkeypatch) -> No"session_key": "websocket:other","title": "Other",}]- assert [row["session_key"] for row in access.search(- "Other",- 5,- exclude_session_key="websocket:current",- )] == ["websocket:other"]- assert access.read(- "websocket:other",- query="",- limit=5,- exclude_session_key="websocket:current",- ) is not Nonedef test_persisted_session_mentions_validate_fields() -> None: