From 77660ea8e5f186689ccd0a21058751783c63fd25 Mon Sep 17 00:00:00 2001 From: Xubin Ren <52506698+Re-bin@users.noreply.github.com> Date: Mon, 12 Oct 2026 00:02:07 +0800 Subject: [PATCH] fix(webui): keep settings restarts out of chat history --- docs/troubleshooting.md | 11 ++ nanobot/channels/websocket/runtime.py | 6 +- .../websocket/tests/test_restart_control.py | 143 ++++++++++++++++++ nanobot/webui/inbound_commands.py | 24 ++- nanobot/webui/metadata.py | 2 + 5 files changed, 181 insertions(+), 5 deletions(-) create mode 100644 nanobot/channels/websocket/tests/test_restart_control.py diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 6b600a5d3..f49e36f39 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -31,6 +31,17 @@ If `nanobot agent -m "Hello!"` fails, fix that before debugging WebUI, Telegram, `nanobot status` does not call the model. If provider/model setup is incomplete, it points to WebUI **Settings → Models** or the CLI setup wizard, then prints the command to check again. +## Empty topics after a WebUI restart + +The Restart button in WebUI settings does not create a conversation or add messages +to an existing conversation. Reopening WebUI or reconnecting to the gateway also +does not save a topic until a message or another session action creates it. + +Older gateway versions could save an empty topic when the Restart button had no +current chat. Update the gateway to stop creating these topics. Existing topics +are not deleted by the update; check their contents before removing them. A typed +`/restart` command remains part of that chat's display history. + ## Session storage overlaps the workspace Sessions live at `/sessions//`, outside the agent workspace. If startup reports a conflict, compare the printed paths. A valid layout is `bot/config.json`, `bot/sessions/`, and `bot/workspace/`. diff --git a/nanobot/channels/websocket/runtime.py b/nanobot/channels/websocket/runtime.py index e70069b21..1ccc38e10 100644 --- a/nanobot/channels/websocket/runtime.py +++ b/nanobot/channels/websocket/runtime.py @@ -47,6 +47,7 @@ from nanobot.webui.http_utils import ( from nanobot.webui.inbound_commands import WebUICommandRouter from nanobot.webui.metadata import ( WEBSOCKET_TURN_OWNER_METADATA_KEY, + WEBUI_RESTART_CONTROL_METADATA_KEY, WEBUI_TURN_METADATA_KEY, ) from nanobot.webui.outbound_projection import WebUIOutboundProjector @@ -1124,7 +1125,10 @@ class WebSocketChannel(BaseChannel): transcript_overrides: dict[str, Any] | None = None, ) -> bool: """Persist one canonical turn event and retain unsafe owners on failure.""" - if not self._temporary_chats.should_persist_transcript(chat_id): + if ( + (metadata or {}).get(WEBUI_RESTART_CONTROL_METADATA_KEY) is True + or not self._temporary_chats.should_persist_transcript(chat_id) + ): self._transcripts.prepare_event( chat_id, event, metadata=metadata, phase=phase, include_source=include_source, ) diff --git a/nanobot/channels/websocket/tests/test_restart_control.py b/nanobot/channels/websocket/tests/test_restart_control.py new file mode 100644 index 000000000..f839ab307 --- /dev/null +++ b/nanobot/channels/websocket/tests/test_restart_control.py @@ -0,0 +1,143 @@ +"""Settings restarts are controls, not persisted chat turns.""" + +import json +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock + +import pytest +from websockets.datastructures import Headers + +from nanobot.bus.events import OutboundMessage +from nanobot.channels.websocket.runtime import WebSocketChannel +from nanobot.command.builtin import cmd_restart +from nanobot.command.router import CommandContext +from nanobot.session.manager import SessionManager +from nanobot.webui.metadata import WEBUI_RESTART_CONTROL_METADATA_KEY +from nanobot.webui.session_list_index import list_webui_sessions +from nanobot.webui.transcript import append_transcript_object, read_transcript_lines + +from .test_websocket_channel import _basic_handler, _sent_ws_payloads + + +def _channel(tmp_path: Path, *, allowed: bool = True): + sessions = SessionManager(tmp_path / "workspace") + bus = MagicMock() + bus.publish_inbound = AsyncMock() + channel = WebSocketChannel( + {"enabled": True, "allowFrom": ["*"] if allowed else ["someone-else"]}, bus, + gateway=_basic_handler(bus, session_manager=sessions, workspace_path=tmp_path / "workspace"), + ) + connection = AsyncMock() + connection.remote_address = ("127.0.0.1", 50123) + connection.request = SimpleNamespace(headers=Headers({"Host": "localhost:8765"})) + channel.gateway.endpoint.webui_connections.add(connection) + return sessions, bus, channel, connection + + +@pytest.mark.asyncio +@pytest.mark.parametrize("existing", ["none", "canonical", "transcript", "both"]) +async def test_settings_restart_does_not_create_or_change_chat_history(tmp_path, monkeypatch, existing): + sessions, bus, channel, connection = _channel(tmp_path) + monkeypatch.setattr("nanobot.command.builtin.set_restart_notice_to_env", MagicMock()) + key = "websocket:existing" + if existing in {"canonical", "both"}: + session = sessions.get_or_create(key) + session.add_message("user", "Keep my conversation") + session.metadata.update({"webui": True, "title": "Keep this title"}) + sessions.save(session) + if existing in {"transcript", "both"}: + append_transcript_object(key, { + "event": "user_message", "chat_id": "existing", "text": "Keep my conversation", + }) + before_rows = list_webui_sessions(sessions) + before_files = {p: p.read_bytes() for p in tmp_path.rglob("*.jsonl")} + before_transcript = read_transcript_lines(key) + + # Use each new connection's default ID, then an existing chat when present. + chat_ids = ["ready-default-1", "ready-default-2"] + if existing != "none": + chat_ids.append("existing") + for chat_id in chat_ids: + envelope = { + "type": "message", "chat_id": chat_id, "content": "/restart", "webui": True, + "turn_id": f"webui-system:restart-{chat_id}", + } + await channel._dispatch_envelope(connection, "browser", envelope) + message = bus.publish_inbound.await_args.args[0] + assert message.metadata[WEBUI_RESTART_CONTROL_METADATA_KEY] is True + # Exercise the real command response, but never execute a process restart. + def discard_restart_task(coro): + coro.close() + with monkeypatch.context() as patch: + patch.setattr("nanobot.command.builtin.asyncio.create_task", discard_restart_task) + response = await cmd_restart(CommandContext( + msg=message, session=None, key=message.session_key, raw=message.content, loop=MagicMock(), + )) + await channel.send(response) + # A lost ACK retry must not enqueue a second restart. + calls = bus.publish_inbound.await_count + await channel._dispatch_envelope(connection, "browser", envelope) + assert bus.publish_inbound.await_count == calls + + frames = _sent_ws_payloads(connection) + assert not any(frame["event"] == "user_message" for frame in frames) + replies = [frame for frame in frames if frame["event"] == "message"] + assert len(replies) == len(chat_ids) + assert all(frame["text"] == "Restarting..." and frame["turn_id"].startswith("webui-system:") for frame in replies) + assert {p: p.read_bytes() for p in tmp_path.rglob("*.jsonl")} == before_files + assert read_transcript_lines(key) == before_transcript + # A fresh manager uses the public sidebar discovery path, not a cached count. + fresh = SessionManager(tmp_path / "workspace") + assert list_webui_sessions(fresh) == before_rows + if existing in {"canonical", "both"}: + restored = fresh.get_existing(key) + assert restored is not None and restored.messages[0]["content"] == "Keep my conversation" + assert restored.metadata["title"] == "Keep this title" + await channel._cleanup_connection(connection) + + +@pytest.mark.asyncio +@pytest.mark.parametrize(("text", "turn_id"), [ + ("/restart", "normal-user-turn"), + ("/model fast", "webui-system:model-switch"), + ("/restart later", "webui-system:not-a-restart"), + ("ordinary message", "webui-system:not-a-command"), +]) +async def test_control_prefix_does_not_suppress_ordinary_or_session_command_history(tmp_path, text, turn_id): + sessions, bus, channel, connection = _channel(tmp_path) + await channel._dispatch_envelope(connection, "browser", { + "type": "message", "chat_id": "chat", "content": text, "webui": True, "turn_id": turn_id, + "metadata": {WEBUI_RESTART_CONTROL_METADATA_KEY: True}, + }) + message = bus.publish_inbound.await_args.args[0] + assert WEBUI_RESTART_CONTROL_METADATA_KEY not in message.metadata + await channel.send(OutboundMessage(channel="websocket", chat_id="chat", content="Reply", metadata=message.metadata)) + assert len(list_webui_sessions(sessions)) == 1 + assert [row["text"] for row in read_transcript_lines("websocket:chat")] == [text, "Reply"] + await channel._cleanup_connection(connection) + + +@pytest.mark.asyncio +async def test_restart_control_keeps_the_client_allowlist_check(tmp_path): + sessions, bus, channel, connection = _channel(tmp_path, allowed=False) + await channel._dispatch_envelope(connection, "browser", { + "type": "message", "chat_id": "chat", "content": "/restart", "webui": True, + "turn_id": "webui-system:restart", + }) + bus.publish_inbound.assert_not_awaited() + assert json.loads(connection.send.await_args.args[0])["detail"] == "access_denied" + assert list_webui_sessions(sessions) == [] + + +@pytest.mark.asyncio +async def test_generic_websocket_cannot_claim_transient_webui_control(tmp_path): + sessions, bus, channel, connection = _channel(tmp_path) + channel.gateway.endpoint.webui_connections.remove(connection) + await channel._dispatch_envelope(connection, "browser", { + "type": "message", "chat_id": "chat", "content": "/restart", "webui": True, + "turn_id": "webui-system:restart", + }) + assert WEBUI_RESTART_CONTROL_METADATA_KEY not in bus.publish_inbound.await_args.args[0].metadata + assert len(list_webui_sessions(sessions)) == 1 + await channel._cleanup_connection(connection) diff --git a/nanobot/webui/inbound_commands.py b/nanobot/webui/inbound_commands.py index edde65b0d..a57b8c3d1 100644 --- a/nanobot/webui/inbound_commands.py +++ b/nanobot/webui/inbound_commands.py @@ -47,7 +47,11 @@ from nanobot.webui.file_preview import ( from nanobot.webui.forking import handle_webui_fork_chat from nanobot.webui.gateway_services import GatewayServices from nanobot.webui.mcp_presets_api import normalize_mcp_preset_mentions -from nanobot.webui.metadata import WEBSOCKET_TURN_OWNER_METADATA_KEY +from nanobot.webui.metadata import ( + WEBSOCKET_TURN_OWNER_METADATA_KEY, + WEBUI_RESTART_CONTROL_METADATA_KEY, + WEBUI_SYSTEM_COMMAND_TURN_PREFIX, +) from nanobot.webui.session_access import ( SessionMention, WebuiSessionAccess, @@ -649,6 +653,17 @@ class WebUICommandRouter: metadata["webui"] = True metadata.update(self._transcripts.client_turn_metadata(envelope.get("turn_id"))) trusted_webui = metadata.get("webui") is True and connection in self._webui_connections + # The settings Restart button uses the existing silent command protocol. + # Its routing chat ID is not a new conversation or a workspace update. + restart_control = ( + trusted_webui + and turn_id is not None + and turn_id.startswith(WEBUI_SYSTEM_COMMAND_TURN_PREFIX) + and content.strip().lower() == "/restart" + and not media_paths + ) + if restart_control: + metadata[WEBUI_RESTART_CONTROL_METADATA_KEY] = True is_user_shell = ( trusted_webui and envelope.get("user_shell") is True @@ -701,7 +716,7 @@ class WebUICommandRouter: accepted = False try: - if is_webui and ( + if is_webui and not restart_control and ( temporary_policy is None or temporary_policy.persist_transcript ): self._transcripts.append_user_message( @@ -746,7 +761,8 @@ class WebUICommandRouter: else False ), ) - self._workspaces.persist_scope(chat_id, scope) + if not restart_control: + self._workspaces.persist_scope(chat_id, scope) accepted = True if turn_id: self._accepted_messages[(chat_id, turn_id)] = time.monotonic() + 600 @@ -756,7 +772,7 @@ class WebUICommandRouter: if not accepted and queued_owner is not None: clear_websocket_turn_if_current(chat_id, queued_owner) - if is_webui: + if is_webui and not restart_control: await self.broadcast_user_message( connection, chat_id, diff --git a/nanobot/webui/metadata.py b/nanobot/webui/metadata.py index 2830dfed7..81b098ee9 100644 --- a/nanobot/webui/metadata.py +++ b/nanobot/webui/metadata.py @@ -2,5 +2,7 @@ WEBUI_TURN_METADATA_KEY = "webui_turn_id" WEBUI_SYSTEM_COMMAND_TURN_PREFIX = "webui-system:" +# Set by authenticated WebUI ingress, never copied from an envelope's metadata. +WEBUI_RESTART_CONTROL_METADATA_KEY = "_webui_restart_control" WEBSOCKET_TURN_OWNER_METADATA_KEY = "_websocket_turn_owner" WEBUI_MESSAGE_SOURCE_METADATA_KEY = "_webui_message_source"