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

+3 -1
View File
@@ -163,6 +163,8 @@ Temporary does not mean consequence-free. Requests still go to the configured mo
Use the workspace picker to browse folders on the connected nanobot host, enter an absolute path, or return to recent and starred projects; favorites persist across gateway restarts. The host name appears above saved locations. Project paths refer to that machine, not the browser's filesystem.
Choose the project when starting a new topic. Saved topics, including forks, keep their project directory fixed. Start a new topic for another project. You can still change access mode within the same project while the topic is idle.
Browsing does not change the topic's workspace until you choose **Confirm**. **Filter this folder** searches only the current directory. **Cmd/Ctrl+Shift+G** opens host-path entry, with Tab completion; **Last visited folder** returns to the previous location.
Manual path entry remains available when the connected host does not support directory browsing. The host validates the selected path and access policy.
@@ -175,7 +177,7 @@ Selecting a project does not replace the configured agent workspace. The two pat
| Relative file paths and shell working directory | Long-term memory and history |
| The normal read/write boundary in Restricted mode | Custom skills and instance state |
A new topic separates conversation history; a project selection changes the file working directory. Neither creates a separate long-term memory store. Project switching can therefore carry preferences and facts learned in other topics into the new project. Use [separate instances](./multiple-instances.md) when client or user data must stay separate; see [Memory](./memory.md) for how shared memory is maintained.
A new topic separates conversation history; a project selection changes the file working directory. Neither creates a separate long-term memory store. Choosing another project for a new topic can therefore carry preferences and facts learned in other topics into the new project. Use [separate instances](./multiple-instances.md) when client or user data must stay separate; see [Memory](./memory.md) for how shared memory is maintained.
Project-local `SOUL.md` and `USER.md` files are ignored, and the agent workspace's `AGENTS.md` is not inherited by a separately selected project. When the selected project is the configured agent workspace, both roles naturally use the same directory.
@@ -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()
+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:
+2 -4
View File
@@ -791,10 +791,8 @@ export function ThreadShell({
const showHeroComposer = displayMessages.length === 0 && !initialHistoryLoading;
const composerVariant = showHeroComposer ? emptyComposerVariant : "thread";
// The server owns the project lock. Old servers have no marker, so an existing
// user turn is read-only here too; the gateway remains the editing authority.
const projectLocked = session?.projectLocked === true
|| (session?.projectLocked === undefined && displayMessages.some((message) => message.role === "user" && message.deliveryStatus !== "failed"));
// Only unpersisted drafts can choose a project; history pages do not own this state.
const projectLocked = !!session && session.projectLocked !== false;
const wasShowingHeroComposerRef = useRef(showHeroComposer);
const sessionModelPreset = session?.modelPreset?.trim() || null;
const [localModelPreset, setLocalModelPreset] = useState<string | null>(null);
+1
View File
@@ -137,6 +137,7 @@ export function useSessions(): {
preview: "",
modelPreset: modelPreset ?? null,
workspaceScope: workspaceScope ?? null,
projectLocked: false,
},
...prev.filter((s) => s.key !== key),
]);
+1 -1
View File
@@ -228,7 +228,7 @@ export async function listSessions(
runStartedAt: s.run_started_at ?? null,
recoveryState: s.recovery_state ?? null,
workspaceScope: s.workspace_scope ?? null,
projectLocked: s.project_locked,
projectLocked: s.project_locked ?? true,
handle,
};
});
+1 -1
View File
@@ -457,7 +457,7 @@ export interface ChatSummary {
/** Durable recovery state that needs attention after an interrupted turn. */
recoveryState?: RecoveryState | null;
workspaceScope?: WorkspaceScopePayload | null;
/** Server-owned project binding after the first accepted user message. */
/** Persisted sessions keep their project; only unpersisted drafts can change it. */
projectLocked?: boolean;
/** Stable, server-owned @handle for this session. */
handle?: SessionHandle | null;
+3 -1
View File
@@ -1299,7 +1299,7 @@ describe("webui API helpers", () => {
);
});
it("maps generated session titles from the sessions list", async () => {
it.each([true, undefined])("maps saved sessions with project_locked=%s", async (projectLocked) => {
vi.mocked(fetch).mockResolvedValueOnce({
ok: true,
json: async () => ({
@@ -1309,6 +1309,7 @@ describe("webui API helpers", () => {
created_at: "2026-05-01T10:00:00",
updated_at: "2026-05-01T10:01:00",
title: "优化 WebUI 标题",
project_locked: projectLocked,
model_preset: "fast",
run_started_at: 1_700_000_000,
handle: {
@@ -1324,6 +1325,7 @@ describe("webui API helpers", () => {
{
key: "websocket:chat-1",
title: "优化 WebUI 标题",
projectLocked: true,
preview: "",
modelPreset: "fast",
runStartedAt: 1_700_000_000,
+2 -2
View File
@@ -5724,7 +5724,7 @@ describe("ThreadShell", () => {
expect(screen.getByRole("option", { name: /Other project/i })).toBeInTheDocument();
});
it("allows project selection before first input and locks it after acceptance without duplicating the sidebar label", async () => {
it.each([true, undefined])("locks saved topics with projectLocked=%s independently of displayed history", async (projectLocked) => {
const client = makeClient();
const scope = { project_path: "/srv/alpha", project_name: "alpha", access_mode: "restricted" as const };
const props = {
@@ -5736,7 +5736,7 @@ describe("ThreadShell", () => {
expect(await screen.findByRole("button", { name: "Switch directory" })).toBeEnabled();
expect(screen.getByTestId("thread-header")).not.toHaveTextContent("alpha");
rerender(wrap(client, <ThreadShell {...props} session={{ ...session("project-chat"), projectLocked: true }} />));
rerender(wrap(client, <ThreadShell {...props} session={{ ...session("project-chat"), projectLocked }} />));
expect(screen.queryByRole("button", { name: "Switch directory" })).not.toBeInTheDocument();
expect(screen.getByTestId("thread-header")).not.toHaveTextContent("alpha");
expect(screen.getByRole("button", { name: "Workspace access mode: Default Permission" })).toBeEnabled();
+9 -13
View File
@@ -257,18 +257,9 @@ describe("useSessions", () => {
expect(result.current.sessions.map((s) => s.key)).toEqual(["websocket:chat-a"]);
});
it("refreshes sessions when the websocket reports a session update", async () => {
it("locks a draft project when a session update reports it persisted", async () => {
vi.mocked(api.listSessions)
.mockResolvedValueOnce([
{
key: "websocket:chat-a",
channel: "websocket",
chatId: "chat-a",
createdAt: "2026-04-16T10:00:00Z",
updatedAt: "2026-04-16T10:00:00Z",
preview: "",
},
])
.mockResolvedValueOnce([])
.mockResolvedValueOnce([
{
key: "websocket:chat-a",
@@ -278,21 +269,26 @@ describe("useSessions", () => {
updatedAt: "2026-04-16T10:01:00Z",
title: "生成的小标题",
preview: "用户第一句话",
projectLocked: true,
},
]);
const client = fakeClient();
client.newChat.mockResolvedValue("chat-a");
const { result } = renderHook(() => useSessions(), {
wrapper: wrap(client),
});
await waitFor(() => expect(result.current.sessions[0]?.title).toBeUndefined());
await waitFor(() => expect(result.current.loading).toBe(false));
await act(async () => { await result.current.createChat(); });
expect(result.current.sessions[0].projectLocked).toBe(false);
act(() => {
client.emitSessionUpdate("chat-a");
client.emitSessionUpdate("chat-a", "metadata");
});
await waitFor(() => expect(result.current.sessions[0]?.title).toBe("生成的小标题"));
expect(result.current.sessions[0].projectLocked).toBe(true);
expect(api.listSessions).toHaveBeenCalledTimes(2);
});