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

+2 -2
View File
@@ -5,6 +5,7 @@ from unittest.mock import AsyncMock, MagicMock
import pytest
from agent.session_helpers import stop_loop
from nanobot.agent.goal_permission import goal_mutation_allowed, goal_mutation_permission
from nanobot.agent.loop import AgentLoop
from nanobot.bus.events import InboundMessage
@@ -89,8 +90,7 @@ async def test_goal_input_enters_running_turn_with_scoped_permission(tmp_path, c
assert public_history_messages(hidden)[0]["content"] == task
finally:
release.set()
loop.stop()
await asyncio.wait_for(run, 5)
await stop_loop(loop, run, timeout=5)
async def test_scheduled_goal_command_cannot_generate_internal_input(tmp_path):
+41 -32
View File
@@ -9,6 +9,18 @@ from nanobot.cron.service import CronService
from nanobot.cron.types import CronJob, CronSchedule
async def _wait_for_job_entry(timer: asyncio.Task[None], entered: asyncio.Event) -> None:
entry = asyncio.create_task(entered.wait())
try:
await asyncio.wait((timer, entry), return_when=asyncio.FIRST_COMPLETED)
if timer.done():
await timer
assert entered.is_set(), "timer finished without starting the due job"
finally:
entry.cancel()
await asyncio.gather(entry, return_exceptions=True)
@pytest.mark.asyncio
@pytest.mark.parametrize("action", ["add", "update", "remove", "disable"])
@pytest.mark.parametrize("edit_from_callback", [True, False])
@@ -17,7 +29,6 @@ async def test_edit_during_timer_execution_preserves_turn(
) -> None:
entered = asyncio.Event()
release = asyncio.Event()
settled = asyncio.Event()
outcomes: list[str] = []
def add_job(name: str) -> CronJob:
@@ -50,8 +61,6 @@ async def test_edit_during_timer_execution_preserves_turn(
except asyncio.CancelledError:
outcomes.append("cancelled")
raise
finally:
settled.set()
service = CronService(tmp_path / "cron" / "jobs.json", on_job=on_job)
await service.start()
@@ -61,17 +70,18 @@ async def test_edit_during_timer_execution_preserves_turn(
active.state.next_run_at_ms = 1
service._save_store()
service._arm_timer()
async with asyncio.timeout(2):
await entered.wait()
if not edit_from_callback:
edit_store()
release.set()
await settled.wait()
timer = service._timer_task
assert timer is not None
await _wait_for_job_entry(timer, entered)
if not edit_from_callback:
edit_store()
release.set()
# Rearming cancels the finished tick; the job outcome must still be successful.
await asyncio.wait((timer,))
if not timer.cancelled():
timer.result()
assert outcomes == ["completed"]
async with asyncio.timeout(2):
while service._active_executions:
await asyncio.sleep(0)
assert service._active_executions == 0
restored = CronService(service.store_path).get_job(active.id)
assert restored is not None
assert restored.state.last_status == "ok"
@@ -93,7 +103,6 @@ async def test_edit_during_timer_execution_preserves_turn(
async def test_due_job_edited_while_waiting_is_skipped(tmp_path: Path, action: str) -> None:
entered = asyncio.Event()
release = asyncio.Event()
finished = asyncio.Event()
calls: list[str] = []
async def on_job(job: CronJob) -> None:
@@ -101,8 +110,6 @@ async def test_due_job_edited_while_waiting_is_skipped(tmp_path: Path, action: s
if job.name == "first":
entered.set()
await release.wait()
elif job.name == "last":
finished.set()
service = CronService(tmp_path / "cron" / "jobs.json", on_job=on_job)
await service.start()
@@ -123,22 +130,24 @@ async def test_due_job_edited_while_waiting_is_skipped(tmp_path: Path, action: s
service._save_store()
service._arm_timer()
async with asyncio.timeout(2):
await entered.wait()
if action == "remove":
assert service.remove_job(waiting.id) == "removed"
elif action == "disable":
service.enable_job(waiting.id, False)
else:
service.update_job(
waiting.id, schedule=CronSchedule(kind="every", every_ms=7_200_000),
)
edited = service.get_job(waiting.id)
next_run = edited.state.next_run_at_ms if edited is not None else None
release.set()
await finished.wait()
while service._active_executions:
await asyncio.sleep(0)
timer = service._timer_task
assert timer is not None
await _wait_for_job_entry(timer, entered)
if action == "remove":
assert service.remove_job(waiting.id) == "removed"
elif action == "disable":
service.enable_job(waiting.id, False)
else:
service.update_job(
waiting.id, schedule=CronSchedule(kind="every", every_ms=7_200_000),
)
edited = service.get_job(waiting.id)
next_run = edited.state.next_run_at_ms if edited is not None else None
release.set()
await asyncio.wait((timer,))
if not timer.cancelled():
timer.result()
assert service._active_executions == 0
assert calls == ["first", "last"]
restored = CronService(service.store_path)
+22
View File
@@ -203,6 +203,7 @@ async def test_new_chat_scope_is_persisted_only_after_first_message(tmp_path, mo
)
scope = default_workspace_scope(project, restrict_to_workspace=False)
await controller.stage_scope("draft-chat", default_workspace_scope(default, True))
await controller.stage_scope("draft-chat", scope)
assert sessions.list_sessions() == []
@@ -211,6 +212,27 @@ async def test_new_chat_scope_is_persisted_only_after_first_message(tmp_path, mo
await controller.persist_scope("draft-chat", scope)
assert [item["key"] for item in sessions.list_sessions()] == ["websocket:draft-chat"]
with pytest.raises(WorkspaceScopeError, match="project_locked"):
await controller.stage_scope("draft-chat", default_workspace_scope(default, True))
await controller.stage_scope("draft-chat", default_workspace_scope(project, True))
assert controller.scope_for_session_key("websocket:draft-chat").access_mode == "restricted"
async def test_missing_bound_project_does_not_allow_rebinding_to_default(tmp_path, monkeypatch) -> None:
monkeypatch.setattr("nanobot.webui.workspaces.get_webui_dir", lambda: tmp_path / "webui")
project = tmp_path / "project"
project.mkdir()
sessions = SessionManager(tmp_path / "sessions")
controller = WebUIWorkspaceController(
session_manager=sessions, default_workspace=tmp_path, default_restrict_to_workspace=True,
)
await controller.persist_scope("missing-project", default_workspace_scope(project, True))
project.rmdir()
with pytest.raises(WorkspaceScopeError, match="project_locked"):
await controller.persist_scope("missing-project", default_workspace_scope(tmp_path, True))
saved = sessions.read_session_metadata("websocket:missing-project")
assert saved["metadata"][WORKSPACE_SCOPE_METADATA_KEY]["project_path"] == str(project)
def test_scope_for_session_key_always_reads_the_active_store(tmp_path, monkeypatch) -> None: