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

+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()