refactor(session): centralize state ownership in SQLite (#5943)
* fix(session): move persistence off event loop * refactor(session): isolate async persistence boundary * refactor(session): keep a single session manager * refactor(session): use stateless async adapters * fix(session): serialize local persistence without file-lock contention * refactor(session): own async persistence and snapshot commits * refactor(session): narrow persistence changes to async adapters * refactor(session): remove redundant async forwarding helpers * fix(command): offload compact session persistence * fix(session): adapt idle compaction to current main * fix(webui): offload session metadata persistence * refactor(session): centralize state ownership in SQLite * fix(session): skip storage for non-recoverable followups * test(webui): honor the full gateway event deadline * perf(session): persist incremental changes and reuse owner snapshots * test(agent): allow durable worker shutdown in burst test * fix(gateway): drain session storage on Windows console shutdown * fix(session): enforce bounded ownership and lifecycle-safe persistence * fix: reject unresolved home paths and stabilize platform tests * fix(session): preserve request context compatibility and owner-backed tests * docs: focus configuration guide on user-facing behavior * fix(session): adapt goal admission to async ownership after rebase * fix(session): integrate current gateway and subagent contracts * fix(session): align rebased workspace admission and async tests * fix(session): support compatible SQLite schema evolution * test(agent): use session owner in workspace context regressions * test: stabilize Windows lifecycle and browser checks * refactor(session): remove premature JSONL file export * ci: bound Windows full-suite worker concurrency * chore: remove session state refactor notes * fix(session): queue writes and retain worker connections * perf(webui): read detached metadata for session and task lists * perf(agent): bound prompt preparation and local token counting * docs: remove internal session storage guide * perf(session): skip archived transcripts during idle scans * fix(session): coordinate turns and isolate legacy session data Bind WebUI input generations to the execution session and serialize idle and SDK compaction with turns. Keep turn drafts through preparation so the latest channel route persists. Move imported workspace JSONL and checkpoints to durable private backups before gateway admission, resuming cleanup after interruptions. Remove committed child sessions when task creation is cancelled. Validation: focused Python and frontend regressions, Ruff, BasedPyright, import boundaries, WebUI build, and isolated gateway/browser flows. * fix(agent): keep cancellation hooks independent of prompt preparation * fix(session): preserve admission, delivery, and migration contracts * fix(agent): preserve cancellation settlement after rebase * fix(session): preserve request attribution through async ownership
This commit is contained in:
1 parent
33ff520d12
commit
8f6a5594fb
144 files changed
+8293
-4912
No files matched your search
@@ -3,7 +3,6 @@ from __future__ import annotations
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
@@ -19,6 +18,7 @@ from nanobot.session.history_visibility import HIDDEN_HISTORY_META
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.model_selection import SESSION_MODEL_PRESET_METADATA_KEY
|
||||
from nanobot.session.recovery import RECOVERY_METADATA_KEY
|
||||
from nanobot.session.types import SESSION_TYPE_KEY, SessionType
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
@@ -28,31 +28,176 @@ def _isolate_webui_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(session_list_index, "get_webui_dir", lambda: webui_dir)
|
||||
|
||||
|
||||
def test_webui_session_list_reuses_valid_index_without_scanning_files(
|
||||
tmp_path: Path,
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
def test_webui_session_list_reads_previews_without_loading_history(tmp_path, monkeypatch):
|
||||
manager = SessionManager(tmp_path)
|
||||
session = manager.get_or_create("websocket:indexed")
|
||||
session.metadata[SESSION_MODEL_PRESET_METADATA_KEY] = "fast"
|
||||
session.add_message("user", "indexed preview")
|
||||
manager.save(session)
|
||||
|
||||
assert list_webui_sessions(manager)[0]["preview"] == "indexed preview"
|
||||
assert list_webui_sessions(manager)[0]["model_preset"] == "fast"
|
||||
|
||||
def fail_scan(session_manager: SessionManager, path: Path, webui_dir: Path) -> None:
|
||||
raise AssertionError(f"unexpected session file scan: {path}")
|
||||
|
||||
monkeypatch.setattr(session_list_index, "_scan_session_row", fail_scan)
|
||||
def fail_load(*args, **kwargs):
|
||||
raise AssertionError("sidebar must not load conversation history or rewrite unchanged cache")
|
||||
|
||||
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)
|
||||
|
||||
monkeypatch.setattr(Path, "stat", stored_files_only)
|
||||
monkeypatch.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")
|
||||
@@ -143,131 +288,44 @@ def test_webui_session_list_indexes_workspace_scope_and_preserves_null(
|
||||
}
|
||||
|
||||
|
||||
def test_webui_session_list_does_not_cache_old_snapshot_with_new_signature(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
def test_webui_session_list_refreshes_after_concurrent_metadata_change(tmp_path, monkeypatch):
|
||||
manager = SessionManager(tmp_path)
|
||||
session_key = "websocket:scope-race"
|
||||
session = manager.get_or_create(session_key)
|
||||
session.metadata[WORKSPACE_SCOPE_METADATA_KEY] = {
|
||||
"project_path": str(tmp_path),
|
||||
"access_mode": "full",
|
||||
}
|
||||
session.add_message("user", "hello")
|
||||
key = "websocket:scope-race"
|
||||
session = manager.get_or_create(key)
|
||||
session.metadata[WORKSPACE_SCOPE_METADATA_KEY] = {"project_path": str(tmp_path), "access_mode": "full"}
|
||||
manager.save(session)
|
||||
session_path = manager._get_session_path(session_key)
|
||||
original_open = open
|
||||
scope_changed = False
|
||||
original = manager.list_session_metadata
|
||||
|
||||
class RacingReader(io.StringIO):
|
||||
def __next__(self) -> str:
|
||||
nonlocal scope_changed
|
||||
if not scope_changed:
|
||||
scope_changed = True
|
||||
current = manager.get_or_create(session_key)
|
||||
current.metadata[WORKSPACE_SCOPE_METADATA_KEY] = {
|
||||
"project_path": str(tmp_path),
|
||||
"access_mode": "restricted",
|
||||
}
|
||||
manager.save(current)
|
||||
return super().__next__()
|
||||
|
||||
def racing_open(path, *args, **kwargs):
|
||||
if Path(path) == session_path:
|
||||
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)
|
||||
def racing_read():
|
||||
snapshot = original()
|
||||
manager.update_session_metadata(key, {WORKSPACE_SCOPE_METADATA_KEY: {
|
||||
"project_path": str(tmp_path), "access_mode": "restricted",
|
||||
}})
|
||||
return snapshot
|
||||
|
||||
monkeypatch.setattr(manager, "list_session_metadata", racing_read)
|
||||
first = list_webui_sessions(manager)[0]
|
||||
second = list_webui_sessions(manager)[0]
|
||||
|
||||
assert session_list_index.indexed_workspace_scope(first)[1]["access_mode"] == "full"
|
||||
assert session_list_index.indexed_workspace_scope(second)[1]["access_mode"] == "restricted"
|
||||
|
||||
|
||||
def test_webui_session_scan_does_not_overlap_session_save(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
manager = SessionManager(
|
||||
tmp_path / "workspace",
|
||||
sessions_root=tmp_path / "runtime",
|
||||
)
|
||||
session = manager.get_or_create("websocket:windows-reader")
|
||||
|
||||
def test_webui_session_list_sees_committed_snapshot_during_write(tmp_path):
|
||||
manager = SessionManager(tmp_path)
|
||||
session = manager.get_or_create("websocket:concurrent")
|
||||
session.add_message("user", "before")
|
||||
manager.save(session)
|
||||
session_path = manager._get_session_path(session.key)
|
||||
session.messages[0]["content"] = "after"
|
||||
with ThreadPoolExecutor(max_workers=1) as executor:
|
||||
def write() -> None:
|
||||
manager.save(session)
|
||||
rows = executor.submit(list_webui_sessions, manager).result(timeout=3)
|
||||
assert rows[0]["preview"] == "before"
|
||||
|
||||
reader_open = threading.Event()
|
||||
release_reader = threading.Event()
|
||||
save_started = threading.Event()
|
||||
save_lock_attempted = threading.Event()
|
||||
write_entered = threading.Event()
|
||||
original_open = open
|
||||
store = manager._jsonl_store
|
||||
original_acquire = store._session_files_lock.acquire
|
||||
original_save_unlocked = store._save_unlocked
|
||||
manager._store.run_write(write)
|
||||
assert list_webui_sessions(manager)[0]["preview"] == "after"
|
||||
|
||||
class BlockingReader:
|
||||
def __init__(self, file):
|
||||
self.file = file
|
||||
|
||||
def __enter__(self):
|
||||
entered = self.file.__enter__()
|
||||
reader_open.set()
|
||||
if not release_reader.wait(5):
|
||||
raise AssertionError("timed out waiting to release the session reader")
|
||||
return entered
|
||||
|
||||
def __exit__(self, *args):
|
||||
try:
|
||||
return self.file.__exit__(*args)
|
||||
finally:
|
||||
reader_open.clear()
|
||||
|
||||
def blocking_open(path, *args, **kwargs):
|
||||
file = original_open(path, *args, **kwargs)
|
||||
if Path(path) == session_path:
|
||||
return BlockingReader(file)
|
||||
return file
|
||||
|
||||
def observed_acquire(*args, **kwargs):
|
||||
if save_started.is_set():
|
||||
save_lock_attempted.set()
|
||||
return original_acquire(*args, **kwargs)
|
||||
|
||||
def observed_save_unlocked(session, *, fsync=False):
|
||||
write_entered.set()
|
||||
assert not reader_open.is_set(), "save entered while the canonical file was open"
|
||||
return original_save_unlocked(session, fsync=fsync)
|
||||
|
||||
monkeypatch.setattr(session_list_index, "open", blocking_open, raising=False)
|
||||
monkeypatch.setattr(store._session_files_lock, "acquire", observed_acquire)
|
||||
monkeypatch.setattr(store, "_save_unlocked", observed_save_unlocked)
|
||||
|
||||
def save_session() -> None:
|
||||
save_started.set()
|
||||
manager.save(session)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as executor:
|
||||
list_future = executor.submit(list_webui_sessions, manager)
|
||||
try:
|
||||
assert reader_open.wait(5)
|
||||
save_future = executor.submit(save_session)
|
||||
assert save_lock_attempted.wait(5)
|
||||
assert not write_entered.is_set()
|
||||
finally:
|
||||
release_reader.set()
|
||||
|
||||
assert list_future.result(timeout=5)[0]["preview"] == "before"
|
||||
save_future.result(timeout=5)
|
||||
|
||||
assert write_entered.is_set()
|
||||
assert list_webui_sessions(manager)[0]["preview"] == "after"
|
||||
|
||||
|
||||
def test_webui_session_list_rejects_invalid_internal_model_preset_metadata(
|
||||
@@ -286,7 +344,7 @@ def test_webui_session_list_rejects_invalid_internal_model_preset_metadata(
|
||||
assert manager.get_or_create(session.key).metadata["model_preset"] == 7
|
||||
|
||||
|
||||
def test_webui_session_list_rescans_only_changed_file(tmp_path: Path, monkeypatch) -> None:
|
||||
def test_webui_session_list_reflects_changed_preview(tmp_path: Path, monkeypatch) -> None:
|
||||
manager = SessionManager(tmp_path)
|
||||
first = manager.get_or_create("websocket:first")
|
||||
first.add_message("user", "first")
|
||||
@@ -301,22 +359,8 @@ def test_webui_session_list_rescans_only_changed_file(tmp_path: Path, monkeypatc
|
||||
second.add_message("user", "second after")
|
||||
manager.save(second)
|
||||
|
||||
original_scan = session_list_index._scan_session_row
|
||||
scanned: list[str] = []
|
||||
|
||||
def record_scan(
|
||||
session_manager: SessionManager,
|
||||
path: Path,
|
||||
webui_dir: Path,
|
||||
) -> dict | None:
|
||||
scanned.append(path.name)
|
||||
return original_scan(session_manager, path, webui_dir)
|
||||
|
||||
monkeypatch.setattr(session_list_index, "_scan_session_row", record_scan)
|
||||
|
||||
rows = list_webui_sessions(manager)
|
||||
|
||||
assert scanned == [manager._get_session_path("websocket:second").name]
|
||||
assert {row["preview"] for row in rows} == {"first", "second after"}
|
||||
|
||||
|
||||
@@ -377,7 +421,7 @@ def test_webui_session_list_recovers_transcript_without_canonical_session(
|
||||
assert row["key"] == key
|
||||
assert row["preview"] == "original question"
|
||||
assert row["created_at"] == datetime.fromtimestamp(1785502800).isoformat()
|
||||
assert not manager._get_session_path(key).exists()
|
||||
assert manager.read_session_snapshot(key) is None
|
||||
assert manager.list_sessions() == []
|
||||
|
||||
reloaded = SessionManager(tmp_path / "workspace")
|
||||
@@ -741,22 +785,8 @@ def test_webui_session_list_rescans_when_transcript_changes(
|
||||
activity_ns = int(datetime(2026, 6, 15, 12, 30, 0).timestamp() * 1_000_000_000)
|
||||
os.utime(transcript, ns=(activity_ns, activity_ns))
|
||||
|
||||
original_scan = session_list_index._scan_session_row
|
||||
scanned: list[str] = []
|
||||
|
||||
def record_scan(
|
||||
session_manager: SessionManager,
|
||||
path: Path,
|
||||
webui_dir: Path,
|
||||
) -> dict | None:
|
||||
scanned.append(path.name)
|
||||
return original_scan(session_manager, path, webui_dir)
|
||||
|
||||
monkeypatch.setattr(session_list_index, "_scan_session_row", record_scan)
|
||||
|
||||
rows = list_webui_sessions(manager)
|
||||
|
||||
assert scanned == [manager._get_session_path("websocket:transcript-change").name]
|
||||
assert rows[0]["updated_at"].startswith("2026-06-15T12:30:00")
|
||||
|
||||
|
||||
@@ -790,14 +820,74 @@ def list_webui_sessions(manager: SessionManager) -> list[dict]:
|
||||
return session_list_index.list_webui_sessions(manager)
|
||||
|
||||
|
||||
async def test_sidebar_allocates_handles_then_reads_during_pending_write(tmp_path, monkeypatch):
|
||||
import asyncio
|
||||
import threading
|
||||
from types import SimpleNamespace
|
||||
|
||||
from websockets.datastructures import Headers
|
||||
from websockets.http11 import Request
|
||||
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.websocket.runtime import WebSocketConfig
|
||||
from nanobot.webui.gateway_services import build_gateway_services
|
||||
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path / "data")
|
||||
manager = SessionManager(tmp_path / "workspace")
|
||||
state = manager.state
|
||||
key = "websocket:busy"
|
||||
await state.get(key)
|
||||
await state.update_metadata(key, {"title": "committed"})
|
||||
gateway = build_gateway_services(
|
||||
config=WebSocketConfig(), bus=MessageBus(), session_manager=manager,
|
||||
static_dist_path=None, workspace_path=tmp_path / "workspace",
|
||||
default_restrict_to_workspace=True, runtime_model_name=lambda: "test-model",
|
||||
runtime_surface="gateway", runtime_capabilities_overrides=None,
|
||||
)
|
||||
token = gateway.tokens.issue_api_token(60)
|
||||
connection = SimpleNamespace(remote_address=("127.0.0.1", 12345))
|
||||
request = Request("/api/sessions", Headers({"Authorization": f"Bearer {token}"}))
|
||||
started, release = threading.Event(), threading.Event()
|
||||
original = manager._store.replace_metadata
|
||||
|
||||
def blocked(session_key, metadata, **kwargs):
|
||||
started.set()
|
||||
assert release.wait(5)
|
||||
return original(session_key, metadata, **kwargs)
|
||||
|
||||
try:
|
||||
first = await gateway.http.dispatch(connection, request)
|
||||
assert first.status_code == 200
|
||||
first_row, = json.loads(first.body)["sessions"]
|
||||
persisted = await state.read_metadata(key)
|
||||
assert first_row["handle"]["name"] == persisted["metadata"]["session_handle"]
|
||||
monkeypatch.setattr(manager._store, "replace_metadata", blocked)
|
||||
write = asyncio.create_task(state.update_metadata(key, {"title": "next"}))
|
||||
try:
|
||||
assert await asyncio.to_thread(started.wait, 2)
|
||||
response = await asyncio.wait_for(gateway.http.dispatch(connection, request), 0.5)
|
||||
assert response.status_code == 200
|
||||
row, = json.loads(response.body)["sessions"]
|
||||
assert row["title"] == "committed"
|
||||
assert row["handle"] == first_row["handle"]
|
||||
finally:
|
||||
release.set()
|
||||
await write
|
||||
finally:
|
||||
release.set()
|
||||
await state.aclose()
|
||||
|
||||
|
||||
def test_webui_session_list_fallback_time_when_missing(tmp_path: Path) -> None:
|
||||
manager = SessionManager(tmp_path)
|
||||
path = manager._get_session_path("websocket:missing-time")
|
||||
legacy = tmp_path / "sessions"
|
||||
legacy.mkdir()
|
||||
path = legacy / "websocket_missing-time.jsonl"
|
||||
path.write_text(
|
||||
'{"_type": "metadata", "key": "websocket:missing-time"}\n'
|
||||
'{"_type": "message", "role": "user", "content": "hello"}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
manager = SessionManager(tmp_path)
|
||||
|
||||
rows = list_webui_sessions(manager)
|
||||
assert len(rows) == 1
|
||||
@@ -809,13 +899,15 @@ def test_webui_session_list_fallback_time_when_missing(tmp_path: Path) -> None:
|
||||
|
||||
|
||||
def test_session_manager_list_sessions_fallback_time_when_missing(tmp_path: Path) -> None:
|
||||
manager = SessionManager(tmp_path)
|
||||
path = manager._get_session_path("websocket:missing-time2")
|
||||
legacy = tmp_path / "sessions"
|
||||
legacy.mkdir()
|
||||
path = legacy / "websocket_missing-time2.jsonl"
|
||||
path.write_text(
|
||||
'{"_type": "metadata", "key": "websocket:missing-time2"}\n'
|
||||
'{"_type": "message", "role": "user", "content": "hello"}\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
manager = SessionManager(tmp_path)
|
||||
|
||||
sessions = manager.list_sessions()
|
||||
assert len(sessions) == 1
|
||||
|
||||
Reference in new issue
Block a user