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
@@ -848,6 +848,7 @@ class TestToolEventProgress:
|
||||
assert request_ctx.metadata == {
|
||||
"injected_event": "subagent_result",
|
||||
"subagent_task_id": "sub-1",
|
||||
"_history_generation": request_ctx.session_generation,
|
||||
}
|
||||
statuses = [
|
||||
message.event.status
|
||||
@@ -905,6 +906,7 @@ class TestToolEventProgress:
|
||||
"_wants_stream",
|
||||
WEBSOCKET_TURN_OWNER_METADATA_KEY,
|
||||
WEBUI_TURN_METADATA_KEY,
|
||||
"_history_generation",
|
||||
"latency_ms",
|
||||
}
|
||||
for message in visible_events
|
||||
|
||||
@@ -28,8 +28,6 @@ from nanobot.webui.transcript import WebUITranscriptRecorder
|
||||
async def test_committed_model_failure_continues_with_tool_results_without_resending(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
monkeypatch.setattr("nanobot.webui.transcript.get_webui_dir", lambda: tmp_path / "webui")
|
||||
monkeypatch.setattr("nanobot.webui.session_list_index.get_webui_dir", lambda: tmp_path / "webui")
|
||||
bus = MessageBus()
|
||||
sessions = SessionManager(tmp_path)
|
||||
session = sessions.get_or_create("websocket:chat")
|
||||
@@ -146,8 +144,7 @@ async def test_recovery_continuation_runs_without_a_sustained_goal(
|
||||
async def test_recovery_preserves_turn_origin_until_the_next_user_turn(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, late_result: bool,
|
||||
) -> None:
|
||||
monkeypatch.setattr("nanobot.webui.transcript.get_webui_dir", lambda: tmp_path / "webui")
|
||||
monkeypatch.setattr("nanobot.webui.session_list_index.get_webui_dir", lambda: tmp_path / "webui")
|
||||
monkeypatch.setattr("nanobot.webui.history.get_webui_dir", lambda: tmp_path / "webui")
|
||||
bus = MessageBus()
|
||||
provider = MagicMock(aclose=AsyncMock())
|
||||
provider.get_default_model.return_value = "test-model"
|
||||
@@ -208,12 +205,12 @@ async def test_recovery_preserves_turn_origin_until_the_next_user_turn(
|
||||
"message_id": None if late_result else "user-message",
|
||||
"turn_id": delivery.route.turn_id,
|
||||
}
|
||||
recorder = WebUITranscriptRecorder()
|
||||
recorder = WebUITranscriptRecorder(loop.sessions)
|
||||
|
||||
async def record_progress(content, **kwargs):
|
||||
recorder.prepare_and_append(
|
||||
await recorder.prepare_and_append(
|
||||
"chat", {"event": "message", "chat_id": "chat", "text": content, "kind": "progress"},
|
||||
metadata=delivery.route.metadata, phase="activity",
|
||||
metadata=delivery.delivery_message.metadata, phase="activity",
|
||||
)
|
||||
|
||||
task = asyncio.create_task(loop._process_message(
|
||||
|
||||
@@ -23,12 +23,7 @@ from nanobot.providers.base import LLMProvider, LLMResponse, ProviderCallContext
|
||||
from nanobot.providers.factory import make_provider, provider_signature
|
||||
from nanobot.providers.fallback_provider import FallbackProvider
|
||||
from nanobot.utils.llm_runtime import LLMRuntime
|
||||
from nanobot.webui.transcript import (
|
||||
WebUITranscriptRecorder,
|
||||
append_transcript_object,
|
||||
build_webui_thread_response,
|
||||
webui_transcript_path,
|
||||
)
|
||||
from nanobot.webui.transcript import WebUITranscriptRecorder
|
||||
|
||||
|
||||
class AnswerProvider(LLMProvider):
|
||||
@@ -65,7 +60,7 @@ def delivery(chat="chat", *, streaming=True):
|
||||
|
||||
@pytest.mark.parametrize("streaming", [False, True])
|
||||
@pytest.mark.parametrize("failures", [0, 1, 2, 3])
|
||||
async def test_actual_candidate_is_delivered_and_replayed(
|
||||
async def test_actual_candidate_is_delivered_and_replayed(history,
|
||||
streaming,
|
||||
failures,
|
||||
tmp_path,
|
||||
@@ -98,7 +93,7 @@ async def test_actual_candidate_is_delivered_and_replayed(
|
||||
channel="websocket", chat_id="chat", content=result.content or "",
|
||||
), publish_completion=False)
|
||||
records = []
|
||||
recorder = WebUITranscriptRecorder()
|
||||
recorder = WebUITranscriptRecorder(None)
|
||||
while not bus.outbound.empty():
|
||||
msg = bus.outbound.get_nowait()
|
||||
if msg.event is not None and not isinstance(msg.event, StreamDeltaEvent | StreamEndEvent):
|
||||
@@ -112,8 +107,8 @@ async def test_actual_candidate_is_delivered_and_replayed(
|
||||
records.append(record)
|
||||
# Completed segment is the durable record; token-sized deltas aren't needed on replay.
|
||||
for record in (r for r in records if r["event"] != "delta"):
|
||||
append_transcript_object("websocket:chat", record)
|
||||
replay = build_webui_thread_response("websocket:chat")
|
||||
history.append("websocket:chat", record)
|
||||
replay = history.build("websocket:chat")
|
||||
if failures == 3:
|
||||
assert all(not r.get("response_sources") for r in records)
|
||||
if replay is None:
|
||||
@@ -300,7 +295,7 @@ def test_factory_captures_names_even_when_models_and_settings_are_identical():
|
||||
assert make_provider(config)._fallback_preset_names == ("renamed",)
|
||||
|
||||
|
||||
def test_old_history_and_malformed_identity_are_not_guessed(tmp_path, monkeypatch):
|
||||
def test_old_history_and_malformed_identity_are_not_guessed(history, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
records = [
|
||||
{"event": "message", "text": "legacy"},
|
||||
@@ -313,8 +308,8 @@ def test_old_history_and_malformed_identity_are_not_guessed(tmp_path, monkeypatc
|
||||
]},
|
||||
]
|
||||
for record in records:
|
||||
append_transcript_object("websocket:source-history", record)
|
||||
replay = build_webui_thread_response("websocket:source-history")
|
||||
history.append("websocket:source-history", record)
|
||||
replay = history.build("websocket:source-history")
|
||||
assert replay is not None
|
||||
events = replay["events"]
|
||||
assert "response_sources" not in events[0]
|
||||
@@ -355,27 +350,28 @@ async def test_runner_records_each_provider_when_streaming_times_out_and_recover
|
||||
|
||||
|
||||
@pytest.mark.parametrize("temporary", [False, True])
|
||||
async def test_websocket_wire_and_disk_replay_preserve_sources(tmp_path, monkeypatch, temporary):
|
||||
async def test_websocket_wire_and_disk_replay_preserve_sources(history, tmp_path, monkeypatch, temporary):
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
channel = WebSocketChannel({"allowFrom": ["*"]}, MessageBus(), gateway=MagicMock())
|
||||
channel._media.rewrite_local_markdown_images.side_effect = lambda text: text
|
||||
channel._transcripts = WebUITranscriptRecorder()
|
||||
channel._transcripts = WebUITranscriptRecorder(history.sessions)
|
||||
generation, _ = await history.sessions.state.open_with_metadata("websocket:source-chat", {})
|
||||
channel._temporary_chats.should_persist_transcript = lambda _: not temporary
|
||||
channel._safe_send_to = AsyncMock()
|
||||
channel._subs["source-chat"] = {MagicMock()}
|
||||
sources = [{"provider": "xai", "model": "grok", "preset": "snapshot name", "fallback": True}]
|
||||
metadata = {"webui_turn_id": "source-turn", "response_sources": sources}
|
||||
metadata = {"webui_turn_id": "source-turn", "response_sources": sources, "_history_generation": generation}
|
||||
await channel.send_delta("source-chat", "Hello", metadata, stream_id="s")
|
||||
await channel.send_delta("source-chat", "", metadata, stream_id="s", stream_end=True)
|
||||
frames = [json.loads(call.args[1]) for call in channel._safe_send_to.call_args_list]
|
||||
assert [frame["event"] for frame in frames] == ["delta", "stream_end"]
|
||||
assert all(frame["response_sources"] == sources for frame in frames)
|
||||
if temporary:
|
||||
assert not webui_transcript_path("websocket:source-chat").exists()
|
||||
assert history.read("websocket:source-chat") == []
|
||||
else:
|
||||
# A fresh reader after an unrelated preset rename/delete sees the saved snapshot.
|
||||
sources[0]["preset"] = "renamed later"
|
||||
replay = build_webui_thread_response("websocket:source-chat")
|
||||
replay = history.build("websocket:source-chat")
|
||||
assert replay is not None
|
||||
end = next(e for e in replay["events"] if e["event"] == "stream_end")
|
||||
assert end["response_sources"][0]["preset"] == "snapshot name"
|
||||
|
||||
@@ -5,7 +5,6 @@ from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from agent.session_helpers import stop_loop
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
@@ -89,15 +88,14 @@ async def test_session_message_text_is_not_dispatched_as_a_slash_command(
|
||||
loop: AgentLoop,
|
||||
) -> None:
|
||||
loop.sessions.save(loop.sessions.get_or_create("telegram:target"))
|
||||
task = asyncio.create_task(loop.run())
|
||||
try:
|
||||
await loop.bus.publish_inbound(_message("/stop"))
|
||||
response = await asyncio.wait_for(loop.bus.consume_outbound(), timeout=2)
|
||||
await loop._dispatch_inbound(_message("/stop"))
|
||||
await asyncio.wait_for(
|
||||
asyncio.gather(*loop._active_tasks["telegram:target"]), timeout=2,
|
||||
)
|
||||
response = await asyncio.wait_for(loop.bus.consume_outbound(), timeout=2)
|
||||
|
||||
assert response.content == "Reviewed"
|
||||
loop.provider.chat_stream_with_retry.assert_awaited_once()
|
||||
finally:
|
||||
await stop_loop(loop, task, timeout=2)
|
||||
assert response.content == "Reviewed"
|
||||
loop.provider.chat_stream_with_retry.assert_awaited_once()
|
||||
|
||||
|
||||
async def test_path_followup_reaches_running_turn(loop: AgentLoop) -> None:
|
||||
|
||||
@@ -26,7 +26,7 @@ async def test_internal_compaction_never_reaches_its_result_destination(channel,
|
||||
msg = InboundMessage(channel=channel, sender_id="user", chat_id="chat", content="check")
|
||||
delivery = factory.create(msg, key)
|
||||
metadata = {"_compaction_route": {"channel": channel, "chat_id": "chat"}} if legacy_route else {}
|
||||
idle_events = factory.session_events(key, metadata)
|
||||
idle_events = factory.session_events(key, metadata, generation="generation")
|
||||
for sink in (delivery.events, idle_events):
|
||||
assert not sink.accepts(ContextCompactionEvent)
|
||||
for phase in ("started", "succeeded", "failed", "cancelled"):
|
||||
@@ -39,7 +39,7 @@ async def test_internal_compaction_never_reaches_its_result_destination(channel,
|
||||
# The same destination still receives the user's own compaction lifecycle.
|
||||
user_delivery = factory.create(msg, f"{channel}:chat")
|
||||
user_delivery.remember_session_route(metadata)
|
||||
for sink in (user_delivery.events, factory.session_events(f"{channel}:chat", metadata)):
|
||||
for sink in (user_delivery.events, factory.session_events(f"{channel}:chat", metadata, generation="generation")):
|
||||
await sink.emit(ContextCompactionEvent("user-compact", "succeeded"))
|
||||
assert factory.bus.outbound.get_nowait().event == ContextCompactionEvent(
|
||||
"user-compact", "succeeded",
|
||||
@@ -79,7 +79,7 @@ async def test_session_route_delivers_automatic_and_manual_compaction(
|
||||
session_metadata = {}
|
||||
delivery.remember_session_route(session_metadata)
|
||||
|
||||
sink = factory.session_events(key, session_metadata)
|
||||
sink = factory.session_events(key, session_metadata, generation="generation")
|
||||
assert sink.publish is not None
|
||||
await sink.emit(automatic)
|
||||
await sink.emit(notified)
|
||||
@@ -100,7 +100,7 @@ async def test_idle_compaction_keeps_its_route_when_a_unified_session_moves() ->
|
||||
metadata={"slack": {"thread_ts": "1700000000.000100"}},
|
||||
)
|
||||
factory.create(original, key).remember_session_route(session_metadata)
|
||||
sink = factory.session_events(key, session_metadata)
|
||||
sink = factory.session_events(key, session_metadata, generation="generation")
|
||||
assert sink.publish is not None
|
||||
await sink.emit(ContextCompactionEvent("compact-1", "started", notify=True))
|
||||
|
||||
@@ -119,7 +119,7 @@ async def test_idle_compaction_keeps_its_route_when_a_unified_session_moves() ->
|
||||
async def test_automatic_compaction_reaches_legacy_websocket_session() -> None:
|
||||
factory = TurnDeliveryFactory(MessageBus())
|
||||
event = ContextCompactionEvent(compaction_id="compact-1", phase="succeeded")
|
||||
sink = factory.session_events("websocket:chat", {})
|
||||
sink = factory.session_events("websocket:chat", {}, generation="generation")
|
||||
assert sink.publish is not None
|
||||
await sink.emit(event)
|
||||
assert factory.bus.outbound.get_nowait().event is event
|
||||
@@ -474,3 +474,32 @@ async def test_late_subagent_route_requires_webui_owned_session(tmp_path: Path)
|
||||
"injected_event": "subagent_result",
|
||||
"subagent_task_id": "sub-1",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unified_display_route_admits_alias_generation_and_rejects_stale_lifetime(tmp_path):
|
||||
from nanobot.session.display_history import HISTORY_GENERATION_METADATA_KEY
|
||||
from nanobot.session.sqlite_store import SessionConflictError
|
||||
|
||||
sessions = SessionManager(tmp_path)
|
||||
alias = await sessions.state.get_header("websocket:chat")
|
||||
source = await sessions.state.get_header("unified:default")
|
||||
policy = WebuiTurnRoutePolicy(sessions)
|
||||
factory = TurnDeliveryFactory(MessageBus(), route_policy=policy, route_admission=policy.admit)
|
||||
message = InboundMessage(channel="system", sender_id="cron", chat_id="websocket:chat", content="notice")
|
||||
delivery = factory.create(message, source.key)
|
||||
await delivery.bind_session_generation(source.generation)
|
||||
assert delivery.route.metadata[HISTORY_GENERATION_METADATA_KEY] == alias.generation
|
||||
assert delivery.delivery_message.session_generation == source.generation
|
||||
response = delivery.background_response("done", stop_reason="end_turn", streamed=False, latency_ms=1)
|
||||
assert response.metadata[HISTORY_GENERATION_METADATA_KEY] == alias.generation
|
||||
await sessions.state.delete(alias.key)
|
||||
replacement = await sessions.state.get_header(alias.key)
|
||||
stale = factory.create(InboundMessage(
|
||||
channel="websocket", sender_id="user", chat_id="chat", content="old queued input",
|
||||
metadata={HISTORY_GENERATION_METADATA_KEY: alias.generation},
|
||||
), source.key)
|
||||
with pytest.raises(SessionConflictError):
|
||||
await stale.bind_session_generation(source.generation)
|
||||
assert replacement.generation != alias.generation
|
||||
await sessions.state.aclose()
|
||||
@@ -9,7 +9,6 @@ import pytest
|
||||
from nanobot.agent.tools.context import RequestContext, request_context
|
||||
from nanobot.agent.tools.sessions import ReadSessionTool, SearchSessionsTool
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.webui.transcript import append_transcript_object
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -57,10 +56,10 @@ async def test_session_tools_find_old_matches_in_full_session(
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("state", ["canonical", "transcript", "mixed"])
|
||||
async def test_session_tools_use_canonical_records_after_restart(tmp_path, monkeypatch, state):
|
||||
async def test_session_tools_use_canonical_records_after_restart(history, tmp_path, monkeypatch, state):
|
||||
webui_dir = tmp_path / "webui"
|
||||
monkeypatch.setattr("nanobot.webui.transcript.get_webui_dir", lambda: webui_dir)
|
||||
manager = SessionManager(tmp_path)
|
||||
monkeypatch.setattr("nanobot.webui.history.get_webui_dir", lambda: webui_dir)
|
||||
manager = history.sessions
|
||||
key = "websocket:history"
|
||||
if state != "transcript":
|
||||
session = manager.get_or_create(key)
|
||||
@@ -68,10 +67,10 @@ async def test_session_tools_use_canonical_records_after_restart(tmp_path, monke
|
||||
session.add_message("user", "canonical needle")
|
||||
manager.save(session)
|
||||
if state != "canonical":
|
||||
append_transcript_object(key, {
|
||||
history.append(key, {
|
||||
"event": "user", "chat_id": "history", "text": "display-only needle",
|
||||
})
|
||||
append_transcript_object(key, {"event": "turn_end", "chat_id": "history"})
|
||||
history.append(key, {"event": "turn_end", "chat_id": "history"})
|
||||
|
||||
def durable_files():
|
||||
return {
|
||||
@@ -82,7 +81,7 @@ async def test_session_tools_use_canonical_records_after_restart(tmp_path, monke
|
||||
|
||||
original = durable_files()
|
||||
for _ in range(2):
|
||||
manager = SessionManager(tmp_path)
|
||||
manager = history.sessions
|
||||
with request_context(RequestContext(
|
||||
channel="websocket", chat_id="current", session_key="websocket:current",
|
||||
)):
|
||||
@@ -91,7 +90,7 @@ async def test_session_tools_use_canonical_records_after_restart(tmp_path, monke
|
||||
display_search = json.loads(await SearchSessionsTool(manager).execute(query="display-only"))
|
||||
if state == "transcript":
|
||||
assert search["results"] == []
|
||||
assert read.is_error and "session not found" in str(read)
|
||||
assert json.loads(read)["messages"] == []
|
||||
else:
|
||||
assert [row["session_key"] for row in search["results"]] == [key]
|
||||
assert search["results"][0]["excerpts"][0]["content"] == "canonical needle"
|
||||
|
||||
@@ -7,8 +7,12 @@ import pytest
|
||||
from nanobot.agent.tools.context import RequestContext, request_context
|
||||
from nanobot.agent.tools.message import MessageTool
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.websocket.runtime import WebSocketChannel, WebSocketConfig
|
||||
from nanobot.cli.gateway_runtime import _deliver_to_channel
|
||||
from nanobot.session.display_history import HISTORY_GENERATION_METADATA_KEY
|
||||
from nanobot.session.keys import UNIFIED_SESSION_KEY
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.webui.gateway_services import build_gateway_services
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -102,3 +106,109 @@ async def test_cross_target_reset_after_admission_revokes_media(delivery, monkey
|
||||
assert "replaced session" in result
|
||||
assert bus.outbound.empty()
|
||||
assert (await sessions.state.read("email:fresh@example.invalid")).messages == []
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def webui_delivery(delivery, tmp_path, monkeypatch):
|
||||
sessions, bus, tool = delivery
|
||||
data = tmp_path / "instance"
|
||||
data.mkdir()
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: data)
|
||||
config = WebSocketConfig.model_validate({
|
||||
"enabled": True, "allowFrom": ["*"], "host": "127.0.0.1", "port": 0,
|
||||
})
|
||||
gateway = build_gateway_services(
|
||||
config=config, bus=bus, session_manager=sessions, static_dist_path=None,
|
||||
workspace_path=sessions.workspace, default_restrict_to_workspace=True,
|
||||
runtime_model_name=None, runtime_surface="browser", runtime_capabilities_overrides=None,
|
||||
config_path=data / "config.json",
|
||||
)
|
||||
return sessions, bus, tool, WebSocketChannel(config, bus, gateway=gateway)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("caption", ["caption", ""])
|
||||
async def test_unified_webui_media_keeps_its_display_generation(webui_delivery, caption):
|
||||
sessions, bus, tool, channel = webui_delivery
|
||||
alias = await sessions.state.get_header("websocket:chat")
|
||||
canonical = await sessions.state.get_header(UNIFIED_SESSION_KEY)
|
||||
tool.set_send_callback(partial(
|
||||
_deliver_to_channel, bus=bus, session_manager=sessions, unified_session=True,
|
||||
))
|
||||
with request_context(RequestContext(
|
||||
"websocket", "chat", session_key=canonical.key,
|
||||
session_generation=canonical.generation,
|
||||
metadata={HISTORY_GENERATION_METADATA_KEY: alias.generation},
|
||||
)):
|
||||
result = await tool.execute(content=caption, media=["attachment.txt"])
|
||||
|
||||
assert result == "Message sent to websocket:chat with 1 attachments"
|
||||
sent = bus.outbound.get_nowait()
|
||||
assert sent.metadata[HISTORY_GENERATION_METADATA_KEY] == alias.generation
|
||||
await channel.send(sent)
|
||||
facts = await sessions.state.project_history(alias.key, lambda history: history.all_facts())
|
||||
assert len(facts) == 1
|
||||
assert facts[0].content["text"] == caption
|
||||
assert facts[0].content["media"] == sent.media
|
||||
|
||||
|
||||
async def test_cross_channel_text_is_saved_in_webui_history(webui_delivery):
|
||||
sessions, bus, tool, channel = webui_delivery
|
||||
alias = await sessions.state.get_header("websocket:chat")
|
||||
source = await sessions.state.get_header("telegram:origin")
|
||||
with request_context(RequestContext(
|
||||
"telegram", "origin", session_key=source.key, session_generation=source.generation,
|
||||
)):
|
||||
result = await tool.execute(content="notice", channel="websocket", chat_id="chat")
|
||||
|
||||
assert result == "Message sent to websocket:chat"
|
||||
sent = bus.outbound.get_nowait()
|
||||
await channel.send(sent)
|
||||
facts = await sessions.state.project_history(alias.key, lambda history: history.all_facts())
|
||||
assert [fact.content["text"] for fact in facts] == ["notice"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("operation", ["reset", "delete"])
|
||||
async def test_webui_destination_revocation_after_admission_blocks_history(
|
||||
webui_delivery, monkeypatch, operation,
|
||||
):
|
||||
sessions, bus, tool, channel = webui_delivery
|
||||
target = await sessions.state.get_header("websocket:chat")
|
||||
original = bus.publish_outbound
|
||||
|
||||
async def revoke_before_enqueue(message):
|
||||
assert message.metadata[HISTORY_GENERATION_METADATA_KEY] == target.generation
|
||||
await getattr(sessions.state, operation)(target.key)
|
||||
await original(message)
|
||||
|
||||
monkeypatch.setattr(bus, "publish_outbound", revoke_before_enqueue)
|
||||
result = await tool.execute(content="late notice", channel="websocket", chat_id="chat")
|
||||
assert result == "Message sent to websocket:chat"
|
||||
await channel.send(bus.outbound.get_nowait())
|
||||
assert await sessions.state.project_history(target.key, lambda history: history.all_facts()) == []
|
||||
current = await sessions.state.read(target.key)
|
||||
assert current is None or current.generation != target.generation
|
||||
|
||||
|
||||
@pytest.mark.parametrize("media", [None, ["attachment.txt"]])
|
||||
async def test_direct_webui_send_does_not_create_a_missing_destination(webui_delivery, media):
|
||||
sessions, bus, tool, _ = webui_delivery
|
||||
result = await tool.execute(
|
||||
content="notice", channel="websocket", chat_id="missing", media=media,
|
||||
)
|
||||
assert result.startswith("Error sending message:")
|
||||
assert bus.outbound.empty()
|
||||
assert await sessions.state.read("websocket:missing") is None
|
||||
|
||||
|
||||
async def test_temporary_webui_media_stays_nonpersistent(webui_delivery):
|
||||
sessions, bus, tool, channel = webui_delivery
|
||||
target = await sessions.state.register_transient("websocket:temporary")
|
||||
with request_context(RequestContext(
|
||||
"websocket", "temporary", session_key=target.key,
|
||||
session_generation=target.generation,
|
||||
metadata={HISTORY_GENERATION_METADATA_KEY: target.generation},
|
||||
)):
|
||||
result = await tool.execute(content="caption", media=["attachment.txt"])
|
||||
assert result == "Message sent to websocket:temporary with 1 attachments"
|
||||
await channel.send(bus.outbound.get_nowait())
|
||||
assert await sessions.state.project_history(target.key, lambda history: history.revision) is None
|
||||
@@ -131,6 +131,7 @@ class _EmptyGatewaySessionManager:
|
||||
def state(self):
|
||||
return SimpleNamespace(
|
||||
list_sessions=AsyncMock(return_value=[]),
|
||||
migrate_history=AsyncMock(),
|
||||
record_delivery=AsyncMock(),
|
||||
aclose=AsyncMock(),
|
||||
)
|
||||
|
||||
@@ -0,0 +1,358 @@
|
||||
"""One SQLite owner for model messages and durable, generation-bound display facts."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sqlite3
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.session.display_history import HistoryFact, HistoryKind
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.sqlite_store import SessionConflictError
|
||||
from nanobot.webui.forking import create_webui_chat_fork
|
||||
from nanobot.webui.history import HISTORY_IMPORT_MARKER, collect_legacy_history
|
||||
from nanobot.webui.transcript import WebUITranscriptRecorder, build_webui_thread_response
|
||||
|
||||
|
||||
def _manager(tmp_path: Path) -> SessionManager:
|
||||
return SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "sessions")
|
||||
|
||||
|
||||
def _legacy(directory: Path, key: str, records: list[dict]) -> Path:
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
path = directory / f"{SessionManager.safe_key(key)}.jsonl"
|
||||
path.write_text("".join(json.dumps(record, ensure_ascii=False) + "\n" for record in records), encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
async def test_display_facts_survive_reopen_without_entering_model_history(tmp_path):
|
||||
sessions = _manager(tmp_path)
|
||||
session = await sessions.state.get("websocket:durable")
|
||||
session.add_message("user", "question")
|
||||
session.add_message("assistant", "answer")
|
||||
await sessions.state.finish_turn(session)
|
||||
facts = [
|
||||
HistoryFact(HistoryKind.INPUT, {"text": "question"}, "turn-1", "user", 1, 1000),
|
||||
HistoryFact(HistoryKind.REASONING_SEGMENT, {"text": "reasoning"}, "turn-1", "reasoning", 2, 1001),
|
||||
HistoryFact(HistoryKind.FILE_ACTIVITY, {"edits": [{"path": "a.py", "diff": "-old\n+new"}]}, "turn-1", "activity", 3, 1002),
|
||||
HistoryFact(HistoryKind.ANSWER_SEGMENT, {"text": "answer", "response_sources": [{
|
||||
"provider": "test", "model": "actual-fallback", "preset": "default", "fallback": True,
|
||||
}]}, "turn-1", "answer", 4, 1003),
|
||||
HistoryFact(HistoryKind.COMPLETION, {"usage": {"total_tokens": 30}, "round_usages": [{"total_tokens": 30}],
|
||||
"latency_ms": 40, "outcome": "failed", "failure_message": "model unavailable"},
|
||||
"turn-1", "complete", 5, 1004),
|
||||
]
|
||||
await sessions.state.append_history(session.key, facts, expected_generation=session.generation)
|
||||
with closing(sqlite3.connect(sessions.sessions_dir / "sessions.sqlite3")) as db:
|
||||
stored = db.execute("SELECT record FROM history_entries ORDER BY position").fetchall()
|
||||
assert [json.loads(row[0])["kind"] for row in stored] == [fact.kind for fact in facts]
|
||||
assert all("chat_id" not in json.loads(row[0]) and "event" not in json.loads(row[0]) for row in stored)
|
||||
await sessions.state.aclose()
|
||||
|
||||
reopened = _manager(tmp_path)
|
||||
assert reopened.project_history(session.key, lambda history: history.all_facts()) == facts
|
||||
model = reopened.read_session_file(session.key)
|
||||
assert [message["content"] for message in model["messages"]] == ["question", "answer"]
|
||||
payload = reopened.project_history(session.key, lambda history: build_webui_thread_response(session.key, history=history))
|
||||
assert payload["completed_turn_ids"] == ["turn-1"]
|
||||
terminal = next(event for event in payload["events"] if event["event"] == "turn_end")
|
||||
assert terminal["failure_message"] == "model unavailable" and terminal["outcome"] == "failed"
|
||||
assert terminal["round_usages"] == [{"total_tokens": 30}]
|
||||
assert any(event.get("edits") == facts[2].content["edits"] for event in payload["events"])
|
||||
assert next(event for event in payload["events"] if event["event"] == "stream_end")["response_sources"] == facts[3].content["response_sources"]
|
||||
|
||||
|
||||
async def test_delete_reset_reject_old_display_generation(tmp_path):
|
||||
sessions = _manager(tmp_path)
|
||||
key = "websocket:generation"
|
||||
first = await sessions.state.get(key)
|
||||
first.add_message("user", "old")
|
||||
await sessions.state.finish_turn(first)
|
||||
fact = HistoryFact(HistoryKind.INPUT, {"text": "old"})
|
||||
await sessions.state.append_history(key, [fact], expected_generation=first.generation)
|
||||
assert await sessions.state.delete(key)
|
||||
with pytest.raises(SessionConflictError):
|
||||
await sessions.state.append_history(key, [fact], expected_generation=first.generation)
|
||||
assert await sessions.state.project_history(key, lambda history: history.revision) is None
|
||||
second = await sessions.state.get(key)
|
||||
second.add_message("user", "new")
|
||||
await sessions.state.finish_turn(second)
|
||||
with pytest.raises(SessionConflictError):
|
||||
await sessions.state.append_history(key, [fact], expected_generation=first.generation)
|
||||
assert await sessions.state.project_history(key, lambda history: history.all_facts()) == []
|
||||
await sessions.state.aclose()
|
||||
|
||||
|
||||
async def test_fork_rolls_back_both_histories_if_display_copy_fails(tmp_path, monkeypatch):
|
||||
sessions = _manager(tmp_path)
|
||||
source = await sessions.state.get("websocket:source")
|
||||
source.add_message("user", "question")
|
||||
source.add_message("assistant", "answer")
|
||||
await sessions.state.finish_turn(source)
|
||||
monkeypatch.setattr("nanobot.webui.forking.uuid.uuid4", lambda: "failed-fork")
|
||||
original = sessions._store.append_history
|
||||
|
||||
def fail(key, facts, *, expected_generation):
|
||||
original(key, facts, expected_generation=expected_generation)
|
||||
raise OSError("disk full")
|
||||
|
||||
monkeypatch.setattr(sessions._store, "append_history", fail)
|
||||
with pytest.raises(OSError, match="disk full"):
|
||||
await create_webui_chat_fork(sessions, source_chat_id="source", before_user_index=1)
|
||||
assert await sessions.state.read_metadata("websocket:failed-fork") is None
|
||||
assert await sessions.state.project_history("websocket:failed-fork", lambda history: history.all_facts()) == []
|
||||
assert (await sessions.state.get(source.key)).messages == source.messages
|
||||
await sessions.state.aclose()
|
||||
|
||||
|
||||
async def test_legacy_import_is_atomic_repeatable_and_deletion_cannot_resurrect_backup(tmp_path):
|
||||
sessions = _manager(tmp_path)
|
||||
directory = tmp_path / "legacy"
|
||||
path = _legacy(directory, "websocket:imported", [
|
||||
{"event": "user", "chat_id": "imported", "text": "hello", "created_at_ms": 1000},
|
||||
{"event": "delta", "chat_id": "imported", "text": "an"},
|
||||
{"event": "delta", "chat_id": "imported", "text": "swer"},
|
||||
{"event": "stream_end", "chat_id": "imported"},
|
||||
{"event": "turn_end", "chat_id": "imported"},
|
||||
])
|
||||
before = path.read_bytes()
|
||||
def collect(rows):
|
||||
return collect_legacy_history(rows, directory=directory)
|
||||
await sessions.state.migrate_history(HISTORY_IMPORT_MARKER, collect)
|
||||
facts = await sessions.state.project_history("websocket:imported", lambda history: history.all_facts())
|
||||
assert [fact.kind for fact in facts] == [HistoryKind.INPUT, HistoryKind.ANSWER_SEGMENT, HistoryKind.COMPLETION]
|
||||
assert facts[1].content["text"] == "answer"
|
||||
assert path.read_bytes() == before
|
||||
await sessions.state.migrate_history(HISTORY_IMPORT_MARKER, collect)
|
||||
assert await sessions.state.project_history("websocket:imported", lambda history: history.all_facts()) == facts
|
||||
assert await sessions.state.delete("websocket:imported")
|
||||
await sessions.state.aclose()
|
||||
reopened = _manager(tmp_path)
|
||||
await reopened.state.migrate_history(HISTORY_IMPORT_MARKER, collect)
|
||||
assert await reopened.state.read_metadata("websocket:imported") is None
|
||||
await reopened.state.aclose()
|
||||
|
||||
|
||||
async def test_corrupt_legacy_input_rolls_back_import_marker_and_all_records(tmp_path):
|
||||
sessions = _manager(tmp_path)
|
||||
directory = tmp_path / "legacy"
|
||||
_legacy(directory, "websocket:first", [{"event": "user", "chat_id": "first", "text": "safe"}])
|
||||
corrupt = _legacy(directory, "websocket:second", [{"event": "user", "chat_id": "second", "text": "also safe"}])
|
||||
with corrupt.open("a", encoding="utf-8") as handle:
|
||||
handle.write('{"event":\n')
|
||||
with pytest.raises(ValueError, match="cannot import history"):
|
||||
await sessions.state.migrate_history(HISTORY_IMPORT_MARKER, lambda rows: collect_legacy_history(rows, directory=directory))
|
||||
assert await sessions.state.list_sessions() == []
|
||||
with closing(sqlite3.connect(sessions.sessions_dir / "sessions.sqlite3")) as db:
|
||||
assert db.execute("SELECT value FROM storage_meta WHERE key=?", (HISTORY_IMPORT_MARKER,)).fetchone() is None
|
||||
_legacy(directory, "websocket:second", [{"event": "user", "chat_id": "second", "text": "fixed"}])
|
||||
await sessions.state.migrate_history(HISTORY_IMPORT_MARKER, lambda rows: collect_legacy_history(rows, directory=directory))
|
||||
assert {row["key"] for row in await sessions.state.list_sessions()} == {"websocket:first", "websocket:second"}
|
||||
await sessions.state.aclose()
|
||||
|
||||
|
||||
async def test_segments_import_in_order_without_trusting_damaged_manifest(tmp_path):
|
||||
sessions = _manager(tmp_path)
|
||||
directory = tmp_path / "legacy"
|
||||
segments = directory / "websocket_order.segments"
|
||||
segments.mkdir(parents=True)
|
||||
for number in (2, 1):
|
||||
(segments / f"{number:06}.jsonl").write_text(json.dumps({"event": "message", "chat_id": "order", "text": str(number)}) + "\n", encoding="utf-8")
|
||||
(segments / "manifest.json").write_text("broken cached manifest", encoding="utf-8")
|
||||
_legacy(directory, "websocket:order", [{"event": "message", "chat_id": "order", "text": "3"}])
|
||||
await sessions.state.migrate_history(HISTORY_IMPORT_MARKER, lambda rows: collect_legacy_history(rows, directory=directory))
|
||||
assert await sessions.state.project_history("websocket:order", lambda history: [fact.content["text"] for fact in history.all_facts()]) == ["1", "2", "3"]
|
||||
await sessions.state.aclose()
|
||||
|
||||
|
||||
def test_orphan_lossy_filename_requires_recorded_identity(tmp_path):
|
||||
directory = tmp_path / "legacy"
|
||||
_legacy(directory, "websocket:a_b", [{"event": "message", "text": "unknown whether a_b or a:b"}])
|
||||
with pytest.raises(ValueError, match="ambiguous legacy history identity"):
|
||||
collect_legacy_history([], directory=directory)
|
||||
|
||||
|
||||
async def test_recorder_keeps_completed_segments_not_every_transport_delta(tmp_path):
|
||||
sessions = _manager(tmp_path)
|
||||
key = "websocket:stream"
|
||||
generation, _ = await sessions.state.open_with_metadata(key, {})
|
||||
recorder = WebUITranscriptRecorder(sessions)
|
||||
metadata = {"_history_generation": generation, "_webui_turn_id": "turn"}
|
||||
for _ in range(8):
|
||||
assert await recorder.prepare_and_append_stream_event("stream", {"event": "delta", "text": "x"}, completed_text=None, metadata=metadata, phase="answer")
|
||||
assert await recorder.prepare_and_append_stream_event("stream", {"event": "stream_end"}, completed_text="x" * 8, metadata=metadata, phase="answer")
|
||||
facts = await sessions.state.project_history(key, lambda history: history.all_facts())
|
||||
assert [fact.kind for fact in facts] == [HistoryKind.ANSWER_SEGMENT]
|
||||
assert facts[0].content["text"] == "x" * 8
|
||||
await sessions.state.aclose()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("committed", [False, True])
|
||||
async def test_real_process_exit_cannot_split_fork_model_and_display_histories(tmp_path, committed):
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
sessions = _manager(tmp_path)
|
||||
source = await sessions.state.get("websocket:source")
|
||||
source.add_message("user", "question")
|
||||
source.add_message("assistant", "answer")
|
||||
await sessions.state.finish_turn(source)
|
||||
await sessions.state.append_history(source.key, [
|
||||
HistoryFact(HistoryKind.INPUT, {"text": "question"}),
|
||||
HistoryFact(HistoryKind.ANSWER, {"text": "answer"}),
|
||||
HistoryFact(HistoryKind.COMPLETION),
|
||||
], expected_generation=source.generation)
|
||||
await sessions.state.aclose()
|
||||
child = tmp_path / "crash.py"
|
||||
child.write_text('''import asyncio, os, sys
|
||||
from pathlib import Path
|
||||
from nanobot.session.manager import SessionManager
|
||||
root = Path(sys.argv[1])
|
||||
sessions = SessionManager(root / "workspace", sessions_root=root / "sessions")
|
||||
original = sessions._store.append_history
|
||||
def append(key, facts, *, expected_generation):
|
||||
original(key, facts, expected_generation=expected_generation)
|
||||
if sys.argv[2] == "False":
|
||||
os._exit(91)
|
||||
sessions._store.append_history = append
|
||||
async def run():
|
||||
await sessions.state.fork("websocket:source", "websocket:fork", 1)
|
||||
os._exit(92)
|
||||
asyncio.run(run())
|
||||
''', encoding="utf-8")
|
||||
result = subprocess.run([sys.executable, str(child), str(tmp_path), str(committed)], capture_output=True, timeout=15)
|
||||
assert result.returncode == (92 if committed else 91), result.stderr.decode("utf-8", errors="replace")
|
||||
reopened = _manager(tmp_path)
|
||||
fork = reopened.read_session_file("websocket:fork")
|
||||
facts = reopened.project_history("websocket:fork", lambda history: history.all_facts())
|
||||
if committed:
|
||||
assert [message["content"] for message in fork["messages"]] == ["question", "answer"]
|
||||
assert [fact.kind for fact in facts] == [HistoryKind.INPUT, HistoryKind.ANSWER, HistoryKind.COMPLETION, HistoryKind.FORK_BOUNDARY]
|
||||
else:
|
||||
assert fork is None and facts == []
|
||||
assert reopened.read_session_file(source.key)["messages"] == source.messages
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_legacy_import_owner_survives_delete_and_new_workspace(tmp_path):
|
||||
from nanobot.webui.history import collect_legacy_history
|
||||
|
||||
root = tmp_path / "sessions"
|
||||
legacy = tmp_path / "webui"
|
||||
legacy.mkdir()
|
||||
key = "websocket:owned"
|
||||
(legacy / f"{SessionManager.safe_key(key)}.jsonl").write_text(
|
||||
'{"event":"user","chat_id":"owned","text":"keep ownership"}\n', encoding="utf-8",
|
||||
)
|
||||
first = SessionManager(tmp_path / "first", sessions_root=root)
|
||||
await first.state.migrate_history(HISTORY_IMPORT_MARKER, lambda rows: collect_legacy_history(
|
||||
rows, directory=legacy, namespace=first.sessions_dir,
|
||||
))
|
||||
await first.state.delete(key)
|
||||
await first.state.aclose()
|
||||
second = SessionManager(tmp_path / "second", sessions_root=root)
|
||||
await second.state.migrate_history(HISTORY_IMPORT_MARKER, lambda rows: collect_legacy_history(
|
||||
rows, directory=legacy, namespace=second.sessions_dir,
|
||||
))
|
||||
assert await second.state.read(key) is None
|
||||
await second.state.aclose()
|
||||
|
||||
|
||||
async def test_large_display_fact_serialization_and_copy_stay_off_runtime_loop(tmp_path, monkeypatch):
|
||||
import threading
|
||||
|
||||
import nanobot.session.state as state_module
|
||||
|
||||
sessions = _manager(tmp_path)
|
||||
session = await sessions.state.get_header("websocket:large-activity")
|
||||
runtime_thread = threading.get_ident()
|
||||
encode, copy = HistoryFact.encode, state_module.deepcopy
|
||||
|
||||
def worker_encode(fact):
|
||||
assert threading.get_ident() != runtime_thread
|
||||
return encode(fact)
|
||||
|
||||
def worker_copy(value, *args, **kwargs):
|
||||
if isinstance(value, list) and value and isinstance(value[0], HistoryFact):
|
||||
assert threading.get_ident() != runtime_thread
|
||||
return copy(value, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(HistoryFact, "encode", worker_encode)
|
||||
monkeypatch.setattr(state_module, "deepcopy", worker_copy)
|
||||
recorder = WebUITranscriptRecorder(sessions)
|
||||
assert await recorder.prepare_and_append("large-activity", {
|
||||
"event": "message", "kind": "tool_hint", "text": "exec",
|
||||
"tool_events": [{"tool": "exec", "result": "x" * 1_000_000}],
|
||||
}, metadata={"_history_generation": session.generation})
|
||||
facts = await sessions.state.project_history(session.key, lambda history: history.all_facts())
|
||||
assert len(facts[0].content["tool_events"][0]["result"]) == 1_000_000
|
||||
await sessions.state.aclose()
|
||||
|
||||
|
||||
def test_message_projection_adapter_preserves_reply_and_agent_activity():
|
||||
from nanobot.webui.history import fact_from_record, record_from_fact
|
||||
|
||||
record = {
|
||||
"event": "message", "chat_id": "activity", "kind": "progress",
|
||||
"text": "Inspecting workspace", "reply_to": "message-1", "created_at_ms": 1000,
|
||||
"agent_ui": {"version": 1, "status": "working", "label": "Inspecting workspace"},
|
||||
}
|
||||
fact = HistoryFact.decode(fact_from_record(record).encode())
|
||||
assert record_from_fact(fact, "websocket:activity") == record
|
||||
|
||||
|
||||
async def test_legacy_activity_without_record_timestamps_preserves_file_time(tmp_path):
|
||||
import os
|
||||
|
||||
from nanobot.webui.session_list_index import list_webui_sessions
|
||||
|
||||
sessions = _manager(tmp_path)
|
||||
session = await sessions.state.get_header("websocket:old-activity")
|
||||
directory = tmp_path / "legacy"
|
||||
path = _legacy(directory, session.key, [{
|
||||
"event": "message", "chat_id": "old-activity", "text": "historical display activity",
|
||||
}])
|
||||
os.utime(path, (1760000000, 1760000000))
|
||||
await sessions.state.migrate_history(HISTORY_IMPORT_MARKER, lambda rows: collect_legacy_history(
|
||||
rows, directory=directory,
|
||||
))
|
||||
rows = list_webui_sessions(sessions, await sessions.state.list_metadata())
|
||||
from datetime import datetime
|
||||
|
||||
assert datetime.fromisoformat(rows[0]["updated_at"]).timestamp() == 1760000000
|
||||
assert rows[0]["preview"] == "historical display activity"
|
||||
await sessions.state.aclose()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stored_display", [False, True])
|
||||
async def test_new_fork_activity_uses_creation_time_not_inherited_history(tmp_path, stored_display):
|
||||
from datetime import datetime
|
||||
|
||||
from nanobot.webui.session_list_index import list_webui_sessions
|
||||
|
||||
sessions = _manager(tmp_path)
|
||||
source = await sessions.state.get("websocket:old-source")
|
||||
old_time = datetime(2020, 1, 1)
|
||||
source.add_message("user", "old question", timestamp=old_time.isoformat())
|
||||
source.add_message("assistant", "old answer", timestamp=old_time.isoformat())
|
||||
await sessions.state.finish_turn(source)
|
||||
if stored_display:
|
||||
old_ms = int(old_time.timestamp() * 1000)
|
||||
await sessions.state.append_history(source.key, [
|
||||
HistoryFact(HistoryKind.INPUT, {"text": "old question"}, created_at_ms=old_ms),
|
||||
HistoryFact(HistoryKind.ANSWER, {"text": "old answer"}, created_at_ms=old_ms),
|
||||
HistoryFact(HistoryKind.COMPLETION, created_at_ms=old_ms),
|
||||
], expected_generation=source.generation)
|
||||
forked = await create_webui_chat_fork(sessions, source_chat_id="old-source", before_user_index=1)
|
||||
assert forked is not None
|
||||
_, fork_key = forked
|
||||
fork = await sessions.state.get(fork_key)
|
||||
facts = await sessions.state.project_history(fork_key, lambda history: history.all_facts())
|
||||
assert facts[-1].kind is HistoryKind.FORK_BOUNDARY
|
||||
assert facts[-1].created_at_ms == int(fork.created_at.timestamp() * 1000)
|
||||
rows = list_webui_sessions(sessions, await sessions.state.list_metadata())
|
||||
assert rows[0]["key"] == fork_key
|
||||
await sessions.state.aclose()
|
||||
@@ -35,7 +35,7 @@ def _input(text, turn_id):
|
||||
@pytest.mark.parametrize("count", [1, 2])
|
||||
@pytest.mark.parametrize("leave_unconsumed", [False, True])
|
||||
async def test_late_consumption_commits_history_and_only_its_ids(tmp_path, monkeypatch, count, leave_unconsumed):
|
||||
monkeypatch.setattr("nanobot.webui.transcript.get_webui_dir", lambda: tmp_path / "webui")
|
||||
monkeypatch.setattr("nanobot.webui.history.get_webui_dir", lambda: tmp_path / "webui")
|
||||
sessions = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "sessions")
|
||||
state = sessions.state
|
||||
try:
|
||||
|
||||
@@ -19,7 +19,7 @@ from nanobot.session.recovery import (
|
||||
pending_followups,
|
||||
record_pending_followup,
|
||||
)
|
||||
from nanobot.webui import session_list_index, transcript
|
||||
from nanobot.webui import history as history_module
|
||||
from nanobot.webui.recovery import RecoveryActionError, RecoveryCoordinator
|
||||
|
||||
|
||||
@@ -28,8 +28,8 @@ def _isolate_webui_transcripts(tmp_path: Path, monkeypatch: pytest.MonkeyPatch)
|
||||
"""Recovery scans must discover only test-owned transcripts, not active user chats."""
|
||||
webui_dir = tmp_path / "isolated-webui"
|
||||
webui_dir.mkdir()
|
||||
monkeypatch.setattr(session_list_index, "get_webui_dir", lambda: webui_dir)
|
||||
monkeypatch.setattr(transcript, "get_webui_dir", lambda: webui_dir)
|
||||
monkeypatch.setattr(history_module, "get_webui_dir", lambda: webui_dir)
|
||||
monkeypatch.setattr(history_module, "get_webui_dir", lambda: webui_dir)
|
||||
|
||||
|
||||
def _persist(manager: SessionManager, session: Session) -> None:
|
||||
@@ -69,7 +69,7 @@ async def test_stale_incomplete_transcript_waits_for_confirmation(tmp_path: Path
|
||||
_persist(sessions, session)
|
||||
monkeypatch.setattr(
|
||||
"nanobot.webui.transcript.has_unfinished_transcript_tail",
|
||||
lambda _key: True,
|
||||
lambda _key, **_kwargs: True,
|
||||
)
|
||||
|
||||
coordinator, bus, restarted = _coordinator(tmp_path)
|
||||
@@ -102,7 +102,7 @@ async def test_materialized_interruption_can_continue_from_saved_context(
|
||||
_persist(sessions, session)
|
||||
monkeypatch.setattr(
|
||||
"nanobot.webui.transcript.has_unfinished_transcript_tail",
|
||||
lambda _key: True,
|
||||
lambda _key, **_kwargs: True,
|
||||
)
|
||||
|
||||
coordinator, bus, restarted = _coordinator(tmp_path)
|
||||
@@ -132,8 +132,8 @@ async def test_transcript_only_interruption_is_discovered_without_materializing_
|
||||
) -> None:
|
||||
webui_dir = tmp_path / "webui"
|
||||
webui_dir.mkdir()
|
||||
monkeypatch.setattr(session_list_index, "get_webui_dir", lambda: webui_dir)
|
||||
monkeypatch.setattr(transcript, "get_webui_dir", lambda: webui_dir)
|
||||
monkeypatch.setattr(history_module, "get_webui_dir", lambda: webui_dir)
|
||||
monkeypatch.setattr(history_module, "get_webui_dir", lambda: webui_dir)
|
||||
unfinished_key = "websocket:unfinished"
|
||||
completed_key = "websocket:completed"
|
||||
(webui_dir / f"{SessionManager.safe_key(unfinished_key)}.jsonl").write_text(
|
||||
@@ -155,7 +155,9 @@ async def test_transcript_only_interruption_is_discovered_without_materializing_
|
||||
assert restored.metadata[RECOVERY_METADATA_KEY]["status"] == "awaiting_user"
|
||||
assert restored.metadata[RECOVERY_METADATA_KEY]["reason"] == "interrupted_without_checkpoint"
|
||||
assert restored.metadata[RECOVERY_METADATA_KEY]["can_continue"] is False
|
||||
assert sessions.read_session_metadata(completed_key) is None
|
||||
completed = sessions.get_existing(completed_key)
|
||||
assert completed is not None and completed.messages == []
|
||||
assert RECOVERY_METADATA_KEY not in completed.metadata
|
||||
event = bus.outbound.get_nowait().event
|
||||
assert isinstance(event, RecoveryStateEvent)
|
||||
assert event.status == "awaiting_user"
|
||||
@@ -196,7 +198,7 @@ async def test_scan_loads_only_sessions_that_need_webui_recovery(
|
||||
monkeypatch.setattr(restarted.state, "get", tracked_get_or_create)
|
||||
monkeypatch.setattr(
|
||||
"nanobot.webui.transcript.has_unfinished_transcript_tail",
|
||||
lambda _key: False,
|
||||
lambda _key, **_kwargs: False,
|
||||
)
|
||||
|
||||
await coordinator.scan()
|
||||
|
||||
@@ -86,7 +86,7 @@ def test_ordered_upgrades_preserve_records_and_do_not_repeat_import(tmp_path, mo
|
||||
source.write_text("stale malformed source must not be imported again", encoding="utf-8")
|
||||
upgraded = SqliteSessionStore(tmp_path)
|
||||
upgraded.initialize(workspace)
|
||||
assert _database_snapshot(store.path)[0] == 3
|
||||
assert _database_snapshot(store.path)[0] == len(sqlite_store._SCHEMA_MIGRATIONS)
|
||||
loaded = upgraded.load(original.key)
|
||||
assert loaded is not None
|
||||
assert loaded.messages == original.messages
|
||||
@@ -138,7 +138,7 @@ def test_failed_upgrade_rolls_back_schema_version_and_records_then_can_retry(tmp
|
||||
*migrations, add_archived, complete_upgrade,
|
||||
))
|
||||
store.initialize(workspace)
|
||||
assert _database_snapshot(store.path)[0] == 3
|
||||
assert _database_snapshot(store.path)[0] == len(sqlite_store._SCHEMA_MIGRATIONS)
|
||||
loaded = store.load(original.key)
|
||||
assert loaded is not None
|
||||
assert loaded.messages == original.messages
|
||||
|
||||
@@ -1,14 +1,12 @@
|
||||
import importlib
|
||||
|
||||
from nanobot.session import webui_turns
|
||||
from nanobot.webui import thread_disk, transcript
|
||||
from nanobot.webui import transcript
|
||||
|
||||
|
||||
def test_legacy_webui_utils_imports_resolve_to_new_modules() -> None:
|
||||
legacy_thread_disk = importlib.import_module("nanobot.utils.webui_thread_disk")
|
||||
legacy_transcript = importlib.import_module("nanobot.utils.webui_transcript")
|
||||
legacy_turn_helpers = importlib.import_module("nanobot.utils.webui_turn_helpers")
|
||||
|
||||
assert legacy_thread_disk.delete_webui_thread is thread_disk.delete_webui_thread
|
||||
assert legacy_transcript.append_transcript_object is transcript.append_transcript_object
|
||||
assert legacy_turn_helpers.mark_webui_session is webui_turns.mark_webui_session
|
||||
@@ -1,38 +0,0 @@
|
||||
"""Tests for WebUI on-disk cleanup (legacy JSON + transcript JSONL)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from nanobot.webui.thread_disk import delete_webui_thread, webui_thread_file_path
|
||||
from nanobot.webui.transcript import (
|
||||
append_transcript_object,
|
||||
webui_transcript_path,
|
||||
webui_transcript_segments_dir,
|
||||
)
|
||||
|
||||
|
||||
def test_delete_webui_thread_removes_legacy_json_and_transcript(tmp_path, monkeypatch) -> None:
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
monkeypatch.setattr("nanobot.webui.transcript._MAX_TRANSCRIPT_FILE_BYTES", 520)
|
||||
monkeypatch.setattr("nanobot.webui.transcript._ACTIVE_TRANSCRIPT_ROTATE_BYTES", 520)
|
||||
monkeypatch.setattr("nanobot.webui.transcript._TARGET_ACTIVE_TRANSCRIPT_BYTES", 260)
|
||||
key = "websocket:k1"
|
||||
json_path = webui_thread_file_path(key)
|
||||
json_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
json_path.write_text('{"x":1}', encoding="utf-8")
|
||||
for idx in range(1, 5):
|
||||
append_transcript_object(
|
||||
key,
|
||||
{"event": "user", "chat_id": "k1", "text": f"question {idx} " + ("x" * 24)},
|
||||
)
|
||||
append_transcript_object(
|
||||
key,
|
||||
{"event": "message", "chat_id": "k1", "text": f"answer {idx} " + ("y" * 24)},
|
||||
)
|
||||
append_transcript_object(key, {"event": "turn_end", "chat_id": "k1"})
|
||||
assert webui_transcript_path(key).is_file()
|
||||
assert webui_transcript_segments_dir(key).is_dir()
|
||||
assert delete_webui_thread(key) is True
|
||||
assert not json_path.is_file()
|
||||
assert not webui_transcript_path(key).is_file()
|
||||
assert not webui_transcript_segments_dir(key).exists()
|
||||
assert delete_webui_thread(key) is False
|
||||
File diff suppressed because it is too large.
Load diff
@@ -310,7 +310,7 @@ async def test_session_input_is_projected_by_the_webui_coordinator(
|
||||
"source_session_key": "websocket:source",
|
||||
"target_session_key": "websocket:target",
|
||||
}
|
||||
append_input = MagicMock()
|
||||
append_input = AsyncMock()
|
||||
monkeypatch.setattr(wth, "append_session_message_input", append_input)
|
||||
coordinator = wth.WebuiTurnCoordinator(
|
||||
bus=bus,
|
||||
@@ -324,12 +324,14 @@ async def test_session_input_is_projected_by_the_webui_coordinator(
|
||||
channel="system",
|
||||
chat_id="websocket:target",
|
||||
session_key="websocket:target",
|
||||
session_generation=target_session.generation,
|
||||
metadata={SESSION_MESSAGE_METADATA_KEY: envelope},
|
||||
),
|
||||
content="Review this",
|
||||
))
|
||||
|
||||
append_input.assert_called_once()
|
||||
append_input.assert_awaited_once()
|
||||
assert append_input.await_args.kwargs["expected_generation"] == target_session.generation
|
||||
outbound = bus.publish_outbound.await_args.args[0]
|
||||
assert outbound.channel == "websocket"
|
||||
assert outbound.chat_id == "target"
|
||||
|
||||
+33
-75
@@ -8,81 +8,6 @@ import pytest
|
||||
import nanobot.webui.forking as forking
|
||||
|
||||
|
||||
async def test_create_fork_rebuilds_missing_transcript_and_saves_clean_title(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
forked = SimpleNamespace(messages=[{"role": "user", "content": "hello"}], metadata={})
|
||||
manager = MagicMock()
|
||||
manager.state.fork = AsyncMock(return_value=forked)
|
||||
rebuild = MagicMock()
|
||||
marker = MagicMock()
|
||||
monkeypatch.setattr(forking.uuid, "uuid4", lambda: "fork-id")
|
||||
monkeypatch.setattr(forking, "fork_transcript_before_user_index", lambda *_args: False)
|
||||
monkeypatch.setattr(forking, "write_session_messages_as_transcript", rebuild)
|
||||
monkeypatch.setattr(forking, "append_fork_marker", marker)
|
||||
|
||||
result = await forking.create_webui_chat_fork(
|
||||
manager,
|
||||
source_chat_id="source",
|
||||
before_user_index=2,
|
||||
title=" Useful fork ",
|
||||
)
|
||||
|
||||
assert result == ("fork-id", "websocket:fork-id")
|
||||
manager.state.fork.assert_awaited_once_with(
|
||||
"websocket:source",
|
||||
"websocket:fork-id",
|
||||
2,
|
||||
title="Useful fork",
|
||||
)
|
||||
rebuild.assert_called_once_with("websocket:fork-id", forked.messages)
|
||||
marker.assert_called_once_with("websocket:fork-id")
|
||||
|
||||
|
||||
async def test_create_fork_rolls_back_session_and_transcript_together(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
manager = MagicMock()
|
||||
manager.state.fork = AsyncMock(return_value=SimpleNamespace(messages=[], metadata={}))
|
||||
manager.state.delete = AsyncMock()
|
||||
delete_transcript = MagicMock()
|
||||
monkeypatch.setattr(forking.uuid, "uuid4", lambda: "failed-fork")
|
||||
monkeypatch.setattr(
|
||||
forking,
|
||||
"fork_transcript_before_user_index",
|
||||
MagicMock(side_effect=OSError("disk full")),
|
||||
)
|
||||
monkeypatch.setattr(forking, "delete_webui_transcript", delete_transcript)
|
||||
|
||||
with pytest.raises(OSError, match="disk full"):
|
||||
await forking.create_webui_chat_fork(
|
||||
manager,
|
||||
source_chat_id="source",
|
||||
before_user_index=1,
|
||||
)
|
||||
|
||||
delete_transcript.assert_called_once_with("websocket:failed-fork")
|
||||
manager.state.delete.assert_awaited_once_with("websocket:failed-fork")
|
||||
|
||||
|
||||
async def test_create_fork_stops_before_transcript_work_when_source_is_invalid(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
manager = MagicMock()
|
||||
manager.state.fork = AsyncMock(return_value=None)
|
||||
fork_transcript = MagicMock()
|
||||
monkeypatch.setattr(forking, "fork_transcript_before_user_index", fork_transcript)
|
||||
|
||||
result = await forking.create_webui_chat_fork(
|
||||
manager,
|
||||
source_chat_id="missing",
|
||||
before_user_index=1,
|
||||
)
|
||||
|
||||
assert result is None
|
||||
fork_transcript.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("envelope", "detail"),
|
||||
[
|
||||
@@ -157,3 +82,36 @@ async def test_fork_handler_maps_invalid_source_and_internal_failure_to_stable_e
|
||||
|
||||
warning.assert_called_once_with("fork_chat failed: {}", ANY)
|
||||
channel.send_webui_protocol_error.assert_awaited_once_with(connection, "fork_chat_failed")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("with_display", [False, True])
|
||||
async def test_fork_copies_prefix_and_boundary_in_the_session_transaction(history, monkeypatch, with_display):
|
||||
sessions = history.sessions
|
||||
source = sessions.get_or_create("websocket:source")
|
||||
source.metadata.update(title="source title", session_handle="original", webui=True)
|
||||
for number in range(3):
|
||||
source.add_message("user", f"question {number}")
|
||||
source.add_message("assistant", f"answer {number}")
|
||||
sessions.save(source)
|
||||
if with_display:
|
||||
for number in range(3):
|
||||
history.append(source.key, {"event": "user", "text": f"question {number}"})
|
||||
history.append(source.key, {"event": "message", "text": f"answer {number}"})
|
||||
history.append(source.key, {"event": "turn_end"})
|
||||
monkeypatch.setattr(forking.uuid, "uuid4", lambda: "fork-id")
|
||||
result = await forking.create_webui_chat_fork(sessions, source_chat_id="source", before_user_index=2, title=" Useful fork ")
|
||||
assert result == ("fork-id", "websocket:fork-id")
|
||||
forked = await sessions.state.get(result[1])
|
||||
assert [message["content"] for message in forked.messages] == ["question 0", "answer 0", "question 1", "answer 1"]
|
||||
assert forked.metadata["title"] == "Useful fork"
|
||||
assert forked.metadata.get("session_handle") != "original"
|
||||
payload = history.build(forked.key)
|
||||
visible = [event["text"] for event in payload["events"] if "text" in event]
|
||||
assert visible == ["question 0", "answer 0", "question 1", "answer 1"]
|
||||
assert payload["fork_boundary_event_index"] == len(payload["events"])
|
||||
assert (await sessions.state.get(source.key)).messages == source.messages
|
||||
|
||||
|
||||
async def test_fork_missing_source_leaves_no_partial_session(history):
|
||||
assert await forking.create_webui_chat_fork(history.sessions, source_chat_id="missing", before_user_index=1) is None
|
||||
assert await history.sessions.state.list_sessions() == []
|
||||
@@ -15,60 +15,57 @@ from nanobot.webui.client_contract import webui_contract
|
||||
from nanobot.webui.gateway_services import build_gateway_services
|
||||
|
||||
|
||||
def test_complete_index_and_bidirectional_pages_without_loading_sqlite(tmp_path, monkeypatch):
|
||||
def test_complete_index_and_bidirectional_pages_without_loading_model_messages(history, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
monkeypatch.setattr(transcript, "_ACTIVE_TRANSCRIPT_ROTATE_BYTES", 2000)
|
||||
monkeypatch.setattr(transcript, "_TARGET_ACTIVE_TRANSCRIPT_BYTES", 1000)
|
||||
key = "websocket:navigation"
|
||||
for i in range(120):
|
||||
transcript.append_transcript_object(key, {"event": "user", "chat_id": "navigation", "text": f"question {i}", "turn_id": f"t{i}"})
|
||||
transcript.append_transcript_object(key, {"event": "message", "chat_id": "navigation", "text": "answer " + "x" * 200, "turn_id": f"t{i}"})
|
||||
transcript.append_transcript_object(key, {"event": "turn_end", "chat_id": "navigation", "turn_id": f"t{i}"})
|
||||
index = transcript.build_prompt_index(key)
|
||||
history.append(key, {"event": "user", "chat_id": "navigation", "text": f"question {i}", "turn_id": f"t{i}"})
|
||||
history.append(key, {"event": "message", "chat_id": "navigation", "text": "answer " + "x" * 200, "turn_id": f"t{i}"})
|
||||
history.append(key, {"event": "turn_end", "chat_id": "navigation", "turn_id": f"t{i}"})
|
||||
index = history.prompts(key)
|
||||
assert len(index) == 120
|
||||
assert not (tmp_path / "sessions" / "sessions.sqlite3").exists()
|
||||
latest = transcript.build_webui_thread_response(key, limit=3)
|
||||
latest = history.build(key, limit=3)
|
||||
assert len(latest["events"]) < len(index)
|
||||
target = index[42]
|
||||
stats = transcript.TranscriptReplayStats()
|
||||
page = transcript.build_webui_thread_response(key, after=target["cursor"], limit=6, stats=stats)
|
||||
page = history.build(key, after=target["cursor"], limit=6, stats=stats)
|
||||
assert page["events"][0]["projection_id"] == target["id"]
|
||||
assert page["events"][0]["text"] == "question 42"
|
||||
assert page["page"]["user_message_offset"] == 42
|
||||
assert page["page"]["has_more_before"] and page["page"]["has_more_after"]
|
||||
assert stats.parsed_records < 40 # Not the 360-record transcript.
|
||||
newer = transcript.build_webui_thread_response(key, after=page["page"]["after_cursor"], limit=6)
|
||||
older = transcript.build_webui_thread_response(key, before=newer["page"]["before_cursor"], limit=6)
|
||||
newer = history.build(key, after=page["page"]["after_cursor"], limit=6)
|
||||
older = history.build(key, before=newer["page"]["before_cursor"], limit=6)
|
||||
assert older["events"] == page["events"]
|
||||
# Warm navigation uses file metadata + cached summaries, not replay.
|
||||
# Warm navigation uses the committed revision and cached summaries.
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr(transcript, "_read_transcript_file", lambda _: (_ for _ in ()).throw(AssertionError("replayed history")))
|
||||
assert transcript.build_prompt_index(key) == index
|
||||
transcript.append_transcript_object(key, {"event": "user", "chat_id": "navigation", "text": "new question"})
|
||||
assert len(transcript.build_prompt_index(key)) == 121
|
||||
patch.setattr("nanobot.session.display_history.HistoryReader.navigation", lambda _: (_ for _ in ()).throw(AssertionError("replayed history")))
|
||||
assert history.prompts(key) == index
|
||||
history.append(key, {"event": "user", "chat_id": "navigation", "text": "new question"})
|
||||
assert len(history.prompts(key)) == 121
|
||||
|
||||
|
||||
def test_oversized_turn_keeps_matching_navigation_identity(tmp_path, monkeypatch):
|
||||
def test_oversized_turn_keeps_matching_navigation_identity(history, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_RECORDS", 6)
|
||||
key = "websocket:large-turn"
|
||||
transcript.append_transcript_object(key, {"event": "user", "chat_id": "large-turn", "text": "target"})
|
||||
history.append(key, {"event": "user", "chat_id": "large-turn", "text": "target"})
|
||||
for i in range(20):
|
||||
transcript.append_transcript_object(key, {"event": "message", "chat_id": "large-turn", "kind": "tool_hint", "text": str(i)})
|
||||
transcript.append_transcript_object(key, {"event": "message", "chat_id": "large-turn", "text": "done"})
|
||||
transcript.append_transcript_object(key, {"event": "turn_end", "chat_id": "large-turn"})
|
||||
target = transcript.build_prompt_index(key)[0]
|
||||
page = transcript.build_webui_thread_response(key, after=target["cursor"], limit=40)
|
||||
history.append(key, {"event": "message", "chat_id": "large-turn", "kind": "tool_hint", "text": str(i)})
|
||||
history.append(key, {"event": "message", "chat_id": "large-turn", "text": "done"})
|
||||
history.append(key, {"event": "turn_end", "chat_id": "large-turn"})
|
||||
target = history.prompts(key)[0]
|
||||
page = history.build(key, after=target["cursor"], limit=40)
|
||||
assert page["page"]["truncated_oversized_turn"]
|
||||
assert page["events"][0]["projection_id"] == target["id"]
|
||||
assert len(target["answerPreview"]) <= 240
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_navigation_public_routes_auth_validation_and_old_reads(tmp_path, monkeypatch):
|
||||
async def test_navigation_public_routes_auth_validation_and_old_reads(history, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
gateway = build_gateway_services(
|
||||
config=WebSocketConfig(), bus=MessageBus(), session_manager=None,
|
||||
config=WebSocketConfig(), bus=MessageBus(), session_manager=history.sessions,
|
||||
static_dist_path=None, workspace_path=tmp_path, config_path=tmp_path / "config.json",
|
||||
default_restrict_to_workspace=False, runtime_model_name=None,
|
||||
runtime_surface="browser", runtime_capabilities_overrides=None,
|
||||
@@ -78,7 +75,7 @@ async def test_navigation_public_routes_auth_validation_and_old_reads(tmp_path,
|
||||
assert denied.status_code == 401
|
||||
gateway.tokens.api_tokens["test-token"] = time.monotonic() + 60
|
||||
headers = Headers([("Authorization", "Bearer test-token")])
|
||||
transcript.append_transcript_object("websocket:test", {"event": "user", "chat_id": "test", "text": "hello"})
|
||||
history.append("websocket:test", {"event": "user", "chat_id": "test", "text": "hello"})
|
||||
response = await gateway.http._dispatch_session_routes(Request(path + "/prompts", headers), path + "/prompts")
|
||||
prompt = json.loads(response.body)["prompts"][0]
|
||||
revision = json.loads(response.body)["revision"]
|
||||
@@ -96,37 +93,37 @@ async def test_navigation_public_routes_auth_validation_and_old_reads(tmp_path,
|
||||
assert "webui.prompt-navigation.v1" in webui_contract()["capabilities"]
|
||||
|
||||
|
||||
def test_summary_deltas_rebuild_after_append_rewrite_eviction_and_delete(tmp_path, monkeypatch):
|
||||
def test_summary_deltas_rebuild_after_append_rewrite_eviction_and_delete(history, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
key = "websocket:index-delta"
|
||||
for i in range(100):
|
||||
transcript.append_transcript_object(key, {"event": "user", "text": f"question {i}", "turn_id": f"t{i}"})
|
||||
transcript.append_transcript_object(key, {"event": "turn_end", "turn_id": f"t{i}"})
|
||||
initial = transcript.prompt_index_response(key, None)
|
||||
history.append(key, {"event": "user", "text": f"question {i}", "turn_id": f"t{i}"})
|
||||
history.append(key, {"event": "turn_end", "turn_id": f"t{i}"})
|
||||
initial = history.prompt_response(key, None)
|
||||
assert len(initial["prompts"]) == 100
|
||||
transcript.append_transcript_object(key, {"event": "user", "text": "next", "turn_id": "next"})
|
||||
appended = transcript.prompt_index_response(key, initial["revision"])
|
||||
history.append(key, {"event": "user", "text": "next", "turn_id": "next"})
|
||||
appended = history.prompt_response(key, initial["revision"])
|
||||
assert appended["replaceFrom"] == 100
|
||||
assert len(appended["prompts"]) == 1
|
||||
assert [*initial["prompts"], *appended["prompts"]] == transcript.build_prompt_index(key)
|
||||
assert [*initial["prompts"], *appended["prompts"]] == history.prompts(key)
|
||||
# A late answer changes the last preview; it must replace that prompt, not append it.
|
||||
transcript.append_transcript_object(key, {"event": "message", "text": "answer", "turn_id": "next"})
|
||||
changed = transcript.prompt_index_response(key, appended["revision"])
|
||||
history.append(key, {"event": "message", "text": "answer", "turn_id": "next"})
|
||||
changed = history.prompt_response(key, appended["revision"])
|
||||
assert changed["replaceFrom"] == 100
|
||||
assert changed["prompts"][0]["answerPreview"] == "answer"
|
||||
transcript.delete_webui_transcript(key)
|
||||
transcript.append_transcript_object(key, {"event": "user", "text": "replacement"})
|
||||
replaced = transcript.prompt_index_response(key, changed["revision"])
|
||||
history.sessions.delete_session(key)
|
||||
history.append(key, {"event": "user", "text": "replacement"})
|
||||
replaced = history.prompt_response(key, changed["revision"])
|
||||
assert replaced["replaceFrom"] == 0
|
||||
assert len(replaced["prompts"]) == 1
|
||||
transcript._PROMPT_SNAPSHOTS.clear() # Restart/eviction sends a complete response.
|
||||
assert transcript.prompt_index_response(key, replaced["revision"])["replaceFrom"] == 0
|
||||
transcript.delete_webui_transcript(key)
|
||||
assert transcript.prompt_index_response(key, replaced["revision"])["prompts"] == ()
|
||||
assert history.prompt_response(key, replaced["revision"])["replaceFrom"] == 0
|
||||
history.sessions.delete_session(key)
|
||||
assert history.prompt_response(key, replaced["revision"])["prompts"] == ()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("input_id", [None, "injected-guidance"])
|
||||
def test_recovered_prompt_identity_time_and_cursor_survive_pages(tmp_path, monkeypatch, input_id):
|
||||
def test_recovered_prompt_identity_time_and_cursor_survive_pages(history, tmp_path, monkeypatch, input_id):
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
key = "websocket:recovered-navigation"
|
||||
messages = [{"role": "system", "content": "context"}]
|
||||
@@ -135,31 +132,31 @@ def test_recovered_prompt_identity_time_and_cursor_survive_pages(tmp_path, monke
|
||||
if input_id:
|
||||
user["webui_turn_id"] = f"{input_id}-{i}"
|
||||
messages.extend([user, {"role": "assistant", "content": f"answer {i}"}])
|
||||
transcript.append_transcript_object(key, {"event": "message", "text": f"answer {i}", "turn_id": f"execution-{i}"})
|
||||
transcript.append_transcript_object(key, {"event": "turn_end", "turn_id": f"execution-{i}"})
|
||||
history.append(key, {"event": "message", "text": f"answer {i}", "turn_id": f"execution-{i}"})
|
||||
history.append(key, {"event": "turn_end", "turn_id": f"execution-{i}"})
|
||||
def loader():
|
||||
return messages
|
||||
|
||||
cold_page = transcript.build_webui_thread_response(key, limit=1, session_messages_loader=loader)
|
||||
index = transcript.build_prompt_index(key, session_messages_loader=loader)
|
||||
assert transcript.build_webui_thread_response(key, limit=1, session_messages_loader=loader) == cold_page
|
||||
cold_page = history.build(key, limit=1, session_messages_loader=loader)
|
||||
index = history.prompts(key, session_messages_loader=loader)
|
||||
assert history.build(key, limit=1, session_messages_loader=loader) == cold_page
|
||||
assert len(index) == 2
|
||||
assert index[0]["id"] != index[1]["id"]
|
||||
assert [prompt["createdAt"] for prompt in index] == [1780394400000, 1780394460000]
|
||||
for position, prompt in enumerate(index):
|
||||
page = transcript.build_webui_thread_response(key, after=prompt["cursor"], limit=1, session_messages_loader=loader)
|
||||
page = history.build(key, after=prompt["cursor"], limit=1, session_messages_loader=loader)
|
||||
user = next(event for event in page["events"] if event["event"] == "user_message")
|
||||
assert user["projection_id"] == prompt["id"]
|
||||
assert user["created_at_ms"] == prompt["createdAt"]
|
||||
assert user.get("turn_id") == (f"{input_id}-{position}" if input_id else None)
|
||||
assert transcript.build_prompt_index(key, session_messages_loader=loader) == index
|
||||
assert history.prompts(key, session_messages_loader=loader) == index
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_recovered_public_index_and_page_validators_include_canonical_timestamp(tmp_path, monkeypatch):
|
||||
async def test_recovered_public_index_and_page_validators_include_canonical_timestamp(history, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
key = "websocket:canonical-revision"
|
||||
manager = SessionManager(tmp_path)
|
||||
manager = history.sessions
|
||||
session = manager.get_or_create(key)
|
||||
session.messages = [
|
||||
{"role": "user", "content": "guidance", "webui_turn_id": "input", "timestamp": "2026-06-02T10:00:00+00:00"},
|
||||
@@ -167,7 +164,7 @@ async def test_recovered_public_index_and_page_validators_include_canonical_time
|
||||
]
|
||||
manager.save(session)
|
||||
for event in ({"event": "message", "text": "answer"}, {"event": "turn_end"}):
|
||||
transcript.append_transcript_object(key, event)
|
||||
history.append(key, event)
|
||||
gateway = build_gateway_services(
|
||||
config=WebSocketConfig(), bus=MessageBus(), session_manager=manager,
|
||||
static_dist_path=None, workspace_path=tmp_path, config_path=tmp_path / "config.json",
|
||||
@@ -188,8 +185,9 @@ async def test_recovered_public_index_and_page_validators_include_canonical_time
|
||||
assert unchanged.status_code == 304
|
||||
# A canonical-only update must invalidate the recovered display even when
|
||||
# transcript artifacts and the session's updated_at are unchanged.
|
||||
session = await manager.state.get(key)
|
||||
session.messages[0]["timestamp"] = "2026-06-02T10:01:00+00:00"
|
||||
manager.save(session)
|
||||
await manager.state.finish_turn(session)
|
||||
changed = {}
|
||||
for path, previous in initial.items():
|
||||
request_path = path + "?since=" + json.loads(previous.body)["revision"]
|
||||
@@ -208,20 +206,21 @@ async def test_recovered_public_index_and_page_validators_include_canonical_time
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("missing_user", [False, True])
|
||||
async def test_cached_history_routes_skip_replay_and_canonical_reads(tmp_path, monkeypatch, missing_user):
|
||||
async def test_cached_history_routes_skip_replay_and_canonical_reads(history, tmp_path, monkeypatch, missing_user):
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
key = "websocket:cached-history"
|
||||
manager = SessionManager(tmp_path)
|
||||
manager = history.sessions
|
||||
session = manager.get_or_create(key)
|
||||
manager.save(session)
|
||||
for i in range(3):
|
||||
session.messages.extend([
|
||||
{"role": "user", "content": f"question {i}", "webui_turn_id": f"input-{i}"},
|
||||
{"role": "assistant", "content": f"answer {i}"},
|
||||
])
|
||||
if not missing_user or i < 2:
|
||||
transcript.append_transcript_object(key, {"event": "user", "text": f"question {i}", "turn_id": f"input-{i}"})
|
||||
transcript.append_transcript_object(key, {"event": "message", "text": f"answer {i}"})
|
||||
transcript.append_transcript_object(key, {"event": "turn_end"})
|
||||
history.append(key, {"event": "user", "text": f"question {i}", "turn_id": f"input-{i}"})
|
||||
history.append(key, {"event": "message", "text": f"answer {i}"})
|
||||
history.append(key, {"event": "turn_end"})
|
||||
manager.save(session)
|
||||
gateway = build_gateway_services(
|
||||
config=WebSocketConfig(), bus=MessageBus(), session_manager=manager,
|
||||
@@ -244,7 +243,7 @@ async def test_cached_history_routes_skip_replay_and_canonical_reads(tmp_path, m
|
||||
pytest.fail("unchanged history was rebuilt")
|
||||
|
||||
monkeypatch.setattr(transcript, "_build_prompt_view", unexpected_work)
|
||||
monkeypatch.setattr(transcript, "_read_transcript_file", unexpected_work)
|
||||
monkeypatch.setattr("nanobot.session.display_history.HistoryReader.navigation", unexpected_work)
|
||||
monkeypatch.setattr(manager, "read_session_file", unexpected_work)
|
||||
monkeypatch.setattr("nanobot.webui.ws_http.build_webui_thread_response", unexpected_work)
|
||||
for path, previous in initial.items():
|
||||
@@ -271,10 +270,10 @@ async def test_cached_history_routes_skip_replay_and_canonical_reads(tmp_path, m
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("endpoint", ["", "/prompts"])
|
||||
async def test_canonical_change_during_recovery_is_not_cached(tmp_path, monkeypatch, endpoint):
|
||||
async def test_canonical_change_during_recovery_keeps_a_consistent_snapshot(history, tmp_path, monkeypatch, endpoint):
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
key = "websocket:racing-history"
|
||||
manager = SessionManager(tmp_path)
|
||||
manager = history.sessions
|
||||
session = manager.get_or_create(key)
|
||||
session.messages = [
|
||||
{"role": "user", "content": "question", "timestamp": "2026-06-02T10:00:00+00:00"},
|
||||
@@ -282,7 +281,7 @@ async def test_canonical_change_during_recovery_is_not_cached(tmp_path, monkeypa
|
||||
]
|
||||
manager.save(session)
|
||||
for event in ({"event": "message", "text": "answer"}, {"event": "turn_end"}):
|
||||
transcript.append_transcript_object(key, event)
|
||||
history.append(key, event)
|
||||
gateway = build_gateway_services(
|
||||
config=WebSocketConfig(), bus=MessageBus(), session_manager=manager,
|
||||
static_dist_path=None, workspace_path=tmp_path, config_path=tmp_path / "config.json",
|
||||
@@ -292,6 +291,7 @@ async def test_canonical_change_during_recovery_is_not_cached(tmp_path, monkeypa
|
||||
gateway.tokens.api_tokens["test-token"] = time.monotonic() + 60
|
||||
auth = Headers([("Authorization", "Bearer test-token")])
|
||||
original_read = manager.read_session_file
|
||||
external = SessionManager(tmp_path)
|
||||
changed = False
|
||||
|
||||
def read_and_commit(key):
|
||||
@@ -299,17 +299,18 @@ async def test_canonical_change_during_recovery_is_not_cached(tmp_path, monkeypa
|
||||
data = original_read(key)
|
||||
if not changed:
|
||||
changed = True
|
||||
session.messages[0]["timestamp"] = "2026-06-02T10:01:00+00:00"
|
||||
manager.save(session)
|
||||
update = external.get_or_create(key)
|
||||
update.messages[0]["timestamp"] = "2026-06-02T10:01:00+00:00"
|
||||
external.save(update)
|
||||
return data
|
||||
|
||||
monkeypatch.setattr(manager, "read_session_file", read_and_commit)
|
||||
path = "/api/sessions/websocket%3Aracing-history/webui-thread" + endpoint
|
||||
mixed = await gateway.http._dispatch_session_routes(Request(path, auth), path)
|
||||
assert changed and mixed.status_code == 200
|
||||
assert "ETag" not in mixed.headers and "revision" not in json.loads(mixed.body)
|
||||
assert mixed.headers["ETag"] and json.loads(mixed.body)["revision"]
|
||||
current = await gateway.http._dispatch_session_routes(Request(path, auth), path)
|
||||
assert current.status_code == 200 and current.headers["ETag"]
|
||||
assert current.status_code == 200 and current.headers["ETag"] != mixed.headers["ETag"]
|
||||
data = json.loads(current.body)
|
||||
if endpoint:
|
||||
assert data["prompts"][0]["createdAt"] == 1780394460000
|
||||
@@ -319,7 +320,7 @@ async def test_canonical_change_during_recovery_is_not_cached(tmp_path, monkeypa
|
||||
|
||||
|
||||
@pytest.mark.parametrize("with_anchor", [False, True])
|
||||
def test_indexed_backfill_preserves_unique_in_suffix_matching(tmp_path, monkeypatch, with_anchor):
|
||||
def test_indexed_backfill_preserves_unique_in_suffix_matching(history, tmp_path, monkeypatch, with_anchor):
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
key = "websocket:repeated-answers"
|
||||
answers = ["same answer", "anchor answer", "same answer"] if with_anchor else ["same answer"] * 2
|
||||
@@ -328,13 +329,13 @@ def test_indexed_backfill_preserves_unique_in_suffix_matching(tmp_path, monkeypa
|
||||
user = {"role": "user", "content": f"question {position}", "webui_turn_id": f"input-{position}"}
|
||||
messages.extend([user, {"role": "assistant", "content": answer}])
|
||||
if position < len(answers) - 1:
|
||||
transcript.append_transcript_object(key, {"event": "user", "text": user["content"], "turn_id": user["webui_turn_id"]})
|
||||
transcript.append_transcript_object(key, {"event": "message", "text": answer})
|
||||
transcript.append_transcript_object(key, {"event": "turn_end"})
|
||||
prompts = transcript.build_prompt_index(key, session_messages_loader=lambda: messages)
|
||||
history.append(key, {"event": "user", "text": user["content"], "turn_id": user["webui_turn_id"]})
|
||||
history.append(key, {"event": "message", "text": answer})
|
||||
history.append(key, {"event": "turn_end"})
|
||||
prompts = history.prompts(key, session_messages_loader=lambda: messages)
|
||||
# A unique intervening answer advances the alignment past the first duplicate.
|
||||
assert len(prompts) == (len(answers) if with_anchor else 1)
|
||||
page = transcript.build_webui_thread_response(key, limit=1, session_messages=messages)
|
||||
page = history.build(key, limit=1, session_messages=messages)
|
||||
users = [event for event in page["events"] if event["event"] == "user_message"]
|
||||
assert [user["text"] for user in users] == (["question 2"] if with_anchor else [])
|
||||
if with_anchor:
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
@@ -21,13 +19,6 @@ from nanobot.session.recovery import RECOVERY_METADATA_KEY
|
||||
from nanobot.session.types import SESSION_TYPE_KEY, SessionType
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _isolate_webui_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
webui_dir = tmp_path / "webui"
|
||||
webui_dir.mkdir(exist_ok=True)
|
||||
monkeypatch.setattr(session_list_index, "get_webui_dir", lambda: webui_dir)
|
||||
|
||||
|
||||
def test_webui_session_list_reads_previews_without_loading_history(tmp_path, monkeypatch):
|
||||
manager = SessionManager(tmp_path)
|
||||
session = manager.get_or_create("websocket:indexed")
|
||||
@@ -41,164 +32,12 @@ def test_webui_session_list_reads_previews_without_loading_history(tmp_path, mon
|
||||
|
||||
monkeypatch.setattr(manager._store, "load", fail_load)
|
||||
monkeypatch.setattr(manager, "read_session_metadata", fail_load)
|
||||
monkeypatch.setattr(session_list_index, "_read_index_rows", fail_load)
|
||||
monkeypatch.setattr(session_list_index, "_write_index_rows", fail_load)
|
||||
rows = list_webui_sessions(manager)
|
||||
assert rows[0]["key"] == "websocket:indexed"
|
||||
assert rows[0]["preview"] == "indexed preview"
|
||||
assert rows[0]["model_preset"] == "fast"
|
||||
|
||||
|
||||
def test_webui_session_list_private_rows_suppress_transcript_fallback(tmp_path, monkeypatch):
|
||||
manager = SessionManager(tmp_path)
|
||||
manager.types.register(SessionType("internal", needs_handle=False, public_history=False))
|
||||
webui_dir = tmp_path / "webui"
|
||||
private_key, transcript_key = "websocket:internal", "websocket:transcript-only"
|
||||
for key in (private_key, transcript_key):
|
||||
(webui_dir / f"{SessionManager.safe_key(key)}.jsonl").write_text(
|
||||
json.dumps({"event": "user", "chat_id": key.removeprefix("websocket:"),
|
||||
"text": "transcript preview"}) + "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
assert {row["key"] for row in list_webui_sessions(manager)} == {private_key, transcript_key}
|
||||
|
||||
public = manager.get_or_create("websocket:public")
|
||||
public.add_message("user", "public preview")
|
||||
manager.save(public)
|
||||
private = manager.get_or_create(private_key)
|
||||
private.metadata[SESSION_TYPE_KEY] = "internal"
|
||||
private.add_message("user", "private preview")
|
||||
manager.save(private)
|
||||
unknown = manager.get_or_create("websocket:unregistered")
|
||||
unknown.metadata[SESSION_TYPE_KEY] = "unregistered"
|
||||
manager.save(unknown)
|
||||
|
||||
def individual_metadata_unavailable(*_args, **_kwargs):
|
||||
pytest.fail("sidebar visibility must use the existing metadata query snapshot")
|
||||
|
||||
monkeypatch.setattr(manager, "read_session_metadata", individual_metadata_unavailable)
|
||||
rows = {row["key"]: row for row in list_webui_sessions(manager)}
|
||||
assert set(rows) == {public.key, transcript_key}
|
||||
assert rows[public.key]["preview"] == "public preview"
|
||||
assert rows[transcript_key]["preview"] == "transcript preview"
|
||||
assert {row["key"] for row in list_webui_sessions(manager)} == set(rows)
|
||||
|
||||
|
||||
def test_webui_session_list_scans_empty_display_directory_once_per_request(tmp_path, monkeypatch):
|
||||
manager = SessionManager(tmp_path)
|
||||
keys = {"websocket:first", "websocket:second", "websocket:third"}
|
||||
for key in keys:
|
||||
manager.save(manager.get_or_create(key))
|
||||
list_webui_sessions(manager)
|
||||
webui_dir = tmp_path / "webui"
|
||||
original_stat, original_scandir = Path.stat, os.scandir
|
||||
scans = []
|
||||
|
||||
def stored_files_only(path, *args, **kwargs):
|
||||
assert path.parent != webui_dir, "sidebar must not probe absent per-session display files"
|
||||
return original_stat(path, *args, **kwargs)
|
||||
|
||||
def scan(path):
|
||||
scans.append(Path(path))
|
||||
return original_scandir(path)
|
||||
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr(Path, "stat", stored_files_only)
|
||||
patch.setattr(session_list_index.os, "scandir", scan)
|
||||
for _ in range(2):
|
||||
assert {row["key"] for row in list_webui_sessions(manager)} == keys
|
||||
assert scans == [webui_dir, webui_dir]
|
||||
|
||||
|
||||
def test_webui_session_list_snapshot_tracks_all_display_artifacts(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
webui_dir = tmp_path / "webui"
|
||||
key = "websocket:artifacts"
|
||||
stem = SessionManager.safe_key(key)
|
||||
segments = webui_dir / f"{stem}.segments"
|
||||
segments.mkdir()
|
||||
active = webui_dir / f"{stem}.jsonl"
|
||||
active.write_text('{"event":"user","chat_id":"artifacts","text":"active question"}\n', encoding="utf-8")
|
||||
segment = segments / "000001.jsonl"
|
||||
segment.write_text('{"event":"user","chat_id":"artifacts","text":"older question"}\n', encoding="utf-8")
|
||||
other_files = [webui_dir / f"{stem}.json", segments / "manifest.json",
|
||||
segments / "state.json", segments / "delivery.json"]
|
||||
for path in other_files:
|
||||
path.write_text("{}\n", encoding="utf-8")
|
||||
all_files = [active, segment, *other_files]
|
||||
base_ns = int(datetime(2026, 1, 1).timestamp() * 1_000_000_000)
|
||||
for path in all_files:
|
||||
os.utime(path, ns=(base_ns, base_ns))
|
||||
|
||||
row, = list_webui_sessions(manager)
|
||||
assert row["preview"] == "older question"
|
||||
cache = json.loads((manager.sessions_dir / ".webui_session_index.json").read_text(encoding="utf-8"))
|
||||
cached, = cache["sessions"]
|
||||
assert cached["webui_activity_files"] == len(all_files)
|
||||
assert cached["webui_activity_size"] == sum(path.stat().st_size for path in all_files)
|
||||
state_file = segments / "state.json"
|
||||
state_file.write_text('{"active":true}\n', encoding="utf-8")
|
||||
newer_ns = base_ns + 1_000_000_000
|
||||
os.utime(state_file, ns=(newer_ns, newer_ns))
|
||||
refreshed, = list_webui_sessions(manager)
|
||||
assert refreshed["updated_at"] == datetime.fromtimestamp(newer_ns / 1_000_000_000).isoformat()
|
||||
other_files[0].unlink()
|
||||
other_files[-1].unlink()
|
||||
list_webui_sessions(manager)
|
||||
cached, = json.loads((manager.sessions_dir / ".webui_session_index.json").read_text(encoding="utf-8"))["sessions"]
|
||||
assert cached["webui_activity_files"] == len(all_files) - 2
|
||||
assert cached["webui_activity_size"] == sum(path.stat().st_size for path in all_files if path.exists())
|
||||
|
||||
|
||||
def test_webui_session_list_activity_uses_host_filename_case_semantics(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
key = "websocket:MixedCase"
|
||||
session = manager.get_or_create(key)
|
||||
session.add_message("user", "stored question")
|
||||
session.messages[0]["timestamp"] = "2026-01-01T00:00:00"
|
||||
session.updated_at = datetime(2026, 1, 1)
|
||||
manager.save(session)
|
||||
path = tmp_path / "webui" / f"{SessionManager.safe_key(key).swapcase()}.jsonl"
|
||||
path.write_text('{"event":"turn_end","chat_id":"MixedCase"}\n', encoding="utf-8")
|
||||
activity = datetime(2026, 1, 2)
|
||||
activity_ns = int(activity.timestamp() * 1_000_000_000)
|
||||
os.utime(path, ns=(activity_ns, activity_ns))
|
||||
row, = list_webui_sessions(manager)
|
||||
assert row["updated_at"] == (activity.isoformat() if os.name == "nt" else "2026-01-01T00:00:00")
|
||||
|
||||
|
||||
def test_webui_session_list_keeps_transcript_only_key_case(tmp_path):
|
||||
key = "websocket:MixedCase"
|
||||
path = tmp_path / "webui" / f"{SessionManager.safe_key(key)}.jsonl"
|
||||
path.write_text('{"event":"user","chat_id":"MixedCase","text":"question"}\n', encoding="utf-8")
|
||||
row, = list_webui_sessions(SessionManager(tmp_path))
|
||||
assert row["key"] == key and row["preview"] == "question"
|
||||
|
||||
|
||||
def test_webui_session_list_rejects_display_file_and_segment_symlinks(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
webui_dir = tmp_path / "webui"
|
||||
outside = tmp_path / "outside"
|
||||
outside.mkdir()
|
||||
target = outside / "000000.jsonl"
|
||||
target.write_text('{"event":"user","chat_id":"linked","text":"outside secret"}\n', encoding="utf-8")
|
||||
safe_segments = webui_dir / "websocket_safe.segments"
|
||||
safe_segments.mkdir()
|
||||
(safe_segments / "000001.jsonl").write_text(
|
||||
'{"event":"user","chat_id":"safe","text":"safe question"}\n', encoding="utf-8",
|
||||
)
|
||||
try:
|
||||
(webui_dir / "websocket_linked.jsonl").symlink_to(target)
|
||||
(webui_dir / "websocket_directory.segments").symlink_to(outside, target_is_directory=True)
|
||||
(safe_segments / "000000.jsonl").symlink_to(target)
|
||||
except OSError:
|
||||
pytest.skip("symlink creation is unavailable")
|
||||
|
||||
row, = list_webui_sessions(manager)
|
||||
assert row["key"] == "websocket:safe" and row["preview"] == "safe question"
|
||||
|
||||
|
||||
|
||||
def test_webui_session_list_refreshes_after_model_preset_rename(tmp_path: Path) -> None:
|
||||
manager = SessionManager(tmp_path)
|
||||
session = manager.get_or_create("websocket:renamed-preset")
|
||||
@@ -237,30 +76,6 @@ def test_webui_session_list_surfaces_pending_recovery_state(tmp_path: Path) -> N
|
||||
}
|
||||
|
||||
|
||||
def test_webui_session_index_uses_unique_temp_file(tmp_path: Path) -> None:
|
||||
key = "websocket:unique-index-temp"
|
||||
transcript = tmp_path / "webui" / f"{SessionManager.safe_key(key)}.jsonl"
|
||||
transcript.write_text(
|
||||
'{"event":"user","chat_id":"unique-index-temp","text":"hello"}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
manager = SessionManager(tmp_path)
|
||||
stale_shared_tmp = manager.sessions_dir / ".webui_session_index.json.tmp"
|
||||
stale_bytes = b"pre-existing shared temp\x00\xff"
|
||||
stale_shared_tmp.write_bytes(stale_bytes)
|
||||
|
||||
row, = list_webui_sessions(manager)
|
||||
|
||||
assert row["key"] == key
|
||||
assert row["preview"] == "hello"
|
||||
cache = json.loads((manager.sessions_dir / ".webui_session_index.json").read_text(encoding="utf-8"))
|
||||
cached_row, = cache["sessions"]
|
||||
assert cached_row["key"] == key
|
||||
assert cached_row["preview"] == "hello"
|
||||
assert stale_shared_tmp.read_bytes() == stale_bytes
|
||||
assert not list(manager.sessions_dir.glob(".webui_session_index.json.*.tmp"))
|
||||
|
||||
|
||||
def test_webui_session_list_indexes_workspace_scope_and_preserves_null(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
@@ -321,7 +136,6 @@ def test_webui_session_list_refreshes_after_concurrent_metadata_change(tmp_path,
|
||||
assert session_list_index.indexed_workspace_scope(second)[1]["access_mode"] == "restricted"
|
||||
|
||||
|
||||
|
||||
def test_webui_session_list_sees_committed_snapshot_during_write(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
session = manager.get_or_create("websocket:concurrent")
|
||||
@@ -338,7 +152,6 @@ def test_webui_session_list_sees_committed_snapshot_during_write(tmp_path):
|
||||
assert list_webui_sessions(manager)[0]["preview"] == "after"
|
||||
|
||||
|
||||
|
||||
def test_webui_session_list_rejects_invalid_internal_model_preset_metadata(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
@@ -379,7 +192,6 @@ def test_webui_session_list_skips_provider_state_before_preview_budget(
|
||||
tmp_path: Path,
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
monkeypatch.setattr(session_list_index, "_SESSION_LIST_PREVIEW_MAX_CHARS", 100)
|
||||
manager = SessionManager(tmp_path)
|
||||
session = manager.get_or_create("websocket:private-state")
|
||||
session.provider_state = ProviderConversationState(
|
||||
@@ -408,283 +220,6 @@ def test_webui_session_list_drops_deleted_index_rows(tmp_path: Path) -> None:
|
||||
assert list_webui_sessions(manager) == []
|
||||
|
||||
|
||||
def test_webui_session_list_recovers_transcript_without_canonical_session(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
webui_dir = tmp_path / "webui"
|
||||
webui_dir.mkdir(exist_ok=True)
|
||||
monkeypatch.setattr(session_list_index, "get_webui_dir", lambda: webui_dir)
|
||||
key = "websocket:restored"
|
||||
transcript = webui_dir / f"{SessionManager.safe_key(key)}.jsonl"
|
||||
transcript.write_text(
|
||||
'{"event":"user","chat_id":"restored","text":"original question",'
|
||||
'"created_at_ms":1785502800000}\n'
|
||||
'{"event":"message","chat_id":"restored","text":"original answer",'
|
||||
'"created_at_ms":1785502801000}\n'
|
||||
'{"event":"turn_end","chat_id":"restored","created_at_ms":1785502802000}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
manager = SessionManager(tmp_path / "workspace")
|
||||
|
||||
[row] = list_webui_sessions(manager)
|
||||
|
||||
assert row["key"] == key
|
||||
assert row["preview"] == "original question"
|
||||
assert row["created_at"] == datetime.fromtimestamp(1785502800).isoformat()
|
||||
assert manager.read_session_snapshot(key) is None
|
||||
assert manager.list_sessions() == []
|
||||
|
||||
reloaded = SessionManager(tmp_path / "workspace")
|
||||
assert [row["key"] for row in list_webui_sessions(reloaded)] == [key]
|
||||
|
||||
|
||||
def test_webui_session_list_recovers_colon_chat_id_from_transcript(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
webui_dir = tmp_path / "webui"
|
||||
webui_dir.mkdir(exist_ok=True)
|
||||
monkeypatch.setattr(session_list_index, "get_webui_dir", lambda: webui_dir)
|
||||
key = "websocket:scope:child"
|
||||
transcript = webui_dir / f"{SessionManager.safe_key(key)}.jsonl"
|
||||
transcript.write_text(
|
||||
'{"event":"user","chat_id":"scope:child","text":"scoped history"}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
[row] = list_webui_sessions(SessionManager(tmp_path / "workspace"))
|
||||
|
||||
assert row["key"] == key
|
||||
assert row["preview"] == "scoped history"
|
||||
|
||||
|
||||
def test_webui_session_list_normalizes_transcript_preview(tmp_path: Path) -> None:
|
||||
key = "websocket:long-preview"
|
||||
transcript = tmp_path / "webui" / f"{SessionManager.safe_key(key)}.jsonl"
|
||||
transcript.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"event": "user",
|
||||
"chat_id": "long-preview",
|
||||
"text": "first\n\n" + "word " * 100,
|
||||
}
|
||||
)
|
||||
+ "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
[row] = list_webui_sessions(SessionManager(tmp_path / "workspace"))
|
||||
|
||||
assert row["preview"].startswith("first word")
|
||||
assert "\n" not in row["preview"]
|
||||
assert row["preview"].endswith("…")
|
||||
|
||||
|
||||
def test_webui_session_list_tolerates_invalid_transcript_timestamp(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
key = "websocket:bad-time"
|
||||
transcript = tmp_path / "webui" / f"{SessionManager.safe_key(key)}.jsonl"
|
||||
transcript.write_text(
|
||||
'{"event":"user","chat_id":"bad-time","text":"still visible",'
|
||||
'"created_at_ms":1e100}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
[row] = list_webui_sessions(SessionManager(tmp_path / "workspace"))
|
||||
|
||||
assert row["preview"] == "still visible"
|
||||
datetime.fromisoformat(row["created_at"])
|
||||
|
||||
|
||||
def test_webui_session_list_ignores_invalid_transcript_chat_id(tmp_path: Path) -> None:
|
||||
transcript = tmp_path / "webui" / "websocket_.._outside.jsonl"
|
||||
transcript.write_text(
|
||||
'{"event":"user","chat_id":"../outside","text":"do not expose"}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
assert list_webui_sessions(SessionManager(tmp_path / "workspace")) == []
|
||||
|
||||
|
||||
def test_webui_session_list_recovers_segment_only_transcript(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
webui_dir = tmp_path / "webui"
|
||||
webui_dir.mkdir(exist_ok=True)
|
||||
monkeypatch.setattr(session_list_index, "get_webui_dir", lambda: webui_dir)
|
||||
key = "websocket:segmented"
|
||||
segments = webui_dir / f"{SessionManager.safe_key(key)}.segments"
|
||||
segments.mkdir()
|
||||
(segments / "000001.jsonl").write_text(
|
||||
'{"event":"user","chat_id":"segmented","text":"older segment"}\n'
|
||||
'{"event":"turn_end","chat_id":"segmented"}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
[row] = list_webui_sessions(SessionManager(tmp_path / "workspace"))
|
||||
|
||||
assert row["key"] == key
|
||||
assert row["preview"] == "older segment"
|
||||
|
||||
|
||||
def test_webui_session_list_prefers_canonical_metadata_without_duplicate(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
webui_dir = tmp_path / "webui"
|
||||
webui_dir.mkdir(exist_ok=True)
|
||||
monkeypatch.setattr(session_list_index, "get_webui_dir", lambda: webui_dir)
|
||||
key = "websocket:canonical"
|
||||
(webui_dir / f"{SessionManager.safe_key(key)}.jsonl").write_text(
|
||||
'{"event":"user","chat_id":"canonical","text":"display copy"}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
manager = SessionManager(tmp_path / "workspace")
|
||||
session = manager.get_or_create(key)
|
||||
session.metadata["title"] = "Canonical title"
|
||||
session.add_message("user", "canonical preview")
|
||||
manager.save(session)
|
||||
|
||||
rows = list_webui_sessions(manager)
|
||||
|
||||
assert len(rows) == 1
|
||||
assert rows[0]["key"] == key
|
||||
assert rows[0]["preview"] == "canonical preview"
|
||||
|
||||
|
||||
def test_webui_session_list_reuses_unchanged_transcript_index(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
webui_dir = tmp_path / "webui"
|
||||
webui_dir.mkdir(exist_ok=True)
|
||||
monkeypatch.setattr(session_list_index, "get_webui_dir", lambda: webui_dir)
|
||||
key = "websocket:cached-transcript"
|
||||
(webui_dir / f"{SessionManager.safe_key(key)}.jsonl").write_text(
|
||||
'{"event":"user","chat_id":"cached-transcript","text":"cached"}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
manager = SessionManager(tmp_path / "workspace")
|
||||
assert list_webui_sessions(manager)[0]["preview"] == "cached"
|
||||
|
||||
def fail_scan(*args, **kwargs):
|
||||
raise AssertionError("unchanged transcript should reuse its index row")
|
||||
|
||||
monkeypatch.setattr(session_list_index, "_scan_transcript_row", fail_scan)
|
||||
|
||||
assert list_webui_sessions(manager)[0]["preview"] == "cached"
|
||||
|
||||
|
||||
def test_webui_session_list_does_not_cache_changed_transcript_with_old_signature(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
webui_dir = tmp_path / "webui"
|
||||
key = "websocket:transcript-race"
|
||||
transcript = webui_dir / f"{SessionManager.safe_key(key)}.jsonl"
|
||||
transcript.write_text(
|
||||
'{"event":"user","chat_id":"transcript-race","text":"initial"}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
manager = SessionManager(tmp_path / "workspace")
|
||||
assert list_webui_sessions(manager)[0]["preview"] == "initial"
|
||||
transcript.write_text(
|
||||
'{"event":"user","chat_id":"transcript-race","text":"first scan"}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
original_open = open
|
||||
changed = False
|
||||
|
||||
class RacingReader(io.StringIO):
|
||||
def __next__(self) -> str:
|
||||
nonlocal changed
|
||||
if not changed:
|
||||
changed = True
|
||||
transcript.write_text(
|
||||
'{"event":"user","chat_id":"transcript-race","text":"second scan"}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
return super().__next__()
|
||||
|
||||
def racing_open(path, *args, **kwargs):
|
||||
if Path(path) == transcript:
|
||||
with original_open(path, *args, **kwargs) as source:
|
||||
return RacingReader(source.read())
|
||||
return original_open(path, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(session_list_index, "open", racing_open, raising=False)
|
||||
|
||||
first = list_webui_sessions(manager)
|
||||
second = list_webui_sessions(manager)
|
||||
|
||||
assert first[0]["preview"] == "first scan"
|
||||
assert second[0]["preview"] == "second scan"
|
||||
|
||||
|
||||
def test_webui_session_list_drops_deleted_transcript_index_row(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
webui_dir = tmp_path / "webui"
|
||||
webui_dir.mkdir(exist_ok=True)
|
||||
monkeypatch.setattr(session_list_index, "get_webui_dir", lambda: webui_dir)
|
||||
key = "websocket:deleted-transcript"
|
||||
transcript = webui_dir / f"{SessionManager.safe_key(key)}.jsonl"
|
||||
transcript.write_text(
|
||||
'{"event":"user","chat_id":"deleted-transcript","text":"delete me"}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
manager = SessionManager(tmp_path / "workspace")
|
||||
assert list_webui_sessions(manager)[0]["key"] == key
|
||||
|
||||
transcript.unlink()
|
||||
|
||||
assert list_webui_sessions(manager) == []
|
||||
|
||||
|
||||
def test_webui_session_list_keeps_runtime_instances_isolated(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
first_dir = tmp_path / "instance-a" / "webui"
|
||||
second_dir = tmp_path / "instance-b" / "webui"
|
||||
first_dir.mkdir(parents=True)
|
||||
second_dir.mkdir(parents=True)
|
||||
(first_dir / "websocket_first.jsonl").write_text(
|
||||
'{"event":"user","chat_id":"first","text":"first instance"}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
(second_dir / "websocket_second.jsonl").write_text(
|
||||
'{"event":"user","chat_id":"second","text":"second instance"}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
manager = SessionManager(tmp_path / "workspace")
|
||||
|
||||
monkeypatch.setattr(session_list_index, "get_webui_dir", lambda: first_dir)
|
||||
assert [row["key"] for row in list_webui_sessions(manager)] == ["websocket:first"]
|
||||
|
||||
monkeypatch.setattr(session_list_index, "get_webui_dir", lambda: second_dir)
|
||||
assert [row["key"] for row in list_webui_sessions(manager)] == ["websocket:second"]
|
||||
|
||||
|
||||
def test_webui_session_list_ignores_legacy_stem(tmp_path: Path) -> None:
|
||||
manager = SessionManager(tmp_path)
|
||||
legacy_path = manager.sessions_dir / "websocket_legacy.jsonl"
|
||||
legacy_path.write_text(
|
||||
'{"_type":"metadata","key":"websocket:legacy",'
|
||||
'"created_at":"2025-01-01T00:00:00",'
|
||||
'"updated_at":"2025-01-01T00:00:00","metadata":{}}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
assert list_webui_sessions(manager) == []
|
||||
assert legacy_path.exists()
|
||||
|
||||
|
||||
def test_webui_session_list_skips_cron_internal_user_preview(tmp_path: Path) -> None:
|
||||
manager = SessionManager(tmp_path)
|
||||
session = manager.get_or_create("websocket:cron-preview")
|
||||
@@ -727,80 +262,6 @@ def test_webui_session_list_skips_hidden_history_user_preview(tmp_path: Path) ->
|
||||
assert list_webui_sessions(manager)[0]["preview"] == "subagent summary"
|
||||
|
||||
|
||||
def test_webui_session_list_uses_webui_transcript_activity_for_sort(
|
||||
tmp_path: Path,
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
webui_dir = tmp_path / "webui"
|
||||
webui_dir.mkdir(exist_ok=True)
|
||||
monkeypatch.setattr(session_list_index, "get_webui_dir", lambda: webui_dir)
|
||||
|
||||
manager = SessionManager(tmp_path)
|
||||
old_session = manager.get_or_create("websocket:old-metadata")
|
||||
old_session.created_at = datetime(2026, 6, 15, 10, 0, 0)
|
||||
old_session.updated_at = datetime(2026, 6, 15, 10, 0, 0)
|
||||
old_session.add_message("user", "old metadata")
|
||||
old_session.messages[-1]["timestamp"] = "2026-06-15T10:00:00"
|
||||
old_session.updated_at = datetime(2026, 6, 15, 10, 0, 0)
|
||||
manager.save(old_session)
|
||||
|
||||
newer_metadata = manager.get_or_create("websocket:newer-metadata")
|
||||
newer_metadata.created_at = datetime(2026, 6, 15, 11, 0, 0)
|
||||
newer_metadata.updated_at = datetime(2026, 6, 15, 11, 0, 0)
|
||||
newer_metadata.add_message("user", "newer metadata")
|
||||
newer_metadata.messages[-1]["timestamp"] = "2026-06-15T11:00:00"
|
||||
newer_metadata.updated_at = datetime(2026, 6, 15, 11, 0, 0)
|
||||
manager.save(newer_metadata)
|
||||
|
||||
transcript = webui_dir / "websocket_old-metadata.jsonl"
|
||||
transcript.write_text(
|
||||
'{"event":"turn_end","chat_id":"old-metadata"}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
activity_ns = int(datetime(2026, 6, 15, 12, 0, 0).timestamp() * 1_000_000_000)
|
||||
os.utime(transcript, ns=(activity_ns, activity_ns))
|
||||
|
||||
rows = list_webui_sessions(manager)
|
||||
|
||||
assert [row["key"] for row in rows] == [
|
||||
"websocket:old-metadata",
|
||||
"websocket:newer-metadata",
|
||||
]
|
||||
assert rows[0]["updated_at"].startswith("2026-06-15T12:00:00")
|
||||
|
||||
|
||||
def test_webui_session_list_rescans_when_transcript_changes(
|
||||
tmp_path: Path,
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
webui_dir = tmp_path / "webui"
|
||||
webui_dir.mkdir(exist_ok=True)
|
||||
monkeypatch.setattr(session_list_index, "get_webui_dir", lambda: webui_dir)
|
||||
|
||||
manager = SessionManager(tmp_path)
|
||||
session = manager.get_or_create("websocket:transcript-change")
|
||||
session.created_at = datetime(2026, 6, 15, 10, 0, 0)
|
||||
session.updated_at = datetime(2026, 6, 15, 10, 0, 0)
|
||||
session.add_message("user", "preview")
|
||||
session.messages[-1]["timestamp"] = "2026-06-15T10:00:00"
|
||||
session.updated_at = datetime(2026, 6, 15, 10, 0, 0)
|
||||
manager.save(session)
|
||||
|
||||
assert list_webui_sessions(manager)[0]["preview"] == "preview"
|
||||
|
||||
transcript = webui_dir / "websocket_transcript-change.jsonl"
|
||||
transcript.write_text(
|
||||
'{"event":"turn_end","chat_id":"transcript-change"}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
activity_ns = int(datetime(2026, 6, 15, 12, 30, 0).timestamp() * 1_000_000_000)
|
||||
os.utime(transcript, ns=(activity_ns, activity_ns))
|
||||
|
||||
rows = list_webui_sessions(manager)
|
||||
|
||||
assert rows[0]["updated_at"].startswith("2026-06-15T12:30:00")
|
||||
|
||||
|
||||
def test_webui_session_list_sorts_by_message_activity_not_maintenance_timestamp(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
@@ -927,3 +388,22 @@ def test_session_manager_list_sessions_fallback_time_when_missing(tmp_path: Path
|
||||
assert sessions[0]["updated_at"] is not None
|
||||
datetime.fromisoformat(sessions[0]["created_at"])
|
||||
datetime.fromisoformat(sessions[0]["updated_at"])
|
||||
|
||||
|
||||
def test_sidebar_uses_durable_display_summary_and_filters_private_sessions(history):
|
||||
sessions = history.sessions
|
||||
sessions.types.register(SessionType("internal", needs_handle=False, public_history=False))
|
||||
for key in ("websocket:visible", "websocket:private"):
|
||||
history.append(key, {"event": "user", "text": " display\n preview ", "created_at_ms": 1760000001000})
|
||||
history.append(key, {"event": "message", "text": "answer", "created_at_ms": 1760000002000})
|
||||
private = sessions.get_or_create("websocket:private")
|
||||
private.metadata[SESSION_TYPE_KEY] = "internal"
|
||||
sessions.save(private)
|
||||
rows = list_webui_sessions(sessions)
|
||||
assert [row["key"] for row in rows] == ["websocket:visible"]
|
||||
assert rows[0]["preview"] == "display preview"
|
||||
assert datetime.fromisoformat(rows[0]["updated_at"]).timestamp() == 1760000002
|
||||
history.append("websocket:visible", {"event": "turn_end", "created_at_ms": 1760000003000})
|
||||
assert datetime.fromisoformat(list_webui_sessions(sessions)[0]["updated_at"]).timestamp() == 1760000003
|
||||
sessions.delete_session("websocket:visible")
|
||||
assert list_webui_sessions(sessions) == []
|
||||
@@ -125,8 +125,7 @@ def test_session_mention_context_treats_titles_as_data() -> None:
|
||||
@pytest.mark.asyncio
|
||||
async def test_session_mentions_do_not_isolate_workspaces(tmp_path, monkeypatch) -> None:
|
||||
webui_dir = tmp_path / "webui"
|
||||
monkeypatch.setattr("nanobot.webui.transcript.get_webui_dir", lambda: webui_dir)
|
||||
monkeypatch.setattr("nanobot.webui.session_list_index.get_webui_dir", lambda: webui_dir)
|
||||
monkeypatch.setattr("nanobot.webui.history.get_webui_dir", lambda: webui_dir)
|
||||
manager = SessionManager(tmp_path)
|
||||
project_b = tmp_path / "b"
|
||||
project_b.mkdir()
|
||||
|
||||
Reference in new issue
Block a user