refactor(session): decouple history tools from WebUI replay (#6017)
* refactor(session): decouple history tools from WebUI replay * test(oauth): make callback expiry independent of thread scheduling
This commit is contained in:
1 parent
ae6801d3eb
commit
4904305450
9 files changed
+273
-503
No files matched your search
@@ -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
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("compacted", [False, True])
|
||||
@pytest.mark.parametrize("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]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("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() == original
|
||||
@@ -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
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("compacted", [False, True])
|
||||
@pytest.mark.parametrize("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]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("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)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("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)
|
||||
@@ -15,7 +15,6 @@ from nanobot.agent.tools.sessions import ReadSessionTool, SearchSessionsTool
|
||||
from nanobot.runtime_context import RuntimeContextBlock, append_runtime_context
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.session_handles import SessionHandleResolver
|
||||
from nanobot.webui.transcript import append_transcript_object
|
||||
|
||||
|
||||
def _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"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
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,
|
||||
|
||||
@@ -2,6 +2,7 @@ from __future__ import annotations
|
||||
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from types import SimpleNamespace
|
||||
from urllib.parse import parse_qs, urlencode, urlsplit
|
||||
|
||||
import 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.0
|
||||
with pytest.raises(OpenAICodexOAuthError, match="expired"):
|
||||
complete_openai_codex_oauth_login(flow)
|
||||
finally:
|
||||
|
||||
@@ -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 None
|
||||
|
||||
|
||||
def test_persisted_session_mentions_validate_fields() -> None:
|
||||
|
||||
Reference in new issue
Block a user