Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
fix(webui): preserve unmigrated workspace history ownership
chengyongru92e6608e6e6c
diff --git a/nanobot/webui/history.py b/nanobot/webui/history.pyindex 2cff7ad86..b18e5e7e7 100644--- a/nanobot/webui/history.py+++ b/nanobot/webui/history.py@@ -159,20 +159,27 @@ def collect_legacy_history(keys_by_stem.setdefault(SessionManager.safe_key(session["key"]), set()).add(session["key"])foreign_owners: dict[str, list[Path]] = {}if namespace is not None and groups:- for database in namespace.parent.glob("*/sessions.sqlite3"):- if database.parent == namespace:+ for other_namespace in namespace.parent.iterdir():+ if other_namespace == namespace or not other_namespace.is_dir():continue- if database.is_symlink() or database.parent.is_symlink():- raise ValueError(f"invalid session namespace for history migration: {database}")- with closing(sqlite3.connect(database.as_uri() + "?mode=ro", uri=True)) as db:- owned = {str(row[0]) for row in db.execute("SELECT key FROM sessions")}- prefix = f"{HISTORY_IMPORT_MARKER}:"- owned.update(str(row[0])[len(prefix):] for row in db.execute(- "SELECT key FROM storage_meta WHERE key LIKE ? AND value='complete'",- (prefix + "%",),- ))- for key in owned:- foreign_owners.setdefault(key, []).append(database)+ database = other_namespace / "sessions.sqlite3"+ if database.is_symlink() or other_namespace.is_symlink():+ raise ValueError(f"invalid session namespace for history migration: {other_namespace}")+ if database.exists():+ # SQLite and deletion receipts take precedence over retained JSONL backups.+ with closing(sqlite3.connect(database.as_uri() + "?mode=ro", uri=True)) as db:+ owned = {str(row[0]) for row in db.execute("SELECT key FROM sessions")}+ prefix = f"{HISTORY_IMPORT_MARKER}:"+ owned.update(str(row[0])[len(prefix):] for row in db.execute(+ "SELECT key FROM storage_meta WHERE key LIKE ? AND value='complete'",+ (prefix + "%",),+ ))+ else:+ from nanobot.session.jsonl_migration import read_jsonl++ owned = {read_jsonl(path)[0].key for path in other_namespace.glob("*.jsonl")}+ for key in owned:+ foreign_owners.setdefault(key, []).append(other_namespace)imports: list[HistoryImport] = []for stem, paths in groups.items():records = [record for path in paths for record in _read_legacy_file(path)]diff --git a/tests/session/test_display_history.py b/tests/session/test_display_history.pyindex f007cc5e9..954d6d931 100644--- a/tests/session/test_display_history.py+++ b/tests/session/test_display_history.py@@ -8,6 +8,7 @@ from pathlib import Pathimport pytestfrom nanobot.session.display_history import HistoryFact, HistoryKind+from nanobot.session.location import SessionLocationfrom nanobot.session.manager import SessionManagerfrom nanobot.session.sqlite_store import SessionConflictErrorfrom nanobot.webui.forking import create_webui_chat_fork@@ -247,6 +248,54 @@ asyncio.run(run())assert reopened.read_session_file(source.key)["messages"] == source.messages+async def test_legacy_import_waits_for_unmigrated_workspace_owner(tmp_path, monkeypatch):+ root = tmp_path / "sessions"+ directory = tmp_path / "webui"+ monkeypatch.setattr("nanobot.webui.history.get_webui_dir", lambda: directory)+ locations = {}+ sources = {}+ for name in ("first", "second"):+ location = SessionLocation(tmp_path / name, sessions_root=root)+ locations[name] = location+ key = f"websocket:{name}"+ source = location.sessions_dir / f"{SessionLocation.storage_key(key)}.jsonl"+ source.write_text("\n".join(json.dumps(record) for record in [+ {"_type": "metadata", "key": key, "metadata": {}},+ {"role": "user", "content": f"question {name}"},+ ]) + "\n", encoding="utf-8")+ display = _legacy(directory, key, [+ {"event": "user", "chat_id": name, "text": f"question {name}"},+ {"event": "message", "chat_id": name, "text": f"answer {name}"},+ {"event": "turn_end", "chat_id": name},+ ])+ sources.update({path: path.read_bytes() for path in (source, display)})++ async def initialize(name: str):+ sessions = SessionManager(tmp_path / name, sessions_root=root)+ key = f"websocket:{name}"+ try:+ await WebUITranscriptRecorder(sessions).initialize()+ assert [row["key"] for row in await sessions.state.list_sessions()] == [key]+ session = await sessions.state.read(key)+ assert session is not None+ assert session.messages == [{"role": "user", "content": f"question {name}"}]+ facts = await sessions.state.project_history(key, lambda history: history.all_facts())+ assert [(fact.kind, fact.content.get("text")) for fact in facts] == [+ (HistoryKind.INPUT, f"question {name}"),+ (HistoryKind.ANSWER, f"answer {name}"),+ (HistoryKind.COMPLETION, None),+ ]+ finally:+ await sessions.state.aclose()++ await initialize("second")+ assert not (locations["first"].sessions_dir / "sessions.sqlite3").exists()+ await initialize("first")+ await initialize("second")+ await initialize("first")+ assert {path: path.read_bytes() for path in sources} == sources++@pytest.mark.asyncioasync def test_legacy_import_owner_survives_delete_and_new_workspace(tmp_path):from nanobot.webui.history import collect_legacy_history