fix(webui): keep saved topics bound to their project (#6509)

* fix(webui): keep saved topics bound to their project

Lock the project as soon as the session exists, independently of loaded history. Validate both explicit updates and message admissions against the persisted directory while retaining same-project permission changes.

Related to #6505.

Co-authored-by: Xiaoyu-hub <17346801517@163.com>

* test(agent): retain goal shutdown failure stacks

Use the existing stop_loop diagnostic without changing the five-second teardown deadline or the goal assertions. The Windows failure on #6509 reached session shutdown but did not capture its worker stacks.

* test(cron): await rearm tick completion instead of disk timing

The Windows run completed the first and last jobs correctly, but rescheduling took over three seconds inside a two-second timeout. Await the original timer task, detect an early exit before callback entry, and preserve job-order, cancellation, persistence and rearming assertions. Keep real disk writes and all parameterized cases.

Also place the goal-shutdown diagnostic import in the existing first-party group.

---------

Co-authored-by: Xiaoyu-hub <17346801517@163.com>
This commit is contained in:
chengyongruandXiaoyu-hub authored and GitHub committed 2026-10-28 21:37:23 +08:00
1 parent 8f7a7d1759
commit 4a14faa47e
17 files changed
+241 -85

No files matched your search

@@ -1801,6 +1801,7 @@ async def test_webui_message_scope_inherits_persisted_session_scope(
},
)
assert sessions.list_sessions() == []
conn.reset_mock()
await channel._dispatch_envelope(
conn,
"webui-client",
@@ -1812,6 +1813,70 @@ async def test_webui_message_scope_inherits_persisted_session_scope(
"project_path": str(project.resolve()),
"access_mode": "full",
}
assert any(
event.get("event") == "session_updated" and event.get("scope") == "metadata"
for event in (json.loads(call.args[0]) for call in conn.send.await_args_list)
)
@pytest.mark.parametrize("command", ["set_workspace_scope", "message"])
@pytest.mark.parametrize("persist_during_request", [False, True], ids=["existing", "admission-race"])
async def test_persisted_project_rejects_scope_changes_but_keeps_access_controls(
bus: MagicMock, tmp_path, monkeypatch, command: str, persist_during_request: bool,
) -> None:
from nanobot.security.workspace_access import default_workspace_scope
project = tmp_path / "other-project"
project.mkdir()
sessions = SessionManager(tmp_path / "sessions")
channel = WebSocketChannel(
{"enabled": True, "allowFrom": ["*"]}, bus,
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=tmp_path),
)
controller = channel.gateway.workspaces
scope = default_workspace_scope(tmp_path, True)
chat_id = "bound-project"
if persist_during_request:
method = "scope_for_message" if command == "message" else "scope_for_set_request"
resolve = getattr(controller, method)
async def resolve_before_other_admission(*args, **kwargs):
requested = await resolve(*args, **kwargs)
await controller.persist_scope(chat_id, scope)
return requested
monkeypatch.setattr(controller, method, resolve_before_other_admission)
else:
await controller.persist_scope(chat_id, scope)
conn = AsyncMock()
conn.remote_address = ("203.0.113.8", 50123)
await channel._dispatch_envelope(conn, "remote-client", {
"type": command, "chat_id": chat_id, "turn_id": "scope-change",
"webui": True, "content": "continue editing",
"workspace_scope": {"project_path": str(project), "access_mode": "full"},
})
rejected = json.loads(conn.send.await_args.args[0])
assert rejected["event"] == "error"
assert rejected["detail"] == "workspace_scope_rejected"
assert rejected["reason"] == "project_locked"
assert rejected["chat_id"] == chat_id
if command == "message":
assert rejected["turn_id"] == "scope-change"
bus.publish_inbound.assert_not_awaited()
saved = sessions.read_session_file(f"websocket:{chat_id}")
assert saved["messages"] == []
assert saved["metadata"]["workspace_scope"] == scope.metadata()
if persist_during_request:
monkeypatch.setattr(controller, method, resolve)
for mode in ("full", "restricted"):
await channel._dispatch_envelope(conn, "remote-client", {
"type": "set_workspace_scope", "chat_id": chat_id,
"workspace_scope": {"project_path": str(tmp_path), "access_mode": mode},
})
assert json.loads(conn.send.await_args.args[0])["workspace_scope"]["access_mode"] == mode
assert controller.scope_for_session_key(f"websocket:{chat_id}").project_path == tmp_path.resolve()
@pytest.mark.asyncio
@@ -5850,6 +5915,7 @@ def test_sessions_list_includes_active_run_started_at(monkeypatch) -> None:
"preview": "work",
"model_preset": "fast",
"run_started_at": 1_700_000_000.0,
"project_locked": True,
"handle": handle.public_payload(),
}
]
@@ -2412,6 +2412,7 @@ async def test_sessions_list_only_returns_websocket_sessions_by_default(
project.resolve()
)
assert rows["websocket:beta"]["workspace_scope"]["access_mode"] == "restricted"
assert all(row["project_locked"] is True for row in sessions)
assert all(not any(key.startswith("_") for key in row) for row in sessions)
finally:
await channel.stop()
+4 -1
View File
@@ -617,8 +617,9 @@ class SessionState:
updates: Mapping[str, Any],
*,
expected_generation: str | None = None,
validate_existing: Callable[[Mapping[str, Any]], None] | None = None,
) -> tuple[str, bool]:
"""Open one generation and atomically attach admission metadata."""
"""Open one generation and atomically validate and attach admission metadata."""
values = deepcopy(dict(updates))
if _RESERVED_KEYS.intersection(values):
raise ValueError("turn state must be changed through turn operations")
@@ -638,6 +639,8 @@ class SessionState:
and session.generation != expected_generation
):
raise SessionConflictError("session admission belongs to a replaced session")
if not created and validate_existing is not None:
validate_existing(session.metadata)
session.metadata.update(values)
header_only = session.policy.persist and session.persisted
if header_only:
+22 -9
View File
@@ -456,7 +456,10 @@ class WebUICommandRouter:
)
if scope is None:
return
await self._workspaces.stage_scope(chat_id, scope)
if await self.workspace_scope_or_error(
connection, lambda: self._workspaces.stage_scope(chat_id, scope), chat_id=chat_id,
) is None:
return
await self._transport.send_session_updated(chat_id, scope="metadata")
await self._transport.webui_send_event(
connection,
@@ -759,16 +762,24 @@ class WebUICommandRouter:
execution_created = False
try:
if not restart_control:
session_generation, session_created = await self._workspaces.persist_scope(
chat_id,
scope,
session_key=admission_session_key,
expected_generation=(
temporary_policy.session_generation
if temporary_policy is not None
else None
admission = await self.workspace_scope_or_error(
connection,
lambda: self._workspaces.persist_scope(
chat_id,
scope,
session_key=admission_session_key,
expected_generation=(
temporary_policy.session_generation
if temporary_policy is not None
else None
),
),
chat_id=chat_id,
turn_id=turn_id,
)
if admission is None:
return
session_generation, session_created = admission
execution_generation = session_generation
if (
execution_session_key != admission_session_key
@@ -859,6 +870,8 @@ class WebUICommandRouter:
if name:
attachment["name"] = name
if is_webui and not restart_control:
if session_created:
await self._transport.send_session_updated(chat_id, scope="metadata")
await self.broadcast_user_message(
connection,
chat_id,
+60 -18
View File
@@ -2,12 +2,15 @@
from __future__ import annotations
import asyncio
import json
import os
import platform
import socket
import time
import weakref
from collections import OrderedDict
from collections.abc import Mapping
from pathlib import Path
from typing import TYPE_CHECKING, Any, cast
@@ -23,6 +26,7 @@ from nanobot.security.workspace_access import (
default_workspace_scope,
validate_workspace_scope_payload,
)
from nanobot.session.webui_turns import websocket_turn_wall_started_at
from nanobot.webui.session_identity import webui_session_key
if TYPE_CHECKING:
@@ -223,6 +227,15 @@ class WebUIWorkspaceController:
self._default_workspace = default_workspace
self._default_restrict_to_workspace = default_restrict_to_workspace
self._draft_scopes: OrderedDict[str, WorkspaceScope] = OrderedDict()
self._scope_locks: weakref.WeakValueDictionary[str, asyncio.Lock] = weakref.WeakValueDictionary()
def _scope_lock(self, chat_id: str) -> asyncio.Lock:
"""Serialize draft edits with message admission, not with agent execution."""
lock = self._scope_locks.get(chat_id)
if lock is None:
lock = asyncio.Lock()
self._scope_locks[chat_id] = lock
return lock
def default_scope(self) -> WorkspaceScope:
return default_scope_for_webui(
@@ -316,6 +329,15 @@ class WebUIWorkspaceController:
cast(object, metadata_data.get(WORKSPACE_SCOPE_METADATA_KEY))
)
def _validate_existing_project(self, metadata: Mapping[str, Any], scope: WorkspaceScope) -> None:
raw = metadata.get(WORKSPACE_SCOPE_METADATA_KEY)
stored = cast(dict[str, Any], raw) if isinstance(raw, dict) else {}
path = stored.get("project_path") or stored.get("path")
# Compare the stored path even when the directory has since disappeared.
project = Path(path) if isinstance(path, str) and path else self._default_workspace
if project.expanduser().resolve(strict=False) != scope.project_path:
raise WorkspaceScopeError("project_locked", status=409)
def payload(
self,
*,
@@ -375,11 +397,17 @@ class WebUIWorkspaceController:
session_key: str | None,
can_change_project: bool,
) -> WorkspaceScope:
current = (
await self.async_scope_for_session_key(session_key)
if session_key
else self.default_scope()
data = (
await self._sessions.state.read_metadata(session_key)
if self._sessions is not None and session_key else None
)
if data is not None:
current = self._scope_from_snapshot(data)
elif session_key and (draft := self._draft_scopes.get(session_key)) is not None:
self._draft_scopes.move_to_end(session_key)
current = draft
else:
current = self.default_scope()
raw = envelope.get(WORKSPACE_SCOPE_METADATA_KEY)
if raw is None:
scope = current
@@ -390,6 +418,8 @@ class WebUIWorkspaceController:
default_restrict_to_workspace=self._default_restrict_to_workspace,
source_channel=_WEBUI_SCOPE_CHANNEL,
)
if data is not None:
self._validate_existing_project(data["metadata"], scope)
if not can_change_project and not _scope_change_is_non_escalating(current, scope):
raise WorkspaceScopeError(
"project selection is unavailable for this connection",
@@ -455,7 +485,14 @@ class WebUIWorkspaceController:
session_key: str | None = None,
expected_generation: str | None = None,
) -> tuple[str | None, bool]:
session_key = session_key or webui_session_key(chat_id)
async with self._scope_lock(chat_id):
return await self._persist_scope(
session_key or webui_session_key(chat_id), scope, expected_generation,
)
async def _persist_scope(
self, session_key: str, scope: WorkspaceScope, expected_generation: str | None = None,
) -> tuple[str | None, bool]:
generation = expected_generation
created = False
if self._sessions is not None:
@@ -463,6 +500,7 @@ class WebUIWorkspaceController:
session_key,
{"webui": True, WORKSPACE_SCOPE_METADATA_KEY: scope.metadata()},
expected_generation=generation,
validate_existing=lambda metadata: self._validate_existing_project(metadata, scope),
)
self._draft_scopes.pop(session_key, None)
remember_webui_project(scope.project_path)
@@ -483,20 +521,24 @@ class WebUIWorkspaceController:
expected_generation=generation,
)
async def stage_scope(self, chat_id: str, scope: WorkspaceScope) -> None:
async def stage_scope(self, chat_id: str, scope: WorkspaceScope) -> WorkspaceScope:
"""Keep a new chat's scope transient until its first accepted message."""
session_key = webui_session_key(chat_id)
if (
self._sessions is not None
and await self._sessions.state.read_metadata(session_key) is not None
):
await self.persist_scope(chat_id, scope)
return
remember_webui_project(scope.project_path)
self._draft_scopes[session_key] = scope
self._draft_scopes.move_to_end(session_key)
while len(self._draft_scopes) > _MAX_DRAFT_SCOPES:
self._draft_scopes.popitem(last=False)
async with self._scope_lock(chat_id):
if websocket_turn_wall_started_at(chat_id) is not None:
raise WorkspaceScopeError("chat_running", status=409)
session_key = webui_session_key(chat_id)
if (
self._sessions is not None
and await self._sessions.state.read_metadata(session_key) is not None
):
await self._persist_scope(session_key, scope)
return scope
remember_webui_project(scope.project_path)
self._draft_scopes[session_key] = scope
self._draft_scopes.move_to_end(session_key)
while len(self._draft_scopes) > _MAX_DRAFT_SCOPES:
self._draft_scopes.popitem(last=False)
return scope
def discard_draft_scope(self, session_key: str) -> bool:
"""Discard the staged scope for a chat that has not persisted yet."""
+1
View File
@@ -1052,6 +1052,7 @@ class GatewayHTTPHandler:
else:
scope = default_scope
row["workspace_scope"] = scope.payload()
row["project_locked"] = True
handle = handles.get(key)
if handle is not None:
row["handle"] = handle.public_payload()