refactor(sessions): persist archive state in SQLite (#6536)
* feat(webui): add archived chat management * fix(webui): keep archived chats in the sidebar * feat(webui): scope archived topics to sidebar groups * fix(webui): reuse group dissolve label * fix(webui): fail fast when adding panes * refactor(sessions): persist archive state in SQLite * refactor: limit archive changes to SQLite storage * perf(sessions): avoid redundant archive I/O and read barriers * fix(sessions): archive only persisted conversations
This commit is contained in:
1 parent
58a05ea3e0
commit
80ac41b1f4
16 files changed
+751
-107
No files matched your search
@@ -1579,66 +1579,63 @@ async def test_webui_persists_sidebar_state_larger_than_http_request_line(
|
||||
"event": "webui_response",
|
||||
"request_id": request_id,
|
||||
"ok": True,
|
||||
"result": saved,
|
||||
"result": {**saved, "archived_keys": []},
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("command_type", ["webui_request", "set_sidebar_state"])
|
||||
async def test_webui_sidebar_state_update_broadcasts_workbench_to_other_devices(
|
||||
bus: MagicMock,
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
command_type: str,
|
||||
) -> None:
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
channel = _ch(bus)
|
||||
sessions = SessionManager(tmp_path)
|
||||
await sessions.state.import_messages("websocket:a", [{"role": "user", "content": "saved"}])
|
||||
await sessions.state.fork("websocket:a", "websocket:b", 0)
|
||||
sessions.get_or_create("websocket:draft")
|
||||
channel = _ch(bus, session_manager=sessions)
|
||||
source = AsyncMock()
|
||||
source.request = SimpleNamespace(headers=Headers())
|
||||
other_device = AsyncMock()
|
||||
channel._webui_connections.update({source, other_device})
|
||||
channel._register_connection_outbound(other_device)
|
||||
request_id = "sidebar-workbench-state"
|
||||
|
||||
await channel._dispatch_envelope(
|
||||
source,
|
||||
"webui-client",
|
||||
{
|
||||
"type": "webui_request",
|
||||
"request_id": request_id,
|
||||
"action": "sidebar.update",
|
||||
"payload": {
|
||||
"state": {
|
||||
"workbench": {
|
||||
"version": 1,
|
||||
"tabs": {
|
||||
"tab:websocket:a": {
|
||||
"explicit": True,
|
||||
"title": "Research",
|
||||
"paneKeys": ["websocket:a", "websocket:b"],
|
||||
"layoutPaneKeys": ["websocket:b", "websocket:a"],
|
||||
"layout": "columns",
|
||||
"splitRatios": [0.35],
|
||||
}
|
||||
},
|
||||
}
|
||||
state = {
|
||||
"archived_keys": ["websocket:b", "websocket:draft"],
|
||||
"workbench": {
|
||||
"version": 1,
|
||||
"tabs": {
|
||||
"tab:websocket:a": {
|
||||
"explicit": True,
|
||||
"title": "Research",
|
||||
"paneKeys": ["websocket:a", "websocket:b"],
|
||||
"layoutPaneKeys": ["websocket:b", "websocket:a"],
|
||||
"layout": "columns",
|
||||
"splitRatios": [0.35],
|
||||
}
|
||||
},
|
||||
},
|
||||
)
|
||||
await asyncio.gather(*tuple(channel._webui_request_tasks.values()))
|
||||
|
||||
event = json.loads(other_device.send.await_args.args[0])
|
||||
assert event["event"] == "sidebar_state_updated"
|
||||
assert event["state"]["workbench"]["tabs"]["tab:websocket:a"]["paneKeys"] == [
|
||||
"websocket:a",
|
||||
"websocket:b",
|
||||
]
|
||||
assert event["state"]["workbench"]["tabs"]["tab:websocket:a"]["layoutPaneKeys"] == [
|
||||
"websocket:b",
|
||||
"websocket:a",
|
||||
]
|
||||
assert event["state"]["workbench"]["tabs"]["tab:websocket:a"]["splitRatios"] == [
|
||||
0.35
|
||||
]
|
||||
}
|
||||
envelope = {"type": command_type, "state": state} if command_type == "set_sidebar_state" else {
|
||||
"type": command_type, "request_id": "sidebar-workbench-state",
|
||||
"action": "sidebar.update", "payload": {"state": state},
|
||||
}
|
||||
try:
|
||||
await channel._dispatch_envelope(source, "webui-client", envelope)
|
||||
await asyncio.gather(*tuple(channel._webui_request_tasks.values()))
|
||||
event = json.loads(other_device.send.await_args.args[0])
|
||||
assert event["event"] == "sidebar_state_updated"
|
||||
assert event["state"]["archived_keys"] == ["websocket:b"]
|
||||
assert await sessions.state.archived_keys() == ["websocket:b"]
|
||||
assert event["state"]["workbench"] == state["workbench"]
|
||||
persisted = json.loads((tmp_path / "webui" / "sidebar-state.json").read_text(encoding="utf-8"))
|
||||
assert "archived_keys" not in persisted
|
||||
assert persisted["workbench"] == state["workbench"]
|
||||
finally:
|
||||
await channel.stop()
|
||||
await sessions.state.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -2442,6 +2442,8 @@ async def test_webui_sidebar_state_routes_are_config_dir_scoped(
|
||||
) -> None:
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
sm = _seed_session(tmp_path, key="websocket:sidebar")
|
||||
await sm.state.fork("websocket:sidebar", "websocket:old", 0)
|
||||
sm.get_or_create("websocket:draft")
|
||||
channel = _ch(bus, session_manager=sm, port=29911)
|
||||
server_task = asyncio.create_task(channel.start())
|
||||
try:
|
||||
@@ -2458,7 +2460,7 @@ async def test_webui_sidebar_state_routes_are_config_dir_scoped(
|
||||
|
||||
payload = {
|
||||
"pinned_keys": ["websocket:sidebar"],
|
||||
"archived_keys": ["websocket:old"],
|
||||
"archived_keys": ["websocket:old", "websocket:draft"],
|
||||
"session_order": ["websocket:old", "websocket:sidebar"],
|
||||
"title_overrides": {"websocket:sidebar": "Pinned work"},
|
||||
"view": {"density": "compact", "show_archived": True},
|
||||
@@ -2471,15 +2473,19 @@ async def test_webui_sidebar_state_routes_are_config_dir_scoped(
|
||||
assert updated.status_code == 200
|
||||
body = updated.json()
|
||||
assert body["pinned_keys"] == ["websocket:sidebar"]
|
||||
assert body["archived_keys"] == ["websocket:old"]
|
||||
assert await sm.state.archived_keys() == ["websocket:old"]
|
||||
assert body["session_order"] == ["websocket:old", "websocket:sidebar"]
|
||||
assert body["title_overrides"] == {"websocket:sidebar": "Pinned work"}
|
||||
assert body["view"]["density"] == "compact"
|
||||
|
||||
state_path = tmp_path / "webui" / "sidebar-state.json"
|
||||
assert state_path.is_file()
|
||||
assert json.loads(state_path.read_text(encoding="utf-8"))["pinned_keys"] == [
|
||||
"websocket:sidebar"
|
||||
]
|
||||
persisted = json.loads(state_path.read_text(encoding="utf-8"))
|
||||
assert persisted["pinned_keys"] == ["websocket:sidebar"]
|
||||
assert "archived_keys" not in persisted
|
||||
read_back = await _http_get("http://127.0.0.1:29911/api/webui/sidebar-state", headers=auth)
|
||||
assert read_back.json()["archived_keys"] == ["websocket:old"]
|
||||
finally:
|
||||
await channel.stop()
|
||||
await server_task
|
||||
|
||||
@@ -56,7 +56,7 @@ from nanobot.utils.helpers import sync_workspace_templates
|
||||
from nanobot.utils.token_encoding import warmup_token_encoding
|
||||
from nanobot.webui.build import BuildMode
|
||||
from nanobot.webui.dev import WebUIDevError, WebUIDevServer
|
||||
from nanobot.webui.sidebar_state import read_webui_sidebar_state
|
||||
from nanobot.webui.sidebar_state import ensure_webui_session_archives
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from nanobot.update_profiles import ProfileReceipt
|
||||
@@ -829,7 +829,7 @@ def _run_claimed_gateway(
|
||||
)
|
||||
|
||||
async def _pick_heartbeat_target() -> tuple[str, str]:
|
||||
sidebar_state = await asyncio.to_thread(read_webui_sidebar_state)
|
||||
archived_keys = await ensure_webui_session_archives(session_manager.state)
|
||||
unified_metadata = None
|
||||
if config.agents.defaults.unified_session:
|
||||
record = await session_manager.state.read_metadata(UNIFIED_SESSION_KEY)
|
||||
@@ -838,7 +838,7 @@ def _run_claimed_gateway(
|
||||
return _pick_heartbeat_target_from_sessions(
|
||||
enabled_channels=channels.enabled_channels,
|
||||
sessions=await session_manager.state.list_sessions(),
|
||||
archived_keys=sidebar_state.get("archived_keys", []),
|
||||
archived_keys=archived_keys,
|
||||
unified_session_metadata=unified_metadata,
|
||||
)
|
||||
|
||||
|
||||
@@ -94,9 +94,29 @@ def _create_schema_v2(db: sqlite3.Connection) -> None:
|
||||
db.execute(statement)
|
||||
|
||||
|
||||
def _create_schema_v3(db: sqlite3.Connection) -> None:
|
||||
# Empty chats can be archived before their first persisted message.
|
||||
db.execute("""CREATE TABLE session_archives (
|
||||
key TEXT PRIMARY KEY, archived_at TEXT NOT NULL
|
||||
)""")
|
||||
|
||||
|
||||
def _create_schema_v4(db: sqlite3.Connection) -> None:
|
||||
db.execute("""CREATE TABLE session_archives_v4 (
|
||||
key TEXT PRIMARY KEY REFERENCES sessions(key)
|
||||
ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED,
|
||||
archived_at TEXT NOT NULL
|
||||
)""")
|
||||
db.execute("""INSERT INTO session_archives_v4 (key, archived_at)
|
||||
SELECT archives.key, archives.archived_at FROM session_archives AS archives
|
||||
JOIN sessions ON sessions.key = archives.key""")
|
||||
db.execute("DROP TABLE session_archives")
|
||||
db.execute("ALTER TABLE session_archives_v4 RENAME TO session_archives")
|
||||
|
||||
|
||||
# Entries upgrade version N to N+1. Preserve released entries and append upgrades.
|
||||
_SCHEMA_MIGRATIONS: tuple[Callable[[sqlite3.Connection], None], ...] = (
|
||||
_create_schema_v1, _create_schema_v2,
|
||||
_create_schema_v1, _create_schema_v2, _create_schema_v3, _create_schema_v4,
|
||||
)
|
||||
|
||||
|
||||
@@ -475,9 +495,47 @@ class SqliteSessionStore:
|
||||
return True
|
||||
|
||||
|
||||
def delete(self, key: str) -> bool:
|
||||
def archives_imported(self) -> bool:
|
||||
with self.transaction(write=False) as db:
|
||||
return db.execute("SELECT 1 FROM storage_meta WHERE key='session_archives_imported'").fetchone() is not None
|
||||
|
||||
def archived_keys(self) -> list[str]:
|
||||
with self.transaction(write=False) as db:
|
||||
encoded = db.execute("SELECT json_group_array(key) FROM (SELECT key FROM session_archives ORDER BY key)").fetchone()[0]
|
||||
return cast(list[str], json.loads(encoded))
|
||||
|
||||
def import_archives(self, keys: list[str]) -> list[str]:
|
||||
with self.transaction() as db:
|
||||
return db.execute("DELETE FROM sessions WHERE key=?", (key,)).rowcount > 0
|
||||
if self.archives_imported():
|
||||
return self.archived_keys()
|
||||
imported = self.set_archived_keys(keys)
|
||||
db.execute("INSERT INTO storage_meta (key, value) VALUES ('session_archives_imported', '1')")
|
||||
return imported
|
||||
|
||||
def set_archived_keys(self, keys: list[str]) -> list[str]:
|
||||
with self.transaction() as db:
|
||||
current = set(self.archived_keys())
|
||||
requested = set(keys)
|
||||
# Existing memberships are valid by FK; only new keys need validation.
|
||||
added = requested - current
|
||||
if added:
|
||||
added = {row[0] for row in db.execute(
|
||||
"SELECT key FROM sessions WHERE key IN (SELECT value FROM json_each(?))",
|
||||
(_encode(list(added)),),
|
||||
)}
|
||||
target = (requested & current) | added
|
||||
db.executemany("DELETE FROM session_archives WHERE key=?", ((key,) for key in current - target))
|
||||
now = datetime.now().isoformat()
|
||||
db.executemany("INSERT INTO session_archives (key, archived_at) VALUES (?, ?)", ((key, now) for key in target - current))
|
||||
return sorted(target)
|
||||
|
||||
def delete(self, key: str, *, preserve_archive: bool = False) -> bool:
|
||||
with self.transaction() as db:
|
||||
archived = False
|
||||
if not preserve_archive:
|
||||
archived = db.execute("DELETE FROM session_archives WHERE key=?", (key,)).rowcount > 0
|
||||
deleted = db.execute("DELETE FROM sessions WHERE key=?", (key,)).rowcount > 0
|
||||
return archived or deleted
|
||||
|
||||
def list_sessions(self) -> list[SessionInfo]:
|
||||
with self.transaction(write=False) as db:
|
||||
|
||||
@@ -83,6 +83,8 @@ class SessionState:
|
||||
thread_name_prefix="session-write",
|
||||
)
|
||||
self._closed = False
|
||||
# Import completion is permanent; archive contents are never cached.
|
||||
self._archives_imported = False
|
||||
self._close_task: asyncio.Task[None] | None = None
|
||||
self._loop: asyncio.AbstractEventLoop | None = None
|
||||
|
||||
@@ -121,12 +123,14 @@ class SessionState:
|
||||
*,
|
||||
operation_name: str | None = None,
|
||||
write: bool = True,
|
||||
barrier: bool = True,
|
||||
) -> _T:
|
||||
async def run() -> _T:
|
||||
return await self._run_operation(operation, write=write)
|
||||
|
||||
return await self._submit(
|
||||
key, run, operation_name=operation_name or getattr(operation, "__name__", "session operation"),
|
||||
barrier=barrier,
|
||||
)
|
||||
|
||||
async def _submit(
|
||||
@@ -817,6 +821,34 @@ class SessionState:
|
||||
write=False,
|
||||
)
|
||||
|
||||
async def archives_imported(self) -> bool:
|
||||
if not self._archives_imported and await self._execute(
|
||||
None, self._store.archives_imported, operation_name="archives_imported",
|
||||
write=False, barrier=False,
|
||||
):
|
||||
self._archives_imported = True
|
||||
return self._archives_imported
|
||||
|
||||
async def archived_keys(self) -> list[str]:
|
||||
return await self._execute(
|
||||
None, self._store.archived_keys, operation_name="archived_keys",
|
||||
write=False, barrier=False,
|
||||
)
|
||||
|
||||
async def import_archives(self, keys: Sequence[str]) -> list[str]:
|
||||
values = list(keys)
|
||||
imported = await self._execute(
|
||||
None, lambda: self._store.import_archives(values), operation_name="import_archives",
|
||||
)
|
||||
self._archives_imported = True
|
||||
return imported
|
||||
|
||||
async def set_archived_keys(self, keys: Sequence[str]) -> list[str]:
|
||||
values = list(dict.fromkeys(keys))
|
||||
return await self._execute(
|
||||
None, lambda: self._store.set_archived_keys(values), operation_name="set_archived_keys",
|
||||
)
|
||||
|
||||
async def list_sessions(self) -> list[dict[str, Any]]:
|
||||
return await self._execute(
|
||||
None,
|
||||
@@ -1114,7 +1146,7 @@ class SessionState:
|
||||
for name in (*_RESERVED_KEYS, "webui_recovery", "_last_summary", "_stopped_at_iteration_limit"):
|
||||
session.metadata.pop(name, None)
|
||||
if session.policy.persist:
|
||||
self._store.delete(key)
|
||||
self._store.delete(key, preserve_archive=True)
|
||||
self._commit(session)
|
||||
return session
|
||||
|
||||
|
||||
@@ -60,7 +60,6 @@ from nanobot.webui.session_access import (
|
||||
session_mentions_runtime_context,
|
||||
)
|
||||
from nanobot.webui.session_identity import is_valid_webui_chat_id, webui_session_key
|
||||
from nanobot.webui.sidebar_state import write_webui_sidebar_state
|
||||
from nanobot.webui.temporary_chats import TemporaryChatError
|
||||
from nanobot.webui.transcription_ws import webui_transcription_event
|
||||
|
||||
@@ -405,10 +404,7 @@ class WebUICommandRouter:
|
||||
)
|
||||
return
|
||||
try:
|
||||
saved_state = await asyncio.to_thread(
|
||||
write_webui_sidebar_state,
|
||||
cast(dict[str, Any], state),
|
||||
)
|
||||
saved_state = await self._http_router.sidebar_state.write(cast(dict[str, Any], state))
|
||||
except (OSError, ValueError):
|
||||
await self._transport.webui_send_event(
|
||||
connection,
|
||||
|
||||
@@ -1,23 +1,29 @@
|
||||
"""Persisted WebUI sidebar workspace state.
|
||||
"""Compose sidebar preferences with session archive state.
|
||||
|
||||
This state is UI-only metadata, scoped to the active nanobot instance data
|
||||
directory (the directory containing the current config.json). It deliberately
|
||||
does not modify agent sessions.
|
||||
Layout and display preferences stay in the config-scoped JSON file. Archive
|
||||
flags live in the session database; the public sidebar payload combines both.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import AsyncGenerator
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
from typing import Any, cast
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from nanobot.config.paths import get_webui_dir
|
||||
from nanobot.utils.cancellation import shield_and_drain
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from nanobot.session.state import SessionState
|
||||
|
||||
WEBUI_SIDEBAR_STATE_SCHEMA_VERSION = 1
|
||||
_MAX_STATE_FILE_BYTES = 256 * 1024
|
||||
@@ -41,7 +47,6 @@ def default_webui_sidebar_state() -> dict[str, Any]:
|
||||
return {
|
||||
"schema_version": WEBUI_SIDEBAR_STATE_SCHEMA_VERSION,
|
||||
"pinned_keys": [],
|
||||
"archived_keys": [],
|
||||
"session_order": [],
|
||||
"title_overrides": {},
|
||||
"project_name_overrides": {},
|
||||
@@ -202,7 +207,6 @@ def normalize_webui_sidebar_state(raw: Any) -> dict[str, Any]:
|
||||
raw = cast(dict[str, Any], raw)
|
||||
state = default_webui_sidebar_state()
|
||||
state["pinned_keys"] = _clean_string_list(raw.get("pinned_keys"))
|
||||
state["archived_keys"] = _clean_string_list(raw.get("archived_keys"))
|
||||
state["session_order"] = _clean_string_list(raw.get("session_order"))
|
||||
state["title_overrides"] = _clean_title_overrides(raw.get("title_overrides"))
|
||||
state["project_name_overrides"] = _clean_title_overrides(
|
||||
@@ -233,13 +237,64 @@ def read_webui_sidebar_state() -> dict[str, Any]:
|
||||
return normalize_webui_sidebar_state(raw)
|
||||
|
||||
|
||||
def read_legacy_archived_keys() -> list[str]:
|
||||
"""Do not mark the import complete when the source cannot be read."""
|
||||
path = webui_sidebar_state_path()
|
||||
try:
|
||||
with path.open(encoding="utf-8") as source:
|
||||
raw = json.load(source)
|
||||
except FileNotFoundError:
|
||||
return []
|
||||
if not isinstance(raw, dict):
|
||||
raise ValueError("sidebar state must be an object")
|
||||
return _clean_string_list(cast(dict[str, Any], raw).get("archived_keys"))
|
||||
|
||||
|
||||
def remove_legacy_archived_keys() -> None:
|
||||
with _SIDEBAR_STATE_WRITE_LOCK:
|
||||
path = webui_sidebar_state_path()
|
||||
try:
|
||||
with path.open(encoding="utf-8") as source:
|
||||
raw = json.load(source)
|
||||
except FileNotFoundError:
|
||||
return
|
||||
if isinstance(raw, dict) and "archived_keys" in raw:
|
||||
_write_webui_sidebar_state(cast(dict[str, Any], raw))
|
||||
|
||||
|
||||
def write_webui_sidebar_state(raw: dict[str, Any]) -> dict[str, Any]:
|
||||
with _SIDEBAR_STATE_WRITE_LOCK:
|
||||
return _write_webui_sidebar_state(raw)
|
||||
|
||||
|
||||
def write_webui_sidebar_preferences(raw: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Archive-only changes must not rewrite the unchanged preference file."""
|
||||
with _SIDEBAR_STATE_WRITE_LOCK:
|
||||
target = normalize_webui_sidebar_state(raw)
|
||||
current: object = None
|
||||
try:
|
||||
with webui_sidebar_state_path().open("rb") as source:
|
||||
encoded = source.read(_MAX_STATE_FILE_BYTES + 1)
|
||||
if len(encoded) <= _MAX_STATE_FILE_BYTES:
|
||||
current = json.loads(encoded)
|
||||
except (OSError, ValueError):
|
||||
# Comparison is optional; the normal write still validates and
|
||||
# reports errors, and can replace a missing or damaged file.
|
||||
pass
|
||||
if isinstance(current, dict) and "archived_keys" not in current:
|
||||
previous_timestamp = cast(dict[str, Any], current).get("updated_at")
|
||||
if previous_timestamp is None or isinstance(previous_timestamp, str):
|
||||
target["updated_at"] = previous_timestamp
|
||||
if target == current:
|
||||
return target
|
||||
return _persist_webui_sidebar_state(target)
|
||||
|
||||
|
||||
def _write_webui_sidebar_state(raw: dict[str, Any]) -> dict[str, Any]:
|
||||
state = normalize_webui_sidebar_state(raw)
|
||||
return _persist_webui_sidebar_state(normalize_webui_sidebar_state(raw))
|
||||
|
||||
|
||||
def _persist_webui_sidebar_state(state: dict[str, Any]) -> dict[str, Any]:
|
||||
state["updated_at"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
||||
encoded = json.dumps(
|
||||
state,
|
||||
@@ -268,3 +323,75 @@ def _write_webui_sidebar_state(raw: dict[str, Any]) -> dict[str, Any]:
|
||||
finally:
|
||||
os.close(dir_fd)
|
||||
return state
|
||||
|
||||
|
||||
async def ensure_webui_archives_imported(sessions: SessionState) -> None:
|
||||
if not await sessions.archives_imported():
|
||||
legacy = await asyncio.to_thread(read_legacy_archived_keys)
|
||||
await sessions.import_archives(legacy)
|
||||
await asyncio.to_thread(remove_legacy_archived_keys)
|
||||
|
||||
|
||||
async def ensure_webui_session_archives(sessions: SessionState) -> list[str]:
|
||||
await ensure_webui_archives_imported(sessions)
|
||||
return await sessions.archived_keys()
|
||||
|
||||
|
||||
class WebUISidebarState:
|
||||
def __init__(self, sessions: SessionState | None) -> None:
|
||||
self._sessions = sessions
|
||||
self._lock = asyncio.Lock()
|
||||
self._readers = 0
|
||||
self._readers_drained = asyncio.Event()
|
||||
self._readers_drained.set()
|
||||
|
||||
@asynccontextmanager
|
||||
async def _read_snapshot(self) -> AsyncGenerator[None, None]:
|
||||
# The FIFO admission lock lets readers overlap without overtaking a writer.
|
||||
async with self._lock:
|
||||
self._readers += 1
|
||||
self._readers_drained.clear()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
self._readers -= 1
|
||||
if not self._readers:
|
||||
self._readers_drained.set()
|
||||
|
||||
async def read(self) -> dict[str, Any]:
|
||||
async with self._read_snapshot():
|
||||
if self._sessions is None:
|
||||
preferences = await asyncio.to_thread(read_webui_sidebar_state)
|
||||
return {**preferences, "archived_keys": []}
|
||||
await ensure_webui_archives_imported(self._sessions)
|
||||
preferences, archived = await asyncio.gather(
|
||||
asyncio.to_thread(read_webui_sidebar_state), self._sessions.archived_keys(),
|
||||
)
|
||||
return {**preferences, "archived_keys": archived}
|
||||
|
||||
async def write(self, raw: dict[str, Any]) -> dict[str, Any]:
|
||||
# Keep each successful wire snapshot ordered across the two stores.
|
||||
async with self._lock:
|
||||
await self._readers_drained.wait()
|
||||
return await shield_and_drain(self._write_snapshot(raw))
|
||||
|
||||
async def _write_snapshot(self, raw: dict[str, Any]) -> dict[str, Any]:
|
||||
if self._sessions is None:
|
||||
preferences = await asyncio.to_thread(write_webui_sidebar_preferences, raw)
|
||||
return {**preferences, "archived_keys": []}
|
||||
await ensure_webui_archives_imported(self._sessions)
|
||||
preferences, archived = await asyncio.gather(
|
||||
asyncio.to_thread(write_webui_sidebar_preferences, raw), self._sessions.archived_keys(),
|
||||
return_exceptions=True,
|
||||
)
|
||||
# Settle both branches before releasing admission, including failed reads.
|
||||
if isinstance(preferences, BaseException):
|
||||
raise preferences
|
||||
if isinstance(archived, BaseException):
|
||||
raise archived
|
||||
if "archived_keys" in raw:
|
||||
target = _clean_string_list(raw["archived_keys"])
|
||||
# Unchanged flags complete at the committed read, without a writer.
|
||||
if set(target) != set(archived):
|
||||
archived = await self._sessions.set_archived_keys(target)
|
||||
return {**preferences, "archived_keys": archived}
|
||||
@@ -112,8 +112,8 @@ from nanobot.webui.session_list_index import (
|
||||
list_webui_sessions,
|
||||
)
|
||||
from nanobot.webui.sidebar_state import (
|
||||
read_webui_sidebar_state,
|
||||
write_webui_sidebar_state,
|
||||
WebUISidebarState,
|
||||
ensure_webui_archives_imported,
|
||||
)
|
||||
from nanobot.webui.skills_api import (
|
||||
SkillManagementError,
|
||||
@@ -395,6 +395,7 @@ class GatewayHTTPHandler:
|
||||
) -> None:
|
||||
self.config = config
|
||||
self.session_manager = session_manager
|
||||
self.sidebar_state = WebUISidebarState(session_manager.state if session_manager is not None else None)
|
||||
self.static_dist_path = static_dist_path
|
||||
self.runtime_model_name = runtime_model_name
|
||||
self.bus = bus
|
||||
@@ -1370,6 +1371,7 @@ class GatewayHTTPHandler:
|
||||
"automations": serialize_automation_jobs(automation_jobs),
|
||||
}
|
||||
)
|
||||
await ensure_webui_archives_imported(self.session_manager.state)
|
||||
if automation_jobs:
|
||||
for job in automation_jobs:
|
||||
if isinstance(job, LocalTrigger):
|
||||
@@ -1707,9 +1709,9 @@ class GatewayHTTPHandler:
|
||||
return _http_error(500, "failed to save reminder preference")
|
||||
return _http_json_response({"show": show})
|
||||
if got == "/api/webui/sidebar-state":
|
||||
return self._handle_webui_sidebar_state(request)
|
||||
return await self._handle_webui_sidebar_state(request)
|
||||
if got == "/api/webui/sidebar-state/update":
|
||||
return self._handle_webui_sidebar_state_update(request)
|
||||
return await self._handle_webui_sidebar_state_update(request)
|
||||
return None
|
||||
|
||||
def _handle_commands(self, request: WsRequest) -> Response:
|
||||
@@ -1951,12 +1953,17 @@ class GatewayHTTPHandler:
|
||||
return _http_error(404, "skill not found")
|
||||
return _http_json_response(payload)
|
||||
|
||||
def _handle_webui_sidebar_state(self, request: WsRequest) -> Response:
|
||||
async def _handle_webui_sidebar_state(self, request: WsRequest) -> Response:
|
||||
if not self.check_api_token(request):
|
||||
return _http_error(401, "Unauthorized")
|
||||
return _http_json_response(read_webui_sidebar_state())
|
||||
try:
|
||||
state = await self.sidebar_state.read()
|
||||
except (OSError, ValueError):
|
||||
self._log.exception("failed to read webui sidebar state")
|
||||
return _http_error(500, "failed to read sidebar state")
|
||||
return _http_json_response(state)
|
||||
|
||||
def _handle_webui_sidebar_state_update(self, request: WsRequest) -> Response:
|
||||
async def _handle_webui_sidebar_state_update(self, request: WsRequest) -> Response:
|
||||
if not self.check_api_token(request):
|
||||
return _http_error(401, "Unauthorized")
|
||||
payload = _mutation_payload(request)
|
||||
@@ -1966,7 +1973,7 @@ class GatewayHTTPHandler:
|
||||
if not isinstance(state_value, dict):
|
||||
return _http_error(400, "state must be an object")
|
||||
try:
|
||||
state = write_webui_sidebar_state(cast(dict[str, Any], state_value))
|
||||
state = await self.sidebar_state.write(cast(dict[str, Any], state_value))
|
||||
except ValueError as e:
|
||||
return _http_error(400, str(e))
|
||||
except OSError:
|
||||
|
||||
Reference in new issue
Block a user