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:
1 parent
d617b723aa
commit
b32b1327ce
50 files changed
+2123
-3235
No files matched your search
@@ -1007,7 +1007,7 @@ class AgentLoop:
|
||||
if session is None:
|
||||
return NO_EVENTS
|
||||
return self.turn_delivery_factory.session_events(
|
||||
session_key, session.metadata,
|
||||
session_key, session.metadata, generation=session.generation,
|
||||
)
|
||||
|
||||
def _remember_session_route(
|
||||
@@ -2061,7 +2061,7 @@ class AgentLoop:
|
||||
else:
|
||||
ctx.session = await self.sessions.state.get(ctx.session_key)
|
||||
session = ctx.session
|
||||
ctx.delivery.bind_session_generation(session.generation)
|
||||
await ctx.delivery.bind_session_generation(session.generation)
|
||||
ctx.ephemeral = ctx.ephemeral or not session.policy.persist
|
||||
tools = ctx.tools if ctx.tools is not None else self.tools
|
||||
if session.policy.disabled_tools:
|
||||
@@ -2141,6 +2141,9 @@ class AgentLoop:
|
||||
ctx.turn_scopes.append(GoalInputScope(ctx.msg))
|
||||
if result is not None:
|
||||
ctx.outbound = result
|
||||
if cmd_ctx.raw.lower() == "/new":
|
||||
current = await self.sessions.state.get_header(ctx.session_key)
|
||||
await ctx.delivery.bind_session_generation(current.generation)
|
||||
# Shortcut commands skip BUILD and SAVE, so we must persist the
|
||||
# turn here so WebUI history hydration after turn_end sees the
|
||||
# message. Mark messages with _command so get_history can filter
|
||||
|
||||
@@ -4,7 +4,7 @@ from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from collections.abc import Awaitable, Callable
|
||||
from copy import deepcopy
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
@@ -29,6 +29,7 @@ from nanobot.events import (
|
||||
ResponseSourceEvent,
|
||||
)
|
||||
from nanobot.providers.base import LLMUsage
|
||||
from nanobot.session.display_history import HISTORY_GENERATION_METADATA_KEY
|
||||
from nanobot.session.keys import (
|
||||
UNIFIED_SESSION_KEY,
|
||||
is_internal_session,
|
||||
@@ -53,6 +54,7 @@ class TurnRoute:
|
||||
|
||||
|
||||
TurnRoutePolicy = Callable[[InboundMessage, str, TurnRoute], TurnRoute]
|
||||
TurnRouteAdmission = Callable[[TurnRoute, str, str], Awaitable[TurnRoute]]
|
||||
|
||||
|
||||
def _bind_events(
|
||||
@@ -94,10 +96,12 @@ class TurnDeliveryFactory:
|
||||
self,
|
||||
bus: MessageBus,
|
||||
route_policy: TurnRoutePolicy | None = None,
|
||||
route_admission: TurnRouteAdmission | None = None,
|
||||
) -> None:
|
||||
self.bus = bus
|
||||
self.runtime_event_publisher = RuntimeEventPublisher(bus)
|
||||
self.route_policy = route_policy
|
||||
self.route_admission = route_admission
|
||||
|
||||
def create(
|
||||
self,
|
||||
@@ -117,6 +121,7 @@ class TurnDeliveryFactory:
|
||||
input_message=msg,
|
||||
session_key=session_key,
|
||||
route=route,
|
||||
route_admission=self.route_admission,
|
||||
enable_stream=enable_stream,
|
||||
)
|
||||
|
||||
@@ -138,6 +143,7 @@ class TurnDeliveryFactory:
|
||||
self,
|
||||
session_key: str,
|
||||
session_metadata: dict[str, Any],
|
||||
*, generation: str,
|
||||
) -> EventSink:
|
||||
"""Bind idle notifications to one route without acquiring a turn owner."""
|
||||
if is_internal_session(session_key):
|
||||
@@ -151,7 +157,9 @@ class TurnDeliveryFactory:
|
||||
return EventSink()
|
||||
if not isinstance(metadata, dict):
|
||||
return EventSink()
|
||||
metadata = cast(dict[str, Any], metadata)
|
||||
metadata = dict(cast(dict[str, Any], metadata))
|
||||
if isinstance(saved_generation := saved_route.get("generation"), str):
|
||||
metadata[HISTORY_GENERATION_METADATA_KEY] = saved_generation
|
||||
else:
|
||||
# Older sessions have no route snapshot. Only direct clients have a
|
||||
# session key that is also an unambiguous delivery address.
|
||||
@@ -165,7 +173,8 @@ class TurnDeliveryFactory:
|
||||
channel, chat_id = route
|
||||
metadata = {}
|
||||
metadata = deepcopy(metadata)
|
||||
|
||||
if channel == "websocket":
|
||||
metadata.setdefault(HISTORY_GENERATION_METADATA_KEY, generation)
|
||||
return _bind_events(self.bus, TurnRoute(channel, chat_id, metadata), session_key)
|
||||
|
||||
@staticmethod
|
||||
@@ -196,6 +205,7 @@ class TurnDelivery:
|
||||
input_message: InboundMessage
|
||||
session_key: str
|
||||
route: TurnRoute
|
||||
route_admission: TurnRouteAdmission | None = None
|
||||
enable_stream: bool = False
|
||||
delivery_message: InboundMessage = field(init=False)
|
||||
lifecycle_message: InboundMessage = field(init=False)
|
||||
@@ -232,10 +242,26 @@ class TurnDelivery:
|
||||
def streaming(self) -> bool:
|
||||
return self._stream_base_id is not None
|
||||
|
||||
def bind_session_generation(self, generation: str) -> None:
|
||||
"""Attach the admitted session identity to all later lifecycle events."""
|
||||
async def bind_session_generation(self, generation: str) -> None:
|
||||
"""Admit the destination before publishing any durable turn facts."""
|
||||
previous = self.delivery_message.session_generation
|
||||
metadata = dict(self.route.metadata)
|
||||
stored_generation = metadata.get(HISTORY_GENERATION_METADATA_KEY)
|
||||
if self.route.channel == "websocket" and (stored_generation is None or stored_generation == previous):
|
||||
metadata[HISTORY_GENERATION_METADATA_KEY] = generation
|
||||
route = dataclasses.replace(self.route, metadata=metadata)
|
||||
if self.route_admission is not None:
|
||||
route = await self.route_admission(route, self.session_key, generation)
|
||||
self.route = route
|
||||
self.delivery_message.metadata = dict(route.metadata)
|
||||
self.delivery_message.session_generation = generation
|
||||
self.lifecycle_message.session_generation = generation
|
||||
if HISTORY_GENERATION_METADATA_KEY in route.metadata:
|
||||
for message in (self.lifecycle_message, self.input_message):
|
||||
message.metadata[HISTORY_GENERATION_METADATA_KEY] = route.metadata[
|
||||
HISTORY_GENERATION_METADATA_KEY
|
||||
]
|
||||
self._routed_events = _bind_events(self.bus, self.route, self.session_key)
|
||||
|
||||
def remember_session_route(self, session_metadata: dict[str, Any]) -> None:
|
||||
"""Keep only routing fields needed to deliver a later idle notification."""
|
||||
@@ -248,6 +274,8 @@ class TurnDelivery:
|
||||
"chat_id": self.route.chat_id,
|
||||
"metadata": notification_metadata(self.route.channel, self.route.metadata),
|
||||
}
|
||||
if generation := self.route.metadata.get(HISTORY_GENERATION_METADATA_KEY):
|
||||
session_metadata["_compaction_route"]["generation"] = generation
|
||||
|
||||
async def started(self) -> None:
|
||||
if self.route.publish_lifecycle:
|
||||
@@ -331,6 +359,9 @@ class TurnDelivery:
|
||||
if response is not None:
|
||||
completed_channel = response.channel
|
||||
completed_chat_id = response.chat_id
|
||||
generation = self.route.metadata.get(HISTORY_GENERATION_METADATA_KEY)
|
||||
if generation is not None and (response.channel, response.chat_id) == (self.route.channel, self.route.chat_id):
|
||||
response = dataclasses.replace(response, metadata={**response.metadata, HISTORY_GENERATION_METADATA_KEY: generation})
|
||||
if (
|
||||
self._response_source is not None
|
||||
and self._response_content is not None
|
||||
|
||||
@@ -1251,7 +1251,7 @@ async def test_idle_compaction_does_not_reactivate_a_completed_agent_session(tmp
|
||||
))
|
||||
activity_count = len(client.activities)
|
||||
|
||||
idle_events = factory.session_events(inbound.session_key, session_metadata)
|
||||
idle_events = factory.session_events(inbound.session_key, session_metadata, generation="generation")
|
||||
for phase in ("started", "succeeded"):
|
||||
await idle_events.emit(ContextCompactionEvent(compaction_id="idle-1", phase=phase))
|
||||
await channel.send(await channel.bus.consume_outbound())
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -83,14 +83,26 @@ async def _deliver_to_channel(
|
||||
if session_generation is not None
|
||||
else raw_generation if isinstance(raw_generation, str) else None
|
||||
)
|
||||
key = session_key or (raw_key if isinstance(raw_key, str) else None)
|
||||
if key is None:
|
||||
key = session_key_for_channel(
|
||||
msg.channel, msg.chat_id, unified_session=unified_session,
|
||||
)
|
||||
if msg.channel == "websocket":
|
||||
from nanobot.agent.turn_delivery import TurnRoute
|
||||
from nanobot.session.display_history import HISTORY_GENERATION_METADATA_KEY
|
||||
from nanobot.session.webui_turns import WebuiTurnRoutePolicy
|
||||
from nanobot.webui.session_identity import webui_session_key
|
||||
|
||||
route = await WebuiTurnRoutePolicy(session_manager).admit(
|
||||
TurnRoute(msg.channel, msg.chat_id, metadata), key, expected_generation,
|
||||
)
|
||||
metadata = route.metadata
|
||||
if key == webui_session_key(msg.chat_id):
|
||||
expected_generation = cast(str, metadata[HISTORY_GENERATION_METADATA_KEY])
|
||||
if metadata != (msg.metadata or {}):
|
||||
msg = replace(msg, metadata=metadata)
|
||||
if record and msg.channel != "cli" and msg.content.strip():
|
||||
key = session_key or (raw_key if isinstance(raw_key, str) else None)
|
||||
if key is None:
|
||||
key = session_key_for_channel(
|
||||
msg.channel, msg.chat_id, unified_session=unified_session,
|
||||
)
|
||||
if expected_generation is None:
|
||||
# Cross-target sends admit their target before recording; subsequent
|
||||
# deletion or reset must still revoke this delivery's generation.
|
||||
@@ -525,9 +537,11 @@ def _run_gateway(
|
||||
cron = CronService(cron_store_path)
|
||||
trigger_store = LocalTriggerStore(config.workspace_path)
|
||||
|
||||
webui_route_policy = WebuiTurnRoutePolicy(session_manager)
|
||||
turn_delivery_factory = TurnDeliveryFactory(
|
||||
bus,
|
||||
route_policy=WebuiTurnRoutePolicy(session_manager),
|
||||
route_policy=webui_route_policy,
|
||||
route_admission=webui_route_policy.admit,
|
||||
)
|
||||
|
||||
tools = ToolRegistry()
|
||||
|
||||
@@ -45,7 +45,7 @@ def get_logs_dir() -> Path:
|
||||
|
||||
|
||||
def get_webui_dir() -> Path:
|
||||
"""Return the directory for WebUI JSONL transcripts and legacy JSON snapshots."""
|
||||
"""Return WebUI state and legacy display-history import/backup storage."""
|
||||
return get_runtime_subdir("webui")
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
"""Durable display facts, separate from provider/model messages and transports."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sqlite3
|
||||
from collections.abc import Iterator, Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from enum import StrEnum
|
||||
from pathlib import Path
|
||||
from typing import Any, cast
|
||||
|
||||
MAX_HISTORY_FACT_BYTES = 8 * 1024 * 1024
|
||||
HISTORY_GENERATION_METADATA_KEY = "_history_generation"
|
||||
|
||||
|
||||
class HistoryKind(StrEnum):
|
||||
INPUT = "input"
|
||||
ANSWER = "answer"
|
||||
ANSWER_SEGMENT = "answer_segment"
|
||||
REASONING = "reasoning"
|
||||
REASONING_SEGMENT = "reasoning_segment"
|
||||
PROGRESS = "progress"
|
||||
TOOL_ACTIVITY = "tool_activity"
|
||||
FILE_ACTIVITY = "file_activity"
|
||||
COMPLETION = "completion"
|
||||
FORK_BOUNDARY = "fork_boundary"
|
||||
COMPACTION = "compaction"
|
||||
# Only old transcripts can contain unfinished transport fragments.
|
||||
ANSWER_FRAGMENT = "answer_fragment"
|
||||
REASONING_FRAGMENT = "reasoning_fragment"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class HistoryFact:
|
||||
kind: HistoryKind
|
||||
content: Mapping[str, Any] = field(default_factory=lambda: cast(dict[str, Any], {}))
|
||||
turn_id: str | None = None
|
||||
phase: str | None = None
|
||||
sequence: int | None = None
|
||||
created_at_ms: int = 0
|
||||
|
||||
def encode(self) -> str:
|
||||
record = json.dumps({
|
||||
"kind": self.kind.value, "content": dict(self.content),
|
||||
"turn_id": self.turn_id, "phase": self.phase,
|
||||
"sequence": self.sequence, "created_at_ms": self.created_at_ms,
|
||||
}, ensure_ascii=False, allow_nan=False, separators=(",", ":"))
|
||||
if len(record.encode("utf-8")) > MAX_HISTORY_FACT_BYTES:
|
||||
raise ValueError("history fact exceeds the 8 MiB storage limit")
|
||||
return record
|
||||
|
||||
@classmethod
|
||||
def decode(cls, record: str) -> HistoryFact:
|
||||
value = cast(dict[str, Any], json.loads(record))
|
||||
return cls(
|
||||
HistoryKind(value["kind"]), value["content"], value["turn_id"],
|
||||
value["phase"], value["sequence"], value["created_at_ms"],
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class HistoryImport:
|
||||
key: str
|
||||
facts: list[HistoryFact]
|
||||
created_at_ms: int = 0
|
||||
updated_at_ms: int = 0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class HistoryTurn:
|
||||
ordinal: int
|
||||
record_count: int
|
||||
byte_count: int
|
||||
user_count: int
|
||||
|
||||
|
||||
class HistoryReader:
|
||||
"""A single-session view valid only inside its owner's read transaction."""
|
||||
|
||||
def __init__(self, db: sqlite3.Connection, key: str, storage_path: Path) -> None:
|
||||
self._db = db
|
||||
self.key = key
|
||||
self.storage_path = storage_path
|
||||
|
||||
@property
|
||||
def revision(self) -> tuple[str, int] | None:
|
||||
row = self._db.execute(
|
||||
"""SELECT sessions.generation, coalesce(history_heads.revision, -1) FROM sessions
|
||||
LEFT JOIN history_heads ON history_heads.session_key=sessions.key WHERE sessions.key=?""",
|
||||
(self.key,),
|
||||
).fetchone()
|
||||
return (str(row[0]), int(row[1])) if row is not None else None
|
||||
|
||||
@property
|
||||
def turn_count(self) -> int:
|
||||
return int(self._db.execute(
|
||||
"SELECT coalesce(max(ordinal)+1, 0) FROM history_turns WHERE session_key=?",
|
||||
(self.key,),
|
||||
).fetchone()[0])
|
||||
|
||||
def turns(
|
||||
self, *, before: int | None = None, after: int = 0, reverse: bool = False,
|
||||
) -> Iterator[HistoryTurn]:
|
||||
upper = self.turn_count if before is None else before
|
||||
order = "DESC" if reverse else "ASC"
|
||||
for row in self._db.execute(
|
||||
f"""SELECT ordinal, record_count, byte_count, user_count FROM history_turns
|
||||
WHERE session_key=? AND ordinal>=? AND ordinal<? ORDER BY ordinal {order}""",
|
||||
(self.key, after, upper),
|
||||
):
|
||||
yield HistoryTurn(*row)
|
||||
|
||||
def read_turn(self, ordinal: int) -> list[HistoryFact]:
|
||||
return [fact for _, fact in self.read_entries(ordinal)]
|
||||
|
||||
def read_entries(
|
||||
self, ordinal: int, *, max_records: int | None = None, max_bytes: int | None = None,
|
||||
) -> list[tuple[int, HistoryFact]]:
|
||||
clause = "session_key=? AND turn_ordinal=?"
|
||||
params = (self.key, ordinal)
|
||||
selected: list[int] | None = None
|
||||
if max_records is not None and max_bytes is not None:
|
||||
# Inspect sizes/positions, not unbounded JSON bodies, before decoding
|
||||
# a pathological single turn. Preserve the first input and useful tail.
|
||||
priorities: list[tuple[int, int]] = []
|
||||
for kinds, order in (((HistoryKind.INPUT,), "ASC"),
|
||||
((HistoryKind.COMPLETION,), "DESC"),
|
||||
((HistoryKind.ANSWER, HistoryKind.ANSWER_SEGMENT, HistoryKind.ANSWER_FRAGMENT), "DESC")):
|
||||
row = self._db.execute(
|
||||
f"SELECT position, length(CAST(record AS BLOB)) FROM history_entries WHERE {clause} "
|
||||
f"AND kind IN ({','.join('?' for _ in kinds)}) ORDER BY position {order} LIMIT 1",
|
||||
(*params, *kinds),
|
||||
).fetchone()
|
||||
if row is not None:
|
||||
priorities.append((row[0], row[1]))
|
||||
candidates = self._db.execute(
|
||||
f"SELECT position, length(CAST(record AS BLOB)) FROM history_entries WHERE {clause} ORDER BY position DESC LIMIT ?",
|
||||
(*params, max_records),
|
||||
)
|
||||
positions: set[int] = set()
|
||||
used = 0
|
||||
for position, size in (*priorities, *candidates):
|
||||
if position not in positions and len(positions) < max_records and used + size <= max_bytes:
|
||||
positions.add(position)
|
||||
used += size
|
||||
selected = sorted(positions)
|
||||
if not selected:
|
||||
return []
|
||||
clause += f" AND position IN ({','.join('?' for _ in selected)})"
|
||||
return [(row[0], HistoryFact.decode(row[1])) for row in self._db.execute(
|
||||
f"SELECT position, record FROM history_entries WHERE {clause} ORDER BY position",
|
||||
(*params, *(selected or [])),
|
||||
)]
|
||||
|
||||
def user_count_before(self, ordinal: int) -> int:
|
||||
return int(self._db.execute(
|
||||
"SELECT coalesce(sum(user_count), 0) FROM history_turns WHERE session_key=? AND ordinal<?",
|
||||
(self.key, ordinal),
|
||||
).fetchone()[0])
|
||||
|
||||
def navigation(self) -> Iterator[tuple[int, int, HistoryFact]]:
|
||||
"""Read input/answer records only, never file diffs or tool result bodies."""
|
||||
kinds = (HistoryKind.INPUT, HistoryKind.ANSWER, HistoryKind.ANSWER_SEGMENT,
|
||||
HistoryKind.ANSWER_FRAGMENT, HistoryKind.COMPLETION)
|
||||
for row in self._db.execute(
|
||||
"""SELECT turn_ordinal, position, record FROM history_entries
|
||||
WHERE session_key=? AND kind IN (?, ?, ?, ?, ?) ORDER BY turn_ordinal, position""",
|
||||
(self.key, *kinds),
|
||||
):
|
||||
yield int(row[0]), int(row[1]), HistoryFact.decode(row[2])
|
||||
|
||||
def all_facts(self) -> list[HistoryFact]:
|
||||
return [HistoryFact.decode(row[0]) for row in self._db.execute(
|
||||
"SELECT record FROM history_entries WHERE session_key=? ORDER BY turn_ordinal, position",
|
||||
(self.key,),
|
||||
)]
|
||||
@@ -8,7 +8,7 @@ from copy import deepcopy
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, Callable, TypedDict, cast
|
||||
from typing import TYPE_CHECKING, Any, Callable, TypedDict, TypeVar, cast
|
||||
from uuid import uuid4
|
||||
|
||||
from nanobot.providers.base import ProviderConversationState
|
||||
@@ -16,6 +16,7 @@ from nanobot.runtime_context import (
|
||||
RUNTIME_CONTEXT_HISTORY_META,
|
||||
public_history_message,
|
||||
)
|
||||
from nanobot.session.display_history import HistoryFact, HistoryReader
|
||||
from nanobot.session.history_visibility import HIDDEN_HISTORY_META, is_hidden_history_message
|
||||
from nanobot.session.location import SessionLocation
|
||||
from nanobot.session.model_selection import SESSION_MODEL_PRESET_METADATA_KEY
|
||||
@@ -33,6 +34,7 @@ from nanobot.utils.subagent_channel_display import scrub_subagent_announce_body
|
||||
if TYPE_CHECKING:
|
||||
from nanobot.session.state import SessionState
|
||||
|
||||
_T = TypeVar("_T")
|
||||
SESSION_CACHE_MAX_SIZE = 128
|
||||
_MESSAGE_TIME_PREFIX_RE = re.compile(r"^\[Message Time: [^\]]+\]\n?")
|
||||
_LOCAL_IMAGE_BREADCRUMB_RE = re.compile(r"^\[image: (?:/|~)[^\]]+\]\s*$")
|
||||
@@ -585,10 +587,27 @@ class SessionManager:
|
||||
target = fork_session(source, target_key, before_user_index)
|
||||
if target is not None:
|
||||
self._store.save(target)
|
||||
self._store.copy_history_prefix(source_key, target, before_user_index)
|
||||
return target
|
||||
|
||||
return self._store.run_write(fork)
|
||||
|
||||
def project_history(self, key: str, project: Callable[[HistoryReader], _T]) -> _T:
|
||||
"""Read an administrative display snapshot; runtime uses state.project_history."""
|
||||
return self._store.project_history(key, project)
|
||||
|
||||
def append_history(self, key: str, facts: list[HistoryFact]) -> None:
|
||||
"""Append offline fixture/import facts with the current admitted generation."""
|
||||
self._require_offline_mutation()
|
||||
|
||||
def append() -> None:
|
||||
session = self._store.load(key, history=False)
|
||||
if session is None:
|
||||
session = self.get_or_create(key)
|
||||
self._store.save(session)
|
||||
self._store.append_history(key, facts, expected_generation=session.generation)
|
||||
self._store.run_write(append)
|
||||
|
||||
def read_session_file(self, key: str) -> dict[str, Any] | None:
|
||||
"""Read a session without populating the cache."""
|
||||
return cast(dict[str, Any] | None, self._store.read(key))
|
||||
|
||||
@@ -13,6 +13,7 @@ from pathlib import Path
|
||||
from typing import Any, TypeVar, cast
|
||||
|
||||
from nanobot.providers.base import ProviderConversationState
|
||||
from nanobot.session.display_history import HistoryFact, HistoryImport, HistoryKind, HistoryReader
|
||||
from nanobot.session.history_visibility import is_hidden_history_message
|
||||
from nanobot.session.manager import (
|
||||
Session,
|
||||
@@ -69,8 +70,36 @@ def _create_schema_v1(db: sqlite3.Connection) -> None:
|
||||
db.execute(statement)
|
||||
|
||||
|
||||
def _create_schema_v2(db: sqlite3.Connection) -> None:
|
||||
for statement in (
|
||||
"""CREATE TABLE history_heads (
|
||||
session_key TEXT PRIMARY KEY REFERENCES sessions(key) ON DELETE CASCADE,
|
||||
revision INTEGER NOT NULL DEFAULT 0,
|
||||
updated_at_ms INTEGER NOT NULL DEFAULT 0,
|
||||
preview TEXT NOT NULL DEFAULT '', user_preview TEXT NOT NULL DEFAULT ''
|
||||
)""",
|
||||
"""CREATE TABLE history_turns (
|
||||
session_key TEXT NOT NULL REFERENCES sessions(key) ON DELETE CASCADE,
|
||||
ordinal INTEGER NOT NULL, record_count INTEGER NOT NULL,
|
||||
byte_count INTEGER NOT NULL, user_count INTEGER NOT NULL,
|
||||
completed INTEGER NOT NULL,
|
||||
PRIMARY KEY (session_key, ordinal)
|
||||
)""",
|
||||
"""CREATE TABLE history_entries (
|
||||
session_key TEXT NOT NULL, turn_ordinal INTEGER NOT NULL,
|
||||
position INTEGER NOT NULL, kind TEXT NOT NULL, record TEXT NOT NULL,
|
||||
PRIMARY KEY (session_key, turn_ordinal, position),
|
||||
FOREIGN KEY (session_key, turn_ordinal)
|
||||
REFERENCES history_turns(session_key, ordinal) ON DELETE CASCADE
|
||||
)""",
|
||||
):
|
||||
db.execute(statement)
|
||||
|
||||
|
||||
# Entries upgrade version N to N+1. Preserve released entries and append upgrades.
|
||||
_SCHEMA_MIGRATIONS: tuple[Callable[[sqlite3.Connection], None], ...] = (_create_schema_v1,)
|
||||
_SCHEMA_MIGRATIONS: tuple[Callable[[sqlite3.Connection], None], ...] = (
|
||||
_create_schema_v1, _create_schema_v2,
|
||||
)
|
||||
|
||||
|
||||
def _schema_version(db: sqlite3.Connection) -> int:
|
||||
@@ -391,6 +420,110 @@ class SqliteSessionStore:
|
||||
"updated_at": session.updated_at.isoformat(),
|
||||
"metadata": session.metadata, "messages": session.messages}
|
||||
|
||||
def migrate_history(
|
||||
self, name: str, collect: Callable[[list[SessionInfo]], list[HistoryImport]],
|
||||
) -> None:
|
||||
"""Commit a channel-owned legacy import and its once-only marker together."""
|
||||
with self.transaction() as db:
|
||||
marker = db.execute("SELECT value FROM storage_meta WHERE key=?", (name,)).fetchone()
|
||||
if marker is not None:
|
||||
if marker[0] != "complete":
|
||||
raise RuntimeError(f"invalid history import marker: {name}")
|
||||
return
|
||||
for item in collect(self.list_sessions()):
|
||||
session = self.load(item.key, history=False)
|
||||
if session is None:
|
||||
session = Session(key=item.key)
|
||||
if item.created_at_ms:
|
||||
session.created_at = datetime.fromtimestamp(item.created_at_ms / 1000)
|
||||
if item.updated_at_ms:
|
||||
session.updated_at = datetime.fromtimestamp(item.updated_at_ms / 1000)
|
||||
self.save(session)
|
||||
revision = self.project_history(item.key, lambda reader: reader.revision)
|
||||
if revision is not None and revision[1] >= 0:
|
||||
raise SessionConflictError(f"history already exists before import: {item.key}")
|
||||
self.append_history(item.key, item.facts, expected_generation=session.generation)
|
||||
db.execute("UPDATE history_heads SET updated_at_ms=max(updated_at_ms, ?) WHERE session_key=?",
|
||||
(item.updated_at_ms, item.key))
|
||||
# Import ownership survives deletion: another namespace must not
|
||||
# mistake this instance-wide backup for a new orphan later.
|
||||
db.execute("INSERT INTO storage_meta (key, value) VALUES (?, 'complete')", (f"{name}:{item.key}",))
|
||||
db.execute("INSERT INTO storage_meta (key, value) VALUES (?, 'complete')", (name,))
|
||||
|
||||
def project_history(self, key: str, project: Callable[[HistoryReader], _T]) -> _T:
|
||||
"""Project durable display facts and canonical messages from one snapshot."""
|
||||
with self.transaction(write=False) as db:
|
||||
return project(HistoryReader(db, key, self.path))
|
||||
|
||||
def append_history(
|
||||
self, key: str, facts: list[HistoryFact], *, expected_generation: str,
|
||||
) -> None:
|
||||
encoded = [(fact, fact.encode()) for fact in facts]
|
||||
with self.transaction() as db:
|
||||
row = db.execute("SELECT generation FROM sessions WHERE key=?", (key,)).fetchone()
|
||||
if row is None or row[0] != expected_generation:
|
||||
raise SessionConflictError("history belongs to a deleted or replaced session")
|
||||
db.execute("INSERT OR IGNORE INTO history_heads (session_key) VALUES (?)", (key,))
|
||||
tail = db.execute(
|
||||
"SELECT ordinal, record_count, completed FROM history_turns WHERE session_key=? ORDER BY ordinal DESC LIMIT 1",
|
||||
(key,),
|
||||
).fetchone()
|
||||
ordinal, position = (int(tail[0]), int(tail[1])) if tail is not None else (0, 0)
|
||||
completed = tail is not None and bool(tail[2])
|
||||
for fact, record in encoded:
|
||||
if completed:
|
||||
ordinal, position = ordinal + 1, 0
|
||||
if position == 0:
|
||||
db.execute(
|
||||
"INSERT INTO history_turns VALUES (?, ?, 0, 0, 0, 0)", (key, ordinal),
|
||||
)
|
||||
db.execute("INSERT INTO history_entries VALUES (?, ?, ?, ?, ?)", (
|
||||
key, ordinal, position, fact.kind.value, record,
|
||||
))
|
||||
completed = fact.kind is HistoryKind.COMPLETION
|
||||
db.execute(
|
||||
"""UPDATE history_turns SET record_count=record_count+1, byte_count=byte_count+?,
|
||||
user_count=user_count+?, completed=? WHERE session_key=? AND ordinal=?""",
|
||||
(len(record.encode("utf-8")), int(fact.kind is HistoryKind.INPUT),
|
||||
int(completed), key, ordinal),
|
||||
)
|
||||
position += 1
|
||||
if fact.kind in {HistoryKind.INPUT, HistoryKind.ANSWER, HistoryKind.ANSWER_SEGMENT}:
|
||||
preview = message_preview_text({"content": fact.content.get("text", "")})
|
||||
if preview:
|
||||
field = "user_preview" if fact.kind is HistoryKind.INPUT else "preview"
|
||||
db.execute(f"UPDATE history_heads SET {field}=? WHERE session_key=? AND {field}=''", (preview, key))
|
||||
db.execute("UPDATE history_heads SET updated_at_ms=max(updated_at_ms, ?) WHERE session_key=?",
|
||||
(fact.created_at_ms, key))
|
||||
if encoded:
|
||||
db.execute("UPDATE history_heads SET revision=revision+1 WHERE session_key=?", (key,))
|
||||
|
||||
def copy_history_prefix(self, source_key: str, target: Session, before_input: int) -> bool:
|
||||
"""Copy a display prefix alongside its canonical fork, in the caller's transaction."""
|
||||
def select(reader: HistoryReader) -> list[HistoryFact] | None:
|
||||
revision = reader.revision
|
||||
if revision is None or revision[1] < 0:
|
||||
return None
|
||||
copied: list[HistoryFact] = []
|
||||
inputs = 0
|
||||
for fact in reader.all_facts():
|
||||
if fact.kind is HistoryKind.FORK_BOUNDARY:
|
||||
continue
|
||||
if fact.kind is HistoryKind.INPUT:
|
||||
if inputs == before_input:
|
||||
return copied
|
||||
inputs += 1
|
||||
copied.append(fact)
|
||||
return copied if inputs == before_input else None
|
||||
|
||||
facts = self.project_history(source_key, select)
|
||||
if facts is None:
|
||||
return False
|
||||
facts.append(HistoryFact(HistoryKind.FORK_BOUNDARY, created_at_ms=int(target.created_at.timestamp() * 1000)))
|
||||
self.append_history(target.key, facts, expected_generation=target.generation)
|
||||
return True
|
||||
|
||||
|
||||
def delete(self, key: str) -> bool:
|
||||
with self.transaction() as db:
|
||||
return db.execute("DELETE FROM sessions WHERE key=?", (key,)).rowcount > 0
|
||||
@@ -433,10 +566,13 @@ class SqliteSessionStore:
|
||||
SELECT json_group_array(json_object(
|
||||
'key', key, 'created_at', created_at, 'updated_at', updated_at,
|
||||
'title', title, 'preview', preview, 'visible_updated_at', visible_updated_at,
|
||||
'metadata', metadata
|
||||
'metadata', metadata, 'history_updated_at_ms', history_updated_at_ms,
|
||||
'history_preview', history_preview
|
||||
)) FROM (
|
||||
SELECT key, created_at, updated_at, title, preview, visible_updated_at, metadata
|
||||
FROM sessions ORDER BY updated_at DESC
|
||||
SELECT sessions.*, coalesce(history_heads.updated_at_ms, 0) AS history_updated_at_ms,
|
||||
coalesce(nullif(history_heads.user_preview, ''), history_heads.preview, '') AS history_preview
|
||||
FROM sessions LEFT JOIN history_heads ON history_heads.session_key=sessions.key
|
||||
ORDER BY sessions.updated_at DESC
|
||||
)
|
||||
""").fetchone()[0]
|
||||
# The SQL projection constructs this list and its dictionary fields.
|
||||
|
||||
@@ -14,8 +14,15 @@ from datetime import datetime
|
||||
from typing import Any, TypeVar, cast
|
||||
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.session.display_history import HistoryFact, HistoryImport, HistoryKind, HistoryReader
|
||||
from nanobot.session.keys import is_dream_session
|
||||
from nanobot.session.manager import Session, SessionIdentity, SessionPolicy, fork_session
|
||||
from nanobot.session.manager import (
|
||||
Session,
|
||||
SessionIdentity,
|
||||
SessionInfo,
|
||||
SessionPolicy,
|
||||
fork_session,
|
||||
)
|
||||
from nanobot.session.model_selection import SESSION_MODEL_PRESET_METADATA_KEY
|
||||
from nanobot.session.sqlite_store import SessionConflictError, SqliteSessionStore
|
||||
from nanobot.session.types import PARENT_SESSION_KEY, SessionTypes
|
||||
@@ -692,6 +699,31 @@ class SessionState:
|
||||
metadata = {**baseline.metadata, _CHECKPOINT_KEY: committed.metadata[_CHECKPOINT_KEY]}
|
||||
draft._baseline = replace(baseline, metadata=metadata, provider_state=committed.provider_state) # pyright: ignore[reportPrivateUsage]
|
||||
|
||||
async def migrate_history(
|
||||
self, name: str, collect: Callable[[list[SessionInfo]], list[HistoryImport]],
|
||||
) -> None:
|
||||
await self._execute(
|
||||
None, lambda: self._store.migrate_history(name, collect), operation_name="migrate_history",
|
||||
)
|
||||
|
||||
async def project_history(
|
||||
self, key: str, project: Callable[[HistoryReader], _T],
|
||||
) -> _T:
|
||||
return await self._execute(
|
||||
key, lambda: self._store.project_history(key, project),
|
||||
operation_name="project_history", write=False,
|
||||
)
|
||||
|
||||
async def append_history(
|
||||
self, key: str, facts: Sequence[HistoryFact], *, expected_generation: str,
|
||||
) -> None:
|
||||
records = list(facts)
|
||||
await self._execute(
|
||||
key,
|
||||
lambda: self._store.append_history(key, deepcopy(records), expected_generation=expected_generation),
|
||||
operation_name="append_history",
|
||||
)
|
||||
|
||||
async def record_delivery(
|
||||
self,
|
||||
key: str,
|
||||
@@ -933,6 +965,7 @@ class SessionState:
|
||||
async def fork(
|
||||
self, source_key: str, target_key: str, before_user_index: int,
|
||||
*, title: str | None = None,
|
||||
history_projection: Callable[[Session], list[HistoryFact]] | None = None,
|
||||
) -> Session | None:
|
||||
def commit() -> Session | None:
|
||||
def write() -> Session | None:
|
||||
@@ -945,6 +978,11 @@ class SessionState:
|
||||
if title:
|
||||
target.metadata["title"] = title
|
||||
self._commit(target)
|
||||
copied = self._store.copy_history_prefix(source_key, target, before_user_index)
|
||||
if not copied and history_projection is not None:
|
||||
facts = history_projection(target)
|
||||
facts.append(HistoryFact(HistoryKind.FORK_BOUNDARY, created_at_ms=int(target.created_at.timestamp() * 1000)))
|
||||
self._store.append_history(target.key, facts, expected_generation=target.generation)
|
||||
return target
|
||||
|
||||
target = self._store.run_write(write)
|
||||
|
||||
@@ -41,6 +41,7 @@ from nanobot.llm_usage.context import llm_usage_source
|
||||
from nanobot.providers.base import LLMProvider, LLMUsage
|
||||
from nanobot.providers.fallback_provider import FallbackModelObserver, FallbackModelSelection
|
||||
from nanobot.runtime_context import public_history_message
|
||||
from nanobot.session.display_history import HISTORY_GENERATION_METADATA_KEY
|
||||
from nanobot.session.goal_state import goal_state_ws_blob
|
||||
from nanobot.session.history_visibility import is_hidden_history_message
|
||||
from nanobot.session.manager import Session, SessionManager
|
||||
@@ -531,6 +532,25 @@ class WebuiTurnRoutePolicy:
|
||||
|
||||
return routed
|
||||
|
||||
async def admit(self, route: TurnRoute, session_key: str, generation: str | None) -> TurnRoute:
|
||||
"""Bind replies to the display destination's admitted lifetime."""
|
||||
if route.channel != "websocket":
|
||||
return route
|
||||
target_key = webui_session_key(route.chat_id)
|
||||
metadata = dict(route.metadata)
|
||||
if target_key == session_key and generation is not None:
|
||||
metadata.setdefault(HISTORY_GENERATION_METADATA_KEY, generation)
|
||||
return replace(route, metadata=metadata)
|
||||
revision = await self.sessions.state.project_history(target_key, lambda history: history.revision)
|
||||
if revision is None:
|
||||
raise SessionConflictError("display destination is no longer active")
|
||||
admitted = metadata.get(HISTORY_GENERATION_METADATA_KEY)
|
||||
# A distinct alias admitted by the WebSocket edge must still be current.
|
||||
if admitted not in (None, generation, revision[0]):
|
||||
raise SessionConflictError("display destination generation was replaced")
|
||||
metadata[HISTORY_GENERATION_METADATA_KEY] = revision[0]
|
||||
return replace(route, metadata=metadata)
|
||||
|
||||
|
||||
def build_webui_fallback_model_observer(bus: MessageBus) -> FallbackModelObserver:
|
||||
"""Translate provider fallback choices into chat-scoped WebUI events."""
|
||||
@@ -630,6 +650,7 @@ class WebuiTurnCoordinator:
|
||||
content="",
|
||||
metadata=dict(ctx.metadata or {}),
|
||||
session_key_override=ctx.session_key,
|
||||
session_generation=ctx.session_generation,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
@@ -657,8 +678,11 @@ class WebuiTurnCoordinator:
|
||||
return
|
||||
public_metadata = _session_message_public_metadata(envelope)
|
||||
try:
|
||||
append_session_message_input(
|
||||
assert event.context.session_generation is not None
|
||||
await append_session_message_input(
|
||||
session_key,
|
||||
sessions=self.sessions,
|
||||
expected_generation=event.context.session_generation,
|
||||
content=event.content,
|
||||
created_at_ms=envelope["created_at_ms"],
|
||||
session_message=public_metadata,
|
||||
|
||||
@@ -30,7 +30,6 @@ class _LazyModuleAlias(ModuleType):
|
||||
|
||||
|
||||
_LEGACY_MODULE_ALIASES = {
|
||||
"webui_thread_disk": "nanobot.webui.thread_disk",
|
||||
"webui_transcript": "nanobot.webui.transcript",
|
||||
"webui_turn_helpers": "nanobot.session.webui_turns",
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import uuid
|
||||
from collections.abc import Mapping
|
||||
from typing import TYPE_CHECKING, Any, Protocol
|
||||
@@ -12,12 +11,7 @@ from loguru import logger
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.webui_turns import clean_generated_title
|
||||
from nanobot.webui.session_identity import is_valid_webui_chat_id, webui_session_key
|
||||
from nanobot.webui.transcript import (
|
||||
append_fork_marker,
|
||||
delete_webui_transcript,
|
||||
fork_transcript_before_user_index,
|
||||
write_session_messages_as_transcript,
|
||||
)
|
||||
from nanobot.webui.transcript import session_display_facts
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from websockets.asyncio.server import ServerConnection
|
||||
@@ -54,28 +48,12 @@ async def create_webui_chat_fork(
|
||||
new_id = str(uuid.uuid4())
|
||||
source_key = webui_session_key(source_chat_id)
|
||||
target_key = webui_session_key(new_id)
|
||||
try:
|
||||
forked = await session_manager.state.fork(
|
||||
source_key,
|
||||
target_key,
|
||||
before_user_index,
|
||||
title=clean_generated_title(title),
|
||||
)
|
||||
if forked is None:
|
||||
return None
|
||||
|
||||
def write_transcript() -> None:
|
||||
transcript_ok = fork_transcript_before_user_index(
|
||||
source_key, target_key, before_user_index,
|
||||
)
|
||||
if not transcript_ok:
|
||||
write_session_messages_as_transcript(target_key, forked.messages)
|
||||
append_fork_marker(target_key)
|
||||
await asyncio.to_thread(write_transcript)
|
||||
except Exception:
|
||||
await asyncio.to_thread(delete_webui_transcript, target_key)
|
||||
await session_manager.state.delete(target_key)
|
||||
raise
|
||||
forked = await session_manager.state.fork(
|
||||
source_key, target_key, before_user_index,
|
||||
title=clean_generated_title(title), history_projection=session_display_facts,
|
||||
)
|
||||
if forked is None:
|
||||
return None
|
||||
return new_id, target_key
|
||||
|
||||
|
||||
|
||||
@@ -112,7 +112,7 @@ def build_gateway_services(
|
||||
uploads = AttachmentHTTP(AttachmentStore(
|
||||
get_media_dir("websocket"), limits=ingress.attachments,
|
||||
))
|
||||
transcripts = WebUITranscriptRecorder(log=logger)
|
||||
transcripts = WebUITranscriptRecorder(session_manager, log=logger)
|
||||
workspaces = WebUIWorkspaceController(
|
||||
session_manager=session_manager,
|
||||
default_workspace=workspace_path,
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
"""WebUI projection of durable session facts and strict legacy transcript import."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import sqlite3
|
||||
from collections.abc import Mapping, Sequence
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
from typing import Any, cast
|
||||
|
||||
from nanobot.config.paths import get_webui_dir
|
||||
from nanobot.session.display_history import HistoryFact, HistoryImport, HistoryKind, HistoryReader
|
||||
from nanobot.session.manager import SessionInfo, SessionManager
|
||||
from nanobot.webui.session_identity import is_valid_webui_chat_id, webui_chat_id, webui_session_key
|
||||
|
||||
HISTORY_IMPORT_MARKER = "webui_history_import_v1"
|
||||
_SEGMENT_NAME = re.compile(r"^\d{6}\.jsonl$")
|
||||
_EVENTS = {
|
||||
"user": HistoryKind.INPUT,
|
||||
"message": HistoryKind.ANSWER,
|
||||
"stream_end": HistoryKind.ANSWER_SEGMENT,
|
||||
"reasoning_end": HistoryKind.REASONING_SEGMENT,
|
||||
"file_edit": HistoryKind.FILE_ACTIVITY,
|
||||
"turn_end": HistoryKind.COMPLETION,
|
||||
"fork_marker": HistoryKind.FORK_BOUNDARY,
|
||||
"context_compaction": HistoryKind.COMPACTION,
|
||||
"delta": HistoryKind.ANSWER_FRAGMENT,
|
||||
"reasoning_delta": HistoryKind.REASONING_FRAGMENT,
|
||||
}
|
||||
_MESSAGE_KINDS = {
|
||||
"reasoning": HistoryKind.REASONING,
|
||||
"progress": HistoryKind.PROGRESS,
|
||||
"tool_hint": HistoryKind.TOOL_ACTIVITY,
|
||||
}
|
||||
_CONTENT_FIELDS = frozenset({
|
||||
"text", "media_paths", "media", "media_urls", "reply_to", "agent_ui", "cli_apps", "mcp_presets", "session_mentions",
|
||||
"session_message", "tool_events", "edits", "source", "response_sources", "resuming",
|
||||
"merge_next", "latency_ms", "usage", "round_usages", "context_window_tokens", "goal_state",
|
||||
"outcome", "failure_kind", "failure_error_kind", "failure_attempts", "failure_message",
|
||||
"transcript_incomplete", "stream_id", "compaction_id", "phase",
|
||||
})
|
||||
|
||||
|
||||
def fact_from_record(record: Mapping[str, Any]) -> HistoryFact:
|
||||
"""Parse the channel boundary once; core storage never sees event/chat_id keys."""
|
||||
event = record.get("event")
|
||||
if event is None and record.get("role") in {"user", "assistant"}:
|
||||
event = "user" if record["role"] == "user" else "message"
|
||||
record = {**record, "text": record.get("text", record.get("content", ""))}
|
||||
if event not in _EVENTS:
|
||||
raise ValueError(f"unsupported legacy history event: {event!r}")
|
||||
kind = _EVENTS[event]
|
||||
if event == "message":
|
||||
message_kind = record.get("kind")
|
||||
if message_kind is not None and message_kind not in _MESSAGE_KINDS:
|
||||
raise ValueError(f"unsupported history message kind: {message_kind!r}")
|
||||
if isinstance(message_kind, str):
|
||||
kind = _MESSAGE_KINDS[message_kind]
|
||||
created = record.get("created_at_ms", 0)
|
||||
if isinstance(created, bool) or not isinstance(created, int | float) or not 0 <= created < 10**16:
|
||||
raise ValueError("invalid history timestamp")
|
||||
sequence = record.get("turn_seq")
|
||||
if sequence is not None and (isinstance(sequence, bool) or not isinstance(sequence, int) or sequence < 0):
|
||||
raise ValueError("invalid history sequence")
|
||||
turn_id, phase = record.get("turn_id"), record.get("turn_phase")
|
||||
if turn_id is not None and (not isinstance(turn_id, str) or len(turn_id) > 128):
|
||||
raise ValueError("invalid history turn identity")
|
||||
if phase is not None and not isinstance(phase, str):
|
||||
raise ValueError("invalid history phase")
|
||||
fact = HistoryFact(kind, {key: value for key, value in record.items() if key in _CONTENT_FIELDS},
|
||||
turn_id, phase, sequence, int(created))
|
||||
return fact
|
||||
|
||||
|
||||
def record_from_fact(fact: HistoryFact, key: str) -> dict[str, Any]:
|
||||
if fact.kind in _MESSAGE_KINDS.values():
|
||||
event = "message"
|
||||
message_kind = next(name for name, kind in _MESSAGE_KINDS.items() if kind is fact.kind)
|
||||
else:
|
||||
event = next(name for name, kind in _EVENTS.items() if kind is fact.kind)
|
||||
message_kind = None
|
||||
record = {"event": event, "chat_id": webui_chat_id(key), **fact.content,
|
||||
"created_at_ms": fact.created_at_ms}
|
||||
if message_kind:
|
||||
record["kind"] = message_kind
|
||||
if fact.turn_id is not None:
|
||||
record["turn_id"] = fact.turn_id
|
||||
if fact.phase is not None:
|
||||
record["turn_phase"] = fact.phase
|
||||
if fact.sequence is not None:
|
||||
record["turn_seq"] = fact.sequence
|
||||
return record
|
||||
|
||||
|
||||
def turn_records(
|
||||
history: HistoryReader, ordinal: int, *, max_records: int | None = None, max_bytes: int | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
return [{**record_from_fact(fact, history.key),
|
||||
"_webui_replay_identity": f"turn:{ordinal}:record:{position}"}
|
||||
for position, fact in history.read_entries(ordinal, max_records=max_records, max_bytes=max_bytes)]
|
||||
|
||||
|
||||
def _read_legacy_file(path: Path) -> list[dict[str, Any]]:
|
||||
if path.is_symlink() or not path.is_file():
|
||||
raise ValueError(f"legacy history must be a regular, non-symlink file: {path}")
|
||||
before = path.stat()
|
||||
records: list[dict[str, Any]] = []
|
||||
with path.open(encoding="utf-8") as handle:
|
||||
for line_number, line in enumerate(handle, 1):
|
||||
if not line.strip():
|
||||
continue
|
||||
try:
|
||||
value: object = json.loads(line)
|
||||
if not isinstance(value, dict):
|
||||
raise ValueError("record is not an object")
|
||||
record = cast(dict[str, Any], value)
|
||||
fact_from_record(record).encode()
|
||||
except (ValueError, TypeError) as exc:
|
||||
raise ValueError(f"cannot import history {path}:{line_number}: {exc}") from exc
|
||||
records.append(record)
|
||||
after = path.stat()
|
||||
if (before.st_ino, before.st_size, before.st_mtime_ns) != (after.st_ino, after.st_size, after.st_mtime_ns):
|
||||
raise ValueError(f"legacy history changed during import: {path}")
|
||||
return records
|
||||
|
||||
|
||||
def collect_legacy_history(
|
||||
sessions: Sequence[SessionInfo], *, directory: Path | None = None,
|
||||
namespace: Path | None = None,
|
||||
) -> list[HistoryImport]:
|
||||
"""Resolve recorded identities; a lossy filename alone cannot identify an orphan."""
|
||||
from nanobot.webui.transcript import compact_legacy_records
|
||||
|
||||
directory = directory if directory is not None else get_webui_dir()
|
||||
if directory.is_symlink():
|
||||
raise ValueError(f"legacy history directory must not be a symlink: {directory}")
|
||||
if not directory.exists():
|
||||
return []
|
||||
groups: dict[str, list[Path]] = {}
|
||||
for path in sorted(directory.iterdir()):
|
||||
if path.name.endswith(".segments"):
|
||||
if path.is_symlink() or not path.is_dir():
|
||||
raise ValueError(f"invalid legacy history segments directory: {path}")
|
||||
groups.setdefault(path.name[:-len(".segments")], []).extend(
|
||||
item for item in sorted(path.iterdir()) if _SEGMENT_NAME.fullmatch(item.name)
|
||||
)
|
||||
elif path.suffix == ".jsonl":
|
||||
groups.setdefault(path.stem, [])
|
||||
for stem, paths in groups.items():
|
||||
active = directory / f"{stem}.jsonl"
|
||||
if active.exists() or active.is_symlink():
|
||||
paths.append(active)
|
||||
keys_by_stem: dict[str, set[str]] = {}
|
||||
for session in sessions:
|
||||
keys_by_stem.setdefault(SessionManager.safe_key(session["key"]), set()).add(session["key"])
|
||||
foreign_owners: dict[str, list[Path]] = {}
|
||||
if namespace is not None and groups:
|
||||
for database in namespace.parent.glob("*/sessions.sqlite3"):
|
||||
if database.parent == namespace:
|
||||
continue
|
||||
if database.is_symlink() or database.parent.is_symlink():
|
||||
raise ValueError(f"invalid session namespace for history migration: {database}")
|
||||
with closing(sqlite3.connect(database.as_uri() + "?mode=ro", uri=True)) as db:
|
||||
owned = {str(row[0]) for row in db.execute("SELECT key FROM sessions")}
|
||||
prefix = f"{HISTORY_IMPORT_MARKER}:"
|
||||
owned.update(str(row[0])[len(prefix):] for row in db.execute(
|
||||
"SELECT key FROM storage_meta WHERE key LIKE ? AND value='complete'",
|
||||
(prefix + "%",),
|
||||
))
|
||||
for key in owned:
|
||||
foreign_owners.setdefault(key, []).append(database)
|
||||
imports: list[HistoryImport] = []
|
||||
for stem, paths in groups.items():
|
||||
records = [record for path in paths for record in _read_legacy_file(path)]
|
||||
if not records:
|
||||
continue
|
||||
recorded_keys: set[str] = set()
|
||||
for record in records:
|
||||
chat_id = record.get("chat_id")
|
||||
if chat_id is not None:
|
||||
if not is_valid_webui_chat_id(chat_id):
|
||||
raise ValueError(f"invalid recorded chat identity in legacy history: {stem}")
|
||||
recorded_keys.add(webui_session_key(chat_id))
|
||||
candidates = recorded_keys or keys_by_stem.get(stem, set())
|
||||
if len(candidates) != 1:
|
||||
raise ValueError(f"ambiguous legacy history identity: {stem}; expected one recorded chat or canonical session")
|
||||
key = next(iter(candidates))
|
||||
if SessionManager.safe_key(key) != stem:
|
||||
raise ValueError(f"legacy history filename conflicts with its recorded identity: {stem}")
|
||||
if key in foreign_owners:
|
||||
if key not in keys_by_stem.get(stem, set()) and len(foreign_owners[key]) == 1:
|
||||
# This instance-wide backup belongs to another workspace. Its
|
||||
# owner will import it when that namespace starts.
|
||||
continue
|
||||
raise ValueError(
|
||||
f"cannot select a SQLite owner for legacy history {key}: also present in "
|
||||
f"{foreign_owners[key]}; resolve the duplicate explicitly before restarting"
|
||||
)
|
||||
facts = [fact_from_record(record) for record in compact_legacy_records(records)]
|
||||
times = [fact.created_at_ms for fact in facts if fact.created_at_ms]
|
||||
file_times = [int(path.stat().st_mtime * 1000) for path in paths]
|
||||
imports.append(HistoryImport(key, facts, min(times or file_times), max(times or file_times)))
|
||||
return imports
|
||||
|
||||
|
||||
async def initialize_history(sessions: SessionManager) -> None:
|
||||
"""Finish the once-only import before recovery or transport admission."""
|
||||
await sessions.state.migrate_history(
|
||||
HISTORY_IMPORT_MARKER,
|
||||
lambda rows: collect_legacy_history(rows, namespace=sessions.sessions_dir),
|
||||
)
|
||||
@@ -28,6 +28,7 @@ from nanobot.security.workspace_access import (
|
||||
WORKSPACE_SCOPE_METADATA_KEY,
|
||||
WorkspaceScopeError,
|
||||
)
|
||||
from nanobot.session.display_history import HISTORY_GENERATION_METADATA_KEY
|
||||
from nanobot.session.keys import session_key_for_channel
|
||||
from nanobot.session.webui_turns import (
|
||||
clear_websocket_turn_if_current,
|
||||
@@ -752,10 +753,12 @@ class WebUICommandRouter:
|
||||
execution_session_key, {},
|
||||
)
|
||||
)
|
||||
if session_generation is not None:
|
||||
metadata[HISTORY_GENERATION_METADATA_KEY] = session_generation
|
||||
if is_webui and not restart_control and (
|
||||
temporary_policy is None or temporary_policy.persist_transcript
|
||||
):
|
||||
self._transcripts.append_user_message(
|
||||
await self._transcripts.append_user_message(
|
||||
chat_id,
|
||||
content,
|
||||
metadata=metadata,
|
||||
|
||||
+12
-39
@@ -86,6 +86,9 @@ class RecoveryCoordinator:
|
||||
|
||||
async def scan(self) -> None:
|
||||
"""Recover every interrupted WebUI session once at gateway startup."""
|
||||
from nanobot.webui.history import initialize_history
|
||||
|
||||
await initialize_history(self.sessions)
|
||||
for key in await self._recovery_candidates():
|
||||
metadata_payload = await self.sessions.state.read_metadata(key)
|
||||
raw_metadata = metadata_payload.get("metadata") if metadata_payload else None
|
||||
@@ -93,7 +96,7 @@ class RecoveryCoordinator:
|
||||
route = self._websocket_route_for(key, metadata)
|
||||
if route is None:
|
||||
continue
|
||||
unfinished = self._has_unfinished_webui_transcript(key)
|
||||
unfinished = await self._has_unfinished_webui_transcript(key)
|
||||
if not self._needs_recovery(metadata) and not unfinished:
|
||||
continue
|
||||
session = await self.sessions.state.get(key)
|
||||
@@ -115,27 +118,8 @@ class RecoveryCoordinator:
|
||||
await self._publish(route[1], failed)
|
||||
|
||||
async def _recovery_candidates(self) -> list[str]:
|
||||
"""Discover canonical and transcript-only WebUI sessions cheaply."""
|
||||
candidates = dict.fromkeys(
|
||||
key
|
||||
for item in await self.sessions.state.list_sessions()
|
||||
if isinstance((key := item.get("key")), str)
|
||||
)
|
||||
try:
|
||||
# Imported lazily because the sidebar index also projects recovery
|
||||
# metadata. The index is the owner of transcript-only discovery;
|
||||
# duplicating its filename and migration rules here would drift.
|
||||
from nanobot.webui.session_list_index import list_webui_sessions
|
||||
|
||||
for item in await asyncio.to_thread(list_webui_sessions, self.sessions):
|
||||
key = item.get("key")
|
||||
if isinstance(key, str):
|
||||
candidates.setdefault(key, None)
|
||||
except Exception:
|
||||
# Canonical checkpoint recovery remains available even if the
|
||||
# optional display-history index is corrupt or unavailable.
|
||||
logger.exception("failed to discover transcript-only WebUI sessions")
|
||||
return list(candidates)
|
||||
"""Legacy display-only sessions have canonical headers after import."""
|
||||
return [item["key"] for item in await self.sessions.state.list_sessions()]
|
||||
|
||||
@staticmethod
|
||||
def _needs_recovery(metadata: Mapping[str, Any]) -> bool:
|
||||
@@ -293,7 +277,7 @@ class RecoveryCoordinator:
|
||||
)
|
||||
await self.sessions.state.restore_interruption(session)
|
||||
await self._publish(chat_id, next_state)
|
||||
elif self._has_unfinished_webui_transcript(session.key):
|
||||
elif await self._has_unfinished_webui_transcript(session.key):
|
||||
# A normal last-client shutdown can materialize the checkpoint
|
||||
# before the process exits. In that path there is no pending
|
||||
# marker left to classify, but the append-only transcript still
|
||||
@@ -505,23 +489,12 @@ class RecoveryCoordinator:
|
||||
def _session_key(self, chat_id: str) -> str:
|
||||
return UNIFIED_SESSION_KEY if self.unified_session else webui_session_key(chat_id)
|
||||
|
||||
@staticmethod
|
||||
def _has_unfinished_webui_transcript(session_key: str) -> bool:
|
||||
"""Detect a stale WebUI activity tail after an unclean gateway stop.
|
||||
async def _has_unfinished_webui_transcript(self, session_key: str) -> bool:
|
||||
from nanobot.webui.transcript import has_unfinished_transcript_tail
|
||||
|
||||
The transcript is intentionally consulted only as a last-resort signal:
|
||||
a durable pending turn or runtime checkpoint always takes precedence.
|
||||
This keeps browser disconnects harmless while preventing a materialized
|
||||
partial turn from being presented as active forever after a restart.
|
||||
"""
|
||||
try:
|
||||
from nanobot.webui.transcript import has_unfinished_transcript_tail
|
||||
|
||||
return has_unfinished_transcript_tail(session_key)
|
||||
except (OSError, ValueError, TypeError):
|
||||
# Recovery must fail closed if the optional display transcript is
|
||||
# corrupt or unavailable; the normal checkpoint path still applies.
|
||||
return False
|
||||
return await self.sessions.state.project_history(
|
||||
session_key, lambda history: has_unfinished_transcript_tail(session_key, history=history),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _has_saved_continuation_context(session: Session) -> bool:
|
||||
|
||||
@@ -1,47 +1,16 @@
|
||||
"""SQLite sidebar queries and a rebuildable display-transcript cache.
|
||||
|
||||
The core ``SessionManager`` owns model context while the WebUI transcript owns
|
||||
durable display history. The sidebar discovers both without reconstructing one
|
||||
store from the other, so core session writes stay independent from UI state.
|
||||
"""
|
||||
"""Sidebar projection from session headers and SQLite display summaries."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import stat
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, cast
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from nanobot.config.paths import get_webui_dir
|
||||
from nanobot.security.workspace_access import WORKSPACE_SCOPE_METADATA_KEY
|
||||
from nanobot.session.manager import (
|
||||
_SESSION_LIST_PREVIEW_MAX_CHARS, # pyright: ignore[reportPrivateUsage]
|
||||
_SESSION_LIST_PREVIEW_MAX_RECORDS, # pyright: ignore[reportPrivateUsage]
|
||||
SessionManager,
|
||||
message_preview_text, # pyright: ignore[reportPrivateUsage]
|
||||
)
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.model_selection import model_preset_from_metadata
|
||||
from nanobot.session.recovery import recovery_state_from_metadata
|
||||
from nanobot.webui.session_identity import (
|
||||
WEBUI_SESSION_STORAGE_PREFIX,
|
||||
is_webui_session_key,
|
||||
webui_chat_id,
|
||||
webui_session_key,
|
||||
)
|
||||
|
||||
_INDEX_VERSION = 8
|
||||
_INDEX_FILENAME = ".webui_session_index.json"
|
||||
_MODEL_PRESET_FIELD = "model_preset"
|
||||
_ROW_SOURCE_FIELD = "_source"
|
||||
_SESSION_SOURCE = "session"
|
||||
_TRANSCRIPT_SOURCE = "webui_transcript"
|
||||
_WORKSPACE_SCOPE_PRESENT_FIELD = "_workspace_scope_present"
|
||||
_WORKSPACE_SCOPE_VALUE_FIELD = "_workspace_scope_value"
|
||||
WEBUI_SESSION_INDEX_INTERNAL_FIELDS = frozenset(
|
||||
@@ -49,205 +18,30 @@ WEBUI_SESSION_INDEX_INTERNAL_FIELDS = frozenset(
|
||||
)
|
||||
_INDEXED_WORKSPACE_SCOPE_KEYS = ("project_path", "path", "access_mode")
|
||||
_MAX_INDEXED_WORKSPACE_SCOPE_BYTES = 4096
|
||||
_WEBUI_ACTIVITY_MTIME_NS = "webui_activity_mtime_ns"
|
||||
_WEBUI_ACTIVITY_SIZE = "webui_activity_size"
|
||||
_WEBUI_ACTIVITY_FILES = "webui_activity_files"
|
||||
_VISIBLE_TRANSCRIPT_ROLES = {"user", "assistant"}
|
||||
_WEBUI_SESSION_STEM_PREFIX = SessionManager.safe_key(WEBUI_SESSION_STORAGE_PREFIX)
|
||||
_WEBUI_CHAT_ID_RE = re.compile(r"^[A-Za-z0-9_:-]{1,64}$")
|
||||
_TRANSCRIPT_SEGMENTS_SUFFIX = ".segments"
|
||||
_TRANSCRIPT_NON_ANSWER_KINDS = {"progress", "reasoning", "tool_hint"}
|
||||
|
||||
|
||||
@dataclass
|
||||
class _WebuiFiles:
|
||||
signature: dict[str, int] = field(default_factory=lambda: {
|
||||
_WEBUI_ACTIVITY_MTIME_NS: 0, _WEBUI_ACTIVITY_SIZE: 0, _WEBUI_ACTIVITY_FILES: 0,
|
||||
})
|
||||
records: list[tuple[Path, float]] = field(default_factory=list)
|
||||
|
||||
|
||||
def list_webui_sessions(
|
||||
session_manager: SessionManager,
|
||||
stored_sessions: list[dict[str, Any]] | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Return session rows for the WebUI sidebar, backed by a rebuildable cache."""
|
||||
webui_dir = get_webui_dir()
|
||||
rows, changed = _reconcile_index(session_manager, stored_sessions, webui_dir)
|
||||
if changed:
|
||||
try:
|
||||
_write_index_rows(session_manager.sessions_dir, [row for row in rows if row.get(_ROW_SOURCE_FIELD) == _TRANSCRIPT_SOURCE])
|
||||
except Exception as e:
|
||||
logger.debug("Failed to write WebUI transcript list cache: {}", e)
|
||||
sessions = [_public_row(session_manager.sessions_dir, webui_dir, row) for row in rows]
|
||||
return sorted(sessions, key=lambda row: row.get("updated_at", ""), reverse=True)
|
||||
|
||||
|
||||
def _reconcile_index(
|
||||
session_manager: SessionManager,
|
||||
stored_sessions: list[dict[str, Any]] | None,
|
||||
webui_dir: Path,
|
||||
) -> tuple[list[dict[str, Any]], bool]:
|
||||
files_by_stem = _read_webui_files(webui_dir)
|
||||
activity_by_stem: dict[str, dict[str, int]] = {}
|
||||
for stem, files in files_by_stem.items():
|
||||
identity = os.path.normcase(stem)
|
||||
previous = activity_by_stem.get(identity)
|
||||
activity_by_stem[identity] = files.signature if previous is None else {
|
||||
_WEBUI_ACTIVITY_MTIME_NS: max(previous[_WEBUI_ACTIVITY_MTIME_NS], files.signature[_WEBUI_ACTIVITY_MTIME_NS]),
|
||||
_WEBUI_ACTIVITY_SIZE: previous[_WEBUI_ACTIVITY_SIZE] + files.signature[_WEBUI_ACTIVITY_SIZE],
|
||||
_WEBUI_ACTIVITY_FILES: previous[_WEBUI_ACTIVITY_FILES] + files.signature[_WEBUI_ACTIVITY_FILES],
|
||||
}
|
||||
"""Read one database snapshot; no display files or sidebar sidecar cache."""
|
||||
stored = session_manager.list_session_metadata() if stored_sessions is None else stored_sessions
|
||||
session_keys = {row["key"] for row in stored}
|
||||
session_stems = {os.path.normcase(SessionManager.safe_key(key)) for key in session_keys if is_webui_session_key(key)}
|
||||
rows: list[dict[str, Any]] = []
|
||||
for row in stored:
|
||||
metadata = row["metadata"]
|
||||
if not session_manager.types.public_history(metadata):
|
||||
continue
|
||||
signature = activity_by_stem.get(os.path.normcase(SessionManager.safe_key(row["key"])))
|
||||
activity = _webui_activity_updated_at(signature) if signature is not None else None
|
||||
millis = row["history_updated_at_ms"]
|
||||
activity = datetime.fromtimestamp(millis / 1000).isoformat() if millis else None
|
||||
rows.append({
|
||||
"key": row["key"], "created_at": row["created_at"],
|
||||
"updated_at": _visible_activity_updated_at(row["updated_at"], row["visible_updated_at"], activity),
|
||||
"title": row["title"], "preview": row["preview"],
|
||||
_MODEL_PRESET_FIELD: model_preset_from_metadata(metadata),
|
||||
"title": row["title"], "preview": row["preview"] or row["history_preview"],
|
||||
"model_preset": model_preset_from_metadata(metadata),
|
||||
"recovery_state": recovery_state_from_metadata(metadata),
|
||||
**_indexed_workspace_scope_fields(metadata),
|
||||
_ROW_SOURCE_FIELD: _SESSION_SOURCE, "file": "sessions.sqlite3",
|
||||
**_indexed_workspace_scope_fields(metadata), "path": row["path"],
|
||||
})
|
||||
|
||||
transcripts = [
|
||||
(stem, files) for stem, files in sorted(files_by_stem.items())
|
||||
if stem.startswith(_WEBUI_SESSION_STEM_PREFIX) and files.records
|
||||
and os.path.normcase(stem) not in session_stems
|
||||
]
|
||||
if not transcripts:
|
||||
return rows, False
|
||||
# Only transcript-only sessions use the file cache; SQLite rows are fresh.
|
||||
existing_rows = _read_index_rows(session_manager.sessions_dir)
|
||||
existing_by_source = {
|
||||
(row.get(_ROW_SOURCE_FIELD), row.get("file")): row
|
||||
for row in existing_rows or []
|
||||
if isinstance(row.get(_ROW_SOURCE_FIELD), str)
|
||||
and isinstance(row.get("file"), str)
|
||||
}
|
||||
changed = existing_rows is None
|
||||
expected_sources: set[tuple[str, str]] = set()
|
||||
for stem, files in transcripts:
|
||||
files.signature = activity_by_stem[os.path.normcase(stem)]
|
||||
identity = (_TRANSCRIPT_SOURCE, stem)
|
||||
row = existing_by_source.get(identity)
|
||||
cached_key = row.get("key") if row is not None else None
|
||||
key = (
|
||||
cached_key
|
||||
if isinstance(cached_key, str) and _valid_transcript_session_key(cached_key, stem)
|
||||
else None
|
||||
)
|
||||
if key is not None and row is not None and _indexed_transcript_row_matches(
|
||||
row,
|
||||
key,
|
||||
files.signature,
|
||||
):
|
||||
rows.append(row)
|
||||
expected_sources.add(identity)
|
||||
continue
|
||||
|
||||
changed = True
|
||||
scanned = _scan_transcript_row(key, stem, files, webui_dir)
|
||||
scanned_key = scanned.get("key") if scanned is not None else None
|
||||
if scanned is not None and scanned_key not in session_keys:
|
||||
rows.append(scanned)
|
||||
expected_sources.add(identity)
|
||||
|
||||
if set(existing_by_source) != expected_sources:
|
||||
changed = True
|
||||
transcript_rows = [row for row in rows if row.get(_ROW_SOURCE_FIELD) == _TRANSCRIPT_SOURCE]
|
||||
if existing_rows is not None and transcript_rows != existing_rows:
|
||||
changed = True
|
||||
return rows, changed
|
||||
|
||||
|
||||
def _index_path(sessions_dir: Path) -> Path:
|
||||
return sessions_dir / _INDEX_FILENAME
|
||||
|
||||
|
||||
def _read_index_rows(sessions_dir: Path) -> list[dict[str, Any]] | None:
|
||||
path = _index_path(sessions_dir)
|
||||
if not path.is_file():
|
||||
return None
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
return None
|
||||
if not isinstance(data, dict):
|
||||
return None
|
||||
index_data = cast(dict[str, Any], data)
|
||||
if index_data.get("version") != _INDEX_VERSION:
|
||||
return None
|
||||
rows = index_data.get("sessions")
|
||||
if not isinstance(rows, list):
|
||||
return None
|
||||
index_rows = cast(list[Any], rows)
|
||||
if not all(isinstance(row, dict) for row in index_rows):
|
||||
return None
|
||||
return [cast(dict[str, Any], row) for row in index_rows]
|
||||
|
||||
|
||||
def _write_index_rows(sessions_dir: Path, rows: list[dict[str, Any]]) -> None:
|
||||
path = _index_path(sessions_dir)
|
||||
tmp_path = path.with_name(f"{path.name}.{secrets.token_hex(8)}.tmp")
|
||||
data = {"version": _INDEX_VERSION, "sessions": rows}
|
||||
try:
|
||||
with open(tmp_path, "x", encoding="utf-8") as file:
|
||||
file.write(json.dumps(data, ensure_ascii=False) + "\n")
|
||||
os.replace(tmp_path, path)
|
||||
finally:
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
|
||||
def _indexed_transcript_row_matches(
|
||||
row: dict[str, Any],
|
||||
session_key: str,
|
||||
signature: dict[str, int],
|
||||
) -> bool:
|
||||
if not all(isinstance(row.get(key), str) for key in ("key", "created_at", "updated_at")):
|
||||
return False
|
||||
if row.get(_ROW_SOURCE_FIELD) != _TRANSCRIPT_SOURCE:
|
||||
return False
|
||||
if row.get("key") != session_key or row.get("file") != SessionManager.safe_key(session_key):
|
||||
return False
|
||||
if not isinstance(row.get("title", ""), str) or not isinstance(row.get("preview", ""), str):
|
||||
return False
|
||||
if not isinstance(row.get(_WORKSPACE_SCOPE_PRESENT_FIELD), bool):
|
||||
return False
|
||||
return (
|
||||
row.get(_WEBUI_ACTIVITY_MTIME_NS) == signature[_WEBUI_ACTIVITY_MTIME_NS]
|
||||
and row.get(_WEBUI_ACTIVITY_SIZE) == signature[_WEBUI_ACTIVITY_SIZE]
|
||||
and row.get(_WEBUI_ACTIVITY_FILES) == signature[_WEBUI_ACTIVITY_FILES]
|
||||
)
|
||||
|
||||
|
||||
def _public_row(sessions_dir: Path, webui_dir: Path, row: dict[str, Any]) -> dict[str, Any]:
|
||||
file = str(row.get("file", ""))
|
||||
if row.get(_ROW_SOURCE_FIELD) == _TRANSCRIPT_SOURCE:
|
||||
path = webui_dir / f"{file}.jsonl"
|
||||
else:
|
||||
path = sessions_dir / file
|
||||
return {
|
||||
"key": row.get("key"),
|
||||
"created_at": row.get("created_at"),
|
||||
"updated_at": row.get("updated_at"),
|
||||
"title": row.get("title", ""),
|
||||
"preview": row.get("preview", ""),
|
||||
_MODEL_PRESET_FIELD: row.get(_MODEL_PRESET_FIELD),
|
||||
"recovery_state": row.get("recovery_state"),
|
||||
_WORKSPACE_SCOPE_PRESENT_FIELD: row.get(_WORKSPACE_SCOPE_PRESENT_FIELD, False),
|
||||
_WORKSPACE_SCOPE_VALUE_FIELD: row.get(_WORKSPACE_SCOPE_VALUE_FIELD),
|
||||
"path": str(path),
|
||||
}
|
||||
return sorted(rows, key=lambda row: row.get("updated_at", ""), reverse=True)
|
||||
|
||||
|
||||
def indexed_workspace_scope(row: dict[str, Any]) -> tuple[bool, object]:
|
||||
@@ -295,67 +89,6 @@ def _indexed_workspace_scope_fields(metadata: object) -> dict[str, object]:
|
||||
}
|
||||
|
||||
|
||||
|
||||
def _read_webui_files(webui_dir: Path) -> dict[str, _WebuiFiles]:
|
||||
"""Discover present display files once per request, including all segment activity."""
|
||||
files_by_stem: dict[str, _WebuiFiles] = {}
|
||||
|
||||
def add_file(stem: str, entry: os.DirEntry[str]) -> None:
|
||||
try:
|
||||
info = entry.stat(follow_symlinks=False)
|
||||
except OSError:
|
||||
return
|
||||
if not stat.S_ISREG(info.st_mode):
|
||||
return
|
||||
files = files_by_stem.setdefault(stem, _WebuiFiles())
|
||||
signature = files.signature
|
||||
signature[_WEBUI_ACTIVITY_MTIME_NS] = max(signature[_WEBUI_ACTIVITY_MTIME_NS], info.st_mtime_ns)
|
||||
signature[_WEBUI_ACTIVITY_SIZE] += info.st_size
|
||||
signature[_WEBUI_ACTIVITY_FILES] += 1
|
||||
if os.path.normcase(entry.name).endswith(".jsonl"):
|
||||
files.records.append((Path(entry.path), info.st_mtime))
|
||||
|
||||
try:
|
||||
with os.scandir(webui_dir) as entries:
|
||||
for entry in entries:
|
||||
name = os.path.normcase(entry.name)
|
||||
if name.endswith(_TRANSCRIPT_SEGMENTS_SUFFIX) and entry.is_dir(follow_symlinks=False):
|
||||
stem = entry.name[:-len(_TRANSCRIPT_SEGMENTS_SUFFIX)]
|
||||
try:
|
||||
with os.scandir(entry.path) as segments:
|
||||
for segment in segments:
|
||||
add_file(stem, segment)
|
||||
except OSError:
|
||||
pass
|
||||
elif name.endswith((".jsonl", ".json")):
|
||||
add_file(entry.name.rsplit(".", 1)[0], entry)
|
||||
except OSError:
|
||||
pass
|
||||
return files_by_stem
|
||||
|
||||
|
||||
def _transcript_record(line: str) -> dict[str, Any] | None:
|
||||
try:
|
||||
value: object = json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
return None
|
||||
return cast(dict[str, Any], value) if isinstance(value, dict) else None
|
||||
|
||||
|
||||
def _valid_transcript_session_key(key: str, stem: str) -> bool:
|
||||
chat_id = webui_chat_id(key)
|
||||
if chat_id is None:
|
||||
return False
|
||||
return _WEBUI_CHAT_ID_RE.fullmatch(chat_id) is not None and SessionManager.safe_key(key) == stem
|
||||
|
||||
|
||||
def _webui_activity_updated_at(signature: dict[str, int]) -> str | None:
|
||||
mtime_ns = signature.get(_WEBUI_ACTIVITY_MTIME_NS, 0)
|
||||
if mtime_ns <= 0:
|
||||
return None
|
||||
return datetime.fromtimestamp(mtime_ns / 1_000_000_000).isoformat()
|
||||
|
||||
|
||||
def _timestamp(value: str | None) -> float:
|
||||
if not value:
|
||||
return 0.0
|
||||
@@ -371,128 +104,9 @@ def _latest_updated_at(stored: str | None, activity: str | None) -> str | None:
|
||||
return stored
|
||||
|
||||
|
||||
|
||||
def _visible_activity_updated_at(
|
||||
stored: str | None,
|
||||
visible_message_at: str | None,
|
||||
webui_activity: str | None,
|
||||
) -> str | None:
|
||||
return _latest_updated_at(visible_message_at, webui_activity) or stored
|
||||
|
||||
|
||||
|
||||
def _transcript_preview(record: dict[str, Any]) -> tuple[str, str]:
|
||||
text = record.get("text")
|
||||
if not isinstance(text, str) or not text.strip():
|
||||
return "", ""
|
||||
preview = message_preview_text({"content": text})
|
||||
if not preview:
|
||||
return "", ""
|
||||
event = record.get("event")
|
||||
if event == "user" or record.get("role") == "user":
|
||||
return preview, ""
|
||||
if (
|
||||
event == "message"
|
||||
and record.get("kind") not in _TRANSCRIPT_NON_ANSWER_KINDS
|
||||
) or record.get("role") == "assistant":
|
||||
return "", preview
|
||||
return "", ""
|
||||
|
||||
|
||||
def _transcript_created_at(record: dict[str, Any]) -> str | None:
|
||||
value = record.get("created_at_ms")
|
||||
if (
|
||||
not isinstance(value, int | float)
|
||||
or isinstance(value, bool)
|
||||
or value < 0
|
||||
):
|
||||
return None
|
||||
try:
|
||||
return datetime.fromtimestamp(value / 1000).isoformat()
|
||||
except (OSError, OverflowError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _scan_transcript_row(
|
||||
session_key: str | None,
|
||||
stem: str,
|
||||
files: _WebuiFiles,
|
||||
webui_dir: Path,
|
||||
) -> dict[str, Any] | None:
|
||||
signature = files.signature
|
||||
activity_updated_at = _webui_activity_updated_at(signature)
|
||||
if activity_updated_at is None:
|
||||
return None
|
||||
|
||||
preview = ""
|
||||
fallback_preview = ""
|
||||
created_at: str | None = None
|
||||
saw_record = False
|
||||
scanned_records = 0
|
||||
scanned_chars = 0
|
||||
paths = [path for path, _ in sorted(files.records, key=lambda item: (item[0].parent == webui_dir, item[0]))]
|
||||
for path in paths:
|
||||
try:
|
||||
with open(path, encoding="utf-8") as handle:
|
||||
for line in handle:
|
||||
if not line.strip():
|
||||
continue
|
||||
scanned_records += 1
|
||||
scanned_chars += len(line)
|
||||
record = _transcript_record(line)
|
||||
if record is not None:
|
||||
saw_record = True
|
||||
chat_id = record.get("chat_id")
|
||||
if isinstance(chat_id, str) and chat_id.strip():
|
||||
candidate = webui_session_key(chat_id.strip())
|
||||
if _valid_transcript_session_key(candidate, stem):
|
||||
session_key = candidate
|
||||
if created_at is None:
|
||||
created_at = _transcript_created_at(record)
|
||||
user_preview, assistant_preview = _transcript_preview(record)
|
||||
if user_preview:
|
||||
preview = user_preview
|
||||
break
|
||||
if not fallback_preview and assistant_preview:
|
||||
fallback_preview = assistant_preview
|
||||
if (
|
||||
scanned_records >= _SESSION_LIST_PREVIEW_MAX_RECORDS
|
||||
or scanned_chars >= _SESSION_LIST_PREVIEW_MAX_CHARS
|
||||
):
|
||||
break
|
||||
except OSError:
|
||||
continue
|
||||
if preview or (
|
||||
scanned_records >= _SESSION_LIST_PREVIEW_MAX_RECORDS
|
||||
or scanned_chars >= _SESSION_LIST_PREVIEW_MAX_CHARS
|
||||
):
|
||||
break
|
||||
if not saw_record:
|
||||
return None
|
||||
if session_key is None:
|
||||
fallback = webui_session_key(stem.removeprefix(_WEBUI_SESSION_STEM_PREFIX))
|
||||
if not _valid_transcript_session_key(fallback, stem):
|
||||
return None
|
||||
session_key = fallback
|
||||
|
||||
if created_at is None:
|
||||
try:
|
||||
earliest_mtime = min(mtime for _, mtime in files.records)
|
||||
created_at = datetime.fromtimestamp(earliest_mtime).isoformat()
|
||||
except (OSError, OverflowError, ValueError):
|
||||
created_at = activity_updated_at
|
||||
return {
|
||||
"key": session_key,
|
||||
"created_at": created_at,
|
||||
"updated_at": activity_updated_at,
|
||||
"title": "",
|
||||
"preview": preview or fallback_preview,
|
||||
_MODEL_PRESET_FIELD: None,
|
||||
"recovery_state": None,
|
||||
**_indexed_workspace_scope_fields({}),
|
||||
_ROW_SOURCE_FIELD: _TRANSCRIPT_SOURCE,
|
||||
"file": stem,
|
||||
"mtime_ns": signature[_WEBUI_ACTIVITY_MTIME_NS],
|
||||
"size": signature[_WEBUI_ACTIVITY_SIZE],
|
||||
**signature,
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
"""Legacy WebUI JSON snapshot path helpers (JSON file); transcripts use transcript."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from nanobot.config.paths import get_webui_dir
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.webui.transcript import delete_webui_transcript
|
||||
|
||||
|
||||
def webui_thread_file_path(session_key: str) -> Path:
|
||||
stem = SessionManager.safe_key(session_key)
|
||||
return get_webui_dir() / f"{stem}.json"
|
||||
|
||||
|
||||
def delete_webui_thread(session_key: str) -> bool:
|
||||
"""Remove legacy WebUI JSON snapshot and append-only transcript for *session_key*."""
|
||||
removed = False
|
||||
path = webui_thread_file_path(session_key)
|
||||
if path.is_file():
|
||||
try:
|
||||
path.unlink()
|
||||
removed = True
|
||||
except OSError as e:
|
||||
logger.warning("Failed to delete webui thread file {}: {}", path, e)
|
||||
if delete_webui_transcript(session_key):
|
||||
removed = True
|
||||
return removed
|
||||
+182
-1015
File diff suppressed because it is too large.
Load diff
+39
-30
@@ -18,7 +18,7 @@ import time
|
||||
from collections.abc import Awaitable, Callable, Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
from typing import TYPE_CHECKING, Any, Protocol, cast
|
||||
from urllib.parse import quote, unquote, urlsplit, urlunsplit
|
||||
|
||||
from loguru import logger
|
||||
@@ -33,6 +33,7 @@ from nanobot.cron.binding import CronBindingError, binding_revision
|
||||
from nanobot.cron.session_turns import is_bound_cron_job
|
||||
from nanobot.cron.types import CronJob, CronSchedule
|
||||
from nanobot.security.workspace_access import WorkspaceScope, WorkspaceScopeError
|
||||
from nanobot.session.display_history import HistoryReader
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.session_handles import (
|
||||
SessionHandle,
|
||||
@@ -128,7 +129,6 @@ from nanobot.webui.skills_marketplace import (
|
||||
trending_marketplace_skills,
|
||||
)
|
||||
from nanobot.webui.star_prompt import update_star_prompt
|
||||
from nanobot.webui.thread_disk import delete_webui_thread
|
||||
from nanobot.webui.transcript import (
|
||||
TranscriptReplayStats,
|
||||
build_session_thread_response,
|
||||
@@ -345,6 +345,10 @@ def _resolve_bootstrap_model_name(
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class _HistoryProjection(Protocol):
|
||||
def __call__(self, request: WsRequest, key: str, *, history: HistoryReader) -> Response: ...
|
||||
|
||||
|
||||
class GatewayHTTPHandler:
|
||||
"""Handles all HTTP routes served alongside the WebSocket endpoint.
|
||||
|
||||
@@ -810,15 +814,11 @@ class GatewayHTTPHandler:
|
||||
async def _dispatch_session_routes(self, request: WsRequest, got: str) -> Response | None:
|
||||
m = re.fullmatch(r"/api/sessions/([^/]+)/webui-thread/prompts", got)
|
||||
if m:
|
||||
return await asyncio.to_thread(self._handle_prompt_index_get, request, m.group(1))
|
||||
return await self._project_session_history(request, m.group(1), self._handle_prompt_index_get)
|
||||
|
||||
m = re.match(r"^/api/sessions/([^/]+)/webui-thread/trace-detail$", got)
|
||||
if m:
|
||||
return await asyncio.to_thread(
|
||||
self._handle_webui_trace_detail_get,
|
||||
request,
|
||||
m.group(1),
|
||||
)
|
||||
return await self._project_session_history(request, m.group(1), self._handle_webui_trace_detail_get)
|
||||
|
||||
m = re.match(r"^/api/sessions/([^/]+)/webui-thread$", got)
|
||||
if m:
|
||||
@@ -1057,7 +1057,23 @@ class GatewayHTTPHandler:
|
||||
def _read_session_version(self, key: str) -> tuple[str, int] | None:
|
||||
return self.session_manager.read_session_version(key) if self.session_manager is not None else None
|
||||
|
||||
def _handle_prompt_index_get(self, request: WsRequest, key: str) -> Response:
|
||||
async def _project_session_history(
|
||||
self, request: WsRequest, key: str, project: _HistoryProjection,
|
||||
) -> Response:
|
||||
if not self.check_api_token(request):
|
||||
return _http_error(401, "Unauthorized")
|
||||
decoded = _decode_api_key(key)
|
||||
if decoded is None:
|
||||
return _http_error(400, "invalid session key")
|
||||
if not _is_websocket_channel_session_key(decoded):
|
||||
return _http_error(404, "session not found")
|
||||
if self.session_manager is None:
|
||||
return _http_error(503, "session manager unavailable")
|
||||
return await self.session_manager.state.project_history(
|
||||
decoded, lambda history: project(request, key, history=history),
|
||||
)
|
||||
|
||||
def _handle_prompt_index_get(self, request: WsRequest, key: str, *, history: HistoryReader) -> Response:
|
||||
from nanobot.webui.transcript import prompt_index_response, prompt_index_revision
|
||||
|
||||
if not self.check_api_token(request):
|
||||
@@ -1067,13 +1083,13 @@ class GatewayHTTPHandler:
|
||||
return _http_error(400, "invalid session key")
|
||||
if not _is_websocket_channel_session_key(decoded_key):
|
||||
return _http_error(404, "session not found")
|
||||
revision = prompt_index_revision(decoded_key, self._read_session_version(decoded_key))
|
||||
revision = prompt_index_revision(decoded_key, self._read_session_version(decoded_key), history=history)
|
||||
etag = _quoted_etag(revision) if revision else None
|
||||
if etag and _etag_matches(_case_insensitive_header(request.headers, "If-None-Match"), etag):
|
||||
return _http_response(b"", status=304, extra_headers=[*_NO_STORE_HEADERS, ("ETag", etag)])
|
||||
query = _parse_query(request.path)
|
||||
data = prompt_index_response(
|
||||
decoded_key, _query_first(query, "since"),
|
||||
decoded_key, _query_first(query, "since"), history=history,
|
||||
session_messages_loader=lambda: self._read_session_messages(decoded_key),
|
||||
session_version_loader=lambda: self._read_session_version(decoded_key),
|
||||
)
|
||||
@@ -1105,13 +1121,11 @@ class GatewayHTTPHandler:
|
||||
|
||||
timer = loop.call_later(0.05, sample_event_loop_lag)
|
||||
started = time.perf_counter()
|
||||
def project(request: WsRequest, key: str, *, history: HistoryReader) -> Response:
|
||||
return self._handle_webui_thread_get(request, key, history=history, diagnostics=diagnostics)
|
||||
|
||||
try:
|
||||
response = await asyncio.to_thread(
|
||||
self._handle_webui_thread_get,
|
||||
request,
|
||||
key,
|
||||
diagnostics=diagnostics,
|
||||
)
|
||||
response = await self._project_session_history(request, key, project)
|
||||
finally:
|
||||
active = False
|
||||
timer.cancel()
|
||||
@@ -1128,7 +1142,6 @@ class GatewayHTTPHandler:
|
||||
stats = diagnostics.transcript
|
||||
if not (
|
||||
diagnostics.total_ms >= _SLOW_WEBUI_HTTP_LOG_MS
|
||||
or stats.manifest_rebuilt
|
||||
or stats.capped_by_bytes
|
||||
or stats.capped_by_records
|
||||
):
|
||||
@@ -1136,7 +1149,7 @@ class GatewayHTTPHandler:
|
||||
self._log.warning(
|
||||
"webui thread replay session_hash={} status={} limit={} source_bytes={} "
|
||||
"parsed_records={} selected_bytes={} selected_records={} compacted_deltas={} "
|
||||
"manifest_rebuilt={} manifest_rebuild_ms={} capped_bytes={} capped_records={} "
|
||||
"capped_bytes={} capped_records={} "
|
||||
"truncated_turn={} replay_ms={} build_ms={} json_ms={} gzip_ms={} gzip={} "
|
||||
"response_bytes={} event_loop_lag_ms={} total_ms={}",
|
||||
diagnostics.session_hash or "unknown",
|
||||
@@ -1147,8 +1160,6 @@ class GatewayHTTPHandler:
|
||||
stats.selected_bytes,
|
||||
stats.selected_records,
|
||||
stats.compacted_delta_records,
|
||||
stats.manifest_rebuilt,
|
||||
stats.manifest_rebuild_ms,
|
||||
stats.capped_by_bytes,
|
||||
stats.capped_by_records,
|
||||
stats.truncated_oversized_turn,
|
||||
@@ -1167,6 +1178,7 @@ class GatewayHTTPHandler:
|
||||
request: WsRequest,
|
||||
key: str,
|
||||
*,
|
||||
history: HistoryReader,
|
||||
diagnostics: _WebUIThreadDiagnostics | None = None,
|
||||
) -> Response:
|
||||
if not self.check_api_token(request):
|
||||
@@ -1224,7 +1236,7 @@ class GatewayHTTPHandler:
|
||||
"session_version": self._read_session_version(decoded_key),
|
||||
"workspace_scope": scope.payload(),
|
||||
}
|
||||
initial_revision = webui_transcript_revision(decoded_key, variant=revision_variant)
|
||||
initial_revision = webui_transcript_revision(decoded_key, history=history, variant=revision_variant)
|
||||
if initial_revision is not None:
|
||||
etag = _quoted_etag(initial_revision)
|
||||
if _etag_matches(_case_insensitive_header(request.headers, "If-None-Match"), etag):
|
||||
@@ -1232,7 +1244,7 @@ class GatewayHTTPHandler:
|
||||
build_started = time.perf_counter()
|
||||
replay_stats = diagnostics.transcript if diagnostics is not None else TranscriptReplayStats()
|
||||
data = build_webui_thread_response(
|
||||
decoded_key,
|
||||
decoded_key, history=history,
|
||||
augment_user_media=self.media.augment_transcript_media,
|
||||
augment_assistant_media=self.media.augment_transcript_media,
|
||||
augment_assistant_text=lambda text: self.media.rewrite_local_markdown_images(
|
||||
@@ -1258,7 +1270,7 @@ class GatewayHTTPHandler:
|
||||
return _http_error(404, "webui thread not found")
|
||||
data["workspace_scope"] = scope.payload()
|
||||
revision_variant["session_version"] = self._read_session_version(decoded_key)
|
||||
final_revision = webui_transcript_revision(decoded_key, variant=revision_variant)
|
||||
final_revision = webui_transcript_revision(decoded_key, history=history, variant=revision_variant)
|
||||
response_headers = list(_NO_STORE_HEADERS)
|
||||
if final_revision is not None and final_revision == initial_revision:
|
||||
response_headers.append(("ETag", _quoted_etag(final_revision)))
|
||||
@@ -1270,7 +1282,7 @@ class GatewayHTTPHandler:
|
||||
metrics=diagnostics.response if diagnostics is not None else None,
|
||||
)
|
||||
|
||||
def _handle_webui_trace_detail_get(self, request: WsRequest, key: str) -> Response:
|
||||
def _handle_webui_trace_detail_get(self, request: WsRequest, key: str, *, history: HistoryReader) -> Response:
|
||||
if not self.check_api_token(request):
|
||||
return _http_error(401, "Unauthorized")
|
||||
decoded_key = _decode_api_key(key)
|
||||
@@ -1281,7 +1293,7 @@ class GatewayHTTPHandler:
|
||||
detail_ref = _query_first(_parse_query(request.path), "ref")
|
||||
if not detail_ref:
|
||||
return _http_error(400, "missing trace detail ref")
|
||||
data = build_webui_trace_detail_response(decoded_key, detail_ref)
|
||||
data = build_webui_trace_detail_response(decoded_key, detail_ref, history=history)
|
||||
if data is None:
|
||||
return _http_error(404, "trace detail not found")
|
||||
return _http_json_response(
|
||||
@@ -1373,10 +1385,7 @@ class GatewayHTTPHandler:
|
||||
elif self.subagent_manager is not None:
|
||||
await self.subagent_manager.cancel_by_session(decoded_key)
|
||||
session_deleted = await self.session_manager.state.delete(decoded_key)
|
||||
transcript_deleted = await asyncio.to_thread(delete_webui_thread, decoded_key)
|
||||
return _http_json_response(
|
||||
{"deleted": bool(draft_deleted or session_deleted or transcript_deleted)}
|
||||
)
|
||||
return _http_json_response({"deleted": bool(draft_deleted or session_deleted)})
|
||||
|
||||
# -- Automation routes --------------------------------------------------
|
||||
|
||||
|
||||
Reference in new issue
Block a user