refactor(session): unify model and display history storage (#6336)

* refactor(session): persist display history in SQLite

* fix(session): preserve new fork activity timestamps

* test(agent): use SQLite-owned model failure recovery fixture

* test(agent): isolate session slash routing from loop shutdown

Exercise the real inbound dispatcher and await its session worker. Keep response deadlines and behavioral assertions, while leaving full SQLite cleanup to the existing async fixture rather than an unrelated two-second shutdown deadline.

* fix(webui): admit direct deliveries to display history

* docs: clarify session history migration guidance
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-21 16:13:59 +08:00
1 parent d617b723aa
commit b32b1327ce
50 files changed
+2123 -3235

No files matched your search

+12 -11
View File
@@ -683,6 +683,7 @@ class WebSocketChannel(BaseChannel):
)
async def start(self) -> None:
await self._transcripts.initialize()
self.gateway.http.remote_instances.resume()
from nanobot.utils.logging_bridge import redirect_lib_logging
@@ -1119,7 +1120,7 @@ class WebSocketChannel(BaseChannel):
# Give an idle writer a chance to start without waiting for physical I/O.
await asyncio.sleep(0)
def _persist_turn_transcript_event(
async def _persist_turn_transcript_event(
self,
chat_id: str,
event: dict[str, Any],
@@ -1138,7 +1139,7 @@ class WebSocketChannel(BaseChannel):
chat_id, event, metadata=metadata, phase=phase, include_source=include_source,
)
return True
persisted = self._transcripts.prepare_and_append(
persisted = await self._transcripts.prepare_and_append(
chat_id,
event,
metadata=metadata,
@@ -1169,7 +1170,7 @@ class WebSocketChannel(BaseChannel):
)
return persisted
def _persist_turn_stream_event(
async def _persist_turn_stream_event(
self,
chat_id: str,
event: dict[str, Any],
@@ -1185,7 +1186,7 @@ class WebSocketChannel(BaseChannel):
chat_id, event, metadata=metadata, phase=phase, include_source=include_source,
)
return True
persisted = self._transcripts.prepare_and_append_stream_event(
persisted = await self._transcripts.prepare_and_append_stream_event(
chat_id,
event,
completed_text=completed_text,
@@ -1247,7 +1248,7 @@ class WebSocketChannel(BaseChannel):
elif progress_event:
payload["kind"] = "progress"
phase = "activity" if payload.get("kind") in ("tool_hint", "progress") else "answer"
self._persist_turn_transcript_event(
await self._persist_turn_transcript_event(
msg.chat_id,
payload,
metadata=msg.metadata,
@@ -1287,7 +1288,7 @@ class WebSocketChannel(BaseChannel):
body["stream_id"] = stream_id
stream_key = (chat_id, str(stream_id or ""))
self._reasoning_text_buffers.setdefault(stream_key, []).append(delta)
self._persist_turn_stream_event(
await self._persist_turn_stream_event(
chat_id,
body,
completed_text=None,
@@ -1318,7 +1319,7 @@ class WebSocketChannel(BaseChannel):
body["stream_id"] = stream_id
stream_key = (chat_id, str(stream_id or ""))
reasoning_text = "".join(self._reasoning_text_buffers.pop(stream_key, []))
self._persist_turn_stream_event(
await self._persist_turn_stream_event(
chat_id,
body,
completed_text=reasoning_text or None,
@@ -1343,7 +1344,7 @@ class WebSocketChannel(BaseChannel):
"chat_id": chat_id,
"edits": edits,
}
self._persist_turn_transcript_event(
await self._persist_turn_transcript_event(
chat_id,
payload,
metadata=metadata,
@@ -1397,7 +1398,7 @@ class WebSocketChannel(BaseChannel):
body["resuming"] = True
if stream_end and merge_next:
body["merge_next"] = True
self._persist_turn_stream_event(
await self._persist_turn_stream_event(
chat_id,
body,
completed_text=completed_text,
@@ -1424,7 +1425,7 @@ class WebSocketChannel(BaseChannel):
conns = list(self._subs.get(chat_id, ()))
body: dict[str, Any] = dict(payload)
if persistence == "turn_activity":
self._persist_turn_transcript_event(
await self._persist_turn_transcript_event(
chat_id,
body,
metadata=metadata,
@@ -1436,7 +1437,7 @@ class WebSocketChannel(BaseChannel):
canonical_webui_turn
and websocket_turn_transcript_persistence_failed(chat_id, turn_owner)
)
persisted = self._persist_turn_transcript_event(
persisted = await self._persist_turn_transcript_event(
chat_id,
body,
metadata=metadata,
@@ -15,13 +15,12 @@ from nanobot.command.router import CommandContext
from nanobot.session.manager import SessionManager
from nanobot.webui.metadata import WEBUI_RESTART_CONTROL_METADATA_KEY
from nanobot.webui.session_list_index import list_webui_sessions
from nanobot.webui.transcript import append_transcript_object, read_transcript_lines
from .test_websocket_channel import _basic_handler, _sent_ws_payloads
def _channel(tmp_path: Path, *, allowed: bool = True):
sessions = SessionManager(tmp_path / "workspace")
def _channel(tmp_path: Path, *, allowed: bool = True, sessions=None):
sessions = sessions or SessionManager(tmp_path / "workspace")
bus = MagicMock()
bus.publish_inbound = AsyncMock()
channel = WebSocketChannel(
@@ -37,8 +36,8 @@ def _channel(tmp_path: Path, *, allowed: bool = True):
@pytest.mark.asyncio
@pytest.mark.parametrize("existing", ["none", "canonical", "transcript", "both"])
async def test_settings_restart_does_not_create_or_change_chat_history(tmp_path, monkeypatch, existing):
sessions, bus, channel, connection = _channel(tmp_path)
async def test_settings_restart_does_not_create_or_change_chat_history(history, tmp_path, monkeypatch, existing):
sessions, bus, channel, connection = _channel(tmp_path, sessions=history.sessions)
monkeypatch.setattr("nanobot.command.builtin.set_restart_notice_to_env", MagicMock())
key = "websocket:existing"
if existing in {"canonical", "both"}:
@@ -47,12 +46,12 @@ async def test_settings_restart_does_not_create_or_change_chat_history(tmp_path,
session.metadata.update({"webui": True, "title": "Keep this title"})
sessions.save(session)
if existing in {"transcript", "both"}:
append_transcript_object(key, {
"event": "user_message", "chat_id": "existing", "text": "Keep my conversation",
history.append(key, {
"event": "user", "chat_id": "existing", "text": "Keep my conversation",
})
before_rows = list_webui_sessions(sessions)
before_files = {p: p.read_bytes() for p in tmp_path.rglob("*.jsonl")}
before_transcript = read_transcript_lines(key)
before_transcript = history.read(key)
# Use each new connection's default ID, then an existing chat when present.
chat_ids = ["ready-default-1", "ready-default-2"]
@@ -86,9 +85,9 @@ async def test_settings_restart_does_not_create_or_change_chat_history(tmp_path,
assert len(replies) == len(chat_ids)
assert all(frame["text"] == "Restarting..." and frame["turn_id"].startswith("webui-system:") for frame in replies)
assert {p: p.read_bytes() for p in tmp_path.rglob("*.jsonl")} == before_files
assert read_transcript_lines(key) == before_transcript
assert history.read(key) == before_transcript
# A fresh manager uses the public sidebar discovery path, not a cached count.
fresh = SessionManager(tmp_path / "workspace")
fresh = SessionManager(sessions.workspace)
assert list_webui_sessions(fresh) == before_rows
if existing in {"canonical", "both"}:
restored = fresh.get_existing(key)
@@ -104,8 +103,8 @@ async def test_settings_restart_does_not_create_or_change_chat_history(tmp_path,
("/restart later", "webui-system:not-a-restart"),
("ordinary message", "webui-system:not-a-command"),
])
async def test_control_prefix_does_not_suppress_ordinary_or_session_command_history(tmp_path, text, turn_id):
sessions, bus, channel, connection = _channel(tmp_path)
async def test_control_prefix_does_not_suppress_ordinary_or_session_command_history(history, tmp_path, text, turn_id):
sessions, bus, channel, connection = _channel(tmp_path, sessions=history.sessions)
await channel._dispatch_envelope(connection, "browser", {
"type": "message", "chat_id": "chat", "content": text, "webui": True, "turn_id": turn_id,
"metadata": {WEBUI_RESTART_CONTROL_METADATA_KEY: True},
@@ -114,7 +113,7 @@ async def test_control_prefix_does_not_suppress_ordinary_or_session_command_hist
assert WEBUI_RESTART_CONTROL_METADATA_KEY not in message.metadata
await channel.send(OutboundMessage(channel="websocket", chat_id="chat", content="Reply", metadata=message.metadata))
assert len(list_webui_sessions(sessions)) == 1
assert [row["text"] for row in read_transcript_lines("websocket:chat")] == [text, "Reply"]
assert [row["text"] for row in history.read("websocket:chat")] == [text, "Reply"]
await channel._cleanup_connection(connection)
File diff suppressed because it is too large. Load diff
@@ -297,23 +297,23 @@ async def test_sessions_list_requires_bearer_token(
@pytest.mark.asyncio
async def test_sessions_list_and_thread_restore_transcript_without_canonical_file(
async def test_sessions_list_and_thread_restore_display_without_model_messages(history,
bus: MagicMock, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
sm = SessionManager(tmp_path / "workspace")
from nanobot.webui.transcript import append_transcript_object
sm = history.sessions
key = "websocket:restored-history"
append_transcript_object(
history.append(
key,
{"event": "user", "chat_id": "restored-history", "text": "original question"},
)
append_transcript_object(
history.append(
key,
{"event": "message", "chat_id": "restored-history", "text": "original answer"},
)
assert sm.read_session_snapshot(key) is None
assert sm.read_session_snapshot(key).messages == []
port = _free_port()
channel = _ch(bus, session_manager=sm, port=port)
@@ -344,7 +344,7 @@ async def test_sessions_list_and_thread_restore_transcript_without_canonical_fil
"original question",
"original answer",
]
assert sm.read_session_snapshot(key) is None
assert sm.read_session_snapshot(key).messages == []
finally:
await channel.stop()
await server_task
@@ -2414,21 +2414,23 @@ async def test_webui_sidebar_state_routes_are_config_dir_scoped(
@pytest.mark.asyncio
async def test_session_delete_removes_file(
async def test_session_delete_removes_canonical_and_display_history(history,
bus: MagicMock, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
sm = _seed_session(tmp_path, key="websocket:doomed")
from nanobot.webui.transcript import append_transcript_object
sm = history.sessions
draft = sm.get_or_create("websocket:doomed")
draft.add_message("user", "canonical")
sm.save(draft)
append_transcript_object("websocket:doomed", {"event": "user", "chat_id": "doomed", "text": "x"})
history.append("websocket:doomed", {"event": "user", "chat_id": "doomed", "text": "x"})
channel = _ch(bus, session_manager=sm, port=29903)
server_task = asyncio.create_task(channel.start())
try:
session_key = "websocket:doomed"
assert sm.read_session_snapshot(session_key) is not None
webui_path = tmp_path / "webui" / f"{SessionManager.safe_key('websocket:doomed')}.jsonl"
assert webui_path.is_file()
assert history.read(session_key)[0]["text"] == "x"
resp = await _webui_mutate(
channel,
"session.delete",
@@ -2437,28 +2439,27 @@ async def test_session_delete_removes_file(
assert resp.status_code == 200
assert resp.json()["deleted"] is True
assert sm.read_session_snapshot(session_key) is None
assert not webui_path.exists()
assert history.read(session_key) == []
finally:
await channel.stop()
await server_task
@pytest.mark.asyncio
async def test_session_delete_removes_transcript_without_canonical_file(
async def test_session_delete_removes_display_without_model_messages(history,
bus: MagicMock, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
sm = SessionManager(tmp_path / "workspace")
from nanobot.webui.transcript import append_transcript_object
sm = history.sessions
key = "websocket:transcript-only"
append_transcript_object(
history.append(
key,
{"event": "user", "chat_id": "transcript-only", "text": "recover me"},
)
assert sm.read_session_snapshot(key) is None
webui_path = tmp_path / "webui" / f"{SessionManager.safe_key(key)}.jsonl"
assert webui_path.is_file()
assert sm.read_session_snapshot(key).messages == []
assert history.read(key)[0]["text"] == "recover me"
channel = _ch(bus, session_manager=sm, port=_free_port())
server_task = asyncio.create_task(channel.start())
@@ -2471,7 +2472,8 @@ async def test_session_delete_removes_transcript_without_canonical_file(
assert response.status_code == 200
assert response.json()["deleted"] is True
assert not webui_path.exists()
assert sm.read_session_snapshot(key) is None
assert history.read(key) == []
finally:
await channel.stop()
await server_task
@@ -3211,10 +3213,10 @@ async def test_session_delete_action_accepts_websocket_keys(
@pytest.mark.asyncio
async def test_webui_thread_resigns_assistant_media_urls(
async def test_webui_thread_resigns_assistant_media_urls(history,
bus: MagicMock, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
from nanobot.webui.transcript import append_transcript_object
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
media_root = tmp_path / "media"
@@ -3228,11 +3230,11 @@ async def test_webui_thread_resigns_assistant_media_urls(
monkeypatch.setattr("nanobot.webui.media_gateway.get_media_dir", fake_media_dir)
append_transcript_object(
history.append(
"websocket:video-replay",
{"event": "user", "chat_id": "video-replay", "text": "make a video"},
)
append_transcript_object(
history.append(
"websocket:video-replay",
{
"event": "message",
@@ -3243,7 +3245,7 @@ async def test_webui_thread_resigns_assistant_media_urls(
},
)
channel = _ch(bus, port=29914)
channel = _ch(bus, port=29914, session_manager=history.sessions)
server_task = asyncio.create_task(channel.start())
try:
token = channel.gateway.tokens.issue_api_token(300)
@@ -3311,10 +3313,10 @@ async def test_sessions_list_negotiates_gzip_across_repeated_headers(
@pytest.mark.asyncio
async def test_webui_thread_complete_transcript_skips_session_history_read(
async def test_webui_thread_complete_transcript_skips_session_history_read(history,
bus: MagicMock, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
from nanobot.webui.transcript import append_transcript_object
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
key = "websocket:fast-thread"
@@ -3324,7 +3326,7 @@ async def test_webui_thread_complete_transcript_skips_session_history_read(
{"event": "message", "chat_id": "fast-thread", "text": "hello back"},
{"event": "turn_end", "chat_id": "fast-thread"},
):
append_transcript_object(key, event)
history.append(key, event)
read_session_file = MagicMock(
side_effect=AssertionError("complete transcripts must not read canonical history")
@@ -3361,14 +3363,14 @@ async def test_webui_thread_complete_transcript_skips_session_history_read(
@pytest.mark.asyncio
async def test_webui_thread_negotiates_gzip_for_large_payloads(
async def test_webui_thread_negotiates_gzip_for_large_payloads(history,
bus: MagicMock, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
from nanobot.webui.transcript import append_transcript_object
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
sm = SessionManager(tmp_path)
append_transcript_object(
sm = history.sessions
history.append(
"websocket:gzip-thread",
{
"event": "user",
@@ -3421,10 +3423,10 @@ async def test_webui_thread_negotiates_gzip_for_large_payloads(
@pytest.mark.asyncio
async def test_webui_thread_revalidates_and_loads_large_trace_details(
async def test_webui_thread_revalidates_and_loads_large_trace_details(history,
bus: MagicMock, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
from nanobot.webui.transcript import append_transcript_object
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
key = "websocket:revalidated-thread"
@@ -3441,7 +3443,7 @@ async def test_webui_thread_revalidates_and_loads_large_trace_details(
{"event": "message", "chat_id": "revalidated-thread", "text": "done"},
{"event": "turn_end", "chat_id": "revalidated-thread"},
):
append_transcript_object(key, event)
history.append(key, event)
port = _free_port()
channel = _ch(bus, session_manager=sm, workspace_path=tmp_path, port=port)
server_task = asyncio.create_task(channel.start())
@@ -3481,7 +3483,7 @@ async def test_webui_thread_revalidates_and_loads_large_trace_details(
assert detail.json()["message_id"] == trace_event["projection_id"]
assert detail.json()["events"][0]["text"] == trace
append_transcript_object(
history.append(
key,
{"event": "user", "chat_id": "revalidated-thread", "text": "again"},
)
@@ -3497,15 +3499,15 @@ async def test_webui_thread_revalidates_and_loads_large_trace_details(
@pytest.mark.asyncio
async def test_webui_thread_omits_validator_when_transcript_changes_during_replay(
async def test_webui_thread_omits_validator_when_transcript_changes_during_replay(history,
bus: MagicMock, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
from nanobot.webui.transcript import append_transcript_object
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
key = "websocket:changing-thread"
sm = _seed_session(tmp_path, key=key)
append_transcript_object(
history.append(
key,
{"event": "user", "chat_id": "changing-thread", "text": "hello"},
)
@@ -83,7 +83,7 @@ def _channel() -> WebSocketChannel:
)
channel = WebSocketChannel(config, bus, gateway=gateway)
# Keep disk latency out of every connection delivery synchronization check.
channel._persist_turn_transcript_event = MagicMock(return_value=True)
channel._persist_turn_transcript_event = AsyncMock(return_value=True)
return channel
@@ -44,6 +44,7 @@ class _FakeServer:
def _channel() -> WebSocketChannel:
gateway = MagicMock()
gateway.session_manager = None
gateway.transcripts.initialize = AsyncMock()
gateway.http.settings_routes.close = AsyncMock()
gateway.http.remote_instances.close = AsyncMock()
return WebSocketChannel(
@@ -22,7 +22,6 @@ from nanobot.runtime_context import public_history_message
from nanobot.session.keys import UNIFIED_SESSION_KEY, session_key_for_channel
from nanobot.session.manager import SessionManager
from nanobot.session.webui_turns import clear_websocket_turns
from nanobot.webui.transcript import read_transcript_lines
class _Provider(LLMProvider):
@@ -155,7 +154,7 @@ async def test_failed_transport_admission_removes_new_sessions(
assert await runtime.sessions.state.list_sessions() == []
async def test_temporary_chat_retains_its_own_generation(runtime: _Runtime) -> None:
async def test_temporary_chat_retains_its_own_generation(history, runtime: _Runtime) -> None:
await runtime.channel._dispatch_envelope(
runtime.connection, "webui-client", {"type": "new_temporary_chat"},
)
@@ -166,7 +165,7 @@ async def test_temporary_chat_retains_its_own_generation(runtime: _Runtime) -> N
assert runtime.provider.calls == 1
assert runtime.loop._effective_session_key(first) == f"websocket:{chat_id}"
assert await runtime.sessions.state.list_sessions() == []
assert read_transcript_lines(f"websocket:{chat_id}") == []
assert history.read(f"websocket:{chat_id}") == []
queued = await runtime.message(chat_id, "discarded input")
await runtime.channel.gateway.temporary_chats.discard(runtime.connection, chat_id)